blob: 260061f13208a8dc47d923b87319a7c1e8090206 [file] [log] [blame]
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001/*
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
James Kuszmaul8e62b022022-03-22 09:33:25 -070020#include <functional>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070021#include <map>
22#include <memory>
23#include <stack>
24
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"
30
Austin Schuhe89fa2d2019-08-14 20:24:23 -070031// This file defines the data types representing a parsed IDL (Interface
32// Definition Language) / schema file.
33
34// Limits maximum depth of nested objects.
James Kuszmaul8e62b022022-03-22 09:33:25 -070035// Prevents stack overflow while parse scheme, or json, or flexbuffer.
Austin Schuhe89fa2d2019-08-14 20:24:23 -070036#if !defined(FLATBUFFERS_MAX_PARSING_DEPTH)
37# define FLATBUFFERS_MAX_PARSING_DEPTH 64
38#endif
39
40namespace flatbuffers {
41
42// The order of these matters for Is*() functions below.
43// Additionally, Parser::ParseType assumes bool..string is a contiguous range
44// of type tokens.
45// clang-format off
46#define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
Austin Schuh272c6132020-11-14 16:37:52 -080047 TD(NONE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) \
48 TD(UTYPE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) /* begin scalar/int */ \
49 TD(BOOL, "bool", uint8_t, boolean,bool, bool, bool, bool, Boolean, Bool) \
50 TD(CHAR, "byte", int8_t, byte, int8, sbyte, int8, i8, Byte, Int8) \
51 TD(UCHAR, "ubyte", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) \
52 TD(SHORT, "short", int16_t, short, int16, short, int16, i16, Short, Int16) \
53 TD(USHORT, "ushort", uint16_t, short, uint16, ushort, uint16, u16, UShort, UInt16) \
54 TD(INT, "int", int32_t, int, int32, int, int32, i32, Int, Int32) \
55 TD(UINT, "uint", uint32_t, int, uint32, uint, uint32, u32, UInt, UInt32) \
56 TD(LONG, "long", int64_t, long, int64, long, int64, i64, Long, Int64) \
57 TD(ULONG, "ulong", uint64_t, long, uint64, ulong, uint64, u64, ULong, UInt64) /* end int */ \
58 TD(FLOAT, "float", float, float, float32, float, float32, f32, Float, Float32) /* begin float */ \
59 TD(DOUBLE, "double", double, double, float64, double, float64, f64, Double, Double) /* end float/scalar */
Austin Schuhe89fa2d2019-08-14 20:24:23 -070060#define FLATBUFFERS_GEN_TYPES_POINTER(TD) \
Austin Schuh272c6132020-11-14 16:37:52 -080061 TD(STRING, "string", Offset<void>, int, int, StringOffset, int, unused, Int, Offset<String>) \
62 TD(VECTOR, "", Offset<void>, int, int, VectorOffset, int, unused, Int, Offset<UOffset>) \
63 TD(STRUCT, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>) \
64 TD(UNION, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>)
Austin Schuhe89fa2d2019-08-14 20:24:23 -070065#define FLATBUFFERS_GEN_TYPE_ARRAY(TD) \
Austin Schuh272c6132020-11-14 16:37:52 -080066 TD(ARRAY, "", int, int, int, int, int, unused, Int, Offset<UOffset>)
Austin Schuhe89fa2d2019-08-14 20:24:23 -070067// The fields are:
68// - enum
69// - FlatBuffers schema type.
70// - C++ type.
71// - Java type.
72// - Go type.
73// - C# / .Net type.
74// - Python type.
Austin Schuhe89fa2d2019-08-14 20:24:23 -070075// - Kotlin type.
James Kuszmaul8e62b022022-03-22 09:33:25 -070076// - Rust type.
Austin Schuhe89fa2d2019-08-14 20:24:23 -070077
78// using these macros, we can now write code dealing with types just once, e.g.
79
80/*
81switch (type) {
82 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
83 RTYPE, KTYPE) \
84 case BASE_TYPE_ ## ENUM: \
85 // do something specific to CTYPE here
86 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
87 #undef FLATBUFFERS_TD
88}
89*/
90
Austin Schuh272c6132020-11-14 16:37:52 -080091// If not all FLATBUFFERS_GEN_() arguments are necessary for implementation
92// of FLATBUFFERS_TD, you can use a variadic macro (with __VA_ARGS__ if needed).
93// In the above example, only CTYPE is used to generate the code, it can be rewritten:
94
95/*
96switch (type) {
97 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
98 case BASE_TYPE_ ## ENUM: \
99 // do something specific to CTYPE here
100 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
101 #undef FLATBUFFERS_TD
102}
103*/
104
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700105#define FLATBUFFERS_GEN_TYPES(TD) \
106 FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
107 FLATBUFFERS_GEN_TYPES_POINTER(TD) \
108 FLATBUFFERS_GEN_TYPE_ARRAY(TD)
109
110// Create an enum for all the types above.
111#ifdef __GNUC__
112__extension__ // Stop GCC complaining about trailing comma with -Wpendantic.
113#endif
114enum BaseType {
Austin Schuh272c6132020-11-14 16:37:52 -0800115 #define FLATBUFFERS_TD(ENUM, ...) \
116 BASE_TYPE_ ## ENUM,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700117 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
118 #undef FLATBUFFERS_TD
119};
120
Austin Schuh272c6132020-11-14 16:37:52 -0800121#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
122 static_assert(sizeof(CTYPE) <= sizeof(largest_scalar_t), \
123 "define largest_scalar_t as " #CTYPE);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700124 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
125#undef FLATBUFFERS_TD
126
127inline bool IsScalar (BaseType t) { return t >= BASE_TYPE_UTYPE &&
128 t <= BASE_TYPE_DOUBLE; }
129inline bool IsInteger(BaseType t) { return t >= BASE_TYPE_UTYPE &&
130 t <= BASE_TYPE_ULONG; }
131inline bool IsFloat (BaseType t) { return t == BASE_TYPE_FLOAT ||
132 t == BASE_TYPE_DOUBLE; }
133inline bool IsLong (BaseType t) { return t == BASE_TYPE_LONG ||
134 t == BASE_TYPE_ULONG; }
135inline bool IsBool (BaseType t) { return t == BASE_TYPE_BOOL; }
136inline bool IsOneByte(BaseType t) { return t >= BASE_TYPE_UTYPE &&
137 t <= BASE_TYPE_UCHAR; }
138
139inline bool IsUnsigned(BaseType t) {
140 return (t == BASE_TYPE_UTYPE) || (t == BASE_TYPE_UCHAR) ||
141 (t == BASE_TYPE_USHORT) || (t == BASE_TYPE_UINT) ||
142 (t == BASE_TYPE_ULONG);
143}
144
145// clang-format on
146
147extern const char *const kTypeNames[];
148extern const char kTypeSizes[];
149
150inline size_t SizeOf(BaseType t) { return kTypeSizes[t]; }
151
152struct StructDef;
153struct EnumDef;
154class Parser;
155
156// Represents any type in the IDL, which is a combination of the BaseType
157// and additional information for vectors/structs_.
158struct Type {
159 explicit Type(BaseType _base_type = BASE_TYPE_NONE, StructDef *_sd = nullptr,
160 EnumDef *_ed = nullptr, uint16_t _fixed_length = 0)
161 : base_type(_base_type),
162 element(BASE_TYPE_NONE),
163 struct_def(_sd),
164 enum_def(_ed),
165 fixed_length(_fixed_length) {}
166
167 bool operator==(const Type &o) {
168 return base_type == o.base_type && element == o.element &&
169 struct_def == o.struct_def && enum_def == o.enum_def;
170 }
171
172 Type VectorType() const {
173 return Type(element, struct_def, enum_def, fixed_length);
174 }
175
176 Offset<reflection::Type> Serialize(FlatBufferBuilder *builder) const;
177
178 bool Deserialize(const Parser &parser, const reflection::Type *type);
179
180 BaseType base_type;
181 BaseType element; // only set if t == BASE_TYPE_VECTOR
182 StructDef *struct_def; // only set if t or element == BASE_TYPE_STRUCT
183 EnumDef *enum_def; // set if t == BASE_TYPE_UNION / BASE_TYPE_UTYPE,
184 // or for an integral type derived from an enum.
185 uint16_t fixed_length; // only set if t == BASE_TYPE_ARRAY
186};
187
188// Represents a parsed scalar value, it's type, and field offset.
189struct Value {
190 Value()
191 : constant("0"),
192 offset(static_cast<voffset_t>(~(static_cast<voffset_t>(0U)))) {}
193 Type type;
194 std::string constant;
195 voffset_t offset;
196};
197
198// Helper class that retains the original order of a set of identifiers and
199// also provides quick lookup.
200template<typename T> class SymbolTable {
201 public:
202 ~SymbolTable() {
203 for (auto it = vec.begin(); it != vec.end(); ++it) { delete *it; }
204 }
205
206 bool Add(const std::string &name, T *e) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700207 vec.emplace_back(e);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700208 auto it = dict.find(name);
209 if (it != dict.end()) return true;
210 dict[name] = e;
211 return false;
212 }
213
214 void Move(const std::string &oldname, const std::string &newname) {
215 auto it = dict.find(oldname);
216 if (it != dict.end()) {
217 auto obj = it->second;
218 dict.erase(it);
219 dict[newname] = obj;
220 } else {
221 FLATBUFFERS_ASSERT(false);
222 }
223 }
224
225 T *Lookup(const std::string &name) const {
226 auto it = dict.find(name);
227 return it == dict.end() ? nullptr : it->second;
228 }
229
230 public:
231 std::map<std::string, T *> dict; // quick lookup
232 std::vector<T *> vec; // Used to iterate in order of insertion
233};
234
235// A name space, as set in the schema.
236struct Namespace {
237 Namespace() : from_table(0) {}
238
Austin Schuh272c6132020-11-14 16:37:52 -0800239 // Given a (potentially unqualified) name, return the "fully qualified" name
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700240 // which has a full namespaced descriptor.
241 // With max_components you can request less than the number of components
242 // the current namespace has.
243 std::string GetFullyQualifiedName(const std::string &name,
244 size_t max_components = 1000) const;
245
246 std::vector<std::string> components;
247 size_t from_table; // Part of the namespace corresponds to a message/table.
248};
249
250inline bool operator<(const Namespace &a, const Namespace &b) {
251 size_t min_size = std::min(a.components.size(), b.components.size());
252 for (size_t i = 0; i < min_size; ++i) {
253 if (a.components[i] != b.components[i])
254 return a.components[i] < b.components[i];
255 }
256 return a.components.size() < b.components.size();
257}
258
259// Base class for all definition types (fields, structs_, enums_).
260struct Definition {
261 Definition()
262 : generated(false),
263 defined_namespace(nullptr),
264 serialized_location(0),
265 index(-1),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700266 refcount(1),
267 declaration_file(nullptr) {}
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700268
269 flatbuffers::Offset<
270 flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
271 SerializeAttributes(FlatBufferBuilder *builder, const Parser &parser) const;
272
273 bool DeserializeAttributes(Parser &parser,
274 const Vector<Offset<reflection::KeyValue>> *attrs);
275
276 std::string name;
277 std::string file;
278 std::vector<std::string> doc_comment;
279 SymbolTable<Value> attributes;
280 bool generated; // did we already output code for this definition?
281 Namespace *defined_namespace; // Where it was defined.
282
283 // For use with Serialize()
284 uoffset_t serialized_location;
285 int index; // Inside the vector it is stored.
286 int refcount;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700287 const std::string *declaration_file;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700288};
289
290struct FieldDef : public Definition {
291 FieldDef()
292 : deprecated(false),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700293 key(false),
294 shared(false),
295 native_inline(false),
296 flexbuffer(false),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700297 presence(kDefault),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700298 nested_flatbuffer(NULL),
299 padding(0) {}
300
301 Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id,
302 const Parser &parser) const;
303
304 bool Deserialize(Parser &parser, const reflection::Field *field);
305
Austin Schuh272c6132020-11-14 16:37:52 -0800306 bool IsScalarOptional() const {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700307 return IsScalar(value.type.base_type) && IsOptional();
Austin Schuh272c6132020-11-14 16:37:52 -0800308 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700309 bool IsOptional() const { return presence == kOptional; }
310 bool IsRequired() const { return presence == kRequired; }
311 bool IsDefault() const { return presence == kDefault; }
Austin Schuh272c6132020-11-14 16:37:52 -0800312
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700313 Value value;
314 bool deprecated; // Field is allowed to be present in old data, but can't be.
315 // written in new data nor accessed in new code.
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700316 bool key; // Field functions as a key for creating sorted vectors.
317 bool shared; // Field will be using string pooling (i.e. CreateSharedString)
318 // as default serialization behavior if field is a string.
319 bool native_inline; // Field will be defined inline (instead of as a pointer)
320 // for native tables if field is a struct.
321 bool flexbuffer; // This field contains FlexBuffer data.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700322
323 enum Presence {
324 // Field must always be present.
325 kRequired,
326 // Non-presence should be signalled to and controlled by users.
327 kOptional,
328 // Non-presence is hidden from users.
329 // Implementations may omit writing default values.
330 kDefault,
331 };
332 Presence static MakeFieldPresence(bool optional, bool required) {
333 FLATBUFFERS_ASSERT(!(required && optional));
334 // clang-format off
335 return required ? FieldDef::kRequired
336 : optional ? FieldDef::kOptional
337 : FieldDef::kDefault;
338 // clang-format on
339 }
340 Presence presence;
341
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700342 StructDef *nested_flatbuffer; // This field contains nested FlatBuffer data.
343 size_t padding; // Bytes to always pad after this field.
344};
345
346struct StructDef : public Definition {
347 StructDef()
348 : fixed(false),
349 predecl(true),
350 sortbysize(true),
351 has_key(false),
352 minalign(1),
353 bytesize(0) {}
354
355 void PadLastField(size_t min_align) {
356 auto padding = PaddingBytes(bytesize, min_align);
357 bytesize += padding;
358 if (fields.vec.size()) fields.vec.back()->padding = padding;
359 }
360
361 Offset<reflection::Object> Serialize(FlatBufferBuilder *builder,
362 const Parser &parser) const;
363
364 bool Deserialize(Parser &parser, const reflection::Object *object);
365
366 SymbolTable<FieldDef> fields;
367
368 bool fixed; // If it's struct, not a table.
369 bool predecl; // If it's used before it was defined.
370 bool sortbysize; // Whether fields come in the declaration or size order.
371 bool has_key; // It has a key field.
372 size_t minalign; // What the whole object needs to be aligned to.
373 size_t bytesize; // Size if fixed.
374
375 flatbuffers::unique_ptr<std::string> original_location;
376};
377
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700378struct EnumDef;
379struct EnumValBuilder;
380
381struct EnumVal {
Austin Schuh272c6132020-11-14 16:37:52 -0800382 Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder,
383 const Parser &parser) const;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700384
385 bool Deserialize(const Parser &parser, const reflection::EnumVal *val);
386
387 uint64_t GetAsUInt64() const { return static_cast<uint64_t>(value); }
388 int64_t GetAsInt64() const { return value; }
389 bool IsZero() const { return 0 == value; }
390 bool IsNonZero() const { return !IsZero(); }
391
392 std::string name;
393 std::vector<std::string> doc_comment;
394 Type union_type;
395
396 private:
397 friend EnumDef;
398 friend EnumValBuilder;
399 friend bool operator==(const EnumVal &lhs, const EnumVal &rhs);
400
401 EnumVal(const std::string &_name, int64_t _val) : name(_name), value(_val) {}
402 EnumVal() : value(0) {}
403
404 int64_t value;
405};
406
407struct EnumDef : public Definition {
408 EnumDef() : is_union(false), uses_multiple_type_instances(false) {}
409
410 Offset<reflection::Enum> Serialize(FlatBufferBuilder *builder,
411 const Parser &parser) const;
412
413 bool Deserialize(Parser &parser, const reflection::Enum *values);
414
415 template<typename T> void ChangeEnumValue(EnumVal *ev, T new_val);
416 void SortByValue();
417 void RemoveDuplicates();
418
419 std::string AllFlags() const;
420 const EnumVal *MinValue() const;
421 const EnumVal *MaxValue() const;
422 // Returns the number of integer steps from v1 to v2.
423 uint64_t Distance(const EnumVal *v1, const EnumVal *v2) const;
424 // Returns the number of integer steps from Min to Max.
425 uint64_t Distance() const { return Distance(MinValue(), MaxValue()); }
426
427 EnumVal *ReverseLookup(int64_t enum_idx,
428 bool skip_union_default = false) const;
429 EnumVal *FindByValue(const std::string &constant) const;
430
431 std::string ToString(const EnumVal &ev) const {
432 return IsUInt64() ? NumToString(ev.GetAsUInt64())
433 : NumToString(ev.GetAsInt64());
434 }
435
436 size_t size() const { return vals.vec.size(); }
437
Austin Schuh272c6132020-11-14 16:37:52 -0800438 const std::vector<EnumVal *> &Vals() const { return vals.vec; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700439
440 const EnumVal *Lookup(const std::string &enum_name) const {
441 return vals.Lookup(enum_name);
442 }
443
444 bool is_union;
445 // Type is a union which uses type aliases where at least one type is
446 // available under two different names.
447 bool uses_multiple_type_instances;
448 Type underlying_type;
449
450 private:
451 bool IsUInt64() const {
452 return (BASE_TYPE_ULONG == underlying_type.base_type);
453 }
454
455 friend EnumValBuilder;
456 SymbolTable<EnumVal> vals;
457};
458
Austin Schuh272c6132020-11-14 16:37:52 -0800459inline bool IsString(const Type &type) {
460 return type.base_type == BASE_TYPE_STRING;
461}
462
463inline bool IsStruct(const Type &type) {
464 return type.base_type == BASE_TYPE_STRUCT && type.struct_def->fixed;
465}
466
467inline bool IsUnion(const Type &type) {
468 return type.enum_def != nullptr && type.enum_def->is_union;
469}
470
James Kuszmaul8e62b022022-03-22 09:33:25 -0700471inline bool IsUnionType(const Type &type) {
472 return IsUnion(type) && IsInteger(type.base_type);
473}
474
Austin Schuh272c6132020-11-14 16:37:52 -0800475inline bool IsVector(const Type &type) {
476 return type.base_type == BASE_TYPE_VECTOR;
477}
478
479inline bool IsArray(const Type &type) {
480 return type.base_type == BASE_TYPE_ARRAY;
481}
482
483inline bool IsSeries(const Type &type) {
484 return IsVector(type) || IsArray(type);
485}
486
487inline bool IsEnum(const Type &type) {
488 return type.enum_def != nullptr && IsInteger(type.base_type);
489}
490
491inline size_t InlineSize(const Type &type) {
492 return IsStruct(type)
493 ? type.struct_def->bytesize
494 : (IsArray(type)
495 ? InlineSize(type.VectorType()) * type.fixed_length
496 : SizeOf(type.base_type));
497}
498
499inline size_t InlineAlignment(const Type &type) {
500 if (IsStruct(type)) {
501 return type.struct_def->minalign;
502 } else if (IsArray(type)) {
503 return IsStruct(type.VectorType()) ? type.struct_def->minalign
504 : SizeOf(type.element);
505 } else {
506 return SizeOf(type.base_type);
507 }
508}
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700509inline bool operator==(const EnumVal &lhs, const EnumVal &rhs) {
510 return lhs.value == rhs.value;
511}
512inline bool operator!=(const EnumVal &lhs, const EnumVal &rhs) {
513 return !(lhs == rhs);
514}
515
516inline bool EqualByName(const Type &a, const Type &b) {
517 return a.base_type == b.base_type && a.element == b.element &&
518 (a.struct_def == b.struct_def ||
519 a.struct_def->name == b.struct_def->name) &&
520 (a.enum_def == b.enum_def || a.enum_def->name == b.enum_def->name);
521}
522
523struct RPCCall : public Definition {
Austin Schuh272c6132020-11-14 16:37:52 -0800524 Offset<reflection::RPCCall> Serialize(FlatBufferBuilder *builder,
525 const Parser &parser) const;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700526
527 bool Deserialize(Parser &parser, const reflection::RPCCall *call);
528
529 StructDef *request, *response;
530};
531
532struct ServiceDef : public Definition {
Austin Schuh272c6132020-11-14 16:37:52 -0800533 Offset<reflection::Service> Serialize(FlatBufferBuilder *builder,
534 const Parser &parser) const;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700535 bool Deserialize(Parser &parser, const reflection::Service *service);
536
537 SymbolTable<RPCCall> calls;
538};
539
540// Container of options that may apply to any of the source/text generators.
541struct IDLOptions {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700542 // field case style options for C++
543 enum CaseStyle { CaseStyle_Unchanged = 0, CaseStyle_Upper, CaseStyle_Lower };
544
Austin Schuh272c6132020-11-14 16:37:52 -0800545 bool gen_jvmstatic;
546 // Use flexbuffers instead for binary and text generation
547 bool use_flexbuffers;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700548 bool strict_json;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700549 bool output_default_scalars_in_json;
550 int indent_step;
551 bool output_enum_identifiers;
552 bool prefixed_enums;
553 bool scoped_enums;
554 bool include_dependence_headers;
555 bool mutable_buffer;
556 bool one_file;
557 bool proto_mode;
558 bool proto_oneof_union;
559 bool generate_all;
560 bool skip_unexpected_fields_in_json;
561 bool generate_name_strings;
562 bool generate_object_based_api;
563 bool gen_compare;
564 std::string cpp_object_api_pointer_type;
565 std::string cpp_object_api_string_type;
566 bool cpp_object_api_string_flexible_constructor;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700567 CaseStyle cpp_object_api_field_case_style;
Austin Schuh272c6132020-11-14 16:37:52 -0800568 bool cpp_direct_copy;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700569 bool gen_nullable;
Austin Schuh272c6132020-11-14 16:37:52 -0800570 bool java_checkerframework;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700571 bool gen_generated;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700572 bool gen_json_coders;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700573 std::string object_prefix;
574 std::string object_suffix;
575 bool union_value_namespacing;
576 bool allow_non_utf8;
577 bool natural_utf8;
578 std::string include_prefix;
579 bool keep_include_path;
580 bool binary_schema_comments;
581 bool binary_schema_builtins;
Austin Schuh272c6132020-11-14 16:37:52 -0800582 bool binary_schema_gen_embed;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700583 std::string go_import;
584 std::string go_namespace;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700585 bool protobuf_ascii_alike;
586 bool size_prefixed;
587 std::string root_type;
588 bool force_defaults;
Austin Schuh272c6132020-11-14 16:37:52 -0800589 bool java_primitive_has_method;
590 bool cs_gen_json_serializer;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700591 std::vector<std::string> cpp_includes;
Austin Schuh272c6132020-11-14 16:37:52 -0800592 std::string cpp_std;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700593 bool cpp_static_reflection;
Austin Schuh272c6132020-11-14 16:37:52 -0800594 std::string proto_namespace_suffix;
595 std::string filename_suffix;
596 std::string filename_extension;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700597 bool no_warnings;
598 bool warnings_as_errors;
599 std::string project_root;
600 bool cs_global_alias;
601 bool json_nested_flatbuffers;
602 bool json_nested_flexbuffers;
603 bool json_nested_legacy_flatbuffers;
604 bool ts_flat_file;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700605
606 // Possible options for the more general generator below.
607 enum Language {
608 kJava = 1 << 0,
609 kCSharp = 1 << 1,
610 kGo = 1 << 2,
611 kCpp = 1 << 3,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700612 kPython = 1 << 5,
613 kPhp = 1 << 6,
614 kJson = 1 << 7,
615 kBinary = 1 << 8,
616 kTs = 1 << 9,
617 kJsonSchema = 1 << 10,
618 kDart = 1 << 11,
619 kLua = 1 << 12,
620 kLobster = 1 << 13,
621 kRust = 1 << 14,
622 kKotlin = 1 << 15,
Austin Schuh272c6132020-11-14 16:37:52 -0800623 kSwift = 1 << 16,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700624 kMAX
625 };
626
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700627 enum MiniReflect { kNone, kTypes, kTypesAndNames };
628
629 MiniReflect mini_reflect;
630
Austin Schuh58b9b472020-11-25 19:12:44 -0800631 // If set, require all fields in a table to be explicitly numbered.
632 bool require_explicit_ids;
633
James Kuszmaul8e62b022022-03-22 09:33:25 -0700634 // If set, implement serde::Serialize for generated Rust types
635 bool rust_serialize;
636
637 // If set, generate rust types in individual files with a root module file.
638 bool rust_module_root_file;
639
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700640 // The corresponding language bit will be set if a language is included
641 // for code generation.
642 unsigned long lang_to_generate;
643
Austin Schuh272c6132020-11-14 16:37:52 -0800644 // If set (default behavior), empty string fields will be set to nullptr to
645 // make the flatbuffer more compact.
646 bool set_empty_strings_to_null;
647
648 // If set (default behavior), empty vector fields will be set to nullptr to
649 // make the flatbuffer more compact.
650 bool set_empty_vectors_to_null;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700651
652 IDLOptions()
Austin Schuh272c6132020-11-14 16:37:52 -0800653 : gen_jvmstatic(false),
654 use_flexbuffers(false),
655 strict_json(false),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700656 output_default_scalars_in_json(false),
657 indent_step(2),
658 output_enum_identifiers(true),
659 prefixed_enums(true),
660 scoped_enums(false),
661 include_dependence_headers(true),
662 mutable_buffer(false),
663 one_file(false),
664 proto_mode(false),
665 proto_oneof_union(false),
666 generate_all(false),
667 skip_unexpected_fields_in_json(false),
668 generate_name_strings(false),
669 generate_object_based_api(false),
670 gen_compare(false),
671 cpp_object_api_pointer_type("std::unique_ptr"),
672 cpp_object_api_string_flexible_constructor(false),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700673 cpp_object_api_field_case_style(CaseStyle_Unchanged),
Austin Schuh272c6132020-11-14 16:37:52 -0800674 cpp_direct_copy(true),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700675 gen_nullable(false),
Austin Schuh272c6132020-11-14 16:37:52 -0800676 java_checkerframework(false),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700677 gen_generated(false),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700678 gen_json_coders(false),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700679 object_suffix("T"),
680 union_value_namespacing(true),
681 allow_non_utf8(false),
682 natural_utf8(false),
683 keep_include_path(false),
684 binary_schema_comments(false),
685 binary_schema_builtins(false),
Austin Schuh272c6132020-11-14 16:37:52 -0800686 binary_schema_gen_embed(false),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700687 protobuf_ascii_alike(false),
688 size_prefixed(false),
689 force_defaults(false),
Austin Schuh272c6132020-11-14 16:37:52 -0800690 java_primitive_has_method(false),
691 cs_gen_json_serializer(false),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700692 cpp_static_reflection(false),
Austin Schuh272c6132020-11-14 16:37:52 -0800693 filename_suffix("_generated"),
694 filename_extension(),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700695 no_warnings(false),
696 warnings_as_errors(false),
697 project_root(""),
698 cs_global_alias(false),
699 json_nested_flatbuffers(true),
700 json_nested_flexbuffers(true),
701 json_nested_legacy_flatbuffers(false),
702 ts_flat_file(false),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700703 mini_reflect(IDLOptions::kNone),
Austin Schuh58b9b472020-11-25 19:12:44 -0800704 require_explicit_ids(false),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700705 rust_serialize(false),
706 rust_module_root_file(false),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700707 lang_to_generate(0),
Austin Schuh272c6132020-11-14 16:37:52 -0800708 set_empty_strings_to_null(true),
709 set_empty_vectors_to_null(true) {}
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700710};
711
712// This encapsulates where the parser is in the current source file.
713struct ParserState {
714 ParserState()
715 : cursor_(nullptr),
716 line_start_(nullptr),
717 line_(0),
718 token_(-1),
719 attr_is_trivial_ascii_string_(true) {}
720
721 protected:
722 void ResetState(const char *source) {
723 cursor_ = source;
724 line_ = 0;
725 MarkNewLine();
726 }
727
728 void MarkNewLine() {
729 line_start_ = cursor_;
730 line_ += 1;
731 }
732
733 int64_t CursorPosition() const {
734 FLATBUFFERS_ASSERT(cursor_ && line_start_ && cursor_ >= line_start_);
735 return static_cast<int64_t>(cursor_ - line_start_);
736 }
737
738 const char *cursor_;
739 const char *line_start_;
740 int line_; // the current line being parsed
741 int token_;
742
743 // Flag: text in attribute_ is true ASCII string without escape
744 // sequences. Only printable ASCII (without [\t\r\n]).
745 // Used for number-in-string (and base64 string in future).
746 bool attr_is_trivial_ascii_string_;
747 std::string attribute_;
748 std::vector<std::string> doc_comment_;
749};
750
751// A way to make error propagation less error prone by requiring values to be
752// checked.
753// Once you create a value of this type you must either:
754// - Call Check() on it.
755// - Copy or assign it to another value.
756// Failure to do so leads to an assert.
757// This guarantees that this as return value cannot be ignored.
758class CheckedError {
759 public:
760 explicit CheckedError(bool error)
761 : is_error_(error), has_been_checked_(false) {}
762
763 CheckedError &operator=(const CheckedError &other) {
764 is_error_ = other.is_error_;
765 has_been_checked_ = false;
766 other.has_been_checked_ = true;
767 return *this;
768 }
769
770 CheckedError(const CheckedError &other) {
771 *this = other; // Use assignment operator.
772 }
773
774 ~CheckedError() { FLATBUFFERS_ASSERT(has_been_checked_); }
775
776 bool Check() {
777 has_been_checked_ = true;
778 return is_error_;
779 }
780
781 private:
782 bool is_error_;
783 mutable bool has_been_checked_;
784};
785
786// Additionally, in GCC we can get these errors statically, for additional
787// assurance:
788// clang-format off
789#ifdef __GNUC__
790#define FLATBUFFERS_CHECKED_ERROR CheckedError \
791 __attribute__((warn_unused_result))
792#else
793#define FLATBUFFERS_CHECKED_ERROR CheckedError
794#endif
795// clang-format on
796
797class Parser : public ParserState {
798 public:
799 explicit Parser(const IDLOptions &options = IDLOptions())
800 : current_namespace_(nullptr),
801 empty_namespace_(nullptr),
Austin Schuh272c6132020-11-14 16:37:52 -0800802 flex_builder_(256, flexbuffers::BUILDER_FLAG_SHARE_ALL),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700803 root_struct_def_(nullptr),
804 opts(options),
805 uses_flexbuffers_(false),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700806 has_warning_(false),
807 advanced_features_(0),
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700808 source_(nullptr),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700809 anonymous_counter_(0),
810 parse_depth_counter_(0) {
Austin Schuh272c6132020-11-14 16:37:52 -0800811 if (opts.force_defaults) { builder_.ForceDefaults(true); }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700812 // Start out with the empty namespace being current.
813 empty_namespace_ = new Namespace();
814 namespaces_.push_back(empty_namespace_);
815 current_namespace_ = empty_namespace_;
816 known_attributes_["deprecated"] = true;
817 known_attributes_["required"] = true;
818 known_attributes_["key"] = true;
819 known_attributes_["shared"] = true;
820 known_attributes_["hash"] = true;
821 known_attributes_["id"] = true;
822 known_attributes_["force_align"] = true;
823 known_attributes_["bit_flags"] = true;
824 known_attributes_["original_order"] = true;
825 known_attributes_["nested_flatbuffer"] = true;
826 known_attributes_["csharp_partial"] = true;
827 known_attributes_["streaming"] = true;
828 known_attributes_["idempotent"] = true;
829 known_attributes_["cpp_type"] = true;
830 known_attributes_["cpp_ptr_type"] = true;
831 known_attributes_["cpp_ptr_type_get"] = true;
832 known_attributes_["cpp_str_type"] = true;
833 known_attributes_["cpp_str_flex_ctor"] = true;
834 known_attributes_["native_inline"] = true;
835 known_attributes_["native_custom_alloc"] = true;
836 known_attributes_["native_type"] = true;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700837 known_attributes_["native_type_pack_name"] = true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700838 known_attributes_["native_default"] = true;
839 known_attributes_["flexbuffer"] = true;
840 known_attributes_["private"] = true;
841 }
842
843 ~Parser() {
844 for (auto it = namespaces_.begin(); it != namespaces_.end(); ++it) {
845 delete *it;
846 }
847 }
848
849 // Parse the string containing either schema or JSON data, which will
850 // populate the SymbolTable's or the FlatBufferBuilder above.
851 // include_paths is used to resolve any include statements, and typically
852 // should at least include the project path (where you loaded source_ from).
853 // include_paths must be nullptr terminated if specified.
854 // If include_paths is nullptr, it will attempt to load from the current
855 // directory.
856 // If the source was loaded from a file and isn't an include file,
857 // supply its name in source_filename.
858 // All paths specified in this call must be in posix format, if you accept
859 // paths from user input, please call PosixPath on them first.
860 bool Parse(const char *_source, const char **include_paths = nullptr,
861 const char *source_filename = nullptr);
862
Austin Schuh58b9b472020-11-25 19:12:44 -0800863 bool ParseJson(const char *json, const char *json_filename = nullptr);
864
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700865 // Set the root type. May override the one set in the schema.
866 bool SetRootType(const char *name);
867
868 // Mark all definitions as already having code generated.
869 void MarkGenerated();
870
871 // Get the files recursively included by the given file. The returned
872 // container will have at least the given file.
873 std::set<std::string> GetIncludedFilesRecursive(
874 const std::string &file_name) const;
875
876 // Fills builder_ with a binary version of the schema parsed.
877 // See reflection/reflection.fbs
878 void Serialize();
879
880 // Deserialize a schema buffer
881 bool Deserialize(const uint8_t *buf, const size_t size);
882
883 // Fills internal structure as if the schema passed had been loaded by parsing
884 // with Parse except that included filenames will not be populated.
Austin Schuh272c6132020-11-14 16:37:52 -0800885 bool Deserialize(const reflection::Schema *schema);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700886
Austin Schuh272c6132020-11-14 16:37:52 -0800887 Type *DeserializeType(const reflection::Type *type);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700888
889 // Checks that the schema represented by this parser is a safe evolution
890 // of the schema provided. Returns non-empty error on any problems.
891 std::string ConformTo(const Parser &base);
892
893 // Similar to Parse(), but now only accepts JSON to be parsed into a
894 // FlexBuffer.
895 bool ParseFlexBuffer(const char *source, const char *source_filename,
896 flexbuffers::Builder *builder);
897
898 StructDef *LookupStruct(const std::string &id) const;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700899 StructDef *LookupStructThruParentNamespaces(const std::string &id) const;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700900
901 std::string UnqualifiedName(const std::string &fullQualifiedName);
902
903 FLATBUFFERS_CHECKED_ERROR Error(const std::string &msg);
904
Austin Schuh272c6132020-11-14 16:37:52 -0800905 // @brief Verify that any of 'opts.lang_to_generate' supports Optional scalars
906 // in a schema.
907 // @param opts Options used to parce a schema and generate code.
908 static bool SupportsOptionalScalars(const flatbuffers::IDLOptions &opts);
909
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700910 private:
James Kuszmaul8e62b022022-03-22 09:33:25 -0700911 class ParseDepthGuard;
912
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700913 void Message(const std::string &msg);
914 void Warning(const std::string &msg);
915 FLATBUFFERS_CHECKED_ERROR ParseHexNum(int nibbles, uint64_t *val);
916 FLATBUFFERS_CHECKED_ERROR Next();
917 FLATBUFFERS_CHECKED_ERROR SkipByteOrderMark();
918 bool Is(int t) const;
919 bool IsIdent(const char *id) const;
920 FLATBUFFERS_CHECKED_ERROR Expect(int t);
921 std::string TokenToStringId(int t) const;
922 EnumDef *LookupEnum(const std::string &id);
923 FLATBUFFERS_CHECKED_ERROR ParseNamespacing(std::string *id,
924 std::string *last);
925 FLATBUFFERS_CHECKED_ERROR ParseTypeIdent(Type &type);
926 FLATBUFFERS_CHECKED_ERROR ParseType(Type &type);
927 FLATBUFFERS_CHECKED_ERROR AddField(StructDef &struct_def,
928 const std::string &name, const Type &type,
929 FieldDef **dest);
930 FLATBUFFERS_CHECKED_ERROR ParseField(StructDef &struct_def);
Austin Schuh272c6132020-11-14 16:37:52 -0800931 FLATBUFFERS_CHECKED_ERROR ParseString(Value &val, bool use_string_pooling);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700932 FLATBUFFERS_CHECKED_ERROR ParseComma();
933 FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field,
934 size_t parent_fieldn,
935 const StructDef *parent_struct_def,
936 uoffset_t count,
937 bool inside_vector = false);
938 template<typename F>
939 FLATBUFFERS_CHECKED_ERROR ParseTableDelimiters(size_t &fieldn,
940 const StructDef *struct_def,
941 F body);
942 FLATBUFFERS_CHECKED_ERROR ParseTable(const StructDef &struct_def,
943 std::string *value, uoffset_t *ovalue);
944 void SerializeStruct(const StructDef &struct_def, const Value &val);
945 void SerializeStruct(FlatBufferBuilder &builder, const StructDef &struct_def,
946 const Value &val);
947 template<typename F>
948 FLATBUFFERS_CHECKED_ERROR ParseVectorDelimiters(uoffset_t &count, F body);
949 FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue,
950 FieldDef *field, size_t fieldn);
951 FLATBUFFERS_CHECKED_ERROR ParseArray(Value &array);
Austin Schuh272c6132020-11-14 16:37:52 -0800952 FLATBUFFERS_CHECKED_ERROR ParseNestedFlatbuffer(
953 Value &val, FieldDef *field, size_t fieldn,
954 const StructDef *parent_struct_def);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700955 FLATBUFFERS_CHECKED_ERROR ParseMetaData(SymbolTable<Value> *attributes);
Austin Schuh272c6132020-11-14 16:37:52 -0800956 FLATBUFFERS_CHECKED_ERROR TryTypedValue(const std::string *name, int dtoken,
957 bool check, Value &e, BaseType req,
958 bool *destmatch);
959 FLATBUFFERS_CHECKED_ERROR ParseHash(Value &e, FieldDef *field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700960 FLATBUFFERS_CHECKED_ERROR TokenError();
Austin Schuh272c6132020-11-14 16:37:52 -0800961 FLATBUFFERS_CHECKED_ERROR ParseSingleValue(const std::string *name, Value &e,
962 bool check_now);
963 FLATBUFFERS_CHECKED_ERROR ParseFunction(const std::string *name, Value &e);
964 FLATBUFFERS_CHECKED_ERROR ParseEnumFromString(const Type &type,
965 std::string *result);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700966 StructDef *LookupCreateStruct(const std::string &name,
967 bool create_if_new = true,
968 bool definition = false);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700969 FLATBUFFERS_CHECKED_ERROR ParseEnum(bool is_union, EnumDef **dest,
970 const char *filename);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700971 FLATBUFFERS_CHECKED_ERROR ParseNamespace();
972 FLATBUFFERS_CHECKED_ERROR StartStruct(const std::string &name,
973 StructDef **dest);
Austin Schuh272c6132020-11-14 16:37:52 -0800974 FLATBUFFERS_CHECKED_ERROR StartEnum(const std::string &name, bool is_union,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700975 EnumDef **dest);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700976 FLATBUFFERS_CHECKED_ERROR ParseDecl(const char *filename);
977 FLATBUFFERS_CHECKED_ERROR ParseService(const char *filename);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700978 FLATBUFFERS_CHECKED_ERROR ParseProtoFields(StructDef *struct_def,
979 bool isextend, bool inside_oneof);
980 FLATBUFFERS_CHECKED_ERROR ParseProtoOption();
981 FLATBUFFERS_CHECKED_ERROR ParseProtoKey();
982 FLATBUFFERS_CHECKED_ERROR ParseProtoDecl();
983 FLATBUFFERS_CHECKED_ERROR ParseProtoCurliesOrIdent();
984 FLATBUFFERS_CHECKED_ERROR ParseTypeFromProtoType(Type *type);
985 FLATBUFFERS_CHECKED_ERROR SkipAnyJsonValue();
James Kuszmaul8e62b022022-03-22 09:33:25 -0700986 FLATBUFFERS_CHECKED_ERROR ParseFlexBufferNumericConstant(
987 flexbuffers::Builder *builder);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700988 FLATBUFFERS_CHECKED_ERROR ParseFlexBufferValue(flexbuffers::Builder *builder);
989 FLATBUFFERS_CHECKED_ERROR StartParseFile(const char *source,
990 const char *source_filename);
991 FLATBUFFERS_CHECKED_ERROR ParseRoot(const char *_source,
Austin Schuh272c6132020-11-14 16:37:52 -0800992 const char **include_paths,
993 const char *source_filename);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700994 FLATBUFFERS_CHECKED_ERROR DoParse(const char *_source,
Austin Schuh272c6132020-11-14 16:37:52 -0800995 const char **include_paths,
996 const char *source_filename,
997 const char *include_filename);
Austin Schuh58b9b472020-11-25 19:12:44 -0800998 FLATBUFFERS_CHECKED_ERROR DoParseJson();
Austin Schuh272c6132020-11-14 16:37:52 -0800999 FLATBUFFERS_CHECKED_ERROR CheckClash(std::vector<FieldDef *> &fields,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001000 StructDef *struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -08001001 const char *suffix, BaseType baseType);
James Kuszmaul8e62b022022-03-22 09:33:25 -07001002 FLATBUFFERS_CHECKED_ERROR ParseAlignAttribute(
1003 const std::string &align_constant, size_t min_align, size_t *align);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001004
1005 bool SupportsAdvancedUnionFeatures() const;
1006 bool SupportsAdvancedArrayFeatures() const;
Austin Schuh272c6132020-11-14 16:37:52 -08001007 bool SupportsOptionalScalars() const;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001008 bool SupportsDefaultVectorsAndStrings() const;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001009 Namespace *UniqueNamespace(Namespace *ns);
1010
1011 FLATBUFFERS_CHECKED_ERROR RecurseError();
1012 template<typename F> CheckedError Recurse(F f);
1013
James Kuszmaul8e62b022022-03-22 09:33:25 -07001014 const std::string &GetPooledString(const std::string &s) const;
1015
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001016 public:
1017 SymbolTable<Type> types_;
1018 SymbolTable<StructDef> structs_;
1019 SymbolTable<EnumDef> enums_;
1020 SymbolTable<ServiceDef> services_;
1021 std::vector<Namespace *> namespaces_;
1022 Namespace *current_namespace_;
1023 Namespace *empty_namespace_;
Austin Schuh272c6132020-11-14 16:37:52 -08001024 std::string error_; // User readable error_ if Parse() == false
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001025
1026 FlatBufferBuilder builder_; // any data contained in the file
Austin Schuh272c6132020-11-14 16:37:52 -08001027 flexbuffers::Builder flex_builder_;
1028 flexbuffers::Reference flex_root_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001029 StructDef *root_struct_def_;
1030 std::string file_identifier_;
1031 std::string file_extension_;
1032
James Kuszmaul8e62b022022-03-22 09:33:25 -07001033 std::map<uint64_t, std::string> included_files_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001034 std::map<std::string, std::set<std::string>> files_included_per_file_;
1035 std::vector<std::string> native_included_files_;
1036
1037 std::map<std::string, bool> known_attributes_;
1038
1039 IDLOptions opts;
1040 bool uses_flexbuffers_;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001041 bool has_warning_;
1042
1043 uint64_t advanced_features_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001044
1045 private:
1046 const char *source_;
1047
1048 std::string file_being_parsed_;
1049
1050 std::vector<std::pair<Value, FieldDef *>> field_stack_;
1051
James Kuszmaul8e62b022022-03-22 09:33:25 -07001052 // TODO(cneo): Refactor parser to use string_cache more often to save
1053 // on memory usage.
1054 mutable std::set<std::string> string_cache_;
1055
1056 int anonymous_counter_;
1057 int parse_depth_counter_; // stack-overflow guard
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001058};
1059
1060// Utility functions for multiple generators:
1061
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001062// Generate text (JSON) from a given FlatBuffer, and a given Parser
1063// object that has been populated with the corresponding schema.
1064// If ident_step is 0, no indentation will be generated. Additionally,
1065// if it is less than 0, no linefeeds will be generated either.
1066// See idl_gen_text.cpp.
1067// strict_json adds "quotes" around field names if true.
1068// If the flatbuffer cannot be encoded in JSON (e.g., it contains non-UTF-8
1069// byte arrays in String values), returns false.
Austin Schuh272c6132020-11-14 16:37:52 -08001070extern bool GenerateTextFromTable(const Parser &parser, const void *table,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001071 const std::string &tablename,
1072 std::string *text);
Austin Schuh272c6132020-11-14 16:37:52 -08001073extern bool GenerateText(const Parser &parser, const void *flatbuffer,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001074 std::string *text);
Austin Schuh272c6132020-11-14 16:37:52 -08001075extern bool GenerateTextFile(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001076 const std::string &file_name);
1077
Austin Schuh272c6132020-11-14 16:37:52 -08001078// Generate Json schema to string
1079// See idl_gen_json_schema.cpp.
1080extern bool GenerateJsonSchema(const Parser &parser, std::string *json);
1081
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001082// Generate binary files from a given FlatBuffer, and a given Parser
1083// object that has been populated with the corresponding schema.
Austin Schuh272c6132020-11-14 16:37:52 -08001084// See code_generators.cpp.
1085extern bool GenerateBinary(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001086 const std::string &file_name);
1087
1088// Generate a C++ header from the definitions in the Parser object.
1089// See idl_gen_cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001090extern bool GenerateCPP(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001091 const std::string &file_name);
1092
Austin Schuh272c6132020-11-14 16:37:52 -08001093// Generate C# files from the definitions in the Parser object.
1094// See idl_gen_csharp.cpp.
1095extern bool GenerateCSharp(const Parser &parser, const std::string &path,
1096 const std::string &file_name);
1097
1098extern bool GenerateDart(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001099 const std::string &file_name);
1100
Austin Schuh272c6132020-11-14 16:37:52 -08001101// Generate Java files from the definitions in the Parser object.
1102// See idl_gen_java.cpp.
1103extern bool GenerateJava(const Parser &parser, const std::string &path,
1104 const std::string &file_name);
1105
1106// Generate JavaScript or TypeScript code from the definitions in the Parser
1107// object. See idl_gen_js.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001108extern bool GenerateTS(const Parser &parser, const std::string &path,
1109 const std::string &file_name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001110
1111// Generate Go files from the definitions in the Parser object.
1112// See idl_gen_go.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001113extern bool GenerateGo(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001114 const std::string &file_name);
1115
1116// Generate Php code from the definitions in the Parser object.
1117// See idl_gen_php.
Austin Schuh272c6132020-11-14 16:37:52 -08001118extern bool GeneratePhp(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001119 const std::string &file_name);
1120
1121// Generate Python files from the definitions in the Parser object.
1122// See idl_gen_python.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001123extern bool GeneratePython(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001124 const std::string &file_name);
1125
1126// Generate Lobster files from the definitions in the Parser object.
1127// See idl_gen_lobster.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001128extern bool GenerateLobster(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001129 const std::string &file_name);
1130
1131// Generate Lua files from the definitions in the Parser object.
1132// See idl_gen_lua.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001133extern bool GenerateLua(const Parser &parser, const std::string &path,
1134 const std::string &file_name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001135
1136// Generate Rust files from the definitions in the Parser object.
1137// See idl_gen_rust.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001138extern bool GenerateRust(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001139 const std::string &file_name);
1140
1141// Generate Json schema file
1142// See idl_gen_json_schema.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001143extern bool GenerateJsonSchema(const Parser &parser, const std::string &path,
1144 const std::string &file_name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001145
1146extern bool GenerateKotlin(const Parser &parser, const std::string &path,
1147 const std::string &file_name);
1148
Austin Schuh272c6132020-11-14 16:37:52 -08001149// Generate Swift classes.
1150// See idl_gen_swift.cpp
1151extern bool GenerateSwift(const Parser &parser, const std::string &path,
1152 const std::string &file_name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001153
1154// Generate a schema file from the internal representation, useful after
1155// parsing a .proto schema.
1156extern std::string GenerateFBS(const Parser &parser,
1157 const std::string &file_name);
Austin Schuh272c6132020-11-14 16:37:52 -08001158extern bool GenerateFBS(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001159 const std::string &file_name);
1160
James Kuszmaul8e62b022022-03-22 09:33:25 -07001161// Generate a make rule for the generated TypeScript code.
1162// See idl_gen_ts.cpp.
1163extern std::string TSMakeRule(const Parser &parser, const std::string &path,
1164 const std::string &file_name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001165
1166// Generate a make rule for the generated C++ header.
1167// See idl_gen_cpp.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001168extern std::string CPPMakeRule(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001169 const std::string &file_name);
1170
1171// Generate a make rule for the generated Dart code
1172// see idl_gen_dart.cpp
Austin Schuh272c6132020-11-14 16:37:52 -08001173extern std::string DartMakeRule(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001174 const std::string &file_name);
1175
1176// Generate a make rule for the generated Rust code.
1177// See idl_gen_rust.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001178extern std::string RustMakeRule(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001179 const std::string &file_name);
1180
Austin Schuh272c6132020-11-14 16:37:52 -08001181// Generate a make rule for generated Java or C# files.
1182// See code_generators.cpp.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001183extern std::string CSharpMakeRule(const Parser &parser, const std::string &path,
1184 const std::string &file_name);
1185extern std::string JavaMakeRule(const Parser &parser, const std::string &path,
1186 const std::string &file_name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001187
1188// Generate a make rule for the generated text (JSON) files.
1189// See idl_gen_text.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001190extern std::string TextMakeRule(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001191 const std::string &file_names);
1192
1193// Generate a make rule for the generated binary files.
Austin Schuh272c6132020-11-14 16:37:52 -08001194// See code_generators.cpp.
1195extern std::string BinaryMakeRule(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001196 const std::string &file_name);
1197
1198// Generate GRPC Cpp interfaces.
1199// See idl_gen_grpc.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001200bool GenerateCppGRPC(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001201 const std::string &file_name);
1202
1203// Generate GRPC Go interfaces.
1204// See idl_gen_grpc.cpp.
Austin Schuh272c6132020-11-14 16:37:52 -08001205bool GenerateGoGRPC(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001206 const std::string &file_name);
1207
1208// Generate GRPC Java classes.
1209// See idl_gen_grpc.cpp
Austin Schuh272c6132020-11-14 16:37:52 -08001210bool GenerateJavaGRPC(const Parser &parser, const std::string &path,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001211 const std::string &file_name);
1212
Austin Schuh272c6132020-11-14 16:37:52 -08001213// Generate GRPC Python interfaces.
1214// See idl_gen_grpc.cpp.
1215bool GeneratePythonGRPC(const Parser &parser, const std::string &path,
1216 const std::string &file_name);
1217
1218// Generate GRPC Swift interfaces.
1219// See idl_gen_grpc.cpp.
1220extern bool GenerateSwiftGRPC(const Parser &parser, const std::string &path,
1221 const std::string &file_name);
1222
1223extern bool GenerateTSGRPC(const Parser &parser, const std::string &path,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001224 const std::string &file_name);
1225
1226extern bool GenerateRustModuleRootFile(const Parser &parser,
1227 const std::string &path);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001228} // namespace flatbuffers
1229
1230#endif // FLATBUFFERS_IDL_H_