Lexer.cpp 29 KB

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