1 /*
2 * Copyright 2014 Google Inc. All rights reserved.
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 #include "idl_gen_ts.h"
18
19 #include <algorithm>
20 #include <cassert>
21 #include <cmath>
22 #include <iostream>
23 #include <unordered_map>
24 #include <unordered_set>
25
26 #include "flatbuffers/code_generators.h"
27 #include "flatbuffers/flatbuffers.h"
28 #include "flatbuffers/flatc.h"
29 #include "flatbuffers/idl.h"
30 #include "flatbuffers/util.h"
31 #include "idl_namer.h"
32
33 namespace flatbuffers {
34 namespace {
35 struct ImportDefinition {
36 std::string name;
37 std::string import_statement;
38 std::string export_statement;
39 std::string bare_file_path;
40 std::string rel_file_path;
41 std::string object_name;
42 const Definition *dependent = nullptr;
43 const Definition *dependency = nullptr;
44 };
45
46 struct NsDefinition {
47 std::string path;
48 std::string filepath;
49 std::string symbolic_name;
50 const Namespace *ns;
51 std::map<std::string, const Definition *> definitions;
52 };
53
TypeScriptDefaultConfig()54 Namer::Config TypeScriptDefaultConfig() {
55 return { /*types=*/Case::kKeep,
56 /*constants=*/Case::kUnknown,
57 /*methods=*/Case::kLowerCamel,
58 /*functions=*/Case::kLowerCamel,
59 /*fields=*/Case::kLowerCamel,
60 /*variables=*/Case::kLowerCamel,
61 /*variants=*/Case::kKeep,
62 /*enum_variant_seperator=*/"::",
63 /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
64 /*namespaces=*/Case::kKeep,
65 /*namespace_seperator=*/"_",
66 /*object_prefix=*/"",
67 /*object_suffix=*/"T",
68 /*keyword_prefix=*/"",
69 /*keyword_suffix=*/"_",
70 /*filenames=*/Case::kDasher,
71 /*directories=*/Case::kDasher,
72 /*output_path=*/"",
73 /*filename_suffix=*/"_generated",
74 /*filename_extension=*/".ts" };
75 }
76
TypescriptKeywords()77 std::set<std::string> TypescriptKeywords() {
78 // List of keywords retrieved from here:
79 // https://github.com/microsoft/TypeScript/issues/2536
80 return {
81 "arguments", "break", "case", "catch", "class", "const",
82 "continue", "debugger", "default", "delete", "do", "else",
83 "enum", "export", "extends", "false", "finally", "for",
84 "function", "if", "import", "in", "instanceof", "new",
85 "null", "Object", "return", "super", "switch", "this",
86 "throw", "true", "try", "typeof", "var", "void",
87 "while", "with", "as", "implements", "interface", "let",
88 "package", "private", "protected", "public", "static", "yield",
89 };
90 }
91
92 enum AnnotationType { kParam = 0, kType = 1, kReturns = 2 };
93
94 template<typename T> struct SupportsObjectAPI : std::false_type {};
95
96 template<> struct SupportsObjectAPI<StructDef> : std::true_type {};
97
98 } // namespace
99
100 namespace ts {
101 // Iterate through all definitions we haven't generate code for (enums, structs,
102 // and tables) and output them to a single file.
103 class TsGenerator : public BaseGenerator {
104 public:
105 typedef std::map<std::string, ImportDefinition> import_set;
106
TsGenerator(const Parser & parser,const std::string & path,const std::string & file_name)107 TsGenerator(const Parser &parser, const std::string &path,
108 const std::string &file_name)
109 : BaseGenerator(parser, path, file_name, "", "_", "ts"),
110 namer_(WithFlagOptions(TypeScriptDefaultConfig(), parser.opts, path),
111 TypescriptKeywords()) {}
112
generate()113 bool generate() {
114 generateEnums();
115 generateStructs();
116 if (!parser_.opts.ts_omit_entrypoint) { generateEntry(); }
117 if (!generateBundle()) return false;
118 return true;
119 }
120
GetTypeName(const EnumDef & def,const bool=false,const bool force_ns_wrap=false)121 std::string GetTypeName(const EnumDef &def, const bool = false,
122 const bool force_ns_wrap = false) {
123 if (force_ns_wrap) { return namer_.NamespacedType(def); }
124 return namer_.Type(def);
125 }
126
GetTypeName(const StructDef & def,const bool object_api=false,const bool force_ns_wrap=false)127 std::string GetTypeName(const StructDef &def, const bool object_api = false,
128 const bool force_ns_wrap = false) {
129 if (object_api && parser_.opts.generate_object_based_api) {
130 if (force_ns_wrap) {
131 return namer_.NamespacedObjectType(def);
132 } else {
133 return namer_.ObjectType(def);
134 }
135 } else {
136 if (force_ns_wrap) {
137 return namer_.NamespacedType(def);
138 } else {
139 return namer_.Type(def);
140 }
141 }
142 }
143
144 // Save out the generated code for a single class while adding
145 // declaration boilerplate.
SaveType(const Definition & definition,const std::string & class_code,import_set & imports,import_set & bare_imports)146 bool SaveType(const Definition &definition, const std::string &class_code,
147 import_set &imports, import_set &bare_imports) {
148 if (!class_code.length()) return true;
149
150 std::string code;
151
152 code += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n" +
153 "/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */\n\n";
154
155 for (auto it = bare_imports.begin(); it != bare_imports.end(); it++) {
156 code += it->second.import_statement + "\n";
157 }
158 if (!bare_imports.empty()) code += "\n";
159
160 for (auto it = imports.begin(); it != imports.end(); it++) {
161 if (it->second.dependency != &definition) {
162 code += it->second.import_statement + "\n";
163 }
164 }
165 if (!imports.empty()) code += "\n\n";
166
167 code += class_code;
168
169 auto dirs = namer_.Directories(*definition.defined_namespace);
170 EnsureDirExists(dirs);
171 auto basename = dirs + namer_.File(definition, SkipFile::Suffix);
172
173 return SaveFile(basename.c_str(), code, false);
174 }
175
TrackNsDef(const Definition & definition,std::string type_name)176 void TrackNsDef(const Definition &definition, std::string type_name) {
177 std::string path;
178 std::string filepath;
179 std::string symbolic_name;
180 if (definition.defined_namespace->components.size() > 0) {
181 path = namer_.Directories(*definition.defined_namespace,
182 SkipDir::TrailingPathSeperator);
183 filepath = path + ".ts";
184 path = namer_.Directories(*definition.defined_namespace,
185 SkipDir::OutputPathAndTrailingPathSeparator);
186 symbolic_name = definition.defined_namespace->components.back();
187 } else {
188 auto def_mod_name = namer_.File(definition, SkipFile::SuffixAndExtension);
189 symbolic_name = file_name_;
190 filepath = path_ + symbolic_name + ".ts";
191 }
192 if (ns_defs_.count(path) == 0) {
193 NsDefinition nsDef;
194 nsDef.path = path;
195 nsDef.filepath = filepath;
196 nsDef.ns = definition.defined_namespace;
197 nsDef.definitions.insert(std::make_pair(type_name, &definition));
198 nsDef.symbolic_name = symbolic_name;
199 ns_defs_[path] = nsDef;
200 } else {
201 ns_defs_[path].definitions.insert(std::make_pair(type_name, &definition));
202 }
203 }
204
205 private:
206 IdlNamer namer_;
207
208 std::map<std::string, NsDefinition> ns_defs_;
209
210 // Generate code for all enums.
generateEnums()211 void generateEnums() {
212 for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
213 ++it) {
214 import_set bare_imports;
215 import_set imports;
216 std::string enumcode;
217 auto &enum_def = **it;
218 GenEnum(enum_def, &enumcode, imports, false);
219 GenEnum(enum_def, &enumcode, imports, true);
220 std::string type_name = GetTypeName(enum_def);
221 TrackNsDef(enum_def, type_name);
222 SaveType(enum_def, enumcode, imports, bare_imports);
223 }
224 }
225
226 // Generate code for all structs.
generateStructs()227 void generateStructs() {
228 for (auto it = parser_.structs_.vec.begin();
229 it != parser_.structs_.vec.end(); ++it) {
230 import_set bare_imports;
231 import_set imports;
232 AddImport(bare_imports, "* as flatbuffers", "flatbuffers");
233 auto &struct_def = **it;
234 std::string declcode;
235 GenStruct(parser_, struct_def, &declcode, imports);
236 std::string type_name = GetTypeName(struct_def);
237 TrackNsDef(struct_def, type_name);
238 SaveType(struct_def, declcode, imports, bare_imports);
239 }
240 }
241
242 // Generate code for a single entry point module.
generateEntry()243 void generateEntry() {
244 std::string code;
245
246 // add root namespace def if not already existing from defs tracking
247 std::string root;
248 if (ns_defs_.count(root) == 0) {
249 NsDefinition nsDef;
250 nsDef.path = root;
251 nsDef.symbolic_name = file_name_;
252 nsDef.filepath = path_ + file_name_ + ".ts";
253 nsDef.ns = new Namespace();
254 ns_defs_[nsDef.path] = nsDef;
255 }
256
257 for (const auto &it : ns_defs_) {
258 code = "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n" +
259 "/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */\n\n";
260
261 // export all definitions in ns entry point module
262 int export_counter = 0;
263 for (const auto &def : it.second.definitions) {
264 std::vector<std::string> rel_components;
265 // build path for root level vs child level
266 if (it.second.ns->components.size() > 1)
267 std::copy(it.second.ns->components.begin() + 1,
268 it.second.ns->components.end(),
269 std::back_inserter(rel_components));
270 else
271 std::copy(it.second.ns->components.begin(),
272 it.second.ns->components.end(),
273 std::back_inserter(rel_components));
274 auto base_file_name =
275 namer_.File(*(def.second), SkipFile::SuffixAndExtension);
276 auto base_name =
277 namer_.Directories(it.second.ns->components, SkipDir::OutputPath) +
278 base_file_name;
279 auto ts_file_path = base_name + ".ts";
280 auto base_name_rel = std::string("./");
281 base_name_rel +=
282 namer_.Directories(rel_components, SkipDir::OutputPath);
283 base_name_rel += base_file_name;
284 auto ts_file_path_rel = base_name_rel + ".ts";
285 auto type_name = def.first;
286 auto fully_qualified_type_name =
287 it.second.ns->GetFullyQualifiedName(type_name);
288 auto is_struct = parser_.structs_.Lookup(fully_qualified_type_name);
289 code += "export { " + type_name;
290 if (parser_.opts.generate_object_based_api && is_struct) {
291 code += ", " + type_name + parser_.opts.object_suffix;
292 }
293 code += " } from '";
294 std::string import_extension =
295 parser_.opts.ts_no_import_ext ? "" : ".js";
296 code += base_name_rel + import_extension + "';\n";
297 export_counter++;
298 }
299
300 // re-export child namespace(s) in parent
301 const auto child_ns_level = it.second.ns->components.size() + 1;
302 for (const auto &it2 : ns_defs_) {
303 if (it2.second.ns->components.size() != child_ns_level) continue;
304 auto ts_file_path = it2.second.path + ".ts";
305 code += "export * as " + it2.second.symbolic_name + " from './";
306 std::string rel_path = it2.second.path;
307 code += rel_path + ".js';\n";
308 export_counter++;
309 }
310
311 if (export_counter > 0) SaveFile(it.second.filepath.c_str(), code, false);
312 }
313 }
314
generateBundle()315 bool generateBundle() {
316 if (parser_.opts.ts_flat_files) {
317 std::string inputpath;
318 std::string symbolic_name = file_name_;
319 inputpath = path_ + file_name_ + ".ts";
320 std::string bundlepath =
321 GeneratedFileName(path_, file_name_, parser_.opts);
322 bundlepath = bundlepath.substr(0, bundlepath.size() - 3) + ".js";
323 std::string cmd = "esbuild";
324 cmd += " ";
325 cmd += inputpath;
326 // cmd += " --minify";
327 cmd += " --format=cjs --bundle --outfile=";
328 cmd += bundlepath;
329 cmd += " --external:flatbuffers";
330 std::cout << "Entry point " << inputpath << " generated." << std::endl;
331 std::cout << "A single file bundle can be created using fx. esbuild with:"
332 << std::endl;
333 std::cout << "> " << cmd << std::endl;
334 }
335 return true;
336 }
337
338 // Generate a documentation comment, if available.
GenDocComment(const std::vector<std::string> & dc,std::string * code_ptr,const char * indent=nullptr)339 static void GenDocComment(const std::vector<std::string> &dc,
340 std::string *code_ptr,
341 const char *indent = nullptr) {
342 if (dc.empty()) {
343 // Don't output empty comment blocks with 0 lines of comment content.
344 return;
345 }
346
347 std::string &code = *code_ptr;
348 if (indent) code += indent;
349 code += "/**\n";
350 for (auto it = dc.begin(); it != dc.end(); ++it) {
351 if (indent) code += indent;
352 code += " *" + *it + "\n";
353 }
354 if (indent) code += indent;
355 code += " */\n";
356 }
357
GenDocComment(std::string * code_ptr)358 static void GenDocComment(std::string *code_ptr) {
359 GenDocComment(std::vector<std::string>(), code_ptr);
360 }
361
362 // Generate an enum declaration and an enum string lookup table.
GenEnum(EnumDef & enum_def,std::string * code_ptr,import_set & imports,bool reverse)363 void GenEnum(EnumDef &enum_def, std::string *code_ptr, import_set &imports,
364 bool reverse) {
365 if (enum_def.generated) return;
366 if (reverse) return; // FIXME.
367 std::string &code = *code_ptr;
368 GenDocComment(enum_def.doc_comment, code_ptr);
369 code += "export enum ";
370 code += GetTypeName(enum_def);
371 code += " {\n";
372 for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
373 auto &ev = **it;
374 if (!ev.doc_comment.empty()) {
375 if (it != enum_def.Vals().begin()) { code += '\n'; }
376 GenDocComment(ev.doc_comment, code_ptr, " ");
377 }
378
379 // Generate mapping between EnumName: EnumValue(int)
380 if (reverse) {
381 code += " '" + enum_def.ToString(ev) + "'";
382 code += " = ";
383 code += "'" + namer_.Variant(ev) + "'";
384 } else {
385 code += " " + namer_.Variant(ev);
386 code += " = ";
387 // Unfortunately, because typescript does not support bigint enums,
388 // for 64-bit enums, we instead map the enum names to strings.
389 switch (enum_def.underlying_type.base_type) {
390 case BASE_TYPE_LONG:
391 case BASE_TYPE_ULONG: {
392 code += "'" + enum_def.ToString(ev) + "'";
393 break;
394 }
395 default: code += enum_def.ToString(ev);
396 }
397 }
398
399 code += (it + 1) != enum_def.Vals().end() ? ",\n" : "\n";
400 }
401 code += "}";
402
403 if (enum_def.is_union) {
404 code += GenUnionConvFunc(enum_def.underlying_type, imports);
405 }
406
407 code += "\n";
408 }
409
GenType(const Type & type)410 static std::string GenType(const Type &type) {
411 switch (type.base_type) {
412 case BASE_TYPE_BOOL:
413 case BASE_TYPE_CHAR: return "Int8";
414 case BASE_TYPE_UTYPE: return GenType(GetUnionUnderlyingType(type));
415 case BASE_TYPE_UCHAR: return "Uint8";
416 case BASE_TYPE_SHORT: return "Int16";
417 case BASE_TYPE_USHORT: return "Uint16";
418 case BASE_TYPE_INT: return "Int32";
419 case BASE_TYPE_UINT: return "Uint32";
420 case BASE_TYPE_LONG: return "Int64";
421 case BASE_TYPE_ULONG: return "Uint64";
422 case BASE_TYPE_FLOAT: return "Float32";
423 case BASE_TYPE_DOUBLE: return "Float64";
424 case BASE_TYPE_STRING: return "String";
425 case BASE_TYPE_VECTOR: return GenType(type.VectorType());
426 case BASE_TYPE_STRUCT: return type.struct_def->name;
427 default: return "flatbuffers.Table";
428 }
429 }
430
GenGetter(const Type & type,const std::string & arguments)431 std::string GenGetter(const Type &type, const std::string &arguments) {
432 switch (type.base_type) {
433 case BASE_TYPE_STRING: return GenBBAccess() + ".__string" + arguments;
434 case BASE_TYPE_STRUCT: return GenBBAccess() + ".__struct" + arguments;
435 case BASE_TYPE_UNION:
436 if (!UnionHasStringType(*type.enum_def)) {
437 return GenBBAccess() + ".__union" + arguments;
438 }
439 return GenBBAccess() + ".__union_with_string" + arguments;
440 case BASE_TYPE_VECTOR: return GenGetter(type.VectorType(), arguments);
441 default: {
442 auto getter = GenBBAccess() + "." + "read" + GenType(type) + arguments;
443 if (type.base_type == BASE_TYPE_BOOL) { getter = "!!" + getter; }
444 return getter;
445 }
446 }
447 }
448
GenBBAccess() const449 std::string GenBBAccess() const { return "this.bb!"; }
450
GenDefaultValue(const FieldDef & field,import_set & imports)451 std::string GenDefaultValue(const FieldDef &field, import_set &imports) {
452 if (field.IsScalarOptional()) { return "null"; }
453
454 const auto &value = field.value;
455 if (value.type.enum_def && value.type.base_type != BASE_TYPE_UNION &&
456 value.type.base_type != BASE_TYPE_VECTOR) {
457 switch (value.type.base_type) {
458 case BASE_TYPE_ARRAY: {
459 std::string ret = "[";
460 for (auto i = 0; i < value.type.fixed_length; ++i) {
461 std::string enum_name =
462 AddImport(imports, *value.type.enum_def, *value.type.enum_def)
463 .name;
464 std::string enum_value = namer_.Variant(
465 *value.type.enum_def->FindByValue(value.constant));
466 ret += enum_name + "." + enum_value +
467 (i < value.type.fixed_length - 1 ? ", " : "");
468 }
469 ret += "]";
470 return ret;
471 }
472 case BASE_TYPE_LONG:
473 case BASE_TYPE_ULONG: {
474 // If the value is an enum with a 64-bit base type, we have to just
475 // return the bigint value directly since typescript does not support
476 // enums with bigint backing types.
477 return "BigInt('" + value.constant + "')";
478 }
479 default: {
480 EnumVal *val = value.type.enum_def->FindByValue(value.constant);
481 if (val == nullptr)
482 val = const_cast<EnumVal *>(value.type.enum_def->MinValue());
483 return AddImport(imports, *value.type.enum_def, *value.type.enum_def)
484 .name +
485 "." + namer_.Variant(*val);
486 }
487 }
488 }
489
490 switch (value.type.base_type) {
491 case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
492
493 case BASE_TYPE_STRING:
494 case BASE_TYPE_UNION:
495 case BASE_TYPE_STRUCT: {
496 return "null";
497 }
498
499 case BASE_TYPE_ARRAY:
500 case BASE_TYPE_VECTOR: return "[]";
501
502 case BASE_TYPE_LONG:
503 case BASE_TYPE_ULONG: {
504 return "BigInt('" + value.constant + "')";
505 }
506
507 default: {
508 if (StringIsFlatbufferNan(value.constant)) {
509 return "NaN";
510 } else if (StringIsFlatbufferPositiveInfinity(value.constant)) {
511 return "Infinity";
512 } else if (StringIsFlatbufferNegativeInfinity(value.constant)) {
513 return "-Infinity";
514 }
515 return value.constant;
516 }
517 }
518 }
519
GenTypeName(import_set & imports,const Definition & owner,const Type & type,bool input,bool allowNull=false)520 std::string GenTypeName(import_set &imports, const Definition &owner,
521 const Type &type, bool input,
522 bool allowNull = false) {
523 if (!input) {
524 if (IsString(type) || type.base_type == BASE_TYPE_STRUCT) {
525 std::string name;
526 if (IsString(type)) {
527 name = "string|Uint8Array";
528 } else {
529 name = AddImport(imports, owner, *type.struct_def).name;
530 }
531 return allowNull ? (name + "|null") : name;
532 }
533 }
534
535 switch (type.base_type) {
536 case BASE_TYPE_BOOL: return allowNull ? "boolean|null" : "boolean";
537 case BASE_TYPE_LONG:
538 case BASE_TYPE_ULONG: return allowNull ? "bigint|null" : "bigint";
539 case BASE_TYPE_ARRAY: {
540 std::string name;
541 if (type.element == BASE_TYPE_LONG || type.element == BASE_TYPE_ULONG) {
542 name = "bigint[]";
543 } else if (type.element != BASE_TYPE_STRUCT) {
544 name = "number[]";
545 } else {
546 name = "any[]";
547 if (parser_.opts.generate_object_based_api) {
548 name = "(any|" +
549 GetTypeName(*type.struct_def, /*object_api =*/true) + ")[]";
550 }
551 }
552
553 return name + (allowNull ? "|null" : "");
554 }
555 default:
556 if (IsScalar(type.base_type)) {
557 if (type.enum_def) {
558 const auto enum_name =
559 AddImport(imports, owner, *type.enum_def).name;
560 return allowNull ? (enum_name + "|null") : enum_name;
561 }
562 return allowNull ? "number|null" : "number";
563 }
564 return "flatbuffers.Offset";
565 }
566 }
567
GetUnionUnderlyingType(const Type & type)568 static Type GetUnionUnderlyingType(const Type &type)
569 {
570 if (type.enum_def != nullptr &&
571 type.enum_def->underlying_type.base_type != type.base_type) {
572 return type.enum_def->underlying_type;
573 } else {
574 return Type(BASE_TYPE_UCHAR);
575 }
576 }
577
GetUnderlyingVectorType(const Type & vector_type)578 static Type GetUnderlyingVectorType(const Type &vector_type)
579 {
580 return (vector_type.base_type == BASE_TYPE_UTYPE) ? GetUnionUnderlyingType(vector_type) : vector_type;
581 }
582
583 // Returns the method name for use with add/put calls.
GenWriteMethod(const Type & type)584 std::string GenWriteMethod(const Type &type) {
585 // Forward to signed versions since unsigned versions don't exist
586 switch (type.base_type) {
587 case BASE_TYPE_UTYPE: return GenWriteMethod(GetUnionUnderlyingType(type));
588 case BASE_TYPE_UCHAR: return GenWriteMethod(Type(BASE_TYPE_CHAR));
589 case BASE_TYPE_USHORT: return GenWriteMethod(Type(BASE_TYPE_SHORT));
590 case BASE_TYPE_UINT: return GenWriteMethod(Type(BASE_TYPE_INT));
591 case BASE_TYPE_ULONG: return GenWriteMethod(Type(BASE_TYPE_LONG));
592 default: break;
593 }
594
595 return IsScalar(type.base_type) ? namer_.Type(GenType(type))
596 : (IsStruct(type) ? "Struct" : "Offset");
597 }
598
MaybeAdd(T value)599 template<typename T> static std::string MaybeAdd(T value) {
600 return value != 0 ? " + " + NumToString(value) : "";
601 }
602
MaybeScale(T value)603 template<typename T> static std::string MaybeScale(T value) {
604 return value != 1 ? " * " + NumToString(value) : "";
605 }
606
GenStructArgs(import_set & imports,const StructDef & struct_def,std::string * arguments,const std::string & nameprefix)607 void GenStructArgs(import_set &imports, const StructDef &struct_def,
608 std::string *arguments, const std::string &nameprefix) {
609 for (auto it = struct_def.fields.vec.begin();
610 it != struct_def.fields.vec.end(); ++it) {
611 auto &field = **it;
612 if (IsStruct(field.value.type)) {
613 // Generate arguments for a struct inside a struct. To ensure names
614 // don't clash, and to make it obvious these arguments are constructing
615 // a nested struct, prefix the name with the field name.
616 GenStructArgs(imports, *field.value.type.struct_def, arguments,
617 nameprefix + field.name + "_");
618 } else {
619 *arguments += ", " + nameprefix + field.name + ": " +
620 GenTypeName(imports, field, field.value.type, true,
621 field.IsOptional());
622 }
623 }
624 }
625
GenStructBody(const StructDef & struct_def,std::string * body,const std::string & nameprefix)626 void GenStructBody(const StructDef &struct_def, std::string *body,
627 const std::string &nameprefix) {
628 *body += " builder.prep(";
629 *body += NumToString(struct_def.minalign) + ", ";
630 *body += NumToString(struct_def.bytesize) + ");\n";
631
632 for (auto it = struct_def.fields.vec.rbegin();
633 it != struct_def.fields.vec.rend(); ++it) {
634 auto &field = **it;
635 if (field.padding) {
636 *body += " builder.pad(" + NumToString(field.padding) + ");\n";
637 }
638 if (IsStruct(field.value.type)) {
639 // Generate arguments for a struct inside a struct. To ensure names
640 // don't clash, and to make it obvious these arguments are constructing
641 // a nested struct, prefix the name with the field name.
642 GenStructBody(
643 *field.value.type.struct_def, body,
644 nameprefix.length() ? nameprefix + "_" + field.name : field.name);
645 } else {
646 auto element_type = field.value.type.element;
647
648 if (field.value.type.base_type == BASE_TYPE_ARRAY) {
649 switch (field.value.type.element) {
650 case BASE_TYPE_STRUCT: {
651 std::string str_last_item_idx =
652 NumToString(field.value.type.fixed_length - 1);
653 *body += "\n for (let i = " + str_last_item_idx +
654 "; i >= 0; --i" + ") {\n";
655
656 std::string fname = nameprefix.length()
657 ? nameprefix + "_" + field.name
658 : field.name;
659
660 *body += " const item = " + fname + "?.[i];\n\n";
661
662 if (parser_.opts.generate_object_based_api) {
663 *body += " if (item instanceof " +
664 GetTypeName(*field.value.type.struct_def,
665 /*object_api =*/true) +
666 ") {\n";
667 *body += " item.pack(builder);\n";
668 *body += " continue;\n";
669 *body += " }\n\n";
670 }
671
672 std::string class_name =
673 GetPrefixedName(*field.value.type.struct_def);
674 std::string pack_func_create_call =
675 class_name + ".create" + class_name + "(builder,\n";
676 pack_func_create_call +=
677 " " +
678 GenStructMemberValueTS(*field.value.type.struct_def, "item",
679 ",\n ", false) +
680 "\n ";
681 *body += " " + pack_func_create_call;
682 *body += " );\n }\n\n";
683
684 break;
685 }
686 default: {
687 std::string str_last_item_idx =
688 NumToString(field.value.type.fixed_length - 1);
689 std::string fname = nameprefix.length()
690 ? nameprefix + "_" + field.name
691 : field.name;
692
693 *body += "\n for (let i = " + str_last_item_idx +
694 "; i >= 0; --i) {\n";
695 *body += " builder.write";
696 *body += GenWriteMethod(
697 static_cast<flatbuffers::Type>(field.value.type.element));
698 *body += "(";
699 *body += element_type == BASE_TYPE_BOOL ? "+" : "";
700
701 if (element_type == BASE_TYPE_LONG ||
702 element_type == BASE_TYPE_ULONG) {
703 *body += "BigInt(" + fname + "?.[i] ?? 0));\n";
704 } else {
705 *body += "(" + fname + "?.[i] ?? 0));\n\n";
706 }
707 *body += " }\n\n";
708 break;
709 }
710 }
711 } else {
712 std::string fname =
713 nameprefix.length() ? nameprefix + "_" + field.name : field.name;
714
715 *body += " builder.write" + GenWriteMethod(field.value.type) + "(";
716 if (field.value.type.base_type == BASE_TYPE_BOOL) {
717 *body += "Number(Boolean(" + fname + ")));\n";
718 continue;
719 } else if (field.value.type.base_type == BASE_TYPE_LONG ||
720 field.value.type.base_type == BASE_TYPE_ULONG) {
721 *body += "BigInt(" + fname + " ?? 0));\n";
722 continue;
723 }
724
725 *body += fname + ");\n";
726 }
727 }
728 }
729 }
730
GenerateNewExpression(const std::string & object_name)731 std::string GenerateNewExpression(const std::string &object_name) {
732 return "new " + namer_.Type(object_name) + "()";
733 }
734
GenerateRootAccessor(StructDef & struct_def,std::string * code_ptr,std::string & code,const std::string & object_name,bool size_prefixed)735 void GenerateRootAccessor(StructDef &struct_def, std::string *code_ptr,
736 std::string &code, const std::string &object_name,
737 bool size_prefixed) {
738 if (!struct_def.fixed) {
739 GenDocComment(code_ptr);
740 std::string sizePrefixed("SizePrefixed");
741 code += "static get" + (size_prefixed ? sizePrefixed : "") + "Root" +
742 GetPrefixedName(struct_def, "As");
743 code += "(bb:flatbuffers.ByteBuffer, obj?:" + object_name +
744 "):" + object_name + " {\n";
745 if (size_prefixed) {
746 code +=
747 " bb.setPosition(bb.position() + "
748 "flatbuffers.SIZE_PREFIX_LENGTH);\n";
749 }
750 code += " return (obj || " + GenerateNewExpression(object_name);
751 code += ").__init(bb.readInt32(bb.position()) + bb.position(), bb);\n";
752 code += "}\n\n";
753 }
754 }
755
GenerateFinisher(StructDef & struct_def,std::string * code_ptr,std::string & code,bool size_prefixed)756 void GenerateFinisher(StructDef &struct_def, std::string *code_ptr,
757 std::string &code, bool size_prefixed) {
758 if (parser_.root_struct_def_ == &struct_def) {
759 std::string sizePrefixed("SizePrefixed");
760 GenDocComment(code_ptr);
761
762 code += "static finish" + (size_prefixed ? sizePrefixed : "") +
763 GetPrefixedName(struct_def) + "Buffer";
764 code += "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n";
765 code += " builder.finish(offset";
766 if (!parser_.file_identifier_.empty()) {
767 code += ", '" + parser_.file_identifier_ + "'";
768 }
769 if (size_prefixed) {
770 if (parser_.file_identifier_.empty()) { code += ", undefined"; }
771 code += ", true";
772 }
773 code += ");\n";
774 code += "}\n\n";
775 }
776 }
777
UnionHasStringType(const EnumDef & union_enum)778 bool UnionHasStringType(const EnumDef &union_enum) {
779 return std::any_of(union_enum.Vals().begin(), union_enum.Vals().end(),
780 [](const EnumVal *ev) {
781 return !ev->IsZero() && IsString(ev->union_type);
782 });
783 }
784
GenUnionGenericTypeTS(const EnumDef & union_enum)785 std::string GenUnionGenericTypeTS(const EnumDef &union_enum) {
786 // TODO: make it work without any
787 // return std::string("T") + (UnionHasStringType(union_enum) ? "|string" :
788 // "");
789 return std::string("any") +
790 (UnionHasStringType(union_enum) ? "|string" : "");
791 }
792
GenUnionTypeTS(const EnumDef & union_enum,import_set & imports)793 std::string GenUnionTypeTS(const EnumDef &union_enum, import_set &imports) {
794 std::string ret;
795 std::set<std::string> type_list;
796
797 for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
798 ++it) {
799 const auto &ev = **it;
800 if (ev.IsZero()) { continue; }
801
802 std::string type = "";
803 if (IsString(ev.union_type)) {
804 type = "string"; // no need to wrap string type in namespace
805 } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
806 type = AddImport(imports, union_enum, *ev.union_type.struct_def).name;
807 } else {
808 FLATBUFFERS_ASSERT(false);
809 }
810 type_list.insert(type);
811 }
812
813 for (auto it = type_list.begin(); it != type_list.end(); ++it) {
814 ret += *it + ((std::next(it) == type_list.end()) ? "" : "|");
815 }
816
817 return ret;
818 }
819
CheckIfNameClashes(const import_set & imports,const std::string & name)820 static bool CheckIfNameClashes(const import_set &imports,
821 const std::string &name) {
822 // TODO: this would be better as a hashset.
823 for (auto it = imports.begin(); it != imports.end(); it++) {
824 if (it->second.name == name) { return true; }
825 }
826 return false;
827 }
828
GenSymbolExpression(const StructDef & struct_def,const bool has_name_clash,const std::string & import_name,const std::string & name,const std::string & object_name)829 std::string GenSymbolExpression(const StructDef &struct_def,
830 const bool has_name_clash,
831 const std::string &import_name,
832 const std::string &name,
833 const std::string &object_name) {
834 std::string symbols_expression;
835
836 if (has_name_clash) {
837 // We have a name clash
838 symbols_expression += import_name + " as " + name;
839
840 if (parser_.opts.generate_object_based_api) {
841 symbols_expression += ", " +
842 GetTypeName(struct_def, /*object_api =*/true) +
843 " as " + object_name;
844 }
845 } else {
846 // No name clash, use the provided name
847 symbols_expression += name;
848
849 if (parser_.opts.generate_object_based_api) {
850 symbols_expression += ", " + object_name;
851 }
852 }
853
854 return symbols_expression;
855 }
856
GenSymbolExpression(const EnumDef & enum_def,const bool has_name_clash,const std::string & import_name,const std::string & name,const std::string &)857 std::string GenSymbolExpression(const EnumDef &enum_def,
858 const bool has_name_clash,
859 const std::string &import_name,
860 const std::string &name,
861 const std::string &) {
862 std::string symbols_expression;
863 if (has_name_clash) {
864 symbols_expression += import_name + " as " + name;
865 } else {
866 symbols_expression += name;
867 }
868
869 if (enum_def.is_union) {
870 symbols_expression += (", " + namer_.Function("unionTo" + name));
871 symbols_expression += (", " + namer_.Function("unionListTo" + name));
872 }
873
874 return symbols_expression;
875 }
876
877 template<typename DefinitionT>
AddImport(import_set & imports,const Definition & dependent,const DefinitionT & dependency)878 ImportDefinition AddImport(import_set &imports, const Definition &dependent,
879 const DefinitionT &dependency) {
880 // The unique name of the dependency, fully qualified in its namespace.
881 const std::string unique_name = GetTypeName(
882 dependency, /*object_api = */ false, /*force_ns_wrap=*/true);
883
884 // Look if we have already added this import and return its name if found.
885 const auto import_pair = imports.find(unique_name);
886 if (import_pair != imports.end()) { return import_pair->second; }
887
888 // Check if this name would have a name clash with another type. Just use
889 // the "base" name (properly escaped) without any namespacing applied.
890 const std::string import_name = GetTypeName(dependency);
891 const bool has_name_clash = CheckIfNameClashes(imports, import_name);
892
893 // If we have a name clash, use the unique name, otherwise use simple name.
894 std::string name = has_name_clash ? unique_name : import_name;
895
896 const std::string object_name =
897 GetTypeName(dependency, /*object_api=*/true, has_name_clash);
898
899 const std::string symbols_expression = GenSymbolExpression(
900 dependency, has_name_clash, import_name, name, object_name);
901
902 std::string bare_file_path;
903 std::string rel_file_path;
904 const auto &dep_comps = dependent.defined_namespace->components;
905 for (size_t i = 0; i < dep_comps.size(); i++) {
906 rel_file_path += i == 0 ? ".." : (kPathSeparator + std::string(".."));
907 }
908 if (dep_comps.size() == 0) { rel_file_path += "."; }
909
910 bare_file_path +=
911 kPathSeparator +
912 namer_.Directories(dependency.defined_namespace->components,
913 SkipDir::OutputPath) +
914 namer_.File(dependency, SkipFile::SuffixAndExtension);
915 rel_file_path += bare_file_path;
916
917 ImportDefinition import;
918 import.name = name;
919 import.object_name = object_name;
920 import.bare_file_path = bare_file_path;
921 import.rel_file_path = rel_file_path;
922 std::string import_extension = parser_.opts.ts_no_import_ext ? "" : ".js";
923 import.import_statement = "import { " + symbols_expression + " } from '" +
924 rel_file_path + import_extension + "';";
925 import.export_statement = "export { " + symbols_expression + " } from '." +
926 bare_file_path + import_extension + "';";
927 import.dependency = &dependency;
928 import.dependent = &dependent;
929
930 imports.insert(std::make_pair(unique_name, import));
931
932 return import;
933 }
934
AddImport(import_set & imports,std::string import_name,std::string fileName)935 void AddImport(import_set &imports, std::string import_name,
936 std::string fileName) {
937 ImportDefinition import;
938 import.name = import_name;
939 import.import_statement =
940 "import " + import_name + " from '" + fileName + "';";
941 imports.insert(std::make_pair(import_name, import));
942 }
943
944 // Generate a TS union type based on a union's enum
GenObjApiUnionTypeTS(import_set & imports,const StructDef & dependent,const IDLOptions &,const EnumDef & union_enum)945 std::string GenObjApiUnionTypeTS(import_set &imports,
946 const StructDef &dependent,
947 const IDLOptions &,
948 const EnumDef &union_enum) {
949 std::string ret = "";
950 std::set<std::string> type_list;
951
952 for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
953 ++it) {
954 const auto &ev = **it;
955 if (ev.IsZero()) { continue; }
956
957 std::string type = "";
958 if (IsString(ev.union_type)) {
959 type = "string"; // no need to wrap string type in namespace
960 } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
961 type = AddImport(imports, dependent, *ev.union_type.struct_def)
962 .object_name;
963 } else {
964 FLATBUFFERS_ASSERT(false);
965 }
966 type_list.insert(type);
967 }
968
969 size_t totalPrinted = 0;
970 for (auto it = type_list.begin(); it != type_list.end(); ++it) {
971 ++totalPrinted;
972 ret += *it + ((totalPrinted == type_list.size()) ? "" : "|");
973 }
974
975 return ret;
976 }
977
GenUnionConvFuncName(const EnumDef & enum_def)978 std::string GenUnionConvFuncName(const EnumDef &enum_def) {
979 return namer_.Function("unionTo", enum_def);
980 }
981
GenUnionListConvFuncName(const EnumDef & enum_def)982 std::string GenUnionListConvFuncName(const EnumDef &enum_def) {
983 return namer_.Function("unionListTo", enum_def);
984 }
985
GenUnionConvFunc(const Type & union_type,import_set & imports)986 std::string GenUnionConvFunc(const Type &union_type, import_set &imports) {
987 if (union_type.enum_def) {
988 const auto &enum_def = *union_type.enum_def;
989
990 const auto valid_union_type = GenUnionTypeTS(enum_def, imports);
991 const auto valid_union_type_with_null = valid_union_type + "|null";
992
993 auto ret = "\n\nexport function " + GenUnionConvFuncName(enum_def) +
994 "(\n type: " + GetTypeName(enum_def) +
995 ",\n accessor: (obj:" + valid_union_type + ") => " +
996 valid_union_type_with_null +
997 "\n): " + valid_union_type_with_null + " {\n";
998
999 const auto enum_type = AddImport(imports, enum_def, enum_def).name;
1000
1001 const auto union_enum_loop = [&](const std::string &accessor_str) {
1002 ret += " switch(" + enum_type + "[type]) {\n";
1003 ret += " case 'NONE': return null; \n";
1004
1005 for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
1006 ++it) {
1007 const auto &ev = **it;
1008 if (ev.IsZero()) { continue; }
1009
1010 ret += " case '" + namer_.Variant(ev) + "': ";
1011
1012 if (IsString(ev.union_type)) {
1013 ret += "return " + accessor_str + "'') as string;";
1014 } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
1015 const auto type =
1016 AddImport(imports, enum_def, *ev.union_type.struct_def).name;
1017 ret += "return " + accessor_str + "new " + type + "())! as " +
1018 type + ";";
1019 } else {
1020 FLATBUFFERS_ASSERT(false);
1021 }
1022 ret += "\n";
1023 }
1024
1025 ret += " default: return null;\n";
1026 ret += " }\n";
1027 };
1028
1029 union_enum_loop("accessor(");
1030 ret += "}";
1031
1032 ret += "\n\nexport function " + GenUnionListConvFuncName(enum_def) +
1033 "(\n type: " + GetTypeName(enum_def) +
1034 ", \n accessor: (index: number, obj:" + valid_union_type +
1035 ") => " + valid_union_type_with_null +
1036 ", \n index: number\n): " + valid_union_type_with_null + " {\n";
1037 union_enum_loop("accessor(index, ");
1038 ret += "}";
1039
1040 return ret;
1041 }
1042 FLATBUFFERS_ASSERT(0);
1043 return "";
1044 }
1045
1046 // Used for generating a short function that returns the correct class
1047 // based on union enum type. Assume the context is inside the non object api
1048 // type
GenUnionValTS(import_set & imports,const StructDef & dependent,const std::string & field_name,const Type & union_type,const bool is_array=false)1049 std::string GenUnionValTS(import_set &imports, const StructDef &dependent,
1050 const std::string &field_name,
1051 const Type &union_type,
1052 const bool is_array = false) {
1053 if (union_type.enum_def) {
1054 const auto &enum_def = *union_type.enum_def;
1055 const auto enum_type = AddImport(imports, dependent, enum_def).name;
1056 const std::string union_accessor = "this." + field_name;
1057
1058 const auto union_has_string = UnionHasStringType(enum_def);
1059 const auto field_binded_method = "this." + field_name + ".bind(this)";
1060
1061 std::string ret;
1062
1063 if (!is_array) {
1064 const auto conversion_function = GenUnionConvFuncName(enum_def);
1065
1066 ret = "(() => {\n";
1067 ret += " const temp = " + conversion_function + "(this." +
1068 namer_.Method(field_name, "Type") + "(), " +
1069 field_binded_method + ");\n";
1070 ret += " if(temp === null) { return null; }\n";
1071 ret += union_has_string
1072 ? " if(typeof temp === 'string') { return temp; }\n"
1073 : "";
1074 ret += " return temp.unpack()\n";
1075 ret += " })()";
1076 } else {
1077 const auto conversion_function = GenUnionListConvFuncName(enum_def);
1078
1079 ret = "(() => {\n";
1080 ret += " const ret: (" +
1081 GenObjApiUnionTypeTS(imports, *union_type.struct_def,
1082 parser_.opts, *union_type.enum_def) +
1083 ")[] = [];\n";
1084 ret += " for(let targetEnumIndex = 0; targetEnumIndex < this." +
1085 namer_.Method(field_name, "TypeLength") + "()" +
1086 "; "
1087 "++targetEnumIndex) {\n";
1088 ret += " const targetEnum = this." +
1089 namer_.Method(field_name, "Type") + "(targetEnumIndex);\n";
1090 ret += " if(targetEnum === null || " + enum_type +
1091 "[targetEnum!] === 'NONE') { "
1092 "continue; }\n\n";
1093 ret += " const temp = " + conversion_function + "(targetEnum, " +
1094 field_binded_method + ", targetEnumIndex);\n";
1095 ret += " if(temp === null) { continue; }\n";
1096 ret += union_has_string ? " if(typeof temp === 'string') { "
1097 "ret.push(temp); continue; }\n"
1098 : "";
1099 ret += " ret.push(temp.unpack());\n";
1100 ret += " }\n";
1101 ret += " return ret;\n";
1102 ret += " })()";
1103 }
1104
1105 return ret;
1106 }
1107
1108 FLATBUFFERS_ASSERT(0);
1109 return "";
1110 }
1111
GenNullCheckConditional(const std::string & nullCheckVar,const std::string & trueVal,const std::string & falseVal="null")1112 static std::string GenNullCheckConditional(
1113 const std::string &nullCheckVar, const std::string &trueVal,
1114 const std::string &falseVal = "null") {
1115 return "(" + nullCheckVar + " !== null ? " + trueVal + " : " + falseVal +
1116 ")";
1117 }
1118
GenStructMemberValueTS(const StructDef & struct_def,const std::string & prefix,const std::string & delimiter,const bool nullCheck=true)1119 std::string GenStructMemberValueTS(const StructDef &struct_def,
1120 const std::string &prefix,
1121 const std::string &delimiter,
1122 const bool nullCheck = true) {
1123 std::string ret;
1124 for (auto it = struct_def.fields.vec.begin();
1125 it != struct_def.fields.vec.end(); ++it) {
1126 auto &field = **it;
1127
1128 auto curr_member_accessor = prefix + "." + namer_.Method(field);
1129 if (prefix != "this") {
1130 curr_member_accessor = prefix + "?." + namer_.Method(field);
1131 }
1132 if (IsStruct(field.value.type)) {
1133 ret += GenStructMemberValueTS(*field.value.type.struct_def,
1134 curr_member_accessor, delimiter);
1135 } else {
1136 if (nullCheck) {
1137 std::string nullValue = "0";
1138 if (field.value.type.base_type == BASE_TYPE_BOOL) {
1139 nullValue = "false";
1140 } else if (field.value.type.base_type == BASE_TYPE_LONG ||
1141 field.value.type.base_type == BASE_TYPE_ULONG) {
1142 nullValue = "BigInt(0)";
1143 } else if (field.value.type.base_type == BASE_TYPE_ARRAY) {
1144 nullValue = "[]";
1145 }
1146 ret += "(" + curr_member_accessor + " ?? " + nullValue + ")";
1147 } else {
1148 ret += curr_member_accessor;
1149 }
1150 }
1151
1152 if (std::next(it) != struct_def.fields.vec.end()) { ret += delimiter; }
1153 }
1154
1155 return ret;
1156 }
1157
GenObjApi(const Parser & parser,StructDef & struct_def,std::string & obj_api_unpack_func,std::string & obj_api_class,import_set & imports)1158 void GenObjApi(const Parser &parser, StructDef &struct_def,
1159 std::string &obj_api_unpack_func, std::string &obj_api_class,
1160 import_set &imports) {
1161 const auto class_name = GetTypeName(struct_def, /*object_api=*/true);
1162
1163 std::string unpack_func = "\nunpack(): " + class_name +
1164 " {\n return new " + class_name + "(" +
1165 (struct_def.fields.vec.empty() ? "" : "\n");
1166 std::string unpack_to_func = "\nunpackTo(_o: " + class_name + "): void {" +
1167 +(struct_def.fields.vec.empty() ? "" : "\n");
1168
1169 std::string constructor_func = "constructor(";
1170 constructor_func += (struct_def.fields.vec.empty() ? "" : "\n");
1171
1172 const auto has_create =
1173 struct_def.fixed || CanCreateFactoryMethod(struct_def);
1174
1175 std::string pack_func_prototype =
1176 "\npack(builder:flatbuffers.Builder): flatbuffers.Offset {\n";
1177
1178 std::string pack_func_offset_decl;
1179 std::string pack_func_create_call;
1180
1181 const auto struct_name = AddImport(imports, struct_def, struct_def).name;
1182
1183 if (has_create) {
1184 pack_func_create_call = " return " + struct_name + ".create" +
1185 GetPrefixedName(struct_def) + "(builder" +
1186 (struct_def.fields.vec.empty() ? "" : ",\n ");
1187 } else {
1188 pack_func_create_call = " " + struct_name + ".start" +
1189 GetPrefixedName(struct_def) + "(builder);\n";
1190 }
1191
1192 if (struct_def.fixed) {
1193 // when packing struct, nested struct's members instead of the struct's
1194 // offset are used
1195 pack_func_create_call +=
1196 GenStructMemberValueTS(struct_def, "this", ",\n ", false) + "\n ";
1197 }
1198
1199 for (auto it = struct_def.fields.vec.begin();
1200 it != struct_def.fields.vec.end(); ++it) {
1201 auto &field = **it;
1202 if (field.deprecated) continue;
1203
1204 const auto field_method = namer_.Method(field);
1205 const auto field_field = namer_.Field(field);
1206 const std::string field_binded_method =
1207 "this." + field_method + ".bind(this)";
1208
1209 std::string field_val;
1210 std::string field_type;
1211 // a string that declares a variable containing the
1212 // offset for things that can't be generated inline
1213 // empty otw
1214 std::string field_offset_decl;
1215 // a string that contains values for things that can be created inline or
1216 // the variable name from field_offset_decl
1217 std::string field_offset_val;
1218 const auto field_default_val = GenDefaultValue(field, imports);
1219
1220 // Emit a scalar field
1221 const auto is_string = IsString(field.value.type);
1222 if (IsScalar(field.value.type.base_type) || is_string) {
1223 const auto has_null_default = is_string || HasNullDefault(field);
1224
1225 field_type += GenTypeName(imports, field, field.value.type, false,
1226 has_null_default);
1227 field_val = "this." + namer_.Method(field) + "()";
1228
1229 if (field.value.type.base_type != BASE_TYPE_STRING) {
1230 field_offset_val = "this." + namer_.Field(field);
1231 } else {
1232 field_offset_decl = GenNullCheckConditional(
1233 "this." + namer_.Field(field),
1234 "builder.createString(this." + field_field + "!)", "0");
1235 }
1236 }
1237
1238 // Emit an object field
1239 else {
1240 auto is_vector = false;
1241 switch (field.value.type.base_type) {
1242 case BASE_TYPE_STRUCT: {
1243 const auto &sd = *field.value.type.struct_def;
1244 field_type += AddImport(imports, struct_def, sd).object_name;
1245
1246 const std::string field_accessor =
1247 "this." + namer_.Method(field) + "()";
1248 field_val = GenNullCheckConditional(field_accessor,
1249 field_accessor + "!.unpack()");
1250 auto packing = GenNullCheckConditional(
1251 "this." + field_field,
1252 "this." + field_field + "!.pack(builder)", "0");
1253
1254 if (sd.fixed) {
1255 field_offset_val = std::move(packing);
1256 } else {
1257 field_offset_decl = std::move(packing);
1258 }
1259
1260 break;
1261 }
1262
1263 case BASE_TYPE_ARRAY: {
1264 auto vectortype = field.value.type.VectorType();
1265 auto vectortypename =
1266 GenTypeName(imports, struct_def, vectortype, false);
1267 is_vector = true;
1268
1269 field_type = "(";
1270
1271 switch (vectortype.base_type) {
1272 case BASE_TYPE_STRUCT: {
1273 const auto &sd = *field.value.type.struct_def;
1274 const auto field_type_name =
1275 GetTypeName(sd, /*object_api=*/true);
1276 field_type += field_type_name;
1277 field_type += ")[]";
1278
1279 field_val = GenBBAccess() + ".createObjList<" + vectortypename +
1280 ", " + field_type_name + ">(" +
1281 field_binded_method + ", " +
1282 NumToString(field.value.type.fixed_length) + ")";
1283
1284 if (sd.fixed) {
1285 field_offset_decl =
1286 "builder.createStructOffsetList(this." + field_field +
1287 ", " + AddImport(imports, struct_def, struct_def).name +
1288 "." + namer_.Method("start", field, "Vector") + ")";
1289 } else {
1290 field_offset_decl =
1291 AddImport(imports, struct_def, struct_def).name + "." +
1292 namer_.Method("create", field, "Vector") +
1293 "(builder, builder.createObjectOffsetList(" + "this." +
1294 field_field + "))";
1295 }
1296
1297 break;
1298 }
1299
1300 case BASE_TYPE_STRING: {
1301 field_type += "string)[]";
1302 field_val = GenBBAccess() + ".createScalarList<string>(" +
1303 field_binded_method + ", this." +
1304 namer_.Field(field, "Length") + "())";
1305 field_offset_decl =
1306 AddImport(imports, struct_def, struct_def).name + "." +
1307 namer_.Method("create", field, "Vector") +
1308 "(builder, builder.createObjectOffsetList(" + "this." +
1309 namer_.Field(field) + "))";
1310 break;
1311 }
1312
1313 case BASE_TYPE_UNION: {
1314 field_type += GenObjApiUnionTypeTS(
1315 imports, struct_def, parser.opts, *(vectortype.enum_def));
1316 field_type += ")[]";
1317 field_val = GenUnionValTS(imports, struct_def, field_method,
1318 vectortype, true);
1319
1320 field_offset_decl =
1321 AddImport(imports, struct_def, struct_def).name + "." +
1322 namer_.Method("create", field, "Vector") +
1323 "(builder, builder.createObjectOffsetList(" + "this." +
1324 namer_.Field(field) + "))";
1325
1326 break;
1327 }
1328 default: {
1329 if (vectortype.enum_def) {
1330 field_type += GenTypeName(imports, struct_def, vectortype,
1331 false, HasNullDefault(field));
1332 } else {
1333 field_type += vectortypename;
1334 }
1335 field_type += ")[]";
1336 field_val = GenBBAccess() + ".createScalarList<" +
1337 vectortypename + ">(" + field_binded_method + ", " +
1338 NumToString(field.value.type.fixed_length) + ")";
1339
1340 field_offset_decl =
1341 AddImport(imports, struct_def, struct_def).name + "." +
1342 namer_.Method("create", field, "Vector") +
1343 "(builder, this." + field_field + ")";
1344
1345 break;
1346 }
1347 }
1348
1349 break;
1350 }
1351
1352 case BASE_TYPE_VECTOR: {
1353 auto vectortype = field.value.type.VectorType();
1354 auto vectortypename =
1355 GenTypeName(imports, struct_def, vectortype, false);
1356 is_vector = true;
1357
1358 field_type = "(";
1359
1360 switch (vectortype.base_type) {
1361 case BASE_TYPE_STRUCT: {
1362 const auto &sd = *field.value.type.struct_def;
1363 const auto field_type_name =
1364 GetTypeName(sd, /*object_api=*/true);
1365 field_type += field_type_name;
1366 field_type += ")[]";
1367
1368 field_val = GenBBAccess() + ".createObjList<" + vectortypename +
1369 ", " + field_type_name + ">(" +
1370 field_binded_method + ", this." +
1371 namer_.Method(field, "Length") + "())";
1372
1373 if (sd.fixed) {
1374 field_offset_decl =
1375 "builder.createStructOffsetList(this." + field_field +
1376 ", " + AddImport(imports, struct_def, struct_def).name +
1377 "." + namer_.Method("start", field, "Vector") + ")";
1378 } else {
1379 field_offset_decl =
1380 AddImport(imports, struct_def, struct_def).name + "." +
1381 namer_.Method("create", field, "Vector") +
1382 "(builder, builder.createObjectOffsetList(" + "this." +
1383 field_field + "))";
1384 }
1385
1386 break;
1387 }
1388
1389 case BASE_TYPE_STRING: {
1390 field_type += "string)[]";
1391 field_val = GenBBAccess() + ".createScalarList<string>(" +
1392 field_binded_method + ", this." +
1393 namer_.Field(field, "Length") + "())";
1394 field_offset_decl =
1395 AddImport(imports, struct_def, struct_def).name + "." +
1396 namer_.Method("create", field, "Vector") +
1397 "(builder, builder.createObjectOffsetList(" + "this." +
1398 namer_.Field(field) + "))";
1399 break;
1400 }
1401
1402 case BASE_TYPE_UNION: {
1403 field_type += GenObjApiUnionTypeTS(
1404 imports, struct_def, parser.opts, *(vectortype.enum_def));
1405 field_type += ")[]";
1406 field_val = GenUnionValTS(imports, struct_def, field_method,
1407 vectortype, true);
1408
1409 field_offset_decl =
1410 AddImport(imports, struct_def, struct_def).name + "." +
1411 namer_.Method("create", field, "Vector") +
1412 "(builder, builder.createObjectOffsetList(" + "this." +
1413 namer_.Field(field) + "))";
1414
1415 break;
1416 }
1417 default: {
1418 if (vectortype.enum_def) {
1419 field_type += GenTypeName(imports, struct_def, vectortype,
1420 false, HasNullDefault(field));
1421 } else {
1422 field_type += vectortypename;
1423 }
1424 field_type += ")[]";
1425 field_val = GenBBAccess() + ".createScalarList<" +
1426 vectortypename + ">(" + field_binded_method +
1427 ", this." + namer_.Method(field, "Length") + "())";
1428
1429 field_offset_decl =
1430 AddImport(imports, struct_def, struct_def).name + "." +
1431 namer_.Method("create", field, "Vector") +
1432 "(builder, this." + field_field + ")";
1433
1434 break;
1435 }
1436 }
1437
1438 break;
1439 }
1440
1441 case BASE_TYPE_UNION: {
1442 field_type += GenObjApiUnionTypeTS(imports, struct_def, parser.opts,
1443 *(field.value.type.enum_def));
1444
1445 field_val = GenUnionValTS(imports, struct_def, field_method,
1446 field.value.type);
1447 field_offset_decl =
1448 "builder.createObjectOffset(this." + field_field + ")";
1449 break;
1450 }
1451
1452 default: FLATBUFFERS_ASSERT(0); break;
1453 }
1454
1455 // length 0 vector is simply empty instead of null
1456 field_type += is_vector ? "" : "|null";
1457 }
1458
1459 if (!field_offset_decl.empty()) {
1460 field_offset_decl =
1461 " const " + field_field + " = " + field_offset_decl + ";";
1462 }
1463 if (field_offset_val.empty()) { field_offset_val = field_field; }
1464
1465 unpack_func += " " + field_val;
1466 unpack_to_func += " _o." + field_field + " = " + field_val + ";";
1467
1468 // FIXME: if field_type and field_field are identical, then
1469 // this generates invalid typescript.
1470 constructor_func += " public " + field_field + ": " + field_type +
1471 " = " + field_default_val;
1472
1473 if (!struct_def.fixed) {
1474 if (!field_offset_decl.empty()) {
1475 pack_func_offset_decl += field_offset_decl + "\n";
1476 }
1477
1478 if (has_create) {
1479 pack_func_create_call += field_offset_val;
1480 } else {
1481 if (field.IsScalarOptional()) {
1482 pack_func_create_call +=
1483 " if (" + field_offset_val + " !== null)\n ";
1484 }
1485 pack_func_create_call += " " + struct_name + "." +
1486 namer_.Method("add", field) + "(builder, " +
1487 field_offset_val + ");\n";
1488 }
1489 }
1490
1491 if (std::next(it) != struct_def.fields.vec.end()) {
1492 constructor_func += ",\n";
1493
1494 if (!struct_def.fixed && has_create) {
1495 pack_func_create_call += ",\n ";
1496 }
1497
1498 unpack_func += ",\n";
1499 unpack_to_func += "\n";
1500 } else {
1501 constructor_func += "\n";
1502 if (!struct_def.fixed) {
1503 pack_func_offset_decl += (pack_func_offset_decl.empty() ? "" : "\n");
1504 pack_func_create_call += "\n ";
1505 }
1506
1507 unpack_func += "\n ";
1508 unpack_to_func += "\n";
1509 }
1510 }
1511
1512 constructor_func += "){}\n\n";
1513
1514 if (has_create) {
1515 pack_func_create_call += ");";
1516 } else {
1517 pack_func_create_call += "return " + struct_name + ".end" +
1518 GetPrefixedName(struct_def) + "(builder);";
1519 }
1520 obj_api_class = "\n";
1521 obj_api_class += "export class ";
1522 obj_api_class += GetTypeName(struct_def, /*object_api=*/true);
1523 obj_api_class += " implements flatbuffers.IGeneratedObject {\n";
1524 obj_api_class += constructor_func;
1525 obj_api_class += pack_func_prototype + pack_func_offset_decl +
1526 pack_func_create_call + "\n}";
1527
1528 obj_api_class += "\n}\n";
1529
1530 unpack_func += ");\n}";
1531 unpack_to_func += "}\n";
1532
1533 obj_api_unpack_func = unpack_func + "\n\n" + unpack_to_func;
1534 }
1535
CanCreateFactoryMethod(const StructDef & struct_def)1536 static bool CanCreateFactoryMethod(const StructDef &struct_def) {
1537 // to preserve backwards compatibility, we allow the first field to be a
1538 // struct
1539 return struct_def.fields.vec.size() < 2 ||
1540 std::all_of(std::begin(struct_def.fields.vec) + 1,
1541 std::end(struct_def.fields.vec),
1542 [](const FieldDef *f) -> bool {
1543 FLATBUFFERS_ASSERT(f != nullptr);
1544 return f->value.type.base_type != BASE_TYPE_STRUCT;
1545 });
1546 }
1547
1548 // Generate an accessor struct with constructor for a flatbuffers struct.
GenStruct(const Parser & parser,StructDef & struct_def,std::string * code_ptr,import_set & imports)1549 void GenStruct(const Parser &parser, StructDef &struct_def,
1550 std::string *code_ptr, import_set &imports) {
1551 if (struct_def.generated) return;
1552 std::string &code = *code_ptr;
1553
1554 // Special case for the root struct, since no one will necessarily reference
1555 // it, we have to explicitly add it to the import list.
1556 if (&struct_def == parser_.root_struct_def_) {
1557 AddImport(imports, struct_def, struct_def);
1558 }
1559
1560 const std::string object_name = GetTypeName(struct_def);
1561 const std::string object_api_name = GetTypeName(struct_def, true);
1562
1563 // Emit constructor
1564 GenDocComment(struct_def.doc_comment, code_ptr);
1565 code += "export class ";
1566 code += object_name;
1567 if (parser.opts.generate_object_based_api)
1568 code += " implements flatbuffers.IUnpackableObject<" + object_api_name +
1569 "> {\n";
1570 else
1571 code += " {\n";
1572 code += " bb: flatbuffers.ByteBuffer|null = null;\n";
1573 code += " bb_pos = 0;\n";
1574
1575 // Generate the __init method that sets the field in a pre-existing
1576 // accessor object. This is to allow object reuse.
1577 code +=
1578 " __init(i:number, bb:flatbuffers.ByteBuffer):" + object_name + " {\n";
1579 code += " this.bb_pos = i;\n";
1580 code += " this.bb = bb;\n";
1581 code += " return this;\n";
1582 code += "}\n\n";
1583
1584 // Generate special accessors for the table that when used as the root of a
1585 // FlatBuffer
1586 GenerateRootAccessor(struct_def, code_ptr, code, object_name, false);
1587 GenerateRootAccessor(struct_def, code_ptr, code, object_name, true);
1588
1589 // Generate the identifier check method
1590 if (!struct_def.fixed && parser_.root_struct_def_ == &struct_def &&
1591 !parser_.file_identifier_.empty()) {
1592 GenDocComment(code_ptr);
1593 code +=
1594 "static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean "
1595 "{\n";
1596 code += " return bb.__has_identifier('" + parser_.file_identifier_;
1597 code += "');\n}\n\n";
1598 }
1599
1600 // Emit field accessors
1601 for (auto it = struct_def.fields.vec.begin();
1602 it != struct_def.fields.vec.end(); ++it) {
1603 auto &field = **it;
1604 if (field.deprecated) continue;
1605 std::string offset_prefix = "";
1606
1607 if (field.value.type.base_type == BASE_TYPE_ARRAY) {
1608 offset_prefix = " return ";
1609 } else {
1610 offset_prefix = " const offset = " + GenBBAccess() +
1611 ".__offset(this.bb_pos, " +
1612 NumToString(field.value.offset) + ");\n";
1613 offset_prefix += " return offset ? ";
1614 }
1615
1616 // Emit a scalar field
1617 const auto is_string = IsString(field.value.type);
1618 if (IsScalar(field.value.type.base_type) || is_string) {
1619 const auto has_null_default = is_string || HasNullDefault(field);
1620
1621 GenDocComment(field.doc_comment, code_ptr);
1622 std::string prefix = namer_.Method(field) + "(";
1623 if (is_string) {
1624 code += prefix + "):string|null\n";
1625 code +=
1626 prefix + "optionalEncoding:flatbuffers.Encoding" + "):" +
1627 GenTypeName(imports, struct_def, field.value.type, false, true) +
1628 "\n";
1629 code += prefix + "optionalEncoding?:any";
1630 } else {
1631 code += prefix;
1632 }
1633 if (field.value.type.enum_def) {
1634 code += "):" +
1635 GenTypeName(imports, struct_def, field.value.type, false,
1636 field.IsOptional()) +
1637 " {\n";
1638 } else {
1639 code += "):" +
1640 GenTypeName(imports, struct_def, field.value.type, false,
1641 has_null_default) +
1642 " {\n";
1643 }
1644
1645 if (struct_def.fixed) {
1646 code +=
1647 " return " +
1648 GenGetter(field.value.type,
1649 "(this.bb_pos" + MaybeAdd(field.value.offset) + ")") +
1650 ";\n";
1651 } else {
1652 std::string index = "this.bb_pos + offset";
1653 if (is_string) { index += ", optionalEncoding"; }
1654 code +=
1655 offset_prefix + GenGetter(field.value.type, "(" + index + ")");
1656 if (field.value.type.base_type != BASE_TYPE_ARRAY) {
1657 code += " : " + GenDefaultValue(field, imports);
1658 }
1659 code += ";\n";
1660 }
1661 }
1662
1663 // Emit an object field
1664 else {
1665 switch (field.value.type.base_type) {
1666 case BASE_TYPE_STRUCT: {
1667 const auto type =
1668 AddImport(imports, struct_def, *field.value.type.struct_def)
1669 .name;
1670 GenDocComment(field.doc_comment, code_ptr);
1671 code += namer_.Method(field);
1672 code += "(obj?:" + type + "):" + type + "|null {\n";
1673
1674 if (struct_def.fixed) {
1675 code += " return (obj || " + GenerateNewExpression(type);
1676 code += ").__init(this.bb_pos";
1677 code +=
1678 MaybeAdd(field.value.offset) + ", " + GenBBAccess() + ");\n";
1679 } else {
1680 code += offset_prefix + "(obj || " + GenerateNewExpression(type) +
1681 ").__init(";
1682 code += field.value.type.struct_def->fixed
1683 ? "this.bb_pos + offset"
1684 : GenBBAccess() + ".__indirect(this.bb_pos + offset)";
1685 code += ", " + GenBBAccess() + ") : null;\n";
1686 }
1687
1688 break;
1689 }
1690
1691 case BASE_TYPE_ARRAY: {
1692 auto vectortype = field.value.type.VectorType();
1693 auto vectortypename =
1694 GenTypeName(imports, struct_def, vectortype, false);
1695 auto inline_size = InlineSize(vectortype);
1696 auto index = "this.bb_pos + " + NumToString(field.value.offset) +
1697 " + index" + MaybeScale(inline_size);
1698 std::string ret_type;
1699 bool is_union = false;
1700 switch (vectortype.base_type) {
1701 case BASE_TYPE_STRUCT: ret_type = vectortypename; break;
1702 case BASE_TYPE_STRING: ret_type = vectortypename; break;
1703 case BASE_TYPE_UNION:
1704 ret_type = "?flatbuffers.Table";
1705 is_union = true;
1706 break;
1707 default: ret_type = vectortypename;
1708 }
1709 GenDocComment(field.doc_comment, code_ptr);
1710 std::string prefix = namer_.Method(field);
1711 // TODO: make it work without any
1712 // if (is_union) { prefix += "<T extends flatbuffers.Table>"; }
1713 if (is_union) { prefix += ""; }
1714 prefix += "(index: number";
1715 if (is_union) {
1716 const auto union_type =
1717 GenUnionGenericTypeTS(*(field.value.type.enum_def));
1718
1719 vectortypename = union_type;
1720 code += prefix + ", obj:" + union_type;
1721 } else if (vectortype.base_type == BASE_TYPE_STRUCT) {
1722 code += prefix + ", obj?:" + vectortypename;
1723 } else if (IsString(vectortype)) {
1724 code += prefix + "):string\n";
1725 code += prefix + ",optionalEncoding:flatbuffers.Encoding" +
1726 "):" + vectortypename + "\n";
1727 code += prefix + ",optionalEncoding?:any";
1728 } else {
1729 code += prefix;
1730 }
1731 code += "):" + vectortypename + "|null {\n";
1732
1733 if (vectortype.base_type == BASE_TYPE_STRUCT) {
1734 code += offset_prefix + "(obj || " +
1735 GenerateNewExpression(vectortypename);
1736 code += ").__init(";
1737 code += vectortype.struct_def->fixed
1738 ? index
1739 : GenBBAccess() + ".__indirect(" + index + ")";
1740 code += ", " + GenBBAccess() + ")";
1741 } else {
1742 if (is_union) {
1743 index = "obj, " + index;
1744 } else if (IsString(vectortype)) {
1745 index += ", optionalEncoding";
1746 }
1747 code += offset_prefix + GenGetter(vectortype, "(" + index + ")");
1748 }
1749
1750 switch (field.value.type.base_type) {
1751 case BASE_TYPE_ARRAY: {
1752 break;
1753 }
1754 case BASE_TYPE_BOOL: {
1755 code += " : false";
1756 break;
1757 }
1758 case BASE_TYPE_LONG:
1759 case BASE_TYPE_ULONG: {
1760 code += " : BigInt(0)";
1761 break;
1762 }
1763 default: {
1764 if (IsScalar(field.value.type.element)) {
1765 if (field.value.type.enum_def) {
1766 code += field.value.constant;
1767 } else {
1768 code += " : 0";
1769 }
1770 } else {
1771 code += ": null";
1772 }
1773 break;
1774 }
1775 }
1776 code += ";\n";
1777 break;
1778 }
1779
1780 case BASE_TYPE_VECTOR: {
1781 auto vectortype = field.value.type.VectorType();
1782 auto vectortypename =
1783 GenTypeName(imports, struct_def, vectortype, false);
1784 auto type = GetUnderlyingVectorType(vectortype);
1785 auto inline_size = InlineSize(type);
1786 auto index = GenBBAccess() +
1787 ".__vector(this.bb_pos + offset) + index" +
1788 MaybeScale(inline_size);
1789 std::string ret_type;
1790 bool is_union = false;
1791 switch (vectortype.base_type) {
1792 case BASE_TYPE_STRUCT: ret_type = vectortypename; break;
1793 case BASE_TYPE_STRING: ret_type = vectortypename; break;
1794 case BASE_TYPE_UNION:
1795 ret_type = "?flatbuffers.Table";
1796 is_union = true;
1797 break;
1798 default: ret_type = vectortypename;
1799 }
1800 GenDocComment(field.doc_comment, code_ptr);
1801 std::string prefix = namer_.Method(field);
1802 // TODO: make it work without any
1803 // if (is_union) { prefix += "<T extends flatbuffers.Table>"; }
1804 if (is_union) { prefix += ""; }
1805 prefix += "(index: number";
1806 if (is_union) {
1807 const auto union_type =
1808 GenUnionGenericTypeTS(*(field.value.type.enum_def));
1809
1810 vectortypename = union_type;
1811 code += prefix + ", obj:" + union_type;
1812 } else if (vectortype.base_type == BASE_TYPE_STRUCT) {
1813 code += prefix + ", obj?:" + vectortypename;
1814 } else if (IsString(vectortype)) {
1815 code += prefix + "):string\n";
1816 code += prefix + ",optionalEncoding:flatbuffers.Encoding" +
1817 "):" + vectortypename + "\n";
1818 code += prefix + ",optionalEncoding?:any";
1819 } else {
1820 code += prefix;
1821 }
1822 code += "):" + vectortypename + "|null {\n";
1823
1824 if (vectortype.base_type == BASE_TYPE_STRUCT) {
1825 code += offset_prefix + "(obj || " +
1826 GenerateNewExpression(vectortypename);
1827 code += ").__init(";
1828 code += vectortype.struct_def->fixed
1829 ? index
1830 : GenBBAccess() + ".__indirect(" + index + ")";
1831 code += ", " + GenBBAccess() + ")";
1832 } else {
1833 if (is_union) {
1834 index = "obj, " + index;
1835 } else if (IsString(vectortype)) {
1836 index += ", optionalEncoding";
1837 }
1838 code += offset_prefix + GenGetter(vectortype, "(" + index + ")");
1839 }
1840 code += " : ";
1841 if (field.value.type.element == BASE_TYPE_BOOL) {
1842 code += "false";
1843 } else if (field.value.type.element == BASE_TYPE_LONG ||
1844 field.value.type.element == BASE_TYPE_ULONG) {
1845 code += "BigInt(0)";
1846 } else if (IsScalar(field.value.type.element)) {
1847 if (field.value.type.enum_def) {
1848 code += field.value.constant;
1849 } else {
1850 code += "0";
1851 }
1852 } else {
1853 code += "null";
1854 }
1855 code += ";\n";
1856 break;
1857 }
1858
1859 case BASE_TYPE_UNION: {
1860 GenDocComment(field.doc_comment, code_ptr);
1861 code += namer_.Method(field);
1862
1863 const auto &union_enum = *(field.value.type.enum_def);
1864 const auto union_type = GenUnionGenericTypeTS(union_enum);
1865 code += "<T extends flatbuffers.Table>(obj:" + union_type +
1866 "):" + union_type +
1867 "|null "
1868 "{\n";
1869
1870 code += offset_prefix +
1871 GenGetter(field.value.type, "(obj, this.bb_pos + offset)") +
1872 " : null;\n";
1873 break;
1874 }
1875 default: FLATBUFFERS_ASSERT(0);
1876 }
1877 }
1878 code += "}\n\n";
1879
1880 // Adds the mutable scalar value to the output
1881 if (IsScalar(field.value.type.base_type) && parser.opts.mutable_buffer &&
1882 !IsUnion(field.value.type)) {
1883 std::string type =
1884 GenTypeName(imports, struct_def, field.value.type, true);
1885
1886 code += namer_.LegacyTsMutateMethod(field) + "(value:" + type +
1887 "):boolean {\n";
1888
1889 const std::string write_method =
1890 "." + namer_.Method("write", GenType(field.value.type));
1891
1892 if (struct_def.fixed) {
1893 code += " " + GenBBAccess() + write_method + "(this.bb_pos + " +
1894 NumToString(field.value.offset) + ", ";
1895 } else {
1896 code += " const offset = " + GenBBAccess() +
1897 ".__offset(this.bb_pos, " + NumToString(field.value.offset) +
1898 ");\n\n";
1899 code += " if (offset === 0) {\n";
1900 code += " return false;\n";
1901 code += " }\n\n";
1902
1903 // special case for bools, which are treated as uint8
1904 code +=
1905 " " + GenBBAccess() + write_method + "(this.bb_pos + offset, ";
1906 if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
1907 }
1908
1909 code += "value);\n";
1910 code += " return true;\n";
1911 code += "}\n\n";
1912 }
1913
1914 // Emit vector helpers
1915 if (IsVector(field.value.type)) {
1916 // Emit a length helper
1917 GenDocComment(code_ptr);
1918 code += namer_.Method(field, "Length");
1919 code += "():number {\n" + offset_prefix;
1920
1921 code +=
1922 GenBBAccess() + ".__vector_len(this.bb_pos + offset) : 0;\n}\n\n";
1923
1924 // For scalar types, emit a typed array helper
1925 auto vectorType = field.value.type.VectorType();
1926 if (IsScalar(vectorType.base_type) && !IsLong(vectorType.base_type)) {
1927 GenDocComment(code_ptr);
1928
1929 code += namer_.Method(field, "Array");
1930 code +=
1931 "():" + GenType(vectorType) + "Array|null {\n" + offset_prefix;
1932
1933 code += "new " + GenType(vectorType) + "Array(" + GenBBAccess() +
1934 ".bytes().buffer, " + GenBBAccess() +
1935 ".bytes().byteOffset + " + GenBBAccess() +
1936 ".__vector(this.bb_pos + offset), " + GenBBAccess() +
1937 ".__vector_len(this.bb_pos + offset)) : null;\n}\n\n";
1938 }
1939 }
1940 }
1941
1942 // Emit the fully qualified name
1943 if (parser_.opts.generate_name_strings) {
1944 GenDocComment(code_ptr);
1945 code += "static getFullyQualifiedName():string {\n";
1946 code +=
1947 " return '" +
1948 struct_def.defined_namespace->GetFullyQualifiedName(struct_def.name) +
1949 "';\n";
1950 code += "}\n\n";
1951 }
1952
1953 // Emit the size of the struct.
1954 if (struct_def.fixed) {
1955 GenDocComment(code_ptr);
1956 code += "static sizeOf():number {\n";
1957 code += " return " + NumToString(struct_def.bytesize) + ";\n";
1958 code += "}\n\n";
1959 }
1960
1961 // Emit a factory constructor
1962 if (struct_def.fixed) {
1963 std::string arguments;
1964 GenStructArgs(imports, struct_def, &arguments, "");
1965 GenDocComment(code_ptr);
1966
1967 code += "static create" + GetPrefixedName(struct_def) +
1968 "(builder:flatbuffers.Builder";
1969 code += arguments + "):flatbuffers.Offset {\n";
1970
1971 GenStructBody(struct_def, &code, "");
1972 code += " return builder.offset();\n}\n\n";
1973 } else {
1974 // Generate a method to start building a new object
1975 GenDocComment(code_ptr);
1976
1977 code += "static start" + GetPrefixedName(struct_def) +
1978 "(builder:flatbuffers.Builder) {\n";
1979
1980 code += " builder.startObject(" +
1981 NumToString(struct_def.fields.vec.size()) + ");\n";
1982 code += "}\n\n";
1983
1984 // Generate a set of static methods that allow table construction
1985 for (auto it = struct_def.fields.vec.begin();
1986 it != struct_def.fields.vec.end(); ++it) {
1987 auto &field = **it;
1988 if (field.deprecated) continue;
1989 const auto argname = GetArgName(field);
1990
1991 // Generate the field insertion method
1992 GenDocComment(code_ptr);
1993 code += "static " + namer_.Method("add", field);
1994 code += "(builder:flatbuffers.Builder, " + argname + ":" +
1995 GetArgType(imports, struct_def, field, false) + ") {\n";
1996 code += " builder.addField" + GenWriteMethod(field.value.type) + "(";
1997 code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
1998 if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
1999 code += argname + ", ";
2000 if (!IsScalar(field.value.type.base_type)) {
2001 code += "0";
2002 } else if (HasNullDefault(field)) {
2003 code += "null";
2004 } else {
2005 if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
2006 code += GenDefaultValue(field, imports);
2007 }
2008 code += ");\n}\n\n";
2009
2010 if (IsVector(field.value.type)) {
2011 auto vector_type = field.value.type.VectorType();
2012 auto type = GetUnderlyingVectorType(vector_type);
2013 auto alignment = InlineAlignment(type);
2014 auto elem_size = InlineSize(type);
2015
2016 // Generate a method to create a vector from a JavaScript array
2017 if (!IsStruct(vector_type)) {
2018 GenDocComment(code_ptr);
2019
2020 const std::string sig_begin =
2021 "static " + namer_.Method("create", field, "Vector") +
2022 "(builder:flatbuffers.Builder, data:";
2023 const std::string sig_end = "):flatbuffers.Offset";
2024 std::string type =
2025 GenTypeName(imports, struct_def, vector_type, true) + "[]";
2026 if (type == "number[]") {
2027 const auto &array_type = GenType(vector_type);
2028 // the old type should be deprecated in the future
2029 std::string type_old = "number[]|Uint8Array";
2030 std::string type_new = "number[]|" + array_type + "Array";
2031 if (type_old == type_new) {
2032 type = type_new;
2033 } else {
2034 // add function overloads
2035 code += sig_begin + type_new + sig_end + ";\n";
2036 code +=
2037 "/**\n * @deprecated This Uint8Array overload will "
2038 "be removed in the future.\n */\n";
2039 code += sig_begin + type_old + sig_end + ";\n";
2040 type = type_new + "|Uint8Array";
2041 }
2042 }
2043 code += sig_begin + type + sig_end + " {\n";
2044 code += " builder.startVector(" + NumToString(elem_size);
2045 code += ", data.length, " + NumToString(alignment) + ");\n";
2046 code += " for (let i = data.length - 1; i >= 0; i--) {\n";
2047 code += " builder.add" + GenWriteMethod(vector_type) + "(";
2048 if (vector_type.base_type == BASE_TYPE_BOOL) { code += "+"; }
2049 code += "data[i]!);\n";
2050 code += " }\n";
2051 code += " return builder.endVector();\n";
2052 code += "}\n\n";
2053 }
2054
2055 // Generate a method to start a vector, data to be added manually
2056 // after
2057 GenDocComment(code_ptr);
2058
2059 code += "static ";
2060 code += namer_.Method("start", field, "Vector");
2061 code += "(builder:flatbuffers.Builder, numElems:number) {\n";
2062 code += " builder.startVector(" + NumToString(elem_size);
2063 code += ", numElems, " + NumToString(alignment) + ");\n";
2064 code += "}\n\n";
2065 }
2066 }
2067
2068 // Generate a method to stop building a new object
2069 GenDocComment(code_ptr);
2070
2071 code += "static end" + GetPrefixedName(struct_def);
2072 code += "(builder:flatbuffers.Builder):flatbuffers.Offset {\n";
2073
2074 code += " const offset = builder.endObject();\n";
2075 for (auto it = struct_def.fields.vec.begin();
2076 it != struct_def.fields.vec.end(); ++it) {
2077 auto &field = **it;
2078 if (!field.deprecated && field.IsRequired()) {
2079 code += " builder.requiredField(offset, ";
2080 code += NumToString(field.value.offset);
2081 code += ") // " + field.name + "\n";
2082 }
2083 }
2084 code += " return offset;\n";
2085 code += "}\n\n";
2086
2087 // Generate the methods to complete buffer construction
2088 GenerateFinisher(struct_def, code_ptr, code, false);
2089 GenerateFinisher(struct_def, code_ptr, code, true);
2090
2091 // Generate a convenient CreateX function
2092 if (CanCreateFactoryMethod(struct_def)) {
2093 code += "static create" + GetPrefixedName(struct_def);
2094 code += "(builder:flatbuffers.Builder";
2095 for (auto it = struct_def.fields.vec.begin();
2096 it != struct_def.fields.vec.end(); ++it) {
2097 const auto &field = **it;
2098 if (field.deprecated) continue;
2099 code += ", " + GetArgName(field) + ":" +
2100 GetArgType(imports, struct_def, field, true);
2101 }
2102
2103 code += "):flatbuffers.Offset {\n";
2104 code += " " + object_name + ".start" + GetPrefixedName(struct_def) +
2105 "(builder);\n";
2106
2107 std::string methodPrefix = object_name;
2108 for (auto it = struct_def.fields.vec.begin();
2109 it != struct_def.fields.vec.end(); ++it) {
2110 const auto &field = **it;
2111 if (field.deprecated) continue;
2112
2113 const auto arg_name = GetArgName(field);
2114
2115 if (field.IsScalarOptional()) {
2116 code += " if (" + arg_name + " !== null)\n ";
2117 }
2118
2119 code += " " + methodPrefix + "." + namer_.Method("add", field) + "(";
2120 code += "builder, " + arg_name + ");\n";
2121 }
2122
2123 code += " return " + methodPrefix + ".end" +
2124 GetPrefixedName(struct_def) + "(builder);\n";
2125 code += "}\n";
2126 }
2127 }
2128
2129 if (!struct_def.fixed && parser_.services_.vec.size() != 0) {
2130 auto name = GetPrefixedName(struct_def, "");
2131 code += "\n";
2132 code += "serialize():Uint8Array {\n";
2133 code += " return this.bb!.bytes();\n";
2134 code += "}\n";
2135
2136 code += "\n";
2137 code += "static deserialize(buffer: Uint8Array):" +
2138 namer_.EscapeKeyword(name) + " {\n";
2139 code += " return " + AddImport(imports, struct_def, struct_def).name +
2140 ".getRootAs" + name + "(new flatbuffers.ByteBuffer(buffer))\n";
2141 code += "}\n";
2142 }
2143
2144 if (parser_.opts.generate_object_based_api) {
2145 std::string obj_api_class;
2146 std::string obj_api_unpack_func;
2147 GenObjApi(parser_, struct_def, obj_api_unpack_func, obj_api_class,
2148 imports);
2149
2150 code += obj_api_unpack_func + "}\n" + obj_api_class;
2151 } else {
2152 code += "}\n";
2153 }
2154 }
2155
HasNullDefault(const FieldDef & field)2156 static bool HasNullDefault(const FieldDef &field) {
2157 return field.IsOptional() && field.value.constant == "null";
2158 }
2159
GetArgType(import_set & imports,const Definition & owner,const FieldDef & field,bool allowNull)2160 std::string GetArgType(import_set &imports, const Definition &owner,
2161 const FieldDef &field, bool allowNull) {
2162 return GenTypeName(imports, owner, field.value.type, true,
2163 allowNull && field.IsOptional());
2164 }
2165
GetArgName(const FieldDef & field)2166 std::string GetArgName(const FieldDef &field) {
2167 auto argname = namer_.Variable(field);
2168 if (!IsScalar(field.value.type.base_type)) { argname += "Offset"; }
2169 return argname;
2170 }
2171
GetPrefixedName(const StructDef & struct_def,const char * prefix="")2172 std::string GetPrefixedName(const StructDef &struct_def,
2173 const char *prefix = "") {
2174 return prefix + struct_def.name;
2175 }
2176 }; // namespace ts
2177 } // namespace ts
2178
GenerateTS(const Parser & parser,const std::string & path,const std::string & file_name)2179 static bool GenerateTS(const Parser &parser, const std::string &path,
2180 const std::string &file_name) {
2181 ts::TsGenerator generator(parser, path, file_name);
2182 return generator.generate();
2183 }
2184
TSMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)2185 static std::string TSMakeRule(const Parser &parser, const std::string &path,
2186 const std::string &file_name) {
2187 std::string filebase =
2188 flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
2189 ts::TsGenerator generator(parser, path, file_name);
2190 std::string make_rule =
2191 generator.GeneratedFileName(path, filebase, parser.opts) + ": ";
2192
2193 auto included_files = parser.GetIncludedFilesRecursive(file_name);
2194 for (auto it = included_files.begin(); it != included_files.end(); ++it) {
2195 make_rule += " " + *it;
2196 }
2197 return make_rule;
2198 }
2199
2200 namespace {
2201
2202 class TsCodeGenerator : public CodeGenerator {
2203 public:
GenerateCode(const Parser & parser,const std::string & path,const std::string & filename)2204 Status GenerateCode(const Parser &parser, const std::string &path,
2205 const std::string &filename) override {
2206 if (!GenerateTS(parser, path, filename)) { return Status::ERROR; }
2207 return Status::OK;
2208 }
2209
GenerateCode(const uint8_t *,int64_t,const CodeGenOptions &)2210 Status GenerateCode(const uint8_t *, int64_t,
2211 const CodeGenOptions &) override {
2212 return Status::NOT_IMPLEMENTED;
2213 }
2214
GenerateMakeRule(const Parser & parser,const std::string & path,const std::string & filename,std::string & output)2215 Status GenerateMakeRule(const Parser &parser, const std::string &path,
2216 const std::string &filename,
2217 std::string &output) override {
2218 output = TSMakeRule(parser, path, filename);
2219 return Status::OK;
2220 }
2221
GenerateGrpcCode(const Parser & parser,const std::string & path,const std::string & filename)2222 Status GenerateGrpcCode(const Parser &parser, const std::string &path,
2223 const std::string &filename) override {
2224 if (!GenerateTSGRPC(parser, path, filename)) { return Status::ERROR; }
2225 return Status::OK;
2226 }
2227
GenerateRootFile(const Parser & parser,const std::string & path)2228 Status GenerateRootFile(const Parser &parser,
2229 const std::string &path) override {
2230 (void)parser;
2231 (void)path;
2232 return Status::NOT_IMPLEMENTED;
2233 }
IsSchemaOnly() const2234 bool IsSchemaOnly() const override { return true; }
2235
SupportsBfbsGeneration() const2236 bool SupportsBfbsGeneration() const override { return false; }
SupportsRootFileGeneration() const2237 bool SupportsRootFileGeneration() const override { return false; }
2238
Language() const2239 IDLOptions::Language Language() const override { return IDLOptions::kTs; }
2240
LanguageName() const2241 std::string LanguageName() const override { return "TS"; }
2242 };
2243 } // namespace
2244
NewTsCodeGenerator()2245 std::unique_ptr<CodeGenerator> NewTsCodeGenerator() {
2246 return std::unique_ptr<TsCodeGenerator>(new TsCodeGenerator());
2247 }
2248
2249 } // namespace flatbuffers
2250