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