c@75: /* Copyright (c) 2013 Dropbox, Inc.
c@75:  *
c@75:  * Permission is hereby granted, free of charge, to any person obtaining a copy
c@75:  * of this software and associated documentation files (the "Software"), to deal
c@75:  * in the Software without restriction, including without limitation the rights
c@75:  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
c@75:  * copies of the Software, and to permit persons to whom the Software is
c@75:  * furnished to do so, subject to the following conditions:
c@75:  *
c@75:  * The above copyright notice and this permission notice shall be included in
c@75:  * all copies or substantial portions of the Software.
c@75:  *
c@75:  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
c@75:  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
c@75:  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
c@75:  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
c@75:  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
c@75:  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
c@75:  * THE SOFTWARE.
c@75:  */
c@75: 
c@75: #include "json11.hpp"
c@75: #include <cassert>
c@75: #include <cmath>
c@75: #include <cstdlib>
c@75: #include <cstdio>
c@75: #include <limits>
c@75: 
c@75: namespace json11 {
c@75: 
c@75: static const int max_depth = 200;
c@75: 
c@75: using std::string;
c@75: using std::vector;
c@75: using std::map;
c@75: using std::make_shared;
c@75: using std::initializer_list;
c@75: using std::move;
c@75: 
c@75: /* * * * * * * * * * * * * * * * * * * *
c@75:  * Serialization
c@75:  */
c@75: 
c@75: static void dump(std::nullptr_t, string &out) {
c@75:     out += "null";
c@75: }
c@75: 
c@75: static void dump(double value, string &out) {
c@75:     if (std::isfinite(value)) {
c@75:         char buf[32];
c@75:         snprintf(buf, sizeof buf, "%.17g", value);
c@75:         out += buf;
c@75:     } else {
c@75:         out += "null";
c@75:     }
c@75: }
c@75: 
c@75: static void dump(int value, string &out) {
c@75:     char buf[32];
c@75:     snprintf(buf, sizeof buf, "%d", value);
c@75:     out += buf;
c@75: }
c@75: 
c@75: static void dump(bool value, string &out) {
c@75:     out += value ? "true" : "false";
c@75: }
c@75: 
c@75: static void dump(const string &value, string &out) {
c@75:     out += '"';
c@75:     for (size_t i = 0; i < value.length(); i++) {
c@75:         const char ch = value[i];
c@75:         if (ch == '\\') {
c@75:             out += "\\\\";
c@75:         } else if (ch == '"') {
c@75:             out += "\\\"";
c@75:         } else if (ch == '\b') {
c@75:             out += "\\b";
c@75:         } else if (ch == '\f') {
c@75:             out += "\\f";
c@75:         } else if (ch == '\n') {
c@75:             out += "\\n";
c@75:         } else if (ch == '\r') {
c@75:             out += "\\r";
c@75:         } else if (ch == '\t') {
c@75:             out += "\\t";
c@75:         } else if (static_cast<uint8_t>(ch) <= 0x1f) {
c@75:             char buf[8];
c@75:             snprintf(buf, sizeof buf, "\\u%04x", ch);
c@75:             out += buf;
c@75:         } else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80
c@75:                    && static_cast<uint8_t>(value[i+2]) == 0xa8) {
c@75:             out += "\\u2028";
c@75:             i += 2;
c@75:         } else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80
c@75:                    && static_cast<uint8_t>(value[i+2]) == 0xa9) {
c@75:             out += "\\u2029";
c@75:             i += 2;
c@75:         } else {
c@75:             out += ch;
c@75:         }
c@75:     }
c@75:     out += '"';
c@75: }
c@75: 
c@75: static void dump(const Json::array &values, string &out) {
c@75:     bool first = true;
c@75:     out += "[";
c@75:     for (const auto &value : values) {
c@75:         if (!first)
c@75:             out += ", ";
c@75:         value.dump(out);
c@75:         first = false;
c@75:     }
c@75:     out += "]";
c@75: }
c@75: 
c@75: static void dump(const Json::object &values, string &out) {
c@75:     bool first = true;
c@75:     out += "{";
c@75:     for (const auto &kv : values) {
c@75:         if (!first)
c@75:             out += ", ";
c@75:         dump(kv.first, out);
c@75:         out += ": ";
c@75:         kv.second.dump(out);
c@75:         first = false;
c@75:     }
c@75:     out += "}";
c@75: }
c@75: 
c@75: void Json::dump(string &out) const {
c@75:     m_ptr->dump(out);
c@75: }
c@75: 
c@75: /* * * * * * * * * * * * * * * * * * * *
c@75:  * Value wrappers
c@75:  */
c@75: 
c@75: template <Json::Type tag, typename T>
c@75: class Value : public JsonValue {
c@75: protected:
c@75: 
c@75:     // Constructors
c@75:     explicit Value(const T &value) : m_value(value) {}
c@75:     explicit Value(T &&value)      : m_value(move(value)) {}
c@75: 
c@75:     // Get type tag
c@75:     Json::Type type() const override {
c@75:         return tag;
c@75:     }
c@75: 
c@75:     // Comparisons
c@75:     bool equals(const JsonValue * other) const override {
c@75:         return m_value == static_cast<const Value<tag, T> *>(other)->m_value;
c@75:     }
c@75:     bool less(const JsonValue * other) const override {
c@75:         return m_value < static_cast<const Value<tag, T> *>(other)->m_value;
c@75:     }
c@75: 
c@75:     const T m_value;
c@75:     void dump(string &out) const override { json11::dump(m_value, out); }
c@75: };
c@75: 
c@75: class JsonDouble final : public Value<Json::NUMBER, double> {
c@75:     double number_value() const override { return m_value; }
c@75:     int int_value() const override { return static_cast<int>(m_value); }
c@75:     bool equals(const JsonValue * other) const override { return m_value == other->number_value(); }
c@75:     bool less(const JsonValue * other)   const override { return m_value <  other->number_value(); }
c@75: public:
c@75:     explicit JsonDouble(double value) : Value(value) {}
c@75: };
c@75: 
c@75: class JsonInt final : public Value<Json::NUMBER, int> {
c@75:     double number_value() const override { return m_value; }
c@75:     int int_value() const override { return m_value; }
c@75:     bool equals(const JsonValue * other) const override { return m_value == other->number_value(); }
c@75:     bool less(const JsonValue * other)   const override { return m_value <  other->number_value(); }
c@75: public:
c@75:     explicit JsonInt(int value) : Value(value) {}
c@75: };
c@75: 
c@75: class JsonBoolean final : public Value<Json::BOOL, bool> {
c@75:     bool bool_value() const override { return m_value; }
c@75: public:
c@75:     explicit JsonBoolean(bool value) : Value(value) {}
c@75: };
c@75: 
c@75: class JsonString final : public Value<Json::STRING, string> {
c@75:     const string &string_value() const override { return m_value; }
c@75: public:
c@75:     explicit JsonString(const string &value) : Value(value) {}
c@75:     explicit JsonString(string &&value)      : Value(move(value)) {}
c@75: };
c@75: 
c@75: class JsonArray final : public Value<Json::ARRAY, Json::array> {
c@75:     const Json::array &array_items() const override { return m_value; }
c@75:     const Json & operator[](size_t i) const override;
c@75: public:
c@75:     explicit JsonArray(const Json::array &value) : Value(value) {}
c@75:     explicit JsonArray(Json::array &&value)      : Value(move(value)) {}
c@75: };
c@75: 
c@75: class JsonObject final : public Value<Json::OBJECT, Json::object> {
c@75:     const Json::object &object_items() const override { return m_value; }
c@75:     const Json & operator[](const string &key) const override;
c@75: public:
c@75:     explicit JsonObject(const Json::object &value) : Value(value) {}
c@75:     explicit JsonObject(Json::object &&value)      : Value(move(value)) {}
c@75: };
c@75: 
c@75: class JsonNull final : public Value<Json::NUL, std::nullptr_t> {
c@75: public:
c@75:     JsonNull() : Value(nullptr) {}
c@75: };
c@75: 
c@75: /* * * * * * * * * * * * * * * * * * * *
c@75:  * Static globals - static-init-safe
c@75:  */
c@75: struct Statics {
c@75:     const std::shared_ptr<JsonValue> null = make_shared<JsonNull>();
c@75:     const std::shared_ptr<JsonValue> t = make_shared<JsonBoolean>(true);
c@75:     const std::shared_ptr<JsonValue> f = make_shared<JsonBoolean>(false);
c@75:     const string empty_string;
c@75:     const vector<Json> empty_vector;
c@75:     const map<string, Json> empty_map;
c@75:     Statics() {}
c@75: };
c@75: 
c@75: static const Statics & statics() {
c@75:     static const Statics s {};
c@75:     return s;
c@75: }
c@75: 
c@75: static const Json & static_null() {
c@75:     // This has to be separate, not in Statics, because Json() accesses statics().null.
c@75:     static const Json json_null;
c@75:     return json_null;
c@75: }
c@75: 
c@75: /* * * * * * * * * * * * * * * * * * * *
c@75:  * Constructors
c@75:  */
c@75: 
c@75: Json::Json() noexcept                  : m_ptr(statics().null) {}
c@75: Json::Json(std::nullptr_t) noexcept    : m_ptr(statics().null) {}
c@75: Json::Json(double value)               : m_ptr(make_shared<JsonDouble>(value)) {}
c@75: Json::Json(int value)                  : m_ptr(make_shared<JsonInt>(value)) {}
c@75: Json::Json(bool value)                 : m_ptr(value ? statics().t : statics().f) {}
c@75: Json::Json(const string &value)        : m_ptr(make_shared<JsonString>(value)) {}
c@75: Json::Json(string &&value)             : m_ptr(make_shared<JsonString>(move(value))) {}
c@75: Json::Json(const char * value)         : m_ptr(make_shared<JsonString>(value)) {}
c@75: Json::Json(const Json::array &values)  : m_ptr(make_shared<JsonArray>(values)) {}
c@75: Json::Json(Json::array &&values)       : m_ptr(make_shared<JsonArray>(move(values))) {}
c@75: Json::Json(const Json::object &values) : m_ptr(make_shared<JsonObject>(values)) {}
c@75: Json::Json(Json::object &&values)      : m_ptr(make_shared<JsonObject>(move(values))) {}
c@75: 
c@75: /* * * * * * * * * * * * * * * * * * * *
c@75:  * Accessors
c@75:  */
c@75: 
c@75: Json::Type Json::type()                           const { return m_ptr->type();         }
c@75: double Json::number_value()                       const { return m_ptr->number_value(); }
c@75: int Json::int_value()                             const { return m_ptr->int_value();    }
c@75: bool Json::bool_value()                           const { return m_ptr->bool_value();   }
c@75: const string & Json::string_value()               const { return m_ptr->string_value(); }
c@75: const vector<Json> & Json::array_items()          const { return m_ptr->array_items();  }
c@75: const map<string, Json> & Json::object_items()    const { return m_ptr->object_items(); }
c@75: const Json & Json::operator[] (size_t i)          const { return (*m_ptr)[i];           }
c@75: const Json & Json::operator[] (const string &key) const { return (*m_ptr)[key];         }
c@75: 
c@75: double                    JsonValue::number_value()              const { return 0; }
c@75: int                       JsonValue::int_value()                 const { return 0; }
c@75: bool                      JsonValue::bool_value()                const { return false; }
c@75: const string &            JsonValue::string_value()              const { return statics().empty_string; }
c@75: const vector<Json> &      JsonValue::array_items()               const { return statics().empty_vector; }
c@75: const map<string, Json> & JsonValue::object_items()              const { return statics().empty_map; }
c@75: const Json &              JsonValue::operator[] (size_t)         const { return static_null(); }
c@75: const Json &              JsonValue::operator[] (const string &) const { return static_null(); }
c@75: 
c@75: const Json & JsonObject::operator[] (const string &key) const {
c@75:     auto iter = m_value.find(key);
c@75:     return (iter == m_value.end()) ? static_null() : iter->second;
c@75: }
c@75: const Json & JsonArray::operator[] (size_t i) const {
c@75:     if (i >= m_value.size()) return static_null();
c@75:     else return m_value[i];
c@75: }
c@75: 
c@75: /* * * * * * * * * * * * * * * * * * * *
c@75:  * Comparison
c@75:  */
c@75: 
c@75: bool Json::operator== (const Json &other) const {
c@75:     if (m_ptr->type() != other.m_ptr->type())
c@75:         return false;
c@75: 
c@75:     return m_ptr->equals(other.m_ptr.get());
c@75: }
c@75: 
c@75: bool Json::operator< (const Json &other) const {
c@75:     if (m_ptr->type() != other.m_ptr->type())
c@75:         return m_ptr->type() < other.m_ptr->type();
c@75: 
c@75:     return m_ptr->less(other.m_ptr.get());
c@75: }
c@75: 
c@75: /* * * * * * * * * * * * * * * * * * * *
c@75:  * Parsing
c@75:  */
c@75: 
c@75: /* esc(c)
c@75:  *
c@75:  * Format char c suitable for printing in an error message.
c@75:  */
c@75: static inline string esc(char c) {
c@75:     char buf[12];
c@75:     if (static_cast<uint8_t>(c) >= 0x20 && static_cast<uint8_t>(c) <= 0x7f) {
c@75:         snprintf(buf, sizeof buf, "'%c' (%d)", c, c);
c@75:     } else {
c@75:         snprintf(buf, sizeof buf, "(%d)", c);
c@75:     }
c@75:     return string(buf);
c@75: }
c@75: 
c@75: static inline bool in_range(long x, long lower, long upper) {
c@75:     return (x >= lower && x <= upper);
c@75: }
c@75: 
c@75: /* JsonParser
c@75:  *
c@75:  * Object that tracks all state of an in-progress parse.
c@75:  */
c@75: struct JsonParser {
c@75: 
c@75:     /* State
c@75:      */
c@75:     const string &str;
c@75:     size_t i;
c@75:     string &err;
c@75:     bool failed;
c@75:     const JsonParse strategy;
c@75: 
c@75:     /* fail(msg, err_ret = Json())
c@75:      *
c@75:      * Mark this parse as failed.
c@75:      */
c@75:     Json fail(string &&msg) {
c@75:         return fail(move(msg), Json());
c@75:     }
c@75: 
c@75:     template <typename T>
c@75:     T fail(string &&msg, const T err_ret) {
c@75:         if (!failed)
c@75:             err = std::move(msg);
c@75:         failed = true;
c@75:         return err_ret;
c@75:     }
c@75: 
c@75:     /* consume_whitespace()
c@75:      *
c@75:      * Advance until the current character is non-whitespace.
c@75:      */
c@75:     void consume_whitespace() {
c@75:         while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t')
c@75:             i++;
c@75:     }
c@75: 
c@75:     /* consume_comment()
c@75:      *
c@75:      * Advance comments (c-style inline and multiline).
c@75:      */
c@75:     bool consume_comment() {
c@75:       bool comment_found = false;
c@75:       if (str[i] == '/') {
c@75:         i++;
c@75:         if (i == str.size())
c@75:           return fail("unexpected end of input inside comment", 0);
c@75:         if (str[i] == '/') { // inline comment
c@75:           i++;
c@75:           if (i == str.size())
c@75:             return fail("unexpected end of input inside inline comment", 0);
c@75:           // advance until next line
c@75:           while (str[i] != '\n') {
c@75:             i++;
c@75:             if (i == str.size())
c@75:               return fail("unexpected end of input inside inline comment", 0);
c@75:           }
c@75:           comment_found = true;
c@75:         }
c@75:         else if (str[i] == '*') { // multiline comment
c@75:           i++;
c@75:           if (i > str.size()-2)
c@75:             return fail("unexpected end of input inside multi-line comment", 0);
c@75:           // advance until closing tokens
c@75:           while (!(str[i] == '*' && str[i+1] == '/')) {
c@75:             i++;
c@75:             if (i > str.size()-2)
c@75:               return fail(
c@75:                 "unexpected end of input inside multi-line comment", 0);
c@75:           }
c@75:           i += 2;
c@75:           if (i == str.size())
c@75:             return fail(
c@75:               "unexpected end of input inside multi-line comment", 0);
c@75:           comment_found = true;
c@75:         }
c@75:         else
c@75:           return fail("malformed comment", 0);
c@75:       }
c@75:       return comment_found;
c@75:     }
c@75: 
c@75:     /* consume_garbage()
c@75:      *
c@75:      * Advance until the current character is non-whitespace and non-comment.
c@75:      */
c@75:     void consume_garbage() {
c@75:       consume_whitespace();
c@75:       if(strategy == JsonParse::COMMENTS) {
c@75:         bool comment_found = false;
c@75:         do {
c@75:           comment_found = consume_comment();
c@75:           consume_whitespace();
c@75:         }
c@75:         while(comment_found);
c@75:       }
c@75:     }
c@75: 
c@75:     /* get_next_token()
c@75:      *
c@75:      * Return the next non-whitespace character. If the end of the input is reached,
c@75:      * flag an error and return 0.
c@75:      */
c@75:     char get_next_token() {
c@75:         consume_garbage();
c@75:         if (i == str.size())
c@75:             return fail("unexpected end of input", 0);
c@75: 
c@75:         return str[i++];
c@75:     }
c@75: 
c@75:     /* encode_utf8(pt, out)
c@75:      *
c@75:      * Encode pt as UTF-8 and add it to out.
c@75:      */
c@75:     void encode_utf8(long pt, string & out) {
c@75:         if (pt < 0)
c@75:             return;
c@75: 
c@75:         if (pt < 0x80) {
c@75:             out += static_cast<char>(pt);
c@75:         } else if (pt < 0x800) {
c@75:             out += static_cast<char>((pt >> 6) | 0xC0);
c@75:             out += static_cast<char>((pt & 0x3F) | 0x80);
c@75:         } else if (pt < 0x10000) {
c@75:             out += static_cast<char>((pt >> 12) | 0xE0);
c@75:             out += static_cast<char>(((pt >> 6) & 0x3F) | 0x80);
c@75:             out += static_cast<char>((pt & 0x3F) | 0x80);
c@75:         } else {
c@75:             out += static_cast<char>((pt >> 18) | 0xF0);
c@75:             out += static_cast<char>(((pt >> 12) & 0x3F) | 0x80);
c@75:             out += static_cast<char>(((pt >> 6) & 0x3F) | 0x80);
c@75:             out += static_cast<char>((pt & 0x3F) | 0x80);
c@75:         }
c@75:     }
c@75: 
c@75:     /* parse_string()
c@75:      *
c@75:      * Parse a string, starting at the current position.
c@75:      */
c@75:     string parse_string() {
c@75:         string out;
c@75:         long last_escaped_codepoint = -1;
c@75:         while (true) {
c@75:             if (i == str.size())
c@75:                 return fail("unexpected end of input in string", "");
c@75: 
c@75:             char ch = str[i++];
c@75: 
c@75:             if (ch == '"') {
c@75:                 encode_utf8(last_escaped_codepoint, out);
c@75:                 return out;
c@75:             }
c@75: 
c@75:             if (in_range(ch, 0, 0x1f))
c@75:                 return fail("unescaped " + esc(ch) + " in string", "");
c@75: 
c@75:             // The usual case: non-escaped characters
c@75:             if (ch != '\\') {
c@75:                 encode_utf8(last_escaped_codepoint, out);
c@75:                 last_escaped_codepoint = -1;
c@75:                 out += ch;
c@75:                 continue;
c@75:             }
c@75: 
c@75:             // Handle escapes
c@75:             if (i == str.size())
c@75:                 return fail("unexpected end of input in string", "");
c@75: 
c@75:             ch = str[i++];
c@75: 
c@75:             if (ch == 'u') {
c@75:                 // Extract 4-byte escape sequence
c@75:                 string esc = str.substr(i, 4);
c@75:                 // Explicitly check length of the substring. The following loop
c@75:                 // relies on std::string returning the terminating NUL when
c@75:                 // accessing str[length]. Checking here reduces brittleness.
c@75:                 if (esc.length() < 4) {
c@75:                     return fail("bad \\u escape: " + esc, "");
c@75:                 }
c@75:                 for (int j = 0; j < 4; j++) {
c@75:                     if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F')
c@75:                             && !in_range(esc[j], '0', '9'))
c@75:                         return fail("bad \\u escape: " + esc, "");
c@75:                 }
c@75: 
c@75:                 long codepoint = strtol(esc.data(), nullptr, 16);
c@75: 
c@75:                 // JSON specifies that characters outside the BMP shall be encoded as a pair
c@75:                 // of 4-hex-digit \u escapes encoding their surrogate pair components. Check
c@75:                 // whether we're in the middle of such a beast: the previous codepoint was an
c@75:                 // escaped lead (high) surrogate, and this is a trail (low) surrogate.
c@75:                 if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF)
c@75:                         && in_range(codepoint, 0xDC00, 0xDFFF)) {
c@75:                     // Reassemble the two surrogate pairs into one astral-plane character, per
c@75:                     // the UTF-16 algorithm.
c@75:                     encode_utf8((((last_escaped_codepoint - 0xD800) << 10)
c@75:                                  | (codepoint - 0xDC00)) + 0x10000, out);
c@75:                     last_escaped_codepoint = -1;
c@75:                 } else {
c@75:                     encode_utf8(last_escaped_codepoint, out);
c@75:                     last_escaped_codepoint = codepoint;
c@75:                 }
c@75: 
c@75:                 i += 4;
c@75:                 continue;
c@75:             }
c@75: 
c@75:             encode_utf8(last_escaped_codepoint, out);
c@75:             last_escaped_codepoint = -1;
c@75: 
c@75:             if (ch == 'b') {
c@75:                 out += '\b';
c@75:             } else if (ch == 'f') {
c@75:                 out += '\f';
c@75:             } else if (ch == 'n') {
c@75:                 out += '\n';
c@75:             } else if (ch == 'r') {
c@75:                 out += '\r';
c@75:             } else if (ch == 't') {
c@75:                 out += '\t';
c@75:             } else if (ch == '"' || ch == '\\' || ch == '/') {
c@75:                 out += ch;
c@75:             } else {
c@75:                 return fail("invalid escape character " + esc(ch), "");
c@75:             }
c@75:         }
c@75:     }
c@75: 
c@75:     /* parse_number()
c@75:      *
c@75:      * Parse a double.
c@75:      */
c@75:     Json parse_number() {
c@75:         size_t start_pos = i;
c@75: 
c@75:         if (str[i] == '-')
c@75:             i++;
c@75: 
c@75:         // Integer part
c@75:         if (str[i] == '0') {
c@75:             i++;
c@75:             if (in_range(str[i], '0', '9'))
c@75:                 return fail("leading 0s not permitted in numbers");
c@75:         } else if (in_range(str[i], '1', '9')) {
c@75:             i++;
c@75:             while (in_range(str[i], '0', '9'))
c@75:                 i++;
c@75:         } else {
c@75:             return fail("invalid " + esc(str[i]) + " in number");
c@75:         }
c@75: 
c@75:         if (str[i] != '.' && str[i] != 'e' && str[i] != 'E'
c@75:                 && (i - start_pos) <= static_cast<size_t>(std::numeric_limits<int>::digits10)) {
c@75:             return std::atoi(str.c_str() + start_pos);
c@75:         }
c@75: 
c@75:         // Decimal part
c@75:         if (str[i] == '.') {
c@75:             i++;
c@75:             if (!in_range(str[i], '0', '9'))
c@75:                 return fail("at least one digit required in fractional part");
c@75: 
c@75:             while (in_range(str[i], '0', '9'))
c@75:                 i++;
c@75:         }
c@75: 
c@75:         // Exponent part
c@75:         if (str[i] == 'e' || str[i] == 'E') {
c@75:             i++;
c@75: 
c@75:             if (str[i] == '+' || str[i] == '-')
c@75:                 i++;
c@75: 
c@75:             if (!in_range(str[i], '0', '9'))
c@75:                 return fail("at least one digit required in exponent");
c@75: 
c@75:             while (in_range(str[i], '0', '9'))
c@75:                 i++;
c@75:         }
c@75: 
c@75:         return std::strtod(str.c_str() + start_pos, nullptr);
c@75:     }
c@75: 
c@75:     /* expect(str, res)
c@75:      *
c@75:      * Expect that 'str' starts at the character that was just read. If it does, advance
c@75:      * the input and return res. If not, flag an error.
c@75:      */
c@75:     Json expect(const string &expected, Json res) {
c@75:         assert(i != 0);
c@75:         i--;
c@75:         if (str.compare(i, expected.length(), expected) == 0) {
c@75:             i += expected.length();
c@75:             return res;
c@75:         } else {
c@75:             return fail("parse error: expected " + expected + ", got " + str.substr(i, expected.length()));
c@75:         }
c@75:     }
c@75: 
c@75:     /* parse_json()
c@75:      *
c@75:      * Parse a JSON object.
c@75:      */
c@75:     Json parse_json(int depth) {
c@75:         if (depth > max_depth) {
c@75:             return fail("exceeded maximum nesting depth");
c@75:         }
c@75: 
c@75:         char ch = get_next_token();
c@75:         if (failed)
c@75:             return Json();
c@75: 
c@75:         if (ch == '-' || (ch >= '0' && ch <= '9')) {
c@75:             i--;
c@75:             return parse_number();
c@75:         }
c@75: 
c@75:         if (ch == 't')
c@75:             return expect("true", true);
c@75: 
c@75:         if (ch == 'f')
c@75:             return expect("false", false);
c@75: 
c@75:         if (ch == 'n')
c@75:             return expect("null", Json());
c@75: 
c@75:         if (ch == '"')
c@75:             return parse_string();
c@75: 
c@75:         if (ch == '{') {
c@75:             map<string, Json> data;
c@75:             ch = get_next_token();
c@75:             if (ch == '}')
c@75:                 return data;
c@75: 
c@75:             while (1) {
c@75:                 if (ch != '"')
c@75:                     return fail("expected '\"' in object, got " + esc(ch));
c@75: 
c@75:                 string key = parse_string();
c@75:                 if (failed)
c@75:                     return Json();
c@75: 
c@75:                 ch = get_next_token();
c@75:                 if (ch != ':')
c@75:                     return fail("expected ':' in object, got " + esc(ch));
c@75: 
c@75:                 data[std::move(key)] = parse_json(depth + 1);
c@75:                 if (failed)
c@75:                     return Json();
c@75: 
c@75:                 ch = get_next_token();
c@75:                 if (ch == '}')
c@75:                     break;
c@75:                 if (ch != ',')
c@75:                     return fail("expected ',' in object, got " + esc(ch));
c@75: 
c@75:                 ch = get_next_token();
c@75:             }
c@75:             return data;
c@75:         }
c@75: 
c@75:         if (ch == '[') {
c@75:             vector<Json> data;
c@75:             ch = get_next_token();
c@75:             if (ch == ']')
c@75:                 return data;
c@75: 
c@75:             while (1) {
c@75:                 i--;
c@75:                 data.push_back(parse_json(depth + 1));
c@75:                 if (failed)
c@75:                     return Json();
c@75: 
c@75:                 ch = get_next_token();
c@75:                 if (ch == ']')
c@75:                     break;
c@75:                 if (ch != ',')
c@75:                     return fail("expected ',' in list, got " + esc(ch));
c@75: 
c@75:                 ch = get_next_token();
c@75:                 (void)ch;
c@75:             }
c@75:             return data;
c@75:         }
c@75: 
c@75:         return fail("expected value, got " + esc(ch));
c@75:     }
c@75: };
c@75: 
c@75: Json Json::parse(const string &in, string &err, JsonParse strategy) {
c@75:     JsonParser parser { in, 0, err, false, strategy };
c@75:     Json result = parser.parse_json(0);
c@75: 
c@75:     // Check for any trailing garbage
c@75:     parser.consume_garbage();
c@75:     if (parser.i != in.size())
c@75:         return parser.fail("unexpected trailing " + esc(in[parser.i]));
c@75: 
c@75:     return result;
c@75: }
c@75: 
c@75: // Documented in json11.hpp
c@75: vector<Json> Json::parse_multi(const string &in,
c@75:                                string &err,
c@75:                                JsonParse strategy) {
c@75:     JsonParser parser { in, 0, err, false, strategy };
c@75: 
c@75:     vector<Json> json_vec;
c@75:     while (parser.i != in.size() && !parser.failed) {
c@75:         json_vec.push_back(parser.parse_json(0));
c@75:         // Check for another object
c@75:         parser.consume_garbage();
c@75:     }
c@75:     return json_vec;
c@75: }
c@75: 
c@75: /* * * * * * * * * * * * * * * * * * * *
c@75:  * Shape-checking
c@75:  */
c@75: 
c@75: bool Json::has_shape(const shape & types, string & err) const {
c@75:     if (!is_object()) {
c@75:         err = "expected JSON object, got " + dump();
c@75:         return false;
c@75:     }
c@75: 
c@75:     for (auto & item : types) {
c@75:         if ((*this)[item.first].type() != item.second) {
c@75:             err = "bad type for " + item.first + " in " + dump();
c@75:             return false;
c@75:         }
c@75:     }
c@75: 
c@75:     return true;
c@75: }
c@75: 
c@75: } // namespace json11