LLVM  9.0.0svn
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 /// Typically, JSON data would be read from an external source, parsed into
25 /// a Value, and then converted into some native data structure before doing
26 /// real work on it. (And vice versa when writing).
27 ///
28 /// Other serialization mechanisms you may consider:
29 ///
30 /// - YAML is also text-based, and more human-readable than JSON. It's a more
31 /// complex format and data model, and YAML parsers aren't ubiquitous.
32 /// YAMLParser.h is a streaming parser suitable for parsing large documents
33 /// (including JSON, as YAML is a superset). It can be awkward to use
34 /// directly. YAML I/O (YAMLTraits.h) provides data mapping that is more
35 /// declarative than the toJSON/fromJSON conventions here.
36 ///
37 /// - LLVM bitstream is a space- and CPU- efficient binary format. Typically it
38 /// encodes LLVM IR ("bitcode"), but it can be a container for other data.
39 /// Low-level reader/writer libraries are in Bitcode/Bitstream*.h
40 ///
41 //===---------------------------------------------------------------------===//
42 
43 #ifndef LLVM_SUPPORT_JSON_H
44 #define LLVM_SUPPORT_JSON_H
45 
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/ADT/StringRef.h"
49 #include "llvm/Support/Error.h"
52 #include <map>
53 
54 namespace llvm {
55 namespace json {
56 
57 // === String encodings ===
58 //
59 // JSON strings are character sequences (not byte sequences like std::string).
60 // We need to know the encoding, and for simplicity only support UTF-8.
61 //
62 // - When parsing, invalid UTF-8 is a syntax error like any other
63 //
64 // - When creating Values from strings, callers must ensure they are UTF-8.
65 // with asserts on, invalid UTF-8 will crash the program
66 // with asserts off, we'll substitute the replacement character (U+FFFD)
67 // Callers can use json::isUTF8() and json::fixUTF8() for validation.
68 //
69 // - When retrieving strings from Values (e.g. asString()), the result will
70 // always be valid UTF-8.
71 
72 /// Returns true if \p S is valid UTF-8, which is required for use as JSON.
73 /// If it returns false, \p Offset is set to a byte offset near the first error.
74 bool isUTF8(llvm::StringRef S, size_t *ErrOffset = nullptr);
75 /// Replaces invalid UTF-8 sequences in \p S with the replacement character
76 /// (U+FFFD). The returned string is valid UTF-8.
77 /// This is much slower than isUTF8, so test that first.
78 std::string fixUTF8(llvm::StringRef S);
79 
80 class Array;
81 class ObjectKey;
82 class Value;
83 template <typename T> Value toJSON(const llvm::Optional<T> &Opt);
84 
85 /// An Object is a JSON object, which maps strings to heterogenous JSON values.
86 /// It simulates DenseMap<ObjectKey, Value>. ObjectKey is a maybe-owned string.
87 class Object {
89  Storage M;
90 
91 public:
93  using mapped_type = Value;
97 
98  explicit Object() = default;
99  // KV is a trivial key-value struct for list-initialization.
100  // (using std::pair forces extra copies).
101  struct KV;
102  explicit Object(std::initializer_list<KV> Properties);
103 
104  iterator begin() { return M.begin(); }
105  const_iterator begin() const { return M.begin(); }
106  iterator end() { return M.end(); }
107  const_iterator end() const { return M.end(); }
108 
109  bool empty() const { return M.empty(); }
110  size_t size() const { return M.size(); }
111 
112  void clear() { M.clear(); }
113  std::pair<iterator, bool> insert(KV E);
114  template <typename... Ts>
115  std::pair<iterator, bool> try_emplace(const ObjectKey &K, Ts &&... Args) {
116  return M.try_emplace(K, std::forward<Ts>(Args)...);
117  }
118  template <typename... Ts>
119  std::pair<iterator, bool> try_emplace(ObjectKey &&K, Ts &&... Args) {
120  return M.try_emplace(std::move(K), std::forward<Ts>(Args)...);
121  }
122 
123  iterator find(StringRef K) { return M.find_as(K); }
124  const_iterator find(StringRef K) const { return M.find_as(K); }
125  // operator[] acts as if Value was default-constructible as null.
126  Value &operator[](const ObjectKey &K);
127  Value &operator[](ObjectKey &&K);
128  // Look up a property, returning nullptr if it doesn't exist.
129  Value *get(StringRef K);
130  const Value *get(StringRef K) const;
131  // Typed accessors return None/nullptr if
132  // - the property doesn't exist
133  // - or it has the wrong type
139  const json::Object *getObject(StringRef K) const;
141  const json::Array *getArray(StringRef K) const;
143 };
144 bool operator==(const Object &LHS, const Object &RHS);
145 inline bool operator!=(const Object &LHS, const Object &RHS) {
146  return !(LHS == RHS);
147 }
148 
149 /// An Array is a JSON array, which contains heterogeneous JSON values.
150 /// It simulates std::vector<Value>.
151 class Array {
152  std::vector<Value> V;
153 
154 public:
155  using value_type = Value;
156  using iterator = std::vector<Value>::iterator;
157  using const_iterator = std::vector<Value>::const_iterator;
158 
159  explicit Array() = default;
160  explicit Array(std::initializer_list<Value> Elements);
161  template <typename Collection> explicit Array(const Collection &C) {
162  for (const auto &V : C)
163  emplace_back(V);
164  }
165 
166  Value &operator[](size_t I) { return V[I]; }
167  const Value &operator[](size_t I) const { return V[I]; }
168  Value &front() { return V.front(); }
169  const Value &front() const { return V.front(); }
170  Value &back() { return V.back(); }
171  const Value &back() const { return V.back(); }
172  Value *data() { return V.data(); }
173  const Value *data() const { return V.data(); }
174 
175  iterator begin() { return V.begin(); }
176  const_iterator begin() const { return V.begin(); }
177  iterator end() { return V.end(); }
178  const_iterator end() const { return V.end(); }
179 
180  bool empty() const { return V.empty(); }
181  size_t size() const { return V.size(); }
182 
183  void clear() { V.clear(); }
184  void push_back(const Value &E) { V.push_back(E); }
185  void push_back(Value &&E) { V.push_back(std::move(E)); }
186  template <typename... Args> void emplace_back(Args &&... A) {
187  V.emplace_back(std::forward<Args>(A)...);
188  }
189  void pop_back() { V.pop_back(); }
190  // FIXME: insert() takes const_iterator since C++11, old libstdc++ disagrees.
191  iterator insert(iterator P, const Value &E) { return V.insert(P, E); }
193  return V.insert(P, std::move(E));
194  }
195  template <typename It> iterator insert(iterator P, It A, It Z) {
196  return V.insert(P, A, Z);
197  }
198  template <typename... Args> iterator emplace(const_iterator P, Args &&... A) {
199  return V.emplace(P, std::forward<Args>(A)...);
200  }
201 
202  friend bool operator==(const Array &L, const Array &R) { return L.V == R.V; }
203 };
204 inline bool operator!=(const Array &L, const Array &R) { return !(L == R); }
205 
206 /// A Value is an JSON value of unknown type.
207 /// They can be copied, but should generally be moved.
208 ///
209 /// === Composing values ===
210 ///
211 /// You can implicitly construct Values from:
212 /// - strings: std::string, SmallString, formatv, StringRef, char*
213 /// (char*, and StringRef are references, not copies!)
214 /// - numbers
215 /// - booleans
216 /// - null: nullptr
217 /// - arrays: {"foo", 42.0, false}
218 /// - serializable things: types with toJSON(const T&)->Value, found by ADL
219 ///
220 /// They can also be constructed from object/array helpers:
221 /// - json::Object is a type like map<ObjectKey, Value>
222 /// - json::Array is a type like vector<Value>
223 /// These can be list-initialized, or used to build up collections in a loop.
224 /// json::ary(Collection) converts all items in a collection to Values.
225 ///
226 /// === Inspecting values ===
227 ///
228 /// Each Value is one of the JSON kinds:
229 /// null (nullptr_t)
230 /// boolean (bool)
231 /// number (double or int64)
232 /// string (StringRef)
233 /// array (json::Array)
234 /// object (json::Object)
235 ///
236 /// The kind can be queried directly, or implicitly via the typed accessors:
237 /// if (Optional<StringRef> S = E.getAsString()
238 /// assert(E.kind() == Value::String);
239 ///
240 /// Array and Object also have typed indexing accessors for easy traversal:
241 /// Expected<Value> E = parse(R"( {"options": {"font": "sans-serif"}} )");
242 /// if (Object* O = E->getAsObject())
243 /// if (Object* Opts = O->getObject("options"))
244 /// if (Optional<StringRef> Font = Opts->getString("font"))
245 /// assert(Opts->at("font").kind() == Value::String);
246 ///
247 /// === Converting JSON values to C++ types ===
248 ///
249 /// The convention is to have a deserializer function findable via ADL:
250 /// fromJSON(const json::Value&, T&)->bool
251 /// Deserializers are provided for:
252 /// - bool
253 /// - int and int64_t
254 /// - double
255 /// - std::string
256 /// - vector<T>, where T is deserializable
257 /// - map<string, T>, where T is deserializable
258 /// - Optional<T>, where T is deserializable
259 /// ObjectMapper can help writing fromJSON() functions for object types.
260 ///
261 /// For conversion in the other direction, the serializer function is:
262 /// toJSON(const T&) -> json::Value
263 /// If this exists, then it also allows constructing Value from T, and can
264 /// be used to serialize vector<T>, map<string, T>, and Optional<T>.
265 ///
266 /// === Serialization ===
267 ///
268 /// Values can be serialized to JSON:
269 /// 1) raw_ostream << Value // Basic formatting.
270 /// 2) raw_ostream << formatv("{0}", Value) // Basic formatting.
271 /// 3) raw_ostream << formatv("{0:2}", Value) // Pretty-print with indent 2.
272 ///
273 /// And parsed:
274 /// Expected<Value> E = json::parse("[1, 2, null]");
275 /// assert(E && E->kind() == Value::Array);
276 class Value {
277 public:
278  enum Kind {
281  /// Number values can store both int64s and doubles at full precision,
282  /// depending on what they were constructed/parsed from.
287  };
288 
289  // It would be nice to have Value() be null. But that would make {} null too.
290  Value(const Value &M) { copyFrom(M); }
291  Value(Value &&M) { moveFrom(std::move(M)); }
292  Value(std::initializer_list<Value> Elements);
293  Value(json::Array &&Elements) : Type(T_Array) {
294  create<json::Array>(std::move(Elements));
295  }
296  template <typename Elt>
297  Value(const std::vector<Elt> &C) : Value(json::Array(C)) {}
298  Value(json::Object &&Properties) : Type(T_Object) {
299  create<json::Object>(std::move(Properties));
300  }
301  template <typename Elt>
302  Value(const std::map<std::string, Elt> &C) : Value(json::Object(C)) {}
303  // Strings: types with value semantics. Must be valid UTF-8.
304  Value(std::string V) : Type(T_String) {
305  if (LLVM_UNLIKELY(!isUTF8(V))) {
306  assert(false && "Invalid UTF-8 in value used as JSON");
307  V = fixUTF8(std::move(V));
308  }
309  create<std::string>(std::move(V));
310  }
312  : Value(std::string(V.begin(), V.end())){};
313  Value(const llvm::formatv_object_base &V) : Value(V.str()){};
314  // Strings: types with reference semantics. Must be valid UTF-8.
315  Value(StringRef V) : Type(T_StringRef) {
316  create<llvm::StringRef>(V);
317  if (LLVM_UNLIKELY(!isUTF8(V))) {
318  assert(false && "Invalid UTF-8 in value used as JSON");
319  *this = Value(fixUTF8(V));
320  }
321  }
322  Value(const char *V) : Value(StringRef(V)) {}
323  Value(std::nullptr_t) : Type(T_Null) {}
324  // Boolean (disallow implicit conversions).
325  // (The last template parameter is a dummy to keep templates distinct.)
326  template <
327  typename T,
328  typename = typename std::enable_if<std::is_same<T, bool>::value>::type,
329  bool = false>
330  Value(T B) : Type(T_Boolean) {
331  create<bool>(B);
332  }
333  // Integers (except boolean). Must be non-narrowing convertible to int64_t.
334  template <
335  typename T,
336  typename = typename std::enable_if<std::is_integral<T>::value>::type,
337  typename = typename std::enable_if<!std::is_same<T, bool>::value>::type>
338  Value(T I) : Type(T_Integer) {
339  create<int64_t>(int64_t{I});
340  }
341  // Floating point. Must be non-narrowing convertible to double.
342  template <typename T,
343  typename =
344  typename std::enable_if<std::is_floating_point<T>::value>::type,
345  double * = nullptr>
346  Value(T D) : Type(T_Double) {
347  create<double>(double{D});
348  }
349  // Serializable types: with a toJSON(const T&)->Value function, found by ADL.
350  template <typename T,
351  typename = typename std::enable_if<std::is_same<
352  Value, decltype(toJSON(*(const T *)nullptr))>::value>,
353  Value * = nullptr>
354  Value(const T &V) : Value(toJSON(V)) {}
355 
356  Value &operator=(const Value &M) {
357  destroy();
358  copyFrom(M);
359  return *this;
360  }
361  Value &operator=(Value &&M) {
362  destroy();
363  moveFrom(std::move(M));
364  return *this;
365  }
366  ~Value() { destroy(); }
367 
368  Kind kind() const {
369  switch (Type) {
370  case T_Null:
371  return Null;
372  case T_Boolean:
373  return Boolean;
374  case T_Double:
375  case T_Integer:
376  return Number;
377  case T_String:
378  case T_StringRef:
379  return String;
380  case T_Object:
381  return Object;
382  case T_Array:
383  return Array;
384  }
385  llvm_unreachable("Unknown kind");
386  }
387 
388  // Typed accessors return None/nullptr if the Value is not of this type.
390  if (LLVM_LIKELY(Type == T_Null))
391  return nullptr;
392  return llvm::None;
393  }
395  if (LLVM_LIKELY(Type == T_Boolean))
396  return as<bool>();
397  return llvm::None;
398  }
400  if (LLVM_LIKELY(Type == T_Double))
401  return as<double>();
402  if (LLVM_LIKELY(Type == T_Integer))
403  return as<int64_t>();
404  return llvm::None;
405  }
406  // Succeeds if the Value is a Number, and exactly representable as int64_t.
408  if (LLVM_LIKELY(Type == T_Integer))
409  return as<int64_t>();
410  if (LLVM_LIKELY(Type == T_Double)) {
411  double D = as<double>();
412  if (LLVM_LIKELY(std::modf(D, &D) == 0.0 &&
413  D >= double(std::numeric_limits<int64_t>::min()) &&
415  return D;
416  }
417  return llvm::None;
418  }
420  if (Type == T_String)
421  return llvm::StringRef(as<std::string>());
422  if (LLVM_LIKELY(Type == T_StringRef))
423  return as<llvm::StringRef>();
424  return llvm::None;
425  }
426  const json::Object *getAsObject() const {
427  return LLVM_LIKELY(Type == T_Object) ? &as<json::Object>() : nullptr;
428  }
430  return LLVM_LIKELY(Type == T_Object) ? &as<json::Object>() : nullptr;
431  }
432  const json::Array *getAsArray() const {
433  return LLVM_LIKELY(Type == T_Array) ? &as<json::Array>() : nullptr;
434  }
436  return LLVM_LIKELY(Type == T_Array) ? &as<json::Array>() : nullptr;
437  }
438 
439  /// Serializes this Value to JSON, writing it to the provided stream.
440  /// The formatting is compact (no extra whitespace) and deterministic.
441  /// For pretty-printing, use the formatv() format_provider below.
442  friend llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Value &);
443 
444 private:
445  void destroy();
446  void copyFrom(const Value &M);
447  // We allow moving from *const* Values, by marking all members as mutable!
448  // This hack is needed to support initializer-list syntax efficiently.
449  // (std::initializer_list<T> is a container of const T).
450  void moveFrom(const Value &&M);
451  friend class Array;
452  friend class Object;
453 
454  template <typename T, typename... U> void create(U &&... V) {
455  new (reinterpret_cast<T *>(Union.buffer)) T(std::forward<U>(V)...);
456  }
457  template <typename T> T &as() const {
458  // Using this two-step static_cast via void * instead of reinterpret_cast
459  // silences a -Wstrict-aliasing false positive from GCC6 and earlier.
460  void *Storage = static_cast<void *>(Union.buffer);
461  return *static_cast<T *>(Storage);
462  }
463 
464  template <typename Indenter>
465  void print(llvm::raw_ostream &, const Indenter &) const;
467 
468  enum ValueType : char {
469  T_Null,
470  T_Boolean,
471  T_Double,
472  T_Integer,
473  T_StringRef,
474  T_String,
475  T_Object,
476  T_Array,
477  };
478  // All members mutable, see moveFrom().
479  mutable ValueType Type;
480  mutable llvm::AlignedCharArrayUnion<bool, double, int64_t, llvm::StringRef,
481  std::string, json::Array, json::Object>
482  Union;
483  friend bool operator==(const Value &, const Value &);
484 };
485 
486 bool operator==(const Value &, const Value &);
487 inline bool operator!=(const Value &L, const Value &R) { return !(L == R); }
489 
490 /// ObjectKey is a used to capture keys in Object. Like Value but:
491 /// - only strings are allowed
492 /// - it's optimized for the string literal case (Owned == nullptr)
493 /// Like Value, strings must be UTF-8. See isUTF8 documentation for details.
494 class ObjectKey {
495 public:
496  ObjectKey(const char *S) : ObjectKey(StringRef(S)) {}
497  ObjectKey(std::string S) : Owned(new std::string(std::move(S))) {
498  if (LLVM_UNLIKELY(!isUTF8(*Owned))) {
499  assert(false && "Invalid UTF-8 in value used as JSON");
500  *Owned = fixUTF8(std::move(*Owned));
501  }
502  Data = *Owned;
503  }
505  if (LLVM_UNLIKELY(!isUTF8(Data))) {
506  assert(false && "Invalid UTF-8 in value used as JSON");
507  *this = ObjectKey(fixUTF8(S));
508  }
509  }
511  : ObjectKey(std::string(V.begin(), V.end())) {}
513 
514  ObjectKey(const ObjectKey &C) { *this = C; }
515  ObjectKey(ObjectKey &&C) : ObjectKey(static_cast<const ObjectKey &&>(C)) {}
517  if (C.Owned) {
518  Owned.reset(new std::string(*C.Owned));
519  Data = *Owned;
520  } else {
521  Data = C.Data;
522  }
523  return *this;
524  }
525  ObjectKey &operator=(ObjectKey &&) = default;
526 
527  operator llvm::StringRef() const { return Data; }
528  std::string str() const { return Data.str(); }
529 
530 private:
531  // FIXME: this is unneccesarily large (3 pointers). Pointer + length + owned
532  // could be 2 pointers at most.
533  std::unique_ptr<std::string> Owned;
535 };
536 
537 inline bool operator==(const ObjectKey &L, const ObjectKey &R) {
538  return llvm::StringRef(L) == llvm::StringRef(R);
539 }
540 inline bool operator!=(const ObjectKey &L, const ObjectKey &R) {
541  return !(L == R);
542 }
543 inline bool operator<(const ObjectKey &L, const ObjectKey &R) {
544  return StringRef(L) < StringRef(R);
545 }
546 
547 struct Object::KV {
549  Value V;
550 };
551 
552 inline Object::Object(std::initializer_list<KV> Properties) {
553  for (const auto &P : Properties) {
554  auto R = try_emplace(P.K, nullptr);
555  if (R.second)
556  R.first->getSecond().moveFrom(std::move(P.V));
557  }
558 }
559 inline std::pair<Object::iterator, bool> Object::insert(KV E) {
560  return try_emplace(std::move(E.K), std::move(E.V));
561 }
562 
563 // Standard deserializers are provided for primitive types.
564 // See comments on Value.
565 inline bool fromJSON(const Value &E, std::string &Out) {
566  if (auto S = E.getAsString()) {
567  Out = *S;
568  return true;
569  }
570  return false;
571 }
572 inline bool fromJSON(const Value &E, int &Out) {
573  if (auto S = E.getAsInteger()) {
574  Out = *S;
575  return true;
576  }
577  return false;
578 }
579 inline bool fromJSON(const Value &E, int64_t &Out) {
580  if (auto S = E.getAsInteger()) {
581  Out = *S;
582  return true;
583  }
584  return false;
585 }
586 inline bool fromJSON(const Value &E, double &Out) {
587  if (auto S = E.getAsNumber()) {
588  Out = *S;
589  return true;
590  }
591  return false;
592 }
593 inline bool fromJSON(const Value &E, bool &Out) {
594  if (auto S = E.getAsBoolean()) {
595  Out = *S;
596  return true;
597  }
598  return false;
599 }
600 template <typename T> bool fromJSON(const Value &E, llvm::Optional<T> &Out) {
601  if (E.getAsNull()) {
602  Out = llvm::None;
603  return true;
604  }
605  T Result;
606  if (!fromJSON(E, Result))
607  return false;
608  Out = std::move(Result);
609  return true;
610 }
611 template <typename T> bool fromJSON(const Value &E, std::vector<T> &Out) {
612  if (auto *A = E.getAsArray()) {
613  Out.clear();
614  Out.resize(A->size());
615  for (size_t I = 0; I < A->size(); ++I)
616  if (!fromJSON((*A)[I], Out[I]))
617  return false;
618  return true;
619  }
620  return false;
621 }
622 template <typename T>
623 bool fromJSON(const Value &E, std::map<std::string, T> &Out) {
624  if (auto *O = E.getAsObject()) {
625  Out.clear();
626  for (const auto &KV : *O)
627  if (!fromJSON(KV.second, Out[llvm::StringRef(KV.first)]))
628  return false;
629  return true;
630  }
631  return false;
632 }
633 
634 // Allow serialization of Optional<T> for supported T.
635 template <typename T> Value toJSON(const llvm::Optional<T> &Opt) {
636  return Opt ? Value(*Opt) : Value(nullptr);
637 }
638 
639 /// Helper for mapping JSON objects onto protocol structs.
640 ///
641 /// Example:
642 /// \code
643 /// bool fromJSON(const Value &E, MyStruct &R) {
644 /// ObjectMapper O(E);
645 /// if (!O || !O.map("mandatory_field", R.MandatoryField))
646 /// return false;
647 /// O.map("optional_field", R.OptionalField);
648 /// return true;
649 /// }
650 /// \endcode
652 public:
653  ObjectMapper(const Value &E) : O(E.getAsObject()) {}
654 
655  /// True if the expression is an object.
656  /// Must be checked before calling map().
657  operator bool() { return O; }
658 
659  /// Maps a property to a field, if it exists.
660  template <typename T> bool map(StringRef Prop, T &Out) {
661  assert(*this && "Must check this is an object before calling map()");
662  if (const Value *E = O->get(Prop))
663  return fromJSON(*E, Out);
664  return false;
665  }
666 
667  /// Maps a property to a field, if it exists.
668  /// (Optional requires special handling, because missing keys are OK).
669  template <typename T> bool map(StringRef Prop, llvm::Optional<T> &Out) {
670  assert(*this && "Must check this is an object before calling map()");
671  if (const Value *E = O->get(Prop))
672  return fromJSON(*E, Out);
673  Out = llvm::None;
674  return true;
675  }
676 
677 private:
678  const Object *O;
679 };
680 
681 /// Parses the provided JSON source, or returns a ParseError.
682 /// The returned Value is self-contained and owns its strings (they do not refer
683 /// to the original source).
685 
686 class ParseError : public llvm::ErrorInfo<ParseError> {
687  const char *Msg;
688  unsigned Line, Column, Offset;
689 
690 public:
691  static char ID;
692  ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
693  : Msg(Msg), Line(Line), Column(Column), Offset(Offset) {}
694  void log(llvm::raw_ostream &OS) const override {
695  OS << llvm::formatv("[{0}:{1}, byte={2}]: {3}", Line, Column, Offset, Msg);
696  }
697  std::error_code convertToErrorCode() const override {
699  }
700 };
701 } // namespace json
702 
703 /// Allow printing json::Value with formatv().
704 /// The default style is basic/compact formatting, like operator<<.
705 /// A format string like formatv("{0:2}", Value) pretty-prints with indent 2.
706 template <> struct format_provider<llvm::json::Value> {
707  static void format(const llvm::json::Value &, raw_ostream &, StringRef);
708 };
709 } // namespace llvm
710 
711 #endif
uint64_t CallInst * C
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition: JSON.h:87
static char ID
Definition: JSON.h:691
void clear()
Definition: JSON.h:183
llvm::Optional< std::nullptr_t > getAsNull() const
Definition: JSON.h:389
const json::Array * getAsArray() const
Definition: JSON.h:432
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const Value & back() const
Definition: JSON.h:171
void log(llvm::raw_ostream &OS) const override
Print an error message to an output stream.
Definition: JSON.h:694
bool map(StringRef Prop, T &Out)
Maps a property to a field, if it exists.
Definition: JSON.h:660
const_iterator begin() const
Definition: JSON.h:176
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Value & operator=(Value &&M)
Definition: JSON.h:361
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:191
#define LLVM_LIKELY(EXPR)
Definition: Compiler.h:190
ObjectKey(const ObjectKey &C)
Definition: JSON.h:514
const json::Array * getArray(StringRef K) const
Definition: JSON.cpp:70
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:123
An Array is a JSON array, which contains heterogeneous JSON values.
Definition: JSON.h:151
const Value & front() const
Definition: JSON.h:169
void pop_back()
Definition: JSON.h:189
llvm::Optional< bool > getAsBoolean() const
Definition: JSON.h:394
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
Value(json::Array &&Elements)
Definition: JSON.h:293
void push_back(const Value &E)
Definition: JSON.h:184
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:532
Value(const Value &M)
Definition: JSON.h:290
std::pair< iterator, bool > try_emplace(const ObjectKey &K, Ts &&... Args)
Definition: JSON.h:115
ObjectKey(llvm::StringRef S)
Definition: JSON.h:504
Definition: BitVector.h:937
const json::Object * getAsObject() const
Definition: JSON.h:426
bool empty() const
Definition: JSON.h:109
Value(const std::map< std::string, Elt > &C)
Definition: JSON.h:302
llvm::Optional< int64_t > getAsInteger() const
Definition: JSON.h:407
llvm::Optional< double > getNumber(StringRef K) const
Definition: JSON.cpp:45
ObjectKey(const llvm::formatv_object_base &V)
Definition: JSON.h:512
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
iterator begin()
Definition: JSON.h:104
llvm::Optional< llvm::StringRef > getString(StringRef K) const
Definition: JSON.cpp:55
Value * data()
Definition: JSON.h:172
Value(std::nullptr_t)
Definition: JSON.h:323
ObjectKey(const char *S)
Definition: JSON.h:496
bool fromJSON(const Value &E, std::string &Out)
Definition: JSON.h:565
llvm::Optional< std::nullptr_t > getNull(StringRef K) const
Definition: JSON.cpp:35
#define T
ObjectMapper(const Value &E)
Definition: JSON.h:653
void emplace_back(Args &&... A)
Definition: JSON.h:186
ObjectKey is a used to capture keys in Object.
Definition: JSON.h:494
Value(const llvm::formatv_object_base &V)
Definition: JSON.h:313
bool operator==(const Object &LHS, const Object &RHS)
Definition: JSON.cpp:80
Value toJSON(const llvm::Optional< T > &Opt)
Definition: JSON.h:635
const json::Object * getObject(StringRef K) const
Definition: JSON.cpp:60
std::string str() const
Definition: JSON.h:528
#define P(N)
const_iterator find(StringRef K) const
Definition: JSON.h:124
void push_back(Value &&E)
Definition: JSON.h:185
bool map(StringRef Prop, llvm::Optional< T > &Out)
Maps a property to a field, if it exists.
Definition: JSON.h:669
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
iterator end()
Definition: JSON.h:106
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
A Value is an JSON value of unknown type.
Definition: JSON.h:276
Value & front()
Definition: JSON.h:168
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
Definition: JSON.h:692
unsigned char Boolean
Definition: ConvertUTF.h:112
Number values can store both int64s and doubles at full precision, depending on what they were constr...
Definition: JSON.h:283
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
unsigned size() const
Definition: DenseMap.h:125
llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
Definition: JSON.cpp:510
std::vector< Value >::const_iterator const_iterator
Definition: JSON.h:157
Kind kind() const
Definition: JSON.h:368
std::vector< Value >::iterator iterator
Definition: JSON.h:156
Value(const char *V)
Definition: JSON.h:322
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
Definition: DenseMap.h:236
Value(const T &V)
Definition: JSON.h:354
ObjectKey & operator=(const ObjectKey &C)
Definition: JSON.h:516
Array(const Collection &C)
Definition: JSON.h:161
size_t size() const
Definition: JSON.h:110
uint32_t Number
Definition: Profile.cpp:47
iterator end()
Definition: JSON.h:177
llvm::Optional< llvm::StringRef > getAsString() const
Definition: JSON.h:419
std::string fixUTF8(llvm::StringRef S)
Replaces invalid UTF-8 sequences in S with the replacement character (U+FFFD).
Definition: JSON.cpp:546
Value(std::string V)
Definition: JSON.h:304
Value(json::Object &&Properties)
Definition: JSON.h:298
ObjectKey(std::string S)
Definition: JSON.h:497
const_iterator begin() const
Definition: JSON.h:105
iterator insert(iterator P, Value &&E)
Definition: JSON.h:192
const Value & operator[](size_t I) const
Definition: JSON.h:167
bool operator!=(const Object &LHS, const Object &RHS)
Definition: JSON.h:145
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
size_t size() const
Definition: JSON.h:181
llvm::Optional< int64_t > getInteger(StringRef K) const
Definition: JSON.cpp:50
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: JSON.h:697
iterator insert(iterator P, const Value &E)
Definition: JSON.h:191
llvm::Optional< double > getAsNumber() const
Definition: JSON.h:399
This union template exposes a suitably aligned and sized character array member which can hold elemen...
Definition: AlignOf.h:137
Base class for user error types.
Definition: Error.h:344
Value(const llvm::SmallVectorImpl< char > &V)
Definition: JSON.h:311
ObjectKey(const llvm::SmallVectorImpl< char > &V)
Definition: JSON.h:510
iterator begin()
Definition: JSON.h:175
void clear()
Definition: JSON.h:112
iterator find(StringRef K)
Definition: JSON.h:123
const_iterator end() const
Definition: JSON.h:107
Value & operator[](const ObjectKey &K)
Definition: JSON.cpp:17
iterator begin()
Definition: DenseMap.h:99
iterator insert(iterator P, It A, It Z)
Definition: JSON.h:195
iterator emplace(const_iterator P, Args &&... A)
Definition: JSON.h:198
std::pair< iterator, bool > try_emplace(ObjectKey &&K, Ts &&... Args)
Definition: JSON.h:119
json::Object * getAsObject()
Definition: JSON.h:429
#define I(x, y, z)
Definition: MD5.cpp:58
Helper for mapping JSON objects onto protocol structs.
Definition: JSON.h:651
iterator end()
Definition: DenseMap.h:108
bool empty() const
Definition: JSON.h:180
ObjectKey(ObjectKey &&C)
Definition: JSON.h:515
Value & back()
Definition: JSON.h:170
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:122
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive, key type.
Definition: DenseMap.h:195
llvm::Optional< bool > getBoolean(StringRef K) const
Definition: JSON.cpp:40
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Value & operator=(const Value &M)
Definition: JSON.h:356
aarch64 promote const
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Value(Value &&M)
Definition: JSON.h:291
Value(const std::vector< Elt > &C)
Definition: JSON.h:297
friend bool operator==(const Array &L, const Array &R)
Definition: JSON.h:202
Value & operator[](size_t I)
Definition: JSON.h:166
const_iterator end() const
Definition: JSON.h:178
llvm::raw_ostream & operator<<(llvm::raw_ostream &, const Value &)
Definition: JSON.cpp:695
const Value * data() const
Definition: JSON.h:173
bool operator<(const ObjectKey &L, const ObjectKey &R)
Definition: JSON.h:543
Value(StringRef V)
Definition: JSON.h:315
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77
json::Array * getAsArray()
Definition: JSON.h:435
std::pair< iterator, bool > insert(KV E)
Definition: JSON.h:559