Lexer.cpp 33 KB

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