| 6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 | * copies of the Software, and to permit persons to whom the Software is |
| 8 | * furnished to do so, subject to the following conditions: |
| 9 | * |
| 10 | * The above copyright notice and this permission notice shall be included in |
| 11 | * all copies or substantial portions of the Software. |
| 12 | * |
| 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 19 | * THE SOFTWARE. |
| 20 | */ |
| 21 |
| 22 | #include "json11.hpp" |
| 23 | #include <cassert> |
| 24 | #include <cmath> |
| 25 | #include <cstdlib> |
| 26 | #include <cstdio> |
| 27 | #include <limits> |
| 28 | #include <sstream> |
| 29 | #include <locale> |
| 30 |
| 31 | namespace json11 { |
| 32 |
| 33 | static const int max_depth = 200; |
| 34 |
| 35 | using std::string; |
| 36 | using std::vector; |
| 37 | using std::map; |
| 38 | using std::make_shared; |
| 39 | using std::initializer_list; |
| 40 | using std::move; |
| 41 |
| 42 | /* Helper for representing null - just a do-nothing struct, plus comparison |
| 43 | * operators so the helpers in JsonValue work. We can't use nullptr_t because |
| 44 | * it may not be orderable. |
| 45 | */ |
| 46 | struct NullStruct { |
| 47 | bool operator==(NullStruct) const { return true; } |
| 48 | bool operator<(NullStruct) const { return false; } |
| 49 | }; |
| 50 |
| 51 | /* * * * * * * * * * * * * * * * * * * * |
| 52 | * Serialization |
| 53 | */ |
| 54 |
| 55 | static void dump(NullStruct, string &out) { |
| 56 | out += "null"; |
| 57 | } |
| 58 |
| 59 | static void dump(double value, string &out) { |
| 60 | if (std::isfinite(value)) { |
| 61 | std::ostringstream stm; |
| 62 | stm.imbue(std::locale("C")); |
| 63 | stm << value; |
| 64 | out += stm.str(); |
| 65 | } else { |
| 66 | out += "null"; |
| 67 | } |
| 68 | } |
| 69 |
| 70 | static void dump(int value, string &out) { |
| 71 | char buf[32]; |
| 72 | snprintf(buf, sizeof buf, "%d", value); |
| 73 | out += buf; |
| 74 | } |
| 75 |
| 76 | static void dump(bool value, string &out) { |
| 77 | out += value ? "true" : "false"; |
| 78 | } |
| 79 |
| 80 | static void dump(const string &value, string &out) { |
| 81 | out += '"'; |
| 82 | for (size_t i = 0; i < value.length(); i++) { |
| 83 | const char ch = value[i]; |
| 84 | if (ch == '\\') { |
| 85 | out += "\\\\"; |
| 86 | } else if (ch == '"') { |
| 87 | out += "\\\""; |
| 88 | } else if (ch == '\b') { |
| 89 | out += "\\b"; |
| 90 | } else if (ch == '\f') { |
| 91 | out += "\\f"; |
| 92 | } else if (ch == '\n') { |
| 93 | out += "\\n"; |
| 94 | } else if (ch == '\r') { |
| 95 | out += "\\r"; |
| 96 | } else if (ch == '\t') { |
| 97 | out += "\\t"; |
| 98 | } else if (static_cast<uint8_t>(ch) <= 0x1f) { |
| 99 | char buf[8]; |
| 100 | snprintf(buf, sizeof buf, "\\u%04x", ch); |
| 101 | out += buf; |
| 102 | } else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80 |
| 103 | && static_cast<uint8_t>(value[i+2]) == 0xa8) { |
| 104 | out += "\\u2028"; |
| 105 | i += 2; |
| 106 | } else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80 |
| 107 | && static_cast<uint8_t>(value[i+2]) == 0xa9) { |
| 108 | out += "\\u2029"; |
| 109 | i += 2; |
| 110 | } else { |
| 111 | out += ch; |
| 112 | } |
| 113 | } |
| 114 | out += '"'; |
| 115 | } |
| 116 |
| 117 | static void dump(const Json::array &values, string &out) { |
| 118 | bool first = true; |
| 119 | out += "["; |
| 120 | for (const auto &value : values) { |
| 121 | if (!first) |
| 122 | out += ", "; |
| 123 | value.dump(out); |
| 124 | first = false; |
| 125 | } |
| 126 | out += "]"; |
| 127 | } |
| 128 |
| 129 | static void dump(const Json::object &values, string &out) { |
| 130 | bool first = true; |
| 131 | out += "{"; |
| 132 | for (const auto &kv : values) { |
| 133 | if (!first) |
| 134 | out += ", "; |
| 135 | dump(kv.first, out); |
| 136 | out += ": "; |
| 137 | kv.second.dump(out); |
| 138 | first = false; |
| 139 | } |
| 140 | out += "}"; |
| 141 | } |
| 142 |
| 143 | void Json::dump(string &out) const { |
| 144 | m_ptr->dump(out); |
| 145 | } |
| 146 |
| 147 | /* * * * * * * * * * * * * * * * * * * * |
| 148 | * Value wrappers |
| 149 | */ |
| 150 |
| 151 | template <Json::Type tag, typename T> |
| 152 | class Value : public JsonValue { |
| 153 | protected: |
| 154 |
| 155 | // Constructors |
| 156 | explicit Value(const T &value) : m_value(value) {} |
| 157 | explicit Value(T &&value) : m_value(move(value)) {} |
| 158 |
| 159 | // Get type tag |
| 160 | Json::Type type() const override { |
| 161 | return tag; |
| 162 | } |
| 163 |
| 164 | // Comparisons |
| 165 | bool equals(const JsonValue * other) const override { |
| 166 | return m_value == static_cast<const Value<tag, T> *>(other)->m_value; |
| 167 | } |
| 168 | bool less(const JsonValue * other) const override { |
| 169 | return m_value < static_cast<const Value<tag, T> *>(other)->m_value; |
| 170 | } |
| 171 |
| 172 | const T m_value; |
| 173 | void dump(string &out) const override { json11::dump(m_value, out); } |
| 174 | }; |
| 175 |
| 176 | class JsonDouble final : public Value<Json::NUMBER, double> { |
| 177 | double number_value() const override { return m_value; } |
| 178 | int int_value() const override { return static_cast<int>(m_value); } |
| 179 | bool equals(const JsonValue * other) const override { return m_value == other->number_value(); } |
| 180 | bool less(const JsonValue * other) const override { return m_value < other->number_value(); } |
| 181 | public: |
| 182 | explicit JsonDouble(double value) : Value(value) {} |
| 183 | }; |
| 184 |
| 185 | class JsonInt final : public Value<Json::NUMBER, int> { |
| 186 | double number_value() const override { return m_value; } |
| 187 | int int_value() const override { return m_value; } |
| 188 | bool equals(const JsonValue * other) const override { return m_value == other->number_value(); } |
| 189 | bool less(const JsonValue * other) const override { return m_value < other->number_value(); } |
| 190 | public: |
| 191 | explicit JsonInt(int value) : Value(value) {} |
| 192 | }; |
| 193 |
| 194 | class JsonBoolean final : public Value<Json::BOOL, bool> { |
| 195 | bool bool_value() const override { return m_value; } |
| 196 | public: |
| 197 | explicit JsonBoolean(bool value) : Value(value) {} |
| 198 | }; |
| 199 |
| 200 | class JsonString final : public Value<Json::STRING, string> { |
| 201 | const string &string_value() const override { return m_value; } |
| 202 | public: |
| 203 | explicit JsonString(const string &value) : Value(value) {} |
| 204 | explicit JsonString(string &&value) : Value(move(value)) {} |
| 205 | }; |
| 206 |
| 207 | class JsonArray final : public Value<Json::ARRAY, Json::array> { |
| 208 | const Json::array &array_items() const override { return m_value; } |
| 209 | const Json & operator[](size_t i) const override; |
| 210 | public: |
| 211 | explicit JsonArray(const Json::array &value) : Value(value) {} |
| 212 | explicit JsonArray(Json::array &&value) : Value(move(value)) {} |
| 213 | }; |
| 214 |
| 215 | class JsonObject final : public Value<Json::OBJECT, Json::object> { |
| 216 | const Json::object &object_items() const override { return m_value; } |
| 217 | const Json & operator[](const string &key) const override; |
| 218 | public: |
| 219 | explicit JsonObject(const Json::object &value) : Value(value) {} |
| 220 | explicit JsonObject(Json::object &&value) : Value(move(value)) {} |
| 221 | }; |
| 222 |
| 223 | class JsonNull final : public Value<Json::NUL, NullStruct> { |
| 224 | public: |
| 225 | JsonNull() : Value({}) {} |
| 226 | }; |
| 227 |
| 228 | /* * * * * * * * * * * * * * * * * * * * |
| 229 | * Static globals - static-init-safe |
| 230 | */ |
| 231 | struct Statics { |
| 232 | const std::shared_ptr<JsonValue> null = make_shared<JsonNull>(); |
| 233 | const std::shared_ptr<JsonValue> t = make_shared<JsonBoolean>(true); |
| 234 | const std::shared_ptr<JsonValue> f = make_shared<JsonBoolean>(false); |
| 235 | const string empty_string; |
| 236 | const vector<Json> empty_vector; |
| 237 | const map<string, Json> empty_map; |
| 238 | Statics() {} |
| 239 | }; |
| 240 |
| 241 | static const Statics & statics() { |
| 242 | static const Statics s {}; |
| 243 | return s; |
| 244 | } |
| 245 |
| 246 | static const Json & static_null() { |
| 247 | // This has to be separate, not in Statics, because Json() accesses statics().null. |
| 248 | static const Json json_null; |
| 249 | return json_null; |
| 250 | } |
| 251 |
| 252 | /* * * * * * * * * * * * * * * * * * * * |
| 253 | * Constructors |
| 254 | */ |
| 255 |
| 256 | Json::Json() noexcept : m_ptr(statics().null) {} |
| 257 | Json::Json(std::nullptr_t) noexcept : m_ptr(statics().null) {} |
| 258 | Json::Json(double value) : m_ptr(make_shared<JsonDouble>(value)) {} |
| 259 | Json::Json(int value) : m_ptr(make_shared<JsonInt>(value)) {} |
| 260 | Json::Json(bool value) : m_ptr(value ? statics().t : statics().f) {} |
| 261 | Json::Json(const string &value) : m_ptr(make_shared<JsonString>(value)) {} |
| 262 | Json::Json(string &&value) : m_ptr(make_shared<JsonString>(move(value))) {} |
| 263 | Json::Json(const char * value) : m_ptr(make_shared<JsonString>(value)) {} |
| 264 | Json::Json(const Json::array &values) : m_ptr(make_shared<JsonArray>(values)) {} |
| 265 | Json::Json(Json::array &&values) : m_ptr(make_shared<JsonArray>(move(values))) {} |
| 266 | Json::Json(const Json::object &values) : m_ptr(make_shared<JsonObject>(values)) {} |
| 267 | Json::Json(Json::object &&values) : m_ptr(make_shared<JsonObject>(move(values))) {} |
| 268 |
| 269 | /* * * * * * * * * * * * * * * * * * * * |
| 270 | * Accessors |
| 271 | */ |
| 272 |
| 273 | Json::Type Json::type() const { return m_ptr->type(); } |
| 274 | double Json::number_value() const { return m_ptr->number_value(); } |
| 275 | int Json::int_value() const { return m_ptr->int_value(); } |
| 276 | bool Json::bool_value() const { return m_ptr->bool_value(); } |
| 277 | const string & Json::string_value() const { return m_ptr->string_value(); } |
| 278 | const vector<Json> & Json::array_items() const { return m_ptr->array_items(); } |
| 279 | const map<string, Json> & Json::object_items() const { return m_ptr->object_items(); } |
| 280 | const Json & Json::operator[] (size_t i) const { return (*m_ptr)[i]; } |
| 281 | const Json & Json::operator[] (const string &key) const { return (*m_ptr)[key]; } |
| 282 |
| 283 | double JsonValue::number_value() const { return 0; } |
| 284 | int JsonValue::int_value() const { return 0; } |
| 285 | bool JsonValue::bool_value() const { return false; } |
| 286 | const string & JsonValue::string_value() const { return statics().empty_string; } |
| 287 | const vector<Json> & JsonValue::array_items() const { return statics().empty_vector; } |
| 288 | const map<string, Json> & JsonValue::object_items() const { return statics().empty_map; } |
| 289 | const Json & JsonValue::operator[] (size_t) const { return static_null(); } |
| 290 | const Json & JsonValue::operator[] (const string &) const { return static_null(); } |
| 291 |
| 292 | const Json & JsonObject::operator[] (const string &key) const { |
| 293 | auto iter = m_value.find(key); |
| 294 | return (iter == m_value.end()) ? static_null() : iter->second; |
| 295 | } |
| 296 | const Json & JsonArray::operator[] (size_t i) const { |
| 297 | if (i >= m_value.size()) return static_null(); |
| 298 | else return m_value[i]; |
| 299 | } |
| 300 |
| 301 | /* * * * * * * * * * * * * * * * * * * * |
| 302 | * Comparison |
| 303 | */ |
| 304 |
| 305 | bool Json::operator== (const Json &other) const { |
| 306 | if (m_ptr == other.m_ptr) |
| 307 | return true; |
| 308 | if (m_ptr->type() != other.m_ptr->type()) |
| 309 | return false; |
| 310 |
| 311 | return m_ptr->equals(other.m_ptr.get()); |
| 312 | } |
| 313 |
| 314 | bool Json::operator< (const Json &other) const { |
| 315 | if (m_ptr == other.m_ptr) |
| 316 | return false; |
| 317 | if (m_ptr->type() != other.m_ptr->type()) |
| 318 | return m_ptr->type() < other.m_ptr->type(); |
| 319 |
| 320 | return m_ptr->less(other.m_ptr.get()); |
| 321 | } |
| 322 |
| 323 | /* * * * * * * * * * * * * * * * * * * * |
| 324 | * Parsing |
| 325 | */ |
| 326 |
| 327 | /* esc(c) |
| 328 | * |
| 329 | * Format char c suitable for printing in an error message. |
| 330 | */ |
| 331 | static inline string esc(char c) { |
| 332 | char buf[12]; |
| 333 | if (static_cast<uint8_t>(c) >= 0x20 && static_cast<uint8_t>(c) <= 0x7f) { |
| 334 | snprintf(buf, sizeof buf, "'%c' (%d)", c, c); |
| 335 | } else { |
| 336 | snprintf(buf, sizeof buf, "(%d)", c); |
| 337 | } |
| 338 | return string(buf); |
| 339 | } |
| 340 |
| 341 | static inline bool in_range(long x, long lower, long upper) { |
| 342 | return (x >= lower && x <= upper); |
| 343 | } |
| 344 |
| 345 | namespace { |
| 346 | /* JsonParser |
| 347 | * |
| 348 | * Object that tracks all state of an in-progress parse. |
| 349 | */ |
| 350 | struct JsonParser final { |
| 351 |
| 352 | /* State |
| 353 | */ |
| 354 | const string &str; |
| 355 | size_t i; |
| 356 | string &err; |
| 357 | bool failed; |
| 358 | const JsonParse strategy; |
| 359 |
| 360 | /* fail(msg, err_ret = Json()) |
| 361 | * |
| 362 | * Mark this parse as failed. |
| 363 | */ |
| 364 | Json fail(string &&msg) { |
| 365 | return fail(move(msg), Json()); |
| 366 | } |
| 367 |
| 368 | template <typename T> |
| 369 | T fail(string &&msg, const T err_ret) { |
| 370 | if (!failed) |
| 371 | err = std::move(msg); |
| 372 | failed = true; |
| 373 | return err_ret; |
| 374 | } |
| 375 |
| 376 | /* consume_whitespace() |
| 377 | * |
| 378 | * Advance until the current character is non-whitespace. |
| 379 | */ |
| 380 | void consume_whitespace() { |
| 381 | while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t') |
| 382 | i++; |
| 383 | } |
| 384 |
| 385 | /* consume_comment() |
| 386 | * |
| 387 | * Advance comments (c-style inline and multiline). |
| 388 | */ |
| 389 | bool consume_comment() { |
| 390 | bool comment_found = false; |
| 391 | if (str[i] == '/') { |
| 392 | i++; |
| 393 | if (i == str.size()) |
| 394 | return fail("unexpected end of input after start of comment", false); |
| 395 | if (str[i] == '/') { // inline comment |
| 396 | i++; |
| 397 | // advance until next line, or end of input |
| 398 | while (i < str.size() && str[i] != '\n') { |
| 399 | i++; |
| 400 | } |
| 401 | comment_found = true; |
| 402 | } |
| 403 | else if (str[i] == '*') { // multiline comment |
| 404 | i++; |
| 405 | if (i > str.size()-2) |
| 406 | return fail("unexpected end of input inside multi-line comment", false); |
| 407 | // advance until closing tokens |
| 408 | while (!(str[i] == '*' && str[i+1] == '/')) { |
| 409 | i++; |
| 410 | if (i > str.size()-2) |
| 411 | return fail( |
| 412 | "unexpected end of input inside multi-line comment", false); |
| 413 | } |
| 414 | i += 2; |
| 415 | comment_found = true; |
| 416 | } |
| 417 | else |
| 418 | return fail("malformed comment", false); |
| 419 | } |
| 420 | return comment_found; |
| 421 | } |
| 422 |
| 423 | /* consume_garbage() |
| 424 | * |
| 425 | * Advance until the current character is non-whitespace and non-comment. |
| 426 | */ |
| 427 | void consume_garbage() { |
| 428 | consume_whitespace(); |
| 429 | if(strategy == JsonParse::COMMENTS) { |
| 430 | bool comment_found = false; |
| 431 | do { |
| 432 | comment_found = consume_comment(); |
| 433 | if (failed) return; |
| 434 | consume_whitespace(); |
| 435 | } |
| 436 | while(comment_found); |
| 437 | } |
| 438 | } |
| 439 |
| 440 | /* get_next_token() |
| 441 | * |
| 442 | * Return the next non-whitespace character. If the end of the input is reached, |
| 443 | * flag an error and return 0. |
| 444 | */ |
| 445 | char get_next_token() { |
| 446 | consume_garbage(); |
| 447 | if (failed) return (char)0; |
| 448 | if (i == str.size()) |
| 449 | return fail("unexpected end of input", (char)0); |
| 450 |
| 451 | return str[i++]; |
| 452 | } |
| 453 |
| 454 | /* encode_utf8(pt, out) |
| 455 | * |
| 456 | * Encode pt as UTF-8 and add it to out. |
| 457 | */ |
| 458 | void encode_utf8(long pt, string & out) { |
| 459 | if (pt < 0) |
| 460 | return; |
| 461 |
| 462 | if (pt < 0x80) { |
| 463 | out += static_cast<char>(pt); |
| 464 | } else if (pt < 0x800) { |
| 465 | out += static_cast<char>((pt >> 6) | 0xC0); |
| 466 | out += static_cast<char>((pt & 0x3F) | 0x80); |
| 467 | } else if (pt < 0x10000) { |
| 468 | out += static_cast<char>((pt >> 12) | 0xE0); |
| 469 | out += static_cast<char>(((pt >> 6) & 0x3F) | 0x80); |
| 470 | out += static_cast<char>((pt & 0x3F) | 0x80); |
| 471 | } else { |
| 472 | out += static_cast<char>((pt >> 18) | 0xF0); |
| 473 | out += static_cast<char>(((pt >> 12) & 0x3F) | 0x80); |
| 474 | out += static_cast<char>(((pt >> 6) & 0x3F) | 0x80); |
| 475 | out += static_cast<char>((pt & 0x3F) | 0x80); |
| 476 | } |
| 477 | } |
| 478 |
| 479 | /* parse_string() |
| 480 | * |
| 481 | * Parse a string, starting at the current position. |
| 482 | */ |
| 483 | string parse_string() { |
| 484 | string out; |
| 485 | long last_escaped_codepoint = -1; |
| 486 | while (true) { |
| 487 | if (i == str.size()) |
| 488 | return fail("unexpected end of input in string", ""); |
| 489 |
| 490 | char ch = str[i++]; |
| 491 |
| 492 | if (ch == '"') { |
| 493 | encode_utf8(last_escaped_codepoint, out); |
| 494 | return out; |
| 495 | } |
| 496 |
| 497 | if (in_range(ch, 0, 0x1f)) |
| 498 | return fail("unescaped " + esc(ch) + " in string", ""); |
| 499 |
| 500 | // The usual case: non-escaped characters |
| 501 | if (ch != '\\') { |
| 502 | encode_utf8(last_escaped_codepoint, out); |
| 503 | last_escaped_codepoint = -1; |
| 504 | out += ch; |
| 505 | continue; |
| 506 | } |
| 507 |
| 508 | // Handle escapes |
| 509 | if (i == str.size()) |
| 510 | return fail("unexpected end of input in string", ""); |
| 511 |
| 512 | ch = str[i++]; |
| 513 |
| 514 | if (ch == 'u') { |
| 515 | // Extract 4-byte escape sequence |
| 516 | string esc = str.substr(i, 4); |
| 517 | // Explicitly check length of the substring. The following loop |
| 518 | // relies on std::string returning the terminating NUL when |
| 519 | // accessing str[length]. Checking here reduces brittleness. |
| 520 | if (esc.length() < 4) { |
| 521 | return fail("bad \\u escape: " + esc, ""); |
| 522 | } |
| 523 | for (size_t j = 0; j < 4; j++) { |
| 524 | if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F') |
| 525 | && !in_range(esc[j], '0', '9')) |
| 526 | return fail("bad \\u escape: " + esc, ""); |
| 527 | } |
| 528 |
| 529 | long codepoint = strtol(esc.data(), nullptr, 16); |
| 530 |
| 531 | // JSON specifies that characters outside the BMP shall be encoded as a pair |
| 532 | // of 4-hex-digit \u escapes encoding their surrogate pair components. Check |
| 533 | // whether we're in the middle of such a beast: the previous codepoint was an |
| 534 | // escaped lead (high) surrogate, and this is a trail (low) surrogate. |
| 535 | if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF) |
| 536 | && in_range(codepoint, 0xDC00, 0xDFFF)) { |
| 537 | // Reassemble the two surrogate pairs into one astral-plane character, per |
| 538 | // the UTF-16 algorithm. |
| 539 | encode_utf8((((last_escaped_codepoint - 0xD800) << 10) |
| 540 | | (codepoint - 0xDC00)) + 0x10000, out); |
| 541 | last_escaped_codepoint = -1; |
| 542 | } else { |
| 543 | encode_utf8(last_escaped_codepoint, out); |
| 544 | last_escaped_codepoint = codepoint; |
| 545 | } |
| 546 |
| 547 | i += 4; |
| 548 | continue; |
| 549 | } |
| 550 |
| 551 | encode_utf8(last_escaped_codepoint, out); |
| 552 | last_escaped_codepoint = -1; |
| 553 |
| 554 | if (ch == 'b') { |
| 555 | out += '\b'; |
| 556 | } else if (ch == 'f') { |
| 557 | out += '\f'; |
| 558 | } else if (ch == 'n') { |
| 559 | out += '\n'; |
| 560 | } else if (ch == 'r') { |
| 561 | out += '\r'; |
| 562 | } else if (ch == 't') { |
| 563 | out += '\t'; |
| 564 | } else if (ch == '"' || ch == '\\' || ch == '/') { |
| 565 | out += ch; |
| 566 | } else { |
| 567 | return fail("invalid escape character " + esc(ch), ""); |
| 568 | } |
| 569 | } |
| 570 | } |
| 571 |
| 572 | /* parse_number() |
| 573 | * |
| 574 | * Parse a double. |
| 575 | */ |
| 576 | Json parse_number() { |
| 577 | size_t start_pos = i; |
| 578 |
| 579 | if (str[i] == '-') |
| 580 | i++; |
| 581 |
| 582 | // Integer part |
| 583 | if (str[i] == '0') { |
| 584 | i++; |
| 585 | if (in_range(str[i], '0', '9')) |
| 586 | return fail("leading 0s not permitted in numbers"); |
| 587 | } else if (in_range(str[i], '1', '9')) { |
| 588 | i++; |
| 589 | while (in_range(str[i], '0', '9')) |
| 590 | i++; |
| 591 | } else { |
| 592 | return fail("invalid " + esc(str[i]) + " in number"); |
| 593 | } |
| 594 |
| 595 | if (str[i] != '.' && str[i] != 'e' && str[i] != 'E' |
| 596 | && (i - start_pos) <= static_cast<size_t>(std::numeric_limits<int>::digits10)) { |
| 597 | return std::atoi(str.c_str() + start_pos); |
| 598 | } |
| 599 |
| 600 | // Decimal part |
| 601 | if (str[i] == '.') { |
| 602 | i++; |
| 603 | if (!in_range(str[i], '0', '9')) |
| 604 | return fail("at least one digit required in fractional part"); |
| 605 |
| 606 | while (in_range(str[i], '0', '9')) |
| 607 | i++; |
| 608 | } |
| 609 |
| 610 | // Exponent part |
| 611 | if (str[i] == 'e' || str[i] == 'E') { |
| 612 | i++; |
| 613 |
| 614 | if (str[i] == '+' || str[i] == '-') |
| 615 | i++; |
| 616 |
| 617 | if (!in_range(str[i], '0', '9')) |
| 618 | return fail("at least one digit required in exponent"); |
| 619 |
| 620 | while (in_range(str[i], '0', '9')) |
| 621 | i++; |
| 622 | } |
| 623 |
| 624 | std::istringstream stm(std::string(str.begin()+start_pos, str.end())); |
| 625 | stm.imbue(std::locale("C")); |
| 626 | double result; |
| 627 | stm >> result; |
| 628 | return result; |
| 629 | } |
| 630 |
| 631 | /* expect(str, res) |
| 632 | * |
| 633 | * Expect that 'str' starts at the character that was just read. If it does, advance |
| 634 | * the input and return res. If not, flag an error. |
| 635 | */ |
| 636 | Json expect(const string &expected, Json res) { |
| 637 | assert(i != 0); |
| 638 | i--; |
| 639 | if (str.compare(i, expected.length(), expected) == 0) { |
| 640 | i += expected.length(); |
| 641 | return res; |
| 642 | } else { |
| 643 | return fail("parse error: expected " + expected + ", got " + str.substr(i, expected.length())); |
| 644 | } |
| 645 | } |
| 646 |
| 647 | /* parse_json() |
| 648 | * |
| 649 | * Parse a JSON object. |
| 650 | */ |
| 651 | Json parse_json(int depth) { |
| 652 | if (depth > max_depth) { |
| 653 | return fail("exceeded maximum nesting depth"); |
| 654 | } |
| 655 |
| 656 | char ch = get_next_token(); |
| 657 | if (failed) |
| 658 | return Json(); |
| 659 |
| 660 | if (ch == '-' || (ch >= '0' && ch <= '9')) { |
| 661 | i--; |
| 662 | return parse_number(); |
| 663 | } |
| 664 |
| 665 | if (ch == 't') |
| 666 | return expect("true", true); |
| 667 |
| 668 | if (ch == 'f') |
| 669 | return expect("false", false); |
| 670 |
| 671 | if (ch == 'n') |
| 672 | return expect("null", Json()); |
| 673 |
| 674 | if (ch == '"') |
| 675 | return parse_string(); |
| 676 |
| 677 | if (ch == '{') { |
| 678 | map<string, Json> data; |
| 679 | ch = get_next_token(); |
| 680 | if (ch == '}') |
| 681 | return data; |
| 682 |
| 683 | while (1) { |
| 684 | if (ch != '"') |
| 685 | return fail("expected '\"' in object, got " + esc(ch)); |
| 686 |
| 687 | string key = parse_string(); |
| 688 | if (failed) |
| 689 | return Json(); |
| 690 |
| 691 | ch = get_next_token(); |
| 692 | if (ch != ':') |
| 693 | return fail("expected ':' in object, got " + esc(ch)); |
| 694 |
| 695 | data[std::move(key)] = parse_json(depth + 1); |
| 696 | if (failed) |
| 697 | return Json(); |
| 698 |
| 699 | ch = get_next_token(); |
| 700 | if (ch == '}') |
| 701 | break; |
| 702 | if (ch != ',') |
| 703 | return fail("expected ',' in object, got " + esc(ch)); |
| 704 |
| 705 | ch = get_next_token(); |
| 706 | } |
| 707 | return data; |
| 708 | } |
| 709 |
| 710 | if (ch == '[') { |
| 711 | vector<Json> data; |
| 712 | ch = get_next_token(); |
| 713 | if (ch == ']') |
| 714 | return data; |
| 715 |
| 716 | while (1) { |
| 717 | i--; |
| 718 | data.push_back(parse_json(depth + 1)); |
| 719 | if (failed) |
| 720 | return Json(); |
| 721 |
| 722 | ch = get_next_token(); |
| 723 | if (ch == ']') |
| 724 | break; |
| 725 | if (ch != ',') |
| 726 | return fail("expected ',' in list, got " + esc(ch)); |
| 727 |
| 728 | ch = get_next_token(); |
| 729 | (void)ch; |
| 730 | } |
| 731 | return data; |
| 732 | } |
| 733 |
| 734 | return fail("expected value, got " + esc(ch)); |
| 735 | } |
| 736 | }; |
| 737 | }//namespace { |
| 738 |
| 739 | Json Json::parse(const string &in, string &err, JsonParse strategy) { |
| 740 | JsonParser parser { in, 0, err, false, strategy }; |
| 741 | Json result = parser.parse_json(0); |
| 742 |
| 743 | // Check for any trailing garbage |
| 744 | parser.consume_garbage(); |
| 745 | if (parser.failed) |
| 746 | return Json(); |
| 747 | if (parser.i != in.size()) |
| 748 | return parser.fail("unexpected trailing " + esc(in[parser.i])); |
| 749 |
| 750 | return result; |
| 751 | } |
| 752 |
| 753 | // Documented in json11.hpp |
| 754 | vector<Json> Json::parse_multi(const string &in, |
| 755 | std::string::size_type &parser_stop_pos, |
| 756 | string &err, |
| 757 | JsonParse strategy) { |
| 758 | JsonParser parser { in, 0, err, false, strategy }; |
| 759 | parser_stop_pos = 0; |
| 760 | vector<Json> json_vec; |
| 761 | while (parser.i != in.size() && !parser.failed) { |
| 762 | json_vec.push_back(parser.parse_json(0)); |
| 763 | if (parser.failed) |
| 764 | break; |
| 765 |
| 766 | // Check for another object |
| 767 | parser.consume_garbage(); |
| 768 | if (parser.failed) |
| 769 | break; |
| 770 | parser_stop_pos = parser.i; |
| 771 | } |
| 772 | return json_vec; |
| 773 | } |
| 774 |
| 775 | /* * * * * * * * * * * * * * * * * * * * |
| 776 | * Shape-checking |
| 777 | */ |
| 778 |
| 779 | bool Json::has_shape(const shape & types, string & err) const { |
| 780 | if (!is_object()) { |
| 781 | err = "expected JSON object, got " + dump(); |
| 782 | return false; |
| 783 | } |
| 784 |
| 785 | for (auto & item : types) { |
| 786 | if ((*this)[item.first].type() != item.second) { |
| 787 | err = "bad type for " + item.first + " in " + dump(); |
| 788 | return false; |
| 789 | } |
| 790 | } |
| 791 |
| 792 | return true; |
| 793 | } |
| 794 |
| 795 | } // namespace json11 |
| 796 |