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 #ifndef FLATBUFFERS_IDL_H_
18 #define FLATBUFFERS_IDL_H_
19 
20 #include <map>
21 #include <memory>
22 #include <stack>
23 
24 #include "flatbuffers/base.h"
25 #include "flatbuffers/flatbuffers.h"
26 #include "flatbuffers/flexbuffers.h"
27 #include "flatbuffers/hash.h"
28 #include "flatbuffers/reflection.h"
29 
30 #if !defined(FLATBUFFERS_CPP98_STL)
31 #  include <functional>
32 #endif  // !defined(FLATBUFFERS_CPP98_STL)
33 
34 // This file defines the data types representing a parsed IDL (Interface
35 // Definition Language) / schema file.
36 
37 // Limits maximum depth of nested objects.
38 // Prevents stack overflow while parse flatbuffers or json.
39 #if !defined(FLATBUFFERS_MAX_PARSING_DEPTH)
40 #  define FLATBUFFERS_MAX_PARSING_DEPTH 64
41 #endif
42 
43 namespace flatbuffers {
44 
45 // The order of these matters for Is*() functions below.
46 // Additionally, Parser::ParseType assumes bool..string is a contiguous range
47 // of type tokens.
48 // clang-format off
49 #define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
50   TD(NONE,   "",       uint8_t,  byte,   byte,    byte,   uint8,   u8) \
51   TD(UTYPE,  "",       uint8_t,  byte,   byte,    byte,   uint8,   u8) /* begin scalar/int */ \
52   TD(BOOL,   "bool",   uint8_t,  boolean,bool,    bool,   bool,    bool) \
53   TD(CHAR,   "byte",   int8_t,   byte,   int8,    sbyte,  int8,    i8) \
54   TD(UCHAR,  "ubyte",  uint8_t,  byte,   byte,    byte,   uint8,   u8) \
55   TD(SHORT,  "short",  int16_t,  short,  int16,   short,  int16,   i16) \
56   TD(USHORT, "ushort", uint16_t, short,  uint16,  ushort, uint16,  u16) \
57   TD(INT,    "int",    int32_t,  int,    int32,   int,    int32,   i32) \
58   TD(UINT,   "uint",   uint32_t, int,    uint32,  uint,   uint32,  u32) \
59   TD(LONG,   "long",   int64_t,  long,   int64,   long,   int64,   i64) \
60   TD(ULONG,  "ulong",  uint64_t, long,   uint64,  ulong,  uint64,  u64) /* end int */ \
61   TD(FLOAT,  "float",  float,    float,  float32, float,  float32, f32) /* begin float */ \
62   TD(DOUBLE, "double", double,   double, float64, double, float64, f64) /* end float/scalar */
63 #define FLATBUFFERS_GEN_TYPES_POINTER(TD) \
64   TD(STRING, "string", Offset<void>, int, int, StringOffset, int, unused) \
65   TD(VECTOR, "",       Offset<void>, int, int, VectorOffset, int, unused) \
66   TD(STRUCT, "",       Offset<void>, int, int, int,          int, unused) \
67   TD(UNION,  "",       Offset<void>, int, int, int,          int, unused)
68 
69 // The fields are:
70 // - enum
71 // - FlatBuffers schema type.
72 // - C++ type.
73 // - Java type.
74 // - Go type.
75 // - C# / .Net type.
76 // - Python type.
77 // - Rust type.
78 
79 // using these macros, we can now write code dealing with types just once, e.g.
80 
81 /*
82 switch (type) {
83   #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
84                          RTYPE) \
85     case BASE_TYPE_ ## ENUM: \
86       // do something specific to CTYPE here
87     FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
88   #undef FLATBUFFERS_TD
89 }
90 */
91 
92 #define FLATBUFFERS_GEN_TYPES(TD) \
93         FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
94         FLATBUFFERS_GEN_TYPES_POINTER(TD)
95 
96 // Create an enum for all the types above.
97 #ifdef __GNUC__
98 __extension__  // Stop GCC complaining about trailing comma with -Wpendantic.
99 #endif
100 enum BaseType {
101   #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
102                          RTYPE) \
103       BASE_TYPE_ ## ENUM,
104     FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
105   #undef FLATBUFFERS_TD
106 };
107 
108 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
109                        RTYPE) \
110     static_assert(sizeof(CTYPE) <= sizeof(largest_scalar_t), \
111                   "define largest_scalar_t as " #CTYPE);
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)112   FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
113 #undef FLATBUFFERS_TD
114 
115 inline bool IsScalar (BaseType t) { return t >= BASE_TYPE_UTYPE &&
116                                            t <= BASE_TYPE_DOUBLE; }
IsInteger(BaseType t)117 inline bool IsInteger(BaseType t) { return t >= BASE_TYPE_UTYPE &&
118                                            t <= BASE_TYPE_ULONG; }
IsFloat(BaseType t)119 inline bool IsFloat  (BaseType t) { return t == BASE_TYPE_FLOAT ||
120                                            t == BASE_TYPE_DOUBLE; }
IsLong(BaseType t)121 inline bool IsLong   (BaseType t) { return t == BASE_TYPE_LONG ||
122                                            t == BASE_TYPE_ULONG; }
IsBool(BaseType t)123 inline bool IsBool   (BaseType t) { return t == BASE_TYPE_BOOL; }
IsOneByte(BaseType t)124 inline bool IsOneByte(BaseType t) { return t >= BASE_TYPE_UTYPE &&
125                                            t <= BASE_TYPE_UCHAR; }
126 // clang-format on
127 
128 extern const char *const kTypeNames[];
129 extern const char kTypeSizes[];
130 
SizeOf(BaseType t)131 inline size_t SizeOf(BaseType t) { return kTypeSizes[t]; }
132 
133 struct StructDef;
134 struct EnumDef;
135 class Parser;
136 
137 // Represents any type in the IDL, which is a combination of the BaseType
138 // and additional information for vectors/structs_.
139 struct Type {
140   explicit Type(BaseType _base_type = BASE_TYPE_NONE, StructDef *_sd = nullptr,
141                 EnumDef *_ed = nullptr)
base_typeType142       : base_type(_base_type),
143         element(BASE_TYPE_NONE),
144         struct_def(_sd),
145         enum_def(_ed) {}
146 
147   bool operator==(const Type &o) {
148     return base_type == o.base_type && element == o.element &&
149            struct_def == o.struct_def && enum_def == o.enum_def;
150   }
151 
VectorTypeType152   Type VectorType() const { return Type(element, struct_def, enum_def); }
153 
154   Offset<reflection::Type> Serialize(FlatBufferBuilder *builder) const;
155 
156   bool Deserialize(const Parser &parser, const reflection::Type *type);
157 
158   BaseType base_type;
159   BaseType element;       // only set if t == BASE_TYPE_VECTOR
160   StructDef *struct_def;  // only set if t or element == BASE_TYPE_STRUCT
161   EnumDef *enum_def;      // set if t == BASE_TYPE_UNION / BASE_TYPE_UTYPE,
162                           // or for an integral type derived from an enum.
163 };
164 
165 // Represents a parsed scalar value, it's type, and field offset.
166 struct Value {
ValueValue167   Value()
168       : constant("0"),
169         offset(static_cast<voffset_t>(~(static_cast<voffset_t>(0U)))) {}
170   Type type;
171   std::string constant;
172   voffset_t offset;
173 };
174 
175 // Helper class that retains the original order of a set of identifiers and
176 // also provides quick lookup.
177 template<typename T> class SymbolTable {
178  public:
~SymbolTable()179   ~SymbolTable() {
180     for (auto it = vec.begin(); it != vec.end(); ++it) { delete *it; }
181   }
182 
Add(const std::string & name,T * e)183   bool Add(const std::string &name, T *e) {
184     vector_emplace_back(&vec, e);
185     auto it = dict.find(name);
186     if (it != dict.end()) return true;
187     dict[name] = e;
188     return false;
189   }
190 
Move(const std::string & oldname,const std::string & newname)191   void Move(const std::string &oldname, const std::string &newname) {
192     auto it = dict.find(oldname);
193     if (it != dict.end()) {
194       auto obj = it->second;
195       dict.erase(it);
196       dict[newname] = obj;
197     } else {
198       FLATBUFFERS_ASSERT(false);
199     }
200   }
201 
Lookup(const std::string & name)202   T *Lookup(const std::string &name) const {
203     auto it = dict.find(name);
204     return it == dict.end() ? nullptr : it->second;
205   }
206 
207  public:
208   std::map<std::string, T *> dict;  // quick lookup
209   std::vector<T *> vec;             // Used to iterate in order of insertion
210 };
211 
212 // A name space, as set in the schema.
213 struct Namespace {
NamespaceNamespace214   Namespace() : from_table(0) {}
215 
216   // Given a (potentally unqualified) name, return the "fully qualified" name
217   // which has a full namespaced descriptor.
218   // With max_components you can request less than the number of components
219   // the current namespace has.
220   std::string GetFullyQualifiedName(const std::string &name,
221                                     size_t max_components = 1000) const;
222 
223   std::vector<std::string> components;
224   size_t from_table;  // Part of the namespace corresponds to a message/table.
225 };
226 
227 // Base class for all definition types (fields, structs_, enums_).
228 struct Definition {
DefinitionDefinition229   Definition()
230       : generated(false),
231         defined_namespace(nullptr),
232         serialized_location(0),
233         index(-1),
234         refcount(1) {}
235 
236   flatbuffers::Offset<
237       flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
238   SerializeAttributes(FlatBufferBuilder *builder, const Parser &parser) const;
239 
240   bool DeserializeAttributes(Parser &parser,
241                              const Vector<Offset<reflection::KeyValue>> *attrs);
242 
243   std::string name;
244   std::string file;
245   std::vector<std::string> doc_comment;
246   SymbolTable<Value> attributes;
247   bool generated;  // did we already output code for this definition?
248   Namespace *defined_namespace;  // Where it was defined.
249 
250   // For use with Serialize()
251   uoffset_t serialized_location;
252   int index;  // Inside the vector it is stored.
253   int refcount;
254 };
255 
256 struct FieldDef : public Definition {
FieldDefFieldDef257   FieldDef()
258       : deprecated(false),
259         required(false),
260         key(false),
261         native_inline(false),
262         flexbuffer(false),
263         nested_flatbuffer(NULL),
264         padding(0) {}
265 
266   Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id,
267                                       const Parser &parser) const;
268 
269   bool Deserialize(Parser &parser, const reflection::Field *field);
270 
271   Value value;
272   bool deprecated;  // Field is allowed to be present in old data, but can't be.
273                     // written in new data nor accessed in new code.
274   bool required;    // Field must always be present.
275   bool key;         // Field functions as a key for creating sorted vectors.
276   bool native_inline;  // Field will be defined inline (instead of as a pointer)
277                        // for native tables if field is a struct.
278   bool flexbuffer;     // This field contains FlexBuffer data.
279   StructDef *nested_flatbuffer;  // This field contains nested FlatBuffer data.
280   size_t padding;                // Bytes to always pad after this field.
281 };
282 
283 struct StructDef : public Definition {
StructDefStructDef284   StructDef()
285       : fixed(false),
286         predecl(true),
287         sortbysize(true),
288         has_key(false),
289         minalign(1),
290         bytesize(0) {}
291 
PadLastFieldStructDef292   void PadLastField(size_t min_align) {
293     auto padding = PaddingBytes(bytesize, min_align);
294     bytesize += padding;
295     if (fields.vec.size()) fields.vec.back()->padding = padding;
296   }
297 
298   Offset<reflection::Object> Serialize(FlatBufferBuilder *builder,
299                                        const Parser &parser) const;
300 
301   bool Deserialize(Parser &parser, const reflection::Object *object);
302 
303   SymbolTable<FieldDef> fields;
304 
305   bool fixed;       // If it's struct, not a table.
306   bool predecl;     // If it's used before it was defined.
307   bool sortbysize;  // Whether fields come in the declaration or size order.
308   bool has_key;     // It has a key field.
309   size_t minalign;  // What the whole object needs to be aligned to.
310   size_t bytesize;  // Size if fixed.
311 
312   flatbuffers::unique_ptr<std::string> original_location;
313 };
314 
IsStruct(const Type & type)315 inline bool IsStruct(const Type &type) {
316   return type.base_type == BASE_TYPE_STRUCT && type.struct_def->fixed;
317 }
318 
InlineSize(const Type & type)319 inline size_t InlineSize(const Type &type) {
320   return IsStruct(type) ? type.struct_def->bytesize : SizeOf(type.base_type);
321 }
322 
InlineAlignment(const Type & type)323 inline size_t InlineAlignment(const Type &type) {
324   return IsStruct(type) ? type.struct_def->minalign : SizeOf(type.base_type);
325 }
326 
327 struct EnumVal {
EnumValEnumVal328   EnumVal(const std::string &_name, int64_t _val) : name(_name), value(_val) {}
EnumValEnumVal329   EnumVal(){};
330 
331   Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
332 
333   bool Deserialize(const Parser &parser, const reflection::EnumVal *val);
334 
335   std::string name;
336   std::vector<std::string> doc_comment;
337   int64_t value;
338   Type union_type;
339 };
340 
341 struct EnumDef : public Definition {
EnumDefEnumDef342   EnumDef() : is_union(false), uses_multiple_type_instances(false) {}
343 
344   EnumVal *ReverseLookup(int64_t enum_idx, bool skip_union_default = true) {
345     for (auto it = vals.vec.begin() +
346                    static_cast<int>(is_union && skip_union_default);
347          it != vals.vec.end(); ++it) {
348       if ((*it)->value == enum_idx) { return *it; }
349     }
350     return nullptr;
351   }
352 
353   Offset<reflection::Enum> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
354 
355   bool Deserialize(Parser &parser, const reflection::Enum *values);
356 
357   SymbolTable<EnumVal> vals;
358   bool is_union;
359   // Type is a union which uses type aliases where at least one type is
360   // available under two different names.
361   bool uses_multiple_type_instances;
362   Type underlying_type;
363 };
364 
EqualByName(const Type & a,const Type & b)365 inline bool EqualByName(const Type &a, const Type &b) {
366   return a.base_type == b.base_type && a.element == b.element &&
367          (a.struct_def == b.struct_def ||
368           a.struct_def->name == b.struct_def->name) &&
369          (a.enum_def == b.enum_def || a.enum_def->name == b.enum_def->name);
370 }
371 
372 struct RPCCall : public Definition {
373   Offset<reflection::RPCCall> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
374 
375   bool Deserialize(Parser &parser, const reflection::RPCCall *call);
376 
377   StructDef *request, *response;
378 };
379 
380 struct ServiceDef : public Definition {
381   Offset<reflection::Service> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
382   bool Deserialize(Parser &parser, const reflection::Service *service);
383 
384   SymbolTable<RPCCall> calls;
385 };
386 
387 // Container of options that may apply to any of the source/text generators.
388 struct IDLOptions {
389   bool strict_json;
390   bool skip_js_exports;
391   bool use_goog_js_export_format;
392   bool use_ES6_js_export_format;
393   bool output_default_scalars_in_json;
394   int indent_step;
395   bool output_enum_identifiers;
396   bool prefixed_enums;
397   bool scoped_enums;
398   bool include_dependence_headers;
399   bool mutable_buffer;
400   bool one_file;
401   bool proto_mode;
402   bool proto_oneof_union;
403   bool generate_all;
404   bool skip_unexpected_fields_in_json;
405   bool generate_name_strings;
406   bool generate_object_based_api;
407   bool gen_compare;
408   std::string cpp_object_api_pointer_type;
409   std::string cpp_object_api_string_type;
410   bool gen_nullable;
411   bool gen_generated;
412   std::string object_prefix;
413   std::string object_suffix;
414   bool union_value_namespacing;
415   bool allow_non_utf8;
416   bool natural_utf8;
417   std::string include_prefix;
418   bool keep_include_path;
419   bool binary_schema_comments;
420   bool binary_schema_builtins;
421   bool skip_flatbuffers_import;
422   std::string go_import;
423   std::string go_namespace;
424   bool reexport_ts_modules;
425   bool protobuf_ascii_alike;
426   bool size_prefixed;
427   std::string root_type;
428   bool force_defaults;
429 
430   // Possible options for the more general generator below.
431   enum Language {
432     kJava = 1 << 0,
433     kCSharp = 1 << 1,
434     kGo = 1 << 2,
435     kCpp = 1 << 3,
436     kJs = 1 << 4,
437     kPython = 1 << 5,
438     kPhp = 1 << 6,
439     kJson = 1 << 7,
440     kBinary = 1 << 8,
441     kTs = 1 << 9,
442     kJsonSchema = 1 << 10,
443     kDart = 1 << 11,
444     kLua = 1 << 12,
445     kLobster = 1 << 13,
446     kRust = 1 << 14,
447     kMAX
448   };
449 
450   Language lang;
451 
452   enum MiniReflect { kNone, kTypes, kTypesAndNames };
453 
454   MiniReflect mini_reflect;
455 
456   // The corresponding language bit will be set if a language is included
457   // for code generation.
458   unsigned long lang_to_generate;
459 
460   // If set (default behavior), empty string and vector fields will be set to
461   // nullptr to make the flatbuffer more compact.
462   bool set_empty_to_null;
463 
IDLOptionsIDLOptions464   IDLOptions()
465       : strict_json(false),
466         skip_js_exports(false),
467         use_goog_js_export_format(false),
468         use_ES6_js_export_format(false),
469         output_default_scalars_in_json(false),
470         indent_step(2),
471         output_enum_identifiers(true),
472         prefixed_enums(true),
473         scoped_enums(false),
474         include_dependence_headers(true),
475         mutable_buffer(false),
476         one_file(false),
477         proto_mode(false),
478         proto_oneof_union(false),
479         generate_all(false),
480         skip_unexpected_fields_in_json(false),
481         generate_name_strings(false),
482         generate_object_based_api(false),
483         gen_compare(false),
484         cpp_object_api_pointer_type("std::unique_ptr"),
485         gen_nullable(false),
486         gen_generated(false),
487         object_suffix("T"),
488         union_value_namespacing(true),
489         allow_non_utf8(false),
490         natural_utf8(false),
491         keep_include_path(false),
492         binary_schema_comments(false),
493         binary_schema_builtins(false),
494         skip_flatbuffers_import(false),
495         reexport_ts_modules(true),
496         protobuf_ascii_alike(false),
497         size_prefixed(false),
498         force_defaults(false),
499         lang(IDLOptions::kJava),
500         mini_reflect(IDLOptions::kNone),
501         lang_to_generate(0),
502         set_empty_to_null(true) {}
503 };
504 
505 // This encapsulates where the parser is in the current source file.
506 struct ParserState {
ParserStateParserState507   ParserState()
508       : cursor_(nullptr),
509         line_start_(nullptr),
510         line_(0),
511         token_(-1),
512         attr_is_trivial_ascii_string_(true) {}
513 
514  protected:
ResetStateParserState515   void ResetState(const char *source) {
516     cursor_ = source;
517     line_ = 0;
518     MarkNewLine();
519   }
520 
MarkNewLineParserState521   void MarkNewLine() {
522     line_start_ = cursor_;
523     line_ += 1;
524   }
525 
CursorPositionParserState526   int64_t CursorPosition() const {
527     FLATBUFFERS_ASSERT(cursor_ && line_start_ && cursor_ >= line_start_);
528     return static_cast<int64_t>(cursor_ - line_start_);
529   }
530 
531   const char *cursor_;
532   const char *line_start_;
533   int line_;  // the current line being parsed
534   int token_;
535 
536   // Flag: text in attribute_ is true ASCII string without escape
537   // sequences. Only printable ASCII (without [\t\r\n]).
538   // Used for number-in-string (and base64 string in future).
539   bool attr_is_trivial_ascii_string_;
540   std::string attribute_;
541   std::vector<std::string> doc_comment_;
542 };
543 
544 // A way to make error propagation less error prone by requiring values to be
545 // checked.
546 // Once you create a value of this type you must either:
547 // - Call Check() on it.
548 // - Copy or assign it to another value.
549 // Failure to do so leads to an assert.
550 // This guarantees that this as return value cannot be ignored.
551 class CheckedError {
552  public:
CheckedError(bool error)553   explicit CheckedError(bool error)
554       : is_error_(error), has_been_checked_(false) {}
555 
556   CheckedError &operator=(const CheckedError &other) {
557     is_error_ = other.is_error_;
558     has_been_checked_ = false;
559     other.has_been_checked_ = true;
560     return *this;
561   }
562 
CheckedError(const CheckedError & other)563   CheckedError(const CheckedError &other) {
564     *this = other;  // Use assignment operator.
565   }
566 
~CheckedError()567   ~CheckedError() { FLATBUFFERS_ASSERT(has_been_checked_); }
568 
Check()569   bool Check() {
570     has_been_checked_ = true;
571     return is_error_;
572   }
573 
574  private:
575   bool is_error_;
576   mutable bool has_been_checked_;
577 };
578 
579 // Additionally, in GCC we can get these errors statically, for additional
580 // assurance:
581 // clang-format off
582 #ifdef __GNUC__
583 #define FLATBUFFERS_CHECKED_ERROR CheckedError \
584           __attribute__((warn_unused_result))
585 #else
586 #define FLATBUFFERS_CHECKED_ERROR CheckedError
587 #endif
588 // clang-format on
589 
590 class Parser : public ParserState {
591  public:
592   explicit Parser(const IDLOptions &options = IDLOptions())
current_namespace_(nullptr)593       : current_namespace_(nullptr),
594         empty_namespace_(nullptr),
595         root_struct_def_(nullptr),
596         opts(options),
597         uses_flexbuffers_(false),
598         source_(nullptr),
599         anonymous_counter(0),
600         recurse_protection_counter(0) {
601     if (opts.force_defaults) {
602       builder_.ForceDefaults(true);
603     }
604     // Start out with the empty namespace being current.
605     empty_namespace_ = new Namespace();
606     namespaces_.push_back(empty_namespace_);
607     current_namespace_ = empty_namespace_;
608     known_attributes_["deprecated"] = true;
609     known_attributes_["required"] = true;
610     known_attributes_["key"] = true;
611     known_attributes_["hash"] = true;
612     known_attributes_["id"] = true;
613     known_attributes_["force_align"] = true;
614     known_attributes_["bit_flags"] = true;
615     known_attributes_["original_order"] = true;
616     known_attributes_["nested_flatbuffer"] = true;
617     known_attributes_["csharp_partial"] = true;
618     known_attributes_["streaming"] = true;
619     known_attributes_["idempotent"] = true;
620     known_attributes_["cpp_type"] = true;
621     known_attributes_["cpp_ptr_type"] = true;
622     known_attributes_["cpp_ptr_type_get"] = true;
623     known_attributes_["cpp_str_type"] = true;
624     known_attributes_["native_inline"] = true;
625     known_attributes_["native_custom_alloc"] = true;
626     known_attributes_["native_type"] = true;
627     known_attributes_["native_default"] = true;
628     known_attributes_["flexbuffer"] = true;
629     known_attributes_["private"] = true;
630   }
631 
~Parser()632   ~Parser() {
633     for (auto it = namespaces_.begin(); it != namespaces_.end(); ++it) {
634       delete *it;
635     }
636   }
637 
638   // Parse the string containing either schema or JSON data, which will
639   // populate the SymbolTable's or the FlatBufferBuilder above.
640   // include_paths is used to resolve any include statements, and typically
641   // should at least include the project path (where you loaded source_ from).
642   // include_paths must be nullptr terminated if specified.
643   // If include_paths is nullptr, it will attempt to load from the current
644   // directory.
645   // If the source was loaded from a file and isn't an include file,
646   // supply its name in source_filename.
647   // All paths specified in this call must be in posix format, if you accept
648   // paths from user input, please call PosixPath on them first.
649   bool Parse(const char *_source, const char **include_paths = nullptr,
650              const char *source_filename = nullptr);
651 
652   // Set the root type. May override the one set in the schema.
653   bool SetRootType(const char *name);
654 
655   // Mark all definitions as already having code generated.
656   void MarkGenerated();
657 
658   // Get the files recursively included by the given file. The returned
659   // container will have at least the given file.
660   std::set<std::string> GetIncludedFilesRecursive(
661       const std::string &file_name) const;
662 
663   // Fills builder_ with a binary version of the schema parsed.
664   // See reflection/reflection.fbs
665   void Serialize();
666 
667   // Deserialize a schema buffer
668   bool Deserialize(const uint8_t *buf, const size_t size);
669 
670   // Fills internal structure as if the schema passed had been loaded by parsing
671   // with Parse except that included filenames will not be populated.
672   bool Deserialize(const reflection::Schema* schema);
673 
674   Type* DeserializeType(const reflection::Type* type);
675 
676   // Checks that the schema represented by this parser is a safe evolution
677   // of the schema provided. Returns non-empty error on any problems.
678   std::string ConformTo(const Parser &base);
679 
680   // Similar to Parse(), but now only accepts JSON to be parsed into a
681   // FlexBuffer.
682   bool ParseFlexBuffer(const char *source, const char *source_filename,
683                        flexbuffers::Builder *builder);
684 
685   FLATBUFFERS_CHECKED_ERROR InvalidNumber(const char *number,
686                                           const std::string &msg);
687 
688   StructDef *LookupStruct(const std::string &id) const;
689 
690   std::string UnqualifiedName(std::string fullQualifiedName);
691 
692  private:
693   void Message(const std::string &msg);
694   void Warning(const std::string &msg);
695   FLATBUFFERS_CHECKED_ERROR Error(const std::string &msg);
696   FLATBUFFERS_CHECKED_ERROR ParseHexNum(int nibbles, uint64_t *val);
697   FLATBUFFERS_CHECKED_ERROR Next();
698   FLATBUFFERS_CHECKED_ERROR SkipByteOrderMark();
699   bool Is(int t) const;
700   bool IsIdent(const char *id) const;
701   FLATBUFFERS_CHECKED_ERROR Expect(int t);
702   std::string TokenToStringId(int t) const;
703   EnumDef *LookupEnum(const std::string &id);
704   FLATBUFFERS_CHECKED_ERROR ParseNamespacing(std::string *id,
705                                              std::string *last);
706   FLATBUFFERS_CHECKED_ERROR ParseTypeIdent(Type &type);
707   FLATBUFFERS_CHECKED_ERROR ParseType(Type &type);
708   FLATBUFFERS_CHECKED_ERROR AddField(StructDef &struct_def,
709                                      const std::string &name, const Type &type,
710                                      FieldDef **dest);
711   FLATBUFFERS_CHECKED_ERROR ParseField(StructDef &struct_def);
712   FLATBUFFERS_CHECKED_ERROR ParseString(Value &val);
713   FLATBUFFERS_CHECKED_ERROR ParseComma();
714   FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field,
715                                           size_t parent_fieldn,
716                                           const StructDef *parent_struct_def);
717   template<typename F>
718   FLATBUFFERS_CHECKED_ERROR ParseTableDelimiters(size_t &fieldn,
719                                                  const StructDef *struct_def,
720                                                  F body);
721   FLATBUFFERS_CHECKED_ERROR ParseTable(const StructDef &struct_def,
722                                        std::string *value, uoffset_t *ovalue);
723   void SerializeStruct(const StructDef &struct_def, const Value &val);
724   template<typename F>
725   FLATBUFFERS_CHECKED_ERROR ParseVectorDelimiters(size_t &count, F body);
726   FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue);
727   FLATBUFFERS_CHECKED_ERROR ParseNestedFlatbuffer(Value &val, FieldDef *field,
728                                                   size_t fieldn,
729                                                   const StructDef *parent_struct_def);
730   FLATBUFFERS_CHECKED_ERROR ParseMetaData(SymbolTable<Value> *attributes);
731   FLATBUFFERS_CHECKED_ERROR TryTypedValue(const std::string *name, int dtoken, bool check, Value &e,
732                                           BaseType req, bool *destmatch);
733   FLATBUFFERS_CHECKED_ERROR ParseHash(Value &e, FieldDef* field);
734   FLATBUFFERS_CHECKED_ERROR TokenError();
735   FLATBUFFERS_CHECKED_ERROR ParseSingleValue(const std::string *name, Value &e, bool check_now);
736   FLATBUFFERS_CHECKED_ERROR ParseEnumFromString(Type &type, int64_t *result);
737   StructDef *LookupCreateStruct(const std::string &name,
738                                 bool create_if_new = true,
739                                 bool definition = false);
740   FLATBUFFERS_CHECKED_ERROR ParseEnum(bool is_union, EnumDef **dest);
741   FLATBUFFERS_CHECKED_ERROR ParseNamespace();
742   FLATBUFFERS_CHECKED_ERROR StartStruct(const std::string &name,
743                                         StructDef **dest);
744   FLATBUFFERS_CHECKED_ERROR StartEnum(const std::string &name,
745                                       bool is_union,
746                                       EnumDef **dest);
747   FLATBUFFERS_CHECKED_ERROR ParseDecl();
748   FLATBUFFERS_CHECKED_ERROR ParseService();
749   FLATBUFFERS_CHECKED_ERROR ParseProtoFields(StructDef *struct_def,
750                                              bool isextend, bool inside_oneof);
751   FLATBUFFERS_CHECKED_ERROR ParseProtoOption();
752   FLATBUFFERS_CHECKED_ERROR ParseProtoKey();
753   FLATBUFFERS_CHECKED_ERROR ParseProtoDecl();
754   FLATBUFFERS_CHECKED_ERROR ParseProtoCurliesOrIdent();
755   FLATBUFFERS_CHECKED_ERROR ParseTypeFromProtoType(Type *type);
756   FLATBUFFERS_CHECKED_ERROR SkipAnyJsonValue();
757   FLATBUFFERS_CHECKED_ERROR ParseFlexBufferValue(flexbuffers::Builder *builder);
758   FLATBUFFERS_CHECKED_ERROR StartParseFile(const char *source,
759                                            const char *source_filename);
760   FLATBUFFERS_CHECKED_ERROR ParseRoot(const char *_source,
761                                     const char **include_paths,
762                                     const char *source_filename);
763   FLATBUFFERS_CHECKED_ERROR DoParse(const char *_source,
764                                            const char **include_paths,
765                                            const char *source_filename,
766                                            const char *include_filename);
767   FLATBUFFERS_CHECKED_ERROR CheckClash(std::vector<FieldDef*> &fields,
768                                        StructDef *struct_def,
769                                        const char *suffix,
770                                        BaseType baseType);
771 
772   bool SupportsVectorOfUnions() const;
773   Namespace *UniqueNamespace(Namespace *ns);
774 
775   FLATBUFFERS_CHECKED_ERROR RecurseError();
776   template<typename F> CheckedError Recurse(F f);
777 
778  public:
779   SymbolTable<Type> types_;
780   SymbolTable<StructDef> structs_;
781   SymbolTable<EnumDef> enums_;
782   SymbolTable<ServiceDef> services_;
783   std::vector<Namespace *> namespaces_;
784   Namespace *current_namespace_;
785   Namespace *empty_namespace_;
786   std::string error_;         // User readable error_ if Parse() == false
787 
788   FlatBufferBuilder builder_;  // any data contained in the file
789   StructDef *root_struct_def_;
790   std::string file_identifier_;
791   std::string file_extension_;
792 
793   std::map<std::string, std::string> included_files_;
794   std::map<std::string, std::set<std::string>> files_included_per_file_;
795   std::vector<std::string> native_included_files_;
796 
797   std::map<std::string, bool> known_attributes_;
798 
799   IDLOptions opts;
800   bool uses_flexbuffers_;
801 
802  private:
803   const char *source_;
804 
805   std::string file_being_parsed_;
806 
807   std::vector<std::pair<Value, FieldDef *>> field_stack_;
808 
809   int anonymous_counter;
810   int recurse_protection_counter;
811 };
812 
813 // Utility functions for multiple generators:
814 
815 extern std::string MakeCamel(const std::string &in, bool first = true);
816 
817 // Generate text (JSON) from a given FlatBuffer, and a given Parser
818 // object that has been populated with the corresponding schema.
819 // If ident_step is 0, no indentation will be generated. Additionally,
820 // if it is less than 0, no linefeeds will be generated either.
821 // See idl_gen_text.cpp.
822 // strict_json adds "quotes" around field names if true.
823 // If the flatbuffer cannot be encoded in JSON (e.g., it contains non-UTF-8
824 // byte arrays in String values), returns false.
825 extern bool GenerateText(const Parser &parser,
826                          const void *flatbuffer,
827                          std::string *text);
828 extern bool GenerateTextFile(const Parser &parser,
829                              const std::string &path,
830                              const std::string &file_name);
831 
832 // Generate binary files from a given FlatBuffer, and a given Parser
833 // object that has been populated with the corresponding schema.
834 // See idl_gen_general.cpp.
835 extern bool GenerateBinary(const Parser &parser,
836                            const std::string &path,
837                            const std::string &file_name);
838 
839 // Generate a C++ header from the definitions in the Parser object.
840 // See idl_gen_cpp.
841 extern bool GenerateCPP(const Parser &parser,
842                         const std::string &path,
843                         const std::string &file_name);
844 
845 extern bool GenerateDart(const Parser &parser,
846                          const std::string &path,
847                          const std::string &file_name);
848 
849 // Generate JavaScript or TypeScript code from the definitions in the Parser object.
850 // See idl_gen_js.
851 extern bool GenerateJSTS(const Parser &parser,
852                        const std::string &path,
853                        const std::string &file_name);
854 
855 // Generate Go files from the definitions in the Parser object.
856 // See idl_gen_go.cpp.
857 extern bool GenerateGo(const Parser &parser,
858                        const std::string &path,
859                        const std::string &file_name);
860 
861 // Generate Php code from the definitions in the Parser object.
862 // See idl_gen_php.
863 extern bool GeneratePhp(const Parser &parser,
864                         const std::string &path,
865                         const std::string &file_name);
866 
867 // Generate Python files from the definitions in the Parser object.
868 // See idl_gen_python.cpp.
869 extern bool GeneratePython(const Parser &parser,
870                            const std::string &path,
871                            const std::string &file_name);
872 
873 // Generate Lobster files from the definitions in the Parser object.
874 // See idl_gen_lobster.cpp.
875 extern bool GenerateLobster(const Parser &parser,
876                             const std::string &path,
877                             const std::string &file_name);
878 
879 // Generate Lua files from the definitions in the Parser object.
880 // See idl_gen_lua.cpp.
881 extern bool GenerateLua(const Parser &parser,
882                       const std::string &path,
883                       const std::string &file_name);
884 
885 // Generate Rust files from the definitions in the Parser object.
886 // See idl_gen_rust.cpp.
887 extern bool GenerateRust(const Parser &parser,
888                          const std::string &path,
889                          const std::string &file_name);
890 
891 // Generate Json schema file
892 // See idl_gen_json_schema.cpp.
893 extern bool GenerateJsonSchema(const Parser &parser,
894                            const std::string &path,
895                            const std::string &file_name);
896 
897 // Generate Java/C#/.. files from the definitions in the Parser object.
898 // See idl_gen_general.cpp.
899 extern bool GenerateGeneral(const Parser &parser,
900                             const std::string &path,
901                             const std::string &file_name);
902 
903 // Generate a schema file from the internal representation, useful after
904 // parsing a .proto schema.
905 extern std::string GenerateFBS(const Parser &parser,
906                                const std::string &file_name);
907 extern bool GenerateFBS(const Parser &parser,
908                         const std::string &path,
909                         const std::string &file_name);
910 
911 // Generate a make rule for the generated JavaScript or TypeScript code.
912 // See idl_gen_js.cpp.
913 extern std::string JSTSMakeRule(const Parser &parser,
914                               const std::string &path,
915                               const std::string &file_name);
916 
917 // Generate a make rule for the generated C++ header.
918 // See idl_gen_cpp.cpp.
919 extern std::string CPPMakeRule(const Parser &parser,
920                                const std::string &path,
921                                const std::string &file_name);
922 
923 // Generate a make rule for the generated Dart code
924 // see idl_gen_dart.cpp
925 extern std::string DartMakeRule(const Parser &parser,
926                                 const std::string &path,
927                                 const std::string &file_name);
928 
929 // Generate a make rule for the generated Rust code.
930 // See idl_gen_rust.cpp.
931 extern std::string RustMakeRule(const Parser &parser,
932                                 const std::string &path,
933                                 const std::string &file_name);
934 
935 // Generate a make rule for the generated Java/C#/... files.
936 // See idl_gen_general.cpp.
937 extern std::string GeneralMakeRule(const Parser &parser,
938                                    const std::string &path,
939                                    const std::string &file_name);
940 
941 // Generate a make rule for the generated text (JSON) files.
942 // See idl_gen_text.cpp.
943 extern std::string TextMakeRule(const Parser &parser,
944                                 const std::string &path,
945                                 const std::string &file_names);
946 
947 // Generate a make rule for the generated binary files.
948 // See idl_gen_general.cpp.
949 extern std::string BinaryMakeRule(const Parser &parser,
950                                   const std::string &path,
951                                   const std::string &file_name);
952 
953 // Generate GRPC Cpp interfaces.
954 // See idl_gen_grpc.cpp.
955 bool GenerateCppGRPC(const Parser &parser,
956                      const std::string &path,
957                      const std::string &file_name);
958 
959 // Generate GRPC Go interfaces.
960 // See idl_gen_grpc.cpp.
961 bool GenerateGoGRPC(const Parser &parser,
962                     const std::string &path,
963                     const std::string &file_name);
964 
965 // Generate GRPC Java classes.
966 // See idl_gen_grpc.cpp
967 bool GenerateJavaGRPC(const Parser &parser,
968                       const std::string &path,
969                       const std::string &file_name);
970 
971 }  // namespace flatbuffers
972 
973 #endif  // FLATBUFFERS_IDL_H_
974