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