lexer.hpp 41 KB

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