• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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().begin(); it != enum_def.Vals().end(); ++it) {
255       auto &ev = **it;
256 
257       if (!ev.doc_comment.empty()) {
258         if (it != enum_def.Vals().begin()) { code += '\n'; }
259         GenDocComment(ev.doc_comment, &code, "", "  ");
260       }
261       code += "  static const " + name + " " + ev.name + " = ";
262       code += "const " + name + "._(" + NumToString(ev.value) + ");\n";
263     }
264 
265     code += "  static get values => {";
266     for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
267       auto &ev = **it;
268       code += NumToString(ev.value) + ": " + ev.name + ",";
269     }
270     code += "};\n\n";
271 
272     code += "  static const " + _kFb + ".Reader<" + name +
273             "> reader = const _" + name + "Reader();\n\n";
274     code += "  @override\n";
275     code += "  String toString() {\n";
276     code += "    return '" + name + "{value: $value}';\n";
277     code += "  }\n";
278     code += "}\n\n";
279 
280     GenEnumReader(enum_def, name, &code);
281     (*namespace_code)[ns] += code;
282   }
283 
GenEnumReader(EnumDef & enum_def,const std::string & name,std::string * code_ptr)284   void GenEnumReader(EnumDef &enum_def, const std::string &name,
285                      std::string *code_ptr) {
286     auto &code = *code_ptr;
287 
288     code += "class _" + name + "Reader extends " + _kFb + ".Reader<" + name +
289             "> {\n";
290     code += "  const _" + name + "Reader();\n\n";
291     code += "  @override\n";
292     code += "  int get size => 1;\n\n";
293     code += "  @override\n";
294     code +=
295         "  " + name + " read(" + _kFb + ".BufferContext bc, int offset) =>\n";
296     code += "      new " + name + ".fromValue(const " + _kFb + "." +
297             GenType(enum_def.underlying_type) + "Reader().read(bc, offset));\n";
298     code += "}\n\n";
299   }
300 
GenType(const Type & type)301   static std::string GenType(const Type &type) {
302     switch (type.base_type) {
303       case BASE_TYPE_BOOL: return "Bool";
304       case BASE_TYPE_CHAR: return "Int8";
305       case BASE_TYPE_UTYPE:
306       case BASE_TYPE_UCHAR: return "Uint8";
307       case BASE_TYPE_SHORT: return "Int16";
308       case BASE_TYPE_USHORT: return "Uint16";
309       case BASE_TYPE_INT: return "Int32";
310       case BASE_TYPE_UINT: return "Uint32";
311       case BASE_TYPE_LONG: return "Int64";
312       case BASE_TYPE_ULONG: return "Uint64";
313       case BASE_TYPE_FLOAT: return "Float32";
314       case BASE_TYPE_DOUBLE: return "Float64";
315       case BASE_TYPE_STRING: return "String";
316       case BASE_TYPE_VECTOR: return GenType(type.VectorType());
317       case BASE_TYPE_STRUCT: return type.struct_def->name;
318       case BASE_TYPE_UNION: return type.enum_def->name + "TypeId";
319       default: return "Table";
320     }
321   }
322 
GenReaderTypeName(const Type & type,Namespace * current_namespace,const FieldDef & def,bool parent_is_vector=false)323   std::string GenReaderTypeName(const Type &type, Namespace *current_namespace,
324                                 const FieldDef &def,
325                                 bool parent_is_vector = false) {
326     if (type.base_type == BASE_TYPE_BOOL) {
327       return "const " + _kFb + ".BoolReader()";
328     } else if (type.base_type == BASE_TYPE_VECTOR) {
329       return "const " + _kFb + ".ListReader<" +
330              GenDartTypeName(type.VectorType(), current_namespace, def) + ">(" +
331              GenReaderTypeName(type.VectorType(), current_namespace, def,
332                                true) +
333              ")";
334     } else if (type.base_type == BASE_TYPE_STRING) {
335       return "const " + _kFb + ".StringReader()";
336     }
337     if (IsScalar(type.base_type)) {
338       if (type.enum_def && parent_is_vector) {
339         return GenDartTypeName(type, current_namespace, def) + ".reader";
340       }
341       return "const " + _kFb + "." + GenType(type) + "Reader()";
342     } else {
343       return GenDartTypeName(type, current_namespace, def) + ".reader";
344     }
345   }
346 
GenDartTypeName(const Type & type,Namespace * current_namespace,const FieldDef & def,bool addBuilder=false)347   std::string GenDartTypeName(const Type &type, Namespace *current_namespace,
348                               const FieldDef &def, bool addBuilder = false) {
349     if (type.enum_def) {
350       if (type.enum_def->is_union && type.base_type != BASE_TYPE_UNION) {
351         return type.enum_def->name + "TypeId";
352       } else if (type.enum_def->is_union) {
353         return "dynamic";
354       } else if (type.base_type != BASE_TYPE_VECTOR) {
355         return type.enum_def->name;
356       }
357     }
358 
359     switch (type.base_type) {
360       case BASE_TYPE_BOOL: return "bool";
361       case BASE_TYPE_LONG:
362       case BASE_TYPE_ULONG:
363       case BASE_TYPE_INT:
364       case BASE_TYPE_UINT:
365       case BASE_TYPE_SHORT:
366       case BASE_TYPE_USHORT:
367       case BASE_TYPE_CHAR:
368       case BASE_TYPE_UCHAR: return "int";
369       case BASE_TYPE_FLOAT:
370       case BASE_TYPE_DOUBLE: return "double";
371       case BASE_TYPE_STRING: return "String";
372       case BASE_TYPE_STRUCT:
373         return MaybeWrapNamespace(
374             type.struct_def->name + (addBuilder ? "ObjectBuilder" : ""),
375             current_namespace, def);
376       case BASE_TYPE_VECTOR:
377         return "List<" +
378                GenDartTypeName(type.VectorType(), current_namespace, def,
379                                addBuilder) +
380                ">";
381       default: assert(0); return "dynamic";
382     }
383   }
384 
MaybeWrapNamespace(const std::string & type_name,Namespace * current_ns,const FieldDef & field)385   static const std::string MaybeWrapNamespace(const std::string &type_name,
386                                               Namespace *current_ns,
387                                               const FieldDef &field) {
388     auto curr_ns_str = BuildNamespaceName(*current_ns);
389     std::string field_ns_str = "";
390     if (field.value.type.struct_def) {
391       field_ns_str +=
392           BuildNamespaceName(*field.value.type.struct_def->defined_namespace);
393     } else if (field.value.type.enum_def) {
394       field_ns_str +=
395           BuildNamespaceName(*field.value.type.enum_def->defined_namespace);
396     }
397 
398     if (field_ns_str != "" && field_ns_str != curr_ns_str) {
399       return ImportAliasName(field_ns_str) + "." + type_name;
400     } else {
401       return type_name;
402     }
403   }
404 
405   // Generate an accessor struct with constructor for a flatbuffers struct.
GenStruct(const StructDef & struct_def,namespace_code_map * namespace_code)406   void GenStruct(const StructDef &struct_def,
407                  namespace_code_map *namespace_code) {
408     if (struct_def.generated) return;
409 
410     auto object_namespace = BuildNamespaceName(*struct_def.defined_namespace);
411     std::string code;
412 
413     auto object_name = struct_def.name;
414 
415     // Emit constructor
416 
417     GenDocComment(struct_def.doc_comment, &code, "");
418 
419     auto reader_name = "_" + struct_def.name + "Reader";
420     auto builder_name = struct_def.name + "Builder";
421     auto object_builder_name = struct_def.name + "ObjectBuilder";
422 
423     std::string reader_code, builder_code;
424 
425     code += "class " + struct_def.name + " {\n";
426 
427     code += "  " + struct_def.name + "._(this._bc, this._bcOffset);\n";
428     if (!struct_def.fixed) {
429       code += "  factory " + struct_def.name + "(List<int> bytes) {\n";
430       code += "    " + _kFb + ".BufferContext rootRef = new " + _kFb +
431               ".BufferContext.fromBytes(bytes);\n";
432       code += "    return reader.read(rootRef, 0);\n";
433       code += "  }\n";
434     }
435 
436     code += "\n";
437     code += "  static const " + _kFb + ".Reader<" + struct_def.name +
438             "> reader = const " + reader_name + "();\n\n";
439 
440     code += "  final " + _kFb + ".BufferContext _bc;\n";
441     code += "  final int _bcOffset;\n\n";
442 
443     GenImplementationGetters(struct_def, &code);
444 
445     code += "}\n\n";
446 
447     GenReader(struct_def, &reader_name, &reader_code);
448     GenBuilder(struct_def, &builder_name, &builder_code);
449     GenObjectBuilder(struct_def, &object_builder_name, &builder_code);
450 
451     code += reader_code;
452     code += builder_code;
453 
454     (*namespace_code)[object_namespace] += code;
455   }
456 
NamespaceAliasFromUnionType(const std::string & in)457   std::string NamespaceAliasFromUnionType(const std::string &in) {
458     if (in.find("_") == std::string::npos) { return in; }
459 
460     std::stringstream ss(in);
461     std::string item;
462     std::vector<std::string> parts;
463     std::string ns;
464 
465     while (std::getline(ss, item, '_')) { parts.push_back(item); }
466 
467     for (auto it = parts.begin(); it != parts.end() - 1; ++it) {
468       auto &part = *it;
469 
470       for (size_t i = 0; i < part.length(); i++) {
471         if (i && !isdigit(part[i]) &&
472             part[i] == static_cast<char>(toupper(part[i]))) {
473           ns += "_";
474           ns += static_cast<char>(tolower(part[i]));
475         } else {
476           ns += static_cast<char>(tolower(part[i]));
477         }
478       }
479       if (it != parts.end() - 2) { ns += "_"; }
480     }
481 
482     return ns + "." + parts.back();
483   }
484 
GenImplementationGetters(const StructDef & struct_def,std::string * code_ptr)485   void GenImplementationGetters(const StructDef &struct_def,
486                                 std::string *code_ptr) {
487     auto &code = *code_ptr;
488 
489     for (auto it = struct_def.fields.vec.begin();
490          it != struct_def.fields.vec.end(); ++it) {
491       auto &field = **it;
492       if (field.deprecated) continue;
493 
494       std::string field_name = MakeCamel(field.name, false);
495       std::string type_name = GenDartTypeName(
496           field.value.type, struct_def.defined_namespace, field, false);
497 
498       GenDocComment(field.doc_comment, &code, "");
499 
500       code += "  " + type_name + " get " + field_name;
501       if (field.value.type.base_type == BASE_TYPE_UNION) {
502         code += " {\n";
503         code += "    switch (" + field_name + "Type?.value) {\n";
504         auto &enum_def = *field.value.type.enum_def;
505         for (auto en_it = enum_def.Vals().begin() + 1;
506              en_it != enum_def.Vals().end(); ++en_it) {
507           auto &ev = **en_it;
508 
509           auto enum_name = NamespaceAliasFromUnionType(ev.name);
510           code += "      case " + NumToString(ev.value) + ": return " +
511                   enum_name + ".reader.vTableGet(_bc, _bcOffset, " +
512                   NumToString(field.value.offset) + ", null);\n";
513         }
514         code += "      default: return null;\n";
515         code += "    }\n";
516         code += "  }\n";
517       } else {
518         code += " => ";
519         if (field.value.type.enum_def &&
520             field.value.type.base_type != BASE_TYPE_VECTOR) {
521           code += "new " +
522                   GenDartTypeName(field.value.type,
523                                   struct_def.defined_namespace, field) +
524                   ".fromValue(";
525         }
526 
527         code += GenReaderTypeName(field.value.type,
528                                   struct_def.defined_namespace, field);
529         if (struct_def.fixed) {
530           code +=
531               ".read(_bc, _bcOffset + " + NumToString(field.value.offset) + ")";
532         } else {
533           code += ".vTableGet(_bc, _bcOffset, " +
534                   NumToString(field.value.offset) + ", ";
535           if (!field.value.constant.empty() && field.value.constant != "0") {
536             if (IsBool(field.value.type.base_type)) {
537               code += "true";
538             } else {
539               code += field.value.constant;
540             }
541           } else {
542             if (IsBool(field.value.type.base_type)) {
543               code += "false";
544             } else if (IsScalar(field.value.type.base_type)) {
545               code += "0";
546             } else {
547               code += "null";
548             }
549           }
550           code += ")";
551         }
552         if (field.value.type.enum_def &&
553             field.value.type.base_type != BASE_TYPE_VECTOR) {
554           code += ")";
555         }
556         code += ";\n";
557       }
558     }
559 
560     code += "\n";
561 
562     code += "  @override\n";
563     code += "  String toString() {\n";
564     code += "    return '" + struct_def.name + "{";
565     for (auto it = struct_def.fields.vec.begin();
566          it != struct_def.fields.vec.end(); ++it) {
567       auto &field = **it;
568       if (field.deprecated) continue;
569       code +=
570           MakeCamel(field.name, false) + ": $" + MakeCamel(field.name, false);
571       if (it != struct_def.fields.vec.end() - 1) { code += ", "; }
572     }
573     code += "}';\n";
574     code += "  }\n";
575   }
576 
GenReader(const StructDef & struct_def,std::string * reader_name_ptr,std::string * code_ptr)577   void GenReader(const StructDef &struct_def, std::string *reader_name_ptr,
578                  std::string *code_ptr) {
579     auto &code = *code_ptr;
580     auto &reader_name = *reader_name_ptr;
581     auto &impl_name = struct_def.name;
582 
583     code += "class " + reader_name + " extends " + _kFb;
584     if (struct_def.fixed) {
585       code += ".StructReader<";
586     } else {
587       code += ".TableReader<";
588     }
589     code += impl_name + "> {\n";
590     code += "  const " + reader_name + "();\n\n";
591 
592     if (struct_def.fixed) {
593       code += "  @override\n";
594       code += "  int get size => " + NumToString(struct_def.bytesize) + ";\n\n";
595     }
596     code += "  @override\n";
597     code += "  " + impl_name +
598             " createObject(fb.BufferContext bc, int offset) => \n    new " +
599             impl_name + "._(bc, offset);\n";
600     code += "}\n\n";
601   }
602 
GenBuilder(const StructDef & struct_def,std::string * builder_name_ptr,std::string * code_ptr)603   void GenBuilder(const StructDef &struct_def, std::string *builder_name_ptr,
604                   std::string *code_ptr) {
605     if (struct_def.fields.vec.size() == 0) { return; }
606     auto &code = *code_ptr;
607     auto &builder_name = *builder_name_ptr;
608 
609     code += "class " + builder_name + " {\n";
610     code += "  " + builder_name + "(this.fbBuilder) {\n";
611     code += "    assert(fbBuilder != null);\n";
612     code += "  }\n\n";
613     code += "  final " + _kFb + ".Builder fbBuilder;\n\n";
614 
615     if (struct_def.fixed) {
616       StructBuilderBody(struct_def, code_ptr);
617     } else {
618       TableBuilderBody(struct_def, code_ptr);
619     }
620 
621     code += "}\n\n";
622   }
623 
StructBuilderBody(const StructDef & struct_def,std::string * code_ptr)624   void StructBuilderBody(const StructDef &struct_def, std::string *code_ptr) {
625     auto &code = *code_ptr;
626 
627     code += "  int finish(";
628     for (auto it = struct_def.fields.vec.begin();
629          it != struct_def.fields.vec.end(); ++it) {
630       auto &field = **it;
631       if (field.deprecated) continue;
632 
633       if (IsStruct(field.value.type)) {
634         code += "fb.StructBuilder";
635       } else {
636         code += GenDartTypeName(field.value.type, struct_def.defined_namespace,
637                                 field);
638       }
639       code += " " + field.name;
640       if (it != struct_def.fields.vec.end() - 1) { code += ", "; }
641     }
642     code += ") {\n";
643 
644     for (auto it = struct_def.fields.vec.rbegin();
645          it != struct_def.fields.vec.rend(); ++it) {
646       auto &field = **it;
647 
648       if (field.deprecated) continue;
649 
650       if (field.padding) {
651         code += "    fbBuilder.pad(" + NumToString(field.padding) + ");\n";
652       }
653 
654       if (IsStruct(field.value.type)) {
655         code += "    " + field.name + "();\n";
656       } else {
657         code += "    fbBuilder.put" + GenType(field.value.type) + "(";
658         code += field.name;
659         if (field.value.type.enum_def) { code += "?.value"; }
660         code += ");\n";
661       }
662     }
663     code += "    return fbBuilder.offset;\n";
664     code += "  }\n\n";
665   }
666 
TableBuilderBody(const StructDef & struct_def,std::string * code_ptr)667   void TableBuilderBody(const StructDef &struct_def, std::string *code_ptr) {
668     auto &code = *code_ptr;
669 
670     code += "  void begin() {\n";
671     code += "    fbBuilder.startTable();\n";
672     code += "  }\n\n";
673 
674     for (auto it = struct_def.fields.vec.begin();
675          it != struct_def.fields.vec.end(); ++it) {
676       auto &field = **it;
677       if (field.deprecated) continue;
678 
679       auto offset = it - struct_def.fields.vec.begin();
680 
681       if (IsScalar(field.value.type.base_type)) {
682         code += "  int add" + MakeCamel(field.name) + "(";
683         code += GenDartTypeName(field.value.type, struct_def.defined_namespace,
684                                 field);
685         code += " " + MakeCamel(field.name, false) + ") {\n";
686         code += "    fbBuilder.add" + GenType(field.value.type) + "(" +
687                 NumToString(offset) + ", ";
688         code += MakeCamel(field.name, false);
689         if (field.value.type.enum_def) { code += "?.value"; }
690         code += ");\n";
691       } else if (IsStruct(field.value.type)) {
692         code += "  int add" + MakeCamel(field.name) + "(int offset) {\n";
693         code +=
694             "    fbBuilder.addStruct(" + NumToString(offset) + ", offset);\n";
695       } else {
696         code += "  int add" + MakeCamel(field.name) + "Offset(int offset) {\n";
697         code +=
698             "    fbBuilder.addOffset(" + NumToString(offset) + ", offset);\n";
699       }
700       code += "    return fbBuilder.offset;\n";
701       code += "  }\n";
702     }
703 
704     code += "\n";
705     code += "  int finish() {\n";
706     code += "    return fbBuilder.endTable();\n";
707     code += "  }\n";
708   }
709 
GenObjectBuilder(const StructDef & struct_def,std::string * builder_name_ptr,std::string * code_ptr)710   void GenObjectBuilder(const StructDef &struct_def,
711                         std::string *builder_name_ptr, std::string *code_ptr) {
712     auto &code = *code_ptr;
713     auto &builder_name = *builder_name_ptr;
714 
715     code += "class " + builder_name + " extends " + _kFb + ".ObjectBuilder {\n";
716     for (auto it = struct_def.fields.vec.begin();
717          it != struct_def.fields.vec.end(); ++it) {
718       auto &field = **it;
719       if (field.deprecated) continue;
720       code += "  final " +
721               GenDartTypeName(field.value.type, struct_def.defined_namespace,
722                               field, true) +
723               " _" + MakeCamel(field.name, false) + ";\n";
724     }
725     code += "\n";
726     code += "  " + builder_name + "(";
727     if (struct_def.fields.vec.size() != 0) {
728       code +=
729 
730           "{\n";
731       for (auto it = struct_def.fields.vec.begin();
732            it != struct_def.fields.vec.end(); ++it) {
733         auto &field = **it;
734         if (field.deprecated) continue;
735         code += "    " +
736                 GenDartTypeName(field.value.type, struct_def.defined_namespace,
737                                 field, true) +
738                 " " + MakeCamel(field.name, false) + ",\n";
739       }
740       code += "  })\n";
741       code += "      : ";
742       for (auto it = struct_def.fields.vec.begin();
743            it != struct_def.fields.vec.end(); ++it) {
744         auto &field = **it;
745         if (field.deprecated) continue;
746         code += "_" + MakeCamel(field.name, false) + " = " +
747                 MakeCamel(field.name, false);
748         if (it == struct_def.fields.vec.end() - 1) {
749           code += ";\n\n";
750         } else {
751           code += ",\n        ";
752         }
753       }
754     } else {
755       code += ");\n\n";
756     }
757 
758     code += "  /// Finish building, and store into the [fbBuilder].\n";
759     code += "  @override\n";
760     code += "  int finish(\n";
761     code += "    " + _kFb + ".Builder fbBuilder) {\n";
762     code += "    assert(fbBuilder != null);\n";
763 
764     for (auto it = struct_def.fields.vec.begin();
765          it != struct_def.fields.vec.end(); ++it) {
766       auto &field = **it;
767       if (field.deprecated) continue;
768       if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type))
769         continue;
770 
771       code += "    final int " + MakeCamel(field.name, false) + "Offset";
772       if (field.value.type.base_type == BASE_TYPE_VECTOR) {
773         code +=
774             " = _" + MakeCamel(field.name, false) + "?.isNotEmpty == true\n";
775         code += "        ? fbBuilder.writeList";
776         switch (field.value.type.VectorType().base_type) {
777           case BASE_TYPE_STRING:
778             code += "(_" + MakeCamel(field.name, false) +
779                     ".map((b) => fbBuilder.writeString(b)).toList())";
780             break;
781           case BASE_TYPE_STRUCT:
782             if (field.value.type.struct_def->fixed) {
783               code += "OfStructs(_" + MakeCamel(field.name, false) + ")";
784             } else {
785               code += "(_" + MakeCamel(field.name, false) +
786                       ".map((b) => b.getOrCreateOffset(fbBuilder)).toList())";
787             }
788             break;
789           default:
790             code += GenType(field.value.type.VectorType()) + "(_" +
791                     MakeCamel(field.name, false);
792             if (field.value.type.enum_def) { code += ".map((f) => f.value)"; }
793             code += ")";
794         }
795         code += "\n        : null;\n";
796       } else if (field.value.type.base_type == BASE_TYPE_STRING) {
797         code += " = fbBuilder.writeString(_" + MakeCamel(field.name, false) + ");\n";
798       } else {
799         code += " = _" + MakeCamel(field.name, false) +
800                 "?.getOrCreateOffset(fbBuilder);\n";
801       }
802     }
803 
804     code += "\n";
805     if (struct_def.fixed) {
806       StructObjectBuilderBody(struct_def, code_ptr);
807     } else {
808       TableObjectBuilderBody(struct_def, code_ptr);
809     }
810     code += "  }\n\n";
811 
812     code += "  /// Convenience method to serialize to byte list.\n";
813     code += "  @override\n";
814     code += "  Uint8List toBytes([String fileIdentifier]) {\n";
815     code += "    " + _kFb + ".Builder fbBuilder = new ";
816     code += _kFb + ".Builder();\n";
817     code += "    int offset = finish(fbBuilder);\n";
818     code += "    return fbBuilder.finish(offset, fileIdentifier);\n";
819     code += "  }\n";
820     code += "}\n";
821   }
822 
StructObjectBuilderBody(const StructDef & struct_def,std::string * code_ptr,bool prependUnderscore=true)823   void StructObjectBuilderBody(const StructDef &struct_def,
824                                std::string *code_ptr,
825                                bool prependUnderscore = true) {
826     auto &code = *code_ptr;
827 
828     for (auto it = struct_def.fields.vec.rbegin();
829          it != struct_def.fields.vec.rend(); ++it) {
830       auto &field = **it;
831 
832       if (field.deprecated) continue;
833 
834       if (field.padding) {
835         code += "    fbBuilder.pad(" + NumToString(field.padding) + ");\n";
836       }
837 
838       if (IsStruct(field.value.type)) {
839         code += "    ";
840         if (prependUnderscore) { code += "_"; }
841         code += field.name + ".finish(fbBuilder);\n";
842       } else {
843         code += "    fbBuilder.put" + GenType(field.value.type) + "(";
844         if (prependUnderscore) { code += "_"; }
845         code += field.name;
846         if (field.value.type.enum_def) { code += "?.value"; }
847         code += ");\n";
848       }
849     }
850 
851     code += "    return fbBuilder.offset;\n";
852   }
853 
TableObjectBuilderBody(const StructDef & struct_def,std::string * code_ptr,bool prependUnderscore=true)854   void TableObjectBuilderBody(const StructDef &struct_def,
855                               std::string *code_ptr,
856                               bool prependUnderscore = true) {
857     std::string &code = *code_ptr;
858     code += "    fbBuilder.startTable();\n";
859 
860     for (auto it = struct_def.fields.vec.begin();
861          it != struct_def.fields.vec.end(); ++it) {
862       auto &field = **it;
863 
864       if (field.deprecated) continue;
865 
866       auto offset = it - struct_def.fields.vec.begin();
867       if (IsScalar(field.value.type.base_type)) {
868         code += "    fbBuilder.add" + GenType(field.value.type) + "(" +
869                 NumToString(offset) + ", ";
870         if (prependUnderscore) { code += "_"; }
871         code += MakeCamel(field.name, false);
872         if (field.value.type.enum_def) { code += "?.value"; }
873         code += ");\n";
874       } else if (IsStruct(field.value.type)) {
875         code += "    if (";
876         if (prependUnderscore) { code += "_"; }
877         code += MakeCamel(field.name, false) + " != null) {\n";
878         code += "      fbBuilder.addStruct(" + NumToString(offset) + ", ";
879         code += "_" + MakeCamel(field.name, false) + ".finish(fbBuilder));\n";
880         code += "    }\n";
881       } else {
882         code +=
883             "    if (" + MakeCamel(field.name, false) + "Offset != null) {\n";
884         code += "      fbBuilder.addOffset(" + NumToString(offset) + ", " +
885                 MakeCamel(field.name, false) + "Offset);\n";
886         code += "    }\n";
887       }
888     }
889     code += "    return fbBuilder.endTable();\n";
890   }
891 };
892 }  // namespace dart
893 
GenerateDart(const Parser & parser,const std::string & path,const std::string & file_name)894 bool GenerateDart(const Parser &parser, const std::string &path,
895                   const std::string &file_name) {
896   dart::DartGenerator generator(parser, path, file_name);
897   return generator.generate();
898 }
899 
DartMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)900 std::string DartMakeRule(const Parser &parser, const std::string &path,
901                          const std::string &file_name) {
902   assert(parser.opts.lang <= IDLOptions::kMAX);
903 
904   auto filebase =
905       flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
906   auto make_rule = GeneratedFileName(path, filebase) + ": ";
907 
908   auto included_files = parser.GetIncludedFilesRecursive(file_name);
909   for (auto it = included_files.begin(); it != included_files.end(); ++it) {
910     make_rule += " " + *it;
911   }
912   return make_rule;
913 }
914 
915 }  // namespace flatbuffers
916