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