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.

417 lines
14 KiB

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