1 //=== JSON.cpp - JSON value, parsing and serialization - C++ -----------*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===---------------------------------------------------------------------===//
10 #include "llvm/Support/JSON.h"
11 #include "llvm/Support/Format.h"
17 Value &Object::operator[](const ObjectKey &K) {
18 return try_emplace(K, nullptr).first->getSecond();
20 Value &Object::operator[](ObjectKey &&K) {
21 return try_emplace(std::move(K), nullptr).first->getSecond();
23 Value *Object::get(StringRef K) {
29 const Value *Object::get(StringRef K) const {
35 llvm::Optional<std::nullptr_t> Object::getNull(StringRef K) const {
37 return V->getAsNull();
40 llvm::Optional<bool> Object::getBoolean(StringRef K) const {
42 return V->getAsBoolean();
45 llvm::Optional<double> Object::getNumber(StringRef K) const {
47 return V->getAsNumber();
50 llvm::Optional<int64_t> Object::getInteger(StringRef K) const {
52 return V->getAsInteger();
55 llvm::Optional<llvm::StringRef> Object::getString(StringRef K) const {
57 return V->getAsString();
60 const json::Object *Object::getObject(StringRef K) const {
62 return V->getAsObject();
65 json::Object *Object::getObject(StringRef K) {
67 return V->getAsObject();
70 const json::Array *Object::getArray(StringRef K) const {
72 return V->getAsArray();
75 json::Array *Object::getArray(StringRef K) {
77 return V->getAsArray();
80 bool operator==(const Object &LHS, const Object &RHS) {
81 if (LHS.size() != RHS.size())
83 for (const auto &L : LHS) {
84 auto R = RHS.find(L.first);
85 if (R == RHS.end() || L.second != R->second)
91 Array::Array(std::initializer_list<Value> Elements) {
92 V.reserve(Elements.size());
93 for (const Value &V : Elements) {
94 emplace_back(nullptr);
95 back().moveFrom(std::move(V));
99 Value::Value(std::initializer_list<Value> Elements)
100 : Value(json::Array(Elements)) {}
102 void Value::copyFrom(const Value &M) {
109 memcpy(Union.buffer, M.Union.buffer, sizeof(Union.buffer));
112 create<StringRef>(M.as<StringRef>());
115 create<std::string>(M.as<std::string>());
118 create<json::Object>(M.as<json::Object>());
121 create<json::Array>(M.as<json::Array>());
126 void Value::moveFrom(const Value &&M) {
133 memcpy(Union.buffer, M.Union.buffer, sizeof(Union.buffer));
136 create<StringRef>(M.as<StringRef>());
139 create<std::string>(std::move(M.as<std::string>()));
143 create<json::Object>(std::move(M.as<json::Object>()));
147 create<json::Array>(std::move(M.as<json::Array>()));
153 void Value::destroy() {
161 as<StringRef>().~StringRef();
164 as<std::string>().~basic_string();
167 as<json::Object>().~Object();
170 as<json::Array>().~Array();
175 bool operator==(const Value &L, const Value &R) {
176 if (L.kind() != R.kind())
180 return *L.getAsNull() == *R.getAsNull();
182 return *L.getAsBoolean() == *R.getAsBoolean();
184 return *L.getAsNumber() == *R.getAsNumber();
186 return *L.getAsString() == *R.getAsString();
188 return *L.getAsArray() == *R.getAsArray();
190 return *L.getAsObject() == *R.getAsObject();
192 llvm_unreachable("Unknown value kind");
196 // Simple recursive-descent JSON parser.
199 Parser(StringRef JSON)
200 : Start(JSON.begin()), P(JSON.begin()), End(JSON.end()) {}
202 bool parseValue(Value &Out);
208 return parseError("Text after end of document");
213 return std::move(*Err);
217 void eatWhitespace() {
218 while (P != End && (*P == ' ' || *P == '\r' || *P == '\n' || *P == '\t'))
222 // On invalid syntax, parseX() functions return false and set Err.
223 bool parseNumber(char First, Value &Out);
224 bool parseString(std::string &Out);
225 bool parseUnicode(std::string &Out);
226 bool parseError(const char *Msg); // always returns false
228 char next() { return P == End ? 0 : *P++; }
229 char peek() { return P == End ? 0 : *P; }
230 static bool isNumber(char C) {
231 return C == '0' || C == '1' || C == '2' || C == '3' || C == '4' ||
232 C == '5' || C == '6' || C == '7' || C == '8' || C == '9' ||
233 C == 'e' || C == 'E' || C == '+' || C == '-' || C == '.';
237 const char *Start, *P, *End;
240 bool Parser::parseValue(Value &Out) {
243 return parseError("Unexpected EOF");
244 switch (char C = next()) {
245 // Bare null/true/false are easy - first char identifies them.
248 return (next() == 'u' && next() == 'l' && next() == 'l') ||
249 parseError("Invalid JSON value (null?)");
252 return (next() == 'r' && next() == 'u' && next() == 'e') ||
253 parseError("Invalid JSON value (true?)");
256 return (next() == 'a' && next() == 'l' && next() == 's' && next() == 'e') ||
257 parseError("Invalid JSON value (false?)");
260 if (parseString(S)) {
268 Array &A = *Out.getAsArray();
275 A.emplace_back(nullptr);
276 if (!parseValue(A.back()))
286 return parseError("Expected , or ] after array element");
292 Object &O = *Out.getAsObject();
300 return parseError("Expected object key");
306 return parseError("Expected : after object key");
308 if (!parseValue(O[std::move(K)]))
318 return parseError("Expected , or } after object property");
324 return parseNumber(C, Out);
325 return parseError("Invalid JSON value");
329 bool Parser::parseNumber(char First, Value &Out) {
330 // Read the number into a string. (Must be null-terminated for strto*).
333 while (isNumber(peek()))
336 // Try first to parse as integer, and if so preserve full 64 bits.
337 // strtoll returns long long >= 64 bits, so check it's in range too.
338 auto I = std::strtoll(S.c_str(), &End, 10);
339 if (End == S.end() && I >= std::numeric_limits<int64_t>::min() &&
340 I <= std::numeric_limits<int64_t>::max()) {
344 // If it's not an integer
345 Out = std::strtod(S.c_str(), &End);
346 return End == S.end() || parseError("Invalid JSON value (number?)");
349 bool Parser::parseString(std::string &Out) {
350 // leading quote was already consumed.
351 for (char C = next(); C != '"'; C = next()) {
352 if (LLVM_UNLIKELY(P == End))
353 return parseError("Unterminated string");
354 if (LLVM_UNLIKELY((C & 0x1f) == C))
355 return parseError("Control character in string");
356 if (LLVM_LIKELY(C != '\\')) {
360 // Handle escape sequence.
361 switch (C = next()) {
383 if (!parseUnicode(Out))
387 return parseError("Invalid escape sequence");
393 static void encodeUtf8(uint32_t Rune, std::string &Out) {
395 Out.push_back(Rune & 0x7F);
396 } else if (Rune < 0x800) {
397 uint8_t FirstByte = 0xC0 | ((Rune & 0x7C0) >> 6);
398 uint8_t SecondByte = 0x80 | (Rune & 0x3F);
399 Out.push_back(FirstByte);
400 Out.push_back(SecondByte);
401 } else if (Rune < 0x10000) {
402 uint8_t FirstByte = 0xE0 | ((Rune & 0xF000) >> 12);
403 uint8_t SecondByte = 0x80 | ((Rune & 0xFC0) >> 6);
404 uint8_t ThirdByte = 0x80 | (Rune & 0x3F);
405 Out.push_back(FirstByte);
406 Out.push_back(SecondByte);
407 Out.push_back(ThirdByte);
408 } else if (Rune < 0x110000) {
409 uint8_t FirstByte = 0xF0 | ((Rune & 0x1F0000) >> 18);
410 uint8_t SecondByte = 0x80 | ((Rune & 0x3F000) >> 12);
411 uint8_t ThirdByte = 0x80 | ((Rune & 0xFC0) >> 6);
412 uint8_t FourthByte = 0x80 | (Rune & 0x3F);
413 Out.push_back(FirstByte);
414 Out.push_back(SecondByte);
415 Out.push_back(ThirdByte);
416 Out.push_back(FourthByte);
418 llvm_unreachable("Invalid codepoint");
422 // Parse a UTF-16 \uNNNN escape sequence. "\u" has already been consumed.
423 // May parse several sequential escapes to ensure proper surrogate handling.
424 // We do not use ConvertUTF.h, it can't accept and replace unpaired surrogates.
425 // These are invalid Unicode but valid JSON (RFC 8259, section 8.2).
426 bool Parser::parseUnicode(std::string &Out) {
427 // Invalid UTF is not a JSON error (RFC 8529§8.2). It gets replaced by U+FFFD.
428 auto Invalid = [&] { Out.append(/* UTF-8 */ {'\xef', '\xbf', '\xbd'}); };
429 // Decodes 4 hex digits from the stream into Out, returns false on error.
430 auto Parse4Hex = [this](uint16_t &Out) -> bool {
432 char Bytes[] = {next(), next(), next(), next()};
433 for (unsigned char C : Bytes) {
434 if (!std::isxdigit(C))
435 return parseError("Invalid \\u escape sequence");
437 Out |= (C > '9') ? (C & ~0x20) - 'A' + 10 : (C - '0');
441 uint16_t First; // UTF-16 code unit from the first \u escape.
442 if (!Parse4Hex(First))
445 // We loop to allow proper surrogate-pair error handling.
447 // Case 1: the UTF-16 code unit is already a codepoint in the BMP.
448 if (LLVM_LIKELY(First < 0xD800 || First >= 0xE000)) {
449 encodeUtf8(First, Out);
453 // Case 2: it's an (unpaired) trailing surrogate.
454 if (LLVM_UNLIKELY(First >= 0xDC00)) {
459 // Case 3: it's a leading surrogate. We expect a trailing one next.
460 // Case 3a: there's no trailing \u escape. Don't advance in the stream.
461 if (!LLVM_LIKELY(P + 2 <= End && *P == '\\' && *(P + 1) == 'u')) {
462 Invalid(); // Leading surrogate was unpaired.
467 if (!Parse4Hex(Second))
469 // Case 3b: there was another \u escape, but it wasn't a trailing surrogate.
470 if (LLVM_UNLIKELY(Second < 0xDC00 || Second >= 0xE000)) {
471 Invalid(); // Leading surrogate was unpaired.
472 First = Second; // Second escape still needs to be processed.
475 // Case 3c: a valid surrogate pair encoding an astral codepoint.
476 encodeUtf8(0x10000 | ((First - 0xD800) << 10) | (Second - 0xDC00), Out);
481 bool Parser::parseError(const char *Msg) {
483 const char *StartOfLine = Start;
484 for (const char *X = Start; X < P; ++X) {
491 llvm::make_unique<ParseError>(Msg, Line, P - StartOfLine, P - Start));
496 Expected<Value> parse(StringRef JSON) {
502 return P.takeError();
504 char ParseError::ID = 0;
506 static std::vector<const Object::value_type *> sortedElements(const Object &O) {
507 std::vector<const Object::value_type *> Elements;
508 for (const auto &E : O)
509 Elements.push_back(&E);
510 llvm::sort(Elements.begin(), Elements.end(),
511 [](const Object::value_type *L, const Object::value_type *R) {
512 return L->first < R->first;
520 static void quote(llvm::raw_ostream &OS, llvm::StringRef S) {
522 for (unsigned char C : S) {
523 if (C == 0x22 || C == 0x5C)
531 // A few characters are common enough to make short escapes worthwhile.
543 llvm::write_hex(OS, C, llvm::HexPrintStyle::Lower, 4);
550 enum IndenterAction {
557 // Prints JSON. The indenter can be used to control formatting.
558 template <typename Indenter>
559 void llvm::json::Value::print(raw_ostream &OS, const Indenter &I) const {
565 OS << (as<bool>() ? "true" : "false");
568 OS << format("%.*g", std::numeric_limits<double>::max_digits10,
575 quote(OS, as<StringRef>());
578 quote(OS, as<std::string>());
584 for (const auto *P : sortedElements(as<json::Object>())) {
592 P->second.print(OS, I);
604 for (const auto &E : as<json::Array>()) {
620 void llvm::format_provider<llvm::json::Value>::format(
621 const llvm::json::Value &E, raw_ostream &OS, StringRef Options) {
622 if (Options.empty()) {
626 unsigned IndentAmount = 0;
627 if (Options.getAsInteger(/*Radix=*/10, IndentAmount))
628 llvm_unreachable("json::Value format options should be an integer");
629 unsigned IndentLevel = 0;
630 E.print(OS, [&](IndenterAction A) {
634 OS.indent(IndentLevel);
640 IndentLevel += IndentAmount;
643 IndentLevel -= IndentAmount;
649 llvm::raw_ostream &llvm::json::operator<<(raw_ostream &OS, const Value &E) {
650 E.print(OS, [](IndenterAction A) { /*ignore*/ });