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