Lexer.cpp 32 KB

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