File size: 11,235 Bytes
68888be | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | #include "common/json.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
#include "common/base.h"
namespace hk {
struct JsonParser {
const char* p;
const char* end;
const char* begin;
[[noreturn]] void error(const char* what) {
HK_FAIL("JSON parse error at byte %lld: %s", (long long)(p - begin), what);
}
void skip_ws() {
while (p < end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p;
}
bool match(const char* lit) {
size_t n = strlen(lit);
if ((size_t)(end - p) >= n && memcmp(p, lit, n) == 0) {
p += n;
return true;
}
return false;
}
static void append_utf8(std::string& s, uint32_t cp) {
if (cp < 0x80) {
s += (char)cp;
} else if (cp < 0x800) {
s += (char)(0xC0 | (cp >> 6));
s += (char)(0x80 | (cp & 0x3F));
} else if (cp < 0x10000) {
s += (char)(0xE0 | (cp >> 12));
s += (char)(0x80 | ((cp >> 6) & 0x3F));
s += (char)(0x80 | (cp & 0x3F));
} else {
s += (char)(0xF0 | (cp >> 18));
s += (char)(0x80 | ((cp >> 12) & 0x3F));
s += (char)(0x80 | ((cp >> 6) & 0x3F));
s += (char)(0x80 | (cp & 0x3F));
}
}
uint32_t hex4() {
if (end - p < 4) error("short \\u escape");
uint32_t v = 0;
for (int i = 0; i < 4; ++i) {
char c = *p++;
v <<= 4;
if (c >= '0' && c <= '9') v |= (uint32_t)(c - '0');
else if (c >= 'a' && c <= 'f') v |= (uint32_t)(c - 'a' + 10);
else if (c >= 'A' && c <= 'F') v |= (uint32_t)(c - 'A' + 10);
else error("bad hex digit in \\u escape");
}
return v;
}
std::string parse_string() {
if (p >= end || *p != '"') error("expected string");
++p;
std::string s;
while (true) {
if (p >= end) error("unterminated string");
char c = *p++;
if (c == '"') break;
if (c != '\\') {
s += c;
continue;
}
if (p >= end) error("unterminated escape");
char e = *p++;
switch (e) {
case '"': s += '"'; break;
case '\\': s += '\\'; break;
case '/': s += '/'; break;
case 'b': s += '\b'; break;
case 'f': s += '\f'; break;
case 'n': s += '\n'; break;
case 'r': s += '\r'; break;
case 't': s += '\t'; break;
case 'u': {
uint32_t cp = hex4();
// surrogate pair: two \\u escapes, one code point
if (cp >= 0xD800 && cp <= 0xDBFF && end - p >= 6 && p[0] == '\\' && p[1] == 'u') {
p += 2;
uint32_t lo = hex4();
if (lo >= 0xDC00 && lo <= 0xDFFF) cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
else error("bad low surrogate");
}
append_utf8(s, cp);
break;
}
default: error("unknown escape");
}
}
return s;
}
Json parse_number() {
const char* start = p;
bool is_int = true;
if (p < end && (*p == '-' || *p == '+')) ++p;
while (p < end) {
char c = *p;
if (c >= '0' && c <= '9') {
++p;
} else if (c == '.' || c == 'e' || c == 'E' || c == '-' || c == '+') {
is_int = false;
++p;
} else {
break;
}
}
if (p == start) error("expected number");
std::string tok(start, (size_t)(p - start));
Json j;
j.type_ = Json::Num;
if (is_int && tok.size() <= 18) {
j.i64_ = strtoll(tok.c_str(), nullptr, 10);
j.num_ = (double)j.i64_;
j.is_int_ = true;
} else {
j.num_ = strtod(tok.c_str(), nullptr);
// 12.0 in a config is still an int
double r = std::floor(j.num_);
if (r == j.num_ && std::fabs(j.num_) < 9e15) {
j.i64_ = (int64_t)r;
j.is_int_ = true;
}
}
return j;
}
Json parse_value(int depth) {
if (depth > 200) error("nesting too deep");
skip_ws();
if (p >= end) error("unexpected end of input");
char c = *p;
if (c == '{') {
++p;
Json j = Json::object();
skip_ws();
if (p < end && *p == '}') {
++p;
return j;
}
while (true) {
skip_ws();
std::string key = parse_string();
skip_ws();
if (p >= end || *p != ':') error("expected ':'");
++p;
j.obj_.emplace_back(std::move(key), parse_value(depth + 1));
skip_ws();
if (p < end && *p == ',') {
++p;
continue;
}
if (p < end && *p == '}') {
++p;
break;
}
error("expected ',' or '}'");
}
return j;
}
if (c == '[') {
++p;
Json j = Json::array();
skip_ws();
if (p < end && *p == ']') {
++p;
return j;
}
while (true) {
j.arr_.push_back(parse_value(depth + 1));
skip_ws();
if (p < end && *p == ',') {
++p;
continue;
}
if (p < end && *p == ']') {
++p;
break;
}
error("expected ',' or ']'");
}
return j;
}
if (c == '"') return Json(parse_string());
if (match("true")) return Json(true);
if (match("false")) return Json(false);
if (match("null")) return Json();
// Python's json writes these for nan / inf
if (match("NaN")) return Json(std::nan(""));
if (match("Infinity")) return Json(HUGE_VAL);
if (match("-Infinity")) return Json(-HUGE_VAL);
return parse_number();
}
};
Json Json::parse(const std::string& text) {
JsonParser ps{text.data(), text.data() + text.size(), text.data()};
Json j = ps.parse_value(0);
ps.skip_ws();
if (ps.p != ps.end) ps.error("trailing characters");
return j;
}
Json Json::parse_file(const std::string& path) { return parse(read_text_file(path)); }
bool Json::as_bool() const {
HK_CHECK(type_ == Bool, "JSON value is not a bool");
return b_;
}
int64_t Json::as_int() const {
HK_CHECK(type_ == Num && is_int_, "JSON value is not an integer");
return i64_;
}
double Json::as_num() const {
HK_CHECK(type_ == Num, "JSON value is not a number");
return num_;
}
const std::string& Json::as_str() const {
HK_CHECK(type_ == Str, "JSON value is not a string");
return str_;
}
const Json* Json::find(const std::string& key) const {
if (type_ != Obj) return nullptr;
for (const auto& kv : obj_)
if (kv.first == key) return &kv.second;
return nullptr;
}
const Json& Json::at(const std::string& key) const {
const Json* j = find(key);
HK_CHECK(j != nullptr, "JSON key \"%s\" is missing", key.c_str());
return *j;
}
int64_t Json::get_int(const std::string& key, int64_t def) const {
const Json* j = find(key);
return (j && !j->is_null()) ? j->as_int() : def;
}
double Json::get_num(const std::string& key, double def) const {
const Json* j = find(key);
return (j && !j->is_null()) ? j->as_num() : def;
}
bool Json::get_bool(const std::string& key, bool def) const {
const Json* j = find(key);
return (j && !j->is_null()) ? j->as_bool() : def;
}
std::string Json::get_str(const std::string& key, const std::string& def) const {
const Json* j = find(key);
return (j && !j->is_null()) ? j->as_str() : def;
}
const Json& Json::operator[](size_t i) const {
HK_CHECK(type_ == Arr && i < arr_.size(), "JSON array index %zu out of range", i);
return arr_[i];
}
Json& Json::set(const std::string& key, Json value) {
HK_CHECK(type_ == Obj, "set() on a JSON value that is not an object");
for (auto& kv : obj_)
if (kv.first == key) {
kv.second = std::move(value);
return kv.second;
}
obj_.emplace_back(key, std::move(value));
return obj_.back().second;
}
Json& Json::push(Json value) {
HK_CHECK(type_ == Arr, "push() on a JSON value that is not an array");
arr_.push_back(std::move(value));
return arr_.back();
}
static void dump_string(std::string& out, const std::string& s) {
out += '"';
for (unsigned char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) out += strfmt("\\u%04x", c);
else out += (char)c;
}
}
out += '"';
}
void Json::dump_to(std::string& out, int indent, int depth) const {
auto newline = [&](int d) {
if (indent < 0) return;
out += '\n';
out.append((size_t)(indent * d), ' ');
};
switch (type_) {
case Null: out += "null"; break;
case Bool: out += b_ ? "true" : "false"; break;
case Num:
if (is_int_) out += strfmt("%lld", (long long)i64_);
else if (std::isfinite(num_)) out += strfmt("%.9g", num_);
else out += "null";
break;
case Str: dump_string(out, str_); break;
case Arr: {
out += '[';
// arrays of scalars stay on one line
bool scalars = true;
for (const auto& e : arr_)
if (e.type_ == Arr || e.type_ == Obj) scalars = false;
for (size_t i = 0; i < arr_.size(); ++i) {
if (i) out += indent < 0 ? "," : (scalars ? ", " : ",");
if (!scalars) newline(depth + 1);
arr_[i].dump_to(out, indent, depth + 1);
}
if (!scalars && !arr_.empty()) newline(depth);
out += ']';
break;
}
case Obj: {
out += '{';
for (size_t i = 0; i < obj_.size(); ++i) {
if (i) out += ',';
newline(depth + 1);
dump_string(out, obj_[i].first);
out += indent < 0 ? ":" : ": ";
obj_[i].second.dump_to(out, indent, depth + 1);
}
if (!obj_.empty()) newline(depth);
out += '}';
break;
}
}
}
std::string Json::dump(int indent) const {
std::string out;
dump_to(out, indent, 0);
return out;
}
} // namespace hk
|