Lexer.cpp 31 KB

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