Lexer.cpp 31 KB

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