Lexer.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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, {}, {}, {}, 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. m_hit_invalid_unicode = m_position;
  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. for (size_t i = m_position; i < m_position + char_size; i++) {
  195. if (i >= m_source.length() || (m_source[i] & 0b11000000) != 0b10000000) {
  196. m_hit_invalid_unicode = m_position;
  197. break;
  198. }
  199. }
  200. if (m_hit_invalid_unicode.has_value())
  201. m_position = m_source.length();
  202. else
  203. m_position += char_size;
  204. if (did_reach_eof())
  205. return;
  206. m_line_column++;
  207. } else {
  208. m_line_column++;
  209. }
  210. m_current_char = m_source[m_position++];
  211. }
  212. bool Lexer::consume_decimal_number()
  213. {
  214. if (!is_ascii_digit(m_current_char))
  215. return false;
  216. while (is_ascii_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_digit)) {
  217. consume();
  218. }
  219. return true;
  220. }
  221. bool Lexer::consume_exponent()
  222. {
  223. consume();
  224. if (m_current_char == '-' || m_current_char == '+')
  225. consume();
  226. if (!is_ascii_digit(m_current_char))
  227. return false;
  228. return consume_decimal_number();
  229. }
  230. static constexpr bool is_octal_digit(char ch)
  231. {
  232. return ch >= '0' && ch <= '7';
  233. }
  234. bool Lexer::consume_octal_number()
  235. {
  236. consume();
  237. if (!is_octal_digit(m_current_char))
  238. return false;
  239. while (is_octal_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_octal_digit))
  240. consume();
  241. return true;
  242. }
  243. bool Lexer::consume_hexadecimal_number()
  244. {
  245. consume();
  246. if (!is_ascii_hex_digit(m_current_char))
  247. return false;
  248. while (is_ascii_hex_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_hex_digit))
  249. consume();
  250. return true;
  251. }
  252. static constexpr bool is_binary_digit(char ch)
  253. {
  254. return ch == '0' || ch == '1';
  255. }
  256. bool Lexer::consume_binary_number()
  257. {
  258. consume();
  259. if (!is_binary_digit(m_current_char))
  260. return false;
  261. while (is_binary_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_binary_digit))
  262. consume();
  263. return true;
  264. }
  265. template<typename Callback>
  266. bool Lexer::match_numeric_literal_separator_followed_by(Callback callback) const
  267. {
  268. if (m_position >= m_source.length())
  269. return false;
  270. return m_current_char == '_'
  271. && callback(m_source[m_position]);
  272. }
  273. bool Lexer::match(char a, char b) const
  274. {
  275. if (m_position >= m_source.length())
  276. return false;
  277. return m_current_char == a
  278. && m_source[m_position] == b;
  279. }
  280. bool Lexer::match(char a, char b, char c) const
  281. {
  282. if (m_position + 1 >= m_source.length())
  283. return false;
  284. return m_current_char == a
  285. && m_source[m_position] == b
  286. && m_source[m_position + 1] == c;
  287. }
  288. bool Lexer::match(char a, char b, char c, char d) const
  289. {
  290. if (m_position + 2 >= m_source.length())
  291. return false;
  292. return m_current_char == a
  293. && m_source[m_position] == b
  294. && m_source[m_position + 1] == c
  295. && m_source[m_position + 2] == d;
  296. }
  297. bool Lexer::is_eof() const
  298. {
  299. return m_eof;
  300. }
  301. ALWAYS_INLINE bool Lexer::is_line_terminator() const
  302. {
  303. if (m_current_char == '\n' || m_current_char == '\r')
  304. return true;
  305. if (!is_unicode_character())
  306. return false;
  307. auto code_point = current_code_point();
  308. return code_point == LINE_SEPARATOR || code_point == PARAGRAPH_SEPARATOR;
  309. }
  310. ALWAYS_INLINE bool Lexer::is_unicode_character() const
  311. {
  312. return (m_current_char & 128) != 0;
  313. }
  314. ALWAYS_INLINE u32 Lexer::current_code_point() const
  315. {
  316. static constexpr const u32 REPLACEMENT_CHARACTER = 0xFFFD;
  317. if (m_position == 0)
  318. return REPLACEMENT_CHARACTER;
  319. auto substring = m_source.substring_view(m_position - 1);
  320. if (substring.is_empty())
  321. return REPLACEMENT_CHARACTER;
  322. if (is_ascii(substring[0]))
  323. return substring[0];
  324. Utf8View utf_8_view { substring };
  325. return *utf_8_view.begin();
  326. }
  327. bool Lexer::is_whitespace() const
  328. {
  329. if (is_ascii_space(m_current_char))
  330. return true;
  331. if (!is_unicode_character())
  332. return false;
  333. auto code_point = current_code_point();
  334. if (code_point == NO_BREAK_SPACE || code_point == ZERO_WIDTH_NO_BREAK_SPACE)
  335. return true;
  336. static auto space_separator_category = Unicode::general_category_from_string("Space_Separator"sv);
  337. if (space_separator_category.has_value())
  338. return Unicode::code_point_has_general_category(code_point, *space_separator_category);
  339. return false;
  340. }
  341. // UnicodeEscapeSequence :: https://tc39.es/ecma262/#prod-UnicodeEscapeSequence
  342. // u Hex4Digits
  343. // u{ CodePoint }
  344. Optional<u32> Lexer::is_identifier_unicode_escape(size_t& identifier_length) const
  345. {
  346. GenericLexer lexer(source().substring_view(m_position - 1));
  347. if (auto code_point_or_error = lexer.consume_escaped_code_point(false); !code_point_or_error.is_error()) {
  348. identifier_length = lexer.tell();
  349. return code_point_or_error.value();
  350. }
  351. return {};
  352. }
  353. // IdentifierStart :: https://tc39.es/ecma262/#prod-IdentifierStart
  354. // UnicodeIDStart
  355. // $
  356. // _
  357. // \ UnicodeEscapeSequence
  358. Optional<u32> Lexer::is_identifier_start(size_t& identifier_length) const
  359. {
  360. u32 code_point = current_code_point();
  361. identifier_length = 1;
  362. if (code_point == '\\') {
  363. if (auto maybe_code_point = is_identifier_unicode_escape(identifier_length); maybe_code_point.has_value())
  364. code_point = *maybe_code_point;
  365. else
  366. return {};
  367. }
  368. if (is_ascii_alpha(code_point) || code_point == '_' || code_point == '$')
  369. return code_point;
  370. // Optimization: the first codepoint with the ID_Start property after A-Za-z is outside the
  371. // ASCII range (0x00AA), so we can skip code_point_has_property() for any ASCII characters.
  372. if (is_ascii(code_point))
  373. return {};
  374. static auto id_start_category = Unicode::property_from_string("ID_Start"sv);
  375. if (id_start_category.has_value() && Unicode::code_point_has_property(code_point, *id_start_category))
  376. return code_point;
  377. return {};
  378. }
  379. // IdentifierPart :: https://tc39.es/ecma262/#prod-IdentifierPart
  380. // UnicodeIDContinue
  381. // $
  382. // \ UnicodeEscapeSequence
  383. // <ZWNJ>
  384. // <ZWJ>
  385. Optional<u32> Lexer::is_identifier_middle(size_t& identifier_length) const
  386. {
  387. u32 code_point = current_code_point();
  388. identifier_length = 1;
  389. if (code_point == '\\') {
  390. if (auto maybe_code_point = is_identifier_unicode_escape(identifier_length); maybe_code_point.has_value())
  391. code_point = *maybe_code_point;
  392. else
  393. return {};
  394. }
  395. if (is_ascii_alphanumeric(code_point) || (code_point == '$') || (code_point == ZERO_WIDTH_NON_JOINER) || (code_point == ZERO_WIDTH_JOINER))
  396. return code_point;
  397. // Optimization: the first codepoint with the ID_Continue property after A-Za-z0-9_ is outside the
  398. // ASCII range (0x00AA), so we can skip code_point_has_property() for any ASCII characters.
  399. if (code_point == '_')
  400. return code_point;
  401. if (is_ascii(code_point))
  402. return {};
  403. static auto id_continue_category = Unicode::property_from_string("ID_Continue"sv);
  404. if (id_continue_category.has_value() && Unicode::code_point_has_property(code_point, *id_continue_category))
  405. return code_point;
  406. return {};
  407. }
  408. bool Lexer::is_line_comment_start(bool line_has_token_yet) const
  409. {
  410. return match('/', '/')
  411. || (m_allow_html_comments && match('<', '!', '-', '-'))
  412. // "-->" is considered a line comment start if the current line is only whitespace and/or
  413. // other block comment(s); or in other words: the current line does not have a token or
  414. // ongoing line comment yet
  415. || (m_allow_html_comments && !line_has_token_yet && match('-', '-', '>'))
  416. // https://tc39.es/proposal-hashbang/out.html#sec-updated-syntax
  417. || (match('#', '!') && m_position == 1);
  418. }
  419. bool Lexer::is_block_comment_start() const
  420. {
  421. return match('/', '*');
  422. }
  423. bool Lexer::is_block_comment_end() const
  424. {
  425. return match('*', '/');
  426. }
  427. bool Lexer::is_numeric_literal_start() const
  428. {
  429. return is_ascii_digit(m_current_char) || (m_current_char == '.' && m_position < m_source.length() && is_ascii_digit(m_source[m_position]));
  430. }
  431. bool Lexer::slash_means_division() const
  432. {
  433. auto type = m_current_token.type();
  434. return type == TokenType::BigIntLiteral
  435. || type == TokenType::BoolLiteral
  436. || type == TokenType::BracketClose
  437. || type == TokenType::CurlyClose
  438. || type == TokenType::Identifier
  439. || type == TokenType::In
  440. || type == TokenType::Instanceof
  441. || type == TokenType::MinusMinus
  442. || type == TokenType::NullLiteral
  443. || type == TokenType::NumericLiteral
  444. || type == TokenType::ParenClose
  445. || type == TokenType::PlusPlus
  446. || type == TokenType::PrivateIdentifier
  447. || type == TokenType::RegexLiteral
  448. || type == TokenType::StringLiteral
  449. || type == TokenType::TemplateLiteralEnd
  450. || type == TokenType::This;
  451. }
  452. Token Lexer::next()
  453. {
  454. size_t trivia_start = m_position;
  455. auto in_template = !m_template_states.is_empty();
  456. bool line_has_token_yet = m_line_column > 1;
  457. bool unterminated_comment = false;
  458. if (!in_template || m_template_states.last().in_expr) {
  459. // consume whitespace and comments
  460. while (true) {
  461. if (is_line_terminator()) {
  462. line_has_token_yet = false;
  463. do {
  464. consume();
  465. } while (is_line_terminator());
  466. } else if (is_whitespace()) {
  467. do {
  468. consume();
  469. } while (is_whitespace());
  470. } else if (is_line_comment_start(line_has_token_yet)) {
  471. consume();
  472. do {
  473. consume();
  474. } while (!is_eof() && !is_line_terminator());
  475. } else if (is_block_comment_start()) {
  476. size_t start_line_number = m_line_number;
  477. consume();
  478. do {
  479. consume();
  480. } while (!is_eof() && !is_block_comment_end());
  481. if (is_eof())
  482. unterminated_comment = true;
  483. consume(); // consume *
  484. if (is_eof())
  485. unterminated_comment = true;
  486. consume(); // consume /
  487. if (start_line_number != m_line_number)
  488. line_has_token_yet = false;
  489. } else {
  490. break;
  491. }
  492. }
  493. }
  494. size_t value_start = m_position;
  495. size_t value_start_line_number = m_line_number;
  496. size_t value_start_column_number = m_line_column;
  497. auto token_type = TokenType::Invalid;
  498. auto did_consume_whitespace_or_comments = trivia_start != value_start;
  499. // This is being used to communicate info about invalid tokens to the parser, which then
  500. // can turn that into more specific error messages - instead of us having to make up a
  501. // bunch of Invalid* tokens (bad numeric literals, unterminated comments etc.)
  502. String token_message;
  503. Optional<FlyString> identifier;
  504. size_t identifier_length = 0;
  505. if (m_current_token.type() == TokenType::RegexLiteral && !is_eof() && is_ascii_alpha(m_current_char) && !did_consume_whitespace_or_comments) {
  506. token_type = TokenType::RegexFlags;
  507. while (!is_eof() && is_ascii_alpha(m_current_char))
  508. consume();
  509. } else if (m_current_char == '`') {
  510. consume();
  511. if (!in_template) {
  512. token_type = TokenType::TemplateLiteralStart;
  513. m_template_states.append({ false, 0 });
  514. } else {
  515. if (m_template_states.last().in_expr) {
  516. m_template_states.append({ false, 0 });
  517. token_type = TokenType::TemplateLiteralStart;
  518. } else {
  519. m_template_states.take_last();
  520. token_type = TokenType::TemplateLiteralEnd;
  521. }
  522. }
  523. } else if (in_template && m_template_states.last().in_expr && m_template_states.last().open_bracket_count == 0 && m_current_char == '}') {
  524. consume();
  525. token_type = TokenType::TemplateLiteralExprEnd;
  526. m_template_states.last().in_expr = false;
  527. } else if (in_template && !m_template_states.last().in_expr) {
  528. if (is_eof()) {
  529. token_type = TokenType::UnterminatedTemplateLiteral;
  530. m_template_states.take_last();
  531. } else if (match('$', '{')) {
  532. token_type = TokenType::TemplateLiteralExprStart;
  533. consume();
  534. consume();
  535. m_template_states.last().in_expr = true;
  536. } else {
  537. while (!match('$', '{') && m_current_char != '`' && !is_eof()) {
  538. if (match('\\', '$') || match('\\', '`'))
  539. consume();
  540. consume();
  541. }
  542. if (is_eof() && !m_template_states.is_empty())
  543. token_type = TokenType::UnterminatedTemplateLiteral;
  544. else
  545. token_type = TokenType::TemplateLiteralString;
  546. }
  547. } else if (m_current_char == '#') {
  548. // Note: This has some duplicated code with the identifier lexing below
  549. consume();
  550. auto code_point = is_identifier_start(identifier_length);
  551. if (code_point.has_value()) {
  552. StringBuilder builder;
  553. builder.append_code_point('#');
  554. do {
  555. builder.append_code_point(*code_point);
  556. for (size_t i = 0; i < identifier_length; ++i)
  557. consume();
  558. code_point = is_identifier_middle(identifier_length);
  559. } while (code_point.has_value());
  560. identifier = builder.string_view();
  561. token_type = TokenType::PrivateIdentifier;
  562. m_parsed_identifiers->identifiers.set(*identifier);
  563. } else {
  564. token_type = TokenType::Invalid;
  565. token_message = "Start of private name '#' but not followed by valid identifier";
  566. }
  567. } else if (auto code_point = is_identifier_start(identifier_length); code_point.has_value()) {
  568. bool has_escaped_character = false;
  569. // identifier or keyword
  570. StringBuilder builder;
  571. do {
  572. builder.append_code_point(*code_point);
  573. for (size_t i = 0; i < identifier_length; ++i)
  574. consume();
  575. has_escaped_character |= identifier_length > 1;
  576. code_point = is_identifier_middle(identifier_length);
  577. } while (code_point.has_value());
  578. identifier = builder.string_view();
  579. m_parsed_identifiers->identifiers.set(*identifier);
  580. auto it = s_keywords.find(identifier->hash(), [&](auto& entry) { return entry.key == identifier; });
  581. if (it == s_keywords.end())
  582. token_type = TokenType::Identifier;
  583. else
  584. token_type = has_escaped_character ? TokenType::EscapedKeyword : it->value;
  585. } else if (is_numeric_literal_start()) {
  586. token_type = TokenType::NumericLiteral;
  587. bool is_invalid_numeric_literal = false;
  588. if (m_current_char == '0') {
  589. consume();
  590. if (m_current_char == '.') {
  591. // decimal
  592. consume();
  593. while (is_ascii_digit(m_current_char))
  594. consume();
  595. if (m_current_char == 'e' || m_current_char == 'E')
  596. is_invalid_numeric_literal = !consume_exponent();
  597. } else if (m_current_char == 'e' || m_current_char == 'E') {
  598. is_invalid_numeric_literal = !consume_exponent();
  599. } else if (m_current_char == 'o' || m_current_char == 'O') {
  600. // octal
  601. is_invalid_numeric_literal = !consume_octal_number();
  602. if (m_current_char == 'n') {
  603. consume();
  604. token_type = TokenType::BigIntLiteral;
  605. }
  606. } else if (m_current_char == 'b' || m_current_char == 'B') {
  607. // binary
  608. is_invalid_numeric_literal = !consume_binary_number();
  609. if (m_current_char == 'n') {
  610. consume();
  611. token_type = TokenType::BigIntLiteral;
  612. }
  613. } else if (m_current_char == 'x' || m_current_char == 'X') {
  614. // hexadecimal
  615. is_invalid_numeric_literal = !consume_hexadecimal_number();
  616. if (m_current_char == 'n') {
  617. consume();
  618. token_type = TokenType::BigIntLiteral;
  619. }
  620. } else if (m_current_char == 'n') {
  621. consume();
  622. token_type = TokenType::BigIntLiteral;
  623. } else if (is_ascii_digit(m_current_char)) {
  624. // octal without '0o' prefix. Forbidden in 'strict mode'
  625. do {
  626. consume();
  627. } while (is_ascii_digit(m_current_char));
  628. }
  629. } else {
  630. // 1...9 or period
  631. while (is_ascii_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_digit))
  632. consume();
  633. if (m_current_char == 'n') {
  634. consume();
  635. token_type = TokenType::BigIntLiteral;
  636. } else {
  637. if (m_current_char == '.') {
  638. consume();
  639. if (m_current_char == '_')
  640. is_invalid_numeric_literal = true;
  641. while (is_ascii_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_digit)) {
  642. consume();
  643. }
  644. }
  645. if (m_current_char == 'e' || m_current_char == 'E')
  646. is_invalid_numeric_literal = is_invalid_numeric_literal || !consume_exponent();
  647. }
  648. }
  649. if (is_invalid_numeric_literal) {
  650. token_type = TokenType::Invalid;
  651. token_message = "Invalid numeric literal";
  652. }
  653. } else if (m_current_char == '"' || m_current_char == '\'') {
  654. char stop_char = m_current_char;
  655. consume();
  656. // Note: LS/PS line terminators are allowed in string literals.
  657. while (m_current_char != stop_char && m_current_char != '\r' && m_current_char != '\n' && !is_eof()) {
  658. if (m_current_char == '\\') {
  659. consume();
  660. if (m_current_char == '\r' && m_position < m_source.length() && m_source[m_position] == '\n') {
  661. consume();
  662. }
  663. }
  664. consume();
  665. }
  666. if (m_current_char != stop_char) {
  667. token_type = TokenType::UnterminatedStringLiteral;
  668. } else {
  669. consume();
  670. token_type = TokenType::StringLiteral;
  671. }
  672. } else if (m_current_char == '/' && !slash_means_division()) {
  673. consume();
  674. token_type = consume_regex_literal();
  675. } else if (m_eof) {
  676. if (unterminated_comment) {
  677. token_type = TokenType::Invalid;
  678. token_message = "Unterminated multi-line comment";
  679. } else {
  680. token_type = TokenType::Eof;
  681. }
  682. } else {
  683. // There is only one four-char operator: >>>=
  684. bool found_four_char_token = false;
  685. if (match('>', '>', '>', '=')) {
  686. found_four_char_token = true;
  687. consume();
  688. consume();
  689. consume();
  690. consume();
  691. token_type = TokenType::UnsignedShiftRightEquals;
  692. }
  693. bool found_three_char_token = false;
  694. if (!found_four_char_token && m_position + 1 < m_source.length()) {
  695. auto three_chars_view = m_source.substring_view(m_position - 1, 3);
  696. auto it = s_three_char_tokens.find(three_chars_view.hash(), [&](auto& entry) { return entry.key == three_chars_view; });
  697. if (it != s_three_char_tokens.end()) {
  698. found_three_char_token = true;
  699. consume();
  700. consume();
  701. consume();
  702. token_type = it->value;
  703. }
  704. }
  705. bool found_two_char_token = false;
  706. if (!found_four_char_token && !found_three_char_token && m_position < m_source.length()) {
  707. auto two_chars_view = m_source.substring_view(m_position - 1, 2);
  708. auto it = s_two_char_tokens.find(two_chars_view.hash(), [&](auto& entry) { return entry.key == two_chars_view; });
  709. if (it != s_two_char_tokens.end()) {
  710. // OptionalChainingPunctuator :: ?. [lookahead ∉ DecimalDigit]
  711. if (!(it->value == TokenType::QuestionMarkPeriod && m_position + 1 < m_source.length() && is_ascii_digit(m_source[m_position + 1]))) {
  712. found_two_char_token = true;
  713. consume();
  714. consume();
  715. token_type = it->value;
  716. }
  717. }
  718. }
  719. bool found_one_char_token = false;
  720. if (!found_four_char_token && !found_three_char_token && !found_two_char_token) {
  721. auto it = s_single_char_tokens.find(m_current_char);
  722. if (it != s_single_char_tokens.end()) {
  723. found_one_char_token = true;
  724. consume();
  725. token_type = it->value;
  726. }
  727. }
  728. if (!found_four_char_token && !found_three_char_token && !found_two_char_token && !found_one_char_token) {
  729. consume();
  730. token_type = TokenType::Invalid;
  731. }
  732. }
  733. if (!m_template_states.is_empty() && m_template_states.last().in_expr) {
  734. if (token_type == TokenType::CurlyOpen) {
  735. m_template_states.last().open_bracket_count++;
  736. } else if (token_type == TokenType::CurlyClose) {
  737. m_template_states.last().open_bracket_count--;
  738. }
  739. }
  740. if (m_hit_invalid_unicode.has_value()) {
  741. value_start = m_hit_invalid_unicode.value() - 1;
  742. m_current_token = Token(TokenType::Invalid, "Invalid unicode codepoint in source",
  743. ""sv, // Since the invalid unicode can occur anywhere in the current token the trivia is not correct
  744. m_source.substring_view(value_start + 1, min(4u, m_source.length() - value_start - 2)),
  745. m_filename,
  746. m_line_number,
  747. m_line_column - 1,
  748. value_start + 1);
  749. m_hit_invalid_unicode.clear();
  750. // Do not produce any further tokens.
  751. VERIFY(is_eof());
  752. } else {
  753. m_current_token = Token(
  754. token_type,
  755. token_message,
  756. m_source.substring_view(trivia_start - 1, value_start - trivia_start),
  757. m_source.substring_view(value_start - 1, m_position - value_start),
  758. m_filename,
  759. value_start_line_number,
  760. value_start_column_number,
  761. value_start - 1);
  762. }
  763. if (identifier.has_value())
  764. m_current_token.set_identifier_value(identifier.release_value());
  765. if constexpr (LEXER_DEBUG) {
  766. dbgln("------------------------------");
  767. dbgln("Token: {}", m_current_token.name());
  768. dbgln("Trivia: _{}_", m_current_token.trivia());
  769. dbgln("Value: _{}_", m_current_token.value());
  770. dbgln("Line: {}, Column: {}", m_current_token.line_number(), m_current_token.line_column());
  771. dbgln("------------------------------");
  772. }
  773. return m_current_token;
  774. }
  775. Token Lexer::force_slash_as_regex()
  776. {
  777. VERIFY(m_current_token.type() == TokenType::Slash || m_current_token.type() == TokenType::SlashEquals);
  778. bool has_equals = m_current_token.type() == TokenType::SlashEquals;
  779. VERIFY(m_position > 0);
  780. size_t value_start = m_position - 1;
  781. if (has_equals) {
  782. VERIFY(m_source[value_start - 1] == '=');
  783. --value_start;
  784. --m_position;
  785. m_current_char = '=';
  786. }
  787. TokenType token_type = consume_regex_literal();
  788. m_current_token = Token(
  789. token_type,
  790. "",
  791. m_current_token.trivia(),
  792. m_source.substring_view(value_start - 1, m_position - value_start),
  793. m_filename,
  794. m_current_token.line_number(),
  795. m_current_token.line_column(),
  796. value_start - 1);
  797. if constexpr (LEXER_DEBUG) {
  798. dbgln("------------------------------");
  799. dbgln("Token: {}", m_current_token.name());
  800. dbgln("Trivia: _{}_", m_current_token.trivia());
  801. dbgln("Value: _{}_", m_current_token.value());
  802. dbgln("Line: {}, Column: {}", m_current_token.line_number(), m_current_token.line_column());
  803. dbgln("------------------------------");
  804. }
  805. return m_current_token;
  806. }
  807. TokenType Lexer::consume_regex_literal()
  808. {
  809. while (!is_eof()) {
  810. if (is_line_terminator() || (!m_regex_is_in_character_class && m_current_char == '/')) {
  811. break;
  812. } else if (m_current_char == '[') {
  813. m_regex_is_in_character_class = true;
  814. } else if (m_current_char == ']') {
  815. m_regex_is_in_character_class = false;
  816. } else if (!m_regex_is_in_character_class && m_current_char == '/') {
  817. break;
  818. }
  819. if (match('\\', '/') || match('\\', '[') || match('\\', '\\') || (m_regex_is_in_character_class && match('\\', ']')))
  820. consume();
  821. consume();
  822. }
  823. if (m_current_char == '/') {
  824. consume();
  825. return TokenType::RegexLiteral;
  826. }
  827. return TokenType::UnterminatedRegexLiteral;
  828. }
  829. }