You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

414 lines
13 KiB

7 years ago
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
7 years ago
​
​
  1. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  2. // Distributed under MIT license, or public domain if desired and
  3. // recognized in your jurisdiction.
  4. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  5. #ifndef CPPTL_JSON_READER_H_INCLUDED
  6. #define CPPTL_JSON_READER_H_INCLUDED
  7. #if ! defined(JSON_IS_AMALGAMATION)
  8. #include "features.h"
  9. #include "value.h"
  10. #endif // if !defined(JSON_IS_AMALGAMATION)
  11. #include <deque>
  12. #include <iosfwd>
  13. #include <istream>
  14. #include <stack>
  15. #include <string>
  16. // Disable warning C4251: <data member>: <type> needs to have dll-interface to
  17. // be used by...
  18. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  19. #pragma warning(push)
  20. #pragma warning(disable : 4251)
  21. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  22. #pragma pack(push, 8)
  23. namespace Json
  24. {
  25. /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
  26. *Value.
  27. *
  28. * \deprecated Use CharReader and CharReaderBuilder.
  29. */
  30. class JSON_API Reader
  31. {
  32. public:
  33. typedef char Char;
  34. typedef const Char * Location;
  35. /** \brief An error tagged with where in the JSON text it was encountered.
  36. *
  37. * The offsets give the [start, limit) range of bytes within the text. Note
  38. * that this is bytes, not codepoints.
  39. *
  40. */
  41. struct StructuredError
  42. {
  43. ptrdiff_t offset_start;
  44. ptrdiff_t offset_limit;
  45. String message;
  46. };
  47. /** \brief Constructs a Reader allowing all features
  48. * for parsing.
  49. */
  50. JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead")
  51. Reader();
  52. /** \brief Constructs a Reader allowing the specified feature set
  53. * for parsing.
  54. */
  55. JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead")
  56. Reader(const Features & features);
  57. /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
  58. * document.
  59. * \param document UTF-8 encoded string containing the document to read.
  60. * \param root [out] Contains the root value of the document if it was
  61. * successfully parsed.
  62. * \param collectComments \c true to collect comment and allow writing them
  63. * back during
  64. * serialization, \c false to discard comments.
  65. * This parameter is ignored if
  66. * Features::allowComments_
  67. * is \c false.
  68. * \return \c true if the document was successfully parsed, \c false if an
  69. * error occurred.
  70. */
  71. bool parse(const std::string & document, Value & root, bool collectComments = true);
  72. /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
  73. document.
  74. * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
  75. document to read.
  76. * \param endDoc Pointer on the end of the UTF-8 encoded string of the
  77. document to read.
  78. * Must be >= beginDoc.
  79. * \param root [out] Contains the root value of the document if it was
  80. * successfully parsed.
  81. * \param collectComments \c true to collect comment and allow writing them
  82. back during
  83. * serialization, \c false to discard comments.
  84. * This parameter is ignored if
  85. Features::allowComments_
  86. * is \c false.
  87. * \return \c true if the document was successfully parsed, \c false if an
  88. error occurred.
  89. */
  90. bool parse(const char * beginDoc, const char * endDoc, Value & root, bool collectComments = true);
  91. /// \brief Parse from input stream.
  92. /// \see Json::operator>>(std::istream&, Json::Value&).
  93. bool parse(IStream & is, Value & root, bool collectComments = true);
  94. /** \brief Returns a user friendly string that list errors in the parsed
  95. * document.
  96. * \return Formatted error message with the list of errors with their location
  97. * in
  98. * the parsed document. An empty string is returned if no error
  99. * occurred
  100. * during parsing.
  101. * \deprecated Use getFormattedErrorMessages() instead (typo fix).
  102. */
  103. JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
  104. String getFormatedErrorMessages() const;
  105. /** \brief Returns a user friendly string that list errors in the parsed
  106. * document.
  107. * \return Formatted error message with the list of errors with their location
  108. * in
  109. * the parsed document. An empty string is returned if no error
  110. * occurred
  111. * during parsing.
  112. */
  113. String getFormattedErrorMessages() const;
  114. /** \brief Returns a vector of structured erros encounted while parsing.
  115. * \return A (possibly empty) vector of StructuredError objects. Currently
  116. * only one error can be returned, but the caller should tolerate
  117. * multiple
  118. * errors. This can occur if the parser recovers from a non-fatal
  119. * parse error and then encounters additional errors.
  120. */
  121. std::vector<StructuredError> getStructuredErrors() const;
  122. /** \brief Add a semantic error message.
  123. * \param value JSON Value location associated with the error
  124. * \param message The error message.
  125. * \return \c true if the error was successfully added, \c false if the
  126. * Value offset exceeds the document size.
  127. */
  128. bool pushError(const Value & value, const String & message);
  129. /** \brief Add a semantic error message with extra context.
  130. * \param value JSON Value location associated with the error
  131. * \param message The error message.
  132. * \param extra Additional JSON Value location to contextualize the error
  133. * \return \c true if the error was successfully added, \c false if either
  134. * Value offset exceeds the document size.
  135. */
  136. bool pushError(const Value & value, const String & message, const Value & extra);
  137. /** \brief Return whether there are any errors.
  138. * \return \c true if there are no errors to report \c false if
  139. * errors have occurred.
  140. */
  141. bool good() const;
  142. private:
  143. enum TokenType
  144. {
  145. tokenEndOfStream = 0,
  146. tokenObjectBegin,
  147. tokenObjectEnd,
  148. tokenArrayBegin,
  149. tokenArrayEnd,
  150. tokenString,
  151. tokenNumber,
  152. tokenTrue,
  153. tokenFalse,
  154. tokenNull,
  155. tokenArraySeparator,
  156. tokenMemberSeparator,
  157. tokenComment,
  158. tokenError
  159. };
  160. class Token
  161. {
  162. public:
  163. TokenType type_;
  164. Location start_;
  165. Location end_;
  166. };
  167. class ErrorInfo
  168. {
  169. public:
  170. Token token_;
  171. String message_;
  172. Location extra_;
  173. };
  174. typedef std::deque<ErrorInfo> Errors;
  175. bool readToken(Token & token);
  176. void skipSpaces();
  177. bool match(Location pattern, int patternLength);
  178. bool readComment();
  179. bool readCStyleComment();
  180. bool readCppStyleComment();
  181. bool readString();
  182. void readNumber();
  183. bool readValue();
  184. bool readObject(Token & token);
  185. bool readArray(Token & token);
  186. bool decodeNumber(Token & token);
  187. bool decodeNumber(Token & token, Value & decoded);
  188. bool decodeString(Token & token);
  189. bool decodeString(Token & token, String & decoded);
  190. bool decodeDouble(Token & token);
  191. bool decodeDouble(Token & token, Value & decoded);
  192. bool decodeUnicodeCodePoint(Token & token, Location & current, Location end, unsigned int & unicode);
  193. bool decodeUnicodeEscapeSequence(Token & token, Location & current, Location end, unsigned int & unicode);
  194. bool addError(const String & message, Token & token, Location extra = nullptr);
  195. bool recoverFromError(TokenType skipUntilToken);
  196. bool addErrorAndRecover(const String & message, Token & token, TokenType skipUntilToken);
  197. void skipUntilSpace();
  198. Value & currentValue();
  199. Char getNextChar();
  200. void getLocationLineAndColumn(Location location, int & line, int & column) const;
  201. String getLocationLineAndColumn(Location location) const;
  202. void addComment(Location begin, Location end, CommentPlacement placement);
  203. void skipCommentTokens(Token & token);
  204. static bool containsNewLine(Location begin, Location end);
  205. static String normalizeEOL(Location begin, Location end);
  206. typedef std::stack<Value *> Nodes;
  207. Nodes nodes_;
  208. Errors errors_;
  209. String document_;
  210. Location begin_{};
  211. Location end_{};
  212. Location current_{};
  213. Location lastValueEnd_{};
  214. Value * lastValue_{};
  215. String commentsBefore_;
  216. Features features_;
  217. bool collectComments_{};
  218. }; // Reader
  219. /** Interface for reading JSON from a char array.
  220. */
  221. class JSON_API CharReader
  222. {
  223. public:
  224. virtual ~CharReader() = default;
  225. /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
  226. document.
  227. * The document must be a UTF-8 encoded string containing the document to
  228. read.
  229. *
  230. * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
  231. document to read.
  232. * \param endDoc Pointer on the end of the UTF-8 encoded string of the
  233. document to read.
  234. * Must be >= beginDoc.
  235. * \param root [out] Contains the root value of the document if it was
  236. * successfully parsed.
  237. * \param errs [out] Formatted error messages (if not NULL)
  238. * a user friendly string that lists errors in the parsed
  239. * document.
  240. * \return \c true if the document was successfully parsed, \c false if an
  241. error occurred.
  242. */
  243. virtual bool parse(const char * beginDoc, const char * endDoc, Value * root, String * errs) = 0;
  244. class JSON_API Factory
  245. {
  246. public:
  247. virtual ~Factory() = default;
  248. /** \brief Allocate a CharReader via operator new().
  249. * \throw std::exception if something goes wrong (e.g. invalid settings)
  250. */
  251. virtual CharReader * newCharReader() const = 0;
  252. }; // Factory
  253. }; // CharReader
  254. /** \brief Build a CharReader implementation.
  255. Usage:
  256. \code
  257. using namespace Json;
  258. CharReaderBuilder builder;
  259. builder["collectComments"] = false;
  260. Value value;
  261. String errs;
  262. bool ok = parseFromStream(builder, std::cin, &value, &errs);
  263. \endcode
  264. */
  265. class JSON_API CharReaderBuilder : public CharReader::Factory
  266. {
  267. public:
  268. // Note: We use a Json::Value so that we can add data-members to this class
  269. // without a major version bump.
  270. /** Configuration of this builder.
  271. These are case-sensitive.
  272. Available settings (case-sensitive):
  273. - `"collectComments": false or true`
  274. - true to collect comment and allow writing them
  275. back during serialization, false to discard comments.
  276. This parameter is ignored if allowComments is false.
  277. - `"allowComments": false or true`
  278. - true if comments are allowed.
  279. - `"strictRoot": false or true`
  280. - true if root must be either an array or an object value
  281. - `"allowDroppedNullPlaceholders": false or true`
  282. - true if dropped null placeholders are allowed. (See
  283. StreamWriterBuilder.)
  284. - `"allowNumericKeys": false or true`
  285. - true if numeric object keys are allowed.
  286. - `"allowSingleQuotes": false or true`
  287. - true if '' are allowed for strings (both keys and values)
  288. - `"stackLimit": integer`
  289. - Exceeding stackLimit (recursive depth of `readValue()`) will
  290. cause an exception.
  291. - This is a security issue (seg-faults caused by deeply nested JSON),
  292. so the default is low.
  293. - `"failIfExtra": false or true`
  294. - If true, `parse()` returns false when extra non-whitespace trails
  295. the JSON value in the input string.
  296. - `"rejectDupKeys": false or true`
  297. - If true, `parse()` returns false when a key is duplicated within an
  298. object.
  299. - `"allowSpecialFloats": false or true`
  300. - If true, special float values (NaNs and infinities) are allowed
  301. and their values are lossfree restorable.
  302. You can examine 'settings_` yourself
  303. to see the defaults. You can also write and read them just like any
  304. JSON Value.
  305. \sa setDefaults()
  306. */
  307. Json::Value settings_;
  308. CharReaderBuilder();
  309. ~CharReaderBuilder() override;
  310. CharReader * newCharReader() const override;
  311. /** \return true if 'settings' are legal and consistent;
  312. * otherwise, indicate bad settings via 'invalid'.
  313. */
  314. bool validate(Json::Value * invalid) const;
  315. /** A simple way to update a specific setting.
  316. */
  317. Value & operator[](const String & key);
  318. /** Called by ctor, but you can use this to reset settings_.
  319. * \pre 'settings' != NULL (but Json::null is fine)
  320. * \remark Defaults:
  321. * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
  322. */
  323. static void setDefaults(Json::Value * settings);
  324. /** Same as old Features::strictMode().
  325. * \pre 'settings' != NULL (but Json::null is fine)
  326. * \remark Defaults:
  327. * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
  328. */
  329. static void strictMode(Json::Value * settings);
  330. };
  331. /** Consume entire stream and use its begin/end.
  332. * Someday we might have a real StreamReader, but for now this
  333. * is convenient.
  334. */
  335. bool JSON_API parseFromStream(const CharReader::Factory &, IStream &, Value * root, std::string * errs);
  336. /** \brief Read from 'sin' into 'root'.
  337. Always keep comments from the input JSON.
  338. This can be used to read a file into a particular sub-object.
  339. For example:
  340. \code
  341. Json::Value root;
  342. cin >> root["dir"]["file"];
  343. cout << root;
  344. \endcode
  345. Result:
  346. \verbatim
  347. {
  348. "dir": {
  349. "file": {
  350. // The input stream JSON would be nested here.
  351. }
  352. }
  353. }
  354. \endverbatim
  355. \throw std::exception on parse error.
  356. \see Json::operator<<()
  357. */
  358. JSON_API IStream & operator>>(IStream &, Value &);
  359. } // namespace Json
  360. #pragma pack(pop)
  361. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  362. #pragma warning(pop)
  363. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  364. #endif // CPPTL_JSON_READER_H_INCLUDED