Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 1 | /* |
| 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 | |
| 23 | namespace flatbuffers { |
| 24 | |
| 25 | const 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 | |
| 32 | const char kTypeSizes[] = { |
| 33 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) sizeof(CTYPE), |
| 34 | FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) |
| 35 | #undef FLATBUFFERS_TD |
| 36 | }; |
| 37 | |
| 38 | static void Error(const std::string &msg) { |
| 39 | throw msg; |
| 40 | } |
| 41 | |
| 42 | // Ensure that integer values we parse fit inside the declared integer type. |
| 43 | static 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. |
| 52 | template<typename T> inline T atot(const char *s) { |
| 53 | auto val = StringToInt(s); |
| 54 | CheckBitsFit(val, sizeof(T) * 8); |
| 55 | return (T)val; |
| 56 | } |
| 57 | template<> inline bool atot<bool>(const char *s) { |
| 58 | return 0 != atoi(s); |
| 59 | } |
| 60 | template<> inline float atot<float>(const char *s) { |
| 61 | return static_cast<float>(strtod(s, nullptr)); |
| 62 | } |
| 63 | template<> inline double atot<double>(const char *s) { |
| 64 | return strtod(s, nullptr); |
| 65 | } |
| 66 | |
| 67 | template<> 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") |
| 85 | enum { |
Wouter van Oortmerssen | 75349ae | 2014-07-09 11:44:26 -0700 | [diff] [blame] | 86 | #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME = VALUE, |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 87 | 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 | |
| 94 | static 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 | |
| 112 | void 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 Oortmerssen | 93df569 | 2014-07-10 13:40:55 -0700 | [diff] [blame] | 203 | // 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 Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 210 | 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. |
| 228 | bool 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. |
| 235 | void 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. |
| 244 | void 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 | } |
Wouter van Oortmerssen | 3fb6a86 | 2014-07-14 17:49:04 -0700 | [diff] [blame^] | 271 | type = Type(BASE_TYPE_VECTOR, subtype.struct_def, subtype.enum_def); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 272 | type.element = subtype.base_type; |
| 273 | Expect(']'); |
| 274 | return; |
| 275 | } else { |
| 276 | Error("illegal type syntax"); |
| 277 | } |
| 278 | } |
| 279 | Next(); |
| 280 | } |
| 281 | |
| 282 | FieldDef &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 Oortmerssen | 1256307 | 2014-06-30 15:56:31 -0700 | [diff] [blame] | 297 | field.value.offset = static_cast<voffset_t>(struct_def.bytesize); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 298 | struct_def.bytesize += size; |
| 299 | } |
| 300 | if (struct_def.fields.Add(name, &field)) |
| 301 | Error("field already exists: " + name); |
| 302 | return field; |
| 303 | } |
| 304 | |
| 305 | void 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 Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 316 | FieldDef *typefield = nullptr; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 317 | 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 Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 320 | typefield = &AddField(struct_def, name + "_type", |
| 321 | type.enum_def->underlying_type); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 322 | } |
| 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 Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 337 | 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 Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 350 | Expect(';'); |
| 351 | } |
| 352 | |
| 353 | void 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()); |
Wouter van Oortmerssen | 3fb6a86 | 2014-07-14 17:49:04 -0700 | [diff] [blame^] | 362 | auto enum_val = val.type.enum_def->ReverseLookup(enum_idx); |
| 363 | if (!enum_val) Error("illegal type id for: " + field->name); |
| 364 | val.constant = NumToString(ParseTable(*enum_val->struct_def)); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 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 | |
| 387 | void 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 | |
| 396 | uoffset_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 | |
| 477 | uoffset_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 | |
| 510 | void 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 | |
| 526 | bool 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 | |
| 548 | void Parser::ParseSingleValue(Value &e) { |
Wouter van Oortmerssen | 3fb6a86 | 2014-07-14 17:49:04 -0700 | [diff] [blame^] | 549 | // First check if derived from an enum, to allow strings/identifier values: |
| 550 | if (e.type.enum_def && (token_ == kTokenIdentifier || |
| 551 | token_ == kTokenStringConstant)) { |
| 552 | auto enum_val = e.type.enum_def->vals.Lookup(attribute_); |
| 553 | if (!enum_val) |
| 554 | Error("unknown enum value: " + attribute_ + |
| 555 | ", for enum: " + e.type.enum_def->name); |
| 556 | e.constant = NumToString(enum_val->value); |
| 557 | Next(); |
| 558 | } else if (TryTypedValue(kTokenIntegerConstant, |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 559 | IsScalar(e.type.base_type), |
| 560 | e, |
| 561 | BASE_TYPE_INT) || |
| 562 | TryTypedValue(kTokenFloatConstant, |
| 563 | IsFloat(e.type.base_type), |
| 564 | e, |
| 565 | BASE_TYPE_FLOAT) || |
| 566 | TryTypedValue(kTokenStringConstant, |
| 567 | e.type.base_type == BASE_TYPE_STRING, |
| 568 | e, |
| 569 | BASE_TYPE_STRING)) { |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 570 | } else { |
| 571 | Error("cannot parse value starting with: " + TokenToString(token_)); |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | StructDef *Parser::LookupCreateStruct(const std::string &name) { |
| 576 | auto struct_def = structs_.Lookup(name); |
| 577 | if (!struct_def) { |
| 578 | // Rather than failing, we create a "pre declared" StructDef, due to |
| 579 | // circular references, and check for errors at the end of parsing. |
| 580 | struct_def = new StructDef(); |
| 581 | structs_.Add(name, struct_def); |
| 582 | struct_def->name = name; |
| 583 | struct_def->predecl = true; |
| 584 | } |
| 585 | return struct_def; |
| 586 | } |
| 587 | |
| 588 | void Parser::ParseEnum(bool is_union) { |
| 589 | std::string dc = doc_comment_; |
| 590 | Next(); |
| 591 | std::string name = attribute_; |
| 592 | Expect(kTokenIdentifier); |
| 593 | auto &enum_def = *new EnumDef(); |
| 594 | enum_def.name = name; |
| 595 | enum_def.doc_comment = dc; |
| 596 | enum_def.is_union = is_union; |
| 597 | if (enums_.Add(name, &enum_def)) Error("enum already exists: " + name); |
| 598 | if (is_union) { |
| 599 | enum_def.underlying_type.base_type = BASE_TYPE_UTYPE; |
| 600 | enum_def.underlying_type.enum_def = &enum_def; |
Wouter van Oortmerssen | a5f5001 | 2014-07-02 12:01:21 -0700 | [diff] [blame] | 601 | } else { |
| 602 | // Give specialized error message, since this type spec used to |
| 603 | // be optional in the first FlatBuffers release. |
| 604 | if (!IsNext(':')) Error("must specify the underlying integer type for this" |
| 605 | " enum (e.g. \': short\', which was the default)."); |
| 606 | // Specify the integer type underlying this enum. |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 607 | ParseType(enum_def.underlying_type); |
| 608 | if (!IsInteger(enum_def.underlying_type.base_type)) |
| 609 | Error("underlying enum type must be integral"); |
Wouter van Oortmerssen | 3fb6a86 | 2014-07-14 17:49:04 -0700 | [diff] [blame^] | 610 | // Make this type refer back to the enum it was derived from. |
| 611 | enum_def.underlying_type.enum_def = &enum_def; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 612 | } |
| 613 | ParseMetaData(enum_def); |
| 614 | Expect('{'); |
| 615 | if (is_union) enum_def.vals.Add("NONE", new EnumVal("NONE", 0)); |
| 616 | do { |
| 617 | std::string name = attribute_; |
| 618 | std::string dc = doc_comment_; |
| 619 | Expect(kTokenIdentifier); |
| 620 | auto prevsize = enum_def.vals.vec.size(); |
| 621 | auto &ev = *new EnumVal(name, static_cast<int>( |
| 622 | enum_def.vals.vec.size() |
| 623 | ? enum_def.vals.vec.back()->value + 1 |
| 624 | : 0)); |
| 625 | if (enum_def.vals.Add(name, &ev)) |
| 626 | Error("enum value already exists: " + name); |
| 627 | ev.doc_comment = dc; |
| 628 | if (is_union) { |
| 629 | ev.struct_def = LookupCreateStruct(name); |
| 630 | } |
| 631 | if (IsNext('=')) { |
| 632 | ev.value = atoi(attribute_.c_str()); |
| 633 | Expect(kTokenIntegerConstant); |
| 634 | if (prevsize && enum_def.vals.vec[prevsize - 1]->value >= ev.value) |
| 635 | Error("enum values must be specified in ascending order"); |
| 636 | } |
| 637 | } while (IsNext(',')); |
| 638 | Expect('}'); |
| 639 | } |
| 640 | |
| 641 | void Parser::ParseDecl() { |
| 642 | std::string dc = doc_comment_; |
| 643 | bool fixed = IsNext(kTokenStruct); |
| 644 | if (!fixed) Expect(kTokenTable); |
| 645 | std::string name = attribute_; |
| 646 | Expect(kTokenIdentifier); |
| 647 | auto &struct_def = *LookupCreateStruct(name); |
| 648 | if (!struct_def.predecl) Error("datatype already exists: " + name); |
| 649 | struct_def.predecl = false; |
| 650 | struct_def.name = name; |
| 651 | struct_def.doc_comment = dc; |
| 652 | struct_def.fixed = fixed; |
| 653 | // Move this struct to the back of the vector just in case it was predeclared, |
| 654 | // to preserve declartion order. |
| 655 | remove(structs_.vec.begin(), structs_.vec.end(), &struct_def); |
| 656 | structs_.vec.back() = &struct_def; |
| 657 | ParseMetaData(struct_def); |
| 658 | struct_def.sortbysize = |
| 659 | struct_def.attributes.Lookup("original_order") == nullptr && !fixed; |
| 660 | Expect('{'); |
| 661 | while (token_ != '}') ParseField(struct_def); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 662 | auto force_align = struct_def.attributes.Lookup("force_align"); |
| 663 | if (fixed && force_align) { |
| 664 | auto align = static_cast<size_t>(atoi(force_align->constant.c_str())); |
| 665 | if (force_align->type.base_type != BASE_TYPE_INT || |
| 666 | align < struct_def.minalign || |
| 667 | align > 256 || |
| 668 | align & (align - 1)) |
| 669 | Error("force_align must be a power of two integer ranging from the" |
| 670 | "struct\'s natural alignment to 256"); |
| 671 | struct_def.minalign = align; |
| 672 | } |
Wouter van Oortmerssen | 65cfa18 | 2014-06-23 11:34:19 -0700 | [diff] [blame] | 673 | struct_def.PadLastField(struct_def.minalign); |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 674 | // Check if this is a table that has manual id assignments |
| 675 | auto &fields = struct_def.fields.vec; |
| 676 | if (!struct_def.fixed && fields.size()) { |
Wouter van Oortmerssen | 7fcbe72 | 2014-07-08 16:35:14 -0700 | [diff] [blame] | 677 | size_t num_id_fields = 0; |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 678 | for (auto it = fields.begin(); it != fields.end(); ++it) { |
| 679 | if ((*it)->attributes.Lookup("id")) num_id_fields++; |
| 680 | } |
| 681 | // If any fields have ids.. |
| 682 | if (num_id_fields) { |
| 683 | // Then all fields must have them. |
| 684 | if (num_id_fields != fields.size()) |
| 685 | Error("either all fields or no fields must have an 'id' attribute"); |
| 686 | // Simply sort by id, then the fields are the same as if no ids had |
| 687 | // been specified. |
| 688 | std::sort(fields.begin(), fields.end(), |
| 689 | [](const FieldDef *a, const FieldDef *b) -> bool { |
| 690 | auto a_id = atoi(a->attributes.Lookup("id")->constant.c_str()); |
| 691 | auto b_id = atoi(b->attributes.Lookup("id")->constant.c_str()); |
| 692 | return a_id < b_id; |
| 693 | }); |
| 694 | // Verify we have a contiguous set, and reassign vtable offsets. |
| 695 | for (int i = 0; i < static_cast<int>(fields.size()); i++) { |
| 696 | if (i != atoi(fields[i]->attributes.Lookup("id")->constant.c_str())) |
| 697 | Error("field id\'s must be consecutive from 0, id " + |
| 698 | NumToString(i) + " missing or set twice"); |
| 699 | fields[i]->value.offset = FieldIndexToOffset(static_cast<voffset_t>(i)); |
| 700 | } |
| 701 | } |
| 702 | } |
Wouter van Oortmerssen | 65cfa18 | 2014-06-23 11:34:19 -0700 | [diff] [blame] | 703 | Expect('}'); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 704 | } |
| 705 | |
| 706 | bool Parser::SetRootType(const char *name) { |
| 707 | root_struct_def = structs_.Lookup(name); |
| 708 | return root_struct_def != nullptr; |
| 709 | } |
| 710 | |
| 711 | bool Parser::Parse(const char *source) { |
| 712 | source_ = cursor_ = source; |
| 713 | line_ = 1; |
| 714 | error_.clear(); |
| 715 | builder_.Clear(); |
| 716 | try { |
| 717 | Next(); |
| 718 | while (token_ != kTokenEof) { |
| 719 | if (token_ == kTokenNameSpace) { |
| 720 | Next(); |
Wouter van Oortmerssen | 2208de0 | 2014-07-09 14:21:11 -0700 | [diff] [blame] | 721 | name_space_.clear(); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 722 | for (;;) { |
| 723 | name_space_.push_back(attribute_); |
| 724 | Expect(kTokenIdentifier); |
| 725 | if (!IsNext('.')) break; |
| 726 | } |
| 727 | Expect(';'); |
| 728 | } else if (token_ == '{') { |
| 729 | if (!root_struct_def) Error("no root type set to parse json with"); |
| 730 | if (builder_.GetSize()) { |
| 731 | Error("cannot have more than one json object in a file"); |
| 732 | } |
| 733 | builder_.Finish(Offset<Table>(ParseTable(*root_struct_def))); |
| 734 | } else if (token_ == kTokenEnum) { |
| 735 | ParseEnum(false); |
| 736 | } else if (token_ == kTokenUnion) { |
| 737 | ParseEnum(true); |
| 738 | } else if (token_ == kTokenRootType) { |
| 739 | Next(); |
| 740 | auto root_type = attribute_; |
| 741 | Expect(kTokenIdentifier); |
| 742 | Expect(';'); |
| 743 | if (!SetRootType(root_type.c_str())) |
| 744 | Error("unknown root type: " + root_type); |
| 745 | if (root_struct_def->fixed) |
| 746 | Error("root type must be a table"); |
| 747 | } else { |
| 748 | ParseDecl(); |
| 749 | } |
| 750 | } |
| 751 | for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) { |
| 752 | if ((*it)->predecl) |
| 753 | Error("type referenced but not defined: " + (*it)->name); |
| 754 | } |
| 755 | for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) { |
| 756 | auto &enum_def = **it; |
| 757 | if (enum_def.is_union) { |
| 758 | for (auto it = enum_def.vals.vec.begin(); |
| 759 | it != enum_def.vals.vec.end(); |
| 760 | ++it) { |
| 761 | auto &val = **it; |
| 762 | if (val.struct_def && val.struct_def->fixed) |
| 763 | Error("only tables can be union elements: " + val.name); |
| 764 | } |
| 765 | } |
| 766 | } |
| 767 | } catch (const std::string &msg) { |
| 768 | error_ = "line " + NumToString(line_) + ": " + msg; |
| 769 | return false; |
| 770 | } |
| 771 | assert(!struct_stack_.size()); |
| 772 | return true; |
| 773 | } |
| 774 | |
| 775 | } // namespace flatbuffers |