reader.h 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231
  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 "allocators.h"
  18. #include "stream.h"
  19. #include "encodedstream.h"
  20. #include "internal/clzll.h"
  21. #include "internal/meta.h"
  22. #include "internal/stack.h"
  23. #include "internal/strtod.h"
  24. #include <limits>
  25. #if defined(RAPIDJSON_SIMD) && defined(_MSC_VER)
  26. #include <intrin.h>
  27. #pragma intrinsic(_BitScanForward)
  28. #endif
  29. #ifdef RAPIDJSON_SSE42
  30. #include <nmmintrin.h>
  31. #elif defined(RAPIDJSON_SSE2)
  32. #include <emmintrin.h>
  33. #elif defined(RAPIDJSON_NEON)
  34. #include <arm_neon.h>
  35. #endif
  36. #ifdef __clang__
  37. RAPIDJSON_DIAG_PUSH
  38. RAPIDJSON_DIAG_OFF(old-style-cast)
  39. RAPIDJSON_DIAG_OFF(padded)
  40. RAPIDJSON_DIAG_OFF(switch-enum)
  41. #elif defined(_MSC_VER)
  42. RAPIDJSON_DIAG_PUSH
  43. RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
  44. RAPIDJSON_DIAG_OFF(4702) // unreachable code
  45. #endif
  46. #ifdef __GNUC__
  47. RAPIDJSON_DIAG_PUSH
  48. RAPIDJSON_DIAG_OFF(effc++)
  49. #endif
  50. //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
  51. #define RAPIDJSON_NOTHING /* deliberately empty */
  52. #ifndef RAPIDJSON_PARSE_ERROR_EARLY_RETURN
  53. #define RAPIDJSON_PARSE_ERROR_EARLY_RETURN(value) \
  54. RAPIDJSON_MULTILINEMACRO_BEGIN \
  55. if (RAPIDJSON_UNLIKELY(HasParseError())) { return value; } \
  56. RAPIDJSON_MULTILINEMACRO_END
  57. #endif
  58. #define RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID \
  59. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(RAPIDJSON_NOTHING)
  60. //!@endcond
  61. /*! \def RAPIDJSON_PARSE_ERROR_NORETURN
  62. \ingroup RAPIDJSON_ERRORS
  63. \brief Macro to indicate a parse error.
  64. \param parseErrorCode \ref rapidjson::ParseErrorCode of the error
  65. \param offset position of the error in JSON input (\c size_t)
  66. This macros can be used as a customization point for the internal
  67. error handling mechanism of RapidJSON.
  68. A common usage model is to throw an exception instead of requiring the
  69. caller to explicitly check the \ref rapidjson::GenericReader::Parse's
  70. return value:
  71. \code
  72. #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode,offset) \
  73. throw ParseException(parseErrorCode, #parseErrorCode, offset)
  74. #include <stdexcept> // std::runtime_error
  75. #include "rapidjson/error/error.h" // rapidjson::ParseResult
  76. struct ParseException : std::runtime_error, rapidjson::ParseResult {
  77. ParseException(rapidjson::ParseErrorCode code, const char* msg, size_t offset)
  78. : std::runtime_error(msg), ParseResult(code, offset) {}
  79. };
  80. #include "rapidjson/reader.h"
  81. \endcode
  82. \see RAPIDJSON_PARSE_ERROR, rapidjson::GenericReader::Parse
  83. */
  84. #ifndef RAPIDJSON_PARSE_ERROR_NORETURN
  85. #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) \
  86. RAPIDJSON_MULTILINEMACRO_BEGIN \
  87. RAPIDJSON_ASSERT(!HasParseError()); /* Error can only be assigned once */ \
  88. SetParseError(parseErrorCode, offset); \
  89. RAPIDJSON_MULTILINEMACRO_END
  90. #endif
  91. /*! \def RAPIDJSON_PARSE_ERROR
  92. \ingroup RAPIDJSON_ERRORS
  93. \brief (Internal) macro to indicate and handle a parse error.
  94. \param parseErrorCode \ref rapidjson::ParseErrorCode of the error
  95. \param offset position of the error in JSON input (\c size_t)
  96. Invokes RAPIDJSON_PARSE_ERROR_NORETURN and stops the parsing.
  97. \see RAPIDJSON_PARSE_ERROR_NORETURN
  98. \hideinitializer
  99. */
  100. #ifndef RAPIDJSON_PARSE_ERROR
  101. #define RAPIDJSON_PARSE_ERROR(parseErrorCode, offset) \
  102. RAPIDJSON_MULTILINEMACRO_BEGIN \
  103. RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset); \
  104. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; \
  105. RAPIDJSON_MULTILINEMACRO_END
  106. #endif
  107. #include "error/error.h" // ParseErrorCode, ParseResult
  108. RAPIDJSON_NAMESPACE_BEGIN
  109. ///////////////////////////////////////////////////////////////////////////////
  110. // ParseFlag
  111. /*! \def RAPIDJSON_PARSE_DEFAULT_FLAGS
  112. \ingroup RAPIDJSON_CONFIG
  113. \brief User-defined kParseDefaultFlags definition.
  114. User can define this as any \c ParseFlag combinations.
  115. */
  116. #ifndef RAPIDJSON_PARSE_DEFAULT_FLAGS
  117. #define RAPIDJSON_PARSE_DEFAULT_FLAGS kParseNoFlags
  118. #endif
  119. //! Combination of parseFlags
  120. /*! \see Reader::Parse, Document::Parse, Document::ParseInsitu, Document::ParseStream
  121. */
  122. enum ParseFlag {
  123. kParseNoFlags = 0, //!< No flags are set.
  124. kParseInsituFlag = 1, //!< In-situ(destructive) parsing.
  125. kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings.
  126. kParseIterativeFlag = 4, //!< Iterative(constant complexity in terms of function call stack size) parsing.
  127. 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.
  128. kParseFullPrecisionFlag = 16, //!< Parse number in full precision (but slower).
  129. kParseCommentsFlag = 32, //!< Allow one-line (//) and multi-line (/**/) comments.
  130. kParseNumbersAsStringsFlag = 64, //!< Parse all numbers (ints/doubles) as strings.
  131. kParseTrailingCommasFlag = 128, //!< Allow trailing commas at the end of objects and arrays.
  132. kParseNanAndInfFlag = 256, //!< Allow parsing NaN, Inf, Infinity, -Inf and -Infinity as doubles.
  133. kParseDefaultFlags = RAPIDJSON_PARSE_DEFAULT_FLAGS //!< Default parse flags. Can be customized by defining RAPIDJSON_PARSE_DEFAULT_FLAGS
  134. };
  135. ///////////////////////////////////////////////////////////////////////////////
  136. // Handler
  137. /*! \class rapidjson::Handler
  138. \brief Concept for receiving events from GenericReader upon parsing.
  139. The functions return true if no error occurs. If they return false,
  140. the event publisher should terminate the process.
  141. \code
  142. concept Handler {
  143. typename Ch;
  144. bool Null();
  145. bool Bool(bool b);
  146. bool Int(int i);
  147. bool Uint(unsigned i);
  148. bool Int64(int64_t i);
  149. bool Uint64(uint64_t i);
  150. bool Double(double d);
  151. /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length)
  152. bool RawNumber(const Ch* str, SizeType length, bool copy);
  153. bool String(const Ch* str, SizeType length, bool copy);
  154. bool StartObject();
  155. bool Key(const Ch* str, SizeType length, bool copy);
  156. bool EndObject(SizeType memberCount);
  157. bool StartArray();
  158. bool EndArray(SizeType elementCount);
  159. };
  160. \endcode
  161. */
  162. ///////////////////////////////////////////////////////////////////////////////
  163. // BaseReaderHandler
  164. //! Default implementation of Handler.
  165. /*! This can be used as base class of any reader handler.
  166. \note implements Handler concept
  167. */
  168. template<typename Encoding = UTF8<>, typename Derived = void>
  169. struct BaseReaderHandler {
  170. typedef typename Encoding::Ch Ch;
  171. typedef typename internal::SelectIf<internal::IsSame<Derived, void>, BaseReaderHandler, Derived>::Type Override;
  172. bool Default() { return true; }
  173. bool Null() { return static_cast<Override&>(*this).Default(); }
  174. bool Bool(bool) { return static_cast<Override&>(*this).Default(); }
  175. bool Int(int) { return static_cast<Override&>(*this).Default(); }
  176. bool Uint(unsigned) { return static_cast<Override&>(*this).Default(); }
  177. bool Int64(int64_t) { return static_cast<Override&>(*this).Default(); }
  178. bool Uint64(uint64_t) { return static_cast<Override&>(*this).Default(); }
  179. bool Double(double) { return static_cast<Override&>(*this).Default(); }
  180. /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length)
  181. bool RawNumber(const Ch* str, SizeType len, bool copy) { return static_cast<Override&>(*this).String(str, len, copy); }
  182. bool String(const Ch*, SizeType, bool) { return static_cast<Override&>(*this).Default(); }
  183. bool StartObject() { return static_cast<Override&>(*this).Default(); }
  184. bool Key(const Ch* str, SizeType len, bool copy) { return static_cast<Override&>(*this).String(str, len, copy); }
  185. bool EndObject(SizeType) { return static_cast<Override&>(*this).Default(); }
  186. bool StartArray() { return static_cast<Override&>(*this).Default(); }
  187. bool EndArray(SizeType) { return static_cast<Override&>(*this).Default(); }
  188. };
  189. ///////////////////////////////////////////////////////////////////////////////
  190. // StreamLocalCopy
  191. namespace internal {
  192. template<typename Stream, int = StreamTraits<Stream>::copyOptimization>
  193. class StreamLocalCopy;
  194. //! Do copy optimization.
  195. template<typename Stream>
  196. class StreamLocalCopy<Stream, 1> {
  197. public:
  198. StreamLocalCopy(Stream& original) : s(original), original_(original) {}
  199. ~StreamLocalCopy() { original_ = s; }
  200. Stream s;
  201. private:
  202. StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */;
  203. Stream& original_;
  204. };
  205. //! Keep reference.
  206. template<typename Stream>
  207. class StreamLocalCopy<Stream, 0> {
  208. public:
  209. StreamLocalCopy(Stream& original) : s(original) {}
  210. Stream& s;
  211. private:
  212. StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */;
  213. };
  214. } // namespace internal
  215. ///////////////////////////////////////////////////////////////////////////////
  216. // SkipWhitespace
  217. //! Skip the JSON white spaces in a stream.
  218. /*! \param is A input stream for skipping white spaces.
  219. \note This function has SSE2/SSE4.2 specialization.
  220. */
  221. template<typename InputStream>
  222. void SkipWhitespace(InputStream& is) {
  223. internal::StreamLocalCopy<InputStream> copy(is);
  224. InputStream& s(copy.s);
  225. typename InputStream::Ch c;
  226. while ((c = s.Peek()) == ' ' || c == '\n' || c == '\r' || c == '\t')
  227. s.Take();
  228. }
  229. inline const char* SkipWhitespace(const char* p, const char* end) {
  230. while (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t'))
  231. ++p;
  232. return p;
  233. }
  234. #ifdef RAPIDJSON_SSE42
  235. //! Skip whitespace with SSE 4.2 pcmpistrm instruction, testing 16 8-byte characters at once.
  236. inline const char *SkipWhitespace_SIMD(const char* p) {
  237. // Fast return for single non-whitespace
  238. if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
  239. ++p;
  240. else
  241. return p;
  242. // 16-byte align to the next boundary
  243. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  244. while (p != nextAligned)
  245. if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
  246. ++p;
  247. else
  248. return p;
  249. // The rest of string using SIMD
  250. static const char whitespace[16] = " \n\r\t";
  251. const __m128i w = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespace[0]));
  252. for (;; p += 16) {
  253. const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
  254. const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY);
  255. if (r != 16) // some of characters is non-whitespace
  256. return p + r;
  257. }
  258. }
  259. inline const char *SkipWhitespace_SIMD(const char* p, const char* end) {
  260. // Fast return for single non-whitespace
  261. if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t'))
  262. ++p;
  263. else
  264. return p;
  265. // The middle of string using SIMD
  266. static const char whitespace[16] = " \n\r\t";
  267. const __m128i w = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespace[0]));
  268. for (; p <= end - 16; p += 16) {
  269. const __m128i s = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p));
  270. const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY);
  271. if (r != 16) // some of characters is non-whitespace
  272. return p + r;
  273. }
  274. return SkipWhitespace(p, end);
  275. }
  276. #elif defined(RAPIDJSON_SSE2)
  277. //! Skip whitespace with SSE2 instructions, testing 16 8-byte characters at once.
  278. inline const char *SkipWhitespace_SIMD(const char* p) {
  279. // Fast return for single non-whitespace
  280. if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
  281. ++p;
  282. else
  283. return p;
  284. // 16-byte align to the next boundary
  285. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  286. while (p != nextAligned)
  287. if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
  288. ++p;
  289. else
  290. return p;
  291. // The rest of string
  292. #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c }
  293. static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') };
  294. #undef C16
  295. const __m128i w0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[0][0]));
  296. const __m128i w1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[1][0]));
  297. const __m128i w2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[2][0]));
  298. const __m128i w3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[3][0]));
  299. for (;; p += 16) {
  300. const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
  301. __m128i x = _mm_cmpeq_epi8(s, w0);
  302. x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1));
  303. x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2));
  304. x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3));
  305. unsigned short r = static_cast<unsigned short>(~_mm_movemask_epi8(x));
  306. if (r != 0) { // some of characters may be non-whitespace
  307. #ifdef _MSC_VER // Find the index of first non-whitespace
  308. unsigned long offset;
  309. _BitScanForward(&offset, r);
  310. return p + offset;
  311. #else
  312. return p + __builtin_ffs(r) - 1;
  313. #endif
  314. }
  315. }
  316. }
  317. inline const char *SkipWhitespace_SIMD(const char* p, const char* end) {
  318. // Fast return for single non-whitespace
  319. if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t'))
  320. ++p;
  321. else
  322. return p;
  323. // The rest of string
  324. #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c }
  325. static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') };
  326. #undef C16
  327. const __m128i w0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[0][0]));
  328. const __m128i w1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[1][0]));
  329. const __m128i w2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[2][0]));
  330. const __m128i w3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[3][0]));
  331. for (; p <= end - 16; p += 16) {
  332. const __m128i s = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p));
  333. __m128i x = _mm_cmpeq_epi8(s, w0);
  334. x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1));
  335. x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2));
  336. x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3));
  337. unsigned short r = static_cast<unsigned short>(~_mm_movemask_epi8(x));
  338. if (r != 0) { // some of characters may be non-whitespace
  339. #ifdef _MSC_VER // Find the index of first non-whitespace
  340. unsigned long offset;
  341. _BitScanForward(&offset, r);
  342. return p + offset;
  343. #else
  344. return p + __builtin_ffs(r) - 1;
  345. #endif
  346. }
  347. }
  348. return SkipWhitespace(p, end);
  349. }
  350. #elif defined(RAPIDJSON_NEON)
  351. //! Skip whitespace with ARM Neon instructions, testing 16 8-byte characters at once.
  352. inline const char *SkipWhitespace_SIMD(const char* p) {
  353. // Fast return for single non-whitespace
  354. if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
  355. ++p;
  356. else
  357. return p;
  358. // 16-byte align to the next boundary
  359. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  360. while (p != nextAligned)
  361. if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
  362. ++p;
  363. else
  364. return p;
  365. const uint8x16_t w0 = vmovq_n_u8(' ');
  366. const uint8x16_t w1 = vmovq_n_u8('\n');
  367. const uint8x16_t w2 = vmovq_n_u8('\r');
  368. const uint8x16_t w3 = vmovq_n_u8('\t');
  369. for (;; p += 16) {
  370. const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p));
  371. uint8x16_t x = vceqq_u8(s, w0);
  372. x = vorrq_u8(x, vceqq_u8(s, w1));
  373. x = vorrq_u8(x, vceqq_u8(s, w2));
  374. x = vorrq_u8(x, vceqq_u8(s, w3));
  375. x = vmvnq_u8(x); // Negate
  376. x = vrev64q_u8(x); // Rev in 64
  377. uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract
  378. uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract
  379. if (low == 0) {
  380. if (high != 0) {
  381. uint32_t lz = RAPIDJSON_CLZLL(high);
  382. return p + 8 + (lz >> 3);
  383. }
  384. } else {
  385. uint32_t lz = RAPIDJSON_CLZLL(low);
  386. return p + (lz >> 3);
  387. }
  388. }
  389. }
  390. inline const char *SkipWhitespace_SIMD(const char* p, const char* end) {
  391. // Fast return for single non-whitespace
  392. if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t'))
  393. ++p;
  394. else
  395. return p;
  396. const uint8x16_t w0 = vmovq_n_u8(' ');
  397. const uint8x16_t w1 = vmovq_n_u8('\n');
  398. const uint8x16_t w2 = vmovq_n_u8('\r');
  399. const uint8x16_t w3 = vmovq_n_u8('\t');
  400. for (; p <= end - 16; p += 16) {
  401. const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p));
  402. uint8x16_t x = vceqq_u8(s, w0);
  403. x = vorrq_u8(x, vceqq_u8(s, w1));
  404. x = vorrq_u8(x, vceqq_u8(s, w2));
  405. x = vorrq_u8(x, vceqq_u8(s, w3));
  406. x = vmvnq_u8(x); // Negate
  407. x = vrev64q_u8(x); // Rev in 64
  408. uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract
  409. uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract
  410. if (low == 0) {
  411. if (high != 0) {
  412. uint32_t lz = RAPIDJSON_CLZLL(high);
  413. return p + 8 + (lz >> 3);
  414. }
  415. } else {
  416. uint32_t lz = RAPIDJSON_CLZLL(low);
  417. return p + (lz >> 3);
  418. }
  419. }
  420. return SkipWhitespace(p, end);
  421. }
  422. #endif // RAPIDJSON_NEON
  423. #ifdef RAPIDJSON_SIMD
  424. //! Template function specialization for InsituStringStream
  425. template<> inline void SkipWhitespace(InsituStringStream& is) {
  426. is.src_ = const_cast<char*>(SkipWhitespace_SIMD(is.src_));
  427. }
  428. //! Template function specialization for StringStream
  429. template<> inline void SkipWhitespace(StringStream& is) {
  430. is.src_ = SkipWhitespace_SIMD(is.src_);
  431. }
  432. template<> inline void SkipWhitespace(EncodedInputStream<UTF8<>, MemoryStream>& is) {
  433. is.is_.src_ = SkipWhitespace_SIMD(is.is_.src_, is.is_.end_);
  434. }
  435. #endif // RAPIDJSON_SIMD
  436. ///////////////////////////////////////////////////////////////////////////////
  437. // GenericReader
  438. //! SAX-style JSON parser. Use \ref Reader for UTF8 encoding and default allocator.
  439. /*! GenericReader parses JSON text from a stream, and send events synchronously to an
  440. object implementing Handler concept.
  441. It needs to allocate a stack for storing a single decoded string during
  442. non-destructive parsing.
  443. For in-situ parsing, the decoded string is directly written to the source
  444. text string, no temporary buffer is required.
  445. A GenericReader object can be reused for parsing multiple JSON text.
  446. \tparam SourceEncoding Encoding of the input stream.
  447. \tparam TargetEncoding Encoding of the parse output.
  448. \tparam StackAllocator Allocator type for stack.
  449. */
  450. template <typename SourceEncoding, typename TargetEncoding, typename StackAllocator = CrtAllocator>
  451. class GenericReader {
  452. public:
  453. typedef typename SourceEncoding::Ch Ch; //!< SourceEncoding character type
  454. //! Constructor.
  455. /*! \param stackAllocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing)
  456. \param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing)
  457. */
  458. GenericReader(StackAllocator* stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) :
  459. stack_(stackAllocator, stackCapacity), parseResult_(), state_(IterativeParsingStartState) {}
  460. //! Parse JSON text.
  461. /*! \tparam parseFlags Combination of \ref ParseFlag.
  462. \tparam InputStream Type of input stream, implementing Stream concept.
  463. \tparam Handler Type of handler, implementing Handler concept.
  464. \param is Input stream to be parsed.
  465. \param handler The handler to receive events.
  466. \return Whether the parsing is successful.
  467. */
  468. template <unsigned parseFlags, typename InputStream, typename Handler>
  469. ParseResult Parse(InputStream& is, Handler& handler) {
  470. if (parseFlags & kParseIterativeFlag)
  471. return IterativeParse<parseFlags>(is, handler);
  472. parseResult_.Clear();
  473. ClearStackOnExit scope(*this);
  474. SkipWhitespaceAndComments<parseFlags>(is);
  475. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
  476. if (RAPIDJSON_UNLIKELY(is.Peek() == '\0')) {
  477. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentEmpty, is.Tell());
  478. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
  479. }
  480. else {
  481. ParseValue<parseFlags>(is, handler);
  482. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
  483. if (!(parseFlags & kParseStopWhenDoneFlag)) {
  484. SkipWhitespaceAndComments<parseFlags>(is);
  485. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
  486. if (RAPIDJSON_UNLIKELY(is.Peek() != '\0')) {
  487. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentRootNotSingular, is.Tell());
  488. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
  489. }
  490. }
  491. }
  492. return parseResult_;
  493. }
  494. //! Parse JSON text (with \ref kParseDefaultFlags)
  495. /*! \tparam InputStream Type of input stream, implementing Stream concept
  496. \tparam Handler Type of handler, implementing Handler concept.
  497. \param is Input stream to be parsed.
  498. \param handler The handler to receive events.
  499. \return Whether the parsing is successful.
  500. */
  501. template <typename InputStream, typename Handler>
  502. ParseResult Parse(InputStream& is, Handler& handler) {
  503. return Parse<kParseDefaultFlags>(is, handler);
  504. }
  505. //! Initialize JSON text token-by-token parsing
  506. /*!
  507. */
  508. void IterativeParseInit() {
  509. parseResult_.Clear();
  510. state_ = IterativeParsingStartState;
  511. }
  512. //! Parse one token from JSON text
  513. /*! \tparam InputStream Type of input stream, implementing Stream concept
  514. \tparam Handler Type of handler, implementing Handler concept.
  515. \param is Input stream to be parsed.
  516. \param handler The handler to receive events.
  517. \return Whether the parsing is successful.
  518. */
  519. template <unsigned parseFlags, typename InputStream, typename Handler>
  520. bool IterativeParseNext(InputStream& is, Handler& handler) {
  521. while (RAPIDJSON_LIKELY(is.Peek() != '\0')) {
  522. SkipWhitespaceAndComments<parseFlags>(is);
  523. Token t = Tokenize(is.Peek());
  524. IterativeParsingState n = Predict(state_, t);
  525. IterativeParsingState d = Transit<parseFlags>(state_, t, n, is, handler);
  526. // If we've finished or hit an error...
  527. if (RAPIDJSON_UNLIKELY(IsIterativeParsingCompleteState(d))) {
  528. // Report errors.
  529. if (d == IterativeParsingErrorState) {
  530. HandleError(state_, is);
  531. return false;
  532. }
  533. // Transition to the finish state.
  534. RAPIDJSON_ASSERT(d == IterativeParsingFinishState);
  535. state_ = d;
  536. // If StopWhenDone is not set...
  537. if (!(parseFlags & kParseStopWhenDoneFlag)) {
  538. // ... and extra non-whitespace data is found...
  539. SkipWhitespaceAndComments<parseFlags>(is);
  540. if (is.Peek() != '\0') {
  541. // ... this is considered an error.
  542. HandleError(state_, is);
  543. return false;
  544. }
  545. }
  546. // Success! We are done!
  547. return true;
  548. }
  549. // Transition to the new state.
  550. state_ = d;
  551. // If we parsed anything other than a delimiter, we invoked the handler, so we can return true now.
  552. if (!IsIterativeParsingDelimiterState(n))
  553. return true;
  554. }
  555. // We reached the end of file.
  556. stack_.Clear();
  557. if (state_ != IterativeParsingFinishState) {
  558. HandleError(state_, is);
  559. return false;
  560. }
  561. return true;
  562. }
  563. //! Check if token-by-token parsing JSON text is complete
  564. /*! \return Whether the JSON has been fully decoded.
  565. */
  566. RAPIDJSON_FORCEINLINE bool IterativeParseComplete() const {
  567. return IsIterativeParsingCompleteState(state_);
  568. }
  569. //! Whether a parse error has occurred in the last parsing.
  570. bool HasParseError() const { return parseResult_.IsError(); }
  571. //! Get the \ref ParseErrorCode of last parsing.
  572. ParseErrorCode GetParseErrorCode() const { return parseResult_.Code(); }
  573. //! Get the position of last parsing error in input, 0 otherwise.
  574. size_t GetErrorOffset() const { return parseResult_.Offset(); }
  575. protected:
  576. void SetParseError(ParseErrorCode code, size_t offset) { parseResult_.Set(code, offset); }
  577. private:
  578. // Prohibit copy constructor & assignment operator.
  579. GenericReader(const GenericReader&);
  580. GenericReader& operator=(const GenericReader&);
  581. void ClearStack() { stack_.Clear(); }
  582. // clear stack on any exit from ParseStream, e.g. due to exception
  583. struct ClearStackOnExit {
  584. explicit ClearStackOnExit(GenericReader& r) : r_(r) {}
  585. ~ClearStackOnExit() { r_.ClearStack(); }
  586. private:
  587. GenericReader& r_;
  588. ClearStackOnExit(const ClearStackOnExit&);
  589. ClearStackOnExit& operator=(const ClearStackOnExit&);
  590. };
  591. template<unsigned parseFlags, typename InputStream>
  592. void SkipWhitespaceAndComments(InputStream& is) {
  593. SkipWhitespace(is);
  594. if (parseFlags & kParseCommentsFlag) {
  595. while (RAPIDJSON_UNLIKELY(Consume(is, '/'))) {
  596. if (Consume(is, '*')) {
  597. while (true) {
  598. if (RAPIDJSON_UNLIKELY(is.Peek() == '\0'))
  599. RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell());
  600. else if (Consume(is, '*')) {
  601. if (Consume(is, '/'))
  602. break;
  603. }
  604. else
  605. is.Take();
  606. }
  607. }
  608. else if (RAPIDJSON_LIKELY(Consume(is, '/')))
  609. while (is.Peek() != '\0' && is.Take() != '\n') {}
  610. else
  611. RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell());
  612. SkipWhitespace(is);
  613. }
  614. }
  615. }
  616. // Parse object: { string : value, ... }
  617. template<unsigned parseFlags, typename InputStream, typename Handler>
  618. void ParseObject(InputStream& is, Handler& handler) {
  619. RAPIDJSON_ASSERT(is.Peek() == '{');
  620. is.Take(); // Skip '{'
  621. if (RAPIDJSON_UNLIKELY(!handler.StartObject()))
  622. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  623. SkipWhitespaceAndComments<parseFlags>(is);
  624. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  625. if (Consume(is, '}')) {
  626. if (RAPIDJSON_UNLIKELY(!handler.EndObject(0))) // empty object
  627. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  628. return;
  629. }
  630. for (SizeType memberCount = 0;;) {
  631. if (RAPIDJSON_UNLIKELY(is.Peek() != '"'))
  632. RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell());
  633. ParseString<parseFlags>(is, handler, true);
  634. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  635. SkipWhitespaceAndComments<parseFlags>(is);
  636. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  637. if (RAPIDJSON_UNLIKELY(!Consume(is, ':')))
  638. RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell());
  639. SkipWhitespaceAndComments<parseFlags>(is);
  640. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  641. ParseValue<parseFlags>(is, handler);
  642. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  643. SkipWhitespaceAndComments<parseFlags>(is);
  644. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  645. ++memberCount;
  646. switch (is.Peek()) {
  647. case ',':
  648. is.Take();
  649. SkipWhitespaceAndComments<parseFlags>(is);
  650. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  651. break;
  652. case '}':
  653. is.Take();
  654. if (RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount)))
  655. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  656. return;
  657. default:
  658. RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); break; // This useless break is only for making warning and coverage happy
  659. }
  660. if (parseFlags & kParseTrailingCommasFlag) {
  661. if (is.Peek() == '}') {
  662. if (RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount)))
  663. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  664. is.Take();
  665. return;
  666. }
  667. }
  668. }
  669. }
  670. // Parse array: [ value, ... ]
  671. template<unsigned parseFlags, typename InputStream, typename Handler>
  672. void ParseArray(InputStream& is, Handler& handler) {
  673. RAPIDJSON_ASSERT(is.Peek() == '[');
  674. is.Take(); // Skip '['
  675. if (RAPIDJSON_UNLIKELY(!handler.StartArray()))
  676. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  677. SkipWhitespaceAndComments<parseFlags>(is);
  678. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  679. if (Consume(is, ']')) {
  680. if (RAPIDJSON_UNLIKELY(!handler.EndArray(0))) // empty array
  681. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  682. return;
  683. }
  684. for (SizeType elementCount = 0;;) {
  685. ParseValue<parseFlags>(is, handler);
  686. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  687. ++elementCount;
  688. SkipWhitespaceAndComments<parseFlags>(is);
  689. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  690. if (Consume(is, ',')) {
  691. SkipWhitespaceAndComments<parseFlags>(is);
  692. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  693. }
  694. else if (Consume(is, ']')) {
  695. if (RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount)))
  696. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  697. return;
  698. }
  699. else
  700. RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell());
  701. if (parseFlags & kParseTrailingCommasFlag) {
  702. if (is.Peek() == ']') {
  703. if (RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount)))
  704. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  705. is.Take();
  706. return;
  707. }
  708. }
  709. }
  710. }
  711. template<unsigned parseFlags, typename InputStream, typename Handler>
  712. void ParseNull(InputStream& is, Handler& handler) {
  713. RAPIDJSON_ASSERT(is.Peek() == 'n');
  714. is.Take();
  715. if (RAPIDJSON_LIKELY(Consume(is, 'u') && Consume(is, 'l') && Consume(is, 'l'))) {
  716. if (RAPIDJSON_UNLIKELY(!handler.Null()))
  717. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  718. }
  719. else
  720. RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell());
  721. }
  722. template<unsigned parseFlags, typename InputStream, typename Handler>
  723. void ParseTrue(InputStream& is, Handler& handler) {
  724. RAPIDJSON_ASSERT(is.Peek() == 't');
  725. is.Take();
  726. if (RAPIDJSON_LIKELY(Consume(is, 'r') && Consume(is, 'u') && Consume(is, 'e'))) {
  727. if (RAPIDJSON_UNLIKELY(!handler.Bool(true)))
  728. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  729. }
  730. else
  731. RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell());
  732. }
  733. template<unsigned parseFlags, typename InputStream, typename Handler>
  734. void ParseFalse(InputStream& is, Handler& handler) {
  735. RAPIDJSON_ASSERT(is.Peek() == 'f');
  736. is.Take();
  737. if (RAPIDJSON_LIKELY(Consume(is, 'a') && Consume(is, 'l') && Consume(is, 's') && Consume(is, 'e'))) {
  738. if (RAPIDJSON_UNLIKELY(!handler.Bool(false)))
  739. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
  740. }
  741. else
  742. RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell());
  743. }
  744. template<typename InputStream>
  745. RAPIDJSON_FORCEINLINE static bool Consume(InputStream& is, typename InputStream::Ch expect) {
  746. if (RAPIDJSON_LIKELY(is.Peek() == expect)) {
  747. is.Take();
  748. return true;
  749. }
  750. else
  751. return false;
  752. }
  753. // Helper function to parse four hexadecimal digits in \uXXXX in ParseString().
  754. template<typename InputStream>
  755. unsigned ParseHex4(InputStream& is, size_t escapeOffset) {
  756. unsigned codepoint = 0;
  757. for (int i = 0; i < 4; i++) {
  758. Ch c = is.Peek();
  759. codepoint <<= 4;
  760. codepoint += static_cast<unsigned>(c);
  761. if (c >= '0' && c <= '9')
  762. codepoint -= '0';
  763. else if (c >= 'A' && c <= 'F')
  764. codepoint -= 'A' - 10;
  765. else if (c >= 'a' && c <= 'f')
  766. codepoint -= 'a' - 10;
  767. else {
  768. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorStringUnicodeEscapeInvalidHex, escapeOffset);
  769. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(0);
  770. }
  771. is.Take();
  772. }
  773. return codepoint;
  774. }
  775. template <typename CharType>
  776. class StackStream {
  777. public:
  778. typedef CharType Ch;
  779. StackStream(internal::Stack<StackAllocator>& stack) : stack_(stack), length_(0) {}
  780. RAPIDJSON_FORCEINLINE void Put(Ch c) {
  781. *stack_.template Push<Ch>() = c;
  782. ++length_;
  783. }
  784. RAPIDJSON_FORCEINLINE void* Push(SizeType count) {
  785. length_ += count;
  786. return stack_.template Push<Ch>(count);
  787. }
  788. size_t Length() const { return length_; }
  789. Ch* Pop() {
  790. return stack_.template Pop<Ch>(length_);
  791. }
  792. private:
  793. StackStream(const StackStream&);
  794. StackStream& operator=(const StackStream&);
  795. internal::Stack<StackAllocator>& stack_;
  796. SizeType length_;
  797. };
  798. // Parse string and generate String event. Different code paths for kParseInsituFlag.
  799. template<unsigned parseFlags, typename InputStream, typename Handler>
  800. void ParseString(InputStream& is, Handler& handler, bool isKey = false) {
  801. internal::StreamLocalCopy<InputStream> copy(is);
  802. InputStream& s(copy.s);
  803. RAPIDJSON_ASSERT(s.Peek() == '\"');
  804. s.Take(); // Skip '\"'
  805. bool success = false;
  806. if (parseFlags & kParseInsituFlag) {
  807. typename InputStream::Ch *head = s.PutBegin();
  808. ParseStringToStream<parseFlags, SourceEncoding, SourceEncoding>(s, s);
  809. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  810. size_t length = s.PutEnd(head) - 1;
  811. RAPIDJSON_ASSERT(length <= 0xFFFFFFFF);
  812. const typename TargetEncoding::Ch* const str = reinterpret_cast<typename TargetEncoding::Ch*>(head);
  813. success = (isKey ? handler.Key(str, SizeType(length), false) : handler.String(str, SizeType(length), false));
  814. }
  815. else {
  816. StackStream<typename TargetEncoding::Ch> stackStream(stack_);
  817. ParseStringToStream<parseFlags, SourceEncoding, TargetEncoding>(s, stackStream);
  818. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  819. SizeType length = static_cast<SizeType>(stackStream.Length()) - 1;
  820. const typename TargetEncoding::Ch* const str = stackStream.Pop();
  821. success = (isKey ? handler.Key(str, length, true) : handler.String(str, length, true));
  822. }
  823. if (RAPIDJSON_UNLIKELY(!success))
  824. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, s.Tell());
  825. }
  826. // Parse string to an output is
  827. // This function handles the prefix/suffix double quotes, escaping, and optional encoding validation.
  828. template<unsigned parseFlags, typename SEncoding, typename TEncoding, typename InputStream, typename OutputStream>
  829. RAPIDJSON_FORCEINLINE void ParseStringToStream(InputStream& is, OutputStream& os) {
  830. //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
  831. #define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
  832. static const char escape[256] = {
  833. Z16, Z16, 0, 0,'\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'/',
  834. Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0,
  835. 0, 0,'\b', 0, 0, 0,'\f', 0, 0, 0, 0, 0, 0, 0,'\n', 0,
  836. 0, 0,'\r', 0,'\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  837. Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16
  838. };
  839. #undef Z16
  840. //!@endcond
  841. for (;;) {
  842. // Scan and copy string before "\\\"" or < 0x20. This is an optional optimzation.
  843. if (!(parseFlags & kParseValidateEncodingFlag))
  844. ScanCopyUnescapedString(is, os);
  845. Ch c = is.Peek();
  846. if (RAPIDJSON_UNLIKELY(c == '\\')) { // Escape
  847. size_t escapeOffset = is.Tell(); // For invalid escaping, report the initial '\\' as error offset
  848. is.Take();
  849. Ch e = is.Peek();
  850. if ((sizeof(Ch) == 1 || unsigned(e) < 256) && RAPIDJSON_LIKELY(escape[static_cast<unsigned char>(e)])) {
  851. is.Take();
  852. os.Put(static_cast<typename TEncoding::Ch>(escape[static_cast<unsigned char>(e)]));
  853. }
  854. else if (RAPIDJSON_LIKELY(e == 'u')) { // Unicode
  855. is.Take();
  856. unsigned codepoint = ParseHex4(is, escapeOffset);
  857. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  858. if (RAPIDJSON_UNLIKELY(codepoint >= 0xD800 && codepoint <= 0xDBFF)) {
  859. // Handle UTF-16 surrogate pair
  860. if (RAPIDJSON_UNLIKELY(!Consume(is, '\\') || !Consume(is, 'u')))
  861. RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset);
  862. unsigned codepoint2 = ParseHex4(is, escapeOffset);
  863. RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
  864. if (RAPIDJSON_UNLIKELY(codepoint2 < 0xDC00 || codepoint2 > 0xDFFF))
  865. RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset);
  866. codepoint = (((codepoint - 0xD800) << 10) | (codepoint2 - 0xDC00)) + 0x10000;
  867. }
  868. TEncoding::Encode(os, codepoint);
  869. }
  870. else
  871. RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, escapeOffset);
  872. }
  873. else if (RAPIDJSON_UNLIKELY(c == '"')) { // Closing double quote
  874. is.Take();
  875. os.Put('\0'); // null-terminate the string
  876. return;
  877. }
  878. else if (RAPIDJSON_UNLIKELY(static_cast<unsigned>(c) < 0x20)) { // RFC 4627: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
  879. if (c == '\0')
  880. RAPIDJSON_PARSE_ERROR(kParseErrorStringMissQuotationMark, is.Tell());
  881. else
  882. RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, is.Tell());
  883. }
  884. else {
  885. size_t offset = is.Tell();
  886. if (RAPIDJSON_UNLIKELY((parseFlags & kParseValidateEncodingFlag ?
  887. !Transcoder<SEncoding, TEncoding>::Validate(is, os) :
  888. !Transcoder<SEncoding, TEncoding>::Transcode(is, os))))
  889. RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, offset);
  890. }
  891. }
  892. }
  893. template<typename InputStream, typename OutputStream>
  894. static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InputStream&, OutputStream&) {
  895. // Do nothing for generic version
  896. }
  897. #if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42)
  898. // StringStream -> StackStream<char>
  899. static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream<char>& os) {
  900. const char* p = is.src_;
  901. // Scan one by one until alignment (unaligned load may cross page boundary and cause crash)
  902. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  903. while (p != nextAligned)
  904. if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) {
  905. is.src_ = p;
  906. return;
  907. }
  908. else
  909. os.Put(*p++);
  910. // The rest of string using SIMD
  911. static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' };
  912. static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' };
  913. static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F };
  914. const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
  915. const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
  916. const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
  917. for (;; p += 16) {
  918. const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
  919. const __m128i t1 = _mm_cmpeq_epi8(s, dq);
  920. const __m128i t2 = _mm_cmpeq_epi8(s, bs);
  921. const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F
  922. const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
  923. unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
  924. if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
  925. SizeType length;
  926. #ifdef _MSC_VER // Find the index of first escaped
  927. unsigned long offset;
  928. _BitScanForward(&offset, r);
  929. length = offset;
  930. #else
  931. length = static_cast<SizeType>(__builtin_ffs(r) - 1);
  932. #endif
  933. if (length != 0) {
  934. char* q = reinterpret_cast<char*>(os.Push(length));
  935. for (size_t i = 0; i < length; i++)
  936. q[i] = p[i];
  937. p += length;
  938. }
  939. break;
  940. }
  941. _mm_storeu_si128(reinterpret_cast<__m128i *>(os.Push(16)), s);
  942. }
  943. is.src_ = p;
  944. }
  945. // InsituStringStream -> InsituStringStream
  946. static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) {
  947. RAPIDJSON_ASSERT(&is == &os);
  948. (void)os;
  949. if (is.src_ == is.dst_) {
  950. SkipUnescapedString(is);
  951. return;
  952. }
  953. char* p = is.src_;
  954. char *q = is.dst_;
  955. // Scan one by one until alignment (unaligned load may cross page boundary and cause crash)
  956. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  957. while (p != nextAligned)
  958. if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) {
  959. is.src_ = p;
  960. is.dst_ = q;
  961. return;
  962. }
  963. else
  964. *q++ = *p++;
  965. // The rest of string using SIMD
  966. static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' };
  967. static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' };
  968. static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F };
  969. const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
  970. const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
  971. const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
  972. for (;; p += 16, q += 16) {
  973. const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
  974. const __m128i t1 = _mm_cmpeq_epi8(s, dq);
  975. const __m128i t2 = _mm_cmpeq_epi8(s, bs);
  976. const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F
  977. const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
  978. unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
  979. if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
  980. size_t length;
  981. #ifdef _MSC_VER // Find the index of first escaped
  982. unsigned long offset;
  983. _BitScanForward(&offset, r);
  984. length = offset;
  985. #else
  986. length = static_cast<size_t>(__builtin_ffs(r) - 1);
  987. #endif
  988. for (const char* pend = p + length; p != pend; )
  989. *q++ = *p++;
  990. break;
  991. }
  992. _mm_storeu_si128(reinterpret_cast<__m128i *>(q), s);
  993. }
  994. is.src_ = p;
  995. is.dst_ = q;
  996. }
  997. // When read/write pointers are the same for insitu stream, just skip unescaped characters
  998. static RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) {
  999. RAPIDJSON_ASSERT(is.src_ == is.dst_);
  1000. char* p = is.src_;
  1001. // Scan one by one until alignment (unaligned load may cross page boundary and cause crash)
  1002. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  1003. for (; p != nextAligned; p++)
  1004. if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) {
  1005. is.src_ = is.dst_ = p;
  1006. return;
  1007. }
  1008. // The rest of string using SIMD
  1009. static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' };
  1010. static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' };
  1011. static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F };
  1012. const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
  1013. const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
  1014. const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
  1015. for (;; p += 16) {
  1016. const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
  1017. const __m128i t1 = _mm_cmpeq_epi8(s, dq);
  1018. const __m128i t2 = _mm_cmpeq_epi8(s, bs);
  1019. const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F
  1020. const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
  1021. unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
  1022. if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
  1023. size_t length;
  1024. #ifdef _MSC_VER // Find the index of first escaped
  1025. unsigned long offset;
  1026. _BitScanForward(&offset, r);
  1027. length = offset;
  1028. #else
  1029. length = static_cast<size_t>(__builtin_ffs(r) - 1);
  1030. #endif
  1031. p += length;
  1032. break;
  1033. }
  1034. }
  1035. is.src_ = is.dst_ = p;
  1036. }
  1037. #elif defined(RAPIDJSON_NEON)
  1038. // StringStream -> StackStream<char>
  1039. static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream<char>& os) {
  1040. const char* p = is.src_;
  1041. // Scan one by one until alignment (unaligned load may cross page boundary and cause crash)
  1042. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  1043. while (p != nextAligned)
  1044. if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) {
  1045. is.src_ = p;
  1046. return;
  1047. }
  1048. else
  1049. os.Put(*p++);
  1050. // The rest of string using SIMD
  1051. const uint8x16_t s0 = vmovq_n_u8('"');
  1052. const uint8x16_t s1 = vmovq_n_u8('\\');
  1053. const uint8x16_t s2 = vmovq_n_u8('\b');
  1054. const uint8x16_t s3 = vmovq_n_u8(32);
  1055. for (;; p += 16) {
  1056. const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p));
  1057. uint8x16_t x = vceqq_u8(s, s0);
  1058. x = vorrq_u8(x, vceqq_u8(s, s1));
  1059. x = vorrq_u8(x, vceqq_u8(s, s2));
  1060. x = vorrq_u8(x, vcltq_u8(s, s3));
  1061. x = vrev64q_u8(x); // Rev in 64
  1062. uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract
  1063. uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract
  1064. SizeType length = 0;
  1065. bool escaped = false;
  1066. if (low == 0) {
  1067. if (high != 0) {
  1068. uint32_t lz = RAPIDJSON_CLZLL(high);
  1069. length = 8 + (lz >> 3);
  1070. escaped = true;
  1071. }
  1072. } else {
  1073. uint32_t lz = RAPIDJSON_CLZLL(low);
  1074. length = lz >> 3;
  1075. escaped = true;
  1076. }
  1077. if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped
  1078. if (length != 0) {
  1079. char* q = reinterpret_cast<char*>(os.Push(length));
  1080. for (size_t i = 0; i < length; i++)
  1081. q[i] = p[i];
  1082. p += length;
  1083. }
  1084. break;
  1085. }
  1086. vst1q_u8(reinterpret_cast<uint8_t *>(os.Push(16)), s);
  1087. }
  1088. is.src_ = p;
  1089. }
  1090. // InsituStringStream -> InsituStringStream
  1091. static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) {
  1092. RAPIDJSON_ASSERT(&is == &os);
  1093. (void)os;
  1094. if (is.src_ == is.dst_) {
  1095. SkipUnescapedString(is);
  1096. return;
  1097. }
  1098. char* p = is.src_;
  1099. char *q = is.dst_;
  1100. // Scan one by one until alignment (unaligned load may cross page boundary and cause crash)
  1101. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  1102. while (p != nextAligned)
  1103. if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) {
  1104. is.src_ = p;
  1105. is.dst_ = q;
  1106. return;
  1107. }
  1108. else
  1109. *q++ = *p++;
  1110. // The rest of string using SIMD
  1111. const uint8x16_t s0 = vmovq_n_u8('"');
  1112. const uint8x16_t s1 = vmovq_n_u8('\\');
  1113. const uint8x16_t s2 = vmovq_n_u8('\b');
  1114. const uint8x16_t s3 = vmovq_n_u8(32);
  1115. for (;; p += 16, q += 16) {
  1116. const uint8x16_t s = vld1q_u8(reinterpret_cast<uint8_t *>(p));
  1117. uint8x16_t x = vceqq_u8(s, s0);
  1118. x = vorrq_u8(x, vceqq_u8(s, s1));
  1119. x = vorrq_u8(x, vceqq_u8(s, s2));
  1120. x = vorrq_u8(x, vcltq_u8(s, s3));
  1121. x = vrev64q_u8(x); // Rev in 64
  1122. uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract
  1123. uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract
  1124. SizeType length = 0;
  1125. bool escaped = false;
  1126. if (low == 0) {
  1127. if (high != 0) {
  1128. uint32_t lz = RAPIDJSON_CLZLL(high);
  1129. length = 8 + (lz >> 3);
  1130. escaped = true;
  1131. }
  1132. } else {
  1133. uint32_t lz = RAPIDJSON_CLZLL(low);
  1134. length = lz >> 3;
  1135. escaped = true;
  1136. }
  1137. if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped
  1138. for (const char* pend = p + length; p != pend; ) {
  1139. *q++ = *p++;
  1140. }
  1141. break;
  1142. }
  1143. vst1q_u8(reinterpret_cast<uint8_t *>(q), s);
  1144. }
  1145. is.src_ = p;
  1146. is.dst_ = q;
  1147. }
  1148. // When read/write pointers are the same for insitu stream, just skip unescaped characters
  1149. static RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) {
  1150. RAPIDJSON_ASSERT(is.src_ == is.dst_);
  1151. char* p = is.src_;
  1152. // Scan one by one until alignment (unaligned load may cross page boundary and cause crash)
  1153. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  1154. for (; p != nextAligned; p++)
  1155. if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) {
  1156. is.src_ = is.dst_ = p;
  1157. return;
  1158. }
  1159. // The rest of string using SIMD
  1160. const uint8x16_t s0 = vmovq_n_u8('"');
  1161. const uint8x16_t s1 = vmovq_n_u8('\\');
  1162. const uint8x16_t s2 = vmovq_n_u8('\b');
  1163. const uint8x16_t s3 = vmovq_n_u8(32);
  1164. for (;; p += 16) {
  1165. const uint8x16_t s = vld1q_u8(reinterpret_cast<uint8_t *>(p));
  1166. uint8x16_t x = vceqq_u8(s, s0);
  1167. x = vorrq_u8(x, vceqq_u8(s, s1));
  1168. x = vorrq_u8(x, vceqq_u8(s, s2));
  1169. x = vorrq_u8(x, vcltq_u8(s, s3));
  1170. x = vrev64q_u8(x); // Rev in 64
  1171. uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract
  1172. uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract
  1173. if (low == 0) {
  1174. if (high != 0) {
  1175. uint32_t lz = RAPIDJSON_CLZLL(high);
  1176. p += 8 + (lz >> 3);
  1177. break;
  1178. }
  1179. } else {
  1180. uint32_t lz = RAPIDJSON_CLZLL(low);
  1181. p += lz >> 3;
  1182. break;
  1183. }
  1184. }
  1185. is.src_ = is.dst_ = p;
  1186. }
  1187. #endif // RAPIDJSON_NEON
  1188. template<typename InputStream, bool backup, bool pushOnTake>
  1189. class NumberStream;
  1190. template<typename InputStream>
  1191. class NumberStream<InputStream, false, false> {
  1192. public:
  1193. typedef typename InputStream::Ch Ch;
  1194. NumberStream(GenericReader& reader, InputStream& s) : is(s) { (void)reader; }
  1195. RAPIDJSON_FORCEINLINE Ch Peek() const { return is.Peek(); }
  1196. RAPIDJSON_FORCEINLINE Ch TakePush() { return is.Take(); }
  1197. RAPIDJSON_FORCEINLINE Ch Take() { return is.Take(); }
  1198. RAPIDJSON_FORCEINLINE void Push(char) {}
  1199. size_t Tell() { return is.Tell(); }
  1200. size_t Length() { return 0; }
  1201. const char* Pop() { return 0; }
  1202. protected:
  1203. NumberStream& operator=(const NumberStream&);
  1204. InputStream& is;
  1205. };
  1206. template<typename InputStream>
  1207. class NumberStream<InputStream, true, false> : public NumberStream<InputStream, false, false> {
  1208. typedef NumberStream<InputStream, false, false> Base;
  1209. public:
  1210. NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is), stackStream(reader.stack_) {}
  1211. RAPIDJSON_FORCEINLINE Ch TakePush() {
  1212. stackStream.Put(static_cast<char>(Base::is.Peek()));
  1213. return Base::is.Take();
  1214. }
  1215. RAPIDJSON_FORCEINLINE void Push(char c) {
  1216. stackStream.Put(c);
  1217. }
  1218. size_t Length() { return stackStream.Length(); }
  1219. const char* Pop() {
  1220. stackStream.Put('\0');
  1221. return stackStream.Pop();
  1222. }
  1223. private:
  1224. StackStream<char> stackStream;
  1225. };
  1226. template<typename InputStream>
  1227. class NumberStream<InputStream, true, true> : public NumberStream<InputStream, true, false> {
  1228. typedef NumberStream<InputStream, true, false> Base;
  1229. public:
  1230. NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is) {}
  1231. RAPIDJSON_FORCEINLINE Ch Take() { return Base::TakePush(); }
  1232. };
  1233. template<unsigned parseFlags, typename InputStream, typename Handler>
  1234. void ParseNumber(InputStream& is, Handler& handler) {
  1235. internal::StreamLocalCopy<InputStream> copy(is);
  1236. NumberStream<InputStream,
  1237. ((parseFlags & kParseNumbersAsStringsFlag) != 0) ?
  1238. ((parseFlags & kParseInsituFlag) == 0) :
  1239. ((parseFlags & kParseFullPrecisionFlag) != 0),
  1240. (parseFlags & kParseNumbersAsStringsFlag) != 0 &&
  1241. (parseFlags & kParseInsituFlag) == 0> s(*this, copy.s);
  1242. size_t startOffset = s.Tell();
  1243. double d = 0.0;
  1244. bool useNanOrInf = false;
  1245. // Parse minus
  1246. bool minus = Consume(s, '-');
  1247. // Parse int: zero / ( digit1-9 *DIGIT )
  1248. unsigned i = 0;
  1249. uint64_t i64 = 0;
  1250. bool use64bit = false;
  1251. int significandDigit = 0;
  1252. if (RAPIDJSON_UNLIKELY(s.Peek() == '0')) {
  1253. i = 0;
  1254. s.TakePush();
  1255. }
  1256. else if (RAPIDJSON_LIKELY(s.Peek() >= '1' && s.Peek() <= '9')) {
  1257. i = static_cast<unsigned>(s.TakePush() - '0');
  1258. if (minus)
  1259. while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
  1260. if (RAPIDJSON_UNLIKELY(i >= 214748364)) { // 2^31 = 2147483648
  1261. if (RAPIDJSON_LIKELY(i != 214748364 || s.Peek() > '8')) {
  1262. i64 = i;
  1263. use64bit = true;
  1264. break;
  1265. }
  1266. }
  1267. i = i * 10 + static_cast<unsigned>(s.TakePush() - '0');
  1268. significandDigit++;
  1269. }
  1270. else
  1271. while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
  1272. if (RAPIDJSON_UNLIKELY(i >= 429496729)) { // 2^32 - 1 = 4294967295
  1273. if (RAPIDJSON_LIKELY(i != 429496729 || s.Peek() > '5')) {
  1274. i64 = i;
  1275. use64bit = true;
  1276. break;
  1277. }
  1278. }
  1279. i = i * 10 + static_cast<unsigned>(s.TakePush() - '0');
  1280. significandDigit++;
  1281. }
  1282. }
  1283. // Parse NaN or Infinity here
  1284. else if ((parseFlags & kParseNanAndInfFlag) && RAPIDJSON_LIKELY((s.Peek() == 'I' || s.Peek() == 'N'))) {
  1285. if (Consume(s, 'N')) {
  1286. if (Consume(s, 'a') && Consume(s, 'N')) {
  1287. d = std::numeric_limits<double>::quiet_NaN();
  1288. useNanOrInf = true;
  1289. }
  1290. }
  1291. else if (RAPIDJSON_LIKELY(Consume(s, 'I'))) {
  1292. if (Consume(s, 'n') && Consume(s, 'f')) {
  1293. d = (minus ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity());
  1294. useNanOrInf = true;
  1295. if (RAPIDJSON_UNLIKELY(s.Peek() == 'i' && !(Consume(s, 'i') && Consume(s, 'n')
  1296. && Consume(s, 'i') && Consume(s, 't') && Consume(s, 'y')))) {
  1297. RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell());
  1298. }
  1299. }
  1300. }
  1301. if (RAPIDJSON_UNLIKELY(!useNanOrInf)) {
  1302. RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell());
  1303. }
  1304. }
  1305. else
  1306. RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell());
  1307. // Parse 64bit int
  1308. bool useDouble = false;
  1309. if (use64bit) {
  1310. if (minus)
  1311. while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
  1312. if (RAPIDJSON_UNLIKELY(i64 >= RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC))) // 2^63 = 9223372036854775808
  1313. if (RAPIDJSON_LIKELY(i64 != RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC) || s.Peek() > '8')) {
  1314. d = static_cast<double>(i64);
  1315. useDouble = true;
  1316. break;
  1317. }
  1318. i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
  1319. significandDigit++;
  1320. }
  1321. else
  1322. while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
  1323. if (RAPIDJSON_UNLIKELY(i64 >= RAPIDJSON_UINT64_C2(0x19999999, 0x99999999))) // 2^64 - 1 = 18446744073709551615
  1324. if (RAPIDJSON_LIKELY(i64 != RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || s.Peek() > '5')) {
  1325. d = static_cast<double>(i64);
  1326. useDouble = true;
  1327. break;
  1328. }
  1329. i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
  1330. significandDigit++;
  1331. }
  1332. }
  1333. // Force double for big integer
  1334. if (useDouble) {
  1335. while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
  1336. d = d * 10 + (s.TakePush() - '0');
  1337. }
  1338. }
  1339. // Parse frac = decimal-point 1*DIGIT
  1340. int expFrac = 0;
  1341. size_t decimalPosition;
  1342. if (Consume(s, '.')) {
  1343. decimalPosition = s.Length();
  1344. if (RAPIDJSON_UNLIKELY(!(s.Peek() >= '0' && s.Peek() <= '9')))
  1345. RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissFraction, s.Tell());
  1346. if (!useDouble) {
  1347. #if RAPIDJSON_64BIT
  1348. // Use i64 to store significand in 64-bit architecture
  1349. if (!use64bit)
  1350. i64 = i;
  1351. while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
  1352. if (i64 > RAPIDJSON_UINT64_C2(0x1FFFFF, 0xFFFFFFFF)) // 2^53 - 1 for fast path
  1353. break;
  1354. else {
  1355. i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
  1356. --expFrac;
  1357. if (i64 != 0)
  1358. significandDigit++;
  1359. }
  1360. }
  1361. d = static_cast<double>(i64);
  1362. #else
  1363. // Use double to store significand in 32-bit architecture
  1364. d = static_cast<double>(use64bit ? i64 : i);
  1365. #endif
  1366. useDouble = true;
  1367. }
  1368. while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
  1369. if (significandDigit < 17) {
  1370. d = d * 10.0 + (s.TakePush() - '0');
  1371. --expFrac;
  1372. if (RAPIDJSON_LIKELY(d > 0.0))
  1373. significandDigit++;
  1374. }
  1375. else
  1376. s.TakePush();
  1377. }
  1378. }
  1379. else
  1380. decimalPosition = s.Length(); // decimal position at the end of integer.
  1381. // Parse exp = e [ minus / plus ] 1*DIGIT
  1382. int exp = 0;
  1383. if (Consume(s, 'e') || Consume(s, 'E')) {
  1384. if (!useDouble) {
  1385. d = static_cast<double>(use64bit ? i64 : i);
  1386. useDouble = true;
  1387. }
  1388. bool expMinus = false;
  1389. if (Consume(s, '+'))
  1390. ;
  1391. else if (Consume(s, '-'))
  1392. expMinus = true;
  1393. if (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
  1394. exp = static_cast<int>(s.Take() - '0');
  1395. if (expMinus) {
  1396. // (exp + expFrac) must not underflow int => we're detecting when -exp gets
  1397. // dangerously close to INT_MIN (a pessimistic next digit 9 would push it into
  1398. // underflow territory):
  1399. //
  1400. // -(exp * 10 + 9) + expFrac >= INT_MIN
  1401. // <=> exp <= (expFrac - INT_MIN - 9) / 10
  1402. RAPIDJSON_ASSERT(expFrac <= 0);
  1403. int maxExp = (expFrac + 2147483639) / 10;
  1404. while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
  1405. exp = exp * 10 + static_cast<int>(s.Take() - '0');
  1406. if (RAPIDJSON_UNLIKELY(exp > maxExp)) {
  1407. while (RAPIDJSON_UNLIKELY(s.Peek() >= '0' && s.Peek() <= '9')) // Consume the rest of exponent
  1408. s.Take();
  1409. }
  1410. }
  1411. }
  1412. else { // positive exp
  1413. int maxExp = 308 - expFrac;
  1414. while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
  1415. exp = exp * 10 + static_cast<int>(s.Take() - '0');
  1416. if (RAPIDJSON_UNLIKELY(exp > maxExp))
  1417. RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset);
  1418. }
  1419. }
  1420. }
  1421. else
  1422. RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissExponent, s.Tell());
  1423. if (expMinus)
  1424. exp = -exp;
  1425. }
  1426. // Finish parsing, call event according to the type of number.
  1427. bool cont = true;
  1428. if (parseFlags & kParseNumbersAsStringsFlag) {
  1429. if (parseFlags & kParseInsituFlag) {
  1430. s.Pop(); // Pop stack no matter if it will be used or not.
  1431. typename InputStream::Ch* head = is.PutBegin();
  1432. const size_t length = s.Tell() - startOffset;
  1433. RAPIDJSON_ASSERT(length <= 0xFFFFFFFF);
  1434. // unable to insert the \0 character here, it will erase the comma after this number
  1435. const typename TargetEncoding::Ch* const str = reinterpret_cast<typename TargetEncoding::Ch*>(head);
  1436. cont = handler.RawNumber(str, SizeType(length), false);
  1437. }
  1438. else {
  1439. SizeType numCharsToCopy = static_cast<SizeType>(s.Length());
  1440. StringStream srcStream(s.Pop());
  1441. StackStream<typename TargetEncoding::Ch> dstStream(stack_);
  1442. while (numCharsToCopy--) {
  1443. Transcoder<UTF8<>, TargetEncoding>::Transcode(srcStream, dstStream);
  1444. }
  1445. dstStream.Put('\0');
  1446. const typename TargetEncoding::Ch* str = dstStream.Pop();
  1447. const SizeType length = static_cast<SizeType>(dstStream.Length()) - 1;
  1448. cont = handler.RawNumber(str, SizeType(length), true);
  1449. }
  1450. }
  1451. else {
  1452. size_t length = s.Length();
  1453. const char* decimal = s.Pop(); // Pop stack no matter if it will be used or not.
  1454. if (useDouble) {
  1455. int p = exp + expFrac;
  1456. if (parseFlags & kParseFullPrecisionFlag)
  1457. d = internal::StrtodFullPrecision(d, p, decimal, length, decimalPosition, exp);
  1458. else
  1459. d = internal::StrtodNormalPrecision(d, p);
  1460. // Use > max, instead of == inf, to fix bogus warning -Wfloat-equal
  1461. if (d > (std::numeric_limits<double>::max)()) {
  1462. // Overflow
  1463. // TODO: internal::StrtodX should report overflow (or underflow)
  1464. RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset);
  1465. }
  1466. cont = handler.Double(minus ? -d : d);
  1467. }
  1468. else if (useNanOrInf) {
  1469. cont = handler.Double(d);
  1470. }
  1471. else {
  1472. if (use64bit) {
  1473. if (minus)
  1474. cont = handler.Int64(static_cast<int64_t>(~i64 + 1));
  1475. else
  1476. cont = handler.Uint64(i64);
  1477. }
  1478. else {
  1479. if (minus)
  1480. cont = handler.Int(static_cast<int32_t>(~i + 1));
  1481. else
  1482. cont = handler.Uint(i);
  1483. }
  1484. }
  1485. }
  1486. if (RAPIDJSON_UNLIKELY(!cont))
  1487. RAPIDJSON_PARSE_ERROR(kParseErrorTermination, startOffset);
  1488. }
  1489. // Parse any JSON value
  1490. template<unsigned parseFlags, typename InputStream, typename Handler>
  1491. void ParseValue(InputStream& is, Handler& handler) {
  1492. switch (is.Peek()) {
  1493. case 'n': ParseNull <parseFlags>(is, handler); break;
  1494. case 't': ParseTrue <parseFlags>(is, handler); break;
  1495. case 'f': ParseFalse <parseFlags>(is, handler); break;
  1496. case '"': ParseString<parseFlags>(is, handler); break;
  1497. case '{': ParseObject<parseFlags>(is, handler); break;
  1498. case '[': ParseArray <parseFlags>(is, handler); break;
  1499. default :
  1500. ParseNumber<parseFlags>(is, handler);
  1501. break;
  1502. }
  1503. }
  1504. // Iterative Parsing
  1505. // States
  1506. enum IterativeParsingState {
  1507. IterativeParsingFinishState = 0, // sink states at top
  1508. IterativeParsingErrorState, // sink states at top
  1509. IterativeParsingStartState,
  1510. // Object states
  1511. IterativeParsingObjectInitialState,
  1512. IterativeParsingMemberKeyState,
  1513. IterativeParsingMemberValueState,
  1514. IterativeParsingObjectFinishState,
  1515. // Array states
  1516. IterativeParsingArrayInitialState,
  1517. IterativeParsingElementState,
  1518. IterativeParsingArrayFinishState,
  1519. // Single value state
  1520. IterativeParsingValueState,
  1521. // Delimiter states (at bottom)
  1522. IterativeParsingElementDelimiterState,
  1523. IterativeParsingMemberDelimiterState,
  1524. IterativeParsingKeyValueDelimiterState,
  1525. cIterativeParsingStateCount
  1526. };
  1527. // Tokens
  1528. enum Token {
  1529. LeftBracketToken = 0,
  1530. RightBracketToken,
  1531. LeftCurlyBracketToken,
  1532. RightCurlyBracketToken,
  1533. CommaToken,
  1534. ColonToken,
  1535. StringToken,
  1536. FalseToken,
  1537. TrueToken,
  1538. NullToken,
  1539. NumberToken,
  1540. kTokenCount
  1541. };
  1542. RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) const {
  1543. //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
  1544. #define N NumberToken
  1545. #define N16 N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N
  1546. // Maps from ASCII to Token
  1547. static const unsigned char tokenMap[256] = {
  1548. N16, // 00~0F
  1549. N16, // 10~1F
  1550. N, N, StringToken, N, N, N, N, N, N, N, N, N, CommaToken, N, N, N, // 20~2F
  1551. N, N, N, N, N, N, N, N, N, N, ColonToken, N, N, N, N, N, // 30~3F
  1552. N16, // 40~4F
  1553. N, N, N, N, N, N, N, N, N, N, N, LeftBracketToken, N, RightBracketToken, N, N, // 50~5F
  1554. N, N, N, N, N, N, FalseToken, N, N, N, N, N, N, N, NullToken, N, // 60~6F
  1555. N, N, N, N, TrueToken, N, N, N, N, N, N, LeftCurlyBracketToken, N, RightCurlyBracketToken, N, N, // 70~7F
  1556. N16, N16, N16, N16, N16, N16, N16, N16 // 80~FF
  1557. };
  1558. #undef N
  1559. #undef N16
  1560. //!@endcond
  1561. if (sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256)
  1562. return static_cast<Token>(tokenMap[static_cast<unsigned char>(c)]);
  1563. else
  1564. return NumberToken;
  1565. }
  1566. RAPIDJSON_FORCEINLINE IterativeParsingState Predict(IterativeParsingState state, Token token) const {
  1567. // current state x one lookahead token -> new state
  1568. static const char G[cIterativeParsingStateCount][kTokenCount] = {
  1569. // Finish(sink state)
  1570. {
  1571. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1572. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1573. IterativeParsingErrorState
  1574. },
  1575. // Error(sink state)
  1576. {
  1577. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1578. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1579. IterativeParsingErrorState
  1580. },
  1581. // Start
  1582. {
  1583. IterativeParsingArrayInitialState, // Left bracket
  1584. IterativeParsingErrorState, // Right bracket
  1585. IterativeParsingObjectInitialState, // Left curly bracket
  1586. IterativeParsingErrorState, // Right curly bracket
  1587. IterativeParsingErrorState, // Comma
  1588. IterativeParsingErrorState, // Colon
  1589. IterativeParsingValueState, // String
  1590. IterativeParsingValueState, // False
  1591. IterativeParsingValueState, // True
  1592. IterativeParsingValueState, // Null
  1593. IterativeParsingValueState // Number
  1594. },
  1595. // ObjectInitial
  1596. {
  1597. IterativeParsingErrorState, // Left bracket
  1598. IterativeParsingErrorState, // Right bracket
  1599. IterativeParsingErrorState, // Left curly bracket
  1600. IterativeParsingObjectFinishState, // Right curly bracket
  1601. IterativeParsingErrorState, // Comma
  1602. IterativeParsingErrorState, // Colon
  1603. IterativeParsingMemberKeyState, // String
  1604. IterativeParsingErrorState, // False
  1605. IterativeParsingErrorState, // True
  1606. IterativeParsingErrorState, // Null
  1607. IterativeParsingErrorState // Number
  1608. },
  1609. // MemberKey
  1610. {
  1611. IterativeParsingErrorState, // Left bracket
  1612. IterativeParsingErrorState, // Right bracket
  1613. IterativeParsingErrorState, // Left curly bracket
  1614. IterativeParsingErrorState, // Right curly bracket
  1615. IterativeParsingErrorState, // Comma
  1616. IterativeParsingKeyValueDelimiterState, // Colon
  1617. IterativeParsingErrorState, // String
  1618. IterativeParsingErrorState, // False
  1619. IterativeParsingErrorState, // True
  1620. IterativeParsingErrorState, // Null
  1621. IterativeParsingErrorState // Number
  1622. },
  1623. // MemberValue
  1624. {
  1625. IterativeParsingErrorState, // Left bracket
  1626. IterativeParsingErrorState, // Right bracket
  1627. IterativeParsingErrorState, // Left curly bracket
  1628. IterativeParsingObjectFinishState, // Right curly bracket
  1629. IterativeParsingMemberDelimiterState, // Comma
  1630. IterativeParsingErrorState, // Colon
  1631. IterativeParsingErrorState, // String
  1632. IterativeParsingErrorState, // False
  1633. IterativeParsingErrorState, // True
  1634. IterativeParsingErrorState, // Null
  1635. IterativeParsingErrorState // Number
  1636. },
  1637. // ObjectFinish(sink state)
  1638. {
  1639. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1640. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1641. IterativeParsingErrorState
  1642. },
  1643. // ArrayInitial
  1644. {
  1645. IterativeParsingArrayInitialState, // Left bracket(push Element state)
  1646. IterativeParsingArrayFinishState, // Right bracket
  1647. IterativeParsingObjectInitialState, // Left curly bracket(push Element state)
  1648. IterativeParsingErrorState, // Right curly bracket
  1649. IterativeParsingErrorState, // Comma
  1650. IterativeParsingErrorState, // Colon
  1651. IterativeParsingElementState, // String
  1652. IterativeParsingElementState, // False
  1653. IterativeParsingElementState, // True
  1654. IterativeParsingElementState, // Null
  1655. IterativeParsingElementState // Number
  1656. },
  1657. // Element
  1658. {
  1659. IterativeParsingErrorState, // Left bracket
  1660. IterativeParsingArrayFinishState, // Right bracket
  1661. IterativeParsingErrorState, // Left curly bracket
  1662. IterativeParsingErrorState, // Right curly bracket
  1663. IterativeParsingElementDelimiterState, // Comma
  1664. IterativeParsingErrorState, // Colon
  1665. IterativeParsingErrorState, // String
  1666. IterativeParsingErrorState, // False
  1667. IterativeParsingErrorState, // True
  1668. IterativeParsingErrorState, // Null
  1669. IterativeParsingErrorState // Number
  1670. },
  1671. // ArrayFinish(sink state)
  1672. {
  1673. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1674. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1675. IterativeParsingErrorState
  1676. },
  1677. // Single Value (sink state)
  1678. {
  1679. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1680. IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
  1681. IterativeParsingErrorState
  1682. },
  1683. // ElementDelimiter
  1684. {
  1685. IterativeParsingArrayInitialState, // Left bracket(push Element state)
  1686. IterativeParsingArrayFinishState, // Right bracket
  1687. IterativeParsingObjectInitialState, // Left curly bracket(push Element state)
  1688. IterativeParsingErrorState, // Right curly bracket
  1689. IterativeParsingErrorState, // Comma
  1690. IterativeParsingErrorState, // Colon
  1691. IterativeParsingElementState, // String
  1692. IterativeParsingElementState, // False
  1693. IterativeParsingElementState, // True
  1694. IterativeParsingElementState, // Null
  1695. IterativeParsingElementState // Number
  1696. },
  1697. // MemberDelimiter
  1698. {
  1699. IterativeParsingErrorState, // Left bracket
  1700. IterativeParsingErrorState, // Right bracket
  1701. IterativeParsingErrorState, // Left curly bracket
  1702. IterativeParsingObjectFinishState, // Right curly bracket
  1703. IterativeParsingErrorState, // Comma
  1704. IterativeParsingErrorState, // Colon
  1705. IterativeParsingMemberKeyState, // String
  1706. IterativeParsingErrorState, // False
  1707. IterativeParsingErrorState, // True
  1708. IterativeParsingErrorState, // Null
  1709. IterativeParsingErrorState // Number
  1710. },
  1711. // KeyValueDelimiter
  1712. {
  1713. IterativeParsingArrayInitialState, // Left bracket(push MemberValue state)
  1714. IterativeParsingErrorState, // Right bracket
  1715. IterativeParsingObjectInitialState, // Left curly bracket(push MemberValue state)
  1716. IterativeParsingErrorState, // Right curly bracket
  1717. IterativeParsingErrorState, // Comma
  1718. IterativeParsingErrorState, // Colon
  1719. IterativeParsingMemberValueState, // String
  1720. IterativeParsingMemberValueState, // False
  1721. IterativeParsingMemberValueState, // True
  1722. IterativeParsingMemberValueState, // Null
  1723. IterativeParsingMemberValueState // Number
  1724. },
  1725. }; // End of G
  1726. return static_cast<IterativeParsingState>(G[state][token]);
  1727. }
  1728. // Make an advance in the token stream and state based on the candidate destination state which was returned by Transit().
  1729. // May return a new state on state pop.
  1730. template <unsigned parseFlags, typename InputStream, typename Handler>
  1731. RAPIDJSON_FORCEINLINE IterativeParsingState Transit(IterativeParsingState src, Token token, IterativeParsingState dst, InputStream& is, Handler& handler) {
  1732. (void)token;
  1733. switch (dst) {
  1734. case IterativeParsingErrorState:
  1735. return dst;
  1736. case IterativeParsingObjectInitialState:
  1737. case IterativeParsingArrayInitialState:
  1738. {
  1739. // Push the state(Element or MemeberValue) if we are nested in another array or value of member.
  1740. // In this way we can get the correct state on ObjectFinish or ArrayFinish by frame pop.
  1741. IterativeParsingState n = src;
  1742. if (src == IterativeParsingArrayInitialState || src == IterativeParsingElementDelimiterState)
  1743. n = IterativeParsingElementState;
  1744. else if (src == IterativeParsingKeyValueDelimiterState)
  1745. n = IterativeParsingMemberValueState;
  1746. // Push current state.
  1747. *stack_.template Push<SizeType>(1) = n;
  1748. // Initialize and push the member/element count.
  1749. *stack_.template Push<SizeType>(1) = 0;
  1750. // Call handler
  1751. bool hr = (dst == IterativeParsingObjectInitialState) ? handler.StartObject() : handler.StartArray();
  1752. // On handler short circuits the parsing.
  1753. if (!hr) {
  1754. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
  1755. return IterativeParsingErrorState;
  1756. }
  1757. else {
  1758. is.Take();
  1759. return dst;
  1760. }
  1761. }
  1762. case IterativeParsingMemberKeyState:
  1763. ParseString<parseFlags>(is, handler, true);
  1764. if (HasParseError())
  1765. return IterativeParsingErrorState;
  1766. else
  1767. return dst;
  1768. case IterativeParsingKeyValueDelimiterState:
  1769. RAPIDJSON_ASSERT(token == ColonToken);
  1770. is.Take();
  1771. return dst;
  1772. case IterativeParsingMemberValueState:
  1773. // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
  1774. ParseValue<parseFlags>(is, handler);
  1775. if (HasParseError()) {
  1776. return IterativeParsingErrorState;
  1777. }
  1778. return dst;
  1779. case IterativeParsingElementState:
  1780. // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
  1781. ParseValue<parseFlags>(is, handler);
  1782. if (HasParseError()) {
  1783. return IterativeParsingErrorState;
  1784. }
  1785. return dst;
  1786. case IterativeParsingMemberDelimiterState:
  1787. case IterativeParsingElementDelimiterState:
  1788. is.Take();
  1789. // Update member/element count.
  1790. *stack_.template Top<SizeType>() = *stack_.template Top<SizeType>() + 1;
  1791. return dst;
  1792. case IterativeParsingObjectFinishState:
  1793. {
  1794. // Transit from delimiter is only allowed when trailing commas are enabled
  1795. if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingMemberDelimiterState) {
  1796. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorObjectMissName, is.Tell());
  1797. return IterativeParsingErrorState;
  1798. }
  1799. // Get member count.
  1800. SizeType c = *stack_.template Pop<SizeType>(1);
  1801. // If the object is not empty, count the last member.
  1802. if (src == IterativeParsingMemberValueState)
  1803. ++c;
  1804. // Restore the state.
  1805. IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1));
  1806. // Transit to Finish state if this is the topmost scope.
  1807. if (n == IterativeParsingStartState)
  1808. n = IterativeParsingFinishState;
  1809. // Call handler
  1810. bool hr = handler.EndObject(c);
  1811. // On handler short circuits the parsing.
  1812. if (!hr) {
  1813. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
  1814. return IterativeParsingErrorState;
  1815. }
  1816. else {
  1817. is.Take();
  1818. return n;
  1819. }
  1820. }
  1821. case IterativeParsingArrayFinishState:
  1822. {
  1823. // Transit from delimiter is only allowed when trailing commas are enabled
  1824. if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingElementDelimiterState) {
  1825. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorValueInvalid, is.Tell());
  1826. return IterativeParsingErrorState;
  1827. }
  1828. // Get element count.
  1829. SizeType c = *stack_.template Pop<SizeType>(1);
  1830. // If the array is not empty, count the last element.
  1831. if (src == IterativeParsingElementState)
  1832. ++c;
  1833. // Restore the state.
  1834. IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1));
  1835. // Transit to Finish state if this is the topmost scope.
  1836. if (n == IterativeParsingStartState)
  1837. n = IterativeParsingFinishState;
  1838. // Call handler
  1839. bool hr = handler.EndArray(c);
  1840. // On handler short circuits the parsing.
  1841. if (!hr) {
  1842. RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
  1843. return IterativeParsingErrorState;
  1844. }
  1845. else {
  1846. is.Take();
  1847. return n;
  1848. }
  1849. }
  1850. default:
  1851. // This branch is for IterativeParsingValueState actually.
  1852. // Use `default:` rather than
  1853. // `case IterativeParsingValueState:` is for code coverage.
  1854. // The IterativeParsingStartState is not enumerated in this switch-case.
  1855. // It is impossible for that case. And it can be caught by following assertion.
  1856. // The IterativeParsingFinishState is not enumerated in this switch-case either.
  1857. // It is a "derivative" state which cannot triggered from Predict() directly.
  1858. // Therefore it cannot happen here. And it can be caught by following assertion.
  1859. RAPIDJSON_ASSERT(dst == IterativeParsingValueState);
  1860. // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
  1861. ParseValue<parseFlags>(is, handler);
  1862. if (HasParseError()) {
  1863. return IterativeParsingErrorState;
  1864. }
  1865. return IterativeParsingFinishState;
  1866. }
  1867. }
  1868. template <typename InputStream>
  1869. void HandleError(IterativeParsingState src, InputStream& is) {
  1870. if (HasParseError()) {
  1871. // Error flag has been set.
  1872. return;
  1873. }
  1874. switch (src) {
  1875. case IterativeParsingStartState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentEmpty, is.Tell()); return;
  1876. case IterativeParsingFinishState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentRootNotSingular, is.Tell()); return;
  1877. case IterativeParsingObjectInitialState:
  1878. case IterativeParsingMemberDelimiterState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); return;
  1879. case IterativeParsingMemberKeyState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); return;
  1880. case IterativeParsingMemberValueState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); return;
  1881. case IterativeParsingKeyValueDelimiterState:
  1882. case IterativeParsingArrayInitialState:
  1883. case IterativeParsingElementDelimiterState: RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); return;
  1884. default: RAPIDJSON_ASSERT(src == IterativeParsingElementState); RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell()); return;
  1885. }
  1886. }
  1887. RAPIDJSON_FORCEINLINE bool IsIterativeParsingDelimiterState(IterativeParsingState s) const {
  1888. return s >= IterativeParsingElementDelimiterState;
  1889. }
  1890. RAPIDJSON_FORCEINLINE bool IsIterativeParsingCompleteState(IterativeParsingState s) const {
  1891. return s <= IterativeParsingErrorState;
  1892. }
  1893. template <unsigned parseFlags, typename InputStream, typename Handler>
  1894. ParseResult IterativeParse(InputStream& is, Handler& handler) {
  1895. parseResult_.Clear();
  1896. ClearStackOnExit scope(*this);
  1897. IterativeParsingState state = IterativeParsingStartState;
  1898. SkipWhitespaceAndComments<parseFlags>(is);
  1899. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
  1900. while (is.Peek() != '\0') {
  1901. Token t = Tokenize(is.Peek());
  1902. IterativeParsingState n = Predict(state, t);
  1903. IterativeParsingState d = Transit<parseFlags>(state, t, n, is, handler);
  1904. if (d == IterativeParsingErrorState) {
  1905. HandleError(state, is);
  1906. break;
  1907. }
  1908. state = d;
  1909. // Do not further consume streams if a root JSON has been parsed.
  1910. if ((parseFlags & kParseStopWhenDoneFlag) && state == IterativeParsingFinishState)
  1911. break;
  1912. SkipWhitespaceAndComments<parseFlags>(is);
  1913. RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
  1914. }
  1915. // Handle the end of file.
  1916. if (state != IterativeParsingFinishState)
  1917. HandleError(state, is);
  1918. return parseResult_;
  1919. }
  1920. static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string.
  1921. internal::Stack<StackAllocator> stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing.
  1922. ParseResult parseResult_;
  1923. IterativeParsingState state_;
  1924. }; // class GenericReader
  1925. //! Reader with UTF8 encoding and default allocator.
  1926. typedef GenericReader<UTF8<>, UTF8<> > Reader;
  1927. RAPIDJSON_NAMESPACE_END
  1928. #if defined(__clang__) || defined(_MSC_VER)
  1929. RAPIDJSON_DIAG_POP
  1930. #endif
  1931. #ifdef __GNUC__
  1932. RAPIDJSON_DIAG_POP
  1933. #endif
  1934. #endif // RAPIDJSON_READER_H_