Lexer.cpp 33 KB

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