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. , 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. static auto id_start_category = Unicode::property_from_string("ID_Start"sv);
  358. if (id_start_category.has_value() && Unicode::code_point_has_property(code_point, *id_start_category))
  359. return code_point;
  360. return {};
  361. }
  362. // IdentifierPart :: https://tc39.es/ecma262/#prod-IdentifierPart
  363. // UnicodeIDContinue
  364. // $
  365. // \ UnicodeEscapeSequence
  366. // <ZWNJ>
  367. // <ZWJ>
  368. Optional<u32> Lexer::is_identifier_middle(size_t& identifier_length) const
  369. {
  370. u32 code_point = current_code_point();
  371. identifier_length = 1;
  372. if (code_point == '\\') {
  373. if (auto maybe_code_point = is_identifier_unicode_escape(identifier_length); maybe_code_point.has_value())
  374. code_point = *maybe_code_point;
  375. else
  376. return {};
  377. }
  378. if (is_ascii_alphanumeric(code_point) || (code_point == '$') || (code_point == ZERO_WIDTH_NON_JOINER) || (code_point == ZERO_WIDTH_JOINER))
  379. return code_point;
  380. static auto id_continue_category = Unicode::property_from_string("ID_Continue"sv);
  381. if (id_continue_category.has_value() && Unicode::code_point_has_property(code_point, *id_continue_category))
  382. return code_point;
  383. return {};
  384. }
  385. bool Lexer::is_line_comment_start(bool line_has_token_yet) const
  386. {
  387. return match('/', '/')
  388. || (m_allow_html_comments && match('<', '!', '-', '-'))
  389. // "-->" is considered a line comment start if the current line is only whitespace and/or
  390. // other block comment(s); or in other words: the current line does not have a token or
  391. // ongoing line comment yet
  392. || (m_allow_html_comments && !line_has_token_yet && match('-', '-', '>'))
  393. // https://tc39.es/proposal-hashbang/out.html#sec-updated-syntax
  394. || (match('#', '!') && m_position == 1);
  395. }
  396. bool Lexer::is_block_comment_start() const
  397. {
  398. return match('/', '*');
  399. }
  400. bool Lexer::is_block_comment_end() const
  401. {
  402. return match('*', '/');
  403. }
  404. bool Lexer::is_numeric_literal_start() const
  405. {
  406. return is_ascii_digit(m_current_char) || (m_current_char == '.' && m_position < m_source.length() && is_ascii_digit(m_source[m_position]));
  407. }
  408. bool Lexer::slash_means_division() const
  409. {
  410. auto type = m_current_token.type();
  411. return type == TokenType::BigIntLiteral
  412. || type == TokenType::BoolLiteral
  413. || type == TokenType::BracketClose
  414. || type == TokenType::CurlyClose
  415. || type == TokenType::Identifier
  416. || type == TokenType::In
  417. || type == TokenType::Instanceof
  418. || type == TokenType::MinusMinus
  419. || type == TokenType::NullLiteral
  420. || type == TokenType::NumericLiteral
  421. || type == TokenType::ParenClose
  422. || type == TokenType::PlusPlus
  423. || type == TokenType::RegexLiteral
  424. || type == TokenType::StringLiteral
  425. || type == TokenType::TemplateLiteralEnd
  426. || type == TokenType::This;
  427. }
  428. Token Lexer::next()
  429. {
  430. size_t trivia_start = m_position;
  431. auto in_template = !m_template_states.is_empty();
  432. bool line_has_token_yet = m_line_column > 1;
  433. bool unterminated_comment = false;
  434. if (!in_template || m_template_states.last().in_expr) {
  435. // consume whitespace and comments
  436. while (true) {
  437. if (is_line_terminator()) {
  438. line_has_token_yet = false;
  439. do {
  440. consume();
  441. } while (is_line_terminator());
  442. } else if (is_whitespace()) {
  443. do {
  444. consume();
  445. } while (is_whitespace());
  446. } else if (is_line_comment_start(line_has_token_yet)) {
  447. consume();
  448. do {
  449. consume();
  450. } while (!is_eof() && !is_line_terminator());
  451. } else if (is_block_comment_start()) {
  452. consume();
  453. do {
  454. consume();
  455. } while (!is_eof() && !is_block_comment_end());
  456. if (is_eof())
  457. unterminated_comment = true;
  458. consume(); // consume *
  459. if (is_eof())
  460. unterminated_comment = true;
  461. consume(); // consume /
  462. } else {
  463. break;
  464. }
  465. }
  466. }
  467. size_t value_start = m_position;
  468. size_t value_start_line_number = m_line_number;
  469. size_t value_start_column_number = m_line_column;
  470. auto token_type = TokenType::Invalid;
  471. auto did_consume_whitespace_or_comments = trivia_start != value_start;
  472. // This is being used to communicate info about invalid tokens to the parser, which then
  473. // can turn that into more specific error messages - instead of us having to make up a
  474. // bunch of Invalid* tokens (bad numeric literals, unterminated comments etc.)
  475. String token_message;
  476. Optional<FlyString> identifier;
  477. size_t identifier_length = 0;
  478. if (m_current_token.type() == TokenType::RegexLiteral && !is_eof() && is_ascii_alpha(m_current_char) && !did_consume_whitespace_or_comments) {
  479. token_type = TokenType::RegexFlags;
  480. while (!is_eof() && is_ascii_alpha(m_current_char))
  481. consume();
  482. } else if (m_current_char == '`') {
  483. consume();
  484. if (!in_template) {
  485. token_type = TokenType::TemplateLiteralStart;
  486. m_template_states.append({ false, 0 });
  487. } else {
  488. if (m_template_states.last().in_expr) {
  489. m_template_states.append({ false, 0 });
  490. token_type = TokenType::TemplateLiteralStart;
  491. } else {
  492. m_template_states.take_last();
  493. token_type = TokenType::TemplateLiteralEnd;
  494. }
  495. }
  496. } else if (in_template && m_template_states.last().in_expr && m_template_states.last().open_bracket_count == 0 && m_current_char == '}') {
  497. consume();
  498. token_type = TokenType::TemplateLiteralExprEnd;
  499. m_template_states.last().in_expr = false;
  500. } else if (in_template && !m_template_states.last().in_expr) {
  501. if (is_eof()) {
  502. token_type = TokenType::UnterminatedTemplateLiteral;
  503. m_template_states.take_last();
  504. } else if (match('$', '{')) {
  505. token_type = TokenType::TemplateLiteralExprStart;
  506. consume();
  507. consume();
  508. m_template_states.last().in_expr = true;
  509. } else {
  510. while (!match('$', '{') && m_current_char != '`' && !is_eof()) {
  511. if (match('\\', '$') || match('\\', '`'))
  512. consume();
  513. consume();
  514. }
  515. if (is_eof() && !m_template_states.is_empty())
  516. token_type = TokenType::UnterminatedTemplateLiteral;
  517. else
  518. token_type = TokenType::TemplateLiteralString;
  519. }
  520. } else if (auto code_point = is_identifier_start(identifier_length); code_point.has_value()) {
  521. bool has_escaped_character = false;
  522. // identifier or keyword
  523. StringBuilder builder;
  524. do {
  525. builder.append_code_point(*code_point);
  526. for (size_t i = 0; i < identifier_length; ++i)
  527. consume();
  528. has_escaped_character |= identifier_length > 1;
  529. code_point = is_identifier_middle(identifier_length);
  530. } while (code_point.has_value());
  531. identifier = builder.build();
  532. m_parsed_identifiers->identifiers.set(*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. }