LLVM  15.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"
50 #include "llvm/ADT/SmallVector.h"
51 #include "llvm/ADT/StringRef.h"
53 #include "llvm/Support/Error.h"
56 #include <map>
57 
58 namespace llvm {
59 namespace json {
60 
61 // === String encodings ===
62 //
63 // JSON strings are character sequences (not byte sequences like std::string).
64 // We need to know the encoding, and for simplicity only support UTF-8.
65 //
66 // - When parsing, invalid UTF-8 is a syntax error like any other
67 //
68 // - When creating Values from strings, callers must ensure they are UTF-8.
69 // with asserts on, invalid UTF-8 will crash the program
70 // with asserts off, we'll substitute the replacement character (U+FFFD)
71 // Callers can use json::isUTF8() and json::fixUTF8() for validation.
72 //
73 // - When retrieving strings from Values (e.g. asString()), the result will
74 // always be valid UTF-8.
75 
76 /// Returns true if \p S is valid UTF-8, which is required for use as JSON.
77 /// If it returns false, \p Offset is set to a byte offset near the first error.
78 bool isUTF8(llvm::StringRef S, size_t *ErrOffset = nullptr);
79 /// Replaces invalid UTF-8 sequences in \p S with the replacement character
80 /// (U+FFFD). The returned string is valid UTF-8.
81 /// This is much slower than isUTF8, so test that first.
82 std::string fixUTF8(llvm::StringRef S);
83 
84 class Array;
85 class ObjectKey;
86 class Value;
87 template <typename T> Value toJSON(const llvm::Optional<T> &Opt);
88 
89 /// An Object is a JSON object, which maps strings to heterogenous JSON values.
90 /// It simulates DenseMap<ObjectKey, Value>. ObjectKey is a maybe-owned string.
91 class Object {
93  Storage M;
94 
95 public:
97  using mapped_type = Value;
101 
102  Object() = default;
103  // KV is a trivial key-value struct for list-initialization.
104  // (using std::pair forces extra copies).
105  struct KV;
106  explicit Object(std::initializer_list<KV> Properties);
107 
108  iterator begin() { return M.begin(); }
109  const_iterator begin() const { return M.begin(); }
110  iterator end() { return M.end(); }
111  const_iterator end() const { return M.end(); }
112 
113  bool empty() const { return M.empty(); }
114  size_t size() const { return M.size(); }
115 
116  void clear() { M.clear(); }
117  std::pair<iterator, bool> insert(KV E);
118  template <typename... Ts>
119  std::pair<iterator, bool> try_emplace(const ObjectKey &K, Ts &&... Args) {
120  return M.try_emplace(K, std::forward<Ts>(Args)...);
121  }
122  template <typename... Ts>
123  std::pair<iterator, bool> try_emplace(ObjectKey &&K, Ts &&... Args) {
124  return M.try_emplace(std::move(K), std::forward<Ts>(Args)...);
125  }
126  bool erase(StringRef K);
127  void erase(iterator I) { M.erase(I); }
128 
129  iterator find(StringRef K) { return M.find_as(K); }
130  const_iterator find(StringRef K) const { return M.find_as(K); }
131  // operator[] acts as if Value was default-constructible as null.
132  Value &operator[](const ObjectKey &K);
133  Value &operator[](ObjectKey &&K);
134  // Look up a property, returning nullptr if it doesn't exist.
135  Value *get(StringRef K);
136  const Value *get(StringRef K) const;
137  // Typed accessors return None/nullptr if
138  // - the property doesn't exist
139  // - or it has the wrong type
145  const json::Object *getObject(StringRef K) const;
147  const json::Array *getArray(StringRef K) const;
149 };
150 bool operator==(const Object &LHS, const Object &RHS);
151 inline bool operator!=(const Object &LHS, const Object &RHS) {
152  return !(LHS == RHS);
153 }
154 
155 /// An Array is a JSON array, which contains heterogeneous JSON values.
156 /// It simulates std::vector<Value>.
157 class Array {
158  std::vector<Value> V;
159 
160 public:
161  using value_type = Value;
162  using iterator = std::vector<Value>::iterator;
163  using const_iterator = std::vector<Value>::const_iterator;
164 
165  Array() = default;
166  explicit Array(std::initializer_list<Value> Elements);
167  template <typename Collection> explicit Array(const Collection &C) {
168  for (const auto &V : C)
169  emplace_back(V);
170  }
171 
172  Value &operator[](size_t I) { return V[I]; }
173  const Value &operator[](size_t I) const { return V[I]; }
174  Value &front() { return V.front(); }
175  const Value &front() const { return V.front(); }
176  Value &back() { return V.back(); }
177  const Value &back() const { return V.back(); }
178  Value *data() { return V.data(); }
179  const Value *data() const { return V.data(); }
180 
181  iterator begin() { return V.begin(); }
182  const_iterator begin() const { return V.begin(); }
183  iterator end() { return V.end(); }
184  const_iterator end() const { return V.end(); }
185 
186  bool empty() const { return V.empty(); }
187  size_t size() const { return V.size(); }
188  void reserve(size_t S) { V.reserve(S); }
189 
190  void clear() { V.clear(); }
191  void push_back(const Value &E) { V.push_back(E); }
192  void push_back(Value &&E) { V.push_back(std::move(E)); }
193  template <typename... Args> void emplace_back(Args &&... A) {
194  V.emplace_back(std::forward<Args>(A)...);
195  }
196  void pop_back() { V.pop_back(); }
197  // FIXME: insert() takes const_iterator since C++11, old libstdc++ disagrees.
198  iterator insert(iterator P, const Value &E) { return V.insert(P, E); }
200  return V.insert(P, std::move(E));
201  }
202  template <typename It> iterator insert(iterator P, It A, It Z) {
203  return V.insert(P, A, Z);
204  }
205  template <typename... Args> iterator emplace(const_iterator P, Args &&... A) {
206  return V.emplace(P, std::forward<Args>(A)...);
207  }
208 
209  friend bool operator==(const Array &L, const Array &R) { return L.V == R.V; }
210 };
211 inline 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 (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 (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 /// - 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 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);
290 class Value {
291 public:
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  Value(std::initializer_list<Value> Elements);
307  Value(json::Array &&Elements) : Type(T_Array) {
308  create<json::Array>(std::move(Elements));
309  }
310  template <typename Elt>
311  Value(const std::vector<Elt> &C) : Value(json::Array(C)) {}
312  Value(json::Object &&Properties) : Type(T_Object) {
313  create<json::Object>(std::move(Properties));
314  }
315  template <typename Elt>
316  Value(const std::map<std::string, Elt> &C) : Value(json::Object(C)) {}
317  // Strings: types with value semantics. Must be valid UTF-8.
318  Value(std::string V) : Type(T_String) {
319  if (LLVM_UNLIKELY(!isUTF8(V))) {
320  assert(false && "Invalid UTF-8 in value used as JSON");
321  V = fixUTF8(std::move(V));
322  }
323  create<std::string>(std::move(V));
324  }
326  : Value(std::string(V.begin(), V.end())) {}
327  Value(const llvm::formatv_object_base &V) : Value(V.str()) {}
328  // Strings: types with reference semantics. Must be valid UTF-8.
329  Value(StringRef V) : Type(T_StringRef) {
330  create<llvm::StringRef>(V);
331  if (LLVM_UNLIKELY(!isUTF8(V))) {
332  assert(false && "Invalid UTF-8 in value used as JSON");
333  *this = Value(fixUTF8(V));
334  }
335  }
336  Value(const char *V) : Value(StringRef(V)) {}
337  Value(std::nullptr_t) : Type(T_Null) {}
338  // Boolean (disallow implicit conversions).
339  // (The last template parameter is a dummy to keep templates distinct.)
340  template <typename T,
341  typename = std::enable_if_t<std::is_same<T, bool>::value>,
342  bool = false>
343  Value(T B) : Type(T_Boolean) {
344  create<bool>(B);
345  }
346 
347  // Unsigned 64-bit long integers.
348  template <typename T,
349  typename = std::enable_if_t<std::is_same<T, uint64_t>::value>,
350  bool = false, bool = false>
351  Value(T V) : Type(T_UINT64) {
352  create<uint64_t>(uint64_t{V});
353  }
354 
355  // Integers (except boolean and uint64_t).
356  // Must be non-narrowing convertible to int64_t.
357  template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>,
358  typename = std::enable_if_t<!std::is_same<T, bool>::value>,
359  typename = std::enable_if_t<!std::is_same<T, uint64_t>::value>>
360  Value(T I) : Type(T_Integer) {
361  create<int64_t>(int64_t{I});
362  }
363  // Floating point. Must be non-narrowing convertible to double.
364  template <typename T,
365  typename = std::enable_if_t<std::is_floating_point<T>::value>,
366  double * = nullptr>
367  Value(T D) : Type(T_Double) {
368  create<double>(double{D});
369  }
370  // Serializable types: with a toJSON(const T&)->Value function, found by ADL.
371  template <typename T,
372  typename = std::enable_if_t<std::is_same<
373  Value, decltype(toJSON(*(const T *)nullptr))>::value>,
374  Value * = nullptr>
375  Value(const T &V) : Value(toJSON(V)) {}
376 
377  Value &operator=(const Value &M) {
378  destroy();
379  copyFrom(M);
380  return *this;
381  }
383  destroy();
384  moveFrom(std::move(M));
385  return *this;
386  }
387  ~Value() { destroy(); }
388 
389  Kind kind() const {
390  switch (Type) {
391  case T_Null:
392  return Null;
393  case T_Boolean:
394  return Boolean;
395  case T_Double:
396  case T_Integer:
397  case T_UINT64:
398  return Number;
399  case T_String:
400  case T_StringRef:
401  return String;
402  case T_Object:
403  return Object;
404  case T_Array:
405  return Array;
406  }
407  llvm_unreachable("Unknown kind");
408  }
409 
410  // Typed accessors return None/nullptr if the Value is not of this type.
412  if (LLVM_LIKELY(Type == T_Null))
413  return nullptr;
414  return llvm::None;
415  }
417  if (LLVM_LIKELY(Type == T_Boolean))
418  return as<bool>();
419  return llvm::None;
420  }
422  if (LLVM_LIKELY(Type == T_Double))
423  return as<double>();
424  if (LLVM_LIKELY(Type == T_Integer))
425  return as<int64_t>();
426  if (LLVM_LIKELY(Type == T_UINT64))
427  return as<uint64_t>();
428  return llvm::None;
429  }
430  // Succeeds if the Value is a Number, and exactly representable as int64_t.
432  if (LLVM_LIKELY(Type == T_Integer))
433  return as<int64_t>();
434  if (LLVM_LIKELY(Type == T_Double)) {
435  double D = as<double>();
436  if (LLVM_LIKELY(std::modf(D, &D) == 0.0 &&
437  D >= double(std::numeric_limits<int64_t>::min()) &&
438  D <= double(std::numeric_limits<int64_t>::max())))
439  return D;
440  }
441  return llvm::None;
442  }
444  if (Type == T_UINT64)
445  return as<uint64_t>();
446  else if (Type == T_Integer) {
447  int64_t N = as<int64_t>();
448  if (N >= 0)
449  return as<uint64_t>();
450  }
451  return llvm::None;
452  }
454  if (Type == T_String)
455  return llvm::StringRef(as<std::string>());
456  if (LLVM_LIKELY(Type == T_StringRef))
457  return as<llvm::StringRef>();
458  return llvm::None;
459  }
460  const json::Object *getAsObject() const {
461  return LLVM_LIKELY(Type == T_Object) ? &as<json::Object>() : nullptr;
462  }
464  return LLVM_LIKELY(Type == T_Object) ? &as<json::Object>() : nullptr;
465  }
466  const json::Array *getAsArray() const {
467  return LLVM_LIKELY(Type == T_Array) ? &as<json::Array>() : nullptr;
468  }
470  return LLVM_LIKELY(Type == T_Array) ? &as<json::Array>() : nullptr;
471  }
472 
473 private:
474  void destroy();
475  void copyFrom(const Value &M);
476  // We allow moving from *const* Values, by marking all members as mutable!
477  // This hack is needed to support initializer-list syntax efficiently.
478  // (std::initializer_list<T> is a container of const T).
479  void moveFrom(const Value &&M);
480  friend class Array;
481  friend class Object;
482 
483  template <typename T, typename... U> void create(U &&... V) {
484  new (reinterpret_cast<T *>(&Union)) T(std::forward<U>(V)...);
485  }
486  template <typename T> T &as() const {
487  // Using this two-step static_cast via void * instead of reinterpret_cast
488  // silences a -Wstrict-aliasing false positive from GCC6 and earlier.
489  void *Storage = static_cast<void *>(&Union);
490  return *static_cast<T *>(Storage);
491  }
492 
493  friend class OStream;
494 
495  enum ValueType : char16_t {
496  T_Null,
497  T_Boolean,
498  T_Double,
499  T_Integer,
500  T_UINT64,
501  T_StringRef,
502  T_String,
503  T_Object,
504  T_Array,
505  };
506  // All members mutable, see moveFrom().
507  mutable ValueType Type;
508  mutable llvm::AlignedCharArrayUnion<bool, double, int64_t, uint64_t,
509  llvm::StringRef, std::string, json::Array,
510  json::Object>
511  Union;
512  friend bool operator==(const Value &, const Value &);
513 };
514 
515 bool operator==(const Value &, const Value &);
516 inline bool operator!=(const Value &L, const Value &R) { return !(L == R); }
517 
518 /// ObjectKey is a used to capture keys in Object. Like Value but:
519 /// - only strings are allowed
520 /// - it's optimized for the string literal case (Owned == nullptr)
521 /// Like Value, strings must be UTF-8. See isUTF8 documentation for details.
522 class ObjectKey {
523 public:
524  ObjectKey(const char *S) : ObjectKey(StringRef(S)) {}
525  ObjectKey(std::string S) : Owned(new std::string(std::move(S))) {
526  if (LLVM_UNLIKELY(!isUTF8(*Owned))) {
527  assert(false && "Invalid UTF-8 in value used as JSON");
528  *Owned = fixUTF8(std::move(*Owned));
529  }
530  Data = *Owned;
531  }
533  if (LLVM_UNLIKELY(!isUTF8(Data))) {
534  assert(false && "Invalid UTF-8 in value used as JSON");
535  *this = ObjectKey(fixUTF8(S));
536  }
537  }
539  : ObjectKey(std::string(V.begin(), V.end())) {}
541 
542  ObjectKey(const ObjectKey &C) { *this = C; }
543  ObjectKey(ObjectKey &&C) : ObjectKey(static_cast<const ObjectKey &&>(C)) {}
545  if (C.Owned) {
546  Owned.reset(new std::string(*C.Owned));
547  Data = *Owned;
548  } else {
549  Data = C.Data;
550  }
551  return *this;
552  }
553  ObjectKey &operator=(ObjectKey &&) = default;
554 
555  operator llvm::StringRef() const { return Data; }
556  std::string str() const { return Data.str(); }
557 
558 private:
559  // FIXME: this is unneccesarily large (3 pointers). Pointer + length + owned
560  // could be 2 pointers at most.
561  std::unique_ptr<std::string> Owned;
562  llvm::StringRef Data;
563 };
564 
565 inline bool operator==(const ObjectKey &L, const ObjectKey &R) {
566  return llvm::StringRef(L) == llvm::StringRef(R);
567 }
568 inline bool operator!=(const ObjectKey &L, const ObjectKey &R) {
569  return !(L == R);
570 }
571 inline bool operator<(const ObjectKey &L, const ObjectKey &R) {
572  return StringRef(L) < StringRef(R);
573 }
574 
575 struct Object::KV {
578 };
579 
580 inline Object::Object(std::initializer_list<KV> Properties) {
581  for (const auto &P : Properties) {
582  auto R = try_emplace(P.K, nullptr);
583  if (R.second)
584  R.first->getSecond().moveFrom(std::move(P.V));
585  }
586 }
587 inline std::pair<Object::iterator, bool> Object::insert(KV E) {
588  return try_emplace(std::move(E.K), std::move(E.V));
589 }
590 inline bool Object::erase(StringRef K) {
591  return M.erase(ObjectKey(K));
592 }
593 
594 /// A "cursor" marking a position within a Value.
595 /// The Value is a tree, and this is the path from the root to the current node.
596 /// This is used to associate errors with particular subobjects.
597 class Path {
598 public:
599  class Root;
600 
601  /// Records that the value at the current path is invalid.
602  /// Message is e.g. "expected number" and becomes part of the final error.
603  /// This overwrites any previously written error message in the root.
604  void report(llvm::StringLiteral Message);
605 
606  /// The root may be treated as a Path.
607  Path(Root &R) : Parent(nullptr), Seg(&R) {}
608  /// Derives a path for an array element: this[Index]
609  Path index(unsigned Index) const { return Path(this, Segment(Index)); }
610  /// Derives a path for an object field: this.Field
611  Path field(StringRef Field) const { return Path(this, Segment(Field)); }
612 
613 private:
614  /// One element in a JSON path: an object field (.foo) or array index [27].
615  /// Exception: the root Path encodes a pointer to the Path::Root.
616  class Segment {
617  uintptr_t Pointer;
618  unsigned Offset;
619 
620  public:
621  Segment() = default;
622  Segment(Root *R) : Pointer(reinterpret_cast<uintptr_t>(R)) {}
623  Segment(llvm::StringRef Field)
624  : Pointer(reinterpret_cast<uintptr_t>(Field.data())),
625  Offset(static_cast<unsigned>(Field.size())) {}
626  Segment(unsigned Index) : Pointer(0), Offset(Index) {}
627 
628  bool isField() const { return Pointer != 0; }
629  StringRef field() const {
630  return StringRef(reinterpret_cast<const char *>(Pointer), Offset);
631  }
632  unsigned index() const { return Offset; }
633  Root *root() const { return reinterpret_cast<Root *>(Pointer); }
634  };
635 
636  const Path *Parent;
637  Segment Seg;
638 
639  Path(const Path *Parent, Segment S) : Parent(Parent), Seg(S) {}
640 };
641 
642 /// The root is the trivial Path to the root value.
643 /// It also stores the latest reported error and the path where it occurred.
644 class Path::Root {
645  llvm::StringRef Name;
646  llvm::StringLiteral ErrorMessage;
647  std::vector<Path::Segment> ErrorPath; // Only valid in error state. Reversed.
648 
649  friend void Path::report(llvm::StringLiteral Message);
650 
651 public:
652  Root(llvm::StringRef Name = "") : Name(Name), ErrorMessage("") {}
653  // No copy/move allowed as there are incoming pointers.
654  Root(Root &&) = delete;
655  Root &operator=(Root &&) = delete;
656  Root(const Root &) = delete;
657  Root &operator=(const Root &) = delete;
658 
659  /// Returns the last error reported, or else a generic error.
660  Error getError() const;
661  /// Print the root value with the error shown inline as a comment.
662  /// Unrelated parts of the value are elided for brevity, e.g.
663  /// {
664  /// "id": 42,
665  /// "name": /* expected string */ null,
666  /// "properties": { ... }
667  /// }
668  void printErrorContext(const Value &, llvm::raw_ostream &) const;
669 };
670 
671 // Standard deserializers are provided for primitive types.
672 // See comments on Value.
673 inline bool fromJSON(const Value &E, std::string &Out, Path P) {
674  if (auto S = E.getAsString()) {
675  Out = std::string(*S);
676  return true;
677  }
678  P.report("expected string");
679  return false;
680 }
681 inline bool fromJSON(const Value &E, int &Out, Path P) {
682  if (auto S = E.getAsInteger()) {
683  Out = *S;
684  return true;
685  }
686  P.report("expected integer");
687  return false;
688 }
689 inline bool fromJSON(const Value &E, int64_t &Out, Path P) {
690  if (auto S = E.getAsInteger()) {
691  Out = *S;
692  return true;
693  }
694  P.report("expected integer");
695  return false;
696 }
697 inline bool fromJSON(const Value &E, double &Out, Path P) {
698  if (auto S = E.getAsNumber()) {
699  Out = *S;
700  return true;
701  }
702  P.report("expected number");
703  return false;
704 }
705 inline bool fromJSON(const Value &E, bool &Out, Path P) {
706  if (auto S = E.getAsBoolean()) {
707  Out = *S;
708  return true;
709  }
710  P.report("expected boolean");
711  return false;
712 }
713 inline bool fromJSON(const Value &E, uint64_t &Out, Path P) {
714  if (auto S = E.getAsUINT64()) {
715  Out = *S;
716  return true;
717  }
718  P.report("expected uint64_t");
719  return false;
720 }
721 inline bool fromJSON(const Value &E, std::nullptr_t &Out, Path P) {
722  if (auto S = E.getAsNull()) {
723  Out = *S;
724  return true;
725  }
726  P.report("expected null");
727  return false;
728 }
729 template <typename T>
730 bool fromJSON(const Value &E, llvm::Optional<T> &Out, Path P) {
731  if (E.getAsNull()) {
732  Out = llvm::None;
733  return true;
734  }
735  T Result;
736  if (!fromJSON(E, Result, P))
737  return false;
738  Out = std::move(Result);
739  return true;
740 }
741 template <typename T>
742 bool fromJSON(const Value &E, std::vector<T> &Out, Path P) {
743  if (auto *A = E.getAsArray()) {
744  Out.clear();
745  Out.resize(A->size());
746  for (size_t I = 0; I < A->size(); ++I)
747  if (!fromJSON((*A)[I], Out[I], P.index(I)))
748  return false;
749  return true;
750  }
751  P.report("expected array");
752  return false;
753 }
754 template <typename T>
755 bool fromJSON(const Value &E, std::map<std::string, T> &Out, Path P) {
756  if (auto *O = E.getAsObject()) {
757  Out.clear();
758  for (const auto &KV : *O)
759  if (!fromJSON(KV.second, Out[std::string(llvm::StringRef(KV.first))],
760  P.field(KV.first)))
761  return false;
762  return true;
763  }
764  P.report("expected object");
765  return false;
766 }
767 
768 // Allow serialization of Optional<T> for supported T.
769 template <typename T> Value toJSON(const llvm::Optional<T> &Opt) {
770  return Opt ? Value(*Opt) : Value(nullptr);
771 }
772 
773 /// Helper for mapping JSON objects onto protocol structs.
774 ///
775 /// Example:
776 /// \code
777 /// bool fromJSON(const Value &E, MyStruct &R, Path P) {
778 /// ObjectMapper O(E, P);
779 /// // When returning false, error details were already reported.
780 /// return O && O.map("mandatory_field", R.MandatoryField) &&
781 /// O.mapOptional("optional_field", R.OptionalField);
782 /// }
783 /// \endcode
785 public:
786  /// If O is not an object, this mapper is invalid and an error is reported.
787  ObjectMapper(const Value &E, Path P) : O(E.getAsObject()), P(P) {
788  if (!O)
789  P.report("expected object");
790  }
791 
792  /// True if the expression is an object.
793  /// Must be checked before calling map().
794  operator bool() const { return O; }
795 
796  /// Maps a property to a field.
797  /// If the property is missing or invalid, reports an error.
798  template <typename T> bool map(StringLiteral Prop, T &Out) {
799  assert(*this && "Must check this is an object before calling map()");
800  if (const Value *E = O->get(Prop))
801  return fromJSON(*E, Out, P.field(Prop));
802  P.field(Prop).report("missing value");
803  return false;
804  }
805 
806  /// Maps a property to a field, if it exists.
807  /// If the property exists and is invalid, reports an error.
808  /// (Optional requires special handling, because missing keys are OK).
809  template <typename T> bool map(StringLiteral Prop, llvm::Optional<T> &Out) {
810  assert(*this && "Must check this is an object before calling map()");
811  if (const Value *E = O->get(Prop))
812  return fromJSON(*E, Out, P.field(Prop));
813  Out = llvm::None;
814  return true;
815  }
816 
817  /// Maps a property to a field, if it exists.
818  /// If the property exists and is invalid, reports an error.
819  /// If the property does not exist, Out is unchanged.
820  template <typename T> bool mapOptional(StringLiteral Prop, T &Out) {
821  assert(*this && "Must check this is an object before calling map()");
822  if (const Value *E = O->get(Prop))
823  return fromJSON(*E, Out, P.field(Prop));
824  return true;
825  }
826 
827 private:
828  const Object *O;
829  Path P;
830 };
831 
832 /// Parses the provided JSON source, or returns a ParseError.
833 /// The returned Value is self-contained and owns its strings (they do not refer
834 /// to the original source).
836 
837 class ParseError : public llvm::ErrorInfo<ParseError> {
838  const char *Msg;
839  unsigned Line, Column, Offset;
840 
841 public:
842  static char ID;
843  ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
844  : Msg(Msg), Line(Line), Column(Column), Offset(Offset) {}
845  void log(llvm::raw_ostream &OS) const override {
846  OS << llvm::formatv("[{0}:{1}, byte={2}]: {3}", Line, Column, Offset, Msg);
847  }
848  std::error_code convertToErrorCode() const override {
850  }
851 };
852 
853 /// Version of parse() that converts the parsed value to the type T.
854 /// RootName describes the root object and is used in error messages.
855 template <typename T>
856 Expected<T> parse(const llvm::StringRef &JSON, const char *RootName = "") {
857  auto V = parse(JSON);
858  if (!V)
859  return V.takeError();
860  Path::Root R(RootName);
861  T Result;
862  if (fromJSON(*V, Result, R))
863  return std::move(Result);
864  return R.getError();
865 }
866 
867 /// json::OStream allows writing well-formed JSON without materializing
868 /// all structures as json::Value ahead of time.
869 /// It's faster, lower-level, and less safe than OS << json::Value.
870 /// It also allows emitting more constructs, such as comments.
871 ///
872 /// Only one "top-level" object can be written to a stream.
873 /// Simplest usage involves passing lambdas (Blocks) to fill in containers:
874 ///
875 /// json::OStream J(OS);
876 /// J.array([&]{
877 /// for (const Event &E : Events)
878 /// J.object([&] {
879 /// J.attribute("timestamp", int64_t(E.Time));
880 /// J.attributeArray("participants", [&] {
881 /// for (const Participant &P : E.Participants)
882 /// J.value(P.toString());
883 /// });
884 /// });
885 /// });
886 ///
887 /// This would produce JSON like:
888 ///
889 /// [
890 /// {
891 /// "timestamp": 19287398741,
892 /// "participants": [
893 /// "King Kong",
894 /// "Miley Cyrus",
895 /// "Cleopatra"
896 /// ]
897 /// },
898 /// ...
899 /// ]
900 ///
901 /// The lower level begin/end methods (arrayBegin()) are more flexible but
902 /// care must be taken to pair them correctly:
903 ///
904 /// json::OStream J(OS);
905 // J.arrayBegin();
906 /// for (const Event &E : Events) {
907 /// J.objectBegin();
908 /// J.attribute("timestamp", int64_t(E.Time));
909 /// J.attributeBegin("participants");
910 /// for (const Participant &P : E.Participants)
911 /// J.value(P.toString());
912 /// J.attributeEnd();
913 /// J.objectEnd();
914 /// }
915 /// J.arrayEnd();
916 ///
917 /// If the call sequence isn't valid JSON, asserts will fire in debug mode.
918 /// This can be mismatched begin()/end() pairs, trying to emit attributes inside
919 /// an array, and so on.
920 /// With asserts disabled, this is undefined behavior.
921 class OStream {
922  public:
923  using Block = llvm::function_ref<void()>;
924  // If IndentSize is nonzero, output is pretty-printed.
925  explicit OStream(llvm::raw_ostream &OS, unsigned IndentSize = 0)
926  : OS(OS), IndentSize(IndentSize) {
927  Stack.emplace_back();
928  }
930  assert(Stack.size() == 1 && "Unmatched begin()/end()");
931  assert(Stack.back().Ctx == Singleton);
932  assert(Stack.back().HasValue && "Did not write top-level value");
933  }
934 
935  /// Flushes the underlying ostream. OStream does not buffer internally.
936  void flush() { OS.flush(); }
937 
938  // High level functions to output a value.
939  // Valid at top-level (exactly once), in an attribute value (exactly once),
940  // or in an array (any number of times).
941 
942  /// Emit a self-contained value (number, string, vector<string> etc).
943  void value(const Value &V);
944  /// Emit an array whose elements are emitted in the provided Block.
945  void array(Block Contents) {
946  arrayBegin();
947  Contents();
948  arrayEnd();
949  }
950  /// Emit an object whose elements are emitted in the provided Block.
951  void object(Block Contents) {
952  objectBegin();
953  Contents();
954  objectEnd();
955  }
956  /// Emit an externally-serialized value.
957  /// The caller must write exactly one valid JSON value to the provided stream.
958  /// No validation or formatting of this value occurs.
959  void rawValue(llvm::function_ref<void(raw_ostream &)> Contents) {
960  rawValueBegin();
961  Contents(OS);
962  rawValueEnd();
963  }
964  void rawValue(llvm::StringRef Contents) {
965  rawValue([&](raw_ostream &OS) { OS << Contents; });
966  }
967  /// Emit a JavaScript comment associated with the next printed value.
968  /// The string must be valid until the next attribute or value is emitted.
969  /// Comments are not part of standard JSON, and many parsers reject them!
970  void comment(llvm::StringRef);
971 
972  // High level functions to output object attributes.
973  // Valid only within an object (any number of times).
974 
975  /// Emit an attribute whose value is self-contained (number, vector<int> etc).
976  void attribute(llvm::StringRef Key, const Value& Contents) {
977  attributeImpl(Key, [&] { value(Contents); });
978  }
979  /// Emit an attribute whose value is an array with elements from the Block.
981  attributeImpl(Key, [&] { array(Contents); });
982  }
983  /// Emit an attribute whose value is an object with attributes from the Block.
985  attributeImpl(Key, [&] { object(Contents); });
986  }
987 
988  // Low-level begin/end functions to output arrays, objects, and attributes.
989  // Must be correctly paired. Allowed contexts are as above.
990 
991  void arrayBegin();
992  void arrayEnd();
993  void objectBegin();
994  void objectEnd();
996  void attributeEnd();
998  void rawValueEnd();
999 
1000 private:
1001  void attributeImpl(llvm::StringRef Key, Block Contents) {
1003  Contents();
1004  attributeEnd();
1005  }
1006 
1007  void valueBegin();
1008  void flushComment();
1009  void newline();
1010 
1011  enum Context {
1012  Singleton, // Top level, or object attribute.
1013  Array,
1014  Object,
1015  RawValue, // External code writing a value to OS directly.
1016  };
1017  struct State {
1018  Context Ctx = Singleton;
1019  bool HasValue = false;
1020  };
1021  llvm::SmallVector<State, 16> Stack; // Never empty.
1022  llvm::StringRef PendingComment;
1023  llvm::raw_ostream &OS;
1024  unsigned IndentSize;
1025  unsigned Indent = 0;
1026 };
1027 
1028 /// Serializes this Value to JSON, writing it to the provided stream.
1029 /// The formatting is compact (no extra whitespace) and deterministic.
1030 /// For pretty-printing, use the formatv() format_provider below.
1032  OStream(OS).value(V);
1033  return OS;
1034 }
1035 } // namespace json
1036 
1037 /// Allow printing json::Value with formatv().
1038 /// The default style is basic/compact formatting, like operator<<.
1039 /// A format string like formatv("{0:2}", Value) pretty-prints with indent 2.
1040 template <> struct format_provider<llvm::json::Value> {
1041  static void format(const llvm::json::Value &, raw_ostream &, StringRef);
1042 };
1043 } // namespace llvm
1044 
1045 #endif
llvm::json::Object::Object
Object()=default
llvm::json::Object::erase
bool erase(StringRef K)
Definition: JSON.h:590
llvm::json::Array::operator[]
Value & operator[](size_t I)
Definition: JSON.h:172
llvm::json::OStream::comment
void comment(llvm::StringRef)
Emit a JavaScript comment associated with the next printed value.
Definition: JSON.cpp:804
llvm::json::OStream::attributeBegin
void attributeBegin(llvm::StringRef Key)
Definition: JSON.cpp:879
llvm::json::Path::Root
The root is the trivial Path to the root value.
Definition: JSON.h:644
as
compiles conv shl5 shl ret i32 or10 it would be better as
Definition: README.txt:615
llvm::json::Value
A Value is an JSON value of unknown type.
Definition: JSON.h:290
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:17
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::json::Value::Value
Value(std::nullptr_t)
Definition: JSON.h:337
llvm::json::Value::kind
Kind kind() const
Definition: JSON.h:389
llvm::json::Value::Value
Value(const char *V)
Definition: JSON.h:336
llvm::json::Value::Value
Value(T I)
Definition: JSON.h:360
llvm::json::OStream::~OStream
~OStream()
Definition: JSON.h:929
llvm::format_provider
Definition: FormatVariadicDetails.h:19
llvm::json::Value::Boolean
@ Boolean
Definition: JSON.h:294
llvm::json::Value::Object
friend class Object
Definition: JSON.h:481
llvm::json::Array::empty
bool empty() const
Definition: JSON.h:186
StringRef.h
P
This currently compiles esp xmm0 movsd esp eax eax esp ret We should use not the dag combiner This is because dagcombine2 needs to be able to see through the X86ISD::Wrapper which DAGCombine can t really do The code for turning x load into a single vector load is target independent and should be moved to the dag combiner The code for turning x load into a vector load can only handle a direct load from a global or a direct load from the stack It should be generalized to handle any load from P
Definition: README-SSE.txt:411
llvm::json::OStream::attributeEnd
void attributeEnd()
Definition: JSON.cpp:899
llvm::json::Array::emplace
iterator emplace(const_iterator P, Args &&... A)
Definition: JSON.h:205
llvm::json::Object::find
const_iterator find(StringRef K) const
Definition: JSON.h:130
llvm::json::Array::emplace_back
void emplace_back(Args &&... A)
Definition: JSON.h:193
double
into xmm2 addss xmm2 xmm1 xmm3 addss xmm3 movaps xmm0 unpcklps xmm0 ret seems silly when it could just be one addps Expand libm rounding functions main should enable SSE DAZ mode and other fast SSE modes Think about doing i64 math in SSE regs on x86 This testcase should have no SSE instructions in and only one load from a constant double
Definition: README-SSE.txt:85
llvm::SmallVector< State, 16 >
llvm::json::Value::Value
Value(T V)
Definition: JSON.h:351
Error.h
llvm::json::Value::operator==
friend bool operator==(const Value &, const Value &)
Definition: JSON.cpp:182
llvm::json::Value::getAsNull
llvm::Optional< std::nullptr_t > getAsNull() const
Definition: JSON.h:411
llvm::DenseMapBase::erase
bool erase(const KeyT &Val)
Definition: DenseMap.h:304
llvm::json::ObjectKey::ObjectKey
ObjectKey(const char *S)
Definition: JSON.h:524
llvm::DenseMapIterator
Definition: DenseMap.h:57
llvm::json::OStream::Block
llvm::function_ref< void()> Block
Definition: JSON.h:923
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
DenseMap.h
llvm::sys::path::end
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:235
llvm::sys::path::begin
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:226
llvm::json::Path::Root::printErrorContext
void printErrorContext(const Value &, llvm::raw_ostream &) const
Print the root value with the error shown inline as a comment.
Definition: JSON.cpp:308
llvm::json::OStream::attributeArray
void attributeArray(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an array with elements from the Block.
Definition: JSON.h:980
llvm::json::ObjectMapper::ObjectMapper
ObjectMapper(const Value &E, Path P)
If O is not an object, this mapper is invalid and an error is reported.
Definition: JSON.h:787
llvm::Optional
Definition: APInt.h:33
llvm::json::Value::Null
@ Null
Definition: JSON.h:293
T
#define T
Definition: Mips16ISelLowering.cpp:341
llvm::json::ObjectMapper::map
bool map(StringLiteral Prop, T &Out)
Maps a property to a field.
Definition: JSON.h:798
llvm::json::Object::erase
void erase(iterator I)
Definition: JSON.h:127
llvm::max
Expected< ExpressionValue > max(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:337
llvm::json::Value::getAsNumber
llvm::Optional< double > getAsNumber() const
Definition: JSON.h:421
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
llvm::json::Array::insert
iterator insert(iterator P, const Value &E)
Definition: JSON.h:198
RHS
Value * RHS
Definition: X86PartialReduction.cpp:76
llvm::json::ParseError::log
void log(llvm::raw_ostream &OS) const override
Print an error message to an output stream.
Definition: JSON.h:845
llvm::json::OStream::rawValue
void rawValue(llvm::StringRef Contents)
Definition: JSON.h:964
llvm::AlignedCharArrayUnion
A suitably aligned and sized character array member which can hold elements of any type.
Definition: AlignOf.h:27
llvm::codeview::PointerMode::Pointer
@ Pointer
llvm::json::Array::operator==
friend bool operator==(const Array &L, const Array &R)
Definition: JSON.h:209
llvm::json::Array::push_back
void push_back(const Value &E)
Definition: JSON.h:191
llvm::detail::DenseMapPair< ObjectKey, Value >
llvm::json::ObjectMapper::map
bool map(StringLiteral Prop, llvm::Optional< T > &Out)
Maps a property to a field, if it exists.
Definition: JSON.h:809
llvm::json::Path::report
void report(llvm::StringLiteral Message)
Records that the value at the current path is invalid.
Definition: JSON.cpp:208
llvm::json::Array::const_iterator
std::vector< Value >::const_iterator const_iterator
Definition: JSON.h:163
new
Common register allocation spilling lr str ldr sxth r3 ldr mla r4 can lr mov lr str ldr sxth r3 mla r4 and then merge mul and lr str ldr sxth r3 mla r4 It also increase the likelihood the store may become dead bb27 Successors according to LLVM ID Predecessors according to mbb< bb27, 0x8b0a7c0 > Note ADDri is not a two address instruction its result reg1037 is an operand of the PHI node in bb76 and its operand reg1039 is the result of the PHI node We should treat it as a two address code and make sure the ADDri is scheduled after any node that reads reg1039 Use info(i.e. register scavenger) to assign it a free register to allow reuse the collector could move the objects and invalidate the derived pointer This is bad enough in the first but safe points can crop up unpredictably **array_addr i32 n y store obj * new
Definition: README.txt:125
llvm::RISCVFenceField::R
@ R
Definition: RISCVBaseInfo.h:240
llvm::json::Array::begin
iterator begin()
Definition: JSON.h:181
Context
LLVMContext & Context
Definition: NVVMIntrRange.cpp:66
llvm::DenseMapBase< DenseMap< ObjectKey, Value, llvm::DenseMapInfo< StringRef >, llvm::detail::DenseMapPair< ObjectKey, Value > >, ObjectKey, Value, llvm::DenseMapInfo< StringRef >, llvm::detail::DenseMapPair< ObjectKey, Value > >::const_iterator
DenseMapIterator< ObjectKey, Value, llvm::DenseMapInfo< StringRef >, llvm::detail::DenseMapPair< ObjectKey, Value >, true > const_iterator
Definition: DenseMap.h:73
llvm::json::operator==
bool operator==(const Object &LHS, const Object &RHS)
Definition: JSON.cpp:84
LHS
Value * LHS
Definition: X86PartialReduction.cpp:75
llvm::formatv
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
Definition: FormatVariadic.h:251
llvm::json::ParseError::ParseError
ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
Definition: JSON.h:843
llvm::StringLiteral
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:914
llvm::json::Object::begin
const_iterator begin() const
Definition: JSON.h:109
llvm::json::Object::getString
llvm::Optional< llvm::StringRef > getString(StringRef K) const
Definition: JSON.cpp:59
llvm::json::Value::Value
Value(const Value &M)
Definition: JSON.h:304
llvm::json::Array::back
const Value & back() const
Definition: JSON.h:177
llvm::json::Value::Value
Value(std::string V)
Definition: JSON.h:318
llvm::json::Value::Value
Value(const llvm::formatv_object_base &V)
Definition: JSON.h:327
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::json::OStream::object
void object(Block Contents)
Emit an object whose elements are emitted in the provided Block.
Definition: JSON.h:951
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::json::OStream::array
void array(Block Contents)
Emit an array whose elements are emitted in the provided Block.
Definition: JSON.h:945
llvm::json::Path::Root::Root
Root(llvm::StringRef Name="")
Definition: JSON.h:652
llvm::json::Object::KV::V
Value V
Definition: JSON.h:577
llvm::json::Object::getObject
const json::Object * getObject(StringRef K) const
Definition: JSON.cpp:64
llvm::json::Array::end
iterator end()
Definition: JSON.h:183
llvm::AMDGPU::PALMD::Key
Key
PAL metadata keys.
Definition: AMDGPUMetadata.h:486
llvm::json::ObjectMapper::mapOptional
bool mapOptional(StringLiteral Prop, T &Out)
Maps a property to a field, if it exists.
Definition: JSON.h:820
llvm::json::Array::insert
iterator insert(iterator P, Value &&E)
Definition: JSON.h:199
llvm::dwarf::Index
Index
Definition: Dwarf.h:472
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::json::Value::operator=
Value & operator=(Value &&M)
Definition: JSON.h:382
llvm::json::Value::Number
@ Number
Number values can store both int64s and doubles at full precision, depending on what they were constr...
Definition: JSON.h:297
llvm::json::Value::Array
friend class Array
Definition: JSON.h:480
llvm::json::Array
An Array is a JSON array, which contains heterogeneous JSON values.
Definition: JSON.h:157
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:54
llvm::json::Value::Object
@ Object
Definition: JSON.h:300
llvm::raw_ostream::flush
void flush()
Definition: raw_ostream.h:187
llvm::json::Array::operator[]
const Value & operator[](size_t I) const
Definition: JSON.h:173
STLFunctionalExtras.h
llvm::json::Value::Value
Value(json::Array &&Elements)
Definition: JSON.h:307
llvm::json::parse
llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
Definition: JSON.cpp:683
llvm::json::Object::KV
Definition: JSON.h:575
llvm::json::Object::try_emplace
std::pair< iterator, bool > try_emplace(const ObjectKey &K, Ts &&... Args)
Definition: JSON.h:119
FormatVariadic.h
llvm::StringRef::str
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:249
llvm::None
const NoneType None
Definition: None.h:24
llvm::json::OStream::objectEnd
void objectEnd()
Definition: JSON.cpp:868
llvm::json::Array::size
size_t size() const
Definition: JSON.h:187
llvm::json::Value::Value
Value(T D)
Definition: JSON.h:367
llvm::json::Array::data
const Value * data() const
Definition: JSON.h:179
llvm::json::Object::getNumber
llvm::Optional< double > getNumber(StringRef K) const
Definition: JSON.cpp:49
llvm::json::ObjectKey::ObjectKey
ObjectKey(const llvm::formatv_object_base &V)
Definition: JSON.h:540
llvm::json::Value::Value
Value(StringRef V)
Definition: JSON.h:329
llvm::function_ref
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLFunctionalExtras.h:36
llvm::json::ObjectKey::ObjectKey
ObjectKey(std::string S)
Definition: JSON.h:525
llvm::json::Object::try_emplace
std::pair< iterator, bool > try_emplace(ObjectKey &&K, Ts &&... Args)
Definition: JSON.h:123
llvm::json::Object::find
iterator find(StringRef K)
Definition: JSON.h:129
llvm::json::Value::getAsArray
json::Array * getAsArray()
Definition: JSON.h:469
llvm::RISCVFenceField::O
@ O
Definition: RISCVBaseInfo.h:239
llvm::json::Array::insert
iterator insert(iterator P, It A, It Z)
Definition: JSON.h:202
llvm::json::Value::getAsArray
const json::Array * getAsArray() const
Definition: JSON.h:466
llvm::json::OStream::rawValueEnd
void rawValueEnd()
Definition: JSON.cpp:914
llvm::json::fromJSON
bool fromJSON(const Value &E, std::string &Out, Path P)
Definition: JSON.h:673
llvm::json::OStream
json::OStream allows writing well-formed JSON without materializing all structures as json::Value ahe...
Definition: JSON.h:921
llvm::AMDGPU::Hwreg::Offset
Offset
Definition: SIDefines.h:413
llvm::json::Object::get
Value * get(StringRef K)
Definition: JSON.cpp:27
uint64_t
D
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
const
aarch64 promote const
Definition: AArch64PromoteConstant.cpp:232
llvm::DenseMapBase< DenseMap< ObjectKey, Value, llvm::DenseMapInfo< StringRef >, llvm::detail::DenseMapPair< ObjectKey, Value > >, ObjectKey, Value, llvm::DenseMapInfo< StringRef >, llvm::detail::DenseMapPair< ObjectKey, Value > >::value_type
llvm::detail::DenseMapPair< ObjectKey, Value > value_type
Definition: DenseMap.h:69
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::json::OStream::arrayBegin
void arrayBegin()
Definition: JSON.cpp:841
llvm::DenseMap< ObjectKey, Value, llvm::DenseMapInfo< StringRef > >
llvm::json::Object::operator[]
Value & operator[](const ObjectKey &K)
Definition: JSON.cpp:21
llvm::json::ParseError
Definition: JSON.h:837
llvm::json::Value::getAsInteger
llvm::Optional< int64_t > getAsInteger() const
Definition: JSON.h:431
I
#define I(x, y, z)
Definition: MD5.cpp:58
llvm::json::Path::index
Path index(unsigned Index) const
Derives a path for an array element: this[Index].
Definition: JSON.h:609
llvm::json::operator!=
bool operator!=(const Object &LHS, const Object &RHS)
Definition: JSON.h:151
TemplateParamKind::Type
@ Type
llvm::AMDGPU::HSAMD::ValueType
ValueType
Value types.
Definition: AMDGPUMetadata.h:100
llvm::json::Array::data
Value * data()
Definition: JSON.h:178
llvm::json::Array::back
Value & back()
Definition: JSON.h:176
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::move
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:1675
llvm::json::ObjectKey::ObjectKey
ObjectKey(llvm::StringRef S)
Definition: JSON.h:532
llvm::json::fixUTF8
std::string fixUTF8(llvm::StringRef S)
Replaces invalid UTF-8 sequences in S with the replacement character (U+FFFD).
Definition: JSON.cpp:708
llvm::json::Object::empty
bool empty() const
Definition: JSON.h:113
llvm::ErrorInfo
Base class for user error types.
Definition: Error.h:347
llvm::json::Array::Array
Array()=default
llvm::size
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:1598
llvm::json::ParseError::convertToErrorCode
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: JSON.h:848
llvm::json::Value::getAsBoolean
llvm::Optional< bool > getAsBoolean() const
Definition: JSON.h:416
llvm::json::Array::iterator
std::vector< Value >::iterator iterator
Definition: JSON.h:162
llvm::json::Array::pop_back
void pop_back()
Definition: JSON.h:196
llvm::json::Value::getAsUINT64
llvm::Optional< uint64_t > getAsUINT64() const
Definition: JSON.h:443
llvm::min
Expected< ExpressionValue > min(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:357
llvm::json::Object::size
size_t size() const
Definition: JSON.h:114
llvm::json::ObjectKey::ObjectKey
ObjectKey(const ObjectKey &C)
Definition: JSON.h:542
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
llvm::json::Object::getInteger
llvm::Optional< int64_t > getInteger(StringRef K) const
Definition: JSON.cpp:54
llvm::json::Object::end
iterator end()
Definition: JSON.h:110
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:143
llvm::json::Path::field
Path field(StringRef Field) const
Derives a path for an object field: this.Field.
Definition: JSON.h:611
llvm::json::Value::Value
Value(const llvm::SmallVectorImpl< char > &V)
Definition: JSON.h:325
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::json::Array::reserve
void reserve(size_t S)
Definition: JSON.h:188
llvm::json::Object::clear
void clear()
Definition: JSON.h:116
llvm::json::toJSON
Value toJSON(const llvm::Optional< T > &Opt)
Definition: JSON.h:769
llvm::json::ObjectKey::operator=
ObjectKey & operator=(const ObjectKey &C)
Definition: JSON.h:544
llvm::json::Object::end
const_iterator end() const
Definition: JSON.h:111
llvm::format
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
llvm::json::ParseError::ID
static char ID
Definition: JSON.h:842
llvm::json::Value::~Value
~Value()
Definition: JSON.h:387
llvm::PointerUnion< const Value *, const PseudoSourceValue * >
llvm::json::Path::Root::getError
Error getError() const
Returns the last error reported, or else a generic error.
Definition: JSON.cpp:223
llvm::json::Value::Value
Value(T B)
Definition: JSON.h:343
std
Definition: BitVector.h:851
llvm::inconvertibleErrorCode
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77
llvm::json::Value::getAsObject
const json::Object * getAsObject() const
Definition: JSON.h:460
llvm::json::Value::Value
Value(const std::map< std::string, Elt > &C)
Definition: JSON.h:316
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:155
llvm::json::ObjectKey::str
std::string str() const
Definition: JSON.h:556
llvm::TargetStackID::Value
Value
Definition: TargetFrameLowering.h:27
llvm::json::OStream::value
void value(const Value &V)
Emit a self-contained value (number, string, vector<string> etc).
Definition: JSON.cpp:755
llvm::json::Object::getArray
const json::Array * getArray(StringRef K) const
Definition: JSON.cpp:74
llvm::HasValue
detail::ValueMatchesPoly< M > HasValue(M Matcher)
Definition: Error.h:221
llvm::json::operator<<
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:1031
llvm::json::Value::String
@ String
Definition: JSON.h:298
llvm::json::Path::Path
Path(Root &R)
The root may be treated as a Path.
Definition: JSON.h:607
llvm::json::ObjectKey::ObjectKey
ObjectKey(const llvm::SmallVectorImpl< char > &V)
Definition: JSON.h:538
llvm::DenseMapBase< DenseMap< ObjectKey, Value, llvm::DenseMapInfo< StringRef >, llvm::detail::DenseMapPair< ObjectKey, Value > >, ObjectKey, Value, llvm::DenseMapInfo< StringRef >, llvm::detail::DenseMapPair< ObjectKey, Value > >::iterator
DenseMapIterator< ObjectKey, Value, llvm::DenseMapInfo< StringRef >, llvm::detail::DenseMapPair< ObjectKey, Value > > iterator
Definition: DenseMap.h:71
SmallVector.h
llvm::json::Value::Array
@ Array
Definition: JSON.h:299
llvm::json::Value::Value
Value(Value &&M)
Definition: JSON.h:305
llvm::json::Value::Value
Value(const std::vector< Elt > &C)
Definition: JSON.h:311
N
#define N
P
#define P(N)
llvm::json::OStream::arrayEnd
void arrayEnd()
Definition: JSON.cpp:849
llvm::json::Value::getAsObject
json::Object * getAsObject()
Definition: JSON.h:463
llvm::json::Array::end
const_iterator end() const
Definition: JSON.h:184
llvm::json::Array::front
const Value & front() const
Definition: JSON.h:175
LLVM_LIKELY
#define LLVM_LIKELY(EXPR)
Definition: Compiler.h:219
llvm::json::Array::Array
Array(const Collection &C)
Definition: JSON.h:167
llvm::SmallVectorImpl< char >
llvm::json::Value::Value
Value(json::Object &&Properties)
Definition: JSON.h:312
llvm::json::OStream::attributeObject
void attributeObject(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an object with attributes from the Block.
Definition: JSON.h:984
llvm::json::Value::Kind
Kind
Definition: JSON.h:292
llvm::json::Value::Value
Value(const T &V)
Definition: JSON.h:375
llvm::formatv_object_base
Definition: FormatVariadic.h:66
llvm::json::isUTF8
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:694
llvm::OptimizedStructLayoutField
A field in a structure.
Definition: OptimizedStructLayout.h:45
llvm::json::ObjectKey
ObjectKey is a used to capture keys in Object.
Definition: JSON.h:522
llvm::json::ObjectKey::ObjectKey
ObjectKey(ObjectKey &&C)
Definition: JSON.h:543
llvm::AMDGPU::HSAMD::Kernel::Key::Args
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Definition: AMDGPUMetadata.h:394
llvm::json::OStream::attribute
void attribute(llvm::StringRef Key, const Value &Contents)
Emit an attribute whose value is self-contained (number, vector<int> etc).
Definition: JSON.h:976
LLVM_UNLIKELY
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:220
raw_ostream.h
llvm::json::Object
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition: JSON.h:91
llvm::json::Value::getAsString
llvm::Optional< llvm::StringRef > getAsString() const
Definition: JSON.h:453
llvm::json::Object::insert
std::pair< iterator, bool > insert(KV E)
Definition: JSON.h:587
llvm::json::Object::KV::K
ObjectKey K
Definition: JSON.h:576
llvm::json::OStream::rawValueBegin
raw_ostream & rawValueBegin()
Definition: JSON.cpp:907
llvm::json::Object::getBoolean
llvm::Optional< bool > getBoolean(StringRef K) const
Definition: JSON.cpp:44
llvm::json::Array::push_back
void push_back(Value &&E)
Definition: JSON.h:192
llvm::json::Array::clear
void clear()
Definition: JSON.h:190
llvm::json::OStream::objectBegin
void objectBegin()
Definition: JSON.cpp:860
llvm::json::Path
A "cursor" marking a position within a Value.
Definition: JSON.h:597
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
llvm::json::OStream::OStream
OStream(llvm::raw_ostream &OS, unsigned IndentSize=0)
Definition: JSON.h:925
llvm::json::OStream::flush
void flush()
Flushes the underlying ostream. OStream does not buffer internally.
Definition: JSON.h:936
llvm::json::Array::front
Value & front()
Definition: JSON.h:174
SpecialSubKind::string
@ string
llvm::json::Path::Root::operator=
Root & operator=(Root &&)=delete
llvm::json::ObjectMapper
Helper for mapping JSON objects onto protocol structs.
Definition: JSON.h:784
llvm::json::Object::begin
iterator begin()
Definition: JSON.h:108
llvm::SmallVectorImpl::emplace_back
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:927
llvm::json::Array::begin
const_iterator begin() const
Definition: JSON.h:182
llvm::json::OStream::rawValue
void rawValue(llvm::function_ref< void(raw_ostream &)> Contents)
Emit an externally-serialized value.
Definition: JSON.h:959
llvm::json::operator<
bool operator<(const ObjectKey &L, const ObjectKey &R)
Definition: JSON.h:571
llvm::json::Object::getNull
llvm::Optional< std::nullptr_t > getNull(StringRef K) const
Definition: JSON.cpp:39
llvm::json::Value::operator=
Value & operator=(const Value &M)
Definition: JSON.h:377