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