LLVM 23.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"
53#include "llvm/Support/Error.h"
56#include <cmath>
57#include <map>
58
59namespace llvm {
60namespace json {
61
62// === String encodings ===
63//
64// JSON strings are character sequences (not byte sequences like std::string).
65// We need to know the encoding, and for simplicity only support UTF-8.
66//
67// - When parsing, invalid UTF-8 is a syntax error like any other
68//
69// - When creating Values from strings, callers must ensure they are UTF-8.
70// with asserts on, invalid UTF-8 will crash the program
71// with asserts off, we'll substitute the replacement character (U+FFFD)
72// Callers can use json::isUTF8() and json::fixUTF8() for validation.
73//
74// - When retrieving strings from Values (e.g. asString()), the result will
75// always be valid UTF-8.
76
77template <typename T>
78constexpr bool is_uint_64_bit_v =
79 std::is_integral_v<T> && std::is_unsigned_v<T> &&
80 sizeof(T) == sizeof(uint64_t);
81
82/// Returns true if \p S is valid UTF-8, which is required for use as JSON.
83/// If it returns false, \p Offset is set to a byte offset near the first error.
84LLVM_ABI bool isUTF8(llvm::StringRef S, size_t *ErrOffset = nullptr);
85/// Replaces invalid UTF-8 sequences in \p S with the replacement character
86/// (U+FFFD). The returned string is valid UTF-8.
87/// This is much slower than isUTF8, so test that first.
88LLVM_ABI std::string fixUTF8(llvm::StringRef S);
89
90class Array;
91class ObjectKey;
92class Value;
93template <typename T> Value toJSON(const std::optional<T> &Opt);
94
95/// An Object is a JSON object, which maps strings to heterogenous JSON values.
96/// It simulates DenseMap<ObjectKey, Value>. ObjectKey is a maybe-owned string.
97class Object {
99 Storage M;
100
101public:
107
108 Object() = default;
109 // KV is a trivial key-value struct for list-initialization.
110 // (using std::pair forces extra copies).
111 struct KV;
112 explicit Object(std::initializer_list<KV> Properties);
113
114 iterator begin() { return M.begin(); }
115 const_iterator begin() const { return M.begin(); }
116 iterator end() { return M.end(); }
117 const_iterator end() const { return M.end(); }
118
119 bool empty() const { return M.empty(); }
120 size_t size() const { return M.size(); }
121
122 void clear() { M.clear(); }
123 std::pair<iterator, bool> insert(KV E);
124 template <typename... Ts>
125 std::pair<iterator, bool> try_emplace(const ObjectKey &K, Ts &&... Args) {
126 return M.try_emplace(K, std::forward<Ts>(Args)...);
127 }
128 template <typename... Ts>
129 std::pair<iterator, bool> try_emplace(ObjectKey &&K, Ts &&... Args) {
130 return M.try_emplace(std::move(K), std::forward<Ts>(Args)...);
131 }
132 bool erase(StringRef K);
133 void erase(iterator I) { M.erase(I); }
134
135 iterator find(StringRef K) { return M.find_as(K); }
136 const_iterator find(StringRef K) const { return M.find_as(K); }
137 // operator[] acts as if Value was default-constructible as null.
140 // Look up a property, returning nullptr if it doesn't exist.
142 LLVM_ABI const Value *get(StringRef K) const;
143 // Typed accessors return std::nullopt/nullptr if
144 // - the property doesn't exist
145 // - or it has the wrong type
146 LLVM_ABI std::optional<std::nullptr_t> getNull(StringRef K) const;
147 LLVM_ABI std::optional<bool> getBoolean(StringRef K) const;
148 LLVM_ABI std::optional<double> getNumber(StringRef K) const;
149 LLVM_ABI std::optional<int64_t> getInteger(StringRef K) const;
150 LLVM_ABI std::optional<llvm::StringRef> getString(StringRef K) const;
153 LLVM_ABI const json::Array *getArray(StringRef K) const;
155
156 friend LLVM_ABI bool operator==(const Object &LHS, const Object &RHS);
157};
158LLVM_ABI bool operator==(const Object &LHS, const Object &RHS);
159inline bool operator!=(const Object &LHS, const Object &RHS) {
160 return !(LHS == RHS);
161}
162
163/// An Array is a JSON array, which contains heterogeneous JSON values.
164/// It simulates std::vector<Value>.
165class Array {
166 std::vector<Value> V;
167
168public:
170 using iterator = std::vector<Value>::iterator;
171 using const_iterator = std::vector<Value>::const_iterator;
172
173 Array() = default;
174 LLVM_ABI explicit Array(std::initializer_list<Value> Elements);
175 template <typename Collection> explicit Array(const Collection &C) {
176 for (const auto &V : C)
177 emplace_back(V);
178 }
179
180 Value &operator[](size_t I);
181 const Value &operator[](size_t I) const;
182 Value &front();
183 const Value &front() const;
184 Value &back();
185 const Value &back() const;
186 Value *data();
187 const Value *data() const;
188
189 iterator begin();
190 const_iterator begin() const;
191 iterator end();
192 const_iterator end() const;
193
194 bool empty() const;
195 size_t size() const;
196 void reserve(size_t S);
197
198 void clear();
199 void push_back(const Value &E);
200 void push_back(Value &&E);
201 template <typename... Args> void emplace_back(Args &&...A);
202 void pop_back();
205 template <typename It> iterator insert(const_iterator P, It A, It Z);
206 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(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#endif // !NDEBUG || LLVM_ENABLE_DUMP
481
482private:
483 LLVM_ABI void destroy();
484 LLVM_ABI void copyFrom(const Value &M);
485 // We allow moving from *const* Values, by marking all members as mutable!
486 // This hack is needed to support initializer-list syntax efficiently.
487 // (std::initializer_list<T> is a container of const T).
488 LLVM_ABI void moveFrom(const Value &&M);
489 friend class Array;
490 friend class Object;
491
492 template <typename T, typename... U> void create(U &&...V) {
493 new (reinterpret_cast<T *>(&Union)) T(std::forward<U>(V)...);
494 }
495 template <typename T> T &as() const {
496 // Using this two-step static_cast via void * instead of reinterpret_cast
497 // silences a -Wstrict-aliasing false positive from GCC6 and earlier.
498 void *Storage = static_cast<void *>(&Union);
499 return *static_cast<T *>(Storage);
500 }
501
502 friend class OStream;
503
504 enum ValueType : char16_t {
505 T_Null,
506 T_Boolean,
507 T_Double,
508 T_Integer,
509 T_UINT64,
510 T_StringRef,
511 T_String,
512 T_Object,
513 T_Array,
514 };
515 // All members mutable, see moveFrom().
516 mutable ValueType Type;
517 mutable llvm::AlignedCharArrayUnion<bool, double, int64_t, uint64_t,
518 llvm::StringRef, std::string, json::Array,
520 Union;
521 LLVM_ABI friend bool operator==(const Value &, const Value &);
522};
523
524LLVM_ABI bool operator==(const Value &, const Value &);
525inline bool operator!=(const Value &L, const Value &R) { return !(L == R); }
526
527// Array Methods
528inline Value &Array::operator[](size_t I) { return V[I]; }
529inline const Value &Array::operator[](size_t I) const { return V[I]; }
530inline Value &Array::front() { return V.front(); }
531inline const Value &Array::front() const { return V.front(); }
532inline Value &Array::back() { return V.back(); }
533inline const Value &Array::back() const { return V.back(); }
534inline Value *Array::data() { return V.data(); }
535inline const Value *Array::data() const { return V.data(); }
536
537inline Array::iterator Array::begin() { return V.begin(); }
538inline Array::const_iterator Array::begin() const { return V.begin(); }
539inline Array::iterator Array::end() { return V.end(); }
540inline Array::const_iterator Array::end() const { return V.end(); }
541
542inline bool Array::empty() const { return V.empty(); }
543inline size_t Array::size() const { return V.size(); }
544inline void Array::reserve(size_t S) { V.reserve(S); }
545
546inline void Array::clear() { V.clear(); }
547inline void Array::push_back(const Value &E) { V.push_back(E); }
548inline void Array::push_back(Value &&E) { V.push_back(std::move(E)); }
549template <typename... Args> inline void Array::emplace_back(Args &&...A) {
550 V.emplace_back(std::forward<Args>(A)...);
551}
552inline void Array::pop_back() { V.pop_back(); }
554 return V.insert(P, E);
555}
557 return V.insert(P, std::move(E));
558}
559template <typename It>
561 return V.insert(P, A, Z);
562}
563template <typename... Args>
565 return V.emplace(P, std::forward<Args>(A)...);
566}
567inline Array::iterator Array::erase(const_iterator P) { return V.erase(P); }
568inline bool operator==(const Array &L, const Array &R) { return L.V == R.V; }
569
570/// ObjectKey is a used to capture keys in Object. Like Value but:
571/// - only strings are allowed
572/// - it's optimized for the string literal case (Owned == nullptr)
573/// Like Value, strings must be UTF-8. See isUTF8 documentation for details.
575public:
576 ObjectKey(const char *S) : ObjectKey(StringRef(S)) {}
577 ObjectKey(std::string S) : Owned(new std::string(std::move(S))) {
578 if (LLVM_UNLIKELY(!isUTF8(*Owned))) {
579 assert(false && "Invalid UTF-8 in value used as JSON");
580 *Owned = fixUTF8(*Owned);
581 }
582 Data = *Owned;
583 }
585 if (LLVM_UNLIKELY(!isUTF8(Data))) {
586 assert(false && "Invalid UTF-8 in value used as JSON");
587 *this = ObjectKey(fixUTF8(S));
588 }
589 }
591 : ObjectKey(std::string(V.begin(), V.end())) {}
593
594 ObjectKey(const ObjectKey &C) { *this = C; }
595 ObjectKey(ObjectKey &&C) : ObjectKey(static_cast<const ObjectKey &&>(C)) {}
597 if (C.Owned) {
598 Owned.reset(new std::string(*C.Owned));
599 Data = *Owned;
600 } else {
601 Data = C.Data;
602 }
603 return *this;
604 }
606
607 operator llvm::StringRef() const { return Data; }
608 std::string str() const { return Data.str(); }
609
610private:
611 // FIXME: this is unneccesarily large (3 pointers). Pointer + length + owned
612 // could be 2 pointers at most.
613 std::unique_ptr<std::string> Owned;
615};
616
617inline bool operator==(const ObjectKey &L, const ObjectKey &R) {
618 return llvm::StringRef(L) == llvm::StringRef(R);
619}
620inline bool operator!=(const ObjectKey &L, const ObjectKey &R) {
621 return !(L == R);
622}
623inline bool operator<(const ObjectKey &L, const ObjectKey &R) {
624 return StringRef(L) < StringRef(R);
625}
626
631
632inline Object::Object(std::initializer_list<KV> Properties) {
633 for (const auto &P : Properties) {
634 auto R = try_emplace(P.K, nullptr);
635 if (R.second)
636 R.first->getSecond().moveFrom(std::move(P.V));
637 }
638}
639inline std::pair<Object::iterator, bool> Object::insert(KV E) {
640 return try_emplace(std::move(E.K), std::move(E.V));
641}
642inline bool Object::erase(StringRef K) {
643 return M.erase(ObjectKey(K));
644}
645
646LLVM_ABI std::vector<const Object::value_type *>
647sortedElements(const Object &O);
648
649/// A "cursor" marking a position within a Value.
650/// The Value is a tree, and this is the path from the root to the current node.
651/// This is used to associate errors with particular subobjects.
652class Path {
653public:
654 class Root;
655
656 /// Records that the value at the current path is invalid.
657 /// Message is e.g. "expected number" and becomes part of the final error.
658 /// This overwrites any previously written error message in the root.
659 LLVM_ABI void report(llvm::StringLiteral Message);
660
661 /// The root may be treated as a Path.
662 Path(Root &R) : Parent(nullptr), Seg(&R) {}
663 /// Derives a path for an array element: this[Index]
664 Path index(unsigned Index) const { return Path(this, Segment(Index)); }
665 /// Derives a path for an object field: this.Field
666 Path field(StringRef Field) const { return Path(this, Segment(Field)); }
667
668private:
669 /// One element in a JSON path: an object field (.foo) or array index [27].
670 /// Exception: the root Path encodes a pointer to the Path::Root.
671 class Segment {
672 uintptr_t Pointer;
673 unsigned Offset;
674
675 public:
676 Segment() = default;
677 Segment(Root *R) : Pointer(reinterpret_cast<uintptr_t>(R)) {}
678 Segment(llvm::StringRef Field)
679 : Pointer(reinterpret_cast<uintptr_t>(Field.data())),
680 Offset(static_cast<unsigned>(Field.size())) {}
681 Segment(unsigned Index) : Pointer(0), Offset(Index) {}
682
683 bool isField() const { return Pointer != 0; }
684 StringRef field() const {
685 return StringRef(reinterpret_cast<const char *>(Pointer), Offset);
686 }
687 unsigned index() const { return Offset; }
688 Root *root() const { return reinterpret_cast<Root *>(Pointer); }
689 };
690
691 const Path *Parent;
692 Segment Seg;
693
694 Path(const Path *Parent, Segment S) : Parent(Parent), Seg(S) {}
695};
696
697/// The root is the trivial Path to the root value.
698/// It also stores the latest reported error and the path where it occurred.
700 llvm::StringRef Name;
701 llvm::StringLiteral ErrorMessage;
702 std::vector<Path::Segment> ErrorPath; // Only valid in error state. Reversed.
703
705
706public:
707 Root(llvm::StringRef Name = "") : Name(Name), ErrorMessage("") {}
708 // No copy/move allowed as there are incoming pointers.
709 Root(Root &&) = delete;
710 Root &operator=(Root &&) = delete;
711 Root(const Root &) = delete;
712 Root &operator=(const Root &) = delete;
713
714 /// Returns the last error reported, or else a generic error.
715 LLVM_ABI Error getError() const;
716 /// Print the root value with the error shown inline as a comment.
717 /// Unrelated parts of the value are elided for brevity, e.g.
718 /// {
719 /// "id": 42,
720 /// "name": /* expected string */ null,
721 /// "properties": { ... }
722 /// }
723 LLVM_ABI void printErrorContext(const Value &, llvm::raw_ostream &) const;
724};
725
726// Standard deserializers are provided for primitive types.
727// See comments on Value.
728inline bool fromJSON(const Value &E, std::string &Out, Path P) {
729 if (auto S = E.getAsString()) {
730 Out = std::string(*S);
731 return true;
732 }
733 P.report("expected string");
734 return false;
735}
736inline bool fromJSON(const Value &E, int &Out, Path P) {
737 if (auto S = E.getAsInteger()) {
738 Out = *S;
739 return true;
740 }
741 P.report("expected integer");
742 return false;
743}
744inline bool fromJSON(const Value &E, int64_t &Out, Path P) {
745 if (auto S = E.getAsInteger()) {
746 Out = *S;
747 return true;
748 }
749 P.report("expected integer");
750 return false;
751}
752inline bool fromJSON(const Value &E, double &Out, Path P) {
753 if (auto S = E.getAsNumber()) {
754 Out = *S;
755 return true;
756 }
757 P.report("expected number");
758 return false;
759}
760inline bool fromJSON(const Value &E, bool &Out, Path P) {
761 if (auto S = E.getAsBoolean()) {
762 Out = *S;
763 return true;
764 }
765 P.report("expected boolean");
766 return false;
767}
768inline bool fromJSON(const Value &E, unsigned int &Out, Path P) {
769 if (auto S = E.getAsInteger()) {
770 Out = *S;
771 return true;
772 }
773 P.report("expected unsigned integer");
774 return false;
775}
776inline bool fromJSON(const Value &E, uint64_t &Out, Path P) {
777 if (auto S = E.getAsUINT64()) {
778 Out = *S;
779 return true;
780 }
781 P.report("expected uint64_t");
782 return false;
783}
784inline bool fromJSON(const Value &E, std::nullptr_t &Out, Path P) {
785 if (auto S = E.getAsNull()) {
786 Out = *S;
787 return true;
788 }
789 P.report("expected null");
790 return false;
791}
792template <typename T>
793bool fromJSON(const Value &E, std::optional<T> &Out, Path P) {
794 if (E.getAsNull()) {
795 Out = std::nullopt;
796 return true;
797 }
798 T Result{};
799 if (!fromJSON(E, Result, P))
800 return false;
801 Out = std::move(Result);
802 return true;
803}
804template <typename T>
805bool fromJSON(const Value &E, std::vector<T> &Out, Path P) {
806 if (auto *A = E.getAsArray()) {
807 Out.clear();
808 Out.resize(A->size());
809 for (size_t I = 0; I < A->size(); ++I)
810 if (!fromJSON((*A)[I], Out[I], P.index(I)))
811 return false;
812 return true;
813 }
814 P.report("expected array");
815 return false;
816}
817template <typename T>
818bool fromJSON(const Value &E, std::map<std::string, T> &Out, Path P) {
819 if (auto *O = E.getAsObject()) {
820 Out.clear();
821 for (const auto &KV : *O)
822 if (!fromJSON(KV.second, Out[std::string(llvm::StringRef(KV.first))],
823 P.field(KV.first)))
824 return false;
825 return true;
826 }
827 P.report("expected object");
828 return false;
829}
830
831// Allow serialization of std::optional<T> for supported T.
832template <typename T> Value toJSON(const std::optional<T> &Opt) {
833 return Opt ? Value(*Opt) : Value(nullptr);
834}
835
836/// Helper for mapping JSON objects onto protocol structs.
837///
838/// Example:
839/// \code
840/// bool fromJSON(const Value &E, MyStruct &R, Path P) {
841/// ObjectMapper O(E, P);
842/// // When returning false, error details were already reported.
843/// return O && O.map("mandatory_field", R.MandatoryField) &&
844/// O.mapOptional("optional_field", R.OptionalField);
845/// }
846/// \endcode
848public:
849 /// If O is not an object, this mapper is invalid and an error is reported.
850 ObjectMapper(const Value &E, Path P) : O(E.getAsObject()), P(P) {
851 if (!O)
852 P.report("expected object");
853 }
854
855 /// True if the expression is an object.
856 /// Must be checked before calling map().
857 operator bool() const { return O; }
858
859 /// Maps a property to a field.
860 /// If the property is missing or invalid, reports an error.
861 template <typename T> bool map(StringLiteral Prop, T &Out) {
862 assert(*this && "Must check this is an object before calling map()");
863 if (const Value *E = O->get(Prop))
864 return fromJSON(*E, Out, P.field(Prop));
865 P.field(Prop).report("missing value");
866 return false;
867 }
868
869 /// Maps a property to a field, if it exists.
870 /// If the property exists and is invalid, reports an error.
871 /// (Optional requires special handling, because missing keys are OK).
872 template <typename T> bool map(StringLiteral Prop, std::optional<T> &Out) {
873 assert(*this && "Must check this is an object before calling map()");
874 if (const Value *E = O->get(Prop))
875 return fromJSON(*E, Out, P.field(Prop));
876 Out = std::nullopt;
877 return true;
878 }
879
880 /// Maps a property to a field, if it exists.
881 /// If the property exists and is invalid, reports an error.
882 /// If the property does not exist, Out is unchanged.
883 template <typename T> bool mapOptional(StringLiteral Prop, T &Out) {
884 assert(*this && "Must check this is an object before calling map()");
885 if (const Value *E = O->get(Prop))
886 return fromJSON(*E, Out, P.field(Prop));
887 return true;
888 }
889
890private:
891 const Object *O;
892 Path P;
893};
894
895/// Parses the provided JSON source, or returns a ParseError.
896/// The returned Value is self-contained and owns its strings (they do not refer
897/// to the original source).
899
900class ParseError : public llvm::ErrorInfo<ParseError> {
901 const char *Msg;
902 unsigned Line, Column, Offset;
903
904public:
905 LLVM_ABI static char ID;
906 ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
907 : Msg(Msg), Line(Line), Column(Column), Offset(Offset) {}
908 void log(llvm::raw_ostream &OS) const override;
909 std::error_code convertToErrorCode() const override {
911 }
912};
913
914/// Version of parse() that converts the parsed value to the type T.
915/// RootName describes the root object and is used in error messages.
916template <typename T>
917Expected<T> parse(const llvm::StringRef &JSON, const char *RootName = "") {
918 auto V = parse(JSON);
919 if (!V)
920 return V.takeError();
921 Path::Root R(RootName);
922 T Result;
923 if (fromJSON(*V, Result, R))
924 return std::move(Result);
925 return R.getError();
926}
927
928/// json::OStream allows writing well-formed JSON without materializing
929/// all structures as json::Value ahead of time.
930/// It's faster, lower-level, and less safe than OS << json::Value.
931/// It also allows emitting more constructs, such as comments.
932///
933/// Only one "top-level" object can be written to a stream.
934/// Simplest usage involves passing lambdas (Blocks) to fill in containers:
935///
936/// json::OStream J(OS);
937/// J.array([&]{
938/// for (const Event &E : Events)
939/// J.object([&] {
940/// J.attribute("timestamp", int64_t(E.Time));
941/// J.attributeArray("participants", [&] {
942/// for (const Participant &P : E.Participants)
943/// J.value(P.toString());
944/// });
945/// });
946/// });
947///
948/// This would produce JSON like:
949///
950/// [
951/// {
952/// "timestamp": 19287398741,
953/// "participants": [
954/// "King Kong",
955/// "Miley Cyrus",
956/// "Cleopatra"
957/// ]
958/// },
959/// ...
960/// ]
961///
962/// The lower level begin/end methods (arrayBegin()) are more flexible but
963/// care must be taken to pair them correctly:
964///
965/// json::OStream J(OS);
966// J.arrayBegin();
967/// for (const Event &E : Events) {
968/// J.objectBegin();
969/// J.attribute("timestamp", int64_t(E.Time));
970/// J.attributeBegin("participants");
971/// for (const Participant &P : E.Participants)
972/// J.value(P.toString());
973/// J.attributeEnd();
974/// J.objectEnd();
975/// }
976/// J.arrayEnd();
977///
978/// If the call sequence isn't valid JSON, asserts will fire in debug mode.
979/// This can be mismatched begin()/end() pairs, trying to emit attributes inside
980/// an array, and so on.
981/// With asserts disabled, this is undefined behavior.
982class OStream {
983 public:
984 using Block = llvm::function_ref<void()>;
985 // If IndentSize is nonzero, output is pretty-printed.
986 explicit OStream(llvm::raw_ostream &OS, unsigned IndentSize = 0)
987 : OS(OS), IndentSize(IndentSize) {
988 Stack.emplace_back();
989 }
991 assert(Stack.size() == 1 && "Unmatched begin()/end()");
992 assert(Stack.back().Ctx == Singleton);
993 assert(Stack.back().HasValue && "Did not write top-level value");
994 }
995
996 /// Flushes the underlying ostream. OStream does not buffer internally.
997 void flush() { OS.flush(); }
998
999 // High level functions to output a value.
1000 // Valid at top-level (exactly once), in an attribute value (exactly once),
1001 // or in an array (any number of times).
1002
1003 /// Emit a self-contained value (number, string, vector<string> etc).
1004 LLVM_ABI void value(const Value &V);
1005 /// Emit an array whose elements are emitted in the provided Block.
1006 void array(Block Contents) {
1007 arrayBegin();
1008 Contents();
1009 arrayEnd();
1010 }
1011 /// Emit an object whose elements are emitted in the provided Block.
1012 void object(Block Contents) {
1013 objectBegin();
1014 Contents();
1015 objectEnd();
1016 }
1017 /// Emit an externally-serialized value.
1018 /// The caller must write exactly one valid JSON value to the provided stream.
1019 /// No validation or formatting of this value occurs.
1020 void rawValue(llvm::function_ref<void(raw_ostream &)> Contents) {
1021 rawValueBegin();
1022 Contents(OS);
1023 rawValueEnd();
1024 }
1025 void rawValue(llvm::StringRef Contents) {
1026 rawValue([&](raw_ostream &OS) { OS << Contents; });
1027 }
1028 /// Emit a JavaScript comment associated with the next printed value.
1029 /// The string must be valid until the next attribute or value is emitted.
1030 /// Comments are not part of standard JSON, and many parsers reject them!
1032
1033 // High level functions to output object attributes.
1034 // Valid only within an object (any number of times).
1035
1036 /// Emit an attribute whose value is self-contained (number, vector<int> etc).
1037 void attribute(llvm::StringRef Key, const Value& Contents) {
1038 attributeImpl(Key, [&] { value(Contents); });
1039 }
1040 /// Emit an attribute whose value is an array with elements from the Block.
1042 attributeImpl(Key, [&] { array(Contents); });
1043 }
1044 /// Emit an attribute whose value is an object with attributes from the Block.
1046 attributeImpl(Key, [&] { object(Contents); });
1047 }
1048
1049 // Low-level begin/end functions to output arrays, objects, and attributes.
1050 // Must be correctly paired. Allowed contexts are as above.
1051
1052 LLVM_ABI void arrayBegin();
1053 LLVM_ABI void arrayEnd();
1054 LLVM_ABI void objectBegin();
1055 LLVM_ABI void objectEnd();
1057 LLVM_ABI void attributeEnd();
1059 LLVM_ABI void rawValueEnd();
1060
1061private:
1062 void attributeImpl(llvm::StringRef Key, Block Contents) {
1064 Contents();
1065 attributeEnd();
1066 }
1067
1068 LLVM_ABI void valueBegin();
1069 LLVM_ABI void flushComment();
1070 LLVM_ABI void newline();
1071
1072 enum Context {
1073 Singleton, // Top level, or object attribute.
1074 Array,
1075 Object,
1076 RawValue, // External code writing a value to OS directly.
1077 };
1078 struct State {
1079 Context Ctx = Singleton;
1080 bool HasValue = false;
1081 };
1082 llvm::SmallVector<State, 16> Stack; // Never empty.
1083 llvm::StringRef PendingComment;
1084 llvm::raw_ostream &OS;
1085 unsigned IndentSize;
1086 unsigned Indent = 0;
1087};
1088
1089/// Serializes this Value to JSON, writing it to the provided stream.
1090/// The formatting is compact (no extra whitespace) and deterministic.
1091/// For pretty-printing, use the formatv() format_provider below.
1093 OStream(OS).value(V);
1094 return OS;
1095}
1096} // namespace json
1097
1098/// Allow printing json::Value with formatv().
1099/// The default style is basic/compact formatting, like operator<<.
1100/// A format string like formatv("{0:2}", Value) pretty-prints with indent 2.
1101template <> struct format_provider<llvm::json::Value> {
1102 LLVM_ABI static void format(const llvm::json::Value &, raw_ostream &,
1103 StringRef);
1104};
1105} // namespace llvm
1106
1107#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 LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
#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:882
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
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:165
Value * data()
Definition JSON.h:534
void emplace_back(Args &&...A)
Definition JSON.h:549
Value & front()
Definition JSON.h:530
friend bool operator==(const Array &L, const Array &R)
Definition JSON.h:568
iterator begin()
Definition JSON.h:537
size_t size() const
Definition JSON.h:543
std::vector< Value >::const_iterator const_iterator
Definition JSON.h:171
Value & operator[](size_t I)
Definition JSON.h:528
iterator emplace(const_iterator P, Args &&...A)
Definition JSON.h:564
std::vector< Value >::iterator iterator
Definition JSON.h:170
void pop_back()
Definition JSON.h:552
iterator insert(const_iterator P, const Value &E)
Definition JSON.h:553
bool empty() const
Definition JSON.h:542
void clear()
Definition JSON.h:546
void push_back(const Value &E)
Definition JSON.h:547
void reserve(size_t S)
Definition JSON.h:544
Array(const Collection &C)
Definition JSON.h:175
Value value_type
Definition JSON.h:169
iterator erase(const_iterator P)
Definition JSON.h:567
Value & back()
Definition JSON.h:532
iterator end()
Definition JSON.h:539
json::OStream allows writing well-formed JSON without materializing all structures as json::Value ahe...
Definition JSON.h:982
void object(Block Contents)
Emit an object whose elements are emitted in the provided Block.
Definition JSON.h:1012
void rawValue(llvm::function_ref< void(raw_ostream &)> Contents)
Emit an externally-serialized value.
Definition JSON.h:1020
void attributeObject(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an object with attributes from the Block.
Definition JSON.h:1045
OStream(llvm::raw_ostream &OS, unsigned IndentSize=0)
Definition JSON.h:986
LLVM_ABI void attributeBegin(llvm::StringRef Key)
Definition JSON.cpp:883
void attribute(llvm::StringRef Key, const Value &Contents)
Emit an attribute whose value is self-contained (number, vector<int> etc).
Definition JSON.h:1037
void flush()
Flushes the underlying ostream. OStream does not buffer internally.
Definition JSON.h:997
LLVM_ABI void arrayBegin()
Definition JSON.cpp:845
LLVM_ABI void objectBegin()
Definition JSON.cpp:864
LLVM_ABI raw_ostream & rawValueBegin()
Definition JSON.cpp:911
void attributeArray(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an array with elements from the Block.
Definition JSON.h:1041
LLVM_ABI void comment(llvm::StringRef)
Emit a JavaScript comment associated with the next printed value.
Definition JSON.cpp:808
void array(Block Contents)
Emit an array whose elements are emitted in the provided Block.
Definition JSON.h:1006
LLVM_ABI void arrayEnd()
Definition JSON.cpp:853
LLVM_ABI void attributeEnd()
Definition JSON.cpp:903
void rawValue(llvm::StringRef Contents)
Definition JSON.h:1025
LLVM_ABI void value(const Value &V)
Emit a self-contained value (number, string, vector<string> etc).
Definition JSON.cpp:759
LLVM_ABI void rawValueEnd()
Definition JSON.cpp:918
llvm::function_ref< void()> Block
Definition JSON.h:984
LLVM_ABI void objectEnd()
Definition JSON.cpp:872
ObjectKey is a used to capture keys in Object.
Definition JSON.h:574
ObjectKey & operator=(ObjectKey &&)=default
ObjectKey(ObjectKey &&C)
Definition JSON.h:595
ObjectKey(const ObjectKey &C)
Definition JSON.h:594
ObjectKey(const llvm::formatv_object_base &V)
Definition JSON.h:592
ObjectKey(const char *S)
Definition JSON.h:576
ObjectKey(llvm::StringRef S)
Definition JSON.h:584
operator llvm::StringRef() const
Definition JSON.h:607
ObjectKey(std::string S)
Definition JSON.h:577
std::string str() const
Definition JSON.h:608
ObjectKey & operator=(const ObjectKey &C)
Definition JSON.h:596
ObjectKey(const llvm::SmallVectorImpl< char > &V)
Definition JSON.h:590
ObjectMapper(const Value &E, Path P)
If O is not an object, this mapper is invalid and an error is reported.
Definition JSON.h:850
bool map(StringLiteral Prop, T &Out)
Maps a property to a field.
Definition JSON.h:861
bool mapOptional(StringLiteral Prop, T &Out)
Maps a property to a field, if it exists.
Definition JSON.h:883
bool map(StringLiteral Prop, std::optional< T > &Out)
Maps a property to a field, if it exists.
Definition JSON.h:872
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition JSON.h:97
iterator end()
Definition JSON.h:116
LLVM_ABI std::optional< bool > getBoolean(StringRef K) const
Definition JSON.cpp:47
const_iterator end() const
Definition JSON.h:117
LLVM_ABI Value & operator[](const ObjectKey &K)
Definition JSON.cpp:24
Value mapped_type
Definition JSON.h:103
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:104
LLVM_ABI Value * get(StringRef K)
Definition JSON.cpp:30
ObjectKey key_type
Definition JSON.h:102
std::pair< iterator, bool > try_emplace(ObjectKey &&K, Ts &&... Args)
Definition JSON.h:129
LLVM_ABI std::optional< int64_t > getInteger(StringRef K) const
Definition JSON.cpp:57
bool erase(StringRef K)
Definition JSON.h:642
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:125
const_iterator begin() const
Definition JSON.h:115
void erase(iterator I)
Definition JSON.h:133
Storage::iterator iterator
Definition JSON.h:105
bool empty() const
Definition JSON.h:119
const_iterator find(StringRef K) const
Definition JSON.h:136
iterator begin()
Definition JSON.h:114
Storage::const_iterator const_iterator
Definition JSON.h:106
iterator find(StringRef K)
Definition JSON.h:135
std::pair< iterator, bool > insert(KV E)
Definition JSON.h:639
size_t size() const
Definition JSON.h:120
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:909
void log(llvm::raw_ostream &OS) const override
Print an error message to an output stream.
Definition JSON.cpp:694
ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
Definition JSON.h:906
static LLVM_ABI char ID
Definition JSON.h:905
The root is the trivial Path to the root value.
Definition JSON.h:699
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:306
Root & operator=(const Root &)=delete
LLVM_ABI Error getError() const
Returns the last error reported, or else a generic error.
Definition JSON.cpp:225
Root(const Root &)=delete
Root & operator=(Root &&)=delete
Root(llvm::StringRef Name="")
Definition JSON.h:707
Root(Root &&)=delete
A "cursor" marking a position within a Value.
Definition JSON.h:652
Path index(unsigned Index) const
Derives a path for an array element: this[Index].
Definition JSON.h:664
LLVM_ABI void report(llvm::StringLiteral Message)
Records that the value at the current path is invalid.
Definition JSON.cpp:210
Path field(StringRef Field) const
Derives a path for an object field: this.Field.
Definition JSON.h:666
Path(Root &R)
The root may be treated as a Path.
Definition JSON.h:662
A Value is an JSON value of unknown type.
Definition JSON.h:290
friend class Object
Definition JSON.h:490
LLVM_ABI void print(llvm::raw_ostream &OS) const
Definition JSON.cpp:175
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.cpp:178
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:502
Value(const std::map< std::string, Elt > &C)
Definition JSON.h:316
LLVM_ABI friend bool operator==(const Value &, const Value &)
Definition JSON.cpp:184
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:489
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:78
Value toJSON(const std::optional< T > &Opt)
Definition JSON.h:832
LLVM_ABI llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
Definition JSON.cpp:681
bool operator<(const ObjectKey &L, const ObjectKey &R)
Definition JSON.h:623
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:698
bool fromJSON(const Value &E, std::string &Out, Path P)
Definition JSON.h:728
LLVM_ABI std::vector< const Object::value_type * > sortedElements(const Object &O)
Definition JSON.cpp:244
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:1092
LLVM_ABI std::string fixUTF8(llvm::StringRef S)
Replaces invalid UTF-8 sequences in S with the replacement character (U+FFFD).
Definition JSON.cpp:712
bool operator!=(const Object &LHS, const Object &RHS)
Definition JSON.h:159
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:557
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:1668
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:94
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:221
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:1916
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:874
#define N
A suitably aligned and sized character array member which can hold elements of any type.
Definition AlignOf.h:22