Update embedded jsoncpp from unk version to 0.10.6 + move libs to lib/ instead of...
[oweals/minetest.git] / lib / jsoncpp / json / json.h
1 /// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
2 /// It is intended to be used with #include "json/json.h"
3
4 // //////////////////////////////////////////////////////////////////////
5 // Beginning of content of file: LICENSE
6 // //////////////////////////////////////////////////////////////////////
7
8 /*
9 The JsonCpp library's source code, including accompanying documentation,
10 tests and demonstration applications, are licensed under the following
11 conditions...
12
13 The author (Baptiste Lepilleur) explicitly disclaims copyright in all
14 jurisdictions which recognize such a disclaimer. In such jurisdictions,
15 this software is released into the Public Domain.
16
17 In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
18 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
19 released under the terms of the MIT License (see below).
20
21 In jurisdictions which recognize Public Domain property, the user of this
22 software may choose to accept it either as 1) Public Domain, 2) under the
23 conditions of the MIT License (see below), or 3) under the terms of dual
24 Public Domain/MIT License conditions described here, as they choose.
25
26 The MIT License is about as close to Public Domain as a license can get, and is
27 described in clear, concise terms at:
28
29    http://en.wikipedia.org/wiki/MIT_License
30
31 The full text of the MIT License follows:
32
33 ========================================================================
34 Copyright (c) 2007-2010 Baptiste Lepilleur
35
36 Permission is hereby granted, free of charge, to any person
37 obtaining a copy of this software and associated documentation
38 files (the "Software"), to deal in the Software without
39 restriction, including without limitation the rights to use, copy,
40 modify, merge, publish, distribute, sublicense, and/or sell copies
41 of the Software, and to permit persons to whom the Software is
42 furnished to do so, subject to the following conditions:
43
44 The above copyright notice and this permission notice shall be
45 included in all copies or substantial portions of the Software.
46
47 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
48 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
49 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
50 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
51 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
52 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
53 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
54 SOFTWARE.
55 ========================================================================
56 (END LICENSE TEXT)
57
58 The MIT license is compatible with both the GPL and commercial
59 software, affording one all of the rights of Public Domain with the
60 minor nuisance of being required to keep the above copyright notice
61 and license text in the source code. Note also that by accepting the
62 Public Domain "license" you can re-license your copy using whatever
63 license you like.
64
65 */
66
67 // //////////////////////////////////////////////////////////////////////
68 // End of content of file: LICENSE
69 // //////////////////////////////////////////////////////////////////////
70
71
72
73
74
75 #ifndef JSON_AMALGATED_H_INCLUDED
76 # define JSON_AMALGATED_H_INCLUDED
77 /// If defined, indicates that the source file is amalgated
78 /// to prevent private header inclusion.
79 #define JSON_IS_AMALGAMATION
80 #define JSONCPP_STRING
81 // //////////////////////////////////////////////////////////////////////
82 // Beginning of content of file: include/json/version.h
83 // //////////////////////////////////////////////////////////////////////
84
85 // DO NOT EDIT. This file (and "version") is generated by CMake.
86 // Run CMake configure step to update it.
87 #ifndef JSON_VERSION_H_INCLUDED
88 # define JSON_VERSION_H_INCLUDED
89
90 # define JSONCPP_VERSION_STRING "0.10.6"
91 # define JSONCPP_VERSION_MAJOR 0
92 # define JSONCPP_VERSION_MINOR 10
93 # define JSONCPP_VERSION_PATCH 6
94 # define JSONCPP_VERSION_QUALIFIER
95 # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
96
97 #endif // JSON_VERSION_H_INCLUDED
98
99 // //////////////////////////////////////////////////////////////////////
100 // End of content of file: include/json/version.h
101 // //////////////////////////////////////////////////////////////////////
102
103
104
105
106
107
108 // //////////////////////////////////////////////////////////////////////
109 // Beginning of content of file: include/json/config.h
110 // //////////////////////////////////////////////////////////////////////
111
112 // Copyright 2007-2010 Baptiste Lepilleur
113 // Distributed under MIT license, or public domain if desired and
114 // recognized in your jurisdiction.
115 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
116
117 #ifndef JSON_CONFIG_H_INCLUDED
118 #define JSON_CONFIG_H_INCLUDED
119
120 /// If defined, indicates that json library is embedded in CppTL library.
121 //# define JSON_IN_CPPTL 1
122
123 /// If defined, indicates that json may leverage CppTL library
124 //#  define JSON_USE_CPPTL 1
125 /// If defined, indicates that cpptl vector based map should be used instead of
126 /// std::map
127 /// as Value container.
128 //#  define JSON_USE_CPPTL_SMALLMAP 1
129
130 // If non-zero, the library uses exceptions to report bad input instead of C
131 // assertion macros. The default is to use exceptions.
132 #ifndef JSON_USE_EXCEPTION
133 #define JSON_USE_EXCEPTION 1
134 #endif
135
136 /// If defined, indicates that the source file is amalgated
137 /// to prevent private header inclusion.
138 /// Remarks: it is automatically defined in the generated amalgated header.
139 // #define JSON_IS_AMALGAMATION
140
141 #ifdef JSON_IN_CPPTL
142 #include <cpptl/config.h>
143 #ifndef JSON_USE_CPPTL
144 #define JSON_USE_CPPTL 1
145 #endif
146 #endif
147
148 #ifdef JSON_IN_CPPTL
149 #define JSON_API CPPTL_API
150 #elif defined(JSON_DLL_BUILD)
151 #if defined(_MSC_VER)
152 #define JSON_API __declspec(dllexport)
153 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
154 #endif // if defined(_MSC_VER)
155 #elif defined(JSON_DLL)
156 #if defined(_MSC_VER)
157 #define JSON_API __declspec(dllimport)
158 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
159 #endif // if defined(_MSC_VER)
160 #endif // ifdef JSON_IN_CPPTL
161 #if !defined(JSON_API)
162 #define JSON_API
163 #endif
164
165 // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
166 // integer
167 // Storages, and 64 bits integer support is disabled.
168 // #define JSON_NO_INT64 1
169
170 #if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6
171 // Microsoft Visual Studio 6 only support conversion from __int64 to double
172 // (no conversion from unsigned __int64).
173 #define JSON_USE_INT64_DOUBLE_CONVERSION 1
174 // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
175 // characters in the debug information)
176 // All projects I've ever seen with VS6 were using this globally (not bothering
177 // with pragma push/pop).
178 #pragma warning(disable : 4786)
179 #endif // if defined(_MSC_VER)  &&  _MSC_VER < 1200 // MSVC 6
180
181 #if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008
182 /// Indicates that the following function is deprecated.
183 #define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
184 #elif defined(__clang__) && defined(__has_feature)
185 #if __has_feature(attribute_deprecated_with_message)
186 #define JSONCPP_DEPRECATED(message)  __attribute__ ((deprecated(message)))
187 #endif
188 #elif defined(__GNUC__) &&  (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
189 #define JSONCPP_DEPRECATED(message)  __attribute__ ((deprecated(message)))
190 #elif defined(__GNUC__) &&  (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
191 #define JSONCPP_DEPRECATED(message)  __attribute__((__deprecated__))
192 #endif
193
194 #if !defined(JSONCPP_DEPRECATED)
195 #define JSONCPP_DEPRECATED(message)
196 #endif // if !defined(JSONCPP_DEPRECATED)
197
198 namespace Json {
199 typedef int Int;
200 typedef unsigned int UInt;
201 #if defined(JSON_NO_INT64)
202 typedef int LargestInt;
203 typedef unsigned int LargestUInt;
204 #undef JSON_HAS_INT64
205 #else                 // if defined(JSON_NO_INT64)
206 // For Microsoft Visual use specific types as long long is not supported
207 #if defined(_MSC_VER) // Microsoft Visual Studio
208 typedef __int64 Int64;
209 typedef unsigned __int64 UInt64;
210 #else                 // if defined(_MSC_VER) // Other platforms, use long long
211 typedef long long int Int64;
212 typedef unsigned long long int UInt64;
213 #endif // if defined(_MSC_VER)
214 typedef Int64 LargestInt;
215 typedef UInt64 LargestUInt;
216 #define JSON_HAS_INT64
217 #endif // if defined(JSON_NO_INT64)
218 } // end namespace Json
219
220 #endif // JSON_CONFIG_H_INCLUDED
221
222 // //////////////////////////////////////////////////////////////////////
223 // End of content of file: include/json/config.h
224 // //////////////////////////////////////////////////////////////////////
225
226
227
228
229
230
231 // //////////////////////////////////////////////////////////////////////
232 // Beginning of content of file: include/json/forwards.h
233 // //////////////////////////////////////////////////////////////////////
234
235 // Copyright 2007-2010 Baptiste Lepilleur
236 // Distributed under MIT license, or public domain if desired and
237 // recognized in your jurisdiction.
238 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
239
240 #ifndef JSON_FORWARDS_H_INCLUDED
241 #define JSON_FORWARDS_H_INCLUDED
242
243 #if !defined(JSON_IS_AMALGAMATION)
244 #include "config.h"
245 #endif // if !defined(JSON_IS_AMALGAMATION)
246
247 namespace Json {
248
249 // writer.h
250 class FastWriter;
251 class StyledWriter;
252
253 // reader.h
254 class Reader;
255
256 // features.h
257 class Features;
258
259 // value.h
260 typedef unsigned int ArrayIndex;
261 class StaticString;
262 class Path;
263 class PathArgument;
264 class Value;
265 class ValueIteratorBase;
266 class ValueIterator;
267 class ValueConstIterator;
268
269 } // namespace Json
270
271 #endif // JSON_FORWARDS_H_INCLUDED
272
273 // //////////////////////////////////////////////////////////////////////
274 // End of content of file: include/json/forwards.h
275 // //////////////////////////////////////////////////////////////////////
276
277
278
279
280
281
282 // //////////////////////////////////////////////////////////////////////
283 // Beginning of content of file: include/json/features.h
284 // //////////////////////////////////////////////////////////////////////
285
286 // Copyright 2007-2010 Baptiste Lepilleur
287 // Distributed under MIT license, or public domain if desired and
288 // recognized in your jurisdiction.
289 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
290
291 #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
292 #define CPPTL_JSON_FEATURES_H_INCLUDED
293
294 #if !defined(JSON_IS_AMALGAMATION)
295 #include "forwards.h"
296 #endif // if !defined(JSON_IS_AMALGAMATION)
297
298 namespace Json {
299
300 /** \brief Configuration passed to reader and writer.
301  * This configuration object can be used to force the Reader or Writer
302  * to behave in a standard conforming way.
303  */
304 class JSON_API Features {
305 public:
306   /** \brief A configuration that allows all features and assumes all strings
307    * are UTF-8.
308    * - C & C++ comments are allowed
309    * - Root object can be any JSON value
310    * - Assumes Value strings are encoded in UTF-8
311    */
312   static Features all();
313
314   /** \brief A configuration that is strictly compatible with the JSON
315    * specification.
316    * - Comments are forbidden.
317    * - Root object must be either an array or an object value.
318    * - Assumes Value strings are encoded in UTF-8
319    */
320   static Features strictMode();
321
322   /** \brief Initialize the configuration like JsonConfig::allFeatures;
323    */
324   Features();
325
326   /// \c true if comments are allowed. Default: \c true.
327   bool allowComments_;
328
329   /// \c true if root must be either an array or an object value. Default: \c
330   /// false.
331   bool strictRoot_;
332 };
333
334 } // namespace Json
335
336 #endif // CPPTL_JSON_FEATURES_H_INCLUDED
337
338 // //////////////////////////////////////////////////////////////////////
339 // End of content of file: include/json/features.h
340 // //////////////////////////////////////////////////////////////////////
341
342
343
344
345
346
347 // //////////////////////////////////////////////////////////////////////
348 // Beginning of content of file: include/json/value.h
349 // //////////////////////////////////////////////////////////////////////
350
351 // Copyright 2007-2010 Baptiste Lepilleur
352 // Distributed under MIT license, or public domain if desired and
353 // recognized in your jurisdiction.
354 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
355
356 #ifndef CPPTL_JSON_H_INCLUDED
357 #define CPPTL_JSON_H_INCLUDED
358
359 #if !defined(JSON_IS_AMALGAMATION)
360 #include "forwards.h"
361 #endif // if !defined(JSON_IS_AMALGAMATION)
362 #include <string>
363 #include <vector>
364 #include <exception>
365
366 #ifndef JSON_USE_CPPTL_SMALLMAP
367 #include <map>
368 #else
369 #include <cpptl/smallmap.h>
370 #endif
371 #ifdef JSON_USE_CPPTL
372 #include <cpptl/forwards.h>
373 #endif
374
375 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
376 // be used by...
377 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
378 #pragma warning(push)
379 #pragma warning(disable : 4251)
380 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
381
382 //Conditional NORETURN attribute on the throw functions would:
383 // a) suppress false positives from static code analysis
384 // b) possibly improve optimization opportunities.
385 #if !defined(JSONCPP_NORETURN)
386 #  if defined(_MSC_VER)
387 #    define JSONCPP_NORETURN __declspec(noreturn)
388 #  elif defined(__GNUC__)
389 #    define JSONCPP_NORETURN __attribute__ ((__noreturn__))
390 #  else
391 #    define JSONCPP_NORETURN
392 #  endif
393 #endif
394
395 /** \brief JSON (JavaScript Object Notation).
396  */
397 namespace Json {
398
399 /** Base class for all exceptions we throw.
400  *
401  * We use nothing but these internally. Of course, STL can throw others.
402  */
403 class JSON_API Exception : public std::exception {
404 public:
405   Exception(std::string const& msg);
406   virtual ~Exception() throw();
407   virtual char const* what() const throw();
408 protected:
409   std::string const msg_;
410 };
411
412 /** Exceptions which the user cannot easily avoid.
413  *
414  * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
415  *
416  * \remark derived from Json::Exception
417  */
418 class JSON_API RuntimeError : public Exception {
419 public:
420   RuntimeError(std::string const& msg);
421 };
422
423 /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
424  *
425  * These are precondition-violations (user bugs) and internal errors (our bugs).
426  *
427  * \remark derived from Json::Exception
428  */
429 class JSON_API LogicError : public Exception {
430 public:
431   LogicError(std::string const& msg);
432 };
433
434 /// used internally
435 JSONCPP_NORETURN void throwRuntimeError(std::string const& msg);
436 /// used internally
437 JSONCPP_NORETURN void throwLogicError(std::string const& msg);
438
439 /** \brief Type of the value held by a Value object.
440  */
441 enum ValueType {
442   nullValue = 0, ///< 'null' value
443   intValue,      ///< signed integer value
444   uintValue,     ///< unsigned integer value
445   realValue,     ///< double value
446   stringValue,   ///< UTF-8 string value
447   booleanValue,  ///< bool value
448   arrayValue,    ///< array value (ordered list)
449   objectValue    ///< object value (collection of name/value pairs).
450 };
451
452 enum CommentPlacement {
453   commentBefore = 0,      ///< a comment placed on the line before a value
454   commentAfterOnSameLine, ///< a comment just after a value on the same line
455   commentAfter, ///< a comment on the line after a value (only make sense for
456   /// root value)
457   numberOfCommentPlacement
458 };
459
460 //# ifdef JSON_USE_CPPTL
461 //   typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
462 //   typedef CppTL::AnyEnumerator<const Value &> EnumValues;
463 //# endif
464
465 /** \brief Lightweight wrapper to tag static string.
466  *
467  * Value constructor and objectValue member assignement takes advantage of the
468  * StaticString and avoid the cost of string duplication when storing the
469  * string or the member name.
470  *
471  * Example of usage:
472  * \code
473  * Json::Value aValue( StaticString("some text") );
474  * Json::Value object;
475  * static const StaticString code("code");
476  * object[code] = 1234;
477  * \endcode
478  */
479 class JSON_API StaticString {
480 public:
481   explicit StaticString(const char* czstring) : c_str_(czstring) {}
482
483   operator const char*() const { return c_str_; }
484
485   const char* c_str() const { return c_str_; }
486
487 private:
488   const char* c_str_;
489 };
490
491 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
492  *
493  * This class is a discriminated union wrapper that can represents a:
494  * - signed integer [range: Value::minInt - Value::maxInt]
495  * - unsigned integer (range: 0 - Value::maxUInt)
496  * - double
497  * - UTF-8 string
498  * - boolean
499  * - 'null'
500  * - an ordered list of Value
501  * - collection of name/value pairs (javascript object)
502  *
503  * The type of the held value is represented by a #ValueType and
504  * can be obtained using type().
505  *
506  * Values of an #objectValue or #arrayValue can be accessed using operator[]()
507  * methods.
508  * Non-const methods will automatically create the a #nullValue element
509  * if it does not exist.
510  * The sequence of an #arrayValue will be automatically resized and initialized
511  * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
512  *
513  * The get() methods can be used to obtain default value in the case the
514  * required element does not exist.
515  *
516  * It is possible to iterate over the list of a #objectValue values using
517  * the getMemberNames() method.
518  *
519  * \note #Value string-length fit in size_t, but keys must be < 2^30.
520  * (The reason is an implementation detail.) A #CharReader will raise an
521  * exception if a bound is exceeded to avoid security holes in your app,
522  * but the Value API does *not* check bounds. That is the responsibility
523  * of the caller.
524  */
525 class JSON_API Value {
526   friend class ValueIteratorBase;
527 public:
528   typedef std::vector<std::string> Members;
529   typedef ValueIterator iterator;
530   typedef ValueConstIterator const_iterator;
531   typedef Json::UInt UInt;
532   typedef Json::Int Int;
533 #if defined(JSON_HAS_INT64)
534   typedef Json::UInt64 UInt64;
535   typedef Json::Int64 Int64;
536 #endif // defined(JSON_HAS_INT64)
537   typedef Json::LargestInt LargestInt;
538   typedef Json::LargestUInt LargestUInt;
539   typedef Json::ArrayIndex ArrayIndex;
540
541   static const Value& nullRef;
542 #if !defined(__ARMEL__)
543   /// \deprecated This exists for binary compatibility only. Use nullRef.
544   static const Value null;
545 #endif
546   /// Minimum signed integer value that can be stored in a Json::Value.
547   static const LargestInt minLargestInt;
548   /// Maximum signed integer value that can be stored in a Json::Value.
549   static const LargestInt maxLargestInt;
550   /// Maximum unsigned integer value that can be stored in a Json::Value.
551   static const LargestUInt maxLargestUInt;
552
553   /// Minimum signed int value that can be stored in a Json::Value.
554   static const Int minInt;
555   /// Maximum signed int value that can be stored in a Json::Value.
556   static const Int maxInt;
557   /// Maximum unsigned int value that can be stored in a Json::Value.
558   static const UInt maxUInt;
559
560 #if defined(JSON_HAS_INT64)
561   /// Minimum signed 64 bits int value that can be stored in a Json::Value.
562   static const Int64 minInt64;
563   /// Maximum signed 64 bits int value that can be stored in a Json::Value.
564   static const Int64 maxInt64;
565   /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
566   static const UInt64 maxUInt64;
567 #endif // defined(JSON_HAS_INT64)
568
569 private:
570 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
571   class CZString {
572   public:
573     enum DuplicationPolicy {
574       noDuplication = 0,
575       duplicate,
576       duplicateOnCopy
577     };
578     CZString(ArrayIndex index);
579     CZString(char const* str, unsigned length, DuplicationPolicy allocate);
580     CZString(CZString const& other);
581     ~CZString();
582     CZString& operator=(CZString other);
583     bool operator<(CZString const& other) const;
584     bool operator==(CZString const& other) const;
585     ArrayIndex index() const;
586     //const char* c_str() const; ///< \deprecated
587     char const* data() const;
588     unsigned length() const;
589     bool isStaticString() const;
590
591   private:
592     void swap(CZString& other);
593
594     struct StringStorage {
595       unsigned policy_: 2;
596       unsigned length_: 30; // 1GB max
597     };
598
599     char const* cstr_;  // actually, a prefixed string, unless policy is noDup
600     union {
601       ArrayIndex index_;
602       StringStorage storage_;
603     };
604   };
605
606 public:
607 #ifndef JSON_USE_CPPTL_SMALLMAP
608   typedef std::map<CZString, Value> ObjectValues;
609 #else
610   typedef CppTL::SmallMap<CZString, Value> ObjectValues;
611 #endif // ifndef JSON_USE_CPPTL_SMALLMAP
612 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
613
614 public:
615   /** \brief Create a default Value of the given type.
616
617     This is a very useful constructor.
618     To create an empty array, pass arrayValue.
619     To create an empty object, pass objectValue.
620     Another Value can then be set to this one by assignment.
621 This is useful since clear() and resize() will not alter types.
622
623     Examples:
624 \code
625 Json::Value null_value; // null
626 Json::Value arr_value(Json::arrayValue); // []
627 Json::Value obj_value(Json::objectValue); // {}
628 \endcode
629   */
630   Value(ValueType type = nullValue);
631   Value(Int value);
632   Value(UInt value);
633 #if defined(JSON_HAS_INT64)
634   Value(Int64 value);
635   Value(UInt64 value);
636 #endif // if defined(JSON_HAS_INT64)
637   Value(double value);
638   Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
639   Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
640   /** \brief Constructs a value from a static string.
641
642    * Like other value string constructor but do not duplicate the string for
643    * internal storage. The given string must remain alive after the call to this
644    * constructor.
645    * \note This works only for null-terminated strings. (We cannot change the
646    *   size of this class, so we have nowhere to store the length,
647    *   which might be computed later for various operations.)
648    *
649    * Example of usage:
650    * \code
651    * static StaticString foo("some text");
652    * Json::Value aValue(foo);
653    * \endcode
654    */
655   Value(const StaticString& value);
656   Value(const std::string& value); ///< Copy data() til size(). Embedded zeroes too.
657 #ifdef JSON_USE_CPPTL
658   Value(const CppTL::ConstString& value);
659 #endif
660   Value(bool value);
661   /// Deep copy.
662   Value(const Value& other);
663   ~Value();
664
665   /// Deep copy, then swap(other).
666   /// \note Over-write existing comments. To preserve comments, use #swapPayload().
667   Value &operator=(const Value &other);
668   /// Swap everything.
669   void swap(Value& other);
670   /// Swap values but leave comments and source offsets in place.
671   void swapPayload(Value& other);
672
673   ValueType type() const;
674
675   /// Compare payload only, not comments etc.
676   bool operator<(const Value& other) const;
677   bool operator<=(const Value& other) const;
678   bool operator>=(const Value& other) const;
679   bool operator>(const Value& other) const;
680   bool operator==(const Value& other) const;
681   bool operator!=(const Value& other) const;
682   int compare(const Value& other) const;
683
684   const char* asCString() const; ///< Embedded zeroes could cause you trouble!
685   std::string asString() const; ///< Embedded zeroes are possible.
686   /** Get raw char* of string-value.
687    *  \return false if !string. (Seg-fault if str or end are NULL.)
688    */
689   bool getString(
690       char const** begin, char const** end) const;
691 #ifdef JSON_USE_CPPTL
692   CppTL::ConstString asConstString() const;
693 #endif
694   Int asInt() const;
695   UInt asUInt() const;
696 #if defined(JSON_HAS_INT64)
697   Int64 asInt64() const;
698   UInt64 asUInt64() const;
699 #endif // if defined(JSON_HAS_INT64)
700   LargestInt asLargestInt() const;
701   LargestUInt asLargestUInt() const;
702   float asFloat() const;
703   double asDouble() const;
704   bool asBool() const;
705
706   bool isNull() const;
707   bool isBool() const;
708   bool isInt() const;
709   bool isInt64() const;
710   bool isUInt() const;
711   bool isUInt64() const;
712   bool isIntegral() const;
713   bool isDouble() const;
714   bool isNumeric() const;
715   bool isString() const;
716   bool isArray() const;
717   bool isObject() const;
718
719   bool isConvertibleTo(ValueType other) const;
720
721   /// Number of values in array or object
722   ArrayIndex size() const;
723
724   /// \brief Return true if empty array, empty object, or null;
725   /// otherwise, false.
726   bool empty() const;
727
728   /// Return isNull()
729   bool operator!() const;
730
731   /// Remove all object members and array elements.
732   /// \pre type() is arrayValue, objectValue, or nullValue
733   /// \post type() is unchanged
734   void clear();
735
736   /// Resize the array to size elements.
737   /// New elements are initialized to null.
738   /// May only be called on nullValue or arrayValue.
739   /// \pre type() is arrayValue or nullValue
740   /// \post type() is arrayValue
741   void resize(ArrayIndex size);
742
743   /// Access an array element (zero based index ).
744   /// If the array contains less than index element, then null value are
745   /// inserted
746   /// in the array so that its size is index+1.
747   /// (You may need to say 'value[0u]' to get your compiler to distinguish
748   ///  this from the operator[] which takes a string.)
749   Value& operator[](ArrayIndex index);
750
751   /// Access an array element (zero based index ).
752   /// If the array contains less than index element, then null value are
753   /// inserted
754   /// in the array so that its size is index+1.
755   /// (You may need to say 'value[0u]' to get your compiler to distinguish
756   ///  this from the operator[] which takes a string.)
757   Value& operator[](int index);
758
759   /// Access an array element (zero based index )
760   /// (You may need to say 'value[0u]' to get your compiler to distinguish
761   ///  this from the operator[] which takes a string.)
762   const Value& operator[](ArrayIndex index) const;
763
764   /// Access an array element (zero based index )
765   /// (You may need to say 'value[0u]' to get your compiler to distinguish
766   ///  this from the operator[] which takes a string.)
767   const Value& operator[](int index) const;
768
769   /// If the array contains at least index+1 elements, returns the element
770   /// value,
771   /// otherwise returns defaultValue.
772   Value get(ArrayIndex index, const Value& defaultValue) const;
773   /// Return true if index < size().
774   bool isValidIndex(ArrayIndex index) const;
775   /// \brief Append value to array at the end.
776   ///
777   /// Equivalent to jsonvalue[jsonvalue.size()] = value;
778   Value& append(const Value& value);
779
780   /// Access an object value by name, create a null member if it does not exist.
781   /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
782   ///  Exceeding that will cause an exception.
783   Value& operator[](const char* key);
784   /// Access an object value by name, returns null if there is no member with
785   /// that name.
786   const Value& operator[](const char* key) const;
787   /// Access an object value by name, create a null member if it does not exist.
788   /// \param key may contain embedded nulls.
789   Value& operator[](const std::string& key);
790   /// Access an object value by name, returns null if there is no member with
791   /// that name.
792   /// \param key may contain embedded nulls.
793   const Value& operator[](const std::string& key) const;
794   /** \brief Access an object value by name, create a null member if it does not
795    exist.
796
797    * If the object has no entry for that name, then the member name used to store
798    * the new entry is not duplicated.
799    * Example of use:
800    * \code
801    * Json::Value object;
802    * static const StaticString code("code");
803    * object[code] = 1234;
804    * \endcode
805    */
806   Value& operator[](const StaticString& key);
807 #ifdef JSON_USE_CPPTL
808   /// Access an object value by name, create a null member if it does not exist.
809   Value& operator[](const CppTL::ConstString& key);
810   /// Access an object value by name, returns null if there is no member with
811   /// that name.
812   const Value& operator[](const CppTL::ConstString& key) const;
813 #endif
814   /// Return the member named key if it exist, defaultValue otherwise.
815   /// \note deep copy
816   Value get(const char* key, const Value& defaultValue) const;
817   /// Return the member named key if it exist, defaultValue otherwise.
818   /// \note deep copy
819   /// \note key may contain embedded nulls.
820   Value get(const char* begin, const char* end, const Value& defaultValue) const;
821   /// Return the member named key if it exist, defaultValue otherwise.
822   /// \note deep copy
823   /// \param key may contain embedded nulls.
824   Value get(const std::string& key, const Value& defaultValue) const;
825 #ifdef JSON_USE_CPPTL
826   /// Return the member named key if it exist, defaultValue otherwise.
827   /// \note deep copy
828   Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
829 #endif
830   /// Most general and efficient version of isMember()const, get()const,
831   /// and operator[]const
832   /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
833   Value const* find(char const* begin, char const* end) const;
834   /// Most general and efficient version of object-mutators.
835   /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
836   /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
837   Value const* demand(char const* begin, char const* end);
838   /// \brief Remove and return the named member.
839   ///
840   /// Do nothing if it did not exist.
841   /// \return the removed Value, or null.
842   /// \pre type() is objectValue or nullValue
843   /// \post type() is unchanged
844   /// \deprecated
845   Value removeMember(const char* key);
846   /// Same as removeMember(const char*)
847   /// \param key may contain embedded nulls.
848   /// \deprecated
849   Value removeMember(const std::string& key);
850   /// Same as removeMember(const char* begin, const char* end, Value* removed),
851   /// but 'key' is null-terminated.
852   bool removeMember(const char* key, Value* removed);
853   /** \brief Remove the named map member.
854
855       Update 'removed' iff removed.
856       \param key may contain embedded nulls.
857       \return true iff removed (no exceptions)
858   */
859   bool removeMember(std::string const& key, Value* removed);
860   /// Same as removeMember(std::string const& key, Value* removed)
861   bool removeMember(const char* begin, const char* end, Value* removed);
862   /** \brief Remove the indexed array element.
863
864       O(n) expensive operations.
865       Update 'removed' iff removed.
866       \return true iff removed (no exceptions)
867   */
868   bool removeIndex(ArrayIndex i, Value* removed);
869
870   /// Return true if the object has a member named key.
871   /// \note 'key' must be null-terminated.
872   bool isMember(const char* key) const;
873   /// Return true if the object has a member named key.
874   /// \param key may contain embedded nulls.
875   bool isMember(const std::string& key) const;
876   /// Same as isMember(std::string const& key)const
877   bool isMember(const char* begin, const char* end) const;
878 #ifdef JSON_USE_CPPTL
879   /// Return true if the object has a member named key.
880   bool isMember(const CppTL::ConstString& key) const;
881 #endif
882
883   /// \brief Return a list of the member names.
884   ///
885   /// If null, return an empty list.
886   /// \pre type() is objectValue or nullValue
887   /// \post if type() was nullValue, it remains nullValue
888   Members getMemberNames() const;
889
890   //# ifdef JSON_USE_CPPTL
891   //      EnumMemberNames enumMemberNames() const;
892   //      EnumValues enumValues() const;
893   //# endif
894
895   /// \deprecated Always pass len.
896   JSONCPP_DEPRECATED("Use setComment(std::string const&) instead.")
897   void setComment(const char* comment, CommentPlacement placement);
898   /// Comments must be //... or /* ... */
899   void setComment(const char* comment, size_t len, CommentPlacement placement);
900   /// Comments must be //... or /* ... */
901   void setComment(const std::string& comment, CommentPlacement placement);
902   bool hasComment(CommentPlacement placement) const;
903   /// Include delimiters and embedded newlines.
904   std::string getComment(CommentPlacement placement) const;
905
906   std::string toStyledString() const;
907
908   const_iterator begin() const;
909   const_iterator end() const;
910
911   iterator begin();
912   iterator end();
913
914 private:
915   void initBasic(ValueType type, bool allocated = false);
916
917   Value& resolveReference(const char* key);
918   Value& resolveReference(const char* key, const char* end);
919
920   struct CommentInfo {
921     CommentInfo();
922     ~CommentInfo();
923
924     void setComment(const char* text, size_t len);
925
926     char* comment_;
927   };
928
929   // struct MemberNamesTransform
930   //{
931   //   typedef const char *result_type;
932   //   const char *operator()( const CZString &name ) const
933   //   {
934   //      return name.c_str();
935   //   }
936   //};
937
938   union ValueHolder {
939     LargestInt int_;
940     LargestUInt uint_;
941     double real_;
942     bool bool_;
943     char* string_;  // actually ptr to unsigned, followed by str, unless !allocated_
944     ObjectValues* map_;
945   } value_;
946   ValueType type_ : 8;
947   unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
948                                // If not allocated_, string_ must be null-terminated.
949   CommentInfo* comments_;
950 };
951
952 /** \brief Experimental and untested: represents an element of the "path" to
953  * access a node.
954  */
955 class JSON_API PathArgument {
956 public:
957   friend class Path;
958
959   PathArgument();
960   PathArgument(ArrayIndex index);
961   PathArgument(const char* key);
962   PathArgument(const std::string& key);
963
964 private:
965   enum Kind {
966     kindNone = 0,
967     kindIndex,
968     kindKey
969   };
970   std::string key_;
971   ArrayIndex index_;
972   Kind kind_;
973 };
974
975 /** \brief Experimental and untested: represents a "path" to access a node.
976  *
977  * Syntax:
978  * - "." => root node
979  * - ".[n]" => elements at index 'n' of root node (an array value)
980  * - ".name" => member named 'name' of root node (an object value)
981  * - ".name1.name2.name3"
982  * - ".[0][1][2].name1[3]"
983  * - ".%" => member name is provided as parameter
984  * - ".[%]" => index is provied as parameter
985  */
986 class JSON_API Path {
987 public:
988   Path(const std::string& path,
989        const PathArgument& a1 = PathArgument(),
990        const PathArgument& a2 = PathArgument(),
991        const PathArgument& a3 = PathArgument(),
992        const PathArgument& a4 = PathArgument(),
993        const PathArgument& a5 = PathArgument());
994
995   const Value& resolve(const Value& root) const;
996   Value resolve(const Value& root, const Value& defaultValue) const;
997   /// Creates the "path" to access the specified node and returns a reference on
998   /// the node.
999   Value& make(Value& root) const;
1000
1001 private:
1002   typedef std::vector<const PathArgument*> InArgs;
1003   typedef std::vector<PathArgument> Args;
1004
1005   void makePath(const std::string& path, const InArgs& in);
1006   void addPathInArg(const std::string& path,
1007                     const InArgs& in,
1008                     InArgs::const_iterator& itInArg,
1009                     PathArgument::Kind kind);
1010   void invalidPath(const std::string& path, int location);
1011
1012   Args args_;
1013 };
1014
1015 /** \brief base class for Value iterators.
1016  *
1017  */
1018 class JSON_API ValueIteratorBase {
1019 public:
1020   typedef std::bidirectional_iterator_tag iterator_category;
1021   typedef unsigned int size_t;
1022   typedef int difference_type;
1023   typedef ValueIteratorBase SelfType;
1024
1025   bool operator==(const SelfType& other) const { return isEqual(other); }
1026
1027   bool operator!=(const SelfType& other) const { return !isEqual(other); }
1028
1029   difference_type operator-(const SelfType& other) const {
1030     return other.computeDistance(*this);
1031   }
1032
1033   /// Return either the index or the member name of the referenced value as a
1034   /// Value.
1035   Value key() const;
1036
1037   /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
1038   UInt index() const;
1039
1040   /// Return the member name of the referenced Value, or "" if it is not an
1041   /// objectValue.
1042   /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
1043   std::string name() const;
1044
1045   /// Return the member name of the referenced Value. "" if it is not an
1046   /// objectValue.
1047   /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
1048   JSONCPP_DEPRECATED("Use `key = name();` instead.")
1049   char const* memberName() const;
1050   /// Return the member name of the referenced Value, or NULL if it is not an
1051   /// objectValue.
1052   /// \note Better version than memberName(). Allows embedded nulls.
1053   char const* memberName(char const** end) const;
1054
1055 protected:
1056   Value& deref() const;
1057
1058   void increment();
1059
1060   void decrement();
1061
1062   difference_type computeDistance(const SelfType& other) const;
1063
1064   bool isEqual(const SelfType& other) const;
1065
1066   void copy(const SelfType& other);
1067
1068 private:
1069   Value::ObjectValues::iterator current_;
1070   // Indicates that iterator is for a null value.
1071   bool isNull_;
1072
1073 public:
1074   // For some reason, BORLAND needs these at the end, rather
1075   // than earlier. No idea why.
1076   ValueIteratorBase();
1077   explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
1078 };
1079
1080 /** \brief const iterator for object and array value.
1081  *
1082  */
1083 class JSON_API ValueConstIterator : public ValueIteratorBase {
1084   friend class Value;
1085
1086 public:
1087   typedef const Value value_type;
1088   //typedef unsigned int size_t;
1089   //typedef int difference_type;
1090   typedef const Value& reference;
1091   typedef const Value* pointer;
1092   typedef ValueConstIterator SelfType;
1093
1094   ValueConstIterator();
1095
1096 private:
1097 /*! \internal Use by Value to create an iterator.
1098  */
1099   explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
1100 public:
1101   SelfType& operator=(const ValueIteratorBase& other);
1102
1103   SelfType operator++(int) {
1104     SelfType temp(*this);
1105     ++*this;
1106     return temp;
1107   }
1108
1109   SelfType operator--(int) {
1110     SelfType temp(*this);
1111     --*this;
1112     return temp;
1113   }
1114
1115   SelfType& operator--() {
1116     decrement();
1117     return *this;
1118   }
1119
1120   SelfType& operator++() {
1121     increment();
1122     return *this;
1123   }
1124
1125   reference operator*() const { return deref(); }
1126
1127   pointer operator->() const { return &deref(); }
1128 };
1129
1130 /** \brief Iterator for object and array value.
1131  */
1132 class JSON_API ValueIterator : public ValueIteratorBase {
1133   friend class Value;
1134
1135 public:
1136   typedef Value value_type;
1137   typedef unsigned int size_t;
1138   typedef int difference_type;
1139   typedef Value& reference;
1140   typedef Value* pointer;
1141   typedef ValueIterator SelfType;
1142
1143   ValueIterator();
1144   ValueIterator(const ValueConstIterator& other);
1145   ValueIterator(const ValueIterator& other);
1146
1147 private:
1148 /*! \internal Use by Value to create an iterator.
1149  */
1150   explicit ValueIterator(const Value::ObjectValues::iterator& current);
1151 public:
1152   SelfType& operator=(const SelfType& other);
1153
1154   SelfType operator++(int) {
1155     SelfType temp(*this);
1156     ++*this;
1157     return temp;
1158   }
1159
1160   SelfType operator--(int) {
1161     SelfType temp(*this);
1162     --*this;
1163     return temp;
1164   }
1165
1166   SelfType& operator--() {
1167     decrement();
1168     return *this;
1169   }
1170
1171   SelfType& operator++() {
1172     increment();
1173     return *this;
1174   }
1175
1176   reference operator*() const { return deref(); }
1177
1178   pointer operator->() const { return &deref(); }
1179 };
1180
1181 } // namespace Json
1182
1183
1184 namespace std {
1185 /// Specialize std::swap() for Json::Value.
1186 template<>
1187 inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
1188 }
1189
1190
1191 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1192 #pragma warning(pop)
1193 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1194
1195 #endif // CPPTL_JSON_H_INCLUDED
1196
1197 // //////////////////////////////////////////////////////////////////////
1198 // End of content of file: include/json/value.h
1199 // //////////////////////////////////////////////////////////////////////
1200
1201
1202
1203
1204
1205
1206 // //////////////////////////////////////////////////////////////////////
1207 // Beginning of content of file: include/json/reader.h
1208 // //////////////////////////////////////////////////////////////////////
1209
1210 // Copyright 2007-2010 Baptiste Lepilleur
1211 // Distributed under MIT license, or public domain if desired and
1212 // recognized in your jurisdiction.
1213 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1214
1215 #ifndef CPPTL_JSON_READER_H_INCLUDED
1216 #define CPPTL_JSON_READER_H_INCLUDED
1217
1218 #if !defined(JSON_IS_AMALGAMATION)
1219 #include "features.h"
1220 #include "value.h"
1221 #endif // if !defined(JSON_IS_AMALGAMATION)
1222 #include <deque>
1223 #include <iosfwd>
1224 #include <stack>
1225 #include <string>
1226 #include <istream>
1227
1228 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1229 // be used by...
1230 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1231 #pragma warning(push)
1232 #pragma warning(disable : 4251)
1233 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1234
1235 namespace Json {
1236
1237 /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
1238  *Value.
1239  *
1240  * \deprecated Use CharReader and CharReaderBuilder.
1241  */
1242 class JSON_API Reader {
1243 public:
1244   typedef char Char;
1245   typedef const Char* Location;
1246
1247   /** \brief Constructs a Reader allowing all features
1248    * for parsing.
1249    */
1250   Reader();
1251
1252   /** \brief Constructs a Reader allowing the specified feature set
1253    * for parsing.
1254    */
1255   Reader(const Features& features);
1256
1257   /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1258    * document.
1259    * \param document UTF-8 encoded string containing the document to read.
1260    * \param root [out] Contains the root value of the document if it was
1261    *             successfully parsed.
1262    * \param collectComments \c true to collect comment and allow writing them
1263    * back during
1264    *                        serialization, \c false to discard comments.
1265    *                        This parameter is ignored if
1266    * Features::allowComments_
1267    *                        is \c false.
1268    * \return \c true if the document was successfully parsed, \c false if an
1269    * error occurred.
1270    */
1271   bool
1272   parse(const std::string& document, Value& root, bool collectComments = true);
1273
1274   /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1275    document.
1276    * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1277    document to read.
1278    * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1279    document to read.
1280    *               Must be >= beginDoc.
1281    * \param root [out] Contains the root value of the document if it was
1282    *             successfully parsed.
1283    * \param collectComments \c true to collect comment and allow writing them
1284    back during
1285    *                        serialization, \c false to discard comments.
1286    *                        This parameter is ignored if
1287    Features::allowComments_
1288    *                        is \c false.
1289    * \return \c true if the document was successfully parsed, \c false if an
1290    error occurred.
1291    */
1292   bool parse(const char* beginDoc,
1293              const char* endDoc,
1294              Value& root,
1295              bool collectComments = true);
1296
1297   /// \brief Parse from input stream.
1298   /// \see Json::operator>>(std::istream&, Json::Value&).
1299   bool parse(std::istream& is, Value& root, bool collectComments = true);
1300
1301   /** \brief Returns a user friendly string that list errors in the parsed
1302    * document.
1303    * \return Formatted error message with the list of errors with their location
1304    * in
1305    *         the parsed document. An empty string is returned if no error
1306    * occurred
1307    *         during parsing.
1308    * \deprecated Use getFormattedErrorMessages() instead (typo fix).
1309    */
1310   JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
1311   std::string getFormatedErrorMessages() const;
1312
1313   /** \brief Returns a user friendly string that list errors in the parsed
1314    * document.
1315    * \return Formatted error message with the list of errors with their location
1316    * in
1317    *         the parsed document. An empty string is returned if no error
1318    * occurred
1319    *         during parsing.
1320    */
1321   std::string getFormattedErrorMessages() const;
1322
1323 private:
1324   enum TokenType {
1325     tokenEndOfStream = 0,
1326     tokenObjectBegin,
1327     tokenObjectEnd,
1328     tokenArrayBegin,
1329     tokenArrayEnd,
1330     tokenString,
1331     tokenNumber,
1332     tokenTrue,
1333     tokenFalse,
1334     tokenNull,
1335     tokenArraySeparator,
1336     tokenMemberSeparator,
1337     tokenComment,
1338     tokenError
1339   };
1340
1341   class Token {
1342   public:
1343     TokenType type_;
1344     Location start_;
1345     Location end_;
1346   };
1347
1348   class ErrorInfo {
1349   public:
1350     Token token_;
1351     std::string message_;
1352     Location extra_;
1353   };
1354
1355   typedef std::deque<ErrorInfo> Errors;
1356
1357   bool readToken(Token& token);
1358   void skipSpaces();
1359   bool match(Location pattern, int patternLength);
1360   bool readComment();
1361   bool readCStyleComment();
1362   bool readCppStyleComment();
1363   bool readString();
1364   void readNumber();
1365   bool readValue();
1366   bool readObject(Token& token);
1367   bool readArray(Token& token);
1368   bool decodeNumber(Token& token);
1369   bool decodeNumber(Token& token, Value& decoded);
1370   bool decodeString(Token& token);
1371   bool decodeString(Token& token, std::string& decoded);
1372   bool decodeDouble(Token& token);
1373   bool decodeDouble(Token& token, Value& decoded);
1374   bool decodeUnicodeCodePoint(Token& token,
1375                               Location& current,
1376                               Location end,
1377                               unsigned int& unicode);
1378   bool decodeUnicodeEscapeSequence(Token& token,
1379                                    Location& current,
1380                                    Location end,
1381                                    unsigned int& unicode);
1382   bool addError(const std::string& message, Token& token, Location extra = 0);
1383   bool recoverFromError(TokenType skipUntilToken);
1384   bool addErrorAndRecover(const std::string& message,
1385                           Token& token,
1386                           TokenType skipUntilToken);
1387   void skipUntilSpace();
1388   Value& currentValue();
1389   Char getNextChar();
1390   void
1391   getLocationLineAndColumn(Location location, int& line, int& column) const;
1392   std::string getLocationLineAndColumn(Location location) const;
1393   void addComment(Location begin, Location end, CommentPlacement placement);
1394   void skipCommentTokens(Token& token);
1395
1396   typedef std::stack<Value*> Nodes;
1397   Nodes nodes_;
1398   Errors errors_;
1399   std::string document_;
1400   Location begin_;
1401   Location end_;
1402   Location current_;
1403   Location lastValueEnd_;
1404   Value* lastValue_;
1405   std::string commentsBefore_;
1406   Features features_;
1407   bool collectComments_;
1408 };  // Reader
1409
1410 /** Interface for reading JSON from a char array.
1411  */
1412 class JSON_API CharReader {
1413 public:
1414   virtual ~CharReader() {}
1415   /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1416    document.
1417    * The document must be a UTF-8 encoded string containing the document to read.
1418    *
1419    * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1420    document to read.
1421    * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1422    document to read.
1423    *        Must be >= beginDoc.
1424    * \param root [out] Contains the root value of the document if it was
1425    *             successfully parsed.
1426    * \param errs [out] Formatted error messages (if not NULL)
1427    *        a user friendly string that lists errors in the parsed
1428    * document.
1429    * \return \c true if the document was successfully parsed, \c false if an
1430    error occurred.
1431    */
1432   virtual bool parse(
1433       char const* beginDoc, char const* endDoc,
1434       Value* root, std::string* errs) = 0;
1435
1436   class Factory {
1437   public:
1438     virtual ~Factory() {}
1439     /** \brief Allocate a CharReader via operator new().
1440      * \throw std::exception if something goes wrong (e.g. invalid settings)
1441      */
1442     virtual CharReader* newCharReader() const = 0;
1443   };  // Factory
1444 };  // CharReader
1445
1446 /** \brief Build a CharReader implementation.
1447
1448 Usage:
1449 \code
1450   using namespace Json;
1451   CharReaderBuilder builder;
1452   builder["collectComments"] = false;
1453   Value value;
1454   std::string errs;
1455   bool ok = parseFromStream(builder, std::cin, &value, &errs);
1456 \endcode
1457 */
1458 class JSON_API CharReaderBuilder : public CharReader::Factory {
1459 public:
1460   // Note: We use a Json::Value so that we can add data-members to this class
1461   // without a major version bump.
1462   /** Configuration of this builder.
1463     These are case-sensitive.
1464     Available settings (case-sensitive):
1465     - `"collectComments": false or true`
1466       - true to collect comment and allow writing them
1467         back during serialization, false to discard comments.
1468         This parameter is ignored if allowComments is false.
1469     - `"allowComments": false or true`
1470       - true if comments are allowed.
1471     - `"strictRoot": false or true`
1472       - true if root must be either an array or an object value
1473     - `"allowDroppedNullPlaceholders": false or true`
1474       - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
1475     - `"allowNumericKeys": false or true`
1476       - true if numeric object keys are allowed.
1477     - `"allowSingleQuotes": false or true`
1478       - true if '' are allowed for strings (both keys and values)
1479     - `"stackLimit": integer`
1480       - Exceeding stackLimit (recursive depth of `readValue()`) will
1481         cause an exception.
1482       - This is a security issue (seg-faults caused by deeply nested JSON),
1483         so the default is low.
1484     - `"failIfExtra": false or true`
1485       - If true, `parse()` returns false when extra non-whitespace trails
1486         the JSON value in the input string.
1487     - `"rejectDupKeys": false or true`
1488       - If true, `parse()` returns false when a key is duplicated within an object.
1489     - `"allowSpecialFloats": false or true`
1490       - If true, special float values (NaNs and infinities) are allowed
1491         and their values are lossfree restorable.
1492
1493     You can examine 'settings_` yourself
1494     to see the defaults. You can also write and read them just like any
1495     JSON Value.
1496     \sa setDefaults()
1497     */
1498   Json::Value settings_;
1499
1500   CharReaderBuilder();
1501   virtual ~CharReaderBuilder();
1502
1503   virtual CharReader* newCharReader() const;
1504
1505   /** \return true if 'settings' are legal and consistent;
1506    *   otherwise, indicate bad settings via 'invalid'.
1507    */
1508   bool validate(Json::Value* invalid) const;
1509
1510   /** A simple way to update a specific setting.
1511    */
1512   Value& operator[](std::string key);
1513
1514   /** Called by ctor, but you can use this to reset settings_.
1515    * \pre 'settings' != NULL (but Json::null is fine)
1516    * \remark Defaults:
1517    * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
1518    */
1519   static void setDefaults(Json::Value* settings);
1520   /** Same as old Features::strictMode().
1521    * \pre 'settings' != NULL (but Json::null is fine)
1522    * \remark Defaults:
1523    * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
1524    */
1525   static void strictMode(Json::Value* settings);
1526 };
1527
1528 /** Consume entire stream and use its begin/end.
1529   * Someday we might have a real StreamReader, but for now this
1530   * is convenient.
1531   */
1532 bool JSON_API parseFromStream(
1533     CharReader::Factory const&,
1534     std::istream&,
1535     Value* root, std::string* errs);
1536
1537 /** \brief Read from 'sin' into 'root'.
1538
1539  Always keep comments from the input JSON.
1540
1541  This can be used to read a file into a particular sub-object.
1542  For example:
1543  \code
1544  Json::Value root;
1545  cin >> root["dir"]["file"];
1546  cout << root;
1547  \endcode
1548  Result:
1549  \verbatim
1550  {
1551  "dir": {
1552      "file": {
1553      // The input stream JSON would be nested here.
1554      }
1555  }
1556  }
1557  \endverbatim
1558  \throw std::exception on parse error.
1559  \see Json::operator<<()
1560 */
1561 JSON_API std::istream& operator>>(std::istream&, Value&);
1562
1563 } // namespace Json
1564
1565 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1566 #pragma warning(pop)
1567 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1568
1569 #endif // CPPTL_JSON_READER_H_INCLUDED
1570
1571 // //////////////////////////////////////////////////////////////////////
1572 // End of content of file: include/json/reader.h
1573 // //////////////////////////////////////////////////////////////////////
1574
1575
1576
1577
1578
1579
1580 // //////////////////////////////////////////////////////////////////////
1581 // Beginning of content of file: include/json/writer.h
1582 // //////////////////////////////////////////////////////////////////////
1583
1584 // Copyright 2007-2010 Baptiste Lepilleur
1585 // Distributed under MIT license, or public domain if desired and
1586 // recognized in your jurisdiction.
1587 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1588
1589 #ifndef JSON_WRITER_H_INCLUDED
1590 #define JSON_WRITER_H_INCLUDED
1591
1592 #if !defined(JSON_IS_AMALGAMATION)
1593 #include "value.h"
1594 #endif // if !defined(JSON_IS_AMALGAMATION)
1595 #include <vector>
1596 #include <string>
1597 #include <ostream>
1598
1599 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1600 // be used by...
1601 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1602 #pragma warning(push)
1603 #pragma warning(disable : 4251)
1604 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1605
1606 namespace Json {
1607
1608 class Value;
1609
1610 /**
1611
1612 Usage:
1613 \code
1614   using namespace Json;
1615   void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
1616     std::unique_ptr<StreamWriter> const writer(
1617       factory.newStreamWriter());
1618     writer->write(value, &std::cout);
1619     std::cout << std::endl;  // add lf and flush
1620   }
1621 \endcode
1622 */
1623 class JSON_API StreamWriter {
1624 protected:
1625   std::ostream* sout_;  // not owned; will not delete
1626 public:
1627   StreamWriter();
1628   virtual ~StreamWriter();
1629   /** Write Value into document as configured in sub-class.
1630       Do not take ownership of sout, but maintain a reference during function.
1631       \pre sout != NULL
1632       \return zero on success (For now, we always return zero, so check the stream instead.)
1633       \throw std::exception possibly, depending on configuration
1634    */
1635   virtual int write(Value const& root, std::ostream* sout) = 0;
1636
1637   /** \brief A simple abstract factory.
1638    */
1639   class JSON_API Factory {
1640   public:
1641     virtual ~Factory();
1642     /** \brief Allocate a CharReader via operator new().
1643      * \throw std::exception if something goes wrong (e.g. invalid settings)
1644      */
1645     virtual StreamWriter* newStreamWriter() const = 0;
1646   };  // Factory
1647 };  // StreamWriter
1648
1649 /** \brief Write into stringstream, then return string, for convenience.
1650  * A StreamWriter will be created from the factory, used, and then deleted.
1651  */
1652 std::string JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
1653
1654
1655 /** \brief Build a StreamWriter implementation.
1656
1657 Usage:
1658 \code
1659   using namespace Json;
1660   Value value = ...;
1661   StreamWriterBuilder builder;
1662   builder["commentStyle"] = "None";
1663   builder["indentation"] = "   ";  // or whatever you like
1664   std::unique_ptr<Json::StreamWriter> writer(
1665       builder.newStreamWriter());
1666   writer->write(value, &std::cout);
1667   std::cout << std::endl;  // add lf and flush
1668 \endcode
1669 */
1670 class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
1671 public:
1672   // Note: We use a Json::Value so that we can add data-members to this class
1673   // without a major version bump.
1674   /** Configuration of this builder.
1675     Available settings (case-sensitive):
1676     - "commentStyle": "None" or "All"
1677     - "indentation":  "<anything>"
1678     - "enableYAMLCompatibility": false or true
1679       - slightly change the whitespace around colons
1680     - "dropNullPlaceholders": false or true
1681       - Drop the "null" string from the writer's output for nullValues.
1682         Strictly speaking, this is not valid JSON. But when the output is being
1683         fed to a browser's Javascript, it makes for smaller output and the
1684         browser can handle the output just fine.
1685     - "useSpecialFloats": false or true
1686       - If true, outputs non-finite floating point values in the following way:
1687         NaN values as "NaN", positive infinity as "Infinity", and negative infinity
1688         as "-Infinity".
1689
1690     You can examine 'settings_` yourself
1691     to see the defaults. You can also write and read them just like any
1692     JSON Value.
1693     \sa setDefaults()
1694     */
1695   Json::Value settings_;
1696
1697   StreamWriterBuilder();
1698   virtual ~StreamWriterBuilder();
1699
1700   /**
1701    * \throw std::exception if something goes wrong (e.g. invalid settings)
1702    */
1703   virtual StreamWriter* newStreamWriter() const;
1704
1705   /** \return true if 'settings' are legal and consistent;
1706    *   otherwise, indicate bad settings via 'invalid'.
1707    */
1708   bool validate(Json::Value* invalid) const;
1709   /** A simple way to update a specific setting.
1710    */
1711   Value& operator[](std::string key);
1712
1713   /** Called by ctor, but you can use this to reset settings_.
1714    * \pre 'settings' != NULL (but Json::null is fine)
1715    * \remark Defaults:
1716    * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
1717    */
1718   static void setDefaults(Json::Value* settings);
1719 };
1720
1721 /** \brief Abstract class for writers.
1722  * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
1723  */
1724 class JSON_API Writer {
1725 public:
1726   virtual ~Writer();
1727
1728   virtual std::string write(const Value& root) = 0;
1729 };
1730
1731 /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
1732  *without formatting (not human friendly).
1733  *
1734  * The JSON document is written in a single line. It is not intended for 'human'
1735  *consumption,
1736  * but may be usefull to support feature such as RPC where bandwith is limited.
1737  * \sa Reader, Value
1738  * \deprecated Use StreamWriterBuilder.
1739  */
1740 class JSON_API FastWriter : public Writer {
1741
1742 public:
1743   FastWriter();
1744   virtual ~FastWriter() {}
1745
1746   void enableYAMLCompatibility();
1747
1748 public: // overridden from Writer
1749   virtual std::string write(const Value& root);
1750
1751 private:
1752   void writeValue(const Value& value);
1753
1754   std::string document_;
1755   bool yamlCompatiblityEnabled_;
1756 };
1757
1758 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1759  *human friendly way.
1760  *
1761  * The rules for line break and indent are as follow:
1762  * - Object value:
1763  *     - if empty then print {} without indent and line break
1764  *     - if not empty the print '{', line break & indent, print one value per
1765  *line
1766  *       and then unindent and line break and print '}'.
1767  * - Array value:
1768  *     - if empty then print [] without indent and line break
1769  *     - if the array contains no object value, empty array or some other value
1770  *types,
1771  *       and all the values fit on one lines, then print the array on a single
1772  *line.
1773  *     - otherwise, it the values do not fit on one line, or the array contains
1774  *       object or non empty array, then print one value per line.
1775  *
1776  * If the Value have comments then they are outputed according to their
1777  *#CommentPlacement.
1778  *
1779  * \sa Reader, Value, Value::setComment()
1780  * \deprecated Use StreamWriterBuilder.
1781  */
1782 class JSON_API StyledWriter : public Writer {
1783 public:
1784   StyledWriter();
1785   virtual ~StyledWriter() {}
1786
1787 public: // overridden from Writer
1788   /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1789    * \param root Value to serialize.
1790    * \return String containing the JSON document that represents the root value.
1791    */
1792   virtual std::string write(const Value& root);
1793
1794 private:
1795   void writeValue(const Value& value);
1796   void writeArrayValue(const Value& value);
1797   bool isMultineArray(const Value& value);
1798   void pushValue(const std::string& value);
1799   void writeIndent();
1800   void writeWithIndent(const std::string& value);
1801   void indent();
1802   void unindent();
1803   void writeCommentBeforeValue(const Value& root);
1804   void writeCommentAfterValueOnSameLine(const Value& root);
1805   bool hasCommentForValue(const Value& value);
1806   static std::string normalizeEOL(const std::string& text);
1807
1808   typedef std::vector<std::string> ChildValues;
1809
1810   ChildValues childValues_;
1811   std::string document_;
1812   std::string indentString_;
1813   int rightMargin_;
1814   int indentSize_;
1815   bool addChildValues_;
1816 };
1817
1818 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1819  human friendly way,
1820      to a stream rather than to a string.
1821  *
1822  * The rules for line break and indent are as follow:
1823  * - Object value:
1824  *     - if empty then print {} without indent and line break
1825  *     - if not empty the print '{', line break & indent, print one value per
1826  line
1827  *       and then unindent and line break and print '}'.
1828  * - Array value:
1829  *     - if empty then print [] without indent and line break
1830  *     - if the array contains no object value, empty array or some other value
1831  types,
1832  *       and all the values fit on one lines, then print the array on a single
1833  line.
1834  *     - otherwise, it the values do not fit on one line, or the array contains
1835  *       object or non empty array, then print one value per line.
1836  *
1837  * If the Value have comments then they are outputed according to their
1838  #CommentPlacement.
1839  *
1840  * \param indentation Each level will be indented by this amount extra.
1841  * \sa Reader, Value, Value::setComment()
1842  * \deprecated Use StreamWriterBuilder.
1843  */
1844 class JSON_API StyledStreamWriter {
1845 public:
1846   StyledStreamWriter(std::string indentation = "\t");
1847   ~StyledStreamWriter() {}
1848
1849 public:
1850   /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1851    * \param out Stream to write to. (Can be ostringstream, e.g.)
1852    * \param root Value to serialize.
1853    * \note There is no point in deriving from Writer, since write() should not
1854    * return a value.
1855    */
1856   void write(std::ostream& out, const Value& root);
1857
1858 private:
1859   void writeValue(const Value& value);
1860   void writeArrayValue(const Value& value);
1861   bool isMultineArray(const Value& value);
1862   void pushValue(const std::string& value);
1863   void writeIndent();
1864   void writeWithIndent(const std::string& value);
1865   void indent();
1866   void unindent();
1867   void writeCommentBeforeValue(const Value& root);
1868   void writeCommentAfterValueOnSameLine(const Value& root);
1869   bool hasCommentForValue(const Value& value);
1870   static std::string normalizeEOL(const std::string& text);
1871
1872   typedef std::vector<std::string> ChildValues;
1873
1874   ChildValues childValues_;
1875   std::ostream* document_;
1876   std::string indentString_;
1877   int rightMargin_;
1878   std::string indentation_;
1879   bool addChildValues_ : 1;
1880   bool indented_ : 1;
1881 };
1882
1883 #if defined(JSON_HAS_INT64)
1884 std::string JSON_API valueToString(Int value);
1885 std::string JSON_API valueToString(UInt value);
1886 #endif // if defined(JSON_HAS_INT64)
1887 std::string JSON_API valueToString(LargestInt value);
1888 std::string JSON_API valueToString(LargestUInt value);
1889 std::string JSON_API valueToString(double value);
1890 std::string JSON_API valueToString(bool value);
1891 std::string JSON_API valueToQuotedString(const char* value);
1892
1893 /// \brief Output using the StyledStreamWriter.
1894 /// \see Json::operator>>()
1895 JSON_API std::ostream& operator<<(std::ostream&, const Value& root);
1896
1897 } // namespace Json
1898
1899 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1900 #pragma warning(pop)
1901 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1902
1903 #endif // JSON_WRITER_H_INCLUDED
1904
1905 // //////////////////////////////////////////////////////////////////////
1906 // End of content of file: include/json/writer.h
1907 // //////////////////////////////////////////////////////////////////////
1908
1909
1910
1911
1912
1913
1914 // //////////////////////////////////////////////////////////////////////
1915 // Beginning of content of file: include/json/assertions.h
1916 // //////////////////////////////////////////////////////////////////////
1917
1918 // Copyright 2007-2010 Baptiste Lepilleur
1919 // Distributed under MIT license, or public domain if desired and
1920 // recognized in your jurisdiction.
1921 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1922
1923 #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
1924 #define CPPTL_JSON_ASSERTIONS_H_INCLUDED
1925
1926 #include <stdlib.h>
1927 #include <sstream>
1928
1929 #if !defined(JSON_IS_AMALGAMATION)
1930 #include "config.h"
1931 #endif // if !defined(JSON_IS_AMALGAMATION)
1932
1933 /** It should not be possible for a maliciously designed file to
1934  *  cause an abort() or seg-fault, so these macros are used only
1935  *  for pre-condition violations and internal logic errors.
1936  */
1937 #if JSON_USE_EXCEPTION
1938
1939 // @todo <= add detail about condition in exception
1940 # define JSON_ASSERT(condition)                                                \
1941   {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
1942
1943 # define JSON_FAIL_MESSAGE(message)                                            \
1944   {                                                                            \
1945     std::ostringstream oss; oss << message;                                    \
1946     Json::throwLogicError(oss.str());                                          \
1947     abort();                                                                   \
1948   }
1949
1950 #else // JSON_USE_EXCEPTION
1951
1952 # define JSON_ASSERT(condition) assert(condition)
1953
1954 // The call to assert() will show the failure message in debug builds. In
1955 // release builds we abort, for a core-dump or debugger.
1956 # define JSON_FAIL_MESSAGE(message)                                            \
1957   {                                                                            \
1958     std::ostringstream oss; oss << message;                                    \
1959     assert(false && oss.str().c_str());                                        \
1960     abort();                                                                   \
1961   }
1962
1963
1964 #endif
1965
1966 #define JSON_ASSERT_MESSAGE(condition, message)                                \
1967   if (!(condition)) {                                                          \
1968     JSON_FAIL_MESSAGE(message);                                                \
1969   }
1970
1971 #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
1972
1973 // //////////////////////////////////////////////////////////////////////
1974 // End of content of file: include/json/assertions.h
1975 // //////////////////////////////////////////////////////////////////////
1976
1977
1978
1979
1980
1981 #endif //ifndef JSON_AMALGATED_H_INCLUDED