include/brotensor/json.h
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #pragma once | ||
| 2 | |||
| 3 | // Header-only general-purpose JSON parser, shared by every library on | ||
| 4 | // brotensor: model configs (config.json, model_index.json, scheduler | ||
| 5 | // configs), HuggingFace tokenizer.json files and test fixtures. | ||
| 6 | // | ||
| 7 | // Handles nested objects, arrays, strings (with the standard | ||
| 8 | // \" \\ \/ \n \t \r \b \f \uXXXX escapes, including UTF-16 surrogate pairs), | ||
| 9 | // integers, floating-point with exponents, true, false and null. Numbers are | ||
| 10 | // stored internally as double (config files freely mix ints and floats). | ||
| 11 | // Python json's non-finite literals (Infinity, -Infinity, NaN) are accepted, | ||
| 12 | // since real model configs carry them. | ||
| 13 | // | ||
| 14 | // Recursive-descent. On malformed input, parse() throws std::runtime_error | ||
| 15 | // with a "json: ..." message that includes a byte offset. | ||
| 16 | |||
| 17 | #include <cstdint> | ||
| 18 | #include <limits> | ||
| 19 | #include <stdexcept> | ||
| 20 | #include <string> | ||
| 21 | #include <utility> | ||
| 22 | #include <vector> | ||
| 23 | |||
| 24 | namespace brotensor::json { | ||
| 25 | |||
| 26 | enum class Type { Null, Bool, Number, String, Array, Object }; | ||
| 27 | |||
| 28 | class Value { | ||
| 29 | public: | ||
| 30 | using Array = std::vector<Value>; | ||
| 31 | using Member = std::pair<std::string, Value>; | ||
| 32 | using Object = std::vector<Member>; | ||
| 33 | |||
| 34 | ✗ | Value() : type_(Type::Null) {} | |
| 35 | |||
| 36 | ✗ | static Value make_null() { return Value(); } | |
| 37 | ✗ | static Value make_bool(bool b) { Value v; v.type_ = Type::Bool; v.bool_ = b; return v; } | |
| 38 | ✗ | static Value make_number(double d) { Value v; v.type_ = Type::Number; v.num_ = d; return v; } | |
| 39 | ✗ | static Value make_string(std::string s) { Value v; v.type_ = Type::String; v.str_ = std::move(s); return v; } | |
| 40 | ✗ | static Value make_array(Array a) { Value v; v.type_ = Type::Array; v.arr_ = std::move(a); return v; } | |
| 41 | ✗ | static Value make_object(Object o) { Value v; v.type_ = Type::Object; v.obj_ = std::move(o); return v; } | |
| 42 | |||
| 43 | Type type() const { return type_; } | ||
| 44 | bool is_null() const { return type_ == Type::Null; } | ||
| 45 | bool is_bool() const { return type_ == Type::Bool; } | ||
| 46 | bool is_number() const { return type_ == Type::Number; } | ||
| 47 | bool is_string() const { return type_ == Type::String; } | ||
| 48 | bool is_array() const { return type_ == Type::Array; } | ||
| 49 | bool is_object() const { return type_ == Type::Object; } | ||
| 50 | |||
| 51 | // Throwing typed accessors. | ||
| 52 | double as_number() const { | ||
| 53 | if (type_ != Type::Number) throw std::runtime_error("json: value is not a number"); | ||
| 54 | return num_; | ||
| 55 | } | ||
| 56 | bool as_bool() const { | ||
| 57 | if (type_ != Type::Bool) throw std::runtime_error("json: value is not a bool"); | ||
| 58 | return bool_; | ||
| 59 | } | ||
| 60 | const std::string& as_string() const { | ||
| 61 | if (type_ != Type::String) throw std::runtime_error("json: value is not a string"); | ||
| 62 | return str_; | ||
| 63 | } | ||
| 64 | const Array& as_array() const { | ||
| 65 | if (type_ != Type::Array) throw std::runtime_error("json: value is not an array"); | ||
| 66 | return arr_; | ||
| 67 | } | ||
| 68 | const Object& as_object() const { | ||
| 69 | if (type_ != Type::Object) throw std::runtime_error("json: value is not an object"); | ||
| 70 | return obj_; | ||
| 71 | } | ||
| 72 | |||
| 73 | // Object lookup. | ||
| 74 | bool contains(const std::string& key) const { return find(key) != nullptr; } | ||
| 75 | |||
| 76 | const Value* find(const std::string& key) const { | ||
| 77 | if (type_ != Type::Object) return nullptr; | ||
| 78 | for (const auto& m : obj_) { | ||
| 79 | if (m.first == key) return &m.second; | ||
| 80 | } | ||
| 81 | return nullptr; | ||
| 82 | } | ||
| 83 | const Value& at(const std::string& key) const { | ||
| 84 | const Value* v = find(key); | ||
| 85 | if (!v) throw std::runtime_error("json: missing key '" + key + "'"); | ||
| 86 | return *v; | ||
| 87 | } | ||
| 88 | |||
| 89 | // Convenience getters with defaults. A key that is absent OR explicitly | ||
| 90 | // JSON-null returns the default. | ||
| 91 | int get_int(const std::string& key, int dflt) const { | ||
| 92 | const Value* v = find(key); | ||
| 93 | if (!v || v->is_null()) return dflt; | ||
| 94 | return static_cast<int>(v->as_number()); | ||
| 95 | } | ||
| 96 | float get_float(const std::string& key, float dflt) const { | ||
| 97 | const Value* v = find(key); | ||
| 98 | if (!v || v->is_null()) return dflt; | ||
| 99 | return static_cast<float>(v->as_number()); | ||
| 100 | } | ||
| 101 | bool get_bool(const std::string& key, bool dflt) const { | ||
| 102 | const Value* v = find(key); | ||
| 103 | if (!v || v->is_null()) return dflt; | ||
| 104 | return v->as_bool(); | ||
| 105 | } | ||
| 106 | std::string get_string(const std::string& key, const std::string& dflt) const { | ||
| 107 | const Value* v = find(key); | ||
| 108 | if (!v || v->is_null()) return dflt; | ||
| 109 | return v->as_string(); | ||
| 110 | } | ||
| 111 | std::vector<int> get_int_array(const std::string& key, | ||
| 112 | const std::vector<int>& dflt) const { | ||
| 113 | const Value* v = find(key); | ||
| 114 | if (!v || v->is_null()) return dflt; | ||
| 115 | const Array& a = v->as_array(); | ||
| 116 | std::vector<int> out; | ||
| 117 | out.reserve(a.size()); | ||
| 118 | for (const auto& e : a) out.push_back(static_cast<int>(e.as_number())); | ||
| 119 | return out; | ||
| 120 | } | ||
| 121 | |||
| 122 | private: | ||
| 123 | Type type_; | ||
| 124 | ✗ | bool bool_ = false; | |
| 125 | ✗ | double num_ = 0.0; | |
| 126 | std::string str_; | ||
| 127 | Array arr_; | ||
| 128 | Object obj_; | ||
| 129 | }; | ||
| 130 | |||
| 131 | namespace detail { | ||
| 132 | |||
| 133 | // Recursive-descent parser over a contiguous text buffer. | ||
| 134 | class Parser { | ||
| 135 | public: | ||
| 136 | 2 | explicit Parser(const std::string& text) | |
| 137 | 3 | : begin_(text.data()), p_(text.data()), end_(text.data() + text.size()) {} | |
| 138 | |||
| 139 | ✗ | Value parse_document() { | |
| 140 | ✗ | skip_ws(); | |
| 141 | ✗ | Value v = parse_value(); | |
| 142 | ✗ | skip_ws(); | |
| 143 | ✗ | if (p_ != end_) fail("trailing characters after document"); | |
| 144 | ✗ | return v; | |
| 145 | ✗ | } | |
| 146 | |||
| 147 | private: | ||
| 148 | const char* begin_; | ||
| 149 | const char* p_; | ||
| 150 | const char* end_; | ||
| 151 | 1 | int depth_ = 0; | |
| 152 | static constexpr int kMaxDepth = 256; | ||
| 153 | |||
| 154 | struct DepthGuard { | ||
| 155 | int& d; | ||
| 156 | 514 | explicit DepthGuard(Parser& ps) : d(ps.depth_) { | |
| 157 | 257 | if (++d > kMaxDepth) ps.fail("maximum nesting depth exceeded"); | |
| 158 | 514 | } | |
| 159 | 512 | ~DepthGuard() { --d; } | |
| 160 | }; | ||
| 161 | |||
| 162 | 1 | [[noreturn]] void fail(const std::string& msg) const { | |
| 163 | 2 | throw std::runtime_error("json: " + msg + " at offset " | |
| 164 | 1 | + std::to_string(p_ - begin_)); | |
| 165 | 1 | } | |
| 166 | |||
| 167 | 514 | void skip_ws() { | |
| 168 | 1028 | while (p_ < end_ && | |
| 169 | 514 | (*p_ == ' ' || *p_ == '\t' || *p_ == '\n' || *p_ == '\r')) { | |
| 170 | ✗ | ++p_; | |
| 171 | } | ||
| 172 | 514 | } | |
| 173 | |||
| 174 | 256 | char peek() const { | |
| 175 | 256 | if (p_ >= end_) return '\0'; | |
| 176 | 256 | return *p_; | |
| 177 | 256 | } | |
| 178 | |||
| 179 | 257 | Value parse_value() { | |
| 180 | 257 | skip_ws(); | |
| 181 | 257 | if (p_ >= end_) fail("unexpected end of input"); | |
| 182 | 257 | switch (*p_) { | |
| 183 | ✗ | case '{': return parse_object(); | |
| 184 | 257 | case '[': return parse_array(); | |
| 185 | ✗ | case '"': return Value::make_string(parse_string()); | |
| 186 | ✗ | case 't': case 'f': return parse_bool(); | |
| 187 | ✗ | case 'n': return parse_null(); | |
| 188 | // Non-finite literals as emitted by Python's json (and therefore by | ||
| 189 | // diffusers config files): Infinity / -Infinity / NaN. RFC 8259 | ||
| 190 | // forbids them, but real Sana scheduler configs carry | ||
| 191 | // "lambda_min_clipped": -Infinity, so accept them. '-Infinity' is | ||
| 192 | // reached through parse_number (it starts with '-'); bare | ||
| 193 | // 'Infinity' and 'NaN' are routed here. | ||
| 194 | ✗ | case 'I': return parse_number(); // "Infinity" | |
| 195 | ✗ | case 'N': return parse_nan(); // "NaN" (note: 'n'/null is lower) | |
| 196 | default: | ||
| 197 | ✗ | if (*p_ == '-' || (*p_ >= '0' && *p_ <= '9')) { | |
| 198 | ✗ | return parse_number(); | |
| 199 | } | ||
| 200 | ✗ | fail("unexpected character"); | |
| 201 | } | ||
| 202 | 257 | } | |
| 203 | |||
| 204 | ✗ | Value parse_object() { | |
| 205 | ✗ | DepthGuard guard(*this); | |
| 206 | ✗ | ++p_; // consume '{' | |
| 207 | ✗ | Value::Object members; | |
| 208 | ✗ | skip_ws(); | |
| 209 | ✗ | if (peek() == '}') { ++p_; return Value::make_object(std::move(members)); } | |
| 210 | ✗ | while (true) { | |
| 211 | ✗ | skip_ws(); | |
| 212 | ✗ | if (peek() != '"') fail("expected object key string"); | |
| 213 | ✗ | std::string key = parse_string(); | |
| 214 | ✗ | skip_ws(); | |
| 215 | ✗ | if (peek() != ':') fail("expected ':' after object key"); | |
| 216 | ✗ | ++p_; | |
| 217 | ✗ | Value val = parse_value(); | |
| 218 | ✗ | members.emplace_back(std::move(key), std::move(val)); | |
| 219 | ✗ | skip_ws(); | |
| 220 | ✗ | char c = peek(); | |
| 221 | ✗ | if (c == ',') { ++p_; continue; } | |
| 222 | ✗ | if (c == '}') { ++p_; break; } | |
| 223 | ✗ | fail("expected ',' or '}' in object"); | |
| 224 | ✗ | } | |
| 225 | ✗ | return Value::make_object(std::move(members)); | |
| 226 | ✗ | } | |
| 227 | |||
| 228 | 256 | Value parse_array() { | |
| 229 | 256 | DepthGuard guard(*this); | |
| 230 | 256 | ++p_; // consume '[' | |
| 231 | 256 | Value::Array elems; | |
| 232 | 256 | skip_ws(); | |
| 233 | 256 | if (peek() == ']') { ++p_; return Value::make_array(std::move(elems)); } | |
| 234 | 256 | while (true) { | |
| 235 | 256 | elems.push_back(parse_value()); | |
| 236 | ✗ | skip_ws(); | |
| 237 | ✗ | char c = peek(); | |
| 238 | ✗ | if (c == ',') { ++p_; continue; } | |
| 239 | ✗ | if (c == ']') { ++p_; break; } | |
| 240 | ✗ | fail("expected ',' or ']' in array"); | |
| 241 | } | ||
| 242 | ✗ | return Value::make_array(std::move(elems)); | |
| 243 | 256 | } | |
| 244 | |||
| 245 | // Append a Unicode codepoint to `out` as UTF-8. | ||
| 246 | ✗ | static void append_utf8(uint32_t cp, std::string& out) { | |
| 247 | ✗ | if (cp <= 0x7F) { | |
| 248 | ✗ | out += static_cast<char>(cp); | |
| 249 | ✗ | } else if (cp <= 0x7FF) { | |
| 250 | ✗ | out += static_cast<char>(0xC0 | (cp >> 6)); | |
| 251 | ✗ | out += static_cast<char>(0x80 | (cp & 0x3F)); | |
| 252 | ✗ | } else if (cp <= 0xFFFF) { | |
| 253 | ✗ | out += static_cast<char>(0xE0 | (cp >> 12)); | |
| 254 | ✗ | out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F)); | |
| 255 | ✗ | out += static_cast<char>(0x80 | (cp & 0x3F)); | |
| 256 | ✗ | } else { | |
| 257 | ✗ | out += static_cast<char>(0xF0 | (cp >> 18)); | |
| 258 | ✗ | out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F)); | |
| 259 | ✗ | out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F)); | |
| 260 | ✗ | out += static_cast<char>(0x80 | (cp & 0x3F)); | |
| 261 | } | ||
| 262 | ✗ | } | |
| 263 | |||
| 264 | ✗ | uint32_t parse_hex4() { | |
| 265 | ✗ | if (end_ - p_ < 4) fail("truncated \\u escape"); | |
| 266 | ✗ | uint32_t cp = 0; | |
| 267 | ✗ | for (int i = 0; i < 4; ++i) { | |
| 268 | ✗ | char c = p_[i]; | |
| 269 | ✗ | int v = (c >= '0' && c <= '9') ? c - '0' | |
| 270 | ✗ | : (c >= 'a' && c <= 'f') ? c - 'a' + 10 | |
| 271 | ✗ | : (c >= 'A' && c <= 'F') ? c - 'A' + 10 | |
| 272 | : -1; | ||
| 273 | ✗ | if (v < 0) fail("bad hex digit in \\u escape"); | |
| 274 | ✗ | cp = (cp << 4) | static_cast<uint32_t>(v); | |
| 275 | ✗ | } | |
| 276 | ✗ | p_ += 4; | |
| 277 | ✗ | return cp; | |
| 278 | ✗ | } | |
| 279 | |||
| 280 | ✗ | std::string parse_string() { | |
| 281 | ✗ | if (peek() != '"') fail("expected string"); | |
| 282 | ✗ | ++p_; // consume opening quote | |
| 283 | ✗ | std::string out; | |
| 284 | ✗ | while (p_ < end_) { | |
| 285 | ✗ | char c = *p_; | |
| 286 | ✗ | if (c == '"') { ++p_; return out; } | |
| 287 | ✗ | if (c == '\\') { | |
| 288 | ✗ | ++p_; | |
| 289 | ✗ | if (p_ >= end_) fail("unterminated escape in string"); | |
| 290 | ✗ | char e = *p_++; | |
| 291 | ✗ | switch (e) { | |
| 292 | ✗ | case '"': out += '"'; break; | |
| 293 | ✗ | case '\\': out += '\\'; break; | |
| 294 | ✗ | case '/': out += '/'; break; | |
| 295 | ✗ | case 'n': out += '\n'; break; | |
| 296 | ✗ | case 't': out += '\t'; break; | |
| 297 | ✗ | case 'r': out += '\r'; break; | |
| 298 | ✗ | case 'b': out += '\b'; break; | |
| 299 | ✗ | case 'f': out += '\f'; break; | |
| 300 | case 'u': { | ||
| 301 | ✗ | uint32_t cp = parse_hex4(); | |
| 302 | // UTF-16 surrogate pair handling. | ||
| 303 | ✗ | if (cp >= 0xD800 && cp <= 0xDBFF) { | |
| 304 | ✗ | if (end_ - p_ >= 2 && p_[0] == '\\' && p_[1] == 'u') { | |
| 305 | ✗ | p_ += 2; | |
| 306 | ✗ | uint32_t lo = parse_hex4(); | |
| 307 | ✗ | if (lo >= 0xDC00 && lo <= 0xDFFF) { | |
| 308 | ✗ | cp = 0x10000 + ((cp - 0xD800) << 10) | |
| 309 | ✗ | + (lo - 0xDC00); | |
| 310 | ✗ | } else { | |
| 311 | // Unpaired high surrogate; emit both raw. | ||
| 312 | ✗ | append_utf8(cp, out); | |
| 313 | ✗ | cp = lo; | |
| 314 | } | ||
| 315 | ✗ | } | |
| 316 | ✗ | } | |
| 317 | ✗ | append_utf8(cp, out); | |
| 318 | ✗ | break; | |
| 319 | } | ||
| 320 | ✗ | default: fail("unsupported escape sequence"); | |
| 321 | } | ||
| 322 | ✗ | } else { | |
| 323 | ✗ | out += c; | |
| 324 | ✗ | ++p_; | |
| 325 | } | ||
| 326 | } | ||
| 327 | ✗ | fail("unterminated string"); | |
| 328 | ✗ | } | |
| 329 | |||
| 330 | // Match `lit` at the cursor and advance past it, or fail. | ||
| 331 | ✗ | void expect_literal(const char* lit) { | |
| 332 | ✗ | const std::size_t n = std::char_traits<char>::length(lit); | |
| 333 | ✗ | if (static_cast<std::size_t>(end_ - p_) < n || | |
| 334 | ✗ | std::string(p_, p_ + n) != lit) { | |
| 335 | ✗ | fail(std::string("invalid literal, expected '") + lit + "'"); | |
| 336 | } | ||
| 337 | ✗ | p_ += n; | |
| 338 | ✗ | } | |
| 339 | |||
| 340 | ✗ | Value parse_nan() { | |
| 341 | ✗ | expect_literal("NaN"); | |
| 342 | ✗ | return Value::make_number(std::numeric_limits<double>::quiet_NaN()); | |
| 343 | } | ||
| 344 | |||
| 345 | ✗ | Value parse_number() { | |
| 346 | ✗ | const char* start = p_; | |
| 347 | ✗ | const bool neg = (peek() == '-'); | |
| 348 | ✗ | if (neg) ++p_; | |
| 349 | // Python-json non-finite literal: (-)Infinity. Accept and map to ±inf. | ||
| 350 | ✗ | if (peek() == 'I') { | |
| 351 | ✗ | expect_literal("Infinity"); | |
| 352 | ✗ | return Value::make_number( | |
| 353 | ✗ | neg ? -std::numeric_limits<double>::infinity() | |
| 354 | ✗ | : std::numeric_limits<double>::infinity()); | |
| 355 | } | ||
| 356 | ✗ | if (peek() == '0') { | |
| 357 | ✗ | ++p_; | |
| 358 | ✗ | } else if (peek() >= '1' && peek() <= '9') { | |
| 359 | ✗ | while (peek() >= '0' && peek() <= '9') ++p_; | |
| 360 | ✗ | } else { | |
| 361 | ✗ | fail("invalid number"); | |
| 362 | } | ||
| 363 | ✗ | if (peek() == '.') { | |
| 364 | ✗ | ++p_; | |
| 365 | ✗ | if (!(peek() >= '0' && peek() <= '9')) fail("invalid number: digits expected after '.'"); | |
| 366 | ✗ | while (peek() >= '0' && peek() <= '9') ++p_; | |
| 367 | ✗ | } | |
| 368 | ✗ | if (peek() == 'e' || peek() == 'E') { | |
| 369 | ✗ | ++p_; | |
| 370 | ✗ | if (peek() == '+' || peek() == '-') ++p_; | |
| 371 | ✗ | if (!(peek() >= '0' && peek() <= '9')) fail("invalid number: digits expected in exponent"); | |
| 372 | ✗ | while (peek() >= '0' && peek() <= '9') ++p_; | |
| 373 | ✗ | } | |
| 374 | ✗ | std::string num(start, p_); | |
| 375 | try { | ||
| 376 | ✗ | return Value::make_number(std::stod(num)); | |
| 377 | ✗ | } catch (const std::exception&) { | |
| 378 | ✗ | fail("number out of range"); | |
| 379 | ✗ | } | |
| 380 | ✗ | } | |
| 381 | |||
| 382 | ✗ | Value parse_bool() { | |
| 383 | ✗ | if (end_ - p_ >= 4 && std::string(p_, p_ + 4) == "true") { | |
| 384 | ✗ | p_ += 4; | |
| 385 | ✗ | return Value::make_bool(true); | |
| 386 | } | ||
| 387 | ✗ | if (end_ - p_ >= 5 && std::string(p_, p_ + 5) == "false") { | |
| 388 | ✗ | p_ += 5; | |
| 389 | ✗ | return Value::make_bool(false); | |
| 390 | } | ||
| 391 | ✗ | fail("invalid literal"); | |
| 392 | ✗ | } | |
| 393 | |||
| 394 | ✗ | Value parse_null() { | |
| 395 | ✗ | if (end_ - p_ >= 4 && std::string(p_, p_ + 4) == "null") { | |
| 396 | ✗ | p_ += 4; | |
| 397 | ✗ | return Value::make_null(); | |
| 398 | } | ||
| 399 | ✗ | fail("invalid literal"); | |
| 400 | ✗ | } | |
| 401 | }; | ||
| 402 | |||
| 403 | } // namespace detail | ||
| 404 | |||
| 405 | // Parse a whole JSON document. Throws std::runtime_error on malformed input. | ||
| 406 | 1 | inline Value parse(const std::string& text) { | |
| 407 | 1 | detail::Parser parser(text); | |
| 408 | 1 | return parser.parse_document(); | |
| 409 | } | ||
| 410 | |||
| 411 | } // namespace brotensor::json | ||
| 412 |