]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/include/llvm/Support/JSON.h
zfs: merge openzfs/zfs@aee26af27 (zfs-2.1-release) into stable/13
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / include / llvm / Support / JSON.h
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"
52 #include "llvm/Support/Error.h"
53 #include "llvm/Support/FormatVariadic.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include <map>
56
57 namespace llvm {
58 namespace json {
59
60 // === String encodings ===
61 //
62 // JSON strings are character sequences (not byte sequences like std::string).
63 // We need to know the encoding, and for simplicity only support UTF-8.
64 //
65 //   - When parsing, invalid UTF-8 is a syntax error like any other
66 //
67 //   - When creating Values from strings, callers must ensure they are UTF-8.
68 //        with asserts on, invalid UTF-8 will crash the program
69 //        with asserts off, we'll substitute the replacement character (U+FFFD)
70 //     Callers can use json::isUTF8() and json::fixUTF8() for validation.
71 //
72 //   - When retrieving strings from Values (e.g. asString()), the result will
73 //     always be valid UTF-8.
74
75 /// Returns true if \p S is valid UTF-8, which is required for use as JSON.
76 /// If it returns false, \p Offset is set to a byte offset near the first error.
77 bool isUTF8(llvm::StringRef S, size_t *ErrOffset = nullptr);
78 /// Replaces invalid UTF-8 sequences in \p S with the replacement character
79 /// (U+FFFD). The returned string is valid UTF-8.
80 /// This is much slower than isUTF8, so test that first.
81 std::string fixUTF8(llvm::StringRef S);
82
83 class Array;
84 class ObjectKey;
85 class Value;
86 template <typename T> Value toJSON(const llvm::Optional<T> &Opt);
87
88 /// An Object is a JSON object, which maps strings to heterogenous JSON values.
89 /// It simulates DenseMap<ObjectKey, Value>. ObjectKey is a maybe-owned string.
90 class Object {
91   using Storage = DenseMap<ObjectKey, Value, llvm::DenseMapInfo<StringRef>>;
92   Storage M;
93
94 public:
95   using key_type = ObjectKey;
96   using mapped_type = Value;
97   using value_type = Storage::value_type;
98   using iterator = Storage::iterator;
99   using const_iterator = Storage::const_iterator;
100
101   Object() = default;
102   // KV is a trivial key-value struct for list-initialization.
103   // (using std::pair forces extra copies).
104   struct KV;
105   explicit Object(std::initializer_list<KV> Properties);
106
107   iterator begin() { return M.begin(); }
108   const_iterator begin() const { return M.begin(); }
109   iterator end() { return M.end(); }
110   const_iterator end() const { return M.end(); }
111
112   bool empty() const { return M.empty(); }
113   size_t size() const { return M.size(); }
114
115   void clear() { M.clear(); }
116   std::pair<iterator, bool> insert(KV E);
117   template <typename... Ts>
118   std::pair<iterator, bool> try_emplace(const ObjectKey &K, Ts &&... Args) {
119     return M.try_emplace(K, std::forward<Ts>(Args)...);
120   }
121   template <typename... Ts>
122   std::pair<iterator, bool> try_emplace(ObjectKey &&K, Ts &&... Args) {
123     return M.try_emplace(std::move(K), std::forward<Ts>(Args)...);
124   }
125   bool erase(StringRef K);
126   void erase(iterator I) { M.erase(I); }
127
128   iterator find(StringRef K) { return M.find_as(K); }
129   const_iterator find(StringRef K) const { return M.find_as(K); }
130   // operator[] acts as if Value was default-constructible as null.
131   Value &operator[](const ObjectKey &K);
132   Value &operator[](ObjectKey &&K);
133   // Look up a property, returning nullptr if it doesn't exist.
134   Value *get(StringRef K);
135   const Value *get(StringRef K) const;
136   // Typed accessors return None/nullptr if
137   //   - the property doesn't exist
138   //   - or it has the wrong type
139   llvm::Optional<std::nullptr_t> getNull(StringRef K) const;
140   llvm::Optional<bool> getBoolean(StringRef K) const;
141   llvm::Optional<double> getNumber(StringRef K) const;
142   llvm::Optional<int64_t> getInteger(StringRef K) const;
143   llvm::Optional<llvm::StringRef> getString(StringRef K) const;
144   const json::Object *getObject(StringRef K) const;
145   json::Object *getObject(StringRef K);
146   const json::Array *getArray(StringRef K) const;
147   json::Array *getArray(StringRef K);
148 };
149 bool operator==(const Object &LHS, const Object &RHS);
150 inline bool operator!=(const Object &LHS, const Object &RHS) {
151   return !(LHS == RHS);
152 }
153
154 /// An Array is a JSON array, which contains heterogeneous JSON values.
155 /// It simulates std::vector<Value>.
156 class Array {
157   std::vector<Value> V;
158
159 public:
160   using value_type = Value;
161   using iterator = std::vector<Value>::iterator;
162   using const_iterator = std::vector<Value>::const_iterator;
163
164   Array() = default;
165   explicit Array(std::initializer_list<Value> Elements);
166   template <typename Collection> explicit Array(const Collection &C) {
167     for (const auto &V : C)
168       emplace_back(V);
169   }
170
171   Value &operator[](size_t I) { return V[I]; }
172   const Value &operator[](size_t I) const { return V[I]; }
173   Value &front() { return V.front(); }
174   const Value &front() const { return V.front(); }
175   Value &back() { return V.back(); }
176   const Value &back() const { return V.back(); }
177   Value *data() { return V.data(); }
178   const Value *data() const { return V.data(); }
179
180   iterator begin() { return V.begin(); }
181   const_iterator begin() const { return V.begin(); }
182   iterator end() { return V.end(); }
183   const_iterator end() const { return V.end(); }
184
185   bool empty() const { return V.empty(); }
186   size_t size() const { return V.size(); }
187   void reserve(size_t S) { V.reserve(S); }
188
189   void clear() { V.clear(); }
190   void push_back(const Value &E) { V.push_back(E); }
191   void push_back(Value &&E) { V.push_back(std::move(E)); }
192   template <typename... Args> void emplace_back(Args &&... A) {
193     V.emplace_back(std::forward<Args>(A)...);
194   }
195   void pop_back() { V.pop_back(); }
196   // FIXME: insert() takes const_iterator since C++11, old libstdc++ disagrees.
197   iterator insert(iterator P, const Value &E) { return V.insert(P, E); }
198   iterator insert(iterator P, Value &&E) {
199     return V.insert(P, std::move(E));
200   }
201   template <typename It> iterator insert(iterator P, It A, It Z) {
202     return V.insert(P, A, Z);
203   }
204   template <typename... Args> iterator emplace(const_iterator P, Args &&... A) {
205     return V.emplace(P, std::forward<Args>(A)...);
206   }
207
208   friend bool operator==(const Array &L, const Array &R) { return L.V == R.V; }
209 };
210 inline bool operator!=(const Array &L, const Array &R) { return !(L == R); }
211
212 /// A Value is an JSON value of unknown type.
213 /// They can be copied, but should generally be moved.
214 ///
215 /// === Composing values ===
216 ///
217 /// You can implicitly construct Values from:
218 ///   - strings: std::string, SmallString, formatv, StringRef, char*
219 ///              (char*, and StringRef are references, not copies!)
220 ///   - numbers
221 ///   - booleans
222 ///   - null: nullptr
223 ///   - arrays: {"foo", 42.0, false}
224 ///   - serializable things: types with toJSON(const T&)->Value, found by ADL
225 ///
226 /// They can also be constructed from object/array helpers:
227 ///   - json::Object is a type like map<ObjectKey, Value>
228 ///   - json::Array is a type like vector<Value>
229 /// These can be list-initialized, or used to build up collections in a loop.
230 /// json::ary(Collection) converts all items in a collection to Values.
231 ///
232 /// === Inspecting values ===
233 ///
234 /// Each Value is one of the JSON kinds:
235 ///   null    (nullptr_t)
236 ///   boolean (bool)
237 ///   number  (double or int64)
238 ///   string  (StringRef)
239 ///   array   (json::Array)
240 ///   object  (json::Object)
241 ///
242 /// The kind can be queried directly, or implicitly via the typed accessors:
243 ///   if (Optional<StringRef> S = E.getAsString()
244 ///     assert(E.kind() == Value::String);
245 ///
246 /// Array and Object also have typed indexing accessors for easy traversal:
247 ///   Expected<Value> E = parse(R"( {"options": {"font": "sans-serif"}} )");
248 ///   if (Object* O = E->getAsObject())
249 ///     if (Object* Opts = O->getObject("options"))
250 ///       if (Optional<StringRef> Font = Opts->getString("font"))
251 ///         assert(Opts->at("font").kind() == Value::String);
252 ///
253 /// === Converting JSON values to C++ types ===
254 ///
255 /// The convention is to have a deserializer function findable via ADL:
256 ///     fromJSON(const json::Value&, T&)->bool
257 /// Deserializers are provided for:
258 ///   - bool
259 ///   - int and int64_t
260 ///   - double
261 ///   - std::string
262 ///   - vector<T>, where T is deserializable
263 ///   - map<string, T>, where T is deserializable
264 ///   - Optional<T>, where T is deserializable
265 /// ObjectMapper can help writing fromJSON() functions for object types.
266 ///
267 /// For conversion in the other direction, the serializer function is:
268 ///    toJSON(const T&) -> json::Value
269 /// If this exists, then it also allows constructing Value from T, and can
270 /// be used to serialize vector<T>, map<string, T>, and Optional<T>.
271 ///
272 /// === Serialization ===
273 ///
274 /// Values can be serialized to JSON:
275 ///   1) raw_ostream << Value                    // Basic formatting.
276 ///   2) raw_ostream << formatv("{0}", Value)    // Basic formatting.
277 ///   3) raw_ostream << formatv("{0:2}", Value)  // Pretty-print with indent 2.
278 ///
279 /// And parsed:
280 ///   Expected<Value> E = json::parse("[1, 2, null]");
281 ///   assert(E && E->kind() == Value::Array);
282 class Value {
283 public:
284   enum Kind {
285     Null,
286     Boolean,
287     /// Number values can store both int64s and doubles at full precision,
288     /// depending on what they were constructed/parsed from.
289     Number,
290     String,
291     Array,
292     Object,
293   };
294
295   // It would be nice to have Value() be null. But that would make {} null too.
296   Value(const Value &M) { copyFrom(M); }
297   Value(Value &&M) { moveFrom(std::move(M)); }
298   Value(std::initializer_list<Value> Elements);
299   Value(json::Array &&Elements) : Type(T_Array) {
300     create<json::Array>(std::move(Elements));
301   }
302   template <typename Elt>
303   Value(const std::vector<Elt> &C) : Value(json::Array(C)) {}
304   Value(json::Object &&Properties) : Type(T_Object) {
305     create<json::Object>(std::move(Properties));
306   }
307   template <typename Elt>
308   Value(const std::map<std::string, Elt> &C) : Value(json::Object(C)) {}
309   // Strings: types with value semantics. Must be valid UTF-8.
310   Value(std::string V) : Type(T_String) {
311     if (LLVM_UNLIKELY(!isUTF8(V))) {
312       assert(false && "Invalid UTF-8 in value used as JSON");
313       V = fixUTF8(std::move(V));
314     }
315     create<std::string>(std::move(V));
316   }
317   Value(const llvm::SmallVectorImpl<char> &V)
318       : Value(std::string(V.begin(), V.end())) {}
319   Value(const llvm::formatv_object_base &V) : Value(V.str()) {}
320   // Strings: types with reference semantics. Must be valid UTF-8.
321   Value(StringRef V) : Type(T_StringRef) {
322     create<llvm::StringRef>(V);
323     if (LLVM_UNLIKELY(!isUTF8(V))) {
324       assert(false && "Invalid UTF-8 in value used as JSON");
325       *this = Value(fixUTF8(V));
326     }
327   }
328   Value(const char *V) : Value(StringRef(V)) {}
329   Value(std::nullptr_t) : Type(T_Null) {}
330   // Boolean (disallow implicit conversions).
331   // (The last template parameter is a dummy to keep templates distinct.)
332   template <typename T,
333             typename = std::enable_if_t<std::is_same<T, bool>::value>,
334             bool = false>
335   Value(T B) : Type(T_Boolean) {
336     create<bool>(B);
337   }
338   // Integers (except boolean). Must be non-narrowing convertible to int64_t.
339   template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>,
340             typename = std::enable_if_t<!std::is_same<T, bool>::value>>
341   Value(T I) : Type(T_Integer) {
342     create<int64_t>(int64_t{I});
343   }
344   // Floating point. Must be non-narrowing convertible to double.
345   template <typename T,
346             typename = std::enable_if_t<std::is_floating_point<T>::value>,
347             double * = nullptr>
348   Value(T D) : Type(T_Double) {
349     create<double>(double{D});
350   }
351   // Serializable types: with a toJSON(const T&)->Value function, found by ADL.
352   template <typename T,
353             typename = std::enable_if_t<std::is_same<
354                 Value, decltype(toJSON(*(const T *)nullptr))>::value>,
355             Value * = nullptr>
356   Value(const T &V) : Value(toJSON(V)) {}
357
358   Value &operator=(const Value &M) {
359     destroy();
360     copyFrom(M);
361     return *this;
362   }
363   Value &operator=(Value &&M) {
364     destroy();
365     moveFrom(std::move(M));
366     return *this;
367   }
368   ~Value() { destroy(); }
369
370   Kind kind() const {
371     switch (Type) {
372     case T_Null:
373       return Null;
374     case T_Boolean:
375       return Boolean;
376     case T_Double:
377     case T_Integer:
378       return Number;
379     case T_String:
380     case T_StringRef:
381       return String;
382     case T_Object:
383       return Object;
384     case T_Array:
385       return Array;
386     }
387     llvm_unreachable("Unknown kind");
388   }
389
390   // Typed accessors return None/nullptr if the Value is not of this type.
391   llvm::Optional<std::nullptr_t> getAsNull() const {
392     if (LLVM_LIKELY(Type == T_Null))
393       return nullptr;
394     return llvm::None;
395   }
396   llvm::Optional<bool> getAsBoolean() const {
397     if (LLVM_LIKELY(Type == T_Boolean))
398       return as<bool>();
399     return llvm::None;
400   }
401   llvm::Optional<double> getAsNumber() const {
402     if (LLVM_LIKELY(Type == T_Double))
403       return as<double>();
404     if (LLVM_LIKELY(Type == T_Integer))
405       return as<int64_t>();
406     return llvm::None;
407   }
408   // Succeeds if the Value is a Number, and exactly representable as int64_t.
409   llvm::Optional<int64_t> getAsInteger() const {
410     if (LLVM_LIKELY(Type == T_Integer))
411       return as<int64_t>();
412     if (LLVM_LIKELY(Type == T_Double)) {
413       double D = as<double>();
414       if (LLVM_LIKELY(std::modf(D, &D) == 0.0 &&
415                       D >= double(std::numeric_limits<int64_t>::min()) &&
416                       D <= double(std::numeric_limits<int64_t>::max())))
417         return D;
418     }
419     return llvm::None;
420   }
421   llvm::Optional<llvm::StringRef> getAsString() const {
422     if (Type == T_String)
423       return llvm::StringRef(as<std::string>());
424     if (LLVM_LIKELY(Type == T_StringRef))
425       return as<llvm::StringRef>();
426     return llvm::None;
427   }
428   const json::Object *getAsObject() const {
429     return LLVM_LIKELY(Type == T_Object) ? &as<json::Object>() : nullptr;
430   }
431   json::Object *getAsObject() {
432     return LLVM_LIKELY(Type == T_Object) ? &as<json::Object>() : nullptr;
433   }
434   const json::Array *getAsArray() const {
435     return LLVM_LIKELY(Type == T_Array) ? &as<json::Array>() : nullptr;
436   }
437   json::Array *getAsArray() {
438     return LLVM_LIKELY(Type == T_Array) ? &as<json::Array>() : nullptr;
439   }
440
441 private:
442   void destroy();
443   void copyFrom(const Value &M);
444   // We allow moving from *const* Values, by marking all members as mutable!
445   // This hack is needed to support initializer-list syntax efficiently.
446   // (std::initializer_list<T> is a container of const T).
447   void moveFrom(const Value &&M);
448   friend class Array;
449   friend class Object;
450
451   template <typename T, typename... U> void create(U &&... V) {
452     new (reinterpret_cast<T *>(Union.buffer)) T(std::forward<U>(V)...);
453   }
454   template <typename T> T &as() const {
455     // Using this two-step static_cast via void * instead of reinterpret_cast
456     // silences a -Wstrict-aliasing false positive from GCC6 and earlier.
457     void *Storage = static_cast<void *>(Union.buffer);
458     return *static_cast<T *>(Storage);
459   }
460
461   friend class OStream;
462
463   enum ValueType : char {
464     T_Null,
465     T_Boolean,
466     T_Double,
467     T_Integer,
468     T_StringRef,
469     T_String,
470     T_Object,
471     T_Array,
472   };
473   // All members mutable, see moveFrom().
474   mutable ValueType Type;
475   mutable llvm::AlignedCharArrayUnion<bool, double, int64_t, llvm::StringRef,
476                                       std::string, json::Array, json::Object>
477       Union;
478   friend bool operator==(const Value &, const Value &);
479 };
480
481 bool operator==(const Value &, const Value &);
482 inline bool operator!=(const Value &L, const Value &R) { return !(L == R); }
483
484 /// ObjectKey is a used to capture keys in Object. Like Value but:
485 ///   - only strings are allowed
486 ///   - it's optimized for the string literal case (Owned == nullptr)
487 /// Like Value, strings must be UTF-8. See isUTF8 documentation for details.
488 class ObjectKey {
489 public:
490   ObjectKey(const char *S) : ObjectKey(StringRef(S)) {}
491   ObjectKey(std::string S) : Owned(new std::string(std::move(S))) {
492     if (LLVM_UNLIKELY(!isUTF8(*Owned))) {
493       assert(false && "Invalid UTF-8 in value used as JSON");
494       *Owned = fixUTF8(std::move(*Owned));
495     }
496     Data = *Owned;
497   }
498   ObjectKey(llvm::StringRef S) : Data(S) {
499     if (LLVM_UNLIKELY(!isUTF8(Data))) {
500       assert(false && "Invalid UTF-8 in value used as JSON");
501       *this = ObjectKey(fixUTF8(S));
502     }
503   }
504   ObjectKey(const llvm::SmallVectorImpl<char> &V)
505       : ObjectKey(std::string(V.begin(), V.end())) {}
506   ObjectKey(const llvm::formatv_object_base &V) : ObjectKey(V.str()) {}
507
508   ObjectKey(const ObjectKey &C) { *this = C; }
509   ObjectKey(ObjectKey &&C) : ObjectKey(static_cast<const ObjectKey &&>(C)) {}
510   ObjectKey &operator=(const ObjectKey &C) {
511     if (C.Owned) {
512       Owned.reset(new std::string(*C.Owned));
513       Data = *Owned;
514     } else {
515       Data = C.Data;
516     }
517     return *this;
518   }
519   ObjectKey &operator=(ObjectKey &&) = default;
520
521   operator llvm::StringRef() const { return Data; }
522   std::string str() const { return Data.str(); }
523
524 private:
525   // FIXME: this is unneccesarily large (3 pointers). Pointer + length + owned
526   // could be 2 pointers at most.
527   std::unique_ptr<std::string> Owned;
528   llvm::StringRef Data;
529 };
530
531 inline bool operator==(const ObjectKey &L, const ObjectKey &R) {
532   return llvm::StringRef(L) == llvm::StringRef(R);
533 }
534 inline bool operator!=(const ObjectKey &L, const ObjectKey &R) {
535   return !(L == R);
536 }
537 inline bool operator<(const ObjectKey &L, const ObjectKey &R) {
538   return StringRef(L) < StringRef(R);
539 }
540
541 struct Object::KV {
542   ObjectKey K;
543   Value V;
544 };
545
546 inline Object::Object(std::initializer_list<KV> Properties) {
547   for (const auto &P : Properties) {
548     auto R = try_emplace(P.K, nullptr);
549     if (R.second)
550       R.first->getSecond().moveFrom(std::move(P.V));
551   }
552 }
553 inline std::pair<Object::iterator, bool> Object::insert(KV E) {
554   return try_emplace(std::move(E.K), std::move(E.V));
555 }
556 inline bool Object::erase(StringRef K) {
557   return M.erase(ObjectKey(K));
558 }
559
560 // Standard deserializers are provided for primitive types.
561 // See comments on Value.
562 inline bool fromJSON(const Value &E, std::string &Out) {
563   if (auto S = E.getAsString()) {
564     Out = std::string(*S);
565     return true;
566   }
567   return false;
568 }
569 inline bool fromJSON(const Value &E, int &Out) {
570   if (auto S = E.getAsInteger()) {
571     Out = *S;
572     return true;
573   }
574   return false;
575 }
576 inline bool fromJSON(const Value &E, int64_t &Out) {
577   if (auto S = E.getAsInteger()) {
578     Out = *S;
579     return true;
580   }
581   return false;
582 }
583 inline bool fromJSON(const Value &E, double &Out) {
584   if (auto S = E.getAsNumber()) {
585     Out = *S;
586     return true;
587   }
588   return false;
589 }
590 inline bool fromJSON(const Value &E, bool &Out) {
591   if (auto S = E.getAsBoolean()) {
592     Out = *S;
593     return true;
594   }
595   return false;
596 }
597 inline bool fromJSON(const Value &E, std::nullptr_t &Out) {
598   if (auto S = E.getAsNull()) {
599     Out = *S;
600     return true;
601   }
602   return false;
603 }
604 template <typename T> bool fromJSON(const Value &E, llvm::Optional<T> &Out) {
605   if (E.getAsNull()) {
606     Out = llvm::None;
607     return true;
608   }
609   T Result;
610   if (!fromJSON(E, Result))
611     return false;
612   Out = std::move(Result);
613   return true;
614 }
615 template <typename T> bool fromJSON(const Value &E, std::vector<T> &Out) {
616   if (auto *A = E.getAsArray()) {
617     Out.clear();
618     Out.resize(A->size());
619     for (size_t I = 0; I < A->size(); ++I)
620       if (!fromJSON((*A)[I], Out[I]))
621         return false;
622     return true;
623   }
624   return false;
625 }
626 template <typename T>
627 bool fromJSON(const Value &E, std::map<std::string, T> &Out) {
628   if (auto *O = E.getAsObject()) {
629     Out.clear();
630     for (const auto &KV : *O)
631       if (!fromJSON(KV.second, Out[std::string(llvm::StringRef(KV.first))]))
632         return false;
633     return true;
634   }
635   return false;
636 }
637
638 // Allow serialization of Optional<T> for supported T.
639 template <typename T> Value toJSON(const llvm::Optional<T> &Opt) {
640   return Opt ? Value(*Opt) : Value(nullptr);
641 }
642
643 /// Helper for mapping JSON objects onto protocol structs.
644 ///
645 /// Example:
646 /// \code
647 ///   bool fromJSON(const Value &E, MyStruct &R) {
648 ///     ObjectMapper O(E);
649 ///     if (!O || !O.map("mandatory_field", R.MandatoryField))
650 ///       return false;
651 ///     O.map("optional_field", R.OptionalField);
652 ///     return true;
653 ///   }
654 /// \endcode
655 class ObjectMapper {
656 public:
657   ObjectMapper(const Value &E) : O(E.getAsObject()) {}
658
659   /// True if the expression is an object.
660   /// Must be checked before calling map().
661   operator bool() { return O; }
662
663   /// Maps a property to a field, if it exists.
664   template <typename T> bool map(StringRef Prop, T &Out) {
665     assert(*this && "Must check this is an object before calling map()");
666     if (const Value *E = O->get(Prop))
667       return fromJSON(*E, Out);
668     return false;
669   }
670
671   /// Maps a property to a field, if it exists.
672   /// (Optional requires special handling, because missing keys are OK).
673   template <typename T> bool map(StringRef Prop, llvm::Optional<T> &Out) {
674     assert(*this && "Must check this is an object before calling map()");
675     if (const Value *E = O->get(Prop))
676       return fromJSON(*E, Out);
677     Out = llvm::None;
678     return true;
679   }
680
681 private:
682   const Object *O;
683 };
684
685 /// Parses the provided JSON source, or returns a ParseError.
686 /// The returned Value is self-contained and owns its strings (they do not refer
687 /// to the original source).
688 llvm::Expected<Value> parse(llvm::StringRef JSON);
689
690 class ParseError : public llvm::ErrorInfo<ParseError> {
691   const char *Msg;
692   unsigned Line, Column, Offset;
693
694 public:
695   static char ID;
696   ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
697       : Msg(Msg), Line(Line), Column(Column), Offset(Offset) {}
698   void log(llvm::raw_ostream &OS) const override {
699     OS << llvm::formatv("[{0}:{1}, byte={2}]: {3}", Line, Column, Offset, Msg);
700   }
701   std::error_code convertToErrorCode() const override {
702     return llvm::inconvertibleErrorCode();
703   }
704 };
705
706 /// json::OStream allows writing well-formed JSON without materializing
707 /// all structures as json::Value ahead of time.
708 /// It's faster, lower-level, and less safe than OS << json::Value.
709 ///
710 /// Only one "top-level" object can be written to a stream.
711 /// Simplest usage involves passing lambdas (Blocks) to fill in containers:
712 ///
713 ///   json::OStream J(OS);
714 ///   J.array([&]{
715 ///     for (const Event &E : Events)
716 ///       J.object([&] {
717 ///         J.attribute("timestamp", int64_t(E.Time));
718 ///         J.attributeArray("participants", [&] {
719 ///           for (const Participant &P : E.Participants)
720 ///             J.value(P.toString());
721 ///         });
722 ///       });
723 ///   });
724 ///
725 /// This would produce JSON like:
726 ///
727 ///   [
728 ///     {
729 ///       "timestamp": 19287398741,
730 ///       "participants": [
731 ///         "King Kong",
732 ///         "Miley Cyrus",
733 ///         "Cleopatra"
734 ///       ]
735 ///     },
736 ///     ...
737 ///   ]
738 ///
739 /// The lower level begin/end methods (arrayBegin()) are more flexible but
740 /// care must be taken to pair them correctly:
741 ///
742 ///   json::OStream J(OS);
743 //    J.arrayBegin();
744 ///   for (const Event &E : Events) {
745 ///     J.objectBegin();
746 ///     J.attribute("timestamp", int64_t(E.Time));
747 ///     J.attributeBegin("participants");
748 ///     for (const Participant &P : E.Participants)
749 ///       J.value(P.toString());
750 ///     J.attributeEnd();
751 ///     J.objectEnd();
752 ///   }
753 ///   J.arrayEnd();
754 ///
755 /// If the call sequence isn't valid JSON, asserts will fire in debug mode.
756 /// This can be mismatched begin()/end() pairs, trying to emit attributes inside
757 /// an array, and so on.
758 /// With asserts disabled, this is undefined behavior.
759 class OStream {
760  public:
761   using Block = llvm::function_ref<void()>;
762   // If IndentSize is nonzero, output is pretty-printed.
763   explicit OStream(llvm::raw_ostream &OS, unsigned IndentSize = 0)
764       : OS(OS), IndentSize(IndentSize) {
765     Stack.emplace_back();
766   }
767   ~OStream() {
768     assert(Stack.size() == 1 && "Unmatched begin()/end()");
769     assert(Stack.back().Ctx == Singleton);
770     assert(Stack.back().HasValue && "Did not write top-level value");
771   }
772
773   /// Flushes the underlying ostream. OStream does not buffer internally.
774   void flush() { OS.flush(); }
775
776   // High level functions to output a value.
777   // Valid at top-level (exactly once), in an attribute value (exactly once),
778   // or in an array (any number of times).
779
780   /// Emit a self-contained value (number, string, vector<string> etc).
781   void value(const Value &V);
782   /// Emit an array whose elements are emitted in the provided Block.
783   void array(Block Contents) {
784     arrayBegin();
785     Contents();
786     arrayEnd();
787   }
788   /// Emit an object whose elements are emitted in the provided Block.
789   void object(Block Contents) {
790     objectBegin();
791     Contents();
792     objectEnd();
793   }
794
795   // High level functions to output object attributes.
796   // Valid only within an object (any number of times).
797
798   /// Emit an attribute whose value is self-contained (number, vector<int> etc).
799   void attribute(llvm::StringRef Key, const Value& Contents) {
800     attributeImpl(Key, [&] { value(Contents); });
801   }
802   /// Emit an attribute whose value is an array with elements from the Block.
803   void attributeArray(llvm::StringRef Key, Block Contents) {
804     attributeImpl(Key, [&] { array(Contents); });
805   }
806   /// Emit an attribute whose value is an object with attributes from the Block.
807   void attributeObject(llvm::StringRef Key, Block Contents) {
808     attributeImpl(Key, [&] { object(Contents); });
809   }
810
811   // Low-level begin/end functions to output arrays, objects, and attributes.
812   // Must be correctly paired. Allowed contexts are as above.
813
814   void arrayBegin();
815   void arrayEnd();
816   void objectBegin();
817   void objectEnd();
818   void attributeBegin(llvm::StringRef Key);
819   void attributeEnd();
820
821  private:
822   void attributeImpl(llvm::StringRef Key, Block Contents) {
823     attributeBegin(Key);
824     Contents();
825     attributeEnd();
826   }
827
828   void valueBegin();
829   void newline();
830
831   enum Context {
832     Singleton, // Top level, or object attribute.
833     Array,
834     Object,
835   };
836   struct State {
837     Context Ctx = Singleton;
838     bool HasValue = false;
839   };
840   llvm::SmallVector<State, 16> Stack; // Never empty.
841   llvm::raw_ostream &OS;
842   unsigned IndentSize;
843   unsigned Indent = 0;
844 };
845
846 /// Serializes this Value to JSON, writing it to the provided stream.
847 /// The formatting is compact (no extra whitespace) and deterministic.
848 /// For pretty-printing, use the formatv() format_provider below.
849 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Value &V) {
850   OStream(OS).value(V);
851   return OS;
852 }
853 } // namespace json
854
855 /// Allow printing json::Value with formatv().
856 /// The default style is basic/compact formatting, like operator<<.
857 /// A format string like formatv("{0:2}", Value) pretty-prints with indent 2.
858 template <> struct format_provider<llvm::json::Value> {
859   static void format(const llvm::json::Value &, raw_ostream &, StringRef);
860 };
861 } // namespace llvm
862
863 #endif