make flatbuffers::IsFieldPresent safer (#4988)
[platform/upstream/flatbuffers.git] / src / idl_gen_cpp.cpp
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 // independent from idl_parser, since this code is not needed for most clients
18
19 #include "flatbuffers/code_generators.h"
20 #include "flatbuffers/flatbuffers.h"
21 #include "flatbuffers/idl.h"
22 #include "flatbuffers/util.h"
23
24 #include <unordered_set>
25
26 namespace flatbuffers {
27
28 // Pedantic warning free version of toupper().
29 inline char ToUpper(char c) { return static_cast<char>(::toupper(c)); }
30
31 static std::string GeneratedFileName(const std::string &path,
32                                      const std::string &file_name) {
33   return path + file_name + "_generated.h";
34 }
35
36 namespace cpp {
37 class CppGenerator : public BaseGenerator {
38  public:
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[] = {
44                                "alignas",
45                                "alignof",
46                                "and",
47                                "and_eq",
48                                "asm",
49                                "atomic_cancel",
50                                "atomic_commit",
51                                "atomic_noexcept",
52                                "auto",
53                                "bitand",
54                                "bitor",
55                                "bool",
56                                "break",
57                                "case",
58                                "catch",
59                                "char",
60                                "char16_t",
61                                "char32_t",
62                                "class",
63                                "compl",
64                                "concept",
65                                "const",
66                                "constexpr",
67                                "const_cast",
68                                "continue",
69                                "co_await",
70                                "co_return",
71                                "co_yield",
72                                "decltype",
73                                "default",
74                                "delete",
75                                "do",
76                                "double",
77                                "dynamic_cast",
78                                "else",
79                                "enum",
80                                "explicit",
81                                "export",
82                                "extern",
83                                "false",
84                                "float",
85                                "for",
86                                "friend",
87                                "goto",
88                                "if",
89                                "import",
90                                "inline",
91                                "int",
92                                "long",
93                                "module",
94                                "mutable",
95                                "namespace",
96                                "new",
97                                "noexcept",
98                                "not",
99                                "not_eq",
100                                "nullptr",
101                                "operator",
102                                "or",
103                                "or_eq",
104                                "private",
105                                "protected",
106                                "public",
107                                "register",
108                                "reinterpret_cast",
109                                "requires",
110                                "return",
111                                "short",
112                                "signed",
113                                "sizeof",
114                                "static",
115                                "static_assert",
116                                "static_cast",
117                                "struct",
118                                "switch",
119                                "synchronized",
120                                "template",
121                                "this",
122                                "thread_local",
123                                "throw",
124                                "true",
125                                "try",
126                                "typedef",
127                                "typeid",
128                                "typename",
129                                "union",
130                                "unsigned",
131                                "using",
132                                "virtual",
133                                "void",
134                                "volatile",
135                                "wchar_t",
136                                "while",
137                                "xor",
138                                "xor_eq",
139                                nullptr };
140     for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
141   }
142
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.
147     struct IsAlnum {
148       bool operator()(char c) const { return !is_alnum(c); }
149     };
150     guard.erase(std::remove_if(guard.begin(), guard.end(), IsAlnum()),
151                 guard.end());
152     guard = "FLATBUFFERS_GENERATED_" + guard;
153     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) {
158       guard += *it + "_";
159     }
160     guard += "H_";
161     std::transform(guard.begin(), guard.end(), guard.begin(), ToUpper);
162     return guard;
163   }
164
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 + "\"";
170       num_includes++;
171     }
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);
177
178       code_ += "#include \"" + parser_.opts.include_prefix +
179                (parser_.opts.keep_include_path ? noext : basename) +
180                "_generated.h\"";
181       num_includes++;
182     }
183     if (num_includes) code_ += "";
184   }
185
186   std::string EscapeKeyword(const std::string &name) const {
187     return keywords_.find(name) == keywords_.end() ? name : name + "_";
188   }
189
190   std::string Name(const Definition &def) const {
191     return EscapeKeyword(def.name);
192   }
193
194   std::string Name(const EnumVal &ev) const { return EscapeKeyword(ev.name); }
195
196   // Iterate through all definitions we haven't generate code for (enums,
197   // structs, and tables) and output them to a single file.
198   bool generate() {
199     code_.Clear();
200     code_ += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
201
202     const auto include_guard = GenIncludeGuard();
203     code_ += "#ifndef " + include_guard;
204     code_ += "#define " + include_guard;
205     code_ += "";
206
207     if (parser_.opts.gen_nullable) {
208       code_ += "#pragma clang system_header\n\n";
209     }
210
211     code_ += "#include \"flatbuffers/flatbuffers.h\"";
212     if (parser_.uses_flexbuffers_) {
213       code_ += "#include \"flatbuffers/flexbuffers.h\"";
214     }
215     code_ += "";
216
217     if (parser_.opts.include_dependence_headers) { GenIncludeDependencies(); }
218
219     FLATBUFFERS_ASSERT(!cur_name_space_);
220
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 + ";";
233           }
234         }
235         code_ += "";
236       }
237     }
238
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);";
248         }
249       }
250       code_ += "";
251     }
252
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);
262         }
263       }
264     }
265
266     // Generate code for all the enum declarations.
267     for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
268          ++it) {
269       const auto &enum_def = **it;
270       if (!enum_def.generated) {
271         SetNameSpace(enum_def.defined_namespace);
272         GenEnum(enum_def);
273       }
274     }
275
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);
283       }
284     }
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);
291       }
292     }
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);
299       }
300     }
301
302     // Generate code for union verifiers.
303     for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
304          ++it) {
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);
309       }
310     }
311
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();
316            ++it) {
317         const auto &enum_def = **it;
318         if (!enum_def.generated) {
319           SetNameSpace(enum_def.defined_namespace);
320           GenMiniReflect(nullptr, &enum_def);
321         }
322       }
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);
330         }
331       }
332     }
333
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);
341
342       code_.SetValue("STRUCT_NAME", name);
343       code_.SetValue("CPP_NAME", cpp_name);
344       code_.SetValue("NULLABLE_EXT", NullableExtension());
345
346       // The root datatype accessor:
347       code_ += "inline \\";
348       code_ +=
349           "const {{CPP_NAME}} *{{NULLABLE_EXT}}Get{{STRUCT_NAME}}(const void "
350           "*buf) {";
351       code_ += "  return flatbuffers::GetRoot<{{CPP_NAME}}>(buf);";
352       code_ += "}";
353       code_ += "";
354
355       code_ += "inline \\";
356       code_ +=
357           "const {{CPP_NAME}} *{{NULLABLE_EXT}}GetSizePrefixed{{STRUCT_NAME}}(const void "
358           "*buf) {";
359       code_ += "  return flatbuffers::GetSizePrefixedRoot<{{CPP_NAME}}>(buf);";
360       code_ += "}";
361       code_ += "";
362
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);";
367         code_ += "}";
368         code_ += "";
369       }
370
371       if (parser_.file_identifier_.length()) {
372         // Return the identifier
373         code_ += "inline const char *{{STRUCT_NAME}}Identifier() {";
374         code_ += "  return \"" + parser_.file_identifier_ + "\";";
375         code_ += "}";
376         code_ += "";
377
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());";
383         code_ += "}";
384         code_ += "";
385       }
386
387       // The root verifier.
388       if (parser_.file_identifier_.length()) {
389         code_.SetValue("ID", name + "Identifier()");
390       } else {
391         code_.SetValue("ID", "nullptr");
392       }
393
394       code_ += "inline bool Verify{{STRUCT_NAME}}Buffer(";
395       code_ += "    flatbuffers::Verifier &verifier) {";
396       code_ += "  return verifier.VerifyBuffer<{{CPP_NAME}}>({{ID}});";
397       code_ += "}";
398       code_ += "";
399
400       code_ += "inline bool VerifySizePrefixed{{STRUCT_NAME}}Buffer(";
401       code_ += "    flatbuffers::Verifier &verifier) {";
402       code_ += "  return verifier.VerifySizePrefixedBuffer<{{CPP_NAME}}>({{ID}});";
403       code_ += "}";
404       code_ += "";
405
406       if (parser_.file_extension_.length()) {
407         // Return the extension
408         code_ += "inline const char *{{STRUCT_NAME}}Extension() {";
409         code_ += "  return \"" + parser_.file_extension_ + "\";";
410         code_ += "}";
411         code_ += "";
412       }
413
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());";
420       else
421         code_ += "  fbb.Finish(root);";
422       code_ += "}";
423       code_ += "";
424
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());";
430       else
431         code_ += "  fbb.FinishSizePrefixed(root);";
432       code_ += "}";
433       code_ += "";
434
435       if (parser_.opts.generate_object_based_api) {
436         // A convenient root unpack function.
437         auto native_name =
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));
443
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));";
449         code_ += "}";
450         code_ += "";
451       }
452     }
453
454     if (cur_name_space_) SetNameSpace(nullptr);
455
456     // Close the include guard.
457     code_ += "#endif  // " + include_guard;
458
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);
462   }
463
464  private:
465   CodeWriter code_;
466
467   std::unordered_set<std::string> keywords_;
468
469   // This tracks the current namespace so we can insert namespace declarations.
470   const Namespace *cur_name_space_;
471
472   const Namespace *CurrentNameSpace() const { return cur_name_space_; }
473
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)) !=
480            std::string::npos) {
481       cpp_qualified_name.replace(start_pos, 1, "::");
482     }
483     return cpp_qualified_name;
484   }
485
486   void GenComment(const std::vector<std::string> &dc, const char *prefix = "") {
487     std::string text;
488     ::flatbuffers::GenComment(dc, &text, nullptr, prefix);
489     code_ += text + "\\";
490   }
491
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[] = {
495     // clang-format off
496     #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
497                            RTYPE) \
498             #CTYPE,
499         FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
500     #undef FLATBUFFERS_TD
501       // clang-format on
502     };
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";
506     }
507     return ctypename[type.base_type];
508   }
509
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";
516       }
517       case BASE_TYPE_VECTOR: {
518         const auto type_name = GenTypeWire(type.VectorType(), "", false);
519         return "flatbuffers::Vector<" + type_name + ">";
520       }
521       case BASE_TYPE_STRUCT: {
522         return WrapInNameSpace(*type.struct_def);
523       }
524       case BASE_TYPE_UNION:
525       // fall through
526       default: { return "void"; }
527     }
528   }
529
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) + " *";
538     } else {
539       return "flatbuffers::Offset<" + GenTypePointer(type) + ">" + postfix;
540     }
541   }
542
543   // Return a C++ type for any type (scalar/pointer) that reflects its
544   // serialized size.
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);
550     } else {
551       return "flatbuffers::uoffset_t";
552     }
553   }
554
555   std::string NullableExtension() {
556     return parser_.opts.gen_nullable ? " _Nullable " : "";
557   }
558
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
562                             : name;
563   }
564
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;
568   }
569
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"; }
574     return ret;
575   }
576
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) {
584       return "";
585     } else {
586       return type + " *";
587     }
588   }
589
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()";
596   }
597
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);
603       }
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 + ">>";
612         } else
613           return "std::vector<" + type_name + ">";
614       }
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) {
621             return type_name;
622           } else {
623             return GenTypeNativePtr(type_name, &field, false);
624           }
625         } else {
626           return GenTypeNativePtr(
627               NativeName(type_name, type.struct_def, parser_.opts), &field,
628               false);
629         }
630       }
631       case BASE_TYPE_UNION: {
632         return type.enum_def->name + "Union";
633       }
634       default: { return GenTypeBasic(type, true); }
635     }
636   }
637
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;
645     } else {
646       return beforeptr + GenTypePointer(type) + afterptr;
647     }
648   }
649
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);
653   }
654
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;
659   }
660
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);
668     } else {
669       return Name(enum_val);
670     }
671   }
672
673   std::string StripUnionType(const std::string &name) {
674     return name.substr(0, name.size() - strlen(UnionTypeFieldSuffix()));
675   }
676
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,
682                                     name)
683                   : name;
684     } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
685       return actual_type ? (native_type ? "std::string" : "flatbuffers::String")
686                          : Name(ev);
687     } else {
688       FLATBUFFERS_ASSERT(false);
689       return Name(ev);
690     }
691   }
692
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)";
697   }
698
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)";
704   }
705
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)";
711   }
712
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";
719   }
720
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" : "") + ")";
728   }
729
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" : "") + ")";
738   }
739
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";
746   }
747
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";
754   }
755
756   void GenMiniReflectPre(const StructDef *struct_def) {
757     code_.SetValue("NAME", struct_def->name);
758     code_ += "inline const flatbuffers::TypeTable *{{NAME}}TypeTable();";
759     code_ += "";
760   }
761
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"));
767     auto num_fields =
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;
773     if (struct_def) {
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);
779       }
780     } else {
781       for (auto it = enum_def->vals.vec.begin(); it != enum_def->vals.vec.end();
782            ++it) {
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;
789         }
790       }
791     }
792     std::string ts;
793     std::vector<std::string> type_refs;
794     for (auto it = types.begin(); it != types.end(); ++it) {
795       auto &type = *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
801                     : ET_SEQUENCE;
802       int ref_idx = -1;
803       std::string ref_name =
804           type.struct_def
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());
812             break;
813           }
814         }
815         if (rit == type_refs.end()) {
816           ref_idx = static_cast<int>(type_refs.size());
817           type_refs.push_back(ref_name);
818         }
819       }
820       ts += "{ flatbuffers::" + std::string(ElementaryTypeNames()[et]) + ", " +
821             NumToString(is_vector) + ", " + NumToString(ref_idx) + " }";
822     }
823     std::string rs;
824     for (auto it = type_refs.begin(); it != type_refs.end(); ++it) {
825       if (!rs.empty()) rs += ",\n    ";
826       rs += *it + "TypeTable";
827     }
828     std::string ns;
829     for (auto it = names.begin(); it != names.end(); ++it) {
830       if (!ns.empty()) ns += ",\n    ";
831       ns += "\"" + *it + "\"";
832     }
833     std::string vs;
834     if (enum_def && !consecutive_enum_from_zero) {
835       for (auto it = enum_def->vals.vec.begin(); it != enum_def->vals.vec.end();
836            ++it) {
837         const auto &ev = **it;
838         if (!vs.empty()) vs += ", ";
839         vs += NumToString(ev.value);
840       }
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);
846         vs += ", ";
847       }
848       vs += NumToString(struct_def->bytesize);
849     }
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() {";
855     if (num_fields) {
856       code_ += "  static const flatbuffers::TypeCode type_codes[] = {";
857       code_ += "    {{TYPES}}";
858       code_ += "  };";
859     }
860     if (!type_refs.empty()) {
861       code_ += "  static const flatbuffers::TypeFunction type_refs[] = {";
862       code_ += "    {{REFS}}";
863       code_ += "  };";
864     }
865     if (!vs.empty()) {
866       code_ += "  static const int64_t values[] = { {{VALUES}} };";
867     }
868     auto has_names =
869         num_fields && parser_.opts.mini_reflect == IDLOptions::kTypesAndNames;
870     if (has_names) {
871       code_ += "  static const char * const names[] = {";
872       code_ += "    {{NAMES}}";
873       code_ += "  };";
874     }
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");
881     code_ += "  };";
882     code_ += "  return &tt;";
883     code_ += "}";
884     code_ += "";
885   }
886
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", "");
894
895     GenComment(enum_def.doc_comment);
896     code_ += GenEnumDecl(enum_def) + "\\";
897     if (parser_.opts.scoped_enums) code_ += " : {{BASE_TYPE}}\\";
898     code_ += " {";
899
900     int64_t anyv = 0;
901     const EnumVal *minv = nullptr, *maxv = nullptr;
902     for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
903          ++it) {
904       const auto &ev = **it;
905
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");
911
912       minv = !minv || minv->value > ev.value ? &ev : minv;
913       maxv = !maxv || maxv->value < ev.value ? &ev : maxv;
914       anyv |= ev.value;
915     }
916
917     if (parser_.opts.scoped_enums || parser_.opts.prefixed_enums) {
918       FLATBUFFERS_ASSERT(minv && maxv);
919
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}}\\";
925
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}}\\";
933
934         code_.SetValue("KEY", GenEnumValDecl(enum_def, "MAX"));
935         code_.SetValue("VALUE", GenEnumValDecl(enum_def, maxv->name));
936         code_ += "{{SEP}}  {{KEY}} = {{VALUE}}\\";
937       }
938     }
939     code_ += "";
940     code_ += "};";
941
942     if (parser_.opts.scoped_enums && enum_def.attributes.Lookup("bit_flags")) {
943       code_ += "FLATBUFFERS_DEFINE_BITMASK_OPERATORS({{ENUM_NAME}}, {{BASE_TYPE}})";
944     }
945     code_ += "";
946
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 +
950              "] {";
951     code_ += "  static const {{ENUM_NAME}} values[] = {";
952     for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
953          ++it) {
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;
958     }
959     code_ += "  };";
960     code_ += "  return values;";
961     code_ += "}";
962     code_ += "";
963
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.
968     auto range =
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()) <
974         kMaxSparseness) {
975       code_ += "inline const char * const *EnumNames{{ENUM_NAME}}() {";
976       code_ += "  static const char * const names[] = {";
977
978       auto val = enum_def.vals.vec.front()->value;
979       for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
980            ++it) {
981         const auto &ev = **it;
982         while (val++ != ev.value) { code_ += "    \"\","; }
983         code_ += "    \"" + Name(ev) + "\",";
984       }
985       code_ += "    nullptr";
986       code_ += "  };";
987
988       code_ += "  return names;";
989       code_ += "}";
990       code_ += "";
991
992       code_ += "inline const char *EnumName{{ENUM_NAME}}({{ENUM_NAME}} e) {";
993
994       code_ += "  if (e < " + GetEnumValUse(enum_def, *enum_def.vals.vec.front()) +
995                " || e > " + GetEnumValUse(enum_def, *enum_def.vals.vec.back()) +
996                ") return \"\";";
997
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 + ")\\";
1002       }
1003       code_ += ";";
1004
1005       code_ += "  return EnumNames{{ENUM_NAME}}()[index];";
1006       code_ += "}";
1007       code_ += "";
1008     } else {
1009       code_ += "inline const char *EnumName{{ENUM_NAME}}({{ENUM_NAME}} e) {";
1010
1011       code_ += "  switch (e) {";
1012
1013       for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1014            ++it) {
1015         const auto &ev = **it;
1016         code_ += "    case " + GetEnumValUse(enum_def, ev) + ": return \"" +
1017                  Name(ev) + "\";";
1018       }
1019
1020       code_ += "    default: return \"\";";
1021       code_ += "  }";
1022
1023       code_ += "}";
1024       code_ += "";
1025     }
1026
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();
1030            ++it) {
1031         const auto &ev = **it;
1032
1033         if (it == enum_def.vals.vec.begin()) {
1034           code_ += "template<typename T> struct {{ENUM_NAME}}Traits {";
1035         } else {
1036           auto name = GetUnionElement(ev, true, true);
1037           code_ += "template<> struct {{ENUM_NAME}}Traits<" + name + "> {";
1038         }
1039
1040         auto value = GetEnumValUse(enum_def, ev);
1041         code_ += "  static const {{ENUM_NAME}} enum_value = " + value + ";";
1042         code_ += "};";
1043         code_ += "";
1044       }
1045     }
1046
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")));
1052
1053       code_ += "struct {{NAME}}Union {";
1054       code_ += "  {{NAME}} type;";
1055       code_ += "  void *value;";
1056       code_ += "";
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;";
1062       code_ +=
1063           "  {{NAME}}Union &operator=(const {{NAME}}Union &u) "
1064           "FLATBUFFERS_NOEXCEPT";
1065       code_ +=
1066           "    { {{NAME}}Union t(u); std::swap(type, t.type); std::swap(value, "
1067           "t.value); return *this; }";
1068       code_ +=
1069           "  {{NAME}}Union &operator=({{NAME}}Union &&u) FLATBUFFERS_NOEXCEPT";
1070       code_ +=
1071           "    { std::swap(type, u.type); std::swap(value, u.value); return "
1072           "*this; }";
1073       code_ += "  ~{{NAME}}Union() { Reset(); }";
1074       code_ += "";
1075       code_ += "  void Reset();";
1076       code_ += "";
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();";
1082         code_ +=
1083             "    type = {{NAME}}Traits<typename T::TableType>::enum_value;";
1084         code_ += "    if (type != {{NONE}}) {";
1085         code_ += "      value = new T(std::forward<T>(val));";
1086         code_ += "    }";
1087         code_ += "  }";
1088         code_ += "#endif  // FLATBUFFERS_CPP98_STL";
1089         code_ += "";
1090       }
1091       code_ += "  " + UnionUnPackSignature(enum_def, true) + ";";
1092       code_ += "  " + UnionPackSignature(enum_def, true) + ";";
1093       code_ += "";
1094
1095       for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1096            ++it) {
1097         const auto &ev = **it;
1098         if (!ev.value) { continue; }
1099
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));
1106
1107         code_ += "  {{NATIVE_TYPE}} *As{{NATIVE_NAME}}() {";
1108         code_ += "    return type == {{NATIVE_ID}} ?";
1109         code_ += "      reinterpret_cast<{{NATIVE_TYPE}} *>(value) : nullptr;";
1110         code_ += "  }";
1111
1112         code_ += "  const {{NATIVE_TYPE}} *As{{NATIVE_NAME}}() const {";
1113         code_ += "    return type == {{NATIVE_ID}} ?";
1114         code_ +=
1115             "      reinterpret_cast<const {{NATIVE_TYPE}} *>(value) : nullptr;";
1116         code_ += "  }";
1117       }
1118       code_ += "};";
1119       code_ += "";
1120
1121       if (parser_.opts.gen_compare) {
1122         code_ += "";
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) {";
1126
1127         for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1128            ++it) {
1129           const auto &ev = **it;
1130           code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
1131           if (ev.value) {
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));";
1139             code_ += "    }";
1140           } else {
1141             code_ += "    case {{NATIVE_ID}}: {";
1142             code_ += "      return true;";  // "NONE" enum value.
1143             code_ += "    }";
1144           }
1145         }
1146         code_ += "    default: {";
1147         code_ += "      return false;";
1148         code_ += "    }";
1149         code_ += "  }";
1150         code_ += "}";
1151       }
1152     }
1153
1154     if (enum_def.is_union) {
1155       code_ += UnionVerifySignature(enum_def) + ";";
1156       code_ += UnionVectorVerifySignature(enum_def) + ";";
1157       code_ += "";
1158     }
1159   }
1160
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));
1168
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();
1172          ++it) {
1173       const auto &ev = **it;
1174       code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
1175
1176       if (ev.value) {
1177         code_.SetValue("TYPE", GetUnionElement(ev, true, true));
1178         code_ += "    case {{LABEL}}: {";
1179         auto getptr =
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;";
1184           } else {
1185             code_ += getptr;
1186             code_ += "      return verifier.VerifyTable(ptr);";
1187           }
1188         } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
1189           code_ += getptr;
1190           code_ += "      return verifier.VerifyString(ptr);";
1191         } else {
1192           FLATBUFFERS_ASSERT(false);
1193         }
1194         code_ += "    }";
1195       } else {
1196         code_ += "    case {{LABEL}}: {";
1197         code_ += "      return true;";  // "NONE" enum value.
1198         code_ += "    }";
1199       }
1200     }
1201     code_ += "    default: return false;";
1202     code_ += "  }";
1203     code_ += "}";
1204     code_ += "";
1205
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;";
1214     code_ += "    }";
1215     code_ += "  }";
1216     code_ += "  return true;";
1217     code_ += "}";
1218     code_ += "";
1219
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();
1225            ++it) {
1226         const auto &ev = **it;
1227         if (!ev.value) { continue; }
1228
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);";
1237           } else {
1238             code_ += "      return ptr->UnPack(resolver);";
1239           }
1240         } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
1241           code_ += "      return new std::string(ptr->c_str(), ptr->size());";
1242         } else {
1243           FLATBUFFERS_ASSERT(false);
1244         }
1245         code_ += "    }";
1246       }
1247       code_ += "    default: return nullptr;";
1248       code_ += "  }";
1249       code_ += "}";
1250       code_ += "";
1251
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();
1255            ++it) {
1256         auto &ev = **it;
1257         if (!ev.value) { continue; }
1258
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();";
1269           } else {
1270             code_ +=
1271                 "      return Create{{NAME}}(_fbb, ptr, _rehasher).Union();";
1272           }
1273         } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
1274           code_ += "      return _fbb.CreateString(*ptr).Union();";
1275         } else {
1276           FLATBUFFERS_ASSERT(false);
1277         }
1278         code_ += "    }";
1279       }
1280       code_ += "    default: return 0;";
1281       code_ += "  }";
1282       code_ += "}";
1283       code_ += "";
1284
1285       // Union copy constructor
1286       code_ +=
1287           "inline {{ENUM_NAME}}Union::{{ENUM_NAME}}Union(const "
1288           "{{ENUM_NAME}}Union &u) FLATBUFFERS_NOEXCEPT : type(u.type), "
1289           "value(nullptr) {";
1290       code_ += "  switch (type) {";
1291       for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
1292            ++it) {
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) {
1309               copyable = false;
1310               break;
1311             }
1312           }
1313         }
1314         if (copyable) {
1315           code_ +=
1316               "      value = new {{TYPE}}(*reinterpret_cast<{{TYPE}} *>"
1317               "(u.value));";
1318         } else {
1319           code_ += "      FLATBUFFERS_ASSERT(false);  // {{TYPE}} not copyable.";
1320         }
1321         code_ += "      break;";
1322         code_ += "    }";
1323       }
1324       code_ += "    default:";
1325       code_ += "      break;";
1326       code_ += "  }";
1327       code_ += "}";
1328       code_ += "";
1329
1330       // Union Reset() function.
1331       code_.SetValue("NONE",
1332                      GetEnumValUse(enum_def, *enum_def.vals.Lookup("NONE")));
1333
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();
1337            ++it) {
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;";
1347         code_ += "      break;";
1348         code_ += "    }";
1349       }
1350       code_ += "    default: break;";
1351       code_ += "  }";
1352       code_ += "  value = nullptr;";
1353       code_ += "  type = {{NONE}};";
1354       code_ += "}";
1355       code_ += "";
1356     }
1357   }
1358
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) + ">(" +
1371              val + ")";
1372     } else {
1373       return val;
1374     }
1375   }
1376
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;
1381   }
1382
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}}\";";
1391     code_ += "  }";
1392   }
1393
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;
1398   }
1399
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);
1404       if (ev) {
1405         return WrapInNameSpace(field.value.type.enum_def->defined_namespace,
1406                                GetEnumValUse(*field.value.type.enum_def, *ev));
1407       } else {
1408         return GenUnderlyingCast(field, true, field.value.constant);
1409       }
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")) {
1413       if (is_ctor) {
1414         if (PtrType(&field) == "naked") {
1415           return "nullptr";
1416         } else {
1417           return "";
1418         }
1419       } else {
1420         return "0";
1421       }
1422     } else {
1423       return GenDefaultConstant(field);
1424     }
1425   }
1426
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();
1435       std::string type;
1436       if (IsStruct(vtype)) {
1437         type = WrapInNameSpace(*vtype.struct_def);
1438       } else {
1439         type = GenTypeWire(vtype, "", false);
1440       }
1441       code_.SetValue("PARAM_TYPE", "const std::vector<" + type + "> *");
1442       code_.SetValue("PARAM_VALUE", "nullptr");
1443     } else {
1444       code_.SetValue("PARAM_TYPE", GenTypeWire(field.value.type, " ", true));
1445       code_.SetValue("PARAM_VALUE", GetDefaultScalarValue(field, false));
1446     }
1447     code_ += "{{PRE}}{{PARAM_TYPE}}{{PARAM_NAME}} = {{PARAM_VALUE}}\\";
1448   }
1449
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");
1458       auto full_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))
1462                     : type + " ");
1463       code_.SetValue("FIELD_TYPE", full_type);
1464       code_.SetValue("FIELD_NAME", Name(field));
1465       code_ += "  {{FIELD_TYPE}}{{FIELD_NAME}};";
1466     }
1467   }
1468
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        ";
1490               }
1491               initializer_list +=
1492                   Name(field) + "(" + native_default->constant + ")";
1493             }
1494           }
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)";
1498         }
1499       }
1500     }
1501     if (!initializer_list.empty()) {
1502       initializer_list = "\n      : " + initializer_list;
1503     }
1504
1505     code_.SetValue("NATIVE_NAME",
1506                    NativeName(Name(struct_def), &struct_def, parser_.opts));
1507     code_.SetValue("INIT_LIST", initializer_list);
1508
1509     code_ += "  {{NATIVE_NAME}}(){{INIT_LIST}} {";
1510     code_ += "  }";
1511   }
1512
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      ";
1524         }
1525         auto accessor = Name(field) + accessSuffix;
1526         compare_op += "(lhs." + accessor + " == rhs." + accessor + ")";
1527       }
1528     }
1529
1530     std::string cmp_lhs;
1531     std::string cmp_rhs;
1532     if (compare_op.empty()) {
1533       cmp_lhs = "";
1534       cmp_rhs = "";
1535       compare_op = "  return true;";
1536     } else {
1537       cmp_lhs = "lhs";
1538       cmp_rhs = "rhs";
1539       compare_op = "  return\n      " + compare_op + ";";
1540     }
1541     
1542     code_.SetValue("CMP_OP", compare_op);
1543     code_.SetValue("CMP_LHS", cmp_lhs);
1544     code_.SetValue("CMP_RHS", cmp_rhs);
1545     code_ += "";
1546     code_ += "inline bool operator==(const {{NATIVE_NAME}} &{{CMP_LHS}}, const {{NATIVE_NAME}} &{{CMP_RHS}}) {";
1547     code_ += "{{CMP_OP}}";
1548     code_ += "}";
1549   }
1550
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}}));";
1557       code_ += "  }";
1558       code_ += "  inline void operator delete (void *ptr) {";
1559       code_ += "    return " + native_custom_alloc->constant +
1560                "<{{NATIVE_NAME}}>().deallocate(static_cast<{{NATIVE_NAME}}*>("
1561                "ptr),1);";
1562       code_ += "  }";
1563     }
1564   }
1565
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);
1571
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) {
1578       GenMember(**it);
1579     }
1580     GenOperatorNewDelete(struct_def);
1581     GenDefaultConstructor(struct_def);
1582     code_ += "};";
1583     if (parser_.opts.gen_compare) GenCompareOperator(struct_def);
1584     code_ += "";
1585   }
1586
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)) {
1595       code_ +=
1596           "{{PRE}}VerifyField{{REQUIRED}}<{{SIZE}}>(verifier, {{OFFSET}})\\";
1597     } else {
1598       code_ += "{{PRE}}VerifyOffset{{REQUIRED}}(verifier, {{OFFSET}})\\";
1599     }
1600
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());
1605         code_ +=
1606             "{{PRE}}Verify{{ENUM_NAME}}(verifier, {{NAME}}(), "
1607             "{{NAME}}{{SUFFIX}}())\\";
1608         break;
1609       }
1610       case BASE_TYPE_STRUCT: {
1611         if (!field.value.type.struct_def->fixed) {
1612           code_ += "{{PRE}}verifier.VerifyTable({{NAME}}())\\";
1613         }
1614         break;
1615       }
1616       case BASE_TYPE_STRING: {
1617         code_ += "{{PRE}}verifier.VerifyString({{NAME}}())\\";
1618         break;
1619       }
1620       case BASE_TYPE_VECTOR: {
1621         code_ += "{{PRE}}verifier.VerifyVector({{NAME}}())\\";
1622
1623         switch (field.value.type.element) {
1624           case BASE_TYPE_STRING: {
1625             code_ += "{{PRE}}verifier.VerifyVectorOfStrings({{NAME}}())\\";
1626             break;
1627           }
1628           case BASE_TYPE_STRUCT: {
1629             if (!field.value.type.struct_def->fixed) {
1630               code_ += "{{PRE}}verifier.VerifyVectorOfTables({{NAME}}())\\";
1631             }
1632             break;
1633           }
1634           case BASE_TYPE_UNION: {
1635             code_.SetValue("ENUM_NAME", field.value.type.enum_def->name);
1636             code_ +=
1637                 "{{PRE}}Verify{{ENUM_NAME}}Vector(verifier, {{NAME}}(), "
1638                 "{{NAME}}_type())\\";
1639             break;
1640           }
1641           default: break;
1642         }
1643         break;
1644       }
1645       default: { break; }
1646     }
1647   }
1648
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);
1653
1654     code_ += "  bool KeyCompareLessThan(const {{STRUCT_NAME}} *o) const {";
1655     if (is_string) {
1656       // use operator< of flatbuffers::String
1657       code_ += "    return *{{FIELD_NAME}}() < *o->{{FIELD_NAME}}();";
1658     } else {
1659       code_ += "    return {{FIELD_NAME}}() < o->{{FIELD_NAME}}();";
1660     }
1661     code_ += "  }";
1662
1663     if (is_string) {
1664       code_ += "  int KeyCompareWithValue(const char *val) const {";
1665       code_ += "    return strcmp({{FIELD_NAME}}()->c_str(), val);";
1666       code_ += "  }";
1667     } else {
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);
1673       }
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 {";
1677       code_ +=
1678           "    return static_cast<int>({{FIELD_NAME}}() > val) - "
1679           "static_cast<int>({{FIELD_NAME}}() < val);";
1680       code_ += "  }";
1681     }
1682   }
1683
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); }
1687
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);
1691
1692     code_.SetValue("STRUCT_NAME", Name(struct_def));
1693     code_ +=
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;";
1698     }
1699     if (parser_.opts.mini_reflect != IDLOptions::kNone) {
1700       code_ += "  static const flatbuffers::TypeTable *MiniReflectTypeTable() {";
1701       code_ += "    return {{STRUCT_NAME}}TypeTable();";
1702       code_ += "  }";
1703     }
1704
1705
1706     GenFullyQualifiedNameGetter(struct_def, Name(struct_def));
1707
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.
1719           continue;
1720         }
1721
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");
1726       }
1727       code_ += "";
1728       code_ += "  };";
1729     }
1730
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.
1737         continue;
1738       }
1739
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));
1743
1744       // Call a different accessor for pointers, that indirects.
1745       std::string accessor = "";
1746       if (is_scalar) {
1747         accessor = "GetField<";
1748       } else if (is_struct) {
1749         accessor = "GetStruct<";
1750       } else {
1751         accessor = "GetPointer<";
1752       }
1753       auto offset_str = GenFieldOffsetName(field);
1754       auto offset_type =
1755           GenTypeGet(field.value.type, "", "const ", " *", false);
1756
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); }
1760       call += ")";
1761
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());
1768
1769       code_ += "  {{FIELD_TYPE}}{{FIELD_NAME}}() const {";
1770       code_ += "    return {{FIELD_VALUE}};";
1771       code_ += "  }";
1772
1773       if (field.value.type.base_type == BASE_TYPE_UNION) {
1774         auto u = field.value.type.enum_def;
1775
1776         code_ +=
1777             "  template<typename T> "
1778             "const T *{{NULLABLE_EXT}}{{FIELD_NAME}}_as() const;";
1779
1780         for (auto u_it = u->vals.vec.begin(); u_it != u->vals.vec.end();
1781              ++u_it) {
1782           auto &ev = **u_it;
1783           if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
1784           auto full_struct_name = GetUnionElement(ev, true, true);
1785
1786           // @TODO: Mby make this decisions more universal? How?
1787           code_.SetValue(
1788               "U_GET_TYPE",
1789               EscapeKeyword(field.name + UnionTypeFieldSuffix()));
1790           code_.SetValue(
1791               "U_ELEMENT_TYPE",
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());
1796
1797           // `const Type *union_name_asType() const` accessor.
1798           code_ += "  {{U_FIELD_TYPE}}{{U_NULLABLE}}{{U_FIELD_NAME}}() const {";
1799           code_ +=
1800               "    return {{U_GET_TYPE}}() == {{U_ELEMENT_TYPE}} ? "
1801               "static_cast<{{U_FIELD_TYPE}}>({{FIELD_NAME}}()) "
1802               ": nullptr;";
1803           code_ += "  }";
1804         }
1805       }
1806
1807       if (parser_.opts.mutable_buffer) {
1808         if (is_scalar) {
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));
1816
1817           code_ +=
1818               "  bool mutate_{{FIELD_NAME}}({{FIELD_TYPE}} "
1819               "_{{FIELD_NAME}}) {";
1820           code_ +=
1821               "    return {{SET_FN}}({{OFFSET_NAME}}, {{FIELD_VALUE}}, "
1822               "{{DEFAULT_VALUE}});";
1823           code_ += "  }";
1824         } else {
1825           auto postptr = " *" + NullableExtension();
1826           auto type =
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));
1832
1833           code_ += "  {{FIELD_TYPE}}mutable_{{FIELD_NAME}}() {";
1834           code_ += "    return {{FIELD_VALUE}};";
1835           code_ += "  }";
1836         }
1837       }
1838
1839       auto nested = field.attributes.Lookup("nested_flatbuffer");
1840       if (nested) {
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(
1845               nested->constant);
1846           nested_root = parser_.LookupStruct(qualified_name);
1847         }
1848         FLATBUFFERS_ASSERT(nested_root);  // Guaranteed to exist by parser.
1849         (void)nested_root;
1850         code_.SetValue("CPP_NAME", TranslateNameSpace(qualified_name));
1851
1852         code_ += "  const {{CPP_NAME}} *{{FIELD_NAME}}_nested_root() const {";
1853         code_ += "    return flatbuffers::GetRoot<{{CPP_NAME}}>({{FIELD_NAME}}()->Data());";
1854         code_ += "  }";
1855       }
1856
1857       if (field.flexbuffer) {
1858         code_ +=
1859             "  flexbuffers::Reference {{FIELD_NAME}}_flexbuffer_root()"
1860             " const {";
1861         // Both Data() and size() are const-methods, therefore call order doesn't matter.
1862         code_ +=
1863             "    return flexbuffers::GetRoot({{FIELD_NAME}}()->Data(), "
1864             "{{FIELD_NAME}}()->size());";
1865         code_ += "  }";
1866       }
1867
1868       // Generate a comparison function for this field if it is a key.
1869       if (field.key) {
1870         GenKeyFieldMethods(field);
1871       }
1872     }
1873
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           ");
1883     }
1884
1885     code_ += " &&\n           verifier.EndTable();";
1886     code_ += "  }";
1887
1888     if (parser_.opts.generate_object_based_api) {
1889       // Generate the UnPack() pre declaration.
1890       code_ +=
1891           "  " + TableUnPackSignature(struct_def, true, parser_.opts) + ";";
1892       code_ +=
1893           "  " + TableUnPackToSignature(struct_def, true, parser_.opts) + ";";
1894       code_ += "  " + TablePackSignature(struct_def, true, parser_.opts) + ";";
1895     }
1896
1897     code_ += "};";  // End of table.
1898     code_ += "";
1899
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) {
1905         continue;
1906       }
1907
1908       auto u = field.value.type.enum_def;
1909       if (u->uses_type_aliases) continue;
1910
1911       code_.SetValue("FIELD_NAME", Name(field));
1912
1913       for (auto u_it = u->vals.vec.begin(); u_it != u->vals.vec.end(); ++u_it) {
1914         auto &ev = **u_it;
1915         if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
1916
1917         auto full_struct_name = GetUnionElement(ev, true, true);
1918
1919         code_.SetValue(
1920             "U_ELEMENT_TYPE",
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));
1925
1926         // `template<> const T *union_name_as<T>() const` accessor.
1927         code_ +=
1928             "template<> "
1929             "inline {{U_FIELD_TYPE}}{{STRUCT_NAME}}::{{FIELD_NAME}}_as"
1930             "<{{U_ELEMENT_NAME}}>() const {";
1931         code_ += "  return {{U_FIELD_NAME}}();";
1932         code_ += "}";
1933         code_ += "";
1934       }
1935     }
1936
1937     GenBuilders(struct_def);
1938
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) + ";";
1943       code_ += "";
1944     }
1945   }
1946
1947   void GenBuilders(const StructDef &struct_def) {
1948     code_.SetValue("STRUCT_NAME", Name(struct_def));
1949
1950     // Generate a builder struct:
1951     code_ += "struct {{STRUCT_NAME}}Builder {";
1952     code_ += "  flatbuffers::FlatBufferBuilder &fbb_;";
1953     code_ += "  flatbuffers::uoffset_t start_;";
1954
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; }
1964
1965         std::string offset = GenFieldOffsetName(field);
1966         std::string name = GenUnderlyingCast(field, false, Name(field));
1967         std::string value = is_scalar ? GenDefaultConstant(field) : "";
1968
1969         // Generate accessor functions of the form:
1970         // void add_name(type name) {
1971         //   fbb_.AddElement<type>(offset, name, default);
1972         // }
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);
1978         if (is_scalar) {
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");
1983         } else {
1984           code_.SetValue("ADD_FN", "AddOffset");
1985         }
1986
1987         code_ += "  void add_{{FIELD_NAME}}({{FIELD_TYPE}}{{FIELD_NAME}}) {";
1988         code_ += "    fbb_.{{ADD_FN}}(\\";
1989         if (is_scalar) {
1990           code_ += "{{ADD_OFFSET}}, {{ADD_NAME}}, {{ADD_VALUE}});";
1991         } else {
1992           code_ += "{{ADD_OFFSET}}, {{ADD_NAME}});";
1993         }
1994         code_ += "  }";
1995       }
1996     }
1997
1998     // Builder constructor
1999     code_ +=
2000         "  explicit {{STRUCT_NAME}}Builder(flatbuffers::FlatBufferBuilder "
2001         "&_fbb)";
2002     code_ += "        : fbb_(_fbb) {";
2003     code_ += "    start_ = fbb_.StartTable();";
2004     code_ += "  }";
2005
2006     // Assignment operator;
2007     code_ +=
2008         "  {{STRUCT_NAME}}Builder &operator="
2009         "(const {{STRUCT_NAME}}Builder &);";
2010
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);";
2015
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}});";
2023       }
2024     }
2025     code_ += "    return o;";
2026     code_ += "  }";
2027     code_ += "};";
2028     code_ += "";
2029
2030     // Generate a convenient CreateX function that uses the above builder
2031     // to create a table in one go.
2032     code_ +=
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    "); }
2040     }
2041     code_ += ") {";
2042
2043     code_ += "  {{STRUCT_NAME}}Builder builder_(_fbb);";
2044     for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
2045          size; size /= 2) {
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}});";
2053         }
2054       }
2055     }
2056     code_ += "  return builder_.Finish();";
2057     code_ += "}";
2058     code_ += "";
2059
2060     // Generate a CreateXDirect function with vector types as parameters
2061     if (has_string_or_vector_fields) {
2062       code_ +=
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    "); }
2070       }
2071
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));
2076
2077       code_ += ") {";
2078       code_ += "  return {{CREATE_NAME}}{{STRUCT_NAME}}(";
2079       code_ += "      _fbb\\";
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));
2085
2086           if (field.value.type.base_type == BASE_TYPE_STRING) {
2087             code_ +=
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 + ">\\";
2096             } else {
2097               const auto type = GenTypeWire(vtype, "", false);
2098               code_ += "_fbb.CreateVector<" + type + ">\\";
2099             }
2100             code_ += "(*{{FIELD_NAME}}) : 0\\";
2101           } else {
2102             code_ += ",\n      {{FIELD_NAME}}\\";
2103           }
2104         }
2105       }
2106       code_ += ");";
2107       code_ += "}";
2108       code_ += "";
2109     }
2110   }
2111
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)";
2119   }
2120
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()";
2126       }
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");
2131           if (native_type) {
2132             return "flatbuffers::UnPack(*" + val + ")";
2133           } else if (invector || afield.native_inline) {
2134             return "*" + val;
2135           } else {
2136             const auto ptype = GenTypeNativePtr(name, &afield, true);
2137             return ptype + "(new " + name + "(*" + val + "))";
2138           }
2139         } else {
2140           const auto ptype = GenTypeNativePtr(
2141               NativeName(name, type.struct_def, parser_.opts), &afield, true);
2142           return ptype + "(" + val + "->UnPack(_resolver))";
2143         }
2144       }
2145       case BASE_TYPE_UNION: {
2146         return GenUnionUnpackVal(
2147             afield, invector ? "->Get(_i)" : "",
2148             invector ? ("->GetEnum<" + type.enum_def->name + ">(_i)").c_str()
2149                      : "");
2150       }
2151       default: {
2152         return val;
2153         break;
2154       }
2155     }
2156   };
2157
2158   std::string GenUnpackFieldStatement(const FieldDef &field,
2159                                       const FieldDef *union_field) {
2160     std::string code;
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) + ">(";
2168         }
2169         indexing += "_e->Get(_i)";
2170         if (field.value.type.enum_def) { indexing += ")"; }
2171         if (field.value.type.element == BASE_TYPE_BOOL) { indexing += " != 0"; }
2172
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));
2176         //   }
2177         auto name = Name(field);
2178         if (field.value.type.element == BASE_TYPE_UTYPE) {
2179           name = StripUnionType(Name(field));
2180         }
2181         auto access =
2182             field.value.type.element == BASE_TYPE_UTYPE
2183                 ? ".type"
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++) { ";
2188         if (cpp_type) {
2189           // Generate code that resolves the cpp pointer type, of the form:
2190           //  if (resolver)
2191           //    (*resolver)(&_o->field, (hash_value_t)(_e));
2192           //  else
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") {
2200             code += " else ";
2201             code += "_o->" + name + "[_i]" + access + " = nullptr";
2202           } else {
2203             //code += " else ";
2204             //code += "_o->" + name + "[_i]" + access + " = " + GenTypeNativePtr(cpp_type->constant, &field, true) + "();";
2205             code += "/* else do nothing */";
2206           }
2207         } else {
2208           code += "_o->" + name + "[_i]" + access + " = ";
2209           code +=
2210             GenUnpackVal(field.value.type.VectorType(), indexing, true, field);
2211         }
2212         code += "; } }";
2213         break;
2214       }
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;";
2220         break;
2221       }
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, "", "");
2227         code += ";";
2228         break;
2229       }
2230       default: {
2231         auto cpp_type = field.attributes.Lookup("cpp_type");
2232         if (cpp_type) {
2233           // Generate code that resolves the cpp pointer type, of the form:
2234           //  if (resolver)
2235           //    (*resolver)(&_o->field, (hash_value_t)(_e));
2236           //  else
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") {
2244             code += " else ";
2245             code += "_o->" + Name(field) + " = nullptr;";
2246           } else {
2247             //code += " else ";
2248             //code += "_o->" + Name(field) + " = " + GenTypeNativePtr(cpp_type->constant, &field, true) + "();";
2249             code += "/* else do nothing */;";
2250           }
2251         } else {
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) + ";";
2256         }
2257         break;
2258       }
2259     }
2260     return code;
2261   }
2262
2263   std::string GenCreateParam(const FieldDef &field) {
2264     const IDLOptions &opts = parser_.opts;
2265
2266     std::string value = "_o->";
2267     if (field.value.type.base_type == BASE_TYPE_UTYPE) {
2268       value += StripUnionType(Name(field));
2269       value += ".type";
2270     } else {
2271       value += Name(field);
2272     }
2273     if (field.value.type.base_type != BASE_TYPE_VECTOR && field.attributes.Lookup("cpp_type")) {
2274       auto type = GenTypeBasic(field.value.type, false);
2275       value =
2276           "_rehasher ? "
2277           "static_cast<" +
2278           type + ">((*_rehasher)(" + value + GenPtrGet(field) + ")) : 0";
2279     }
2280
2281
2282     std::string code;
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 + ")";
2288
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) {
2293           auto empty_value =
2294               opts.set_empty_to_null ? "0" : "_fbb.CreateSharedString(\"\")";
2295           code = value + ".empty() ? " + empty_value + " : " + code;
2296         }
2297         break;
2298       }
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);
2306       //   });
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 + ")";
2312             break;
2313           }
2314           case BASE_TYPE_STRUCT: {
2315             if (IsStruct(vector_type)) {
2316               auto native_type =
2317                   field.value.type.struct_def->attributes.Lookup("native_type");
2318               if (native_type) {
2319                 code += "_fbb.CreateVectorOfNativeStructs<";
2320                 code += WrapInNameSpace(*vector_type.struct_def) + ">";
2321               } else {
2322                 code += "_fbb.CreateVectorOfStructs";
2323               }
2324               code += "(" + value + ")";
2325             } else {
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 )";
2334             }
2335             break;
2336           }
2337           case BASE_TYPE_BOOL: {
2338             code += "_fbb.CreateVector(" + value + ")";
2339             break;
2340           }
2341           case BASE_TYPE_UNION: {
2342             code +=
2343                 "_fbb.CreateVector<flatbuffers::"
2344                 "Offset<void>>(" +
2345                 value +
2346                 ".size(), [](size_t i, _VectorArgs *__va) { "
2347                 "return __va->_" +
2348                 value + "[i].Pack(*__va->__fbb, __va->__rehasher); }, &_va)";
2349             break;
2350           }
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)";
2357             break;
2358           }
2359           default: {
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 )";
2375             } else {
2376               code += "_fbb.CreateVector(" + value + ")";
2377             }
2378             break;
2379           }
2380         }
2381
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
2384         // access it.
2385         if (opts.set_empty_to_null && !field.required) {
2386           code = value + ".size() ? " + code + " : 0";
2387         }
2388         break;
2389       }
2390       case BASE_TYPE_UNION: {
2391         // _o->field.Pack(_fbb);
2392         code += value + ".Pack(_fbb)";
2393         break;
2394       }
2395       case BASE_TYPE_STRUCT: {
2396         if (IsStruct(field.value.type)) {
2397           auto native_type =
2398               field.value.type.struct_def->attributes.Lookup("native_type");
2399           if (native_type) {
2400             code += "flatbuffers::Pack(" + value + ")";
2401           } else if (field.native_inline) {
2402             code += "&" + value;
2403           } else {
2404             code += value + " ? " + value + GenPtrGet(field) + " : 0";
2405           }
2406         } else {
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)";
2411           code += " : 0";
2412         }
2413         break;
2414       }
2415       default: {
2416         code += value;
2417         break;
2418       }
2419     }
2420     return code;
2421   }
2422
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));
2428
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;";
2436       code_ += "}";
2437       code_ += "";
2438
2439       code_ += "inline " +
2440                TableUnPackToSignature(struct_def, false, parser_.opts) + " {";
2441       code_ += "  (void)_o;";
2442       code_ += "  (void)_resolver;";
2443
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; }
2448
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);
2455
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;
2461       }
2462       code_ += "}";
2463       code_ += "";
2464
2465       // Generate the X::Pack member function that simply calls the global
2466       // CreateX function.
2467       code_ += "inline " + TablePackSignature(struct_def, false, parser_.opts) +
2468                " {";
2469       code_ += "  return Create{{STRUCT_NAME}}(_fbb, _o, _rehasher);";
2470       code_ += "}";
2471       code_ += "";
2472
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;";
2478
2479       code_ +=
2480           "  struct _VectorArgs "
2481           "{ flatbuffers::FlatBufferBuilder *__fbb; "
2482           "const " +
2483           NativeName(Name(struct_def), &struct_def, parser_.opts) +
2484           "* __o; "
2485           "const flatbuffers::rehasher_function_t *__rehasher; } _va = { "
2486           "&_fbb, _o, _rehasher}; (void)_va;";
2487
2488       for (auto it = struct_def.fields.vec.begin();
2489            it != struct_def.fields.vec.end(); ++it) {
2490         auto &field = **it;
2491         if (field.deprecated) { continue; }
2492         code_ += "  auto _" + Name(field) + " = " + GenCreateParam(field) + ";";
2493       }
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));
2498
2499       code_ += "  return {{CREATE_NAME}}{{STRUCT_NAME}}(";
2500       code_ += "      _fbb\\";
2501       for (auto it = struct_def.fields.vec.begin();
2502            it != struct_def.fields.vec.end(); ++it) {
2503         auto &field = **it;
2504         if (field.deprecated) { continue; }
2505
2506         bool pass_by_address = false;
2507         if (field.value.type.base_type == BASE_TYPE_STRUCT) {
2508           if (IsStruct(field.value.type)) {
2509             auto native_type =
2510                 field.value.type.struct_def->attributes.Lookup("native_type");
2511             if (native_type) { pass_by_address = true; }
2512           }
2513         }
2514
2515         // Call the CreateX function using values from |_o|.
2516         if (pass_by_address) {
2517           code_ += ",\n      &_" + Name(field) + "\\";
2518         } else {
2519           code_ += ",\n      _" + Name(field) + "\\";
2520         }
2521       }
2522       code_ += ");";
2523       code_ += "}";
2524       code_ += "";
2525     }
2526   }
2527
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);
2535         }
2536       }
2537       FLATBUFFERS_ASSERT(!(field.padding & ~0xF));
2538     }
2539   }
2540
2541   static void PaddingDefinition(int bits, std::string *code_ptr, int *id) {
2542     *code_ptr += "  int" + NumToString(bits) + "_t padding" +
2543                  NumToString((*id)++) + "__;";
2544   }
2545
2546   static void PaddingInitializer(int bits, std::string *code_ptr, int *id) {
2547     (void)bits;
2548     *code_ptr += ",\n        padding" + NumToString((*id)++) + "__(0)";
2549   }
2550
2551   static void PaddingNoop(int bits, std::string *code_ptr, int *id) {
2552     (void)bits;
2553     *code_ptr += "    (void)padding" + NumToString((*id)++) + "__;";
2554   }
2555
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:
2559     // type name_;
2560     // Generates manual padding and alignment.
2561     // Variables are private because they contain little endian data on all
2562     // platforms.
2563     GenComment(struct_def.doc_comment);
2564     code_.SetValue("ALIGN", NumToString(struct_def.minalign));
2565     code_.SetValue("STRUCT_NAME", Name(struct_def));
2566
2567     code_ +=
2568         "FLATBUFFERS_MANUALLY_ALIGNED_STRUCT({{ALIGN}}) "
2569         "{{STRUCT_NAME}} FLATBUFFERS_FINAL_CLASS {";
2570     code_ += " private:";
2571
2572     int padding_id = 0;
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}}_;";
2580
2581       if (field.padding) {
2582         std::string padding;
2583         GenPadding(field, &padding, &padding_id, PaddingDefinition);
2584         code_ += padding;
2585       }
2586     }
2587
2588     // Generate GetFullyQualifiedName
2589     code_ += "";
2590     code_ += " public:";
2591     GenFullyQualifiedNameGetter(struct_def, Name(struct_def));
2592
2593     // Generate a default constructor.
2594     code_ += "  {{STRUCT_NAME}}() {";
2595     code_ += "    memset(this, 0, sizeof({{STRUCT_NAME}}));";
2596     code_ += "  }";
2597
2598     // Generate a constructor that takes all fields as arguments.
2599     std::string arg_list;
2600     std::string init_list;
2601     padding_id = 0;
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);
2609
2610       if (it != struct_def.fields.vec.begin()) {
2611         arg_list += ", ";
2612         init_list += ",\n        ";
2613       }
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 + "))";
2620       } else {
2621         init_list += "(" + arg_name + ")";
2622       }
2623       if (field.padding) {
2624         GenPadding(field, &init_list, &padding_id, PaddingInitializer);
2625       }
2626     }
2627
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}} {";
2633       padding_id = 0;
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);
2640           code_ += padding;
2641         }
2642       }
2643       code_ += "  }";
2644     }
2645
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;
2651
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) + "_";
2655       auto value =
2656           is_scalar ? "flatbuffers::EndianScalar(" + member + ")" : member;
2657
2658       code_.SetValue("FIELD_NAME", Name(field));
2659       code_.SetValue("FIELD_TYPE", field_type);
2660       code_.SetValue("FIELD_VALUE", GenUnderlyingCast(field, true, value));
2661
2662       GenComment(field.doc_comment, "  ");
2663       code_ += "  {{FIELD_TYPE}}{{FIELD_NAME}}() const {";
2664       code_ += "    return {{FIELD_VALUE}};";
2665       code_ += "  }";
2666
2667       if (parser_.opts.mutable_buffer) {
2668         auto mut_field_type = GenTypeGet(field.value.type, " ", "", " &", true);
2669         code_.SetValue("FIELD_TYPE", mut_field_type);
2670         if (is_scalar) {
2671           code_.SetValue("ARG", GenTypeBasic(field.value.type, true));
2672           code_.SetValue("FIELD_VALUE",
2673                          GenUnderlyingCast(field, false, "_" + Name(field)));
2674
2675           code_ += "  void mutate_{{FIELD_NAME}}({{ARG}} _{{FIELD_NAME}}) {";
2676           code_ +=
2677               "    flatbuffers::WriteScalar(&{{FIELD_NAME}}_, "
2678               "{{FIELD_VALUE}});";
2679           code_ += "  }";
2680         } else {
2681           code_ += "  {{FIELD_TYPE}}mutable_{{FIELD_NAME}}() {";
2682           code_ += "    return {{FIELD_NAME}}_;";
2683           code_ += "  }";
2684         }
2685       }
2686
2687       // Generate a comparison function for this field if it is a key.
2688       if (field.key) {
2689         GenKeyFieldMethods(field);
2690       }
2691     }
2692     code_.SetValue("NATIVE_NAME", Name(struct_def));
2693     GenOperatorNewDelete(struct_def);
2694     code_ += "};";
2695
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, "()");
2699     code_ += "";
2700   }
2701
2702   // Set up the correct namespace. Only open a namespace if the existing one is
2703   // different (closing/opening only what is necessary).
2704   //
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; }
2709
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;
2716
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++;
2722     }
2723
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];
2728     }
2729     if (old_size != common_prefix_size) { code_ += ""; }
2730
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] + " {";
2735     }
2736     if (new_size != common_prefix_size) { code_ += ""; }
2737
2738     cur_name_space_ = ns;
2739   }
2740 };
2741
2742 }  // namespace cpp
2743
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();
2748 }
2749
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;
2758   }
2759   return make_rule;
2760 }
2761
2762 }  // namespace flatbuffers