2 * Copyright 2014 Google Inc. All rights reserved.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 // independent from idl_parser, since this code is not needed for most clients
19 #include "flatbuffers/code_generators.h"
20 #include "flatbuffers/flatbuffers.h"
21 #include "flatbuffers/idl.h"
22 #include "flatbuffers/util.h"
24 #include <unordered_set>
26 namespace flatbuffers {
28 // Pedantic warning free version of toupper().
29 inline char ToUpper(char c) { return static_cast<char>(::toupper(c)); }
31 static std::string GeneratedFileName(const std::string &path,
32 const std::string &file_name) {
33 return path + file_name + "_generated.h";
37 class CppGenerator : public BaseGenerator {
39 CppGenerator(const Parser &parser, const std::string &path,
40 const std::string &file_name)
41 : BaseGenerator(parser, path, file_name, "", "::"),
42 cur_name_space_(nullptr) {
43 static const char * const keywords[] = {
140 for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
143 std::string GenIncludeGuard() const {
144 // Generate include guard.
145 std::string guard = file_name_;
146 // Remove any non-alpha-numeric characters that may appear in a filename.
148 bool operator()(char c) const { return !is_alnum(c); }
150 guard.erase(std::remove_if(guard.begin(), guard.end(), IsAlnum()),
152 guard = "FLATBUFFERS_GENERATED_" + guard;
154 // For further uniqueness, also add the namespace.
155 auto name_space = parser_.current_namespace_;
156 for (auto it = name_space->components.begin();
157 it != name_space->components.end(); ++it) {
161 std::transform(guard.begin(), guard.end(), guard.begin(), ToUpper);
165 void GenIncludeDependencies() {
166 int num_includes = 0;
167 for (auto it = parser_.native_included_files_.begin();
168 it != parser_.native_included_files_.end(); ++it) {
169 code_ += "#include \"" + *it + "\"";
172 for (auto it = parser_.included_files_.begin();
173 it != parser_.included_files_.end(); ++it) {
174 if (it->second.empty()) continue;
175 auto noext = flatbuffers::StripExtension(it->second);
176 auto basename = flatbuffers::StripPath(noext);
178 code_ += "#include \"" + parser_.opts.include_prefix +
179 (parser_.opts.keep_include_path ? noext : basename) +
183 if (num_includes) code_ += "";
186 std::string EscapeKeyword(const std::string &name) const {
187 return keywords_.find(name) == keywords_.end() ? name : name + "_";
190 std::string Name(const Definition &def) const {
191 return EscapeKeyword(def.name);
194 std::string Name(const EnumVal &ev) const { return EscapeKeyword(ev.name); }
196 // Iterate through all definitions we haven't generate code for (enums,
197 // structs, and tables) and output them to a single file.
200 code_ += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
202 const auto include_guard = GenIncludeGuard();
203 code_ += "#ifndef " + include_guard;
204 code_ += "#define " + include_guard;
207 if (parser_.opts.gen_nullable) {
208 code_ += "#pragma clang system_header\n\n";
211 code_ += "#include \"flatbuffers/flatbuffers.h\"";
212 if (parser_.uses_flexbuffers_) {
213 code_ += "#include \"flatbuffers/flexbuffers.h\"";
217 if (parser_.opts.include_dependence_headers) { GenIncludeDependencies(); }
219 FLATBUFFERS_ASSERT(!cur_name_space_);
221 // Generate forward declarations for all structs/tables, since they may
222 // have circular references.
223 for (auto it = parser_.structs_.vec.begin();
224 it != parser_.structs_.vec.end(); ++it) {
225 const auto &struct_def = **it;
226 if (!struct_def.generated) {
227 SetNameSpace(struct_def.defined_namespace);
228 code_ += "struct " + Name(struct_def) + ";";
229 if (parser_.opts.generate_object_based_api) {
230 auto nativeName = NativeName(Name(struct_def), &struct_def, parser_.opts);
231 if (!struct_def.fixed) {
232 code_ += "struct " + nativeName + ";";
239 // Generate forward declarations for all equal operators
240 if (parser_.opts.generate_object_based_api && parser_.opts.gen_compare) {
241 for (auto it = parser_.structs_.vec.begin();
242 it != parser_.structs_.vec.end(); ++it) {
243 const auto &struct_def = **it;
244 if (!struct_def.generated) {
245 SetNameSpace(struct_def.defined_namespace);
246 auto nativeName = NativeName(Name(struct_def), &struct_def, parser_.opts);
247 code_ += "bool operator==(const " + nativeName + " &lhs, const " + nativeName + " &rhs);";
253 // Generate preablmle code for mini reflection.
254 if (parser_.opts.mini_reflect != IDLOptions::kNone) {
255 // To break cyclic dependencies, first pre-declare all tables/structs.
256 for (auto it = parser_.structs_.vec.begin();
257 it != parser_.structs_.vec.end(); ++it) {
258 const auto &struct_def = **it;
259 if (!struct_def.generated) {
260 SetNameSpace(struct_def.defined_namespace);
261 GenMiniReflectPre(&struct_def);
266 // Generate code for all the enum declarations.
267 for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
269 const auto &enum_def = **it;
270 if (!enum_def.generated) {
271 SetNameSpace(enum_def.defined_namespace);
276 // Generate code for all structs, then all tables.
277 for (auto it = parser_.structs_.vec.begin();
278 it != parser_.structs_.vec.end(); ++it) {
279 const auto &struct_def = **it;
280 if (struct_def.fixed && !struct_def.generated) {
281 SetNameSpace(struct_def.defined_namespace);
282 GenStruct(struct_def);
285 for (auto it = parser_.structs_.vec.begin();
286 it != parser_.structs_.vec.end(); ++it) {
287 const auto &struct_def = **it;
288 if (!struct_def.fixed && !struct_def.generated) {
289 SetNameSpace(struct_def.defined_namespace);
290 GenTable(struct_def);
293 for (auto it = parser_.structs_.vec.begin();
294 it != parser_.structs_.vec.end(); ++it) {
295 const auto &struct_def = **it;
296 if (!struct_def.fixed && !struct_def.generated) {
297 SetNameSpace(struct_def.defined_namespace);
298 GenTablePost(struct_def);
302 // Generate code for union verifiers.
303 for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
305 const auto &enum_def = **it;
306 if (enum_def.is_union && !enum_def.generated) {
307 SetNameSpace(enum_def.defined_namespace);
308 GenUnionPost(enum_def);
312 // Generate code for mini reflection.
313 if (parser_.opts.mini_reflect != IDLOptions::kNone) {
314 // Then the unions/enums that may refer to them.
315 for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
317 const auto &enum_def = **it;
318 if (!enum_def.generated) {
319 SetNameSpace(enum_def.defined_namespace);
320 GenMiniReflect(nullptr, &enum_def);
323 // Then the full tables/structs.
324 for (auto it = parser_.structs_.vec.begin();
325 it != parser_.structs_.vec.end(); ++it) {
326 const auto &struct_def = **it;
327 if (!struct_def.generated) {
328 SetNameSpace(struct_def.defined_namespace);
329 GenMiniReflect(&struct_def, nullptr);
334 // Generate convenient global helper functions:
335 if (parser_.root_struct_def_) {
336 auto &struct_def = *parser_.root_struct_def_;
337 SetNameSpace(struct_def.defined_namespace);
338 auto name = Name(struct_def);
339 auto qualified_name = cur_name_space_->GetFullyQualifiedName(name);
340 auto cpp_name = TranslateNameSpace(qualified_name);
342 code_.SetValue("STRUCT_NAME", name);
343 code_.SetValue("CPP_NAME", cpp_name);
344 code_.SetValue("NULLABLE_EXT", NullableExtension());
346 // The root datatype accessor:
347 code_ += "inline \\";
349 "const {{CPP_NAME}} *{{NULLABLE_EXT}}Get{{STRUCT_NAME}}(const void "
351 code_ += " return flatbuffers::GetRoot<{{CPP_NAME}}>(buf);";
355 code_ += "inline \\";
357 "const {{CPP_NAME}} *{{NULLABLE_EXT}}GetSizePrefixed{{STRUCT_NAME}}(const void "
359 code_ += " return flatbuffers::GetSizePrefixedRoot<{{CPP_NAME}}>(buf);";
363 if (parser_.opts.mutable_buffer) {
364 code_ += "inline \\";
365 code_ += "{{STRUCT_NAME}} *GetMutable{{STRUCT_NAME}}(void *buf) {";
366 code_ += " return flatbuffers::GetMutableRoot<{{STRUCT_NAME}}>(buf);";
371 if (parser_.file_identifier_.length()) {
372 // Return the identifier
373 code_ += "inline const char *{{STRUCT_NAME}}Identifier() {";
374 code_ += " return \"" + parser_.file_identifier_ + "\";";
378 // Check if a buffer has the identifier.
379 code_ += "inline \\";
380 code_ += "bool {{STRUCT_NAME}}BufferHasIdentifier(const void *buf) {";
381 code_ += " return flatbuffers::BufferHasIdentifier(";
382 code_ += " buf, {{STRUCT_NAME}}Identifier());";
387 // The root verifier.
388 if (parser_.file_identifier_.length()) {
389 code_.SetValue("ID", name + "Identifier()");
391 code_.SetValue("ID", "nullptr");
394 code_ += "inline bool Verify{{STRUCT_NAME}}Buffer(";
395 code_ += " flatbuffers::Verifier &verifier) {";
396 code_ += " return verifier.VerifyBuffer<{{CPP_NAME}}>({{ID}});";
400 code_ += "inline bool VerifySizePrefixed{{STRUCT_NAME}}Buffer(";
401 code_ += " flatbuffers::Verifier &verifier) {";
402 code_ += " return verifier.VerifySizePrefixedBuffer<{{CPP_NAME}}>({{ID}});";
406 if (parser_.file_extension_.length()) {
407 // Return the extension
408 code_ += "inline const char *{{STRUCT_NAME}}Extension() {";
409 code_ += " return \"" + parser_.file_extension_ + "\";";
414 // Finish a buffer with a given root object:
415 code_ += "inline void Finish{{STRUCT_NAME}}Buffer(";
416 code_ += " flatbuffers::FlatBufferBuilder &fbb,";
417 code_ += " flatbuffers::Offset<{{CPP_NAME}}> root) {";
418 if (parser_.file_identifier_.length())
419 code_ += " fbb.Finish(root, {{STRUCT_NAME}}Identifier());";
421 code_ += " fbb.Finish(root);";
425 code_ += "inline void FinishSizePrefixed{{STRUCT_NAME}}Buffer(";
426 code_ += " flatbuffers::FlatBufferBuilder &fbb,";
427 code_ += " flatbuffers::Offset<{{CPP_NAME}}> root) {";
428 if (parser_.file_identifier_.length())
429 code_ += " fbb.FinishSizePrefixed(root, {{STRUCT_NAME}}Identifier());";
431 code_ += " fbb.FinishSizePrefixed(root);";
435 if (parser_.opts.generate_object_based_api) {
436 // A convenient root unpack function.
438 NativeName(WrapInNameSpace(struct_def), &struct_def, parser_.opts);
439 code_.SetValue("UNPACK_RETURN",
440 GenTypeNativePtr(native_name, nullptr, false));
441 code_.SetValue("UNPACK_TYPE",
442 GenTypeNativePtr(native_name, nullptr, true));
444 code_ += "inline {{UNPACK_RETURN}} UnPack{{STRUCT_NAME}}(";
445 code_ += " const void *buf,";
446 code_ += " const flatbuffers::resolver_function_t *res = nullptr) {";
447 code_ += " return {{UNPACK_TYPE}}\\";
448 code_ += "(Get{{STRUCT_NAME}}(buf)->UnPack(res));";
454 if (cur_name_space_) SetNameSpace(nullptr);
456 // Close the include guard.
457 code_ += "#endif // " + include_guard;
459 const auto file_path = GeneratedFileName(path_, file_name_);
460 const auto final_code = code_.ToString();
461 return SaveFile(file_path.c_str(), final_code, false);
467 std::unordered_set<std::string> keywords_;
469 // This tracks the current namespace so we can insert namespace declarations.
470 const Namespace *cur_name_space_;
472 const Namespace *CurrentNameSpace() const { return cur_name_space_; }
474 // Translates a qualified name in flatbuffer text format to the same name in
475 // the equivalent C++ namespace.
476 static std::string TranslateNameSpace(const std::string &qualified_name) {
477 std::string cpp_qualified_name = qualified_name;
478 size_t start_pos = 0;
479 while ((start_pos = cpp_qualified_name.find(".", start_pos)) !=
481 cpp_qualified_name.replace(start_pos, 1, "::");
483 return cpp_qualified_name;
486 void GenComment(const std::vector<std::string> &dc, const char *prefix = "") {
488 ::flatbuffers::GenComment(dc, &text, nullptr, prefix);
489 code_ += text + "\\";
492 // Return a C++ type from the table in idl.h
493 std::string GenTypeBasic(const Type &type, bool user_facing_type) const {
494 static const char * const ctypename[] = {
496 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
499 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
500 #undef FLATBUFFERS_TD
503 if (user_facing_type) {
504 if (type.enum_def) return WrapInNameSpace(*type.enum_def);
505 if (type.base_type == BASE_TYPE_BOOL) return "bool";
507 return ctypename[type.base_type];
510 // Return a C++ pointer type, specialized to the actual struct/table types,
511 // and vector element types.
512 std::string GenTypePointer(const Type &type) const {
513 switch (type.base_type) {
514 case BASE_TYPE_STRING: {
515 return "flatbuffers::String";
517 case BASE_TYPE_VECTOR: {
518 const auto type_name = GenTypeWire(type.VectorType(), "", false);
519 return "flatbuffers::Vector<" + type_name + ">";
521 case BASE_TYPE_STRUCT: {
522 return WrapInNameSpace(*type.struct_def);
524 case BASE_TYPE_UNION:
526 default: { return "void"; }
530 // Return a C++ type for any type (scalar/pointer) specifically for
531 // building a flatbuffer.
532 std::string GenTypeWire(const Type &type, const char *postfix,
533 bool user_facing_type) const {
534 if (IsScalar(type.base_type)) {
535 return GenTypeBasic(type, user_facing_type) + postfix;
536 } else if (IsStruct(type)) {
537 return "const " + GenTypePointer(type) + " *";
539 return "flatbuffers::Offset<" + GenTypePointer(type) + ">" + postfix;
543 // Return a C++ type for any type (scalar/pointer) that reflects its
545 std::string GenTypeSize(const Type &type) const {
546 if (IsScalar(type.base_type)) {
547 return GenTypeBasic(type, false);
548 } else if (IsStruct(type)) {
549 return GenTypePointer(type);
551 return "flatbuffers::uoffset_t";
555 std::string NullableExtension() {
556 return parser_.opts.gen_nullable ? " _Nullable " : "";
559 static std::string NativeName(const std::string &name, const StructDef *sd,
560 const IDLOptions &opts) {
561 return sd && !sd->fixed ? opts.object_prefix + name + opts.object_suffix
565 const std::string &PtrType(const FieldDef *field) {
566 auto attr = field ? field->attributes.Lookup("cpp_ptr_type") : nullptr;
567 return attr ? attr->constant : parser_.opts.cpp_object_api_pointer_type;
570 const std::string NativeString(const FieldDef *field) {
571 auto attr = field ? field->attributes.Lookup("cpp_str_type") : nullptr;
572 auto &ret = attr ? attr->constant : parser_.opts.cpp_object_api_string_type;
573 if (ret.empty()) { return "std::string"; }
577 std::string GenTypeNativePtr(const std::string &type, const FieldDef *field,
578 bool is_constructor) {
579 auto &ptr_type = PtrType(field);
580 if (ptr_type != "naked") {
581 return (ptr_type != "default_ptr_type" ? ptr_type :
582 parser_.opts.cpp_object_api_pointer_type) + "<" + type + ">";
583 } else if (is_constructor) {
590 std::string GenPtrGet(const FieldDef &field) {
591 auto cpp_ptr_type_get = field.attributes.Lookup("cpp_ptr_type_get");
592 if (cpp_ptr_type_get)
593 return cpp_ptr_type_get->constant;
594 auto &ptr_type = PtrType(&field);
595 return ptr_type == "naked" ? "" : ".get()";
598 std::string GenTypeNative(const Type &type, bool invector,
599 const FieldDef &field) {
600 switch (type.base_type) {
601 case BASE_TYPE_STRING: {
602 return NativeString(&field);
604 case BASE_TYPE_VECTOR: {
605 const auto type_name = GenTypeNative(type.VectorType(), true, field);
606 if (type.struct_def &&
607 type.struct_def->attributes.Lookup("native_custom_alloc")) {
608 auto native_custom_alloc =
609 type.struct_def->attributes.Lookup("native_custom_alloc");
610 return "std::vector<" + type_name + "," +
611 native_custom_alloc->constant + "<" + type_name + ">>";
613 return "std::vector<" + type_name + ">";
615 case BASE_TYPE_STRUCT: {
616 auto type_name = WrapInNameSpace(*type.struct_def);
617 if (IsStruct(type)) {
618 auto native_type = type.struct_def->attributes.Lookup("native_type");
619 if (native_type) { type_name = native_type->constant; }
620 if (invector || field.native_inline) {
623 return GenTypeNativePtr(type_name, &field, false);
626 return GenTypeNativePtr(
627 NativeName(type_name, type.struct_def, parser_.opts), &field,
631 case BASE_TYPE_UNION: {
632 return type.enum_def->name + "Union";
634 default: { return GenTypeBasic(type, true); }
638 // Return a C++ type for any type (scalar/pointer) specifically for
639 // using a flatbuffer.
640 std::string GenTypeGet(const Type &type, const char *afterbasic,
641 const char *beforeptr, const char *afterptr,
642 bool user_facing_type) {
643 if (IsScalar(type.base_type)) {
644 return GenTypeBasic(type, user_facing_type) + afterbasic;
646 return beforeptr + GenTypePointer(type) + afterptr;
650 std::string GenEnumDecl(const EnumDef &enum_def) const {
651 const IDLOptions &opts = parser_.opts;
652 return (opts.scoped_enums ? "enum class " : "enum ") + Name(enum_def);
655 std::string GenEnumValDecl(const EnumDef &enum_def,
656 const std::string &enum_val) const {
657 const IDLOptions &opts = parser_.opts;
658 return opts.prefixed_enums ? Name(enum_def) + "_" + enum_val : enum_val;
661 std::string GetEnumValUse(const EnumDef &enum_def,
662 const EnumVal &enum_val) const {
663 const IDLOptions &opts = parser_.opts;
664 if (opts.scoped_enums) {
665 return Name(enum_def) + "::" + Name(enum_val);
666 } else if (opts.prefixed_enums) {
667 return Name(enum_def) + "_" + Name(enum_val);
669 return Name(enum_val);
673 std::string StripUnionType(const std::string &name) {
674 return name.substr(0, name.size() - strlen(UnionTypeFieldSuffix()));
677 std::string GetUnionElement(const EnumVal &ev, bool wrap, bool actual_type,
678 bool native_type = false) {
679 if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
680 auto name = actual_type ? ev.union_type.struct_def->name : Name(ev);
681 return wrap ? WrapInNameSpace(ev.union_type.struct_def->defined_namespace,
684 } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
685 return actual_type ? (native_type ? "std::string" : "flatbuffers::String")
688 FLATBUFFERS_ASSERT(false);
693 std::string UnionVerifySignature(const EnumDef &enum_def) {
694 return "bool Verify" + Name(enum_def) +
695 "(flatbuffers::Verifier &verifier, const void *obj, " +
696 Name(enum_def) + " type)";
699 std::string UnionVectorVerifySignature(const EnumDef &enum_def) {
700 return "bool Verify" + Name(enum_def) + "Vector" +
701 "(flatbuffers::Verifier &verifier, " +
702 "const flatbuffers::Vector<flatbuffers::Offset<void>> *values, " +
703 "const flatbuffers::Vector<uint8_t> *types)";
706 std::string UnionUnPackSignature(const EnumDef &enum_def, bool inclass) {
707 return (inclass ? "static " : "") + std::string("void *") +
708 (inclass ? "" : Name(enum_def) + "Union::") +
709 "UnPack(const void *obj, " + Name(enum_def) +
710 " type, const flatbuffers::resolver_function_t *resolver)";
713 std::string UnionPackSignature(const EnumDef &enum_def, bool inclass) {
714 return "flatbuffers::Offset<void> " +
715 (inclass ? "" : Name(enum_def) + "Union::") +
716 "Pack(flatbuffers::FlatBufferBuilder &_fbb, " +
717 "const flatbuffers::rehasher_function_t *_rehasher" +
718 (inclass ? " = nullptr" : "") + ") const";
721 std::string TableCreateSignature(const StructDef &struct_def, bool predecl,
722 const IDLOptions &opts) {
723 return "flatbuffers::Offset<" + Name(struct_def) + "> Create" +
724 Name(struct_def) + "(flatbuffers::FlatBufferBuilder &_fbb, const " +
725 NativeName(Name(struct_def), &struct_def, opts) +
726 " *_o, const flatbuffers::rehasher_function_t *_rehasher" +
727 (predecl ? " = nullptr" : "") + ")";
730 std::string TablePackSignature(const StructDef &struct_def, bool inclass,
731 const IDLOptions &opts) {
732 return std::string(inclass ? "static " : "") + "flatbuffers::Offset<" +
733 Name(struct_def) + "> " + (inclass ? "" : Name(struct_def) + "::") +
734 "Pack(flatbuffers::FlatBufferBuilder &_fbb, " + "const " +
735 NativeName(Name(struct_def), &struct_def, opts) + "* _o, " +
736 "const flatbuffers::rehasher_function_t *_rehasher" +
737 (inclass ? " = nullptr" : "") + ")";
740 std::string TableUnPackSignature(const StructDef &struct_def, bool inclass,
741 const IDLOptions &opts) {
742 return NativeName(Name(struct_def), &struct_def, opts) + " *" +
743 (inclass ? "" : Name(struct_def) + "::") +
744 "UnPack(const flatbuffers::resolver_function_t *_resolver" +
745 (inclass ? " = nullptr" : "") + ") const";
748 std::string TableUnPackToSignature(const StructDef &struct_def, bool inclass,
749 const IDLOptions &opts) {
750 return "void " + (inclass ? "" : Name(struct_def) + "::") + "UnPackTo(" +
751 NativeName(Name(struct_def), &struct_def, opts) + " *" +
752 "_o, const flatbuffers::resolver_function_t *_resolver" +
753 (inclass ? " = nullptr" : "") + ") const";
756 void GenMiniReflectPre(const StructDef *struct_def) {
757 code_.SetValue("NAME", struct_def->name);
758 code_ += "inline const flatbuffers::TypeTable *{{NAME}}TypeTable();";
762 void GenMiniReflect(const StructDef *struct_def, const EnumDef *enum_def) {
763 code_.SetValue("NAME", struct_def ? struct_def->name : enum_def->name);
764 code_.SetValue("SEQ_TYPE",
765 struct_def ? (struct_def->fixed ? "ST_STRUCT" : "ST_TABLE")
766 : (enum_def->is_union ? "ST_UNION" : "ST_ENUM"));
768 struct_def ? struct_def->fields.vec.size() : enum_def->vals.vec.size();
769 code_.SetValue("NUM_FIELDS", NumToString(num_fields));
770 std::vector<std::string> names;
771 std::vector<Type> types;
772 bool consecutive_enum_from_zero = true;
774 for (auto it = struct_def->fields.vec.begin();
775 it != struct_def->fields.vec.end(); ++it) {
776 const auto &field = **it;
777 names.push_back(Name(field));
778 types.push_back(field.value.type);
781 for (auto it = enum_def->vals.vec.begin(); it != enum_def->vals.vec.end();
783 const auto &ev = **it;
784 names.push_back(Name(ev));
785 types.push_back(enum_def->is_union ? ev.union_type
786 : Type(enum_def->underlying_type));
787 if (static_cast<int64_t>(it - enum_def->vals.vec.begin()) != ev.value) {
788 consecutive_enum_from_zero = false;
793 std::vector<std::string> type_refs;
794 for (auto it = types.begin(); it != types.end(); ++it) {
796 if (!ts.empty()) ts += ",\n ";
797 auto is_vector = type.base_type == BASE_TYPE_VECTOR;
798 auto bt = is_vector ? type.element : type.base_type;
799 auto et = IsScalar(bt) || bt == BASE_TYPE_STRING
800 ? bt - BASE_TYPE_UTYPE + ET_UTYPE
803 std::string ref_name =
805 ? WrapInNameSpace(*type.struct_def)
806 : type.enum_def ? WrapInNameSpace(*type.enum_def) : "";
807 if (!ref_name.empty()) {
808 auto rit = type_refs.begin();
809 for (; rit != type_refs.end(); ++rit) {
810 if (*rit == ref_name) {
811 ref_idx = static_cast<int>(rit - type_refs.begin());
815 if (rit == type_refs.end()) {
816 ref_idx = static_cast<int>(type_refs.size());
817 type_refs.push_back(ref_name);
820 ts += "{ flatbuffers::" + std::string(ElementaryTypeNames()[et]) + ", " +
821 NumToString(is_vector) + ", " + NumToString(ref_idx) + " }";
824 for (auto it = type_refs.begin(); it != type_refs.end(); ++it) {
825 if (!rs.empty()) rs += ",\n ";
826 rs += *it + "TypeTable";
829 for (auto it = names.begin(); it != names.end(); ++it) {
830 if (!ns.empty()) ns += ",\n ";
831 ns += "\"" + *it + "\"";
834 if (enum_def && !consecutive_enum_from_zero) {
835 for (auto it = enum_def->vals.vec.begin(); it != enum_def->vals.vec.end();
837 const auto &ev = **it;
838 if (!vs.empty()) vs += ", ";
839 vs += NumToString(ev.value);
841 } else if (struct_def && struct_def->fixed) {
842 for (auto it = struct_def->fields.vec.begin();
843 it != struct_def->fields.vec.end(); ++it) {
844 const auto &field = **it;
845 vs += NumToString(field.value.offset);
848 vs += NumToString(struct_def->bytesize);
850 code_.SetValue("TYPES", ts);
851 code_.SetValue("REFS", rs);
852 code_.SetValue("NAMES", ns);
853 code_.SetValue("VALUES", vs);
854 code_ += "inline const flatbuffers::TypeTable *{{NAME}}TypeTable() {";
856 code_ += " static const flatbuffers::TypeCode type_codes[] = {";
857 code_ += " {{TYPES}}";
860 if (!type_refs.empty()) {
861 code_ += " static const flatbuffers::TypeFunction type_refs[] = {";
862 code_ += " {{REFS}}";
866 code_ += " static const int64_t values[] = { {{VALUES}} };";
869 num_fields && parser_.opts.mini_reflect == IDLOptions::kTypesAndNames;
871 code_ += " static const char * const names[] = {";
872 code_ += " {{NAMES}}";
875 code_ += " static const flatbuffers::TypeTable tt = {";
876 code_ += std::string(" flatbuffers::{{SEQ_TYPE}}, {{NUM_FIELDS}}, ") +
877 (num_fields ? "type_codes, " : "nullptr, ") +
878 (!type_refs.empty() ? "type_refs, " : "nullptr, ") +
879 (!vs.empty() ? "values, " : "nullptr, ") +
880 (has_names ? "names" : "nullptr");
882 code_ += " return &tt;";
887 // Generate an enum declaration,
888 // an enum string lookup table,
889 // and an enum array of values
890 void GenEnum(const EnumDef &enum_def) {
891 code_.SetValue("ENUM_NAME", Name(enum_def));
892 code_.SetValue("BASE_TYPE", GenTypeBasic(enum_def.underlying_type, false));
893 code_.SetValue("SEP", "");
895 GenComment(enum_def.doc_comment);
896 code_ += GenEnumDecl(enum_def) + "\\";
897 if (parser_.opts.scoped_enums) code_ += " : {{BASE_TYPE}}\\";
901 const EnumVal *minv = nullptr, *maxv = nullptr;
902 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
904 const auto &ev = **it;
906 GenComment(ev.doc_comment, " ");
907 code_.SetValue("KEY", GenEnumValDecl(enum_def, Name(ev)));
908 code_.SetValue("VALUE", NumToString(ev.value));
909 code_ += "{{SEP}} {{KEY}} = {{VALUE}}\\";
910 code_.SetValue("SEP", ",\n");
912 minv = !minv || minv->value > ev.value ? &ev : minv;
913 maxv = !maxv || maxv->value < ev.value ? &ev : maxv;
917 if (parser_.opts.scoped_enums || parser_.opts.prefixed_enums) {
918 FLATBUFFERS_ASSERT(minv && maxv);
920 code_.SetValue("SEP", ",\n");
921 if (enum_def.attributes.Lookup("bit_flags")) {
922 code_.SetValue("KEY", GenEnumValDecl(enum_def, "NONE"));
923 code_.SetValue("VALUE", "0");
924 code_ += "{{SEP}} {{KEY}} = {{VALUE}}\\";
926 code_.SetValue("KEY", GenEnumValDecl(enum_def, "ANY"));
927 code_.SetValue("VALUE", NumToString(anyv));
928 code_ += "{{SEP}} {{KEY}} = {{VALUE}}\\";
929 } else { // MIN & MAX are useless for bit_flags
930 code_.SetValue("KEY", GenEnumValDecl(enum_def, "MIN"));
931 code_.SetValue("VALUE", GenEnumValDecl(enum_def, minv->name));
932 code_ += "{{SEP}} {{KEY}} = {{VALUE}}\\";
934 code_.SetValue("KEY", GenEnumValDecl(enum_def, "MAX"));
935 code_.SetValue("VALUE", GenEnumValDecl(enum_def, maxv->name));
936 code_ += "{{SEP}} {{KEY}} = {{VALUE}}\\";
942 if (parser_.opts.scoped_enums && enum_def.attributes.Lookup("bit_flags")) {
943 code_ += "FLATBUFFERS_DEFINE_BITMASK_OPERATORS({{ENUM_NAME}}, {{BASE_TYPE}})";
947 // Generate an array of all enumeration values
948 auto num_fields = NumToString(enum_def.vals.vec.size());
949 code_ += "inline const {{ENUM_NAME}} (&EnumValues{{ENUM_NAME}}())[" + num_fields +
951 code_ += " static const {{ENUM_NAME}} values[] = {";
952 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
954 const auto &ev = **it;
955 auto value = GetEnumValUse(enum_def, ev);
956 auto suffix = *it != enum_def.vals.vec.back() ? "," : "";
957 code_ += " " + value + suffix;
960 code_ += " return values;";
964 // Generate a generate string table for enum values.
965 // Problem is, if values are very sparse that could generate really big
966 // tables. Ideally in that case we generate a map lookup instead, but for
967 // the moment we simply don't output a table at all.
969 enum_def.vals.vec.back()->value - enum_def.vals.vec.front()->value + 1;
970 // Average distance between values above which we consider a table
971 // "too sparse". Change at will.
972 static const int kMaxSparseness = 5;
973 if (range / static_cast<int64_t>(enum_def.vals.vec.size()) <
975 code_ += "inline const char * const *EnumNames{{ENUM_NAME}}() {";
976 code_ += " static const char * const names[] = {";
978 auto val = enum_def.vals.vec.front()->value;
979 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
981 const auto &ev = **it;
982 while (val++ != ev.value) { code_ += " \"\","; }
983 code_ += " \"" + Name(ev) + "\",";
988 code_ += " return names;";
992 code_ += "inline const char *EnumName{{ENUM_NAME}}({{ENUM_NAME}} e) {";
994 code_ += " if (e < " + GetEnumValUse(enum_def, *enum_def.vals.vec.front()) +
995 " || e > " + GetEnumValUse(enum_def, *enum_def.vals.vec.back()) +
998 code_ += " const size_t index = static_cast<int>(e)\\";
999 if (enum_def.vals.vec.front()->value) {
1000 auto vals = GetEnumValUse(enum_def, *enum_def.vals.vec.front());
1001 code_ += " - static_cast<int>(" + vals + ")\\";
1005 code_ += " return EnumNames{{ENUM_NAME}}()[index];";
1009 code_ += "inline const char *EnumName{{ENUM_NAME}}({{ENUM_NAME}} e) {";
1011 code_ += " switch (e) {";
1013 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1015 const auto &ev = **it;
1016 code_ += " case " + GetEnumValUse(enum_def, ev) + ": return \"" +
1020 code_ += " default: return \"\";";
1027 // Generate type traits for unions to map from a type to union enum value.
1028 if (enum_def.is_union && !enum_def.uses_type_aliases) {
1029 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1031 const auto &ev = **it;
1033 if (it == enum_def.vals.vec.begin()) {
1034 code_ += "template<typename T> struct {{ENUM_NAME}}Traits {";
1036 auto name = GetUnionElement(ev, true, true);
1037 code_ += "template<> struct {{ENUM_NAME}}Traits<" + name + "> {";
1040 auto value = GetEnumValUse(enum_def, ev);
1041 code_ += " static const {{ENUM_NAME}} enum_value = " + value + ";";
1047 if (parser_.opts.generate_object_based_api && enum_def.is_union) {
1048 // Generate a union type
1049 code_.SetValue("NAME", Name(enum_def));
1050 code_.SetValue("NONE",
1051 GetEnumValUse(enum_def, *enum_def.vals.Lookup("NONE")));
1053 code_ += "struct {{NAME}}Union {";
1054 code_ += " {{NAME}} type;";
1055 code_ += " void *value;";
1057 code_ += " {{NAME}}Union() : type({{NONE}}), value(nullptr) {}";
1058 code_ += " {{NAME}}Union({{NAME}}Union&& u) FLATBUFFERS_NOEXCEPT :";
1059 code_ += " type({{NONE}}), value(nullptr)";
1060 code_ += " { std::swap(type, u.type); std::swap(value, u.value); }";
1061 code_ += " {{NAME}}Union(const {{NAME}}Union &) FLATBUFFERS_NOEXCEPT;";
1063 " {{NAME}}Union &operator=(const {{NAME}}Union &u) "
1064 "FLATBUFFERS_NOEXCEPT";
1066 " { {{NAME}}Union t(u); std::swap(type, t.type); std::swap(value, "
1067 "t.value); return *this; }";
1069 " {{NAME}}Union &operator=({{NAME}}Union &&u) FLATBUFFERS_NOEXCEPT";
1071 " { std::swap(type, u.type); std::swap(value, u.value); return "
1073 code_ += " ~{{NAME}}Union() { Reset(); }";
1075 code_ += " void Reset();";
1077 if (!enum_def.uses_type_aliases) {
1078 code_ += "#ifndef FLATBUFFERS_CPP98_STL";
1079 code_ += " template <typename T>";
1080 code_ += " void Set(T&& val) {";
1081 code_ += " Reset();";
1083 " type = {{NAME}}Traits<typename T::TableType>::enum_value;";
1084 code_ += " if (type != {{NONE}}) {";
1085 code_ += " value = new T(std::forward<T>(val));";
1088 code_ += "#endif // FLATBUFFERS_CPP98_STL";
1091 code_ += " " + UnionUnPackSignature(enum_def, true) + ";";
1092 code_ += " " + UnionPackSignature(enum_def, true) + ";";
1095 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1097 const auto &ev = **it;
1098 if (!ev.value) { continue; }
1100 const auto native_type =
1101 NativeName(GetUnionElement(ev, true, true, true),
1102 ev.union_type.struct_def, parser_.opts);
1103 code_.SetValue("NATIVE_TYPE", native_type);
1104 code_.SetValue("NATIVE_NAME", Name(ev));
1105 code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
1107 code_ += " {{NATIVE_TYPE}} *As{{NATIVE_NAME}}() {";
1108 code_ += " return type == {{NATIVE_ID}} ?";
1109 code_ += " reinterpret_cast<{{NATIVE_TYPE}} *>(value) : nullptr;";
1112 code_ += " const {{NATIVE_TYPE}} *As{{NATIVE_NAME}}() const {";
1113 code_ += " return type == {{NATIVE_ID}} ?";
1115 " reinterpret_cast<const {{NATIVE_TYPE}} *>(value) : nullptr;";
1121 if (parser_.opts.gen_compare) {
1123 code_ += "inline bool operator==(const {{NAME}}Union &lhs, const {{NAME}}Union &rhs) {";
1124 code_ += " if (lhs.type != rhs.type) return false;";
1125 code_ += " switch (lhs.type) {";
1127 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1129 const auto &ev = **it;
1130 code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
1132 const auto native_type =
1133 NativeName(GetUnionElement(ev, true, true, true),
1134 ev.union_type.struct_def, parser_.opts);
1135 code_.SetValue("NATIVE_TYPE", native_type);
1136 code_ += " case {{NATIVE_ID}}: {";
1137 code_ += " return *(reinterpret_cast<const {{NATIVE_TYPE}} *>(lhs.value)) ==";
1138 code_ += " *(reinterpret_cast<const {{NATIVE_TYPE}} *>(rhs.value));";
1141 code_ += " case {{NATIVE_ID}}: {";
1142 code_ += " return true;"; // "NONE" enum value.
1146 code_ += " default: {";
1147 code_ += " return false;";
1154 if (enum_def.is_union) {
1155 code_ += UnionVerifySignature(enum_def) + ";";
1156 code_ += UnionVectorVerifySignature(enum_def) + ";";
1161 void GenUnionPost(const EnumDef &enum_def) {
1162 // Generate a verifier function for this union that can be called by the
1163 // table verifier functions. It uses a switch case to select a specific
1164 // verifier function to call, this should be safe even if the union type
1165 // has been corrupted, since the verifiers will simply fail when called
1166 // on the wrong type.
1167 code_.SetValue("ENUM_NAME", Name(enum_def));
1169 code_ += "inline " + UnionVerifySignature(enum_def) + " {";
1170 code_ += " switch (type) {";
1171 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1173 const auto &ev = **it;
1174 code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
1177 code_.SetValue("TYPE", GetUnionElement(ev, true, true));
1178 code_ += " case {{LABEL}}: {";
1180 " auto ptr = reinterpret_cast<const {{TYPE}} *>(obj);";
1181 if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
1182 if (ev.union_type.struct_def->fixed) {
1183 code_ += " return true;";
1186 code_ += " return verifier.VerifyTable(ptr);";
1188 } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
1190 code_ += " return verifier.VerifyString(ptr);";
1192 FLATBUFFERS_ASSERT(false);
1196 code_ += " case {{LABEL}}: {";
1197 code_ += " return true;"; // "NONE" enum value.
1201 code_ += " default: return false;";
1206 code_ += "inline " + UnionVectorVerifySignature(enum_def) + " {";
1207 code_ += " if (!values || !types) return !values && !types;";
1208 code_ += " if (values->size() != types->size()) return false;";
1209 code_ += " for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {";
1210 code_ += " if (!Verify" + Name(enum_def) + "(";
1211 code_ += " verifier, values->Get(i), types->GetEnum<" +
1212 Name(enum_def) + ">(i))) {";
1213 code_ += " return false;";
1216 code_ += " return true;";
1220 if (parser_.opts.generate_object_based_api) {
1221 // Generate union Unpack() and Pack() functions.
1222 code_ += "inline " + UnionUnPackSignature(enum_def, false) + " {";
1223 code_ += " switch (type) {";
1224 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1226 const auto &ev = **it;
1227 if (!ev.value) { continue; }
1229 code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
1230 code_.SetValue("TYPE", GetUnionElement(ev, true, true));
1231 code_ += " case {{LABEL}}: {";
1232 code_ += " auto ptr = reinterpret_cast<const {{TYPE}} *>(obj);";
1233 if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
1234 if (ev.union_type.struct_def->fixed) {
1235 code_ += " return new " +
1236 WrapInNameSpace(*ev.union_type.struct_def) + "(*ptr);";
1238 code_ += " return ptr->UnPack(resolver);";
1240 } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
1241 code_ += " return new std::string(ptr->c_str(), ptr->size());";
1243 FLATBUFFERS_ASSERT(false);
1247 code_ += " default: return nullptr;";
1252 code_ += "inline " + UnionPackSignature(enum_def, false) + " {";
1253 code_ += " switch (type) {";
1254 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1257 if (!ev.value) { continue; }
1259 code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
1260 code_.SetValue("TYPE",
1261 NativeName(GetUnionElement(ev, true, true, true),
1262 ev.union_type.struct_def, parser_.opts));
1263 code_.SetValue("NAME", GetUnionElement(ev, false, true));
1264 code_ += " case {{LABEL}}: {";
1265 code_ += " auto ptr = reinterpret_cast<const {{TYPE}} *>(value);";
1266 if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
1267 if (ev.union_type.struct_def->fixed) {
1268 code_ += " return _fbb.CreateStruct(*ptr).Union();";
1271 " return Create{{NAME}}(_fbb, ptr, _rehasher).Union();";
1273 } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
1274 code_ += " return _fbb.CreateString(*ptr).Union();";
1276 FLATBUFFERS_ASSERT(false);
1280 code_ += " default: return 0;";
1285 // Union copy constructor
1287 "inline {{ENUM_NAME}}Union::{{ENUM_NAME}}Union(const "
1288 "{{ENUM_NAME}}Union &u) FLATBUFFERS_NOEXCEPT : type(u.type), "
1290 code_ += " switch (type) {";
1291 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1293 const auto &ev = **it;
1294 if (!ev.value) { continue; }
1295 code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
1296 code_.SetValue("TYPE",
1297 NativeName(GetUnionElement(ev, true, true, true),
1298 ev.union_type.struct_def, parser_.opts));
1299 code_ += " case {{LABEL}}: {";
1300 bool copyable = true;
1301 if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
1302 // Don't generate code to copy if table is not copyable.
1303 // TODO(wvo): make tables copyable instead.
1304 for (auto fit = ev.union_type.struct_def->fields.vec.begin();
1305 fit != ev.union_type.struct_def->fields.vec.end(); ++fit) {
1306 const auto &field = **fit;
1307 if (!field.deprecated && field.value.type.struct_def &&
1308 !field.native_inline) {
1316 " value = new {{TYPE}}(*reinterpret_cast<{{TYPE}} *>"
1319 code_ += " FLATBUFFERS_ASSERT(false); // {{TYPE}} not copyable.";
1324 code_ += " default:";
1330 // Union Reset() function.
1331 code_.SetValue("NONE",
1332 GetEnumValUse(enum_def, *enum_def.vals.Lookup("NONE")));
1334 code_ += "inline void {{ENUM_NAME}}Union::Reset() {";
1335 code_ += " switch (type) {";
1336 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1338 const auto &ev = **it;
1339 if (!ev.value) { continue; }
1340 code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
1341 code_.SetValue("TYPE",
1342 NativeName(GetUnionElement(ev, true, true, true),
1343 ev.union_type.struct_def, parser_.opts));
1344 code_ += " case {{LABEL}}: {";
1345 code_ += " auto ptr = reinterpret_cast<{{TYPE}} *>(value);";
1346 code_ += " delete ptr;";
1350 code_ += " default: break;";
1352 code_ += " value = nullptr;";
1353 code_ += " type = {{NONE}};";
1359 // Generates a value with optionally a cast applied if the field has a
1360 // different underlying type from its interface type (currently only the
1361 // case for enums. "from" specify the direction, true meaning from the
1362 // underlying type to the interface type.
1363 std::string GenUnderlyingCast(const FieldDef &field, bool from,
1364 const std::string &val) {
1365 if (from && field.value.type.base_type == BASE_TYPE_BOOL) {
1366 return val + " != 0";
1367 } else if ((field.value.type.enum_def &&
1368 IsScalar(field.value.type.base_type)) ||
1369 field.value.type.base_type == BASE_TYPE_BOOL) {
1370 return "static_cast<" + GenTypeBasic(field.value.type, from) + ">(" +
1377 std::string GenFieldOffsetName(const FieldDef &field) {
1378 std::string uname = Name(field);
1379 std::transform(uname.begin(), uname.end(), uname.begin(), ToUpper);
1380 return "VT_" + uname;
1383 void GenFullyQualifiedNameGetter(const StructDef &struct_def,
1384 const std::string &name) {
1385 if (!parser_.opts.generate_name_strings) { return; }
1386 auto fullname = struct_def.defined_namespace->GetFullyQualifiedName(name);
1387 code_.SetValue("NAME", fullname);
1388 code_.SetValue("CONSTEXPR", "FLATBUFFERS_CONSTEXPR");
1389 code_ += " static {{CONSTEXPR}} const char *GetFullyQualifiedName() {";
1390 code_ += " return \"{{NAME}}\";";
1394 std::string GenDefaultConstant(const FieldDef &field) {
1395 return field.value.type.base_type == BASE_TYPE_FLOAT
1396 ? field.value.constant + "f"
1397 : field.value.constant;
1400 std::string GetDefaultScalarValue(const FieldDef &field, bool is_ctor) {
1401 if (field.value.type.enum_def && IsScalar(field.value.type.base_type)) {
1402 auto ev = field.value.type.enum_def->ReverseLookup(
1403 StringToInt(field.value.constant.c_str()), false);
1405 return WrapInNameSpace(field.value.type.enum_def->defined_namespace,
1406 GetEnumValUse(*field.value.type.enum_def, *ev));
1408 return GenUnderlyingCast(field, true, field.value.constant);
1410 } else if (field.value.type.base_type == BASE_TYPE_BOOL) {
1411 return field.value.constant == "0" ? "false" : "true";
1412 } else if (field.attributes.Lookup("cpp_type")) {
1414 if (PtrType(&field) == "naked") {
1423 return GenDefaultConstant(field);
1427 void GenParam(const FieldDef &field, bool direct, const char *prefix) {
1428 code_.SetValue("PRE", prefix);
1429 code_.SetValue("PARAM_NAME", Name(field));
1430 if (direct && field.value.type.base_type == BASE_TYPE_STRING) {
1431 code_.SetValue("PARAM_TYPE", "const char *");
1432 code_.SetValue("PARAM_VALUE", "nullptr");
1433 } else if (direct && field.value.type.base_type == BASE_TYPE_VECTOR) {
1434 const auto vtype = field.value.type.VectorType();
1436 if (IsStruct(vtype)) {
1437 type = WrapInNameSpace(*vtype.struct_def);
1439 type = GenTypeWire(vtype, "", false);
1441 code_.SetValue("PARAM_TYPE", "const std::vector<" + type + "> *");
1442 code_.SetValue("PARAM_VALUE", "nullptr");
1444 code_.SetValue("PARAM_TYPE", GenTypeWire(field.value.type, " ", true));
1445 code_.SetValue("PARAM_VALUE", GetDefaultScalarValue(field, false));
1447 code_ += "{{PRE}}{{PARAM_TYPE}}{{PARAM_NAME}} = {{PARAM_VALUE}}\\";
1450 // Generate a member, including a default value for scalars and raw pointers.
1451 void GenMember(const FieldDef &field) {
1452 if (!field.deprecated && // Deprecated fields won't be accessible.
1453 field.value.type.base_type != BASE_TYPE_UTYPE &&
1454 (field.value.type.base_type != BASE_TYPE_VECTOR ||
1455 field.value.type.element != BASE_TYPE_UTYPE)) {
1456 auto type = GenTypeNative(field.value.type, false, field);
1457 auto cpp_type = field.attributes.Lookup("cpp_type");
1459 (cpp_type ? (field.value.type.base_type == BASE_TYPE_VECTOR
1460 ? "std::vector<" + GenTypeNativePtr(cpp_type->constant, &field, false) + "> "
1461 : GenTypeNativePtr(cpp_type->constant, &field, false))
1463 code_.SetValue("FIELD_TYPE", full_type);
1464 code_.SetValue("FIELD_NAME", Name(field));
1465 code_ += " {{FIELD_TYPE}}{{FIELD_NAME}};";
1469 // Generate the default constructor for this struct. Properly initialize all
1470 // scalar members with default values.
1471 void GenDefaultConstructor(const StructDef &struct_def) {
1472 std::string initializer_list;
1473 for (auto it = struct_def.fields.vec.begin();
1474 it != struct_def.fields.vec.end(); ++it) {
1475 const auto &field = **it;
1476 if (!field.deprecated && // Deprecated fields won't be accessible.
1477 field.value.type.base_type != BASE_TYPE_UTYPE) {
1478 auto cpp_type = field.attributes.Lookup("cpp_type");
1479 auto native_default = field.attributes.Lookup("native_default");
1480 // Scalar types get parsed defaults, raw pointers get nullptrs.
1481 if (IsScalar(field.value.type.base_type)) {
1482 if (!initializer_list.empty()) { initializer_list += ",\n "; }
1483 initializer_list += Name(field);
1484 initializer_list += "(" + (native_default ? std::string(native_default->constant) : GetDefaultScalarValue(field, true)) + ")";
1485 } else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
1486 if (IsStruct(field.value.type)) {
1487 if (native_default) {
1488 if (!initializer_list.empty()) {
1489 initializer_list += ",\n ";
1492 Name(field) + "(" + native_default->constant + ")";
1495 } else if (cpp_type && field.value.type.base_type != BASE_TYPE_VECTOR) {
1496 if (!initializer_list.empty()) { initializer_list += ",\n "; }
1497 initializer_list += Name(field) + "(0)";
1501 if (!initializer_list.empty()) {
1502 initializer_list = "\n : " + initializer_list;
1505 code_.SetValue("NATIVE_NAME",
1506 NativeName(Name(struct_def), &struct_def, parser_.opts));
1507 code_.SetValue("INIT_LIST", initializer_list);
1509 code_ += " {{NATIVE_NAME}}(){{INIT_LIST}} {";
1513 void GenCompareOperator(const StructDef &struct_def, std::string accessSuffix = "") {
1514 std::string compare_op;
1515 for (auto it = struct_def.fields.vec.begin();
1516 it != struct_def.fields.vec.end(); ++it) {
1517 const auto &field = **it;
1518 if (!field.deprecated && // Deprecated fields won't be accessible.
1519 field.value.type.base_type != BASE_TYPE_UTYPE &&
1520 (field.value.type.base_type != BASE_TYPE_VECTOR ||
1521 field.value.type.element != BASE_TYPE_UTYPE)) {
1522 if (!compare_op.empty()) {
1523 compare_op += " &&\n ";
1525 auto accessor = Name(field) + accessSuffix;
1526 compare_op += "(lhs." + accessor + " == rhs." + accessor + ")";
1530 std::string cmp_lhs;
1531 std::string cmp_rhs;
1532 if (compare_op.empty()) {
1535 compare_op = " return true;";
1539 compare_op = " return\n " + compare_op + ";";
1542 code_.SetValue("CMP_OP", compare_op);
1543 code_.SetValue("CMP_LHS", cmp_lhs);
1544 code_.SetValue("CMP_RHS", cmp_rhs);
1546 code_ += "inline bool operator==(const {{NATIVE_NAME}} &{{CMP_LHS}}, const {{NATIVE_NAME}} &{{CMP_RHS}}) {";
1547 code_ += "{{CMP_OP}}";
1551 void GenOperatorNewDelete(const StructDef &struct_def) {
1552 if (auto native_custom_alloc =
1553 struct_def.attributes.Lookup("native_custom_alloc")) {
1554 code_ += " inline void *operator new (std::size_t count) {";
1555 code_ += " return " + native_custom_alloc->constant +
1556 "<{{NATIVE_NAME}}>().allocate(count / sizeof({{NATIVE_NAME}}));";
1558 code_ += " inline void operator delete (void *ptr) {";
1559 code_ += " return " + native_custom_alloc->constant +
1560 "<{{NATIVE_NAME}}>().deallocate(static_cast<{{NATIVE_NAME}}*>("
1566 void GenNativeTable(const StructDef &struct_def) {
1567 const auto native_name =
1568 NativeName(Name(struct_def), &struct_def, parser_.opts);
1569 code_.SetValue("STRUCT_NAME", Name(struct_def));
1570 code_.SetValue("NATIVE_NAME", native_name);
1572 // Generate a C++ object that can hold an unpacked version of this table.
1573 code_ += "struct {{NATIVE_NAME}} : public flatbuffers::NativeTable {";
1574 code_ += " typedef {{STRUCT_NAME}} TableType;";
1575 GenFullyQualifiedNameGetter(struct_def, native_name);
1576 for (auto it = struct_def.fields.vec.begin();
1577 it != struct_def.fields.vec.end(); ++it) {
1580 GenOperatorNewDelete(struct_def);
1581 GenDefaultConstructor(struct_def);
1583 if (parser_.opts.gen_compare) GenCompareOperator(struct_def);
1587 // Generate the code to call the appropriate Verify function(s) for a field.
1588 void GenVerifyCall(const FieldDef &field, const char *prefix) {
1589 code_.SetValue("PRE", prefix);
1590 code_.SetValue("NAME", Name(field));
1591 code_.SetValue("REQUIRED", field.required ? "Required" : "");
1592 code_.SetValue("SIZE", GenTypeSize(field.value.type));
1593 code_.SetValue("OFFSET", GenFieldOffsetName(field));
1594 if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type)) {
1596 "{{PRE}}VerifyField{{REQUIRED}}<{{SIZE}}>(verifier, {{OFFSET}})\\";
1598 code_ += "{{PRE}}VerifyOffset{{REQUIRED}}(verifier, {{OFFSET}})\\";
1601 switch (field.value.type.base_type) {
1602 case BASE_TYPE_UNION: {
1603 code_.SetValue("ENUM_NAME", field.value.type.enum_def->name);
1604 code_.SetValue("SUFFIX", UnionTypeFieldSuffix());
1606 "{{PRE}}Verify{{ENUM_NAME}}(verifier, {{NAME}}(), "
1607 "{{NAME}}{{SUFFIX}}())\\";
1610 case BASE_TYPE_STRUCT: {
1611 if (!field.value.type.struct_def->fixed) {
1612 code_ += "{{PRE}}verifier.VerifyTable({{NAME}}())\\";
1616 case BASE_TYPE_STRING: {
1617 code_ += "{{PRE}}verifier.VerifyString({{NAME}}())\\";
1620 case BASE_TYPE_VECTOR: {
1621 code_ += "{{PRE}}verifier.VerifyVector({{NAME}}())\\";
1623 switch (field.value.type.element) {
1624 case BASE_TYPE_STRING: {
1625 code_ += "{{PRE}}verifier.VerifyVectorOfStrings({{NAME}}())\\";
1628 case BASE_TYPE_STRUCT: {
1629 if (!field.value.type.struct_def->fixed) {
1630 code_ += "{{PRE}}verifier.VerifyVectorOfTables({{NAME}}())\\";
1634 case BASE_TYPE_UNION: {
1635 code_.SetValue("ENUM_NAME", field.value.type.enum_def->name);
1637 "{{PRE}}Verify{{ENUM_NAME}}Vector(verifier, {{NAME}}(), "
1638 "{{NAME}}_type())\\";
1649 // Generate CompareWithValue method for a key field.
1650 void GenKeyFieldMethods(const FieldDef &field) {
1651 FLATBUFFERS_ASSERT(field.key);
1652 const bool is_string = (field.value.type.base_type == BASE_TYPE_STRING);
1654 code_ += " bool KeyCompareLessThan(const {{STRUCT_NAME}} *o) const {";
1656 // use operator< of flatbuffers::String
1657 code_ += " return *{{FIELD_NAME}}() < *o->{{FIELD_NAME}}();";
1659 code_ += " return {{FIELD_NAME}}() < o->{{FIELD_NAME}}();";
1664 code_ += " int KeyCompareWithValue(const char *val) const {";
1665 code_ += " return strcmp({{FIELD_NAME}}()->c_str(), val);";
1668 FLATBUFFERS_ASSERT(IsScalar(field.value.type.base_type));
1669 auto type = GenTypeBasic(field.value.type, false);
1670 if (parser_.opts.scoped_enums && field.value.type.enum_def &&
1671 IsScalar(field.value.type.base_type)) {
1672 type = GenTypeGet(field.value.type, " ", "const ", " *", true);
1674 // Returns {field<val: -1, field==val: 0, field>val: +1}.
1675 code_.SetValue("KEY_TYPE", type);
1676 code_ += " int KeyCompareWithValue({{KEY_TYPE}} val) const {";
1678 " return static_cast<int>({{FIELD_NAME}}() > val) - "
1679 "static_cast<int>({{FIELD_NAME}}() < val);";
1684 // Generate an accessor struct, builder structs & function for a table.
1685 void GenTable(const StructDef &struct_def) {
1686 if (parser_.opts.generate_object_based_api) { GenNativeTable(struct_def); }
1688 // Generate an accessor struct, with methods of the form:
1689 // type name() const { return GetField<type>(offset, defaultval); }
1690 GenComment(struct_def.doc_comment);
1692 code_.SetValue("STRUCT_NAME", Name(struct_def));
1694 "struct {{STRUCT_NAME}} FLATBUFFERS_FINAL_CLASS"
1695 " : private flatbuffers::Table {";
1696 if (parser_.opts.generate_object_based_api) {
1697 code_ += " typedef {{NATIVE_NAME}} NativeTableType;";
1699 if (parser_.opts.mini_reflect != IDLOptions::kNone) {
1700 code_ += " static const flatbuffers::TypeTable *MiniReflectTypeTable() {";
1701 code_ += " return {{STRUCT_NAME}}TypeTable();";
1706 GenFullyQualifiedNameGetter(struct_def, Name(struct_def));
1708 // Generate field id constants.
1709 if (struct_def.fields.vec.size() > 0) {
1710 // We need to add a trailing comma to all elements except the last one as
1711 // older versions of gcc complain about this.
1712 code_.SetValue("SEP", "");
1713 code_ += " enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {";
1714 for (auto it = struct_def.fields.vec.begin();
1715 it != struct_def.fields.vec.end(); ++it) {
1716 const auto &field = **it;
1717 if (field.deprecated) {
1718 // Deprecated fields won't be accessible.
1722 code_.SetValue("OFFSET_NAME", GenFieldOffsetName(field));
1723 code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset));
1724 code_ += "{{SEP}} {{OFFSET_NAME}} = {{OFFSET_VALUE}}\\";
1725 code_.SetValue("SEP", ",\n");
1731 // Generate the accessors.
1732 for (auto it = struct_def.fields.vec.begin();
1733 it != struct_def.fields.vec.end(); ++it) {
1734 const auto &field = **it;
1735 if (field.deprecated) {
1736 // Deprecated fields won't be accessible.
1740 const bool is_struct = IsStruct(field.value.type);
1741 const bool is_scalar = IsScalar(field.value.type.base_type);
1742 code_.SetValue("FIELD_NAME", Name(field));
1744 // Call a different accessor for pointers, that indirects.
1745 std::string accessor = "";
1747 accessor = "GetField<";
1748 } else if (is_struct) {
1749 accessor = "GetStruct<";
1751 accessor = "GetPointer<";
1753 auto offset_str = GenFieldOffsetName(field);
1755 GenTypeGet(field.value.type, "", "const ", " *", false);
1757 auto call = accessor + offset_type + ">(" + offset_str;
1758 // Default value as second arg for non-pointer types.
1759 if (is_scalar) { call += ", " + GenDefaultConstant(field); }
1762 std::string afterptr = " *" + NullableExtension();
1763 GenComment(field.doc_comment, " ");
1764 code_.SetValue("FIELD_TYPE", GenTypeGet(field.value.type, " ", "const ",
1765 afterptr.c_str(), true));
1766 code_.SetValue("FIELD_VALUE", GenUnderlyingCast(field, true, call));
1767 code_.SetValue("NULLABLE_EXT", NullableExtension());
1769 code_ += " {{FIELD_TYPE}}{{FIELD_NAME}}() const {";
1770 code_ += " return {{FIELD_VALUE}};";
1773 if (field.value.type.base_type == BASE_TYPE_UNION) {
1774 auto u = field.value.type.enum_def;
1777 " template<typename T> "
1778 "const T *{{NULLABLE_EXT}}{{FIELD_NAME}}_as() const;";
1780 for (auto u_it = u->vals.vec.begin(); u_it != u->vals.vec.end();
1783 if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
1784 auto full_struct_name = GetUnionElement(ev, true, true);
1786 // @TODO: Mby make this decisions more universal? How?
1789 EscapeKeyword(field.name + UnionTypeFieldSuffix()));
1792 WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev)));
1793 code_.SetValue("U_FIELD_TYPE", "const " + full_struct_name + " *");
1794 code_.SetValue("U_FIELD_NAME", Name(field) + "_as_" + Name(ev));
1795 code_.SetValue("U_NULLABLE", NullableExtension());
1797 // `const Type *union_name_asType() const` accessor.
1798 code_ += " {{U_FIELD_TYPE}}{{U_NULLABLE}}{{U_FIELD_NAME}}() const {";
1800 " return {{U_GET_TYPE}}() == {{U_ELEMENT_TYPE}} ? "
1801 "static_cast<{{U_FIELD_TYPE}}>({{FIELD_NAME}}()) "
1807 if (parser_.opts.mutable_buffer) {
1809 const auto type = GenTypeWire(field.value.type, "", false);
1810 code_.SetValue("SET_FN", "SetField<" + type + ">");
1811 code_.SetValue("OFFSET_NAME", offset_str);
1812 code_.SetValue("FIELD_TYPE", GenTypeBasic(field.value.type, true));
1813 code_.SetValue("FIELD_VALUE",
1814 GenUnderlyingCast(field, false, "_" + Name(field)));
1815 code_.SetValue("DEFAULT_VALUE", GenDefaultConstant(field));
1818 " bool mutate_{{FIELD_NAME}}({{FIELD_TYPE}} "
1819 "_{{FIELD_NAME}}) {";
1821 " return {{SET_FN}}({{OFFSET_NAME}}, {{FIELD_VALUE}}, "
1822 "{{DEFAULT_VALUE}});";
1825 auto postptr = " *" + NullableExtension();
1827 GenTypeGet(field.value.type, " ", "", postptr.c_str(), true);
1828 auto underlying = accessor + type + ">(" + offset_str + ")";
1829 code_.SetValue("FIELD_TYPE", type);
1830 code_.SetValue("FIELD_VALUE",
1831 GenUnderlyingCast(field, true, underlying));
1833 code_ += " {{FIELD_TYPE}}mutable_{{FIELD_NAME}}() {";
1834 code_ += " return {{FIELD_VALUE}};";
1839 auto nested = field.attributes.Lookup("nested_flatbuffer");
1841 std::string qualified_name = nested->constant;
1842 auto nested_root = parser_.LookupStruct(nested->constant);
1843 if (nested_root == nullptr) {
1844 qualified_name = parser_.current_namespace_->GetFullyQualifiedName(
1846 nested_root = parser_.LookupStruct(qualified_name);
1848 FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser.
1850 code_.SetValue("CPP_NAME", TranslateNameSpace(qualified_name));
1852 code_ += " const {{CPP_NAME}} *{{FIELD_NAME}}_nested_root() const {";
1853 code_ += " return flatbuffers::GetRoot<{{CPP_NAME}}>({{FIELD_NAME}}()->Data());";
1857 if (field.flexbuffer) {
1859 " flexbuffers::Reference {{FIELD_NAME}}_flexbuffer_root()"
1861 // Both Data() and size() are const-methods, therefore call order doesn't matter.
1863 " return flexbuffers::GetRoot({{FIELD_NAME}}()->Data(), "
1864 "{{FIELD_NAME}}()->size());";
1868 // Generate a comparison function for this field if it is a key.
1870 GenKeyFieldMethods(field);
1874 // Generate a verifier function that can check a buffer from an untrusted
1875 // source will never cause reads outside the buffer.
1876 code_ += " bool Verify(flatbuffers::Verifier &verifier) const {";
1877 code_ += " return VerifyTableStart(verifier)\\";
1878 for (auto it = struct_def.fields.vec.begin();
1879 it != struct_def.fields.vec.end(); ++it) {
1880 const auto &field = **it;
1881 if (field.deprecated) { continue; }
1882 GenVerifyCall(field, " &&\n ");
1885 code_ += " &&\n verifier.EndTable();";
1888 if (parser_.opts.generate_object_based_api) {
1889 // Generate the UnPack() pre declaration.
1891 " " + TableUnPackSignature(struct_def, true, parser_.opts) + ";";
1893 " " + TableUnPackToSignature(struct_def, true, parser_.opts) + ";";
1894 code_ += " " + TablePackSignature(struct_def, true, parser_.opts) + ";";
1897 code_ += "};"; // End of table.
1900 // Explicit specializations for union accessors
1901 for (auto it = struct_def.fields.vec.begin();
1902 it != struct_def.fields.vec.end(); ++it) {
1903 const auto &field = **it;
1904 if (field.deprecated || field.value.type.base_type != BASE_TYPE_UNION) {
1908 auto u = field.value.type.enum_def;
1909 if (u->uses_type_aliases) continue;
1911 code_.SetValue("FIELD_NAME", Name(field));
1913 for (auto u_it = u->vals.vec.begin(); u_it != u->vals.vec.end(); ++u_it) {
1915 if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
1917 auto full_struct_name = GetUnionElement(ev, true, true);
1921 WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev)));
1922 code_.SetValue("U_FIELD_TYPE", "const " + full_struct_name + " *");
1923 code_.SetValue("U_ELEMENT_NAME", full_struct_name);
1924 code_.SetValue("U_FIELD_NAME", Name(field) + "_as_" + Name(ev));
1926 // `template<> const T *union_name_as<T>() const` accessor.
1929 "inline {{U_FIELD_TYPE}}{{STRUCT_NAME}}::{{FIELD_NAME}}_as"
1930 "<{{U_ELEMENT_NAME}}>() const {";
1931 code_ += " return {{U_FIELD_NAME}}();";
1937 GenBuilders(struct_def);
1939 if (parser_.opts.generate_object_based_api) {
1940 // Generate a pre-declaration for a CreateX method that works with an
1941 // unpacked C++ object.
1942 code_ += TableCreateSignature(struct_def, true, parser_.opts) + ";";
1947 void GenBuilders(const StructDef &struct_def) {
1948 code_.SetValue("STRUCT_NAME", Name(struct_def));
1950 // Generate a builder struct:
1951 code_ += "struct {{STRUCT_NAME}}Builder {";
1952 code_ += " flatbuffers::FlatBufferBuilder &fbb_;";
1953 code_ += " flatbuffers::uoffset_t start_;";
1955 bool has_string_or_vector_fields = false;
1956 for (auto it = struct_def.fields.vec.begin();
1957 it != struct_def.fields.vec.end(); ++it) {
1958 const auto &field = **it;
1959 if (!field.deprecated) {
1960 const bool is_scalar = IsScalar(field.value.type.base_type);
1961 const bool is_string = field.value.type.base_type == BASE_TYPE_STRING;
1962 const bool is_vector = field.value.type.base_type == BASE_TYPE_VECTOR;
1963 if (is_string || is_vector) { has_string_or_vector_fields = true; }
1965 std::string offset = GenFieldOffsetName(field);
1966 std::string name = GenUnderlyingCast(field, false, Name(field));
1967 std::string value = is_scalar ? GenDefaultConstant(field) : "";
1969 // Generate accessor functions of the form:
1970 // void add_name(type name) {
1971 // fbb_.AddElement<type>(offset, name, default);
1973 code_.SetValue("FIELD_NAME", Name(field));
1974 code_.SetValue("FIELD_TYPE", GenTypeWire(field.value.type, " ", true));
1975 code_.SetValue("ADD_OFFSET", Name(struct_def) + "::" + offset);
1976 code_.SetValue("ADD_NAME", name);
1977 code_.SetValue("ADD_VALUE", value);
1979 const auto type = GenTypeWire(field.value.type, "", false);
1980 code_.SetValue("ADD_FN", "AddElement<" + type + ">");
1981 } else if (IsStruct(field.value.type)) {
1982 code_.SetValue("ADD_FN", "AddStruct");
1984 code_.SetValue("ADD_FN", "AddOffset");
1987 code_ += " void add_{{FIELD_NAME}}({{FIELD_TYPE}}{{FIELD_NAME}}) {";
1988 code_ += " fbb_.{{ADD_FN}}(\\";
1990 code_ += "{{ADD_OFFSET}}, {{ADD_NAME}}, {{ADD_VALUE}});";
1992 code_ += "{{ADD_OFFSET}}, {{ADD_NAME}});";
1998 // Builder constructor
2000 " explicit {{STRUCT_NAME}}Builder(flatbuffers::FlatBufferBuilder "
2002 code_ += " : fbb_(_fbb) {";
2003 code_ += " start_ = fbb_.StartTable();";
2006 // Assignment operator;
2008 " {{STRUCT_NAME}}Builder &operator="
2009 "(const {{STRUCT_NAME}}Builder &);";
2011 // Finish() function.
2012 code_ += " flatbuffers::Offset<{{STRUCT_NAME}}> Finish() {";
2013 code_ += " const auto end = fbb_.EndTable(start_);";
2014 code_ += " auto o = flatbuffers::Offset<{{STRUCT_NAME}}>(end);";
2016 for (auto it = struct_def.fields.vec.begin();
2017 it != struct_def.fields.vec.end(); ++it) {
2018 const auto &field = **it;
2019 if (!field.deprecated && field.required) {
2020 code_.SetValue("FIELD_NAME", Name(field));
2021 code_.SetValue("OFFSET_NAME", GenFieldOffsetName(field));
2022 code_ += " fbb_.Required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}});";
2025 code_ += " return o;";
2030 // Generate a convenient CreateX function that uses the above builder
2031 // to create a table in one go.
2033 "inline flatbuffers::Offset<{{STRUCT_NAME}}> "
2034 "Create{{STRUCT_NAME}}(";
2035 code_ += " flatbuffers::FlatBufferBuilder &_fbb\\";
2036 for (auto it = struct_def.fields.vec.begin();
2037 it != struct_def.fields.vec.end(); ++it) {
2038 const auto &field = **it;
2039 if (!field.deprecated) { GenParam(field, false, ",\n "); }
2043 code_ += " {{STRUCT_NAME}}Builder builder_(_fbb);";
2044 for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
2046 for (auto it = struct_def.fields.vec.rbegin();
2047 it != struct_def.fields.vec.rend(); ++it) {
2048 const auto &field = **it;
2049 if (!field.deprecated && (!struct_def.sortbysize ||
2050 size == SizeOf(field.value.type.base_type))) {
2051 code_.SetValue("FIELD_NAME", Name(field));
2052 code_ += " builder_.add_{{FIELD_NAME}}({{FIELD_NAME}});";
2056 code_ += " return builder_.Finish();";
2060 // Generate a CreateXDirect function with vector types as parameters
2061 if (has_string_or_vector_fields) {
2063 "inline flatbuffers::Offset<{{STRUCT_NAME}}> "
2064 "Create{{STRUCT_NAME}}Direct(";
2065 code_ += " flatbuffers::FlatBufferBuilder &_fbb\\";
2066 for (auto it = struct_def.fields.vec.begin();
2067 it != struct_def.fields.vec.end(); ++it) {
2068 const auto &field = **it;
2069 if (!field.deprecated) { GenParam(field, true, ",\n "); }
2072 // Need to call "Create" with the struct namespace.
2073 const auto qualified_create_name =
2074 struct_def.defined_namespace->GetFullyQualifiedName("Create");
2075 code_.SetValue("CREATE_NAME", TranslateNameSpace(qualified_create_name));
2078 code_ += " return {{CREATE_NAME}}{{STRUCT_NAME}}(";
2080 for (auto it = struct_def.fields.vec.begin();
2081 it != struct_def.fields.vec.end(); ++it) {
2082 const auto &field = **it;
2083 if (!field.deprecated) {
2084 code_.SetValue("FIELD_NAME", Name(field));
2086 if (field.value.type.base_type == BASE_TYPE_STRING) {
2088 ",\n {{FIELD_NAME}} ? "
2089 "_fbb.CreateString({{FIELD_NAME}}) : 0\\";
2090 } else if (field.value.type.base_type == BASE_TYPE_VECTOR) {
2091 code_ += ",\n {{FIELD_NAME}} ? \\";
2092 const auto vtype = field.value.type.VectorType();
2093 if (IsStruct(vtype)) {
2094 const auto type = WrapInNameSpace(*vtype.struct_def);
2095 code_ += "_fbb.CreateVectorOfStructs<" + type + ">\\";
2097 const auto type = GenTypeWire(vtype, "", false);
2098 code_ += "_fbb.CreateVector<" + type + ">\\";
2100 code_ += "(*{{FIELD_NAME}}) : 0\\";
2102 code_ += ",\n {{FIELD_NAME}}\\";
2112 std::string GenUnionUnpackVal(const FieldDef &afield,
2113 const char *vec_elem_access,
2114 const char *vec_type_access) {
2115 return afield.value.type.enum_def->name +
2116 "Union::UnPack(" + "_e" + vec_elem_access + ", " +
2117 EscapeKeyword(afield.name + UnionTypeFieldSuffix()) +
2118 "()" + vec_type_access + ", _resolver)";
2121 std::string GenUnpackVal(const Type &type, const std::string &val,
2122 bool invector, const FieldDef &afield) {
2123 switch (type.base_type) {
2124 case BASE_TYPE_STRING: {
2125 return val + "->str()";
2127 case BASE_TYPE_STRUCT: {
2128 const auto name = WrapInNameSpace(*type.struct_def);
2129 if (IsStruct(type)) {
2130 auto native_type = type.struct_def->attributes.Lookup("native_type");
2132 return "flatbuffers::UnPack(*" + val + ")";
2133 } else if (invector || afield.native_inline) {
2136 const auto ptype = GenTypeNativePtr(name, &afield, true);
2137 return ptype + "(new " + name + "(*" + val + "))";
2140 const auto ptype = GenTypeNativePtr(
2141 NativeName(name, type.struct_def, parser_.opts), &afield, true);
2142 return ptype + "(" + val + "->UnPack(_resolver))";
2145 case BASE_TYPE_UNION: {
2146 return GenUnionUnpackVal(
2147 afield, invector ? "->Get(_i)" : "",
2148 invector ? ("->GetEnum<" + type.enum_def->name + ">(_i)").c_str()
2158 std::string GenUnpackFieldStatement(const FieldDef &field,
2159 const FieldDef *union_field) {
2161 switch (field.value.type.base_type) {
2162 case BASE_TYPE_VECTOR: {
2163 auto cpp_type = field.attributes.Lookup("cpp_type");
2164 std::string indexing;
2165 if (field.value.type.enum_def) {
2166 indexing += "static_cast<" +
2167 WrapInNameSpace(*field.value.type.enum_def) + ">(";
2169 indexing += "_e->Get(_i)";
2170 if (field.value.type.enum_def) { indexing += ")"; }
2171 if (field.value.type.element == BASE_TYPE_BOOL) { indexing += " != 0"; }
2173 // Generate code that pushes data from _e to _o in the form:
2174 // for (uoffset_t i = 0; i < _e->size(); ++i) {
2175 // _o->field.push_back(_e->Get(_i));
2177 auto name = Name(field);
2178 if (field.value.type.element == BASE_TYPE_UTYPE) {
2179 name = StripUnionType(Name(field));
2182 field.value.type.element == BASE_TYPE_UTYPE
2184 : (field.value.type.element == BASE_TYPE_UNION ? ".value" : "");
2185 code += "{ _o->" + name + ".resize(_e->size()); ";
2186 code += "for (flatbuffers::uoffset_t _i = 0;";
2187 code += " _i < _e->size(); _i++) { ";
2189 // Generate code that resolves the cpp pointer type, of the form:
2191 // (*resolver)(&_o->field, (hash_value_t)(_e));
2193 // _o->field = nullptr;
2194 code += "//vector resolver, " + PtrType(&field) + "\n";
2195 code += "if (_resolver) ";
2196 code += "(*_resolver)";
2197 code += "(reinterpret_cast<void **>(&_o->" + name + "[_i]" + access + "), ";
2198 code += "static_cast<flatbuffers::hash_value_t>(" + indexing + "));";
2199 if (PtrType(&field) == "naked") {
2201 code += "_o->" + name + "[_i]" + access + " = nullptr";
2204 //code += "_o->" + name + "[_i]" + access + " = " + GenTypeNativePtr(cpp_type->constant, &field, true) + "();";
2205 code += "/* else do nothing */";
2208 code += "_o->" + name + "[_i]" + access + " = ";
2210 GenUnpackVal(field.value.type.VectorType(), indexing, true, field);
2215 case BASE_TYPE_UTYPE: {
2216 FLATBUFFERS_ASSERT(union_field->value.type.base_type == BASE_TYPE_UNION);
2217 // Generate code that sets the union type, of the form:
2218 // _o->field.type = _e;
2219 code += "_o->" + union_field->name + ".type = _e;";
2222 case BASE_TYPE_UNION: {
2223 // Generate code that sets the union value, of the form:
2224 // _o->field.value = Union::Unpack(_e, field_type(), resolver);
2225 code += "_o->" + Name(field) + ".value = ";
2226 code += GenUnionUnpackVal(field, "", "");
2231 auto cpp_type = field.attributes.Lookup("cpp_type");
2233 // Generate code that resolves the cpp pointer type, of the form:
2235 // (*resolver)(&_o->field, (hash_value_t)(_e));
2237 // _o->field = nullptr;
2238 code += "//scalar resolver, " + PtrType(&field) + " \n";
2239 code += "if (_resolver) ";
2240 code += "(*_resolver)";
2241 code += "(reinterpret_cast<void **>(&_o->" + Name(field) + "), ";
2242 code += "static_cast<flatbuffers::hash_value_t>(_e));";
2243 if (PtrType(&field) == "naked") {
2245 code += "_o->" + Name(field) + " = nullptr;";
2248 //code += "_o->" + Name(field) + " = " + GenTypeNativePtr(cpp_type->constant, &field, true) + "();";
2249 code += "/* else do nothing */;";
2252 // Generate code for assigning the value, of the form:
2253 // _o->field = value;
2254 code += "_o->" + Name(field) + " = ";
2255 code += GenUnpackVal(field.value.type, "_e", false, field) + ";";
2263 std::string GenCreateParam(const FieldDef &field) {
2264 const IDLOptions &opts = parser_.opts;
2266 std::string value = "_o->";
2267 if (field.value.type.base_type == BASE_TYPE_UTYPE) {
2268 value += StripUnionType(Name(field));
2271 value += Name(field);
2273 if (field.value.type.base_type != BASE_TYPE_VECTOR && field.attributes.Lookup("cpp_type")) {
2274 auto type = GenTypeBasic(field.value.type, false);
2278 type + ">((*_rehasher)(" + value + GenPtrGet(field) + ")) : 0";
2283 switch (field.value.type.base_type) {
2284 // String fields are of the form:
2285 // _fbb.CreateString(_o->field)
2286 case BASE_TYPE_STRING: {
2287 code += "_fbb.CreateString(" + value + ")";
2289 // For optional fields, check to see if there actually is any data
2290 // in _o->field before attempting to access it. If there isn't,
2291 // depending on set_empty_to_null either set it to 0 or an empty string.
2292 if (!field.required) {
2294 opts.set_empty_to_null ? "0" : "_fbb.CreateSharedString(\"\")";
2295 code = value + ".empty() ? " + empty_value + " : " + code;
2299 // Vector fields come in several flavours, of the forms:
2300 // _fbb.CreateVector(_o->field);
2301 // _fbb.CreateVector((const utype*)_o->field.data(), _o->field.size());
2302 // _fbb.CreateVectorOfStrings(_o->field)
2303 // _fbb.CreateVectorOfStructs(_o->field)
2304 // _fbb.CreateVector<Offset<T>>(_o->field.size() [&](size_t i) {
2305 // return CreateT(_fbb, _o->Get(i), rehasher);
2307 case BASE_TYPE_VECTOR: {
2308 auto vector_type = field.value.type.VectorType();
2309 switch (vector_type.base_type) {
2310 case BASE_TYPE_STRING: {
2311 code += "_fbb.CreateVectorOfStrings(" + value + ")";
2314 case BASE_TYPE_STRUCT: {
2315 if (IsStruct(vector_type)) {
2317 field.value.type.struct_def->attributes.Lookup("native_type");
2319 code += "_fbb.CreateVectorOfNativeStructs<";
2320 code += WrapInNameSpace(*vector_type.struct_def) + ">";
2322 code += "_fbb.CreateVectorOfStructs";
2324 code += "(" + value + ")";
2326 code += "_fbb.CreateVector<flatbuffers::Offset<";
2327 code += WrapInNameSpace(*vector_type.struct_def) + ">> ";
2328 code += "(" + value + ".size(), ";
2329 code += "[](size_t i, _VectorArgs *__va) { ";
2330 code += "return Create" + vector_type.struct_def->name;
2331 code += "(*__va->__fbb, __va->_" + value + "[i]" +
2332 GenPtrGet(field) + ", ";
2333 code += "__va->__rehasher); }, &_va )";
2337 case BASE_TYPE_BOOL: {
2338 code += "_fbb.CreateVector(" + value + ")";
2341 case BASE_TYPE_UNION: {
2343 "_fbb.CreateVector<flatbuffers::"
2346 ".size(), [](size_t i, _VectorArgs *__va) { "
2348 value + "[i].Pack(*__va->__fbb, __va->__rehasher); }, &_va)";
2351 case BASE_TYPE_UTYPE: {
2352 value = StripUnionType(value);
2353 code += "_fbb.CreateVector<uint8_t>(" + value +
2354 ".size(), [](size_t i, _VectorArgs *__va) { "
2355 "return static_cast<uint8_t>(__va->_" +
2356 value + "[i].type); }, &_va)";
2360 if (field.value.type.enum_def) {
2361 // For enumerations, we need to get access to the array data for
2362 // the underlying storage type (eg. uint8_t).
2363 const auto basetype = GenTypeBasic(
2364 field.value.type.enum_def->underlying_type, false);
2365 code += "_fbb.CreateVector((const " + basetype + "*)" + value +
2366 ".data(), " + value + ".size())";
2367 } else if (field.attributes.Lookup("cpp_type")) {
2368 auto type = GenTypeBasic(vector_type, false);
2369 code += "_fbb.CreateVector<" + type + ">(" + value + ".size(), ";
2370 code += "[](size_t i, _VectorArgs *__va) { ";
2371 code += "return __va->__rehasher ? ";
2372 code += "static_cast<" + type + ">((*__va->__rehasher)";
2373 code += "(__va->_" + value + "[i]" + GenPtrGet(field) + ")) : 0";
2374 code += "; }, &_va )";
2376 code += "_fbb.CreateVector(" + value + ")";
2382 // If set_empty_to_null option is enabled, for optional fields, check to
2383 // see if there actually is any data in _o->field before attempting to
2385 if (opts.set_empty_to_null && !field.required) {
2386 code = value + ".size() ? " + code + " : 0";
2390 case BASE_TYPE_UNION: {
2391 // _o->field.Pack(_fbb);
2392 code += value + ".Pack(_fbb)";
2395 case BASE_TYPE_STRUCT: {
2396 if (IsStruct(field.value.type)) {
2398 field.value.type.struct_def->attributes.Lookup("native_type");
2400 code += "flatbuffers::Pack(" + value + ")";
2401 } else if (field.native_inline) {
2402 code += "&" + value;
2404 code += value + " ? " + value + GenPtrGet(field) + " : 0";
2407 // _o->field ? CreateT(_fbb, _o->field.get(), _rehasher);
2408 const auto type = field.value.type.struct_def->name;
2409 code += value + " ? Create" + type;
2410 code += "(_fbb, " + value + GenPtrGet(field) + ", _rehasher)";
2423 // Generate code for tables that needs to come after the regular definition.
2424 void GenTablePost(const StructDef &struct_def) {
2425 code_.SetValue("STRUCT_NAME", Name(struct_def));
2426 code_.SetValue("NATIVE_NAME",
2427 NativeName(Name(struct_def), &struct_def, parser_.opts));
2429 if (parser_.opts.generate_object_based_api) {
2430 // Generate the X::UnPack() method.
2431 code_ += "inline " +
2432 TableUnPackSignature(struct_def, false, parser_.opts) + " {";
2433 code_ += " auto _o = new {{NATIVE_NAME}}();";
2434 code_ += " UnPackTo(_o, _resolver);";
2435 code_ += " return _o;";
2439 code_ += "inline " +
2440 TableUnPackToSignature(struct_def, false, parser_.opts) + " {";
2441 code_ += " (void)_o;";
2442 code_ += " (void)_resolver;";
2444 for (auto it = struct_def.fields.vec.begin();
2445 it != struct_def.fields.vec.end(); ++it) {
2446 const auto &field = **it;
2447 if (field.deprecated) { continue; }
2449 // Assign a value from |this| to |_o|. Values from |this| are stored
2450 // in a variable |_e| by calling this->field_type(). The value is then
2451 // assigned to |_o| using the GenUnpackFieldStatement.
2452 const bool is_union = field.value.type.base_type == BASE_TYPE_UTYPE;
2453 const auto statement =
2454 GenUnpackFieldStatement(field, is_union ? *(it + 1) : nullptr);
2456 code_.SetValue("FIELD_NAME", Name(field));
2457 auto prefix = " { auto _e = {{FIELD_NAME}}(); ";
2458 auto check = IsScalar(field.value.type.base_type) ? "" : "if (_e) ";
2459 auto postfix = " };";
2460 code_ += std::string(prefix) + check + statement + postfix;
2465 // Generate the X::Pack member function that simply calls the global
2466 // CreateX function.
2467 code_ += "inline " + TablePackSignature(struct_def, false, parser_.opts) +
2469 code_ += " return Create{{STRUCT_NAME}}(_fbb, _o, _rehasher);";
2473 // Generate a CreateX method that works with an unpacked C++ object.
2474 code_ += "inline " +
2475 TableCreateSignature(struct_def, false, parser_.opts) + " {";
2476 code_ += " (void)_rehasher;";
2477 code_ += " (void)_o;";
2480 " struct _VectorArgs "
2481 "{ flatbuffers::FlatBufferBuilder *__fbb; "
2483 NativeName(Name(struct_def), &struct_def, parser_.opts) +
2485 "const flatbuffers::rehasher_function_t *__rehasher; } _va = { "
2486 "&_fbb, _o, _rehasher}; (void)_va;";
2488 for (auto it = struct_def.fields.vec.begin();
2489 it != struct_def.fields.vec.end(); ++it) {
2491 if (field.deprecated) { continue; }
2492 code_ += " auto _" + Name(field) + " = " + GenCreateParam(field) + ";";
2494 // Need to call "Create" with the struct namespace.
2495 const auto qualified_create_name =
2496 struct_def.defined_namespace->GetFullyQualifiedName("Create");
2497 code_.SetValue("CREATE_NAME", TranslateNameSpace(qualified_create_name));
2499 code_ += " return {{CREATE_NAME}}{{STRUCT_NAME}}(";
2501 for (auto it = struct_def.fields.vec.begin();
2502 it != struct_def.fields.vec.end(); ++it) {
2504 if (field.deprecated) { continue; }
2506 bool pass_by_address = false;
2507 if (field.value.type.base_type == BASE_TYPE_STRUCT) {
2508 if (IsStruct(field.value.type)) {
2510 field.value.type.struct_def->attributes.Lookup("native_type");
2511 if (native_type) { pass_by_address = true; }
2515 // Call the CreateX function using values from |_o|.
2516 if (pass_by_address) {
2517 code_ += ",\n &_" + Name(field) + "\\";
2519 code_ += ",\n _" + Name(field) + "\\";
2528 static void GenPadding(
2529 const FieldDef &field, std::string *code_ptr, int *id,
2530 const std::function<void(int bits, std::string *code_ptr, int *id)> &f) {
2531 if (field.padding) {
2532 for (int i = 0; i < 4; i++) {
2533 if (static_cast<int>(field.padding) & (1 << i)) {
2534 f((1 << i) * 8, code_ptr, id);
2537 FLATBUFFERS_ASSERT(!(field.padding & ~0xF));
2541 static void PaddingDefinition(int bits, std::string *code_ptr, int *id) {
2542 *code_ptr += " int" + NumToString(bits) + "_t padding" +
2543 NumToString((*id)++) + "__;";
2546 static void PaddingInitializer(int bits, std::string *code_ptr, int *id) {
2548 *code_ptr += ",\n padding" + NumToString((*id)++) + "__(0)";
2551 static void PaddingNoop(int bits, std::string *code_ptr, int *id) {
2553 *code_ptr += " (void)padding" + NumToString((*id)++) + "__;";
2556 // Generate an accessor struct with constructor for a flatbuffers struct.
2557 void GenStruct(const StructDef &struct_def) {
2558 // Generate an accessor struct, with private variables of the form:
2560 // Generates manual padding and alignment.
2561 // Variables are private because they contain little endian data on all
2563 GenComment(struct_def.doc_comment);
2564 code_.SetValue("ALIGN", NumToString(struct_def.minalign));
2565 code_.SetValue("STRUCT_NAME", Name(struct_def));
2568 "FLATBUFFERS_MANUALLY_ALIGNED_STRUCT({{ALIGN}}) "
2569 "{{STRUCT_NAME}} FLATBUFFERS_FINAL_CLASS {";
2570 code_ += " private:";
2573 for (auto it = struct_def.fields.vec.begin();
2574 it != struct_def.fields.vec.end(); ++it) {
2575 const auto &field = **it;
2576 code_.SetValue("FIELD_TYPE",
2577 GenTypeGet(field.value.type, " ", "", " ", false));
2578 code_.SetValue("FIELD_NAME", Name(field));
2579 code_ += " {{FIELD_TYPE}}{{FIELD_NAME}}_;";
2581 if (field.padding) {
2582 std::string padding;
2583 GenPadding(field, &padding, &padding_id, PaddingDefinition);
2588 // Generate GetFullyQualifiedName
2590 code_ += " public:";
2591 GenFullyQualifiedNameGetter(struct_def, Name(struct_def));
2593 // Generate a default constructor.
2594 code_ += " {{STRUCT_NAME}}() {";
2595 code_ += " memset(this, 0, sizeof({{STRUCT_NAME}}));";
2598 // Generate a constructor that takes all fields as arguments.
2599 std::string arg_list;
2600 std::string init_list;
2602 for (auto it = struct_def.fields.vec.begin();
2603 it != struct_def.fields.vec.end(); ++it) {
2604 const auto &field = **it;
2605 const auto member_name = Name(field) + "_";
2606 const auto arg_name = "_" + Name(field);
2607 const auto arg_type =
2608 GenTypeGet(field.value.type, " ", "const ", " &", true);
2610 if (it != struct_def.fields.vec.begin()) {
2612 init_list += ",\n ";
2614 arg_list += arg_type;
2615 arg_list += arg_name;
2616 init_list += member_name;
2617 if (IsScalar(field.value.type.base_type)) {
2618 auto type = GenUnderlyingCast(field, false, arg_name);
2619 init_list += "(flatbuffers::EndianScalar(" + type + "))";
2621 init_list += "(" + arg_name + ")";
2623 if (field.padding) {
2624 GenPadding(field, &init_list, &padding_id, PaddingInitializer);
2628 if (!arg_list.empty()) {
2629 code_.SetValue("ARG_LIST", arg_list);
2630 code_.SetValue("INIT_LIST", init_list);
2631 code_ += " {{STRUCT_NAME}}({{ARG_LIST}})";
2632 code_ += " : {{INIT_LIST}} {";
2634 for (auto it = struct_def.fields.vec.begin();
2635 it != struct_def.fields.vec.end(); ++it) {
2636 const auto &field = **it;
2637 if (field.padding) {
2638 std::string padding;
2639 GenPadding(field, &padding, &padding_id, PaddingNoop);
2646 // Generate accessor methods of the form:
2647 // type name() const { return flatbuffers::EndianScalar(name_); }
2648 for (auto it = struct_def.fields.vec.begin();
2649 it != struct_def.fields.vec.end(); ++it) {
2650 const auto &field = **it;
2652 auto field_type = GenTypeGet(field.value.type, " ", "const ", " &", true);
2653 auto is_scalar = IsScalar(field.value.type.base_type);
2654 auto member = Name(field) + "_";
2656 is_scalar ? "flatbuffers::EndianScalar(" + member + ")" : member;
2658 code_.SetValue("FIELD_NAME", Name(field));
2659 code_.SetValue("FIELD_TYPE", field_type);
2660 code_.SetValue("FIELD_VALUE", GenUnderlyingCast(field, true, value));
2662 GenComment(field.doc_comment, " ");
2663 code_ += " {{FIELD_TYPE}}{{FIELD_NAME}}() const {";
2664 code_ += " return {{FIELD_VALUE}};";
2667 if (parser_.opts.mutable_buffer) {
2668 auto mut_field_type = GenTypeGet(field.value.type, " ", "", " &", true);
2669 code_.SetValue("FIELD_TYPE", mut_field_type);
2671 code_.SetValue("ARG", GenTypeBasic(field.value.type, true));
2672 code_.SetValue("FIELD_VALUE",
2673 GenUnderlyingCast(field, false, "_" + Name(field)));
2675 code_ += " void mutate_{{FIELD_NAME}}({{ARG}} _{{FIELD_NAME}}) {";
2677 " flatbuffers::WriteScalar(&{{FIELD_NAME}}_, "
2678 "{{FIELD_VALUE}});";
2681 code_ += " {{FIELD_TYPE}}mutable_{{FIELD_NAME}}() {";
2682 code_ += " return {{FIELD_NAME}}_;";
2687 // Generate a comparison function for this field if it is a key.
2689 GenKeyFieldMethods(field);
2692 code_.SetValue("NATIVE_NAME", Name(struct_def));
2693 GenOperatorNewDelete(struct_def);
2696 code_.SetValue("STRUCT_BYTE_SIZE", NumToString(struct_def.bytesize));
2697 code_ += "FLATBUFFERS_STRUCT_END({{STRUCT_NAME}}, {{STRUCT_BYTE_SIZE}});";
2698 if (parser_.opts.gen_compare) GenCompareOperator(struct_def, "()");
2702 // Set up the correct namespace. Only open a namespace if the existing one is
2703 // different (closing/opening only what is necessary).
2705 // The file must start and end with an empty (or null) namespace so that
2706 // namespaces are properly opened and closed.
2707 void SetNameSpace(const Namespace *ns) {
2708 if (cur_name_space_ == ns) { return; }
2710 // Compute the size of the longest common namespace prefix.
2711 // If cur_name_space is A::B::C::D and ns is A::B::E::F::G,
2712 // the common prefix is A::B:: and we have old_size = 4, new_size = 5
2713 // and common_prefix_size = 2
2714 size_t old_size = cur_name_space_ ? cur_name_space_->components.size() : 0;
2715 size_t new_size = ns ? ns->components.size() : 0;
2717 size_t common_prefix_size = 0;
2718 while (common_prefix_size < old_size && common_prefix_size < new_size &&
2719 ns->components[common_prefix_size] ==
2720 cur_name_space_->components[common_prefix_size]) {
2721 common_prefix_size++;
2724 // Close cur_name_space in reverse order to reach the common prefix.
2725 // In the previous example, D then C are closed.
2726 for (size_t j = old_size; j > common_prefix_size; --j) {
2727 code_ += "} // namespace " + cur_name_space_->components[j - 1];
2729 if (old_size != common_prefix_size) { code_ += ""; }
2731 // open namespace parts to reach the ns namespace
2732 // in the previous example, E, then F, then G are opened
2733 for (auto j = common_prefix_size; j != new_size; ++j) {
2734 code_ += "namespace " + ns->components[j] + " {";
2736 if (new_size != common_prefix_size) { code_ += ""; }
2738 cur_name_space_ = ns;
2744 bool GenerateCPP(const Parser &parser, const std::string &path,
2745 const std::string &file_name) {
2746 cpp::CppGenerator generator(parser, path, file_name);
2747 return generator.generate();
2750 std::string CPPMakeRule(const Parser &parser, const std::string &path,
2751 const std::string &file_name) {
2752 const auto filebase =
2753 flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
2754 const auto included_files = parser.GetIncludedFilesRecursive(file_name);
2755 std::string make_rule = GeneratedFileName(path, filebase) + ": ";
2756 for (auto it = included_files.begin(); it != included_files.end(); ++it) {
2757 make_rule += " " + *it;
2762 } // namespace flatbuffers