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 { |
| 86 | #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME, |
| 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_++; |
| 203 | token_ = kTokenFloatConstant; |
| 204 | } else { |
| 205 | token_ = kTokenIntegerConstant; |
| 206 | } |
| 207 | attribute_.clear(); |
| 208 | attribute_.append(start, cursor_); |
| 209 | return; |
| 210 | } |
| 211 | std::string ch; |
| 212 | ch = c; |
| 213 | if (c < ' ' || c > '~') ch = "code: " + NumToString(c); |
| 214 | Error("illegal character: " + ch); |
| 215 | break; |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | // Check if a given token is next, if so, consume it as well. |
| 221 | bool Parser::IsNext(int t) { |
| 222 | bool isnext = t == token_; |
| 223 | if (isnext) Next(); |
| 224 | return isnext; |
| 225 | } |
| 226 | |
| 227 | // Expect a given token to be next, consume it, or error if not present. |
| 228 | void Parser::Expect(int t) { |
| 229 | if (t != token_) { |
| 230 | Error("expecting: " + TokenToString(t) + " instead got: " + |
| 231 | TokenToString(token_)); |
| 232 | } |
| 233 | Next(); |
| 234 | } |
| 235 | |
| 236 | // Parse any IDL type. |
| 237 | void Parser::ParseType(Type &type) { |
| 238 | if (token_ >= kTokenBOOL && token_ <= kTokenSTRING) { |
| 239 | type.base_type = static_cast<BaseType>(token_ - kTokenNONE); |
| 240 | } else { |
| 241 | if (token_ == kTokenIdentifier) { |
| 242 | auto enum_def = enums_.Lookup(attribute_); |
| 243 | if (enum_def) { |
| 244 | type = enum_def->underlying_type; |
| 245 | if (enum_def->is_union) type.base_type = BASE_TYPE_UNION; |
| 246 | } else { |
| 247 | type.base_type = BASE_TYPE_STRUCT; |
| 248 | type.struct_def = LookupCreateStruct(attribute_); |
| 249 | } |
| 250 | } else if (token_ == '[') { |
| 251 | Next(); |
| 252 | Type subtype; |
| 253 | ParseType(subtype); |
| 254 | if (subtype.base_type == BASE_TYPE_VECTOR) { |
| 255 | // We could support this, but it will complicate things, and it's |
| 256 | // easier to work around with a struct around the inner vector. |
| 257 | Error("nested vector types not supported (wrap in table first)."); |
| 258 | } |
| 259 | if (subtype.base_type == BASE_TYPE_UNION) { |
| 260 | // We could support this if we stored a struct of 2 elements per |
| 261 | // union element. |
| 262 | Error("vector of union types not supported (wrap in table first)."); |
| 263 | } |
| 264 | type = Type(BASE_TYPE_VECTOR, subtype.struct_def); |
| 265 | type.element = subtype.base_type; |
| 266 | Expect(']'); |
| 267 | return; |
| 268 | } else { |
| 269 | Error("illegal type syntax"); |
| 270 | } |
| 271 | } |
| 272 | Next(); |
| 273 | } |
| 274 | |
| 275 | FieldDef &Parser::AddField(StructDef &struct_def, |
| 276 | const std::string &name, |
| 277 | const Type &type) { |
| 278 | auto &field = *new FieldDef(); |
| 279 | field.value.offset = |
| 280 | FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size())); |
| 281 | field.name = name; |
| 282 | field.value.type = type; |
| 283 | if (struct_def.fixed) { // statically compute the field offset |
| 284 | auto size = InlineSize(type); |
| 285 | auto alignment = InlineAlignment(type); |
| 286 | // structs_ need to have a predictable format, so we need to align to |
| 287 | // the largest scalar |
| 288 | struct_def.minalign = std::max(struct_def.minalign, alignment); |
| 289 | struct_def.PadLastField(alignment); |
Wouter van Oortmerssen | 1256307 | 2014-06-30 15:56:31 -0700 | [diff] [blame] | 290 | field.value.offset = static_cast<voffset_t>(struct_def.bytesize); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 291 | struct_def.bytesize += size; |
| 292 | } |
| 293 | if (struct_def.fields.Add(name, &field)) |
| 294 | Error("field already exists: " + name); |
| 295 | return field; |
| 296 | } |
| 297 | |
| 298 | void Parser::ParseField(StructDef &struct_def) { |
| 299 | std::string name = attribute_; |
| 300 | std::string dc = doc_comment_; |
| 301 | Expect(kTokenIdentifier); |
| 302 | Expect(':'); |
| 303 | Type type; |
| 304 | ParseType(type); |
| 305 | |
| 306 | if (struct_def.fixed && !IsScalar(type.base_type) && !IsStruct(type)) |
| 307 | Error("structs_ may contain only scalar or struct fields"); |
| 308 | |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 309 | FieldDef *typefield = nullptr; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 310 | if (type.base_type == BASE_TYPE_UNION) { |
| 311 | // For union fields, add a second auto-generated field to hold the type, |
| 312 | // with _type appended as the name. |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 313 | typefield = &AddField(struct_def, name + "_type", |
| 314 | type.enum_def->underlying_type); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 315 | } |
| 316 | |
| 317 | auto &field = AddField(struct_def, name, type); |
| 318 | |
| 319 | if (token_ == '=') { |
| 320 | Next(); |
| 321 | ParseSingleValue(field.value); |
| 322 | } |
| 323 | |
| 324 | field.doc_comment = dc; |
| 325 | ParseMetaData(field); |
| 326 | field.deprecated = field.attributes.Lookup("deprecated") != nullptr; |
| 327 | if (field.deprecated && struct_def.fixed) |
| 328 | Error("can't deprecate fields in a struct"); |
| 329 | |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 330 | if (typefield) { |
| 331 | // If this field is a union, and it has a manually assigned id, |
| 332 | // the automatically added type field should have an id as well (of N - 1). |
| 333 | auto attr = field.attributes.Lookup("id"); |
| 334 | if (attr) { |
| 335 | auto id = atoi(attr->constant.c_str()); |
| 336 | auto val = new Value(); |
| 337 | val->type = attr->type; |
| 338 | val->constant = NumToString(id - 1); |
| 339 | typefield->attributes.Add("id", val); |
| 340 | } |
| 341 | } |
| 342 | |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 343 | Expect(';'); |
| 344 | } |
| 345 | |
| 346 | void Parser::ParseAnyValue(Value &val, FieldDef *field) { |
| 347 | switch (val.type.base_type) { |
| 348 | case BASE_TYPE_UNION: { |
| 349 | assert(field); |
| 350 | if (!field_stack_.size() || |
| 351 | field_stack_.back().second->value.type.base_type != BASE_TYPE_UTYPE) |
| 352 | Error("missing type field before this union value: " + field->name); |
| 353 | auto enum_idx = atot<unsigned char>( |
| 354 | field_stack_.back().first.constant.c_str()); |
| 355 | auto struct_def = val.type.enum_def->ReverseLookup(enum_idx); |
| 356 | if (!struct_def) Error("illegal type id for: " + field->name); |
| 357 | val.constant = NumToString(ParseTable(*struct_def)); |
| 358 | break; |
| 359 | } |
| 360 | case BASE_TYPE_STRUCT: |
| 361 | val.constant = NumToString(ParseTable(*val.type.struct_def)); |
| 362 | break; |
| 363 | case BASE_TYPE_STRING: { |
| 364 | auto s = attribute_; |
| 365 | Expect(kTokenStringConstant); |
| 366 | val.constant = NumToString(builder_.CreateString(s).o); |
| 367 | break; |
| 368 | } |
| 369 | case BASE_TYPE_VECTOR: { |
| 370 | Expect('['); |
| 371 | val.constant = NumToString(ParseVector(val.type.VectorType())); |
| 372 | break; |
| 373 | } |
| 374 | default: |
| 375 | ParseSingleValue(val); |
| 376 | break; |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | void Parser::SerializeStruct(const StructDef &struct_def, const Value &val) { |
| 381 | auto off = atot<uoffset_t>(val.constant.c_str()); |
| 382 | assert(struct_stack_.size() - off == struct_def.bytesize); |
| 383 | builder_.Align(struct_def.minalign); |
| 384 | builder_.PushBytes(&struct_stack_[off], struct_def.bytesize); |
| 385 | struct_stack_.resize(struct_stack_.size() - struct_def.bytesize); |
| 386 | builder_.AddStructOffset(val.offset, builder_.GetSize()); |
| 387 | } |
| 388 | |
| 389 | uoffset_t Parser::ParseTable(const StructDef &struct_def) { |
| 390 | Expect('{'); |
| 391 | size_t fieldn = 0; |
| 392 | for (;;) { |
| 393 | std::string name = attribute_; |
| 394 | if (!IsNext(kTokenStringConstant)) Expect(kTokenIdentifier); |
| 395 | auto field = struct_def.fields.Lookup(name); |
| 396 | if (!field) Error("unknown field: " + name); |
| 397 | if (struct_def.fixed && (fieldn >= struct_def.fields.vec.size() |
| 398 | || struct_def.fields.vec[fieldn] != field)) { |
| 399 | Error("struct field appearing out of order: " + name); |
| 400 | } |
| 401 | Expect(':'); |
| 402 | Value val = field->value; |
| 403 | ParseAnyValue(val, field); |
| 404 | field_stack_.push_back(std::make_pair(val, field)); |
| 405 | fieldn++; |
| 406 | if (IsNext('}')) break; |
| 407 | Expect(','); |
| 408 | } |
| 409 | if (struct_def.fixed && fieldn != struct_def.fields.vec.size()) |
| 410 | Error("incomplete struct initialization: " + struct_def.name); |
| 411 | auto start = struct_def.fixed |
| 412 | ? builder_.StartStruct(struct_def.minalign) |
| 413 | : builder_.StartTable(); |
| 414 | |
| 415 | for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1; |
| 416 | size; |
| 417 | size /= 2) { |
| 418 | // Go through elements in reverse, since we're building the data backwards. |
| 419 | for (auto it = field_stack_.rbegin(); |
| 420 | it != field_stack_.rbegin() + fieldn; ++it) { |
| 421 | auto &value = it->first; |
| 422 | auto field = it->second; |
| 423 | if (!struct_def.sortbysize || size == SizeOf(value.type.base_type)) { |
| 424 | switch (value.type.base_type) { |
| 425 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \ |
| 426 | case BASE_TYPE_ ## ENUM: \ |
| 427 | builder_.Pad(field->padding); \ |
| 428 | builder_.AddElement(value.offset, \ |
| 429 | atot<CTYPE>( value.constant.c_str()), \ |
| 430 | atot<CTYPE>(field->value.constant.c_str())); \ |
| 431 | break; |
| 432 | FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD); |
| 433 | #undef FLATBUFFERS_TD |
| 434 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \ |
| 435 | case BASE_TYPE_ ## ENUM: \ |
| 436 | builder_.Pad(field->padding); \ |
| 437 | if (IsStruct(field->value.type)) { \ |
| 438 | SerializeStruct(*field->value.type.struct_def, value); \ |
| 439 | } else { \ |
| 440 | builder_.AddOffset(value.offset, \ |
| 441 | atot<CTYPE>(value.constant.c_str())); \ |
| 442 | } \ |
| 443 | break; |
| 444 | FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD); |
| 445 | #undef FLATBUFFERS_TD |
| 446 | } |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | for (size_t i = 0; i < fieldn; i++) field_stack_.pop_back(); |
| 451 | |
| 452 | if (struct_def.fixed) { |
| 453 | builder_.ClearOffsets(); |
| 454 | builder_.EndStruct(); |
| 455 | // Temporarily store this struct in a side buffer, since this data has to |
| 456 | // be stored in-line later in the parent object. |
| 457 | auto off = struct_stack_.size(); |
| 458 | struct_stack_.insert(struct_stack_.end(), |
| 459 | builder_.GetBufferPointer(), |
| 460 | builder_.GetBufferPointer() + struct_def.bytesize); |
| 461 | builder_.PopBytes(struct_def.bytesize); |
| 462 | return static_cast<uoffset_t>(off); |
| 463 | } else { |
| 464 | return builder_.EndTable( |
| 465 | start, |
| 466 | static_cast<voffset_t>(struct_def.fields.vec.size())); |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | uoffset_t Parser::ParseVector(const Type &type) { |
| 471 | int count = 0; |
| 472 | if (token_ != ']') for (;;) { |
| 473 | Value val; |
| 474 | val.type = type; |
| 475 | ParseAnyValue(val, NULL); |
| 476 | field_stack_.push_back(std::make_pair(val, nullptr)); |
| 477 | count++; |
| 478 | if (token_ == ']') break; |
| 479 | Expect(','); |
| 480 | } |
| 481 | Next(); |
| 482 | |
| 483 | builder_.StartVector(count * InlineSize(type), InlineAlignment((type))); |
| 484 | for (int i = 0; i < count; i++) { |
| 485 | // start at the back, since we're building the data backwards. |
| 486 | auto &val = field_stack_.back().first; |
| 487 | switch (val.type.base_type) { |
| 488 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \ |
| 489 | case BASE_TYPE_ ## ENUM: \ |
| 490 | if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \ |
| 491 | else builder_.PushElement(atot<CTYPE>(val.constant.c_str())); \ |
| 492 | break; |
| 493 | FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) |
| 494 | #undef FLATBUFFERS_TD |
| 495 | } |
| 496 | field_stack_.pop_back(); |
| 497 | } |
| 498 | |
| 499 | builder_.ClearOffsets(); |
| 500 | return builder_.EndVector(count); |
| 501 | } |
| 502 | |
| 503 | void Parser::ParseMetaData(Definition &def) { |
| 504 | if (IsNext('(')) { |
| 505 | for (;;) { |
| 506 | auto name = attribute_; |
| 507 | Expect(kTokenIdentifier); |
| 508 | auto e = new Value(); |
| 509 | def.attributes.Add(name, e); |
| 510 | if (IsNext(':')) { |
| 511 | ParseSingleValue(*e); |
| 512 | } |
| 513 | if (IsNext(')')) break; |
| 514 | Expect(','); |
| 515 | } |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | bool Parser::TryTypedValue(int dtoken, |
| 520 | bool check, |
| 521 | Value &e, |
| 522 | BaseType req) { |
| 523 | bool match = dtoken == token_; |
| 524 | if (match) { |
| 525 | e.constant = attribute_; |
| 526 | if (!check) { |
| 527 | if (e.type.base_type == BASE_TYPE_NONE) { |
| 528 | e.type.base_type = req; |
| 529 | } else { |
| 530 | Error(std::string("type mismatch: expecting: ") + |
| 531 | kTypeNames[e.type.base_type] + |
| 532 | ", found: " + |
| 533 | kTypeNames[req]); |
| 534 | } |
| 535 | } |
| 536 | Next(); |
| 537 | } |
| 538 | return match; |
| 539 | } |
| 540 | |
| 541 | void Parser::ParseSingleValue(Value &e) { |
| 542 | if (TryTypedValue(kTokenIntegerConstant, |
| 543 | IsScalar(e.type.base_type), |
| 544 | e, |
| 545 | BASE_TYPE_INT) || |
| 546 | TryTypedValue(kTokenFloatConstant, |
| 547 | IsFloat(e.type.base_type), |
| 548 | e, |
| 549 | BASE_TYPE_FLOAT) || |
| 550 | TryTypedValue(kTokenStringConstant, |
| 551 | e.type.base_type == BASE_TYPE_STRING, |
| 552 | e, |
| 553 | BASE_TYPE_STRING)) { |
| 554 | } else if (token_ == kTokenIdentifier) { |
| 555 | for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) { |
| 556 | auto ev = (*it)->vals.Lookup(attribute_); |
| 557 | if (ev) { |
| 558 | attribute_ = NumToString(ev->value); |
| 559 | TryTypedValue(kTokenIdentifier, |
| 560 | IsInteger(e.type.base_type), |
| 561 | e, |
| 562 | BASE_TYPE_INT); |
| 563 | return; |
| 564 | } |
| 565 | } |
| 566 | Error("not valid enum value: " + attribute_); |
| 567 | } else { |
| 568 | Error("cannot parse value starting with: " + TokenToString(token_)); |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | StructDef *Parser::LookupCreateStruct(const std::string &name) { |
| 573 | auto struct_def = structs_.Lookup(name); |
| 574 | if (!struct_def) { |
| 575 | // Rather than failing, we create a "pre declared" StructDef, due to |
| 576 | // circular references, and check for errors at the end of parsing. |
| 577 | struct_def = new StructDef(); |
| 578 | structs_.Add(name, struct_def); |
| 579 | struct_def->name = name; |
| 580 | struct_def->predecl = true; |
| 581 | } |
| 582 | return struct_def; |
| 583 | } |
| 584 | |
| 585 | void Parser::ParseEnum(bool is_union) { |
| 586 | std::string dc = doc_comment_; |
| 587 | Next(); |
| 588 | std::string name = attribute_; |
| 589 | Expect(kTokenIdentifier); |
| 590 | auto &enum_def = *new EnumDef(); |
| 591 | enum_def.name = name; |
| 592 | enum_def.doc_comment = dc; |
| 593 | enum_def.is_union = is_union; |
| 594 | if (enums_.Add(name, &enum_def)) Error("enum already exists: " + name); |
| 595 | if (is_union) { |
| 596 | enum_def.underlying_type.base_type = BASE_TYPE_UTYPE; |
| 597 | enum_def.underlying_type.enum_def = &enum_def; |
Wouter van Oortmerssen | a5f5001 | 2014-07-02 12:01:21 -0700 | [diff] [blame] | 598 | } else { |
| 599 | // Give specialized error message, since this type spec used to |
| 600 | // be optional in the first FlatBuffers release. |
| 601 | if (!IsNext(':')) Error("must specify the underlying integer type for this" |
| 602 | " enum (e.g. \': short\', which was the default)."); |
| 603 | // Specify the integer type underlying this enum. |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 604 | ParseType(enum_def.underlying_type); |
| 605 | if (!IsInteger(enum_def.underlying_type.base_type)) |
| 606 | Error("underlying enum type must be integral"); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 607 | } |
| 608 | ParseMetaData(enum_def); |
| 609 | Expect('{'); |
| 610 | if (is_union) enum_def.vals.Add("NONE", new EnumVal("NONE", 0)); |
| 611 | do { |
| 612 | std::string name = attribute_; |
| 613 | std::string dc = doc_comment_; |
| 614 | Expect(kTokenIdentifier); |
| 615 | auto prevsize = enum_def.vals.vec.size(); |
| 616 | auto &ev = *new EnumVal(name, static_cast<int>( |
| 617 | enum_def.vals.vec.size() |
| 618 | ? enum_def.vals.vec.back()->value + 1 |
| 619 | : 0)); |
| 620 | if (enum_def.vals.Add(name, &ev)) |
| 621 | Error("enum value already exists: " + name); |
| 622 | ev.doc_comment = dc; |
| 623 | if (is_union) { |
| 624 | ev.struct_def = LookupCreateStruct(name); |
| 625 | } |
| 626 | if (IsNext('=')) { |
| 627 | ev.value = atoi(attribute_.c_str()); |
| 628 | Expect(kTokenIntegerConstant); |
| 629 | if (prevsize && enum_def.vals.vec[prevsize - 1]->value >= ev.value) |
| 630 | Error("enum values must be specified in ascending order"); |
| 631 | } |
| 632 | } while (IsNext(',')); |
| 633 | Expect('}'); |
| 634 | } |
| 635 | |
| 636 | void Parser::ParseDecl() { |
| 637 | std::string dc = doc_comment_; |
| 638 | bool fixed = IsNext(kTokenStruct); |
| 639 | if (!fixed) Expect(kTokenTable); |
| 640 | std::string name = attribute_; |
| 641 | Expect(kTokenIdentifier); |
| 642 | auto &struct_def = *LookupCreateStruct(name); |
| 643 | if (!struct_def.predecl) Error("datatype already exists: " + name); |
| 644 | struct_def.predecl = false; |
| 645 | struct_def.name = name; |
| 646 | struct_def.doc_comment = dc; |
| 647 | struct_def.fixed = fixed; |
| 648 | // Move this struct to the back of the vector just in case it was predeclared, |
| 649 | // to preserve declartion order. |
| 650 | remove(structs_.vec.begin(), structs_.vec.end(), &struct_def); |
| 651 | structs_.vec.back() = &struct_def; |
| 652 | ParseMetaData(struct_def); |
| 653 | struct_def.sortbysize = |
| 654 | struct_def.attributes.Lookup("original_order") == nullptr && !fixed; |
| 655 | Expect('{'); |
| 656 | while (token_ != '}') ParseField(struct_def); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 657 | auto force_align = struct_def.attributes.Lookup("force_align"); |
| 658 | if (fixed && force_align) { |
| 659 | auto align = static_cast<size_t>(atoi(force_align->constant.c_str())); |
| 660 | if (force_align->type.base_type != BASE_TYPE_INT || |
| 661 | align < struct_def.minalign || |
| 662 | align > 256 || |
| 663 | align & (align - 1)) |
| 664 | Error("force_align must be a power of two integer ranging from the" |
| 665 | "struct\'s natural alignment to 256"); |
| 666 | struct_def.minalign = align; |
| 667 | } |
Wouter van Oortmerssen | 65cfa18 | 2014-06-23 11:34:19 -0700 | [diff] [blame] | 668 | struct_def.PadLastField(struct_def.minalign); |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 669 | // Check if this is a table that has manual id assignments |
| 670 | auto &fields = struct_def.fields.vec; |
| 671 | if (!struct_def.fixed && fields.size()) { |
Wouter van Oortmerssen | 7fcbe72 | 2014-07-08 16:35:14 -0700 | [diff] [blame^] | 672 | size_t num_id_fields = 0; |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 673 | for (auto it = fields.begin(); it != fields.end(); ++it) { |
| 674 | if ((*it)->attributes.Lookup("id")) num_id_fields++; |
| 675 | } |
| 676 | // If any fields have ids.. |
| 677 | if (num_id_fields) { |
| 678 | // Then all fields must have them. |
| 679 | if (num_id_fields != fields.size()) |
| 680 | Error("either all fields or no fields must have an 'id' attribute"); |
| 681 | // Simply sort by id, then the fields are the same as if no ids had |
| 682 | // been specified. |
| 683 | std::sort(fields.begin(), fields.end(), |
| 684 | [](const FieldDef *a, const FieldDef *b) -> bool { |
| 685 | auto a_id = atoi(a->attributes.Lookup("id")->constant.c_str()); |
| 686 | auto b_id = atoi(b->attributes.Lookup("id")->constant.c_str()); |
| 687 | return a_id < b_id; |
| 688 | }); |
| 689 | // Verify we have a contiguous set, and reassign vtable offsets. |
| 690 | for (int i = 0; i < static_cast<int>(fields.size()); i++) { |
| 691 | if (i != atoi(fields[i]->attributes.Lookup("id")->constant.c_str())) |
| 692 | Error("field id\'s must be consecutive from 0, id " + |
| 693 | NumToString(i) + " missing or set twice"); |
| 694 | fields[i]->value.offset = FieldIndexToOffset(static_cast<voffset_t>(i)); |
| 695 | } |
| 696 | } |
| 697 | } |
Wouter van Oortmerssen | 65cfa18 | 2014-06-23 11:34:19 -0700 | [diff] [blame] | 698 | Expect('}'); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 699 | } |
| 700 | |
| 701 | bool Parser::SetRootType(const char *name) { |
| 702 | root_struct_def = structs_.Lookup(name); |
| 703 | return root_struct_def != nullptr; |
| 704 | } |
| 705 | |
| 706 | bool Parser::Parse(const char *source) { |
| 707 | source_ = cursor_ = source; |
| 708 | line_ = 1; |
| 709 | error_.clear(); |
| 710 | builder_.Clear(); |
| 711 | try { |
| 712 | Next(); |
| 713 | while (token_ != kTokenEof) { |
| 714 | if (token_ == kTokenNameSpace) { |
| 715 | Next(); |
| 716 | for (;;) { |
| 717 | name_space_.push_back(attribute_); |
| 718 | Expect(kTokenIdentifier); |
| 719 | if (!IsNext('.')) break; |
| 720 | } |
| 721 | Expect(';'); |
| 722 | } else if (token_ == '{') { |
| 723 | if (!root_struct_def) Error("no root type set to parse json with"); |
| 724 | if (builder_.GetSize()) { |
| 725 | Error("cannot have more than one json object in a file"); |
| 726 | } |
| 727 | builder_.Finish(Offset<Table>(ParseTable(*root_struct_def))); |
| 728 | } else if (token_ == kTokenEnum) { |
| 729 | ParseEnum(false); |
| 730 | } else if (token_ == kTokenUnion) { |
| 731 | ParseEnum(true); |
| 732 | } else if (token_ == kTokenRootType) { |
| 733 | Next(); |
| 734 | auto root_type = attribute_; |
| 735 | Expect(kTokenIdentifier); |
| 736 | Expect(';'); |
| 737 | if (!SetRootType(root_type.c_str())) |
| 738 | Error("unknown root type: " + root_type); |
| 739 | if (root_struct_def->fixed) |
| 740 | Error("root type must be a table"); |
| 741 | } else { |
| 742 | ParseDecl(); |
| 743 | } |
| 744 | } |
| 745 | for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) { |
| 746 | if ((*it)->predecl) |
| 747 | Error("type referenced but not defined: " + (*it)->name); |
| 748 | } |
| 749 | for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) { |
| 750 | auto &enum_def = **it; |
| 751 | if (enum_def.is_union) { |
| 752 | for (auto it = enum_def.vals.vec.begin(); |
| 753 | it != enum_def.vals.vec.end(); |
| 754 | ++it) { |
| 755 | auto &val = **it; |
| 756 | if (val.struct_def && val.struct_def->fixed) |
| 757 | Error("only tables can be union elements: " + val.name); |
| 758 | } |
| 759 | } |
| 760 | } |
| 761 | } catch (const std::string &msg) { |
| 762 | error_ = "line " + NumToString(line_) + ": " + msg; |
| 763 | return false; |
| 764 | } |
| 765 | assert(!struct_stack_.size()); |
| 766 | return true; |
| 767 | } |
| 768 | |
| 769 | } // namespace flatbuffers |