LLVM 22.0.0git
JSON.h
Go to the documentation of this file.
1//===--- JSON.h - JSON values, 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/// \file
10/// This file supports working with JSON data.
11///
12/// It comprises:
13///
14/// - classes which hold dynamically-typed parsed JSON structures
15/// These are value types that can be composed, inspected, and modified.
16/// See json::Value, and the related types json::Object and json::Array.
17///
18/// - functions to parse JSON text into Values, and to serialize Values to text.
19/// See parse(), operator<<, and format_provider.
20///
21/// - a convention and helpers for mapping between json::Value and user-defined
22/// types. See fromJSON(), ObjectMapper, and the class comment on Value.
23///
24/// - an output API json::OStream which can emit JSON without materializing
25/// all structures as json::Value.
26///
27/// Typically, JSON data would be read from an external source, parsed into
28/// a Value, and then converted into some native data structure before doing
29/// real work on it. (And vice versa when writing).
30///
31/// Other serialization mechanisms you may consider:
32///
33/// - YAML is also text-based, and more human-readable than JSON. It's a more
34/// complex format and data model, and YAML parsers aren't ubiquitous.
35/// YAMLParser.h is a streaming parser suitable for parsing large documents
36/// (including JSON, as YAML is a superset). It can be awkward to use
37/// directly. YAML I/O (YAMLTraits.h) provides data mapping that is more
38/// declarative than the toJSON/fromJSON conventions here.
39///
40/// - LLVM bitstream is a space- and CPU- efficient binary format. Typically it
41/// encodes LLVM IR ("bitcode"), but it can be a container for other data.
42/// Low-level reader/writer libraries are in Bitstream/Bitstream*.h
43///
44//===---------------------------------------------------------------------===//
45
46#ifndef LLVM_SUPPORT_JSON_H
47#define LLVM_SUPPORT_JSON_H
48
49#include "llvm/ADT/DenseMap.h"
52#include "llvm/ADT/StringRef.h"
54#include "llvm/Support/Error.h"
57#include <cmath>
58#include <map>
59
60namespace llvm {
61namespace json {
62
63// === String encodings ===
64//
65// JSON strings are character sequences (not byte sequences like std::string).
66// We need to know the encoding, and for simplicity only support UTF-8.
67//
68// - When parsing, invalid UTF-8 is a syntax error like any other
69//
70// - When creating Values from strings, callers must ensure they are UTF-8.
71// with asserts on, invalid UTF-8 will crash the program
72// with asserts off, we'll substitute the replacement character (U+FFFD)
73// Callers can use json::isUTF8() and json::fixUTF8() for validation.
74//
75// - When retrieving strings from Values (e.g. asString()), the result will
76// always be valid UTF-8.
77
78template <typename T>
79constexpr bool is_uint_64_bit_v =
80 std::is_integral_v<T> && std::is_unsigned_v<T> &&
81 sizeof(T) == sizeof(uint64_t);
82
83/// Returns true if \p S is valid UTF-8, which is required for use as JSON.
84/// If it returns false, \p Offset is set to a byte offset near the first error.
85LLVM_ABI bool isUTF8(llvm::StringRef S, size_t *ErrOffset = nullptr);
86/// Replaces invalid UTF-8 sequences in \p S with the replacement character
87/// (U+FFFD). The returned string is valid UTF-8.
88/// This is much slower than isUTF8, so test that first.
89LLVM_ABI std::string fixUTF8(llvm::StringRef S);
90
91class Array;
92class ObjectKey;
93class Value;
94template <typename T> Value toJSON(const std::optional<T> &Opt);
95
96/// An Object is a JSON object, which maps strings to heterogenous JSON values.
97/// It simulates DenseMap<ObjectKey, Value>. ObjectKey is a maybe-owned string.
98class Object {
100 Storage M;
101
102public:
108
109 Object() = default;
110 // KV is a trivial key-value struct for list-initialization.
111 // (using std::pair forces extra copies).
112 struct KV;
113 explicit Object(std::initializer_list<KV> Properties);
114
115 iterator begin() { return M.begin(); }
116 const_iterator begin() const { return M.begin(); }
117 iterator end() { return M.end(); }
118 const_iterator end() const { return M.end(); }
119
120 bool empty() const { return M.empty(); }
121 size_t size() const { return M.size(); }
122
123 void clear() { M.clear(); }
124 std::pair<iterator, bool> insert(KV E);
125 template <typename... Ts>
126 std::pair<iterator, bool> try_emplace(const ObjectKey &K, Ts &&... Args) {
127 return M.try_emplace(K, std::forward<Ts>(Args)...);
128 }
129 template <typename... Ts>
130 std::pair<iterator, bool> try_emplace(ObjectKey &&K, Ts &&... Args) {
131 return M.try_emplace(std::move(K), std::forward<Ts>(Args)...);
132 }
133 bool erase(StringRef K);
134 void erase(iterator I) { M.erase(I); }
135
136 iterator find(StringRef K) { return M.find_as(K); }
137 const_iterator find(StringRef K) const { return M.find_as(K); }
138 // operator[] acts as if Value was default-constructible as null.
141 // Look up a property, returning nullptr if it doesn't exist.
143 LLVM_ABI const Value *get(StringRef K) const;
144 // Typed accessors return std::nullopt/nullptr if
145 // - the property doesn't exist
146 // - or it has the wrong type
147 LLVM_ABI std::optional<std::nullptr_t> getNull(StringRef K) const;
148 LLVM_ABI std::optional<bool> getBoolean(StringRef K) const;
149 LLVM_ABI std::optional<double> getNumber(StringRef K) const;
150 LLVM_ABI std::optional<int64_t> getInteger(StringRef K) const;
151 LLVM_ABI std::optional<llvm::StringRef> getString(StringRef K) const;
154 LLVM_ABI const json::Array *getArray(StringRef K) const;
156};
157LLVM_ABI bool operator==(const Object &LHS, const Object &RHS);
158inline bool operator!=(const Object &LHS, const Object &RHS) {
159 return !(LHS == RHS);
160}
161
162/// An Array is a JSON array, which contains heterogeneous JSON values.
163/// It simulates std::vector<Value>.
164class Array {
165 std::vector<Value> V;
166
167public:
169 using iterator = std::vector<Value>::iterator;
170 using const_iterator = std::vector<Value>::const_iterator;
171
172 Array() = default;
173 LLVM_ABI explicit Array(std::initializer_list<Value> Elements);
174 template <typename Collection> explicit Array(const Collection &C) {
175 for (const auto &V : C)
176 emplace_back(V);
177 }
178
179 Value &operator[](size_t I);
180 const Value &operator[](size_t I) const;
181 Value &front();
182 const Value &front() const;
183 Value &back();
184 const Value &back() const;
185 Value *data();
186 const Value *data() const;
187
188 iterator begin();
189 const_iterator begin() const;
190 iterator end();
191 const_iterator end() const;
192
193 bool empty() const;
194 size_t size() const;
195 void reserve(size_t S);
196
197 void clear();
198 void push_back(const Value &E);
199 void push_back(Value &&E);
200 template <typename... Args> void emplace_back(Args &&...A);
201 void pop_back();
204 template <typename It> iterator insert(const_iterator P, It A, It Z);
205 template <typename... Args> iterator emplace(const_iterator P, Args &&...A);
206
207 friend bool operator==(const Array &L, const Array &R);
208};
209inline bool operator!=(const Array &L, const Array &R) { return !(L == R); }
210
211/// A Value is an JSON value of unknown type.
212/// They can be copied, but should generally be moved.
213///
214/// === Composing values ===
215///
216/// You can implicitly construct Values from:
217/// - strings: std::string, SmallString, formatv, StringRef, char*
218/// (char*, and StringRef are references, not copies!)
219/// - numbers
220/// - booleans
221/// - null: nullptr
222/// - arrays: {"foo", 42.0, false}
223/// - serializable things: types with toJSON(const T&)->Value, found by ADL
224///
225/// They can also be constructed from object/array helpers:
226/// - json::Object is a type like map<ObjectKey, Value>
227/// - json::Array is a type like vector<Value>
228/// These can be list-initialized, or used to build up collections in a loop.
229/// json::ary(Collection) converts all items in a collection to Values.
230///
231/// === Inspecting values ===
232///
233/// Each Value is one of the JSON kinds:
234/// null (nullptr_t)
235/// boolean (bool)
236/// number (double, int64 or uint64)
237/// string (StringRef)
238/// array (json::Array)
239/// object (json::Object)
240///
241/// The kind can be queried directly, or implicitly via the typed accessors:
242/// if (std::optional<StringRef> S = E.getAsString()
243/// assert(E.kind() == Value::String);
244///
245/// Array and Object also have typed indexing accessors for easy traversal:
246/// Expected<Value> E = parse(R"( {"options": {"font": "sans-serif"}} )");
247/// if (Object* O = E->getAsObject())
248/// if (Object* Opts = O->getObject("options"))
249/// if (std::optional<StringRef> Font = Opts->getString("font"))
250/// assert(Opts->at("font").kind() == Value::String);
251///
252/// === Converting JSON values to C++ types ===
253///
254/// The convention is to have a deserializer function findable via ADL:
255/// fromJSON(const json::Value&, T&, Path) -> bool
256///
257/// The return value indicates overall success, and Path is used for precise
258/// error reporting. (The Path::Root passed in at the top level fromJSON call
259/// captures any nested error and can render it in context).
260/// If conversion fails, fromJSON calls Path::report() and immediately returns.
261/// This ensures that the first fatal error survives.
262///
263/// Deserializers are provided for:
264/// - bool
265/// - int and int64_t
266/// - double
267/// - std::string
268/// - vector<T>, where T is deserializable
269/// - map<string, T>, where T is deserializable
270/// - std::optional<T>, where T is deserializable
271/// ObjectMapper can help writing fromJSON() functions for object types.
272///
273/// For conversion in the other direction, the serializer function is:
274/// toJSON(const T&) -> json::Value
275/// If this exists, then it also allows constructing Value from T, and can
276/// be used to serialize vector<T>, map<string, T>, and std::optional<T>.
277///
278/// === Serialization ===
279///
280/// Values can be serialized to JSON:
281/// 1) raw_ostream << Value // Basic formatting.
282/// 2) raw_ostream << formatv("{0}", Value) // Basic formatting.
283/// 3) raw_ostream << formatv("{0:2}", Value) // Pretty-print with indent 2.
284///
285/// And parsed:
286/// Expected<Value> E = json::parse("[1, 2, null]");
287/// assert(E && E->kind() == Value::Array);
288class Value {
289public:
290 enum Kind {
293 /// Number values can store both int64s and doubles at full precision,
294 /// depending on what they were constructed/parsed from.
299 };
300
301 // It would be nice to have Value() be null. But that would make {} null too.
302 Value(const Value &M) { copyFrom(M); }
303 Value(Value &&M) { moveFrom(std::move(M)); }
304 LLVM_ABI Value(std::initializer_list<Value> Elements);
305 Value(json::Array &&Elements) : Type(T_Array) {
306 create<json::Array>(std::move(Elements));
307 }
308 template <typename Elt>
309 Value(const std::vector<Elt> &C) : Value(json::Array(C)) {}
310 Value(json::Object &&Properties) : Type(T_Object) {
311 create<json::Object>(std::move(Properties));
312 }
313 template <typename Elt>
314 Value(const std::map<std::string, Elt> &C) : Value(json::Object(C)) {}
315 // Strings: types with value semantics. Must be valid UTF-8.
316 Value(std::string V) : Type(T_String) {
317 if (LLVM_UNLIKELY(!isUTF8(V))) {
318 assert(false && "Invalid UTF-8 in value used as JSON");
319 V = fixUTF8(std::move(V));
320 }
321 create<std::string>(std::move(V));
322 }
324 : Value(std::string(V.begin(), V.end())) {}
325 Value(const llvm::formatv_object_base &V) : Value(V.str()) {}
326 // Strings: types with reference semantics. Must be valid UTF-8.
327 Value(StringRef V) : Type(T_StringRef) {
328 create<llvm::StringRef>(V);
329 if (LLVM_UNLIKELY(!isUTF8(V))) {
330 assert(false && "Invalid UTF-8 in value used as JSON");
331 *this = Value(fixUTF8(V));
332 }
333 }
334 Value(const char *V) : Value(StringRef(V)) {}
335 Value(std::nullptr_t) : Type(T_Null) {}
336 // Boolean (disallow implicit conversions).
337 // (The last template parameter is a dummy to keep templates distinct.)
338 template <typename T, typename = std::enable_if_t<std::is_same_v<T, bool>>,
339 bool = false>
340 Value(T B) : Type(T_Boolean) {
341 create<bool>(B);
342 }
343
344 // Unsigned 64-bit integers.
345 template <typename T, typename = std::enable_if_t<is_uint_64_bit_v<T>>>
346 Value(T V) : Type(T_UINT64) {
347 create<uint64_t>(uint64_t{V});
348 }
349
350 // Integers (except boolean and uint64_t).
351 // Must be non-narrowing convertible to int64_t.
352 template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>,
353 typename = std::enable_if_t<!std::is_same_v<T, bool>>,
354 typename = std::enable_if_t<!is_uint_64_bit_v<T>>>
355 Value(T I) : Type(T_Integer) {
356 create<int64_t>(int64_t{I});
357 }
358 // Floating point. Must be non-narrowing convertible to double.
359 template <typename T,
360 typename = std::enable_if_t<std::is_floating_point_v<T>>,
361 double * = nullptr>
362 Value(T D) : Type(T_Double) {
363 create<double>(double{D});
364 }
365 // Serializable types: with a toJSON(const T&)->Value function, found by ADL.
366 template <typename T,
367 typename = std::enable_if_t<
368 std::is_same_v<Value, decltype(toJSON(*(const T *)nullptr))>>,
369 Value * = nullptr>
370 Value(const T &V) : Value(toJSON(V)) {}
371
372 Value &operator=(const Value &M) {
373 destroy();
374 copyFrom(M);
375 return *this;
376 }
378 destroy();
379 moveFrom(std::move(M));
380 return *this;
381 }
382 ~Value() { destroy(); }
383
384 Kind kind() const {
385 switch (Type) {
386 case T_Null:
387 return Null;
388 case T_Boolean:
389 return Boolean;
390 case T_Double:
391 case T_Integer:
392 case T_UINT64:
393 return Number;
394 case T_String:
395 case T_StringRef:
396 return String;
397 case T_Object:
398 return Object;
399 case T_Array:
400 return Array;
401 }
402 llvm_unreachable("Unknown kind");
403 }
404
405 // Typed accessors return std::nullopt/nullptr if the Value is not of this
406 // type.
407 std::optional<std::nullptr_t> getAsNull() const {
408 if (LLVM_LIKELY(Type == T_Null))
409 return nullptr;
410 return std::nullopt;
411 }
412 std::optional<bool> getAsBoolean() const {
413 if (LLVM_LIKELY(Type == T_Boolean))
414 return as<bool>();
415 return std::nullopt;
416 }
417 std::optional<double> getAsNumber() const {
418 if (LLVM_LIKELY(Type == T_Double))
419 return as<double>();
420 if (LLVM_LIKELY(Type == T_Integer))
421 return as<int64_t>();
422 if (LLVM_LIKELY(Type == T_UINT64))
423 return as<uint64_t>();
424 return std::nullopt;
425 }
426 // Succeeds if the Value is a Number, and exactly representable as int64_t.
427 std::optional<int64_t> getAsInteger() const {
428 if (LLVM_LIKELY(Type == T_Integer))
429 return as<int64_t>();
430 if (LLVM_LIKELY(Type == T_UINT64)) {
431 uint64_t U = as<uint64_t>();
432 if (LLVM_LIKELY(U <= uint64_t(std::numeric_limits<int64_t>::max()))) {
433 return U;
434 }
435 }
436 if (LLVM_LIKELY(Type == T_Double)) {
437 double D = as<double>();
438 if (LLVM_LIKELY(std::modf(D, &D) == 0.0 &&
439 D >= double(std::numeric_limits<int64_t>::min()) &&
440 D <= double(std::numeric_limits<int64_t>::max())))
441 return D;
442 }
443 return std::nullopt;
444 }
445 std::optional<uint64_t> getAsUINT64() const {
446 if (Type == T_UINT64)
447 return as<uint64_t>();
448 else if (Type == T_Integer) {
449 int64_t N = as<int64_t>();
450 if (N >= 0)
451 return as<uint64_t>();
452 }
453 return std::nullopt;
454 }
455 std::optional<llvm::StringRef> getAsString() const {
456 if (Type == T_String)
457 return llvm::StringRef(as<std::string>());
458 if (LLVM_LIKELY(Type == T_StringRef))
459 return as<llvm::StringRef>();
460 return std::nullopt;
461 }
462 const json::Object *getAsObject() const {
463 return LLVM_LIKELY(Type == T_Object) ? &as<json::Object>() : nullptr;
464 }
466 return LLVM_LIKELY(Type == T_Object) ? &as<json::Object>() : nullptr;
467 }
468 const json::Array *getAsArray() const {
469 return LLVM_LIKELY(Type == T_Array) ? &as<json::Array>() : nullptr;
470 }
472 return LLVM_LIKELY(Type == T_Array) ? &as<json::Array>() : nullptr;
473 }
474
475 LLVM_ABI void print(llvm::raw_ostream &OS) const;
476#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
477 LLVM_DUMP_METHOD void dump() const {
478 print(llvm::dbgs());
479 llvm::dbgs() << '\n';
480 }
481#endif // !NDEBUG || LLVM_ENABLE_DUMP
482
483private:
484 LLVM_ABI void destroy();
485 LLVM_ABI void copyFrom(const Value &M);
486 // We allow moving from *const* Values, by marking all members as mutable!
487 // This hack is needed to support initializer-list syntax efficiently.
488 // (std::initializer_list<T> is a container of const T).
489 LLVM_ABI void moveFrom(const Value &&M);
490 friend class Array;
491 friend class Object;
492
493 template <typename T, typename... U> void create(U &&... V) {
494#if LLVM_ADDRESS_SANITIZER_BUILD
495 // Unpoisoning to prevent overwriting poisoned object (e.g., annotated short
496 // string). Objects that have had their memory poisoned may cause an ASan
497 // error if their memory is reused without calling their destructor.
498 // Unpoisoning the memory prevents this error from occurring.
499 // FIXME: This is a temporary solution to prevent buildbots from failing.
500 // The more appropriate approach would be to call the object's destructor
501 // to unpoison memory. This would prevent any potential memory leaks (long
502 // strings). Read for details:
503 // https://github.com/llvm/llvm-project/pull/79065#discussion_r1462621761
504 __asan_unpoison_memory_region(&Union, sizeof(T));
505#endif
506 new (reinterpret_cast<T *>(&Union)) T(std::forward<U>(V)...);
507 }
508 template <typename T> T &as() const {
509 // Using this two-step static_cast via void * instead of reinterpret_cast
510 // silences a -Wstrict-aliasing false positive from GCC6 and earlier.
511 void *Storage = static_cast<void *>(&Union);
512 return *static_cast<T *>(Storage);
513 }
514
515 friend class OStream;
516
517 enum ValueType : char16_t {
518 T_Null,
519 T_Boolean,
520 T_Double,
521 T_Integer,
522 T_UINT64,
523 T_StringRef,
524 T_String,
525 T_Object,
526 T_Array,
527 };
528 // All members mutable, see moveFrom().
529 mutable ValueType Type;
530 mutable llvm::AlignedCharArrayUnion<bool, double, int64_t, uint64_t,
531 llvm::StringRef, std::string, json::Array,
533 Union;
534 LLVM_ABI friend bool operator==(const Value &, const Value &);
535};
536
537LLVM_ABI bool operator==(const Value &, const Value &);
538inline bool operator!=(const Value &L, const Value &R) { return !(L == R); }
539
540// Array Methods
541inline Value &Array::operator[](size_t I) { return V[I]; }
542inline const Value &Array::operator[](size_t I) const { return V[I]; }
543inline Value &Array::front() { return V.front(); }
544inline const Value &Array::front() const { return V.front(); }
545inline Value &Array::back() { return V.back(); }
546inline const Value &Array::back() const { return V.back(); }
547inline Value *Array::data() { return V.data(); }
548inline const Value *Array::data() const { return V.data(); }
549
550inline typename Array::iterator Array::begin() { return V.begin(); }
551inline typename Array::const_iterator Array::begin() const { return V.begin(); }
552inline typename Array::iterator Array::end() { return V.end(); }
553inline typename Array::const_iterator Array::end() const { return V.end(); }
554
555inline bool Array::empty() const { return V.empty(); }
556inline size_t Array::size() const { return V.size(); }
557inline void Array::reserve(size_t S) { V.reserve(S); }
558
559inline void Array::clear() { V.clear(); }
560inline void Array::push_back(const Value &E) { V.push_back(E); }
561inline void Array::push_back(Value &&E) { V.push_back(std::move(E)); }
562template <typename... Args> inline void Array::emplace_back(Args &&...A) {
563 V.emplace_back(std::forward<Args>(A)...);
564}
565inline void Array::pop_back() { V.pop_back(); }
567 return V.insert(P, E);
568}
570 return V.insert(P, std::move(E));
571}
572template <typename It>
573inline typename Array::iterator Array::insert(const_iterator P, It A, It Z) {
574 return V.insert(P, A, Z);
575}
576template <typename... Args>
577inline typename Array::iterator Array::emplace(const_iterator P, Args &&...A) {
578 return V.emplace(P, std::forward<Args>(A)...);
579}
580inline bool operator==(const Array &L, const Array &R) { return L.V == R.V; }
581
582/// ObjectKey is a used to capture keys in Object. Like Value but:
583/// - only strings are allowed
584/// - it's optimized for the string literal case (Owned == nullptr)
585/// Like Value, strings must be UTF-8. See isUTF8 documentation for details.
587public:
588 ObjectKey(const char *S) : ObjectKey(StringRef(S)) {}
589 ObjectKey(std::string S) : Owned(new std::string(std::move(S))) {
590 if (LLVM_UNLIKELY(!isUTF8(*Owned))) {
591 assert(false && "Invalid UTF-8 in value used as JSON");
592 *Owned = fixUTF8(std::move(*Owned));
593 }
594 Data = *Owned;
595 }
597 if (LLVM_UNLIKELY(!isUTF8(Data))) {
598 assert(false && "Invalid UTF-8 in value used as JSON");
599 *this = ObjectKey(fixUTF8(S));
600 }
601 }
603 : ObjectKey(std::string(V.begin(), V.end())) {}
605
606 ObjectKey(const ObjectKey &C) { *this = C; }
607 ObjectKey(ObjectKey &&C) : ObjectKey(static_cast<const ObjectKey &&>(C)) {}
609 if (C.Owned) {
610 Owned.reset(new std::string(*C.Owned));
611 Data = *Owned;
612 } else {
613 Data = C.Data;
614 }
615 return *this;
616 }
618
619 operator llvm::StringRef() const { return Data; }
620 std::string str() const { return Data.str(); }
621
622private:
623 // FIXME: this is unneccesarily large (3 pointers). Pointer + length + owned
624 // could be 2 pointers at most.
625 std::unique_ptr<std::string> Owned;
626 llvm::StringRef Data;
627};
628
629inline bool operator==(const ObjectKey &L, const ObjectKey &R) {
630 return llvm::StringRef(L) == llvm::StringRef(R);
631}
632inline bool operator!=(const ObjectKey &L, const ObjectKey &R) {
633 return !(L == R);
634}
635inline bool operator<(const ObjectKey &L, const ObjectKey &R) {
636 return StringRef(L) < StringRef(R);
637}
638
642};
643
644inline Object::Object(std::initializer_list<KV> Properties) {
645 for (const auto &P : Properties) {
646 auto R = try_emplace(P.K, nullptr);
647 if (R.second)
648 R.first->getSecond().moveFrom(std::move(P.V));
649 }
650}
651inline std::pair<Object::iterator, bool> Object::insert(KV E) {
652 return try_emplace(std::move(E.K), std::move(E.V));
653}
654inline bool Object::erase(StringRef K) {
655 return M.erase(ObjectKey(K));
656}
657
658LLVM_ABI std::vector<const Object::value_type *>
659sortedElements(const Object &O);
660
661/// A "cursor" marking a position within a Value.
662/// The Value is a tree, and this is the path from the root to the current node.
663/// This is used to associate errors with particular subobjects.
664class Path {
665public:
666 class Root;
667
668 /// Records that the value at the current path is invalid.
669 /// Message is e.g. "expected number" and becomes part of the final error.
670 /// This overwrites any previously written error message in the root.
671 LLVM_ABI void report(llvm::StringLiteral Message);
672
673 /// The root may be treated as a Path.
674 Path(Root &R) : Parent(nullptr), Seg(&R) {}
675 /// Derives a path for an array element: this[Index]
676 Path index(unsigned Index) const { return Path(this, Segment(Index)); }
677 /// Derives a path for an object field: this.Field
678 Path field(StringRef Field) const { return Path(this, Segment(Field)); }
679
680private:
681 /// One element in a JSON path: an object field (.foo) or array index [27].
682 /// Exception: the root Path encodes a pointer to the Path::Root.
683 class Segment {
684 uintptr_t Pointer;
685 unsigned Offset;
686
687 public:
688 Segment() = default;
689 Segment(Root *R) : Pointer(reinterpret_cast<uintptr_t>(R)) {}
690 Segment(llvm::StringRef Field)
691 : Pointer(reinterpret_cast<uintptr_t>(Field.data())),
692 Offset(static_cast<unsigned>(Field.size())) {}
693 Segment(unsigned Index) : Pointer(0), Offset(Index) {}
694
695 bool isField() const { return Pointer != 0; }
696 StringRef field() const {
697 return StringRef(reinterpret_cast<const char *>(Pointer), Offset);
698 }
699 unsigned index() const { return Offset; }
700 Root *root() const { return reinterpret_cast<Root *>(Pointer); }
701 };
702
703 const Path *Parent;
704 Segment Seg;
705
706 Path(const Path *Parent, Segment S) : Parent(Parent), Seg(S) {}
707};
708
709/// The root is the trivial Path to the root value.
710/// It also stores the latest reported error and the path where it occurred.
712 llvm::StringRef Name;
713 llvm::StringLiteral ErrorMessage;
714 std::vector<Path::Segment> ErrorPath; // Only valid in error state. Reversed.
715
717
718public:
719 Root(llvm::StringRef Name = "") : Name(Name), ErrorMessage("") {}
720 // No copy/move allowed as there are incoming pointers.
721 Root(Root &&) = delete;
722 Root &operator=(Root &&) = delete;
723 Root(const Root &) = delete;
724 Root &operator=(const Root &) = delete;
725
726 /// Returns the last error reported, or else a generic error.
727 LLVM_ABI Error getError() const;
728 /// Print the root value with the error shown inline as a comment.
729 /// Unrelated parts of the value are elided for brevity, e.g.
730 /// {
731 /// "id": 42,
732 /// "name": /* expected string */ null,
733 /// "properties": { ... }
734 /// }
735 LLVM_ABI void printErrorContext(const Value &, llvm::raw_ostream &) const;
736};
737
738// Standard deserializers are provided for primitive types.
739// See comments on Value.
740inline bool fromJSON(const Value &E, std::string &Out, Path P) {
741 if (auto S = E.getAsString()) {
742 Out = std::string(*S);
743 return true;
744 }
745 P.report("expected string");
746 return false;
747}
748inline bool fromJSON(const Value &E, int &Out, Path P) {
749 if (auto S = E.getAsInteger()) {
750 Out = *S;
751 return true;
752 }
753 P.report("expected integer");
754 return false;
755}
756inline bool fromJSON(const Value &E, int64_t &Out, Path P) {
757 if (auto S = E.getAsInteger()) {
758 Out = *S;
759 return true;
760 }
761 P.report("expected integer");
762 return false;
763}
764inline bool fromJSON(const Value &E, double &Out, Path P) {
765 if (auto S = E.getAsNumber()) {
766 Out = *S;
767 return true;
768 }
769 P.report("expected number");
770 return false;
771}
772inline bool fromJSON(const Value &E, bool &Out, Path P) {
773 if (auto S = E.getAsBoolean()) {
774 Out = *S;
775 return true;
776 }
777 P.report("expected boolean");
778 return false;
779}
780inline bool fromJSON(const Value &E, unsigned int &Out, Path P) {
781 if (auto S = E.getAsInteger()) {
782 Out = *S;
783 return true;
784 }
785 P.report("expected unsigned integer");
786 return false;
787}
788inline bool fromJSON(const Value &E, uint64_t &Out, Path P) {
789 if (auto S = E.getAsUINT64()) {
790 Out = *S;
791 return true;
792 }
793 P.report("expected uint64_t");
794 return false;
795}
796inline bool fromJSON(const Value &E, std::nullptr_t &Out, Path P) {
797 if (auto S = E.getAsNull()) {
798 Out = *S;
799 return true;
800 }
801 P.report("expected null");
802 return false;
803}
804template <typename T>
805bool fromJSON(const Value &E, std::optional<T> &Out, Path P) {
806 if (E.getAsNull()) {
807 Out = std::nullopt;
808 return true;
809 }
810 T Result = {};
811 if (!fromJSON(E, Result, P))
812 return false;
813 Out = std::move(Result);
814 return true;
815}
816template <typename T>
817bool fromJSON(const Value &E, std::vector<T> &Out, Path P) {
818 if (auto *A = E.getAsArray()) {
819 Out.clear();
820 Out.resize(A->size());
821 for (size_t I = 0; I < A->size(); ++I)
822 if (!fromJSON((*A)[I], Out[I], P.index(I)))
823 return false;
824 return true;
825 }
826 P.report("expected array");
827 return false;
828}
829template <typename T>
830bool fromJSON(const Value &E, std::map<std::string, T> &Out, Path P) {
831 if (auto *O = E.getAsObject()) {
832 Out.clear();
833 for (const auto &KV : *O)
834 if (!fromJSON(KV.second, Out[std::string(llvm::StringRef(KV.first))],
835 P.field(KV.first)))
836 return false;
837 return true;
838 }
839 P.report("expected object");
840 return false;
841}
842
843// Allow serialization of std::optional<T> for supported T.
844template <typename T> Value toJSON(const std::optional<T> &Opt) {
845 return Opt ? Value(*Opt) : Value(nullptr);
846}
847
848/// Helper for mapping JSON objects onto protocol structs.
849///
850/// Example:
851/// \code
852/// bool fromJSON(const Value &E, MyStruct &R, Path P) {
853/// ObjectMapper O(E, P);
854/// // When returning false, error details were already reported.
855/// return O && O.map("mandatory_field", R.MandatoryField) &&
856/// O.mapOptional("optional_field", R.OptionalField);
857/// }
858/// \endcode
860public:
861 /// If O is not an object, this mapper is invalid and an error is reported.
862 ObjectMapper(const Value &E, Path P) : O(E.getAsObject()), P(P) {
863 if (!O)
864 P.report("expected object");
865 }
866
867 /// True if the expression is an object.
868 /// Must be checked before calling map().
869 operator bool() const { return O; }
870
871 /// Maps a property to a field.
872 /// If the property is missing or invalid, reports an error.
873 template <typename T> bool map(StringLiteral Prop, T &Out) {
874 assert(*this && "Must check this is an object before calling map()");
875 if (const Value *E = O->get(Prop))
876 return fromJSON(*E, Out, P.field(Prop));
877 P.field(Prop).report("missing value");
878 return false;
879 }
880
881 /// Maps a property to a field, if it exists.
882 /// If the property exists and is invalid, reports an error.
883 /// (Optional requires special handling, because missing keys are OK).
884 template <typename T> bool map(StringLiteral Prop, std::optional<T> &Out) {
885 assert(*this && "Must check this is an object before calling map()");
886 if (const Value *E = O->get(Prop))
887 return fromJSON(*E, Out, P.field(Prop));
888 Out = std::nullopt;
889 return true;
890 }
891
892 /// Maps a property to a field, if it exists.
893 /// If the property exists and is invalid, reports an error.
894 /// If the property does not exist, Out is unchanged.
895 template <typename T> bool mapOptional(StringLiteral Prop, T &Out) {
896 assert(*this && "Must check this is an object before calling map()");
897 if (const Value *E = O->get(Prop))
898 return fromJSON(*E, Out, P.field(Prop));
899 return true;
900 }
901
902private:
903 const Object *O;
904 Path P;
905};
906
907/// Parses the provided JSON source, or returns a ParseError.
908/// The returned Value is self-contained and owns its strings (they do not refer
909/// to the original source).
911
912class ParseError : public llvm::ErrorInfo<ParseError> {
913 const char *Msg;
914 unsigned Line, Column, Offset;
915
916public:
917 LLVM_ABI static char ID;
918 ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
919 : Msg(Msg), Line(Line), Column(Column), Offset(Offset) {}
920 void log(llvm::raw_ostream &OS) const override {
921 OS << llvm::formatv("[{0}:{1}, byte={2}]: {3}", Line, Column, Offset, Msg);
922 }
923 std::error_code convertToErrorCode() const override {
925 }
926};
927
928/// Version of parse() that converts the parsed value to the type T.
929/// RootName describes the root object and is used in error messages.
930template <typename T>
931Expected<T> parse(const llvm::StringRef &JSON, const char *RootName = "") {
932 auto V = parse(JSON);
933 if (!V)
934 return V.takeError();
935 Path::Root R(RootName);
936 T Result;
937 if (fromJSON(*V, Result, R))
938 return std::move(Result);
939 return R.getError();
940}
941
942/// json::OStream allows writing well-formed JSON without materializing
943/// all structures as json::Value ahead of time.
944/// It's faster, lower-level, and less safe than OS << json::Value.
945/// It also allows emitting more constructs, such as comments.
946///
947/// Only one "top-level" object can be written to a stream.
948/// Simplest usage involves passing lambdas (Blocks) to fill in containers:
949///
950/// json::OStream J(OS);
951/// J.array([&]{
952/// for (const Event &E : Events)
953/// J.object([&] {
954/// J.attribute("timestamp", int64_t(E.Time));
955/// J.attributeArray("participants", [&] {
956/// for (const Participant &P : E.Participants)
957/// J.value(P.toString());
958/// });
959/// });
960/// });
961///
962/// This would produce JSON like:
963///
964/// [
965/// {
966/// "timestamp": 19287398741,
967/// "participants": [
968/// "King Kong",
969/// "Miley Cyrus",
970/// "Cleopatra"
971/// ]
972/// },
973/// ...
974/// ]
975///
976/// The lower level begin/end methods (arrayBegin()) are more flexible but
977/// care must be taken to pair them correctly:
978///
979/// json::OStream J(OS);
980// J.arrayBegin();
981/// for (const Event &E : Events) {
982/// J.objectBegin();
983/// J.attribute("timestamp", int64_t(E.Time));
984/// J.attributeBegin("participants");
985/// for (const Participant &P : E.Participants)
986/// J.value(P.toString());
987/// J.attributeEnd();
988/// J.objectEnd();
989/// }
990/// J.arrayEnd();
991///
992/// If the call sequence isn't valid JSON, asserts will fire in debug mode.
993/// This can be mismatched begin()/end() pairs, trying to emit attributes inside
994/// an array, and so on.
995/// With asserts disabled, this is undefined behavior.
996class OStream {
997 public:
998 using Block = llvm::function_ref<void()>;
999 // If IndentSize is nonzero, output is pretty-printed.
1000 explicit OStream(llvm::raw_ostream &OS, unsigned IndentSize = 0)
1001 : OS(OS), IndentSize(IndentSize) {
1002 Stack.emplace_back();
1003 }
1005 assert(Stack.size() == 1 && "Unmatched begin()/end()");
1006 assert(Stack.back().Ctx == Singleton);
1007 assert(Stack.back().HasValue && "Did not write top-level value");
1008 }
1009
1010 /// Flushes the underlying ostream. OStream does not buffer internally.
1011 void flush() { OS.flush(); }
1012
1013 // High level functions to output a value.
1014 // Valid at top-level (exactly once), in an attribute value (exactly once),
1015 // or in an array (any number of times).
1016
1017 /// Emit a self-contained value (number, string, vector<string> etc).
1018 LLVM_ABI void value(const Value &V);
1019 /// Emit an array whose elements are emitted in the provided Block.
1020 void array(Block Contents) {
1021 arrayBegin();
1022 Contents();
1023 arrayEnd();
1024 }
1025 /// Emit an object whose elements are emitted in the provided Block.
1026 void object(Block Contents) {
1027 objectBegin();
1028 Contents();
1029 objectEnd();
1030 }
1031 /// Emit an externally-serialized value.
1032 /// The caller must write exactly one valid JSON value to the provided stream.
1033 /// No validation or formatting of this value occurs.
1034 void rawValue(llvm::function_ref<void(raw_ostream &)> Contents) {
1035 rawValueBegin();
1036 Contents(OS);
1037 rawValueEnd();
1038 }
1039 void rawValue(llvm::StringRef Contents) {
1040 rawValue([&](raw_ostream &OS) { OS << Contents; });
1041 }
1042 /// Emit a JavaScript comment associated with the next printed value.
1043 /// The string must be valid until the next attribute or value is emitted.
1044 /// Comments are not part of standard JSON, and many parsers reject them!
1046
1047 // High level functions to output object attributes.
1048 // Valid only within an object (any number of times).
1049
1050 /// Emit an attribute whose value is self-contained (number, vector<int> etc).
1051 void attribute(llvm::StringRef Key, const Value& Contents) {
1052 attributeImpl(Key, [&] { value(Contents); });
1053 }
1054 /// Emit an attribute whose value is an array with elements from the Block.
1056 attributeImpl(Key, [&] { array(Contents); });
1057 }
1058 /// Emit an attribute whose value is an object with attributes from the Block.
1060 attributeImpl(Key, [&] { object(Contents); });
1061 }
1062
1063 // Low-level begin/end functions to output arrays, objects, and attributes.
1064 // Must be correctly paired. Allowed contexts are as above.
1065
1066 LLVM_ABI void arrayBegin();
1067 LLVM_ABI void arrayEnd();
1068 LLVM_ABI void objectBegin();
1069 LLVM_ABI void objectEnd();
1071 LLVM_ABI void attributeEnd();
1073 LLVM_ABI void rawValueEnd();
1074
1075private:
1076 void attributeImpl(llvm::StringRef Key, Block Contents) {
1077 attributeBegin(Key);
1078 Contents();
1079 attributeEnd();
1080 }
1081
1082 LLVM_ABI void valueBegin();
1083 LLVM_ABI void flushComment();
1084 LLVM_ABI void newline();
1085
1086 enum Context {
1087 Singleton, // Top level, or object attribute.
1088 Array,
1089 Object,
1090 RawValue, // External code writing a value to OS directly.
1091 };
1092 struct State {
1093 Context Ctx = Singleton;
1094 bool HasValue = false;
1095 };
1096 llvm::SmallVector<State, 16> Stack; // Never empty.
1097 llvm::StringRef PendingComment;
1099 unsigned IndentSize;
1100 unsigned Indent = 0;
1101};
1102
1103/// Serializes this Value to JSON, writing it to the provided stream.
1104/// The formatting is compact (no extra whitespace) and deterministic.
1105/// For pretty-printing, use the formatv() format_provider below.
1107 OStream(OS).value(V);
1108 return OS;
1109}
1110} // namespace json
1111
1112/// Allow printing json::Value with formatv().
1113/// The default style is basic/compact formatting, like operator<<.
1114/// A format string like formatv("{0:2}", Value) pretty-prints with indent 2.
1115template <> struct format_provider<llvm::json::Value> {
1116 LLVM_ABI static void format(const llvm::json::Value &, raw_ostream &,
1117 StringRef);
1118};
1119} // namespace llvm
1120
1121#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
RelocType Type
Definition: COFFYAML.cpp:410
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:336
#define LLVM_ABI
Definition: Compiler.h:213
#define __asan_unpoison_memory_region(p, size)
Definition: Compiler.h:569
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:638
#define LLVM_LIKELY(EXPR)
Definition: Compiler.h:335
Given that RA is a live value
This file defines the DenseMap class.
uint32_t Index
#define I(x, y, z)
Definition: MD5.cpp:58
#define T
#define P(N)
raw_pwrite_stream & OS
This file defines the SmallVector class.
static Split data
Value * RHS
Value * LHS
bool erase(const KeyT &Val)
Definition: DenseMap.h:319
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition: DenseMap.h:74
BucketT value_type
Definition: DenseMap.h:72
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition: DenseMap.h:76
Base class for user error types.
Definition: Error.h:354
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
Tagged union holding either a T or a Error.
Definition: Error.h:485
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:862
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:233
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
An Array is a JSON array, which contains heterogeneous JSON values.
Definition: JSON.h:164
Value * data()
Definition: JSON.h:547
void emplace_back(Args &&...A)
Definition: JSON.h:562
Value & front()
Definition: JSON.h:543
friend bool operator==(const Array &L, const Array &R)
Definition: JSON.h:580
iterator begin()
Definition: JSON.h:550
size_t size() const
Definition: JSON.h:556
std::vector< Value >::const_iterator const_iterator
Definition: JSON.h:170
Value & operator[](size_t I)
Definition: JSON.h:541
iterator emplace(const_iterator P, Args &&...A)
Definition: JSON.h:577
std::vector< Value >::iterator iterator
Definition: JSON.h:169
void pop_back()
Definition: JSON.h:565
iterator insert(const_iterator P, const Value &E)
Definition: JSON.h:566
bool empty() const
Definition: JSON.h:555
void clear()
Definition: JSON.h:559
void push_back(const Value &E)
Definition: JSON.h:560
void reserve(size_t S)
Definition: JSON.h:557
Array(const Collection &C)
Definition: JSON.h:174
Value & back()
Definition: JSON.h:545
iterator end()
Definition: JSON.h:552
json::OStream allows writing well-formed JSON without materializing all structures as json::Value ahe...
Definition: JSON.h:996
void object(Block Contents)
Emit an object whose elements are emitted in the provided Block.
Definition: JSON.h:1026
void rawValue(llvm::function_ref< void(raw_ostream &)> Contents)
Emit an externally-serialized value.
Definition: JSON.h:1034
void attributeObject(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an object with attributes from the Block.
Definition: JSON.h:1059
OStream(llvm::raw_ostream &OS, unsigned IndentSize=0)
Definition: JSON.h:1000
LLVM_ABI void attributeBegin(llvm::StringRef Key)
Definition: JSON.cpp:880
void attribute(llvm::StringRef Key, const Value &Contents)
Emit an attribute whose value is self-contained (number, vector<int> etc).
Definition: JSON.h:1051
void flush()
Flushes the underlying ostream. OStream does not buffer internally.
Definition: JSON.h:1011
LLVM_ABI void arrayBegin()
Definition: JSON.cpp:842
LLVM_ABI void objectBegin()
Definition: JSON.cpp:861
LLVM_ABI raw_ostream & rawValueBegin()
Definition: JSON.cpp:908
void attributeArray(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an array with elements from the Block.
Definition: JSON.h:1055
LLVM_ABI void comment(llvm::StringRef)
Emit a JavaScript comment associated with the next printed value.
Definition: JSON.cpp:805
void array(Block Contents)
Emit an array whose elements are emitted in the provided Block.
Definition: JSON.h:1020
LLVM_ABI void arrayEnd()
Definition: JSON.cpp:850
LLVM_ABI void attributeEnd()
Definition: JSON.cpp:900
void rawValue(llvm::StringRef Contents)
Definition: JSON.h:1039
LLVM_ABI void value(const Value &V)
Emit a self-contained value (number, string, vector<string> etc).
Definition: JSON.cpp:756
LLVM_ABI void rawValueEnd()
Definition: JSON.cpp:915
llvm::function_ref< void()> Block
Definition: JSON.h:998
LLVM_ABI void objectEnd()
Definition: JSON.cpp:869
ObjectKey is a used to capture keys in Object.
Definition: JSON.h:586
ObjectKey & operator=(ObjectKey &&)=default
ObjectKey(ObjectKey &&C)
Definition: JSON.h:607
ObjectKey(const ObjectKey &C)
Definition: JSON.h:606
ObjectKey(const llvm::formatv_object_base &V)
Definition: JSON.h:604
ObjectKey(const char *S)
Definition: JSON.h:588
ObjectKey(llvm::StringRef S)
Definition: JSON.h:596
ObjectKey(std::string S)
Definition: JSON.h:589
std::string str() const
Definition: JSON.h:620
ObjectKey & operator=(const ObjectKey &C)
Definition: JSON.h:608
ObjectKey(const llvm::SmallVectorImpl< char > &V)
Definition: JSON.h:602
Helper for mapping JSON objects onto protocol structs.
Definition: JSON.h:859
ObjectMapper(const Value &E, Path P)
If O is not an object, this mapper is invalid and an error is reported.
Definition: JSON.h:862
bool map(StringLiteral Prop, T &Out)
Maps a property to a field.
Definition: JSON.h:873
bool mapOptional(StringLiteral Prop, T &Out)
Maps a property to a field, if it exists.
Definition: JSON.h:895
bool map(StringLiteral Prop, std::optional< T > &Out)
Maps a property to a field, if it exists.
Definition: JSON.h:884
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition: JSON.h:98
iterator end()
Definition: JSON.h:117
LLVM_ABI std::optional< bool > getBoolean(StringRef K) const
Definition: JSON.cpp:47
const_iterator end() const
Definition: JSON.h:118
LLVM_ABI Value & operator[](const ObjectKey &K)
Definition: JSON.cpp:24
LLVM_ABI std::optional< double > getNumber(StringRef K) const
Definition: JSON.cpp:52
LLVM_ABI const json::Object * getObject(StringRef K) const
Definition: JSON.cpp:67
LLVM_ABI std::optional< llvm::StringRef > getString(StringRef K) const
Definition: JSON.cpp:62
Storage::value_type value_type
Definition: JSON.h:105
LLVM_ABI Value * get(StringRef K)
Definition: JSON.cpp:30
std::pair< iterator, bool > try_emplace(ObjectKey &&K, Ts &&... Args)
Definition: JSON.h:130
LLVM_ABI std::optional< int64_t > getInteger(StringRef K) const
Definition: JSON.cpp:57
bool erase(StringRef K)
Definition: JSON.h:654
LLVM_ABI std::optional< std::nullptr_t > getNull(StringRef K) const
Definition: JSON.cpp:42
std::pair< iterator, bool > try_emplace(const ObjectKey &K, Ts &&... Args)
Definition: JSON.h:126
const_iterator begin() const
Definition: JSON.h:116
void erase(iterator I)
Definition: JSON.h:134
bool empty() const
Definition: JSON.h:120
const_iterator find(StringRef K) const
Definition: JSON.h:137
iterator begin()
Definition: JSON.h:115
iterator find(StringRef K)
Definition: JSON.h:136
std::pair< iterator, bool > insert(KV E)
Definition: JSON.h:651
size_t size() const
Definition: JSON.h:121
void clear()
Definition: JSON.h:123
LLVM_ABI const json::Array * getArray(StringRef K) const
Definition: JSON.cpp:77
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: JSON.h:923
void log(llvm::raw_ostream &OS) const override
Print an error message to an output stream.
Definition: JSON.h:920
ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
Definition: JSON.h:918
static LLVM_ABI char ID
Definition: JSON.h:917
The root is the trivial Path to the root value.
Definition: JSON.h:711
LLVM_ABI void printErrorContext(const Value &, llvm::raw_ostream &) const
Print the root value with the error shown inline as a comment.
Definition: JSON.cpp:309
Root & operator=(const Root &)=delete
LLVM_ABI Error getError() const
Returns the last error reported, or else a generic error.
Definition: JSON.cpp:228
Root(const Root &)=delete
Root & operator=(Root &&)=delete
Root(llvm::StringRef Name="")
Definition: JSON.h:719
Root(Root &&)=delete
A "cursor" marking a position within a Value.
Definition: JSON.h:664
Path index(unsigned Index) const
Derives a path for an array element: this[Index].
Definition: JSON.h:676
LLVM_ABI void report(llvm::StringLiteral Message)
Records that the value at the current path is invalid.
Definition: JSON.cpp:213
Path field(StringRef Field) const
Derives a path for an object field: this.Field.
Definition: JSON.h:678
Path(Root &R)
The root may be treated as a Path.
Definition: JSON.h:674
A Value is an JSON value of unknown type.
Definition: JSON.h:288
friend class Object
Definition: JSON.h:491
LLVM_ABI void print(llvm::raw_ostream &OS) const
Definition: JSON.cpp:185
Value(json::Object &&Properties)
Definition: JSON.h:310
Value(const std::vector< Elt > &C)
Definition: JSON.h:309
std::optional< bool > getAsBoolean() const
Definition: JSON.h:412
std::optional< double > getAsNumber() const
Definition: JSON.h:417
std::optional< uint64_t > getAsUINT64() const
Definition: JSON.h:445
Value(std::nullptr_t)
Definition: JSON.h:335
Value & operator=(Value &&M)
Definition: JSON.h:377
Value(const char *V)
Definition: JSON.h:334
Value(const Value &M)
Definition: JSON.h:302
Value & operator=(const Value &M)
Definition: JSON.h:372
LLVM_ABI friend bool operator==(const Value &, const Value &)
Definition: JSON.cpp:187
LLVM_DUMP_METHOD void dump() const
Definition: JSON.h:477
Value(const llvm::formatv_object_base &V)
Definition: JSON.h:325
Value(Value &&M)
Definition: JSON.h:303
json::Object * getAsObject()
Definition: JSON.h:465
std::optional< int64_t > getAsInteger() const
Definition: JSON.h:427
Value(const llvm::SmallVectorImpl< char > &V)
Definition: JSON.h:323
Kind kind() const
Definition: JSON.h:384
Value(std::string V)
Definition: JSON.h:316
Value(const std::map< std::string, Elt > &C)
Definition: JSON.h:314
json::Array * getAsArray()
Definition: JSON.h:471
Value(json::Array &&Elements)
Definition: JSON.h:305
@ Number
Number values can store both int64s and doubles at full precision, depending on what they were constr...
Definition: JSON.h:295
friend class Array
Definition: JSON.h:490
Value(const T &V)
Definition: JSON.h:370
Value(StringRef V)
Definition: JSON.h:327
std::optional< llvm::StringRef > getAsString() const
Definition: JSON.h:455
std::optional< std::nullptr_t > getAsNull() const
Definition: JSON.h:407
const json::Object * getAsObject() const
Definition: JSON.h:462
const json::Array * getAsArray() const
Definition: JSON.h:468
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
constexpr bool is_uint_64_bit_v
Definition: JSON.h:79
Value toJSON(const std::optional< T > &Opt)
Definition: JSON.h:844
bool operator<(const ObjectKey &L, const ObjectKey &R)
Definition: JSON.h:635
LLVM_ABI bool isUTF8(llvm::StringRef S, size_t *ErrOffset=nullptr)
Returns true if S is valid UTF-8, which is required for use as JSON.
Definition: JSON.cpp:695
bool fromJSON(const Value &E, std::string &Out, Path P)
Definition: JSON.h:740
LLVM_ABI std::vector< const Object::value_type * > sortedElements(const Object &O)
Definition: JSON.cpp:247
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const Value &V)
Serializes this Value to JSON, writing it to the provided stream.
Definition: JSON.h:1106
LLVM_ABI std::string fixUTF8(llvm::StringRef S)
Replaces invalid UTF-8 sequences in S with the replacement character (U+FFFD).
Definition: JSON.cpp:709
bool operator!=(const Object &LHS, const Object &RHS)
Definition: JSON.h:158
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1702
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:126
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
#define N
A suitably aligned and sized character array member which can hold elements of any type.
Definition: AlignOf.h:22
Definition: regcomp.c:186