Lexer.cpp 36 KB

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