Lexer.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Lexer.h"
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/Debug.h>
  10. #include <AK/GenericLexer.h>
  11. #include <AK/HashMap.h>
  12. #include <AK/Utf8View.h>
  13. #include <LibUnicode/CharacterTypes.h>
  14. #include <stdio.h>
  15. namespace JS {
  16. HashMap<DeprecatedFlyString, TokenType> Lexer::s_keywords;
  17. static constexpr TokenType parse_two_char_token(StringView view)
  18. {
  19. if (view.length() != 2)
  20. return TokenType::Invalid;
  21. auto const* bytes = view.bytes().data();
  22. switch (bytes[0]) {
  23. case '=':
  24. switch (bytes[1]) {
  25. case '>':
  26. return TokenType::Arrow;
  27. case '=':
  28. return TokenType::EqualsEquals;
  29. default:
  30. return TokenType::Invalid;
  31. }
  32. case '+':
  33. switch (bytes[1]) {
  34. case '=':
  35. return TokenType::PlusEquals;
  36. case '+':
  37. return TokenType::PlusPlus;
  38. default:
  39. return TokenType::Invalid;
  40. }
  41. case '-':
  42. switch (bytes[1]) {
  43. case '=':
  44. return TokenType::MinusEquals;
  45. case '-':
  46. return TokenType::MinusMinus;
  47. default:
  48. return TokenType::Invalid;
  49. }
  50. case '*':
  51. switch (bytes[1]) {
  52. case '=':
  53. return TokenType::AsteriskEquals;
  54. case '*':
  55. return TokenType::DoubleAsterisk;
  56. default:
  57. return TokenType::Invalid;
  58. }
  59. case '/':
  60. switch (bytes[1]) {
  61. case '=':
  62. return TokenType::SlashEquals;
  63. default:
  64. return TokenType::Invalid;
  65. }
  66. case '%':
  67. switch (bytes[1]) {
  68. case '=':
  69. return TokenType::PercentEquals;
  70. default:
  71. return TokenType::Invalid;
  72. }
  73. case '&':
  74. switch (bytes[1]) {
  75. case '=':
  76. return TokenType::AmpersandEquals;
  77. case '&':
  78. return TokenType::DoubleAmpersand;
  79. default:
  80. return TokenType::Invalid;
  81. }
  82. case '|':
  83. switch (bytes[1]) {
  84. case '=':
  85. return TokenType::PipeEquals;
  86. case '|':
  87. return TokenType::DoublePipe;
  88. default:
  89. return TokenType::Invalid;
  90. }
  91. case '^':
  92. switch (bytes[1]) {
  93. case '=':
  94. return TokenType::CaretEquals;
  95. default:
  96. return TokenType::Invalid;
  97. }
  98. case '<':
  99. switch (bytes[1]) {
  100. case '=':
  101. return TokenType::LessThanEquals;
  102. case '<':
  103. return TokenType::ShiftLeft;
  104. default:
  105. return TokenType::Invalid;
  106. }
  107. case '>':
  108. switch (bytes[1]) {
  109. case '=':
  110. return TokenType::GreaterThanEquals;
  111. case '>':
  112. return TokenType::ShiftRight;
  113. default:
  114. return TokenType::Invalid;
  115. }
  116. case '?':
  117. switch (bytes[1]) {
  118. case '?':
  119. return TokenType::DoubleQuestionMark;
  120. case '.':
  121. return TokenType::QuestionMarkPeriod;
  122. default:
  123. return TokenType::Invalid;
  124. }
  125. case '!':
  126. switch (bytes[1]) {
  127. case '=':
  128. return TokenType::ExclamationMarkEquals;
  129. default:
  130. return TokenType::Invalid;
  131. }
  132. default:
  133. return TokenType::Invalid;
  134. }
  135. }
  136. static constexpr TokenType parse_three_char_token(StringView view)
  137. {
  138. if (view.length() != 3)
  139. return TokenType::Invalid;
  140. auto const* bytes = view.bytes().data();
  141. switch (bytes[0]) {
  142. case '<':
  143. if (bytes[1] == '<' && bytes[2] == '=')
  144. return TokenType::ShiftLeftEquals;
  145. return TokenType::Invalid;
  146. case '>':
  147. if (bytes[1] == '>' && bytes[2] == '=')
  148. return TokenType::ShiftRightEquals;
  149. if (bytes[1] == '>' && bytes[2] == '>')
  150. return TokenType::UnsignedShiftRight;
  151. return TokenType::Invalid;
  152. case '=':
  153. if (bytes[1] == '=' && bytes[2] == '=')
  154. return TokenType::EqualsEqualsEquals;
  155. return TokenType::Invalid;
  156. case '!':
  157. if (bytes[1] == '=' && bytes[2] == '=')
  158. return TokenType::ExclamationMarkEqualsEquals;
  159. return TokenType::Invalid;
  160. case '.':
  161. if (bytes[1] == '.' && bytes[2] == '.')
  162. return TokenType::TripleDot;
  163. return TokenType::Invalid;
  164. case '*':
  165. if (bytes[1] == '*' && bytes[2] == '=')
  166. return TokenType::DoubleAsteriskEquals;
  167. return TokenType::Invalid;
  168. case '&':
  169. if (bytes[1] == '&' && bytes[2] == '=')
  170. return TokenType::DoubleAmpersandEquals;
  171. return TokenType::Invalid;
  172. case '|':
  173. if (bytes[1] == '|' && bytes[2] == '=')
  174. return TokenType::DoublePipeEquals;
  175. return TokenType::Invalid;
  176. case '?':
  177. if (bytes[1] == '?' && bytes[2] == '=')
  178. return TokenType::DoubleQuestionMarkEquals;
  179. return TokenType::Invalid;
  180. default:
  181. return TokenType::Invalid;
  182. }
  183. }
  184. static consteval Array<TokenType, 256> make_single_char_tokens_array()
  185. {
  186. Array<TokenType, 256> array;
  187. array.fill(TokenType::Invalid);
  188. array['&'] = TokenType::Ampersand;
  189. array['*'] = TokenType::Asterisk;
  190. array['['] = TokenType::BracketOpen;
  191. array[']'] = TokenType::BracketClose;
  192. array['^'] = TokenType::Caret;
  193. array[':'] = TokenType::Colon;
  194. array[','] = TokenType::Comma;
  195. array['{'] = TokenType::CurlyOpen;
  196. array['}'] = TokenType::CurlyClose;
  197. array['='] = TokenType::Equals;
  198. array['!'] = TokenType::ExclamationMark;
  199. array['-'] = TokenType::Minus;
  200. array['('] = TokenType::ParenOpen;
  201. array[')'] = TokenType::ParenClose;
  202. array['%'] = TokenType::Percent;
  203. array['.'] = TokenType::Period;
  204. array['|'] = TokenType::Pipe;
  205. array['+'] = TokenType::Plus;
  206. array['?'] = TokenType::QuestionMark;
  207. array[';'] = TokenType::Semicolon;
  208. array['/'] = TokenType::Slash;
  209. array['~'] = TokenType::Tilde;
  210. array['<'] = TokenType::LessThan;
  211. array['>'] = TokenType::GreaterThan;
  212. return array;
  213. }
  214. static constexpr auto s_single_char_tokens = make_single_char_tokens_array();
  215. Lexer::Lexer(StringView source, StringView filename, size_t line_number, size_t line_column)
  216. : m_source(source)
  217. , m_current_token(TokenType::Eof, {}, {}, {}, 0, 0, 0)
  218. , m_filename(String::from_utf8(filename).release_value_but_fixme_should_propagate_errors())
  219. , m_line_number(line_number)
  220. , m_line_column(line_column)
  221. , m_parsed_identifiers(adopt_ref(*new ParsedIdentifiers))
  222. {
  223. if (s_keywords.is_empty()) {
  224. s_keywords.set("async", TokenType::Async);
  225. s_keywords.set("await", TokenType::Await);
  226. s_keywords.set("break", TokenType::Break);
  227. s_keywords.set("case", TokenType::Case);
  228. s_keywords.set("catch", TokenType::Catch);
  229. s_keywords.set("class", TokenType::Class);
  230. s_keywords.set("const", TokenType::Const);
  231. s_keywords.set("continue", TokenType::Continue);
  232. s_keywords.set("debugger", TokenType::Debugger);
  233. s_keywords.set("default", TokenType::Default);
  234. s_keywords.set("delete", TokenType::Delete);
  235. s_keywords.set("do", TokenType::Do);
  236. s_keywords.set("else", TokenType::Else);
  237. s_keywords.set("enum", TokenType::Enum);
  238. s_keywords.set("export", TokenType::Export);
  239. s_keywords.set("extends", TokenType::Extends);
  240. s_keywords.set("false", TokenType::BoolLiteral);
  241. s_keywords.set("finally", TokenType::Finally);
  242. s_keywords.set("for", TokenType::For);
  243. s_keywords.set("function", TokenType::Function);
  244. s_keywords.set("if", TokenType::If);
  245. s_keywords.set("import", TokenType::Import);
  246. s_keywords.set("in", TokenType::In);
  247. s_keywords.set("instanceof", TokenType::Instanceof);
  248. s_keywords.set("let", TokenType::Let);
  249. s_keywords.set("new", TokenType::New);
  250. s_keywords.set("null", TokenType::NullLiteral);
  251. s_keywords.set("return", TokenType::Return);
  252. s_keywords.set("super", TokenType::Super);
  253. s_keywords.set("switch", TokenType::Switch);
  254. s_keywords.set("this", TokenType::This);
  255. s_keywords.set("throw", TokenType::Throw);
  256. s_keywords.set("true", TokenType::BoolLiteral);
  257. s_keywords.set("try", TokenType::Try);
  258. s_keywords.set("typeof", TokenType::Typeof);
  259. s_keywords.set("var", TokenType::Var);
  260. s_keywords.set("void", TokenType::Void);
  261. s_keywords.set("while", TokenType::While);
  262. s_keywords.set("with", TokenType::With);
  263. s_keywords.set("yield", TokenType::Yield);
  264. }
  265. consume();
  266. }
  267. void Lexer::consume()
  268. {
  269. auto did_reach_eof = [this] {
  270. if (m_position < m_source.length())
  271. return false;
  272. m_eof = true;
  273. m_current_char = '\0';
  274. m_position = m_source.length() + 1;
  275. m_line_column++;
  276. return true;
  277. };
  278. if (m_position > m_source.length())
  279. return;
  280. if (did_reach_eof())
  281. return;
  282. if (is_line_terminator()) {
  283. if constexpr (LEXER_DEBUG) {
  284. ByteString type;
  285. if (m_current_char == '\n')
  286. type = "LINE FEED";
  287. else if (m_current_char == '\r')
  288. type = "CARRIAGE RETURN";
  289. else if (m_source[m_position + 1] == (char)0xa8)
  290. type = "LINE SEPARATOR";
  291. else
  292. type = "PARAGRAPH SEPARATOR";
  293. dbgln("Found a line terminator: {}", type);
  294. }
  295. // This is a three-char line terminator, we need to increase m_position some more.
  296. // We might reach EOF and need to check again.
  297. if (m_current_char != '\n' && m_current_char != '\r') {
  298. m_position += 2;
  299. if (did_reach_eof())
  300. return;
  301. }
  302. // If the previous character is \r and the current one \n we already updated line number
  303. // and column - don't do it again. From https://tc39.es/ecma262/#sec-line-terminators:
  304. // The sequence <CR><LF> is commonly used as a line terminator.
  305. // It should be considered a single SourceCharacter for the purpose of reporting line numbers.
  306. auto second_char_of_crlf = m_position > 1 && m_source[m_position - 2] == '\r' && m_current_char == '\n';
  307. if (!second_char_of_crlf) {
  308. m_line_number++;
  309. m_line_column = 1;
  310. dbgln_if(LEXER_DEBUG, "Incremented line number, now at: line {}, column 1", m_line_number);
  311. } else {
  312. dbgln_if(LEXER_DEBUG, "Previous was CR, this is LF - not incrementing line number again.");
  313. }
  314. } else if (is_unicode_character()) {
  315. size_t char_size = 1;
  316. if ((m_current_char & 64) == 0) {
  317. m_hit_invalid_unicode = m_position;
  318. } else if ((m_current_char & 32) == 0) {
  319. char_size = 2;
  320. } else if ((m_current_char & 16) == 0) {
  321. char_size = 3;
  322. } else if ((m_current_char & 8) == 0) {
  323. char_size = 4;
  324. }
  325. VERIFY(char_size >= 1);
  326. --char_size;
  327. for (size_t i = m_position; i < m_position + char_size; i++) {
  328. if (i >= m_source.length() || (m_source[i] & 0b11000000) != 0b10000000) {
  329. m_hit_invalid_unicode = m_position;
  330. break;
  331. }
  332. }
  333. if (m_hit_invalid_unicode.has_value())
  334. m_position = m_source.length();
  335. else
  336. m_position += char_size;
  337. if (did_reach_eof())
  338. return;
  339. m_line_column++;
  340. } else {
  341. m_line_column++;
  342. }
  343. m_current_char = m_source[m_position++];
  344. }
  345. bool Lexer::consume_decimal_number()
  346. {
  347. if (!is_ascii_digit(m_current_char))
  348. return false;
  349. while (is_ascii_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_digit)) {
  350. consume();
  351. }
  352. return true;
  353. }
  354. bool Lexer::consume_exponent()
  355. {
  356. consume();
  357. if (m_current_char == '-' || m_current_char == '+')
  358. consume();
  359. if (!is_ascii_digit(m_current_char))
  360. return false;
  361. return consume_decimal_number();
  362. }
  363. static constexpr bool is_octal_digit(char ch)
  364. {
  365. return ch >= '0' && ch <= '7';
  366. }
  367. bool Lexer::consume_octal_number()
  368. {
  369. consume();
  370. if (!is_octal_digit(m_current_char))
  371. return false;
  372. while (is_octal_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_octal_digit))
  373. consume();
  374. return true;
  375. }
  376. bool Lexer::consume_hexadecimal_number()
  377. {
  378. consume();
  379. if (!is_ascii_hex_digit(m_current_char))
  380. return false;
  381. while (is_ascii_hex_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_hex_digit))
  382. consume();
  383. return true;
  384. }
  385. static constexpr bool is_binary_digit(char ch)
  386. {
  387. return ch == '0' || ch == '1';
  388. }
  389. bool Lexer::consume_binary_number()
  390. {
  391. consume();
  392. if (!is_binary_digit(m_current_char))
  393. return false;
  394. while (is_binary_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_binary_digit))
  395. consume();
  396. return true;
  397. }
  398. template<typename Callback>
  399. bool Lexer::match_numeric_literal_separator_followed_by(Callback callback) const
  400. {
  401. if (m_position >= m_source.length())
  402. return false;
  403. return m_current_char == '_'
  404. && callback(m_source[m_position]);
  405. }
  406. bool Lexer::match(char a, char b) const
  407. {
  408. if (m_position >= m_source.length())
  409. return false;
  410. return m_current_char == a
  411. && m_source[m_position] == b;
  412. }
  413. bool Lexer::match(char a, char b, char c) const
  414. {
  415. if (m_position + 1 >= m_source.length())
  416. return false;
  417. return m_current_char == a
  418. && m_source[m_position] == b
  419. && m_source[m_position + 1] == c;
  420. }
  421. bool Lexer::match(char a, char b, char c, char d) const
  422. {
  423. if (m_position + 2 >= m_source.length())
  424. return false;
  425. return m_current_char == a
  426. && m_source[m_position] == b
  427. && m_source[m_position + 1] == c
  428. && m_source[m_position + 2] == d;
  429. }
  430. bool Lexer::is_eof() const
  431. {
  432. return m_eof;
  433. }
  434. ALWAYS_INLINE bool Lexer::is_line_terminator() const
  435. {
  436. if (m_current_char == '\n' || m_current_char == '\r')
  437. return true;
  438. if (!is_unicode_character())
  439. return false;
  440. auto code_point = current_code_point();
  441. return code_point == LINE_SEPARATOR || code_point == PARAGRAPH_SEPARATOR;
  442. }
  443. ALWAYS_INLINE bool Lexer::is_unicode_character() const
  444. {
  445. return (m_current_char & 128) != 0;
  446. }
  447. ALWAYS_INLINE u32 Lexer::current_code_point() const
  448. {
  449. static constexpr u32 const REPLACEMENT_CHARACTER = 0xFFFD;
  450. if (m_position == 0)
  451. return REPLACEMENT_CHARACTER;
  452. auto substring = m_source.substring_view(m_position - 1);
  453. if (substring.is_empty())
  454. return REPLACEMENT_CHARACTER;
  455. if (is_ascii(substring[0]))
  456. return substring[0];
  457. Utf8View utf_8_view { substring };
  458. return *utf_8_view.begin();
  459. }
  460. bool Lexer::is_whitespace() const
  461. {
  462. if (is_ascii_space(m_current_char))
  463. return true;
  464. if (!is_unicode_character())
  465. return false;
  466. auto code_point = current_code_point();
  467. if (code_point == NO_BREAK_SPACE || code_point == ZERO_WIDTH_NO_BREAK_SPACE)
  468. return true;
  469. return Unicode::code_point_has_space_separator_general_category(code_point);
  470. }
  471. // UnicodeEscapeSequence :: https://tc39.es/ecma262/#prod-UnicodeEscapeSequence
  472. // u Hex4Digits
  473. // u{ CodePoint }
  474. Optional<u32> Lexer::is_identifier_unicode_escape(size_t& identifier_length) const
  475. {
  476. GenericLexer lexer(source().substring_view(m_position - 1));
  477. if (auto code_point_or_error = lexer.consume_escaped_code_point(false); !code_point_or_error.is_error()) {
  478. identifier_length = lexer.tell();
  479. return code_point_or_error.value();
  480. }
  481. return {};
  482. }
  483. // IdentifierStart :: https://tc39.es/ecma262/#prod-IdentifierStart
  484. // UnicodeIDStart
  485. // $
  486. // _
  487. // \ UnicodeEscapeSequence
  488. Optional<u32> Lexer::is_identifier_start(size_t& identifier_length) const
  489. {
  490. u32 code_point = current_code_point();
  491. identifier_length = 1;
  492. if (code_point == '\\') {
  493. if (auto maybe_code_point = is_identifier_unicode_escape(identifier_length); maybe_code_point.has_value())
  494. code_point = *maybe_code_point;
  495. else
  496. return {};
  497. }
  498. if (is_ascii_alpha(code_point) || code_point == '_' || code_point == '$')
  499. return code_point;
  500. // Optimization: the first codepoint with the ID_Start property after A-Za-z is outside the
  501. // ASCII range (0x00AA), so we can skip code_point_has_property() for any ASCII characters.
  502. if (is_ascii(code_point))
  503. return {};
  504. if (Unicode::code_point_has_identifier_start_property(code_point))
  505. return code_point;
  506. return {};
  507. }
  508. // IdentifierPart :: https://tc39.es/ecma262/#prod-IdentifierPart
  509. // UnicodeIDContinue
  510. // $
  511. // \ UnicodeEscapeSequence
  512. // <ZWNJ>
  513. // <ZWJ>
  514. Optional<u32> Lexer::is_identifier_middle(size_t& identifier_length) const
  515. {
  516. u32 code_point = current_code_point();
  517. identifier_length = 1;
  518. if (code_point == '\\') {
  519. if (auto maybe_code_point = is_identifier_unicode_escape(identifier_length); maybe_code_point.has_value())
  520. code_point = *maybe_code_point;
  521. else
  522. return {};
  523. }
  524. if (is_ascii_alphanumeric(code_point) || (code_point == '$') || (code_point == ZERO_WIDTH_NON_JOINER) || (code_point == ZERO_WIDTH_JOINER))
  525. return code_point;
  526. // Optimization: the first codepoint with the ID_Continue property after A-Za-z0-9_ is outside the
  527. // ASCII range (0x00AA), so we can skip code_point_has_property() for any ASCII characters.
  528. if (code_point == '_')
  529. return code_point;
  530. if (is_ascii(code_point))
  531. return {};
  532. if (Unicode::code_point_has_identifier_continue_property(code_point))
  533. return code_point;
  534. return {};
  535. }
  536. bool Lexer::is_line_comment_start(bool line_has_token_yet) const
  537. {
  538. return match('/', '/')
  539. || (m_allow_html_comments && match('<', '!', '-', '-'))
  540. // "-->" is considered a line comment start if the current line is only whitespace and/or
  541. // other block comment(s); or in other words: the current line does not have a token or
  542. // ongoing line comment yet
  543. || (m_allow_html_comments && !line_has_token_yet && match('-', '-', '>'))
  544. // https://tc39.es/ecma262/#sec-hashbang
  545. || (match('#', '!') && m_position == 1);
  546. }
  547. bool Lexer::is_block_comment_start() const
  548. {
  549. return match('/', '*');
  550. }
  551. bool Lexer::is_block_comment_end() const
  552. {
  553. return match('*', '/');
  554. }
  555. bool Lexer::is_numeric_literal_start() const
  556. {
  557. return is_ascii_digit(m_current_char) || (m_current_char == '.' && m_position < m_source.length() && is_ascii_digit(m_source[m_position]));
  558. }
  559. bool Lexer::slash_means_division() const
  560. {
  561. auto type = m_current_token.type();
  562. return m_current_token.is_identifier_name()
  563. || type == TokenType::BigIntLiteral
  564. || type == TokenType::BracketClose
  565. || type == TokenType::CurlyClose
  566. || type == TokenType::MinusMinus
  567. || type == TokenType::NumericLiteral
  568. || type == TokenType::ParenClose
  569. || type == TokenType::PlusPlus
  570. || type == TokenType::PrivateIdentifier
  571. || type == TokenType::RegexLiteral
  572. || type == TokenType::StringLiteral
  573. || type == TokenType::TemplateLiteralEnd;
  574. }
  575. Token Lexer::next()
  576. {
  577. size_t trivia_start = m_position;
  578. auto in_template = !m_template_states.is_empty();
  579. bool line_has_token_yet = m_line_column > 1;
  580. bool unterminated_comment = false;
  581. if (!in_template || m_template_states.last().in_expr) {
  582. // consume whitespace and comments
  583. while (true) {
  584. if (is_line_terminator()) {
  585. line_has_token_yet = false;
  586. do {
  587. consume();
  588. } while (is_line_terminator());
  589. } else if (is_whitespace()) {
  590. do {
  591. consume();
  592. } while (is_whitespace());
  593. } else if (is_line_comment_start(line_has_token_yet)) {
  594. consume();
  595. do {
  596. consume();
  597. } while (!is_eof() && !is_line_terminator());
  598. } else if (is_block_comment_start()) {
  599. size_t start_line_number = m_line_number;
  600. consume();
  601. do {
  602. consume();
  603. } while (!is_eof() && !is_block_comment_end());
  604. if (is_eof())
  605. unterminated_comment = true;
  606. consume(); // consume *
  607. if (is_eof())
  608. unterminated_comment = true;
  609. consume(); // consume /
  610. if (start_line_number != m_line_number)
  611. line_has_token_yet = false;
  612. } else {
  613. break;
  614. }
  615. }
  616. }
  617. size_t value_start = m_position;
  618. size_t value_start_line_number = m_line_number;
  619. size_t value_start_column_number = m_line_column;
  620. auto token_type = TokenType::Invalid;
  621. auto did_consume_whitespace_or_comments = trivia_start != value_start;
  622. // This is being used to communicate info about invalid tokens to the parser, which then
  623. // can turn that into more specific error messages - instead of us having to make up a
  624. // bunch of Invalid* tokens (bad numeric literals, unterminated comments etc.)
  625. StringView token_message;
  626. Optional<DeprecatedFlyString> identifier;
  627. size_t identifier_length = 0;
  628. if (m_current_token.type() == TokenType::RegexLiteral && !is_eof() && is_ascii_alpha(m_current_char) && !did_consume_whitespace_or_comments) {
  629. token_type = TokenType::RegexFlags;
  630. while (!is_eof() && is_ascii_alpha(m_current_char))
  631. consume();
  632. } else if (m_current_char == '`') {
  633. consume();
  634. if (!in_template) {
  635. token_type = TokenType::TemplateLiteralStart;
  636. m_template_states.append({ false, 0 });
  637. } else {
  638. if (m_template_states.last().in_expr) {
  639. m_template_states.append({ false, 0 });
  640. token_type = TokenType::TemplateLiteralStart;
  641. } else {
  642. m_template_states.take_last();
  643. token_type = TokenType::TemplateLiteralEnd;
  644. }
  645. }
  646. } else if (in_template && m_template_states.last().in_expr && m_template_states.last().open_bracket_count == 0 && m_current_char == '}') {
  647. consume();
  648. token_type = TokenType::TemplateLiteralExprEnd;
  649. m_template_states.last().in_expr = false;
  650. } else if (in_template && !m_template_states.last().in_expr) {
  651. if (is_eof()) {
  652. token_type = TokenType::UnterminatedTemplateLiteral;
  653. m_template_states.take_last();
  654. } else if (match('$', '{')) {
  655. token_type = TokenType::TemplateLiteralExprStart;
  656. consume();
  657. consume();
  658. m_template_states.last().in_expr = true;
  659. } else {
  660. // TemplateCharacter ::
  661. // $ [lookahead ≠ {]
  662. // \ TemplateEscapeSequence
  663. // \ NotEscapeSequence
  664. // LineContinuation
  665. // LineTerminatorSequence
  666. // SourceCharacter but not one of ` or \ or $ or LineTerminator
  667. while (!match('$', '{') && m_current_char != '`' && !is_eof()) {
  668. if (match('\\', '$') || match('\\', '`') || match('\\', '\\'))
  669. consume();
  670. consume();
  671. }
  672. if (is_eof() && !m_template_states.is_empty())
  673. token_type = TokenType::UnterminatedTemplateLiteral;
  674. else
  675. token_type = TokenType::TemplateLiteralString;
  676. }
  677. } else if (m_current_char == '#') {
  678. // Note: This has some duplicated code with the identifier lexing below
  679. consume();
  680. auto code_point = is_identifier_start(identifier_length);
  681. if (code_point.has_value()) {
  682. StringBuilder builder;
  683. builder.append_code_point('#');
  684. do {
  685. builder.append_code_point(*code_point);
  686. for (size_t i = 0; i < identifier_length; ++i)
  687. consume();
  688. code_point = is_identifier_middle(identifier_length);
  689. } while (code_point.has_value());
  690. identifier = builder.string_view();
  691. token_type = TokenType::PrivateIdentifier;
  692. m_parsed_identifiers->identifiers.set(*identifier);
  693. } else {
  694. token_type = TokenType::Invalid;
  695. token_message = "Start of private name '#' but not followed by valid identifier"sv;
  696. }
  697. } else if (auto code_point = is_identifier_start(identifier_length); code_point.has_value()) {
  698. bool has_escaped_character = false;
  699. // identifier or keyword
  700. StringBuilder builder;
  701. do {
  702. builder.append_code_point(*code_point);
  703. for (size_t i = 0; i < identifier_length; ++i)
  704. consume();
  705. has_escaped_character |= identifier_length > 1;
  706. code_point = is_identifier_middle(identifier_length);
  707. } while (code_point.has_value());
  708. identifier = builder.string_view();
  709. m_parsed_identifiers->identifiers.set(*identifier);
  710. auto it = s_keywords.find(identifier->hash(), [&](auto& entry) { return entry.key == identifier; });
  711. if (it == s_keywords.end())
  712. token_type = TokenType::Identifier;
  713. else
  714. token_type = has_escaped_character ? TokenType::EscapedKeyword : it->value;
  715. } else if (is_numeric_literal_start()) {
  716. token_type = TokenType::NumericLiteral;
  717. bool is_invalid_numeric_literal = false;
  718. if (m_current_char == '0') {
  719. consume();
  720. if (m_current_char == '.') {
  721. // decimal
  722. consume();
  723. while (is_ascii_digit(m_current_char))
  724. consume();
  725. if (m_current_char == 'e' || m_current_char == 'E')
  726. is_invalid_numeric_literal = !consume_exponent();
  727. } else if (m_current_char == 'e' || m_current_char == 'E') {
  728. is_invalid_numeric_literal = !consume_exponent();
  729. } else if (m_current_char == 'o' || m_current_char == 'O') {
  730. // octal
  731. is_invalid_numeric_literal = !consume_octal_number();
  732. if (m_current_char == 'n') {
  733. consume();
  734. token_type = TokenType::BigIntLiteral;
  735. }
  736. } else if (m_current_char == 'b' || m_current_char == 'B') {
  737. // binary
  738. is_invalid_numeric_literal = !consume_binary_number();
  739. if (m_current_char == 'n') {
  740. consume();
  741. token_type = TokenType::BigIntLiteral;
  742. }
  743. } else if (m_current_char == 'x' || m_current_char == 'X') {
  744. // hexadecimal
  745. is_invalid_numeric_literal = !consume_hexadecimal_number();
  746. if (m_current_char == 'n') {
  747. consume();
  748. token_type = TokenType::BigIntLiteral;
  749. }
  750. } else if (m_current_char == 'n') {
  751. consume();
  752. token_type = TokenType::BigIntLiteral;
  753. } else if (is_ascii_digit(m_current_char)) {
  754. // octal without '0o' prefix. Forbidden in 'strict mode'
  755. do {
  756. consume();
  757. } while (is_ascii_digit(m_current_char));
  758. }
  759. } else {
  760. // 1...9 or period
  761. while (is_ascii_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_digit))
  762. consume();
  763. if (m_current_char == 'n') {
  764. consume();
  765. token_type = TokenType::BigIntLiteral;
  766. } else {
  767. if (m_current_char == '.') {
  768. consume();
  769. if (m_current_char == '_')
  770. is_invalid_numeric_literal = true;
  771. while (is_ascii_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_digit)) {
  772. consume();
  773. }
  774. }
  775. if (m_current_char == 'e' || m_current_char == 'E')
  776. is_invalid_numeric_literal = is_invalid_numeric_literal || !consume_exponent();
  777. }
  778. }
  779. if (is_invalid_numeric_literal) {
  780. token_type = TokenType::Invalid;
  781. token_message = "Invalid numeric literal"sv;
  782. }
  783. } else if (m_current_char == '"' || m_current_char == '\'') {
  784. char stop_char = m_current_char;
  785. consume();
  786. // Note: LS/PS line terminators are allowed in string literals.
  787. while (m_current_char != stop_char && m_current_char != '\r' && m_current_char != '\n' && !is_eof()) {
  788. if (m_current_char == '\\') {
  789. consume();
  790. if (m_current_char == '\r' && m_position < m_source.length() && m_source[m_position] == '\n') {
  791. consume();
  792. }
  793. }
  794. consume();
  795. }
  796. if (m_current_char != stop_char) {
  797. token_type = TokenType::UnterminatedStringLiteral;
  798. } else {
  799. consume();
  800. token_type = TokenType::StringLiteral;
  801. }
  802. } else if (m_current_char == '/' && !slash_means_division()) {
  803. consume();
  804. token_type = consume_regex_literal();
  805. } else if (m_eof) {
  806. if (unterminated_comment) {
  807. token_type = TokenType::Invalid;
  808. token_message = "Unterminated multi-line comment"sv;
  809. } else {
  810. token_type = TokenType::Eof;
  811. }
  812. } else {
  813. // There is only one four-char operator: >>>=
  814. bool found_four_char_token = false;
  815. if (match('>', '>', '>', '=')) {
  816. found_four_char_token = true;
  817. consume();
  818. consume();
  819. consume();
  820. consume();
  821. token_type = TokenType::UnsignedShiftRightEquals;
  822. }
  823. bool found_three_char_token = false;
  824. if (!found_four_char_token && m_position + 1 < m_source.length()) {
  825. auto three_chars_view = m_source.substring_view(m_position - 1, 3);
  826. if (auto type = parse_three_char_token(three_chars_view); type != TokenType::Invalid) {
  827. found_three_char_token = true;
  828. consume();
  829. consume();
  830. consume();
  831. token_type = type;
  832. }
  833. }
  834. bool found_two_char_token = false;
  835. if (!found_four_char_token && !found_three_char_token && m_position < m_source.length()) {
  836. auto two_chars_view = m_source.substring_view(m_position - 1, 2);
  837. if (auto type = parse_two_char_token(two_chars_view); type != TokenType::Invalid) {
  838. // OptionalChainingPunctuator :: ?. [lookahead ∉ DecimalDigit]
  839. if (!(type == TokenType::QuestionMarkPeriod && m_position + 1 < m_source.length() && is_ascii_digit(m_source[m_position + 1]))) {
  840. found_two_char_token = true;
  841. consume();
  842. consume();
  843. token_type = type;
  844. }
  845. }
  846. }
  847. bool found_one_char_token = false;
  848. if (!found_four_char_token && !found_three_char_token && !found_two_char_token) {
  849. if (auto type = s_single_char_tokens[static_cast<u8>(m_current_char)]; type != TokenType::Invalid) {
  850. found_one_char_token = true;
  851. consume();
  852. token_type = type;
  853. }
  854. }
  855. if (!found_four_char_token && !found_three_char_token && !found_two_char_token && !found_one_char_token) {
  856. consume();
  857. token_type = TokenType::Invalid;
  858. }
  859. }
  860. if (!m_template_states.is_empty() && m_template_states.last().in_expr) {
  861. if (token_type == TokenType::CurlyOpen) {
  862. m_template_states.last().open_bracket_count++;
  863. } else if (token_type == TokenType::CurlyClose) {
  864. m_template_states.last().open_bracket_count--;
  865. }
  866. }
  867. if (m_hit_invalid_unicode.has_value()) {
  868. value_start = m_hit_invalid_unicode.value() - 1;
  869. m_current_token = Token(TokenType::Invalid, "Invalid unicode codepoint in source"_string,
  870. ""sv, // Since the invalid unicode can occur anywhere in the current token the trivia is not correct
  871. m_source.substring_view(value_start + 1, min(4u, m_source.length() - value_start - 2)),
  872. m_line_number,
  873. m_line_column - 1,
  874. value_start + 1);
  875. m_hit_invalid_unicode.clear();
  876. // Do not produce any further tokens.
  877. VERIFY(is_eof());
  878. } else {
  879. m_current_token = Token(
  880. token_type,
  881. token_message,
  882. m_source.substring_view(trivia_start - 1, value_start - trivia_start),
  883. m_source.substring_view(value_start - 1, m_position - value_start),
  884. value_start_line_number,
  885. value_start_column_number,
  886. value_start - 1);
  887. }
  888. if (identifier.has_value())
  889. m_current_token.set_identifier_value(identifier.release_value());
  890. if constexpr (LEXER_DEBUG) {
  891. dbgln("------------------------------");
  892. dbgln("Token: {}", m_current_token.name());
  893. dbgln("Trivia: _{}_", m_current_token.trivia());
  894. dbgln("Value: _{}_", m_current_token.value());
  895. dbgln("Line: {}, Column: {}", m_current_token.line_number(), m_current_token.line_column());
  896. dbgln("------------------------------");
  897. }
  898. return m_current_token;
  899. }
  900. Token Lexer::force_slash_as_regex()
  901. {
  902. VERIFY(m_current_token.type() == TokenType::Slash || m_current_token.type() == TokenType::SlashEquals);
  903. bool has_equals = m_current_token.type() == TokenType::SlashEquals;
  904. VERIFY(m_position > 0);
  905. size_t value_start = m_position - 1;
  906. if (has_equals) {
  907. VERIFY(m_source[value_start - 1] == '=');
  908. --value_start;
  909. --m_position;
  910. m_current_char = '=';
  911. }
  912. TokenType token_type = consume_regex_literal();
  913. m_current_token = Token(
  914. token_type,
  915. String {},
  916. m_current_token.trivia(),
  917. m_source.substring_view(value_start - 1, m_position - value_start),
  918. m_current_token.line_number(),
  919. m_current_token.line_column(),
  920. value_start - 1);
  921. if constexpr (LEXER_DEBUG) {
  922. dbgln("------------------------------");
  923. dbgln("Token: {}", m_current_token.name());
  924. dbgln("Trivia: _{}_", m_current_token.trivia());
  925. dbgln("Value: _{}_", m_current_token.value());
  926. dbgln("Line: {}, Column: {}", m_current_token.line_number(), m_current_token.line_column());
  927. dbgln("------------------------------");
  928. }
  929. return m_current_token;
  930. }
  931. TokenType Lexer::consume_regex_literal()
  932. {
  933. while (!is_eof()) {
  934. if (is_line_terminator() || (!m_regex_is_in_character_class && m_current_char == '/')) {
  935. break;
  936. } else if (m_current_char == '[') {
  937. m_regex_is_in_character_class = true;
  938. } else if (m_current_char == ']') {
  939. m_regex_is_in_character_class = false;
  940. } else if (!m_regex_is_in_character_class && m_current_char == '/') {
  941. break;
  942. }
  943. if (match('\\', '/') || match('\\', '[') || match('\\', '\\') || (m_regex_is_in_character_class && match('\\', ']')))
  944. consume();
  945. consume();
  946. }
  947. if (m_current_char == '/') {
  948. consume();
  949. return TokenType::RegexLiteral;
  950. }
  951. return TokenType::UnterminatedRegexLiteral;
  952. }
  953. }