Lexer.cpp 24 KB

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