Lexer.cpp 25 KB

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