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[] = { |
Wouter van Oortmerssen | 557c88c | 2014-09-16 17:37:17 -0700 | [diff] [blame] | 26 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) IDLTYPE, |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 27 | FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) |
| 28 | #undef FLATBUFFERS_TD |
| 29 | nullptr |
| 30 | }; |
| 31 | |
| 32 | const char kTypeSizes[] = { |
Wouter van Oortmerssen | 557c88c | 2014-09-16 17:37:17 -0700 | [diff] [blame] | 33 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ |
| 34 | sizeof(CTYPE), |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 35 | FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) |
| 36 | #undef FLATBUFFERS_TD |
| 37 | }; |
| 38 | |
| 39 | static void Error(const std::string &msg) { |
| 40 | throw msg; |
| 41 | } |
| 42 | |
| 43 | // Ensure that integer values we parse fit inside the declared integer type. |
| 44 | static void CheckBitsFit(int64_t val, size_t bits) { |
| 45 | auto mask = (1ll << bits) - 1; // Bits we allow to be used. |
| 46 | if (bits < 64 && |
| 47 | (val & ~mask) != 0 && // Positive or unsigned. |
| 48 | (val | mask) != -1) // Negative. |
| 49 | Error("constant does not fit in a " + NumToString(bits) + "-bit field"); |
| 50 | } |
| 51 | |
| 52 | // atot: templated version of atoi/atof: convert a string to an instance of T. |
| 53 | template<typename T> inline T atot(const char *s) { |
| 54 | auto val = StringToInt(s); |
| 55 | CheckBitsFit(val, sizeof(T) * 8); |
| 56 | return (T)val; |
| 57 | } |
| 58 | template<> inline bool atot<bool>(const char *s) { |
| 59 | return 0 != atoi(s); |
| 60 | } |
| 61 | template<> inline float atot<float>(const char *s) { |
| 62 | return static_cast<float>(strtod(s, nullptr)); |
| 63 | } |
| 64 | template<> inline double atot<double>(const char *s) { |
| 65 | return strtod(s, nullptr); |
| 66 | } |
| 67 | |
| 68 | template<> inline Offset<void> atot<Offset<void>>(const char *s) { |
| 69 | return Offset<void>(atoi(s)); |
| 70 | } |
| 71 | |
| 72 | // Declare tokens we'll use. Single character tokens are represented by their |
| 73 | // ascii character code (e.g. '{'), others above 256. |
| 74 | #define FLATBUFFERS_GEN_TOKENS(TD) \ |
| 75 | TD(Eof, 256, "end of file") \ |
| 76 | TD(StringConstant, 257, "string constant") \ |
| 77 | TD(IntegerConstant, 258, "integer constant") \ |
| 78 | TD(FloatConstant, 259, "float constant") \ |
| 79 | TD(Identifier, 260, "identifier") \ |
| 80 | TD(Table, 261, "table") \ |
| 81 | TD(Struct, 262, "struct") \ |
| 82 | TD(Enum, 263, "enum") \ |
| 83 | TD(Union, 264, "union") \ |
| 84 | TD(NameSpace, 265, "namespace") \ |
Wouter van Oortmerssen | 5da7bda | 2014-07-31 15:11:03 -0700 | [diff] [blame] | 85 | TD(RootType, 266, "root_type") \ |
| 86 | TD(FileIdentifier, 267, "file_identifier") \ |
Wouter van Oortmerssen | be894f0 | 2014-08-19 14:20:05 -0700 | [diff] [blame] | 87 | TD(FileExtension, 268, "file_extension") \ |
Wouter van Oortmerssen | 0952143 | 2014-11-17 17:27:26 -0800 | [diff] [blame] | 88 | TD(Include, 269, "include") \ |
| 89 | TD(Attribute, 270, "attribute") |
Wouter van Oortmerssen | 8f80fec | 2014-07-29 10:29:38 -0700 | [diff] [blame] | 90 | #ifdef __GNUC__ |
| 91 | __extension__ // Stop GCC complaining about trailing comma with -Wpendantic. |
| 92 | #endif |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 93 | enum { |
Wouter van Oortmerssen | 75349ae | 2014-07-09 11:44:26 -0700 | [diff] [blame] | 94 | #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME = VALUE, |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 95 | FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN) |
| 96 | #undef FLATBUFFERS_TOKEN |
Wouter van Oortmerssen | 557c88c | 2014-09-16 17:37:17 -0700 | [diff] [blame] | 97 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ |
| 98 | kToken ## ENUM, |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 99 | FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) |
| 100 | #undef FLATBUFFERS_TD |
| 101 | }; |
| 102 | |
| 103 | static std::string TokenToString(int t) { |
| 104 | static const char *tokens[] = { |
| 105 | #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) STRING, |
| 106 | FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN) |
| 107 | #undef FLATBUFFERS_TOKEN |
Wouter van Oortmerssen | 557c88c | 2014-09-16 17:37:17 -0700 | [diff] [blame] | 108 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) IDLTYPE, |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 109 | FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) |
| 110 | #undef FLATBUFFERS_TD |
| 111 | }; |
| 112 | if (t < 256) { // A single ascii char token. |
| 113 | std::string s; |
Wouter van Oortmerssen | 8e40902 | 2014-09-02 17:32:12 -0700 | [diff] [blame] | 114 | s.append(1, static_cast<char>(t)); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 115 | return s; |
| 116 | } else { // Other tokens. |
| 117 | return tokens[t - 256]; |
| 118 | } |
| 119 | } |
| 120 | |
Wouter van Oortmerssen | ebac1e1 | 2014-08-20 13:22:16 -0700 | [diff] [blame] | 121 | // Parses exactly nibbles worth of hex digits into a number, or error. |
| 122 | int64_t Parser::ParseHexNum(int nibbles) { |
| 123 | for (int i = 0; i < nibbles; i++) |
| 124 | if (!isxdigit(cursor_[i])) |
| 125 | Error("escape code must be followed by " + NumToString(nibbles) + |
| 126 | " hex digits"); |
| 127 | auto val = StringToInt(cursor_, 16); |
| 128 | cursor_ += nibbles; |
| 129 | return val; |
| 130 | } |
| 131 | |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 132 | void Parser::Next() { |
| 133 | doc_comment_.clear(); |
| 134 | bool seen_newline = false; |
| 135 | for (;;) { |
| 136 | char c = *cursor_++; |
| 137 | token_ = c; |
| 138 | switch (c) { |
| 139 | case '\0': cursor_--; token_ = kTokenEof; return; |
| 140 | case ' ': case '\r': case '\t': break; |
| 141 | case '\n': line_++; seen_newline = true; break; |
| 142 | case '{': case '}': case '(': case ')': case '[': case ']': return; |
| 143 | case ',': case ':': case ';': case '=': return; |
| 144 | case '.': |
| 145 | if(!isdigit(*cursor_)) return; |
| 146 | Error("floating point constant can\'t start with \".\""); |
| 147 | break; |
| 148 | case '\"': |
| 149 | attribute_ = ""; |
| 150 | while (*cursor_ != '\"') { |
| 151 | if (*cursor_ < ' ' && *cursor_ >= 0) |
| 152 | Error("illegal character in string constant"); |
| 153 | if (*cursor_ == '\\') { |
| 154 | cursor_++; |
| 155 | switch (*cursor_) { |
| 156 | case 'n': attribute_ += '\n'; cursor_++; break; |
| 157 | case 't': attribute_ += '\t'; cursor_++; break; |
| 158 | case 'r': attribute_ += '\r'; cursor_++; break; |
Wouter van Oortmerssen | ebac1e1 | 2014-08-20 13:22:16 -0700 | [diff] [blame] | 159 | case 'b': attribute_ += '\b'; cursor_++; break; |
| 160 | case 'f': attribute_ += '\f'; cursor_++; break; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 161 | case '\"': attribute_ += '\"'; cursor_++; break; |
| 162 | case '\\': attribute_ += '\\'; cursor_++; break; |
Wouter van Oortmerssen | ebac1e1 | 2014-08-20 13:22:16 -0700 | [diff] [blame] | 163 | case '/': attribute_ += '/'; cursor_++; break; |
| 164 | case 'x': { // Not in the JSON standard |
| 165 | cursor_++; |
| 166 | attribute_ += static_cast<char>(ParseHexNum(2)); |
| 167 | break; |
| 168 | } |
| 169 | case 'u': { |
| 170 | cursor_++; |
| 171 | ToUTF8(static_cast<int>(ParseHexNum(4)), &attribute_); |
| 172 | break; |
| 173 | } |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 174 | default: Error("unknown escape code in string constant"); break; |
| 175 | } |
| 176 | } else { // printable chars + UTF-8 bytes |
| 177 | attribute_ += *cursor_++; |
| 178 | } |
| 179 | } |
| 180 | cursor_++; |
| 181 | token_ = kTokenStringConstant; |
| 182 | return; |
| 183 | case '/': |
| 184 | if (*cursor_ == '/') { |
| 185 | const char *start = ++cursor_; |
| 186 | while (*cursor_ && *cursor_ != '\n') cursor_++; |
| 187 | if (*start == '/') { // documentation comment |
Zbigniew Mandziejewicz | 07d5965 | 2014-10-22 22:40:03 +0800 | [diff] [blame] | 188 | if (cursor_ != source_ && !seen_newline) |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 189 | Error("a documentation comment should be on a line on its own"); |
Gabriel Martinez | 730c0ca | 2014-09-24 11:46:32 -0700 | [diff] [blame] | 190 | doc_comment_.push_back(std::string(start + 1, cursor_)); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 191 | } |
| 192 | break; |
| 193 | } |
| 194 | // fall thru |
| 195 | default: |
| 196 | if (isalpha(static_cast<unsigned char>(c))) { |
| 197 | // Collect all chars of an identifier: |
| 198 | const char *start = cursor_ - 1; |
| 199 | while (isalnum(static_cast<unsigned char>(*cursor_)) || |
| 200 | *cursor_ == '_') |
| 201 | cursor_++; |
| 202 | attribute_.clear(); |
| 203 | attribute_.append(start, cursor_); |
| 204 | // First, see if it is a type keyword from the table of types: |
Wouter van Oortmerssen | 557c88c | 2014-09-16 17:37:17 -0700 | [diff] [blame] | 205 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 206 | if (attribute_ == IDLTYPE) { \ |
| 207 | token_ = kToken ## ENUM; \ |
| 208 | return; \ |
| 209 | } |
| 210 | FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) |
| 211 | #undef FLATBUFFERS_TD |
| 212 | // If it's a boolean constant keyword, turn those into integers, |
| 213 | // which simplifies our logic downstream. |
| 214 | if (attribute_ == "true" || attribute_ == "false") { |
| 215 | attribute_ = NumToString(attribute_ == "true"); |
| 216 | token_ = kTokenIntegerConstant; |
| 217 | return; |
| 218 | } |
| 219 | // Check for declaration keywords: |
| 220 | if (attribute_ == "table") { token_ = kTokenTable; return; } |
| 221 | if (attribute_ == "struct") { token_ = kTokenStruct; return; } |
| 222 | if (attribute_ == "enum") { token_ = kTokenEnum; return; } |
| 223 | if (attribute_ == "union") { token_ = kTokenUnion; return; } |
| 224 | if (attribute_ == "namespace") { token_ = kTokenNameSpace; return; } |
| 225 | if (attribute_ == "root_type") { token_ = kTokenRootType; return; } |
Wouter van Oortmerssen | 0952143 | 2014-11-17 17:27:26 -0800 | [diff] [blame] | 226 | if (attribute_ == "include") { token_ = kTokenInclude; return; } |
| 227 | if (attribute_ == "attribute") { token_ = kTokenAttribute; return; } |
Wouter van Oortmerssen | 5da7bda | 2014-07-31 15:11:03 -0700 | [diff] [blame] | 228 | if (attribute_ == "file_identifier") { |
| 229 | token_ = kTokenFileIdentifier; |
| 230 | return; |
| 231 | } |
| 232 | if (attribute_ == "file_extension") { |
| 233 | token_ = kTokenFileExtension; |
| 234 | return; |
| 235 | } |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 236 | // If not, it is a user-defined identifier: |
| 237 | token_ = kTokenIdentifier; |
| 238 | return; |
| 239 | } else if (isdigit(static_cast<unsigned char>(c)) || c == '-') { |
| 240 | const char *start = cursor_ - 1; |
| 241 | while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++; |
| 242 | if (*cursor_ == '.') { |
| 243 | cursor_++; |
| 244 | while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++; |
Wouter van Oortmerssen | 93df569 | 2014-07-10 13:40:55 -0700 | [diff] [blame] | 245 | // See if this float has a scientific notation suffix. Both JSON |
| 246 | // and C++ (through strtod() we use) have the same format: |
| 247 | if (*cursor_ == 'e' || *cursor_ == 'E') { |
| 248 | cursor_++; |
| 249 | if (*cursor_ == '+' || *cursor_ == '-') cursor_++; |
| 250 | while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++; |
| 251 | } |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 252 | token_ = kTokenFloatConstant; |
| 253 | } else { |
| 254 | token_ = kTokenIntegerConstant; |
| 255 | } |
| 256 | attribute_.clear(); |
| 257 | attribute_.append(start, cursor_); |
| 258 | return; |
| 259 | } |
| 260 | std::string ch; |
| 261 | ch = c; |
| 262 | if (c < ' ' || c > '~') ch = "code: " + NumToString(c); |
| 263 | Error("illegal character: " + ch); |
| 264 | break; |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | // Check if a given token is next, if so, consume it as well. |
| 270 | bool Parser::IsNext(int t) { |
| 271 | bool isnext = t == token_; |
| 272 | if (isnext) Next(); |
| 273 | return isnext; |
| 274 | } |
| 275 | |
| 276 | // Expect a given token to be next, consume it, or error if not present. |
| 277 | void Parser::Expect(int t) { |
| 278 | if (t != token_) { |
| 279 | Error("expecting: " + TokenToString(t) + " instead got: " + |
| 280 | TokenToString(token_)); |
| 281 | } |
| 282 | Next(); |
| 283 | } |
| 284 | |
Wouter van Oortmerssen | d38b9af | 2014-09-26 16:46:30 -0700 | [diff] [blame] | 285 | void Parser::ParseTypeIdent(Type &type) { |
| 286 | auto enum_def = enums_.Lookup(attribute_); |
| 287 | if (enum_def) { |
| 288 | type = enum_def->underlying_type; |
| 289 | if (enum_def->is_union) type.base_type = BASE_TYPE_UNION; |
| 290 | } else { |
| 291 | type.base_type = BASE_TYPE_STRUCT; |
| 292 | type.struct_def = LookupCreateStruct(attribute_); |
| 293 | } |
| 294 | } |
| 295 | |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 296 | // Parse any IDL type. |
| 297 | void Parser::ParseType(Type &type) { |
| 298 | if (token_ >= kTokenBOOL && token_ <= kTokenSTRING) { |
| 299 | type.base_type = static_cast<BaseType>(token_ - kTokenNONE); |
| 300 | } else { |
| 301 | if (token_ == kTokenIdentifier) { |
Wouter van Oortmerssen | d38b9af | 2014-09-26 16:46:30 -0700 | [diff] [blame] | 302 | ParseTypeIdent(type); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 303 | } else if (token_ == '[') { |
| 304 | Next(); |
| 305 | Type subtype; |
| 306 | ParseType(subtype); |
| 307 | if (subtype.base_type == BASE_TYPE_VECTOR) { |
| 308 | // We could support this, but it will complicate things, and it's |
| 309 | // easier to work around with a struct around the inner vector. |
| 310 | Error("nested vector types not supported (wrap in table first)."); |
| 311 | } |
| 312 | if (subtype.base_type == BASE_TYPE_UNION) { |
| 313 | // We could support this if we stored a struct of 2 elements per |
| 314 | // union element. |
| 315 | Error("vector of union types not supported (wrap in table first)."); |
| 316 | } |
Wouter van Oortmerssen | 3fb6a86 | 2014-07-14 17:49:04 -0700 | [diff] [blame] | 317 | type = Type(BASE_TYPE_VECTOR, subtype.struct_def, subtype.enum_def); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 318 | type.element = subtype.base_type; |
| 319 | Expect(']'); |
| 320 | return; |
| 321 | } else { |
| 322 | Error("illegal type syntax"); |
| 323 | } |
| 324 | } |
| 325 | Next(); |
| 326 | } |
| 327 | |
| 328 | FieldDef &Parser::AddField(StructDef &struct_def, |
| 329 | const std::string &name, |
| 330 | const Type &type) { |
| 331 | auto &field = *new FieldDef(); |
| 332 | field.value.offset = |
| 333 | FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size())); |
| 334 | field.name = name; |
| 335 | field.value.type = type; |
| 336 | if (struct_def.fixed) { // statically compute the field offset |
| 337 | auto size = InlineSize(type); |
| 338 | auto alignment = InlineAlignment(type); |
| 339 | // structs_ need to have a predictable format, so we need to align to |
| 340 | // the largest scalar |
| 341 | struct_def.minalign = std::max(struct_def.minalign, alignment); |
| 342 | struct_def.PadLastField(alignment); |
Wouter van Oortmerssen | 1256307 | 2014-06-30 15:56:31 -0700 | [diff] [blame] | 343 | field.value.offset = static_cast<voffset_t>(struct_def.bytesize); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 344 | struct_def.bytesize += size; |
| 345 | } |
| 346 | if (struct_def.fields.Add(name, &field)) |
| 347 | Error("field already exists: " + name); |
| 348 | return field; |
| 349 | } |
| 350 | |
| 351 | void Parser::ParseField(StructDef &struct_def) { |
| 352 | std::string name = attribute_; |
Gabriel Martinez | 730c0ca | 2014-09-24 11:46:32 -0700 | [diff] [blame] | 353 | std::vector<std::string> dc = doc_comment_; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 354 | Expect(kTokenIdentifier); |
| 355 | Expect(':'); |
| 356 | Type type; |
| 357 | ParseType(type); |
| 358 | |
| 359 | if (struct_def.fixed && !IsScalar(type.base_type) && !IsStruct(type)) |
| 360 | Error("structs_ may contain only scalar or struct fields"); |
| 361 | |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 362 | FieldDef *typefield = nullptr; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 363 | if (type.base_type == BASE_TYPE_UNION) { |
| 364 | // For union fields, add a second auto-generated field to hold the type, |
| 365 | // with _type appended as the name. |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 366 | typefield = &AddField(struct_def, name + "_type", |
| 367 | type.enum_def->underlying_type); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 368 | } |
| 369 | |
| 370 | auto &field = AddField(struct_def, name, type); |
| 371 | |
| 372 | if (token_ == '=') { |
| 373 | Next(); |
Wouter van Oortmerssen | 15dc1a8 | 2014-09-03 12:23:15 -0700 | [diff] [blame] | 374 | if (!IsScalar(type.base_type)) |
| 375 | Error("default values currently only supported for scalars"); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 376 | ParseSingleValue(field.value); |
| 377 | } |
| 378 | |
Wouter van Oortmerssen | 7b80535 | 2014-09-23 11:55:42 -0700 | [diff] [blame] | 379 | if (type.enum_def && |
| 380 | IsScalar(type.base_type) && |
| 381 | !struct_def.fixed && |
| 382 | !type.enum_def->attributes.Lookup("bit_flags") && |
Wouter van Oortmerssen | d38b9af | 2014-09-26 16:46:30 -0700 | [diff] [blame] | 383 | !type.enum_def->ReverseLookup(static_cast<int>( |
| 384 | StringToInt(field.value.constant.c_str())))) |
Wouter van Oortmerssen | 7b80535 | 2014-09-23 11:55:42 -0700 | [diff] [blame] | 385 | Error("enum " + type.enum_def->name + |
| 386 | " does not have a declaration for this field\'s default of " + |
| 387 | field.value.constant); |
| 388 | |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 389 | field.doc_comment = dc; |
| 390 | ParseMetaData(field); |
| 391 | field.deprecated = field.attributes.Lookup("deprecated") != nullptr; |
| 392 | if (field.deprecated && struct_def.fixed) |
| 393 | Error("can't deprecate fields in a struct"); |
Wouter van Oortmerssen | 517c964 | 2014-09-19 16:51:36 -0700 | [diff] [blame] | 394 | field.required = field.attributes.Lookup("required") != nullptr; |
| 395 | if (field.required && (struct_def.fixed || |
| 396 | IsScalar(field.value.type.base_type))) |
| 397 | Error("only non-scalar fields in tables may be 'required'"); |
Wouter van Oortmerssen | 3550899 | 2015-01-07 17:51:31 -0800 | [diff] [blame] | 398 | field.key = field.attributes.Lookup("key") != nullptr; |
| 399 | if (field.key) { |
| 400 | if (struct_def.has_key) |
| 401 | Error("only one field may be set as 'key'"); |
| 402 | struct_def.has_key = true; |
| 403 | if (!IsScalar(field.value.type.base_type)) { |
| 404 | field.required = true; |
| 405 | if (field.value.type.base_type != BASE_TYPE_STRING) |
| 406 | Error("'key' field must be string or scalar type"); |
| 407 | } |
| 408 | } |
Wouter van Oortmerssen | 3e201a9 | 2014-07-15 17:50:22 -0700 | [diff] [blame] | 409 | auto nested = field.attributes.Lookup("nested_flatbuffer"); |
| 410 | if (nested) { |
| 411 | if (nested->type.base_type != BASE_TYPE_STRING) |
| 412 | Error("nested_flatbuffer attribute must be a string (the root type)"); |
| 413 | if (field.value.type.base_type != BASE_TYPE_VECTOR || |
| 414 | field.value.type.element != BASE_TYPE_UCHAR) |
| 415 | Error("nested_flatbuffer attribute may only apply to a vector of ubyte"); |
| 416 | // This will cause an error if the root type of the nested flatbuffer |
| 417 | // wasn't defined elsewhere. |
| 418 | LookupCreateStruct(nested->constant); |
| 419 | } |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 420 | |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 421 | if (typefield) { |
| 422 | // If this field is a union, and it has a manually assigned id, |
| 423 | // the automatically added type field should have an id as well (of N - 1). |
| 424 | auto attr = field.attributes.Lookup("id"); |
| 425 | if (attr) { |
| 426 | auto id = atoi(attr->constant.c_str()); |
| 427 | auto val = new Value(); |
| 428 | val->type = attr->type; |
| 429 | val->constant = NumToString(id - 1); |
| 430 | typefield->attributes.Add("id", val); |
| 431 | } |
| 432 | } |
| 433 | |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 434 | Expect(';'); |
| 435 | } |
| 436 | |
| 437 | void Parser::ParseAnyValue(Value &val, FieldDef *field) { |
| 438 | switch (val.type.base_type) { |
| 439 | case BASE_TYPE_UNION: { |
| 440 | assert(field); |
| 441 | if (!field_stack_.size() || |
| 442 | field_stack_.back().second->value.type.base_type != BASE_TYPE_UTYPE) |
| 443 | Error("missing type field before this union value: " + field->name); |
| 444 | auto enum_idx = atot<unsigned char>( |
| 445 | field_stack_.back().first.constant.c_str()); |
Wouter van Oortmerssen | 3fb6a86 | 2014-07-14 17:49:04 -0700 | [diff] [blame] | 446 | auto enum_val = val.type.enum_def->ReverseLookup(enum_idx); |
| 447 | if (!enum_val) Error("illegal type id for: " + field->name); |
| 448 | val.constant = NumToString(ParseTable(*enum_val->struct_def)); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 449 | break; |
| 450 | } |
| 451 | case BASE_TYPE_STRUCT: |
| 452 | val.constant = NumToString(ParseTable(*val.type.struct_def)); |
| 453 | break; |
| 454 | case BASE_TYPE_STRING: { |
| 455 | auto s = attribute_; |
| 456 | Expect(kTokenStringConstant); |
| 457 | val.constant = NumToString(builder_.CreateString(s).o); |
| 458 | break; |
| 459 | } |
| 460 | case BASE_TYPE_VECTOR: { |
| 461 | Expect('['); |
| 462 | val.constant = NumToString(ParseVector(val.type.VectorType())); |
| 463 | break; |
| 464 | } |
| 465 | default: |
| 466 | ParseSingleValue(val); |
| 467 | break; |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | void Parser::SerializeStruct(const StructDef &struct_def, const Value &val) { |
| 472 | auto off = atot<uoffset_t>(val.constant.c_str()); |
| 473 | assert(struct_stack_.size() - off == struct_def.bytesize); |
| 474 | builder_.Align(struct_def.minalign); |
| 475 | builder_.PushBytes(&struct_stack_[off], struct_def.bytesize); |
| 476 | struct_stack_.resize(struct_stack_.size() - struct_def.bytesize); |
| 477 | builder_.AddStructOffset(val.offset, builder_.GetSize()); |
| 478 | } |
| 479 | |
| 480 | uoffset_t Parser::ParseTable(const StructDef &struct_def) { |
| 481 | Expect('{'); |
| 482 | size_t fieldn = 0; |
Wouter van Oortmerssen | 0b47e69 | 2014-08-12 16:20:13 -0700 | [diff] [blame] | 483 | if (!IsNext('}')) for (;;) { |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 484 | std::string name = attribute_; |
| 485 | if (!IsNext(kTokenStringConstant)) Expect(kTokenIdentifier); |
| 486 | auto field = struct_def.fields.Lookup(name); |
| 487 | if (!field) Error("unknown field: " + name); |
| 488 | if (struct_def.fixed && (fieldn >= struct_def.fields.vec.size() |
| 489 | || struct_def.fields.vec[fieldn] != field)) { |
| 490 | Error("struct field appearing out of order: " + name); |
| 491 | } |
| 492 | Expect(':'); |
| 493 | Value val = field->value; |
| 494 | ParseAnyValue(val, field); |
| 495 | field_stack_.push_back(std::make_pair(val, field)); |
| 496 | fieldn++; |
| 497 | if (IsNext('}')) break; |
| 498 | Expect(','); |
| 499 | } |
Wouter van Oortmerssen | 11f2538 | 2014-09-04 11:57:09 -0700 | [diff] [blame] | 500 | for (auto it = field_stack_.rbegin(); |
| 501 | it != field_stack_.rbegin() + fieldn; ++it) { |
| 502 | if (it->second->used) |
| 503 | Error("field set more than once: " + it->second->name); |
| 504 | it->second->used = true; |
| 505 | } |
| 506 | for (auto it = field_stack_.rbegin(); |
| 507 | it != field_stack_.rbegin() + fieldn; ++it) { |
| 508 | it->second->used = false; |
| 509 | } |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 510 | if (struct_def.fixed && fieldn != struct_def.fields.vec.size()) |
| 511 | Error("incomplete struct initialization: " + struct_def.name); |
| 512 | auto start = struct_def.fixed |
| 513 | ? builder_.StartStruct(struct_def.minalign) |
| 514 | : builder_.StartTable(); |
| 515 | |
| 516 | for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1; |
| 517 | size; |
| 518 | size /= 2) { |
| 519 | // Go through elements in reverse, since we're building the data backwards. |
| 520 | for (auto it = field_stack_.rbegin(); |
| 521 | it != field_stack_.rbegin() + fieldn; ++it) { |
| 522 | auto &value = it->first; |
| 523 | auto field = it->second; |
| 524 | if (!struct_def.sortbysize || size == SizeOf(value.type.base_type)) { |
| 525 | switch (value.type.base_type) { |
Wouter van Oortmerssen | 557c88c | 2014-09-16 17:37:17 -0700 | [diff] [blame] | 526 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 527 | case BASE_TYPE_ ## ENUM: \ |
| 528 | builder_.Pad(field->padding); \ |
Wouter van Oortmerssen | be3c874 | 2014-08-11 17:38:54 -0700 | [diff] [blame] | 529 | if (struct_def.fixed) { \ |
| 530 | builder_.PushElement(atot<CTYPE>(value.constant.c_str())); \ |
| 531 | } else { \ |
| 532 | builder_.AddElement(value.offset, \ |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 533 | atot<CTYPE>( value.constant.c_str()), \ |
| 534 | atot<CTYPE>(field->value.constant.c_str())); \ |
Wouter van Oortmerssen | be3c874 | 2014-08-11 17:38:54 -0700 | [diff] [blame] | 535 | } \ |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 536 | break; |
| 537 | FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD); |
| 538 | #undef FLATBUFFERS_TD |
Wouter van Oortmerssen | 557c88c | 2014-09-16 17:37:17 -0700 | [diff] [blame] | 539 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 540 | case BASE_TYPE_ ## ENUM: \ |
| 541 | builder_.Pad(field->padding); \ |
| 542 | if (IsStruct(field->value.type)) { \ |
| 543 | SerializeStruct(*field->value.type.struct_def, value); \ |
| 544 | } else { \ |
| 545 | builder_.AddOffset(value.offset, \ |
| 546 | atot<CTYPE>(value.constant.c_str())); \ |
| 547 | } \ |
| 548 | break; |
| 549 | FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD); |
| 550 | #undef FLATBUFFERS_TD |
| 551 | } |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | for (size_t i = 0; i < fieldn; i++) field_stack_.pop_back(); |
| 556 | |
| 557 | if (struct_def.fixed) { |
| 558 | builder_.ClearOffsets(); |
| 559 | builder_.EndStruct(); |
| 560 | // Temporarily store this struct in a side buffer, since this data has to |
| 561 | // be stored in-line later in the parent object. |
| 562 | auto off = struct_stack_.size(); |
| 563 | struct_stack_.insert(struct_stack_.end(), |
| 564 | builder_.GetBufferPointer(), |
| 565 | builder_.GetBufferPointer() + struct_def.bytesize); |
| 566 | builder_.PopBytes(struct_def.bytesize); |
| 567 | return static_cast<uoffset_t>(off); |
| 568 | } else { |
| 569 | return builder_.EndTable( |
| 570 | start, |
| 571 | static_cast<voffset_t>(struct_def.fields.vec.size())); |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | uoffset_t Parser::ParseVector(const Type &type) { |
| 576 | int count = 0; |
| 577 | if (token_ != ']') for (;;) { |
| 578 | Value val; |
| 579 | val.type = type; |
| 580 | ParseAnyValue(val, NULL); |
| 581 | field_stack_.push_back(std::make_pair(val, nullptr)); |
| 582 | count++; |
| 583 | if (token_ == ']') break; |
| 584 | Expect(','); |
| 585 | } |
| 586 | Next(); |
| 587 | |
Wouter van Oortmerssen | be3c874 | 2014-08-11 17:38:54 -0700 | [diff] [blame] | 588 | builder_.StartVector(count * InlineSize(type) / InlineAlignment(type), |
| 589 | InlineAlignment(type)); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 590 | for (int i = 0; i < count; i++) { |
| 591 | // start at the back, since we're building the data backwards. |
| 592 | auto &val = field_stack_.back().first; |
| 593 | switch (val.type.base_type) { |
Wouter van Oortmerssen | 557c88c | 2014-09-16 17:37:17 -0700 | [diff] [blame] | 594 | #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 595 | case BASE_TYPE_ ## ENUM: \ |
| 596 | if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \ |
| 597 | else builder_.PushElement(atot<CTYPE>(val.constant.c_str())); \ |
| 598 | break; |
| 599 | FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) |
| 600 | #undef FLATBUFFERS_TD |
| 601 | } |
| 602 | field_stack_.pop_back(); |
| 603 | } |
| 604 | |
| 605 | builder_.ClearOffsets(); |
| 606 | return builder_.EndVector(count); |
| 607 | } |
| 608 | |
| 609 | void Parser::ParseMetaData(Definition &def) { |
| 610 | if (IsNext('(')) { |
| 611 | for (;;) { |
| 612 | auto name = attribute_; |
| 613 | Expect(kTokenIdentifier); |
Wouter van Oortmerssen | 0952143 | 2014-11-17 17:27:26 -0800 | [diff] [blame] | 614 | if (known_attributes_.find(name) == known_attributes_.end()) |
| 615 | Error("user define attributes must be declared before use: " + name); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 616 | auto e = new Value(); |
| 617 | def.attributes.Add(name, e); |
| 618 | if (IsNext(':')) { |
| 619 | ParseSingleValue(*e); |
| 620 | } |
| 621 | if (IsNext(')')) break; |
| 622 | Expect(','); |
| 623 | } |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | bool Parser::TryTypedValue(int dtoken, |
| 628 | bool check, |
| 629 | Value &e, |
| 630 | BaseType req) { |
| 631 | bool match = dtoken == token_; |
| 632 | if (match) { |
| 633 | e.constant = attribute_; |
| 634 | if (!check) { |
| 635 | if (e.type.base_type == BASE_TYPE_NONE) { |
| 636 | e.type.base_type = req; |
| 637 | } else { |
| 638 | Error(std::string("type mismatch: expecting: ") + |
| 639 | kTypeNames[e.type.base_type] + |
| 640 | ", found: " + |
| 641 | kTypeNames[req]); |
| 642 | } |
| 643 | } |
| 644 | Next(); |
| 645 | } |
| 646 | return match; |
| 647 | } |
| 648 | |
Wouter van Oortmerssen | 9c3de1e | 2014-07-25 15:04:35 -0700 | [diff] [blame] | 649 | int64_t Parser::ParseIntegerFromString(Type &type) { |
| 650 | int64_t result = 0; |
| 651 | // Parse one or more enum identifiers, separated by spaces. |
| 652 | const char *next = attribute_.c_str(); |
| 653 | do { |
| 654 | const char *divider = strchr(next, ' '); |
| 655 | std::string word; |
| 656 | if (divider) { |
| 657 | word = std::string(next, divider); |
| 658 | next = divider + strspn(divider, " "); |
| 659 | } else { |
| 660 | word = next; |
| 661 | next += word.length(); |
| 662 | } |
| 663 | if (type.enum_def) { // The field has an enum type |
| 664 | auto enum_val = type.enum_def->vals.Lookup(word); |
| 665 | if (!enum_val) |
| 666 | Error("unknown enum value: " + word + |
| 667 | ", for enum: " + type.enum_def->name); |
| 668 | result |= enum_val->value; |
| 669 | } else { // No enum type, probably integral field. |
| 670 | if (!IsInteger(type.base_type)) |
| 671 | Error("not a valid value for this field: " + word); |
| 672 | // TODO: could check if its a valid number constant here. |
| 673 | const char *dot = strchr(word.c_str(), '.'); |
| 674 | if (!dot) Error("enum values need to be qualified by an enum type"); |
| 675 | std::string enum_def_str(word.c_str(), dot); |
| 676 | std::string enum_val_str(dot + 1, word.c_str() + word.length()); |
| 677 | auto enum_def = enums_.Lookup(enum_def_str); |
| 678 | if (!enum_def) Error("unknown enum: " + enum_def_str); |
| 679 | auto enum_val = enum_def->vals.Lookup(enum_val_str); |
| 680 | if (!enum_val) Error("unknown enum value: " + enum_val_str); |
| 681 | result |= enum_val->value; |
| 682 | } |
| 683 | } while(*next); |
| 684 | return result; |
| 685 | } |
| 686 | |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 687 | void Parser::ParseSingleValue(Value &e) { |
Wouter van Oortmerssen | 9c3de1e | 2014-07-25 15:04:35 -0700 | [diff] [blame] | 688 | // First check if this could be a string/identifier enum value: |
| 689 | if (e.type.base_type != BASE_TYPE_STRING && |
| 690 | e.type.base_type != BASE_TYPE_NONE && |
| 691 | (token_ == kTokenIdentifier || token_ == kTokenStringConstant)) { |
| 692 | e.constant = NumToString(ParseIntegerFromString(e.type)); |
| 693 | Next(); |
Wouter van Oortmerssen | 3fb6a86 | 2014-07-14 17:49:04 -0700 | [diff] [blame] | 694 | } else if (TryTypedValue(kTokenIntegerConstant, |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 695 | IsScalar(e.type.base_type), |
| 696 | e, |
| 697 | BASE_TYPE_INT) || |
| 698 | TryTypedValue(kTokenFloatConstant, |
| 699 | IsFloat(e.type.base_type), |
| 700 | e, |
| 701 | BASE_TYPE_FLOAT) || |
| 702 | TryTypedValue(kTokenStringConstant, |
| 703 | e.type.base_type == BASE_TYPE_STRING, |
| 704 | e, |
| 705 | BASE_TYPE_STRING)) { |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 706 | } else { |
| 707 | Error("cannot parse value starting with: " + TokenToString(token_)); |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | StructDef *Parser::LookupCreateStruct(const std::string &name) { |
| 712 | auto struct_def = structs_.Lookup(name); |
| 713 | if (!struct_def) { |
| 714 | // Rather than failing, we create a "pre declared" StructDef, due to |
| 715 | // circular references, and check for errors at the end of parsing. |
| 716 | struct_def = new StructDef(); |
| 717 | structs_.Add(name, struct_def); |
| 718 | struct_def->name = name; |
| 719 | struct_def->predecl = true; |
Wouter van Oortmerssen | c2ba7fd | 2014-08-19 16:37:46 -0700 | [diff] [blame] | 720 | struct_def->defined_namespace = namespaces_.back(); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 721 | } |
| 722 | return struct_def; |
| 723 | } |
| 724 | |
| 725 | void Parser::ParseEnum(bool is_union) { |
Gabriel Martinez | 730c0ca | 2014-09-24 11:46:32 -0700 | [diff] [blame] | 726 | std::vector<std::string> dc = doc_comment_; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 727 | Next(); |
| 728 | std::string name = attribute_; |
| 729 | Expect(kTokenIdentifier); |
| 730 | auto &enum_def = *new EnumDef(); |
| 731 | enum_def.name = name; |
| 732 | enum_def.doc_comment = dc; |
| 733 | enum_def.is_union = is_union; |
Wouter van Oortmerssen | 7b80535 | 2014-09-23 11:55:42 -0700 | [diff] [blame] | 734 | enum_def.defined_namespace = namespaces_.back(); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 735 | if (enums_.Add(name, &enum_def)) Error("enum already exists: " + name); |
| 736 | if (is_union) { |
| 737 | enum_def.underlying_type.base_type = BASE_TYPE_UTYPE; |
| 738 | enum_def.underlying_type.enum_def = &enum_def; |
Wouter van Oortmerssen | a5f5001 | 2014-07-02 12:01:21 -0700 | [diff] [blame] | 739 | } else { |
Wouter van Oortmerssen | d38b9af | 2014-09-26 16:46:30 -0700 | [diff] [blame] | 740 | if (proto_mode_) { |
| 741 | enum_def.underlying_type.base_type = BASE_TYPE_SHORT; |
| 742 | } else { |
| 743 | // Give specialized error message, since this type spec used to |
| 744 | // be optional in the first FlatBuffers release. |
| 745 | if (!IsNext(':')) Error("must specify the underlying integer type for this" |
| 746 | " enum (e.g. \': short\', which was the default)."); |
| 747 | // Specify the integer type underlying this enum. |
| 748 | ParseType(enum_def.underlying_type); |
| 749 | if (!IsInteger(enum_def.underlying_type.base_type)) |
| 750 | Error("underlying enum type must be integral"); |
| 751 | } |
Wouter van Oortmerssen | 3fb6a86 | 2014-07-14 17:49:04 -0700 | [diff] [blame] | 752 | // Make this type refer back to the enum it was derived from. |
| 753 | enum_def.underlying_type.enum_def = &enum_def; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 754 | } |
| 755 | ParseMetaData(enum_def); |
| 756 | Expect('{'); |
| 757 | if (is_union) enum_def.vals.Add("NONE", new EnumVal("NONE", 0)); |
| 758 | do { |
| 759 | std::string name = attribute_; |
Gabriel Martinez | 730c0ca | 2014-09-24 11:46:32 -0700 | [diff] [blame] | 760 | std::vector<std::string> dc = doc_comment_; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 761 | Expect(kTokenIdentifier); |
| 762 | auto prevsize = enum_def.vals.vec.size(); |
Wouter van Oortmerssen | 127d350 | 2014-07-17 15:12:37 -0700 | [diff] [blame] | 763 | auto value = enum_def.vals.vec.size() |
| 764 | ? enum_def.vals.vec.back()->value + 1 |
| 765 | : 0; |
| 766 | auto &ev = *new EnumVal(name, value); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 767 | if (enum_def.vals.Add(name, &ev)) |
| 768 | Error("enum value already exists: " + name); |
| 769 | ev.doc_comment = dc; |
| 770 | if (is_union) { |
| 771 | ev.struct_def = LookupCreateStruct(name); |
| 772 | } |
| 773 | if (IsNext('=')) { |
| 774 | ev.value = atoi(attribute_.c_str()); |
| 775 | Expect(kTokenIntegerConstant); |
| 776 | if (prevsize && enum_def.vals.vec[prevsize - 1]->value >= ev.value) |
| 777 | Error("enum values must be specified in ascending order"); |
| 778 | } |
Wouter van Oortmerssen | d38b9af | 2014-09-26 16:46:30 -0700 | [diff] [blame] | 779 | } while (IsNext(proto_mode_ ? ';' : ',') && token_ != '}'); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 780 | Expect('}'); |
Wouter van Oortmerssen | 127d350 | 2014-07-17 15:12:37 -0700 | [diff] [blame] | 781 | if (enum_def.attributes.Lookup("bit_flags")) { |
| 782 | for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end(); |
| 783 | ++it) { |
| 784 | if (static_cast<size_t>((*it)->value) >= |
| 785 | SizeOf(enum_def.underlying_type.base_type) * 8) |
| 786 | Error("bit flag out of range of underlying integral type"); |
Wouter van Oortmerssen | 9c3de1e | 2014-07-25 15:04:35 -0700 | [diff] [blame] | 787 | (*it)->value = 1LL << (*it)->value; |
Wouter van Oortmerssen | 127d350 | 2014-07-17 15:12:37 -0700 | [diff] [blame] | 788 | } |
| 789 | } |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 790 | } |
| 791 | |
Wouter van Oortmerssen | d38b9af | 2014-09-26 16:46:30 -0700 | [diff] [blame] | 792 | StructDef &Parser::StartStruct() { |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 793 | std::string name = attribute_; |
| 794 | Expect(kTokenIdentifier); |
| 795 | auto &struct_def = *LookupCreateStruct(name); |
| 796 | if (!struct_def.predecl) Error("datatype already exists: " + name); |
| 797 | struct_def.predecl = false; |
| 798 | struct_def.name = name; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 799 | // Move this struct to the back of the vector just in case it was predeclared, |
Wouter van Oortmerssen | d38b9af | 2014-09-26 16:46:30 -0700 | [diff] [blame] | 800 | // to preserve declaration order. |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 801 | remove(structs_.vec.begin(), structs_.vec.end(), &struct_def); |
| 802 | structs_.vec.back() = &struct_def; |
Wouter van Oortmerssen | d38b9af | 2014-09-26 16:46:30 -0700 | [diff] [blame] | 803 | return struct_def; |
| 804 | } |
| 805 | |
| 806 | void Parser::ParseDecl() { |
| 807 | std::vector<std::string> dc = doc_comment_; |
| 808 | bool fixed = IsNext(kTokenStruct); |
| 809 | if (!fixed) Expect(kTokenTable); |
| 810 | auto &struct_def = StartStruct(); |
| 811 | struct_def.doc_comment = dc; |
| 812 | struct_def.fixed = fixed; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 813 | ParseMetaData(struct_def); |
| 814 | struct_def.sortbysize = |
| 815 | struct_def.attributes.Lookup("original_order") == nullptr && !fixed; |
| 816 | Expect('{'); |
| 817 | while (token_ != '}') ParseField(struct_def); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 818 | auto force_align = struct_def.attributes.Lookup("force_align"); |
| 819 | if (fixed && force_align) { |
| 820 | auto align = static_cast<size_t>(atoi(force_align->constant.c_str())); |
| 821 | if (force_align->type.base_type != BASE_TYPE_INT || |
| 822 | align < struct_def.minalign || |
| 823 | align > 256 || |
| 824 | align & (align - 1)) |
| 825 | Error("force_align must be a power of two integer ranging from the" |
| 826 | "struct\'s natural alignment to 256"); |
| 827 | struct_def.minalign = align; |
| 828 | } |
Wouter van Oortmerssen | 65cfa18 | 2014-06-23 11:34:19 -0700 | [diff] [blame] | 829 | struct_def.PadLastField(struct_def.minalign); |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 830 | // Check if this is a table that has manual id assignments |
| 831 | auto &fields = struct_def.fields.vec; |
| 832 | if (!struct_def.fixed && fields.size()) { |
Wouter van Oortmerssen | 7fcbe72 | 2014-07-08 16:35:14 -0700 | [diff] [blame] | 833 | size_t num_id_fields = 0; |
Wouter van Oortmerssen | 9140144 | 2014-07-07 17:34:23 -0700 | [diff] [blame] | 834 | for (auto it = fields.begin(); it != fields.end(); ++it) { |
| 835 | if ((*it)->attributes.Lookup("id")) num_id_fields++; |
| 836 | } |
| 837 | // If any fields have ids.. |
| 838 | if (num_id_fields) { |
| 839 | // Then all fields must have them. |
| 840 | if (num_id_fields != fields.size()) |
| 841 | Error("either all fields or no fields must have an 'id' attribute"); |
| 842 | // Simply sort by id, then the fields are the same as if no ids had |
| 843 | // been specified. |
| 844 | std::sort(fields.begin(), fields.end(), |
| 845 | [](const FieldDef *a, const FieldDef *b) -> bool { |
| 846 | auto a_id = atoi(a->attributes.Lookup("id")->constant.c_str()); |
| 847 | auto b_id = atoi(b->attributes.Lookup("id")->constant.c_str()); |
| 848 | return a_id < b_id; |
| 849 | }); |
| 850 | // Verify we have a contiguous set, and reassign vtable offsets. |
| 851 | for (int i = 0; i < static_cast<int>(fields.size()); i++) { |
| 852 | if (i != atoi(fields[i]->attributes.Lookup("id")->constant.c_str())) |
| 853 | Error("field id\'s must be consecutive from 0, id " + |
| 854 | NumToString(i) + " missing or set twice"); |
| 855 | fields[i]->value.offset = FieldIndexToOffset(static_cast<voffset_t>(i)); |
| 856 | } |
| 857 | } |
| 858 | } |
Wouter van Oortmerssen | 541b067 | 2014-08-21 15:02:15 -0700 | [diff] [blame] | 859 | // Check that no identifiers clash with auto generated fields. |
| 860 | // This is not an ideal situation, but should occur very infrequently, |
| 861 | // and allows us to keep using very readable names for type & length fields |
| 862 | // without inducing compile errors. |
| 863 | auto CheckClash = [&fields, &struct_def](const char *suffix, |
| 864 | BaseType basetype) { |
| 865 | auto len = strlen(suffix); |
| 866 | for (auto it = fields.begin(); it != fields.end(); ++it) { |
| 867 | auto &name = (*it)->name; |
| 868 | if (name.length() > len && |
| 869 | name.compare(name.length() - len, len, suffix) == 0 && |
| 870 | (*it)->value.type.base_type != BASE_TYPE_UTYPE) { |
| 871 | auto field = struct_def.fields.Lookup( |
| 872 | name.substr(0, name.length() - len)); |
| 873 | if (field && field->value.type.base_type == basetype) |
| 874 | Error("Field " + name + |
| 875 | " would clash with generated functions for field " + |
| 876 | field->name); |
| 877 | } |
| 878 | } |
| 879 | }; |
| 880 | CheckClash("_type", BASE_TYPE_UNION); |
| 881 | CheckClash("Type", BASE_TYPE_UNION); |
| 882 | CheckClash("_length", BASE_TYPE_VECTOR); |
| 883 | CheckClash("Length", BASE_TYPE_VECTOR); |
Wouter van Oortmerssen | 65cfa18 | 2014-06-23 11:34:19 -0700 | [diff] [blame] | 884 | Expect('}'); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 885 | } |
| 886 | |
| 887 | bool Parser::SetRootType(const char *name) { |
| 888 | root_struct_def = structs_.Lookup(name); |
| 889 | return root_struct_def != nullptr; |
| 890 | } |
| 891 | |
Wouter van Oortmerssen | be894f0 | 2014-08-19 14:20:05 -0700 | [diff] [blame] | 892 | void Parser::MarkGenerated() { |
| 893 | // Since the Parser object retains definitions across files, we must |
| 894 | // ensure we only output code for definitions once, in the file they are first |
| 895 | // declared. This function marks all existing definitions as having already |
| 896 | // been generated. |
| 897 | for (auto it = enums_.vec.begin(); |
| 898 | it != enums_.vec.end(); ++it) { |
| 899 | (*it)->generated = true; |
| 900 | } |
| 901 | for (auto it = structs_.vec.begin(); |
| 902 | it != structs_.vec.end(); ++it) { |
| 903 | (*it)->generated = true; |
| 904 | } |
| 905 | } |
| 906 | |
Wouter van Oortmerssen | d38b9af | 2014-09-26 16:46:30 -0700 | [diff] [blame] | 907 | void Parser::ParseNamespace() { |
| 908 | Next(); |
| 909 | auto ns = new Namespace(); |
| 910 | namespaces_.push_back(ns); |
| 911 | for (;;) { |
| 912 | ns->components.push_back(attribute_); |
| 913 | Expect(kTokenIdentifier); |
| 914 | if (!IsNext('.')) break; |
| 915 | } |
| 916 | Expect(';'); |
| 917 | } |
| 918 | |
| 919 | // Best effort parsing of .proto declarations, with the aim to turn them |
| 920 | // in the closest corresponding FlatBuffer equivalent. |
| 921 | // We parse everything as identifiers instead of keywords, since we don't |
| 922 | // want protobuf keywords to become invalid identifiers in FlatBuffers. |
| 923 | void Parser::ParseProtoDecl() { |
| 924 | if (attribute_ == "package") { |
| 925 | // These are identical in syntax to FlatBuffer's namespace decl. |
| 926 | ParseNamespace(); |
| 927 | } else if (attribute_ == "message") { |
| 928 | Next(); |
| 929 | auto &struct_def = StartStruct(); |
| 930 | Expect('{'); |
| 931 | while (token_ != '}') { |
| 932 | // Parse the qualifier. |
| 933 | bool required = false; |
| 934 | bool repeated = false; |
| 935 | if (attribute_ == "optional") { |
| 936 | // This is the default. |
| 937 | } else if (attribute_ == "required") { |
| 938 | required = true; |
| 939 | } else if (attribute_ == "repeated") { |
| 940 | repeated = true; |
| 941 | } else { |
| 942 | Error("expecting optional/required/repeated, got: " + attribute_); |
| 943 | } |
| 944 | Type type = ParseTypeFromProtoType(); |
| 945 | // Repeated elements get mapped to a vector. |
| 946 | if (repeated) { |
| 947 | type.element = type.base_type; |
| 948 | type.base_type = BASE_TYPE_VECTOR; |
| 949 | } |
| 950 | std::string name = attribute_; |
| 951 | Expect(kTokenIdentifier); |
| 952 | // Parse the field id. Since we're just translating schemas, not |
| 953 | // any kind of binary compatibility, we can safely ignore these, and |
| 954 | // assign our own. |
| 955 | Expect('='); |
| 956 | Expect(kTokenIntegerConstant); |
| 957 | auto &field = AddField(struct_def, name, type); |
| 958 | field.required = required; |
| 959 | // See if there's a default specified. |
| 960 | if (IsNext('[')) { |
| 961 | if (attribute_ != "default") Error("\'default\' expected"); |
| 962 | Next(); |
| 963 | Expect('='); |
| 964 | field.value.constant = attribute_; |
| 965 | Next(); |
| 966 | Expect(']'); |
| 967 | } |
| 968 | Expect(';'); |
| 969 | } |
| 970 | Next(); |
| 971 | } else if (attribute_ == "enum") { |
| 972 | // These are almost the same, just with different terminator: |
| 973 | ParseEnum(false); |
| 974 | } else if (attribute_ == "import") { |
| 975 | Next(); |
| 976 | included_files_[attribute_] = true; |
| 977 | Expect(kTokenStringConstant); |
| 978 | Expect(';'); |
| 979 | } else if (attribute_ == "option") { // Skip these. |
| 980 | Next(); |
| 981 | Expect(kTokenIdentifier); |
| 982 | Expect('='); |
| 983 | Next(); // Any single token. |
| 984 | Expect(';'); |
| 985 | } else { |
| 986 | Error("don\'t know how to parse .proto declaration starting with " + |
| 987 | attribute_); |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | // Parse a protobuf type, and map it to the corresponding FlatBuffer one. |
| 992 | Type Parser::ParseTypeFromProtoType() { |
| 993 | Expect(kTokenIdentifier); |
| 994 | struct type_lookup { const char *proto_type; BaseType fb_type; }; |
| 995 | static type_lookup lookup[] = { |
| 996 | { "float", BASE_TYPE_FLOAT }, { "double", BASE_TYPE_DOUBLE }, |
| 997 | { "int32", BASE_TYPE_INT }, { "int64", BASE_TYPE_LONG }, |
| 998 | { "uint32", BASE_TYPE_UINT }, { "uint64", BASE_TYPE_ULONG }, |
| 999 | { "sint32", BASE_TYPE_INT }, { "sint64", BASE_TYPE_LONG }, |
| 1000 | { "fixed32", BASE_TYPE_UINT }, { "fixed64", BASE_TYPE_ULONG }, |
| 1001 | { "sfixed32", BASE_TYPE_INT }, { "sfixed64", BASE_TYPE_LONG }, |
| 1002 | { "bool", BASE_TYPE_BOOL }, |
| 1003 | { "string", BASE_TYPE_STRING }, |
| 1004 | { "bytes", BASE_TYPE_STRING }, |
| 1005 | { nullptr, BASE_TYPE_NONE } |
| 1006 | }; |
| 1007 | Type type; |
| 1008 | for (auto tl = lookup; tl->proto_type; tl++) { |
| 1009 | if (attribute_ == tl->proto_type) { |
| 1010 | type.base_type = tl->fb_type; |
| 1011 | Next(); |
| 1012 | return type; |
| 1013 | } |
| 1014 | } |
| 1015 | ParseTypeIdent(type); |
| 1016 | Expect(kTokenIdentifier); |
| 1017 | return type; |
| 1018 | } |
| 1019 | |
Wouter van Oortmerssen | 30642c5 | 2014-09-22 15:49:43 -0700 | [diff] [blame] | 1020 | bool Parser::Parse(const char *source, const char **include_paths, |
| 1021 | const char *source_filename) { |
| 1022 | if (source_filename) included_files_[source_filename] = true; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 1023 | source_ = cursor_ = source; |
| 1024 | line_ = 1; |
| 1025 | error_.clear(); |
| 1026 | builder_.Clear(); |
| 1027 | try { |
| 1028 | Next(); |
Wouter van Oortmerssen | be894f0 | 2014-08-19 14:20:05 -0700 | [diff] [blame] | 1029 | // Includes must come first: |
| 1030 | while (IsNext(kTokenInclude)) { |
| 1031 | auto name = attribute_; |
| 1032 | Expect(kTokenStringConstant); |
Wouter van Oortmerssen | be894f0 | 2014-08-19 14:20:05 -0700 | [diff] [blame] | 1033 | if (included_files_.find(name) == included_files_.end()) { |
| 1034 | // We found an include file that we have not parsed yet. |
| 1035 | // Load it and parse it. |
| 1036 | std::string contents; |
Wouter van Oortmerssen | e57b86b | 2014-09-11 17:13:21 -0700 | [diff] [blame] | 1037 | if (!include_paths) { |
| 1038 | const char *current_directory[] = { "", nullptr }; |
| 1039 | include_paths = current_directory; |
| 1040 | } |
| 1041 | for (auto paths = include_paths; paths && *paths; paths++) { |
| 1042 | auto filepath = flatbuffers::ConCatPathFileName(*paths, name); |
| 1043 | if(LoadFile(filepath.c_str(), true, &contents)) break; |
| 1044 | } |
| 1045 | if (contents.empty()) |
Wouter van Oortmerssen | be894f0 | 2014-08-19 14:20:05 -0700 | [diff] [blame] | 1046 | Error("unable to load include file: " + name); |
Wouter van Oortmerssen | e57b86b | 2014-09-11 17:13:21 -0700 | [diff] [blame] | 1047 | included_files_[name] = true; |
| 1048 | if (!Parse(contents.c_str(), include_paths)) { |
| 1049 | // Any errors, we're done. |
| 1050 | return false; |
| 1051 | } |
Wouter van Oortmerssen | be894f0 | 2014-08-19 14:20:05 -0700 | [diff] [blame] | 1052 | // We do not want to output code for any included files: |
| 1053 | MarkGenerated(); |
| 1054 | // This is the easiest way to continue this file after an include: |
| 1055 | // instead of saving and restoring all the state, we simply start the |
| 1056 | // file anew. This will cause it to encounter the same include statement |
| 1057 | // again, but this time it will skip it, because it was entered into |
| 1058 | // included_files_. |
Wouter van Oortmerssen | e57b86b | 2014-09-11 17:13:21 -0700 | [diff] [blame] | 1059 | // This is recursive, but only go as deep as the number of include |
| 1060 | // statements. |
Wouter van Oortmerssen | 85c9c83 | 2014-09-22 17:17:13 -0700 | [diff] [blame] | 1061 | return Parse(source, include_paths, source_filename); |
Wouter van Oortmerssen | be894f0 | 2014-08-19 14:20:05 -0700 | [diff] [blame] | 1062 | } |
| 1063 | Expect(';'); |
| 1064 | } |
| 1065 | // Now parse all other kinds of declarations: |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 1066 | while (token_ != kTokenEof) { |
Wouter van Oortmerssen | d38b9af | 2014-09-26 16:46:30 -0700 | [diff] [blame] | 1067 | if (proto_mode_) { |
| 1068 | ParseProtoDecl(); |
| 1069 | } else if (token_ == kTokenNameSpace) { |
| 1070 | ParseNamespace(); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 1071 | } else if (token_ == '{') { |
| 1072 | if (!root_struct_def) Error("no root type set to parse json with"); |
| 1073 | if (builder_.GetSize()) { |
| 1074 | Error("cannot have more than one json object in a file"); |
| 1075 | } |
Wouter van Oortmerssen | 09a2999 | 2014-09-04 16:31:44 -0700 | [diff] [blame] | 1076 | builder_.Finish(Offset<Table>(ParseTable(*root_struct_def)), |
| 1077 | file_identifier_.length() ? file_identifier_.c_str() : nullptr); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 1078 | } else if (token_ == kTokenEnum) { |
| 1079 | ParseEnum(false); |
| 1080 | } else if (token_ == kTokenUnion) { |
| 1081 | ParseEnum(true); |
| 1082 | } else if (token_ == kTokenRootType) { |
| 1083 | Next(); |
| 1084 | auto root_type = attribute_; |
| 1085 | Expect(kTokenIdentifier); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 1086 | if (!SetRootType(root_type.c_str())) |
| 1087 | Error("unknown root type: " + root_type); |
| 1088 | if (root_struct_def->fixed) |
| 1089 | Error("root type must be a table"); |
Wouter van Oortmerssen | 5da7bda | 2014-07-31 15:11:03 -0700 | [diff] [blame] | 1090 | Expect(';'); |
| 1091 | } else if (token_ == kTokenFileIdentifier) { |
| 1092 | Next(); |
| 1093 | file_identifier_ = attribute_; |
| 1094 | Expect(kTokenStringConstant); |
| 1095 | if (file_identifier_.length() != |
| 1096 | FlatBufferBuilder::kFileIdentifierLength) |
| 1097 | Error("file_identifier must be exactly " + |
| 1098 | NumToString(FlatBufferBuilder::kFileIdentifierLength) + |
| 1099 | " characters"); |
| 1100 | Expect(';'); |
| 1101 | } else if (token_ == kTokenFileExtension) { |
| 1102 | Next(); |
| 1103 | file_extension_ = attribute_; |
| 1104 | Expect(kTokenStringConstant); |
| 1105 | Expect(';'); |
Wouter van Oortmerssen | be894f0 | 2014-08-19 14:20:05 -0700 | [diff] [blame] | 1106 | } else if(token_ == kTokenInclude) { |
| 1107 | Error("includes must come before declarations"); |
Wouter van Oortmerssen | 0952143 | 2014-11-17 17:27:26 -0800 | [diff] [blame] | 1108 | } else if(token_ == kTokenAttribute) { |
| 1109 | Next(); |
| 1110 | auto name = attribute_; |
| 1111 | Expect(kTokenStringConstant); |
| 1112 | Expect(';'); |
| 1113 | known_attributes_.insert(name); |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 1114 | } else { |
| 1115 | ParseDecl(); |
| 1116 | } |
| 1117 | } |
| 1118 | for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) { |
| 1119 | if ((*it)->predecl) |
| 1120 | Error("type referenced but not defined: " + (*it)->name); |
| 1121 | } |
| 1122 | for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) { |
| 1123 | auto &enum_def = **it; |
| 1124 | if (enum_def.is_union) { |
| 1125 | for (auto it = enum_def.vals.vec.begin(); |
| 1126 | it != enum_def.vals.vec.end(); |
| 1127 | ++it) { |
| 1128 | auto &val = **it; |
| 1129 | if (val.struct_def && val.struct_def->fixed) |
| 1130 | Error("only tables can be union elements: " + val.name); |
| 1131 | } |
| 1132 | } |
| 1133 | } |
| 1134 | } catch (const std::string &msg) { |
Wouter van Oortmerssen | 85c9c83 | 2014-09-22 17:17:13 -0700 | [diff] [blame] | 1135 | error_ = source_filename ? AbsolutePath(source_filename) : ""; |
| 1136 | #ifdef _WIN32 |
| 1137 | error_ += "(" + NumToString(line_) + ")"; // MSVC alike |
| 1138 | #else |
| 1139 | if (source_filename) error_ += ":"; |
| 1140 | error_ += NumToString(line_) + ":0"; // gcc alike |
| 1141 | #endif |
| 1142 | error_ += ": error: " + msg; |
Wouter van Oortmerssen | 26a3073 | 2014-01-27 16:52:49 -0800 | [diff] [blame] | 1143 | return false; |
| 1144 | } |
| 1145 | assert(!struct_stack_.size()); |
| 1146 | return true; |
| 1147 | } |
| 1148 | |
| 1149 | } // namespace flatbuffers |