reader.h 91 KB

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