blob: 4a372b8e7495dc65d12569f1b787e76b8224d7fc [file] [log] [blame]
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -08001/*
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>
18
19#include "flatbuffers/flatbuffers.h"
20#include "flatbuffers/idl.h"
21#include "flatbuffers/util.h"
22
23namespace flatbuffers {
24
25const char *const kTypeNames[] = {
26 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) IDLTYPE,
27 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
28 #undef FLATBUFFERS_TD
29 nullptr
30};
31
32const char kTypeSizes[] = {
33 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) sizeof(CTYPE),
34 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
35 #undef FLATBUFFERS_TD
36};
37
38static void Error(const std::string &msg) {
39 throw msg;
40}
41
42// Ensure that integer values we parse fit inside the declared integer type.
43static void CheckBitsFit(int64_t val, size_t bits) {
44 auto mask = (1ll << bits) - 1; // Bits we allow to be used.
45 if (bits < 64 &&
46 (val & ~mask) != 0 && // Positive or unsigned.
47 (val | mask) != -1) // Negative.
48 Error("constant does not fit in a " + NumToString(bits) + "-bit field");
49}
50
51// atot: templated version of atoi/atof: convert a string to an instance of T.
52template<typename T> inline T atot(const char *s) {
53 auto val = StringToInt(s);
54 CheckBitsFit(val, sizeof(T) * 8);
55 return (T)val;
56}
57template<> inline bool atot<bool>(const char *s) {
58 return 0 != atoi(s);
59}
60template<> inline float atot<float>(const char *s) {
61 return static_cast<float>(strtod(s, nullptr));
62}
63template<> inline double atot<double>(const char *s) {
64 return strtod(s, nullptr);
65}
66
67template<> inline Offset<void> atot<Offset<void>>(const char *s) {
68 return Offset<void>(atoi(s));
69}
70
71// Declare tokens we'll use. Single character tokens are represented by their
72// ascii character code (e.g. '{'), others above 256.
73#define FLATBUFFERS_GEN_TOKENS(TD) \
74 TD(Eof, 256, "end of file") \
75 TD(StringConstant, 257, "string constant") \
76 TD(IntegerConstant, 258, "integer constant") \
77 TD(FloatConstant, 259, "float constant") \
78 TD(Identifier, 260, "identifier") \
79 TD(Table, 261, "table") \
80 TD(Struct, 262, "struct") \
81 TD(Enum, 263, "enum") \
82 TD(Union, 264, "union") \
83 TD(NameSpace, 265, "namespace") \
84 TD(RootType, 266, "root_type")
85enum {
Wouter van Oortmerssen75349ae2014-07-09 11:44:26 -070086 #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME = VALUE,
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -080087 FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
88 #undef FLATBUFFERS_TOKEN
89 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) kToken ## ENUM,
90 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
91 #undef FLATBUFFERS_TD
92};
93
94static std::string TokenToString(int t) {
95 static const char *tokens[] = {
96 #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) STRING,
97 FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
98 #undef FLATBUFFERS_TOKEN
99 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) IDLTYPE,
100 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
101 #undef FLATBUFFERS_TD
102 };
103 if (t < 256) { // A single ascii char token.
104 std::string s;
105 s.append(1, t);
106 return s;
107 } else { // Other tokens.
108 return tokens[t - 256];
109 }
110}
111
112void Parser::Next() {
113 doc_comment_.clear();
114 bool seen_newline = false;
115 for (;;) {
116 char c = *cursor_++;
117 token_ = c;
118 switch (c) {
119 case '\0': cursor_--; token_ = kTokenEof; return;
120 case ' ': case '\r': case '\t': break;
121 case '\n': line_++; seen_newline = true; break;
122 case '{': case '}': case '(': case ')': case '[': case ']': return;
123 case ',': case ':': case ';': case '=': return;
124 case '.':
125 if(!isdigit(*cursor_)) return;
126 Error("floating point constant can\'t start with \".\"");
127 break;
128 case '\"':
129 attribute_ = "";
130 while (*cursor_ != '\"') {
131 if (*cursor_ < ' ' && *cursor_ >= 0)
132 Error("illegal character in string constant");
133 if (*cursor_ == '\\') {
134 cursor_++;
135 switch (*cursor_) {
136 case 'n': attribute_ += '\n'; cursor_++; break;
137 case 't': attribute_ += '\t'; cursor_++; break;
138 case 'r': attribute_ += '\r'; cursor_++; break;
139 case '\"': attribute_ += '\"'; cursor_++; break;
140 case '\\': attribute_ += '\\'; cursor_++; break;
141 default: Error("unknown escape code in string constant"); break;
142 }
143 } else { // printable chars + UTF-8 bytes
144 attribute_ += *cursor_++;
145 }
146 }
147 cursor_++;
148 token_ = kTokenStringConstant;
149 return;
150 case '/':
151 if (*cursor_ == '/') {
152 const char *start = ++cursor_;
153 while (*cursor_ && *cursor_ != '\n') cursor_++;
154 if (*start == '/') { // documentation comment
155 if (!seen_newline)
156 Error("a documentation comment should be on a line on its own");
157 // todo: do we want to support multiline comments instead?
158 doc_comment_ += std::string(start + 1, cursor_);
159 }
160 break;
161 }
162 // fall thru
163 default:
164 if (isalpha(static_cast<unsigned char>(c))) {
165 // Collect all chars of an identifier:
166 const char *start = cursor_ - 1;
167 while (isalnum(static_cast<unsigned char>(*cursor_)) ||
168 *cursor_ == '_')
169 cursor_++;
170 attribute_.clear();
171 attribute_.append(start, cursor_);
172 // First, see if it is a type keyword from the table of types:
173 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \
174 if (attribute_ == IDLTYPE) { \
175 token_ = kToken ## ENUM; \
176 return; \
177 }
178 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
179 #undef FLATBUFFERS_TD
180 // If it's a boolean constant keyword, turn those into integers,
181 // which simplifies our logic downstream.
182 if (attribute_ == "true" || attribute_ == "false") {
183 attribute_ = NumToString(attribute_ == "true");
184 token_ = kTokenIntegerConstant;
185 return;
186 }
187 // Check for declaration keywords:
188 if (attribute_ == "table") { token_ = kTokenTable; return; }
189 if (attribute_ == "struct") { token_ = kTokenStruct; return; }
190 if (attribute_ == "enum") { token_ = kTokenEnum; return; }
191 if (attribute_ == "union") { token_ = kTokenUnion; return; }
192 if (attribute_ == "namespace") { token_ = kTokenNameSpace; return; }
193 if (attribute_ == "root_type") { token_ = kTokenRootType; return; }
194 // If not, it is a user-defined identifier:
195 token_ = kTokenIdentifier;
196 return;
197 } else if (isdigit(static_cast<unsigned char>(c)) || c == '-') {
198 const char *start = cursor_ - 1;
199 while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
200 if (*cursor_ == '.') {
201 cursor_++;
202 while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
Wouter van Oortmerssen93df5692014-07-10 13:40:55 -0700203 // See if this float has a scientific notation suffix. Both JSON
204 // and C++ (through strtod() we use) have the same format:
205 if (*cursor_ == 'e' || *cursor_ == 'E') {
206 cursor_++;
207 if (*cursor_ == '+' || *cursor_ == '-') cursor_++;
208 while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
209 }
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800210 token_ = kTokenFloatConstant;
211 } else {
212 token_ = kTokenIntegerConstant;
213 }
214 attribute_.clear();
215 attribute_.append(start, cursor_);
216 return;
217 }
218 std::string ch;
219 ch = c;
220 if (c < ' ' || c > '~') ch = "code: " + NumToString(c);
221 Error("illegal character: " + ch);
222 break;
223 }
224 }
225}
226
227// Check if a given token is next, if so, consume it as well.
228bool Parser::IsNext(int t) {
229 bool isnext = t == token_;
230 if (isnext) Next();
231 return isnext;
232}
233
234// Expect a given token to be next, consume it, or error if not present.
235void Parser::Expect(int t) {
236 if (t != token_) {
237 Error("expecting: " + TokenToString(t) + " instead got: " +
238 TokenToString(token_));
239 }
240 Next();
241}
242
243// Parse any IDL type.
244void Parser::ParseType(Type &type) {
245 if (token_ >= kTokenBOOL && token_ <= kTokenSTRING) {
246 type.base_type = static_cast<BaseType>(token_ - kTokenNONE);
247 } else {
248 if (token_ == kTokenIdentifier) {
249 auto enum_def = enums_.Lookup(attribute_);
250 if (enum_def) {
251 type = enum_def->underlying_type;
252 if (enum_def->is_union) type.base_type = BASE_TYPE_UNION;
253 } else {
254 type.base_type = BASE_TYPE_STRUCT;
255 type.struct_def = LookupCreateStruct(attribute_);
256 }
257 } else if (token_ == '[') {
258 Next();
259 Type subtype;
260 ParseType(subtype);
261 if (subtype.base_type == BASE_TYPE_VECTOR) {
262 // We could support this, but it will complicate things, and it's
263 // easier to work around with a struct around the inner vector.
264 Error("nested vector types not supported (wrap in table first).");
265 }
266 if (subtype.base_type == BASE_TYPE_UNION) {
267 // We could support this if we stored a struct of 2 elements per
268 // union element.
269 Error("vector of union types not supported (wrap in table first).");
270 }
271 type = Type(BASE_TYPE_VECTOR, subtype.struct_def);
272 type.element = subtype.base_type;
273 Expect(']');
274 return;
275 } else {
276 Error("illegal type syntax");
277 }
278 }
279 Next();
280}
281
282FieldDef &Parser::AddField(StructDef &struct_def,
283 const std::string &name,
284 const Type &type) {
285 auto &field = *new FieldDef();
286 field.value.offset =
287 FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size()));
288 field.name = name;
289 field.value.type = type;
290 if (struct_def.fixed) { // statically compute the field offset
291 auto size = InlineSize(type);
292 auto alignment = InlineAlignment(type);
293 // structs_ need to have a predictable format, so we need to align to
294 // the largest scalar
295 struct_def.minalign = std::max(struct_def.minalign, alignment);
296 struct_def.PadLastField(alignment);
Wouter van Oortmerssen12563072014-06-30 15:56:31 -0700297 field.value.offset = static_cast<voffset_t>(struct_def.bytesize);
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800298 struct_def.bytesize += size;
299 }
300 if (struct_def.fields.Add(name, &field))
301 Error("field already exists: " + name);
302 return field;
303}
304
305void Parser::ParseField(StructDef &struct_def) {
306 std::string name = attribute_;
307 std::string dc = doc_comment_;
308 Expect(kTokenIdentifier);
309 Expect(':');
310 Type type;
311 ParseType(type);
312
313 if (struct_def.fixed && !IsScalar(type.base_type) && !IsStruct(type))
314 Error("structs_ may contain only scalar or struct fields");
315
Wouter van Oortmerssen91401442014-07-07 17:34:23 -0700316 FieldDef *typefield = nullptr;
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800317 if (type.base_type == BASE_TYPE_UNION) {
318 // For union fields, add a second auto-generated field to hold the type,
319 // with _type appended as the name.
Wouter van Oortmerssen91401442014-07-07 17:34:23 -0700320 typefield = &AddField(struct_def, name + "_type",
321 type.enum_def->underlying_type);
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800322 }
323
324 auto &field = AddField(struct_def, name, type);
325
326 if (token_ == '=') {
327 Next();
328 ParseSingleValue(field.value);
329 }
330
331 field.doc_comment = dc;
332 ParseMetaData(field);
333 field.deprecated = field.attributes.Lookup("deprecated") != nullptr;
334 if (field.deprecated && struct_def.fixed)
335 Error("can't deprecate fields in a struct");
336
Wouter van Oortmerssen91401442014-07-07 17:34:23 -0700337 if (typefield) {
338 // If this field is a union, and it has a manually assigned id,
339 // the automatically added type field should have an id as well (of N - 1).
340 auto attr = field.attributes.Lookup("id");
341 if (attr) {
342 auto id = atoi(attr->constant.c_str());
343 auto val = new Value();
344 val->type = attr->type;
345 val->constant = NumToString(id - 1);
346 typefield->attributes.Add("id", val);
347 }
348 }
349
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800350 Expect(';');
351}
352
353void Parser::ParseAnyValue(Value &val, FieldDef *field) {
354 switch (val.type.base_type) {
355 case BASE_TYPE_UNION: {
356 assert(field);
357 if (!field_stack_.size() ||
358 field_stack_.back().second->value.type.base_type != BASE_TYPE_UTYPE)
359 Error("missing type field before this union value: " + field->name);
360 auto enum_idx = atot<unsigned char>(
361 field_stack_.back().first.constant.c_str());
362 auto struct_def = val.type.enum_def->ReverseLookup(enum_idx);
363 if (!struct_def) Error("illegal type id for: " + field->name);
364 val.constant = NumToString(ParseTable(*struct_def));
365 break;
366 }
367 case BASE_TYPE_STRUCT:
368 val.constant = NumToString(ParseTable(*val.type.struct_def));
369 break;
370 case BASE_TYPE_STRING: {
371 auto s = attribute_;
372 Expect(kTokenStringConstant);
373 val.constant = NumToString(builder_.CreateString(s).o);
374 break;
375 }
376 case BASE_TYPE_VECTOR: {
377 Expect('[');
378 val.constant = NumToString(ParseVector(val.type.VectorType()));
379 break;
380 }
381 default:
382 ParseSingleValue(val);
383 break;
384 }
385}
386
387void Parser::SerializeStruct(const StructDef &struct_def, const Value &val) {
388 auto off = atot<uoffset_t>(val.constant.c_str());
389 assert(struct_stack_.size() - off == struct_def.bytesize);
390 builder_.Align(struct_def.minalign);
391 builder_.PushBytes(&struct_stack_[off], struct_def.bytesize);
392 struct_stack_.resize(struct_stack_.size() - struct_def.bytesize);
393 builder_.AddStructOffset(val.offset, builder_.GetSize());
394}
395
396uoffset_t Parser::ParseTable(const StructDef &struct_def) {
397 Expect('{');
398 size_t fieldn = 0;
399 for (;;) {
400 std::string name = attribute_;
401 if (!IsNext(kTokenStringConstant)) Expect(kTokenIdentifier);
402 auto field = struct_def.fields.Lookup(name);
403 if (!field) Error("unknown field: " + name);
404 if (struct_def.fixed && (fieldn >= struct_def.fields.vec.size()
405 || struct_def.fields.vec[fieldn] != field)) {
406 Error("struct field appearing out of order: " + name);
407 }
408 Expect(':');
409 Value val = field->value;
410 ParseAnyValue(val, field);
411 field_stack_.push_back(std::make_pair(val, field));
412 fieldn++;
413 if (IsNext('}')) break;
414 Expect(',');
415 }
416 if (struct_def.fixed && fieldn != struct_def.fields.vec.size())
417 Error("incomplete struct initialization: " + struct_def.name);
418 auto start = struct_def.fixed
419 ? builder_.StartStruct(struct_def.minalign)
420 : builder_.StartTable();
421
422 for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
423 size;
424 size /= 2) {
425 // Go through elements in reverse, since we're building the data backwards.
426 for (auto it = field_stack_.rbegin();
427 it != field_stack_.rbegin() + fieldn; ++it) {
428 auto &value = it->first;
429 auto field = it->second;
430 if (!struct_def.sortbysize || size == SizeOf(value.type.base_type)) {
431 switch (value.type.base_type) {
432 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \
433 case BASE_TYPE_ ## ENUM: \
434 builder_.Pad(field->padding); \
435 builder_.AddElement(value.offset, \
436 atot<CTYPE>( value.constant.c_str()), \
437 atot<CTYPE>(field->value.constant.c_str())); \
438 break;
439 FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD);
440 #undef FLATBUFFERS_TD
441 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \
442 case BASE_TYPE_ ## ENUM: \
443 builder_.Pad(field->padding); \
444 if (IsStruct(field->value.type)) { \
445 SerializeStruct(*field->value.type.struct_def, value); \
446 } else { \
447 builder_.AddOffset(value.offset, \
448 atot<CTYPE>(value.constant.c_str())); \
449 } \
450 break;
451 FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD);
452 #undef FLATBUFFERS_TD
453 }
454 }
455 }
456 }
457 for (size_t i = 0; i < fieldn; i++) field_stack_.pop_back();
458
459 if (struct_def.fixed) {
460 builder_.ClearOffsets();
461 builder_.EndStruct();
462 // Temporarily store this struct in a side buffer, since this data has to
463 // be stored in-line later in the parent object.
464 auto off = struct_stack_.size();
465 struct_stack_.insert(struct_stack_.end(),
466 builder_.GetBufferPointer(),
467 builder_.GetBufferPointer() + struct_def.bytesize);
468 builder_.PopBytes(struct_def.bytesize);
469 return static_cast<uoffset_t>(off);
470 } else {
471 return builder_.EndTable(
472 start,
473 static_cast<voffset_t>(struct_def.fields.vec.size()));
474 }
475}
476
477uoffset_t Parser::ParseVector(const Type &type) {
478 int count = 0;
479 if (token_ != ']') for (;;) {
480 Value val;
481 val.type = type;
482 ParseAnyValue(val, NULL);
483 field_stack_.push_back(std::make_pair(val, nullptr));
484 count++;
485 if (token_ == ']') break;
486 Expect(',');
487 }
488 Next();
489
490 builder_.StartVector(count * InlineSize(type), InlineAlignment((type)));
491 for (int i = 0; i < count; i++) {
492 // start at the back, since we're building the data backwards.
493 auto &val = field_stack_.back().first;
494 switch (val.type.base_type) {
495 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \
496 case BASE_TYPE_ ## ENUM: \
497 if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \
498 else builder_.PushElement(atot<CTYPE>(val.constant.c_str())); \
499 break;
500 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
501 #undef FLATBUFFERS_TD
502 }
503 field_stack_.pop_back();
504 }
505
506 builder_.ClearOffsets();
507 return builder_.EndVector(count);
508}
509
510void Parser::ParseMetaData(Definition &def) {
511 if (IsNext('(')) {
512 for (;;) {
513 auto name = attribute_;
514 Expect(kTokenIdentifier);
515 auto e = new Value();
516 def.attributes.Add(name, e);
517 if (IsNext(':')) {
518 ParseSingleValue(*e);
519 }
520 if (IsNext(')')) break;
521 Expect(',');
522 }
523 }
524}
525
526bool Parser::TryTypedValue(int dtoken,
527 bool check,
528 Value &e,
529 BaseType req) {
530 bool match = dtoken == token_;
531 if (match) {
532 e.constant = attribute_;
533 if (!check) {
534 if (e.type.base_type == BASE_TYPE_NONE) {
535 e.type.base_type = req;
536 } else {
537 Error(std::string("type mismatch: expecting: ") +
538 kTypeNames[e.type.base_type] +
539 ", found: " +
540 kTypeNames[req]);
541 }
542 }
543 Next();
544 }
545 return match;
546}
547
548void Parser::ParseSingleValue(Value &e) {
549 if (TryTypedValue(kTokenIntegerConstant,
550 IsScalar(e.type.base_type),
551 e,
552 BASE_TYPE_INT) ||
553 TryTypedValue(kTokenFloatConstant,
554 IsFloat(e.type.base_type),
555 e,
556 BASE_TYPE_FLOAT) ||
557 TryTypedValue(kTokenStringConstant,
558 e.type.base_type == BASE_TYPE_STRING,
559 e,
560 BASE_TYPE_STRING)) {
561 } else if (token_ == kTokenIdentifier) {
562 for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
563 auto ev = (*it)->vals.Lookup(attribute_);
564 if (ev) {
565 attribute_ = NumToString(ev->value);
566 TryTypedValue(kTokenIdentifier,
567 IsInteger(e.type.base_type),
568 e,
569 BASE_TYPE_INT);
570 return;
571 }
572 }
573 Error("not valid enum value: " + attribute_);
574 } else {
575 Error("cannot parse value starting with: " + TokenToString(token_));
576 }
577}
578
579StructDef *Parser::LookupCreateStruct(const std::string &name) {
580 auto struct_def = structs_.Lookup(name);
581 if (!struct_def) {
582 // Rather than failing, we create a "pre declared" StructDef, due to
583 // circular references, and check for errors at the end of parsing.
584 struct_def = new StructDef();
585 structs_.Add(name, struct_def);
586 struct_def->name = name;
587 struct_def->predecl = true;
588 }
589 return struct_def;
590}
591
592void Parser::ParseEnum(bool is_union) {
593 std::string dc = doc_comment_;
594 Next();
595 std::string name = attribute_;
596 Expect(kTokenIdentifier);
597 auto &enum_def = *new EnumDef();
598 enum_def.name = name;
599 enum_def.doc_comment = dc;
600 enum_def.is_union = is_union;
601 if (enums_.Add(name, &enum_def)) Error("enum already exists: " + name);
602 if (is_union) {
603 enum_def.underlying_type.base_type = BASE_TYPE_UTYPE;
604 enum_def.underlying_type.enum_def = &enum_def;
Wouter van Oortmerssena5f50012014-07-02 12:01:21 -0700605 } else {
606 // Give specialized error message, since this type spec used to
607 // be optional in the first FlatBuffers release.
608 if (!IsNext(':')) Error("must specify the underlying integer type for this"
609 " enum (e.g. \': short\', which was the default).");
610 // Specify the integer type underlying this enum.
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800611 ParseType(enum_def.underlying_type);
612 if (!IsInteger(enum_def.underlying_type.base_type))
613 Error("underlying enum type must be integral");
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800614 }
615 ParseMetaData(enum_def);
616 Expect('{');
617 if (is_union) enum_def.vals.Add("NONE", new EnumVal("NONE", 0));
618 do {
619 std::string name = attribute_;
620 std::string dc = doc_comment_;
621 Expect(kTokenIdentifier);
622 auto prevsize = enum_def.vals.vec.size();
623 auto &ev = *new EnumVal(name, static_cast<int>(
624 enum_def.vals.vec.size()
625 ? enum_def.vals.vec.back()->value + 1
626 : 0));
627 if (enum_def.vals.Add(name, &ev))
628 Error("enum value already exists: " + name);
629 ev.doc_comment = dc;
630 if (is_union) {
631 ev.struct_def = LookupCreateStruct(name);
632 }
633 if (IsNext('=')) {
634 ev.value = atoi(attribute_.c_str());
635 Expect(kTokenIntegerConstant);
636 if (prevsize && enum_def.vals.vec[prevsize - 1]->value >= ev.value)
637 Error("enum values must be specified in ascending order");
638 }
639 } while (IsNext(','));
640 Expect('}');
641}
642
643void Parser::ParseDecl() {
644 std::string dc = doc_comment_;
645 bool fixed = IsNext(kTokenStruct);
646 if (!fixed) Expect(kTokenTable);
647 std::string name = attribute_;
648 Expect(kTokenIdentifier);
649 auto &struct_def = *LookupCreateStruct(name);
650 if (!struct_def.predecl) Error("datatype already exists: " + name);
651 struct_def.predecl = false;
652 struct_def.name = name;
653 struct_def.doc_comment = dc;
654 struct_def.fixed = fixed;
655 // Move this struct to the back of the vector just in case it was predeclared,
656 // to preserve declartion order.
657 remove(structs_.vec.begin(), structs_.vec.end(), &struct_def);
658 structs_.vec.back() = &struct_def;
659 ParseMetaData(struct_def);
660 struct_def.sortbysize =
661 struct_def.attributes.Lookup("original_order") == nullptr && !fixed;
662 Expect('{');
663 while (token_ != '}') ParseField(struct_def);
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800664 auto force_align = struct_def.attributes.Lookup("force_align");
665 if (fixed && force_align) {
666 auto align = static_cast<size_t>(atoi(force_align->constant.c_str()));
667 if (force_align->type.base_type != BASE_TYPE_INT ||
668 align < struct_def.minalign ||
669 align > 256 ||
670 align & (align - 1))
671 Error("force_align must be a power of two integer ranging from the"
672 "struct\'s natural alignment to 256");
673 struct_def.minalign = align;
674 }
Wouter van Oortmerssen65cfa182014-06-23 11:34:19 -0700675 struct_def.PadLastField(struct_def.minalign);
Wouter van Oortmerssen91401442014-07-07 17:34:23 -0700676 // Check if this is a table that has manual id assignments
677 auto &fields = struct_def.fields.vec;
678 if (!struct_def.fixed && fields.size()) {
Wouter van Oortmerssen7fcbe722014-07-08 16:35:14 -0700679 size_t num_id_fields = 0;
Wouter van Oortmerssen91401442014-07-07 17:34:23 -0700680 for (auto it = fields.begin(); it != fields.end(); ++it) {
681 if ((*it)->attributes.Lookup("id")) num_id_fields++;
682 }
683 // If any fields have ids..
684 if (num_id_fields) {
685 // Then all fields must have them.
686 if (num_id_fields != fields.size())
687 Error("either all fields or no fields must have an 'id' attribute");
688 // Simply sort by id, then the fields are the same as if no ids had
689 // been specified.
690 std::sort(fields.begin(), fields.end(),
691 [](const FieldDef *a, const FieldDef *b) -> bool {
692 auto a_id = atoi(a->attributes.Lookup("id")->constant.c_str());
693 auto b_id = atoi(b->attributes.Lookup("id")->constant.c_str());
694 return a_id < b_id;
695 });
696 // Verify we have a contiguous set, and reassign vtable offsets.
697 for (int i = 0; i < static_cast<int>(fields.size()); i++) {
698 if (i != atoi(fields[i]->attributes.Lookup("id")->constant.c_str()))
699 Error("field id\'s must be consecutive from 0, id " +
700 NumToString(i) + " missing or set twice");
701 fields[i]->value.offset = FieldIndexToOffset(static_cast<voffset_t>(i));
702 }
703 }
704 }
Wouter van Oortmerssen65cfa182014-06-23 11:34:19 -0700705 Expect('}');
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800706}
707
708bool Parser::SetRootType(const char *name) {
709 root_struct_def = structs_.Lookup(name);
710 return root_struct_def != nullptr;
711}
712
713bool Parser::Parse(const char *source) {
714 source_ = cursor_ = source;
715 line_ = 1;
716 error_.clear();
717 builder_.Clear();
718 try {
719 Next();
720 while (token_ != kTokenEof) {
721 if (token_ == kTokenNameSpace) {
722 Next();
Wouter van Oortmerssen2208de02014-07-09 14:21:11 -0700723 name_space_.clear();
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800724 for (;;) {
725 name_space_.push_back(attribute_);
726 Expect(kTokenIdentifier);
727 if (!IsNext('.')) break;
728 }
729 Expect(';');
730 } else if (token_ == '{') {
731 if (!root_struct_def) Error("no root type set to parse json with");
732 if (builder_.GetSize()) {
733 Error("cannot have more than one json object in a file");
734 }
735 builder_.Finish(Offset<Table>(ParseTable(*root_struct_def)));
736 } else if (token_ == kTokenEnum) {
737 ParseEnum(false);
738 } else if (token_ == kTokenUnion) {
739 ParseEnum(true);
740 } else if (token_ == kTokenRootType) {
741 Next();
742 auto root_type = attribute_;
743 Expect(kTokenIdentifier);
744 Expect(';');
745 if (!SetRootType(root_type.c_str()))
746 Error("unknown root type: " + root_type);
747 if (root_struct_def->fixed)
748 Error("root type must be a table");
749 } else {
750 ParseDecl();
751 }
752 }
753 for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
754 if ((*it)->predecl)
755 Error("type referenced but not defined: " + (*it)->name);
756 }
757 for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
758 auto &enum_def = **it;
759 if (enum_def.is_union) {
760 for (auto it = enum_def.vals.vec.begin();
761 it != enum_def.vals.vec.end();
762 ++it) {
763 auto &val = **it;
764 if (val.struct_def && val.struct_def->fixed)
765 Error("only tables can be union elements: " + val.name);
766 }
767 }
768 }
769 } catch (const std::string &msg) {
770 error_ = "line " + NumToString(line_) + ": " + msg;
771 return false;
772 }
773 assert(!struct_stack_.size());
774 return true;
775}
776
777} // namespace flatbuffers