blob: 1d9018eb89c12da9dbd2c5f18451e8d133e03439 [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[] = {
rw74d5f372014-07-11 16:12:35 -070026 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) IDLTYPE,
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -080027 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
28 #undef FLATBUFFERS_TD
29 nullptr
30};
31
32const char kTypeSizes[] = {
rw74d5f372014-07-11 16:12:35 -070033 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) sizeof(CTYPE),
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -080034 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")
Wouter van Oortmerssen8f80fec2014-07-29 10:29:38 -070085#ifdef __GNUC__
86__extension__ // Stop GCC complaining about trailing comma with -Wpendantic.
87#endif
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -080088enum {
Wouter van Oortmerssen75349ae2014-07-09 11:44:26 -070089 #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME = VALUE,
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -080090 FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
91 #undef FLATBUFFERS_TOKEN
rw74d5f372014-07-11 16:12:35 -070092 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) kToken ## ENUM,
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -080093 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
94 #undef FLATBUFFERS_TD
95};
96
97static std::string TokenToString(int t) {
98 static const char *tokens[] = {
99 #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) STRING,
100 FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
101 #undef FLATBUFFERS_TOKEN
rw74d5f372014-07-11 16:12:35 -0700102 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) IDLTYPE,
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800103 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
104 #undef FLATBUFFERS_TD
105 };
106 if (t < 256) { // A single ascii char token.
107 std::string s;
108 s.append(1, t);
109 return s;
110 } else { // Other tokens.
111 return tokens[t - 256];
112 }
113}
114
115void Parser::Next() {
116 doc_comment_.clear();
117 bool seen_newline = false;
118 for (;;) {
119 char c = *cursor_++;
120 token_ = c;
121 switch (c) {
122 case '\0': cursor_--; token_ = kTokenEof; return;
123 case ' ': case '\r': case '\t': break;
124 case '\n': line_++; seen_newline = true; break;
125 case '{': case '}': case '(': case ')': case '[': case ']': return;
126 case ',': case ':': case ';': case '=': return;
127 case '.':
128 if(!isdigit(*cursor_)) return;
129 Error("floating point constant can\'t start with \".\"");
130 break;
131 case '\"':
132 attribute_ = "";
133 while (*cursor_ != '\"') {
134 if (*cursor_ < ' ' && *cursor_ >= 0)
135 Error("illegal character in string constant");
136 if (*cursor_ == '\\') {
137 cursor_++;
138 switch (*cursor_) {
139 case 'n': attribute_ += '\n'; cursor_++; break;
140 case 't': attribute_ += '\t'; cursor_++; break;
141 case 'r': attribute_ += '\r'; cursor_++; break;
142 case '\"': attribute_ += '\"'; cursor_++; break;
143 case '\\': attribute_ += '\\'; cursor_++; break;
144 default: Error("unknown escape code in string constant"); break;
145 }
146 } else { // printable chars + UTF-8 bytes
147 attribute_ += *cursor_++;
148 }
149 }
150 cursor_++;
151 token_ = kTokenStringConstant;
152 return;
153 case '/':
154 if (*cursor_ == '/') {
155 const char *start = ++cursor_;
156 while (*cursor_ && *cursor_ != '\n') cursor_++;
157 if (*start == '/') { // documentation comment
158 if (!seen_newline)
159 Error("a documentation comment should be on a line on its own");
160 // todo: do we want to support multiline comments instead?
161 doc_comment_ += std::string(start + 1, cursor_);
162 }
163 break;
164 }
165 // fall thru
166 default:
167 if (isalpha(static_cast<unsigned char>(c))) {
168 // Collect all chars of an identifier:
169 const char *start = cursor_ - 1;
170 while (isalnum(static_cast<unsigned char>(*cursor_)) ||
171 *cursor_ == '_')
172 cursor_++;
173 attribute_.clear();
174 attribute_.append(start, cursor_);
175 // First, see if it is a type keyword from the table of types:
rw74d5f372014-07-11 16:12:35 -0700176 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800177 if (attribute_ == IDLTYPE) { \
178 token_ = kToken ## ENUM; \
179 return; \
180 }
181 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
182 #undef FLATBUFFERS_TD
183 // If it's a boolean constant keyword, turn those into integers,
184 // which simplifies our logic downstream.
185 if (attribute_ == "true" || attribute_ == "false") {
186 attribute_ = NumToString(attribute_ == "true");
187 token_ = kTokenIntegerConstant;
188 return;
189 }
190 // Check for declaration keywords:
191 if (attribute_ == "table") { token_ = kTokenTable; return; }
192 if (attribute_ == "struct") { token_ = kTokenStruct; return; }
193 if (attribute_ == "enum") { token_ = kTokenEnum; return; }
194 if (attribute_ == "union") { token_ = kTokenUnion; return; }
195 if (attribute_ == "namespace") { token_ = kTokenNameSpace; return; }
196 if (attribute_ == "root_type") { token_ = kTokenRootType; return; }
197 // If not, it is a user-defined identifier:
198 token_ = kTokenIdentifier;
199 return;
200 } else if (isdigit(static_cast<unsigned char>(c)) || c == '-') {
201 const char *start = cursor_ - 1;
202 while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
203 if (*cursor_ == '.') {
204 cursor_++;
205 while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
Wouter van Oortmerssen93df5692014-07-10 13:40:55 -0700206 // See if this float has a scientific notation suffix. Both JSON
207 // and C++ (through strtod() we use) have the same format:
208 if (*cursor_ == 'e' || *cursor_ == 'E') {
209 cursor_++;
210 if (*cursor_ == '+' || *cursor_ == '-') cursor_++;
211 while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
212 }
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800213 token_ = kTokenFloatConstant;
214 } else {
215 token_ = kTokenIntegerConstant;
216 }
217 attribute_.clear();
218 attribute_.append(start, cursor_);
219 return;
220 }
221 std::string ch;
222 ch = c;
223 if (c < ' ' || c > '~') ch = "code: " + NumToString(c);
224 Error("illegal character: " + ch);
225 break;
226 }
227 }
228}
229
230// Check if a given token is next, if so, consume it as well.
231bool Parser::IsNext(int t) {
232 bool isnext = t == token_;
233 if (isnext) Next();
234 return isnext;
235}
236
237// Expect a given token to be next, consume it, or error if not present.
238void Parser::Expect(int t) {
239 if (t != token_) {
240 Error("expecting: " + TokenToString(t) + " instead got: " +
241 TokenToString(token_));
242 }
243 Next();
244}
245
246// Parse any IDL type.
247void Parser::ParseType(Type &type) {
248 if (token_ >= kTokenBOOL && token_ <= kTokenSTRING) {
249 type.base_type = static_cast<BaseType>(token_ - kTokenNONE);
250 } else {
251 if (token_ == kTokenIdentifier) {
252 auto enum_def = enums_.Lookup(attribute_);
253 if (enum_def) {
254 type = enum_def->underlying_type;
255 if (enum_def->is_union) type.base_type = BASE_TYPE_UNION;
256 } else {
257 type.base_type = BASE_TYPE_STRUCT;
258 type.struct_def = LookupCreateStruct(attribute_);
259 }
260 } else if (token_ == '[') {
261 Next();
262 Type subtype;
263 ParseType(subtype);
264 if (subtype.base_type == BASE_TYPE_VECTOR) {
265 // We could support this, but it will complicate things, and it's
266 // easier to work around with a struct around the inner vector.
267 Error("nested vector types not supported (wrap in table first).");
268 }
269 if (subtype.base_type == BASE_TYPE_UNION) {
270 // We could support this if we stored a struct of 2 elements per
271 // union element.
272 Error("vector of union types not supported (wrap in table first).");
273 }
Wouter van Oortmerssen3fb6a862014-07-14 17:49:04 -0700274 type = Type(BASE_TYPE_VECTOR, subtype.struct_def, subtype.enum_def);
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800275 type.element = subtype.base_type;
276 Expect(']');
277 return;
278 } else {
279 Error("illegal type syntax");
280 }
281 }
282 Next();
283}
284
285FieldDef &Parser::AddField(StructDef &struct_def,
286 const std::string &name,
287 const Type &type) {
288 auto &field = *new FieldDef();
289 field.value.offset =
290 FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size()));
291 field.name = name;
292 field.value.type = type;
293 if (struct_def.fixed) { // statically compute the field offset
294 auto size = InlineSize(type);
295 auto alignment = InlineAlignment(type);
296 // structs_ need to have a predictable format, so we need to align to
297 // the largest scalar
298 struct_def.minalign = std::max(struct_def.minalign, alignment);
299 struct_def.PadLastField(alignment);
Wouter van Oortmerssen12563072014-06-30 15:56:31 -0700300 field.value.offset = static_cast<voffset_t>(struct_def.bytesize);
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800301 struct_def.bytesize += size;
302 }
303 if (struct_def.fields.Add(name, &field))
304 Error("field already exists: " + name);
305 return field;
306}
307
308void Parser::ParseField(StructDef &struct_def) {
309 std::string name = attribute_;
310 std::string dc = doc_comment_;
311 Expect(kTokenIdentifier);
312 Expect(':');
313 Type type;
314 ParseType(type);
315
316 if (struct_def.fixed && !IsScalar(type.base_type) && !IsStruct(type))
317 Error("structs_ may contain only scalar or struct fields");
318
Wouter van Oortmerssen91401442014-07-07 17:34:23 -0700319 FieldDef *typefield = nullptr;
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800320 if (type.base_type == BASE_TYPE_UNION) {
321 // For union fields, add a second auto-generated field to hold the type,
322 // with _type appended as the name.
Wouter van Oortmerssen91401442014-07-07 17:34:23 -0700323 typefield = &AddField(struct_def, name + "_type",
324 type.enum_def->underlying_type);
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800325 }
326
327 auto &field = AddField(struct_def, name, type);
328
329 if (token_ == '=') {
330 Next();
331 ParseSingleValue(field.value);
332 }
333
334 field.doc_comment = dc;
335 ParseMetaData(field);
336 field.deprecated = field.attributes.Lookup("deprecated") != nullptr;
337 if (field.deprecated && struct_def.fixed)
338 Error("can't deprecate fields in a struct");
Wouter van Oortmerssen3e201a92014-07-15 17:50:22 -0700339 auto nested = field.attributes.Lookup("nested_flatbuffer");
340 if (nested) {
341 if (nested->type.base_type != BASE_TYPE_STRING)
342 Error("nested_flatbuffer attribute must be a string (the root type)");
343 if (field.value.type.base_type != BASE_TYPE_VECTOR ||
344 field.value.type.element != BASE_TYPE_UCHAR)
345 Error("nested_flatbuffer attribute may only apply to a vector of ubyte");
346 // This will cause an error if the root type of the nested flatbuffer
347 // wasn't defined elsewhere.
348 LookupCreateStruct(nested->constant);
349 }
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800350
Wouter van Oortmerssen91401442014-07-07 17:34:23 -0700351 if (typefield) {
352 // If this field is a union, and it has a manually assigned id,
353 // the automatically added type field should have an id as well (of N - 1).
354 auto attr = field.attributes.Lookup("id");
355 if (attr) {
356 auto id = atoi(attr->constant.c_str());
357 auto val = new Value();
358 val->type = attr->type;
359 val->constant = NumToString(id - 1);
360 typefield->attributes.Add("id", val);
361 }
362 }
363
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800364 Expect(';');
365}
366
367void Parser::ParseAnyValue(Value &val, FieldDef *field) {
368 switch (val.type.base_type) {
369 case BASE_TYPE_UNION: {
370 assert(field);
371 if (!field_stack_.size() ||
372 field_stack_.back().second->value.type.base_type != BASE_TYPE_UTYPE)
373 Error("missing type field before this union value: " + field->name);
374 auto enum_idx = atot<unsigned char>(
375 field_stack_.back().first.constant.c_str());
Wouter van Oortmerssen3fb6a862014-07-14 17:49:04 -0700376 auto enum_val = val.type.enum_def->ReverseLookup(enum_idx);
377 if (!enum_val) Error("illegal type id for: " + field->name);
378 val.constant = NumToString(ParseTable(*enum_val->struct_def));
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800379 break;
380 }
381 case BASE_TYPE_STRUCT:
382 val.constant = NumToString(ParseTable(*val.type.struct_def));
383 break;
384 case BASE_TYPE_STRING: {
385 auto s = attribute_;
386 Expect(kTokenStringConstant);
387 val.constant = NumToString(builder_.CreateString(s).o);
388 break;
389 }
390 case BASE_TYPE_VECTOR: {
391 Expect('[');
392 val.constant = NumToString(ParseVector(val.type.VectorType()));
393 break;
394 }
395 default:
396 ParseSingleValue(val);
397 break;
398 }
399}
400
401void Parser::SerializeStruct(const StructDef &struct_def, const Value &val) {
402 auto off = atot<uoffset_t>(val.constant.c_str());
403 assert(struct_stack_.size() - off == struct_def.bytesize);
404 builder_.Align(struct_def.minalign);
405 builder_.PushBytes(&struct_stack_[off], struct_def.bytesize);
406 struct_stack_.resize(struct_stack_.size() - struct_def.bytesize);
407 builder_.AddStructOffset(val.offset, builder_.GetSize());
408}
409
410uoffset_t Parser::ParseTable(const StructDef &struct_def) {
411 Expect('{');
412 size_t fieldn = 0;
413 for (;;) {
414 std::string name = attribute_;
415 if (!IsNext(kTokenStringConstant)) Expect(kTokenIdentifier);
416 auto field = struct_def.fields.Lookup(name);
417 if (!field) Error("unknown field: " + name);
418 if (struct_def.fixed && (fieldn >= struct_def.fields.vec.size()
419 || struct_def.fields.vec[fieldn] != field)) {
420 Error("struct field appearing out of order: " + name);
421 }
422 Expect(':');
423 Value val = field->value;
424 ParseAnyValue(val, field);
425 field_stack_.push_back(std::make_pair(val, field));
426 fieldn++;
427 if (IsNext('}')) break;
428 Expect(',');
429 }
430 if (struct_def.fixed && fieldn != struct_def.fields.vec.size())
431 Error("incomplete struct initialization: " + struct_def.name);
432 auto start = struct_def.fixed
433 ? builder_.StartStruct(struct_def.minalign)
434 : builder_.StartTable();
435
436 for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
437 size;
438 size /= 2) {
439 // Go through elements in reverse, since we're building the data backwards.
440 for (auto it = field_stack_.rbegin();
441 it != field_stack_.rbegin() + fieldn; ++it) {
442 auto &value = it->first;
443 auto field = it->second;
444 if (!struct_def.sortbysize || size == SizeOf(value.type.base_type)) {
445 switch (value.type.base_type) {
rw74d5f372014-07-11 16:12:35 -0700446 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800447 case BASE_TYPE_ ## ENUM: \
448 builder_.Pad(field->padding); \
449 builder_.AddElement(value.offset, \
450 atot<CTYPE>( value.constant.c_str()), \
451 atot<CTYPE>(field->value.constant.c_str())); \
452 break;
453 FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD);
454 #undef FLATBUFFERS_TD
rw74d5f372014-07-11 16:12:35 -0700455 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800456 case BASE_TYPE_ ## ENUM: \
457 builder_.Pad(field->padding); \
458 if (IsStruct(field->value.type)) { \
459 SerializeStruct(*field->value.type.struct_def, value); \
460 } else { \
461 builder_.AddOffset(value.offset, \
462 atot<CTYPE>(value.constant.c_str())); \
463 } \
464 break;
465 FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD);
466 #undef FLATBUFFERS_TD
467 }
468 }
469 }
470 }
471 for (size_t i = 0; i < fieldn; i++) field_stack_.pop_back();
472
473 if (struct_def.fixed) {
474 builder_.ClearOffsets();
475 builder_.EndStruct();
476 // Temporarily store this struct in a side buffer, since this data has to
477 // be stored in-line later in the parent object.
478 auto off = struct_stack_.size();
479 struct_stack_.insert(struct_stack_.end(),
480 builder_.GetBufferPointer(),
481 builder_.GetBufferPointer() + struct_def.bytesize);
482 builder_.PopBytes(struct_def.bytesize);
483 return static_cast<uoffset_t>(off);
484 } else {
485 return builder_.EndTable(
486 start,
487 static_cast<voffset_t>(struct_def.fields.vec.size()));
488 }
489}
490
491uoffset_t Parser::ParseVector(const Type &type) {
492 int count = 0;
493 if (token_ != ']') for (;;) {
494 Value val;
495 val.type = type;
496 ParseAnyValue(val, NULL);
497 field_stack_.push_back(std::make_pair(val, nullptr));
498 count++;
499 if (token_ == ']') break;
500 Expect(',');
501 }
502 Next();
503
504 builder_.StartVector(count * InlineSize(type), InlineAlignment((type)));
505 for (int i = 0; i < count; i++) {
506 // start at the back, since we're building the data backwards.
507 auto &val = field_stack_.back().first;
508 switch (val.type.base_type) {
rw74d5f372014-07-11 16:12:35 -0700509 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800510 case BASE_TYPE_ ## ENUM: \
511 if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \
512 else builder_.PushElement(atot<CTYPE>(val.constant.c_str())); \
513 break;
514 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
515 #undef FLATBUFFERS_TD
516 }
517 field_stack_.pop_back();
518 }
519
520 builder_.ClearOffsets();
521 return builder_.EndVector(count);
522}
523
524void Parser::ParseMetaData(Definition &def) {
525 if (IsNext('(')) {
526 for (;;) {
527 auto name = attribute_;
528 Expect(kTokenIdentifier);
529 auto e = new Value();
530 def.attributes.Add(name, e);
531 if (IsNext(':')) {
532 ParseSingleValue(*e);
533 }
534 if (IsNext(')')) break;
535 Expect(',');
536 }
537 }
538}
539
540bool Parser::TryTypedValue(int dtoken,
541 bool check,
542 Value &e,
543 BaseType req) {
544 bool match = dtoken == token_;
545 if (match) {
546 e.constant = attribute_;
547 if (!check) {
548 if (e.type.base_type == BASE_TYPE_NONE) {
549 e.type.base_type = req;
550 } else {
551 Error(std::string("type mismatch: expecting: ") +
552 kTypeNames[e.type.base_type] +
553 ", found: " +
554 kTypeNames[req]);
555 }
556 }
557 Next();
558 }
559 return match;
560}
561
Wouter van Oortmerssen9c3de1e2014-07-25 15:04:35 -0700562int64_t Parser::ParseIntegerFromString(Type &type) {
563 int64_t result = 0;
564 // Parse one or more enum identifiers, separated by spaces.
565 const char *next = attribute_.c_str();
566 do {
567 const char *divider = strchr(next, ' ');
568 std::string word;
569 if (divider) {
570 word = std::string(next, divider);
571 next = divider + strspn(divider, " ");
572 } else {
573 word = next;
574 next += word.length();
575 }
576 if (type.enum_def) { // The field has an enum type
577 auto enum_val = type.enum_def->vals.Lookup(word);
578 if (!enum_val)
579 Error("unknown enum value: " + word +
580 ", for enum: " + type.enum_def->name);
581 result |= enum_val->value;
582 } else { // No enum type, probably integral field.
583 if (!IsInteger(type.base_type))
584 Error("not a valid value for this field: " + word);
585 // TODO: could check if its a valid number constant here.
586 const char *dot = strchr(word.c_str(), '.');
587 if (!dot) Error("enum values need to be qualified by an enum type");
588 std::string enum_def_str(word.c_str(), dot);
589 std::string enum_val_str(dot + 1, word.c_str() + word.length());
590 auto enum_def = enums_.Lookup(enum_def_str);
591 if (!enum_def) Error("unknown enum: " + enum_def_str);
592 auto enum_val = enum_def->vals.Lookup(enum_val_str);
593 if (!enum_val) Error("unknown enum value: " + enum_val_str);
594 result |= enum_val->value;
595 }
596 } while(*next);
597 return result;
598}
599
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800600void Parser::ParseSingleValue(Value &e) {
Wouter van Oortmerssen9c3de1e2014-07-25 15:04:35 -0700601 // First check if this could be a string/identifier enum value:
602 if (e.type.base_type != BASE_TYPE_STRING &&
603 e.type.base_type != BASE_TYPE_NONE &&
604 (token_ == kTokenIdentifier || token_ == kTokenStringConstant)) {
605 e.constant = NumToString(ParseIntegerFromString(e.type));
606 Next();
Wouter van Oortmerssen3fb6a862014-07-14 17:49:04 -0700607 } else if (TryTypedValue(kTokenIntegerConstant,
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800608 IsScalar(e.type.base_type),
609 e,
610 BASE_TYPE_INT) ||
611 TryTypedValue(kTokenFloatConstant,
612 IsFloat(e.type.base_type),
613 e,
614 BASE_TYPE_FLOAT) ||
615 TryTypedValue(kTokenStringConstant,
616 e.type.base_type == BASE_TYPE_STRING,
617 e,
618 BASE_TYPE_STRING)) {
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800619 } else {
620 Error("cannot parse value starting with: " + TokenToString(token_));
621 }
622}
623
624StructDef *Parser::LookupCreateStruct(const std::string &name) {
625 auto struct_def = structs_.Lookup(name);
626 if (!struct_def) {
627 // Rather than failing, we create a "pre declared" StructDef, due to
628 // circular references, and check for errors at the end of parsing.
629 struct_def = new StructDef();
630 structs_.Add(name, struct_def);
631 struct_def->name = name;
632 struct_def->predecl = true;
633 }
634 return struct_def;
635}
636
637void Parser::ParseEnum(bool is_union) {
638 std::string dc = doc_comment_;
639 Next();
640 std::string name = attribute_;
641 Expect(kTokenIdentifier);
642 auto &enum_def = *new EnumDef();
643 enum_def.name = name;
644 enum_def.doc_comment = dc;
645 enum_def.is_union = is_union;
646 if (enums_.Add(name, &enum_def)) Error("enum already exists: " + name);
647 if (is_union) {
648 enum_def.underlying_type.base_type = BASE_TYPE_UTYPE;
649 enum_def.underlying_type.enum_def = &enum_def;
Wouter van Oortmerssena5f50012014-07-02 12:01:21 -0700650 } else {
651 // Give specialized error message, since this type spec used to
652 // be optional in the first FlatBuffers release.
653 if (!IsNext(':')) Error("must specify the underlying integer type for this"
654 " enum (e.g. \': short\', which was the default).");
655 // Specify the integer type underlying this enum.
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800656 ParseType(enum_def.underlying_type);
657 if (!IsInteger(enum_def.underlying_type.base_type))
658 Error("underlying enum type must be integral");
Wouter van Oortmerssen3fb6a862014-07-14 17:49:04 -0700659 // Make this type refer back to the enum it was derived from.
660 enum_def.underlying_type.enum_def = &enum_def;
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800661 }
662 ParseMetaData(enum_def);
663 Expect('{');
664 if (is_union) enum_def.vals.Add("NONE", new EnumVal("NONE", 0));
665 do {
666 std::string name = attribute_;
667 std::string dc = doc_comment_;
668 Expect(kTokenIdentifier);
669 auto prevsize = enum_def.vals.vec.size();
Wouter van Oortmerssen127d3502014-07-17 15:12:37 -0700670 auto value = enum_def.vals.vec.size()
671 ? enum_def.vals.vec.back()->value + 1
672 : 0;
673 auto &ev = *new EnumVal(name, value);
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800674 if (enum_def.vals.Add(name, &ev))
675 Error("enum value already exists: " + name);
676 ev.doc_comment = dc;
677 if (is_union) {
678 ev.struct_def = LookupCreateStruct(name);
679 }
680 if (IsNext('=')) {
681 ev.value = atoi(attribute_.c_str());
682 Expect(kTokenIntegerConstant);
683 if (prevsize && enum_def.vals.vec[prevsize - 1]->value >= ev.value)
684 Error("enum values must be specified in ascending order");
685 }
686 } while (IsNext(','));
687 Expect('}');
Wouter van Oortmerssen127d3502014-07-17 15:12:37 -0700688 if (enum_def.attributes.Lookup("bit_flags")) {
689 for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
690 ++it) {
691 if (static_cast<size_t>((*it)->value) >=
692 SizeOf(enum_def.underlying_type.base_type) * 8)
693 Error("bit flag out of range of underlying integral type");
Wouter van Oortmerssen9c3de1e2014-07-25 15:04:35 -0700694 (*it)->value = 1LL << (*it)->value;
Wouter van Oortmerssen127d3502014-07-17 15:12:37 -0700695 }
696 }
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800697}
698
699void Parser::ParseDecl() {
700 std::string dc = doc_comment_;
701 bool fixed = IsNext(kTokenStruct);
702 if (!fixed) Expect(kTokenTable);
703 std::string name = attribute_;
704 Expect(kTokenIdentifier);
705 auto &struct_def = *LookupCreateStruct(name);
706 if (!struct_def.predecl) Error("datatype already exists: " + name);
707 struct_def.predecl = false;
708 struct_def.name = name;
709 struct_def.doc_comment = dc;
710 struct_def.fixed = fixed;
711 // Move this struct to the back of the vector just in case it was predeclared,
712 // to preserve declartion order.
713 remove(structs_.vec.begin(), structs_.vec.end(), &struct_def);
714 structs_.vec.back() = &struct_def;
715 ParseMetaData(struct_def);
716 struct_def.sortbysize =
717 struct_def.attributes.Lookup("original_order") == nullptr && !fixed;
718 Expect('{');
719 while (token_ != '}') ParseField(struct_def);
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800720 auto force_align = struct_def.attributes.Lookup("force_align");
721 if (fixed && force_align) {
722 auto align = static_cast<size_t>(atoi(force_align->constant.c_str()));
723 if (force_align->type.base_type != BASE_TYPE_INT ||
724 align < struct_def.minalign ||
725 align > 256 ||
726 align & (align - 1))
727 Error("force_align must be a power of two integer ranging from the"
728 "struct\'s natural alignment to 256");
729 struct_def.minalign = align;
730 }
Wouter van Oortmerssen65cfa182014-06-23 11:34:19 -0700731 struct_def.PadLastField(struct_def.minalign);
Wouter van Oortmerssen91401442014-07-07 17:34:23 -0700732 // Check if this is a table that has manual id assignments
733 auto &fields = struct_def.fields.vec;
734 if (!struct_def.fixed && fields.size()) {
Wouter van Oortmerssen7fcbe722014-07-08 16:35:14 -0700735 size_t num_id_fields = 0;
Wouter van Oortmerssen91401442014-07-07 17:34:23 -0700736 for (auto it = fields.begin(); it != fields.end(); ++it) {
737 if ((*it)->attributes.Lookup("id")) num_id_fields++;
738 }
739 // If any fields have ids..
740 if (num_id_fields) {
741 // Then all fields must have them.
742 if (num_id_fields != fields.size())
743 Error("either all fields or no fields must have an 'id' attribute");
744 // Simply sort by id, then the fields are the same as if no ids had
745 // been specified.
746 std::sort(fields.begin(), fields.end(),
747 [](const FieldDef *a, const FieldDef *b) -> bool {
748 auto a_id = atoi(a->attributes.Lookup("id")->constant.c_str());
749 auto b_id = atoi(b->attributes.Lookup("id")->constant.c_str());
750 return a_id < b_id;
751 });
752 // Verify we have a contiguous set, and reassign vtable offsets.
753 for (int i = 0; i < static_cast<int>(fields.size()); i++) {
754 if (i != atoi(fields[i]->attributes.Lookup("id")->constant.c_str()))
755 Error("field id\'s must be consecutive from 0, id " +
756 NumToString(i) + " missing or set twice");
757 fields[i]->value.offset = FieldIndexToOffset(static_cast<voffset_t>(i));
758 }
759 }
760 }
Wouter van Oortmerssen65cfa182014-06-23 11:34:19 -0700761 Expect('}');
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800762}
763
764bool Parser::SetRootType(const char *name) {
765 root_struct_def = structs_.Lookup(name);
766 return root_struct_def != nullptr;
767}
768
769bool Parser::Parse(const char *source) {
770 source_ = cursor_ = source;
771 line_ = 1;
772 error_.clear();
773 builder_.Clear();
774 try {
775 Next();
776 while (token_ != kTokenEof) {
777 if (token_ == kTokenNameSpace) {
778 Next();
Wouter van Oortmerssen2208de02014-07-09 14:21:11 -0700779 name_space_.clear();
Wouter van Oortmerssen26a30732014-01-27 16:52:49 -0800780 for (;;) {
781 name_space_.push_back(attribute_);
782 Expect(kTokenIdentifier);
783 if (!IsNext('.')) break;
784 }
785 Expect(';');
786 } else if (token_ == '{') {
787 if (!root_struct_def) Error("no root type set to parse json with");
788 if (builder_.GetSize()) {
789 Error("cannot have more than one json object in a file");
790 }
791 builder_.Finish(Offset<Table>(ParseTable(*root_struct_def)));
792 } else if (token_ == kTokenEnum) {
793 ParseEnum(false);
794 } else if (token_ == kTokenUnion) {
795 ParseEnum(true);
796 } else if (token_ == kTokenRootType) {
797 Next();
798 auto root_type = attribute_;
799 Expect(kTokenIdentifier);
800 Expect(';');
801 if (!SetRootType(root_type.c_str()))
802 Error("unknown root type: " + root_type);
803 if (root_struct_def->fixed)
804 Error("root type must be a table");
805 } else {
806 ParseDecl();
807 }
808 }
809 for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
810 if ((*it)->predecl)
811 Error("type referenced but not defined: " + (*it)->name);
812 }
813 for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
814 auto &enum_def = **it;
815 if (enum_def.is_union) {
816 for (auto it = enum_def.vals.vec.begin();
817 it != enum_def.vals.vec.end();
818 ++it) {
819 auto &val = **it;
820 if (val.struct_def && val.struct_def->fixed)
821 Error("only tables can be union elements: " + val.name);
822 }
823 }
824 }
825 } catch (const std::string &msg) {
826 error_ = "line " + NumToString(line_) + ": " + msg;
827 return false;
828 }
829 assert(!struct_stack_.size());
830 return true;
831}
832
833} // namespace flatbuffers