xref: /llvm-project/llvm/lib/Support/JSON.cpp (revision 16619e7139bdcb0021598ba76cb5cf30ac669dbb)
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 // Simple recursive-descent JSON parser.
240 class Parser {
241 public:
242   Parser(StringRef JSON)
243       : Start(JSON.begin()), P(JSON.begin()), End(JSON.end()) {}
244 
245   bool checkUTF8() {
246     size_t ErrOffset;
247     if (isUTF8(StringRef(Start, End - Start), &ErrOffset))
248       return true;
249     P = Start + ErrOffset; // For line/column calculation.
250     return parseError("Invalid UTF-8 sequence");
251   }
252 
253   bool parseValue(Value &Out);
254 
255   bool assertEnd() {
256     eatWhitespace();
257     if (P == End)
258       return true;
259     return parseError("Text after end of document");
260   }
261 
262   Error takeError() {
263     assert(Err);
264     return std::move(*Err);
265   }
266 
267 private:
268   void eatWhitespace() {
269     while (P != End && (*P == ' ' || *P == '\r' || *P == '\n' || *P == '\t'))
270       ++P;
271   }
272 
273   // On invalid syntax, parseX() functions return false and set Err.
274   bool parseNumber(char First, Value &Out);
275   bool parseString(std::string &Out);
276   bool parseUnicode(std::string &Out);
277   bool parseError(const char *Msg); // always returns false
278 
279   char next() { return P == End ? 0 : *P++; }
280   char peek() { return P == End ? 0 : *P; }
281   static bool isNumber(char C) {
282     return C == '0' || C == '1' || C == '2' || C == '3' || C == '4' ||
283            C == '5' || C == '6' || C == '7' || C == '8' || C == '9' ||
284            C == 'e' || C == 'E' || C == '+' || C == '-' || C == '.';
285   }
286 
287   Optional<Error> Err;
288   const char *Start, *P, *End;
289 };
290 
291 bool Parser::parseValue(Value &Out) {
292   eatWhitespace();
293   if (P == End)
294     return parseError("Unexpected EOF");
295   switch (char C = next()) {
296   // Bare null/true/false are easy - first char identifies them.
297   case 'n':
298     Out = nullptr;
299     return (next() == 'u' && next() == 'l' && next() == 'l') ||
300            parseError("Invalid JSON value (null?)");
301   case 't':
302     Out = true;
303     return (next() == 'r' && next() == 'u' && next() == 'e') ||
304            parseError("Invalid JSON value (true?)");
305   case 'f':
306     Out = false;
307     return (next() == 'a' && next() == 'l' && next() == 's' && next() == 'e') ||
308            parseError("Invalid JSON value (false?)");
309   case '"': {
310     std::string S;
311     if (parseString(S)) {
312       Out = std::move(S);
313       return true;
314     }
315     return false;
316   }
317   case '[': {
318     Out = Array{};
319     Array &A = *Out.getAsArray();
320     eatWhitespace();
321     if (peek() == ']') {
322       ++P;
323       return true;
324     }
325     for (;;) {
326       A.emplace_back(nullptr);
327       if (!parseValue(A.back()))
328         return false;
329       eatWhitespace();
330       switch (next()) {
331       case ',':
332         eatWhitespace();
333         continue;
334       case ']':
335         return true;
336       default:
337         return parseError("Expected , or ] after array element");
338       }
339     }
340   }
341   case '{': {
342     Out = Object{};
343     Object &O = *Out.getAsObject();
344     eatWhitespace();
345     if (peek() == '}') {
346       ++P;
347       return true;
348     }
349     for (;;) {
350       if (next() != '"')
351         return parseError("Expected object key");
352       std::string K;
353       if (!parseString(K))
354         return false;
355       eatWhitespace();
356       if (next() != ':')
357         return parseError("Expected : after object key");
358       eatWhitespace();
359       if (!parseValue(O[std::move(K)]))
360         return false;
361       eatWhitespace();
362       switch (next()) {
363       case ',':
364         eatWhitespace();
365         continue;
366       case '}':
367         return true;
368       default:
369         return parseError("Expected , or } after object property");
370       }
371     }
372   }
373   default:
374     if (isNumber(C))
375       return parseNumber(C, Out);
376     return parseError("Invalid JSON value");
377   }
378 }
379 
380 bool Parser::parseNumber(char First, Value &Out) {
381   // Read the number into a string. (Must be null-terminated for strto*).
382   SmallString<24> S;
383   S.push_back(First);
384   while (isNumber(peek()))
385     S.push_back(next());
386   char *End;
387   // Try first to parse as integer, and if so preserve full 64 bits.
388   // strtoll returns long long >= 64 bits, so check it's in range too.
389   auto I = std::strtoll(S.c_str(), &End, 10);
390   if (End == S.end() && I >= std::numeric_limits<int64_t>::min() &&
391       I <= std::numeric_limits<int64_t>::max()) {
392     Out = int64_t(I);
393     return true;
394   }
395   // If it's not an integer
396   Out = std::strtod(S.c_str(), &End);
397   return End == S.end() || parseError("Invalid JSON value (number?)");
398 }
399 
400 bool Parser::parseString(std::string &Out) {
401   // leading quote was already consumed.
402   for (char C = next(); C != '"'; C = next()) {
403     if (LLVM_UNLIKELY(P == End))
404       return parseError("Unterminated string");
405     if (LLVM_UNLIKELY((C & 0x1f) == C))
406       return parseError("Control character in string");
407     if (LLVM_LIKELY(C != '\\')) {
408       Out.push_back(C);
409       continue;
410     }
411     // Handle escape sequence.
412     switch (C = next()) {
413     case '"':
414     case '\\':
415     case '/':
416       Out.push_back(C);
417       break;
418     case 'b':
419       Out.push_back('\b');
420       break;
421     case 'f':
422       Out.push_back('\f');
423       break;
424     case 'n':
425       Out.push_back('\n');
426       break;
427     case 'r':
428       Out.push_back('\r');
429       break;
430     case 't':
431       Out.push_back('\t');
432       break;
433     case 'u':
434       if (!parseUnicode(Out))
435         return false;
436       break;
437     default:
438       return parseError("Invalid escape sequence");
439     }
440   }
441   return true;
442 }
443 
444 static void encodeUtf8(uint32_t Rune, std::string &Out) {
445   if (Rune < 0x80) {
446     Out.push_back(Rune & 0x7F);
447   } else if (Rune < 0x800) {
448     uint8_t FirstByte = 0xC0 | ((Rune & 0x7C0) >> 6);
449     uint8_t SecondByte = 0x80 | (Rune & 0x3F);
450     Out.push_back(FirstByte);
451     Out.push_back(SecondByte);
452   } else if (Rune < 0x10000) {
453     uint8_t FirstByte = 0xE0 | ((Rune & 0xF000) >> 12);
454     uint8_t SecondByte = 0x80 | ((Rune & 0xFC0) >> 6);
455     uint8_t ThirdByte = 0x80 | (Rune & 0x3F);
456     Out.push_back(FirstByte);
457     Out.push_back(SecondByte);
458     Out.push_back(ThirdByte);
459   } else if (Rune < 0x110000) {
460     uint8_t FirstByte = 0xF0 | ((Rune & 0x1F0000) >> 18);
461     uint8_t SecondByte = 0x80 | ((Rune & 0x3F000) >> 12);
462     uint8_t ThirdByte = 0x80 | ((Rune & 0xFC0) >> 6);
463     uint8_t FourthByte = 0x80 | (Rune & 0x3F);
464     Out.push_back(FirstByte);
465     Out.push_back(SecondByte);
466     Out.push_back(ThirdByte);
467     Out.push_back(FourthByte);
468   } else {
469     llvm_unreachable("Invalid codepoint");
470   }
471 }
472 
473 // Parse a UTF-16 \uNNNN escape sequence. "\u" has already been consumed.
474 // May parse several sequential escapes to ensure proper surrogate handling.
475 // We do not use ConvertUTF.h, it can't accept and replace unpaired surrogates.
476 // These are invalid Unicode but valid JSON (RFC 8259, section 8.2).
477 bool Parser::parseUnicode(std::string &Out) {
478   // Invalid UTF is not a JSON error (RFC 8529§8.2). It gets replaced by U+FFFD.
479   auto Invalid = [&] { Out.append(/* UTF-8 */ {'\xef', '\xbf', '\xbd'}); };
480   // Decodes 4 hex digits from the stream into Out, returns false on error.
481   auto Parse4Hex = [this](uint16_t &Out) -> bool {
482     Out = 0;
483     char Bytes[] = {next(), next(), next(), next()};
484     for (unsigned char C : Bytes) {
485       if (!std::isxdigit(C))
486         return parseError("Invalid \\u escape sequence");
487       Out <<= 4;
488       Out |= (C > '9') ? (C & ~0x20) - 'A' + 10 : (C - '0');
489     }
490     return true;
491   };
492   uint16_t First; // UTF-16 code unit from the first \u escape.
493   if (!Parse4Hex(First))
494     return false;
495 
496   // We loop to allow proper surrogate-pair error handling.
497   while (true) {
498     // Case 1: the UTF-16 code unit is already a codepoint in the BMP.
499     if (LLVM_LIKELY(First < 0xD800 || First >= 0xE000)) {
500       encodeUtf8(First, Out);
501       return true;
502     }
503 
504     // Case 2: it's an (unpaired) trailing surrogate.
505     if (LLVM_UNLIKELY(First >= 0xDC00)) {
506       Invalid();
507       return true;
508     }
509 
510     // Case 3: it's a leading surrogate. We expect a trailing one next.
511     // Case 3a: there's no trailing \u escape. Don't advance in the stream.
512     if (LLVM_UNLIKELY(P + 2 > End || *P != '\\' || *(P + 1) != 'u')) {
513       Invalid(); // Leading surrogate was unpaired.
514       return true;
515     }
516     P += 2;
517     uint16_t Second;
518     if (!Parse4Hex(Second))
519       return false;
520     // Case 3b: there was another \u escape, but it wasn't a trailing surrogate.
521     if (LLVM_UNLIKELY(Second < 0xDC00 || Second >= 0xE000)) {
522       Invalid();      // Leading surrogate was unpaired.
523       First = Second; // Second escape still needs to be processed.
524       continue;
525     }
526     // Case 3c: a valid surrogate pair encoding an astral codepoint.
527     encodeUtf8(0x10000 | ((First - 0xD800) << 10) | (Second - 0xDC00), Out);
528     return true;
529   }
530 }
531 
532 bool Parser::parseError(const char *Msg) {
533   int Line = 1;
534   const char *StartOfLine = Start;
535   for (const char *X = Start; X < P; ++X) {
536     if (*X == 0x0A) {
537       ++Line;
538       StartOfLine = X + 1;
539     }
540   }
541   Err.emplace(
542       std::make_unique<ParseError>(Msg, Line, P - StartOfLine, P - Start));
543   return false;
544 }
545 } // namespace
546 
547 Expected<Value> parse(StringRef JSON) {
548   Parser P(JSON);
549   Value E = nullptr;
550   if (P.checkUTF8())
551     if (P.parseValue(E))
552       if (P.assertEnd())
553         return std::move(E);
554   return P.takeError();
555 }
556 char ParseError::ID = 0;
557 
558 static std::vector<const Object::value_type *> sortedElements(const Object &O) {
559   std::vector<const Object::value_type *> Elements;
560   for (const auto &E : O)
561     Elements.push_back(&E);
562   llvm::sort(Elements,
563              [](const Object::value_type *L, const Object::value_type *R) {
564                return L->first < R->first;
565              });
566   return Elements;
567 }
568 
569 bool isUTF8(llvm::StringRef S, size_t *ErrOffset) {
570   // Fast-path for ASCII, which is valid UTF-8.
571   if (LLVM_LIKELY(isASCII(S)))
572     return true;
573 
574   const UTF8 *Data = reinterpret_cast<const UTF8 *>(S.data()), *Rest = Data;
575   if (LLVM_LIKELY(isLegalUTF8String(&Rest, Data + S.size())))
576     return true;
577 
578   if (ErrOffset)
579     *ErrOffset = Rest - Data;
580   return false;
581 }
582 
583 std::string fixUTF8(llvm::StringRef S) {
584   // This isn't particularly efficient, but is only for error-recovery.
585   std::vector<UTF32> Codepoints(S.size()); // 1 codepoint per byte suffices.
586   const UTF8 *In8 = reinterpret_cast<const UTF8 *>(S.data());
587   UTF32 *Out32 = Codepoints.data();
588   ConvertUTF8toUTF32(&In8, In8 + S.size(), &Out32, Out32 + Codepoints.size(),
589                      lenientConversion);
590   Codepoints.resize(Out32 - Codepoints.data());
591   std::string Res(4 * Codepoints.size(), 0); // 4 bytes per codepoint suffice
592   const UTF32 *In32 = Codepoints.data();
593   UTF8 *Out8 = reinterpret_cast<UTF8 *>(&Res[0]);
594   ConvertUTF32toUTF8(&In32, In32 + Codepoints.size(), &Out8, Out8 + Res.size(),
595                      strictConversion);
596   Res.resize(reinterpret_cast<char *>(Out8) - Res.data());
597   return Res;
598 }
599 
600 static void quote(llvm::raw_ostream &OS, llvm::StringRef S) {
601   OS << '\"';
602   for (unsigned char C : S) {
603     if (C == 0x22 || C == 0x5C)
604       OS << '\\';
605     if (C >= 0x20) {
606       OS << C;
607       continue;
608     }
609     OS << '\\';
610     switch (C) {
611     // A few characters are common enough to make short escapes worthwhile.
612     case '\t':
613       OS << 't';
614       break;
615     case '\n':
616       OS << 'n';
617       break;
618     case '\r':
619       OS << 'r';
620       break;
621     default:
622       OS << 'u';
623       llvm::write_hex(OS, C, llvm::HexPrintStyle::Lower, 4);
624       break;
625     }
626   }
627   OS << '\"';
628 }
629 
630 void llvm::json::OStream::value(const Value &V) {
631   switch (V.kind()) {
632   case Value::Null:
633     valueBegin();
634     OS << "null";
635     return;
636   case Value::Boolean:
637     valueBegin();
638     OS << (*V.getAsBoolean() ? "true" : "false");
639     return;
640   case Value::Number:
641     valueBegin();
642     if (V.Type == Value::T_Integer)
643       OS << *V.getAsInteger();
644     else
645       OS << format("%.*g", std::numeric_limits<double>::max_digits10,
646                    *V.getAsNumber());
647     return;
648   case Value::String:
649     valueBegin();
650     quote(OS, *V.getAsString());
651     return;
652   case Value::Array:
653     return array([&] {
654       for (const Value &E : *V.getAsArray())
655         value(E);
656     });
657   case Value::Object:
658     return object([&] {
659       for (const Object::value_type *E : sortedElements(*V.getAsObject()))
660         attribute(E->first, E->second);
661     });
662   }
663 }
664 
665 void llvm::json::OStream::valueBegin() {
666   assert(Stack.back().Ctx != Object && "Only attributes allowed here");
667   if (Stack.back().HasValue) {
668     assert(Stack.back().Ctx != Singleton && "Only one value allowed here");
669     OS << ',';
670   }
671   if (Stack.back().Ctx == Array)
672     newline();
673   flushComment();
674   Stack.back().HasValue = true;
675 }
676 
677 void OStream::comment(llvm::StringRef Comment) {
678   assert(PendingComment.empty() && "Only one comment per value!");
679   PendingComment = Comment;
680 }
681 
682 void OStream::flushComment() {
683   if (PendingComment.empty())
684     return;
685   OS << (IndentSize ? "/* " : "/*");
686   // Be sure not to accidentally emit "*/". Transform to "* /".
687   while (!PendingComment.empty()) {
688     auto Pos = PendingComment.find("*/");
689     if (Pos == StringRef::npos) {
690       OS << PendingComment;
691       PendingComment = "";
692     } else {
693       OS << PendingComment.take_front(Pos) << "* /";
694       PendingComment = PendingComment.drop_front(Pos + 2);
695     }
696   }
697   OS << (IndentSize ? " */" : "*/");
698   // Comments are on their own line unless attached to an attribute value.
699   if (Stack.size() > 1 && Stack.back().Ctx == Singleton) {
700     if (IndentSize)
701       OS << ' ';
702   } else {
703     newline();
704   }
705 }
706 
707 void llvm::json::OStream::newline() {
708   if (IndentSize) {
709     OS.write('\n');
710     OS.indent(Indent);
711   }
712 }
713 
714 void llvm::json::OStream::arrayBegin() {
715   valueBegin();
716   Stack.emplace_back();
717   Stack.back().Ctx = Array;
718   Indent += IndentSize;
719   OS << '[';
720 }
721 
722 void llvm::json::OStream::arrayEnd() {
723   assert(Stack.back().Ctx == Array);
724   Indent -= IndentSize;
725   if (Stack.back().HasValue)
726     newline();
727   OS << ']';
728   assert(PendingComment.empty());
729   Stack.pop_back();
730   assert(!Stack.empty());
731 }
732 
733 void llvm::json::OStream::objectBegin() {
734   valueBegin();
735   Stack.emplace_back();
736   Stack.back().Ctx = Object;
737   Indent += IndentSize;
738   OS << '{';
739 }
740 
741 void llvm::json::OStream::objectEnd() {
742   assert(Stack.back().Ctx == Object);
743   Indent -= IndentSize;
744   if (Stack.back().HasValue)
745     newline();
746   OS << '}';
747   assert(PendingComment.empty());
748   Stack.pop_back();
749   assert(!Stack.empty());
750 }
751 
752 void llvm::json::OStream::attributeBegin(llvm::StringRef Key) {
753   assert(Stack.back().Ctx == Object);
754   if (Stack.back().HasValue)
755     OS << ',';
756   newline();
757   flushComment();
758   Stack.back().HasValue = true;
759   Stack.emplace_back();
760   Stack.back().Ctx = Singleton;
761   if (LLVM_LIKELY(isUTF8(Key))) {
762     quote(OS, Key);
763   } else {
764     assert(false && "Invalid UTF-8 in attribute key");
765     quote(OS, fixUTF8(Key));
766   }
767   OS.write(':');
768   if (IndentSize)
769     OS.write(' ');
770 }
771 
772 void llvm::json::OStream::attributeEnd() {
773   assert(Stack.back().Ctx == Singleton);
774   assert(Stack.back().HasValue && "Attribute must have a value");
775   assert(PendingComment.empty());
776   Stack.pop_back();
777   assert(Stack.back().Ctx == Object);
778 }
779 
780 } // namespace json
781 } // namespace llvm
782 
783 void llvm::format_provider<llvm::json::Value>::format(
784     const llvm::json::Value &E, raw_ostream &OS, StringRef Options) {
785   unsigned IndentAmount = 0;
786   if (!Options.empty() && Options.getAsInteger(/*Radix=*/10, IndentAmount))
787     llvm_unreachable("json::Value format options should be an integer");
788   json::OStream(OS, IndentAmount).value(E);
789 }
790 
791