1 /*
2 * Copyright 2018 Dan Field
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 // independent from idl_parser, since this code is not needed for most clients
18 #include <cassert>
19
20 #include "flatbuffers/code_generators.h"
21 #include "flatbuffers/flatbuffers.h"
22 #include "flatbuffers/idl.h"
23 #include "flatbuffers/util.h"
24
25 namespace flatbuffers {
26
GeneratedFileName(const std::string & path,const std::string & file_name)27 static std::string GeneratedFileName(const std::string &path,
28 const std::string &file_name) {
29 return path + file_name + "_generated.dart";
30 }
31
32 namespace dart {
33
34 const std::string _kFb = "fb";
35 // see https://www.dartlang.org/guides/language/language-tour#keywords
36 // yeild*, async*, and sync* shouldn't be problems anyway but keeping them in
37 static const char *keywords[] = {
38 "abstract", "deferred", "if", "super", "as", "do",
39 "implements", "switch", "assert", "dynamic", "import", "sync*",
40 "async", "else", "in", "this", "async*", "enum",
41 "is", "throw", "await", "export", "library", "true",
42 "break", "external", "new", "try", "case", "extends",
43 "null", "typedef", "catch", "factory", "operator", "var",
44 "class", "false", "part", "void", "const", "final",
45 "rethrow", "while", "continue", "finally", "return", "with",
46 "covariant", "for", "set", "yield", "default", "get",
47 "static", "yield*"
48 };
49
50 // Iterate through all definitions we haven't generate code for (enums, structs,
51 // and tables) and output them to a single file.
52 class DartGenerator : public BaseGenerator {
53 public:
54 typedef std::map<std::string, std::string> namespace_code_map;
55
DartGenerator(const Parser & parser,const std::string & path,const std::string & file_name)56 DartGenerator(const Parser &parser, const std::string &path,
57 const std::string &file_name)
58 : BaseGenerator(parser, path, file_name, "", ".") {}
59 // Iterate through all definitions we haven't generate code for (enums,
60 // structs, and tables) and output them to a single file.
generate()61 bool generate() {
62 std::string code;
63 namespace_code_map namespace_code;
64 GenerateEnums(&namespace_code);
65 GenerateStructs(&namespace_code);
66
67 for (auto kv = namespace_code.begin(); kv != namespace_code.end(); ++kv) {
68 code.clear();
69 code = code + "// " + FlatBuffersGeneratedWarning() + "\n";
70 code = code +
71 "// ignore_for_file: unused_import, unused_field, "
72 "unused_local_variable\n\n";
73
74 code += "library " + kv->first + ";\n\n";
75
76 code += "import 'dart:typed_data' show Uint8List;\n";
77 code += "import 'package:flat_buffers/flat_buffers.dart' as " + _kFb +
78 ";\n\n";
79
80 if (parser_.opts.include_dependence_headers) {
81 GenIncludeDependencies(&code, kv->first);
82 }
83
84 for (auto kv2 = namespace_code.begin(); kv2 != namespace_code.end();
85 ++kv2) {
86 if (kv2->first != kv->first) {
87 code += "import '" +
88 GeneratedFileName("./", file_name_ + "_" + kv2->first) +
89 "' as " + ImportAliasName(kv2->first) + ";\n";
90 }
91 }
92 code += "\n";
93 code += kv->second;
94
95 if (!SaveFile(
96 GeneratedFileName(path_, file_name_ + "_" + kv->first).c_str(),
97 code, false)) {
98 return false;
99 }
100 }
101 return true;
102 }
103
104 private:
ImportAliasName(const std::string & ns)105 static std::string ImportAliasName(const std::string &ns) {
106 std::string ret;
107 ret.assign(ns);
108 size_t pos = ret.find(".");
109 while (pos != std::string::npos) {
110 ret.replace(pos, 1, "_");
111 pos = ret.find(".", pos + 1);
112 }
113
114 return ret;
115 }
116
BuildNamespaceName(const Namespace & ns)117 static std::string BuildNamespaceName(const Namespace &ns) {
118 std::stringstream sstream;
119 std::copy(ns.components.begin(), ns.components.end() - 1,
120 std::ostream_iterator<std::string>(sstream, "."));
121
122 auto ret = sstream.str() + ns.components.back();
123 for (int i = 0; ret[i]; i++) {
124 auto lower = tolower(ret[i]);
125 if (lower != ret[i]) {
126 ret[i] = static_cast<char>(lower);
127 if (i != 0 && ret[i - 1] != '.') {
128 ret.insert(i, "_");
129 i++;
130 }
131 }
132 }
133 // std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
134 return ret;
135 }
136
GenIncludeDependencies(std::string * code,const std::string & the_namespace)137 void GenIncludeDependencies(std::string* code, const std::string& the_namespace) {
138 for (auto it = parser_.included_files_.begin();
139 it != parser_.included_files_.end(); ++it) {
140 if (it->second.empty()) continue;
141
142 auto noext = flatbuffers::StripExtension(it->second);
143 auto basename = flatbuffers::StripPath(noext);
144
145 *code += "import '" + GeneratedFileName("", basename + "_" + the_namespace) + "';\n";
146 }
147 }
148
EscapeKeyword(const std::string & name)149 static std::string EscapeKeyword(const std::string &name) {
150 for (size_t i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) {
151 if (name == keywords[i]) { return MakeCamel(name + "_", false); }
152 }
153
154 return MakeCamel(name, false);
155 }
156
GenerateEnums(namespace_code_map * namespace_code)157 void GenerateEnums(namespace_code_map *namespace_code) {
158 for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
159 ++it) {
160 auto &enum_def = **it;
161 GenEnum(enum_def, namespace_code); // enum_code_ptr);
162 }
163 }
164
GenerateStructs(namespace_code_map * namespace_code)165 void GenerateStructs(namespace_code_map *namespace_code) {
166 for (auto it = parser_.structs_.vec.begin();
167 it != parser_.structs_.vec.end(); ++it) {
168 auto &struct_def = **it;
169 GenStruct(struct_def, namespace_code);
170 }
171 }
172
173 // Generate a documentation comment, if available.
GenDocComment(const std::vector<std::string> & dc,std::string * code_ptr,const std::string & extra_lines,const char * indent=nullptr)174 static void GenDocComment(const std::vector<std::string> &dc,
175 std::string *code_ptr,
176 const std::string &extra_lines,
177 const char *indent = nullptr) {
178 if (dc.empty() && extra_lines.empty()) {
179 // Don't output empty comment blocks with 0 lines of comment content.
180 return;
181 }
182
183 auto &code = *code_ptr;
184 if (indent) code += indent;
185
186 for (auto it = dc.begin(); it != dc.end(); ++it) {
187 if (indent) code += indent;
188 code += "/// " + *it + "\n";
189 }
190 if (!extra_lines.empty()) {
191 if (!dc.empty()) {
192 if (indent) code += indent;
193 code += "///\n";
194 }
195 if (indent) code += indent;
196 std::string::size_type start = 0;
197 for (;;) {
198 auto end = extra_lines.find('\n', start);
199 if (end != std::string::npos) {
200 code += "/// " + extra_lines.substr(start, end - start) + "\n";
201 start = end + 1;
202 } else {
203 code += "/// " + extra_lines.substr(start) + "\n";
204 break;
205 }
206 }
207 }
208 }
209
GenDocComment(std::string * code_ptr,const std::string & extra_lines)210 static void GenDocComment(std::string *code_ptr,
211 const std::string &extra_lines) {
212 GenDocComment(std::vector<std::string>(), code_ptr, extra_lines);
213 }
214
215 // Generate an enum declaration and an enum string lookup table.
GenEnum(EnumDef & enum_def,namespace_code_map * namespace_code)216 void GenEnum(EnumDef &enum_def, namespace_code_map *namespace_code) {
217 if (enum_def.generated) return;
218 auto ns = BuildNamespaceName(*enum_def.defined_namespace);
219 std::string code;
220 GenDocComment(enum_def.doc_comment, &code, "");
221
222 auto name = enum_def.is_union ? enum_def.name + "TypeId" : enum_def.name;
223 auto is_bit_flags = enum_def.attributes.Lookup("bit_flags");
224
225 code += "class " + name + " {\n";
226 code += " final int value;\n";
227 code += " const " + name + "._(this.value);\n\n";
228 code += " factory " + name + ".fromValue(int value) {\n";
229 code += " if (value == null) value = 0;\n";
230
231 code += " if (!values.containsKey(value)) {\n";
232 code +=
233 " throw new StateError('Invalid value $value for bit flag enum ";
234 code += name + "');\n";
235 code += " }\n";
236
237 code += " return values[value];\n";
238 code += " }\n\n";
239
240 // this is meaningless for bit_flags
241 // however, note that unlike "regular" dart enums this enum can still have
242 // holes.
243 if (!is_bit_flags) {
244 code += " static const int minValue = " +
245 NumToString(enum_def.vals.vec.front()->value) + ";\n";
246 code += " static const int maxValue = " +
247 NumToString(enum_def.vals.vec.back()->value) + ";\n";
248 }
249
250 code +=
251 " static bool containsValue(int value) =>"
252 " values.containsKey(value);\n\n";
253
254 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
255 ++it) {
256 auto &ev = **it;
257
258 if (!ev.doc_comment.empty()) {
259 if (it != enum_def.vals.vec.begin()) { code += '\n'; }
260 GenDocComment(ev.doc_comment, &code, "", " ");
261 }
262 code += " static const " + name + " " + ev.name + " = ";
263 code += "const " + name + "._(" + NumToString(ev.value) + ");\n";
264 }
265
266 code += " static get values => {";
267 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
268 ++it) {
269 auto &ev = **it;
270 code += NumToString(ev.value) + ": " + ev.name + ",";
271 }
272 code += "};\n\n";
273
274 code += " static const " + _kFb + ".Reader<" + name +
275 "> reader = const _" + name + "Reader();\n\n";
276 code += " @override\n";
277 code += " String toString() {\n";
278 code += " return '" + name + "{value: $value}';\n";
279 code += " }\n";
280 code += "}\n\n";
281
282 GenEnumReader(enum_def, name, &code);
283 (*namespace_code)[ns] += code;
284 }
285
GenEnumReader(EnumDef & enum_def,const std::string & name,std::string * code_ptr)286 void GenEnumReader(EnumDef &enum_def, const std::string &name,
287 std::string *code_ptr) {
288 auto &code = *code_ptr;
289
290 code += "class _" + name + "Reader extends " + _kFb + ".Reader<" + name +
291 "> {\n";
292 code += " const _" + name + "Reader();\n\n";
293 code += " @override\n";
294 code += " int get size => 1;\n\n";
295 code += " @override\n";
296 code +=
297 " " + name + " read(" + _kFb + ".BufferContext bc, int offset) =>\n";
298 code += " new " + name + ".fromValue(const " + _kFb + "." +
299 GenType(enum_def.underlying_type) + "Reader().read(bc, offset));\n";
300 code += "}\n\n";
301 }
302
GenType(const Type & type)303 static std::string GenType(const Type &type) {
304 switch (type.base_type) {
305 case BASE_TYPE_BOOL: return "Bool";
306 case BASE_TYPE_CHAR: return "Int8";
307 case BASE_TYPE_UTYPE:
308 case BASE_TYPE_UCHAR: return "Uint8";
309 case BASE_TYPE_SHORT: return "Int16";
310 case BASE_TYPE_USHORT: return "Uint16";
311 case BASE_TYPE_INT: return "Int32";
312 case BASE_TYPE_UINT: return "Uint32";
313 case BASE_TYPE_LONG: return "Int64";
314 case BASE_TYPE_ULONG: return "Uint64";
315 case BASE_TYPE_FLOAT: return "Float32";
316 case BASE_TYPE_DOUBLE: return "Float64";
317 case BASE_TYPE_STRING: return "String";
318 case BASE_TYPE_VECTOR: return GenType(type.VectorType());
319 case BASE_TYPE_STRUCT: return type.struct_def->name;
320 case BASE_TYPE_UNION: return type.enum_def->name + "TypeId";
321 default: return "Table";
322 }
323 }
324
GenReaderTypeName(const Type & type,Namespace * current_namespace,const FieldDef & def,bool parent_is_vector=false)325 std::string GenReaderTypeName(const Type &type, Namespace *current_namespace,
326 const FieldDef &def,
327 bool parent_is_vector = false) {
328 if (type.base_type == BASE_TYPE_BOOL) {
329 return "const " + _kFb + ".BoolReader()";
330 } else if (type.base_type == BASE_TYPE_VECTOR) {
331 return "const " + _kFb + ".ListReader<" +
332 GenDartTypeName(type.VectorType(), current_namespace, def) + ">(" +
333 GenReaderTypeName(type.VectorType(), current_namespace, def,
334 true) +
335 ")";
336 } else if (type.base_type == BASE_TYPE_STRING) {
337 return "const " + _kFb + ".StringReader()";
338 }
339 if (IsScalar(type.base_type)) {
340 if (type.enum_def && parent_is_vector) {
341 return GenDartTypeName(type, current_namespace, def) + ".reader";
342 }
343 return "const " + _kFb + "." + GenType(type) + "Reader()";
344 } else {
345 return GenDartTypeName(type, current_namespace, def) + ".reader";
346 }
347 }
348
GenDartTypeName(const Type & type,Namespace * current_namespace,const FieldDef & def,bool addBuilder=false)349 std::string GenDartTypeName(const Type &type, Namespace *current_namespace,
350 const FieldDef &def, bool addBuilder = false) {
351 if (type.enum_def) {
352 if (type.enum_def->is_union && type.base_type != BASE_TYPE_UNION) {
353 return type.enum_def->name + "TypeId";
354 } else if (type.enum_def->is_union) {
355 return "dynamic";
356 } else if (type.base_type != BASE_TYPE_VECTOR) {
357 return type.enum_def->name;
358 }
359 }
360
361 switch (type.base_type) {
362 case BASE_TYPE_BOOL: return "bool";
363 case BASE_TYPE_LONG:
364 case BASE_TYPE_ULONG:
365 case BASE_TYPE_INT:
366 case BASE_TYPE_UINT:
367 case BASE_TYPE_SHORT:
368 case BASE_TYPE_USHORT:
369 case BASE_TYPE_CHAR:
370 case BASE_TYPE_UCHAR: return "int";
371 case BASE_TYPE_FLOAT:
372 case BASE_TYPE_DOUBLE: return "double";
373 case BASE_TYPE_STRING: return "String";
374 case BASE_TYPE_STRUCT:
375 return MaybeWrapNamespace(
376 type.struct_def->name + (addBuilder ? "ObjectBuilder" : ""),
377 current_namespace, def);
378 case BASE_TYPE_VECTOR:
379 return "List<" +
380 GenDartTypeName(type.VectorType(), current_namespace, def,
381 addBuilder) +
382 ">";
383 default: assert(0); return "dynamic";
384 }
385 }
386
MaybeWrapNamespace(const std::string & type_name,Namespace * current_ns,const FieldDef & field)387 static const std::string MaybeWrapNamespace(const std::string &type_name,
388 Namespace *current_ns,
389 const FieldDef &field) {
390 auto curr_ns_str = BuildNamespaceName(*current_ns);
391 std::string field_ns_str = "";
392 if (field.value.type.struct_def) {
393 field_ns_str +=
394 BuildNamespaceName(*field.value.type.struct_def->defined_namespace);
395 } else if (field.value.type.enum_def) {
396 field_ns_str +=
397 BuildNamespaceName(*field.value.type.enum_def->defined_namespace);
398 }
399
400 if (field_ns_str != "" && field_ns_str != curr_ns_str) {
401 return ImportAliasName(field_ns_str) + "." + type_name;
402 } else {
403 return type_name;
404 }
405 }
406
407 // Generate an accessor struct with constructor for a flatbuffers struct.
GenStruct(const StructDef & struct_def,namespace_code_map * namespace_code)408 void GenStruct(const StructDef &struct_def,
409 namespace_code_map *namespace_code) {
410 if (struct_def.generated) return;
411
412 auto object_namespace = BuildNamespaceName(*struct_def.defined_namespace);
413 std::string code;
414
415 auto object_name = struct_def.name;
416
417 // Emit constructor
418
419 GenDocComment(struct_def.doc_comment, &code, "");
420
421 auto reader_name = "_" + struct_def.name + "Reader";
422 auto builder_name = struct_def.name + "Builder";
423 auto object_builder_name = struct_def.name + "ObjectBuilder";
424
425 std::string reader_code, builder_code;
426
427 code += "class " + struct_def.name + " {\n";
428
429 code += " " + struct_def.name + "._(this._bc, this._bcOffset);\n";
430 if (!struct_def.fixed) {
431 code += " factory " + struct_def.name + "(List<int> bytes) {\n";
432 code += " " + _kFb + ".BufferContext rootRef = new " + _kFb +
433 ".BufferContext.fromBytes(bytes);\n";
434 code += " return reader.read(rootRef, 0);\n";
435 code += " }\n";
436 }
437
438 code += "\n";
439 code += " static const " + _kFb + ".Reader<" + struct_def.name +
440 "> reader = const " + reader_name + "();\n\n";
441
442 code += " final " + _kFb + ".BufferContext _bc;\n";
443 code += " final int _bcOffset;\n\n";
444
445 GenImplementationGetters(struct_def, &code);
446
447 code += "}\n\n";
448
449 GenReader(struct_def, &reader_name, &reader_code);
450 GenBuilder(struct_def, &builder_name, &builder_code);
451 GenObjectBuilder(struct_def, &object_builder_name, &builder_code);
452
453 code += reader_code;
454 code += builder_code;
455
456 (*namespace_code)[object_namespace] += code;
457 }
458
NamespaceAliasFromUnionType(const std::string & in)459 std::string NamespaceAliasFromUnionType(const std::string &in) {
460 if (in.find("_") == std::string::npos) { return in; }
461
462 std::stringstream ss(in);
463 std::string item;
464 std::vector<std::string> parts;
465 std::string ns;
466
467 while (std::getline(ss, item, '_')) { parts.push_back(item); }
468
469 for (auto it = parts.begin(); it != parts.end() - 1; ++it) {
470 auto &part = *it;
471
472 for (size_t i = 0; i < part.length(); i++) {
473 if (i && !isdigit(part[i]) &&
474 part[i] == static_cast<char>(toupper(part[i]))) {
475 ns += "_";
476 ns += static_cast<char>(tolower(part[i]));
477 } else {
478 ns += static_cast<char>(tolower(part[i]));
479 }
480 }
481 if (it != parts.end() - 2) { ns += "_"; }
482 }
483
484 return ns + "." + parts.back();
485 }
486
GenImplementationGetters(const StructDef & struct_def,std::string * code_ptr)487 void GenImplementationGetters(const StructDef &struct_def,
488 std::string *code_ptr) {
489 auto &code = *code_ptr;
490
491 for (auto it = struct_def.fields.vec.begin();
492 it != struct_def.fields.vec.end(); ++it) {
493 auto &field = **it;
494 if (field.deprecated) continue;
495
496 std::string field_name = MakeCamel(field.name, false);
497 std::string type_name = GenDartTypeName(
498 field.value.type, struct_def.defined_namespace, field, false);
499
500 GenDocComment(field.doc_comment, &code, "");
501
502 code += " " + type_name + " get " + field_name;
503 if (field.value.type.base_type == BASE_TYPE_UNION) {
504 code += " {\n";
505 code += " switch (" + field_name + "Type?.value) {\n";
506 for (auto en_it = field.value.type.enum_def->vals.vec.begin() + 1;
507 en_it != field.value.type.enum_def->vals.vec.end(); ++en_it) {
508 auto &ev = **en_it;
509
510 auto enum_name = NamespaceAliasFromUnionType(ev.name);
511 code += " case " + NumToString(ev.value) + ": return " +
512 enum_name + ".reader.vTableGet(_bc, _bcOffset, " +
513 NumToString(field.value.offset) + ", null);\n";
514 }
515 code += " default: return null;\n";
516 code += " }\n";
517 code += " }\n";
518 } else {
519 code += " => ";
520 if (field.value.type.enum_def &&
521 field.value.type.base_type != BASE_TYPE_VECTOR) {
522 code += "new " +
523 GenDartTypeName(field.value.type,
524 struct_def.defined_namespace, field) +
525 ".fromValue(";
526 }
527
528 code += GenReaderTypeName(field.value.type,
529 struct_def.defined_namespace, field);
530 if (struct_def.fixed) {
531 code +=
532 ".read(_bc, _bcOffset + " + NumToString(field.value.offset) + ")";
533 } else {
534 code += ".vTableGet(_bc, _bcOffset, " +
535 NumToString(field.value.offset) + ", ";
536 if (!field.value.constant.empty() && field.value.constant != "0") {
537 if (IsBool(field.value.type.base_type)) {
538 code += "true";
539 } else {
540 code += field.value.constant;
541 }
542 } else {
543 if (IsBool(field.value.type.base_type)) {
544 code += "false";
545 } else if (IsScalar(field.value.type.base_type)) {
546 code += "0";
547 } else {
548 code += "null";
549 }
550 }
551 code += ")";
552 }
553 if (field.value.type.enum_def &&
554 field.value.type.base_type != BASE_TYPE_VECTOR) {
555 code += ")";
556 }
557 code += ";\n";
558 }
559 }
560
561 code += "\n";
562
563 code += " @override\n";
564 code += " String toString() {\n";
565 code += " return '" + struct_def.name + "{";
566 for (auto it = struct_def.fields.vec.begin();
567 it != struct_def.fields.vec.end(); ++it) {
568 auto &field = **it;
569 if (field.deprecated) continue;
570 code +=
571 MakeCamel(field.name, false) + ": $" + MakeCamel(field.name, false);
572 if (it != struct_def.fields.vec.end() - 1) { code += ", "; }
573 }
574 code += "}';\n";
575 code += " }\n";
576 }
577
GenReader(const StructDef & struct_def,std::string * reader_name_ptr,std::string * code_ptr)578 void GenReader(const StructDef &struct_def, std::string *reader_name_ptr,
579 std::string *code_ptr) {
580 auto &code = *code_ptr;
581 auto &reader_name = *reader_name_ptr;
582 auto &impl_name = struct_def.name;
583
584 code += "class " + reader_name + " extends " + _kFb;
585 if (struct_def.fixed) {
586 code += ".StructReader<";
587 } else {
588 code += ".TableReader<";
589 }
590 code += impl_name + "> {\n";
591 code += " const " + reader_name + "();\n\n";
592
593 if (struct_def.fixed) {
594 code += " @override\n";
595 code += " int get size => " + NumToString(struct_def.bytesize) + ";\n\n";
596 }
597 code += " @override\n";
598 code += " " + impl_name +
599 " createObject(fb.BufferContext bc, int offset) => \n new " +
600 impl_name + "._(bc, offset);\n";
601 code += "}\n\n";
602 }
603
GenBuilder(const StructDef & struct_def,std::string * builder_name_ptr,std::string * code_ptr)604 void GenBuilder(const StructDef &struct_def, std::string *builder_name_ptr,
605 std::string *code_ptr) {
606 if (struct_def.fields.vec.size() == 0) { return; }
607 auto &code = *code_ptr;
608 auto &builder_name = *builder_name_ptr;
609
610 code += "class " + builder_name + " {\n";
611 code += " " + builder_name + "(this.fbBuilder) {\n";
612 code += " assert(fbBuilder != null);\n";
613 code += " }\n\n";
614 code += " final " + _kFb + ".Builder fbBuilder;\n\n";
615
616 if (struct_def.fixed) {
617 StructBuilderBody(struct_def, code_ptr);
618 } else {
619 TableBuilderBody(struct_def, code_ptr);
620 }
621
622 code += "}\n\n";
623 }
624
StructBuilderBody(const StructDef & struct_def,std::string * code_ptr)625 void StructBuilderBody(const StructDef &struct_def, std::string *code_ptr) {
626 auto &code = *code_ptr;
627
628 code += " int finish(";
629 for (auto it = struct_def.fields.vec.begin();
630 it != struct_def.fields.vec.end(); ++it) {
631 auto &field = **it;
632 if (field.deprecated) continue;
633
634 if (IsStruct(field.value.type)) {
635 code += "fb.StructBuilder";
636 } else {
637 code += GenDartTypeName(field.value.type, struct_def.defined_namespace,
638 field);
639 }
640 code += " " + field.name;
641 if (it != struct_def.fields.vec.end() - 1) { code += ", "; }
642 }
643 code += ") {\n";
644
645 for (auto it = struct_def.fields.vec.rbegin();
646 it != struct_def.fields.vec.rend(); ++it) {
647 auto &field = **it;
648
649 if (field.deprecated) continue;
650
651 if (field.padding) {
652 code += " fbBuilder.pad(" + NumToString(field.padding) + ");\n";
653 }
654
655 if (IsStruct(field.value.type)) {
656 code += " " + field.name + "();\n";
657 } else {
658 code += " fbBuilder.put" + GenType(field.value.type) + "(";
659 code += field.name;
660 if (field.value.type.enum_def) { code += "?.value"; }
661 code += ");\n";
662 }
663 }
664 code += " return fbBuilder.offset;\n";
665 code += " }\n\n";
666 }
667
TableBuilderBody(const StructDef & struct_def,std::string * code_ptr)668 void TableBuilderBody(const StructDef &struct_def, std::string *code_ptr) {
669 auto &code = *code_ptr;
670
671 code += " void begin() {\n";
672 code += " fbBuilder.startTable();\n";
673 code += " }\n\n";
674
675 for (auto it = struct_def.fields.vec.begin();
676 it != struct_def.fields.vec.end(); ++it) {
677 auto &field = **it;
678 if (field.deprecated) continue;
679
680 auto offset = it - struct_def.fields.vec.begin();
681
682 if (IsScalar(field.value.type.base_type)) {
683 code += " int add" + MakeCamel(field.name) + "(";
684 code += GenDartTypeName(field.value.type, struct_def.defined_namespace,
685 field);
686 code += " " + MakeCamel(field.name, false) + ") {\n";
687 code += " fbBuilder.add" + GenType(field.value.type) + "(" +
688 NumToString(offset) + ", ";
689 code += MakeCamel(field.name, false);
690 if (field.value.type.enum_def) { code += "?.value"; }
691 code += ");\n";
692 } else if (IsStruct(field.value.type)) {
693 code += " int add" + MakeCamel(field.name) + "(int offset) {\n";
694 code +=
695 " fbBuilder.addStruct(" + NumToString(offset) + ", offset);\n";
696 } else {
697 code += " int add" + MakeCamel(field.name) + "Offset(int offset) {\n";
698 code +=
699 " fbBuilder.addOffset(" + NumToString(offset) + ", offset);\n";
700 }
701 code += " return fbBuilder.offset;\n";
702 code += " }\n";
703 }
704
705 code += "\n";
706 code += " int finish() {\n";
707 code += " return fbBuilder.endTable();\n";
708 code += " }\n";
709 }
710
GenObjectBuilder(const StructDef & struct_def,std::string * builder_name_ptr,std::string * code_ptr)711 void GenObjectBuilder(const StructDef &struct_def,
712 std::string *builder_name_ptr, std::string *code_ptr) {
713 auto &code = *code_ptr;
714 auto &builder_name = *builder_name_ptr;
715
716 code += "class " + builder_name + " extends " + _kFb + ".ObjectBuilder {\n";
717 for (auto it = struct_def.fields.vec.begin();
718 it != struct_def.fields.vec.end(); ++it) {
719 auto &field = **it;
720 if (field.deprecated) continue;
721 code += " final " +
722 GenDartTypeName(field.value.type, struct_def.defined_namespace,
723 field, true) +
724 " _" + MakeCamel(field.name, false) + ";\n";
725 }
726 code += "\n";
727 code += " " + builder_name + "(";
728 if (struct_def.fields.vec.size() != 0) {
729 code +=
730
731 "{\n";
732 for (auto it = struct_def.fields.vec.begin();
733 it != struct_def.fields.vec.end(); ++it) {
734 auto &field = **it;
735 if (field.deprecated) continue;
736 code += " " +
737 GenDartTypeName(field.value.type, struct_def.defined_namespace,
738 field, true) +
739 " " + MakeCamel(field.name, false) + ",\n";
740 }
741 code += " })\n";
742 code += " : ";
743 for (auto it = struct_def.fields.vec.begin();
744 it != struct_def.fields.vec.end(); ++it) {
745 auto &field = **it;
746 if (field.deprecated) continue;
747 code += "_" + MakeCamel(field.name, false) + " = " +
748 MakeCamel(field.name, false);
749 if (it == struct_def.fields.vec.end() - 1) {
750 code += ";\n\n";
751 } else {
752 code += ",\n ";
753 }
754 }
755 } else {
756 code += ");\n\n";
757 }
758
759 code += " /// Finish building, and store into the [fbBuilder].\n";
760 code += " @override\n";
761 code += " int finish(\n";
762 code += " " + _kFb + ".Builder fbBuilder) {\n";
763 code += " assert(fbBuilder != null);\n";
764
765 for (auto it = struct_def.fields.vec.begin();
766 it != struct_def.fields.vec.end(); ++it) {
767 auto &field = **it;
768 if (field.deprecated) continue;
769 if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type))
770 continue;
771
772 code += " final int " + MakeCamel(field.name, false) + "Offset";
773 if (field.value.type.base_type == BASE_TYPE_VECTOR) {
774 code +=
775 " = _" + MakeCamel(field.name, false) + "?.isNotEmpty == true\n";
776 code += " ? fbBuilder.writeList";
777 switch (field.value.type.VectorType().base_type) {
778 case BASE_TYPE_STRING:
779 code += "(_" + MakeCamel(field.name, false) +
780 ".map((b) => fbBuilder.writeString(b)).toList())";
781 break;
782 case BASE_TYPE_STRUCT:
783 if (field.value.type.struct_def->fixed) {
784 code += "OfStructs(_" + MakeCamel(field.name, false) + ")";
785 } else {
786 code += "(_" + MakeCamel(field.name, false) +
787 ".map((b) => b.getOrCreateOffset(fbBuilder)).toList())";
788 }
789 break;
790 default:
791 code += GenType(field.value.type.VectorType()) + "(_" +
792 MakeCamel(field.name, false);
793 if (field.value.type.enum_def) { code += ".map((f) => f.value)"; }
794 code += ")";
795 }
796 code += "\n : null;\n";
797 } else if (field.value.type.base_type == BASE_TYPE_STRING) {
798 code += " = fbBuilder.writeString(_" + MakeCamel(field.name, false) + ");\n";
799 } else {
800 code += " = _" + MakeCamel(field.name, false) +
801 "?.getOrCreateOffset(fbBuilder);\n";
802 }
803 }
804
805 code += "\n";
806 if (struct_def.fixed) {
807 StructObjectBuilderBody(struct_def, code_ptr);
808 } else {
809 TableObjectBuilderBody(struct_def, code_ptr);
810 }
811 code += " }\n\n";
812
813 code += " /// Convenience method to serialize to byte list.\n";
814 code += " @override\n";
815 code += " Uint8List toBytes([String fileIdentifier]) {\n";
816 code += " " + _kFb + ".Builder fbBuilder = new ";
817 code += _kFb + ".Builder();\n";
818 code += " int offset = finish(fbBuilder);\n";
819 code += " return fbBuilder.finish(offset, fileIdentifier);\n";
820 code += " }\n";
821 code += "}\n";
822 }
823
StructObjectBuilderBody(const StructDef & struct_def,std::string * code_ptr,bool prependUnderscore=true)824 void StructObjectBuilderBody(const StructDef &struct_def,
825 std::string *code_ptr,
826 bool prependUnderscore = true) {
827 auto &code = *code_ptr;
828
829 for (auto it = struct_def.fields.vec.rbegin();
830 it != struct_def.fields.vec.rend(); ++it) {
831 auto &field = **it;
832
833 if (field.deprecated) continue;
834
835 if (field.padding) {
836 code += " fbBuilder.pad(" + NumToString(field.padding) + ");\n";
837 }
838
839 if (IsStruct(field.value.type)) {
840 code += " ";
841 if (prependUnderscore) { code += "_"; }
842 code += field.name + ".finish(fbBuilder);\n";
843 } else {
844 code += " fbBuilder.put" + GenType(field.value.type) + "(";
845 if (prependUnderscore) { code += "_"; }
846 code += field.name;
847 if (field.value.type.enum_def) { code += "?.value"; }
848 code += ");\n";
849 }
850 }
851
852 code += " return fbBuilder.offset;\n";
853 }
854
TableObjectBuilderBody(const StructDef & struct_def,std::string * code_ptr,bool prependUnderscore=true)855 void TableObjectBuilderBody(const StructDef &struct_def,
856 std::string *code_ptr,
857 bool prependUnderscore = true) {
858 std::string &code = *code_ptr;
859 code += " fbBuilder.startTable();\n";
860
861 for (auto it = struct_def.fields.vec.begin();
862 it != struct_def.fields.vec.end(); ++it) {
863 auto &field = **it;
864
865 if (field.deprecated) continue;
866
867 auto offset = it - struct_def.fields.vec.begin();
868 if (IsScalar(field.value.type.base_type)) {
869 code += " fbBuilder.add" + GenType(field.value.type) + "(" +
870 NumToString(offset) + ", ";
871 if (prependUnderscore) { code += "_"; }
872 code += MakeCamel(field.name, false);
873 if (field.value.type.enum_def) { code += "?.value"; }
874 code += ");\n";
875 } else if (IsStruct(field.value.type)) {
876 code += " if (";
877 if (prependUnderscore) { code += "_"; }
878 code += MakeCamel(field.name, false) + " != null) {\n";
879 code += " fbBuilder.addStruct(" + NumToString(offset) + ", ";
880 code += "_" + MakeCamel(field.name, false) + ".finish(fbBuilder));\n";
881 code += " }\n";
882 } else {
883 code +=
884 " if (" + MakeCamel(field.name, false) + "Offset != null) {\n";
885 code += " fbBuilder.addOffset(" + NumToString(offset) + ", " +
886 MakeCamel(field.name, false) + "Offset);\n";
887 code += " }\n";
888 }
889 }
890 code += " return fbBuilder.endTable();\n";
891 }
892 };
893 } // namespace dart
894
GenerateDart(const Parser & parser,const std::string & path,const std::string & file_name)895 bool GenerateDart(const Parser &parser, const std::string &path,
896 const std::string &file_name) {
897 dart::DartGenerator generator(parser, path, file_name);
898 return generator.generate();
899 }
900
DartMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)901 std::string DartMakeRule(const Parser &parser, const std::string &path,
902 const std::string &file_name) {
903 assert(parser.opts.lang <= IDLOptions::kMAX);
904
905 auto filebase =
906 flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
907 auto make_rule = GeneratedFileName(path, filebase) + ": ";
908
909 auto included_files = parser.GetIncludedFilesRecursive(file_name);
910 for (auto it = included_files.begin(); it != included_files.end(); ++it) {
911 make_rule += " " + *it;
912 }
913 return make_rule;
914 }
915
916 } // namespace flatbuffers
917