1 //=== JSON.cpp - JSON value, parsing and serialization - C++ -----------*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===---------------------------------------------------------------------===// 8 9 #include "llvm/Support/JSON.h" 10 #include "llvm/ADT/STLExtras.h" 11 #include "llvm/Support/ConvertUTF.h" 12 #include "llvm/Support/Error.h" 13 #include "llvm/Support/Format.h" 14 #include "llvm/Support/raw_ostream.h" 15 #include <cctype> 16 17 namespace llvm { 18 namespace json { 19 20 Value &Object::operator[](const ObjectKey &K) { 21 return try_emplace(K, nullptr).first->getSecond(); 22 } 23 Value &Object::operator[](ObjectKey &&K) { 24 return try_emplace(std::move(K), nullptr).first->getSecond(); 25 } 26 Value *Object::get(StringRef K) { 27 auto I = find(K); 28 if (I == end()) 29 return nullptr; 30 return &I->second; 31 } 32 const Value *Object::get(StringRef K) const { 33 auto I = find(K); 34 if (I == end()) 35 return nullptr; 36 return &I->second; 37 } 38 llvm::Optional<std::nullptr_t> Object::getNull(StringRef K) const { 39 if (auto *V = get(K)) 40 return V->getAsNull(); 41 return llvm::None; 42 } 43 llvm::Optional<bool> Object::getBoolean(StringRef K) const { 44 if (auto *V = get(K)) 45 return V->getAsBoolean(); 46 return llvm::None; 47 } 48 llvm::Optional<double> Object::getNumber(StringRef K) const { 49 if (auto *V = get(K)) 50 return V->getAsNumber(); 51 return llvm::None; 52 } 53 llvm::Optional<int64_t> Object::getInteger(StringRef K) const { 54 if (auto *V = get(K)) 55 return V->getAsInteger(); 56 return llvm::None; 57 } 58 llvm::Optional<llvm::StringRef> Object::getString(StringRef K) const { 59 if (auto *V = get(K)) 60 return V->getAsString(); 61 return llvm::None; 62 } 63 const json::Object *Object::getObject(StringRef K) const { 64 if (auto *V = get(K)) 65 return V->getAsObject(); 66 return nullptr; 67 } 68 json::Object *Object::getObject(StringRef K) { 69 if (auto *V = get(K)) 70 return V->getAsObject(); 71 return nullptr; 72 } 73 const json::Array *Object::getArray(StringRef K) const { 74 if (auto *V = get(K)) 75 return V->getAsArray(); 76 return nullptr; 77 } 78 json::Array *Object::getArray(StringRef K) { 79 if (auto *V = get(K)) 80 return V->getAsArray(); 81 return nullptr; 82 } 83 bool operator==(const Object &LHS, const Object &RHS) { 84 if (LHS.size() != RHS.size()) 85 return false; 86 for (const auto &L : LHS) { 87 auto R = RHS.find(L.first); 88 if (R == RHS.end() || L.second != R->second) 89 return false; 90 } 91 return true; 92 } 93 94 Array::Array(std::initializer_list<Value> Elements) { 95 V.reserve(Elements.size()); 96 for (const Value &V : Elements) { 97 emplace_back(nullptr); 98 back().moveFrom(std::move(V)); 99 } 100 } 101 102 Value::Value(std::initializer_list<Value> Elements) 103 : Value(json::Array(Elements)) {} 104 105 void Value::copyFrom(const Value &M) { 106 Type = M.Type; 107 switch (Type) { 108 case T_Null: 109 case T_Boolean: 110 case T_Double: 111 case T_Integer: 112 memcpy(Union.buffer, M.Union.buffer, sizeof(Union.buffer)); 113 break; 114 case T_StringRef: 115 create<StringRef>(M.as<StringRef>()); 116 break; 117 case T_String: 118 create<std::string>(M.as<std::string>()); 119 break; 120 case T_Object: 121 create<json::Object>(M.as<json::Object>()); 122 break; 123 case T_Array: 124 create<json::Array>(M.as<json::Array>()); 125 break; 126 } 127 } 128 129 void Value::moveFrom(const Value &&M) { 130 Type = M.Type; 131 switch (Type) { 132 case T_Null: 133 case T_Boolean: 134 case T_Double: 135 case T_Integer: 136 memcpy(Union.buffer, M.Union.buffer, sizeof(Union.buffer)); 137 break; 138 case T_StringRef: 139 create<StringRef>(M.as<StringRef>()); 140 break; 141 case T_String: 142 create<std::string>(std::move(M.as<std::string>())); 143 M.Type = T_Null; 144 break; 145 case T_Object: 146 create<json::Object>(std::move(M.as<json::Object>())); 147 M.Type = T_Null; 148 break; 149 case T_Array: 150 create<json::Array>(std::move(M.as<json::Array>())); 151 M.Type = T_Null; 152 break; 153 } 154 } 155 156 void Value::destroy() { 157 switch (Type) { 158 case T_Null: 159 case T_Boolean: 160 case T_Double: 161 case T_Integer: 162 break; 163 case T_StringRef: 164 as<StringRef>().~StringRef(); 165 break; 166 case T_String: 167 as<std::string>().~basic_string(); 168 break; 169 case T_Object: 170 as<json::Object>().~Object(); 171 break; 172 case T_Array: 173 as<json::Array>().~Array(); 174 break; 175 } 176 } 177 178 bool operator==(const Value &L, const Value &R) { 179 if (L.kind() != R.kind()) 180 return false; 181 switch (L.kind()) { 182 case Value::Null: 183 return *L.getAsNull() == *R.getAsNull(); 184 case Value::Boolean: 185 return *L.getAsBoolean() == *R.getAsBoolean(); 186 case Value::Number: 187 // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=323 188 // The same integer must convert to the same double, per the standard. 189 // However we see 64-vs-80-bit precision comparisons with gcc-7 -O3 -m32. 190 // So we avoid floating point promotion for exact comparisons. 191 if (L.Type == Value::T_Integer || R.Type == Value::T_Integer) 192 return L.getAsInteger() == R.getAsInteger(); 193 return *L.getAsNumber() == *R.getAsNumber(); 194 case Value::String: 195 return *L.getAsString() == *R.getAsString(); 196 case Value::Array: 197 return *L.getAsArray() == *R.getAsArray(); 198 case Value::Object: 199 return *L.getAsObject() == *R.getAsObject(); 200 } 201 llvm_unreachable("Unknown value kind"); 202 } 203 204 void Path::report(llvm::StringLiteral Msg) { 205 // Walk up to the root context, and count the number of segments. 206 unsigned Count = 0; 207 const Path *P; 208 for (P = this; P->Parent != nullptr; P = P->Parent) 209 ++Count; 210 Path::Root *R = P->Seg.root(); 211 // Fill in the error message and copy the path (in reverse order). 212 R->ErrorMessage = Msg; 213 R->ErrorPath.resize(Count); 214 auto It = R->ErrorPath.begin(); 215 for (P = this; P->Parent != nullptr; P = P->Parent) 216 *It++ = P->Seg; 217 } 218 219 Error Path::Root::getError() const { 220 std::string S; 221 raw_string_ostream OS(S); 222 OS << (ErrorMessage.empty() ? "invalid JSON contents" : ErrorMessage); 223 if (ErrorPath.empty()) { 224 if (!Name.empty()) 225 OS << " when parsing " << Name; 226 } else { 227 OS << " at " << (Name.empty() ? "(root)" : Name); 228 for (const Path::Segment &S : llvm::reverse(ErrorPath)) { 229 if (S.isField()) 230 OS << '.' << S.field(); 231 else 232 OS << '[' << S.index() << ']'; 233 } 234 } 235 return createStringError(llvm::inconvertibleErrorCode(), OS.str()); 236 } 237 238 namespace { 239 240 std::vector<const Object::value_type *> sortedElements(const Object &O) { 241 std::vector<const Object::value_type *> Elements; 242 for (const auto &E : O) 243 Elements.push_back(&E); 244 llvm::sort(Elements, 245 [](const Object::value_type *L, const Object::value_type *R) { 246 return L->first < R->first; 247 }); 248 return Elements; 249 } 250 251 // Prints a one-line version of a value that isn't our main focus. 252 // We interleave writes to OS and JOS, exploiting the lack of extra buffering. 253 // This is OK as we own the implementation. 254 // FIXME: once we have a "write custom serialized value" API, use it here. 255 void abbreviate(const Value &V, OStream &JOS, raw_ostream &OS) { 256 switch (V.kind()) { 257 case Value::Array: 258 JOS.array([&] { 259 if (!V.getAsArray()->empty()) 260 OS << " ... "; 261 }); 262 break; 263 case Value::Object: 264 JOS.object([&] { 265 if (!V.getAsObject()->empty()) 266 OS << " ... "; 267 }); 268 break; 269 case Value::String: { 270 llvm::StringRef S = *V.getAsString(); 271 if (S.size() < 40) { 272 JOS.value(V); 273 } else { 274 std::string Truncated = fixUTF8(S.take_front(37)); 275 Truncated.append("..."); 276 JOS.value(Truncated); 277 } 278 break; 279 } 280 default: 281 JOS.value(V); 282 } 283 } 284 285 // Prints a semi-expanded version of a value that is our main focus. 286 // Array/Object entries are printed, but not recursively as they may be huge. 287 void abbreviateChildren(const Value &V, OStream &JOS, raw_ostream &OS) { 288 switch (V.kind()) { 289 case Value::Array: 290 JOS.array([&] { 291 for (const auto &V : *V.getAsArray()) 292 abbreviate(V, JOS, OS); 293 }); 294 break; 295 case Value::Object: 296 JOS.object([&] { 297 for (const auto *KV : sortedElements(*V.getAsObject())) { 298 JOS.attributeBegin(KV->first); 299 abbreviate(KV->second, JOS, OS); 300 JOS.attributeEnd(); 301 } 302 }); 303 break; 304 default: 305 JOS.value(V); 306 } 307 } 308 309 } // namespace 310 311 void Path::Root::printErrorContext(const Value &R, raw_ostream &OS) const { 312 OStream JOS(OS, /*IndentSize=*/2); 313 // PrintValue recurses down the path, printing the ancestors of our target. 314 // Siblings of nodes along the path are printed with abbreviate(), and the 315 // target itself is printed with the somewhat richer abbreviateChildren(). 316 // 'Recurse' is the lambda itself, to allow recursive calls. 317 auto PrintValue = [&](const Value &V, ArrayRef<Segment> Path, auto &Recurse) { 318 // Print the target node itself, with the error as a comment. 319 // Also used if we can't follow our path, e.g. it names a field that 320 // *should* exist but doesn't. 321 auto HighlightCurrent = [&] { 322 std::string Comment = "error: "; 323 Comment.append(ErrorMessage.data(), ErrorMessage.size()); 324 JOS.comment(Comment); 325 abbreviateChildren(V, JOS, OS); 326 }; 327 if (Path.empty()) // We reached our target. 328 return HighlightCurrent(); 329 const Segment &S = Path.back(); // Path is in reverse order. 330 if (S.isField()) { 331 // Current node is an object, path names a field. 332 llvm::StringRef FieldName = S.field(); 333 const Object *O = V.getAsObject(); 334 if (!O || !O->get(FieldName)) 335 return HighlightCurrent(); 336 JOS.object([&] { 337 for (const auto *KV : sortedElements(*O)) { 338 JOS.attributeBegin(KV->first); 339 if (FieldName.equals(KV->first)) 340 Recurse(KV->second, Path.drop_back(), Recurse); 341 else 342 abbreviate(KV->second, JOS, OS); 343 JOS.attributeEnd(); 344 } 345 }); 346 } else { 347 // Current node is an array, path names an element. 348 const Array *A = V.getAsArray(); 349 if (!A || S.index() >= A->size()) 350 return HighlightCurrent(); 351 JOS.array([&] { 352 unsigned Current = 0; 353 for (const auto &V : *A) { 354 if (Current++ == S.index()) 355 Recurse(V, Path.drop_back(), Recurse); 356 else 357 abbreviate(V, JOS, OS); 358 } 359 }); 360 } 361 }; 362 PrintValue(R, ErrorPath, PrintValue); 363 } 364 365 namespace { 366 // Simple recursive-descent JSON parser. 367 class Parser { 368 public: 369 Parser(StringRef JSON) 370 : Start(JSON.begin()), P(JSON.begin()), End(JSON.end()) {} 371 372 bool checkUTF8() { 373 size_t ErrOffset; 374 if (isUTF8(StringRef(Start, End - Start), &ErrOffset)) 375 return true; 376 P = Start + ErrOffset; // For line/column calculation. 377 return parseError("Invalid UTF-8 sequence"); 378 } 379 380 bool parseValue(Value &Out); 381 382 bool assertEnd() { 383 eatWhitespace(); 384 if (P == End) 385 return true; 386 return parseError("Text after end of document"); 387 } 388 389 Error takeError() { 390 assert(Err); 391 return std::move(*Err); 392 } 393 394 private: 395 void eatWhitespace() { 396 while (P != End && (*P == ' ' || *P == '\r' || *P == '\n' || *P == '\t')) 397 ++P; 398 } 399 400 // On invalid syntax, parseX() functions return false and set Err. 401 bool parseNumber(char First, Value &Out); 402 bool parseString(std::string &Out); 403 bool parseUnicode(std::string &Out); 404 bool parseError(const char *Msg); // always returns false 405 406 char next() { return P == End ? 0 : *P++; } 407 char peek() { return P == End ? 0 : *P; } 408 static bool isNumber(char C) { 409 return C == '0' || C == '1' || C == '2' || C == '3' || C == '4' || 410 C == '5' || C == '6' || C == '7' || C == '8' || C == '9' || 411 C == 'e' || C == 'E' || C == '+' || C == '-' || C == '.'; 412 } 413 414 Optional<Error> Err; 415 const char *Start, *P, *End; 416 }; 417 418 bool Parser::parseValue(Value &Out) { 419 eatWhitespace(); 420 if (P == End) 421 return parseError("Unexpected EOF"); 422 switch (char C = next()) { 423 // Bare null/true/false are easy - first char identifies them. 424 case 'n': 425 Out = nullptr; 426 return (next() == 'u' && next() == 'l' && next() == 'l') || 427 parseError("Invalid JSON value (null?)"); 428 case 't': 429 Out = true; 430 return (next() == 'r' && next() == 'u' && next() == 'e') || 431 parseError("Invalid JSON value (true?)"); 432 case 'f': 433 Out = false; 434 return (next() == 'a' && next() == 'l' && next() == 's' && next() == 'e') || 435 parseError("Invalid JSON value (false?)"); 436 case '"': { 437 std::string S; 438 if (parseString(S)) { 439 Out = std::move(S); 440 return true; 441 } 442 return false; 443 } 444 case '[': { 445 Out = Array{}; 446 Array &A = *Out.getAsArray(); 447 eatWhitespace(); 448 if (peek() == ']') { 449 ++P; 450 return true; 451 } 452 for (;;) { 453 A.emplace_back(nullptr); 454 if (!parseValue(A.back())) 455 return false; 456 eatWhitespace(); 457 switch (next()) { 458 case ',': 459 eatWhitespace(); 460 continue; 461 case ']': 462 return true; 463 default: 464 return parseError("Expected , or ] after array element"); 465 } 466 } 467 } 468 case '{': { 469 Out = Object{}; 470 Object &O = *Out.getAsObject(); 471 eatWhitespace(); 472 if (peek() == '}') { 473 ++P; 474 return true; 475 } 476 for (;;) { 477 if (next() != '"') 478 return parseError("Expected object key"); 479 std::string K; 480 if (!parseString(K)) 481 return false; 482 eatWhitespace(); 483 if (next() != ':') 484 return parseError("Expected : after object key"); 485 eatWhitespace(); 486 if (!parseValue(O[std::move(K)])) 487 return false; 488 eatWhitespace(); 489 switch (next()) { 490 case ',': 491 eatWhitespace(); 492 continue; 493 case '}': 494 return true; 495 default: 496 return parseError("Expected , or } after object property"); 497 } 498 } 499 } 500 default: 501 if (isNumber(C)) 502 return parseNumber(C, Out); 503 return parseError("Invalid JSON value"); 504 } 505 } 506 507 bool Parser::parseNumber(char First, Value &Out) { 508 // Read the number into a string. (Must be null-terminated for strto*). 509 SmallString<24> S; 510 S.push_back(First); 511 while (isNumber(peek())) 512 S.push_back(next()); 513 char *End; 514 // Try first to parse as integer, and if so preserve full 64 bits. 515 // strtoll returns long long >= 64 bits, so check it's in range too. 516 auto I = std::strtoll(S.c_str(), &End, 10); 517 if (End == S.end() && I >= std::numeric_limits<int64_t>::min() && 518 I <= std::numeric_limits<int64_t>::max()) { 519 Out = int64_t(I); 520 return true; 521 } 522 // If it's not an integer 523 Out = std::strtod(S.c_str(), &End); 524 return End == S.end() || parseError("Invalid JSON value (number?)"); 525 } 526 527 bool Parser::parseString(std::string &Out) { 528 // leading quote was already consumed. 529 for (char C = next(); C != '"'; C = next()) { 530 if (LLVM_UNLIKELY(P == End)) 531 return parseError("Unterminated string"); 532 if (LLVM_UNLIKELY((C & 0x1f) == C)) 533 return parseError("Control character in string"); 534 if (LLVM_LIKELY(C != '\\')) { 535 Out.push_back(C); 536 continue; 537 } 538 // Handle escape sequence. 539 switch (C = next()) { 540 case '"': 541 case '\\': 542 case '/': 543 Out.push_back(C); 544 break; 545 case 'b': 546 Out.push_back('\b'); 547 break; 548 case 'f': 549 Out.push_back('\f'); 550 break; 551 case 'n': 552 Out.push_back('\n'); 553 break; 554 case 'r': 555 Out.push_back('\r'); 556 break; 557 case 't': 558 Out.push_back('\t'); 559 break; 560 case 'u': 561 if (!parseUnicode(Out)) 562 return false; 563 break; 564 default: 565 return parseError("Invalid escape sequence"); 566 } 567 } 568 return true; 569 } 570 571 static void encodeUtf8(uint32_t Rune, std::string &Out) { 572 if (Rune < 0x80) { 573 Out.push_back(Rune & 0x7F); 574 } else if (Rune < 0x800) { 575 uint8_t FirstByte = 0xC0 | ((Rune & 0x7C0) >> 6); 576 uint8_t SecondByte = 0x80 | (Rune & 0x3F); 577 Out.push_back(FirstByte); 578 Out.push_back(SecondByte); 579 } else if (Rune < 0x10000) { 580 uint8_t FirstByte = 0xE0 | ((Rune & 0xF000) >> 12); 581 uint8_t SecondByte = 0x80 | ((Rune & 0xFC0) >> 6); 582 uint8_t ThirdByte = 0x80 | (Rune & 0x3F); 583 Out.push_back(FirstByte); 584 Out.push_back(SecondByte); 585 Out.push_back(ThirdByte); 586 } else if (Rune < 0x110000) { 587 uint8_t FirstByte = 0xF0 | ((Rune & 0x1F0000) >> 18); 588 uint8_t SecondByte = 0x80 | ((Rune & 0x3F000) >> 12); 589 uint8_t ThirdByte = 0x80 | ((Rune & 0xFC0) >> 6); 590 uint8_t FourthByte = 0x80 | (Rune & 0x3F); 591 Out.push_back(FirstByte); 592 Out.push_back(SecondByte); 593 Out.push_back(ThirdByte); 594 Out.push_back(FourthByte); 595 } else { 596 llvm_unreachable("Invalid codepoint"); 597 } 598 } 599 600 // Parse a UTF-16 \uNNNN escape sequence. "\u" has already been consumed. 601 // May parse several sequential escapes to ensure proper surrogate handling. 602 // We do not use ConvertUTF.h, it can't accept and replace unpaired surrogates. 603 // These are invalid Unicode but valid JSON (RFC 8259, section 8.2). 604 bool Parser::parseUnicode(std::string &Out) { 605 // Invalid UTF is not a JSON error (RFC 8529§8.2). It gets replaced by U+FFFD. 606 auto Invalid = [&] { Out.append(/* UTF-8 */ {'\xef', '\xbf', '\xbd'}); }; 607 // Decodes 4 hex digits from the stream into Out, returns false on error. 608 auto Parse4Hex = [this](uint16_t &Out) -> bool { 609 Out = 0; 610 char Bytes[] = {next(), next(), next(), next()}; 611 for (unsigned char C : Bytes) { 612 if (!std::isxdigit(C)) 613 return parseError("Invalid \\u escape sequence"); 614 Out <<= 4; 615 Out |= (C > '9') ? (C & ~0x20) - 'A' + 10 : (C - '0'); 616 } 617 return true; 618 }; 619 uint16_t First; // UTF-16 code unit from the first \u escape. 620 if (!Parse4Hex(First)) 621 return false; 622 623 // We loop to allow proper surrogate-pair error handling. 624 while (true) { 625 // Case 1: the UTF-16 code unit is already a codepoint in the BMP. 626 if (LLVM_LIKELY(First < 0xD800 || First >= 0xE000)) { 627 encodeUtf8(First, Out); 628 return true; 629 } 630 631 // Case 2: it's an (unpaired) trailing surrogate. 632 if (LLVM_UNLIKELY(First >= 0xDC00)) { 633 Invalid(); 634 return true; 635 } 636 637 // Case 3: it's a leading surrogate. We expect a trailing one next. 638 // Case 3a: there's no trailing \u escape. Don't advance in the stream. 639 if (LLVM_UNLIKELY(P + 2 > End || *P != '\\' || *(P + 1) != 'u')) { 640 Invalid(); // Leading surrogate was unpaired. 641 return true; 642 } 643 P += 2; 644 uint16_t Second; 645 if (!Parse4Hex(Second)) 646 return false; 647 // Case 3b: there was another \u escape, but it wasn't a trailing surrogate. 648 if (LLVM_UNLIKELY(Second < 0xDC00 || Second >= 0xE000)) { 649 Invalid(); // Leading surrogate was unpaired. 650 First = Second; // Second escape still needs to be processed. 651 continue; 652 } 653 // Case 3c: a valid surrogate pair encoding an astral codepoint. 654 encodeUtf8(0x10000 | ((First - 0xD800) << 10) | (Second - 0xDC00), Out); 655 return true; 656 } 657 } 658 659 bool Parser::parseError(const char *Msg) { 660 int Line = 1; 661 const char *StartOfLine = Start; 662 for (const char *X = Start; X < P; ++X) { 663 if (*X == 0x0A) { 664 ++Line; 665 StartOfLine = X + 1; 666 } 667 } 668 Err.emplace( 669 std::make_unique<ParseError>(Msg, Line, P - StartOfLine, P - Start)); 670 return false; 671 } 672 } // namespace 673 674 Expected<Value> parse(StringRef JSON) { 675 Parser P(JSON); 676 Value E = nullptr; 677 if (P.checkUTF8()) 678 if (P.parseValue(E)) 679 if (P.assertEnd()) 680 return std::move(E); 681 return P.takeError(); 682 } 683 char ParseError::ID = 0; 684 685 bool isUTF8(llvm::StringRef S, size_t *ErrOffset) { 686 // Fast-path for ASCII, which is valid UTF-8. 687 if (LLVM_LIKELY(isASCII(S))) 688 return true; 689 690 const UTF8 *Data = reinterpret_cast<const UTF8 *>(S.data()), *Rest = Data; 691 if (LLVM_LIKELY(isLegalUTF8String(&Rest, Data + S.size()))) 692 return true; 693 694 if (ErrOffset) 695 *ErrOffset = Rest - Data; 696 return false; 697 } 698 699 std::string fixUTF8(llvm::StringRef S) { 700 // This isn't particularly efficient, but is only for error-recovery. 701 std::vector<UTF32> Codepoints(S.size()); // 1 codepoint per byte suffices. 702 const UTF8 *In8 = reinterpret_cast<const UTF8 *>(S.data()); 703 UTF32 *Out32 = Codepoints.data(); 704 ConvertUTF8toUTF32(&In8, In8 + S.size(), &Out32, Out32 + Codepoints.size(), 705 lenientConversion); 706 Codepoints.resize(Out32 - Codepoints.data()); 707 std::string Res(4 * Codepoints.size(), 0); // 4 bytes per codepoint suffice 708 const UTF32 *In32 = Codepoints.data(); 709 UTF8 *Out8 = reinterpret_cast<UTF8 *>(&Res[0]); 710 ConvertUTF32toUTF8(&In32, In32 + Codepoints.size(), &Out8, Out8 + Res.size(), 711 strictConversion); 712 Res.resize(reinterpret_cast<char *>(Out8) - Res.data()); 713 return Res; 714 } 715 716 static void quote(llvm::raw_ostream &OS, llvm::StringRef S) { 717 OS << '\"'; 718 for (unsigned char C : S) { 719 if (C == 0x22 || C == 0x5C) 720 OS << '\\'; 721 if (C >= 0x20) { 722 OS << C; 723 continue; 724 } 725 OS << '\\'; 726 switch (C) { 727 // A few characters are common enough to make short escapes worthwhile. 728 case '\t': 729 OS << 't'; 730 break; 731 case '\n': 732 OS << 'n'; 733 break; 734 case '\r': 735 OS << 'r'; 736 break; 737 default: 738 OS << 'u'; 739 llvm::write_hex(OS, C, llvm::HexPrintStyle::Lower, 4); 740 break; 741 } 742 } 743 OS << '\"'; 744 } 745 746 void llvm::json::OStream::value(const Value &V) { 747 switch (V.kind()) { 748 case Value::Null: 749 valueBegin(); 750 OS << "null"; 751 return; 752 case Value::Boolean: 753 valueBegin(); 754 OS << (*V.getAsBoolean() ? "true" : "false"); 755 return; 756 case Value::Number: 757 valueBegin(); 758 if (V.Type == Value::T_Integer) 759 OS << *V.getAsInteger(); 760 else 761 OS << format("%.*g", std::numeric_limits<double>::max_digits10, 762 *V.getAsNumber()); 763 return; 764 case Value::String: 765 valueBegin(); 766 quote(OS, *V.getAsString()); 767 return; 768 case Value::Array: 769 return array([&] { 770 for (const Value &E : *V.getAsArray()) 771 value(E); 772 }); 773 case Value::Object: 774 return object([&] { 775 for (const Object::value_type *E : sortedElements(*V.getAsObject())) 776 attribute(E->first, E->second); 777 }); 778 } 779 } 780 781 void llvm::json::OStream::valueBegin() { 782 assert(Stack.back().Ctx != Object && "Only attributes allowed here"); 783 if (Stack.back().HasValue) { 784 assert(Stack.back().Ctx != Singleton && "Only one value allowed here"); 785 OS << ','; 786 } 787 if (Stack.back().Ctx == Array) 788 newline(); 789 flushComment(); 790 Stack.back().HasValue = true; 791 } 792 793 void OStream::comment(llvm::StringRef Comment) { 794 assert(PendingComment.empty() && "Only one comment per value!"); 795 PendingComment = Comment; 796 } 797 798 void OStream::flushComment() { 799 if (PendingComment.empty()) 800 return; 801 OS << (IndentSize ? "/* " : "/*"); 802 // Be sure not to accidentally emit "*/". Transform to "* /". 803 while (!PendingComment.empty()) { 804 auto Pos = PendingComment.find("*/"); 805 if (Pos == StringRef::npos) { 806 OS << PendingComment; 807 PendingComment = ""; 808 } else { 809 OS << PendingComment.take_front(Pos) << "* /"; 810 PendingComment = PendingComment.drop_front(Pos + 2); 811 } 812 } 813 OS << (IndentSize ? " */" : "*/"); 814 // Comments are on their own line unless attached to an attribute value. 815 if (Stack.size() > 1 && Stack.back().Ctx == Singleton) { 816 if (IndentSize) 817 OS << ' '; 818 } else { 819 newline(); 820 } 821 } 822 823 void llvm::json::OStream::newline() { 824 if (IndentSize) { 825 OS.write('\n'); 826 OS.indent(Indent); 827 } 828 } 829 830 void llvm::json::OStream::arrayBegin() { 831 valueBegin(); 832 Stack.emplace_back(); 833 Stack.back().Ctx = Array; 834 Indent += IndentSize; 835 OS << '['; 836 } 837 838 void llvm::json::OStream::arrayEnd() { 839 assert(Stack.back().Ctx == Array); 840 Indent -= IndentSize; 841 if (Stack.back().HasValue) 842 newline(); 843 OS << ']'; 844 assert(PendingComment.empty()); 845 Stack.pop_back(); 846 assert(!Stack.empty()); 847 } 848 849 void llvm::json::OStream::objectBegin() { 850 valueBegin(); 851 Stack.emplace_back(); 852 Stack.back().Ctx = Object; 853 Indent += IndentSize; 854 OS << '{'; 855 } 856 857 void llvm::json::OStream::objectEnd() { 858 assert(Stack.back().Ctx == Object); 859 Indent -= IndentSize; 860 if (Stack.back().HasValue) 861 newline(); 862 OS << '}'; 863 assert(PendingComment.empty()); 864 Stack.pop_back(); 865 assert(!Stack.empty()); 866 } 867 868 void llvm::json::OStream::attributeBegin(llvm::StringRef Key) { 869 assert(Stack.back().Ctx == Object); 870 if (Stack.back().HasValue) 871 OS << ','; 872 newline(); 873 flushComment(); 874 Stack.back().HasValue = true; 875 Stack.emplace_back(); 876 Stack.back().Ctx = Singleton; 877 if (LLVM_LIKELY(isUTF8(Key))) { 878 quote(OS, Key); 879 } else { 880 assert(false && "Invalid UTF-8 in attribute key"); 881 quote(OS, fixUTF8(Key)); 882 } 883 OS.write(':'); 884 if (IndentSize) 885 OS.write(' '); 886 } 887 888 void llvm::json::OStream::attributeEnd() { 889 assert(Stack.back().Ctx == Singleton); 890 assert(Stack.back().HasValue && "Attribute must have a value"); 891 assert(PendingComment.empty()); 892 Stack.pop_back(); 893 assert(Stack.back().Ctx == Object); 894 } 895 896 } // namespace json 897 } // namespace llvm 898 899 void llvm::format_provider<llvm::json::Value>::format( 900 const llvm::json::Value &E, raw_ostream &OS, StringRef Options) { 901 unsigned IndentAmount = 0; 902 if (!Options.empty() && Options.getAsInteger(/*Radix=*/10, IndentAmount)) 903 llvm_unreachable("json::Value format options should be an integer"); 904 json::OStream(OS, IndentAmount).value(E); 905 } 906 907