Remove dynamic's initializer_list constructor
[folly.git] / folly / dynamic.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * This is a runtime dynamically typed value.  It holds types from a
19  * specific predetermined set of types (ints, bools, arrays, etc).  In
20  * particular, it can be used as a convenient in-memory representation
21  * for complete json objects.
22  *
23  * In general you can try to use these objects as if they were the
24  * type they represent (although in some cases with a slightly less
25  * complete interface than the raw type), and it'll just throw a
26  * TypeError if it is used in an illegal way.
27  *
28  * Some examples:
29  *
30  *   dynamic twelve = 12;
31  *   dynamic str = "string";
32  *   dynamic map = dynamic::object;
33  *   map[str] = twelve;
34  *   map[str + "another_str"] = dynamic::array("array", "of", 4, "elements");
35  *   map.insert("null_element", nullptr);
36  *   ++map[str];
37  *   assert(map[str] == 13);
38  *
39  *   // Building a complex object with a sub array inline:
40  *   dynamic d = dynamic::object
41  *     ("key", "value")
42  *     ("key2", dynamic::array("a", "array"))
43  *     ;
44  *
45  * Also see folly/json.h for the serialization and deserialization
46  * functions for JSON.
47  *
48  * Note: dynamic is not DefaultConstructible.  Rationale:
49  *
50  *   - The intuitive thing to initialize a defaulted dynamic to would
51  *     be nullptr.
52  *
53  *   - However, the expression dynamic d = {} is required to call the
54  *     default constructor by the standard, which is confusing
55  *     behavior for dynamic unless the default constructor creates an
56  *     empty array.
57  *
58  * Additional documentation is in folly/docs/Dynamic.md.
59  *
60  * @author Jordan DeLong <delong.j@fb.com>
61  */
62
63 #pragma once
64
65 #include <cstdint>
66 #include <memory>
67 #include <ostream>
68 #include <string>
69 #include <type_traits>
70 #include <unordered_map>
71 #include <utility>
72 #include <vector>
73
74 #include <boost/operators.hpp>
75
76 #include <folly/Range.h>
77 #include <folly/Traits.h>
78
79 namespace folly {
80
81 //////////////////////////////////////////////////////////////////////
82
83 struct dynamic;
84 struct TypeError;
85
86 //////////////////////////////////////////////////////////////////////
87
88 struct dynamic : private boost::operators<dynamic> {
89   enum Type {
90     NULLT,
91     ARRAY,
92     BOOL,
93     DOUBLE,
94     INT64,
95     OBJECT,
96     STRING,
97   };
98
99   /*
100    * We support direct iteration of arrays, and indirect iteration of objects.
101    * See begin(), end(), keys(), values(), and items() for more.
102    *
103    * Array iterators dereference as the elements in the array.
104    * Object key iterators dereference as the keys in the object.
105    * Object value iterators dereference as the values in the object.
106    * Object item iterators dereference as pairs of (key, value).
107    */
108 private:
109   typedef std::vector<dynamic> Array;
110 public:
111   typedef Array::const_iterator const_iterator;
112   typedef dynamic value_type;
113   struct const_key_iterator;
114   struct const_value_iterator;
115   struct const_item_iterator;
116
117   /*
118    * Creation routines for making dynamic objects and arrays.  Objects
119    * are maps from key to value (so named due to json-related origins
120    * here).
121    *
122    * Example:
123    *
124    *   // Make a fairly complex dynamic:
125    *   dynamic d = dynamic::object("key", "value1")
126    *                              ("key2", dynamic::array("value",
127    *                                                      "with",
128    *                                                      4,
129    *                                                      "words"));
130    *
131    *   // Build an object in a few steps:
132    *   dynamic d = dynamic::object;
133    *   d["key"] = 12;
134    *   d["something_else"] = dynamic::array(1, 2, 3, nullptr);
135    */
136 private:
137   struct EmptyArrayTag {};
138   struct ObjectMaker;
139
140 public:
141   static void array(EmptyArrayTag);
142   template <class... Args>
143   static dynamic array(Args&& ...args);
144
145   static ObjectMaker object();
146   static ObjectMaker object(dynamic&&, dynamic&&);
147   static ObjectMaker object(dynamic const&, dynamic&&);
148   static ObjectMaker object(dynamic&&, dynamic const&);
149   static ObjectMaker object(dynamic const&, dynamic const&);
150
151   /*
152    * String compatibility constructors.
153    */
154   /* implicit */ dynamic(StringPiece val);
155   /* implicit */ dynamic(char const* val);
156   /* implicit */ dynamic(std::string const& val);
157   /* implicit */ dynamic(std::string&& val);
158
159   /*
160    * This is part of the plumbing for array() and object(), above.
161    * Used to create a new array or object dynamic.
162    */
163   /* implicit */ dynamic(void (*)(EmptyArrayTag));
164   /* implicit */ dynamic(ObjectMaker (*)());
165   /* implicit */ dynamic(ObjectMaker const&) = delete;
166   /* implicit */ dynamic(ObjectMaker&&);
167
168   /*
169    * Conversion constructors from most of the other types.
170    */
171   template<class T> /* implicit */ dynamic(T t);
172
173   /*
174    * Create a dynamic that is an array of the values from the supplied
175    * iterator range.
176    */
177   template<class Iterator> dynamic(Iterator first, Iterator last);
178
179   dynamic(dynamic const&);
180   dynamic(dynamic&&) noexcept;
181   ~dynamic() noexcept;
182
183   /*
184    * "Deep" equality comparison.  This will compare all the way down
185    * an object or array, and is potentially expensive.
186    */
187   bool operator==(dynamic const& o) const;
188
189   /*
190    * For all types except object this returns the natural ordering on
191    * those types.  For objects, we throw TypeError.
192    */
193   bool operator<(dynamic const& o) const;
194
195   /*
196    * General operators.
197    *
198    * These throw TypeError when used with types or type combinations
199    * that don't support them.
200    *
201    * These functions may also throw if you use 64-bit integers with
202    * doubles when the integers are too big to fit in a double.
203    */
204   dynamic& operator+=(dynamic const&);
205   dynamic& operator-=(dynamic const&);
206   dynamic& operator*=(dynamic const&);
207   dynamic& operator/=(dynamic const&);
208   dynamic& operator%=(dynamic const&);
209   dynamic& operator|=(dynamic const&);
210   dynamic& operator&=(dynamic const&);
211   dynamic& operator^=(dynamic const&);
212   dynamic& operator++();
213   dynamic& operator--();
214
215   /*
216    * Assignment from other dynamics.  Because of the implicit conversion
217    * to dynamic from its potential types, you can use this to change the
218    * type pretty intuitively.
219    *
220    * Basic guarantee only.
221    */
222   dynamic& operator=(dynamic const&);
223   dynamic& operator=(dynamic&&) noexcept;
224
225   /*
226    * For simple dynamics (not arrays or objects), this prints the
227    * value to an std::ostream in the expected way.  Respects the
228    * formatting manipulators that have been sent to the stream
229    * already.
230    *
231    * If the dynamic holds an object or array, this prints them in a
232    * format very similar to JSON.  (It will in fact actually be JSON
233    * as long as the dynamic validly represents a JSON object---i.e. it
234    * can't have non-string keys.)
235    */
236   friend std::ostream& operator<<(std::ostream&, dynamic const&);
237
238   /*
239    * Returns true if this dynamic is of the specified type.
240    */
241   bool isString() const;
242   bool isObject() const;
243   bool isBool() const;
244   bool isNull() const;
245   bool isArray() const;
246   bool isDouble() const;
247   bool isInt() const;
248
249   /*
250    * Returns: isInt() || isDouble().
251    */
252   bool isNumber() const;
253
254   /*
255    * Returns the type of this dynamic.
256    */
257   Type type() const;
258
259   /*
260    * Returns the type of this dynamic as a printable string.
261    */
262   const char* typeName() const;
263
264   /*
265    * Extract a value while trying to convert to the specified type.
266    * Throws exceptions if we cannot convert from the real type to the
267    * requested type.
268    *
269    * Note you can only use this to access integral types or strings,
270    * since arrays and objects are generally best dealt with as a
271    * dynamic.
272    */
273   std::string asString() const;
274   double   asDouble() const;
275   int64_t  asInt() const;
276   bool     asBool() const;
277
278   /*
279    * Extract the value stored in this dynamic without type conversion.
280    *
281    * These will throw a TypeError if the dynamic has a different type.
282    */
283   const std::string& getString() const&;
284   double          getDouble() const&;
285   int64_t         getInt() const&;
286   bool            getBool() const&;
287   std::string& getString() &;
288   double&   getDouble() &;
289   int64_t&  getInt() &;
290   bool&     getBool() &;
291   std::string&& getString() &&;
292   double   getDouble() &&;
293   int64_t  getInt() &&;
294   bool     getBool() &&;
295
296   /*
297    * It is occasionally useful to access a string's internal pointer
298    * directly, without the type conversion of `asString()`.
299    *
300    * These will throw a TypeError if the dynamic is not a string.
301    */
302   const char* data()  const&;
303   const char* data()  && = delete;
304   const char* c_str() const&;
305   const char* c_str() && = delete;
306   StringPiece stringPiece() const;
307
308   /*
309    * Returns: true if this dynamic is null, an empty array, an empty
310    * object, or an empty string.
311    */
312   bool empty() const;
313
314   /*
315    * If this is an array or an object, returns the number of elements
316    * contained.  If it is a string, returns the length.  Otherwise
317    * throws TypeError.
318    */
319   std::size_t size() const;
320
321   /*
322    * You can iterate over the values of the array.  Calling these on
323    * non-arrays will throw a TypeError.
324    */
325   const_iterator begin()  const;
326   const_iterator end()    const;
327
328 private:
329   /*
330    * Helper object returned by keys(), values(), and items().
331    */
332   template <class T> struct IterableProxy;
333
334 public:
335   /*
336    * You can iterate over the keys, values, or items (std::pair of key and
337    * value) in an object.  Calling these on non-objects will throw a TypeError.
338    */
339   IterableProxy<const_key_iterator> keys() const;
340   IterableProxy<const_value_iterator> values() const;
341   IterableProxy<const_item_iterator> items() const;
342
343   /*
344    * AssociativeContainer-style find interface for objects.  Throws if
345    * this is not an object.
346    *
347    * Returns: items().end() if the key is not present, or a
348    * const_item_iterator pointing to the item.
349    */
350   const_item_iterator find(dynamic const&) const;
351
352   /*
353    * If this is an object, returns whether it contains a field with
354    * the given name.  Otherwise throws TypeError.
355    */
356   std::size_t count(dynamic const&) const;
357
358   /*
359    * For objects or arrays, provides access to sub-fields by index or
360    * field name.
361    *
362    * Using these with dynamic objects that are not arrays or objects
363    * will throw a TypeError.  Using an index that is out of range or
364    * object-element that's not present throws std::out_of_range.
365    */
366   dynamic const& at(dynamic const&) const&;
367   dynamic&       at(dynamic const&) &;
368   dynamic&&      at(dynamic const&) &&;
369
370   /*
371    * Like 'at', above, except it returns either a pointer to the contained
372    * object or nullptr if it wasn't found. This allows a key to be tested for
373    * containment and retrieved in one operation. Example:
374    *
375    *   if (auto* found = d.get_ptr(key))
376    *     // use *found;
377    *
378    * Using these with dynamic objects that are not arrays or objects
379    * will throw a TypeError.
380    */
381   const dynamic* get_ptr(dynamic const&) const&;
382   dynamic* get_ptr(dynamic const&) &;
383   dynamic* get_ptr(dynamic const&) && = delete;
384
385   /*
386    * This works for access to both objects and arrays.
387    *
388    * In the case of an array, the index must be an integer, and this will throw
389    * std::out_of_range if it is less than zero or greater than size().
390    *
391    * In the case of an object, the non-const overload inserts a null
392    * value if the key isn't present.  The const overload will throw
393    * std::out_of_range if the key is not present.
394    *
395    * These functions do not invalidate iterators.
396    */
397   dynamic&       operator[](dynamic const&) &;
398   dynamic const& operator[](dynamic const&) const&;
399   dynamic&&      operator[](dynamic const&) &&;
400
401   /*
402    * Only defined for objects, throws TypeError otherwise.
403    *
404    * getDefault will return the value associated with the supplied key, the
405    * supplied default otherwise. setDefault will set the key to the supplied
406    * default if it is not yet set, otherwise leaving it. setDefault returns
407    * a reference to the existing value if present, the new value otherwise.
408    */
409   dynamic
410   getDefault(const dynamic& k, const dynamic& v = dynamic::object) const&;
411   dynamic getDefault(const dynamic& k, dynamic&& v) const&;
412   dynamic getDefault(const dynamic& k, const dynamic& v = dynamic::object) &&;
413   dynamic getDefault(const dynamic& k, dynamic&& v) &&;
414   template<class K, class V>
415   dynamic& setDefault(K&& k, V&& v);
416   // MSVC 2015 Update 3 needs these extra overloads because if V were a
417   // defaulted template parameter, it causes MSVC to consider v an rvalue
418   // reference rather than a universal reference, resulting in it not being
419   // able to find the correct overload to construct a dynamic with.
420   template<class K>
421   dynamic& setDefault(K&& k, dynamic&& v);
422   template<class K>
423   dynamic& setDefault(K&& k, const dynamic& v = dynamic::object);
424
425   /*
426    * Resizes an array so it has at n elements, using the supplied
427    * default to fill new elements.  Throws TypeError if this dynamic
428    * is not an array.
429    *
430    * May invalidate iterators.
431    *
432    * Post: size() == n
433    */
434   void resize(std::size_t n, dynamic const& = nullptr);
435
436   /*
437    * Inserts the supplied key-value pair to an object, or throws if
438    * it's not an object.
439    *
440    * Invalidates iterators.
441    */
442   template<class K, class V> void insert(K&&, V&& val);
443
444   /*
445    * These functions merge two folly dynamic objects.
446    * The "update" and "update_missing" functions extend the object by
447    *  inserting the key/value pairs of mergeObj into the current object.
448    *  For update, if key is duplicated between the two objects, it
449    *  will overwrite with the value of the object being inserted (mergeObj).
450    *  For "update_missing", it will prefer the value in the original object
451    *
452    * The "merge" function creates a new object consisting of the key/value
453    * pairs of both mergeObj1 and mergeObj2
454    * If the key is duplicated between the two objects,
455    *  it will prefer value in the second object (mergeObj2)
456    */
457   void update(const dynamic& mergeObj);
458   void update_missing(const dynamic& other);
459   static dynamic merge(const dynamic& mergeObj1, const dynamic& mergeObj2);
460
461   /*
462    * Erase an element from a dynamic object, by key.
463    *
464    * Invalidates iterators to the element being erased.
465    *
466    * Returns the number of elements erased (i.e. 1 or 0).
467    */
468   std::size_t erase(dynamic const& key);
469
470   /*
471    * Erase an element from a dynamic object or array, using an
472    * iterator or an iterator range.
473    *
474    * In arrays, invalidates iterators to elements after the element
475    * being erased.  In objects, invalidates iterators to the elements
476    * being erased.
477    *
478    * Returns a new iterator to the first element beyond any elements
479    * removed, or end() if there are none.  (The iteration order does
480    * not change.)
481    */
482   const_iterator erase(const_iterator it);
483   const_iterator erase(const_iterator first, const_iterator last);
484
485   const_key_iterator erase(const_key_iterator it);
486   const_key_iterator erase(const_key_iterator first, const_key_iterator last);
487
488   const_value_iterator erase(const_value_iterator it);
489   const_value_iterator erase(const_value_iterator first,
490                              const_value_iterator last);
491
492   const_item_iterator erase(const_item_iterator it);
493   const_item_iterator erase(const_item_iterator first,
494                             const_item_iterator last);
495   /*
496    * Append elements to an array.  If this is not an array, throws
497    * TypeError.
498    *
499    * Invalidates iterators.
500    */
501   void push_back(dynamic const&);
502   void push_back(dynamic&&);
503
504   /*
505    * Remove an element from the back of an array.  If this is not an array,
506    * throws TypeError.
507    *
508    * Does not invalidate iterators.
509    */
510   void pop_back();
511
512   /*
513    * Get a hash code.  This function is called by a std::hash<>
514    * specialization, also.
515    *
516    * Throws TypeError if this is an object, array, or null.
517    */
518   std::size_t hash() const;
519
520 private:
521   friend struct TypeError;
522   struct ObjectImpl;
523   template<class T> struct TypeInfo;
524   template<class T> struct CompareOp;
525   template<class T> struct GetAddrImpl;
526   template<class T> struct PrintImpl;
527
528   explicit dynamic(Array&& array);
529
530   template<class T> T const& get() const;
531   template<class T> T&       get();
532   template<class T> T*       get_nothrow() & noexcept;
533   template<class T> T const* get_nothrow() const& noexcept;
534   template<class T> T*       get_nothrow() && noexcept = delete;
535   template<class T> T*       getAddress() noexcept;
536   template<class T> T const* getAddress() const noexcept;
537
538   template<class T> T asImpl() const;
539
540   static char const* typeName(Type);
541   void destroy() noexcept;
542   void print(std::ostream&) const;
543   void print_as_pseudo_json(std::ostream&) const; // see json.cpp
544
545 private:
546   Type type_;
547   union Data {
548     explicit Data() : nul(nullptr) {}
549     ~Data() {}
550
551     // XXX: gcc does an ICE if we use std::nullptr_t instead of void*
552     // here.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50361
553     void* nul;
554     Array array;
555     bool boolean;
556     double doubl;
557     int64_t integer;
558     std::string string;
559
560     /*
561      * Objects are placement new'd here.  We have to use a char buffer
562      * because we don't know the type here (std::unordered_map<> with
563      * dynamic would be parameterizing a std:: template with an
564      * incomplete type right now).  (Note that in contrast we know it
565      * is ok to do this with fbvector because we own it.)
566      */
567     std::aligned_storage<
568       sizeof(std::unordered_map<int,int>),
569       alignof(std::unordered_map<int,int>)
570     >::type objectBuffer;
571   } u_;
572 };
573
574 //////////////////////////////////////////////////////////////////////
575
576 }
577
578 #include <folly/dynamic-inl.h>