lexer.hpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  1. #pragma once
  2. #include <array> // array
  3. #include <clocale> // localeconv
  4. #include <cstddef> // size_t
  5. #include <cstdio> // snprintf
  6. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  7. #include <initializer_list> // initializer_list
  8. #include <string> // char_traits, string
  9. #include <utility> // move
  10. #include <vector> // vector
  11. #include <nlohmann/detail/input/input_adapters.hpp>
  12. #include <nlohmann/detail/input/position_t.hpp>
  13. #include <nlohmann/detail/macro_scope.hpp>
  14. namespace nlohmann
  15. {
  16. namespace detail
  17. {
  18. ///////////
  19. // lexer //
  20. ///////////
  21. /*!
  22. @brief lexical analysis
  23. This class organizes the lexical analysis during JSON deserialization.
  24. */
  25. template<typename BasicJsonType>
  26. class lexer
  27. {
  28. using number_integer_t = typename BasicJsonType::number_integer_t;
  29. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  30. using number_float_t = typename BasicJsonType::number_float_t;
  31. using string_t = typename BasicJsonType::string_t;
  32. public:
  33. /// token types for the parser
  34. enum class token_type
  35. {
  36. uninitialized, ///< indicating the scanner is uninitialized
  37. literal_true, ///< the `true` literal
  38. literal_false, ///< the `false` literal
  39. literal_null, ///< the `null` literal
  40. value_string, ///< a string -- use get_string() for actual value
  41. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  42. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  43. value_float, ///< an floating point number -- use get_number_float() for actual value
  44. begin_array, ///< the character for array begin `[`
  45. begin_object, ///< the character for object begin `{`
  46. end_array, ///< the character for array end `]`
  47. end_object, ///< the character for object end `}`
  48. name_separator, ///< the name separator `:`
  49. value_separator, ///< the value separator `,`
  50. parse_error, ///< indicating a parse error
  51. end_of_input, ///< indicating the end of the input buffer
  52. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  53. };
  54. /// return name of values of type token_type (only used for errors)
  55. JSON_HEDLEY_RETURNS_NON_NULL
  56. JSON_HEDLEY_CONST
  57. static const char* token_type_name(const token_type t) noexcept
  58. {
  59. switch (t)
  60. {
  61. case token_type::uninitialized:
  62. return "<uninitialized>";
  63. case token_type::literal_true:
  64. return "true literal";
  65. case token_type::literal_false:
  66. return "false literal";
  67. case token_type::literal_null:
  68. return "null literal";
  69. case token_type::value_string:
  70. return "string literal";
  71. case lexer::token_type::value_unsigned:
  72. case lexer::token_type::value_integer:
  73. case lexer::token_type::value_float:
  74. return "number literal";
  75. case token_type::begin_array:
  76. return "'['";
  77. case token_type::begin_object:
  78. return "'{'";
  79. case token_type::end_array:
  80. return "']'";
  81. case token_type::end_object:
  82. return "'}'";
  83. case token_type::name_separator:
  84. return "':'";
  85. case token_type::value_separator:
  86. return "','";
  87. case token_type::parse_error:
  88. return "<parse error>";
  89. case token_type::end_of_input:
  90. return "end of input";
  91. case token_type::literal_or_value:
  92. return "'[', '{', or a literal";
  93. // LCOV_EXCL_START
  94. default: // catch non-enum values
  95. return "unknown token";
  96. // LCOV_EXCL_STOP
  97. }
  98. }
  99. explicit lexer(detail::input_adapter_t&& adapter)
  100. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  101. // delete because of pointer members
  102. lexer(const lexer&) = delete;
  103. lexer(lexer&&) = delete;
  104. lexer& operator=(lexer&) = delete;
  105. lexer& operator=(lexer&&) = delete;
  106. ~lexer() = default;
  107. private:
  108. /////////////////////
  109. // locales
  110. /////////////////////
  111. /// return the locale-dependent decimal point
  112. JSON_HEDLEY_PURE
  113. static char get_decimal_point() noexcept
  114. {
  115. const auto loc = localeconv();
  116. assert(loc != nullptr);
  117. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  118. }
  119. /////////////////////
  120. // scan functions
  121. /////////////////////
  122. /*!
  123. @brief get codepoint from 4 hex characters following `\u`
  124. For input "\u c1 c2 c3 c4" the codepoint is:
  125. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  126. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  127. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  128. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  129. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  130. between the ASCII value of the character and the desired integer value.
  131. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  132. non-hex character)
  133. */
  134. int get_codepoint()
  135. {
  136. // this function only makes sense after reading `\u`
  137. assert(current == 'u');
  138. int codepoint = 0;
  139. const auto factors = { 12u, 8u, 4u, 0u };
  140. for (const auto factor : factors)
  141. {
  142. get();
  143. if (current >= '0' and current <= '9')
  144. {
  145. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  146. }
  147. else if (current >= 'A' and current <= 'F')
  148. {
  149. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  150. }
  151. else if (current >= 'a' and current <= 'f')
  152. {
  153. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  154. }
  155. else
  156. {
  157. return -1;
  158. }
  159. }
  160. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  161. return codepoint;
  162. }
  163. /*!
  164. @brief check if the next byte(s) are inside a given range
  165. Adds the current byte and, for each passed range, reads a new byte and
  166. checks if it is inside the range. If a violation was detected, set up an
  167. error message and return false. Otherwise, return true.
  168. @param[in] ranges list of integers; interpreted as list of pairs of
  169. inclusive lower and upper bound, respectively
  170. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  171. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  172. @return true if and only if no range violation was detected
  173. */
  174. bool next_byte_in_range(std::initializer_list<int> ranges)
  175. {
  176. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  177. add(current);
  178. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  179. {
  180. get();
  181. if (JSON_HEDLEY_LIKELY(*range <= current and current <= *(++range)))
  182. {
  183. add(current);
  184. }
  185. else
  186. {
  187. error_message = "invalid string: ill-formed UTF-8 byte";
  188. return false;
  189. }
  190. }
  191. return true;
  192. }
  193. /*!
  194. @brief scan a string literal
  195. This function scans a string according to Sect. 7 of RFC 7159. While
  196. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  197. function returns successfully, token_buffer is *not* null-terminated (as it
  198. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  199. string.
  200. @return token_type::value_string if string could be successfully scanned,
  201. token_type::parse_error otherwise
  202. @note In case of errors, variable error_message contains a textual
  203. description.
  204. */
  205. token_type scan_string()
  206. {
  207. // reset token_buffer (ignore opening quote)
  208. reset();
  209. // we entered the function by reading an open quote
  210. assert(current == '\"');
  211. while (true)
  212. {
  213. // get next character
  214. switch (get())
  215. {
  216. // end of file while parsing string
  217. case std::char_traits<char>::eof():
  218. {
  219. error_message = "invalid string: missing closing quote";
  220. return token_type::parse_error;
  221. }
  222. // closing quote
  223. case '\"':
  224. {
  225. return token_type::value_string;
  226. }
  227. // escapes
  228. case '\\':
  229. {
  230. switch (get())
  231. {
  232. // quotation mark
  233. case '\"':
  234. add('\"');
  235. break;
  236. // reverse solidus
  237. case '\\':
  238. add('\\');
  239. break;
  240. // solidus
  241. case '/':
  242. add('/');
  243. break;
  244. // backspace
  245. case 'b':
  246. add('\b');
  247. break;
  248. // form feed
  249. case 'f':
  250. add('\f');
  251. break;
  252. // line feed
  253. case 'n':
  254. add('\n');
  255. break;
  256. // carriage return
  257. case 'r':
  258. add('\r');
  259. break;
  260. // tab
  261. case 't':
  262. add('\t');
  263. break;
  264. // unicode escapes
  265. case 'u':
  266. {
  267. const int codepoint1 = get_codepoint();
  268. int codepoint = codepoint1; // start with codepoint1
  269. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  270. {
  271. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  272. return token_type::parse_error;
  273. }
  274. // check if code point is a high surrogate
  275. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  276. {
  277. // expect next \uxxxx entry
  278. if (JSON_HEDLEY_LIKELY(get() == '\\' and get() == 'u'))
  279. {
  280. const int codepoint2 = get_codepoint();
  281. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  282. {
  283. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  284. return token_type::parse_error;
  285. }
  286. // check if codepoint2 is a low surrogate
  287. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  288. {
  289. // overwrite codepoint
  290. codepoint = static_cast<int>(
  291. // high surrogate occupies the most significant 22 bits
  292. (static_cast<unsigned int>(codepoint1) << 10u)
  293. // low surrogate occupies the least significant 15 bits
  294. + static_cast<unsigned int>(codepoint2)
  295. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  296. // in the result so we have to subtract with:
  297. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  298. - 0x35FDC00u);
  299. }
  300. else
  301. {
  302. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  303. return token_type::parse_error;
  304. }
  305. }
  306. else
  307. {
  308. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  309. return token_type::parse_error;
  310. }
  311. }
  312. else
  313. {
  314. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  315. {
  316. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  317. return token_type::parse_error;
  318. }
  319. }
  320. // result of the above calculation yields a proper codepoint
  321. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  322. // translate codepoint into bytes
  323. if (codepoint < 0x80)
  324. {
  325. // 1-byte characters: 0xxxxxxx (ASCII)
  326. add(codepoint);
  327. }
  328. else if (codepoint <= 0x7FF)
  329. {
  330. // 2-byte characters: 110xxxxx 10xxxxxx
  331. add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  332. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  333. }
  334. else if (codepoint <= 0xFFFF)
  335. {
  336. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  337. add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  338. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  339. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  340. }
  341. else
  342. {
  343. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  344. add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  345. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  346. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  347. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  348. }
  349. break;
  350. }
  351. // other characters after escape
  352. default:
  353. error_message = "invalid string: forbidden character after backslash";
  354. return token_type::parse_error;
  355. }
  356. break;
  357. }
  358. // invalid control characters
  359. case 0x00:
  360. {
  361. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  362. return token_type::parse_error;
  363. }
  364. case 0x01:
  365. {
  366. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  367. return token_type::parse_error;
  368. }
  369. case 0x02:
  370. {
  371. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  372. return token_type::parse_error;
  373. }
  374. case 0x03:
  375. {
  376. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  377. return token_type::parse_error;
  378. }
  379. case 0x04:
  380. {
  381. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  382. return token_type::parse_error;
  383. }
  384. case 0x05:
  385. {
  386. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  387. return token_type::parse_error;
  388. }
  389. case 0x06:
  390. {
  391. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  392. return token_type::parse_error;
  393. }
  394. case 0x07:
  395. {
  396. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  397. return token_type::parse_error;
  398. }
  399. case 0x08:
  400. {
  401. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  402. return token_type::parse_error;
  403. }
  404. case 0x09:
  405. {
  406. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  407. return token_type::parse_error;
  408. }
  409. case 0x0A:
  410. {
  411. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  412. return token_type::parse_error;
  413. }
  414. case 0x0B:
  415. {
  416. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  417. return token_type::parse_error;
  418. }
  419. case 0x0C:
  420. {
  421. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  422. return token_type::parse_error;
  423. }
  424. case 0x0D:
  425. {
  426. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  427. return token_type::parse_error;
  428. }
  429. case 0x0E:
  430. {
  431. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  432. return token_type::parse_error;
  433. }
  434. case 0x0F:
  435. {
  436. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  437. return token_type::parse_error;
  438. }
  439. case 0x10:
  440. {
  441. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  442. return token_type::parse_error;
  443. }
  444. case 0x11:
  445. {
  446. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  447. return token_type::parse_error;
  448. }
  449. case 0x12:
  450. {
  451. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  452. return token_type::parse_error;
  453. }
  454. case 0x13:
  455. {
  456. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  457. return token_type::parse_error;
  458. }
  459. case 0x14:
  460. {
  461. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  462. return token_type::parse_error;
  463. }
  464. case 0x15:
  465. {
  466. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  467. return token_type::parse_error;
  468. }
  469. case 0x16:
  470. {
  471. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  472. return token_type::parse_error;
  473. }
  474. case 0x17:
  475. {
  476. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  477. return token_type::parse_error;
  478. }
  479. case 0x18:
  480. {
  481. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  482. return token_type::parse_error;
  483. }
  484. case 0x19:
  485. {
  486. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  487. return token_type::parse_error;
  488. }
  489. case 0x1A:
  490. {
  491. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  492. return token_type::parse_error;
  493. }
  494. case 0x1B:
  495. {
  496. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  497. return token_type::parse_error;
  498. }
  499. case 0x1C:
  500. {
  501. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  502. return token_type::parse_error;
  503. }
  504. case 0x1D:
  505. {
  506. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  507. return token_type::parse_error;
  508. }
  509. case 0x1E:
  510. {
  511. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  512. return token_type::parse_error;
  513. }
  514. case 0x1F:
  515. {
  516. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  517. return token_type::parse_error;
  518. }
  519. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  520. case 0x20:
  521. case 0x21:
  522. case 0x23:
  523. case 0x24:
  524. case 0x25:
  525. case 0x26:
  526. case 0x27:
  527. case 0x28:
  528. case 0x29:
  529. case 0x2A:
  530. case 0x2B:
  531. case 0x2C:
  532. case 0x2D:
  533. case 0x2E:
  534. case 0x2F:
  535. case 0x30:
  536. case 0x31:
  537. case 0x32:
  538. case 0x33:
  539. case 0x34:
  540. case 0x35:
  541. case 0x36:
  542. case 0x37:
  543. case 0x38:
  544. case 0x39:
  545. case 0x3A:
  546. case 0x3B:
  547. case 0x3C:
  548. case 0x3D:
  549. case 0x3E:
  550. case 0x3F:
  551. case 0x40:
  552. case 0x41:
  553. case 0x42:
  554. case 0x43:
  555. case 0x44:
  556. case 0x45:
  557. case 0x46:
  558. case 0x47:
  559. case 0x48:
  560. case 0x49:
  561. case 0x4A:
  562. case 0x4B:
  563. case 0x4C:
  564. case 0x4D:
  565. case 0x4E:
  566. case 0x4F:
  567. case 0x50:
  568. case 0x51:
  569. case 0x52:
  570. case 0x53:
  571. case 0x54:
  572. case 0x55:
  573. case 0x56:
  574. case 0x57:
  575. case 0x58:
  576. case 0x59:
  577. case 0x5A:
  578. case 0x5B:
  579. case 0x5D:
  580. case 0x5E:
  581. case 0x5F:
  582. case 0x60:
  583. case 0x61:
  584. case 0x62:
  585. case 0x63:
  586. case 0x64:
  587. case 0x65:
  588. case 0x66:
  589. case 0x67:
  590. case 0x68:
  591. case 0x69:
  592. case 0x6A:
  593. case 0x6B:
  594. case 0x6C:
  595. case 0x6D:
  596. case 0x6E:
  597. case 0x6F:
  598. case 0x70:
  599. case 0x71:
  600. case 0x72:
  601. case 0x73:
  602. case 0x74:
  603. case 0x75:
  604. case 0x76:
  605. case 0x77:
  606. case 0x78:
  607. case 0x79:
  608. case 0x7A:
  609. case 0x7B:
  610. case 0x7C:
  611. case 0x7D:
  612. case 0x7E:
  613. case 0x7F:
  614. {
  615. add(current);
  616. break;
  617. }
  618. // U+0080..U+07FF: bytes C2..DF 80..BF
  619. case 0xC2:
  620. case 0xC3:
  621. case 0xC4:
  622. case 0xC5:
  623. case 0xC6:
  624. case 0xC7:
  625. case 0xC8:
  626. case 0xC9:
  627. case 0xCA:
  628. case 0xCB:
  629. case 0xCC:
  630. case 0xCD:
  631. case 0xCE:
  632. case 0xCF:
  633. case 0xD0:
  634. case 0xD1:
  635. case 0xD2:
  636. case 0xD3:
  637. case 0xD4:
  638. case 0xD5:
  639. case 0xD6:
  640. case 0xD7:
  641. case 0xD8:
  642. case 0xD9:
  643. case 0xDA:
  644. case 0xDB:
  645. case 0xDC:
  646. case 0xDD:
  647. case 0xDE:
  648. case 0xDF:
  649. {
  650. if (JSON_HEDLEY_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  651. {
  652. return token_type::parse_error;
  653. }
  654. break;
  655. }
  656. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  657. case 0xE0:
  658. {
  659. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  660. {
  661. return token_type::parse_error;
  662. }
  663. break;
  664. }
  665. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  666. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  667. case 0xE1:
  668. case 0xE2:
  669. case 0xE3:
  670. case 0xE4:
  671. case 0xE5:
  672. case 0xE6:
  673. case 0xE7:
  674. case 0xE8:
  675. case 0xE9:
  676. case 0xEA:
  677. case 0xEB:
  678. case 0xEC:
  679. case 0xEE:
  680. case 0xEF:
  681. {
  682. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  683. {
  684. return token_type::parse_error;
  685. }
  686. break;
  687. }
  688. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  689. case 0xED:
  690. {
  691. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  692. {
  693. return token_type::parse_error;
  694. }
  695. break;
  696. }
  697. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  698. case 0xF0:
  699. {
  700. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  701. {
  702. return token_type::parse_error;
  703. }
  704. break;
  705. }
  706. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  707. case 0xF1:
  708. case 0xF2:
  709. case 0xF3:
  710. {
  711. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  712. {
  713. return token_type::parse_error;
  714. }
  715. break;
  716. }
  717. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  718. case 0xF4:
  719. {
  720. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  721. {
  722. return token_type::parse_error;
  723. }
  724. break;
  725. }
  726. // remaining bytes (80..C1 and F5..FF) are ill-formed
  727. default:
  728. {
  729. error_message = "invalid string: ill-formed UTF-8 byte";
  730. return token_type::parse_error;
  731. }
  732. }
  733. }
  734. }
  735. JSON_HEDLEY_NON_NULL(2)
  736. static void strtof(float& f, const char* str, char** endptr) noexcept
  737. {
  738. f = std::strtof(str, endptr);
  739. }
  740. JSON_HEDLEY_NON_NULL(2)
  741. static void strtof(double& f, const char* str, char** endptr) noexcept
  742. {
  743. f = std::strtod(str, endptr);
  744. }
  745. JSON_HEDLEY_NON_NULL(2)
  746. static void strtof(long double& f, const char* str, char** endptr) noexcept
  747. {
  748. f = std::strtold(str, endptr);
  749. }
  750. /*!
  751. @brief scan a number literal
  752. This function scans a string according to Sect. 6 of RFC 7159.
  753. The function is realized with a deterministic finite state machine derived
  754. from the grammar described in RFC 7159. Starting in state "init", the
  755. input is read and used to determined the next state. Only state "done"
  756. accepts the number. State "error" is a trap state to model errors. In the
  757. table below, "anything" means any character but the ones listed before.
  758. state | 0 | 1-9 | e E | + | - | . | anything
  759. ---------|----------|----------|----------|---------|---------|----------|-----------
  760. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  761. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  762. zero | done | done | exponent | done | done | decimal1 | done
  763. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  764. decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
  765. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  766. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  767. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  768. any2 | any2 | any2 | done | done | done | done | done
  769. The state machine is realized with one label per state (prefixed with
  770. "scan_number_") and `goto` statements between them. The state machine
  771. contains cycles, but any cycle can be left when EOF is read. Therefore,
  772. the function is guaranteed to terminate.
  773. During scanning, the read bytes are stored in token_buffer. This string is
  774. then converted to a signed integer, an unsigned integer, or a
  775. floating-point number.
  776. @return token_type::value_unsigned, token_type::value_integer, or
  777. token_type::value_float if number could be successfully scanned,
  778. token_type::parse_error otherwise
  779. @note The scanner is independent of the current locale. Internally, the
  780. locale's decimal point is used instead of `.` to work with the
  781. locale-dependent converters.
  782. */
  783. token_type scan_number() // lgtm [cpp/use-of-goto]
  784. {
  785. // reset token_buffer to store the number's bytes
  786. reset();
  787. // the type of the parsed number; initially set to unsigned; will be
  788. // changed if minus sign, decimal point or exponent is read
  789. token_type number_type = token_type::value_unsigned;
  790. // state (init): we just found out we need to scan a number
  791. switch (current)
  792. {
  793. case '-':
  794. {
  795. add(current);
  796. goto scan_number_minus;
  797. }
  798. case '0':
  799. {
  800. add(current);
  801. goto scan_number_zero;
  802. }
  803. case '1':
  804. case '2':
  805. case '3':
  806. case '4':
  807. case '5':
  808. case '6':
  809. case '7':
  810. case '8':
  811. case '9':
  812. {
  813. add(current);
  814. goto scan_number_any1;
  815. }
  816. // all other characters are rejected outside scan_number()
  817. default: // LCOV_EXCL_LINE
  818. assert(false); // LCOV_EXCL_LINE
  819. }
  820. scan_number_minus:
  821. // state: we just parsed a leading minus sign
  822. number_type = token_type::value_integer;
  823. switch (get())
  824. {
  825. case '0':
  826. {
  827. add(current);
  828. goto scan_number_zero;
  829. }
  830. case '1':
  831. case '2':
  832. case '3':
  833. case '4':
  834. case '5':
  835. case '6':
  836. case '7':
  837. case '8':
  838. case '9':
  839. {
  840. add(current);
  841. goto scan_number_any1;
  842. }
  843. default:
  844. {
  845. error_message = "invalid number; expected digit after '-'";
  846. return token_type::parse_error;
  847. }
  848. }
  849. scan_number_zero:
  850. // state: we just parse a zero (maybe with a leading minus sign)
  851. switch (get())
  852. {
  853. case '.':
  854. {
  855. add(decimal_point_char);
  856. goto scan_number_decimal1;
  857. }
  858. case 'e':
  859. case 'E':
  860. {
  861. add(current);
  862. goto scan_number_exponent;
  863. }
  864. default:
  865. goto scan_number_done;
  866. }
  867. scan_number_any1:
  868. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  869. switch (get())
  870. {
  871. case '0':
  872. case '1':
  873. case '2':
  874. case '3':
  875. case '4':
  876. case '5':
  877. case '6':
  878. case '7':
  879. case '8':
  880. case '9':
  881. {
  882. add(current);
  883. goto scan_number_any1;
  884. }
  885. case '.':
  886. {
  887. add(decimal_point_char);
  888. goto scan_number_decimal1;
  889. }
  890. case 'e':
  891. case 'E':
  892. {
  893. add(current);
  894. goto scan_number_exponent;
  895. }
  896. default:
  897. goto scan_number_done;
  898. }
  899. scan_number_decimal1:
  900. // state: we just parsed a decimal point
  901. number_type = token_type::value_float;
  902. switch (get())
  903. {
  904. case '0':
  905. case '1':
  906. case '2':
  907. case '3':
  908. case '4':
  909. case '5':
  910. case '6':
  911. case '7':
  912. case '8':
  913. case '9':
  914. {
  915. add(current);
  916. goto scan_number_decimal2;
  917. }
  918. default:
  919. {
  920. error_message = "invalid number; expected digit after '.'";
  921. return token_type::parse_error;
  922. }
  923. }
  924. scan_number_decimal2:
  925. // we just parsed at least one number after a decimal point
  926. switch (get())
  927. {
  928. case '0':
  929. case '1':
  930. case '2':
  931. case '3':
  932. case '4':
  933. case '5':
  934. case '6':
  935. case '7':
  936. case '8':
  937. case '9':
  938. {
  939. add(current);
  940. goto scan_number_decimal2;
  941. }
  942. case 'e':
  943. case 'E':
  944. {
  945. add(current);
  946. goto scan_number_exponent;
  947. }
  948. default:
  949. goto scan_number_done;
  950. }
  951. scan_number_exponent:
  952. // we just parsed an exponent
  953. number_type = token_type::value_float;
  954. switch (get())
  955. {
  956. case '+':
  957. case '-':
  958. {
  959. add(current);
  960. goto scan_number_sign;
  961. }
  962. case '0':
  963. case '1':
  964. case '2':
  965. case '3':
  966. case '4':
  967. case '5':
  968. case '6':
  969. case '7':
  970. case '8':
  971. case '9':
  972. {
  973. add(current);
  974. goto scan_number_any2;
  975. }
  976. default:
  977. {
  978. error_message =
  979. "invalid number; expected '+', '-', or digit after exponent";
  980. return token_type::parse_error;
  981. }
  982. }
  983. scan_number_sign:
  984. // we just parsed an exponent sign
  985. switch (get())
  986. {
  987. case '0':
  988. case '1':
  989. case '2':
  990. case '3':
  991. case '4':
  992. case '5':
  993. case '6':
  994. case '7':
  995. case '8':
  996. case '9':
  997. {
  998. add(current);
  999. goto scan_number_any2;
  1000. }
  1001. default:
  1002. {
  1003. error_message = "invalid number; expected digit after exponent sign";
  1004. return token_type::parse_error;
  1005. }
  1006. }
  1007. scan_number_any2:
  1008. // we just parsed a number after the exponent or exponent sign
  1009. switch (get())
  1010. {
  1011. case '0':
  1012. case '1':
  1013. case '2':
  1014. case '3':
  1015. case '4':
  1016. case '5':
  1017. case '6':
  1018. case '7':
  1019. case '8':
  1020. case '9':
  1021. {
  1022. add(current);
  1023. goto scan_number_any2;
  1024. }
  1025. default:
  1026. goto scan_number_done;
  1027. }
  1028. scan_number_done:
  1029. // unget the character after the number (we only read it to know that
  1030. // we are done scanning a number)
  1031. unget();
  1032. char* endptr = nullptr;
  1033. errno = 0;
  1034. // try to parse integers first and fall back to floats
  1035. if (number_type == token_type::value_unsigned)
  1036. {
  1037. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  1038. // we checked the number format before
  1039. assert(endptr == token_buffer.data() + token_buffer.size());
  1040. if (errno == 0)
  1041. {
  1042. value_unsigned = static_cast<number_unsigned_t>(x);
  1043. if (value_unsigned == x)
  1044. {
  1045. return token_type::value_unsigned;
  1046. }
  1047. }
  1048. }
  1049. else if (number_type == token_type::value_integer)
  1050. {
  1051. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  1052. // we checked the number format before
  1053. assert(endptr == token_buffer.data() + token_buffer.size());
  1054. if (errno == 0)
  1055. {
  1056. value_integer = static_cast<number_integer_t>(x);
  1057. if (value_integer == x)
  1058. {
  1059. return token_type::value_integer;
  1060. }
  1061. }
  1062. }
  1063. // this code is reached if we parse a floating-point number or if an
  1064. // integer conversion above failed
  1065. strtof(value_float, token_buffer.data(), &endptr);
  1066. // we checked the number format before
  1067. assert(endptr == token_buffer.data() + token_buffer.size());
  1068. return token_type::value_float;
  1069. }
  1070. /*!
  1071. @param[in] literal_text the literal text to expect
  1072. @param[in] length the length of the passed literal text
  1073. @param[in] return_type the token type to return on success
  1074. */
  1075. JSON_HEDLEY_NON_NULL(2)
  1076. token_type scan_literal(const char* literal_text, const std::size_t length,
  1077. token_type return_type)
  1078. {
  1079. assert(current == literal_text[0]);
  1080. for (std::size_t i = 1; i < length; ++i)
  1081. {
  1082. if (JSON_HEDLEY_UNLIKELY(get() != literal_text[i]))
  1083. {
  1084. error_message = "invalid literal";
  1085. return token_type::parse_error;
  1086. }
  1087. }
  1088. return return_type;
  1089. }
  1090. /////////////////////
  1091. // input management
  1092. /////////////////////
  1093. /// reset token_buffer; current character is beginning of token
  1094. void reset() noexcept
  1095. {
  1096. token_buffer.clear();
  1097. token_string.clear();
  1098. token_string.push_back(std::char_traits<char>::to_char_type(current));
  1099. }
  1100. /*
  1101. @brief get next character from the input
  1102. This function provides the interface to the used input adapter. It does
  1103. not throw in case the input reached EOF, but returns a
  1104. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  1105. for use in error messages.
  1106. @return character read from the input
  1107. */
  1108. std::char_traits<char>::int_type get()
  1109. {
  1110. ++position.chars_read_total;
  1111. ++position.chars_read_current_line;
  1112. if (next_unget)
  1113. {
  1114. // just reset the next_unget variable and work with current
  1115. next_unget = false;
  1116. }
  1117. else
  1118. {
  1119. current = ia->get_character();
  1120. }
  1121. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  1122. {
  1123. token_string.push_back(std::char_traits<char>::to_char_type(current));
  1124. }
  1125. if (current == '\n')
  1126. {
  1127. ++position.lines_read;
  1128. position.chars_read_current_line = 0;
  1129. }
  1130. return current;
  1131. }
  1132. /*!
  1133. @brief unget current character (read it again on next get)
  1134. We implement unget by setting variable next_unget to true. The input is not
  1135. changed - we just simulate ungetting by modifying chars_read_total,
  1136. chars_read_current_line, and token_string. The next call to get() will
  1137. behave as if the unget character is read again.
  1138. */
  1139. void unget()
  1140. {
  1141. next_unget = true;
  1142. --position.chars_read_total;
  1143. // in case we "unget" a newline, we have to also decrement the lines_read
  1144. if (position.chars_read_current_line == 0)
  1145. {
  1146. if (position.lines_read > 0)
  1147. {
  1148. --position.lines_read;
  1149. }
  1150. }
  1151. else
  1152. {
  1153. --position.chars_read_current_line;
  1154. }
  1155. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  1156. {
  1157. assert(not token_string.empty());
  1158. token_string.pop_back();
  1159. }
  1160. }
  1161. /// add a character to token_buffer
  1162. void add(int c)
  1163. {
  1164. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  1165. }
  1166. public:
  1167. /////////////////////
  1168. // value getters
  1169. /////////////////////
  1170. /// return integer value
  1171. constexpr number_integer_t get_number_integer() const noexcept
  1172. {
  1173. return value_integer;
  1174. }
  1175. /// return unsigned integer value
  1176. constexpr number_unsigned_t get_number_unsigned() const noexcept
  1177. {
  1178. return value_unsigned;
  1179. }
  1180. /// return floating-point value
  1181. constexpr number_float_t get_number_float() const noexcept
  1182. {
  1183. return value_float;
  1184. }
  1185. /// return current string value (implicitly resets the token; useful only once)
  1186. string_t& get_string()
  1187. {
  1188. return token_buffer;
  1189. }
  1190. /////////////////////
  1191. // diagnostics
  1192. /////////////////////
  1193. /// return position of last read token
  1194. constexpr position_t get_position() const noexcept
  1195. {
  1196. return position;
  1197. }
  1198. /// return the last read token (for errors only). Will never contain EOF
  1199. /// (an arbitrary value that is not a valid char value, often -1), because
  1200. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  1201. std::string get_token_string() const
  1202. {
  1203. // escape control characters
  1204. std::string result;
  1205. for (const auto c : token_string)
  1206. {
  1207. if ('\x00' <= c and c <= '\x1F')
  1208. {
  1209. // escape control characters
  1210. std::array<char, 9> cs{{}};
  1211. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  1212. result += cs.data();
  1213. }
  1214. else
  1215. {
  1216. // add character as is
  1217. result.push_back(c);
  1218. }
  1219. }
  1220. return result;
  1221. }
  1222. /// return syntax error message
  1223. JSON_HEDLEY_RETURNS_NON_NULL
  1224. constexpr const char* get_error_message() const noexcept
  1225. {
  1226. return error_message;
  1227. }
  1228. /////////////////////
  1229. // actual scanner
  1230. /////////////////////
  1231. /*!
  1232. @brief skip the UTF-8 byte order mark
  1233. @return true iff there is no BOM or the correct BOM has been skipped
  1234. */
  1235. bool skip_bom()
  1236. {
  1237. if (get() == 0xEF)
  1238. {
  1239. // check if we completely parse the BOM
  1240. return get() == 0xBB and get() == 0xBF;
  1241. }
  1242. // the first character is not the beginning of the BOM; unget it to
  1243. // process is later
  1244. unget();
  1245. return true;
  1246. }
  1247. token_type scan()
  1248. {
  1249. // initially, skip the BOM
  1250. if (position.chars_read_total == 0 and not skip_bom())
  1251. {
  1252. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  1253. return token_type::parse_error;
  1254. }
  1255. // read next character and ignore whitespace
  1256. do
  1257. {
  1258. get();
  1259. }
  1260. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  1261. switch (current)
  1262. {
  1263. // structural characters
  1264. case '[':
  1265. return token_type::begin_array;
  1266. case ']':
  1267. return token_type::end_array;
  1268. case '{':
  1269. return token_type::begin_object;
  1270. case '}':
  1271. return token_type::end_object;
  1272. case ':':
  1273. return token_type::name_separator;
  1274. case ',':
  1275. return token_type::value_separator;
  1276. // literals
  1277. case 't':
  1278. return scan_literal("true", 4, token_type::literal_true);
  1279. case 'f':
  1280. return scan_literal("false", 5, token_type::literal_false);
  1281. case 'n':
  1282. return scan_literal("null", 4, token_type::literal_null);
  1283. // string
  1284. case '\"':
  1285. return scan_string();
  1286. // number
  1287. case '-':
  1288. case '0':
  1289. case '1':
  1290. case '2':
  1291. case '3':
  1292. case '4':
  1293. case '5':
  1294. case '6':
  1295. case '7':
  1296. case '8':
  1297. case '9':
  1298. return scan_number();
  1299. // end of input (the null byte is needed when parsing from
  1300. // string literals)
  1301. case '\0':
  1302. case std::char_traits<char>::eof():
  1303. return token_type::end_of_input;
  1304. // error
  1305. default:
  1306. error_message = "invalid literal";
  1307. return token_type::parse_error;
  1308. }
  1309. }
  1310. private:
  1311. /// input adapter
  1312. detail::input_adapter_t ia = nullptr;
  1313. /// the current character
  1314. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  1315. /// whether the next get() call should just return current
  1316. bool next_unget = false;
  1317. /// the start position of the current token
  1318. position_t position {};
  1319. /// raw input token string (for error messages)
  1320. std::vector<char> token_string {};
  1321. /// buffer for variable-length tokens (numbers, strings)
  1322. string_t token_buffer {};
  1323. /// a description of occurred lexer errors
  1324. const char* error_message = "";
  1325. // number values
  1326. number_integer_t value_integer = 0;
  1327. number_unsigned_t value_unsigned = 0;
  1328. number_float_t value_float = 0;
  1329. /// the decimal point
  1330. const char decimal_point_char = '.';
  1331. };
  1332. } // namespace detail
  1333. } // namespace nlohmann