blob: 524c99688c3e6f42593e95ad10b4a06f573af866 [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#include <algorithm>
Austin Schuh272c6132020-11-14 16:37:52 -080018#include <cmath>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070019#include <list>
20#include <string>
21#include <utility>
22
James Kuszmauldac091f2022-03-22 09:35:06 -070023#include "flatbuffers/base.h"
Austin Schuhe89fa2d2019-08-14 20:24:23 -070024#include "flatbuffers/idl.h"
25#include "flatbuffers/util.h"
26
27namespace flatbuffers {
28
29// Reflects the version at the compiling time of binary(lib/dll/so).
30const char *FLATBUFFERS_VERSION() {
31 // clang-format off
32 return
33 FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
34 FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
35 FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
36 // clang-format on
37}
38
Austin Schuha1d006e2022-09-14 21:50:42 -070039namespace {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070040
Austin Schuha1d006e2022-09-14 21:50:42 -070041static const double kPi = 3.14159265358979323846;
Austin Schuhe89fa2d2019-08-14 20:24:23 -070042
43// The enums in the reflection schema should match the ones we use internally.
44// Compare the last element to check if these go out of sync.
James Kuszmauldac091f2022-03-22 09:35:06 -070045static_assert(BASE_TYPE_UNION == static_cast<BaseType>(reflection::BaseType::Union),
Austin Schuhe89fa2d2019-08-14 20:24:23 -070046 "enums don't match");
47
48// Any parsing calls have to be wrapped in this macro, which automates
49// handling of recursive error checking a bit. It will check the received
50// CheckedError object, and return straight away on error.
51#define ECHECK(call) \
52 { \
53 auto ce = (call); \
54 if (ce.Check()) return ce; \
55 }
56
57// These two functions are called hundreds of times below, so define a short
58// form:
59#define NEXT() ECHECK(Next())
60#define EXPECT(tok) ECHECK(Expect(tok))
61
62static bool ValidateUTF8(const std::string &str) {
63 const char *s = &str[0];
64 const char *const sEnd = s + str.length();
65 while (s < sEnd) {
66 if (FromUTF8(&s) < 0) { return false; }
67 }
68 return true;
69}
70
Austin Schuh272c6132020-11-14 16:37:52 -080071static bool IsLowerSnakeCase(const std::string &str) {
72 for (size_t i = 0; i < str.length(); i++) {
73 char c = str[i];
74 if (!check_ascii_range(c, 'a', 'z') && !is_digit(c) && c != '_') {
75 return false;
76 }
77 }
78 return true;
79}
80
Austin Schuha1d006e2022-09-14 21:50:42 -070081static void DeserializeDoc(std::vector<std::string> &doc,
82 const Vector<Offset<String>> *documentation) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070083 if (documentation == nullptr) return;
84 for (uoffset_t index = 0; index < documentation->size(); index++)
85 doc.push_back(documentation->Get(index)->str());
86}
87
Austin Schuha1d006e2022-09-14 21:50:42 -070088static CheckedError NoError() { return CheckedError(false); }
Austin Schuhe89fa2d2019-08-14 20:24:23 -070089
Austin Schuha1d006e2022-09-14 21:50:42 -070090template<typename T> static std::string TypeToIntervalString() {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070091 return "[" + NumToString((flatbuffers::numeric_limits<T>::lowest)()) + "; " +
92 NumToString((flatbuffers::numeric_limits<T>::max)()) + "]";
93}
94
95// atot: template version of atoi/atof: convert a string to an instance of T.
96template<typename T>
Austin Schuha1d006e2022-09-14 21:50:42 -070097static bool atot_scalar(const char *s, T *val, bool_constant<false>) {
James Kuszmauldac091f2022-03-22 09:35:06 -070098 return StringToNumber(s, val);
99}
100
101template<typename T>
Austin Schuha1d006e2022-09-14 21:50:42 -0700102static bool atot_scalar(const char *s, T *val, bool_constant<true>) {
James Kuszmauldac091f2022-03-22 09:35:06 -0700103 // Normalize NaN parsed from fbs or json to unsigned NaN.
104 if (false == StringToNumber(s, val)) return false;
105 *val = (*val != *val) ? std::fabs(*val) : *val;
106 return true;
107}
108
Austin Schuha1d006e2022-09-14 21:50:42 -0700109template<typename T>
110static CheckedError atot(const char *s, Parser &parser, T *val) {
James Kuszmauldac091f2022-03-22 09:35:06 -0700111 auto done = atot_scalar(s, val, bool_constant<is_floating_point<T>::value>());
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700112 if (done) return NoError();
113 if (0 == *val)
114 return parser.Error("invalid number: \"" + std::string(s) + "\"");
115 else
116 return parser.Error("invalid number: \"" + std::string(s) + "\"" +
117 ", constant does not fit " + TypeToIntervalString<T>());
118}
119template<>
Austin Schuha1d006e2022-09-14 21:50:42 -0700120CheckedError atot<Offset<void>>(const char *s, Parser &parser,
121 Offset<void> *val) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700122 (void)parser;
123 *val = Offset<void>(atoi(s));
124 return NoError();
125}
126
James Kuszmauldac091f2022-03-22 09:35:06 -0700127template<typename T>
Austin Schuha1d006e2022-09-14 21:50:42 -0700128static T *LookupTableByName(const SymbolTable<T> &table,
129 const std::string &name,
130 const Namespace &current_namespace,
131 size_t skip_top) {
James Kuszmauldac091f2022-03-22 09:35:06 -0700132 const auto &components = current_namespace.components;
133 if (table.dict.empty()) return nullptr;
134 if (components.size() < skip_top) return nullptr;
135 const auto N = components.size() - skip_top;
136 std::string full_name;
137 for (size_t i = 0; i < N; i++) {
138 full_name += components[i];
139 full_name += '.';
140 }
141 for (size_t i = N; i > 0; i--) {
142 full_name += name;
143 auto obj = table.Lookup(full_name);
144 if (obj) return obj;
145 auto len = full_name.size() - components[i - 1].size() - 1 - name.size();
146 full_name.resize(len);
147 }
148 FLATBUFFERS_ASSERT(full_name.empty());
149 return table.Lookup(name); // lookup in global namespace
150}
151
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700152// Declare tokens we'll use. Single character tokens are represented by their
153// ascii character code (e.g. '{'), others above 256.
154// clang-format off
155#define FLATBUFFERS_GEN_TOKENS(TD) \
156 TD(Eof, 256, "end of file") \
157 TD(StringConstant, 257, "string constant") \
158 TD(IntegerConstant, 258, "integer constant") \
159 TD(FloatConstant, 259, "float constant") \
160 TD(Identifier, 260, "identifier")
161#ifdef __GNUC__
162__extension__ // Stop GCC complaining about trailing comma with -Wpendantic.
163#endif
164enum {
165 #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME = VALUE,
166 FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
167 #undef FLATBUFFERS_TOKEN
168};
169
170static std::string TokenToString(int t) {
171 static const char * const tokens[] = {
172 #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) STRING,
173 FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
174 #undef FLATBUFFERS_TOKEN
Austin Schuh272c6132020-11-14 16:37:52 -0800175 #define FLATBUFFERS_TD(ENUM, IDLTYPE, ...) \
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700176 IDLTYPE,
177 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
178 #undef FLATBUFFERS_TD
179 };
180 if (t < 256) { // A single ascii char token.
181 std::string s;
182 s.append(1, static_cast<char>(t));
183 return s;
184 } else { // Other tokens.
185 return tokens[t - 256];
186 }
187}
188// clang-format on
189
Austin Schuha1d006e2022-09-14 21:50:42 -0700190static bool IsIdentifierStart(char c) { return is_alpha(c) || (c == '_'); }
191
192static bool CompareSerializedScalars(const uint8_t *a, const uint8_t *b,
193 const FieldDef &key) {
194 switch (key.value.type.base_type) {
195#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
196 case BASE_TYPE_##ENUM: { \
197 CTYPE def = static_cast<CTYPE>(0); \
198 if (!a || !b) { StringToNumber(key.value.constant.c_str(), &def); } \
199 const auto av = a ? ReadScalar<CTYPE>(a) : def; \
200 const auto bv = b ? ReadScalar<CTYPE>(b) : def; \
201 return av < bv; \
202 }
203 FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
204#undef FLATBUFFERS_TD
205 default: {
206 FLATBUFFERS_ASSERT(false && "scalar type expected");
207 return false;
208 }
209 }
210}
211
212static bool CompareTablesByScalarKey(const Offset<Table> *_a,
213 const Offset<Table> *_b,
214 const FieldDef &key) {
215 const voffset_t offset = key.value.offset;
216 // Indirect offset pointer to table pointer.
217 auto a = reinterpret_cast<const uint8_t *>(_a) + ReadScalar<uoffset_t>(_a);
218 auto b = reinterpret_cast<const uint8_t *>(_b) + ReadScalar<uoffset_t>(_b);
219 // Fetch field address from table.
220 a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset);
221 b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset);
222 return CompareSerializedScalars(a, b, key);
223}
224
225static bool CompareTablesByStringKey(const Offset<Table> *_a,
226 const Offset<Table> *_b,
227 const FieldDef &key) {
228 const voffset_t offset = key.value.offset;
229 // Indirect offset pointer to table pointer.
230 auto a = reinterpret_cast<const uint8_t *>(_a) + ReadScalar<uoffset_t>(_a);
231 auto b = reinterpret_cast<const uint8_t *>(_b) + ReadScalar<uoffset_t>(_b);
232 // Fetch field address from table.
233 a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset);
234 b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset);
235 if (a && b) {
236 // Indirect offset pointer to string pointer.
237 a += ReadScalar<uoffset_t>(a);
238 b += ReadScalar<uoffset_t>(b);
239 return *reinterpret_cast<const String *>(a) <
240 *reinterpret_cast<const String *>(b);
241 } else {
242 return a ? true : false;
243 }
244}
245
246static void SwapSerializedTables(Offset<Table> *a, Offset<Table> *b) {
247 // These are serialized offsets, so are relative where they are
248 // stored in memory, so compute the distance between these pointers:
249 ptrdiff_t diff = (b - a) * sizeof(Offset<Table>);
250 FLATBUFFERS_ASSERT(diff >= 0); // Guaranteed by SimpleQsort.
251 auto udiff = static_cast<uoffset_t>(diff);
252 a->o = EndianScalar(ReadScalar<uoffset_t>(a) - udiff);
253 b->o = EndianScalar(ReadScalar<uoffset_t>(b) + udiff);
254 std::swap(*a, *b);
255}
256
257// See below for why we need our own sort :(
258template<typename T, typename F, typename S>
259static void SimpleQsort(T *begin, T *end, size_t width, F comparator,
260 S swapper) {
261 if (end - begin <= static_cast<ptrdiff_t>(width)) return;
262 auto l = begin + width;
263 auto r = end;
264 while (l < r) {
265 if (comparator(begin, l)) {
266 r -= width;
267 swapper(l, r);
268 } else {
269 l += width;
270 }
271 }
272 l -= width;
273 swapper(begin, l);
274 SimpleQsort(begin, l, width, comparator, swapper);
275 SimpleQsort(r, end, width, comparator, swapper);
276}
277
278template<typename T> static inline void SingleValueRepack(Value &e, T val) {
279 // Remove leading zeros.
280 if (IsInteger(e.type.base_type)) { e.constant = NumToString(val); }
281}
282
283#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
284// Normalize defaults NaN to unsigned quiet-NaN(0) if value was parsed from
285// hex-float literal.
286static void SingleValueRepack(Value &e, float val) {
287 if (val != val) e.constant = "nan";
288}
289static void SingleValueRepack(Value &e, double val) {
290 if (val != val) e.constant = "nan";
291}
292#endif
293
294template<typename T> static uint64_t EnumDistanceImpl(T e1, T e2) {
295 if (e1 < e2) { std::swap(e1, e2); } // use std for scalars
296 // Signed overflow may occur, use unsigned calculation.
297 // The unsigned overflow is well-defined by C++ standard (modulo 2^n).
298 return static_cast<uint64_t>(e1) - static_cast<uint64_t>(e2);
299}
300
301static bool compareFieldDefs(const FieldDef *a, const FieldDef *b) {
302 auto a_id = atoi(a->attributes.Lookup("id")->constant.c_str());
303 auto b_id = atoi(b->attributes.Lookup("id")->constant.c_str());
304 return a_id < b_id;
305}
306
307static Namespace *GetNamespace(
308 const std::string &qualified_name, std::vector<Namespace *> &namespaces,
309 std::map<std::string, Namespace *> &namespaces_index) {
310 size_t dot = qualified_name.find_last_of('.');
311 std::string namespace_name = (dot != std::string::npos)
312 ? std::string(qualified_name.c_str(), dot)
313 : "";
314 Namespace *&ns = namespaces_index[namespace_name];
315
316 if (!ns) {
317 ns = new Namespace();
318 namespaces.push_back(ns);
319
320 size_t pos = 0;
321
322 for (;;) {
323 dot = qualified_name.find('.', pos);
324 if (dot == std::string::npos) { break; }
325 ns->components.push_back(qualified_name.substr(pos, dot - pos));
326 pos = dot + 1;
327 }
328 }
329
330 return ns;
331}
332
333// Generate a unique hash for a file based on its name and contents (if any).
334static uint64_t HashFile(const char *source_filename, const char *source) {
335 uint64_t hash = 0;
336
337 if (source_filename)
338 hash = HashFnv1a<uint64_t>(StripPath(source_filename).c_str());
339
340 if (source && *source) hash ^= HashFnv1a<uint64_t>(source);
341
342 return hash;
343}
344
345template<typename T> static bool compareName(const T *a, const T *b) {
346 return a->defined_namespace->GetFullyQualifiedName(a->name) <
347 b->defined_namespace->GetFullyQualifiedName(b->name);
348}
349
350template<typename T> static void AssignIndices(const std::vector<T *> &defvec) {
351 // Pre-sort these vectors, such that we can set the correct indices for them.
352 auto vec = defvec;
353 std::sort(vec.begin(), vec.end(), compareName<T>);
354 for (int i = 0; i < static_cast<int>(vec.size()); i++) vec[i]->index = i;
355}
356
357} // namespace
358
359// clang-format off
360const char *const kTypeNames[] = {
361 #define FLATBUFFERS_TD(ENUM, IDLTYPE, ...) \
362 IDLTYPE,
363 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
364 #undef FLATBUFFERS_TD
365 nullptr
366};
367
368const char kTypeSizes[] = {
369 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
370 sizeof(CTYPE),
371 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
372 #undef FLATBUFFERS_TD
373};
374// clang-format on
375
376void Parser::Message(const std::string &msg) {
377 if (!error_.empty()) error_ += "\n"; // log all warnings and errors
378 error_ += file_being_parsed_.length() ? AbsolutePath(file_being_parsed_) : "";
379 // clang-format off
380
381 #ifdef _WIN32 // MSVC alike
382 error_ +=
383 "(" + NumToString(line_) + ", " + NumToString(CursorPosition()) + ")";
384 #else // gcc alike
385 if (file_being_parsed_.length()) error_ += ":";
386 error_ += NumToString(line_) + ": " + NumToString(CursorPosition());
387 #endif
388 // clang-format on
389 error_ += ": " + msg;
390}
391
392void Parser::Warning(const std::string &msg) {
393 if (!opts.no_warnings) {
394 Message("warning: " + msg);
395 has_warning_ = true; // for opts.warnings_as_errors
396 }
397}
398
399CheckedError Parser::Error(const std::string &msg) {
400 Message("error: " + msg);
401 return CheckedError(true);
402}
403
404CheckedError Parser::RecurseError() {
405 return Error("maximum parsing depth " + NumToString(parse_depth_counter_) +
406 " reached");
407}
408
409const std::string &Parser::GetPooledString(const std::string &s) const {
410 return *(string_cache_.insert(s).first);
411}
412
413class Parser::ParseDepthGuard {
414 public:
415 explicit ParseDepthGuard(Parser *parser_not_null)
416 : parser_(*parser_not_null), caller_depth_(parser_.parse_depth_counter_) {
417 FLATBUFFERS_ASSERT(caller_depth_ <= (FLATBUFFERS_MAX_PARSING_DEPTH) &&
418 "Check() must be called to prevent stack overflow");
419 parser_.parse_depth_counter_ += 1;
420 }
421
422 ~ParseDepthGuard() { parser_.parse_depth_counter_ -= 1; }
423
424 CheckedError Check() {
425 return caller_depth_ >= (FLATBUFFERS_MAX_PARSING_DEPTH)
426 ? parser_.RecurseError()
427 : CheckedError(false);
428 }
429
430 FLATBUFFERS_DELETE_FUNC(ParseDepthGuard(const ParseDepthGuard &));
431 FLATBUFFERS_DELETE_FUNC(ParseDepthGuard &operator=(const ParseDepthGuard &));
432
433 private:
434 Parser &parser_;
435 const int caller_depth_;
436};
437
438std::string Namespace::GetFullyQualifiedName(const std::string &name,
439 size_t max_components) const {
440 // Early exit if we don't have a defined namespace.
441 if (components.empty() || !max_components) { return name; }
442 std::string stream_str;
443 for (size_t i = 0; i < std::min(components.size(), max_components); i++) {
444 stream_str += components[i];
445 stream_str += '.';
446 }
447 if (!stream_str.empty()) stream_str.pop_back();
448 if (name.length()) {
449 stream_str += '.';
450 stream_str += name;
451 }
452 return stream_str;
453}
454
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700455std::string Parser::TokenToStringId(int t) const {
456 return t == kTokenIdentifier ? attribute_ : TokenToString(t);
457}
458
459// Parses exactly nibbles worth of hex digits into a number, or error.
460CheckedError Parser::ParseHexNum(int nibbles, uint64_t *val) {
461 FLATBUFFERS_ASSERT(nibbles > 0);
462 for (int i = 0; i < nibbles; i++)
463 if (!is_xdigit(cursor_[i]))
464 return Error("escape code must be followed by " + NumToString(nibbles) +
465 " hex digits");
466 std::string target(cursor_, cursor_ + nibbles);
467 *val = StringToUInt(target.c_str(), 16);
468 cursor_ += nibbles;
469 return NoError();
470}
471
472CheckedError Parser::SkipByteOrderMark() {
473 if (static_cast<unsigned char>(*cursor_) != 0xef) return NoError();
474 cursor_++;
475 if (static_cast<unsigned char>(*cursor_) != 0xbb)
476 return Error("invalid utf-8 byte order mark");
477 cursor_++;
478 if (static_cast<unsigned char>(*cursor_) != 0xbf)
479 return Error("invalid utf-8 byte order mark");
480 cursor_++;
481 return NoError();
482}
483
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700484CheckedError Parser::Next() {
485 doc_comment_.clear();
486 bool seen_newline = cursor_ == source_;
487 attribute_.clear();
488 attr_is_trivial_ascii_string_ = true;
489 for (;;) {
490 char c = *cursor_++;
491 token_ = c;
492 switch (c) {
493 case '\0':
494 cursor_--;
495 token_ = kTokenEof;
496 return NoError();
497 case ' ':
498 case '\r':
499 case '\t': break;
500 case '\n':
501 MarkNewLine();
502 seen_newline = true;
503 break;
504 case '{':
505 case '}':
506 case '(':
507 case ')':
508 case '[':
509 case ']':
510 case ',':
511 case ':':
512 case ';':
513 case '=': return NoError();
514 case '\"':
515 case '\'': {
516 int unicode_high_surrogate = -1;
517
518 while (*cursor_ != c) {
519 if (*cursor_ < ' ' && static_cast<signed char>(*cursor_) >= 0)
520 return Error("illegal character in string constant");
521 if (*cursor_ == '\\') {
522 attr_is_trivial_ascii_string_ = false; // has escape sequence
523 cursor_++;
524 if (unicode_high_surrogate != -1 && *cursor_ != 'u') {
525 return Error(
526 "illegal Unicode sequence (unpaired high surrogate)");
527 }
528 switch (*cursor_) {
529 case 'n':
530 attribute_ += '\n';
531 cursor_++;
532 break;
533 case 't':
534 attribute_ += '\t';
535 cursor_++;
536 break;
537 case 'r':
538 attribute_ += '\r';
539 cursor_++;
540 break;
541 case 'b':
542 attribute_ += '\b';
543 cursor_++;
544 break;
545 case 'f':
546 attribute_ += '\f';
547 cursor_++;
548 break;
549 case '\"':
550 attribute_ += '\"';
551 cursor_++;
552 break;
553 case '\'':
554 attribute_ += '\'';
555 cursor_++;
556 break;
557 case '\\':
558 attribute_ += '\\';
559 cursor_++;
560 break;
561 case '/':
562 attribute_ += '/';
563 cursor_++;
564 break;
565 case 'x': { // Not in the JSON standard
566 cursor_++;
567 uint64_t val;
568 ECHECK(ParseHexNum(2, &val));
569 attribute_ += static_cast<char>(val);
570 break;
571 }
572 case 'u': {
573 cursor_++;
574 uint64_t val;
575 ECHECK(ParseHexNum(4, &val));
576 if (val >= 0xD800 && val <= 0xDBFF) {
577 if (unicode_high_surrogate != -1) {
578 return Error(
579 "illegal Unicode sequence (multiple high surrogates)");
580 } else {
581 unicode_high_surrogate = static_cast<int>(val);
582 }
583 } else if (val >= 0xDC00 && val <= 0xDFFF) {
584 if (unicode_high_surrogate == -1) {
585 return Error(
586 "illegal Unicode sequence (unpaired low surrogate)");
587 } else {
588 int code_point = 0x10000 +
589 ((unicode_high_surrogate & 0x03FF) << 10) +
590 (val & 0x03FF);
591 ToUTF8(code_point, &attribute_);
592 unicode_high_surrogate = -1;
593 }
594 } else {
595 if (unicode_high_surrogate != -1) {
596 return Error(
597 "illegal Unicode sequence (unpaired high surrogate)");
598 }
599 ToUTF8(static_cast<int>(val), &attribute_);
600 }
601 break;
602 }
603 default: return Error("unknown escape code in string constant");
604 }
605 } else { // printable chars + UTF-8 bytes
606 if (unicode_high_surrogate != -1) {
607 return Error(
608 "illegal Unicode sequence (unpaired high surrogate)");
609 }
610 // reset if non-printable
Austin Schuh272c6132020-11-14 16:37:52 -0800611 attr_is_trivial_ascii_string_ &=
612 check_ascii_range(*cursor_, ' ', '~');
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700613
614 attribute_ += *cursor_++;
615 }
616 }
617 if (unicode_high_surrogate != -1) {
618 return Error("illegal Unicode sequence (unpaired high surrogate)");
619 }
620 cursor_++;
621 if (!attr_is_trivial_ascii_string_ && !opts.allow_non_utf8 &&
622 !ValidateUTF8(attribute_)) {
623 return Error("illegal UTF-8 sequence");
624 }
625 token_ = kTokenStringConstant;
626 return NoError();
627 }
628 case '/':
629 if (*cursor_ == '/') {
630 const char *start = ++cursor_;
631 while (*cursor_ && *cursor_ != '\n' && *cursor_ != '\r') cursor_++;
632 if (*start == '/') { // documentation comment
633 if (!seen_newline)
634 return Error(
635 "a documentation comment should be on a line on its own");
636 doc_comment_.push_back(std::string(start + 1, cursor_));
637 }
638 break;
639 } else if (*cursor_ == '*') {
640 cursor_++;
641 // TODO: make nested.
642 while (*cursor_ != '*' || cursor_[1] != '/') {
643 if (*cursor_ == '\n') MarkNewLine();
644 if (!*cursor_) return Error("end of file in comment");
645 cursor_++;
646 }
647 cursor_ += 2;
648 break;
649 }
Austin Schuh272c6132020-11-14 16:37:52 -0800650 FLATBUFFERS_FALLTHROUGH(); // else fall thru
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700651 default:
James Kuszmauldac091f2022-03-22 09:35:06 -0700652 if (IsIdentifierStart(c)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700653 // Collect all chars of an identifier:
654 const char *start = cursor_ - 1;
655 while (IsIdentifierStart(*cursor_) || is_digit(*cursor_)) cursor_++;
656 attribute_.append(start, cursor_);
James Kuszmauldac091f2022-03-22 09:35:06 -0700657 token_ = kTokenIdentifier;
658 return NoError();
659 }
660
661 const auto has_sign = (c == '+') || (c == '-');
Austin Schuha1d006e2022-09-14 21:50:42 -0700662 if (has_sign) {
663 // Check for +/-inf which is considered a float constant.
664 if (strncmp(cursor_, "inf", 3) == 0 &&
665 !(IsIdentifierStart(cursor_[3]) || is_digit(cursor_[3]))) {
666 attribute_.assign(cursor_ - 1, cursor_ + 3);
667 token_ = kTokenFloatConstant;
668 cursor_ += 3;
669 return NoError();
670 }
671
672 if (IsIdentifierStart(*cursor_)) {
673 // '-'/'+' and following identifier - it could be a predefined
674 // constant. Return the sign in token_, see ParseSingleValue.
675 return NoError();
676 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700677 }
678
Austin Schuh272c6132020-11-14 16:37:52 -0800679 auto dot_lvl =
680 (c == '.') ? 0 : 1; // dot_lvl==0 <=> exactly one '.' seen
681 if (!dot_lvl && !is_digit(*cursor_)) return NoError(); // enum?
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700682 // Parser accepts hexadecimal-floating-literal (see C++ 5.13.4).
683 if (is_digit(c) || has_sign || !dot_lvl) {
684 const auto start = cursor_ - 1;
685 auto start_digits = !is_digit(c) ? cursor_ : cursor_ - 1;
Austin Schuh272c6132020-11-14 16:37:52 -0800686 if (!is_digit(c) && is_digit(*cursor_)) {
687 start_digits = cursor_; // see digit in cursor_ position
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700688 c = *cursor_++;
689 }
690 // hex-float can't begind with '.'
691 auto use_hex = dot_lvl && (c == '0') && is_alpha_char(*cursor_, 'X');
692 if (use_hex) start_digits = ++cursor_; // '0x' is the prefix, skip it
693 // Read an integer number or mantisa of float-point number.
694 do {
695 if (use_hex) {
696 while (is_xdigit(*cursor_)) cursor_++;
697 } else {
698 while (is_digit(*cursor_)) cursor_++;
699 }
700 } while ((*cursor_ == '.') && (++cursor_) && (--dot_lvl >= 0));
701 // Exponent of float-point number.
702 if ((dot_lvl >= 0) && (cursor_ > start_digits)) {
703 // The exponent suffix of hexadecimal float number is mandatory.
704 if (use_hex && !dot_lvl) start_digits = cursor_;
705 if ((use_hex && is_alpha_char(*cursor_, 'P')) ||
706 is_alpha_char(*cursor_, 'E')) {
707 dot_lvl = 0; // Emulate dot to signal about float-point number.
708 cursor_++;
709 if (*cursor_ == '+' || *cursor_ == '-') cursor_++;
710 start_digits = cursor_; // the exponent-part has to have digits
711 // Exponent is decimal integer number
712 while (is_digit(*cursor_)) cursor_++;
713 if (*cursor_ == '.') {
714 cursor_++; // If see a dot treat it as part of invalid number.
715 dot_lvl = -1; // Fall thru to Error().
716 }
717 }
718 }
719 // Finalize.
720 if ((dot_lvl >= 0) && (cursor_ > start_digits)) {
721 attribute_.append(start, cursor_);
722 token_ = dot_lvl ? kTokenIntegerConstant : kTokenFloatConstant;
723 return NoError();
724 } else {
725 return Error("invalid number: " + std::string(start, cursor_));
726 }
727 }
728 std::string ch;
729 ch = c;
Austin Schuh272c6132020-11-14 16:37:52 -0800730 if (false == check_ascii_range(c, ' ', '~'))
731 ch = "code: " + NumToString(c);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700732 return Error("illegal character: " + ch);
733 }
734 }
735}
736
737// Check if a given token is next.
738bool Parser::Is(int t) const { return t == token_; }
739
740bool Parser::IsIdent(const char *id) const {
741 return token_ == kTokenIdentifier && attribute_ == id;
742}
743
744// Expect a given token to be next, consume it, or error if not present.
745CheckedError Parser::Expect(int t) {
746 if (t != token_) {
747 return Error("expecting: " + TokenToString(t) +
748 " instead got: " + TokenToStringId(token_));
749 }
750 NEXT();
751 return NoError();
752}
753
754CheckedError Parser::ParseNamespacing(std::string *id, std::string *last) {
755 while (Is('.')) {
756 NEXT();
757 *id += ".";
758 *id += attribute_;
759 if (last) *last = attribute_;
760 EXPECT(kTokenIdentifier);
761 }
762 return NoError();
763}
764
765EnumDef *Parser::LookupEnum(const std::string &id) {
766 // Search thru parent namespaces.
James Kuszmauldac091f2022-03-22 09:35:06 -0700767 return LookupTableByName(enums_, id, *current_namespace_, 0);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700768}
769
770StructDef *Parser::LookupStruct(const std::string &id) const {
771 auto sd = structs_.Lookup(id);
772 if (sd) sd->refcount++;
773 return sd;
774}
775
James Kuszmauldac091f2022-03-22 09:35:06 -0700776StructDef *Parser::LookupStructThruParentNamespaces(
777 const std::string &id) const {
778 auto sd = LookupTableByName(structs_, id, *current_namespace_, 1);
779 if (sd) sd->refcount++;
780 return sd;
781}
782
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700783CheckedError Parser::ParseTypeIdent(Type &type) {
784 std::string id = attribute_;
785 EXPECT(kTokenIdentifier);
786 ECHECK(ParseNamespacing(&id, nullptr));
787 auto enum_def = LookupEnum(id);
788 if (enum_def) {
789 type = enum_def->underlying_type;
790 if (enum_def->is_union) type.base_type = BASE_TYPE_UNION;
791 } else {
792 type.base_type = BASE_TYPE_STRUCT;
793 type.struct_def = LookupCreateStruct(id);
794 }
795 return NoError();
796}
797
798// Parse any IDL type.
799CheckedError Parser::ParseType(Type &type) {
800 if (token_ == kTokenIdentifier) {
801 if (IsIdent("bool")) {
802 type.base_type = BASE_TYPE_BOOL;
803 NEXT();
804 } else if (IsIdent("byte") || IsIdent("int8")) {
805 type.base_type = BASE_TYPE_CHAR;
806 NEXT();
807 } else if (IsIdent("ubyte") || IsIdent("uint8")) {
808 type.base_type = BASE_TYPE_UCHAR;
809 NEXT();
810 } else if (IsIdent("short") || IsIdent("int16")) {
811 type.base_type = BASE_TYPE_SHORT;
812 NEXT();
813 } else if (IsIdent("ushort") || IsIdent("uint16")) {
814 type.base_type = BASE_TYPE_USHORT;
815 NEXT();
816 } else if (IsIdent("int") || IsIdent("int32")) {
817 type.base_type = BASE_TYPE_INT;
818 NEXT();
819 } else if (IsIdent("uint") || IsIdent("uint32")) {
820 type.base_type = BASE_TYPE_UINT;
821 NEXT();
822 } else if (IsIdent("long") || IsIdent("int64")) {
823 type.base_type = BASE_TYPE_LONG;
824 NEXT();
825 } else if (IsIdent("ulong") || IsIdent("uint64")) {
826 type.base_type = BASE_TYPE_ULONG;
827 NEXT();
828 } else if (IsIdent("float") || IsIdent("float32")) {
829 type.base_type = BASE_TYPE_FLOAT;
830 NEXT();
831 } else if (IsIdent("double") || IsIdent("float64")) {
832 type.base_type = BASE_TYPE_DOUBLE;
833 NEXT();
834 } else if (IsIdent("string")) {
835 type.base_type = BASE_TYPE_STRING;
836 NEXT();
837 } else {
838 ECHECK(ParseTypeIdent(type));
839 }
840 } else if (token_ == '[') {
James Kuszmauldac091f2022-03-22 09:35:06 -0700841 ParseDepthGuard depth_guard(this);
842 ECHECK(depth_guard.Check());
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700843 NEXT();
844 Type subtype;
James Kuszmauldac091f2022-03-22 09:35:06 -0700845 ECHECK(ParseType(subtype));
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700846 if (IsSeries(subtype)) {
847 // We could support this, but it will complicate things, and it's
848 // easier to work around with a struct around the inner vector.
849 return Error("nested vector types not supported (wrap in table first)");
850 }
851 if (token_ == ':') {
852 NEXT();
853 if (token_ != kTokenIntegerConstant) {
854 return Error("length of fixed-length array must be an integer value");
855 }
856 uint16_t fixed_length = 0;
857 bool check = StringToNumber(attribute_.c_str(), &fixed_length);
858 if (!check || fixed_length < 1) {
859 return Error(
860 "length of fixed-length array must be positive and fit to "
861 "uint16_t type");
862 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700863 type = Type(BASE_TYPE_ARRAY, subtype.struct_def, subtype.enum_def,
864 fixed_length);
865 NEXT();
866 } else {
867 type = Type(BASE_TYPE_VECTOR, subtype.struct_def, subtype.enum_def);
868 }
869 type.element = subtype.base_type;
870 EXPECT(']');
871 } else {
872 return Error("illegal type syntax");
873 }
874 return NoError();
875}
876
877CheckedError Parser::AddField(StructDef &struct_def, const std::string &name,
878 const Type &type, FieldDef **dest) {
879 auto &field = *new FieldDef();
880 field.value.offset =
881 FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size()));
882 field.name = name;
883 field.file = struct_def.file;
884 field.value.type = type;
885 if (struct_def.fixed) { // statically compute the field offset
886 auto size = InlineSize(type);
887 auto alignment = InlineAlignment(type);
888 // structs_ need to have a predictable format, so we need to align to
889 // the largest scalar
890 struct_def.minalign = std::max(struct_def.minalign, alignment);
891 struct_def.PadLastField(alignment);
892 field.value.offset = static_cast<voffset_t>(struct_def.bytesize);
893 struct_def.bytesize += size;
894 }
895 if (struct_def.fields.Add(name, &field))
896 return Error("field already exists: " + name);
897 *dest = &field;
898 return NoError();
899}
900
901CheckedError Parser::ParseField(StructDef &struct_def) {
902 std::string name = attribute_;
903
Austin Schuh272c6132020-11-14 16:37:52 -0800904 if (LookupCreateStruct(name, false, false))
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700905 return Error("field name can not be the same as table/struct name");
906
Austin Schuh272c6132020-11-14 16:37:52 -0800907 if (!IsLowerSnakeCase(name)) {
908 Warning("field names should be lowercase snake_case, got: " + name);
909 }
910
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700911 std::vector<std::string> dc = doc_comment_;
912 EXPECT(kTokenIdentifier);
913 EXPECT(':');
914 Type type;
915 ECHECK(ParseType(type));
916
Austin Schuh272c6132020-11-14 16:37:52 -0800917 if (struct_def.fixed) {
918 auto valid = IsScalar(type.base_type) || IsStruct(type);
919 if (!valid && IsArray(type)) {
920 const auto &elem_type = type.VectorType();
921 valid |= IsScalar(elem_type.base_type) || IsStruct(elem_type);
922 }
923 if (!valid)
924 return Error("structs may contain only scalar or struct fields");
925 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700926
927 if (!struct_def.fixed && IsArray(type))
928 return Error("fixed-length array in table must be wrapped in struct");
929
James Kuszmauldac091f2022-03-22 09:35:06 -0700930 if (IsArray(type)) {
931 advanced_features_ |= static_cast<uint64_t>(reflection::AdvancedFeatures::AdvancedArrayFeatures);
932 if (!SupportsAdvancedArrayFeatures()) {
933 return Error(
934 "Arrays are not yet supported in all "
935 "the specified programming languages.");
936 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700937 }
938
939 FieldDef *typefield = nullptr;
940 if (type.base_type == BASE_TYPE_UNION) {
941 // For union fields, add a second auto-generated field to hold the type,
942 // with a special suffix.
943 ECHECK(AddField(struct_def, name + UnionTypeFieldSuffix(),
944 type.enum_def->underlying_type, &typefield));
Austin Schuh272c6132020-11-14 16:37:52 -0800945 } else if (IsVector(type) && type.element == BASE_TYPE_UNION) {
James Kuszmauldac091f2022-03-22 09:35:06 -0700946 advanced_features_ |= static_cast<uint64_t>(reflection::AdvancedFeatures::AdvancedUnionFeatures);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700947 // Only cpp, js and ts supports the union vector feature so far.
948 if (!SupportsAdvancedUnionFeatures()) {
949 return Error(
Austin Schuh272c6132020-11-14 16:37:52 -0800950 "Vectors of unions are not yet supported in at least one of "
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700951 "the specified programming languages.");
952 }
953 // For vector of union fields, add a second auto-generated vector field to
954 // hold the types, with a special suffix.
955 Type union_vector(BASE_TYPE_VECTOR, nullptr, type.enum_def);
956 union_vector.element = BASE_TYPE_UTYPE;
957 ECHECK(AddField(struct_def, name + UnionTypeFieldSuffix(), union_vector,
958 &typefield));
959 }
960
961 FieldDef *field;
962 ECHECK(AddField(struct_def, name, type, &field));
963
964 if (token_ == '=') {
965 NEXT();
966 ECHECK(ParseSingleValue(&field->name, field->value, true));
James Kuszmauldac091f2022-03-22 09:35:06 -0700967 if (IsStruct(type) || (struct_def.fixed && field->value.constant != "0"))
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700968 return Error(
James Kuszmauldac091f2022-03-22 09:35:06 -0700969 "default values are not supported for struct fields, table fields, "
970 "or in structs.");
971 if (IsString(type) || IsVector(type)) {
972 advanced_features_ |= static_cast<uint64_t>(reflection::AdvancedFeatures::DefaultVectorsAndStrings);
973 if (field->value.constant != "0" && !SupportsDefaultVectorsAndStrings()) {
Austin Schuh272c6132020-11-14 16:37:52 -0800974 return Error(
James Kuszmauldac091f2022-03-22 09:35:06 -0700975 "Default values for strings and vectors are not supported in one "
976 "of the specified programming languages");
Austin Schuh272c6132020-11-14 16:37:52 -0800977 }
978 }
James Kuszmauldac091f2022-03-22 09:35:06 -0700979
980 if (IsVector(type) && field->value.constant != "0" &&
981 field->value.constant != "[]") {
982 return Error("The only supported default for vectors is `[]`.");
983 }
Austin Schuh272c6132020-11-14 16:37:52 -0800984 }
985
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700986 // Append .0 if the value has not it (skip hex and scientific floats).
987 // This suffix needed for generated C++ code.
988 if (IsFloat(type.base_type)) {
989 auto &text = field->value.constant;
990 FLATBUFFERS_ASSERT(false == text.empty());
991 auto s = text.c_str();
Austin Schuh272c6132020-11-14 16:37:52 -0800992 while (*s == ' ') s++;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700993 if (*s == '-' || *s == '+') s++;
994 // 1) A float constants (nan, inf, pi, etc) is a kind of identifier.
995 // 2) A float number needn't ".0" at the end if it has exponent.
996 if ((false == IsIdentifierStart(*s)) &&
997 (std::string::npos == field->value.constant.find_first_of(".eEpP"))) {
998 field->value.constant += ".0";
999 }
1000 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001001
1002 field->doc_comment = dc;
1003 ECHECK(ParseMetaData(&field->attributes));
1004 field->deprecated = field->attributes.Lookup("deprecated") != nullptr;
1005 auto hash_name = field->attributes.Lookup("hash");
1006 if (hash_name) {
Austin Schuh272c6132020-11-14 16:37:52 -08001007 switch ((IsVector(type)) ? type.element : type.base_type) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001008 case BASE_TYPE_SHORT:
1009 case BASE_TYPE_USHORT: {
1010 if (FindHashFunction16(hash_name->constant.c_str()) == nullptr)
1011 return Error("Unknown hashing algorithm for 16 bit types: " +
1012 hash_name->constant);
1013 break;
1014 }
1015 case BASE_TYPE_INT:
1016 case BASE_TYPE_UINT: {
1017 if (FindHashFunction32(hash_name->constant.c_str()) == nullptr)
1018 return Error("Unknown hashing algorithm for 32 bit types: " +
1019 hash_name->constant);
1020 break;
1021 }
1022 case BASE_TYPE_LONG:
1023 case BASE_TYPE_ULONG: {
1024 if (FindHashFunction64(hash_name->constant.c_str()) == nullptr)
1025 return Error("Unknown hashing algorithm for 64 bit types: " +
1026 hash_name->constant);
1027 break;
1028 }
1029 default:
1030 return Error(
Austin Schuh272c6132020-11-14 16:37:52 -08001031 "only short, ushort, int, uint, long and ulong data types support "
1032 "hashing.");
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001033 }
1034 }
James Kuszmauldac091f2022-03-22 09:35:06 -07001035
1036 // For historical convenience reasons, string keys are assumed required.
1037 // Scalars are kDefault unless otherwise specified.
1038 // Nonscalars are kOptional unless required;
1039 field->key = field->attributes.Lookup("key") != nullptr;
1040 const bool required = field->attributes.Lookup("required") != nullptr ||
1041 (IsString(type) && field->key);
1042 const bool default_str_or_vec =
1043 ((IsString(type) || IsVector(type)) && field->value.constant != "0");
1044 const bool optional = IsScalar(type.base_type)
1045 ? (field->value.constant == "null")
1046 : !(required || default_str_or_vec);
1047 if (required && optional) {
1048 return Error("Fields cannot be both optional and required.");
1049 }
1050 field->presence = FieldDef::MakeFieldPresence(optional, required);
1051
1052 if (required && (struct_def.fixed || IsScalar(type.base_type))) {
1053 return Error("only non-scalar fields in tables may be 'required'");
1054 }
1055 if (field->key) {
1056 if (struct_def.has_key) return Error("only one field may be set as 'key'");
1057 struct_def.has_key = true;
1058 if (!IsScalar(type.base_type) && !IsString(type)) {
1059 return Error("'key' field must be string or scalar type");
1060 }
1061 }
1062
1063 if (field->IsScalarOptional()) {
1064 advanced_features_ |= static_cast<uint64_t>(reflection::AdvancedFeatures::OptionalScalars);
1065 if (type.enum_def && type.enum_def->Lookup("null")) {
1066 FLATBUFFERS_ASSERT(IsInteger(type.base_type));
1067 return Error(
1068 "the default 'null' is reserved for declaring optional scalar "
1069 "fields, it conflicts with declaration of enum '" +
1070 type.enum_def->name + "'.");
1071 }
1072 if (field->attributes.Lookup("key")) {
1073 return Error(
1074 "only a non-optional scalar field can be used as a 'key' field");
1075 }
1076 if (!SupportsOptionalScalars()) {
1077 return Error(
1078 "Optional scalars are not yet supported in at least one of "
1079 "the specified programming languages.");
1080 }
1081 }
1082
1083 if (type.enum_def) {
1084 // Verify the enum's type and default value.
1085 const std::string &constant = field->value.constant;
1086 if (type.base_type == BASE_TYPE_UNION) {
1087 if (constant != "0") { return Error("Union defaults must be NONE"); }
1088 } else if (IsVector(type)) {
1089 if (constant != "0" && constant != "[]") {
1090 return Error("Vector defaults may only be `[]`.");
1091 }
1092 } else if (IsArray(type)) {
1093 if (constant != "0") {
1094 return Error("Array defaults are not supported yet.");
1095 }
1096 } else {
1097 if (!IsInteger(type.base_type)) {
1098 return Error("Enums must have integer base types");
1099 }
1100 // Optional and bitflags enums may have default constants that are not
1101 // their specified variants.
1102 if (!field->IsOptional() &&
1103 type.enum_def->attributes.Lookup("bit_flags") == nullptr) {
1104 if (type.enum_def->FindByValue(constant) == nullptr) {
1105 return Error("default value of `" + constant + "` for " + "field `" +
1106 name + "` is not part of enum `" + type.enum_def->name +
1107 "`.");
1108 }
1109 }
1110 }
1111 }
1112
1113 if (field->deprecated && struct_def.fixed)
1114 return Error("can't deprecate fields in a struct");
1115
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001116 auto cpp_type = field->attributes.Lookup("cpp_type");
1117 if (cpp_type) {
1118 if (!hash_name)
1119 return Error("cpp_type can only be used with a hashed field");
1120 /// forcing cpp_ptr_type to 'naked' if unset
1121 auto cpp_ptr_type = field->attributes.Lookup("cpp_ptr_type");
1122 if (!cpp_ptr_type) {
1123 auto val = new Value();
1124 val->type = cpp_type->type;
1125 val->constant = "naked";
1126 field->attributes.Add("cpp_ptr_type", val);
1127 }
1128 }
Austin Schuh272c6132020-11-14 16:37:52 -08001129
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001130 field->shared = field->attributes.Lookup("shared") != nullptr;
1131 if (field->shared && field->value.type.base_type != BASE_TYPE_STRING)
1132 return Error("shared can only be defined on strings");
1133
1134 auto field_native_custom_alloc =
1135 field->attributes.Lookup("native_custom_alloc");
1136 if (field_native_custom_alloc)
1137 return Error(
1138 "native_custom_alloc can only be used with a table or struct "
1139 "definition");
1140
1141 field->native_inline = field->attributes.Lookup("native_inline") != nullptr;
Austin Schuha1d006e2022-09-14 21:50:42 -07001142 if (field->native_inline && !IsStruct(field->value.type) &&
1143 !IsVectorOfStruct(field->value.type) &&
1144 !IsVectorOfTable(field->value.type))
1145 return Error(
1146 "'native_inline' can only be defined on structs, vector of structs or "
1147 "vector of tables");
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001148
1149 auto nested = field->attributes.Lookup("nested_flatbuffer");
1150 if (nested) {
1151 if (nested->type.base_type != BASE_TYPE_STRING)
1152 return Error(
1153 "nested_flatbuffer attribute must be a string (the root type)");
1154 if (type.base_type != BASE_TYPE_VECTOR || type.element != BASE_TYPE_UCHAR)
1155 return Error(
1156 "nested_flatbuffer attribute may only apply to a vector of ubyte");
1157 // This will cause an error if the root type of the nested flatbuffer
1158 // wasn't defined elsewhere.
1159 field->nested_flatbuffer = LookupCreateStruct(nested->constant);
1160 }
1161
1162 if (field->attributes.Lookup("flexbuffer")) {
1163 field->flexbuffer = true;
1164 uses_flexbuffers_ = true;
Austin Schuh272c6132020-11-14 16:37:52 -08001165 if (type.base_type != BASE_TYPE_VECTOR || type.element != BASE_TYPE_UCHAR)
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001166 return Error("flexbuffer attribute may only apply to a vector of ubyte");
1167 }
1168
1169 if (typefield) {
1170 if (!IsScalar(typefield->value.type.base_type)) {
1171 // this is a union vector field
James Kuszmauldac091f2022-03-22 09:35:06 -07001172 typefield->presence = field->presence;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001173 }
1174 // If this field is a union, and it has a manually assigned id,
1175 // the automatically added type field should have an id as well (of N - 1).
1176 auto attr = field->attributes.Lookup("id");
1177 if (attr) {
James Kuszmauldac091f2022-03-22 09:35:06 -07001178 const auto &id_str = attr->constant;
1179 voffset_t id = 0;
1180 const auto done = !atot(id_str.c_str(), *this, &id).Check();
1181 if (done && id > 0) {
1182 auto val = new Value();
1183 val->type = attr->type;
1184 val->constant = NumToString(id - 1);
1185 typefield->attributes.Add("id", val);
1186 } else {
1187 return Error(
1188 "a union type effectively adds two fields with non-negative ids, "
1189 "its id must be that of the second field (the first field is "
1190 "the type field and not explicitly declared in the schema);\n"
1191 "field: " +
1192 field->name + ", id: " + id_str);
1193 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001194 }
Austin Schuh272c6132020-11-14 16:37:52 -08001195 // if this field is a union that is deprecated,
1196 // the automatically added type field should be deprecated as well
1197 if (field->deprecated) { typefield->deprecated = true; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001198 }
1199
1200 EXPECT(';');
1201 return NoError();
1202}
1203
Austin Schuh272c6132020-11-14 16:37:52 -08001204CheckedError Parser::ParseString(Value &val, bool use_string_pooling) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001205 auto s = attribute_;
1206 EXPECT(kTokenStringConstant);
Austin Schuh272c6132020-11-14 16:37:52 -08001207 if (use_string_pooling) {
1208 val.constant = NumToString(builder_.CreateSharedString(s).o);
1209 } else {
1210 val.constant = NumToString(builder_.CreateString(s).o);
1211 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001212 return NoError();
1213}
1214
1215CheckedError Parser::ParseComma() {
1216 if (!opts.protobuf_ascii_alike) EXPECT(',');
1217 return NoError();
1218}
1219
1220CheckedError Parser::ParseAnyValue(Value &val, FieldDef *field,
1221 size_t parent_fieldn,
1222 const StructDef *parent_struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -08001223 uoffset_t count, bool inside_vector) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001224 switch (val.type.base_type) {
1225 case BASE_TYPE_UNION: {
1226 FLATBUFFERS_ASSERT(field);
1227 std::string constant;
1228 Vector<uint8_t> *vector_of_union_types = nullptr;
1229 // Find corresponding type field we may have already parsed.
1230 for (auto elem = field_stack_.rbegin() + count;
1231 elem != field_stack_.rbegin() + parent_fieldn + count; ++elem) {
1232 auto &type = elem->second->value.type;
1233 if (type.enum_def == val.type.enum_def) {
1234 if (inside_vector) {
Austin Schuh272c6132020-11-14 16:37:52 -08001235 if (IsVector(type) && type.element == BASE_TYPE_UTYPE) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001236 // Vector of union type field.
1237 uoffset_t offset;
1238 ECHECK(atot(elem->first.constant.c_str(), *this, &offset));
1239 vector_of_union_types = reinterpret_cast<Vector<uint8_t> *>(
Austin Schuh272c6132020-11-14 16:37:52 -08001240 builder_.GetCurrentBufferPointer() + builder_.GetSize() -
1241 offset);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001242 break;
1243 }
1244 } else {
1245 if (type.base_type == BASE_TYPE_UTYPE) {
1246 // Union type field.
1247 constant = elem->first.constant;
1248 break;
1249 }
1250 }
1251 }
1252 }
1253 if (constant.empty() && !inside_vector) {
1254 // We haven't seen the type field yet. Sadly a lot of JSON writers
1255 // output these in alphabetical order, meaning it comes after this
1256 // value. So we scan past the value to find it, then come back here.
1257 // We currently don't do this for vectors of unions because the
1258 // scanning/serialization logic would get very complicated.
1259 auto type_name = field->name + UnionTypeFieldSuffix();
1260 FLATBUFFERS_ASSERT(parent_struct_def);
1261 auto type_field = parent_struct_def->fields.Lookup(type_name);
1262 FLATBUFFERS_ASSERT(type_field); // Guaranteed by ParseField().
1263 // Remember where we are in the source file, so we can come back here.
1264 auto backup = *static_cast<ParserState *>(this);
1265 ECHECK(SkipAnyJsonValue()); // The table.
1266 ECHECK(ParseComma());
1267 auto next_name = attribute_;
1268 if (Is(kTokenStringConstant)) {
1269 NEXT();
1270 } else {
1271 EXPECT(kTokenIdentifier);
1272 }
1273 if (next_name == type_name) {
1274 EXPECT(':');
James Kuszmauldac091f2022-03-22 09:35:06 -07001275 ParseDepthGuard depth_guard(this);
1276 ECHECK(depth_guard.Check());
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001277 Value type_val = type_field->value;
1278 ECHECK(ParseAnyValue(type_val, type_field, 0, nullptr, 0));
1279 constant = type_val.constant;
1280 // Got the information we needed, now rewind:
1281 *static_cast<ParserState *>(this) = backup;
1282 }
1283 }
1284 if (constant.empty() && !vector_of_union_types) {
Austin Schuh272c6132020-11-14 16:37:52 -08001285 return Error("missing type field for this union value: " + field->name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001286 }
1287 uint8_t enum_idx;
1288 if (vector_of_union_types) {
James Kuszmauldac091f2022-03-22 09:35:06 -07001289 if (vector_of_union_types->size() <= count)
Austin Schuha1d006e2022-09-14 21:50:42 -07001290 return Error(
1291 "union types vector smaller than union values vector for: " +
1292 field->name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001293 enum_idx = vector_of_union_types->Get(count);
1294 } else {
1295 ECHECK(atot(constant.c_str(), *this, &enum_idx));
1296 }
1297 auto enum_val = val.type.enum_def->ReverseLookup(enum_idx, true);
1298 if (!enum_val) return Error("illegal type id for: " + field->name);
1299 if (enum_val->union_type.base_type == BASE_TYPE_STRUCT) {
1300 ECHECK(ParseTable(*enum_val->union_type.struct_def, &val.constant,
1301 nullptr));
1302 if (enum_val->union_type.struct_def->fixed) {
1303 // All BASE_TYPE_UNION values are offsets, so turn this into one.
1304 SerializeStruct(*enum_val->union_type.struct_def, val);
1305 builder_.ClearOffsets();
1306 val.constant = NumToString(builder_.GetSize());
1307 }
Austin Schuh272c6132020-11-14 16:37:52 -08001308 } else if (IsString(enum_val->union_type)) {
1309 ECHECK(ParseString(val, field->shared));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001310 } else {
1311 FLATBUFFERS_ASSERT(false);
1312 }
1313 break;
1314 }
1315 case BASE_TYPE_STRUCT:
1316 ECHECK(ParseTable(*val.type.struct_def, &val.constant, nullptr));
1317 break;
1318 case BASE_TYPE_STRING: {
Austin Schuh272c6132020-11-14 16:37:52 -08001319 ECHECK(ParseString(val, field->shared));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001320 break;
1321 }
1322 case BASE_TYPE_VECTOR: {
1323 uoffset_t off;
1324 ECHECK(ParseVector(val.type.VectorType(), &off, field, parent_fieldn));
1325 val.constant = NumToString(off);
1326 break;
1327 }
1328 case BASE_TYPE_ARRAY: {
1329 ECHECK(ParseArray(val));
1330 break;
1331 }
1332 case BASE_TYPE_INT:
1333 case BASE_TYPE_UINT:
1334 case BASE_TYPE_LONG:
1335 case BASE_TYPE_ULONG: {
1336 if (field && field->attributes.Lookup("hash") &&
1337 (token_ == kTokenIdentifier || token_ == kTokenStringConstant)) {
1338 ECHECK(ParseHash(val, field));
1339 } else {
1340 ECHECK(ParseSingleValue(field ? &field->name : nullptr, val, false));
1341 }
1342 break;
1343 }
1344 default:
1345 ECHECK(ParseSingleValue(field ? &field->name : nullptr, val, false));
1346 break;
1347 }
1348 return NoError();
1349}
1350
1351void Parser::SerializeStruct(const StructDef &struct_def, const Value &val) {
1352 SerializeStruct(builder_, struct_def, val);
1353}
1354
1355void Parser::SerializeStruct(FlatBufferBuilder &builder,
1356 const StructDef &struct_def, const Value &val) {
1357 FLATBUFFERS_ASSERT(val.constant.length() == struct_def.bytesize);
1358 builder.Align(struct_def.minalign);
1359 builder.PushBytes(reinterpret_cast<const uint8_t *>(val.constant.c_str()),
1360 struct_def.bytesize);
1361 builder.AddStructOffset(val.offset, builder.GetSize());
1362}
1363
Austin Schuh272c6132020-11-14 16:37:52 -08001364template<typename F>
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001365CheckedError Parser::ParseTableDelimiters(size_t &fieldn,
Austin Schuh272c6132020-11-14 16:37:52 -08001366 const StructDef *struct_def, F body) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001367 // We allow tables both as JSON object{ .. } with field names
1368 // or vector[..] with all fields in order
1369 char terminator = '}';
1370 bool is_nested_vector = struct_def && Is('[');
1371 if (is_nested_vector) {
1372 NEXT();
1373 terminator = ']';
1374 } else {
1375 EXPECT('{');
1376 }
1377 for (;;) {
1378 if ((!opts.strict_json || !fieldn) && Is(terminator)) break;
1379 std::string name;
1380 if (is_nested_vector) {
1381 if (fieldn >= struct_def->fields.vec.size()) {
1382 return Error("too many unnamed fields in nested array");
1383 }
1384 name = struct_def->fields.vec[fieldn]->name;
1385 } else {
1386 name = attribute_;
1387 if (Is(kTokenStringConstant)) {
1388 NEXT();
1389 } else {
1390 EXPECT(opts.strict_json ? kTokenStringConstant : kTokenIdentifier);
1391 }
1392 if (!opts.protobuf_ascii_alike || !(Is('{') || Is('['))) EXPECT(':');
1393 }
1394 ECHECK(body(name, fieldn, struct_def));
1395 if (Is(terminator)) break;
1396 ECHECK(ParseComma());
1397 }
1398 NEXT();
1399 if (is_nested_vector && fieldn != struct_def->fields.vec.size()) {
1400 return Error("wrong number of unnamed fields in table vector");
1401 }
1402 return NoError();
1403}
1404
1405CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value,
1406 uoffset_t *ovalue) {
James Kuszmauldac091f2022-03-22 09:35:06 -07001407 ParseDepthGuard depth_guard(this);
1408 ECHECK(depth_guard.Check());
1409
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001410 size_t fieldn_outer = 0;
1411 auto err = ParseTableDelimiters(
1412 fieldn_outer, &struct_def,
1413 [&](const std::string &name, size_t &fieldn,
1414 const StructDef *struct_def_inner) -> CheckedError {
1415 if (name == "$schema") {
1416 ECHECK(Expect(kTokenStringConstant));
1417 return NoError();
1418 }
1419 auto field = struct_def_inner->fields.Lookup(name);
1420 if (!field) {
1421 if (!opts.skip_unexpected_fields_in_json) {
1422 return Error("unknown field: " + name);
1423 } else {
1424 ECHECK(SkipAnyJsonValue());
1425 }
1426 } else {
1427 if (IsIdent("null") && !IsScalar(field->value.type.base_type)) {
1428 ECHECK(Next()); // Ignore this field.
1429 } else {
1430 Value val = field->value;
1431 if (field->flexbuffer) {
1432 flexbuffers::Builder builder(1024,
1433 flexbuffers::BUILDER_FLAG_SHARE_ALL);
1434 ECHECK(ParseFlexBufferValue(&builder));
1435 builder.Finish();
1436 // Force alignment for nested flexbuffer
1437 builder_.ForceVectorAlignment(builder.GetSize(), sizeof(uint8_t),
1438 sizeof(largest_scalar_t));
1439 auto off = builder_.CreateVector(builder.GetBuffer());
1440 val.constant = NumToString(off.o);
1441 } else if (field->nested_flatbuffer) {
1442 ECHECK(
1443 ParseNestedFlatbuffer(val, field, fieldn, struct_def_inner));
1444 } else {
James Kuszmauldac091f2022-03-22 09:35:06 -07001445 ECHECK(ParseAnyValue(val, field, fieldn, struct_def_inner, 0));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001446 }
1447 // Hardcoded insertion-sort with error-check.
1448 // If fields are specified in order, then this loop exits
1449 // immediately.
1450 auto elem = field_stack_.rbegin();
1451 for (; elem != field_stack_.rbegin() + fieldn; ++elem) {
1452 auto existing_field = elem->second;
1453 if (existing_field == field)
1454 return Error("field set more than once: " + field->name);
1455 if (existing_field->value.offset < field->value.offset) break;
1456 }
1457 // Note: elem points to before the insertion point, thus .base()
1458 // points to the correct spot.
1459 field_stack_.insert(elem.base(), std::make_pair(val, field));
1460 fieldn++;
1461 }
1462 }
1463 return NoError();
1464 });
1465 ECHECK(err);
1466
1467 // Check if all required fields are parsed.
1468 for (auto field_it = struct_def.fields.vec.begin();
1469 field_it != struct_def.fields.vec.end(); ++field_it) {
1470 auto required_field = *field_it;
James Kuszmauldac091f2022-03-22 09:35:06 -07001471 if (!required_field->IsRequired()) { continue; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001472 bool found = false;
1473 for (auto pf_it = field_stack_.end() - fieldn_outer;
1474 pf_it != field_stack_.end(); ++pf_it) {
1475 auto parsed_field = pf_it->second;
1476 if (parsed_field == required_field) {
1477 found = true;
1478 break;
1479 }
1480 }
1481 if (!found) {
1482 return Error("required field is missing: " + required_field->name +
1483 " in " + struct_def.name);
1484 }
1485 }
1486
1487 if (struct_def.fixed && fieldn_outer != struct_def.fields.vec.size())
1488 return Error("struct: wrong number of initializers: " + struct_def.name);
1489
1490 auto start = struct_def.fixed ? builder_.StartStruct(struct_def.minalign)
1491 : builder_.StartTable();
1492
1493 for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1; size;
1494 size /= 2) {
1495 // Go through elements in reverse, since we're building the data backwards.
1496 for (auto it = field_stack_.rbegin();
1497 it != field_stack_.rbegin() + fieldn_outer; ++it) {
1498 auto &field_value = it->first;
1499 auto field = it->second;
1500 if (!struct_def.sortbysize ||
1501 size == SizeOf(field_value.type.base_type)) {
1502 switch (field_value.type.base_type) {
James Kuszmauldac091f2022-03-22 09:35:06 -07001503 // clang-format off
Austin Schuh272c6132020-11-14 16:37:52 -08001504 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001505 case BASE_TYPE_ ## ENUM: \
1506 builder_.Pad(field->padding); \
1507 if (struct_def.fixed) { \
1508 CTYPE val; \
1509 ECHECK(atot(field_value.constant.c_str(), *this, &val)); \
1510 builder_.PushElement(val); \
1511 } else { \
Austin Schuha1d006e2022-09-14 21:50:42 -07001512 if (field->IsScalarOptional()) { \
1513 if (field_value.constant != "null") { \
1514 CTYPE val; \
1515 ECHECK(atot(field_value.constant.c_str(), *this, &val)); \
1516 builder_.AddElement(field_value.offset, val); \
1517 } \
1518 } else { \
1519 CTYPE val, valdef; \
1520 ECHECK(atot(field_value.constant.c_str(), *this, &val)); \
1521 ECHECK(atot(field->value.constant.c_str(), *this, &valdef)); \
1522 builder_.AddElement(field_value.offset, val, valdef); \
1523 } \
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001524 } \
1525 break;
Austin Schuh272c6132020-11-14 16:37:52 -08001526 FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001527 #undef FLATBUFFERS_TD
Austin Schuh272c6132020-11-14 16:37:52 -08001528 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001529 case BASE_TYPE_ ## ENUM: \
1530 builder_.Pad(field->padding); \
1531 if (IsStruct(field->value.type)) { \
1532 SerializeStruct(*field->value.type.struct_def, field_value); \
1533 } else { \
1534 CTYPE val; \
1535 ECHECK(atot(field_value.constant.c_str(), *this, &val)); \
1536 builder_.AddOffset(field_value.offset, val); \
1537 } \
1538 break;
Austin Schuh272c6132020-11-14 16:37:52 -08001539 FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001540 #undef FLATBUFFERS_TD
1541 case BASE_TYPE_ARRAY:
1542 builder_.Pad(field->padding);
1543 builder_.PushBytes(
1544 reinterpret_cast<const uint8_t*>(field_value.constant.c_str()),
1545 InlineSize(field_value.type));
1546 break;
Austin Schuh272c6132020-11-14 16:37:52 -08001547 // clang-format on
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001548 }
1549 }
1550 }
1551 }
1552 for (size_t i = 0; i < fieldn_outer; i++) field_stack_.pop_back();
1553
1554 if (struct_def.fixed) {
1555 builder_.ClearOffsets();
1556 builder_.EndStruct();
1557 FLATBUFFERS_ASSERT(value);
1558 // Temporarily store this struct in the value string, since it is to
1559 // be serialized in-place elsewhere.
1560 value->assign(
1561 reinterpret_cast<const char *>(builder_.GetCurrentBufferPointer()),
1562 struct_def.bytesize);
1563 builder_.PopBytes(struct_def.bytesize);
1564 FLATBUFFERS_ASSERT(!ovalue);
1565 } else {
1566 auto val = builder_.EndTable(start);
1567 if (ovalue) *ovalue = val;
1568 if (value) *value = NumToString(val);
1569 }
1570 return NoError();
1571}
1572
Austin Schuh272c6132020-11-14 16:37:52 -08001573template<typename F>
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001574CheckedError Parser::ParseVectorDelimiters(uoffset_t &count, F body) {
1575 EXPECT('[');
1576 for (;;) {
1577 if ((!opts.strict_json || !count) && Is(']')) break;
1578 ECHECK(body(count));
1579 count++;
1580 if (Is(']')) break;
1581 ECHECK(ParseComma());
1582 }
1583 NEXT();
1584 return NoError();
1585}
1586
Austin Schuh272c6132020-11-14 16:37:52 -08001587
James Kuszmauldac091f2022-03-22 09:35:06 -07001588CheckedError Parser::ParseAlignAttribute(const std::string &align_constant,
1589 size_t min_align, size_t *align) {
1590 // Use uint8_t to avoid problems with size_t==`unsigned long` on LP64.
1591 uint8_t align_value;
1592 if (StringToNumber(align_constant.c_str(), &align_value) &&
1593 VerifyAlignmentRequirements(static_cast<size_t>(align_value),
1594 min_align)) {
1595 *align = align_value;
1596 return NoError();
1597 }
1598 return Error("unexpected force_align value '" + align_constant +
1599 "', alignment must be a power of two integer ranging from the "
1600 "type\'s natural alignment " +
1601 NumToString(min_align) + " to " +
1602 NumToString(FLATBUFFERS_MAX_ALIGNMENT));
1603}
1604
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001605CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue,
1606 FieldDef *field, size_t fieldn) {
1607 uoffset_t count = 0;
1608 auto err = ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
1609 Value val;
1610 val.type = type;
James Kuszmauldac091f2022-03-22 09:35:06 -07001611 ECHECK(ParseAnyValue(val, field, fieldn, nullptr, count, true));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001612 field_stack_.push_back(std::make_pair(val, nullptr));
1613 return NoError();
1614 });
1615 ECHECK(err);
1616
Austin Schuh272c6132020-11-14 16:37:52 -08001617 const size_t len = count * InlineSize(type) / InlineAlignment(type);
1618 const size_t elemsize = InlineAlignment(type);
James Kuszmauldac091f2022-03-22 09:35:06 -07001619 const auto force_align = field->attributes.Lookup("force_align");
1620 if (force_align) {
1621 size_t align;
1622 ECHECK(ParseAlignAttribute(force_align->constant, 1, &align));
1623 if (align > 1) { builder_.ForceVectorAlignment(len, elemsize, align); }
1624 }
Austin Schuh272c6132020-11-14 16:37:52 -08001625
1626 builder_.StartVector(len, elemsize);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001627 for (uoffset_t i = 0; i < count; i++) {
1628 // start at the back, since we're building the data backwards.
1629 auto &val = field_stack_.back().first;
1630 switch (val.type.base_type) {
James Kuszmauldac091f2022-03-22 09:35:06 -07001631 // clang-format off
Austin Schuh272c6132020-11-14 16:37:52 -08001632 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE,...) \
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001633 case BASE_TYPE_ ## ENUM: \
1634 if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \
1635 else { \
1636 CTYPE elem; \
1637 ECHECK(atot(val.constant.c_str(), *this, &elem)); \
1638 builder_.PushElement(elem); \
1639 } \
1640 break;
1641 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
1642 #undef FLATBUFFERS_TD
1643 // clang-format on
1644 }
1645 field_stack_.pop_back();
1646 }
1647
1648 builder_.ClearOffsets();
1649 *ovalue = builder_.EndVector(count);
Austin Schuh272c6132020-11-14 16:37:52 -08001650
1651 if (type.base_type == BASE_TYPE_STRUCT && type.struct_def->has_key) {
1652 // We should sort this vector. Find the key first.
1653 const FieldDef *key = nullptr;
1654 for (auto it = type.struct_def->fields.vec.begin();
1655 it != type.struct_def->fields.vec.end(); ++it) {
1656 if ((*it)->key) {
1657 key = (*it);
1658 break;
1659 }
1660 }
1661 FLATBUFFERS_ASSERT(key);
1662 // Now sort it.
1663 // We can't use std::sort because for structs the size is not known at
1664 // compile time, and for tables our iterators dereference offsets, so can't
1665 // be used to swap elements.
1666 // And we can't use C qsort either, since that would force use to use
1667 // globals, making parsing thread-unsafe.
1668 // So for now, we use SimpleQsort above.
1669 // TODO: replace with something better, preferably not recursive.
Austin Schuh272c6132020-11-14 16:37:52 -08001670
1671 if (type.struct_def->fixed) {
James Kuszmauldac091f2022-03-22 09:35:06 -07001672 const voffset_t offset = key->value.offset;
1673 const size_t struct_size = type.struct_def->bytesize;
Austin Schuh272c6132020-11-14 16:37:52 -08001674 auto v =
1675 reinterpret_cast<VectorOfAny *>(builder_.GetCurrentBufferPointer());
1676 SimpleQsort<uint8_t>(
1677 v->Data(), v->Data() + v->size() * type.struct_def->bytesize,
1678 type.struct_def->bytesize,
James Kuszmauldac091f2022-03-22 09:35:06 -07001679 [offset, key](const uint8_t *a, const uint8_t *b) -> bool {
1680 return CompareSerializedScalars(a + offset, b + offset, *key);
Austin Schuh272c6132020-11-14 16:37:52 -08001681 },
James Kuszmauldac091f2022-03-22 09:35:06 -07001682 [struct_size](uint8_t *a, uint8_t *b) {
Austin Schuh272c6132020-11-14 16:37:52 -08001683 // FIXME: faster?
James Kuszmauldac091f2022-03-22 09:35:06 -07001684 for (size_t i = 0; i < struct_size; i++) { std::swap(a[i], b[i]); }
Austin Schuh272c6132020-11-14 16:37:52 -08001685 });
1686 } else {
1687 auto v = reinterpret_cast<Vector<Offset<Table>> *>(
1688 builder_.GetCurrentBufferPointer());
1689 // Here also can't use std::sort. We do have an iterator type for it,
1690 // but it is non-standard as it will dereference the offsets, and thus
1691 // can't be used to swap elements.
James Kuszmauldac091f2022-03-22 09:35:06 -07001692 if (key->value.type.base_type == BASE_TYPE_STRING) {
1693 SimpleQsort<Offset<Table>>(
1694 v->data(), v->data() + v->size(), 1,
1695 [key](const Offset<Table> *_a, const Offset<Table> *_b) -> bool {
1696 return CompareTablesByStringKey(_a, _b, *key);
1697 },
1698 SwapSerializedTables);
1699 } else {
1700 SimpleQsort<Offset<Table>>(
1701 v->data(), v->data() + v->size(), 1,
1702 [key](const Offset<Table> *_a, const Offset<Table> *_b) -> bool {
1703 return CompareTablesByScalarKey(_a, _b, *key);
1704 },
1705 SwapSerializedTables);
1706 }
Austin Schuh272c6132020-11-14 16:37:52 -08001707 }
1708 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001709 return NoError();
1710}
1711
1712CheckedError Parser::ParseArray(Value &array) {
1713 std::vector<Value> stack;
1714 FlatBufferBuilder builder;
1715 const auto &type = array.type.VectorType();
1716 auto length = array.type.fixed_length;
1717 uoffset_t count = 0;
1718 auto err = ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
James Kuszmauldac091f2022-03-22 09:35:06 -07001719 stack.emplace_back(Value());
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001720 auto &val = stack.back();
1721 val.type = type;
1722 if (IsStruct(type)) {
1723 ECHECK(ParseTable(*val.type.struct_def, &val.constant, nullptr));
1724 } else {
1725 ECHECK(ParseSingleValue(nullptr, val, false));
1726 }
1727 return NoError();
1728 });
1729 ECHECK(err);
1730 if (length != count) return Error("Fixed-length array size is incorrect.");
1731
1732 for (auto it = stack.rbegin(); it != stack.rend(); ++it) {
1733 auto &val = *it;
1734 // clang-format off
1735 switch (val.type.base_type) {
Austin Schuh272c6132020-11-14 16:37:52 -08001736 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001737 case BASE_TYPE_ ## ENUM: \
1738 if (IsStruct(val.type)) { \
1739 SerializeStruct(builder, *val.type.struct_def, val); \
1740 } else { \
1741 CTYPE elem; \
1742 ECHECK(atot(val.constant.c_str(), *this, &elem)); \
1743 builder.PushElement(elem); \
1744 } \
1745 break;
1746 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
1747 #undef FLATBUFFERS_TD
1748 default: FLATBUFFERS_ASSERT(0);
1749 }
1750 // clang-format on
1751 }
1752
1753 array.constant.assign(
1754 reinterpret_cast<const char *>(builder.GetCurrentBufferPointer()),
1755 InlineSize(array.type));
1756 return NoError();
1757}
1758
1759CheckedError Parser::ParseNestedFlatbuffer(Value &val, FieldDef *field,
1760 size_t fieldn,
1761 const StructDef *parent_struct_def) {
1762 if (token_ == '[') { // backwards compat for 'legacy' ubyte buffers
James Kuszmauldac091f2022-03-22 09:35:06 -07001763 if (opts.json_nested_legacy_flatbuffers) {
1764 ECHECK(ParseAnyValue(val, field, fieldn, parent_struct_def, 0));
1765 } else {
1766 return Error(
1767 "cannot parse nested_flatbuffer as bytes unless"
1768 " --json-nested-bytes is set");
1769 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001770 } else {
1771 auto cursor_at_value_begin = cursor_;
1772 ECHECK(SkipAnyJsonValue());
1773 std::string substring(cursor_at_value_begin - 1, cursor_ - 1);
1774
1775 // Create and initialize new parser
1776 Parser nested_parser;
1777 FLATBUFFERS_ASSERT(field->nested_flatbuffer);
1778 nested_parser.root_struct_def_ = field->nested_flatbuffer;
1779 nested_parser.enums_ = enums_;
1780 nested_parser.opts = opts;
1781 nested_parser.uses_flexbuffers_ = uses_flexbuffers_;
James Kuszmauldac091f2022-03-22 09:35:06 -07001782 nested_parser.parse_depth_counter_ = parse_depth_counter_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001783 // Parse JSON substring into new flatbuffer builder using nested_parser
1784 bool ok = nested_parser.Parse(substring.c_str(), nullptr, nullptr);
1785
1786 // Clean nested_parser to avoid deleting the elements in
1787 // the SymbolTables on destruction
1788 nested_parser.enums_.dict.clear();
1789 nested_parser.enums_.vec.clear();
1790
Austin Schuh272c6132020-11-14 16:37:52 -08001791 if (!ok) { ECHECK(Error(nested_parser.error_)); }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001792 // Force alignment for nested flatbuffer
Austin Schuh272c6132020-11-14 16:37:52 -08001793 builder_.ForceVectorAlignment(
1794 nested_parser.builder_.GetSize(), sizeof(uint8_t),
1795 nested_parser.builder_.GetBufferMinAlignment());
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001796
1797 auto off = builder_.CreateVector(nested_parser.builder_.GetBufferPointer(),
1798 nested_parser.builder_.GetSize());
1799 val.constant = NumToString(off.o);
1800 }
1801 return NoError();
1802}
1803
1804CheckedError Parser::ParseMetaData(SymbolTable<Value> *attributes) {
1805 if (Is('(')) {
1806 NEXT();
1807 for (;;) {
1808 auto name = attribute_;
1809 if (false == (Is(kTokenIdentifier) || Is(kTokenStringConstant)))
1810 return Error("attribute name must be either identifier or string: " +
Austin Schuh272c6132020-11-14 16:37:52 -08001811 name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001812 if (known_attributes_.find(name) == known_attributes_.end())
1813 return Error("user define attributes must be declared before use: " +
1814 name);
1815 NEXT();
1816 auto e = new Value();
Austin Schuh272c6132020-11-14 16:37:52 -08001817 if (attributes->Add(name, e)) Warning("attribute already found: " + name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001818 if (Is(':')) {
1819 NEXT();
1820 ECHECK(ParseSingleValue(&name, *e, true));
1821 }
1822 if (Is(')')) {
1823 NEXT();
1824 break;
1825 }
1826 EXPECT(',');
1827 }
1828 }
1829 return NoError();
1830}
1831
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001832CheckedError Parser::ParseEnumFromString(const Type &type,
1833 std::string *result) {
1834 const auto base_type =
1835 type.enum_def ? type.enum_def->underlying_type.base_type : type.base_type;
1836 if (!IsInteger(base_type)) return Error("not a valid value for this field");
1837 uint64_t u64 = 0;
1838 for (size_t pos = 0; pos != std::string::npos;) {
1839 const auto delim = attribute_.find_first_of(' ', pos);
1840 const auto last = (std::string::npos == delim);
1841 auto word = attribute_.substr(pos, !last ? delim - pos : std::string::npos);
1842 pos = !last ? delim + 1 : std::string::npos;
1843 const EnumVal *ev = nullptr;
1844 if (type.enum_def) {
1845 ev = type.enum_def->Lookup(word);
1846 } else {
1847 auto dot = word.find_first_of('.');
1848 if (std::string::npos == dot)
1849 return Error("enum values need to be qualified by an enum type");
1850 auto enum_def_str = word.substr(0, dot);
1851 const auto enum_def = LookupEnum(enum_def_str);
1852 if (!enum_def) return Error("unknown enum: " + enum_def_str);
1853 auto enum_val_str = word.substr(dot + 1);
1854 ev = enum_def->Lookup(enum_val_str);
1855 }
1856 if (!ev) return Error("unknown enum value: " + word);
1857 u64 |= ev->GetAsUInt64();
1858 }
1859 *result = IsUnsigned(base_type) ? NumToString(u64)
1860 : NumToString(static_cast<int64_t>(u64));
1861 return NoError();
1862}
1863
1864CheckedError Parser::ParseHash(Value &e, FieldDef *field) {
1865 FLATBUFFERS_ASSERT(field);
1866 Value *hash_name = field->attributes.Lookup("hash");
1867 switch (e.type.base_type) {
1868 case BASE_TYPE_SHORT: {
1869 auto hash = FindHashFunction16(hash_name->constant.c_str());
1870 int16_t hashed_value = static_cast<int16_t>(hash(attribute_.c_str()));
1871 e.constant = NumToString(hashed_value);
1872 break;
1873 }
1874 case BASE_TYPE_USHORT: {
1875 auto hash = FindHashFunction16(hash_name->constant.c_str());
1876 uint16_t hashed_value = hash(attribute_.c_str());
1877 e.constant = NumToString(hashed_value);
1878 break;
1879 }
1880 case BASE_TYPE_INT: {
1881 auto hash = FindHashFunction32(hash_name->constant.c_str());
1882 int32_t hashed_value = static_cast<int32_t>(hash(attribute_.c_str()));
1883 e.constant = NumToString(hashed_value);
1884 break;
1885 }
1886 case BASE_TYPE_UINT: {
1887 auto hash = FindHashFunction32(hash_name->constant.c_str());
1888 uint32_t hashed_value = hash(attribute_.c_str());
1889 e.constant = NumToString(hashed_value);
1890 break;
1891 }
1892 case BASE_TYPE_LONG: {
1893 auto hash = FindHashFunction64(hash_name->constant.c_str());
1894 int64_t hashed_value = static_cast<int64_t>(hash(attribute_.c_str()));
1895 e.constant = NumToString(hashed_value);
1896 break;
1897 }
1898 case BASE_TYPE_ULONG: {
1899 auto hash = FindHashFunction64(hash_name->constant.c_str());
1900 uint64_t hashed_value = hash(attribute_.c_str());
1901 e.constant = NumToString(hashed_value);
1902 break;
1903 }
1904 default: FLATBUFFERS_ASSERT(0);
1905 }
1906 NEXT();
1907 return NoError();
1908}
1909
1910CheckedError Parser::TokenError() {
1911 return Error("cannot parse value starting with: " + TokenToStringId(token_));
1912}
1913
Austin Schuh272c6132020-11-14 16:37:52 -08001914CheckedError Parser::ParseFunction(const std::string *name, Value &e) {
James Kuszmauldac091f2022-03-22 09:35:06 -07001915 ParseDepthGuard depth_guard(this);
1916 ECHECK(depth_guard.Check());
1917
Austin Schuh272c6132020-11-14 16:37:52 -08001918 // Copy name, attribute will be changed on NEXT().
1919 const auto functionname = attribute_;
1920 if (!IsFloat(e.type.base_type)) {
1921 return Error(functionname + ": type of argument mismatch, expecting: " +
1922 kTypeNames[BASE_TYPE_DOUBLE] +
1923 ", found: " + kTypeNames[e.type.base_type] +
1924 ", name: " + (name ? *name : "") + ", value: " + e.constant);
1925 }
1926 NEXT();
1927 EXPECT('(');
James Kuszmauldac091f2022-03-22 09:35:06 -07001928 ECHECK(ParseSingleValue(name, e, false));
Austin Schuh272c6132020-11-14 16:37:52 -08001929 EXPECT(')');
1930 // calculate with double precision
1931 double x, y = 0.0;
1932 ECHECK(atot(e.constant.c_str(), *this, &x));
1933 // clang-format off
1934 auto func_match = false;
1935 #define FLATBUFFERS_FN_DOUBLE(name, op) \
1936 if (!func_match && functionname == name) { y = op; func_match = true; }
1937 FLATBUFFERS_FN_DOUBLE("deg", x / kPi * 180);
1938 FLATBUFFERS_FN_DOUBLE("rad", x * kPi / 180);
1939 FLATBUFFERS_FN_DOUBLE("sin", sin(x));
1940 FLATBUFFERS_FN_DOUBLE("cos", cos(x));
1941 FLATBUFFERS_FN_DOUBLE("tan", tan(x));
1942 FLATBUFFERS_FN_DOUBLE("asin", asin(x));
1943 FLATBUFFERS_FN_DOUBLE("acos", acos(x));
1944 FLATBUFFERS_FN_DOUBLE("atan", atan(x));
1945 // TODO(wvo): add more useful conversion functions here.
1946 #undef FLATBUFFERS_FN_DOUBLE
1947 // clang-format on
1948 if (true != func_match) {
1949 return Error(std::string("Unknown conversion function: ") + functionname +
1950 ", field name: " + (name ? *name : "") +
1951 ", value: " + e.constant);
1952 }
1953 e.constant = NumToString(y);
1954 return NoError();
1955}
1956
1957CheckedError Parser::TryTypedValue(const std::string *name, int dtoken,
1958 bool check, Value &e, BaseType req,
1959 bool *destmatch) {
James Kuszmauldac091f2022-03-22 09:35:06 -07001960 FLATBUFFERS_ASSERT(*destmatch == false && dtoken == token_);
1961 *destmatch = true;
1962 e.constant = attribute_;
1963 // Check token match
1964 if (!check) {
1965 if (e.type.base_type == BASE_TYPE_NONE) {
1966 e.type.base_type = req;
1967 } else {
1968 return Error(std::string("type mismatch: expecting: ") +
1969 kTypeNames[e.type.base_type] +
1970 ", found: " + kTypeNames[req] +
1971 ", name: " + (name ? *name : "") + ", value: " + e.constant);
Austin Schuh272c6132020-11-14 16:37:52 -08001972 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001973 }
James Kuszmauldac091f2022-03-22 09:35:06 -07001974 // The exponent suffix of hexadecimal float-point number is mandatory.
1975 // A hex-integer constant is forbidden as an initializer of float number.
1976 if ((kTokenFloatConstant != dtoken) && IsFloat(e.type.base_type)) {
1977 const auto &s = e.constant;
1978 const auto k = s.find_first_of("0123456789.");
1979 if ((std::string::npos != k) && (s.length() > (k + 1)) &&
1980 (s[k] == '0' && is_alpha_char(s[k + 1], 'X')) &&
1981 (std::string::npos == s.find_first_of("pP", k + 2))) {
1982 return Error(
1983 "invalid number, the exponent suffix of hexadecimal "
1984 "floating-point literals is mandatory: \"" +
1985 s + "\"");
1986 }
1987 }
1988 NEXT();
Austin Schuh272c6132020-11-14 16:37:52 -08001989 return NoError();
1990}
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001991
Austin Schuh272c6132020-11-14 16:37:52 -08001992CheckedError Parser::ParseSingleValue(const std::string *name, Value &e,
1993 bool check_now) {
James Kuszmauldac091f2022-03-22 09:35:06 -07001994 if (token_ == '+' || token_ == '-') {
1995 const char sign = static_cast<char>(token_);
1996 // Get an indentifier: NAN, INF, or function name like cos/sin/deg.
1997 NEXT();
1998 if (token_ != kTokenIdentifier) return Error("constant name expected");
1999 attribute_.insert(0, 1, sign);
2000 }
2001
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002002 const auto in_type = e.type.base_type;
Austin Schuh272c6132020-11-14 16:37:52 -08002003 const auto is_tok_ident = (token_ == kTokenIdentifier);
2004 const auto is_tok_string = (token_ == kTokenStringConstant);
2005
James Kuszmauldac091f2022-03-22 09:35:06 -07002006 // First see if this could be a conversion function.
Austin Schuh272c6132020-11-14 16:37:52 -08002007 if (is_tok_ident && *cursor_ == '(') { return ParseFunction(name, e); }
2008
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002009 // clang-format off
Austin Schuh272c6132020-11-14 16:37:52 -08002010 auto match = false;
2011
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002012 #define IF_ECHECK_(force, dtoken, check, req) \
James Kuszmauldac091f2022-03-22 09:35:06 -07002013 if (!match && ((dtoken) == token_) && ((check) || IsConstTrue(force))) \
2014 ECHECK(TryTypedValue(name, dtoken, check, e, req, &match))
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002015 #define TRY_ECHECK(dtoken, check, req) IF_ECHECK_(false, dtoken, check, req)
2016 #define FORCE_ECHECK(dtoken, check, req) IF_ECHECK_(true, dtoken, check, req)
2017 // clang-format on
2018
Austin Schuh272c6132020-11-14 16:37:52 -08002019 if (is_tok_ident || is_tok_string) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002020 const auto kTokenStringOrIdent = token_;
2021 // The string type is a most probable type, check it first.
2022 TRY_ECHECK(kTokenStringConstant, in_type == BASE_TYPE_STRING,
2023 BASE_TYPE_STRING);
2024
2025 // avoid escaped and non-ascii in the string
Austin Schuh272c6132020-11-14 16:37:52 -08002026 if (!match && is_tok_string && IsScalar(in_type) &&
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002027 !attr_is_trivial_ascii_string_) {
2028 return Error(
2029 std::string("type mismatch or invalid value, an initializer of "
2030 "non-string field must be trivial ASCII string: type: ") +
2031 kTypeNames[in_type] + ", name: " + (name ? *name : "") +
2032 ", value: " + attribute_);
2033 }
2034
2035 // A boolean as true/false. Boolean as Integer check below.
2036 if (!match && IsBool(in_type)) {
2037 auto is_true = attribute_ == "true";
2038 if (is_true || attribute_ == "false") {
2039 attribute_ = is_true ? "1" : "0";
2040 // accepts both kTokenStringConstant and kTokenIdentifier
2041 TRY_ECHECK(kTokenStringOrIdent, IsBool(in_type), BASE_TYPE_BOOL);
2042 }
2043 }
Austin Schuh272c6132020-11-14 16:37:52 -08002044 // Check for optional scalars.
2045 if (!match && IsScalar(in_type) && attribute_ == "null") {
2046 e.constant = "null";
2047 NEXT();
2048 match = true;
2049 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002050 // Check if this could be a string/identifier enum value.
2051 // Enum can have only true integer base type.
2052 if (!match && IsInteger(in_type) && !IsBool(in_type) &&
2053 IsIdentifierStart(*attribute_.c_str())) {
2054 ECHECK(ParseEnumFromString(e.type, &e.constant));
2055 NEXT();
2056 match = true;
2057 }
2058 // Parse a float/integer number from the string.
Austin Schuh272c6132020-11-14 16:37:52 -08002059 // A "scalar-in-string" value needs extra checks.
2060 if (!match && is_tok_string && IsScalar(in_type)) {
2061 // Strip trailing whitespaces from attribute_.
2062 auto last_non_ws = attribute_.find_last_not_of(' ');
2063 if (std::string::npos != last_non_ws) attribute_.resize(last_non_ws + 1);
2064 if (IsFloat(e.type.base_type)) {
2065 // The functions strtod() and strtof() accept both 'nan' and
2066 // 'nan(number)' literals. While 'nan(number)' is rejected by the parser
2067 // as an unsupported function if is_tok_ident is true.
2068 if (attribute_.find_last_of(')') != std::string::npos) {
2069 return Error("invalid number: " + attribute_);
2070 }
2071 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002072 }
2073 // Float numbers or nan, inf, pi, etc.
2074 TRY_ECHECK(kTokenStringOrIdent, IsFloat(in_type), BASE_TYPE_FLOAT);
2075 // An integer constant in string.
2076 TRY_ECHECK(kTokenStringOrIdent, IsInteger(in_type), BASE_TYPE_INT);
2077 // Unknown tokens will be interpreted as string type.
2078 // An attribute value may be a scalar or string constant.
2079 FORCE_ECHECK(kTokenStringConstant, in_type == BASE_TYPE_STRING,
2080 BASE_TYPE_STRING);
2081 } else {
2082 // Try a float number.
2083 TRY_ECHECK(kTokenFloatConstant, IsFloat(in_type), BASE_TYPE_FLOAT);
2084 // Integer token can init any scalar (integer of float).
2085 FORCE_ECHECK(kTokenIntegerConstant, IsScalar(in_type), BASE_TYPE_INT);
2086 }
James Kuszmauldac091f2022-03-22 09:35:06 -07002087 // Match empty vectors for default-empty-vectors.
2088 if (!match && IsVector(e.type) && token_ == '[') {
2089 NEXT();
2090 if (token_ != ']') { return Error("Expected `]` in vector default"); }
2091 NEXT();
2092 match = true;
2093 e.constant = "[]";
2094 }
2095
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002096#undef FORCE_ECHECK
2097#undef TRY_ECHECK
2098#undef IF_ECHECK_
2099
2100 if (!match) {
2101 std::string msg;
2102 msg += "Cannot assign token starting with '" + TokenToStringId(token_) +
2103 "' to value of <" + std::string(kTypeNames[in_type]) + "> type.";
2104 return Error(msg);
2105 }
Austin Schuh272c6132020-11-14 16:37:52 -08002106 const auto match_type = e.type.base_type; // may differ from in_type
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002107 // The check_now flag must be true when parse a fbs-schema.
2108 // This flag forces to check default scalar values or metadata of field.
2109 // For JSON parser the flag should be false.
2110 // If it is set for JSON each value will be checked twice (see ParseTable).
Austin Schuh272c6132020-11-14 16:37:52 -08002111 // Special case 'null' since atot can't handle that.
2112 if (check_now && IsScalar(match_type) && e.constant != "null") {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002113 // clang-format off
2114 switch (match_type) {
Austin Schuh272c6132020-11-14 16:37:52 -08002115 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
2116 case BASE_TYPE_ ## ENUM: {\
2117 CTYPE val; \
2118 ECHECK(atot(e.constant.c_str(), *this, &val)); \
2119 SingleValueRepack(e, val); \
2120 break; }
2121 FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002122 #undef FLATBUFFERS_TD
2123 default: break;
2124 }
2125 // clang-format on
2126 }
2127 return NoError();
2128}
2129
2130StructDef *Parser::LookupCreateStruct(const std::string &name,
2131 bool create_if_new, bool definition) {
2132 std::string qualified_name = current_namespace_->GetFullyQualifiedName(name);
2133 // See if it exists pre-declared by an unqualified use.
2134 auto struct_def = LookupStruct(name);
2135 if (struct_def && struct_def->predecl) {
2136 if (definition) {
2137 // Make sure it has the current namespace, and is registered under its
2138 // qualified name.
2139 struct_def->defined_namespace = current_namespace_;
2140 structs_.Move(name, qualified_name);
2141 }
2142 return struct_def;
2143 }
2144 // See if it exists pre-declared by an qualified use.
2145 struct_def = LookupStruct(qualified_name);
2146 if (struct_def && struct_def->predecl) {
2147 if (definition) {
2148 // Make sure it has the current namespace.
2149 struct_def->defined_namespace = current_namespace_;
2150 }
2151 return struct_def;
2152 }
James Kuszmauldac091f2022-03-22 09:35:06 -07002153 if (!definition && !struct_def) {
2154 struct_def = LookupStructThruParentNamespaces(name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002155 }
2156 if (!struct_def && create_if_new) {
2157 struct_def = new StructDef();
2158 if (definition) {
2159 structs_.Add(qualified_name, struct_def);
2160 struct_def->name = name;
2161 struct_def->defined_namespace = current_namespace_;
2162 } else {
2163 // Not a definition.
2164 // Rather than failing, we create a "pre declared" StructDef, due to
2165 // circular references, and check for errors at the end of parsing.
2166 // It is defined in the current namespace, as the best guess what the
2167 // final namespace will be.
2168 structs_.Add(name, struct_def);
2169 struct_def->name = name;
2170 struct_def->defined_namespace = current_namespace_;
2171 struct_def->original_location.reset(
2172 new std::string(file_being_parsed_ + ":" + NumToString(line_)));
2173 }
2174 }
2175 return struct_def;
2176}
2177
2178const EnumVal *EnumDef::MinValue() const {
2179 return vals.vec.empty() ? nullptr : vals.vec.front();
2180}
2181const EnumVal *EnumDef::MaxValue() const {
2182 return vals.vec.empty() ? nullptr : vals.vec.back();
2183}
2184
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002185uint64_t EnumDef::Distance(const EnumVal *v1, const EnumVal *v2) const {
2186 return IsUInt64() ? EnumDistanceImpl(v1->GetAsUInt64(), v2->GetAsUInt64())
2187 : EnumDistanceImpl(v1->GetAsInt64(), v2->GetAsInt64());
2188}
2189
2190std::string EnumDef::AllFlags() const {
2191 FLATBUFFERS_ASSERT(attributes.Lookup("bit_flags"));
2192 uint64_t u64 = 0;
2193 for (auto it = Vals().begin(); it != Vals().end(); ++it) {
2194 u64 |= (*it)->GetAsUInt64();
2195 }
2196 return IsUInt64() ? NumToString(u64) : NumToString(static_cast<int64_t>(u64));
2197}
2198
2199EnumVal *EnumDef::ReverseLookup(int64_t enum_idx,
2200 bool skip_union_default) const {
2201 auto skip_first = static_cast<int>(is_union && skip_union_default);
2202 for (auto it = Vals().begin() + skip_first; it != Vals().end(); ++it) {
2203 if ((*it)->GetAsInt64() == enum_idx) { return *it; }
2204 }
2205 return nullptr;
2206}
2207
2208EnumVal *EnumDef::FindByValue(const std::string &constant) const {
2209 int64_t i64;
2210 auto done = false;
2211 if (IsUInt64()) {
2212 uint64_t u64; // avoid reinterpret_cast of pointers
2213 done = StringToNumber(constant.c_str(), &u64);
2214 i64 = static_cast<int64_t>(u64);
2215 } else {
2216 done = StringToNumber(constant.c_str(), &i64);
2217 }
2218 FLATBUFFERS_ASSERT(done);
2219 if (!done) return nullptr;
2220 return ReverseLookup(i64, false);
2221}
2222
2223void EnumDef::SortByValue() {
2224 auto &v = vals.vec;
2225 if (IsUInt64())
2226 std::sort(v.begin(), v.end(), [](const EnumVal *e1, const EnumVal *e2) {
James Kuszmauldac091f2022-03-22 09:35:06 -07002227 if (e1->GetAsUInt64() == e2->GetAsUInt64()) {
2228 return e1->name < e2->name;
2229 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002230 return e1->GetAsUInt64() < e2->GetAsUInt64();
2231 });
2232 else
2233 std::sort(v.begin(), v.end(), [](const EnumVal *e1, const EnumVal *e2) {
James Kuszmauldac091f2022-03-22 09:35:06 -07002234 if (e1->GetAsInt64() == e2->GetAsInt64()) { return e1->name < e2->name; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002235 return e1->GetAsInt64() < e2->GetAsInt64();
2236 });
2237}
2238
2239void EnumDef::RemoveDuplicates() {
2240 // This method depends form SymbolTable implementation!
2241 // 1) vals.vec - owner (raw pointer)
2242 // 2) vals.dict - access map
2243 auto first = vals.vec.begin();
2244 auto last = vals.vec.end();
2245 if (first == last) return;
2246 auto result = first;
2247 while (++first != last) {
2248 if ((*result)->value != (*first)->value) {
2249 *(++result) = *first;
2250 } else {
2251 auto ev = *first;
2252 for (auto it = vals.dict.begin(); it != vals.dict.end(); ++it) {
2253 if (it->second == ev) it->second = *result; // reassign
2254 }
2255 delete ev; // delete enum value
2256 *first = nullptr;
2257 }
2258 }
2259 vals.vec.erase(++result, last);
2260}
2261
2262template<typename T> void EnumDef::ChangeEnumValue(EnumVal *ev, T new_value) {
2263 ev->value = static_cast<int64_t>(new_value);
2264}
2265
2266namespace EnumHelper {
2267template<BaseType E> struct EnumValType { typedef int64_t type; };
2268template<> struct EnumValType<BASE_TYPE_ULONG> { typedef uint64_t type; };
2269} // namespace EnumHelper
2270
2271struct EnumValBuilder {
2272 EnumVal *CreateEnumerator(const std::string &ev_name) {
2273 FLATBUFFERS_ASSERT(!temp);
2274 auto first = enum_def.vals.vec.empty();
2275 user_value = first;
2276 temp = new EnumVal(ev_name, first ? 0 : enum_def.vals.vec.back()->value);
2277 return temp;
2278 }
2279
2280 EnumVal *CreateEnumerator(const std::string &ev_name, int64_t val) {
2281 FLATBUFFERS_ASSERT(!temp);
2282 user_value = true;
2283 temp = new EnumVal(ev_name, val);
2284 return temp;
2285 }
2286
2287 FLATBUFFERS_CHECKED_ERROR AcceptEnumerator(const std::string &name) {
2288 FLATBUFFERS_ASSERT(temp);
2289 ECHECK(ValidateValue(&temp->value, false == user_value));
2290 FLATBUFFERS_ASSERT((temp->union_type.enum_def == nullptr) ||
2291 (temp->union_type.enum_def == &enum_def));
2292 auto not_unique = enum_def.vals.Add(name, temp);
2293 temp = nullptr;
2294 if (not_unique) return parser.Error("enum value already exists: " + name);
2295 return NoError();
2296 }
2297
2298 FLATBUFFERS_CHECKED_ERROR AcceptEnumerator() {
2299 return AcceptEnumerator(temp->name);
2300 }
2301
2302 FLATBUFFERS_CHECKED_ERROR AssignEnumeratorValue(const std::string &value) {
2303 user_value = true;
2304 auto fit = false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002305 if (enum_def.IsUInt64()) {
2306 uint64_t u64;
2307 fit = StringToNumber(value.c_str(), &u64);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002308 temp->value = static_cast<int64_t>(u64); // well-defined since C++20.
2309 } else {
2310 int64_t i64;
2311 fit = StringToNumber(value.c_str(), &i64);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002312 temp->value = i64;
2313 }
2314 if (!fit) return parser.Error("enum value does not fit, \"" + value + "\"");
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002315 return NoError();
2316 }
2317
2318 template<BaseType E, typename CTYPE>
2319 inline FLATBUFFERS_CHECKED_ERROR ValidateImpl(int64_t *ev, int m) {
2320 typedef typename EnumHelper::EnumValType<E>::type T; // int64_t or uint64_t
2321 static_assert(sizeof(T) == sizeof(int64_t), "invalid EnumValType");
2322 const auto v = static_cast<T>(*ev);
2323 auto up = static_cast<T>((flatbuffers::numeric_limits<CTYPE>::max)());
2324 auto dn = static_cast<T>((flatbuffers::numeric_limits<CTYPE>::lowest)());
2325 if (v < dn || v > (up - m)) {
2326 return parser.Error("enum value does not fit, \"" + NumToString(v) +
2327 (m ? " + 1\"" : "\"") + " out of " +
2328 TypeToIntervalString<CTYPE>());
2329 }
2330 *ev = static_cast<int64_t>(v + m); // well-defined since C++20.
2331 return NoError();
2332 }
2333
2334 FLATBUFFERS_CHECKED_ERROR ValidateValue(int64_t *ev, bool next) {
2335 // clang-format off
2336 switch (enum_def.underlying_type.base_type) {
Austin Schuh272c6132020-11-14 16:37:52 -08002337 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002338 case BASE_TYPE_##ENUM: { \
2339 if (!IsInteger(BASE_TYPE_##ENUM)) break; \
2340 return ValidateImpl<BASE_TYPE_##ENUM, CTYPE>(ev, next ? 1 : 0); \
2341 }
Austin Schuh272c6132020-11-14 16:37:52 -08002342 FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002343 #undef FLATBUFFERS_TD
2344 default: break;
2345 }
2346 // clang-format on
2347 return parser.Error("fatal: invalid enum underlying type");
2348 }
2349
Austin Schuh272c6132020-11-14 16:37:52 -08002350 EnumValBuilder(Parser &_parser, EnumDef &_enum_def)
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002351 : parser(_parser),
2352 enum_def(_enum_def),
2353 temp(nullptr),
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002354 user_value(false) {}
2355
2356 ~EnumValBuilder() { delete temp; }
2357
2358 Parser &parser;
2359 EnumDef &enum_def;
2360 EnumVal *temp;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002361 bool user_value;
2362};
2363
James Kuszmauldac091f2022-03-22 09:35:06 -07002364CheckedError Parser::ParseEnum(const bool is_union, EnumDef **dest,
2365 const char *filename) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002366 std::vector<std::string> enum_comment = doc_comment_;
2367 NEXT();
2368 std::string enum_name = attribute_;
2369 EXPECT(kTokenIdentifier);
2370 EnumDef *enum_def;
2371 ECHECK(StartEnum(enum_name, is_union, &enum_def));
James Kuszmauldac091f2022-03-22 09:35:06 -07002372 if (filename != nullptr && !opts.project_root.empty()) {
2373 enum_def->declaration_file =
2374 &GetPooledString(RelativeToRootPath(opts.project_root, filename));
2375 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002376 enum_def->doc_comment = enum_comment;
2377 if (!is_union && !opts.proto_mode) {
2378 // Give specialized error message, since this type spec used to
2379 // be optional in the first FlatBuffers release.
2380 if (!Is(':')) {
2381 return Error(
2382 "must specify the underlying integer type for this"
2383 " enum (e.g. \': short\', which was the default).");
2384 } else {
2385 NEXT();
2386 }
2387 // Specify the integer type underlying this enum.
2388 ECHECK(ParseType(enum_def->underlying_type));
2389 if (!IsInteger(enum_def->underlying_type.base_type) ||
2390 IsBool(enum_def->underlying_type.base_type))
2391 return Error("underlying enum type must be integral");
2392 // Make this type refer back to the enum it was derived from.
2393 enum_def->underlying_type.enum_def = enum_def;
2394 }
2395 ECHECK(ParseMetaData(&enum_def->attributes));
2396 const auto underlying_type = enum_def->underlying_type.base_type;
2397 if (enum_def->attributes.Lookup("bit_flags") &&
2398 !IsUnsigned(underlying_type)) {
2399 // todo: Convert to the Error in the future?
2400 Warning("underlying type of bit_flags enum must be unsigned");
2401 }
Austin Schuha1d006e2022-09-14 21:50:42 -07002402 if (enum_def->attributes.Lookup("force_align")) {
2403 return Error("`force_align` is not a valid attribute for Enums. ");
2404 }
Austin Schuh272c6132020-11-14 16:37:52 -08002405 EnumValBuilder evb(*this, *enum_def);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002406 EXPECT('{');
2407 // A lot of code generatos expect that an enum is not-empty.
2408 if ((is_union || Is('}')) && !opts.proto_mode) {
2409 evb.CreateEnumerator("NONE");
2410 ECHECK(evb.AcceptEnumerator());
2411 }
2412 std::set<std::pair<BaseType, StructDef *>> union_types;
2413 while (!Is('}')) {
2414 if (opts.proto_mode && attribute_ == "option") {
2415 ECHECK(ParseProtoOption());
2416 } else {
2417 auto &ev = *evb.CreateEnumerator(attribute_);
2418 auto full_name = ev.name;
2419 ev.doc_comment = doc_comment_;
2420 EXPECT(kTokenIdentifier);
2421 if (is_union) {
2422 ECHECK(ParseNamespacing(&full_name, &ev.name));
2423 if (opts.union_value_namespacing) {
2424 // Since we can't namespace the actual enum identifiers, turn
2425 // namespace parts into part of the identifier.
2426 ev.name = full_name;
2427 std::replace(ev.name.begin(), ev.name.end(), '.', '_');
2428 }
2429 if (Is(':')) {
2430 NEXT();
2431 ECHECK(ParseType(ev.union_type));
2432 if (ev.union_type.base_type != BASE_TYPE_STRUCT &&
2433 ev.union_type.base_type != BASE_TYPE_STRING)
2434 return Error("union value type may only be table/struct/string");
2435 } else {
2436 ev.union_type = Type(BASE_TYPE_STRUCT, LookupCreateStruct(full_name));
2437 }
2438 if (!enum_def->uses_multiple_type_instances) {
2439 auto ins = union_types.insert(std::make_pair(
2440 ev.union_type.base_type, ev.union_type.struct_def));
2441 enum_def->uses_multiple_type_instances = (false == ins.second);
2442 }
2443 }
2444
2445 if (Is('=')) {
2446 NEXT();
2447 ECHECK(evb.AssignEnumeratorValue(attribute_));
2448 EXPECT(kTokenIntegerConstant);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002449 }
2450
2451 ECHECK(evb.AcceptEnumerator());
2452
2453 if (opts.proto_mode && Is('[')) {
2454 NEXT();
2455 // ignore attributes on enums.
2456 while (token_ != ']') NEXT();
2457 NEXT();
2458 }
2459 }
2460 if (!Is(opts.proto_mode ? ';' : ',')) break;
2461 NEXT();
2462 }
2463 EXPECT('}');
2464
2465 // At this point, the enum can be empty if input is invalid proto-file.
2466 if (!enum_def->size())
2467 return Error("incomplete enum declaration, values not found");
2468
2469 if (enum_def->attributes.Lookup("bit_flags")) {
2470 const auto base_width = static_cast<uint64_t>(8 * SizeOf(underlying_type));
2471 for (auto it = enum_def->Vals().begin(); it != enum_def->Vals().end();
2472 ++it) {
2473 auto ev = *it;
2474 const auto u = ev->GetAsUInt64();
2475 // Stop manipulations with the sign.
2476 if (!IsUnsigned(underlying_type) && u == (base_width - 1))
2477 return Error("underlying type of bit_flags enum must be unsigned");
2478 if (u >= base_width)
2479 return Error("bit flag out of range of underlying integral type");
2480 enum_def->ChangeEnumValue(ev, 1ULL << u);
2481 }
2482 }
2483
Austin Schuh272c6132020-11-14 16:37:52 -08002484 enum_def->SortByValue(); // Must be sorted to use MinValue/MaxValue.
2485
2486 // Ensure enum value uniqueness.
2487 auto prev_it = enum_def->Vals().begin();
2488 for (auto it = prev_it + 1; it != enum_def->Vals().end(); ++it) {
2489 auto prev_ev = *prev_it;
2490 auto ev = *it;
2491 if (prev_ev->GetAsUInt64() == ev->GetAsUInt64())
2492 return Error("all enum values must be unique: " + prev_ev->name +
2493 " and " + ev->name + " are both " +
2494 NumToString(ev->GetAsInt64()));
2495 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002496
2497 if (dest) *dest = enum_def;
James Kuszmauldac091f2022-03-22 09:35:06 -07002498 const auto qualified_name =
2499 current_namespace_->GetFullyQualifiedName(enum_def->name);
2500 if (types_.Add(qualified_name, new Type(BASE_TYPE_UNION, nullptr, enum_def)))
2501 return Error("datatype already exists: " + qualified_name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002502 return NoError();
2503}
2504
2505CheckedError Parser::StartStruct(const std::string &name, StructDef **dest) {
2506 auto &struct_def = *LookupCreateStruct(name, true, true);
James Kuszmauldac091f2022-03-22 09:35:06 -07002507 if (!struct_def.predecl)
2508 return Error("datatype already exists: " +
2509 current_namespace_->GetFullyQualifiedName(name));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002510 struct_def.predecl = false;
2511 struct_def.name = name;
2512 struct_def.file = file_being_parsed_;
2513 // Move this struct to the back of the vector just in case it was predeclared,
2514 // to preserve declaration order.
2515 *std::remove(structs_.vec.begin(), structs_.vec.end(), &struct_def) =
2516 &struct_def;
2517 *dest = &struct_def;
2518 return NoError();
2519}
2520
2521CheckedError Parser::CheckClash(std::vector<FieldDef *> &fields,
2522 StructDef *struct_def, const char *suffix,
2523 BaseType basetype) {
2524 auto len = strlen(suffix);
2525 for (auto it = fields.begin(); it != fields.end(); ++it) {
2526 auto &fname = (*it)->name;
2527 if (fname.length() > len &&
2528 fname.compare(fname.length() - len, len, suffix) == 0 &&
2529 (*it)->value.type.base_type != BASE_TYPE_UTYPE) {
2530 auto field =
2531 struct_def->fields.Lookup(fname.substr(0, fname.length() - len));
2532 if (field && field->value.type.base_type == basetype)
2533 return Error("Field " + fname +
2534 " would clash with generated functions for field " +
2535 field->name);
2536 }
2537 }
2538 return NoError();
2539}
2540
Austin Schuha1d006e2022-09-14 21:50:42 -07002541std::vector<IncludedFile> Parser::GetIncludedFiles() const {
2542 const auto it = files_included_per_file_.find(file_being_parsed_);
2543 if (it == files_included_per_file_.end()) { return {}; }
2544
2545 return { it->second.cbegin(), it->second.cend() };
2546}
2547
Austin Schuh272c6132020-11-14 16:37:52 -08002548bool Parser::SupportsOptionalScalars(const flatbuffers::IDLOptions &opts) {
2549 static FLATBUFFERS_CONSTEXPR unsigned long supported_langs =
2550 IDLOptions::kRust | IDLOptions::kSwift | IDLOptions::kLobster |
2551 IDLOptions::kKotlin | IDLOptions::kCpp | IDLOptions::kJava |
James Kuszmauldac091f2022-03-22 09:35:06 -07002552 IDLOptions::kCSharp | IDLOptions::kTs | IDLOptions::kBinary |
Austin Schuha1d006e2022-09-14 21:50:42 -07002553 IDLOptions::kGo | IDLOptions::kPython | IDLOptions::kJson;
Austin Schuh272c6132020-11-14 16:37:52 -08002554 unsigned long langs = opts.lang_to_generate;
2555 return (langs > 0 && langs < IDLOptions::kMAX) && !(langs & ~supported_langs);
2556}
Austin Schuh272c6132020-11-14 16:37:52 -08002557bool Parser::SupportsOptionalScalars() const {
2558 // Check in general if a language isn't specified.
2559 return opts.lang_to_generate == 0 || SupportsOptionalScalars(opts);
2560}
2561
James Kuszmauldac091f2022-03-22 09:35:06 -07002562bool Parser::SupportsDefaultVectorsAndStrings() const {
2563 static FLATBUFFERS_CONSTEXPR unsigned long supported_langs =
2564 IDLOptions::kRust | IDLOptions::kSwift;
2565 return !(opts.lang_to_generate & ~supported_langs);
2566}
2567
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002568bool Parser::SupportsAdvancedUnionFeatures() const {
James Kuszmauldac091f2022-03-22 09:35:06 -07002569 return (opts.lang_to_generate &
2570 ~(IDLOptions::kCpp | IDLOptions::kTs | IDLOptions::kPhp |
2571 IDLOptions::kJava | IDLOptions::kCSharp | IDLOptions::kKotlin |
2572 IDLOptions::kBinary | IDLOptions::kSwift)) == 0;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002573}
2574
2575bool Parser::SupportsAdvancedArrayFeatures() const {
2576 return (opts.lang_to_generate &
2577 ~(IDLOptions::kCpp | IDLOptions::kPython | IDLOptions::kJava |
2578 IDLOptions::kCSharp | IDLOptions::kJsonSchema | IDLOptions::kJson |
James Kuszmauldac091f2022-03-22 09:35:06 -07002579 IDLOptions::kBinary | IDLOptions::kRust)) == 0;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002580}
2581
2582Namespace *Parser::UniqueNamespace(Namespace *ns) {
2583 for (auto it = namespaces_.begin(); it != namespaces_.end(); ++it) {
2584 if (ns->components == (*it)->components) {
2585 delete ns;
2586 return *it;
2587 }
2588 }
2589 namespaces_.push_back(ns);
2590 return ns;
2591}
2592
2593std::string Parser::UnqualifiedName(const std::string &full_qualified_name) {
2594 Namespace *ns = new Namespace();
2595
2596 std::size_t current, previous = 0;
2597 current = full_qualified_name.find('.');
2598 while (current != std::string::npos) {
2599 ns->components.push_back(
2600 full_qualified_name.substr(previous, current - previous));
2601 previous = current + 1;
2602 current = full_qualified_name.find('.', previous);
2603 }
2604 current_namespace_ = UniqueNamespace(ns);
2605 return full_qualified_name.substr(previous, current - previous);
2606}
2607
James Kuszmauldac091f2022-03-22 09:35:06 -07002608CheckedError Parser::ParseDecl(const char *filename) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002609 std::vector<std::string> dc = doc_comment_;
2610 bool fixed = IsIdent("struct");
2611 if (!fixed && !IsIdent("table")) return Error("declaration expected");
2612 NEXT();
2613 std::string name = attribute_;
2614 EXPECT(kTokenIdentifier);
2615 StructDef *struct_def;
2616 ECHECK(StartStruct(name, &struct_def));
2617 struct_def->doc_comment = dc;
2618 struct_def->fixed = fixed;
James Kuszmauldac091f2022-03-22 09:35:06 -07002619 if (filename && !opts.project_root.empty()) {
2620 struct_def->declaration_file =
2621 &GetPooledString(RelativeToRootPath(opts.project_root, filename));
2622 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002623 ECHECK(ParseMetaData(&struct_def->attributes));
2624 struct_def->sortbysize =
2625 struct_def->attributes.Lookup("original_order") == nullptr && !fixed;
2626 EXPECT('{');
2627 while (token_ != '}') ECHECK(ParseField(*struct_def));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002628 if (fixed) {
James Kuszmauldac091f2022-03-22 09:35:06 -07002629 const auto force_align = struct_def->attributes.Lookup("force_align");
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002630 if (force_align) {
James Kuszmauldac091f2022-03-22 09:35:06 -07002631 size_t align;
2632 ECHECK(ParseAlignAttribute(force_align->constant, struct_def->minalign,
2633 &align));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002634 struct_def->minalign = align;
2635 }
2636 if (!struct_def->bytesize) return Error("size 0 structs not allowed");
2637 }
2638 struct_def->PadLastField(struct_def->minalign);
2639 // Check if this is a table that has manual id assignments
2640 auto &fields = struct_def->fields.vec;
2641 if (!fixed && fields.size()) {
2642 size_t num_id_fields = 0;
2643 for (auto it = fields.begin(); it != fields.end(); ++it) {
2644 if ((*it)->attributes.Lookup("id")) num_id_fields++;
2645 }
2646 // If any fields have ids..
Austin Schuh58b9b472020-11-25 19:12:44 -08002647 if (num_id_fields || opts.require_explicit_ids) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002648 // Then all fields must have them.
Austin Schuh58b9b472020-11-25 19:12:44 -08002649 if (num_id_fields != fields.size()) {
2650 if (opts.require_explicit_ids) {
2651 return Error(
2652 "all fields must have an 'id' attribute when "
2653 "--require-explicit-ids is used");
2654 } else {
2655 return Error(
2656 "either all fields or no fields must have an 'id' attribute");
2657 }
2658 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002659 // Simply sort by id, then the fields are the same as if no ids had
2660 // been specified.
2661 std::sort(fields.begin(), fields.end(), compareFieldDefs);
2662 // Verify we have a contiguous set, and reassign vtable offsets.
James Kuszmauldac091f2022-03-22 09:35:06 -07002663 FLATBUFFERS_ASSERT(fields.size() <=
2664 flatbuffers::numeric_limits<voffset_t>::max());
2665 for (voffset_t i = 0; i < static_cast<voffset_t>(fields.size()); i++) {
2666 auto &field = *fields[i];
2667 const auto &id_str = field.attributes.Lookup("id")->constant;
2668 // Metadata values have a dynamic type, they can be `float`, 'int', or
2669 // 'string`.
2670 // The FieldIndexToOffset(i) expects the voffset_t so `id` is limited by
2671 // this type.
2672 voffset_t id = 0;
2673 const auto done = !atot(id_str.c_str(), *this, &id).Check();
2674 if (!done)
2675 return Error("field id\'s must be non-negative number, field: " +
2676 field.name + ", id: " + id_str);
2677 if (i != id)
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002678 return Error("field id\'s must be consecutive from 0, id " +
James Kuszmauldac091f2022-03-22 09:35:06 -07002679 NumToString(i) + " missing or set twice, field: " +
2680 field.name + ", id: " + id_str);
2681 field.value.offset = FieldIndexToOffset(i);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002682 }
2683 }
2684 }
2685
2686 ECHECK(
2687 CheckClash(fields, struct_def, UnionTypeFieldSuffix(), BASE_TYPE_UNION));
2688 ECHECK(CheckClash(fields, struct_def, "Type", BASE_TYPE_UNION));
2689 ECHECK(CheckClash(fields, struct_def, "_length", BASE_TYPE_VECTOR));
2690 ECHECK(CheckClash(fields, struct_def, "Length", BASE_TYPE_VECTOR));
2691 ECHECK(CheckClash(fields, struct_def, "_byte_vector", BASE_TYPE_STRING));
2692 ECHECK(CheckClash(fields, struct_def, "ByteVector", BASE_TYPE_STRING));
2693 EXPECT('}');
James Kuszmauldac091f2022-03-22 09:35:06 -07002694 const auto qualified_name =
2695 current_namespace_->GetFullyQualifiedName(struct_def->name);
2696 if (types_.Add(qualified_name,
2697 new Type(BASE_TYPE_STRUCT, struct_def, nullptr)))
2698 return Error("datatype already exists: " + qualified_name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002699 return NoError();
2700}
2701
James Kuszmauldac091f2022-03-22 09:35:06 -07002702CheckedError Parser::ParseService(const char *filename) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002703 std::vector<std::string> service_comment = doc_comment_;
2704 NEXT();
2705 auto service_name = attribute_;
2706 EXPECT(kTokenIdentifier);
2707 auto &service_def = *new ServiceDef();
2708 service_def.name = service_name;
2709 service_def.file = file_being_parsed_;
2710 service_def.doc_comment = service_comment;
2711 service_def.defined_namespace = current_namespace_;
James Kuszmauldac091f2022-03-22 09:35:06 -07002712 if (filename != nullptr && !opts.project_root.empty()) {
2713 service_def.declaration_file =
2714 &GetPooledString(RelativeToRootPath(opts.project_root, filename));
2715 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002716 if (services_.Add(current_namespace_->GetFullyQualifiedName(service_name),
2717 &service_def))
2718 return Error("service already exists: " + service_name);
2719 ECHECK(ParseMetaData(&service_def.attributes));
2720 EXPECT('{');
2721 do {
2722 std::vector<std::string> doc_comment = doc_comment_;
2723 auto rpc_name = attribute_;
2724 EXPECT(kTokenIdentifier);
2725 EXPECT('(');
2726 Type reqtype, resptype;
2727 ECHECK(ParseTypeIdent(reqtype));
2728 EXPECT(')');
2729 EXPECT(':');
2730 ECHECK(ParseTypeIdent(resptype));
2731 if (reqtype.base_type != BASE_TYPE_STRUCT || reqtype.struct_def->fixed ||
2732 resptype.base_type != BASE_TYPE_STRUCT || resptype.struct_def->fixed)
2733 return Error("rpc request and response types must be tables");
2734 auto &rpc = *new RPCCall();
2735 rpc.name = rpc_name;
2736 rpc.request = reqtype.struct_def;
2737 rpc.response = resptype.struct_def;
2738 rpc.doc_comment = doc_comment;
2739 if (service_def.calls.Add(rpc_name, &rpc))
2740 return Error("rpc already exists: " + rpc_name);
2741 ECHECK(ParseMetaData(&rpc.attributes));
2742 EXPECT(';');
2743 } while (token_ != '}');
2744 NEXT();
2745 return NoError();
2746}
2747
2748bool Parser::SetRootType(const char *name) {
2749 root_struct_def_ = LookupStruct(name);
2750 if (!root_struct_def_)
2751 root_struct_def_ =
2752 LookupStruct(current_namespace_->GetFullyQualifiedName(name));
2753 return root_struct_def_ != nullptr;
2754}
2755
2756void Parser::MarkGenerated() {
2757 // This function marks all existing definitions as having already
2758 // been generated, which signals no code for included files should be
2759 // generated.
2760 for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
2761 (*it)->generated = true;
2762 }
2763 for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
2764 if (!(*it)->predecl) { (*it)->generated = true; }
2765 }
2766 for (auto it = services_.vec.begin(); it != services_.vec.end(); ++it) {
2767 (*it)->generated = true;
2768 }
2769}
2770
2771CheckedError Parser::ParseNamespace() {
2772 NEXT();
2773 auto ns = new Namespace();
2774 namespaces_.push_back(ns); // Store it here to not leak upon error.
2775 if (token_ != ';') {
2776 for (;;) {
2777 ns->components.push_back(attribute_);
2778 EXPECT(kTokenIdentifier);
2779 if (Is('.')) NEXT() else break;
2780 }
2781 }
2782 namespaces_.pop_back();
2783 current_namespace_ = UniqueNamespace(ns);
2784 EXPECT(';');
2785 return NoError();
2786}
2787
2788// Best effort parsing of .proto declarations, with the aim to turn them
2789// in the closest corresponding FlatBuffer equivalent.
2790// We parse everything as identifiers instead of keywords, since we don't
2791// want protobuf keywords to become invalid identifiers in FlatBuffers.
2792CheckedError Parser::ParseProtoDecl() {
2793 bool isextend = IsIdent("extend");
2794 if (IsIdent("package")) {
2795 // These are identical in syntax to FlatBuffer's namespace decl.
2796 ECHECK(ParseNamespace());
2797 } else if (IsIdent("message") || isextend) {
2798 std::vector<std::string> struct_comment = doc_comment_;
2799 NEXT();
2800 StructDef *struct_def = nullptr;
2801 Namespace *parent_namespace = nullptr;
2802 if (isextend) {
2803 if (Is('.')) NEXT(); // qualified names may start with a . ?
2804 auto id = attribute_;
2805 EXPECT(kTokenIdentifier);
2806 ECHECK(ParseNamespacing(&id, nullptr));
2807 struct_def = LookupCreateStruct(id, false);
2808 if (!struct_def)
2809 return Error("cannot extend unknown message type: " + id);
2810 } else {
2811 std::string name = attribute_;
2812 EXPECT(kTokenIdentifier);
2813 ECHECK(StartStruct(name, &struct_def));
2814 // Since message definitions can be nested, we create a new namespace.
2815 auto ns = new Namespace();
2816 // Copy of current namespace.
2817 *ns = *current_namespace_;
2818 // But with current message name.
2819 ns->components.push_back(name);
2820 ns->from_table++;
2821 parent_namespace = current_namespace_;
2822 current_namespace_ = UniqueNamespace(ns);
2823 }
2824 struct_def->doc_comment = struct_comment;
2825 ECHECK(ParseProtoFields(struct_def, isextend, false));
2826 if (!isextend) { current_namespace_ = parent_namespace; }
2827 if (Is(';')) NEXT();
2828 } else if (IsIdent("enum")) {
2829 // These are almost the same, just with different terminator:
2830 EnumDef *enum_def;
James Kuszmauldac091f2022-03-22 09:35:06 -07002831 ECHECK(ParseEnum(false, &enum_def, nullptr));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002832 if (Is(';')) NEXT();
2833 // Temp: remove any duplicates, as .fbs files can't handle them.
2834 enum_def->RemoveDuplicates();
2835 } else if (IsIdent("syntax")) { // Skip these.
2836 NEXT();
2837 EXPECT('=');
2838 EXPECT(kTokenStringConstant);
2839 EXPECT(';');
2840 } else if (IsIdent("option")) { // Skip these.
2841 ECHECK(ParseProtoOption());
2842 EXPECT(';');
2843 } else if (IsIdent("service")) { // Skip these.
2844 NEXT();
2845 EXPECT(kTokenIdentifier);
2846 ECHECK(ParseProtoCurliesOrIdent());
2847 } else {
2848 return Error("don\'t know how to parse .proto declaration starting with " +
2849 TokenToStringId(token_));
2850 }
2851 return NoError();
2852}
2853
James Kuszmauldac091f2022-03-22 09:35:06 -07002854CheckedError Parser::StartEnum(const std::string &name, bool is_union,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002855 EnumDef **dest) {
2856 auto &enum_def = *new EnumDef();
James Kuszmauldac091f2022-03-22 09:35:06 -07002857 enum_def.name = name;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002858 enum_def.file = file_being_parsed_;
2859 enum_def.doc_comment = doc_comment_;
2860 enum_def.is_union = is_union;
2861 enum_def.defined_namespace = current_namespace_;
James Kuszmauldac091f2022-03-22 09:35:06 -07002862 const auto qualified_name = current_namespace_->GetFullyQualifiedName(name);
2863 if (enums_.Add(qualified_name, &enum_def))
2864 return Error("enum already exists: " + qualified_name);
Austin Schuh272c6132020-11-14 16:37:52 -08002865 enum_def.underlying_type.base_type =
2866 is_union ? BASE_TYPE_UTYPE : BASE_TYPE_INT;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002867 enum_def.underlying_type.enum_def = &enum_def;
2868 if (dest) *dest = &enum_def;
2869 return NoError();
2870}
2871
2872CheckedError Parser::ParseProtoFields(StructDef *struct_def, bool isextend,
2873 bool inside_oneof) {
2874 EXPECT('{');
2875 while (token_ != '}') {
2876 if (IsIdent("message") || IsIdent("extend") || IsIdent("enum")) {
2877 // Nested declarations.
2878 ECHECK(ParseProtoDecl());
2879 } else if (IsIdent("extensions")) { // Skip these.
2880 NEXT();
2881 EXPECT(kTokenIntegerConstant);
2882 if (Is(kTokenIdentifier)) {
2883 NEXT(); // to
2884 NEXT(); // num
2885 }
2886 EXPECT(';');
2887 } else if (IsIdent("option")) { // Skip these.
2888 ECHECK(ParseProtoOption());
2889 EXPECT(';');
2890 } else if (IsIdent("reserved")) { // Skip these.
2891 NEXT();
2892 while (!Is(';')) { NEXT(); } // A variety of formats, just skip.
2893 NEXT();
2894 } else {
2895 std::vector<std::string> field_comment = doc_comment_;
2896 // Parse the qualifier.
2897 bool required = false;
2898 bool repeated = false;
2899 bool oneof = false;
2900 if (!inside_oneof) {
2901 if (IsIdent("optional")) {
2902 // This is the default.
2903 NEXT();
2904 } else if (IsIdent("required")) {
2905 required = true;
2906 NEXT();
2907 } else if (IsIdent("repeated")) {
2908 repeated = true;
2909 NEXT();
2910 } else if (IsIdent("oneof")) {
2911 oneof = true;
2912 NEXT();
2913 } else {
2914 // can't error, proto3 allows decls without any of the above.
2915 }
2916 }
2917 StructDef *anonymous_struct = nullptr;
2918 EnumDef *oneof_union = nullptr;
2919 Type type;
2920 if (IsIdent("group") || oneof) {
2921 if (!oneof) NEXT();
2922 if (oneof && opts.proto_oneof_union) {
James Kuszmauldac091f2022-03-22 09:35:06 -07002923 auto name = ConvertCase(attribute_, Case::kUpperCamel) + "Union";
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002924 ECHECK(StartEnum(name, true, &oneof_union));
2925 type = Type(BASE_TYPE_UNION, nullptr, oneof_union);
2926 } else {
James Kuszmauldac091f2022-03-22 09:35:06 -07002927 auto name = "Anonymous" + NumToString(anonymous_counter_++);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002928 ECHECK(StartStruct(name, &anonymous_struct));
2929 type = Type(BASE_TYPE_STRUCT, anonymous_struct);
2930 }
2931 } else {
2932 ECHECK(ParseTypeFromProtoType(&type));
2933 }
2934 // Repeated elements get mapped to a vector.
2935 if (repeated) {
2936 type.element = type.base_type;
2937 type.base_type = BASE_TYPE_VECTOR;
2938 if (type.element == BASE_TYPE_VECTOR) {
2939 // We have a vector or vectors, which FlatBuffers doesn't support.
2940 // For now make it a vector of string (since the source is likely
2941 // "repeated bytes").
2942 // TODO(wvo): A better solution would be to wrap this in a table.
2943 type.element = BASE_TYPE_STRING;
2944 }
2945 }
2946 std::string name = attribute_;
2947 EXPECT(kTokenIdentifier);
2948 if (!oneof) {
2949 // Parse the field id. Since we're just translating schemas, not
2950 // any kind of binary compatibility, we can safely ignore these, and
2951 // assign our own.
2952 EXPECT('=');
2953 EXPECT(kTokenIntegerConstant);
2954 }
2955 FieldDef *field = nullptr;
2956 if (isextend) {
2957 // We allow a field to be re-defined when extending.
2958 // TODO: are there situations where that is problematic?
2959 field = struct_def->fields.Lookup(name);
2960 }
2961 if (!field) ECHECK(AddField(*struct_def, name, type, &field));
2962 field->doc_comment = field_comment;
James Kuszmauldac091f2022-03-22 09:35:06 -07002963 if (!IsScalar(type.base_type) && required) {
2964 field->presence = FieldDef::kRequired;
2965 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002966 // See if there's a default specified.
2967 if (Is('[')) {
2968 NEXT();
2969 for (;;) {
2970 auto key = attribute_;
2971 ECHECK(ParseProtoKey());
2972 EXPECT('=');
2973 auto val = attribute_;
2974 ECHECK(ParseProtoCurliesOrIdent());
2975 if (key == "default") {
Austin Schuh272c6132020-11-14 16:37:52 -08002976 // Temp: skip non-numeric and non-boolean defaults (enums).
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002977 auto numeric = strpbrk(val.c_str(), "0123456789-+.");
Austin Schuha1d006e2022-09-14 21:50:42 -07002978 if (IsFloat(type.base_type) &&
2979 (val == "inf" || val == "+inf" || val == "-inf")) {
2980 // Prefer to be explicit with +inf.
2981 field->value.constant = val == "inf" ? "+inf" : val;
2982 } else if (IsScalar(type.base_type) && numeric == val.c_str()) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002983 field->value.constant = val;
Austin Schuh272c6132020-11-14 16:37:52 -08002984 } else if (val == "true") {
2985 field->value.constant = val;
2986 } // "false" is default, no need to handle explicitly.
Austin Schuhe89fa2d2019-08-14 20:24:23 -07002987 } else if (key == "deprecated") {
2988 field->deprecated = val == "true";
2989 }
2990 if (!Is(',')) break;
2991 NEXT();
2992 }
2993 EXPECT(']');
2994 }
2995 if (anonymous_struct) {
2996 ECHECK(ParseProtoFields(anonymous_struct, false, oneof));
2997 if (Is(';')) NEXT();
2998 } else if (oneof_union) {
2999 // Parse into a temporary StructDef, then transfer fields into an
3000 // EnumDef describing the oneof as a union.
3001 StructDef oneof_struct;
3002 ECHECK(ParseProtoFields(&oneof_struct, false, oneof));
3003 if (Is(';')) NEXT();
3004 for (auto field_it = oneof_struct.fields.vec.begin();
3005 field_it != oneof_struct.fields.vec.end(); ++field_it) {
3006 const auto &oneof_field = **field_it;
3007 const auto &oneof_type = oneof_field.value.type;
3008 if (oneof_type.base_type != BASE_TYPE_STRUCT ||
3009 !oneof_type.struct_def || oneof_type.struct_def->fixed)
3010 return Error("oneof '" + name +
Austin Schuh272c6132020-11-14 16:37:52 -08003011 "' cannot be mapped to a union because member '" +
3012 oneof_field.name + "' is not a table type.");
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003013 EnumValBuilder evb(*this, *oneof_union);
3014 auto ev = evb.CreateEnumerator(oneof_type.struct_def->name);
3015 ev->union_type = oneof_type;
3016 ev->doc_comment = oneof_field.doc_comment;
3017 ECHECK(evb.AcceptEnumerator(oneof_field.name));
3018 }
3019 } else {
3020 EXPECT(';');
3021 }
3022 }
3023 }
3024 NEXT();
3025 return NoError();
3026}
3027
3028CheckedError Parser::ParseProtoKey() {
3029 if (token_ == '(') {
3030 NEXT();
3031 // Skip "(a.b)" style custom attributes.
3032 while (token_ == '.' || token_ == kTokenIdentifier) NEXT();
3033 EXPECT(')');
3034 while (Is('.')) {
3035 NEXT();
3036 EXPECT(kTokenIdentifier);
3037 }
3038 } else {
3039 EXPECT(kTokenIdentifier);
3040 }
3041 return NoError();
3042}
3043
3044CheckedError Parser::ParseProtoCurliesOrIdent() {
3045 if (Is('{')) {
3046 NEXT();
3047 for (int nesting = 1; nesting;) {
3048 if (token_ == '{')
3049 nesting++;
3050 else if (token_ == '}')
3051 nesting--;
3052 NEXT();
3053 }
3054 } else {
3055 NEXT(); // Any single token.
3056 }
3057 return NoError();
3058}
3059
3060CheckedError Parser::ParseProtoOption() {
3061 NEXT();
3062 ECHECK(ParseProtoKey());
3063 EXPECT('=');
3064 ECHECK(ParseProtoCurliesOrIdent());
3065 return NoError();
3066}
3067
3068// Parse a protobuf type, and map it to the corresponding FlatBuffer one.
3069CheckedError Parser::ParseTypeFromProtoType(Type *type) {
3070 struct type_lookup {
3071 const char *proto_type;
3072 BaseType fb_type, element;
3073 };
3074 static type_lookup lookup[] = {
3075 { "float", BASE_TYPE_FLOAT, BASE_TYPE_NONE },
3076 { "double", BASE_TYPE_DOUBLE, BASE_TYPE_NONE },
3077 { "int32", BASE_TYPE_INT, BASE_TYPE_NONE },
3078 { "int64", BASE_TYPE_LONG, BASE_TYPE_NONE },
3079 { "uint32", BASE_TYPE_UINT, BASE_TYPE_NONE },
3080 { "uint64", BASE_TYPE_ULONG, BASE_TYPE_NONE },
3081 { "sint32", BASE_TYPE_INT, BASE_TYPE_NONE },
3082 { "sint64", BASE_TYPE_LONG, BASE_TYPE_NONE },
3083 { "fixed32", BASE_TYPE_UINT, BASE_TYPE_NONE },
3084 { "fixed64", BASE_TYPE_ULONG, BASE_TYPE_NONE },
3085 { "sfixed32", BASE_TYPE_INT, BASE_TYPE_NONE },
3086 { "sfixed64", BASE_TYPE_LONG, BASE_TYPE_NONE },
3087 { "bool", BASE_TYPE_BOOL, BASE_TYPE_NONE },
3088 { "string", BASE_TYPE_STRING, BASE_TYPE_NONE },
3089 { "bytes", BASE_TYPE_VECTOR, BASE_TYPE_UCHAR },
3090 { nullptr, BASE_TYPE_NONE, BASE_TYPE_NONE }
3091 };
3092 for (auto tl = lookup; tl->proto_type; tl++) {
3093 if (attribute_ == tl->proto_type) {
3094 type->base_type = tl->fb_type;
3095 type->element = tl->element;
3096 NEXT();
3097 return NoError();
3098 }
3099 }
3100 if (Is('.')) NEXT(); // qualified names may start with a . ?
3101 ECHECK(ParseTypeIdent(*type));
3102 return NoError();
3103}
3104
3105CheckedError Parser::SkipAnyJsonValue() {
James Kuszmauldac091f2022-03-22 09:35:06 -07003106 ParseDepthGuard depth_guard(this);
3107 ECHECK(depth_guard.Check());
3108
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003109 switch (token_) {
3110 case '{': {
3111 size_t fieldn_outer = 0;
James Kuszmauldac091f2022-03-22 09:35:06 -07003112 return ParseTableDelimiters(fieldn_outer, nullptr,
3113 [&](const std::string &, size_t &fieldn,
3114 const StructDef *) -> CheckedError {
3115 ECHECK(SkipAnyJsonValue());
3116 fieldn++;
3117 return NoError();
3118 });
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003119 }
3120 case '[': {
3121 uoffset_t count = 0;
3122 return ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
James Kuszmauldac091f2022-03-22 09:35:06 -07003123 return SkipAnyJsonValue();
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003124 });
3125 }
3126 case kTokenStringConstant:
3127 case kTokenIntegerConstant:
3128 case kTokenFloatConstant: NEXT(); break;
3129 default:
Austin Schuha1d006e2022-09-14 21:50:42 -07003130 if (IsIdent("true") || IsIdent("false") || IsIdent("null") ||
3131 IsIdent("inf")) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003132 NEXT();
3133 } else
3134 return TokenError();
3135 }
3136 return NoError();
3137}
3138
James Kuszmauldac091f2022-03-22 09:35:06 -07003139CheckedError Parser::ParseFlexBufferNumericConstant(
3140 flexbuffers::Builder *builder) {
3141 double d;
3142 if (!StringToNumber(attribute_.c_str(), &d))
3143 return Error("unexpected floating-point constant: " + attribute_);
3144 builder->Double(d);
3145 return NoError();
3146}
3147
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003148CheckedError Parser::ParseFlexBufferValue(flexbuffers::Builder *builder) {
James Kuszmauldac091f2022-03-22 09:35:06 -07003149 ParseDepthGuard depth_guard(this);
3150 ECHECK(depth_guard.Check());
3151
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003152 switch (token_) {
3153 case '{': {
3154 auto start = builder->StartMap();
3155 size_t fieldn_outer = 0;
3156 auto err =
3157 ParseTableDelimiters(fieldn_outer, nullptr,
3158 [&](const std::string &name, size_t &fieldn,
3159 const StructDef *) -> CheckedError {
3160 builder->Key(name);
3161 ECHECK(ParseFlexBufferValue(builder));
3162 fieldn++;
3163 return NoError();
3164 });
3165 ECHECK(err);
3166 builder->EndMap(start);
Austin Schuh58b9b472020-11-25 19:12:44 -08003167 if (builder->HasDuplicateKeys())
3168 return Error("FlexBuffers map has duplicate keys");
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003169 break;
3170 }
3171 case '[': {
3172 auto start = builder->StartVector();
3173 uoffset_t count = 0;
3174 ECHECK(ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
3175 return ParseFlexBufferValue(builder);
3176 }));
3177 builder->EndVector(start, false, false);
3178 break;
3179 }
3180 case kTokenStringConstant:
3181 builder->String(attribute_);
3182 EXPECT(kTokenStringConstant);
3183 break;
3184 case kTokenIntegerConstant:
3185 builder->Int(StringToInt(attribute_.c_str()));
3186 EXPECT(kTokenIntegerConstant);
3187 break;
Austin Schuh272c6132020-11-14 16:37:52 -08003188 case kTokenFloatConstant: {
3189 double d;
3190 StringToNumber(attribute_.c_str(), &d);
3191 builder->Double(d);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003192 EXPECT(kTokenFloatConstant);
3193 break;
Austin Schuh272c6132020-11-14 16:37:52 -08003194 }
James Kuszmauldac091f2022-03-22 09:35:06 -07003195 case '-':
3196 case '+': {
3197 // `[-+]?(nan|inf|infinity)`, see ParseSingleValue().
3198 const auto sign = static_cast<char>(token_);
3199 NEXT();
3200 if (token_ != kTokenIdentifier)
3201 return Error("floating-point constant expected");
3202 attribute_.insert(0, 1, sign);
3203 ECHECK(ParseFlexBufferNumericConstant(builder));
3204 NEXT();
3205 break;
3206 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003207 default:
3208 if (IsIdent("true")) {
3209 builder->Bool(true);
3210 NEXT();
3211 } else if (IsIdent("false")) {
3212 builder->Bool(false);
3213 NEXT();
3214 } else if (IsIdent("null")) {
3215 builder->Null();
3216 NEXT();
James Kuszmauldac091f2022-03-22 09:35:06 -07003217 } else if (IsIdent("inf") || IsIdent("infinity") || IsIdent("nan")) {
3218 ECHECK(ParseFlexBufferNumericConstant(builder));
3219 NEXT();
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003220 } else
3221 return TokenError();
3222 }
3223 return NoError();
3224}
3225
3226bool Parser::ParseFlexBuffer(const char *source, const char *source_filename,
3227 flexbuffers::Builder *builder) {
James Kuszmauldac091f2022-03-22 09:35:06 -07003228 const auto initial_depth = parse_depth_counter_;
3229 (void)initial_depth;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003230 auto ok = !StartParseFile(source, source_filename).Check() &&
3231 !ParseFlexBufferValue(builder).Check();
3232 if (ok) builder->Finish();
James Kuszmauldac091f2022-03-22 09:35:06 -07003233 FLATBUFFERS_ASSERT(initial_depth == parse_depth_counter_);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003234 return ok;
3235}
3236
3237bool Parser::Parse(const char *source, const char **include_paths,
3238 const char *source_filename) {
James Kuszmauldac091f2022-03-22 09:35:06 -07003239 const auto initial_depth = parse_depth_counter_;
3240 (void)initial_depth;
Austin Schuh272c6132020-11-14 16:37:52 -08003241 bool r;
3242
3243 if (opts.use_flexbuffers) {
3244 r = ParseFlexBuffer(source, source_filename, &flex_builder_);
3245 } else {
3246 r = !ParseRoot(source, include_paths, source_filename).Check();
3247 }
James Kuszmauldac091f2022-03-22 09:35:06 -07003248 FLATBUFFERS_ASSERT(initial_depth == parse_depth_counter_);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003249 return r;
3250}
3251
Austin Schuh58b9b472020-11-25 19:12:44 -08003252bool Parser::ParseJson(const char *json, const char *json_filename) {
James Kuszmauldac091f2022-03-22 09:35:06 -07003253 const auto initial_depth = parse_depth_counter_;
3254 (void)initial_depth;
Austin Schuh58b9b472020-11-25 19:12:44 -08003255 builder_.Clear();
3256 const auto done =
3257 !StartParseFile(json, json_filename).Check() && !DoParseJson().Check();
James Kuszmauldac091f2022-03-22 09:35:06 -07003258 FLATBUFFERS_ASSERT(initial_depth == parse_depth_counter_);
Austin Schuh58b9b472020-11-25 19:12:44 -08003259 return done;
3260}
3261
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003262CheckedError Parser::StartParseFile(const char *source,
3263 const char *source_filename) {
3264 file_being_parsed_ = source_filename ? source_filename : "";
3265 source_ = source;
3266 ResetState(source_);
3267 error_.clear();
3268 ECHECK(SkipByteOrderMark());
3269 NEXT();
3270 if (Is(kTokenEof)) return Error("input file is empty");
3271 return NoError();
3272}
3273
3274CheckedError Parser::ParseRoot(const char *source, const char **include_paths,
3275 const char *source_filename) {
3276 ECHECK(DoParse(source, include_paths, source_filename, nullptr));
3277
3278 // Check that all types were defined.
3279 for (auto it = structs_.vec.begin(); it != structs_.vec.end();) {
3280 auto &struct_def = **it;
3281 if (struct_def.predecl) {
3282 if (opts.proto_mode) {
3283 // Protos allow enums to be used before declaration, so check if that
3284 // is the case here.
3285 EnumDef *enum_def = nullptr;
3286 for (size_t components =
3287 struct_def.defined_namespace->components.size() + 1;
3288 components && !enum_def; components--) {
3289 auto qualified_name =
3290 struct_def.defined_namespace->GetFullyQualifiedName(
3291 struct_def.name, components - 1);
3292 enum_def = LookupEnum(qualified_name);
3293 }
3294 if (enum_def) {
3295 // This is pretty slow, but a simple solution for now.
3296 auto initial_count = struct_def.refcount;
3297 for (auto struct_it = structs_.vec.begin();
3298 struct_it != structs_.vec.end(); ++struct_it) {
3299 auto &sd = **struct_it;
3300 for (auto field_it = sd.fields.vec.begin();
3301 field_it != sd.fields.vec.end(); ++field_it) {
3302 auto &field = **field_it;
3303 if (field.value.type.struct_def == &struct_def) {
3304 field.value.type.struct_def = nullptr;
3305 field.value.type.enum_def = enum_def;
Austin Schuh272c6132020-11-14 16:37:52 -08003306 auto &bt = IsVector(field.value.type)
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003307 ? field.value.type.element
3308 : field.value.type.base_type;
3309 FLATBUFFERS_ASSERT(bt == BASE_TYPE_STRUCT);
3310 bt = enum_def->underlying_type.base_type;
3311 struct_def.refcount--;
3312 enum_def->refcount++;
3313 }
3314 }
3315 }
3316 if (struct_def.refcount)
3317 return Error("internal: " + NumToString(struct_def.refcount) + "/" +
3318 NumToString(initial_count) +
3319 " use(s) of pre-declaration enum not accounted for: " +
3320 enum_def->name);
3321 structs_.dict.erase(structs_.dict.find(struct_def.name));
3322 it = structs_.vec.erase(it);
3323 delete &struct_def;
3324 continue; // Skip error.
3325 }
3326 }
3327 auto err = "type referenced but not defined (check namespace): " +
3328 struct_def.name;
3329 if (struct_def.original_location)
3330 err += ", originally at: " + *struct_def.original_location;
3331 return Error(err);
3332 }
3333 ++it;
3334 }
3335
3336 // This check has to happen here and not earlier, because only now do we
3337 // know for sure what the type of these are.
3338 for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
3339 auto &enum_def = **it;
3340 if (enum_def.is_union) {
3341 for (auto val_it = enum_def.Vals().begin();
3342 val_it != enum_def.Vals().end(); ++val_it) {
3343 auto &val = **val_it;
Austin Schuha1d006e2022-09-14 21:50:42 -07003344
James Kuszmauldac091f2022-03-22 09:35:06 -07003345 if (!(opts.lang_to_generate != 0 && SupportsAdvancedUnionFeatures()) &&
Austin Schuh272c6132020-11-14 16:37:52 -08003346 (IsStruct(val.union_type) || IsString(val.union_type)))
Austin Schuha1d006e2022-09-14 21:50:42 -07003347
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003348 return Error(
3349 "only tables can be union elements in the generated language: " +
3350 val.name);
3351 }
3352 }
3353 }
Austin Schuha1d006e2022-09-14 21:50:42 -07003354
3355 auto err = CheckPrivateLeak();
3356 if (err.Check()) return err;
3357
James Kuszmauldac091f2022-03-22 09:35:06 -07003358 // Parse JSON object only if the scheme has been parsed.
3359 if (token_ == '{') { ECHECK(DoParseJson()); }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003360 return NoError();
3361}
3362
Austin Schuha1d006e2022-09-14 21:50:42 -07003363CheckedError Parser::CheckPrivateLeak() {
3364 if (!opts.no_leak_private_annotations) return NoError();
3365 // Iterate over all structs/tables to validate we arent leaking
3366 // any private (structs/tables/enums)
3367 for (auto it = structs_.vec.begin(); it != structs_.vec.end(); it++) {
3368 auto &struct_def = **it;
3369 for (auto fld_it = struct_def.fields.vec.begin();
3370 fld_it != struct_def.fields.vec.end(); ++fld_it) {
3371 auto &field = **fld_it;
James Kuszmauldac091f2022-03-22 09:35:06 -07003372
Austin Schuha1d006e2022-09-14 21:50:42 -07003373 if (field.value.type.enum_def) {
3374 auto err =
3375 CheckPrivatelyLeakedFields(struct_def, *field.value.type.enum_def);
3376 if (err.Check()) { return err; }
3377 } else if (field.value.type.struct_def) {
3378 auto err = CheckPrivatelyLeakedFields(struct_def,
3379 *field.value.type.struct_def);
3380 if (err.Check()) { return err; }
3381 }
3382 }
3383 }
3384 // Iterate over all enums to validate we arent leaking
3385 // any private (structs/tables)
3386 for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
3387 auto &enum_def = **it;
3388 if (enum_def.is_union) {
3389 for (auto val_it = enum_def.Vals().begin();
3390 val_it != enum_def.Vals().end(); ++val_it) {
3391 auto &val = **val_it;
3392 if (val.union_type.struct_def) {
3393 auto err =
3394 CheckPrivatelyLeakedFields(enum_def, *val.union_type.struct_def);
3395 if (err.Check()) { return err; }
3396 }
3397 }
3398 }
3399 }
3400 return NoError();
James Kuszmauldac091f2022-03-22 09:35:06 -07003401}
3402
Austin Schuha1d006e2022-09-14 21:50:42 -07003403CheckedError Parser::CheckPrivatelyLeakedFields(const Definition &def,
3404 const Definition &value_type) {
3405 if (!opts.no_leak_private_annotations) return NoError();
3406 const auto is_private = def.attributes.Lookup("private");
3407 const auto is_field_private = value_type.attributes.Lookup("private");
3408 if (!is_private && is_field_private) {
3409 return Error(
3410 "Leaking private implementation, verify all objects have similar "
3411 "annotations");
3412 }
3413 return NoError();
3414}
3415
3416
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003417CheckedError Parser::DoParse(const char *source, const char **include_paths,
3418 const char *source_filename,
3419 const char *include_filename) {
James Kuszmauldac091f2022-03-22 09:35:06 -07003420 uint64_t source_hash = 0;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003421 if (source_filename) {
James Kuszmauldac091f2022-03-22 09:35:06 -07003422 // If the file is in-memory, don't include its contents in the hash as we
3423 // won't be able to load them later.
3424 if (FileExists(source_filename))
3425 source_hash = HashFile(source_filename, source);
3426 else
3427 source_hash = HashFile(source_filename, nullptr);
3428
3429 if (included_files_.find(source_hash) == included_files_.end()) {
3430 included_files_[source_hash] = include_filename ? include_filename : "";
Austin Schuh13ec0722022-09-26 18:12:16 -07003431 files_included_per_file_[include_filename ? include_filename
3432 : source_filename] =
3433 std::set<IncludedFile>();
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003434 } else {
3435 return NoError();
3436 }
3437 }
3438 if (!include_paths) {
3439 static const char *current_directory[] = { "", nullptr };
3440 include_paths = current_directory;
3441 }
3442 field_stack_.clear();
3443 builder_.Clear();
3444 // Start with a blank namespace just in case this file doesn't have one.
3445 current_namespace_ = empty_namespace_;
3446
3447 ECHECK(StartParseFile(source, source_filename));
3448
3449 // Includes must come before type declarations:
3450 for (;;) {
3451 // Parse pre-include proto statements if any:
3452 if (opts.proto_mode && (attribute_ == "option" || attribute_ == "syntax" ||
3453 attribute_ == "package")) {
3454 ECHECK(ParseProtoDecl());
3455 } else if (IsIdent("native_include")) {
3456 NEXT();
James Kuszmauldac091f2022-03-22 09:35:06 -07003457 native_included_files_.emplace_back(attribute_);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003458 EXPECT(kTokenStringConstant);
3459 EXPECT(';');
3460 } else if (IsIdent("include") || (opts.proto_mode && IsIdent("import"))) {
3461 NEXT();
3462 if (opts.proto_mode && attribute_ == "public") NEXT();
3463 auto name = flatbuffers::PosixPath(attribute_.c_str());
3464 EXPECT(kTokenStringConstant);
James Kuszmauldac091f2022-03-22 09:35:06 -07003465 // Look for the file relative to the directory of the current file.
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003466 std::string filepath;
James Kuszmauldac091f2022-03-22 09:35:06 -07003467 if (source_filename) {
3468 auto source_file_directory =
3469 flatbuffers::StripFileName(source_filename);
3470 filepath = flatbuffers::ConCatPathFileName(source_file_directory, name);
3471 }
3472 if (filepath.empty() || !FileExists(filepath.c_str())) {
3473 // Look for the file in include_paths.
3474 for (auto paths = include_paths; paths && *paths; paths++) {
3475 filepath = flatbuffers::ConCatPathFileName(*paths, name);
3476 if (FileExists(filepath.c_str())) break;
3477 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003478 }
3479 if (filepath.empty())
3480 return Error("unable to locate include file: " + name);
Austin Schuha1d006e2022-09-14 21:50:42 -07003481 if (source_filename) {
3482 IncludedFile included_file;
3483 included_file.filename = filepath;
3484 included_file.schema_name = name;
Austin Schuh13ec0722022-09-26 18:12:16 -07003485 files_included_per_file_[include_filename ? include_filename
3486 : source_filename]
3487 .insert(included_file);
Austin Schuha1d006e2022-09-14 21:50:42 -07003488 }
James Kuszmauldac091f2022-03-22 09:35:06 -07003489
3490 std::string contents;
3491 bool file_loaded = LoadFile(filepath.c_str(), true, &contents);
3492 if (included_files_.find(HashFile(filepath.c_str(), contents.c_str())) ==
3493 included_files_.end()) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003494 // We found an include file that we have not parsed yet.
James Kuszmauldac091f2022-03-22 09:35:06 -07003495 // Parse it.
3496 if (!file_loaded) return Error("unable to load include file: " + name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003497 ECHECK(DoParse(contents.c_str(), include_paths, filepath.c_str(),
3498 name.c_str()));
3499 // We generally do not want to output code for any included files:
3500 if (!opts.generate_all) MarkGenerated();
3501 // Reset these just in case the included file had them, and the
3502 // parent doesn't.
3503 root_struct_def_ = nullptr;
3504 file_identifier_.clear();
3505 file_extension_.clear();
3506 // This is the easiest way to continue this file after an include:
3507 // instead of saving and restoring all the state, we simply start the
3508 // file anew. This will cause it to encounter the same include
3509 // statement again, but this time it will skip it, because it was
3510 // entered into included_files_.
3511 // This is recursive, but only go as deep as the number of include
3512 // statements.
James Kuszmauldac091f2022-03-22 09:35:06 -07003513 included_files_.erase(source_hash);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003514 return DoParse(source, include_paths, source_filename,
3515 include_filename);
3516 }
3517 EXPECT(';');
3518 } else {
3519 break;
3520 }
3521 }
3522 // Now parse all other kinds of declarations:
3523 while (token_ != kTokenEof) {
3524 if (opts.proto_mode) {
3525 ECHECK(ParseProtoDecl());
3526 } else if (IsIdent("namespace")) {
3527 ECHECK(ParseNamespace());
3528 } else if (token_ == '{') {
James Kuszmauldac091f2022-03-22 09:35:06 -07003529 return NoError();
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003530 } else if (IsIdent("enum")) {
James Kuszmauldac091f2022-03-22 09:35:06 -07003531 ECHECK(ParseEnum(false, nullptr, source_filename));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003532 } else if (IsIdent("union")) {
James Kuszmauldac091f2022-03-22 09:35:06 -07003533 ECHECK(ParseEnum(true, nullptr, source_filename));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003534 } else if (IsIdent("root_type")) {
3535 NEXT();
3536 auto root_type = attribute_;
3537 EXPECT(kTokenIdentifier);
3538 ECHECK(ParseNamespacing(&root_type, nullptr));
3539 if (opts.root_type.empty()) {
3540 if (!SetRootType(root_type.c_str()))
3541 return Error("unknown root type: " + root_type);
Austin Schuh272c6132020-11-14 16:37:52 -08003542 if (root_struct_def_->fixed) return Error("root type must be a table");
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003543 }
3544 EXPECT(';');
3545 } else if (IsIdent("file_identifier")) {
3546 NEXT();
3547 file_identifier_ = attribute_;
3548 EXPECT(kTokenStringConstant);
James Kuszmauldac091f2022-03-22 09:35:06 -07003549 if (file_identifier_.length() != flatbuffers::kFileIdentifierLength)
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003550 return Error("file_identifier must be exactly " +
James Kuszmauldac091f2022-03-22 09:35:06 -07003551 NumToString(flatbuffers::kFileIdentifierLength) +
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003552 " characters");
3553 EXPECT(';');
3554 } else if (IsIdent("file_extension")) {
3555 NEXT();
3556 file_extension_ = attribute_;
3557 EXPECT(kTokenStringConstant);
3558 EXPECT(';');
3559 } else if (IsIdent("include")) {
3560 return Error("includes must come before declarations");
3561 } else if (IsIdent("attribute")) {
3562 NEXT();
3563 auto name = attribute_;
3564 if (Is(kTokenIdentifier)) {
3565 NEXT();
3566 } else {
3567 EXPECT(kTokenStringConstant);
3568 }
3569 EXPECT(';');
3570 known_attributes_[name] = false;
3571 } else if (IsIdent("rpc_service")) {
James Kuszmauldac091f2022-03-22 09:35:06 -07003572 ECHECK(ParseService(source_filename));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003573 } else {
James Kuszmauldac091f2022-03-22 09:35:06 -07003574 ECHECK(ParseDecl(source_filename));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003575 }
3576 }
Austin Schuha1d006e2022-09-14 21:50:42 -07003577 EXPECT(kTokenEof);
James Kuszmauldac091f2022-03-22 09:35:06 -07003578 if (opts.warnings_as_errors && has_warning_) {
3579 return Error("treating warnings as errors, failed due to above warnings");
3580 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003581 return NoError();
3582}
3583
James Kuszmauldac091f2022-03-22 09:35:06 -07003584CheckedError Parser::DoParseJson() {
Austin Schuh58b9b472020-11-25 19:12:44 -08003585 if (token_ != '{') {
3586 EXPECT('{');
3587 } else {
James Kuszmauldac091f2022-03-22 09:35:06 -07003588 if (!root_struct_def_) return Error("no root type set to parse json with");
Austin Schuh58b9b472020-11-25 19:12:44 -08003589 if (builder_.GetSize()) {
3590 return Error("cannot have more than one json object in a file");
3591 }
3592 uoffset_t toff;
3593 ECHECK(ParseTable(*root_struct_def_, nullptr, &toff));
3594 if (opts.size_prefixed) {
3595 builder_.FinishSizePrefixed(
3596 Offset<Table>(toff),
3597 file_identifier_.length() ? file_identifier_.c_str() : nullptr);
3598 } else {
3599 builder_.Finish(Offset<Table>(toff), file_identifier_.length()
James Kuszmauldac091f2022-03-22 09:35:06 -07003600 ? file_identifier_.c_str()
3601 : nullptr);
Austin Schuh58b9b472020-11-25 19:12:44 -08003602 }
3603 }
3604 // Check that JSON file doesn't contain more objects or IDL directives.
3605 // Comments after JSON are allowed.
3606 EXPECT(kTokenEof);
3607 return NoError();
3608}
3609
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003610std::set<std::string> Parser::GetIncludedFilesRecursive(
3611 const std::string &file_name) const {
3612 std::set<std::string> included_files;
3613 std::list<std::string> to_process;
3614
3615 if (file_name.empty()) return included_files;
3616 to_process.push_back(file_name);
3617
3618 while (!to_process.empty()) {
3619 std::string current = to_process.front();
3620 to_process.pop_front();
3621 included_files.insert(current);
3622
3623 // Workaround the lack of const accessor in C++98 maps.
3624 auto &new_files =
Austin Schuha1d006e2022-09-14 21:50:42 -07003625 (*const_cast<std::map<std::string, std::set<IncludedFile>> *>(
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003626 &files_included_per_file_))[current];
3627 for (auto it = new_files.begin(); it != new_files.end(); ++it) {
Austin Schuha1d006e2022-09-14 21:50:42 -07003628 if (included_files.find(it->filename) == included_files.end())
3629 to_process.push_back(it->filename);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003630 }
3631 }
3632
3633 return included_files;
3634}
3635
3636// Schema serialization functionality:
3637
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003638void Parser::Serialize() {
3639 builder_.Clear();
3640 AssignIndices(structs_.vec);
3641 AssignIndices(enums_.vec);
3642 std::vector<Offset<reflection::Object>> object_offsets;
James Kuszmauldac091f2022-03-22 09:35:06 -07003643 std::set<std::string> files;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003644 for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
3645 auto offset = (*it)->Serialize(&builder_, *this);
3646 object_offsets.push_back(offset);
3647 (*it)->serialized_location = offset.o;
James Kuszmauldac091f2022-03-22 09:35:06 -07003648 const std::string *file = (*it)->declaration_file;
3649 if (file) files.insert(*file);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003650 }
3651 std::vector<Offset<reflection::Enum>> enum_offsets;
3652 for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
3653 auto offset = (*it)->Serialize(&builder_, *this);
3654 enum_offsets.push_back(offset);
James Kuszmauldac091f2022-03-22 09:35:06 -07003655 const std::string *file = (*it)->declaration_file;
3656 if (file) files.insert(*file);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003657 }
3658 std::vector<Offset<reflection::Service>> service_offsets;
3659 for (auto it = services_.vec.begin(); it != services_.vec.end(); ++it) {
3660 auto offset = (*it)->Serialize(&builder_, *this);
3661 service_offsets.push_back(offset);
James Kuszmauldac091f2022-03-22 09:35:06 -07003662 const std::string *file = (*it)->declaration_file;
3663 if (file) files.insert(*file);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003664 }
James Kuszmauldac091f2022-03-22 09:35:06 -07003665
3666 // Create Schemafiles vector of tables.
3667 flatbuffers::Offset<
3668 flatbuffers::Vector<flatbuffers::Offset<reflection::SchemaFile>>>
3669 schema_files__;
3670 if (!opts.project_root.empty()) {
3671 std::vector<Offset<reflection::SchemaFile>> schema_files;
3672 std::vector<Offset<flatbuffers::String>> included_files;
3673 for (auto f = files_included_per_file_.begin();
3674 f != files_included_per_file_.end(); f++) {
3675 // frc971 modification to make file paths in schemas deterministic.
3676 const auto filename__ = builder_.CreateSharedString(f->first);
3677 for (auto i = f->second.begin(); i != f->second.end(); i++) {
Austin Schuha1d006e2022-09-14 21:50:42 -07003678 included_files.push_back(builder_.CreateSharedString(i->schema_name));
James Kuszmauldac091f2022-03-22 09:35:06 -07003679 }
3680 const auto included_files__ = builder_.CreateVector(included_files);
3681 included_files.clear();
3682
3683 schema_files.push_back(
3684 reflection::CreateSchemaFile(builder_, filename__, included_files__));
3685 }
3686 schema_files__ = builder_.CreateVectorOfSortedTables(&schema_files);
3687 }
3688
3689 const auto objs__ = builder_.CreateVectorOfSortedTables(&object_offsets);
3690 const auto enum__ = builder_.CreateVectorOfSortedTables(&enum_offsets);
3691 const auto fiid__ = builder_.CreateString(file_identifier_);
3692 const auto fext__ = builder_.CreateString(file_extension_);
3693 const auto serv__ = builder_.CreateVectorOfSortedTables(&service_offsets);
3694 const auto schema_offset = reflection::CreateSchema(
Austin Schuh272c6132020-11-14 16:37:52 -08003695 builder_, objs__, enum__, fiid__, fext__,
James Kuszmauldac091f2022-03-22 09:35:06 -07003696 (root_struct_def_ ? root_struct_def_->serialized_location : 0), serv__,
3697 static_cast<reflection::AdvancedFeatures>(advanced_features_),
3698 schema_files__);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003699 if (opts.size_prefixed) {
3700 builder_.FinishSizePrefixed(schema_offset, reflection::SchemaIdentifier());
3701 } else {
3702 builder_.Finish(schema_offset, reflection::SchemaIdentifier());
3703 }
3704}
3705
James Kuszmauldac091f2022-03-22 09:35:06 -07003706// frc971 modification to make declaration files in schemas deterministic.
3707// TODO(james): Figure out a clean way to make this workspace root relative.
3708namespace {
3709std::string DeclarationFileStripped(const std::string *declaration_file) {
3710 return declaration_file == nullptr ? "" : StripPath(*declaration_file);
3711}
3712}
3713
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003714Offset<reflection::Object> StructDef::Serialize(FlatBufferBuilder *builder,
3715 const Parser &parser) const {
3716 std::vector<Offset<reflection::Field>> field_offsets;
3717 for (auto it = fields.vec.begin(); it != fields.vec.end(); ++it) {
3718 field_offsets.push_back((*it)->Serialize(
3719 builder, static_cast<uint16_t>(it - fields.vec.begin()), parser));
3720 }
James Kuszmauldac091f2022-03-22 09:35:06 -07003721 const auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
3722 const auto name__ = builder->CreateString(qualified_name);
3723 const auto flds__ = builder->CreateVectorOfSortedTables(&field_offsets);
3724 const auto attr__ = SerializeAttributes(builder, parser);
3725 const auto docs__ = parser.opts.binary_schema_comments
3726 ? builder->CreateVectorOfStrings(doc_comment)
3727 : 0;
3728 const auto file__ =
3729 builder->CreateSharedString(DeclarationFileStripped(declaration_file));
3730 return reflection::CreateObject(
3731 *builder, name__, flds__, fixed, static_cast<int>(minalign),
3732 static_cast<int>(bytesize), attr__, docs__, file__);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003733}
3734
3735bool StructDef::Deserialize(Parser &parser, const reflection::Object *object) {
Austin Schuh272c6132020-11-14 16:37:52 -08003736 if (!DeserializeAttributes(parser, object->attributes())) return false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003737 DeserializeDoc(doc_comment, object->documentation());
3738 name = parser.UnqualifiedName(object->name()->str());
3739 predecl = false;
3740 sortbysize = attributes.Lookup("original_order") == nullptr && !fixed;
Austin Schuh272c6132020-11-14 16:37:52 -08003741 const auto &of = *(object->fields());
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003742 auto indexes = std::vector<uoffset_t>(of.size());
3743 for (uoffset_t i = 0; i < of.size(); i++) indexes[of.Get(i)->id()] = i;
3744 size_t tmp_struct_size = 0;
3745 for (size_t i = 0; i < indexes.size(); i++) {
3746 auto field = of.Get(indexes[i]);
3747 auto field_def = new FieldDef();
3748 if (!field_def->Deserialize(parser, field) ||
3749 fields.Add(field_def->name, field_def)) {
3750 delete field_def;
3751 return false;
3752 }
Austin Schuha1d006e2022-09-14 21:50:42 -07003753 if (field_def->key) {
3754 if (has_key) {
3755 // only one field may be set as key
3756 delete field_def;
3757 return false;
3758 }
3759 has_key = true;
3760 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003761 if (fixed) {
3762 // Recompute padding since that's currently not serialized.
3763 auto size = InlineSize(field_def->value.type);
3764 auto next_field =
Austin Schuh272c6132020-11-14 16:37:52 -08003765 i + 1 < indexes.size() ? of.Get(indexes[i + 1]) : nullptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003766 tmp_struct_size += size;
3767 field_def->padding =
3768 next_field ? (next_field->offset() - field_def->value.offset) - size
3769 : PaddingBytes(tmp_struct_size, minalign);
3770 tmp_struct_size += field_def->padding;
3771 }
3772 }
3773 FLATBUFFERS_ASSERT(static_cast<int>(tmp_struct_size) == object->bytesize());
3774 return true;
3775}
3776
3777Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder,
3778 uint16_t id,
3779 const Parser &parser) const {
3780 auto name__ = builder->CreateString(name);
3781 auto type__ = value.type.Serialize(builder);
3782 auto attr__ = SerializeAttributes(builder, parser);
3783 auto docs__ = parser.opts.binary_schema_comments
Austin Schuh272c6132020-11-14 16:37:52 -08003784 ? builder->CreateVectorOfStrings(doc_comment)
3785 : 0;
3786 double d;
3787 StringToNumber(value.constant.c_str(), &d);
3788 return reflection::CreateField(
3789 *builder, name__, type__, id, value.offset,
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003790 // Is uint64>max(int64) tested?
3791 IsInteger(value.type.base_type) ? StringToInt(value.constant.c_str()) : 0,
3792 // result may be platform-dependent if underlying is float (not double)
James Kuszmauldac091f2022-03-22 09:35:06 -07003793 IsFloat(value.type.base_type) ? d : 0.0, deprecated, IsRequired(), key,
3794 attr__, docs__, IsOptional(), static_cast<uint16_t>(padding));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003795 // TODO: value.constant is almost always "0", we could save quite a bit of
3796 // space by sharing it. Same for common values of value.type.
3797}
3798
3799bool FieldDef::Deserialize(Parser &parser, const reflection::Field *field) {
3800 name = field->name()->str();
3801 defined_namespace = parser.current_namespace_;
Austin Schuh272c6132020-11-14 16:37:52 -08003802 if (!value.type.Deserialize(parser, field->type())) return false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003803 value.offset = field->offset();
3804 if (IsInteger(value.type.base_type)) {
3805 value.constant = NumToString(field->default_integer());
3806 } else if (IsFloat(value.type.base_type)) {
3807 value.constant = FloatToString(field->default_real(), 16);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003808 }
James Kuszmauldac091f2022-03-22 09:35:06 -07003809 presence = FieldDef::MakeFieldPresence(field->optional(), field->required());
3810 padding = field->padding();
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003811 key = field->key();
Austin Schuh272c6132020-11-14 16:37:52 -08003812 if (!DeserializeAttributes(parser, field->attributes())) return false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003813 // TODO: this should probably be handled by a separate attribute
3814 if (attributes.Lookup("flexbuffer")) {
3815 flexbuffer = true;
3816 parser.uses_flexbuffers_ = true;
3817 if (value.type.base_type != BASE_TYPE_VECTOR ||
3818 value.type.element != BASE_TYPE_UCHAR)
3819 return false;
3820 }
3821 if (auto nested = attributes.Lookup("nested_flatbuffer")) {
3822 auto nested_qualified_name =
3823 parser.current_namespace_->GetFullyQualifiedName(nested->constant);
3824 nested_flatbuffer = parser.LookupStruct(nested_qualified_name);
3825 if (!nested_flatbuffer) return false;
3826 }
Austin Schuh272c6132020-11-14 16:37:52 -08003827 shared = attributes.Lookup("shared") != nullptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003828 DeserializeDoc(doc_comment, field->documentation());
3829 return true;
3830}
3831
3832Offset<reflection::RPCCall> RPCCall::Serialize(FlatBufferBuilder *builder,
3833 const Parser &parser) const {
3834 auto name__ = builder->CreateString(name);
3835 auto attr__ = SerializeAttributes(builder, parser);
3836 auto docs__ = parser.opts.binary_schema_comments
Austin Schuh272c6132020-11-14 16:37:52 -08003837 ? builder->CreateVectorOfStrings(doc_comment)
3838 : 0;
3839 return reflection::CreateRPCCall(
3840 *builder, name__, request->serialized_location,
3841 response->serialized_location, attr__, docs__);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003842}
3843
3844bool RPCCall::Deserialize(Parser &parser, const reflection::RPCCall *call) {
3845 name = call->name()->str();
Austin Schuh272c6132020-11-14 16:37:52 -08003846 if (!DeserializeAttributes(parser, call->attributes())) return false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003847 DeserializeDoc(doc_comment, call->documentation());
3848 request = parser.structs_.Lookup(call->request()->name()->str());
3849 response = parser.structs_.Lookup(call->response()->name()->str());
3850 if (!request || !response) { return false; }
3851 return true;
3852}
3853
3854Offset<reflection::Service> ServiceDef::Serialize(FlatBufferBuilder *builder,
3855 const Parser &parser) const {
3856 std::vector<Offset<reflection::RPCCall>> servicecall_offsets;
3857 for (auto it = calls.vec.begin(); it != calls.vec.end(); ++it) {
3858 servicecall_offsets.push_back((*it)->Serialize(builder, parser));
3859 }
James Kuszmauldac091f2022-03-22 09:35:06 -07003860 const auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
3861 const auto name__ = builder->CreateString(qualified_name);
3862 const auto call__ = builder->CreateVector(servicecall_offsets);
3863 const auto attr__ = SerializeAttributes(builder, parser);
3864 const auto docs__ = parser.opts.binary_schema_comments
3865 ? builder->CreateVectorOfStrings(doc_comment)
3866 : 0;
3867 const auto file__ =
3868 builder->CreateSharedString(DeclarationFileStripped(declaration_file));
3869 return reflection::CreateService(*builder, name__, call__, attr__, docs__,
3870 file__);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003871}
3872
3873bool ServiceDef::Deserialize(Parser &parser,
3874 const reflection::Service *service) {
3875 name = parser.UnqualifiedName(service->name()->str());
3876 if (service->calls()) {
3877 for (uoffset_t i = 0; i < service->calls()->size(); ++i) {
3878 auto call = new RPCCall();
3879 if (!call->Deserialize(parser, service->calls()->Get(i)) ||
3880 calls.Add(call->name, call)) {
3881 delete call;
3882 return false;
3883 }
3884 }
3885 }
Austin Schuh272c6132020-11-14 16:37:52 -08003886 if (!DeserializeAttributes(parser, service->attributes())) return false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003887 DeserializeDoc(doc_comment, service->documentation());
3888 return true;
3889}
3890
3891Offset<reflection::Enum> EnumDef::Serialize(FlatBufferBuilder *builder,
3892 const Parser &parser) const {
3893 std::vector<Offset<reflection::EnumVal>> enumval_offsets;
3894 for (auto it = vals.vec.begin(); it != vals.vec.end(); ++it) {
3895 enumval_offsets.push_back((*it)->Serialize(builder, parser));
3896 }
James Kuszmauldac091f2022-03-22 09:35:06 -07003897 const auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
3898 const auto name__ = builder->CreateString(qualified_name);
3899 const auto vals__ = builder->CreateVector(enumval_offsets);
3900 const auto type__ = underlying_type.Serialize(builder);
3901 const auto attr__ = SerializeAttributes(builder, parser);
3902 const auto docs__ = parser.opts.binary_schema_comments
3903 ? builder->CreateVectorOfStrings(doc_comment)
3904 : 0;
3905 const auto file__ =
3906 builder->CreateSharedString(DeclarationFileStripped(declaration_file));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003907 return reflection::CreateEnum(*builder, name__, vals__, is_union, type__,
James Kuszmauldac091f2022-03-22 09:35:06 -07003908 attr__, docs__, file__);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003909}
3910
3911bool EnumDef::Deserialize(Parser &parser, const reflection::Enum *_enum) {
3912 name = parser.UnqualifiedName(_enum->name()->str());
3913 for (uoffset_t i = 0; i < _enum->values()->size(); ++i) {
3914 auto val = new EnumVal();
3915 if (!val->Deserialize(parser, _enum->values()->Get(i)) ||
3916 vals.Add(val->name, val)) {
3917 delete val;
3918 return false;
3919 }
3920 }
3921 is_union = _enum->is_union();
3922 if (!underlying_type.Deserialize(parser, _enum->underlying_type())) {
3923 return false;
3924 }
Austin Schuh272c6132020-11-14 16:37:52 -08003925 if (!DeserializeAttributes(parser, _enum->attributes())) return false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003926 DeserializeDoc(doc_comment, _enum->documentation());
3927 return true;
3928}
3929
3930Offset<reflection::EnumVal> EnumVal::Serialize(FlatBufferBuilder *builder,
3931 const Parser &parser) const {
3932 auto name__ = builder->CreateString(name);
3933 auto type__ = union_type.Serialize(builder);
3934 auto docs__ = parser.opts.binary_schema_comments
Austin Schuh272c6132020-11-14 16:37:52 -08003935 ? builder->CreateVectorOfStrings(doc_comment)
3936 : 0;
James Kuszmauldac091f2022-03-22 09:35:06 -07003937 return reflection::CreateEnumVal(*builder, name__, value, type__, docs__);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003938}
3939
3940bool EnumVal::Deserialize(const Parser &parser,
3941 const reflection::EnumVal *val) {
3942 name = val->name()->str();
3943 value = val->value();
Austin Schuh272c6132020-11-14 16:37:52 -08003944 if (!union_type.Deserialize(parser, val->union_type())) return false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003945 DeserializeDoc(doc_comment, val->documentation());
3946 return true;
3947}
3948
3949Offset<reflection::Type> Type::Serialize(FlatBufferBuilder *builder) const {
3950 return reflection::CreateType(
3951 *builder, static_cast<reflection::BaseType>(base_type),
3952 static_cast<reflection::BaseType>(element),
3953 struct_def ? struct_def->index : (enum_def ? enum_def->index : -1),
James Kuszmauldac091f2022-03-22 09:35:06 -07003954 fixed_length, static_cast<uint32_t>(SizeOf(base_type)),
3955 static_cast<uint32_t>(SizeOf(element)));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003956}
3957
3958bool Type::Deserialize(const Parser &parser, const reflection::Type *type) {
3959 if (type == nullptr) return true;
3960 base_type = static_cast<BaseType>(type->base_type());
3961 element = static_cast<BaseType>(type->element());
3962 fixed_length = type->fixed_length();
3963 if (type->index() >= 0) {
James Kuszmauldac091f2022-03-22 09:35:06 -07003964 bool is_series = type->base_type() == reflection::BaseType::Vector ||
3965 type->base_type() == reflection::BaseType::Array;
3966 if (type->base_type() == reflection::BaseType::Obj ||
3967 (is_series && type->element() == reflection::BaseType::Obj)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07003968 if (static_cast<size_t>(type->index()) < parser.structs_.vec.size()) {
3969 struct_def = parser.structs_.vec[type->index()];
3970 struct_def->refcount++;
3971 } else {
3972 return false;
3973 }
3974 } else {
3975 if (static_cast<size_t>(type->index()) < parser.enums_.vec.size()) {
3976 enum_def = parser.enums_.vec[type->index()];
3977 } else {
3978 return false;
3979 }
3980 }
3981 }
3982 return true;
3983}
3984
3985flatbuffers::Offset<
3986 flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
3987Definition::SerializeAttributes(FlatBufferBuilder *builder,
3988 const Parser &parser) const {
3989 std::vector<flatbuffers::Offset<reflection::KeyValue>> attrs;
3990 for (auto kv = attributes.dict.begin(); kv != attributes.dict.end(); ++kv) {
3991 auto it = parser.known_attributes_.find(kv->first);
3992 FLATBUFFERS_ASSERT(it != parser.known_attributes_.end());
3993 if (parser.opts.binary_schema_builtins || !it->second) {
3994 auto key = builder->CreateString(kv->first);
3995 auto val = builder->CreateString(kv->second->constant);
3996 attrs.push_back(reflection::CreateKeyValue(*builder, key, val));
3997 }
3998 }
3999 if (attrs.size()) {
4000 return builder->CreateVectorOfSortedTables(&attrs);
4001 } else {
4002 return 0;
4003 }
4004}
4005
4006bool Definition::DeserializeAttributes(
4007 Parser &parser, const Vector<Offset<reflection::KeyValue>> *attrs) {
Austin Schuh272c6132020-11-14 16:37:52 -08004008 if (attrs == nullptr) return true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07004009 for (uoffset_t i = 0; i < attrs->size(); ++i) {
4010 auto kv = attrs->Get(i);
4011 auto value = new Value();
4012 if (kv->value()) { value->constant = kv->value()->str(); }
4013 if (attributes.Add(kv->key()->str(), value)) {
4014 delete value;
4015 return false;
4016 }
4017 parser.known_attributes_[kv->key()->str()];
4018 }
4019 return true;
4020}
4021
4022/************************************************************************/
4023/* DESERIALIZATION */
4024/************************************************************************/
4025bool Parser::Deserialize(const uint8_t *buf, const size_t size) {
4026 flatbuffers::Verifier verifier(reinterpret_cast<const uint8_t *>(buf), size);
4027 bool size_prefixed = false;
Austin Schuh272c6132020-11-14 16:37:52 -08004028 if (!reflection::SchemaBufferHasIdentifier(buf)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07004029 if (!flatbuffers::BufferHasIdentifier(buf, reflection::SchemaIdentifier(),
4030 true))
4031 return false;
4032 else
4033 size_prefixed = true;
4034 }
4035 auto verify_fn = size_prefixed ? &reflection::VerifySizePrefixedSchemaBuffer
4036 : &reflection::VerifySchemaBuffer;
Austin Schuh272c6132020-11-14 16:37:52 -08004037 if (!verify_fn(verifier)) { return false; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07004038 auto schema = size_prefixed ? reflection::GetSizePrefixedSchema(buf)
4039 : reflection::GetSchema(buf);
4040 return Deserialize(schema);
4041}
4042
4043bool Parser::Deserialize(const reflection::Schema *schema) {
4044 file_identifier_ = schema->file_ident() ? schema->file_ident()->str() : "";
4045 file_extension_ = schema->file_ext() ? schema->file_ext()->str() : "";
4046 std::map<std::string, Namespace *> namespaces_index;
4047
4048 // Create defs without deserializing so references from fields to structs and
4049 // enums can be resolved.
4050 for (auto it = schema->objects()->begin(); it != schema->objects()->end();
4051 ++it) {
4052 auto struct_def = new StructDef();
4053 struct_def->bytesize = it->bytesize();
4054 struct_def->fixed = it->is_struct();
4055 struct_def->minalign = it->minalign();
4056 if (structs_.Add(it->name()->str(), struct_def)) {
4057 delete struct_def;
4058 return false;
4059 }
4060 auto type = new Type(BASE_TYPE_STRUCT, struct_def, nullptr);
4061 if (types_.Add(it->name()->str(), type)) {
4062 delete type;
4063 return false;
4064 }
4065 }
4066 for (auto it = schema->enums()->begin(); it != schema->enums()->end(); ++it) {
4067 auto enum_def = new EnumDef();
4068 if (enums_.Add(it->name()->str(), enum_def)) {
4069 delete enum_def;
4070 return false;
4071 }
4072 auto type = new Type(BASE_TYPE_UNION, nullptr, enum_def);
4073 if (types_.Add(it->name()->str(), type)) {
4074 delete type;
4075 return false;
4076 }
4077 }
4078
4079 // Now fields can refer to structs and enums by index.
4080 for (auto it = schema->objects()->begin(); it != schema->objects()->end();
4081 ++it) {
4082 std::string qualified_name = it->name()->str();
4083 auto struct_def = structs_.Lookup(qualified_name);
4084 struct_def->defined_namespace =
4085 GetNamespace(qualified_name, namespaces_, namespaces_index);
Austin Schuh272c6132020-11-14 16:37:52 -08004086 if (!struct_def->Deserialize(*this, *it)) { return false; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07004087 if (schema->root_table() == *it) { root_struct_def_ = struct_def; }
4088 }
4089 for (auto it = schema->enums()->begin(); it != schema->enums()->end(); ++it) {
4090 std::string qualified_name = it->name()->str();
4091 auto enum_def = enums_.Lookup(qualified_name);
4092 enum_def->defined_namespace =
4093 GetNamespace(qualified_name, namespaces_, namespaces_index);
4094 if (!enum_def->Deserialize(*this, *it)) { return false; }
4095 }
4096
4097 if (schema->services()) {
4098 for (auto it = schema->services()->begin(); it != schema->services()->end();
4099 ++it) {
4100 std::string qualified_name = it->name()->str();
4101 auto service_def = new ServiceDef();
4102 service_def->defined_namespace =
4103 GetNamespace(qualified_name, namespaces_, namespaces_index);
4104 if (!service_def->Deserialize(*this, *it) ||
4105 services_.Add(qualified_name, service_def)) {
4106 delete service_def;
4107 return false;
4108 }
4109 }
4110 }
James Kuszmauldac091f2022-03-22 09:35:06 -07004111 advanced_features_ = static_cast<uint64_t>(schema->advanced_features());
4112
4113 if (schema->fbs_files())
4114 for (auto s = schema->fbs_files()->begin(); s != schema->fbs_files()->end();
4115 ++s) {
4116 for (auto f = s->included_filenames()->begin();
4117 f != s->included_filenames()->end(); ++f) {
Austin Schuha1d006e2022-09-14 21:50:42 -07004118 IncludedFile included_file;
4119 included_file.filename = f->str();
4120 files_included_per_file_[s->filename()->str()].insert(included_file);
James Kuszmauldac091f2022-03-22 09:35:06 -07004121 }
4122 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07004123
4124 return true;
4125}
4126
4127std::string Parser::ConformTo(const Parser &base) {
4128 for (auto sit = structs_.vec.begin(); sit != structs_.vec.end(); ++sit) {
4129 auto &struct_def = **sit;
4130 auto qualified_name =
4131 struct_def.defined_namespace->GetFullyQualifiedName(struct_def.name);
4132 auto struct_def_base = base.LookupStruct(qualified_name);
4133 if (!struct_def_base) continue;
4134 for (auto fit = struct_def.fields.vec.begin();
4135 fit != struct_def.fields.vec.end(); ++fit) {
4136 auto &field = **fit;
4137 auto field_base = struct_def_base->fields.Lookup(field.name);
4138 if (field_base) {
4139 if (field.value.offset != field_base->value.offset)
4140 return "offsets differ for field: " + field.name;
4141 if (field.value.constant != field_base->value.constant)
4142 return "defaults differ for field: " + field.name;
4143 if (!EqualByName(field.value.type, field_base->value.type))
4144 return "types differ for field: " + field.name;
4145 } else {
4146 // Doesn't have to exist, deleting fields is fine.
4147 // But we should check if there is a field that has the same offset
4148 // but is incompatible (in the case of field renaming).
4149 for (auto fbit = struct_def_base->fields.vec.begin();
4150 fbit != struct_def_base->fields.vec.end(); ++fbit) {
4151 field_base = *fbit;
4152 if (field.value.offset == field_base->value.offset) {
4153 if (!EqualByName(field.value.type, field_base->value.type))
4154 return "field renamed to different type: " + field.name;
4155 break;
4156 }
4157 }
4158 }
4159 }
4160 }
4161 for (auto eit = enums_.vec.begin(); eit != enums_.vec.end(); ++eit) {
4162 auto &enum_def = **eit;
4163 auto qualified_name =
4164 enum_def.defined_namespace->GetFullyQualifiedName(enum_def.name);
4165 auto enum_def_base = base.enums_.Lookup(qualified_name);
4166 if (!enum_def_base) continue;
4167 for (auto evit = enum_def.Vals().begin(); evit != enum_def.Vals().end();
4168 ++evit) {
4169 auto &enum_val = **evit;
4170 auto enum_val_base = enum_def_base->Lookup(enum_val.name);
4171 if (enum_val_base) {
4172 if (enum_val != *enum_val_base)
4173 return "values differ for enum: " + enum_val.name;
4174 }
4175 }
4176 }
4177 return "";
4178}
4179
4180} // namespace flatbuffers