reader.h 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452
  1. // Tencent is pleased to support the open source community by making RapidJSON available.
  2. //
  3. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
  4. //
  5. // Licensed under the MIT License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifndef RAPIDJSON_READER_H_
  15. #define RAPIDJSON_READER_H_
  16. /*! \file reader.h */
  17. #include "rapidjson.h"
  18. #include "encodings.h"
  19. #include "internal/meta.h"
  20. #include "internal/stack.h"
  21. #include "internal/strtod.h"
  22. #if defined(RAPIDJSON_SIMD) && defined(_MSC_VER)
  23. #include <intrin.h>
  24. #pragma intrinsic(_BitScanForward)
  25. #endif
  26. #ifdef RAPIDJSON_SSE42
  27. #include <nmmintrin.h>
  28. #elif defined(RAPIDJSON_SSE2)
  29. #include <emmintrin.h>
  30. #endif
  31. #ifdef _MSC_VER
  32. RAPIDJSON_DIAG_PUSH
  33. RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
  34. RAPIDJSON_DIAG_OFF(4702) // unreachable code
  35. #endif
  36. #ifdef __GNUC__
  37. RAPIDJSON_DIAG_PUSH
  38. RAPIDJSON_DIAG_OFF(effc++)
  39. #endif
  40. //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
  41. #define RAPIDJSON_NOTHING /* deliberately empty */
  42. #ifndef RAPIDJSON_PARSE_ERROR_EARLY_RETURN
  43. #define RAPIDJSON_PARSE_ERROR_EARLY_RETURN(value) \
  44. RAPIDJSON_MULTILINEMACRO_BEGIN \
  45. if (HasParseError()) { return value; } \
  46. RAPIDJSON_MULTILINEMACRO_END
  47. #endif
  48. #define RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID \
  49. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(RAPIDJSON_NOTHING)
  50. //!@endcond
  51. /*! \def RAPIDJSON_PARSE_ERROR_NORETURN
  52. \ingroup RAPIDJSON_ERRORS
  53. \brief Macro to indicate a parse error.
  54. \param parseErrorCode \ref rapidjson::ParseErrorCode of the error
  55. \param offset position of the error in JSON input (\c size_t)
  56. This macros can be used as a customization point for the internal
  57. error handling mechanism of RapidJSON.
  58. A common usage model is to throw an exception instead of requiring the
  59. caller to explicitly check the \ref rapidjson::GenericReader::Parse's
  60. return value:
  61. \code
  62. #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode,offset) \
  63. throw ParseException(parseErrorCode, #parseErrorCode, offset)
  64. #include <stdexcept> // std::runtime_error
  65. #include "rapidjson/error/error.h" // rapidjson::ParseResult
  66. struct ParseException : std::runtime_error, rapidjson::ParseResult {
  67. ParseException(rapidjson::ParseErrorCode code, const char* msg, size_t offset)
  68. : std::runtime_error(msg), ParseResult(code, offset) {}
  69. };
  70. #include "rapidjson/reader.h"
  71. \endcode
  72. \see RAPIDJSON_PARSE_ERROR, rapidjson::GenericReader::Parse
  73. */
  74. #ifndef RAPIDJSON_PARSE_ERROR_NORETURN
  75. #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) \
  76. RAPIDJSON_MULTILINEMACRO_BEGIN \
  77. RAPIDJSON_ASSERT(!HasParseError()); /* Error can only be assigned once */ \
  78. SetParseError(parseErrorCode, offset); \
  79. RAPIDJSON_MULTILINEMACRO_END
  80. #endif
  81. /*! \def RAPIDJSON_PARSE_ERROR
  82. \ingroup RAPIDJSON_ERRORS
  83. \brief (Internal) macro to indicate and handle a parse error.
  84. \param parseErrorCode \ref rapidjson::ParseErrorCode of the error
  85. \param offset position of the error in JSON input (\c size_t)
  86. Invokes RAPIDJSON_PARSE_ERROR_NORETURN and stops the parsing.
  87. \see RAPIDJSON_PARSE_ERROR_NORETURN
  88. \hideinitializer
  89. */
  90. #ifndef RAPIDJSON_PARSE_ERROR
  91. #define RAPIDJSON_PARSE_ERROR(parseErrorCode, offset) \
  92. RAPIDJSON_MULTILINEMACRO_BEGIN \
  93. RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset); \
  94. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; \
  95. RAPIDJSON_MULTILINEMACRO_END
  96. #endif
  97. #include "error/error.h" // ParseErrorCode, ParseResult
  98. RAPIDJSON_NAMESPACE_BEGIN
  99. ///////////////////////////////////////////////////////////////////////////////
  100. // ParseFlag
  101. /*! \def RAPIDJSON_PARSE_DEFAULT_FLAGS
  102. \ingroup RAPIDJSON_CONFIG
  103. \brief User-defined kParseDefaultFlags definition.
  104. User can define this as any \c ParseFlag combinations.
  105. */
  106. #ifndef RAPIDJSON_PARSE_DEFAULT_FLAGS
  107. #define RAPIDJSON_PARSE_DEFAULT_FLAGS kParseNoFlags
  108. #endif
  109. //! Combination of parseFlags
  110. /*! \see Reader::Parse, Document::Parse, Document::ParseInsitu, Document::ParseStream
  111. */
  112. enum ParseFlag {
  113. kParseNoFlags = 0, //!< No flags are set.
  114. kParseInsituFlag = 1, //!< In-situ(destructive) parsing.
  115. kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings.
  116. kParseIterativeFlag = 4, //!< Iterative(constant complexity in terms of function call stack size) parsing.
  117. kParseStopWhenDoneFlag = 8, //!< After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate kParseErrorDocumentRootNotSingular error.
  118. kParseFullPrecisionFlag = 16, //!< Parse number in full precision (but slower).
  119. kParseDefaultFlags = RAPIDJSON_PARSE_DEFAULT_FLAGS //!< Default parse flags. Can be customized by defining RAPIDJSON_PARSE_DEFAULT_FLAGS
  120. };
  121. ///////////////////////////////////////////////////////////////////////////////
  122. // Handler
  123. /*! \class rapidjson::Handler
  124. \brief Concept for receiving events from GenericReader upon parsing.
  125. The functions return true if no error occurs. If they return false,
  126. the event publisher should terminate the process.
  127. \code
  128. concept Handler {
  129. typename Ch;
  130. bool Null();
  131. bool Bool(bool b);
  132. bool Int(int i);
  133. bool Uint(unsigned i);
  134. bool Int64(int64_t i);
  135. bool Uint64(uint64_t i);
  136. bool Double(double d);
  137. bool String(const Ch* str, SizeType length, bool copy);
  138. bool StartObject();
  139. bool Key(const Ch* str, SizeType length, bool copy);
  140. bool EndObject(SizeType memberCount);
  141. bool StartArray();
  142. bool EndArray(SizeType elementCount);
  143. };
  144. \endcode
  145. */
  146. ///////////////////////////////////////////////////////////////////////////////
  147. // BaseReaderHandler
  148. //! Default implementation of Handler.
  149. /*! This can be used as base class of any reader handler.
  150. \note implements Handler concept
  151. */
  152. template<typename Encoding = UTF8<>, typename Derived = void>
  153. struct BaseReaderHandler {
  154. typedef typename Encoding::Ch Ch;
  155. typedef typename internal::SelectIf<internal::IsSame<Derived, void>, BaseReaderHandler, Derived>::Type Override;
  156. bool Default() { return true; }
  157. bool Null() { return static_cast<Override&>(*this).Default(); }
  158. bool Bool(bool) { return static_cast<Override&>(*this).Default(); }
  159. bool Int(int) { return static_cast<Override&>(*this).Default(); }
  160. bool Uint(unsigned) { return static_cast<Override&>(*this).Default(); }
  161. bool Int64(int64_t) { return static_cast<Override&>(*this).Default(); }
  162. bool Uint64(uint64_t) { return static_cast<Override&>(*this).Default(); }
  163. bool Double(double) { return static_cast<Override&>(*this).Default(); }
  164. bool String(const Ch*, SizeType, bool) { return static_cast<Override&>(*this).Default(); }
  165. bool StartObject() { return static_cast<Override&>(*this).Default(); }
  166. bool Key(const Ch* str, SizeType len, bool copy) { return static_cast<Override&>(*this).String(str, len, copy); }
  167. bool EndObject(SizeType) { return static_cast<Override&>(*this).Default(); }
  168. bool StartArray() { return static_cast<Override&>(*this).Default(); }
  169. bool EndArray(SizeType) { return static_cast<Override&>(*this).Default(); }
  170. };
  171. ///////////////////////////////////////////////////////////////////////////////
  172. // StreamLocalCopy
  173. namespace internal {
  174. template<typename Stream, int = StreamTraits<Stream>::copyOptimization>
  175. class StreamLocalCopy;
  176. //! Do copy optimization.
  177. template<typename Stream>
  178. class StreamLocalCopy<Stream, 1> {
  179. public:
  180. StreamLocalCopy(Stream& original) : s(original), original_(original) {}
  181. ~StreamLocalCopy() { original_ = s; }
  182. Stream s;
  183. private:
  184. StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */;
  185. Stream& original_;
  186. };
  187. //! Keep reference.
  188. template<typename Stream>
  189. class StreamLocalCopy<Stream, 0> {
  190. public:
  191. StreamLocalCopy(Stream& original) : s(original) {}
  192. Stream& s;
  193. private:
  194. StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */;
  195. };
  196. } // namespace internal
  197. ///////////////////////////////////////////////////////////////////////////////
  198. // SkipWhitespace
  199. //! Skip the JSON white spaces in a stream.
  200. /*! \param is A input stream for skipping white spaces.
  201. \note This function has SSE2/SSE4.2 specialization.
  202. */
  203. template<typename InputStream>
  204. void SkipWhitespace(InputStream& is) {
  205. internal::StreamLocalCopy<InputStream> copy(is);
  206. InputStream& s(copy.s);
  207. while (s.Peek() == ' ' || s.Peek() == '\n' || s.Peek() == '\r' || s.Peek() == '\t')
  208. s.Take();
  209. }
  210. #ifdef RAPIDJSON_SSE42
  211. //! Skip whitespace with SSE 4.2 pcmpistrm instruction, testing 16 8-byte characters at once.
  212. inline const char *SkipWhitespace_SIMD(const char* p) {
  213. // Fast return for single non-whitespace
  214. if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
  215. ++p;
  216. else
  217. return p;
  218. // 16-byte align to the next boundary
  219. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & ~15);
  220. while (p != nextAligned)
  221. if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
  222. ++p;
  223. else
  224. return p;
  225. // The rest of string using SIMD
  226. static const char whitespace[16] = " \n\r\t";
  227. const __m128i w = _mm_load_si128((const __m128i *)&whitespace[0]);
  228. for (;; p += 16) {
  229. const __m128i s = _mm_load_si128((const __m128i *)p);
  230. const unsigned r = _mm_cvtsi128_si32(_mm_cmpistrm(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK | _SIDD_NEGATIVE_POLARITY));
  231. if (r != 0) { // some of characters is non-whitespace
  232. #ifdef _MSC_VER // Find the index of first non-whitespace
  233. unsigned long offset;
  234. _BitScanForward(&offset, r);
  235. return p + offset;
  236. #else
  237. return p + __builtin_ffs(r) - 1;
  238. #endif
  239. }
  240. }
  241. }
  242. #elif defined(RAPIDJSON_SSE2)
  243. //! Skip whitespace with SSE2 instructions, testing 16 8-byte characters at once.
  244. inline const char *SkipWhitespace_SIMD(const char* p) {
  245. // Fast return for single non-whitespace
  246. if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
  247. ++p;
  248. else
  249. return p;
  250. // 16-byte align to the next boundary
  251. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & ~15);
  252. while (p != nextAligned)
  253. if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
  254. ++p;
  255. else
  256. return p;
  257. // The rest of string
  258. static const char whitespaces[4][17] = {
  259. " ",
  260. "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
  261. "\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r",
  262. "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"};
  263. const __m128i w0 = _mm_loadu_si128((const __m128i *)&whitespaces[0][0]);
  264. const __m128i w1 = _mm_loadu_si128((const __m128i *)&whitespaces[1][0]);
  265. const __m128i w2 = _mm_loadu_si128((const __m128i *)&whitespaces[2][0]);
  266. const __m128i w3 = _mm_loadu_si128((const __m128i *)&whitespaces[3][0]);
  267. for (;; p += 16) {
  268. const __m128i s = _mm_load_si128((const __m128i *)p);
  269. __m128i x = _mm_cmpeq_epi8(s, w0);
  270. x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1));
  271. x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2));
  272. x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3));
  273. unsigned short r = (unsigned short)~_mm_movemask_epi8(x);
  274. if (r != 0) { // some of characters may be non-whitespace
  275. #ifdef _MSC_VER // Find the index of first non-whitespace
  276. unsigned long offset;
  277. _BitScanForward(&offset, r);
  278. return p + offset;
  279. #else
  280. return p + __builtin_ffs(r) - 1;
  281. #endif
  282. }
  283. }
  284. }
  285. #endif // RAPIDJSON_SSE2
  286. #ifdef RAPIDJSON_SIMD
  287. //! Template function specialization for InsituStringStream
  288. template<> inline void SkipWhitespace(InsituStringStream& is) {
  289. is.src_ = const_cast<char*>(SkipWhitespace_SIMD(is.src_));
  290. }
  291. //! Template function specialization for StringStream
  292. template<> inline void SkipWhitespace(StringStream& is) {
  293. is.src_ = SkipWhitespace_SIMD(is.src_);
  294. }
  295. #endif // RAPIDJSON_SIMD
  296. ///////////////////////////////////////////////////////////////////////////////
  297. // GenericReader
  298. //! SAX-style JSON parser. Use \ref Reader for UTF8 encoding and default allocator.
  299. /*! GenericReader parses JSON text from a stream, and send events synchronously to an
  300. object implementing Handler concept.
  301. It needs to allocate a stack for storing a single decoded string during
  302. non-destructive parsing.
  303. For in-situ parsing, the decoded string is directly written to the source
  304. text string, no temporary buffer is required.
  305. A GenericReader object can be reused for parsing multiple JSON text.
  306. \tparam SourceEncoding Encoding of the input stream.
  307. \tparam TargetEncoding Encoding of the parse output.
  308. \tparam StackAllocator Allocator type for stack.
  309. */
  310. template <typename SourceEncoding, typename TargetEncoding, typename StackAllocator = CrtAllocator>
  311. class GenericReader {
  312. public:
  313. typedef typename SourceEncoding::Ch Ch; //!< SourceEncoding character type
  314. //! Constructor.
  315. /*! \param stackAllocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing)
  316. \param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing)
  317. */
  318. GenericReader(StackAllocator* stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(stackAllocator, stackCapacity), parseResult_() {}
  319. //! Parse JSON text.
  320. /*! \tparam parseFlags Combination of \ref ParseFlag.
  321. \tparam InputStream Type of input stream, implementing Stream concept.
  322. \tparam Handler Type of handler, implementing Handler concept.
  323. \param is Input stream to be parsed.
  324. \param handler The handler to receive events.
  325. \return Whether the parsing is successful.
  326. */
  327. template <unsigned parseFlags, typename InputStream, typename Handler>
  328. ParseResult Parse(InputStream& is, Handler& handler) {
  329. if (parseFlags & kParseIterativeFlag)
  330. return IterativeParse<parseFlags>(is, handler);
  331. parseResult_.Clear();
  332. ClearStackOnExit scope(*this);
  333. SkipWhitespace(is);
  334. if (is.Peek() == '\0') {
  335. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentEmpty, is.Tell());
  336. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
  337. }
  338. else {
  339. ParseValue<parseFlags>(is, handler);
  340. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
  341. if (!(parseFlags & kParseStopWhenDoneFlag)) {
  342. SkipWhitespace(is);
  343. if (is.Peek() != '\0') {
  344. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentRootNotSingular, is.Tell());
  345. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
  346. }
  347. }
  348. }
  349. return parseResult_;
  350. }
  351. //! Parse JSON text (with \ref kParseDefaultFlags)
  352. /*! \tparam InputStream Type of input stream, implementing Stream concept
  353. \tparam Handler Type of handler, implementing Handler concept.
  354. \param is Input stream to be parsed.
  355. \param handler The handler to receive events.
  356. \return Whether the parsing is successful.
  357. */
  358. template <typename InputStream, typename Handler>
  359. ParseResult Parse(InputStream& is, Handler& handler) {
  360. return Parse<kParseDefaultFlags>(is, handler);
  361. }
  362. //! Whether a parse error has occured in the last parsing.
  363. bool HasParseError() const { return parseResult_.IsError(); }
  364. //! Get the \ref ParseErrorCode of last parsing.
  365. ParseErrorCode GetParseErrorCode() const { return parseResult_.Code(); }
  366. //! Get the position of last parsing error in input, 0 otherwise.
  367. size_t GetErrorOffset() const { return parseResult_.Offset(); }
  368. protected:
  369. void SetParseError(ParseErrorCode code, size_t offset) { parseResult_.Set(code, offset); }
  370. private:
  371. // Prohibit copy constructor & assignment operator.
  372. GenericReader(const GenericReader&);
  373. GenericReader& operator=(const GenericReader&);
  374. void ClearStack() { stack_.Clear(); }
  375. // clear stack on any exit from ParseStream, e.g. due to exception
  376. struct ClearStackOnExit {
  377. explicit ClearStackOnExit(GenericReader& r) : r_(r) {}
  378. ~ClearStackOnExit() { r_.ClearStack(); }
  379. private:
  380. GenericReader& r_;
  381. ClearStackOnExit(const ClearStackOnExit&);
  382. ClearStackOnExit& operator=(const ClearStackOnExit&);
  383. };
  384. // Parse object: { string : value, ... }
  385. template<unsigned parseFlags, typename InputStream, typename Handler>
  386. void ParseObject(InputStream& is, Handler& handler) {
  387. RAPIDJSON_ASSERT(is.Peek() == '{');
  388. is.Take(); // Skip '{'
  389. if (!handler.StartObject())
  390. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  391. SkipWhitespace(is);
  392. if (is.Peek() == '}') {
  393. is.Take();
  394. if (!handler.EndObject(0)) // empty object
  395. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  396. return;
  397. }
  398. for (SizeType memberCount = 0;;) {
  399. if (is.Peek() != '"')
  400. RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell());
  401. ParseString<parseFlags>(is, handler, true);
  402. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  403. SkipWhitespace(is);
  404. if (is.Take() != ':')
  405. RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell());
  406. SkipWhitespace(is);
  407. ParseValue<parseFlags>(is, handler);
  408. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  409. SkipWhitespace(is);
  410. ++memberCount;
  411. switch (is.Take()) {
  412. case ',': SkipWhitespace(is); break;
  413. case '}':
  414. if (!handler.EndObject(memberCount))
  415. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  416. return;
  417. default: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell());
  418. }
  419. }
  420. }
  421. // Parse array: [ value, ... ]
  422. template<unsigned parseFlags, typename InputStream, typename Handler>
  423. void ParseArray(InputStream& is, Handler& handler) {
  424. RAPIDJSON_ASSERT(is.Peek() == '[');
  425. is.Take(); // Skip '['
  426. if (!handler.StartArray())
  427. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  428. SkipWhitespace(is);
  429. if (is.Peek() == ']') {
  430. is.Take();
  431. if (!handler.EndArray(0)) // empty array
  432. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  433. return;
  434. }
  435. for (SizeType elementCount = 0;;) {
  436. ParseValue<parseFlags>(is, handler);
  437. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  438. ++elementCount;
  439. SkipWhitespace(is);
  440. switch (is.Take()) {
  441. case ',': SkipWhitespace(is); break;
  442. case ']':
  443. if (!handler.EndArray(elementCount))
  444. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  445. return;
  446. default: RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell());
  447. }
  448. }
  449. }
  450. template<unsigned parseFlags, typename InputStream, typename Handler>
  451. void ParseNull(InputStream& is, Handler& handler) {
  452. RAPIDJSON_ASSERT(is.Peek() == 'n');
  453. is.Take();
  454. if (is.Take() == 'u' && is.Take() == 'l' && is.Take() == 'l') {
  455. if (!handler.Null())
  456. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  457. }
  458. else
  459. RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell() - 1);
  460. }
  461. template<unsigned parseFlags, typename InputStream, typename Handler>
  462. void ParseTrue(InputStream& is, Handler& handler) {
  463. RAPIDJSON_ASSERT(is.Peek() == 't');
  464. is.Take();
  465. if (is.Take() == 'r' && is.Take() == 'u' && is.Take() == 'e') {
  466. if (!handler.Bool(true))
  467. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  468. }
  469. else
  470. RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell() - 1);
  471. }
  472. template<unsigned parseFlags, typename InputStream, typename Handler>
  473. void ParseFalse(InputStream& is, Handler& handler) {
  474. RAPIDJSON_ASSERT(is.Peek() == 'f');
  475. is.Take();
  476. if (is.Take() == 'a' && is.Take() == 'l' && is.Take() == 's' && is.Take() == 'e') {
  477. if (!handler.Bool(false))
  478. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  479. }
  480. else
  481. RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell() - 1);
  482. }
  483. // Helper function to parse four hexidecimal digits in \uXXXX in ParseString().
  484. template<typename InputStream>
  485. unsigned ParseHex4(InputStream& is) {
  486. unsigned codepoint = 0;
  487. for (int i = 0; i < 4; i++) {
  488. Ch c = is.Take();
  489. codepoint <<= 4;
  490. codepoint += static_cast<unsigned>(c);
  491. if (c >= '0' && c <= '9')
  492. codepoint -= '0';
  493. else if (c >= 'A' && c <= 'F')
  494. codepoint -= 'A' - 10;
  495. else if (c >= 'a' && c <= 'f')
  496. codepoint -= 'a' - 10;
  497. else {
  498. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorStringUnicodeEscapeInvalidHex, is.Tell() - 1);
  499. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(0);
  500. }
  501. }
  502. return codepoint;
  503. }
  504. template <typename CharType>
  505. class StackStream {
  506. public:
  507. typedef CharType Ch;
  508. StackStream(internal::Stack<StackAllocator>& stack) : stack_(stack), length_(0) {}
  509. RAPIDJSON_FORCEINLINE void Put(Ch c) {
  510. *stack_.template Push<Ch>() = c;
  511. ++length_;
  512. }
  513. size_t Length() const { return length_; }
  514. Ch* Pop() {
  515. return stack_.template Pop<Ch>(length_);
  516. }
  517. private:
  518. StackStream(const StackStream&);
  519. StackStream& operator=(const StackStream&);
  520. internal::Stack<StackAllocator>& stack_;
  521. SizeType length_;
  522. };
  523. // Parse string and generate String event. Different code paths for kParseInsituFlag.
  524. template<unsigned parseFlags, typename InputStream, typename Handler>
  525. void ParseString(InputStream& is, Handler& handler, bool isKey = false) {
  526. internal::StreamLocalCopy<InputStream> copy(is);
  527. InputStream& s(copy.s);
  528. bool success = false;
  529. if (parseFlags & kParseInsituFlag) {
  530. typename InputStream::Ch *head = s.PutBegin();
  531. ParseStringToStream<parseFlags, SourceEncoding, SourceEncoding>(s, s);
  532. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  533. size_t length = s.PutEnd(head) - 1;
  534. RAPIDJSON_ASSERT(length <= 0xFFFFFFFF);
  535. const typename TargetEncoding::Ch* const str = (typename TargetEncoding::Ch*)head;
  536. success = (isKey ? handler.Key(str, SizeType(length), false) : handler.String(str, SizeType(length), false));
  537. }
  538. else {
  539. StackStream<typename TargetEncoding::Ch> stackStream(stack_);
  540. ParseStringToStream<parseFlags, SourceEncoding, TargetEncoding>(s, stackStream);
  541. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  542. SizeType length = static_cast<SizeType>(stackStream.Length()) - 1;
  543. const typename TargetEncoding::Ch* const str = stackStream.Pop();
  544. success = (isKey ? handler.Key(str, length, true) : handler.String(str, length, true));
  545. }
  546. if (!success)
  547. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, s.Tell());
  548. }
  549. // Parse string to an output is
  550. // This function handles the prefix/suffix double quotes, escaping, and optional encoding validation.
  551. template<unsigned parseFlags, typename SEncoding, typename TEncoding, typename InputStream, typename OutputStream>
  552. RAPIDJSON_FORCEINLINE void ParseStringToStream(InputStream& is, OutputStream& os) {
  553. //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
  554. #define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
  555. static const char escape[256] = {
  556. Z16, Z16, 0, 0,'\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'/',
  557. Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0,
  558. 0, 0,'\b', 0, 0, 0,'\f', 0, 0, 0, 0, 0, 0, 0,'\n', 0,
  559. 0, 0,'\r', 0,'\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  560. Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16
  561. };
  562. #undef Z16
  563. //!@endcond
  564. RAPIDJSON_ASSERT(is.Peek() == '\"');
  565. is.Take(); // Skip '\"'
  566. for (;;) {
  567. Ch c = is.Peek();
  568. if (c == '\\') { // Escape
  569. is.Take();
  570. Ch e = is.Take();
  571. if ((sizeof(Ch) == 1 || unsigned(e) < 256) && escape[(unsigned char)e]) {
  572. os.Put(escape[(unsigned char)e]);
  573. }
  574. else if (e == 'u') { // Unicode
  575. unsigned codepoint = ParseHex4(is);
  576. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  577. if (codepoint >= 0xD800 && codepoint <= 0xDBFF) {
  578. // Handle UTF-16 surrogate pair
  579. if (is.Take() != '\\' || is.Take() != 'u')
  580. RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, is.Tell() - 2);
  581. unsigned codepoint2 = ParseHex4(is);
  582. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  583. if (codepoint2 < 0xDC00 || codepoint2 > 0xDFFF)
  584. RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, is.Tell() - 2);
  585. codepoint = (((codepoint - 0xD800) << 10) | (codepoint2 - 0xDC00)) + 0x10000;
  586. }
  587. TEncoding::Encode(os, codepoint);
  588. }
  589. else
  590. RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, is.Tell() - 1);
  591. }
  592. else if (c == '"') { // Closing double quote
  593. is.Take();
  594. os.Put('\0'); // null-terminate the string
  595. return;
  596. }
  597. else if (c == '\0')
  598. RAPIDJSON_PARSE_ERROR(kParseErrorStringMissQuotationMark, is.Tell() - 1);
  599. else if ((unsigned)c < 0x20) // RFC 4627: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
  600. RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, is.Tell() - 1);
  601. else {
  602. if (parseFlags & kParseValidateEncodingFlag ?
  603. !Transcoder<SEncoding, TEncoding>::Validate(is, os) :
  604. !Transcoder<SEncoding, TEncoding>::Transcode(is, os))
  605. RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, is.Tell());
  606. }
  607. }
  608. }
  609. template<typename InputStream, bool backup>
  610. class NumberStream;
  611. template<typename InputStream>
  612. class NumberStream<InputStream, false> {
  613. public:
  614. NumberStream(GenericReader& reader, InputStream& s) : is(s) { (void)reader; }
  615. ~NumberStream() {}
  616. RAPIDJSON_FORCEINLINE Ch Peek() const { return is.Peek(); }
  617. RAPIDJSON_FORCEINLINE Ch TakePush() { return is.Take(); }
  618. RAPIDJSON_FORCEINLINE Ch Take() { return is.Take(); }
  619. size_t Tell() { return is.Tell(); }
  620. size_t Length() { return 0; }
  621. const char* Pop() { return 0; }
  622. protected:
  623. NumberStream& operator=(const NumberStream&);
  624. InputStream& is;
  625. };
  626. template<typename InputStream>
  627. class NumberStream<InputStream, true> : public NumberStream<InputStream, false> {
  628. typedef NumberStream<InputStream, false> Base;
  629. public:
  630. NumberStream(GenericReader& reader, InputStream& is) : NumberStream<InputStream, false>(reader, is), stackStream(reader.stack_) {}
  631. ~NumberStream() {}
  632. RAPIDJSON_FORCEINLINE Ch TakePush() {
  633. stackStream.Put((char)Base::is.Peek());
  634. return Base::is.Take();
  635. }
  636. size_t Length() { return stackStream.Length(); }
  637. const char* Pop() {
  638. stackStream.Put('\0');
  639. return stackStream.Pop();
  640. }
  641. private:
  642. StackStream<char> stackStream;
  643. };
  644. template<unsigned parseFlags, typename InputStream, typename Handler>
  645. void ParseNumber(InputStream& is, Handler& handler) {
  646. internal::StreamLocalCopy<InputStream> copy(is);
  647. NumberStream<InputStream, (parseFlags & kParseFullPrecisionFlag) != 0> s(*this, copy.s);
  648. // Parse minus
  649. bool minus = false;
  650. if (s.Peek() == '-') {
  651. minus = true;
  652. s.Take();
  653. }
  654. // Parse int: zero / ( digit1-9 *DIGIT )
  655. unsigned i = 0;
  656. uint64_t i64 = 0;
  657. bool use64bit = false;
  658. int significandDigit = 0;
  659. if (s.Peek() == '0') {
  660. i = 0;
  661. s.TakePush();
  662. }
  663. else if (s.Peek() >= '1' && s.Peek() <= '9') {
  664. i = static_cast<unsigned>(s.TakePush() - '0');
  665. if (minus)
  666. while (s.Peek() >= '0' && s.Peek() <= '9') {
  667. if (i >= 214748364) { // 2^31 = 2147483648
  668. if (i != 214748364 || s.Peek() > '8') {
  669. i64 = i;
  670. use64bit = true;
  671. break;
  672. }
  673. }
  674. i = i * 10 + static_cast<unsigned>(s.TakePush() - '0');
  675. significandDigit++;
  676. }
  677. else
  678. while (s.Peek() >= '0' && s.Peek() <= '9') {
  679. if (i >= 429496729) { // 2^32 - 1 = 4294967295
  680. if (i != 429496729 || s.Peek() > '5') {
  681. i64 = i;
  682. use64bit = true;
  683. break;
  684. }
  685. }
  686. i = i * 10 + static_cast<unsigned>(s.TakePush() - '0');
  687. significandDigit++;
  688. }
  689. }
  690. else
  691. RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell());
  692. // Parse 64bit int
  693. bool useDouble = false;
  694. double d = 0.0;
  695. if (use64bit) {
  696. if (minus)
  697. while (s.Peek() >= '0' && s.Peek() <= '9') {
  698. if (i64 >= RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC)) // 2^63 = 9223372036854775808
  699. if (i64 != RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC) || s.Peek() > '8') {
  700. d = i64;
  701. useDouble = true;
  702. break;
  703. }
  704. i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
  705. significandDigit++;
  706. }
  707. else
  708. while (s.Peek() >= '0' && s.Peek() <= '9') {
  709. if (i64 >= RAPIDJSON_UINT64_C2(0x19999999, 0x99999999)) // 2^64 - 1 = 18446744073709551615
  710. if (i64 != RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || s.Peek() > '5') {
  711. d = i64;
  712. useDouble = true;
  713. break;
  714. }
  715. i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
  716. significandDigit++;
  717. }
  718. }
  719. // Force double for big integer
  720. if (useDouble) {
  721. while (s.Peek() >= '0' && s.Peek() <= '9') {
  722. if (d >= 1.7976931348623157e307) // DBL_MAX / 10.0
  723. RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, s.Tell());
  724. d = d * 10 + (s.TakePush() - '0');
  725. }
  726. }
  727. // Parse frac = decimal-point 1*DIGIT
  728. int expFrac = 0;
  729. size_t decimalPosition;
  730. if (s.Peek() == '.') {
  731. s.Take();
  732. decimalPosition = s.Length();
  733. if (!(s.Peek() >= '0' && s.Peek() <= '9'))
  734. RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissFraction, s.Tell());
  735. if (!useDouble) {
  736. #if RAPIDJSON_64BIT
  737. // Use i64 to store significand in 64-bit architecture
  738. if (!use64bit)
  739. i64 = i;
  740. while (s.Peek() >= '0' && s.Peek() <= '9') {
  741. if (i64 > RAPIDJSON_UINT64_C2(0x1FFFFF, 0xFFFFFFFF)) // 2^53 - 1 for fast path
  742. break;
  743. else {
  744. i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
  745. --expFrac;
  746. if (i64 != 0)
  747. significandDigit++;
  748. }
  749. }
  750. d = (double)i64;
  751. #else
  752. // Use double to store significand in 32-bit architecture
  753. d = use64bit ? (double)i64 : (double)i;
  754. #endif
  755. useDouble = true;
  756. }
  757. while (s.Peek() >= '0' && s.Peek() <= '9') {
  758. if (significandDigit < 17) {
  759. d = d * 10.0 + (s.TakePush() - '0');
  760. --expFrac;
  761. if (d > 0.0)
  762. significandDigit++;
  763. }
  764. else
  765. s.TakePush();
  766. }
  767. }
  768. else
  769. decimalPosition = s.Length(); // decimal position at the end of integer.
  770. // Parse exp = e [ minus / plus ] 1*DIGIT
  771. int exp = 0;
  772. if (s.Peek() == 'e' || s.Peek() == 'E') {
  773. if (!useDouble) {
  774. d = use64bit ? i64 : i;
  775. useDouble = true;
  776. }
  777. s.Take();
  778. bool expMinus = false;
  779. if (s.Peek() == '+')
  780. s.Take();
  781. else if (s.Peek() == '-') {
  782. s.Take();
  783. expMinus = true;
  784. }
  785. if (s.Peek() >= '0' && s.Peek() <= '9') {
  786. exp = s.Take() - '0';
  787. if (expMinus) {
  788. while (s.Peek() >= '0' && s.Peek() <= '9') {
  789. exp = exp * 10 + (s.Take() - '0');
  790. if (exp >= 214748364) { // Issue #313: prevent overflow exponent
  791. while (s.Peek() >= '0' && s.Peek() <= '9') // Consume the rest of exponent
  792. s.Take();
  793. }
  794. }
  795. }
  796. else { // positive exp
  797. int maxExp = 308 - expFrac;
  798. while (s.Peek() >= '0' && s.Peek() <= '9') {
  799. exp = exp * 10 + (s.Take() - '0');
  800. if (exp > maxExp)
  801. RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, s.Tell());
  802. }
  803. }
  804. }
  805. else
  806. RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissExponent, s.Tell());
  807. if (expMinus)
  808. exp = -exp;
  809. }
  810. // Finish parsing, call event according to the type of number.
  811. bool cont = true;
  812. size_t length = s.Length();
  813. const char* decimal = s.Pop(); // Pop stack no matter if it will be used or not.
  814. if (useDouble) {
  815. int p = exp + expFrac;
  816. if (parseFlags & kParseFullPrecisionFlag)
  817. d = internal::StrtodFullPrecision(d, p, decimal, length, decimalPosition, exp);
  818. else
  819. d = internal::StrtodNormalPrecision(d, p);
  820. cont = handler.Double(minus ? -d : d);
  821. }
  822. else {
  823. if (use64bit) {
  824. if (minus)
  825. cont = handler.Int64(-(int64_t)i64);
  826. else
  827. cont = handler.Uint64(i64);
  828. }
  829. else {
  830. if (minus)
  831. cont = handler.Int(-(int)i);
  832. else
  833. cont = handler.Uint(i);
  834. }
  835. }
  836. if (!cont)
  837. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, s.Tell());
  838. }
  839. // Parse any JSON value
  840. template<unsigned parseFlags, typename InputStream, typename Handler>
  841. void ParseValue(InputStream& is, Handler& handler) {
  842. switch (is.Peek()) {
  843. case 'n': ParseNull <parseFlags>(is, handler); break;
  844. case 't': ParseTrue <parseFlags>(is, handler); break;
  845. case 'f': ParseFalse <parseFlags>(is, handler); break;
  846. case '"': ParseString<parseFlags>(is, handler); break;
  847. case '{': ParseObject<parseFlags>(is, handler); break;
  848. case '[': ParseArray <parseFlags>(is, handler); break;
  849. default : ParseNumber<parseFlags>(is, handler);
  850. }
  851. }
  852. // Iterative Parsing
  853. // States
  854. enum IterativeParsingState {
  855. IterativeParsingStartState = 0,
  856. IterativeParsingFinishState,
  857. IterativeParsingErrorState,
  858. // Object states
  859. IterativeParsingObjectInitialState,
  860. IterativeParsingMemberKeyState,
  861. IterativeParsingKeyValueDelimiterState,
  862. IterativeParsingMemberValueState,
  863. IterativeParsingMemberDelimiterState,
  864. IterativeParsingObjectFinishState,
  865. // Array states
  866. IterativeParsingArrayInitialState,
  867. IterativeParsingElementState,
  868. IterativeParsingElementDelimiterState,
  869. IterativeParsingArrayFinishState,
  870. // Single value state
  871. IterativeParsingValueState,
  872. cIterativeParsingStateCount
  873. };
  874. // Tokens
  875. enum Token {
  876. LeftBracketToken = 0,
  877. RightBracketToken,
  878. LeftCurlyBracketToken,
  879. RightCurlyBracketToken,
  880. CommaToken,
  881. ColonToken,
  882. StringToken,
  883. FalseToken,
  884. TrueToken,
  885. NullToken,
  886. NumberToken,
  887. kTokenCount
  888. };
  889. RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) {
  890. //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
  891. #define N NumberToken
  892. #define N16 N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N
  893. // Maps from ASCII to Token
  894. static const unsigned char tokenMap[256] = {
  895. N16, // 00~0F
  896. N16, // 10~1F
  897. N, N, StringToken, N, N, N, N, N, N, N, N, N, CommaToken, N, N, N, // 20~2F
  898. N, N, N, N, N, N, N, N, N, N, ColonToken, N, N, N, N, N, // 30~3F
  899. N16, // 40~4F
  900. N, N, N, N, N, N, N, N, N, N, N, LeftBracketToken, N, RightBracketToken, N, N, // 50~5F
  901. N, N, N, N, N, N, FalseToken, N, N, N, N, N, N, N, NullToken, N, // 60~6F
  902. N, N, N, N, TrueToken, N, N, N, N, N, N, LeftCurlyBracketToken, N, RightCurlyBracketToken, N, N, // 70~7F
  903. N16, N16, N16, N16, N16, N16, N16, N16 // 80~FF
  904. };
  905. #undef N
  906. #undef N16
  907. //!@endcond
  908. if (sizeof(Ch) == 1 || unsigned(c) < 256)
  909. return (Token)tokenMap[(unsigned char)c];
  910. else
  911. return NumberToken;
  912. }
  913. RAPIDJSON_FORCEINLINE IterativeParsingState Predict(IterativeParsingState state, Token token) {
  914. // current state x one lookahead token -> new state
  915. static const char G[cIterativeParsingStateCount][kTokenCount] = {
  916. // Start
  917. {
  918. IterativeParsingArrayInitialState, // Left bracket
  919. IterativeParsingErrorState, // Right bracket
  920. IterativeParsingObjectInitialState, // Left curly bracket
  921. IterativeParsingErrorState, // Right curly bracket
  922. IterativeParsingErrorState, // Comma
  923. IterativeParsingErrorState, // Colon
  924. IterativeParsingValueState, // String
  925. IterativeParsingValueState, // False
  926. IterativeParsingValueState, // True
  927. IterativeParsingValueState, // Null
  928. IterativeParsingValueState // Number
  929. },
  930. // Finish(sink state)
  931. {
  932. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  933. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  934. IterativeParsingErrorState
  935. },
  936. // Error(sink state)
  937. {
  938. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  939. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  940. IterativeParsingErrorState
  941. },
  942. // ObjectInitial
  943. {
  944. IterativeParsingErrorState, // Left bracket
  945. IterativeParsingErrorState, // Right bracket
  946. IterativeParsingErrorState, // Left curly bracket
  947. IterativeParsingObjectFinishState, // Right curly bracket
  948. IterativeParsingErrorState, // Comma
  949. IterativeParsingErrorState, // Colon
  950. IterativeParsingMemberKeyState, // String
  951. IterativeParsingErrorState, // False
  952. IterativeParsingErrorState, // True
  953. IterativeParsingErrorState, // Null
  954. IterativeParsingErrorState // Number
  955. },
  956. // MemberKey
  957. {
  958. IterativeParsingErrorState, // Left bracket
  959. IterativeParsingErrorState, // Right bracket
  960. IterativeParsingErrorState, // Left curly bracket
  961. IterativeParsingErrorState, // Right curly bracket
  962. IterativeParsingErrorState, // Comma
  963. IterativeParsingKeyValueDelimiterState, // Colon
  964. IterativeParsingErrorState, // String
  965. IterativeParsingErrorState, // False
  966. IterativeParsingErrorState, // True
  967. IterativeParsingErrorState, // Null
  968. IterativeParsingErrorState // Number
  969. },
  970. // KeyValueDelimiter
  971. {
  972. IterativeParsingArrayInitialState, // Left bracket(push MemberValue state)
  973. IterativeParsingErrorState, // Right bracket
  974. IterativeParsingObjectInitialState, // Left curly bracket(push MemberValue state)
  975. IterativeParsingErrorState, // Right curly bracket
  976. IterativeParsingErrorState, // Comma
  977. IterativeParsingErrorState, // Colon
  978. IterativeParsingMemberValueState, // String
  979. IterativeParsingMemberValueState, // False
  980. IterativeParsingMemberValueState, // True
  981. IterativeParsingMemberValueState, // Null
  982. IterativeParsingMemberValueState // Number
  983. },
  984. // MemberValue
  985. {
  986. IterativeParsingErrorState, // Left bracket
  987. IterativeParsingErrorState, // Right bracket
  988. IterativeParsingErrorState, // Left curly bracket
  989. IterativeParsingObjectFinishState, // Right curly bracket
  990. IterativeParsingMemberDelimiterState, // Comma
  991. IterativeParsingErrorState, // Colon
  992. IterativeParsingErrorState, // String
  993. IterativeParsingErrorState, // False
  994. IterativeParsingErrorState, // True
  995. IterativeParsingErrorState, // Null
  996. IterativeParsingErrorState // Number
  997. },
  998. // MemberDelimiter
  999. {
  1000. IterativeParsingErrorState, // Left bracket
  1001. IterativeParsingErrorState, // Right bracket
  1002. IterativeParsingErrorState, // Left curly bracket
  1003. IterativeParsingErrorState, // Right curly bracket
  1004. IterativeParsingErrorState, // Comma
  1005. IterativeParsingErrorState, // Colon
  1006. IterativeParsingMemberKeyState, // String
  1007. IterativeParsingErrorState, // False
  1008. IterativeParsingErrorState, // True
  1009. IterativeParsingErrorState, // Null
  1010. IterativeParsingErrorState // Number
  1011. },
  1012. // ObjectFinish(sink state)
  1013. {
  1014. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1015. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1016. IterativeParsingErrorState
  1017. },
  1018. // ArrayInitial
  1019. {
  1020. IterativeParsingArrayInitialState, // Left bracket(push Element state)
  1021. IterativeParsingArrayFinishState, // Right bracket
  1022. IterativeParsingObjectInitialState, // Left curly bracket(push Element state)
  1023. IterativeParsingErrorState, // Right curly bracket
  1024. IterativeParsingErrorState, // Comma
  1025. IterativeParsingErrorState, // Colon
  1026. IterativeParsingElementState, // String
  1027. IterativeParsingElementState, // False
  1028. IterativeParsingElementState, // True
  1029. IterativeParsingElementState, // Null
  1030. IterativeParsingElementState // Number
  1031. },
  1032. // Element
  1033. {
  1034. IterativeParsingErrorState, // Left bracket
  1035. IterativeParsingArrayFinishState, // Right bracket
  1036. IterativeParsingErrorState, // Left curly bracket
  1037. IterativeParsingErrorState, // Right curly bracket
  1038. IterativeParsingElementDelimiterState, // Comma
  1039. IterativeParsingErrorState, // Colon
  1040. IterativeParsingErrorState, // String
  1041. IterativeParsingErrorState, // False
  1042. IterativeParsingErrorState, // True
  1043. IterativeParsingErrorState, // Null
  1044. IterativeParsingErrorState // Number
  1045. },
  1046. // ElementDelimiter
  1047. {
  1048. IterativeParsingArrayInitialState, // Left bracket(push Element state)
  1049. IterativeParsingErrorState, // Right bracket
  1050. IterativeParsingObjectInitialState, // Left curly bracket(push Element state)
  1051. IterativeParsingErrorState, // Right curly bracket
  1052. IterativeParsingErrorState, // Comma
  1053. IterativeParsingErrorState, // Colon
  1054. IterativeParsingElementState, // String
  1055. IterativeParsingElementState, // False
  1056. IterativeParsingElementState, // True
  1057. IterativeParsingElementState, // Null
  1058. IterativeParsingElementState // Number
  1059. },
  1060. // ArrayFinish(sink state)
  1061. {
  1062. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1063. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1064. IterativeParsingErrorState
  1065. },
  1066. // Single Value (sink state)
  1067. {
  1068. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1069. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1070. IterativeParsingErrorState
  1071. }
  1072. }; // End of G
  1073. return (IterativeParsingState)G[state][token];
  1074. }
  1075. // Make an advance in the token stream and state based on the candidate destination state which was returned by Transit().
  1076. // May return a new state on state pop.
  1077. template <unsigned parseFlags, typename InputStream, typename Handler>
  1078. RAPIDJSON_FORCEINLINE IterativeParsingState Transit(IterativeParsingState src, Token token, IterativeParsingState dst, InputStream& is, Handler& handler) {
  1079. (void)token;
  1080. switch (dst) {
  1081. case IterativeParsingErrorState:
  1082. return dst;
  1083. case IterativeParsingObjectInitialState:
  1084. case IterativeParsingArrayInitialState:
  1085. {
  1086. // Push the state(Element or MemeberValue) if we are nested in another array or value of member.
  1087. // In this way we can get the correct state on ObjectFinish or ArrayFinish by frame pop.
  1088. IterativeParsingState n = src;
  1089. if (src == IterativeParsingArrayInitialState || src == IterativeParsingElementDelimiterState)
  1090. n = IterativeParsingElementState;
  1091. else if (src == IterativeParsingKeyValueDelimiterState)
  1092. n = IterativeParsingMemberValueState;
  1093. // Push current state.
  1094. *stack_.template Push<SizeType>(1) = n;
  1095. // Initialize and push the member/element count.
  1096. *stack_.template Push<SizeType>(1) = 0;
  1097. // Call handler
  1098. bool hr = (dst == IterativeParsingObjectInitialState) ? handler.StartObject() : handler.StartArray();
  1099. // On handler short circuits the parsing.
  1100. if (!hr) {
  1101. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
  1102. return IterativeParsingErrorState;
  1103. }
  1104. else {
  1105. is.Take();
  1106. return dst;
  1107. }
  1108. }
  1109. case IterativeParsingMemberKeyState:
  1110. ParseString<parseFlags>(is, handler, true);
  1111. if (HasParseError())
  1112. return IterativeParsingErrorState;
  1113. else
  1114. return dst;
  1115. case IterativeParsingKeyValueDelimiterState:
  1116. RAPIDJSON_ASSERT(token == ColonToken);
  1117. is.Take();
  1118. return dst;
  1119. case IterativeParsingMemberValueState:
  1120. // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
  1121. ParseValue<parseFlags>(is, handler);
  1122. if (HasParseError()) {
  1123. return IterativeParsingErrorState;
  1124. }
  1125. return dst;
  1126. case IterativeParsingElementState:
  1127. // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
  1128. ParseValue<parseFlags>(is, handler);
  1129. if (HasParseError()) {
  1130. return IterativeParsingErrorState;
  1131. }
  1132. return dst;
  1133. case IterativeParsingMemberDelimiterState:
  1134. case IterativeParsingElementDelimiterState:
  1135. is.Take();
  1136. // Update member/element count.
  1137. *stack_.template Top<SizeType>() = *stack_.template Top<SizeType>() + 1;
  1138. return dst;
  1139. case IterativeParsingObjectFinishState:
  1140. {
  1141. // Get member count.
  1142. SizeType c = *stack_.template Pop<SizeType>(1);
  1143. // If the object is not empty, count the last member.
  1144. if (src == IterativeParsingMemberValueState)
  1145. ++c;
  1146. // Restore the state.
  1147. IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1));
  1148. // Transit to Finish state if this is the topmost scope.
  1149. if (n == IterativeParsingStartState)
  1150. n = IterativeParsingFinishState;
  1151. // Call handler
  1152. bool hr = handler.EndObject(c);
  1153. // On handler short circuits the parsing.
  1154. if (!hr) {
  1155. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
  1156. return IterativeParsingErrorState;
  1157. }
  1158. else {
  1159. is.Take();
  1160. return n;
  1161. }
  1162. }
  1163. case IterativeParsingArrayFinishState:
  1164. {
  1165. // Get element count.
  1166. SizeType c = *stack_.template Pop<SizeType>(1);
  1167. // If the array is not empty, count the last element.
  1168. if (src == IterativeParsingElementState)
  1169. ++c;
  1170. // Restore the state.
  1171. IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1));
  1172. // Transit to Finish state if this is the topmost scope.
  1173. if (n == IterativeParsingStartState)
  1174. n = IterativeParsingFinishState;
  1175. // Call handler
  1176. bool hr = handler.EndArray(c);
  1177. // On handler short circuits the parsing.
  1178. if (!hr) {
  1179. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
  1180. return IterativeParsingErrorState;
  1181. }
  1182. else {
  1183. is.Take();
  1184. return n;
  1185. }
  1186. }
  1187. default:
  1188. // This branch is for IterativeParsingValueState actually.
  1189. // Use `default:` rather than
  1190. // `case IterativeParsingValueState:` is for code coverage.
  1191. // The IterativeParsingStartState is not enumerated in this switch-case.
  1192. // It is impossible for that case. And it can be caught by following assertion.
  1193. // The IterativeParsingFinishState is not enumerated in this switch-case either.
  1194. // It is a "derivative" state which cannot triggered from Predict() directly.
  1195. // Therefore it cannot happen here. And it can be caught by following assertion.
  1196. RAPIDJSON_ASSERT(dst == IterativeParsingValueState);
  1197. // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
  1198. ParseValue<parseFlags>(is, handler);
  1199. if (HasParseError()) {
  1200. return IterativeParsingErrorState;
  1201. }
  1202. return IterativeParsingFinishState;
  1203. }
  1204. }
  1205. template <typename InputStream>
  1206. void HandleError(IterativeParsingState src, InputStream& is) {
  1207. if (HasParseError()) {
  1208. // Error flag has been set.
  1209. return;
  1210. }
  1211. switch (src) {
  1212. case IterativeParsingStartState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentEmpty, is.Tell());
  1213. case IterativeParsingFinishState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentRootNotSingular, is.Tell());
  1214. case IterativeParsingObjectInitialState:
  1215. case IterativeParsingMemberDelimiterState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell());
  1216. case IterativeParsingMemberKeyState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell());
  1217. case IterativeParsingMemberValueState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell());
  1218. case IterativeParsingElementState: RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell());
  1219. default: RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell());
  1220. }
  1221. }
  1222. template <unsigned parseFlags, typename InputStream, typename Handler>
  1223. ParseResult IterativeParse(InputStream& is, Handler& handler) {
  1224. parseResult_.Clear();
  1225. ClearStackOnExit scope(*this);
  1226. IterativeParsingState state = IterativeParsingStartState;
  1227. SkipWhitespace(is);
  1228. while (is.Peek() != '\0') {
  1229. Token t = Tokenize(is.Peek());
  1230. IterativeParsingState n = Predict(state, t);
  1231. IterativeParsingState d = Transit<parseFlags>(state, t, n, is, handler);
  1232. if (d == IterativeParsingErrorState) {
  1233. HandleError(state, is);
  1234. break;
  1235. }
  1236. state = d;
  1237. // Do not further consume streams if a root JSON has been parsed.
  1238. if ((parseFlags & kParseStopWhenDoneFlag) && state == IterativeParsingFinishState)
  1239. break;
  1240. SkipWhitespace(is);
  1241. }
  1242. // Handle the end of file.
  1243. if (state != IterativeParsingFinishState)
  1244. HandleError(state, is);
  1245. return parseResult_;
  1246. }
  1247. static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string.
  1248. internal::Stack<StackAllocator> stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing.
  1249. ParseResult parseResult_;
  1250. }; // class GenericReader
  1251. //! Reader with UTF8 encoding and default allocator.
  1252. typedef GenericReader<UTF8<>, UTF8<> > Reader;
  1253. RAPIDJSON_NAMESPACE_END
  1254. #ifdef __GNUC__
  1255. RAPIDJSON_DIAG_POP
  1256. #endif
  1257. #ifdef _MSC_VER
  1258. RAPIDJSON_DIAG_POP
  1259. #endif
  1260. #endif // RAPIDJSON_READER_H_