Debian Codegraph @

include/json/reader.h

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