readertest.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893
  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. #include "unittest.h"
  15. #include "rapidjson/reader.h"
  16. #include "rapidjson/internal/dtoa.h"
  17. #include "rapidjson/internal/itoa.h"
  18. #include "rapidjson/memorystream.h"
  19. #include <limits>
  20. using namespace rapidjson;
  21. RAPIDJSON_DIAG_PUSH
  22. #ifdef __GNUC__
  23. RAPIDJSON_DIAG_OFF(effc++)
  24. RAPIDJSON_DIAG_OFF(float-equal)
  25. RAPIDJSON_DIAG_OFF(missing-noreturn)
  26. #if __GNUC__ >= 7
  27. RAPIDJSON_DIAG_OFF(dangling-else)
  28. #endif
  29. #endif // __GNUC__
  30. #ifdef __clang__
  31. RAPIDJSON_DIAG_OFF(variadic-macros)
  32. RAPIDJSON_DIAG_OFF(c++98-compat-pedantic)
  33. #endif
  34. template<bool expect>
  35. struct ParseBoolHandler : BaseReaderHandler<UTF8<>, ParseBoolHandler<expect> > {
  36. ParseBoolHandler() : step_(0) {}
  37. bool Default() { ADD_FAILURE(); return false; }
  38. // gcc 4.8.x generates warning in EXPECT_EQ(bool, bool) on this gtest version.
  39. // Workaround with EXPECT_TRUE().
  40. bool Bool(bool b) { /*EXPECT_EQ(expect, b); */EXPECT_TRUE(expect == b); ++step_; return true; }
  41. unsigned step_;
  42. };
  43. TEST(Reader, ParseTrue) {
  44. StringStream s("true");
  45. ParseBoolHandler<true> h;
  46. Reader reader;
  47. reader.Parse(s, h);
  48. EXPECT_EQ(1u, h.step_);
  49. }
  50. TEST(Reader, ParseFalse) {
  51. StringStream s("false");
  52. ParseBoolHandler<false> h;
  53. Reader reader;
  54. reader.Parse(s, h);
  55. EXPECT_EQ(1u, h.step_);
  56. }
  57. struct ParseIntHandler : BaseReaderHandler<UTF8<>, ParseIntHandler> {
  58. ParseIntHandler() : step_(0), actual_() {}
  59. bool Default() { ADD_FAILURE(); return false; }
  60. bool Int(int i) { actual_ = i; step_++; return true; }
  61. unsigned step_;
  62. int actual_;
  63. };
  64. struct ParseUintHandler : BaseReaderHandler<UTF8<>, ParseUintHandler> {
  65. ParseUintHandler() : step_(0), actual_() {}
  66. bool Default() { ADD_FAILURE(); return false; }
  67. bool Uint(unsigned i) { actual_ = i; step_++; return true; }
  68. unsigned step_;
  69. unsigned actual_;
  70. };
  71. struct ParseInt64Handler : BaseReaderHandler<UTF8<>, ParseInt64Handler> {
  72. ParseInt64Handler() : step_(0), actual_() {}
  73. bool Default() { ADD_FAILURE(); return false; }
  74. bool Int64(int64_t i) { actual_ = i; step_++; return true; }
  75. unsigned step_;
  76. int64_t actual_;
  77. };
  78. struct ParseUint64Handler : BaseReaderHandler<UTF8<>, ParseUint64Handler> {
  79. ParseUint64Handler() : step_(0), actual_() {}
  80. bool Default() { ADD_FAILURE(); return false; }
  81. bool Uint64(uint64_t i) { actual_ = i; step_++; return true; }
  82. unsigned step_;
  83. uint64_t actual_;
  84. };
  85. struct ParseDoubleHandler : BaseReaderHandler<UTF8<>, ParseDoubleHandler> {
  86. ParseDoubleHandler() : step_(0), actual_() {}
  87. bool Default() { ADD_FAILURE(); return false; }
  88. bool Double(double d) { actual_ = d; step_++; return true; }
  89. unsigned step_;
  90. double actual_;
  91. };
  92. TEST(Reader, ParseNumber_Integer) {
  93. #define TEST_INTEGER(Handler, str, x) \
  94. { \
  95. StringStream s(str); \
  96. Handler h; \
  97. Reader reader; \
  98. reader.Parse(s, h); \
  99. EXPECT_EQ(1u, h.step_); \
  100. EXPECT_EQ(x, h.actual_); \
  101. }
  102. TEST_INTEGER(ParseUintHandler, "0", 0u);
  103. TEST_INTEGER(ParseUintHandler, "123", 123u);
  104. TEST_INTEGER(ParseUintHandler, "2147483648", 2147483648u); // 2^31 - 1 (cannot be stored in int)
  105. TEST_INTEGER(ParseUintHandler, "4294967295", 4294967295u);
  106. TEST_INTEGER(ParseIntHandler, "-123", -123);
  107. TEST_INTEGER(ParseIntHandler, "-2147483648", static_cast<int32_t>(0x80000000)); // -2^31 (min of int)
  108. TEST_INTEGER(ParseUint64Handler, "4294967296", RAPIDJSON_UINT64_C2(1, 0)); // 2^32 (max of unsigned + 1, force to use uint64_t)
  109. TEST_INTEGER(ParseUint64Handler, "18446744073709551615", RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFFF)); // 2^64 - 1 (max of uint64_t)
  110. TEST_INTEGER(ParseInt64Handler, "-2147483649", static_cast<int64_t>(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x7FFFFFFF))); // -2^31 -1 (min of int - 1, force to use int64_t)
  111. TEST_INTEGER(ParseInt64Handler, "-9223372036854775808", static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0x00000000))); // -2^63 (min of int64_t)
  112. // Random test for uint32_t/int32_t
  113. {
  114. union {
  115. uint32_t u;
  116. int32_t i;
  117. }u;
  118. Random r;
  119. for (unsigned i = 0; i < 100000; i++) {
  120. u.u = r();
  121. char buffer[32];
  122. *internal::u32toa(u.u, buffer) = '\0';
  123. TEST_INTEGER(ParseUintHandler, buffer, u.u);
  124. if (u.i < 0) {
  125. *internal::i32toa(u.i, buffer) = '\0';
  126. TEST_INTEGER(ParseIntHandler, buffer, u.i);
  127. }
  128. }
  129. }
  130. // Random test for uint64_t/int64_t
  131. {
  132. union {
  133. uint64_t u;
  134. int64_t i;
  135. }u;
  136. Random r;
  137. for (unsigned i = 0; i < 100000; i++) {
  138. u.u = uint64_t(r()) << 32;
  139. u.u |= r();
  140. char buffer[32];
  141. if (u.u > uint64_t(4294967295u)) {
  142. *internal::u64toa(u.u, buffer) = '\0';
  143. TEST_INTEGER(ParseUint64Handler, buffer, u.u);
  144. }
  145. if (u.i < -int64_t(2147483648u)) {
  146. *internal::i64toa(u.i, buffer) = '\0';
  147. TEST_INTEGER(ParseInt64Handler, buffer, u.i);
  148. }
  149. }
  150. }
  151. #undef TEST_INTEGER
  152. }
  153. template<bool fullPrecision>
  154. static void TestParseDouble() {
  155. #define TEST_DOUBLE(fullPrecision, str, x) \
  156. { \
  157. StringStream s(str); \
  158. ParseDoubleHandler h; \
  159. Reader reader; \
  160. ASSERT_EQ(kParseErrorNone, reader.Parse<fullPrecision ? kParseFullPrecisionFlag : 0>(s, h).Code()); \
  161. EXPECT_EQ(1u, h.step_); \
  162. internal::Double e(x), a(h.actual_); \
  163. if (fullPrecision) { \
  164. EXPECT_EQ(e.Uint64Value(), a.Uint64Value()); \
  165. if (e.Uint64Value() != a.Uint64Value()) \
  166. printf(" String: %s\n Actual: %.17g\nExpected: %.17g\n", str, h.actual_, x); \
  167. } \
  168. else { \
  169. EXPECT_EQ(e.Sign(), a.Sign()); /* for 0.0 != -0.0 */ \
  170. EXPECT_DOUBLE_EQ(x, h.actual_); \
  171. } \
  172. }
  173. TEST_DOUBLE(fullPrecision, "0.0", 0.0);
  174. TEST_DOUBLE(fullPrecision, "-0.0", -0.0); // For checking issue #289
  175. TEST_DOUBLE(fullPrecision, "1.0", 1.0);
  176. TEST_DOUBLE(fullPrecision, "-1.0", -1.0);
  177. TEST_DOUBLE(fullPrecision, "1.5", 1.5);
  178. TEST_DOUBLE(fullPrecision, "-1.5", -1.5);
  179. TEST_DOUBLE(fullPrecision, "3.1416", 3.1416);
  180. TEST_DOUBLE(fullPrecision, "1E10", 1E10);
  181. TEST_DOUBLE(fullPrecision, "1e10", 1e10);
  182. TEST_DOUBLE(fullPrecision, "1E+10", 1E+10);
  183. TEST_DOUBLE(fullPrecision, "1E-10", 1E-10);
  184. TEST_DOUBLE(fullPrecision, "-1E10", -1E10);
  185. TEST_DOUBLE(fullPrecision, "-1e10", -1e10);
  186. TEST_DOUBLE(fullPrecision, "-1E+10", -1E+10);
  187. TEST_DOUBLE(fullPrecision, "-1E-10", -1E-10);
  188. TEST_DOUBLE(fullPrecision, "1.234E+10", 1.234E+10);
  189. TEST_DOUBLE(fullPrecision, "1.234E-10", 1.234E-10);
  190. TEST_DOUBLE(fullPrecision, "1.79769e+308", 1.79769e+308);
  191. TEST_DOUBLE(fullPrecision, "2.22507e-308", 2.22507e-308);
  192. TEST_DOUBLE(fullPrecision, "-1.79769e+308", -1.79769e+308);
  193. TEST_DOUBLE(fullPrecision, "-2.22507e-308", -2.22507e-308);
  194. TEST_DOUBLE(fullPrecision, "4.9406564584124654e-324", 4.9406564584124654e-324); // minimum denormal
  195. TEST_DOUBLE(fullPrecision, "2.2250738585072009e-308", 2.2250738585072009e-308); // Max subnormal double
  196. TEST_DOUBLE(fullPrecision, "2.2250738585072014e-308", 2.2250738585072014e-308); // Min normal positive double
  197. TEST_DOUBLE(fullPrecision, "1.7976931348623157e+308", 1.7976931348623157e+308); // Max double
  198. TEST_DOUBLE(fullPrecision, "1e-10000", 0.0); // must underflow
  199. TEST_DOUBLE(fullPrecision, "18446744073709551616", 18446744073709551616.0); // 2^64 (max of uint64_t + 1, force to use double)
  200. TEST_DOUBLE(fullPrecision, "-9223372036854775809", -9223372036854775809.0); // -2^63 - 1(min of int64_t + 1, force to use double)
  201. TEST_DOUBLE(fullPrecision, "0.9868011474609375", 0.9868011474609375); // https://github.com/miloyip/rapidjson/issues/120
  202. TEST_DOUBLE(fullPrecision, "123e34", 123e34); // Fast Path Cases In Disguise
  203. TEST_DOUBLE(fullPrecision, "45913141877270640000.0", 45913141877270640000.0);
  204. TEST_DOUBLE(fullPrecision, "2.2250738585072011e-308", 2.2250738585072011e-308); // http://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/
  205. TEST_DOUBLE(fullPrecision, "1e-00011111111111", 0.0); // Issue #313
  206. TEST_DOUBLE(fullPrecision, "-1e-00011111111111", -0.0);
  207. TEST_DOUBLE(fullPrecision, "1e-214748363", 0.0); // Maximum supported negative exponent
  208. TEST_DOUBLE(fullPrecision, "1e-214748364", 0.0);
  209. TEST_DOUBLE(fullPrecision, "1e-21474836311", 0.0);
  210. TEST_DOUBLE(fullPrecision, "0.017976931348623157e+310", 1.7976931348623157e+308); // Max double in another form
  211. // Since
  212. // abs((2^-1022 - 2^-1074) - 2.2250738585072012e-308) = 3.109754131239141401123495768877590405345064751974375599... x 10^-324
  213. // abs((2^-1022) - 2.2250738585072012e-308) = 1.830902327173324040642192159804623318305533274168872044... x 10 ^ -324
  214. // So 2.2250738585072012e-308 should round to 2^-1022 = 2.2250738585072014e-308
  215. TEST_DOUBLE(fullPrecision, "2.2250738585072012e-308", 2.2250738585072014e-308); // http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/
  216. // More closer to normal/subnormal boundary
  217. // boundary = 2^-1022 - 2^-1075 = 2.225073858507201136057409796709131975934819546351645648... x 10^-308
  218. TEST_DOUBLE(fullPrecision, "2.22507385850720113605740979670913197593481954635164564e-308", 2.2250738585072009e-308);
  219. TEST_DOUBLE(fullPrecision, "2.22507385850720113605740979670913197593481954635164565e-308", 2.2250738585072014e-308);
  220. // 1.0 is in (1.0 - 2^-54, 1.0 + 2^-53)
  221. // 1.0 - 2^-54 = 0.999999999999999944488848768742172978818416595458984375
  222. TEST_DOUBLE(fullPrecision, "0.999999999999999944488848768742172978818416595458984375", 1.0); // round to even
  223. TEST_DOUBLE(fullPrecision, "0.999999999999999944488848768742172978818416595458984374", 0.99999999999999989); // previous double
  224. TEST_DOUBLE(fullPrecision, "0.999999999999999944488848768742172978818416595458984376", 1.0); // next double
  225. // 1.0 + 2^-53 = 1.00000000000000011102230246251565404236316680908203125
  226. TEST_DOUBLE(fullPrecision, "1.00000000000000011102230246251565404236316680908203125", 1.0); // round to even
  227. TEST_DOUBLE(fullPrecision, "1.00000000000000011102230246251565404236316680908203124", 1.0); // previous double
  228. TEST_DOUBLE(fullPrecision, "1.00000000000000011102230246251565404236316680908203126", 1.00000000000000022); // next double
  229. // Numbers from https://github.com/floitsch/double-conversion/blob/master/test/cctest/test-strtod.cc
  230. TEST_DOUBLE(fullPrecision, "72057594037927928.0", 72057594037927928.0);
  231. TEST_DOUBLE(fullPrecision, "72057594037927936.0", 72057594037927936.0);
  232. TEST_DOUBLE(fullPrecision, "72057594037927932.0", 72057594037927936.0);
  233. TEST_DOUBLE(fullPrecision, "7205759403792793199999e-5", 72057594037927928.0);
  234. TEST_DOUBLE(fullPrecision, "7205759403792793200001e-5", 72057594037927936.0);
  235. TEST_DOUBLE(fullPrecision, "9223372036854774784.0", 9223372036854774784.0);
  236. TEST_DOUBLE(fullPrecision, "9223372036854775808.0", 9223372036854775808.0);
  237. TEST_DOUBLE(fullPrecision, "9223372036854775296.0", 9223372036854775808.0);
  238. TEST_DOUBLE(fullPrecision, "922337203685477529599999e-5", 9223372036854774784.0);
  239. TEST_DOUBLE(fullPrecision, "922337203685477529600001e-5", 9223372036854775808.0);
  240. TEST_DOUBLE(fullPrecision, "10141204801825834086073718800384", 10141204801825834086073718800384.0);
  241. TEST_DOUBLE(fullPrecision, "10141204801825835211973625643008", 10141204801825835211973625643008.0);
  242. TEST_DOUBLE(fullPrecision, "10141204801825834649023672221696", 10141204801825835211973625643008.0);
  243. TEST_DOUBLE(fullPrecision, "1014120480182583464902367222169599999e-5", 10141204801825834086073718800384.0);
  244. TEST_DOUBLE(fullPrecision, "1014120480182583464902367222169600001e-5", 10141204801825835211973625643008.0);
  245. TEST_DOUBLE(fullPrecision, "5708990770823838890407843763683279797179383808", 5708990770823838890407843763683279797179383808.0);
  246. TEST_DOUBLE(fullPrecision, "5708990770823839524233143877797980545530986496", 5708990770823839524233143877797980545530986496.0);
  247. TEST_DOUBLE(fullPrecision, "5708990770823839207320493820740630171355185152", 5708990770823839524233143877797980545530986496.0);
  248. TEST_DOUBLE(fullPrecision, "5708990770823839207320493820740630171355185151999e-3", 5708990770823838890407843763683279797179383808.0);
  249. TEST_DOUBLE(fullPrecision, "5708990770823839207320493820740630171355185152001e-3", 5708990770823839524233143877797980545530986496.0);
  250. {
  251. char n1e308[310]; // '1' followed by 308 '0'
  252. n1e308[0] = '1';
  253. for (int i = 1; i < 309; i++)
  254. n1e308[i] = '0';
  255. n1e308[309] = '\0';
  256. TEST_DOUBLE(fullPrecision, n1e308, 1E308);
  257. }
  258. // Cover trimming
  259. TEST_DOUBLE(fullPrecision,
  260. "2.22507385850720113605740979670913197593481954635164564802342610972482222202107694551652952390813508"
  261. "7914149158913039621106870086438694594645527657207407820621743379988141063267329253552286881372149012"
  262. "9811224514518898490572223072852551331557550159143974763979834118019993239625482890171070818506906306"
  263. "6665599493827577257201576306269066333264756530000924588831643303777979186961204949739037782970490505"
  264. "1080609940730262937128958950003583799967207254304360284078895771796150945516748243471030702609144621"
  265. "5722898802581825451803257070188608721131280795122334262883686223215037756666225039825343359745688844"
  266. "2390026549819838548794829220689472168983109969836584681402285424333066033985088644580400103493397042"
  267. "7567186443383770486037861622771738545623065874679014086723327636718751234567890123456789012345678901"
  268. "e-308",
  269. 2.2250738585072014e-308);
  270. {
  271. static const unsigned count = 100; // Tested with 1000000 locally
  272. Random r;
  273. Reader reader; // Reusing reader to prevent heap allocation
  274. // Exhaustively test different exponents with random significant
  275. for (uint64_t exp = 0; exp < 2047; exp++) {
  276. ;
  277. for (unsigned i = 0; i < count; i++) {
  278. // Need to call r() in two statements for cross-platform coherent sequence.
  279. uint64_t u = (exp << 52) | uint64_t(r() & 0x000FFFFF) << 32;
  280. u |= uint64_t(r());
  281. internal::Double d = internal::Double(u);
  282. char buffer[32];
  283. *internal::dtoa(d.Value(), buffer) = '\0';
  284. StringStream s(buffer);
  285. ParseDoubleHandler h;
  286. ASSERT_EQ(kParseErrorNone, reader.Parse<fullPrecision ? kParseFullPrecisionFlag : 0>(s, h).Code());
  287. EXPECT_EQ(1u, h.step_);
  288. internal::Double a(h.actual_);
  289. if (fullPrecision) {
  290. EXPECT_EQ(d.Uint64Value(), a.Uint64Value());
  291. if (d.Uint64Value() != a.Uint64Value())
  292. printf(" String: %s\n Actual: %.17g\nExpected: %.17g\n", buffer, h.actual_, d.Value());
  293. }
  294. else {
  295. EXPECT_EQ(d.Sign(), a.Sign()); // for 0.0 != -0.0
  296. EXPECT_DOUBLE_EQ(d.Value(), h.actual_);
  297. }
  298. }
  299. }
  300. }
  301. // Issue #340
  302. TEST_DOUBLE(fullPrecision, "7.450580596923828e-9", 7.450580596923828e-9);
  303. {
  304. internal::Double d(1.0);
  305. for (int i = 0; i < 324; i++) {
  306. char buffer[32];
  307. *internal::dtoa(d.Value(), buffer) = '\0';
  308. StringStream s(buffer);
  309. ParseDoubleHandler h;
  310. Reader reader;
  311. ASSERT_EQ(kParseErrorNone, reader.Parse<fullPrecision ? kParseFullPrecisionFlag : 0>(s, h).Code());
  312. EXPECT_EQ(1u, h.step_);
  313. internal::Double a(h.actual_);
  314. if (fullPrecision) {
  315. EXPECT_EQ(d.Uint64Value(), a.Uint64Value());
  316. if (d.Uint64Value() != a.Uint64Value())
  317. printf(" String: %s\n Actual: %.17g\nExpected: %.17g\n", buffer, h.actual_, d.Value());
  318. }
  319. else {
  320. EXPECT_EQ(d.Sign(), a.Sign()); // for 0.0 != -0.0
  321. EXPECT_DOUBLE_EQ(d.Value(), h.actual_);
  322. }
  323. d = d.Value() * 0.5;
  324. }
  325. }
  326. #undef TEST_DOUBLE
  327. }
  328. TEST(Reader, ParseNumber_NormalPrecisionDouble) {
  329. TestParseDouble<false>();
  330. }
  331. TEST(Reader, ParseNumber_FullPrecisionDouble) {
  332. TestParseDouble<true>();
  333. }
  334. TEST(Reader, ParseNumber_NormalPrecisionError) {
  335. static unsigned count = 1000000;
  336. Random r;
  337. double ulpSum = 0.0;
  338. double ulpMax = 0.0;
  339. for (unsigned i = 0; i < count; i++) {
  340. internal::Double e, a;
  341. do {
  342. // Need to call r() in two statements for cross-platform coherent sequence.
  343. uint64_t u = uint64_t(r()) << 32;
  344. u |= uint64_t(r());
  345. e = u;
  346. } while (e.IsNan() || e.IsInf() || !e.IsNormal());
  347. char buffer[32];
  348. *internal::dtoa(e.Value(), buffer) = '\0';
  349. StringStream s(buffer);
  350. ParseDoubleHandler h;
  351. Reader reader;
  352. ASSERT_EQ(kParseErrorNone, reader.Parse(s, h).Code());
  353. EXPECT_EQ(1u, h.step_);
  354. a = h.actual_;
  355. uint64_t bias1 = e.ToBias();
  356. uint64_t bias2 = a.ToBias();
  357. double ulp = static_cast<double>(bias1 >= bias2 ? bias1 - bias2 : bias2 - bias1);
  358. ulpMax = std::max(ulpMax, ulp);
  359. ulpSum += ulp;
  360. }
  361. printf("ULP Average = %g, Max = %g \n", ulpSum / count, ulpMax);
  362. }
  363. TEST(Reader, ParseNumber_Error) {
  364. #define TEST_NUMBER_ERROR(errorCode, str, errorOffset, streamPos) \
  365. { \
  366. char buffer[1001]; \
  367. sprintf(buffer, "%s", str); \
  368. InsituStringStream s(buffer); \
  369. BaseReaderHandler<> h; \
  370. Reader reader; \
  371. EXPECT_FALSE(reader.Parse(s, h)); \
  372. EXPECT_EQ(errorCode, reader.GetParseErrorCode());\
  373. EXPECT_EQ(errorOffset, reader.GetErrorOffset());\
  374. EXPECT_EQ(streamPos, s.Tell());\
  375. }
  376. // Number too big to be stored in double.
  377. {
  378. char n1e309[311]; // '1' followed by 309 '0'
  379. n1e309[0] = '1';
  380. for (int i = 1; i < 310; i++)
  381. n1e309[i] = '0';
  382. n1e309[310] = '\0';
  383. TEST_NUMBER_ERROR(kParseErrorNumberTooBig, n1e309, 0, 309);
  384. }
  385. TEST_NUMBER_ERROR(kParseErrorNumberTooBig, "1e309", 0, 5);
  386. // Miss fraction part in number.
  387. TEST_NUMBER_ERROR(kParseErrorNumberMissFraction, "1.", 2, 2);
  388. TEST_NUMBER_ERROR(kParseErrorNumberMissFraction, "1.a", 2, 2);
  389. // Miss exponent in number.
  390. TEST_NUMBER_ERROR(kParseErrorNumberMissExponent, "1e", 2, 2);
  391. TEST_NUMBER_ERROR(kParseErrorNumberMissExponent, "1e_", 2, 2);
  392. #undef TEST_NUMBER_ERROR
  393. }
  394. template <typename Encoding>
  395. struct ParseStringHandler : BaseReaderHandler<Encoding, ParseStringHandler<Encoding> > {
  396. ParseStringHandler() : str_(0), length_(0), copy_() {}
  397. ~ParseStringHandler() { EXPECT_TRUE(str_ != 0); if (copy_) free(const_cast<typename Encoding::Ch*>(str_)); }
  398. ParseStringHandler(const ParseStringHandler&);
  399. ParseStringHandler& operator=(const ParseStringHandler&);
  400. bool Default() { ADD_FAILURE(); return false; }
  401. bool String(const typename Encoding::Ch* str, size_t length, bool copy) {
  402. EXPECT_EQ(0, str_);
  403. if (copy) {
  404. str_ = static_cast<typename Encoding::Ch*>(malloc((length + 1) * sizeof(typename Encoding::Ch)));
  405. memcpy(const_cast<typename Encoding::Ch*>(str_), str, (length + 1) * sizeof(typename Encoding::Ch));
  406. }
  407. else
  408. str_ = str;
  409. length_ = length;
  410. copy_ = copy;
  411. return true;
  412. }
  413. const typename Encoding::Ch* str_;
  414. size_t length_;
  415. bool copy_;
  416. };
  417. TEST(Reader, ParseString) {
  418. #define TEST_STRING(Encoding, e, x) \
  419. { \
  420. Encoding::Ch* buffer = StrDup(x); \
  421. GenericInsituStringStream<Encoding> is(buffer); \
  422. ParseStringHandler<Encoding> h; \
  423. GenericReader<Encoding, Encoding> reader; \
  424. reader.Parse<kParseInsituFlag | kParseValidateEncodingFlag>(is, h); \
  425. EXPECT_EQ(0, StrCmp<Encoding::Ch>(e, h.str_)); \
  426. EXPECT_EQ(StrLen(e), h.length_); \
  427. free(buffer); \
  428. GenericStringStream<Encoding> s(x); \
  429. ParseStringHandler<Encoding> h2; \
  430. GenericReader<Encoding, Encoding> reader2; \
  431. reader2.Parse(s, h2); \
  432. EXPECT_EQ(0, StrCmp<Encoding::Ch>(e, h2.str_)); \
  433. EXPECT_EQ(StrLen(e), h2.length_); \
  434. }
  435. // String constant L"\xXX" can only specify character code in bytes, which is not endianness-neutral.
  436. // And old compiler does not support u"" and U"" string literal. So here specify string literal by array of Ch.
  437. // In addition, GCC 4.8 generates -Wnarrowing warnings when character code >= 128 are assigned to signed integer types.
  438. // Therefore, utype is added for declaring unsigned array, and then cast it to Encoding::Ch.
  439. #define ARRAY(...) { __VA_ARGS__ }
  440. #define TEST_STRINGARRAY(Encoding, utype, array, x) \
  441. { \
  442. static const utype ue[] = array; \
  443. static const Encoding::Ch* e = reinterpret_cast<const Encoding::Ch *>(&ue[0]); \
  444. TEST_STRING(Encoding, e, x); \
  445. }
  446. #define TEST_STRINGARRAY2(Encoding, utype, earray, xarray) \
  447. { \
  448. static const utype ue[] = earray; \
  449. static const utype xe[] = xarray; \
  450. static const Encoding::Ch* e = reinterpret_cast<const Encoding::Ch *>(&ue[0]); \
  451. static const Encoding::Ch* x = reinterpret_cast<const Encoding::Ch *>(&xe[0]); \
  452. TEST_STRING(Encoding, e, x); \
  453. }
  454. TEST_STRING(UTF8<>, "", "\"\"");
  455. TEST_STRING(UTF8<>, "Hello", "\"Hello\"");
  456. TEST_STRING(UTF8<>, "Hello\nWorld", "\"Hello\\nWorld\"");
  457. TEST_STRING(UTF8<>, "\"\\/\b\f\n\r\t", "\"\\\"\\\\/\\b\\f\\n\\r\\t\"");
  458. TEST_STRING(UTF8<>, "\x24", "\"\\u0024\""); // Dollar sign U+0024
  459. TEST_STRING(UTF8<>, "\xC2\xA2", "\"\\u00A2\""); // Cents sign U+00A2
  460. TEST_STRING(UTF8<>, "\xE2\x82\xAC", "\"\\u20AC\""); // Euro sign U+20AC
  461. TEST_STRING(UTF8<>, "\xF0\x9D\x84\x9E", "\"\\uD834\\uDD1E\""); // G clef sign U+1D11E
  462. // UTF16
  463. TEST_STRING(UTF16<>, L"", L"\"\"");
  464. TEST_STRING(UTF16<>, L"Hello", L"\"Hello\"");
  465. TEST_STRING(UTF16<>, L"Hello\nWorld", L"\"Hello\\nWorld\"");
  466. TEST_STRING(UTF16<>, L"\"\\/\b\f\n\r\t", L"\"\\\"\\\\/\\b\\f\\n\\r\\t\"");
  467. TEST_STRINGARRAY(UTF16<>, wchar_t, ARRAY(0x0024, 0x0000), L"\"\\u0024\"");
  468. TEST_STRINGARRAY(UTF16<>, wchar_t, ARRAY(0x00A2, 0x0000), L"\"\\u00A2\""); // Cents sign U+00A2
  469. TEST_STRINGARRAY(UTF16<>, wchar_t, ARRAY(0x20AC, 0x0000), L"\"\\u20AC\""); // Euro sign U+20AC
  470. TEST_STRINGARRAY(UTF16<>, wchar_t, ARRAY(0xD834, 0xDD1E, 0x0000), L"\"\\uD834\\uDD1E\""); // G clef sign U+1D11E
  471. // UTF32
  472. TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY('\0'), ARRAY('\"', '\"', '\0'));
  473. TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY('H', 'e', 'l', 'l', 'o', '\0'), ARRAY('\"', 'H', 'e', 'l', 'l', 'o', '\"', '\0'));
  474. TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY('H', 'e', 'l', 'l', 'o', '\n', 'W', 'o', 'r', 'l', 'd', '\0'), ARRAY('\"', 'H', 'e', 'l', 'l', 'o', '\\', 'n', 'W', 'o', 'r', 'l', 'd', '\"', '\0'));
  475. TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY('\"', '\\', '/', '\b', '\f', '\n', '\r', '\t', '\0'), ARRAY('\"', '\\', '\"', '\\', '\\', '/', '\\', 'b', '\\', 'f', '\\', 'n', '\\', 'r', '\\', 't', '\"', '\0'));
  476. TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY(0x00024, 0x0000), ARRAY('\"', '\\', 'u', '0', '0', '2', '4', '\"', '\0'));
  477. TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY(0x000A2, 0x0000), ARRAY('\"', '\\', 'u', '0', '0', 'A', '2', '\"', '\0')); // Cents sign U+00A2
  478. TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY(0x020AC, 0x0000), ARRAY('\"', '\\', 'u', '2', '0', 'A', 'C', '\"', '\0')); // Euro sign U+20AC
  479. TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY(0x1D11E, 0x0000), ARRAY('\"', '\\', 'u', 'D', '8', '3', '4', '\\', 'u', 'D', 'D', '1', 'E', '\"', '\0')); // G clef sign U+1D11E
  480. #undef TEST_STRINGARRAY
  481. #undef ARRAY
  482. #undef TEST_STRING
  483. // Support of null character in string
  484. {
  485. StringStream s("\"Hello\\u0000World\"");
  486. const char e[] = "Hello\0World";
  487. ParseStringHandler<UTF8<> > h;
  488. Reader reader;
  489. reader.Parse(s, h);
  490. EXPECT_EQ(0, memcmp(e, h.str_, h.length_ + 1));
  491. EXPECT_EQ(11u, h.length_);
  492. }
  493. }
  494. TEST(Reader, ParseString_Transcoding) {
  495. const char* x = "\"Hello\"";
  496. const wchar_t* e = L"Hello";
  497. GenericStringStream<UTF8<> > is(x);
  498. GenericReader<UTF8<>, UTF16<> > reader;
  499. ParseStringHandler<UTF16<> > h;
  500. reader.Parse(is, h);
  501. EXPECT_EQ(0, StrCmp<UTF16<>::Ch>(e, h.str_));
  502. EXPECT_EQ(StrLen(e), h.length_);
  503. }
  504. TEST(Reader, ParseString_TranscodingWithValidation) {
  505. const char* x = "\"Hello\"";
  506. const wchar_t* e = L"Hello";
  507. GenericStringStream<UTF8<> > is(x);
  508. GenericReader<UTF8<>, UTF16<> > reader;
  509. ParseStringHandler<UTF16<> > h;
  510. reader.Parse<kParseValidateEncodingFlag>(is, h);
  511. EXPECT_EQ(0, StrCmp<UTF16<>::Ch>(e, h.str_));
  512. EXPECT_EQ(StrLen(e), h.length_);
  513. }
  514. TEST(Reader, ParseString_NonDestructive) {
  515. StringStream s("\"Hello\\nWorld\"");
  516. ParseStringHandler<UTF8<> > h;
  517. Reader reader;
  518. reader.Parse(s, h);
  519. EXPECT_EQ(0, StrCmp("Hello\nWorld", h.str_));
  520. EXPECT_EQ(11u, h.length_);
  521. }
  522. template <typename Encoding>
  523. ParseErrorCode TestString(const typename Encoding::Ch* str) {
  524. GenericStringStream<Encoding> s(str);
  525. BaseReaderHandler<Encoding> h;
  526. GenericReader<Encoding, Encoding> reader;
  527. reader.template Parse<kParseValidateEncodingFlag>(s, h);
  528. return reader.GetParseErrorCode();
  529. }
  530. TEST(Reader, ParseString_Error) {
  531. #define TEST_STRING_ERROR(errorCode, str, errorOffset, streamPos)\
  532. {\
  533. GenericStringStream<UTF8<> > s(str);\
  534. BaseReaderHandler<UTF8<> > h;\
  535. GenericReader<UTF8<> , UTF8<> > reader;\
  536. reader.Parse<kParseValidateEncodingFlag>(s, h);\
  537. EXPECT_EQ(errorCode, reader.GetParseErrorCode());\
  538. EXPECT_EQ(errorOffset, reader.GetErrorOffset());\
  539. EXPECT_EQ(streamPos, s.Tell());\
  540. }
  541. #define ARRAY(...) { __VA_ARGS__ }
  542. #define TEST_STRINGENCODING_ERROR(Encoding, TargetEncoding, utype, array) \
  543. { \
  544. static const utype ue[] = array; \
  545. static const Encoding::Ch* e = reinterpret_cast<const Encoding::Ch *>(&ue[0]); \
  546. EXPECT_EQ(kParseErrorStringInvalidEncoding, TestString<Encoding>(e));\
  547. /* decode error */\
  548. GenericStringStream<Encoding> s(e);\
  549. BaseReaderHandler<TargetEncoding> h;\
  550. GenericReader<Encoding, TargetEncoding> reader;\
  551. reader.Parse(s, h);\
  552. EXPECT_EQ(kParseErrorStringInvalidEncoding, reader.GetParseErrorCode());\
  553. }
  554. // Invalid escape character in string.
  555. TEST_STRING_ERROR(kParseErrorStringEscapeInvalid, "[\"\\a\"]", 2, 3);
  556. // Incorrect hex digit after \\u escape in string.
  557. TEST_STRING_ERROR(kParseErrorStringUnicodeEscapeInvalidHex, "[\"\\uABCG\"]", 2, 7);
  558. // Quotation in \\u escape in string (Issue #288)
  559. TEST_STRING_ERROR(kParseErrorStringUnicodeEscapeInvalidHex, "[\"\\uaaa\"]", 2, 7);
  560. TEST_STRING_ERROR(kParseErrorStringUnicodeEscapeInvalidHex, "[\"\\uD800\\uFFF\"]", 2, 13);
  561. // The surrogate pair in string is invalid.
  562. TEST_STRING_ERROR(kParseErrorStringUnicodeSurrogateInvalid, "[\"\\uD800X\"]", 2, 8);
  563. TEST_STRING_ERROR(kParseErrorStringUnicodeSurrogateInvalid, "[\"\\uD800\\uFFFF\"]", 2, 14);
  564. // Missing a closing quotation mark in string.
  565. TEST_STRING_ERROR(kParseErrorStringMissQuotationMark, "[\"Test]", 7, 7);
  566. // http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
  567. // 3 Malformed sequences
  568. // 3.1 Unexpected continuation bytes
  569. {
  570. char e[] = { '[', '\"', 0, '\"', ']', '\0' };
  571. for (unsigned char c = 0x80u; c <= 0xBFu; c++) {
  572. e[2] = static_cast<char>(c);
  573. ParseErrorCode error = TestString<UTF8<> >(e);
  574. EXPECT_EQ(kParseErrorStringInvalidEncoding, error);
  575. if (error != kParseErrorStringInvalidEncoding)
  576. std::cout << static_cast<unsigned>(c) << std::endl;
  577. }
  578. }
  579. // 3.2 Lonely start characters, 3.5 Impossible bytes
  580. {
  581. char e[] = { '[', '\"', 0, ' ', '\"', ']', '\0' };
  582. for (unsigned c = 0xC0u; c <= 0xFFu; c++) {
  583. e[2] = static_cast<char>(c);
  584. int streamPos;
  585. if (c <= 0xC1u)
  586. streamPos = 3; // 0xC0 - 0xC1
  587. else if (c <= 0xDFu)
  588. streamPos = 4; // 0xC2 - 0xDF
  589. else if (c <= 0xEFu)
  590. streamPos = 5; // 0xE0 - 0xEF
  591. else if (c <= 0xF4u)
  592. streamPos = 6; // 0xF0 - 0xF4
  593. else
  594. streamPos = 3; // 0xF5 - 0xFF
  595. TEST_STRING_ERROR(kParseErrorStringInvalidEncoding, e, 2, streamPos);
  596. }
  597. }
  598. // 4 Overlong sequences
  599. // 4.1 Examples of an overlong ASCII character
  600. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xC0u, 0xAFu, '\"', ']', '\0'));
  601. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xE0u, 0x80u, 0xAFu, '\"', ']', '\0'));
  602. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xF0u, 0x80u, 0x80u, 0xAFu, '\"', ']', '\0'));
  603. // 4.2 Maximum overlong sequences
  604. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xC1u, 0xBFu, '\"', ']', '\0'));
  605. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xE0u, 0x9Fu, 0xBFu, '\"', ']', '\0'));
  606. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xF0u, 0x8Fu, 0xBFu, 0xBFu, '\"', ']', '\0'));
  607. // 4.3 Overlong representation of the NUL character
  608. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xC0u, 0x80u, '\"', ']', '\0'));
  609. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xE0u, 0x80u, 0x80u, '\"', ']', '\0'));
  610. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xF0u, 0x80u, 0x80u, 0x80u, '\"', ']', '\0'));
  611. // 5 Illegal code positions
  612. // 5.1 Single UTF-16 surrogates
  613. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xA0u, 0x80u, '\"', ']', '\0'));
  614. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xADu, 0xBFu, '\"', ']', '\0'));
  615. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xAEu, 0x80u, '\"', ']', '\0'));
  616. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xAFu, 0xBFu, '\"', ']', '\0'));
  617. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xB0u, 0x80u, '\"', ']', '\0'));
  618. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xBEu, 0x80u, '\"', ']', '\0'));
  619. TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xBFu, 0xBFu, '\"', ']', '\0'));
  620. // Malform UTF-16 sequences
  621. TEST_STRINGENCODING_ERROR(UTF16<>, UTF8<>, wchar_t, ARRAY('[', '\"', 0xDC00, 0xDC00, '\"', ']', '\0'));
  622. TEST_STRINGENCODING_ERROR(UTF16<>, UTF8<>, wchar_t, ARRAY('[', '\"', 0xD800, 0xD800, '\"', ']', '\0'));
  623. // Malform UTF-32 sequence
  624. TEST_STRINGENCODING_ERROR(UTF32<>, UTF8<>, unsigned, ARRAY('[', '\"', 0x110000, '\"', ']', '\0'));
  625. // Malform ASCII sequence
  626. TEST_STRINGENCODING_ERROR(ASCII<>, UTF8<>, char, ARRAY('[', '\"', char(0x80u), '\"', ']', '\0'));
  627. #undef ARRAY
  628. #undef TEST_STRINGARRAY_ERROR
  629. }
  630. template <unsigned count>
  631. struct ParseArrayHandler : BaseReaderHandler<UTF8<>, ParseArrayHandler<count> > {
  632. ParseArrayHandler() : step_(0) {}
  633. bool Default() { ADD_FAILURE(); return false; }
  634. bool Uint(unsigned i) { EXPECT_EQ(step_, i); step_++; return true; }
  635. bool StartArray() { EXPECT_EQ(0u, step_); step_++; return true; }
  636. bool EndArray(SizeType) { step_++; return true; }
  637. unsigned step_;
  638. };
  639. TEST(Reader, ParseEmptyArray) {
  640. char *json = StrDup("[ ] ");
  641. InsituStringStream s(json);
  642. ParseArrayHandler<0> h;
  643. Reader reader;
  644. reader.Parse(s, h);
  645. EXPECT_EQ(2u, h.step_);
  646. free(json);
  647. }
  648. TEST(Reader, ParseArray) {
  649. char *json = StrDup("[1, 2, 3, 4]");
  650. InsituStringStream s(json);
  651. ParseArrayHandler<4> h;
  652. Reader reader;
  653. reader.Parse(s, h);
  654. EXPECT_EQ(6u, h.step_);
  655. free(json);
  656. }
  657. TEST(Reader, ParseArray_Error) {
  658. #define TEST_ARRAY_ERROR(errorCode, str, errorOffset) \
  659. { \
  660. int streamPos = errorOffset; \
  661. char buffer[1001]; \
  662. strncpy(buffer, str, 1000); \
  663. InsituStringStream s(buffer); \
  664. BaseReaderHandler<> h; \
  665. GenericReader<UTF8<>, UTF8<>, CrtAllocator> reader; \
  666. EXPECT_FALSE(reader.Parse(s, h)); \
  667. EXPECT_EQ(errorCode, reader.GetParseErrorCode());\
  668. EXPECT_EQ(errorOffset, reader.GetErrorOffset());\
  669. EXPECT_EQ(streamPos, s.Tell());\
  670. }
  671. // Missing a comma or ']' after an array element.
  672. TEST_ARRAY_ERROR(kParseErrorArrayMissCommaOrSquareBracket, "[1", 2);
  673. TEST_ARRAY_ERROR(kParseErrorArrayMissCommaOrSquareBracket, "[1}", 2);
  674. TEST_ARRAY_ERROR(kParseErrorArrayMissCommaOrSquareBracket, "[1 2]", 3);
  675. // Array cannot have a trailing comma (without kParseTrailingCommasFlag);
  676. // a value must follow a comma
  677. TEST_ARRAY_ERROR(kParseErrorValueInvalid, "[1,]", 3);
  678. #undef TEST_ARRAY_ERROR
  679. }
  680. struct ParseObjectHandler : BaseReaderHandler<UTF8<>, ParseObjectHandler> {
  681. ParseObjectHandler() : step_(0) {}
  682. bool Default() { ADD_FAILURE(); return false; }
  683. bool Null() { EXPECT_EQ(8u, step_); step_++; return true; }
  684. bool Bool(bool b) {
  685. switch(step_) {
  686. case 4: EXPECT_TRUE(b); step_++; return true;
  687. case 6: EXPECT_FALSE(b); step_++; return true;
  688. default: ADD_FAILURE(); return false;
  689. }
  690. }
  691. bool Int(int i) {
  692. switch(step_) {
  693. case 10: EXPECT_EQ(123, i); step_++; return true;
  694. case 15: EXPECT_EQ(1, i); step_++; return true;
  695. case 16: EXPECT_EQ(2, i); step_++; return true;
  696. case 17: EXPECT_EQ(3, i); step_++; return true;
  697. default: ADD_FAILURE(); return false;
  698. }
  699. }
  700. bool Uint(unsigned i) { return Int(static_cast<int>(i)); }
  701. bool Double(double d) { EXPECT_EQ(12u, step_); EXPECT_DOUBLE_EQ(3.1416, d); step_++; return true; }
  702. bool String(const char* str, size_t, bool) {
  703. switch(step_) {
  704. case 1: EXPECT_STREQ("hello", str); step_++; return true;
  705. case 2: EXPECT_STREQ("world", str); step_++; return true;
  706. case 3: EXPECT_STREQ("t", str); step_++; return true;
  707. case 5: EXPECT_STREQ("f", str); step_++; return true;
  708. case 7: EXPECT_STREQ("n", str); step_++; return true;
  709. case 9: EXPECT_STREQ("i", str); step_++; return true;
  710. case 11: EXPECT_STREQ("pi", str); step_++; return true;
  711. case 13: EXPECT_STREQ("a", str); step_++; return true;
  712. default: ADD_FAILURE(); return false;
  713. }
  714. }
  715. bool StartObject() { EXPECT_EQ(0u, step_); step_++; return true; }
  716. bool EndObject(SizeType memberCount) { EXPECT_EQ(19u, step_); EXPECT_EQ(7u, memberCount); step_++; return true; }
  717. bool StartArray() { EXPECT_EQ(14u, step_); step_++; return true; }
  718. bool EndArray(SizeType elementCount) { EXPECT_EQ(18u, step_); EXPECT_EQ(3u, elementCount); step_++; return true; }
  719. unsigned step_;
  720. };
  721. TEST(Reader, ParseObject) {
  722. const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } ";
  723. // Insitu
  724. {
  725. char* json2 = StrDup(json);
  726. InsituStringStream s(json2);
  727. ParseObjectHandler h;
  728. Reader reader;
  729. reader.Parse<kParseInsituFlag>(s, h);
  730. EXPECT_EQ(20u, h.step_);
  731. free(json2);
  732. }
  733. // Normal
  734. {
  735. StringStream s(json);
  736. ParseObjectHandler h;
  737. Reader reader;
  738. reader.Parse(s, h);
  739. EXPECT_EQ(20u, h.step_);
  740. }
  741. }
  742. struct ParseEmptyObjectHandler : BaseReaderHandler<UTF8<>, ParseEmptyObjectHandler> {
  743. ParseEmptyObjectHandler() : step_(0) {}
  744. bool Default() { ADD_FAILURE(); return false; }
  745. bool StartObject() { EXPECT_EQ(0u, step_); step_++; return true; }
  746. bool EndObject(SizeType) { EXPECT_EQ(1u, step_); step_++; return true; }
  747. unsigned step_;
  748. };
  749. TEST(Reader, Parse_EmptyObject) {
  750. StringStream s("{ } ");
  751. ParseEmptyObjectHandler h;
  752. Reader reader;
  753. reader.Parse(s, h);
  754. EXPECT_EQ(2u, h.step_);
  755. }
  756. struct ParseMultipleRootHandler : BaseReaderHandler<UTF8<>, ParseMultipleRootHandler> {
  757. ParseMultipleRootHandler() : step_(0) {}
  758. bool Default() { ADD_FAILURE(); return false; }
  759. bool StartObject() { EXPECT_EQ(0u, step_); step_++; return true; }
  760. bool EndObject(SizeType) { EXPECT_EQ(1u, step_); step_++; return true; }
  761. bool StartArray() { EXPECT_EQ(2u, step_); step_++; return true; }
  762. bool EndArray(SizeType) { EXPECT_EQ(3u, step_); step_++; return true; }
  763. unsigned step_;
  764. };
  765. template <unsigned parseFlags>
  766. void TestMultipleRoot() {
  767. StringStream s("{}[] a");
  768. ParseMultipleRootHandler h;
  769. Reader reader;
  770. EXPECT_TRUE(reader.Parse<parseFlags>(s, h));
  771. EXPECT_EQ(2u, h.step_);
  772. EXPECT_TRUE(reader.Parse<parseFlags>(s, h));
  773. EXPECT_EQ(4u, h.step_);
  774. EXPECT_EQ(' ', s.Take());
  775. EXPECT_EQ('a', s.Take());
  776. }
  777. TEST(Reader, Parse_MultipleRoot) {
  778. TestMultipleRoot<kParseStopWhenDoneFlag>();
  779. }
  780. TEST(Reader, ParseIterative_MultipleRoot) {
  781. TestMultipleRoot<kParseIterativeFlag | kParseStopWhenDoneFlag>();
  782. }
  783. template <unsigned parseFlags>
  784. void TestInsituMultipleRoot() {
  785. char* buffer = strdup("{}[] a");
  786. InsituStringStream s(buffer);
  787. ParseMultipleRootHandler h;
  788. Reader reader;
  789. EXPECT_TRUE(reader.Parse<kParseInsituFlag | parseFlags>(s, h));
  790. EXPECT_EQ(2u, h.step_);
  791. EXPECT_TRUE(reader.Parse<kParseInsituFlag | parseFlags>(s, h));
  792. EXPECT_EQ(4u, h.step_);
  793. EXPECT_EQ(' ', s.Take());
  794. EXPECT_EQ('a', s.Take());
  795. free(buffer);
  796. }
  797. TEST(Reader, ParseInsitu_MultipleRoot) {
  798. TestInsituMultipleRoot<kParseStopWhenDoneFlag>();
  799. }
  800. TEST(Reader, ParseInsituIterative_MultipleRoot) {
  801. TestInsituMultipleRoot<kParseIterativeFlag | kParseStopWhenDoneFlag>();
  802. }
  803. #define TEST_ERROR(errorCode, str, errorOffset) \
  804. { \
  805. int streamPos = errorOffset; \
  806. char buffer[1001]; \
  807. strncpy(buffer, str, 1000); \
  808. InsituStringStream s(buffer); \
  809. BaseReaderHandler<> h; \
  810. Reader reader; \
  811. EXPECT_FALSE(reader.Parse(s, h)); \
  812. EXPECT_EQ(errorCode, reader.GetParseErrorCode());\
  813. EXPECT_EQ(errorOffset, reader.GetErrorOffset());\
  814. EXPECT_EQ(streamPos, s.Tell());\
  815. }
  816. TEST(Reader, ParseDocument_Error) {
  817. // The document is empty.
  818. TEST_ERROR(kParseErrorDocumentEmpty, "", 0);
  819. TEST_ERROR(kParseErrorDocumentEmpty, " ", 1);
  820. TEST_ERROR(kParseErrorDocumentEmpty, " \n", 2);
  821. // The document root must not follow by other values.
  822. TEST_ERROR(kParseErrorDocumentRootNotSingular, "[] 0", 3);
  823. TEST_ERROR(kParseErrorDocumentRootNotSingular, "{} 0", 3);
  824. TEST_ERROR(kParseErrorDocumentRootNotSingular, "null []", 5);
  825. TEST_ERROR(kParseErrorDocumentRootNotSingular, "0 {}", 2);
  826. }
  827. TEST(Reader, ParseValue_Error) {
  828. // Invalid value.
  829. TEST_ERROR(kParseErrorValueInvalid, "nulL", 3);
  830. TEST_ERROR(kParseErrorValueInvalid, "truE", 3);
  831. TEST_ERROR(kParseErrorValueInvalid, "falsE", 4);
  832. TEST_ERROR(kParseErrorValueInvalid, "a]", 0);
  833. TEST_ERROR(kParseErrorValueInvalid, ".1", 0);
  834. }
  835. TEST(Reader, ParseObject_Error) {
  836. // Missing a name for object member.
  837. TEST_ERROR(kParseErrorObjectMissName, "{1}", 1);
  838. TEST_ERROR(kParseErrorObjectMissName, "{:1}", 1);
  839. TEST_ERROR(kParseErrorObjectMissName, "{null:1}", 1);
  840. TEST_ERROR(kParseErrorObjectMissName, "{true:1}", 1);
  841. TEST_ERROR(kParseErrorObjectMissName, "{false:1}", 1);
  842. TEST_ERROR(kParseErrorObjectMissName, "{1:1}", 1);
  843. TEST_ERROR(kParseErrorObjectMissName, "{[]:1}", 1);
  844. TEST_ERROR(kParseErrorObjectMissName, "{{}:1}", 1);
  845. TEST_ERROR(kParseErrorObjectMissName, "{xyz:1}", 1);
  846. // Missing a colon after a name of object member.
  847. TEST_ERROR(kParseErrorObjectMissColon, "{\"a\" 1}", 5);
  848. TEST_ERROR(kParseErrorObjectMissColon, "{\"a\",1}", 4);
  849. // Must be a comma or '}' after an object member
  850. TEST_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, "{\"a\":1]", 6);
  851. // Object cannot have a trailing comma (without kParseTrailingCommasFlag);
  852. // an object member name must follow a comma
  853. TEST_ERROR(kParseErrorObjectMissName, "{\"a\":1,}", 7);
  854. // This tests that MemoryStream is checking the length in Peek().
  855. {
  856. MemoryStream ms("{\"a\"", 1);
  857. BaseReaderHandler<> h;
  858. Reader reader;
  859. EXPECT_FALSE(reader.Parse<kParseStopWhenDoneFlag>(ms, h));
  860. EXPECT_EQ(kParseErrorObjectMissName, reader.GetParseErrorCode());
  861. }
  862. }
  863. #undef TEST_ERROR
  864. TEST(Reader, SkipWhitespace) {
  865. StringStream ss(" A \t\tB\n \n\nC\r\r \rD \t\n\r E");
  866. const char* expected = "ABCDE";
  867. for (size_t i = 0; i < 5; i++) {
  868. SkipWhitespace(ss);
  869. EXPECT_EQ(expected[i], ss.Take());
  870. }
  871. }
  872. // Test implementing a stream without copy stream optimization.
  873. // Clone from GenericStringStream except that copy constructor is disabled.
  874. template <typename Encoding>
  875. class CustomStringStream {
  876. public:
  877. typedef typename Encoding::Ch Ch;
  878. CustomStringStream(const Ch *src) : src_(src), head_(src) {}
  879. Ch Peek() const { return *src_; }
  880. Ch Take() { return *src_++; }
  881. size_t Tell() const { return static_cast<size_t>(src_ - head_); }
  882. Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
  883. void Put(Ch) { RAPIDJSON_ASSERT(false); }
  884. void Flush() { RAPIDJSON_ASSERT(false); }
  885. size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
  886. private:
  887. // Prohibit copy constructor & assignment operator.
  888. CustomStringStream(const CustomStringStream&);
  889. CustomStringStream& operator=(const CustomStringStream&);
  890. const Ch* src_; //!< Current read position.
  891. const Ch* head_; //!< Original head of the string.
  892. };
  893. // If the following code is compiled, it should generate compilation error as predicted.
  894. // Because CustomStringStream<> is not copyable via making copy constructor private.
  895. #if 0
  896. namespace rapidjson {
  897. template <typename Encoding>
  898. struct StreamTraits<CustomStringStream<Encoding> > {
  899. enum { copyOptimization = 1 };
  900. };
  901. } // namespace rapidjson
  902. #endif
  903. TEST(Reader, CustomStringStream) {
  904. const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } ";
  905. CustomStringStream<UTF8<char> > s(json);
  906. ParseObjectHandler h;
  907. Reader reader;
  908. reader.Parse(s, h);
  909. EXPECT_EQ(20u, h.step_);
  910. }
  911. #include <sstream>
  912. class IStreamWrapper {
  913. public:
  914. typedef char Ch;
  915. IStreamWrapper(std::istream& is) : is_(is) {}
  916. Ch Peek() const {
  917. int c = is_.peek();
  918. return c == std::char_traits<char>::eof() ? '\0' : static_cast<Ch>(c);
  919. }
  920. Ch Take() {
  921. int c = is_.get();
  922. return c == std::char_traits<char>::eof() ? '\0' : static_cast<Ch>(c);
  923. }
  924. size_t Tell() const { return static_cast<size_t>(is_.tellg()); }
  925. Ch* PutBegin() { assert(false); return 0; }
  926. void Put(Ch) { assert(false); }
  927. void Flush() { assert(false); }
  928. size_t PutEnd(Ch*) { assert(false); return 0; }
  929. private:
  930. IStreamWrapper(const IStreamWrapper&);
  931. IStreamWrapper& operator=(const IStreamWrapper&);
  932. std::istream& is_;
  933. };
  934. TEST(Reader, Parse_IStreamWrapper_StringStream) {
  935. const char* json = "[1,2,3,4]";
  936. std::stringstream ss(json);
  937. IStreamWrapper is(ss);
  938. Reader reader;
  939. ParseArrayHandler<4> h;
  940. reader.Parse(is, h);
  941. EXPECT_FALSE(reader.HasParseError());
  942. }
  943. // Test iterative parsing.
  944. #define TESTERRORHANDLING(text, errorCode, offset)\
  945. {\
  946. int streamPos = offset; \
  947. StringStream json(text); \
  948. BaseReaderHandler<> handler; \
  949. Reader reader; \
  950. reader.Parse<kParseIterativeFlag>(json, handler); \
  951. EXPECT_TRUE(reader.HasParseError()); \
  952. EXPECT_EQ(errorCode, reader.GetParseErrorCode()); \
  953. EXPECT_EQ(offset, reader.GetErrorOffset()); \
  954. EXPECT_EQ(streamPos, json.Tell()); \
  955. }
  956. TEST(Reader, IterativeParsing_ErrorHandling) {
  957. TESTERRORHANDLING("{\"a\": a}", kParseErrorValueInvalid, 6u);
  958. TESTERRORHANDLING("", kParseErrorDocumentEmpty, 0u);
  959. TESTERRORHANDLING("{}{}", kParseErrorDocumentRootNotSingular, 2u);
  960. TESTERRORHANDLING("{1}", kParseErrorObjectMissName, 1u);
  961. TESTERRORHANDLING("{\"a\", 1}", kParseErrorObjectMissColon, 4u);
  962. TESTERRORHANDLING("{\"a\"}", kParseErrorObjectMissColon, 4u);
  963. TESTERRORHANDLING("{\"a\": 1", kParseErrorObjectMissCommaOrCurlyBracket, 7u);
  964. TESTERRORHANDLING("[1 2 3]", kParseErrorArrayMissCommaOrSquareBracket, 3u);
  965. TESTERRORHANDLING("{\"a: 1", kParseErrorStringMissQuotationMark, 6u);
  966. TESTERRORHANDLING("{\"a\":}", kParseErrorValueInvalid, 5u);
  967. TESTERRORHANDLING("{\"a\":]", kParseErrorValueInvalid, 5u);
  968. TESTERRORHANDLING("[1,2,}", kParseErrorValueInvalid, 5u);
  969. TESTERRORHANDLING("[}]", kParseErrorValueInvalid, 1u);
  970. TESTERRORHANDLING("[,]", kParseErrorValueInvalid, 1u);
  971. TESTERRORHANDLING("[1,,]", kParseErrorValueInvalid, 3u);
  972. // Trailing commas are not allowed without kParseTrailingCommasFlag
  973. TESTERRORHANDLING("{\"a\": 1,}", kParseErrorObjectMissName, 8u);
  974. TESTERRORHANDLING("[1,2,3,]", kParseErrorValueInvalid, 7u);
  975. // Any JSON value can be a valid root element in RFC7159.
  976. TESTERRORHANDLING("\"ab", kParseErrorStringMissQuotationMark, 3u);
  977. TESTERRORHANDLING("truE", kParseErrorValueInvalid, 3u);
  978. TESTERRORHANDLING("False", kParseErrorValueInvalid, 0u);
  979. TESTERRORHANDLING("true, false", kParseErrorDocumentRootNotSingular, 4u);
  980. TESTERRORHANDLING("false, false", kParseErrorDocumentRootNotSingular, 5u);
  981. TESTERRORHANDLING("nulL", kParseErrorValueInvalid, 3u);
  982. TESTERRORHANDLING("null , null", kParseErrorDocumentRootNotSingular, 5u);
  983. TESTERRORHANDLING("1a", kParseErrorDocumentRootNotSingular, 1u);
  984. }
  985. template<typename Encoding = UTF8<> >
  986. struct IterativeParsingReaderHandler {
  987. typedef typename Encoding::Ch Ch;
  988. const static uint32_t LOG_NULL = 0x10000000;
  989. const static uint32_t LOG_BOOL = 0x20000000;
  990. const static uint32_t LOG_INT = 0x30000000;
  991. const static uint32_t LOG_UINT = 0x40000000;
  992. const static uint32_t LOG_INT64 = 0x50000000;
  993. const static uint32_t LOG_UINT64 = 0x60000000;
  994. const static uint32_t LOG_DOUBLE = 0x70000000;
  995. const static uint32_t LOG_STRING = 0x80000000;
  996. const static uint32_t LOG_STARTOBJECT = 0x90000000;
  997. const static uint32_t LOG_KEY = 0xA0000000;
  998. const static uint32_t LOG_ENDOBJECT = 0xB0000000;
  999. const static uint32_t LOG_STARTARRAY = 0xC0000000;
  1000. const static uint32_t LOG_ENDARRAY = 0xD0000000;
  1001. const static size_t LogCapacity = 256;
  1002. uint32_t Logs[LogCapacity];
  1003. size_t LogCount;
  1004. IterativeParsingReaderHandler() : LogCount(0) {
  1005. }
  1006. bool Null() { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_NULL; return true; }
  1007. bool Bool(bool) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_BOOL; return true; }
  1008. bool Int(int) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_INT; return true; }
  1009. bool Uint(unsigned) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_INT; return true; }
  1010. bool Int64(int64_t) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_INT64; return true; }
  1011. bool Uint64(uint64_t) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_UINT64; return true; }
  1012. bool Double(double) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_DOUBLE; return true; }
  1013. bool RawNumber(const Ch*, SizeType, bool) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_STRING; return true; }
  1014. bool String(const Ch*, SizeType, bool) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_STRING; return true; }
  1015. bool StartObject() { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_STARTOBJECT; return true; }
  1016. bool Key (const Ch*, SizeType, bool) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_KEY; return true; }
  1017. bool EndObject(SizeType c) {
  1018. RAPIDJSON_ASSERT(LogCount < LogCapacity);
  1019. RAPIDJSON_ASSERT((static_cast<uint32_t>(c) & 0xF0000000) == 0);
  1020. Logs[LogCount++] = LOG_ENDOBJECT | static_cast<uint32_t>(c);
  1021. return true;
  1022. }
  1023. bool StartArray() { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_STARTARRAY; return true; }
  1024. bool EndArray(SizeType c) {
  1025. RAPIDJSON_ASSERT(LogCount < LogCapacity);
  1026. RAPIDJSON_ASSERT((static_cast<uint32_t>(c) & 0xF0000000) == 0);
  1027. Logs[LogCount++] = LOG_ENDARRAY | static_cast<uint32_t>(c);
  1028. return true;
  1029. }
  1030. };
  1031. TEST(Reader, IterativeParsing_General) {
  1032. {
  1033. StringStream is("[1, {\"k\": [1, 2]}, null, false, true, \"string\", 1.2]");
  1034. Reader reader;
  1035. IterativeParsingReaderHandler<> handler;
  1036. ParseResult r = reader.Parse<kParseIterativeFlag>(is, handler);
  1037. EXPECT_FALSE(r.IsError());
  1038. EXPECT_FALSE(reader.HasParseError());
  1039. uint32_t e[] = {
  1040. handler.LOG_STARTARRAY,
  1041. handler.LOG_INT,
  1042. handler.LOG_STARTOBJECT,
  1043. handler.LOG_KEY,
  1044. handler.LOG_STARTARRAY,
  1045. handler.LOG_INT,
  1046. handler.LOG_INT,
  1047. handler.LOG_ENDARRAY | 2,
  1048. handler.LOG_ENDOBJECT | 1,
  1049. handler.LOG_NULL,
  1050. handler.LOG_BOOL,
  1051. handler.LOG_BOOL,
  1052. handler.LOG_STRING,
  1053. handler.LOG_DOUBLE,
  1054. handler.LOG_ENDARRAY | 7
  1055. };
  1056. EXPECT_EQ(sizeof(e) / sizeof(int), handler.LogCount);
  1057. for (size_t i = 0; i < handler.LogCount; ++i) {
  1058. EXPECT_EQ(e[i], handler.Logs[i]) << "i = " << i;
  1059. }
  1060. }
  1061. }
  1062. TEST(Reader, IterativeParsing_Count) {
  1063. {
  1064. StringStream is("[{}, {\"k\": 1}, [1], []]");
  1065. Reader reader;
  1066. IterativeParsingReaderHandler<> handler;
  1067. ParseResult r = reader.Parse<kParseIterativeFlag>(is, handler);
  1068. EXPECT_FALSE(r.IsError());
  1069. EXPECT_FALSE(reader.HasParseError());
  1070. uint32_t e[] = {
  1071. handler.LOG_STARTARRAY,
  1072. handler.LOG_STARTOBJECT,
  1073. handler.LOG_ENDOBJECT | 0,
  1074. handler.LOG_STARTOBJECT,
  1075. handler.LOG_KEY,
  1076. handler.LOG_INT,
  1077. handler.LOG_ENDOBJECT | 1,
  1078. handler.LOG_STARTARRAY,
  1079. handler.LOG_INT,
  1080. handler.LOG_ENDARRAY | 1,
  1081. handler.LOG_STARTARRAY,
  1082. handler.LOG_ENDARRAY | 0,
  1083. handler.LOG_ENDARRAY | 4
  1084. };
  1085. EXPECT_EQ(sizeof(e) / sizeof(int), handler.LogCount);
  1086. for (size_t i = 0; i < handler.LogCount; ++i) {
  1087. EXPECT_EQ(e[i], handler.Logs[i]) << "i = " << i;
  1088. }
  1089. }
  1090. }
  1091. TEST(Reader, IterativePullParsing_General) {
  1092. {
  1093. IterativeParsingReaderHandler<> handler;
  1094. uint32_t e[] = {
  1095. handler.LOG_STARTARRAY,
  1096. handler.LOG_INT,
  1097. handler.LOG_STARTOBJECT,
  1098. handler.LOG_KEY,
  1099. handler.LOG_STARTARRAY,
  1100. handler.LOG_INT,
  1101. handler.LOG_INT,
  1102. handler.LOG_ENDARRAY | 2,
  1103. handler.LOG_ENDOBJECT | 1,
  1104. handler.LOG_NULL,
  1105. handler.LOG_BOOL,
  1106. handler.LOG_BOOL,
  1107. handler.LOG_STRING,
  1108. handler.LOG_DOUBLE,
  1109. handler.LOG_ENDARRAY | 7
  1110. };
  1111. StringStream is("[1, {\"k\": [1, 2]}, null, false, true, \"string\", 1.2]");
  1112. Reader reader;
  1113. reader.IterativeParseInit();
  1114. while (!reader.IterativeParseComplete()) {
  1115. size_t oldLogCount = handler.LogCount;
  1116. EXPECT_TRUE(oldLogCount < sizeof(e) / sizeof(int)) << "overrun";
  1117. EXPECT_TRUE(reader.IterativeParseNext<kParseDefaultFlags>(is, handler)) << "parse fail";
  1118. EXPECT_EQ(handler.LogCount, oldLogCount + 1) << "handler should be invoked exactly once each time";
  1119. EXPECT_EQ(e[oldLogCount], handler.Logs[oldLogCount]) << "wrong event returned";
  1120. }
  1121. EXPECT_FALSE(reader.HasParseError());
  1122. EXPECT_EQ(sizeof(e) / sizeof(int), handler.LogCount) << "handler invoked wrong number of times";
  1123. // The handler should not be invoked when the JSON has been fully read, but it should not fail
  1124. size_t oldLogCount = handler.LogCount;
  1125. EXPECT_TRUE(reader.IterativeParseNext<kParseDefaultFlags>(is, handler)) << "parse-next past complete is allowed";
  1126. EXPECT_EQ(handler.LogCount, oldLogCount) << "parse-next past complete should not invoke handler";
  1127. EXPECT_FALSE(reader.HasParseError()) << "parse-next past complete should not generate parse error";
  1128. }
  1129. }
  1130. // Test iterative parsing on kParseErrorTermination.
  1131. struct HandlerTerminateAtStartObject : public IterativeParsingReaderHandler<> {
  1132. bool StartObject() { return false; }
  1133. };
  1134. struct HandlerTerminateAtStartArray : public IterativeParsingReaderHandler<> {
  1135. bool StartArray() { return false; }
  1136. };
  1137. struct HandlerTerminateAtEndObject : public IterativeParsingReaderHandler<> {
  1138. bool EndObject(SizeType) { return false; }
  1139. };
  1140. struct HandlerTerminateAtEndArray : public IterativeParsingReaderHandler<> {
  1141. bool EndArray(SizeType) { return false; }
  1142. };
  1143. TEST(Reader, IterativeParsing_ShortCircuit) {
  1144. {
  1145. HandlerTerminateAtStartObject handler;
  1146. Reader reader;
  1147. StringStream is("[1, {}]");
  1148. ParseResult r = reader.Parse<kParseIterativeFlag>(is, handler);
  1149. EXPECT_TRUE(reader.HasParseError());
  1150. EXPECT_EQ(kParseErrorTermination, r.Code());
  1151. EXPECT_EQ(4u, r.Offset());
  1152. }
  1153. {
  1154. HandlerTerminateAtStartArray handler;
  1155. Reader reader;
  1156. StringStream is("{\"a\": []}");
  1157. ParseResult r = reader.Parse<kParseIterativeFlag>(is, handler);
  1158. EXPECT_TRUE(reader.HasParseError());
  1159. EXPECT_EQ(kParseErrorTermination, r.Code());
  1160. EXPECT_EQ(6u, r.Offset());
  1161. }
  1162. {
  1163. HandlerTerminateAtEndObject handler;
  1164. Reader reader;
  1165. StringStream is("[1, {}]");
  1166. ParseResult r = reader.Parse<kParseIterativeFlag>(is, handler);
  1167. EXPECT_TRUE(reader.HasParseError());
  1168. EXPECT_EQ(kParseErrorTermination, r.Code());
  1169. EXPECT_EQ(5u, r.Offset());
  1170. }
  1171. {
  1172. HandlerTerminateAtEndArray handler;
  1173. Reader reader;
  1174. StringStream is("{\"a\": []}");
  1175. ParseResult r = reader.Parse<kParseIterativeFlag>(is, handler);
  1176. EXPECT_TRUE(reader.HasParseError());
  1177. EXPECT_EQ(kParseErrorTermination, r.Code());
  1178. EXPECT_EQ(7u, r.Offset());
  1179. }
  1180. }
  1181. // For covering BaseReaderHandler default functions
  1182. TEST(Reader, BaseReaderHandler_Default) {
  1183. BaseReaderHandler<> h;
  1184. Reader reader;
  1185. StringStream is("[null, true, -1, 1, -1234567890123456789, 1234567890123456789, 3.14, \"s\", { \"a\" : 1 }]");
  1186. EXPECT_TRUE(reader.Parse(is, h));
  1187. }
  1188. template <int e>
  1189. struct TerminateHandler {
  1190. bool Null() { return e != 0; }
  1191. bool Bool(bool) { return e != 1; }
  1192. bool Int(int) { return e != 2; }
  1193. bool Uint(unsigned) { return e != 3; }
  1194. bool Int64(int64_t) { return e != 4; }
  1195. bool Uint64(uint64_t) { return e != 5; }
  1196. bool Double(double) { return e != 6; }
  1197. bool RawNumber(const char*, SizeType, bool) { return e != 7; }
  1198. bool String(const char*, SizeType, bool) { return e != 8; }
  1199. bool StartObject() { return e != 9; }
  1200. bool Key(const char*, SizeType, bool) { return e != 10; }
  1201. bool EndObject(SizeType) { return e != 11; }
  1202. bool StartArray() { return e != 12; }
  1203. bool EndArray(SizeType) { return e != 13; }
  1204. };
  1205. #define TEST_TERMINATION(e, json)\
  1206. {\
  1207. Reader reader;\
  1208. TerminateHandler<e> h;\
  1209. StringStream is(json);\
  1210. EXPECT_FALSE(reader.Parse(is, h));\
  1211. EXPECT_EQ(kParseErrorTermination, reader.GetParseErrorCode());\
  1212. }
  1213. TEST(Reader, ParseTerminationByHandler) {
  1214. TEST_TERMINATION(0, "[null");
  1215. TEST_TERMINATION(1, "[true");
  1216. TEST_TERMINATION(1, "[false");
  1217. TEST_TERMINATION(2, "[-1");
  1218. TEST_TERMINATION(3, "[1");
  1219. TEST_TERMINATION(4, "[-1234567890123456789");
  1220. TEST_TERMINATION(5, "[1234567890123456789");
  1221. TEST_TERMINATION(6, "[0.5]");
  1222. // RawNumber() is never called
  1223. TEST_TERMINATION(8, "[\"a\"");
  1224. TEST_TERMINATION(9, "[{");
  1225. TEST_TERMINATION(10, "[{\"a\"");
  1226. TEST_TERMINATION(11, "[{}");
  1227. TEST_TERMINATION(11, "[{\"a\":1}"); // non-empty object
  1228. TEST_TERMINATION(12, "{\"a\":[");
  1229. TEST_TERMINATION(13, "{\"a\":[]");
  1230. TEST_TERMINATION(13, "{\"a\":[1]"); // non-empty array
  1231. }
  1232. TEST(Reader, ParseComments) {
  1233. const char* json =
  1234. "// Here is a one-line comment.\n"
  1235. "{// And here's another one\n"
  1236. " /*And here's an in-line one.*/\"hello\" : \"world\","
  1237. " \"t\" :/* And one with '*' symbol*/true ,"
  1238. "/* A multiline comment\n"
  1239. " goes here*/"
  1240. " \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3]"
  1241. "}/*And the last one to be sure */";
  1242. StringStream s(json);
  1243. ParseObjectHandler h;
  1244. Reader reader;
  1245. EXPECT_TRUE(reader.Parse<kParseCommentsFlag>(s, h));
  1246. EXPECT_EQ(20u, h.step_);
  1247. }
  1248. TEST(Reader, ParseEmptyInlineComment) {
  1249. const char* json = "{/**/\"hello\" : \"world\", \"t\" : true, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }";
  1250. StringStream s(json);
  1251. ParseObjectHandler h;
  1252. Reader reader;
  1253. EXPECT_TRUE(reader.Parse<kParseCommentsFlag>(s, h));
  1254. EXPECT_EQ(20u, h.step_);
  1255. }
  1256. TEST(Reader, ParseEmptyOnelineComment) {
  1257. const char* json = "{//\n\"hello\" : \"world\", \"t\" : true, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }";
  1258. StringStream s(json);
  1259. ParseObjectHandler h;
  1260. Reader reader;
  1261. EXPECT_TRUE(reader.Parse<kParseCommentsFlag>(s, h));
  1262. EXPECT_EQ(20u, h.step_);
  1263. }
  1264. TEST(Reader, ParseMultipleCommentsInARow) {
  1265. const char* json =
  1266. "{/* first comment *//* second */\n"
  1267. "/* third */ /*fourth*/// last one\n"
  1268. "\"hello\" : \"world\", \"t\" : true, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }";
  1269. StringStream s(json);
  1270. ParseObjectHandler h;
  1271. Reader reader;
  1272. EXPECT_TRUE(reader.Parse<kParseCommentsFlag>(s, h));
  1273. EXPECT_EQ(20u, h.step_);
  1274. }
  1275. TEST(Reader, InlineCommentsAreDisabledByDefault) {
  1276. {
  1277. const char* json = "{/* Inline comment. */\"hello\" : \"world\", \"t\" : true, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }";
  1278. StringStream s(json);
  1279. ParseObjectHandler h;
  1280. Reader reader;
  1281. EXPECT_FALSE(reader.Parse<kParseDefaultFlags>(s, h));
  1282. }
  1283. {
  1284. const char* json =
  1285. "{\"hello\" : /* Multiline comment starts here\n"
  1286. " continues here\n"
  1287. " and ends here */\"world\", \"t\" :true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }";
  1288. StringStream s(json);
  1289. ParseObjectHandler h;
  1290. Reader reader;
  1291. EXPECT_FALSE(reader.Parse<kParseDefaultFlags>(s, h));
  1292. }
  1293. }
  1294. TEST(Reader, OnelineCommentsAreDisabledByDefault) {
  1295. const char* json = "{// One-line comment\n\"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }";
  1296. StringStream s(json);
  1297. ParseObjectHandler h;
  1298. Reader reader;
  1299. EXPECT_FALSE(reader.Parse<kParseDefaultFlags>(s, h));
  1300. }
  1301. TEST(Reader, EofAfterOneLineComment) {
  1302. const char* json = "{\"hello\" : \"world\" // EOF is here -->\0 \n}";
  1303. StringStream s(json);
  1304. ParseObjectHandler h;
  1305. Reader reader;
  1306. EXPECT_FALSE(reader.Parse<kParseCommentsFlag>(s, h));
  1307. EXPECT_EQ(kParseErrorObjectMissCommaOrCurlyBracket, reader.GetParseErrorCode());
  1308. }
  1309. TEST(Reader, IncompleteMultilineComment) {
  1310. const char* json = "{\"hello\" : \"world\" /* EOF is here -->\0 */}";
  1311. StringStream s(json);
  1312. ParseObjectHandler h;
  1313. Reader reader;
  1314. EXPECT_FALSE(reader.Parse<kParseCommentsFlag>(s, h));
  1315. EXPECT_EQ(kParseErrorUnspecificSyntaxError, reader.GetParseErrorCode());
  1316. }
  1317. TEST(Reader, IncompleteMultilineComment2) {
  1318. const char* json = "{\"hello\" : \"world\" /* *\0 */}";
  1319. StringStream s(json);
  1320. ParseObjectHandler h;
  1321. Reader reader;
  1322. EXPECT_FALSE(reader.Parse<kParseCommentsFlag>(s, h));
  1323. EXPECT_EQ(kParseErrorUnspecificSyntaxError, reader.GetParseErrorCode());
  1324. }
  1325. TEST(Reader, UnrecognizedComment) {
  1326. const char* json = "{\"hello\" : \"world\" /! }";
  1327. StringStream s(json);
  1328. ParseObjectHandler h;
  1329. Reader reader;
  1330. EXPECT_FALSE(reader.Parse<kParseCommentsFlag>(s, h));
  1331. EXPECT_EQ(kParseErrorUnspecificSyntaxError, reader.GetParseErrorCode());
  1332. }
  1333. struct NumbersAsStringsHandler {
  1334. bool Null() { return true; }
  1335. bool Bool(bool) { return true; }
  1336. bool Int(int) { return true; }
  1337. bool Uint(unsigned) { return true; }
  1338. bool Int64(int64_t) { return true; }
  1339. bool Uint64(uint64_t) { return true; }
  1340. bool Double(double) { return true; }
  1341. // 'str' is not null-terminated
  1342. bool RawNumber(const char* str, SizeType length, bool) {
  1343. EXPECT_TRUE(str != 0);
  1344. EXPECT_TRUE(expected_len_ == length);
  1345. EXPECT_TRUE(strncmp(str, expected_, length) == 0);
  1346. return true;
  1347. }
  1348. bool String(const char*, SizeType, bool) { return true; }
  1349. bool StartObject() { return true; }
  1350. bool Key(const char*, SizeType, bool) { return true; }
  1351. bool EndObject(SizeType) { return true; }
  1352. bool StartArray() { return true; }
  1353. bool EndArray(SizeType) { return true; }
  1354. NumbersAsStringsHandler(const char* expected)
  1355. : expected_(expected)
  1356. , expected_len_(strlen(expected)) {}
  1357. const char* expected_;
  1358. size_t expected_len_;
  1359. };
  1360. TEST(Reader, NumbersAsStrings) {
  1361. {
  1362. const char* json = "{ \"pi\": 3.1416 } ";
  1363. StringStream s(json);
  1364. NumbersAsStringsHandler h("3.1416");
  1365. Reader reader;
  1366. EXPECT_TRUE(reader.Parse<kParseNumbersAsStringsFlag>(s, h));
  1367. }
  1368. {
  1369. char* json = StrDup("{ \"pi\": 3.1416 } ");
  1370. InsituStringStream s(json);
  1371. NumbersAsStringsHandler h("3.1416");
  1372. Reader reader;
  1373. EXPECT_TRUE(reader.Parse<kParseInsituFlag|kParseNumbersAsStringsFlag>(s, h));
  1374. free(json);
  1375. }
  1376. {
  1377. const char* json = "{ \"gigabyte\": 1.0e9 } ";
  1378. StringStream s(json);
  1379. NumbersAsStringsHandler h("1.0e9");
  1380. Reader reader;
  1381. EXPECT_TRUE(reader.Parse<kParseNumbersAsStringsFlag>(s, h));
  1382. }
  1383. {
  1384. char* json = StrDup("{ \"gigabyte\": 1.0e9 } ");
  1385. InsituStringStream s(json);
  1386. NumbersAsStringsHandler h("1.0e9");
  1387. Reader reader;
  1388. EXPECT_TRUE(reader.Parse<kParseInsituFlag|kParseNumbersAsStringsFlag>(s, h));
  1389. free(json);
  1390. }
  1391. {
  1392. const char* json = "{ \"pi\": 314.159e-2 } ";
  1393. StringStream s(json);
  1394. NumbersAsStringsHandler h("314.159e-2");
  1395. Reader reader;
  1396. EXPECT_TRUE(reader.Parse<kParseNumbersAsStringsFlag>(s, h));
  1397. }
  1398. {
  1399. char* json = StrDup("{ \"gigabyte\": 314.159e-2 } ");
  1400. InsituStringStream s(json);
  1401. NumbersAsStringsHandler h("314.159e-2");
  1402. Reader reader;
  1403. EXPECT_TRUE(reader.Parse<kParseInsituFlag|kParseNumbersAsStringsFlag>(s, h));
  1404. free(json);
  1405. }
  1406. {
  1407. const char* json = "{ \"negative\": -1.54321 } ";
  1408. StringStream s(json);
  1409. NumbersAsStringsHandler h("-1.54321");
  1410. Reader reader;
  1411. EXPECT_TRUE(reader.Parse<kParseNumbersAsStringsFlag>(s, h));
  1412. }
  1413. {
  1414. char* json = StrDup("{ \"negative\": -1.54321 } ");
  1415. InsituStringStream s(json);
  1416. NumbersAsStringsHandler h("-1.54321");
  1417. Reader reader;
  1418. EXPECT_TRUE(reader.Parse<kParseInsituFlag|kParseNumbersAsStringsFlag>(s, h));
  1419. free(json);
  1420. }
  1421. {
  1422. const char* json = "{ \"pi\": 314.159e-2 } ";
  1423. std::stringstream ss(json);
  1424. IStreamWrapper s(ss);
  1425. NumbersAsStringsHandler h("314.159e-2");
  1426. Reader reader;
  1427. EXPECT_TRUE(reader.Parse<kParseNumbersAsStringsFlag>(s, h));
  1428. }
  1429. }
  1430. template <unsigned extraFlags>
  1431. void TestTrailingCommas() {
  1432. {
  1433. StringStream s("[1,2,3,]");
  1434. ParseArrayHandler<3> h;
  1435. Reader reader;
  1436. EXPECT_TRUE(reader.Parse<extraFlags|kParseTrailingCommasFlag>(s, h));
  1437. EXPECT_EQ(5u, h.step_);
  1438. }
  1439. {
  1440. const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false,"
  1441. "\"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3],}";
  1442. StringStream s(json);
  1443. ParseObjectHandler h;
  1444. Reader reader;
  1445. EXPECT_TRUE(reader.Parse<extraFlags|kParseTrailingCommasFlag>(s, h));
  1446. EXPECT_EQ(20u, h.step_);
  1447. }
  1448. {
  1449. // whitespace around trailing commas
  1450. const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false,"
  1451. "\"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3\n,\n]\n,\n} ";
  1452. StringStream s(json);
  1453. ParseObjectHandler h;
  1454. Reader reader;
  1455. EXPECT_TRUE(reader.Parse<extraFlags|kParseTrailingCommasFlag>(s, h));
  1456. EXPECT_EQ(20u, h.step_);
  1457. }
  1458. {
  1459. // comments around trailing commas
  1460. const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null,"
  1461. "\"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3/*test*/,/*test*/]/*test*/,/*test*/}";
  1462. StringStream s(json);
  1463. ParseObjectHandler h;
  1464. Reader reader;
  1465. EXPECT_TRUE(reader.Parse<extraFlags|kParseTrailingCommasFlag|kParseCommentsFlag>(s, h));
  1466. EXPECT_EQ(20u, h.step_);
  1467. }
  1468. }
  1469. TEST(Reader, TrailingCommas) {
  1470. TestTrailingCommas<kParseNoFlags>();
  1471. }
  1472. TEST(Reader, TrailingCommasIterative) {
  1473. TestTrailingCommas<kParseIterativeFlag>();
  1474. }
  1475. template <unsigned extraFlags>
  1476. void TestMultipleTrailingCommaErrors() {
  1477. // only a single trailing comma is allowed.
  1478. {
  1479. StringStream s("[1,2,3,,]");
  1480. ParseArrayHandler<3> h;
  1481. Reader reader;
  1482. ParseResult r = reader.Parse<extraFlags|kParseTrailingCommasFlag>(s, h);
  1483. EXPECT_TRUE(reader.HasParseError());
  1484. EXPECT_EQ(kParseErrorValueInvalid, r.Code());
  1485. EXPECT_EQ(7u, r.Offset());
  1486. }
  1487. {
  1488. const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false,"
  1489. "\"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3,],,}";
  1490. StringStream s(json);
  1491. ParseObjectHandler h;
  1492. Reader reader;
  1493. ParseResult r = reader.Parse<extraFlags|kParseTrailingCommasFlag>(s, h);
  1494. EXPECT_TRUE(reader.HasParseError());
  1495. EXPECT_EQ(kParseErrorObjectMissName, r.Code());
  1496. EXPECT_EQ(95u, r.Offset());
  1497. }
  1498. }
  1499. TEST(Reader, MultipleTrailingCommaErrors) {
  1500. TestMultipleTrailingCommaErrors<kParseNoFlags>();
  1501. }
  1502. TEST(Reader, MultipleTrailingCommaErrorsIterative) {
  1503. TestMultipleTrailingCommaErrors<kParseIterativeFlag>();
  1504. }
  1505. template <unsigned extraFlags>
  1506. void TestEmptyExceptForCommaErrors() {
  1507. // not allowed even with trailing commas enabled; the
  1508. // trailing comma must follow a value.
  1509. {
  1510. StringStream s("[,]");
  1511. ParseArrayHandler<3> h;
  1512. Reader reader;
  1513. ParseResult r = reader.Parse<extraFlags|kParseTrailingCommasFlag>(s, h);
  1514. EXPECT_TRUE(reader.HasParseError());
  1515. EXPECT_EQ(kParseErrorValueInvalid, r.Code());
  1516. EXPECT_EQ(1u, r.Offset());
  1517. }
  1518. {
  1519. StringStream s("{,}");
  1520. ParseObjectHandler h;
  1521. Reader reader;
  1522. ParseResult r = reader.Parse<extraFlags|kParseTrailingCommasFlag>(s, h);
  1523. EXPECT_TRUE(reader.HasParseError());
  1524. EXPECT_EQ(kParseErrorObjectMissName, r.Code());
  1525. EXPECT_EQ(1u, r.Offset());
  1526. }
  1527. }
  1528. TEST(Reader, EmptyExceptForCommaErrors) {
  1529. TestEmptyExceptForCommaErrors<kParseNoFlags>();
  1530. }
  1531. TEST(Reader, EmptyExceptForCommaErrorsIterative) {
  1532. TestEmptyExceptForCommaErrors<kParseIterativeFlag>();
  1533. }
  1534. template <unsigned extraFlags>
  1535. void TestTrailingCommaHandlerTermination() {
  1536. {
  1537. HandlerTerminateAtEndArray h;
  1538. Reader reader;
  1539. StringStream s("[1,2,3,]");
  1540. ParseResult r = reader.Parse<extraFlags|kParseTrailingCommasFlag>(s, h);
  1541. EXPECT_TRUE(reader.HasParseError());
  1542. EXPECT_EQ(kParseErrorTermination, r.Code());
  1543. EXPECT_EQ(7u, r.Offset());
  1544. }
  1545. {
  1546. HandlerTerminateAtEndObject h;
  1547. Reader reader;
  1548. StringStream s("{\"t\": true, \"f\": false,}");
  1549. ParseResult r = reader.Parse<extraFlags|kParseTrailingCommasFlag>(s, h);
  1550. EXPECT_TRUE(reader.HasParseError());
  1551. EXPECT_EQ(kParseErrorTermination, r.Code());
  1552. EXPECT_EQ(23u, r.Offset());
  1553. }
  1554. }
  1555. TEST(Reader, TrailingCommaHandlerTermination) {
  1556. TestTrailingCommaHandlerTermination<kParseNoFlags>();
  1557. }
  1558. TEST(Reader, TrailingCommaHandlerTerminationIterative) {
  1559. TestTrailingCommaHandlerTermination<kParseIterativeFlag>();
  1560. }
  1561. TEST(Reader, ParseNanAndInfinity) {
  1562. #define TEST_NAN_INF(str, x) \
  1563. { \
  1564. { \
  1565. StringStream s(str); \
  1566. ParseDoubleHandler h; \
  1567. Reader reader; \
  1568. ASSERT_EQ(kParseErrorNone, reader.Parse<kParseNanAndInfFlag>(s, h).Code()); \
  1569. EXPECT_EQ(1u, h.step_); \
  1570. internal::Double e(x), a(h.actual_); \
  1571. EXPECT_EQ(e.IsNan(), a.IsNan()); \
  1572. EXPECT_EQ(e.IsInf(), a.IsInf()); \
  1573. if (!e.IsNan()) \
  1574. EXPECT_EQ(e.Sign(), a.Sign()); \
  1575. } \
  1576. { \
  1577. const char* json = "{ \"naninfdouble\": " str " } "; \
  1578. StringStream s(json); \
  1579. NumbersAsStringsHandler h(str); \
  1580. Reader reader; \
  1581. EXPECT_TRUE(reader.Parse<kParseNumbersAsStringsFlag|kParseNanAndInfFlag>(s, h)); \
  1582. } \
  1583. { \
  1584. char* json = StrDup("{ \"naninfdouble\": " str " } "); \
  1585. InsituStringStream s(json); \
  1586. NumbersAsStringsHandler h(str); \
  1587. Reader reader; \
  1588. EXPECT_TRUE(reader.Parse<kParseInsituFlag|kParseNumbersAsStringsFlag|kParseNanAndInfFlag>(s, h)); \
  1589. free(json); \
  1590. } \
  1591. }
  1592. #define TEST_NAN_INF_ERROR(errorCode, str, errorOffset) \
  1593. { \
  1594. int streamPos = errorOffset; \
  1595. char buffer[1001]; \
  1596. strncpy(buffer, str, 1000); \
  1597. InsituStringStream s(buffer); \
  1598. BaseReaderHandler<> h; \
  1599. Reader reader; \
  1600. EXPECT_FALSE(reader.Parse<kParseNanAndInfFlag>(s, h)); \
  1601. EXPECT_EQ(errorCode, reader.GetParseErrorCode());\
  1602. EXPECT_EQ(errorOffset, reader.GetErrorOffset());\
  1603. EXPECT_EQ(streamPos, s.Tell());\
  1604. }
  1605. double nan = std::numeric_limits<double>::quiet_NaN();
  1606. double inf = std::numeric_limits<double>::infinity();
  1607. TEST_NAN_INF("NaN", nan);
  1608. TEST_NAN_INF("-NaN", nan);
  1609. TEST_NAN_INF("Inf", inf);
  1610. TEST_NAN_INF("Infinity", inf);
  1611. TEST_NAN_INF("-Inf", -inf);
  1612. TEST_NAN_INF("-Infinity", -inf);
  1613. TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "NInf", 1);
  1614. TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "NaInf", 2);
  1615. TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "INan", 1);
  1616. TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "InNan", 2);
  1617. TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "nan", 1);
  1618. TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "-nan", 1);
  1619. TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "NAN", 1);
  1620. TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "-Infinty", 6);
  1621. #undef TEST_NAN_INF_ERROR
  1622. #undef TEST_NAN_INF
  1623. }
  1624. RAPIDJSON_DIAG_POP