2 * Copyright (c) 2023 Samsung Electronics Co., Ltd. All Rights Reserved
3 * Copyright 2014 Google Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #ifndef FLATBUFFERS_IDL_H_
19 #define FLATBUFFERS_IDL_H_
25 #include "flatbuffers/base.h"
26 #include "flatbuffers/flatbuffers.h"
27 #include "flatbuffers/flexbuffers.h"
28 #include "flatbuffers/hash.h"
29 #include "flatbuffers/reflection.h"
31 #if !defined(FLATBUFFERS_CPP98_STL)
33 #endif // !defined(FLATBUFFERS_CPP98_STL)
35 // This file defines the data types representing a parsed IDL (Interface
36 // Definition Language) / schema file.
38 // Limits maximum depth of nested objects.
39 // Prevents stack overflow while parse scheme, or json, or flexbuffer.
40 #if !defined(FLATBUFFERS_MAX_PARSING_DEPTH)
41 #define FLATBUFFERS_MAX_PARSING_DEPTH 64
47 // The order of these matters for Is*() functions below.
48 // Additionally, Parser::ParseType assumes bool..string is a contiguous range
51 #define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
52 TD(NONE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) \
53 TD(UTYPE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) /* begin scalar/int */ \
54 TD(BOOL, "bool", uint8_t, boolean,bool, bool, bool, bool, Boolean, Bool) \
55 TD(CHAR, "byte", int8_t, byte, int8, sbyte, int8, i8, Byte, Int8) \
56 TD(UCHAR, "ubyte", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) \
57 TD(SHORT, "short", int16_t, short, int16, short, int16, i16, Short, Int16) \
58 TD(USHORT, "ushort", uint16_t, short, uint16, ushort, uint16, u16, UShort, UInt16) \
59 TD(INT, "int", int32_t, int, int32, int, int32, i32, Int, Int32) \
60 TD(UINT, "uint", uint32_t, int, uint32, uint, uint32, u32, UInt, UInt32) \
61 TD(LONG, "long", int64_t, long, int64, long, int64, i64, Long, Int64) \
62 TD(ULONG, "ulong", uint64_t, long, uint64, ulong, uint64, u64, ULong, UInt64) /* end int */ \
63 TD(FLOAT, "float", float, float, float32, float, float32, f32, Float, Float32) /* begin float */ \
64 TD(DOUBLE, "double", double, double, float64, double, float64, f64, Double, Double) /* end float/scalar */
65 #define FLATBUFFERS_GEN_TYPES_POINTER(TD) \
66 TD(STRING, "string", Offset<void>, int, int, StringOffset, int, unused, Int, Offset<String>) \
67 TD(VECTOR, "", Offset<void>, int, int, VectorOffset, int, unused, Int, Offset<UOffset>) \
68 TD(STRUCT, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>) \
69 TD(UNION, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>)
70 #define FLATBUFFERS_GEN_TYPE_ARRAY(TD) \
71 TD(ARRAY, "", int, int, int, int, int, unused, Int, Offset<UOffset>)
74 // - FlatBuffers schema type.
83 // using these macros, we can now write code dealing with types just once, e.g.
87 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
89 case BASE_TYPE_ ## ENUM: \
90 // do something specific to CTYPE here
91 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
96 // If not all FLATBUFFERS_GEN_() arguments are necessary for implementation
97 // of FLATBUFFERS_TD, you can use a variadic macro (with __VA_ARGS__ if needed).
98 // In the above example, only CTYPE is used to generate the code, it can be rewritten:
102 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
103 case BASE_TYPE_ ## ENUM: \
104 // do something specific to CTYPE here
105 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
106 #undef FLATBUFFERS_TD
110 #define FLATBUFFERS_GEN_TYPES(TD) \
111 FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
112 FLATBUFFERS_GEN_TYPES_POINTER(TD) \
113 FLATBUFFERS_GEN_TYPE_ARRAY(TD)
115 // Create an enum for all the types above.
117 __extension__ // Stop GCC complaining about trailing comma with -Wpendantic.
120 #define FLATBUFFERS_TD(ENUM, ...) \
122 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
123 #undef FLATBUFFERS_TD
126 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
127 static_assert(sizeof(CTYPE) <= sizeof(largest_scalar_t), \
128 "define largest_scalar_t as " #CTYPE);
129 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
130 #undef FLATBUFFERS_TD
132 inline bool IsScalar (BaseType t) { return t >= BASE_TYPE_UTYPE &&
133 t <= BASE_TYPE_DOUBLE; }
134 inline bool IsInteger(BaseType t) { return t >= BASE_TYPE_UTYPE &&
135 t <= BASE_TYPE_ULONG; }
136 inline bool IsFloat (BaseType t) { return t == BASE_TYPE_FLOAT ||
137 t == BASE_TYPE_DOUBLE; }
138 inline bool IsLong (BaseType t) { return t == BASE_TYPE_LONG ||
139 t == BASE_TYPE_ULONG; }
140 inline bool IsBool (BaseType t) { return t == BASE_TYPE_BOOL; }
141 inline bool IsOneByte(BaseType t) { return t >= BASE_TYPE_UTYPE &&
142 t <= BASE_TYPE_UCHAR; }
144 inline bool IsUnsigned(BaseType t) {
145 return (t == BASE_TYPE_UTYPE) || (t == BASE_TYPE_UCHAR) ||
146 (t == BASE_TYPE_USHORT) || (t == BASE_TYPE_UINT) ||
147 (t == BASE_TYPE_ULONG);
152 extern const char *const kTypeNames[];
153 extern const char kTypeSizes[];
155 inline size_t SizeOf(BaseType t) { return kTypeSizes[t]; }
161 // Represents any type in the IDL, which is a combination of the BaseType
162 // and additional information for vectors/structs_.
165 explicit Type(BaseType _base_type = BASE_TYPE_NONE, StructDef *_sd = nullptr,
166 EnumDef *_ed = nullptr, uint16_t _fixed_length = 0)
167 : base_type(_base_type), element(BASE_TYPE_NONE), struct_def(_sd), enum_def(_ed),
168 fixed_length(_fixed_length)
172 bool operator==(const Type &o)
174 return base_type == o.base_type && element == o.element && struct_def == o.struct_def &&
175 enum_def == o.enum_def;
178 Type VectorType() const { return Type(element, struct_def, enum_def, fixed_length); }
180 Offset<reflection::Type> Serialize(FlatBufferBuilder *builder) const;
182 bool Deserialize(const Parser &parser, const reflection::Type *type);
185 BaseType element; // only set if t == BASE_TYPE_VECTOR
186 StructDef *struct_def; // only set if t or element == BASE_TYPE_STRUCT
187 EnumDef *enum_def; // set if t == BASE_TYPE_UNION / BASE_TYPE_UTYPE,
188 // or for an integral type derived from an enum.
189 uint16_t fixed_length; // only set if t == BASE_TYPE_ARRAY
192 // Represents a parsed scalar value, it's type, and field offset.
195 Value() : constant("0"), offset(static_cast<voffset_t>(~(static_cast<voffset_t>(0U)))) {}
197 std::string constant;
201 // Helper class that retains the original order of a set of identifiers and
202 // also provides quick lookup.
203 template <typename T> class SymbolTable
208 for (auto it = vec.begin(); it != vec.end(); ++it)
214 bool Add(const std::string &name, T *e)
216 vector_emplace_back(&vec, e);
217 auto it = dict.find(name);
218 if (it != dict.end())
224 void Move(const std::string &oldname, const std::string &newname)
226 auto it = dict.find(oldname);
227 if (it != dict.end())
229 auto obj = it->second;
235 FLATBUFFERS_ASSERT(false);
239 T *Lookup(const std::string &name) const
241 auto it = dict.find(name);
242 return it == dict.end() ? nullptr : it->second;
246 std::map<std::string, T *> dict; // quick lookup
247 std::vector<T *> vec; // Used to iterate in order of insertion
250 // A name space, as set in the schema.
253 Namespace() : from_table(0) {}
255 // Given a (potentially unqualified) name, return the "fully qualified" name
256 // which has a full namespaced descriptor.
257 // With max_components you can request less than the number of components
258 // the current namespace has.
259 std::string GetFullyQualifiedName(const std::string &name, size_t max_components = 1000) const;
261 std::vector<std::string> components;
262 size_t from_table; // Part of the namespace corresponds to a message/table.
265 inline bool operator<(const Namespace &a, const Namespace &b)
267 size_t min_size = std::min(a.components.size(), b.components.size());
268 for (size_t i = 0; i < min_size; ++i)
270 if (a.components[i] != b.components[i])
271 return a.components[i] < b.components[i];
273 return a.components.size() < b.components.size();
276 // Base class for all definition types (fields, structs_, enums_).
280 : generated(false), defined_namespace(nullptr), serialized_location(0), index(-1), refcount(1)
284 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
285 SerializeAttributes(FlatBufferBuilder *builder, const Parser &parser) const;
287 bool DeserializeAttributes(Parser &parser, const Vector<Offset<reflection::KeyValue>> *attrs);
291 std::vector<std::string> doc_comment;
292 SymbolTable<Value> attributes;
293 bool generated; // did we already output code for this definition?
294 Namespace *defined_namespace; // Where it was defined.
296 // For use with Serialize()
297 uoffset_t serialized_location;
298 int index; // Inside the vector it is stored.
302 struct FieldDef : public Definition
305 : deprecated(false), key(false), shared(false), native_inline(false), flexbuffer(false),
306 presence(kDefault), nested_flatbuffer(NULL), padding(0)
310 Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id,
311 const Parser &parser) const;
313 bool Deserialize(Parser &parser, const reflection::Field *field);
315 bool IsScalarOptional() const { return IsScalar(value.type.base_type) && IsOptional(); }
316 bool IsOptional() const { return presence == kOptional; }
317 bool IsRequired() const { return presence == kRequired; }
318 bool IsDefault() const { return presence == kDefault; }
321 bool deprecated; // Field is allowed to be present in old data, but can't be.
322 // written in new data nor accessed in new code.
323 bool key; // Field functions as a key for creating sorted vectors.
324 bool shared; // Field will be using string pooling (i.e. CreateSharedString)
325 // as default serialization behavior if field is a string.
326 bool native_inline; // Field will be defined inline (instead of as a pointer)
327 // for native tables if field is a struct.
328 bool flexbuffer; // This field contains FlexBuffer data.
332 // Field must always be present.
334 // Non-presence should be signalled to and controlled by users.
336 // Non-presence is hidden from users.
337 // Implementations may omit writing default values.
340 Presence static MakeFieldPresence(bool optional, bool required)
342 FLATBUFFERS_ASSERT(!(required && optional));
344 return required ? FieldDef::kRequired
345 : optional ? FieldDef::kOptional
346 : FieldDef::kDefault;
351 StructDef *nested_flatbuffer; // This field contains nested FlatBuffer data.
352 size_t padding; // Bytes to always pad after this field.
355 struct StructDef : public Definition
358 : fixed(false), predecl(true), sortbysize(true), has_key(false), minalign(1), bytesize(0)
362 void PadLastField(size_t min_align)
364 auto padding = PaddingBytes(bytesize, min_align);
366 if (fields.vec.size())
367 fields.vec.back()->padding = padding;
370 Offset<reflection::Object> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
372 bool Deserialize(Parser &parser, const reflection::Object *object);
374 SymbolTable<FieldDef> fields;
376 bool fixed; // If it's struct, not a table.
377 bool predecl; // If it's used before it was defined.
378 bool sortbysize; // Whether fields come in the declaration or size order.
379 bool has_key; // It has a key field.
380 size_t minalign; // What the whole object needs to be aligned to.
381 size_t bytesize; // Size if fixed.
383 flatbuffers::unique_ptr<std::string> original_location;
387 struct EnumValBuilder;
391 Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
393 bool Deserialize(const Parser &parser, const reflection::EnumVal *val);
395 uint64_t GetAsUInt64() const { return static_cast<uint64_t>(value); }
396 int64_t GetAsInt64() const { return value; }
397 bool IsZero() const { return 0 == value; }
398 bool IsNonZero() const { return !IsZero(); }
401 std::vector<std::string> doc_comment;
406 friend EnumValBuilder;
407 friend bool operator==(const EnumVal &lhs, const EnumVal &rhs);
409 EnumVal(const std::string &_name, int64_t _val) : name(_name), value(_val) {}
410 EnumVal() : value(0) {}
415 struct EnumDef : public Definition
417 EnumDef() : is_union(false), uses_multiple_type_instances(false) {}
419 Offset<reflection::Enum> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
421 bool Deserialize(Parser &parser, const reflection::Enum *values);
423 template <typename T> void ChangeEnumValue(EnumVal *ev, T new_val);
425 void RemoveDuplicates();
427 std::string AllFlags() const;
428 const EnumVal *MinValue() const;
429 const EnumVal *MaxValue() const;
430 // Returns the number of integer steps from v1 to v2.
431 uint64_t Distance(const EnumVal *v1, const EnumVal *v2) const;
432 // Returns the number of integer steps from Min to Max.
433 uint64_t Distance() const { return Distance(MinValue(), MaxValue()); }
435 EnumVal *ReverseLookup(int64_t enum_idx, bool skip_union_default = false) const;
436 EnumVal *FindByValue(const std::string &constant) const;
438 std::string ToString(const EnumVal &ev) const
440 return IsUInt64() ? NumToString(ev.GetAsUInt64()) : NumToString(ev.GetAsInt64());
443 size_t size() const { return vals.vec.size(); }
445 const std::vector<EnumVal *> &Vals() const { return vals.vec; }
447 const EnumVal *Lookup(const std::string &enum_name) const { return vals.Lookup(enum_name); }
450 // Type is a union which uses type aliases where at least one type is
451 // available under two different names.
452 bool uses_multiple_type_instances;
453 Type underlying_type;
456 bool IsUInt64() const { return (BASE_TYPE_ULONG == underlying_type.base_type); }
458 friend EnumValBuilder;
459 SymbolTable<EnumVal> vals;
462 inline bool IsString(const Type &type) { return type.base_type == BASE_TYPE_STRING; }
464 inline bool IsStruct(const Type &type)
466 return type.base_type == BASE_TYPE_STRUCT && type.struct_def->fixed;
469 inline bool IsUnion(const Type &type)
471 return type.enum_def != nullptr && type.enum_def->is_union;
474 inline bool IsVector(const Type &type) { return type.base_type == BASE_TYPE_VECTOR; }
476 inline bool IsArray(const Type &type) { return type.base_type == BASE_TYPE_ARRAY; }
478 inline bool IsSeries(const Type &type) { return IsVector(type) || IsArray(type); }
480 inline bool IsEnum(const Type &type)
482 return type.enum_def != nullptr && IsInteger(type.base_type);
485 inline size_t InlineSize(const Type &type)
487 return IsStruct(type) ? type.struct_def->bytesize
488 : (IsArray(type) ? InlineSize(type.VectorType()) * type.fixed_length
489 : SizeOf(type.base_type));
492 inline size_t InlineAlignment(const Type &type)
496 return type.struct_def->minalign;
498 else if (IsArray(type))
500 return IsStruct(type.VectorType()) ? type.struct_def->minalign : SizeOf(type.element);
504 return SizeOf(type.base_type);
507 inline bool operator==(const EnumVal &lhs, const EnumVal &rhs) { return lhs.value == rhs.value; }
508 inline bool operator!=(const EnumVal &lhs, const EnumVal &rhs) { return !(lhs == rhs); }
510 inline bool EqualByName(const Type &a, const Type &b)
512 return a.base_type == b.base_type && a.element == b.element &&
513 (a.struct_def == b.struct_def || a.struct_def->name == b.struct_def->name) &&
514 (a.enum_def == b.enum_def || a.enum_def->name == b.enum_def->name);
517 struct RPCCall : public Definition
519 Offset<reflection::RPCCall> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
521 bool Deserialize(Parser &parser, const reflection::RPCCall *call);
523 StructDef *request, *response;
526 struct ServiceDef : public Definition
528 Offset<reflection::Service> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
529 bool Deserialize(Parser &parser, const reflection::Service *service);
531 SymbolTable<RPCCall> calls;
534 // Container of options that may apply to any of the source/text generators.
538 // Use flexbuffers instead for binary and text generation
539 bool use_flexbuffers;
541 bool output_default_scalars_in_json;
543 bool output_enum_identifiers;
546 bool include_dependence_headers;
550 bool proto_oneof_union;
552 bool skip_unexpected_fields_in_json;
553 bool generate_name_strings;
554 bool generate_object_based_api;
556 std::string cpp_object_api_pointer_type;
557 std::string cpp_object_api_string_type;
558 bool cpp_object_api_string_flexible_constructor;
559 bool cpp_direct_copy;
561 bool java_checkerframework;
563 std::string object_prefix;
564 std::string object_suffix;
565 bool union_value_namespacing;
568 std::string include_prefix;
569 bool keep_include_path;
570 bool binary_schema_comments;
571 bool binary_schema_builtins;
572 bool binary_schema_gen_embed;
573 std::string go_import;
574 std::string go_namespace;
575 bool protobuf_ascii_alike;
577 std::string root_type;
579 bool java_primitive_has_method;
580 bool cs_gen_json_serializer;
581 std::vector<std::string> cpp_includes;
583 bool cpp_static_reflection;
584 std::string proto_namespace_suffix;
585 std::string filename_suffix;
586 std::string filename_extension;
589 // Possible options for the more general generator below.
601 kJsonSchema = 1 << 10,
620 MiniReflect mini_reflect;
622 // If set, require all fields in a table to be explicitly numbered.
623 bool require_explicit_ids;
625 // The corresponding language bit will be set if a language is included
626 // for code generation.
627 unsigned long lang_to_generate;
629 // If set (default behavior), empty string fields will be set to nullptr to
630 // make the flatbuffer more compact.
631 bool set_empty_strings_to_null;
633 // If set (default behavior), empty vector fields will be set to nullptr to
634 // make the flatbuffer more compact.
635 bool set_empty_vectors_to_null;
638 : gen_jvmstatic(false), use_flexbuffers(false), strict_json(false),
639 output_default_scalars_in_json(false), indent_step(2), output_enum_identifiers(true),
640 prefixed_enums(true), scoped_enums(false), include_dependence_headers(true),
641 mutable_buffer(false), one_file(false), proto_mode(false), proto_oneof_union(false),
642 generate_all(false), skip_unexpected_fields_in_json(false), generate_name_strings(false),
643 generate_object_based_api(false), gen_compare(false),
644 cpp_object_api_pointer_type("std::unique_ptr"),
645 cpp_object_api_string_flexible_constructor(false), cpp_direct_copy(true), gen_nullable(false),
646 java_checkerframework(false), gen_generated(false), object_suffix("T"),
647 union_value_namespacing(true), allow_non_utf8(false), natural_utf8(false),
648 keep_include_path(false), binary_schema_comments(false), binary_schema_builtins(false),
649 binary_schema_gen_embed(false), protobuf_ascii_alike(false), size_prefixed(false),
650 force_defaults(false), java_primitive_has_method(false), cs_gen_json_serializer(false),
651 cpp_static_reflection(false), filename_suffix("_generated"), filename_extension(),
652 no_warnings(false), lang(IDLOptions::kJava), mini_reflect(IDLOptions::kNone),
653 require_explicit_ids(false), lang_to_generate(0), set_empty_strings_to_null(true),
654 set_empty_vectors_to_null(true)
659 // This encapsulates where the parser is in the current source file.
663 : cursor_(nullptr), line_start_(nullptr), line_(0), token_(-1),
664 attr_is_trivial_ascii_string_(true)
669 void ResetState(const char *source)
678 line_start_ = cursor_;
682 int64_t CursorPosition() const
684 FLATBUFFERS_ASSERT(cursor_ && line_start_ && cursor_ >= line_start_);
685 return static_cast<int64_t>(cursor_ - line_start_);
689 const char *line_start_;
690 int line_; // the current line being parsed
693 // Flag: text in attribute_ is true ASCII string without escape
694 // sequences. Only printable ASCII (without [\t\r\n]).
695 // Used for number-in-string (and base64 string in future).
696 bool attr_is_trivial_ascii_string_;
697 std::string attribute_;
698 std::vector<std::string> doc_comment_;
701 // A way to make error propagation less error prone by requiring values to be
703 // Once you create a value of this type you must either:
704 // - Call Check() on it.
705 // - Copy or assign it to another value.
706 // Failure to do so leads to an assert.
707 // This guarantees that this as return value cannot be ignored.
711 explicit CheckedError(bool error) : is_error_(error), has_been_checked_(false) {}
713 CheckedError &operator=(const CheckedError &other)
715 is_error_ = other.is_error_;
716 has_been_checked_ = false;
717 other.has_been_checked_ = true;
721 CheckedError(const CheckedError &other)
723 *this = other; // Use assignment operator.
726 ~CheckedError() { FLATBUFFERS_ASSERT(has_been_checked_); }
730 has_been_checked_ = true;
736 mutable bool has_been_checked_;
739 // Additionally, in GCC we can get these errors statically, for additional
743 #define FLATBUFFERS_CHECKED_ERROR CheckedError \
744 __attribute__((warn_unused_result))
746 #define FLATBUFFERS_CHECKED_ERROR CheckedError
750 class Parser : public ParserState
753 explicit Parser(const IDLOptions &options = IDLOptions())
754 : current_namespace_(nullptr), empty_namespace_(nullptr),
755 flex_builder_(256, flexbuffers::BUILDER_FLAG_SHARE_ALL), root_struct_def_(nullptr),
756 opts(options), uses_flexbuffers_(false), advanced_features_(0), source_(nullptr),
757 anonymous_counter_(0), parse_depth_counter_(0)
759 if (opts.force_defaults)
761 builder_.ForceDefaults(true);
763 // Start out with the empty namespace being current.
764 empty_namespace_ = new Namespace();
765 namespaces_.push_back(empty_namespace_);
766 current_namespace_ = empty_namespace_;
767 known_attributes_["deprecated"] = true;
768 known_attributes_["required"] = true;
769 known_attributes_["key"] = true;
770 known_attributes_["shared"] = true;
771 known_attributes_["hash"] = true;
772 known_attributes_["id"] = true;
773 known_attributes_["force_align"] = true;
774 known_attributes_["bit_flags"] = true;
775 known_attributes_["original_order"] = true;
776 known_attributes_["nested_flatbuffer"] = true;
777 known_attributes_["csharp_partial"] = true;
778 known_attributes_["streaming"] = true;
779 known_attributes_["idempotent"] = true;
780 known_attributes_["cpp_type"] = true;
781 known_attributes_["cpp_ptr_type"] = true;
782 known_attributes_["cpp_ptr_type_get"] = true;
783 known_attributes_["cpp_str_type"] = true;
784 known_attributes_["cpp_str_flex_ctor"] = true;
785 known_attributes_["native_inline"] = true;
786 known_attributes_["native_custom_alloc"] = true;
787 known_attributes_["native_type"] = true;
788 known_attributes_["native_type_pack_name"] = true;
789 known_attributes_["native_default"] = true;
790 known_attributes_["flexbuffer"] = true;
791 known_attributes_["private"] = true;
796 for (auto it = namespaces_.begin(); it != namespaces_.end(); ++it)
802 // Parse the string containing either schema or JSON data, which will
803 // populate the SymbolTable's or the FlatBufferBuilder above.
804 // include_paths is used to resolve any include statements, and typically
805 // should at least include the project path (where you loaded source_ from).
806 // include_paths must be nullptr terminated if specified.
807 // If include_paths is nullptr, it will attempt to load from the current
809 // If the source was loaded from a file and isn't an include file,
810 // supply its name in source_filename.
811 // All paths specified in this call must be in posix format, if you accept
812 // paths from user input, please call PosixPath on them first.
813 bool Parse(const char *_source, const char **include_paths = nullptr,
814 const char *source_filename = nullptr);
816 bool ParseJson(const char *json, const char *json_filename = nullptr);
818 // Set the root type. May override the one set in the schema.
819 bool SetRootType(const char *name);
821 // Mark all definitions as already having code generated.
822 void MarkGenerated();
824 // Get the files recursively included by the given file. The returned
825 // container will have at least the given file.
826 std::set<std::string> GetIncludedFilesRecursive(const std::string &file_name) const;
828 // Fills builder_ with a binary version of the schema parsed.
829 // See reflection/reflection.fbs
832 // Deserialize a schema buffer
833 bool Deserialize(const uint8_t *buf, const size_t size);
835 // Fills internal structure as if the schema passed had been loaded by parsing
836 // with Parse except that included filenames will not be populated.
837 bool Deserialize(const reflection::Schema *schema);
839 Type *DeserializeType(const reflection::Type *type);
841 // Checks that the schema represented by this parser is a safe evolution
842 // of the schema provided. Returns non-empty error on any problems.
843 std::string ConformTo(const Parser &base);
845 // Similar to Parse(), but now only accepts JSON to be parsed into a
847 bool ParseFlexBuffer(const char *source, const char *source_filename,
848 flexbuffers::Builder *builder);
850 StructDef *LookupStruct(const std::string &id) const;
851 StructDef *LookupStructThruParentNamespaces(const std::string &id) const;
853 std::string UnqualifiedName(const std::string &fullQualifiedName);
855 FLATBUFFERS_CHECKED_ERROR Error(const std::string &msg);
857 // @brief Verify that any of 'opts.lang_to_generate' supports Optional scalars
859 // @param opts Options used to parce a schema and generate code.
860 static bool SupportsOptionalScalars(const flatbuffers::IDLOptions &opts);
863 class ParseDepthGuard;
865 void Message(const std::string &msg);
866 void Warning(const std::string &msg);
867 FLATBUFFERS_CHECKED_ERROR ParseHexNum(int nibbles, uint64_t *val);
868 FLATBUFFERS_CHECKED_ERROR Next();
869 FLATBUFFERS_CHECKED_ERROR SkipByteOrderMark();
870 bool Is(int t) const;
871 bool IsIdent(const char *id) const;
872 FLATBUFFERS_CHECKED_ERROR Expect(int t);
873 std::string TokenToStringId(int t) const;
874 EnumDef *LookupEnum(const std::string &id);
875 FLATBUFFERS_CHECKED_ERROR ParseNamespacing(std::string *id, std::string *last);
876 FLATBUFFERS_CHECKED_ERROR ParseTypeIdent(Type &type);
877 FLATBUFFERS_CHECKED_ERROR ParseType(Type &type);
878 FLATBUFFERS_CHECKED_ERROR AddField(StructDef &struct_def, const std::string &name,
879 const Type &type, FieldDef **dest);
880 FLATBUFFERS_CHECKED_ERROR ParseField(StructDef &struct_def);
881 FLATBUFFERS_CHECKED_ERROR ParseString(Value &val, bool use_string_pooling);
882 FLATBUFFERS_CHECKED_ERROR ParseComma();
883 FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field, size_t parent_fieldn,
884 const StructDef *parent_struct_def, uoffset_t count,
885 bool inside_vector = false);
886 template <typename F>
887 FLATBUFFERS_CHECKED_ERROR ParseTableDelimiters(size_t &fieldn, const StructDef *struct_def,
889 FLATBUFFERS_CHECKED_ERROR ParseTable(const StructDef &struct_def, std::string *value,
891 void SerializeStruct(const StructDef &struct_def, const Value &val);
892 void SerializeStruct(FlatBufferBuilder &builder, const StructDef &struct_def, const Value &val);
893 template <typename F> FLATBUFFERS_CHECKED_ERROR ParseVectorDelimiters(uoffset_t &count, F body);
894 FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue, FieldDef *field,
896 FLATBUFFERS_CHECKED_ERROR ParseArray(Value &array);
897 FLATBUFFERS_CHECKED_ERROR ParseNestedFlatbuffer(Value &val, FieldDef *field, size_t fieldn,
898 const StructDef *parent_struct_def);
899 FLATBUFFERS_CHECKED_ERROR ParseMetaData(SymbolTable<Value> *attributes);
900 FLATBUFFERS_CHECKED_ERROR TryTypedValue(const std::string *name, int dtoken, bool check, Value &e,
901 BaseType req, bool *destmatch);
902 FLATBUFFERS_CHECKED_ERROR ParseHash(Value &e, FieldDef *field);
903 FLATBUFFERS_CHECKED_ERROR TokenError();
904 FLATBUFFERS_CHECKED_ERROR ParseSingleValue(const std::string *name, Value &e, bool check_now);
905 FLATBUFFERS_CHECKED_ERROR ParseFunction(const std::string *name, Value &e);
906 FLATBUFFERS_CHECKED_ERROR ParseEnumFromString(const Type &type, std::string *result);
907 StructDef *LookupCreateStruct(const std::string &name, bool create_if_new = true,
908 bool definition = false);
909 FLATBUFFERS_CHECKED_ERROR ParseEnum(bool is_union, EnumDef **dest);
910 FLATBUFFERS_CHECKED_ERROR ParseNamespace();
911 FLATBUFFERS_CHECKED_ERROR StartStruct(const std::string &name, StructDef **dest);
912 FLATBUFFERS_CHECKED_ERROR StartEnum(const std::string &name, bool is_union, EnumDef **dest);
913 FLATBUFFERS_CHECKED_ERROR ParseDecl();
914 FLATBUFFERS_CHECKED_ERROR ParseService();
915 FLATBUFFERS_CHECKED_ERROR ParseProtoFields(StructDef *struct_def, bool isextend,
917 FLATBUFFERS_CHECKED_ERROR ParseProtoOption();
918 FLATBUFFERS_CHECKED_ERROR ParseProtoKey();
919 FLATBUFFERS_CHECKED_ERROR ParseProtoDecl();
920 FLATBUFFERS_CHECKED_ERROR ParseProtoCurliesOrIdent();
921 FLATBUFFERS_CHECKED_ERROR ParseTypeFromProtoType(Type *type);
922 FLATBUFFERS_CHECKED_ERROR SkipAnyJsonValue();
923 FLATBUFFERS_CHECKED_ERROR ParseFlexBufferNumericConstant(flexbuffers::Builder *builder);
924 FLATBUFFERS_CHECKED_ERROR ParseFlexBufferValue(flexbuffers::Builder *builder);
925 FLATBUFFERS_CHECKED_ERROR StartParseFile(const char *source, const char *source_filename);
926 FLATBUFFERS_CHECKED_ERROR ParseRoot(const char *_source, const char **include_paths,
927 const char *source_filename);
928 FLATBUFFERS_CHECKED_ERROR DoParse(const char *_source, const char **include_paths,
929 const char *source_filename, const char *include_filename);
930 FLATBUFFERS_CHECKED_ERROR DoParseJson();
931 FLATBUFFERS_CHECKED_ERROR CheckClash(std::vector<FieldDef *> &fields, StructDef *struct_def,
932 const char *suffix, BaseType baseType);
933 FLATBUFFERS_CHECKED_ERROR ParseAlignAttribute(const std::string &align_constant, size_t min_align,
936 bool SupportsAdvancedUnionFeatures() const;
937 bool SupportsAdvancedArrayFeatures() const;
938 bool SupportsOptionalScalars() const;
939 bool SupportsDefaultVectorsAndStrings() const;
940 Namespace *UniqueNamespace(Namespace *ns);
942 FLATBUFFERS_CHECKED_ERROR RecurseError();
943 template <typename F> CheckedError Recurse(F f);
946 SymbolTable<Type> types_;
947 SymbolTable<StructDef> structs_;
948 SymbolTable<EnumDef> enums_;
949 SymbolTable<ServiceDef> services_;
950 std::vector<Namespace *> namespaces_;
951 Namespace *current_namespace_;
952 Namespace *empty_namespace_;
953 std::string error_; // User readable error_ if Parse() == false
955 FlatBufferBuilder builder_; // any data contained in the file
956 flexbuffers::Builder flex_builder_;
957 flexbuffers::Reference flex_root_;
958 StructDef *root_struct_def_;
959 std::string file_identifier_;
960 std::string file_extension_;
962 std::map<uint64_t, std::string> included_files_;
963 std::map<std::string, std::set<std::string>> files_included_per_file_;
964 std::vector<std::string> native_included_files_;
966 std::map<std::string, bool> known_attributes_;
969 bool uses_flexbuffers_;
971 uint64_t advanced_features_;
976 std::string file_being_parsed_;
978 std::vector<std::pair<Value, FieldDef *>> field_stack_;
980 int anonymous_counter_;
981 int parse_depth_counter_; // stack-overflow guard
984 // Utility functions for multiple generators:
986 extern std::string MakeCamel(const std::string &in, bool first = true);
988 extern std::string MakeScreamingCamel(const std::string &in);
990 // Generate text (JSON) from a given FlatBuffer, and a given Parser
991 // object that has been populated with the corresponding schema.
992 // If ident_step is 0, no indentation will be generated. Additionally,
993 // if it is less than 0, no linefeeds will be generated either.
994 // See idl_gen_text.cpp.
995 // strict_json adds "quotes" around field names if true.
996 // If the flatbuffer cannot be encoded in JSON (e.g., it contains non-UTF-8
997 // byte arrays in String values), returns false.
998 extern bool GenerateTextFromTable(const Parser &parser, const void *table,
999 const std::string &tablename, std::string *text);
1000 extern bool GenerateText(const Parser &parser, const void *flatbuffer, std::string *text);
1001 extern bool GenerateTextFile(const Parser &parser, const std::string &path,
1002 const std::string &file_name);
1004 // Generate Json schema to string
1005 // See idl_gen_json_schema.cpp.
1006 extern bool GenerateJsonSchema(const Parser &parser, std::string *json);
1008 // Generate binary files from a given FlatBuffer, and a given Parser
1009 // object that has been populated with the corresponding schema.
1010 // See code_generators.cpp.
1011 extern bool GenerateBinary(const Parser &parser, const std::string &path,
1012 const std::string &file_name);
1014 // Generate a C++ header from the definitions in the Parser object.
1016 extern bool GenerateCPP(const Parser &parser, const std::string &path,
1017 const std::string &file_name);
1019 // Generate C# files from the definitions in the Parser object.
1020 // See idl_gen_csharp.cpp.
1021 extern bool GenerateCSharp(const Parser &parser, const std::string &path,
1022 const std::string &file_name);
1024 extern bool GenerateDart(const Parser &parser, const std::string &path,
1025 const std::string &file_name);
1027 // Generate Java files from the definitions in the Parser object.
1028 // See idl_gen_java.cpp.
1029 extern bool GenerateJava(const Parser &parser, const std::string &path,
1030 const std::string &file_name);
1032 // Generate JavaScript or TypeScript code from the definitions in the Parser
1033 // object. See idl_gen_js.
1034 extern bool GenerateTS(const Parser &parser, const std::string &path, const std::string &file_name);
1036 // Generate Go files from the definitions in the Parser object.
1037 // See idl_gen_go.cpp.
1038 extern bool GenerateGo(const Parser &parser, const std::string &path, const std::string &file_name);
1040 // Generate Php code from the definitions in the Parser object.
1042 extern bool GeneratePhp(const Parser &parser, const std::string &path,
1043 const std::string &file_name);
1045 // Generate Python files from the definitions in the Parser object.
1046 // See idl_gen_python.cpp.
1047 extern bool GeneratePython(const Parser &parser, const std::string &path,
1048 const std::string &file_name);
1050 // Generate Lobster files from the definitions in the Parser object.
1051 // See idl_gen_lobster.cpp.
1052 extern bool GenerateLobster(const Parser &parser, const std::string &path,
1053 const std::string &file_name);
1055 // Generate Lua files from the definitions in the Parser object.
1056 // See idl_gen_lua.cpp.
1057 extern bool GenerateLua(const Parser &parser, const std::string &path,
1058 const std::string &file_name);
1060 // Generate Rust files from the definitions in the Parser object.
1061 // See idl_gen_rust.cpp.
1062 extern bool GenerateRust(const Parser &parser, const std::string &path,
1063 const std::string &file_name);
1065 // Generate Json schema file
1066 // See idl_gen_json_schema.cpp.
1067 extern bool GenerateJsonSchema(const Parser &parser, const std::string &path,
1068 const std::string &file_name);
1070 extern bool GenerateKotlin(const Parser &parser, const std::string &path,
1071 const std::string &file_name);
1073 // Generate Swift classes.
1074 // See idl_gen_swift.cpp
1075 extern bool GenerateSwift(const Parser &parser, const std::string &path,
1076 const std::string &file_name);
1078 // Generate a schema file from the internal representation, useful after
1079 // parsing a .proto schema.
1080 extern std::string GenerateFBS(const Parser &parser, const std::string &file_name);
1081 extern bool GenerateFBS(const Parser &parser, const std::string &path,
1082 const std::string &file_name);
1084 // Generate a make rule for the generated TypeScript code.
1085 // See idl_gen_ts.cpp.
1086 extern std::string TSMakeRule(const Parser &parser, const std::string &path,
1087 const std::string &file_name);
1089 // Generate a make rule for the generated C++ header.
1090 // See idl_gen_cpp.cpp.
1091 extern std::string CPPMakeRule(const Parser &parser, const std::string &path,
1092 const std::string &file_name);
1094 // Generate a make rule for the generated Dart code
1095 // see idl_gen_dart.cpp
1096 extern std::string DartMakeRule(const Parser &parser, const std::string &path,
1097 const std::string &file_name);
1099 // Generate a make rule for the generated Rust code.
1100 // See idl_gen_rust.cpp.
1101 extern std::string RustMakeRule(const Parser &parser, const std::string &path,
1102 const std::string &file_name);
1104 // Generate a make rule for generated Java or C# files.
1105 // See code_generators.cpp.
1106 extern std::string JavaCSharpMakeRule(const Parser &parser, const std::string &path,
1107 const std::string &file_name);
1109 // Generate a make rule for the generated text (JSON) files.
1110 // See idl_gen_text.cpp.
1111 extern std::string TextMakeRule(const Parser &parser, const std::string &path,
1112 const std::string &file_names);
1114 // Generate a make rule for the generated binary files.
1115 // See code_generators.cpp.
1116 extern std::string BinaryMakeRule(const Parser &parser, const std::string &path,
1117 const std::string &file_name);
1119 // Generate GRPC Cpp interfaces.
1120 // See idl_gen_grpc.cpp.
1121 bool GenerateCppGRPC(const Parser &parser, const std::string &path, const std::string &file_name);
1123 // Generate GRPC Go interfaces.
1124 // See idl_gen_grpc.cpp.
1125 bool GenerateGoGRPC(const Parser &parser, const std::string &path, const std::string &file_name);
1127 // Generate GRPC Java classes.
1128 // See idl_gen_grpc.cpp
1129 bool GenerateJavaGRPC(const Parser &parser, const std::string &path, const std::string &file_name);
1131 // Generate GRPC Python interfaces.
1132 // See idl_gen_grpc.cpp.
1133 bool GeneratePythonGRPC(const Parser &parser, const std::string &path,
1134 const std::string &file_name);
1136 // Generate GRPC Swift interfaces.
1137 // See idl_gen_grpc.cpp.
1138 extern bool GenerateSwiftGRPC(const Parser &parser, const std::string &path,
1139 const std::string &file_name);
1141 extern bool GenerateTSGRPC(const Parser &parser, const std::string &path,
1142 const std::string &file_name);
1143 } // namespace flatbuffers
1145 #endif // FLATBUFFERS_IDL_H_