Lexer.cpp 33 KB

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