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