Lexer.cpp 33 KB

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