1 //===--- JSON.h - JSON values, parsing and serialization -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===---------------------------------------------------------------------===//
11 /// This file supports working with JSON data.
15 /// - classes which hold dynamically-typed parsed JSON structures
16 /// These are value types that can be composed, inspected, and modified.
17 /// See json::Value, and the related types json::Object and json::Array.
19 /// - functions to parse JSON text into Values, and to serialize Values to text.
20 /// See parse(), operator<<, and format_provider.
22 /// - a convention and helpers for mapping between json::Value and user-defined
23 /// types. See fromJSON(), ObjectMapper, and the class comment on Value.
25 /// Typically, JSON data would be read from an external source, parsed into
26 /// a Value, and then converted into some native data structure before doing
27 /// real work on it. (And vice versa when writing).
29 /// Other serialization mechanisms you may consider:
31 /// - YAML is also text-based, and more human-readable than JSON. It's a more
32 /// complex format and data model, and YAML parsers aren't ubiquitous.
33 /// YAMLParser.h is a streaming parser suitable for parsing large documents
34 /// (including JSON, as YAML is a superset). It can be awkward to use
35 /// directly. YAML I/O (YAMLTraits.h) provides data mapping that is more
36 /// declarative than the toJSON/fromJSON conventions here.
38 /// - LLVM bitstream is a space- and CPU- efficient binary format. Typically it
39 /// encodes LLVM IR ("bitcode"), but it can be a container for other data.
40 /// Low-level reader/writer libraries are in Bitcode/Bitstream*.h
42 //===---------------------------------------------------------------------===//
44 #ifndef LLVM_SUPPORT_JSON_H
45 #define LLVM_SUPPORT_JSON_H
47 #include "llvm/ADT/DenseMap.h"
48 #include "llvm/ADT/SmallVector.h"
49 #include "llvm/ADT/StringRef.h"
50 #include "llvm/Support/Error.h"
51 #include "llvm/Support/FormatVariadic.h"
52 #include "llvm/Support/raw_ostream.h"
61 /// An Object is a JSON object, which maps strings to heterogenous JSON values.
62 /// It simulates DenseMap<ObjectKey, Value>. ObjectKey is a maybe-owned string.
64 using Storage = DenseMap<ObjectKey, Value, llvm::DenseMapInfo<StringRef>>;
68 using key_type = ObjectKey;
69 using mapped_type = Value;
70 using value_type = Storage::value_type;
71 using iterator = Storage::iterator;
72 using const_iterator = Storage::const_iterator;
74 explicit Object() = default;
75 // KV is a trivial key-value struct for list-initialization.
76 // (using std::pair forces extra copies).
78 explicit Object(std::initializer_list<KV> Properties);
80 iterator begin() { return M.begin(); }
81 const_iterator begin() const { return M.begin(); }
82 iterator end() { return M.end(); }
83 const_iterator end() const { return M.end(); }
85 bool empty() const { return M.empty(); }
86 size_t size() const { return M.size(); }
88 void clear() { M.clear(); }
89 std::pair<iterator, bool> insert(KV E);
90 template <typename... Ts>
91 std::pair<iterator, bool> try_emplace(const ObjectKey &K, Ts &&... Args) {
92 return M.try_emplace(K, std::forward<Ts>(Args)...);
94 template <typename... Ts>
95 std::pair<iterator, bool> try_emplace(ObjectKey &&K, Ts &&... Args) {
96 return M.try_emplace(std::move(K), std::forward<Ts>(Args)...);
99 iterator find(StringRef K) { return M.find_as(K); }
100 const_iterator find(StringRef K) const { return M.find_as(K); }
101 // operator[] acts as if Value was default-constructible as null.
102 Value &operator[](const ObjectKey &K);
103 Value &operator[](ObjectKey &&K);
104 // Look up a property, returning nullptr if it doesn't exist.
105 Value *get(StringRef K);
106 const Value *get(StringRef K) const;
107 // Typed accessors return None/nullptr if
108 // - the property doesn't exist
109 // - or it has the wrong type
110 llvm::Optional<std::nullptr_t> getNull(StringRef K) const;
111 llvm::Optional<bool> getBoolean(StringRef K) const;
112 llvm::Optional<double> getNumber(StringRef K) const;
113 llvm::Optional<int64_t> getInteger(StringRef K) const;
114 llvm::Optional<llvm::StringRef> getString(StringRef K) const;
115 const json::Object *getObject(StringRef K) const;
116 json::Object *getObject(StringRef K);
117 const json::Array *getArray(StringRef K) const;
118 json::Array *getArray(StringRef K);
120 bool operator==(const Object &LHS, const Object &RHS);
121 inline bool operator!=(const Object &LHS, const Object &RHS) {
122 return !(LHS == RHS);
125 /// An Array is a JSON array, which contains heterogeneous JSON values.
126 /// It simulates std::vector<Value>.
128 std::vector<Value> V;
131 using value_type = Value;
132 using iterator = std::vector<Value>::iterator;
133 using const_iterator = std::vector<Value>::const_iterator;
135 explicit Array() = default;
136 explicit Array(std::initializer_list<Value> Elements);
137 template <typename Collection> explicit Array(const Collection &C) {
138 for (const auto &V : C)
142 Value &operator[](size_t I) { return V[I]; }
143 const Value &operator[](size_t I) const { return V[I]; }
144 Value &front() { return V.front(); }
145 const Value &front() const { return V.front(); }
146 Value &back() { return V.back(); }
147 const Value &back() const { return V.back(); }
148 Value *data() { return V.data(); }
149 const Value *data() const { return V.data(); }
151 iterator begin() { return V.begin(); }
152 const_iterator begin() const { return V.begin(); }
153 iterator end() { return V.end(); }
154 const_iterator end() const { return V.end(); }
156 bool empty() const { return V.empty(); }
157 size_t size() const { return V.size(); }
159 void clear() { V.clear(); }
160 void push_back(const Value &E) { V.push_back(E); }
161 void push_back(Value &&E) { V.push_back(std::move(E)); }
162 template <typename... Args> void emplace_back(Args &&... A) {
163 V.emplace_back(std::forward<Args>(A)...);
165 void pop_back() { V.pop_back(); }
166 // FIXME: insert() takes const_iterator since C++11, old libstdc++ disagrees.
167 iterator insert(iterator P, const Value &E) { return V.insert(P, E); }
168 iterator insert(iterator P, Value &&E) {
169 return V.insert(P, std::move(E));
171 template <typename It> iterator insert(iterator P, It A, It Z) {
172 return V.insert(P, A, Z);
174 template <typename... Args> iterator emplace(const_iterator P, Args &&... A) {
175 return V.emplace(P, std::forward<Args>(A)...);
178 friend bool operator==(const Array &L, const Array &R) { return L.V == R.V; }
180 inline bool operator!=(const Array &L, const Array &R) { return !(L == R); }
182 /// A Value is an JSON value of unknown type.
183 /// They can be copied, but should generally be moved.
185 /// === Composing values ===
187 /// You can implicitly construct Values from:
188 /// - strings: std::string, SmallString, formatv, StringRef, char*
189 /// (char*, and StringRef are references, not copies!)
193 /// - arrays: {"foo", 42.0, false}
194 /// - serializable things: types with toJSON(const T&)->Value, found by ADL
196 /// They can also be constructed from object/array helpers:
197 /// - json::Object is a type like map<ObjectKey, Value>
198 /// - json::Array is a type like vector<Value>
199 /// These can be list-initialized, or used to build up collections in a loop.
200 /// json::ary(Collection) converts all items in a collection to Values.
202 /// === Inspecting values ===
204 /// Each Value is one of the JSON kinds:
207 /// number (double or int64)
208 /// string (StringRef)
209 /// array (json::Array)
210 /// object (json::Object)
212 /// The kind can be queried directly, or implicitly via the typed accessors:
213 /// if (Optional<StringRef> S = E.getAsString()
214 /// assert(E.kind() == Value::String);
216 /// Array and Object also have typed indexing accessors for easy traversal:
217 /// Expected<Value> E = parse(R"( {"options": {"font": "sans-serif"}} )");
218 /// if (Object* O = E->getAsObject())
219 /// if (Object* Opts = O->getObject("options"))
220 /// if (Optional<StringRef> Font = Opts->getString("font"))
221 /// assert(Opts->at("font").kind() == Value::String);
223 /// === Converting JSON values to C++ types ===
225 /// The convention is to have a deserializer function findable via ADL:
226 /// fromJSON(const json::Value&, T&)->bool
227 /// Deserializers are provided for:
229 /// - int and int64_t
232 /// - vector<T>, where T is deserializable
233 /// - map<string, T>, where T is deserializable
234 /// - Optional<T>, where T is deserializable
235 /// ObjectMapper can help writing fromJSON() functions for object types.
237 /// For conversion in the other direction, the serializer function is:
238 /// toJSON(const T&) -> json::Value
239 /// If this exists, then it also allows constructing Value from T, and can
240 /// be used to serialize vector<T>, map<string, T>, and Optional<T>.
242 /// === Serialization ===
244 /// Values can be serialized to JSON:
245 /// 1) raw_ostream << Value // Basic formatting.
246 /// 2) raw_ostream << formatv("{0}", Value) // Basic formatting.
247 /// 3) raw_ostream << formatv("{0:2}", Value) // Pretty-print with indent 2.
250 /// Expected<Value> E = json::parse("[1, 2, null]");
251 /// assert(E && E->kind() == Value::Array);
257 /// Number values can store both int64s and doubles at full precision,
258 /// depending on what they were constructed/parsed from.
265 // It would be nice to have Value() be null. But that would make {} null too.
266 Value(const Value &M) { copyFrom(M); }
267 Value(Value &&M) { moveFrom(std::move(M)); }
268 Value(std::initializer_list<Value> Elements);
269 Value(json::Array &&Elements) : Type(T_Array) {
270 create<json::Array>(std::move(Elements));
272 Value(json::Object &&Properties) : Type(T_Object) {
273 create<json::Object>(std::move(Properties));
275 // Strings: types with value semantics.
276 Value(std::string &&V) : Type(T_String) { create<std::string>(std::move(V)); }
277 Value(const std::string &V) : Type(T_String) { create<std::string>(V); }
278 Value(const llvm::SmallVectorImpl<char> &V) : Type(T_String) {
279 create<std::string>(V.begin(), V.end());
281 Value(const llvm::formatv_object_base &V) : Value(V.str()){};
282 // Strings: types with reference semantics.
283 Value(llvm::StringRef V) : Type(T_StringRef) { create<llvm::StringRef>(V); }
284 Value(const char *V) : Type(T_StringRef) { create<llvm::StringRef>(V); }
285 Value(std::nullptr_t) : Type(T_Null) {}
286 // Boolean (disallow implicit conversions).
287 // (The last template parameter is a dummy to keep templates distinct.)
290 typename = typename std::enable_if<std::is_same<T, bool>::value>::type,
292 Value(T B) : Type(T_Boolean) {
295 // Integers (except boolean). Must be non-narrowing convertible to int64_t.
298 typename = typename std::enable_if<std::is_integral<T>::value>::type,
299 typename = typename std::enable_if<!std::is_same<T, bool>::value>::type>
300 Value(T I) : Type(T_Integer) {
301 create<int64_t>(int64_t{I});
303 // Floating point. Must be non-narrowing convertible to double.
304 template <typename T,
306 typename std::enable_if<std::is_floating_point<T>::value>::type,
308 Value(T D) : Type(T_Double) {
309 create<double>(double{D});
311 // Serializable types: with a toJSON(const T&)->Value function, found by ADL.
312 template <typename T,
313 typename = typename std::enable_if<std::is_same<
314 Value, decltype(toJSON(*(const T *)nullptr))>::value>,
316 Value(const T &V) : Value(toJSON(V)) {}
318 Value &operator=(const Value &M) {
323 Value &operator=(Value &&M) {
325 moveFrom(std::move(M));
328 ~Value() { destroy(); }
347 llvm_unreachable("Unknown kind");
350 // Typed accessors return None/nullptr if the Value is not of this type.
351 llvm::Optional<std::nullptr_t> getAsNull() const {
352 if (LLVM_LIKELY(Type == T_Null))
356 llvm::Optional<bool> getAsBoolean() const {
357 if (LLVM_LIKELY(Type == T_Boolean))
361 llvm::Optional<double> getAsNumber() const {
362 if (LLVM_LIKELY(Type == T_Double))
364 if (LLVM_LIKELY(Type == T_Integer))
365 return as<int64_t>();
368 // Succeeds if the Value is a Number, and exactly representable as int64_t.
369 llvm::Optional<int64_t> getAsInteger() const {
370 if (LLVM_LIKELY(Type == T_Integer))
371 return as<int64_t>();
372 if (LLVM_LIKELY(Type == T_Double)) {
373 double D = as<double>();
374 if (LLVM_LIKELY(std::modf(D, &D) == 0.0 &&
375 D >= double(std::numeric_limits<int64_t>::min()) &&
376 D <= double(std::numeric_limits<int64_t>::max())))
381 llvm::Optional<llvm::StringRef> getAsString() const {
382 if (Type == T_String)
383 return llvm::StringRef(as<std::string>());
384 if (LLVM_LIKELY(Type == T_StringRef))
385 return as<llvm::StringRef>();
388 const json::Object *getAsObject() const {
389 return LLVM_LIKELY(Type == T_Object) ? &as<json::Object>() : nullptr;
391 json::Object *getAsObject() {
392 return LLVM_LIKELY(Type == T_Object) ? &as<json::Object>() : nullptr;
394 const json::Array *getAsArray() const {
395 return LLVM_LIKELY(Type == T_Array) ? &as<json::Array>() : nullptr;
397 json::Array *getAsArray() {
398 return LLVM_LIKELY(Type == T_Array) ? &as<json::Array>() : nullptr;
401 /// Serializes this Value to JSON, writing it to the provided stream.
402 /// The formatting is compact (no extra whitespace) and deterministic.
403 /// For pretty-printing, use the formatv() format_provider below.
404 friend llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Value &);
408 void copyFrom(const Value &M);
409 // We allow moving from *const* Values, by marking all members as mutable!
410 // This hack is needed to support initializer-list syntax efficiently.
411 // (std::initializer_list<T> is a container of const T).
412 void moveFrom(const Value &&M);
416 template <typename T, typename... U> void create(U &&... V) {
417 new (reinterpret_cast<T *>(Union.buffer)) T(std::forward<U>(V)...);
419 template <typename T> T &as() const {
420 return *reinterpret_cast<T *>(Union.buffer);
423 template <typename Indenter>
424 void print(llvm::raw_ostream &, const Indenter &) const;
425 friend struct llvm::format_provider<llvm::json::Value>;
427 enum ValueType : char {
437 // All members mutable, see moveFrom().
438 mutable ValueType Type;
439 mutable llvm::AlignedCharArrayUnion<bool, double, int64_t, llvm::StringRef,
440 std::string, json::Array, json::Object>
444 bool operator==(const Value &, const Value &);
445 inline bool operator!=(const Value &L, const Value &R) { return !(L == R); }
446 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Value &);
448 /// ObjectKey is a used to capture keys in Object. Like Value but:
449 /// - only strings are allowed
450 /// - it's optimized for the string literal case (Owned == nullptr)
453 ObjectKey(const char *S) : Data(S) {}
454 ObjectKey(llvm::StringRef S) : Data(S) {}
455 ObjectKey(std::string &&V)
456 : Owned(new std::string(std::move(V))), Data(*Owned) {}
457 ObjectKey(const std::string &V) : Owned(new std::string(V)), Data(*Owned) {}
458 ObjectKey(const llvm::SmallVectorImpl<char> &V)
459 : ObjectKey(std::string(V.begin(), V.end())) {}
460 ObjectKey(const llvm::formatv_object_base &V) : ObjectKey(V.str()) {}
462 ObjectKey(const ObjectKey &C) { *this = C; }
463 ObjectKey(ObjectKey &&C) : ObjectKey(static_cast<const ObjectKey &&>(C)) {}
464 ObjectKey &operator=(const ObjectKey &C) {
466 Owned.reset(new std::string(*C.Owned));
473 ObjectKey &operator=(ObjectKey &&) = default;
475 operator llvm::StringRef() const { return Data; }
476 std::string str() const { return Data.str(); }
479 // FIXME: this is unneccesarily large (3 pointers). Pointer + length + owned
480 // could be 2 pointers at most.
481 std::unique_ptr<std::string> Owned;
482 llvm::StringRef Data;
485 inline bool operator==(const ObjectKey &L, const ObjectKey &R) {
486 return llvm::StringRef(L) == llvm::StringRef(R);
488 inline bool operator!=(const ObjectKey &L, const ObjectKey &R) {
491 inline bool operator<(const ObjectKey &L, const ObjectKey &R) {
492 return StringRef(L) < StringRef(R);
500 inline Object::Object(std::initializer_list<KV> Properties) {
501 for (const auto &P : Properties) {
502 auto R = try_emplace(P.K, nullptr);
504 R.first->getSecond().moveFrom(std::move(P.V));
507 inline std::pair<Object::iterator, bool> Object::insert(KV E) {
508 return try_emplace(std::move(E.K), std::move(E.V));
511 // Standard deserializers are provided for primitive types.
512 // See comments on Value.
513 inline bool fromJSON(const Value &E, std::string &Out) {
514 if (auto S = E.getAsString()) {
520 inline bool fromJSON(const Value &E, int &Out) {
521 if (auto S = E.getAsInteger()) {
527 inline bool fromJSON(const Value &E, int64_t &Out) {
528 if (auto S = E.getAsInteger()) {
534 inline bool fromJSON(const Value &E, double &Out) {
535 if (auto S = E.getAsNumber()) {
541 inline bool fromJSON(const Value &E, bool &Out) {
542 if (auto S = E.getAsBoolean()) {
548 template <typename T> bool fromJSON(const Value &E, llvm::Optional<T> &Out) {
554 if (!fromJSON(E, Result))
556 Out = std::move(Result);
559 template <typename T> bool fromJSON(const Value &E, std::vector<T> &Out) {
560 if (auto *A = E.getAsArray()) {
562 Out.resize(A->size());
563 for (size_t I = 0; I < A->size(); ++I)
564 if (!fromJSON((*A)[I], Out[I]))
570 template <typename T>
571 bool fromJSON(const Value &E, std::map<std::string, T> &Out) {
572 if (auto *O = E.getAsObject()) {
574 for (const auto &KV : *O)
575 if (!fromJSON(KV.second, Out[llvm::StringRef(KV.first)]))
582 /// Helper for mapping JSON objects onto protocol structs.
586 /// bool fromJSON(const Value &E, MyStruct &R) {
587 /// ObjectMapper O(E);
588 /// if (!O || !O.map("mandatory_field", R.MandatoryField))
590 /// O.map("optional_field", R.OptionalField);
596 ObjectMapper(const Value &E) : O(E.getAsObject()) {}
598 /// True if the expression is an object.
599 /// Must be checked before calling map().
600 operator bool() { return O; }
602 /// Maps a property to a field, if it exists.
603 template <typename T> bool map(StringRef Prop, T &Out) {
604 assert(*this && "Must check this is an object before calling map()");
605 if (const Value *E = O->get(Prop))
606 return fromJSON(*E, Out);
610 /// Maps a property to a field, if it exists.
611 /// (Optional requires special handling, because missing keys are OK).
612 template <typename T> bool map(StringRef Prop, llvm::Optional<T> &Out) {
613 assert(*this && "Must check this is an object before calling map()");
614 if (const Value *E = O->get(Prop))
615 return fromJSON(*E, Out);
624 /// Parses the provided JSON source, or returns a ParseError.
625 /// The returned Value is self-contained and owns its strings (they do not refer
626 /// to the original source).
627 llvm::Expected<Value> parse(llvm::StringRef JSON);
629 class ParseError : public llvm::ErrorInfo<ParseError> {
631 unsigned Line, Column, Offset;
635 ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
636 : Msg(Msg), Line(Line), Column(Column), Offset(Offset) {}
637 void log(llvm::raw_ostream &OS) const override {
638 OS << llvm::formatv("[{0}:{1}, byte={2}]: {3}", Line, Column, Offset, Msg);
640 std::error_code convertToErrorCode() const override {
641 return llvm::inconvertibleErrorCode();
646 /// Allow printing json::Value with formatv().
647 /// The default style is basic/compact formatting, like operator<<.
648 /// A format string like formatv("{0:2}", Value) pretty-prints with indent 2.
649 template <> struct format_provider<llvm::json::Value> {
650 static void format(const llvm::json::Value &, raw_ostream &, StringRef);