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