Parser.cpp 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889
  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 "Parser.h"
  28. #include <AK/ScopeGuard.h>
  29. #include <AK/StdLibExtras.h>
  30. #include <AK/TemporaryChange.h>
  31. #include <ctype.h>
  32. namespace JS {
  33. class ScopePusher {
  34. public:
  35. enum Type {
  36. Var = 1,
  37. Let = 2,
  38. Function = 3,
  39. };
  40. ScopePusher(Parser& parser, unsigned mask)
  41. : m_parser(parser)
  42. , m_mask(mask)
  43. {
  44. if (m_mask & Var)
  45. m_parser.m_parser_state.m_var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  46. if (m_mask & Let)
  47. m_parser.m_parser_state.m_let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  48. if (m_mask & Function)
  49. m_parser.m_parser_state.m_function_scopes.append(NonnullRefPtrVector<FunctionDeclaration>());
  50. }
  51. ~ScopePusher()
  52. {
  53. if (m_mask & Var)
  54. m_parser.m_parser_state.m_var_scopes.take_last();
  55. if (m_mask & Let)
  56. m_parser.m_parser_state.m_let_scopes.take_last();
  57. if (m_mask & Function)
  58. m_parser.m_parser_state.m_function_scopes.take_last();
  59. }
  60. Parser& m_parser;
  61. unsigned m_mask { 0 };
  62. };
  63. class OperatorPrecedenceTable {
  64. public:
  65. constexpr OperatorPrecedenceTable()
  66. : m_token_precedence()
  67. {
  68. for (size_t i = 0; i < array_size(m_operator_precedence); ++i) {
  69. auto& op = m_operator_precedence[i];
  70. m_token_precedence[static_cast<size_t>(op.token)] = op.precedence;
  71. }
  72. }
  73. constexpr int get(TokenType token) const
  74. {
  75. int p = m_token_precedence[static_cast<size_t>(token)];
  76. if (p == 0) {
  77. fprintf(stderr, "Internal Error: No precedence for operator %s\n", Token::name(token));
  78. ASSERT_NOT_REACHED();
  79. return -1;
  80. }
  81. return p;
  82. }
  83. private:
  84. int m_token_precedence[cs_num_of_js_tokens];
  85. struct OperatorPrecedence {
  86. TokenType token;
  87. int precedence;
  88. };
  89. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  90. static constexpr const OperatorPrecedence m_operator_precedence[] = {
  91. { TokenType::Period, 20 },
  92. { TokenType::BracketOpen, 20 },
  93. { TokenType::ParenOpen, 20 },
  94. { TokenType::QuestionMarkPeriod, 20 },
  95. { TokenType::New, 19 },
  96. { TokenType::PlusPlus, 18 },
  97. { TokenType::MinusMinus, 18 },
  98. { TokenType::ExclamationMark, 17 },
  99. { TokenType::Tilde, 17 },
  100. { TokenType::Typeof, 17 },
  101. { TokenType::Void, 17 },
  102. { TokenType::Delete, 17 },
  103. { TokenType::Await, 17 },
  104. { TokenType::DoubleAsterisk, 16 },
  105. { TokenType::Asterisk, 15 },
  106. { TokenType::Slash, 15 },
  107. { TokenType::Percent, 15 },
  108. { TokenType::Plus, 14 },
  109. { TokenType::Minus, 14 },
  110. { TokenType::ShiftLeft, 13 },
  111. { TokenType::ShiftRight, 13 },
  112. { TokenType::UnsignedShiftRight, 13 },
  113. { TokenType::LessThan, 12 },
  114. { TokenType::LessThanEquals, 12 },
  115. { TokenType::GreaterThan, 12 },
  116. { TokenType::GreaterThanEquals, 12 },
  117. { TokenType::In, 12 },
  118. { TokenType::Instanceof, 12 },
  119. { TokenType::EqualsEquals, 11 },
  120. { TokenType::ExclamationMarkEquals, 11 },
  121. { TokenType::EqualsEqualsEquals, 11 },
  122. { TokenType::ExclamationMarkEqualsEquals, 11 },
  123. { TokenType::Ampersand, 10 },
  124. { TokenType::Caret, 9 },
  125. { TokenType::Pipe, 8 },
  126. { TokenType::DoubleQuestionMark, 7 },
  127. { TokenType::DoubleAmpersand, 6 },
  128. { TokenType::DoublePipe, 5 },
  129. { TokenType::QuestionMark, 4 },
  130. { TokenType::Equals, 3 },
  131. { TokenType::PlusEquals, 3 },
  132. { TokenType::MinusEquals, 3 },
  133. { TokenType::DoubleAsteriskEquals, 3 },
  134. { TokenType::AsteriskEquals, 3 },
  135. { TokenType::SlashEquals, 3 },
  136. { TokenType::PercentEquals, 3 },
  137. { TokenType::ShiftLeftEquals, 3 },
  138. { TokenType::ShiftRightEquals, 3 },
  139. { TokenType::UnsignedShiftRightEquals, 3 },
  140. { TokenType::AmpersandEquals, 3 },
  141. { TokenType::CaretEquals, 3 },
  142. { TokenType::PipeEquals, 3 },
  143. { TokenType::DoubleAmpersandEquals, 3 },
  144. { TokenType::DoublePipeEquals, 3 },
  145. { TokenType::DoubleQuestionMarkEquals, 3 },
  146. { TokenType::Yield, 2 },
  147. { TokenType::Comma, 1 },
  148. };
  149. };
  150. constexpr OperatorPrecedenceTable g_operator_precedence;
  151. Parser::ParserState::ParserState(Lexer lexer)
  152. : m_lexer(move(lexer))
  153. , m_current_token(m_lexer.next())
  154. {
  155. }
  156. Parser::Parser(Lexer lexer)
  157. : m_parser_state(move(lexer))
  158. {
  159. }
  160. Associativity Parser::operator_associativity(TokenType type) const
  161. {
  162. switch (type) {
  163. case TokenType::Period:
  164. case TokenType::BracketOpen:
  165. case TokenType::ParenOpen:
  166. case TokenType::QuestionMarkPeriod:
  167. case TokenType::Asterisk:
  168. case TokenType::Slash:
  169. case TokenType::Percent:
  170. case TokenType::Plus:
  171. case TokenType::Minus:
  172. case TokenType::ShiftLeft:
  173. case TokenType::ShiftRight:
  174. case TokenType::UnsignedShiftRight:
  175. case TokenType::LessThan:
  176. case TokenType::LessThanEquals:
  177. case TokenType::GreaterThan:
  178. case TokenType::GreaterThanEquals:
  179. case TokenType::In:
  180. case TokenType::Instanceof:
  181. case TokenType::EqualsEquals:
  182. case TokenType::ExclamationMarkEquals:
  183. case TokenType::EqualsEqualsEquals:
  184. case TokenType::ExclamationMarkEqualsEquals:
  185. case TokenType::Typeof:
  186. case TokenType::Void:
  187. case TokenType::Delete:
  188. case TokenType::Ampersand:
  189. case TokenType::Caret:
  190. case TokenType::Pipe:
  191. case TokenType::DoubleQuestionMark:
  192. case TokenType::DoubleAmpersand:
  193. case TokenType::DoublePipe:
  194. case TokenType::Comma:
  195. return Associativity::Left;
  196. default:
  197. return Associativity::Right;
  198. }
  199. }
  200. NonnullRefPtr<Program> Parser::parse_program()
  201. {
  202. ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Let | ScopePusher::Function);
  203. auto program = adopt(*new Program);
  204. bool first = true;
  205. m_parser_state.m_use_strict_directive = UseStrictDirectiveState::Looking;
  206. while (!done()) {
  207. if (match_declaration()) {
  208. program->append(parse_declaration());
  209. if (first) {
  210. first = false;
  211. m_parser_state.m_use_strict_directive = UseStrictDirectiveState::None;
  212. }
  213. } else if (match_statement()) {
  214. program->append(parse_statement());
  215. if (first) {
  216. if (m_parser_state.m_use_strict_directive == UseStrictDirectiveState::Found) {
  217. program->set_strict_mode();
  218. m_parser_state.m_strict_mode = true;
  219. }
  220. first = false;
  221. m_parser_state.m_use_strict_directive = UseStrictDirectiveState::None;
  222. }
  223. } else {
  224. expected("statement or declaration");
  225. consume();
  226. }
  227. }
  228. if (m_parser_state.m_var_scopes.size() == 1) {
  229. program->add_variables(m_parser_state.m_var_scopes.last());
  230. program->add_variables(m_parser_state.m_let_scopes.last());
  231. program->add_functions(m_parser_state.m_function_scopes.last());
  232. } else {
  233. syntax_error("Unclosed scope");
  234. }
  235. return program;
  236. }
  237. NonnullRefPtr<Declaration> Parser::parse_declaration()
  238. {
  239. switch (m_parser_state.m_current_token.type()) {
  240. case TokenType::Class:
  241. return parse_class_declaration();
  242. case TokenType::Function: {
  243. auto declaration = parse_function_node<FunctionDeclaration>();
  244. m_parser_state.m_function_scopes.last().append(declaration);
  245. return declaration;
  246. }
  247. case TokenType::Let:
  248. case TokenType::Const:
  249. return parse_variable_declaration();
  250. default:
  251. expected("declaration");
  252. consume();
  253. return create_ast_node<ErrorDeclaration>();
  254. }
  255. }
  256. NonnullRefPtr<Statement> Parser::parse_statement()
  257. {
  258. switch (m_parser_state.m_current_token.type()) {
  259. case TokenType::CurlyOpen:
  260. return parse_block_statement();
  261. case TokenType::Return:
  262. return parse_return_statement();
  263. case TokenType::Var:
  264. return parse_variable_declaration();
  265. case TokenType::For:
  266. return parse_for_statement();
  267. case TokenType::If:
  268. return parse_if_statement();
  269. case TokenType::Throw:
  270. return parse_throw_statement();
  271. case TokenType::Try:
  272. return parse_try_statement();
  273. case TokenType::Break:
  274. return parse_break_statement();
  275. case TokenType::Continue:
  276. return parse_continue_statement();
  277. case TokenType::Switch:
  278. return parse_switch_statement();
  279. case TokenType::Do:
  280. return parse_do_while_statement();
  281. case TokenType::While:
  282. return parse_while_statement();
  283. case TokenType::Debugger:
  284. return parse_debugger_statement();
  285. case TokenType::Semicolon:
  286. consume();
  287. return create_ast_node<EmptyStatement>();
  288. default:
  289. if (match(TokenType::Identifier)) {
  290. auto result = try_parse_labelled_statement();
  291. if (!result.is_null())
  292. return result.release_nonnull();
  293. }
  294. if (match_expression()) {
  295. if (match(TokenType::Function))
  296. syntax_error("Function declaration not allowed in single-statement context");
  297. auto expr = parse_expression(0);
  298. consume_or_insert_semicolon();
  299. return create_ast_node<ExpressionStatement>(move(expr));
  300. }
  301. expected("statement");
  302. consume();
  303. return create_ast_node<ErrorStatement>();
  304. }
  305. }
  306. RefPtr<FunctionExpression> Parser::try_parse_arrow_function_expression(bool expect_parens)
  307. {
  308. save_state();
  309. m_parser_state.m_var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  310. ArmedScopeGuard state_rollback_guard = [&] {
  311. m_parser_state.m_var_scopes.take_last();
  312. load_state();
  313. };
  314. Vector<FunctionNode::Parameter> parameters;
  315. i32 function_length = -1;
  316. if (expect_parens) {
  317. // We have parens around the function parameters and can re-use the same parsing
  318. // logic used for regular functions: multiple parameters, default values, rest
  319. // parameter, maybe a trailing comma. If we have a new syntax error afterwards we
  320. // know parsing failed and rollback the parser state.
  321. auto previous_syntax_errors = m_parser_state.m_errors.size();
  322. parameters = parse_function_parameters(function_length);
  323. if (m_parser_state.m_errors.size() > previous_syntax_errors)
  324. return nullptr;
  325. if (!match(TokenType::ParenClose))
  326. return nullptr;
  327. consume();
  328. } else {
  329. // No parens - this must be an identifier followed by arrow. That's it.
  330. if (!match(TokenType::Identifier))
  331. return nullptr;
  332. parameters.append({ consume().value(), {} });
  333. }
  334. // If there's a newline between the closing paren and arrow it's not a valid arrow function,
  335. // ASI should kick in instead (it'll then fail with "Unexpected token Arrow")
  336. if (m_parser_state.m_current_token.trivia_contains_line_terminator())
  337. return nullptr;
  338. if (!match(TokenType::Arrow))
  339. return nullptr;
  340. consume();
  341. if (function_length == -1)
  342. function_length = parameters.size();
  343. auto old_labels_in_scope = move(m_parser_state.m_labels_in_scope);
  344. ScopeGuard guard([&]() {
  345. m_parser_state.m_labels_in_scope = move(old_labels_in_scope);
  346. });
  347. bool is_strict = false;
  348. auto function_body_result = [&]() -> RefPtr<BlockStatement> {
  349. TemporaryChange change(m_parser_state.m_in_function_context, true);
  350. if (match(TokenType::CurlyOpen)) {
  351. // Parse a function body with statements
  352. return parse_block_statement(is_strict);
  353. }
  354. if (match_expression()) {
  355. // Parse a function body which returns a single expression
  356. // FIXME: We synthesize a block with a return statement
  357. // for arrow function bodies which are a single expression.
  358. // Esprima generates a single "ArrowFunctionExpression"
  359. // with a "body" property.
  360. auto return_expression = parse_expression(2);
  361. auto return_block = create_ast_node<BlockStatement>();
  362. return_block->append<ReturnStatement>(move(return_expression));
  363. return return_block;
  364. }
  365. // Invalid arrow function body
  366. return nullptr;
  367. }();
  368. if (!function_body_result.is_null()) {
  369. state_rollback_guard.disarm();
  370. auto body = function_body_result.release_nonnull();
  371. return create_ast_node<FunctionExpression>("", move(body), move(parameters), function_length, m_parser_state.m_var_scopes.take_last(), is_strict, true);
  372. }
  373. return nullptr;
  374. }
  375. RefPtr<Statement> Parser::try_parse_labelled_statement()
  376. {
  377. save_state();
  378. ArmedScopeGuard state_rollback_guard = [&] {
  379. load_state();
  380. };
  381. auto identifier = consume(TokenType::Identifier).value();
  382. if (!match(TokenType::Colon))
  383. return {};
  384. consume(TokenType::Colon);
  385. if (!match_statement())
  386. return {};
  387. m_parser_state.m_labels_in_scope.set(identifier);
  388. auto statement = parse_statement();
  389. m_parser_state.m_labels_in_scope.remove(identifier);
  390. statement->set_label(identifier);
  391. state_rollback_guard.disarm();
  392. return statement;
  393. }
  394. NonnullRefPtr<ClassDeclaration> Parser::parse_class_declaration()
  395. {
  396. return create_ast_node<ClassDeclaration>(parse_class_expression(true));
  397. }
  398. NonnullRefPtr<ClassExpression> Parser::parse_class_expression(bool expect_class_name)
  399. {
  400. // Classes are always in strict mode.
  401. TemporaryChange strict_mode_rollback(m_parser_state.m_strict_mode, true);
  402. consume(TokenType::Class);
  403. NonnullRefPtrVector<ClassMethod> methods;
  404. RefPtr<Expression> super_class;
  405. RefPtr<FunctionExpression> constructor;
  406. String class_name = expect_class_name || match(TokenType::Identifier) ? consume(TokenType::Identifier).value().to_string() : "";
  407. if (match(TokenType::Extends)) {
  408. consume();
  409. super_class = parse_primary_expression();
  410. }
  411. consume(TokenType::CurlyOpen);
  412. while (!done() && !match(TokenType::CurlyClose)) {
  413. RefPtr<Expression> property_key;
  414. bool is_static = false;
  415. bool is_constructor = false;
  416. auto method_kind = ClassMethod::Kind::Method;
  417. if (match(TokenType::Semicolon)) {
  418. consume();
  419. continue;
  420. }
  421. if (match_property_key()) {
  422. StringView name;
  423. if (match(TokenType::Identifier) && m_parser_state.m_current_token.value() == "static") {
  424. consume();
  425. is_static = true;
  426. }
  427. if (match(TokenType::Identifier)) {
  428. auto identifier_name = m_parser_state.m_current_token.value();
  429. if (identifier_name == "get") {
  430. method_kind = ClassMethod::Kind::Getter;
  431. consume();
  432. } else if (identifier_name == "set") {
  433. method_kind = ClassMethod::Kind::Setter;
  434. consume();
  435. }
  436. }
  437. if (match_property_key()) {
  438. switch (m_parser_state.m_current_token.type()) {
  439. case TokenType::Identifier:
  440. name = consume().value();
  441. property_key = create_ast_node<StringLiteral>(name);
  442. break;
  443. case TokenType::StringLiteral: {
  444. auto string_literal = parse_string_literal(consume());
  445. name = string_literal->value();
  446. property_key = move(string_literal);
  447. break;
  448. }
  449. default:
  450. property_key = parse_property_key();
  451. break;
  452. }
  453. } else {
  454. expected("property key");
  455. }
  456. // Constructor may be a StringLiteral or an Identifier.
  457. if (!is_static && name == "constructor") {
  458. if (method_kind != ClassMethod::Kind::Method)
  459. syntax_error("Class constructor may not be an accessor");
  460. if (!constructor.is_null())
  461. syntax_error("Classes may not have more than one constructor");
  462. is_constructor = true;
  463. }
  464. }
  465. if (match(TokenType::ParenOpen)) {
  466. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  467. if (!super_class.is_null())
  468. parse_options |= FunctionNodeParseOptions::AllowSuperConstructorCall;
  469. if (method_kind == ClassMethod::Kind::Getter)
  470. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  471. if (method_kind == ClassMethod::Kind::Setter)
  472. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  473. auto function = parse_function_node<FunctionExpression>(parse_options);
  474. if (is_constructor) {
  475. constructor = move(function);
  476. } else if (!property_key.is_null()) {
  477. methods.append(create_ast_node<ClassMethod>(property_key.release_nonnull(), move(function), method_kind, is_static));
  478. } else {
  479. syntax_error("No key for class method");
  480. }
  481. } else {
  482. expected("ParenOpen");
  483. consume();
  484. }
  485. }
  486. consume(TokenType::CurlyClose);
  487. if (constructor.is_null()) {
  488. auto constructor_body = create_ast_node<BlockStatement>();
  489. if (!super_class.is_null()) {
  490. // Set constructor to the result of parsing the source text
  491. // constructor(... args){ super (...args);}
  492. auto super_call = create_ast_node<CallExpression>(create_ast_node<SuperExpression>(), Vector { CallExpression::Argument { create_ast_node<Identifier>("args"), true } });
  493. constructor_body->append(create_ast_node<ExpressionStatement>(move(super_call)));
  494. constructor_body->add_variables(m_parser_state.m_var_scopes.last());
  495. constructor = create_ast_node<FunctionExpression>(class_name, move(constructor_body), Vector { FunctionNode::Parameter { "args", nullptr, true } }, 0, NonnullRefPtrVector<VariableDeclaration>(), true);
  496. } else {
  497. constructor = create_ast_node<FunctionExpression>(class_name, move(constructor_body), Vector<FunctionNode::Parameter> {}, 0, NonnullRefPtrVector<VariableDeclaration>(), true);
  498. }
  499. }
  500. return create_ast_node<ClassExpression>(move(class_name), move(constructor), move(super_class), move(methods));
  501. }
  502. NonnullRefPtr<Expression> Parser::parse_primary_expression()
  503. {
  504. if (match_unary_prefixed_expression())
  505. return parse_unary_prefixed_expression();
  506. switch (m_parser_state.m_current_token.type()) {
  507. case TokenType::ParenOpen: {
  508. consume(TokenType::ParenOpen);
  509. if (match(TokenType::ParenClose) || match(TokenType::Identifier) || match(TokenType::TripleDot)) {
  510. auto arrow_function_result = try_parse_arrow_function_expression(true);
  511. if (!arrow_function_result.is_null()) {
  512. return arrow_function_result.release_nonnull();
  513. }
  514. }
  515. auto expression = parse_expression(0);
  516. consume(TokenType::ParenClose);
  517. return expression;
  518. }
  519. case TokenType::This:
  520. consume();
  521. return create_ast_node<ThisExpression>();
  522. case TokenType::Class:
  523. return parse_class_expression(false);
  524. case TokenType::Super:
  525. consume();
  526. if (!m_parser_state.m_allow_super_property_lookup)
  527. syntax_error("'super' keyword unexpected here");
  528. return create_ast_node<SuperExpression>();
  529. case TokenType::Identifier: {
  530. auto arrow_function_result = try_parse_arrow_function_expression(false);
  531. if (!arrow_function_result.is_null()) {
  532. return arrow_function_result.release_nonnull();
  533. }
  534. return create_ast_node<Identifier>(consume().value());
  535. }
  536. case TokenType::NumericLiteral:
  537. return create_ast_node<NumericLiteral>(consume_and_validate_numeric_literal().double_value());
  538. case TokenType::BigIntLiteral:
  539. return create_ast_node<BigIntLiteral>(consume().value());
  540. case TokenType::BoolLiteral:
  541. return create_ast_node<BooleanLiteral>(consume().bool_value());
  542. case TokenType::StringLiteral:
  543. return parse_string_literal(consume());
  544. case TokenType::NullLiteral:
  545. consume();
  546. return create_ast_node<NullLiteral>();
  547. case TokenType::CurlyOpen:
  548. return parse_object_expression();
  549. case TokenType::Function:
  550. return parse_function_node<FunctionExpression>();
  551. case TokenType::BracketOpen:
  552. return parse_array_expression();
  553. case TokenType::RegexLiteral:
  554. return parse_regexp_literal();
  555. case TokenType::TemplateLiteralStart:
  556. return parse_template_literal(false);
  557. case TokenType::New:
  558. return parse_new_expression();
  559. default:
  560. expected("primary expression");
  561. consume();
  562. return create_ast_node<ErrorExpression>();
  563. }
  564. }
  565. NonnullRefPtr<RegExpLiteral> Parser::parse_regexp_literal()
  566. {
  567. auto content = consume().value();
  568. auto flags = match(TokenType::RegexFlags) ? consume().value() : "";
  569. return create_ast_node<RegExpLiteral>(content.substring_view(1, content.length() - 2), flags);
  570. }
  571. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  572. {
  573. auto precedence = g_operator_precedence.get(m_parser_state.m_current_token.type());
  574. auto associativity = operator_associativity(m_parser_state.m_current_token.type());
  575. switch (m_parser_state.m_current_token.type()) {
  576. case TokenType::PlusPlus: {
  577. consume();
  578. auto rhs_start_line = m_parser_state.m_current_token.line_number();
  579. auto rhs_start_column = m_parser_state.m_current_token.line_column();
  580. auto rhs = parse_expression(precedence, associativity);
  581. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  582. // other engines throw ReferenceError for ++foo()
  583. if (!rhs->is_identifier() && !rhs->is_member_expression())
  584. syntax_error(String::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start_line, rhs_start_column);
  585. return create_ast_node<UpdateExpression>(UpdateOp::Increment, move(rhs), true);
  586. }
  587. case TokenType::MinusMinus: {
  588. consume();
  589. auto rhs_start_line = m_parser_state.m_current_token.line_number();
  590. auto rhs_start_column = m_parser_state.m_current_token.line_column();
  591. auto rhs = parse_expression(precedence, associativity);
  592. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  593. // other engines throw ReferenceError for --foo()
  594. if (!rhs->is_identifier() && !rhs->is_member_expression())
  595. syntax_error(String::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start_line, rhs_start_column);
  596. return create_ast_node<UpdateExpression>(UpdateOp::Decrement, move(rhs), true);
  597. }
  598. case TokenType::ExclamationMark:
  599. consume();
  600. return create_ast_node<UnaryExpression>(UnaryOp::Not, parse_expression(precedence, associativity));
  601. case TokenType::Tilde:
  602. consume();
  603. return create_ast_node<UnaryExpression>(UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  604. case TokenType::Plus:
  605. consume();
  606. return create_ast_node<UnaryExpression>(UnaryOp::Plus, parse_expression(precedence, associativity));
  607. case TokenType::Minus:
  608. consume();
  609. return create_ast_node<UnaryExpression>(UnaryOp::Minus, parse_expression(precedence, associativity));
  610. case TokenType::Typeof:
  611. consume();
  612. return create_ast_node<UnaryExpression>(UnaryOp::Typeof, parse_expression(precedence, associativity));
  613. case TokenType::Void:
  614. consume();
  615. return create_ast_node<UnaryExpression>(UnaryOp::Void, parse_expression(precedence, associativity));
  616. case TokenType::Delete:
  617. consume();
  618. return create_ast_node<UnaryExpression>(UnaryOp::Delete, parse_expression(precedence, associativity));
  619. default:
  620. expected("primary expression");
  621. consume();
  622. return create_ast_node<ErrorExpression>();
  623. }
  624. }
  625. NonnullRefPtr<Expression> Parser::parse_property_key()
  626. {
  627. if (match(TokenType::StringLiteral)) {
  628. return parse_string_literal(consume());
  629. } else if (match(TokenType::NumericLiteral)) {
  630. // FIXME: "evaluate" key to double value, see https://github.com/SerenityOS/serenity/issues/3717
  631. return create_ast_node<StringLiteral>(consume_and_validate_numeric_literal().value());
  632. } else if (match(TokenType::BigIntLiteral)) {
  633. auto value = consume(TokenType::BigIntLiteral).value();
  634. return create_ast_node<StringLiteral>(value.substring_view(0, value.length() - 1));
  635. } else if (match(TokenType::BracketOpen)) {
  636. consume(TokenType::BracketOpen);
  637. auto result = parse_expression(0);
  638. consume(TokenType::BracketClose);
  639. return result;
  640. } else {
  641. if (!match_identifier_name())
  642. expected("IdentifierName");
  643. return create_ast_node<StringLiteral>(consume().value());
  644. }
  645. }
  646. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  647. {
  648. consume(TokenType::CurlyOpen);
  649. NonnullRefPtrVector<ObjectProperty> properties;
  650. ObjectProperty::Type property_type;
  651. auto skip_to_next_property = [&] {
  652. while (!done() && !match(TokenType::Comma) && !match(TokenType::CurlyOpen))
  653. consume();
  654. };
  655. while (!done() && !match(TokenType::CurlyClose)) {
  656. property_type = ObjectProperty::Type::KeyValue;
  657. RefPtr<Expression> property_name;
  658. RefPtr<Expression> property_value;
  659. if (match(TokenType::TripleDot)) {
  660. consume();
  661. property_name = parse_expression(4);
  662. properties.append(create_ast_node<ObjectProperty>(*property_name, nullptr, ObjectProperty::Type::Spread, false));
  663. if (!match(TokenType::Comma))
  664. break;
  665. consume(TokenType::Comma);
  666. continue;
  667. }
  668. if (match(TokenType::Identifier)) {
  669. auto identifier = consume().value();
  670. if (identifier == "get" && match_property_key()) {
  671. property_type = ObjectProperty::Type::Getter;
  672. property_name = parse_property_key();
  673. } else if (identifier == "set" && match_property_key()) {
  674. property_type = ObjectProperty::Type::Setter;
  675. property_name = parse_property_key();
  676. } else {
  677. property_name = create_ast_node<StringLiteral>(identifier);
  678. property_value = create_ast_node<Identifier>(identifier);
  679. }
  680. } else {
  681. property_name = parse_property_key();
  682. }
  683. if (property_type == ObjectProperty::Type::Getter || property_type == ObjectProperty::Type::Setter) {
  684. if (!match(TokenType::ParenOpen)) {
  685. syntax_error(
  686. "Expected '(' for object getter or setter property",
  687. m_parser_state.m_current_token.line_number(),
  688. m_parser_state.m_current_token.line_column());
  689. skip_to_next_property();
  690. continue;
  691. }
  692. }
  693. if (match(TokenType::ParenOpen)) {
  694. ASSERT(property_name);
  695. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  696. if (property_type == ObjectProperty::Type::Getter)
  697. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  698. if (property_type == ObjectProperty::Type::Setter)
  699. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  700. auto function = parse_function_node<FunctionExpression>(parse_options);
  701. properties.append(create_ast_node<ObjectProperty>(*property_name, function, property_type, true));
  702. } else if (match(TokenType::Colon)) {
  703. if (!property_name) {
  704. syntax_error("Expected a property name");
  705. skip_to_next_property();
  706. continue;
  707. }
  708. consume();
  709. properties.append(create_ast_node<ObjectProperty>(*property_name, parse_expression(2), property_type, false));
  710. } else if (property_name && property_value) {
  711. properties.append(create_ast_node<ObjectProperty>(*property_name, *property_value, property_type, false));
  712. } else {
  713. syntax_error("Expected a property");
  714. skip_to_next_property();
  715. continue;
  716. }
  717. if (!match(TokenType::Comma))
  718. break;
  719. consume(TokenType::Comma);
  720. }
  721. consume(TokenType::CurlyClose);
  722. return create_ast_node<ObjectExpression>(properties);
  723. }
  724. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  725. {
  726. consume(TokenType::BracketOpen);
  727. Vector<RefPtr<Expression>> elements;
  728. while (match_expression() || match(TokenType::TripleDot) || match(TokenType::Comma)) {
  729. RefPtr<Expression> expression;
  730. if (match(TokenType::TripleDot)) {
  731. consume(TokenType::TripleDot);
  732. expression = create_ast_node<SpreadExpression>(parse_expression(2));
  733. } else if (match_expression()) {
  734. expression = parse_expression(2);
  735. }
  736. elements.append(expression);
  737. if (!match(TokenType::Comma))
  738. break;
  739. consume(TokenType::Comma);
  740. }
  741. consume(TokenType::BracketClose);
  742. return create_ast_node<ArrayExpression>(move(elements));
  743. }
  744. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(Token token)
  745. {
  746. auto status = Token::StringValueStatus::Ok;
  747. auto string = token.string_value(status);
  748. if (status != Token::StringValueStatus::Ok) {
  749. String message;
  750. if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) {
  751. auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal";
  752. message = String::formatted("Malformed {} escape sequence", type);
  753. } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) {
  754. message = "Unicode code_point must not be greater than 0x10ffff in escape sequence";
  755. }
  756. syntax_error(
  757. message,
  758. m_parser_state.m_current_token.line_number(),
  759. m_parser_state.m_current_token.line_column());
  760. }
  761. if (m_parser_state.m_use_strict_directive == UseStrictDirectiveState::Looking) {
  762. if (string == "use strict" && token.type() != TokenType::TemplateLiteralString) {
  763. m_parser_state.m_use_strict_directive = UseStrictDirectiveState::Found;
  764. } else {
  765. m_parser_state.m_use_strict_directive = UseStrictDirectiveState::None;
  766. }
  767. }
  768. return create_ast_node<StringLiteral>(string);
  769. }
  770. NonnullRefPtr<TemplateLiteral> Parser::parse_template_literal(bool is_tagged)
  771. {
  772. consume(TokenType::TemplateLiteralStart);
  773. NonnullRefPtrVector<Expression> expressions;
  774. NonnullRefPtrVector<Expression> raw_strings;
  775. auto append_empty_string = [&expressions, &raw_strings, is_tagged]() {
  776. auto string_literal = create_ast_node<StringLiteral>("");
  777. expressions.append(string_literal);
  778. if (is_tagged)
  779. raw_strings.append(string_literal);
  780. };
  781. if (!match(TokenType::TemplateLiteralString))
  782. append_empty_string();
  783. while (!done() && !match(TokenType::TemplateLiteralEnd) && !match(TokenType::UnterminatedTemplateLiteral)) {
  784. if (match(TokenType::TemplateLiteralString)) {
  785. auto token = consume();
  786. expressions.append(parse_string_literal(token));
  787. if (is_tagged)
  788. raw_strings.append(create_ast_node<StringLiteral>(token.value()));
  789. } else if (match(TokenType::TemplateLiteralExprStart)) {
  790. consume(TokenType::TemplateLiteralExprStart);
  791. if (match(TokenType::TemplateLiteralExprEnd)) {
  792. syntax_error("Empty template literal expression block");
  793. return create_ast_node<TemplateLiteral>(expressions);
  794. }
  795. expressions.append(parse_expression(0));
  796. if (match(TokenType::UnterminatedTemplateLiteral)) {
  797. syntax_error("Unterminated template literal");
  798. return create_ast_node<TemplateLiteral>(expressions);
  799. }
  800. consume(TokenType::TemplateLiteralExprEnd);
  801. if (!match(TokenType::TemplateLiteralString))
  802. append_empty_string();
  803. } else {
  804. expected("Template literal string or expression");
  805. break;
  806. }
  807. }
  808. if (match(TokenType::UnterminatedTemplateLiteral)) {
  809. syntax_error("Unterminated template literal");
  810. } else {
  811. consume(TokenType::TemplateLiteralEnd);
  812. }
  813. if (is_tagged)
  814. return create_ast_node<TemplateLiteral>(expressions, raw_strings);
  815. return create_ast_node<TemplateLiteral>(expressions);
  816. }
  817. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity, Vector<TokenType> forbidden)
  818. {
  819. auto expression = parse_primary_expression();
  820. while (match(TokenType::TemplateLiteralStart)) {
  821. auto template_literal = parse_template_literal(true);
  822. expression = create_ast_node<TaggedTemplateLiteral>(move(expression), move(template_literal));
  823. }
  824. while (match_secondary_expression(forbidden)) {
  825. int new_precedence = g_operator_precedence.get(m_parser_state.m_current_token.type());
  826. if (new_precedence < min_precedence)
  827. break;
  828. if (new_precedence == min_precedence && associativity == Associativity::Left)
  829. break;
  830. Associativity new_associativity = operator_associativity(m_parser_state.m_current_token.type());
  831. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  832. while (match(TokenType::TemplateLiteralStart)) {
  833. auto template_literal = parse_template_literal(true);
  834. expression = create_ast_node<TaggedTemplateLiteral>(move(expression), move(template_literal));
  835. }
  836. }
  837. if (match(TokenType::Comma) && min_precedence <= 1) {
  838. NonnullRefPtrVector<Expression> expressions;
  839. expressions.append(expression);
  840. while (match(TokenType::Comma)) {
  841. consume();
  842. expressions.append(parse_expression(2));
  843. }
  844. expression = create_ast_node<SequenceExpression>(move(expressions));
  845. }
  846. return expression;
  847. }
  848. NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  849. {
  850. switch (m_parser_state.m_current_token.type()) {
  851. case TokenType::Plus:
  852. consume();
  853. return create_ast_node<BinaryExpression>(BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity));
  854. case TokenType::PlusEquals:
  855. return parse_assignment_expression(AssignmentOp::AdditionAssignment, move(lhs), min_precedence, associativity);
  856. case TokenType::Minus:
  857. consume();
  858. return create_ast_node<BinaryExpression>(BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity));
  859. case TokenType::MinusEquals:
  860. return parse_assignment_expression(AssignmentOp::SubtractionAssignment, move(lhs), min_precedence, associativity);
  861. case TokenType::Asterisk:
  862. consume();
  863. return create_ast_node<BinaryExpression>(BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity));
  864. case TokenType::AsteriskEquals:
  865. return parse_assignment_expression(AssignmentOp::MultiplicationAssignment, move(lhs), min_precedence, associativity);
  866. case TokenType::Slash:
  867. consume();
  868. return create_ast_node<BinaryExpression>(BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity));
  869. case TokenType::SlashEquals:
  870. return parse_assignment_expression(AssignmentOp::DivisionAssignment, move(lhs), min_precedence, associativity);
  871. case TokenType::Percent:
  872. consume();
  873. return create_ast_node<BinaryExpression>(BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity));
  874. case TokenType::PercentEquals:
  875. return parse_assignment_expression(AssignmentOp::ModuloAssignment, move(lhs), min_precedence, associativity);
  876. case TokenType::DoubleAsterisk:
  877. consume();
  878. return create_ast_node<BinaryExpression>(BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity));
  879. case TokenType::DoubleAsteriskEquals:
  880. return parse_assignment_expression(AssignmentOp::ExponentiationAssignment, move(lhs), min_precedence, associativity);
  881. case TokenType::GreaterThan:
  882. consume();
  883. return create_ast_node<BinaryExpression>(BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  884. case TokenType::GreaterThanEquals:
  885. consume();
  886. return create_ast_node<BinaryExpression>(BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  887. case TokenType::LessThan:
  888. consume();
  889. return create_ast_node<BinaryExpression>(BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  890. case TokenType::LessThanEquals:
  891. consume();
  892. return create_ast_node<BinaryExpression>(BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  893. case TokenType::EqualsEqualsEquals:
  894. consume();
  895. return create_ast_node<BinaryExpression>(BinaryOp::TypedEquals, move(lhs), parse_expression(min_precedence, associativity));
  896. case TokenType::ExclamationMarkEqualsEquals:
  897. consume();
  898. return create_ast_node<BinaryExpression>(BinaryOp::TypedInequals, move(lhs), parse_expression(min_precedence, associativity));
  899. case TokenType::EqualsEquals:
  900. consume();
  901. return create_ast_node<BinaryExpression>(BinaryOp::AbstractEquals, move(lhs), parse_expression(min_precedence, associativity));
  902. case TokenType::ExclamationMarkEquals:
  903. consume();
  904. return create_ast_node<BinaryExpression>(BinaryOp::AbstractInequals, move(lhs), parse_expression(min_precedence, associativity));
  905. case TokenType::In:
  906. consume();
  907. return create_ast_node<BinaryExpression>(BinaryOp::In, move(lhs), parse_expression(min_precedence, associativity));
  908. case TokenType::Instanceof:
  909. consume();
  910. return create_ast_node<BinaryExpression>(BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity));
  911. case TokenType::Ampersand:
  912. consume();
  913. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity));
  914. case TokenType::AmpersandEquals:
  915. return parse_assignment_expression(AssignmentOp::BitwiseAndAssignment, move(lhs), min_precedence, associativity);
  916. case TokenType::Pipe:
  917. consume();
  918. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity));
  919. case TokenType::PipeEquals:
  920. return parse_assignment_expression(AssignmentOp::BitwiseOrAssignment, move(lhs), min_precedence, associativity);
  921. case TokenType::Caret:
  922. consume();
  923. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity));
  924. case TokenType::CaretEquals:
  925. return parse_assignment_expression(AssignmentOp::BitwiseXorAssignment, move(lhs), min_precedence, associativity);
  926. case TokenType::ShiftLeft:
  927. consume();
  928. return create_ast_node<BinaryExpression>(BinaryOp::LeftShift, move(lhs), parse_expression(min_precedence, associativity));
  929. case TokenType::ShiftLeftEquals:
  930. return parse_assignment_expression(AssignmentOp::LeftShiftAssignment, move(lhs), min_precedence, associativity);
  931. case TokenType::ShiftRight:
  932. consume();
  933. return create_ast_node<BinaryExpression>(BinaryOp::RightShift, move(lhs), parse_expression(min_precedence, associativity));
  934. case TokenType::ShiftRightEquals:
  935. return parse_assignment_expression(AssignmentOp::RightShiftAssignment, move(lhs), min_precedence, associativity);
  936. case TokenType::UnsignedShiftRight:
  937. consume();
  938. return create_ast_node<BinaryExpression>(BinaryOp::UnsignedRightShift, move(lhs), parse_expression(min_precedence, associativity));
  939. case TokenType::UnsignedShiftRightEquals:
  940. return parse_assignment_expression(AssignmentOp::UnsignedRightShiftAssignment, move(lhs), min_precedence, associativity);
  941. case TokenType::ParenOpen:
  942. return parse_call_expression(move(lhs));
  943. case TokenType::Equals:
  944. return parse_assignment_expression(AssignmentOp::Assignment, move(lhs), min_precedence, associativity);
  945. case TokenType::Period:
  946. consume();
  947. if (!match_identifier_name())
  948. expected("IdentifierName");
  949. return create_ast_node<MemberExpression>(move(lhs), create_ast_node<Identifier>(consume().value()));
  950. case TokenType::BracketOpen: {
  951. consume(TokenType::BracketOpen);
  952. auto expression = create_ast_node<MemberExpression>(move(lhs), parse_expression(0), true);
  953. consume(TokenType::BracketClose);
  954. return expression;
  955. }
  956. case TokenType::PlusPlus:
  957. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  958. // other engines throw ReferenceError for foo()++
  959. if (!lhs->is_identifier() && !lhs->is_member_expression())
  960. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  961. consume();
  962. return create_ast_node<UpdateExpression>(UpdateOp::Increment, move(lhs));
  963. case TokenType::MinusMinus:
  964. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  965. // other engines throw ReferenceError for foo()--
  966. if (!lhs->is_identifier() && !lhs->is_member_expression())
  967. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  968. consume();
  969. return create_ast_node<UpdateExpression>(UpdateOp::Decrement, move(lhs));
  970. case TokenType::DoubleAmpersand:
  971. consume();
  972. return create_ast_node<LogicalExpression>(LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity));
  973. case TokenType::DoubleAmpersandEquals:
  974. return parse_assignment_expression(AssignmentOp::AndAssignment, move(lhs), min_precedence, associativity);
  975. case TokenType::DoublePipe:
  976. consume();
  977. return create_ast_node<LogicalExpression>(LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity));
  978. case TokenType::DoublePipeEquals:
  979. return parse_assignment_expression(AssignmentOp::OrAssignment, move(lhs), min_precedence, associativity);
  980. case TokenType::DoubleQuestionMark:
  981. consume();
  982. return create_ast_node<LogicalExpression>(LogicalOp::NullishCoalescing, move(lhs), parse_expression(min_precedence, associativity));
  983. case TokenType::DoubleQuestionMarkEquals:
  984. return parse_assignment_expression(AssignmentOp::NullishAssignment, move(lhs), min_precedence, associativity);
  985. case TokenType::QuestionMark:
  986. return parse_conditional_expression(move(lhs));
  987. default:
  988. expected("secondary expression");
  989. consume();
  990. return create_ast_node<ErrorExpression>();
  991. }
  992. }
  993. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(AssignmentOp assignment_op, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  994. {
  995. ASSERT(match(TokenType::Equals)
  996. || match(TokenType::PlusEquals)
  997. || match(TokenType::MinusEquals)
  998. || match(TokenType::AsteriskEquals)
  999. || match(TokenType::SlashEquals)
  1000. || match(TokenType::PercentEquals)
  1001. || match(TokenType::DoubleAsteriskEquals)
  1002. || match(TokenType::AmpersandEquals)
  1003. || match(TokenType::PipeEquals)
  1004. || match(TokenType::CaretEquals)
  1005. || match(TokenType::ShiftLeftEquals)
  1006. || match(TokenType::ShiftRightEquals)
  1007. || match(TokenType::UnsignedShiftRightEquals)
  1008. || match(TokenType::DoubleAmpersandEquals)
  1009. || match(TokenType::DoublePipeEquals)
  1010. || match(TokenType::DoubleQuestionMarkEquals));
  1011. consume();
  1012. if (!lhs->is_identifier() && !lhs->is_member_expression() && !lhs->is_call_expression()) {
  1013. syntax_error("Invalid left-hand side in assignment");
  1014. } else if (m_parser_state.m_strict_mode && lhs->is_identifier()) {
  1015. auto name = static_cast<const Identifier&>(*lhs).string();
  1016. if (name == "eval" || name == "arguments")
  1017. syntax_error(String::formatted("'{}' cannot be assigned to in strict mode code", name));
  1018. } else if (m_parser_state.m_strict_mode && lhs->is_call_expression()) {
  1019. syntax_error("Cannot assign to function call");
  1020. }
  1021. return create_ast_node<AssignmentExpression>(assignment_op, move(lhs), parse_expression(min_precedence, associativity));
  1022. }
  1023. NonnullRefPtr<CallExpression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  1024. {
  1025. if (!m_parser_state.m_allow_super_constructor_call && lhs->is_super_expression())
  1026. syntax_error("'super' keyword unexpected here");
  1027. consume(TokenType::ParenOpen);
  1028. Vector<CallExpression::Argument> arguments;
  1029. while (match_expression() || match(TokenType::TripleDot)) {
  1030. if (match(TokenType::TripleDot)) {
  1031. consume();
  1032. arguments.append({ parse_expression(2), true });
  1033. } else {
  1034. arguments.append({ parse_expression(2), false });
  1035. }
  1036. if (!match(TokenType::Comma))
  1037. break;
  1038. consume();
  1039. }
  1040. consume(TokenType::ParenClose);
  1041. return create_ast_node<CallExpression>(move(lhs), move(arguments));
  1042. }
  1043. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  1044. {
  1045. consume(TokenType::New);
  1046. auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen });
  1047. Vector<CallExpression::Argument> arguments;
  1048. if (match(TokenType::ParenOpen)) {
  1049. consume(TokenType::ParenOpen);
  1050. while (match_expression() || match(TokenType::TripleDot)) {
  1051. if (match(TokenType::TripleDot)) {
  1052. consume();
  1053. arguments.append({ parse_expression(2), true });
  1054. } else {
  1055. arguments.append({ parse_expression(2), false });
  1056. }
  1057. if (!match(TokenType::Comma))
  1058. break;
  1059. consume();
  1060. }
  1061. consume(TokenType::ParenClose);
  1062. }
  1063. return create_ast_node<NewExpression>(move(callee), move(arguments));
  1064. }
  1065. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  1066. {
  1067. if (!m_parser_state.m_in_function_context)
  1068. syntax_error("'return' not allowed outside of a function");
  1069. consume(TokenType::Return);
  1070. // Automatic semicolon insertion: terminate statement when return is followed by newline
  1071. if (m_parser_state.m_current_token.trivia_contains_line_terminator())
  1072. return create_ast_node<ReturnStatement>(nullptr);
  1073. if (match_expression()) {
  1074. auto expression = parse_expression(0);
  1075. consume_or_insert_semicolon();
  1076. return create_ast_node<ReturnStatement>(move(expression));
  1077. }
  1078. consume_or_insert_semicolon();
  1079. return create_ast_node<ReturnStatement>(nullptr);
  1080. }
  1081. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  1082. {
  1083. bool dummy = false;
  1084. return parse_block_statement(dummy);
  1085. }
  1086. NonnullRefPtr<BlockStatement> Parser::parse_block_statement(bool& is_strict)
  1087. {
  1088. ScopePusher scope(*this, ScopePusher::Let);
  1089. auto block = create_ast_node<BlockStatement>();
  1090. consume(TokenType::CurlyOpen);
  1091. bool first = true;
  1092. bool initial_strict_mode_state = m_parser_state.m_strict_mode;
  1093. if (initial_strict_mode_state) {
  1094. m_parser_state.m_use_strict_directive = UseStrictDirectiveState::None;
  1095. is_strict = true;
  1096. } else {
  1097. m_parser_state.m_use_strict_directive = UseStrictDirectiveState::Looking;
  1098. }
  1099. while (!done() && !match(TokenType::CurlyClose)) {
  1100. if (match_declaration()) {
  1101. block->append(parse_declaration());
  1102. if (first && !initial_strict_mode_state)
  1103. m_parser_state.m_use_strict_directive = UseStrictDirectiveState::None;
  1104. } else if (match_statement()) {
  1105. block->append(parse_statement());
  1106. if (first && !initial_strict_mode_state) {
  1107. if (m_parser_state.m_use_strict_directive == UseStrictDirectiveState::Found) {
  1108. is_strict = true;
  1109. m_parser_state.m_strict_mode = true;
  1110. }
  1111. m_parser_state.m_use_strict_directive = UseStrictDirectiveState::None;
  1112. }
  1113. } else {
  1114. expected("statement or declaration");
  1115. consume();
  1116. }
  1117. first = false;
  1118. }
  1119. m_parser_state.m_strict_mode = initial_strict_mode_state;
  1120. consume(TokenType::CurlyClose);
  1121. block->add_variables(m_parser_state.m_let_scopes.last());
  1122. block->add_functions(m_parser_state.m_function_scopes.last());
  1123. return block;
  1124. }
  1125. template<typename FunctionNodeType>
  1126. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(u8 parse_options)
  1127. {
  1128. ASSERT(!(parse_options & FunctionNodeParseOptions::IsGetterFunction && parse_options & FunctionNodeParseOptions::IsSetterFunction));
  1129. TemporaryChange super_property_access_rollback(m_parser_state.m_allow_super_property_lookup, !!(parse_options & FunctionNodeParseOptions::AllowSuperPropertyLookup));
  1130. TemporaryChange super_constructor_call_rollback(m_parser_state.m_allow_super_constructor_call, !!(parse_options & FunctionNodeParseOptions::AllowSuperConstructorCall));
  1131. ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Function);
  1132. String name;
  1133. if (parse_options & FunctionNodeParseOptions::CheckForFunctionAndName) {
  1134. consume(TokenType::Function);
  1135. if (FunctionNodeType::must_have_name() || match(TokenType::Identifier))
  1136. name = consume(TokenType::Identifier).value();
  1137. }
  1138. consume(TokenType::ParenOpen);
  1139. i32 function_length = -1;
  1140. auto parameters = parse_function_parameters(function_length, parse_options);
  1141. consume(TokenType::ParenClose);
  1142. if (function_length == -1)
  1143. function_length = parameters.size();
  1144. TemporaryChange change(m_parser_state.m_in_function_context, true);
  1145. auto old_labels_in_scope = move(m_parser_state.m_labels_in_scope);
  1146. ScopeGuard guard([&]() {
  1147. m_parser_state.m_labels_in_scope = move(old_labels_in_scope);
  1148. });
  1149. bool is_strict = false;
  1150. auto body = parse_block_statement(is_strict);
  1151. body->add_variables(m_parser_state.m_var_scopes.last());
  1152. body->add_functions(m_parser_state.m_function_scopes.last());
  1153. return create_ast_node<FunctionNodeType>(name, move(body), move(parameters), function_length, NonnullRefPtrVector<VariableDeclaration>(), is_strict);
  1154. }
  1155. Vector<FunctionNode::Parameter> Parser::parse_function_parameters(int& function_length, u8 parse_options)
  1156. {
  1157. Vector<FunctionNode::Parameter> parameters;
  1158. while (match(TokenType::Identifier) || match(TokenType::TripleDot)) {
  1159. if (parse_options & FunctionNodeParseOptions::IsGetterFunction)
  1160. syntax_error("Getter function must have no arguments");
  1161. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && (parameters.size() >= 1 || match(TokenType::TripleDot)))
  1162. syntax_error("Setter function must have one argument");
  1163. if (match(TokenType::TripleDot)) {
  1164. consume();
  1165. auto parameter_name = consume(TokenType::Identifier).value();
  1166. function_length = parameters.size();
  1167. parameters.append({ parameter_name, nullptr, true });
  1168. break;
  1169. }
  1170. auto parameter_name = consume(TokenType::Identifier).value();
  1171. RefPtr<Expression> default_value;
  1172. if (match(TokenType::Equals)) {
  1173. consume(TokenType::Equals);
  1174. function_length = parameters.size();
  1175. default_value = parse_expression(2);
  1176. }
  1177. parameters.append({ parameter_name, default_value });
  1178. if (match(TokenType::ParenClose))
  1179. break;
  1180. consume(TokenType::Comma);
  1181. }
  1182. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && parameters.is_empty())
  1183. syntax_error("Setter function must have one argument");
  1184. return parameters;
  1185. }
  1186. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool with_semicolon)
  1187. {
  1188. DeclarationKind declaration_kind;
  1189. switch (m_parser_state.m_current_token.type()) {
  1190. case TokenType::Var:
  1191. declaration_kind = DeclarationKind::Var;
  1192. consume(TokenType::Var);
  1193. break;
  1194. case TokenType::Let:
  1195. declaration_kind = DeclarationKind::Let;
  1196. consume(TokenType::Let);
  1197. break;
  1198. case TokenType::Const:
  1199. declaration_kind = DeclarationKind::Const;
  1200. consume(TokenType::Const);
  1201. break;
  1202. default:
  1203. ASSERT_NOT_REACHED();
  1204. }
  1205. NonnullRefPtrVector<VariableDeclarator> declarations;
  1206. for (;;) {
  1207. auto id = consume(TokenType::Identifier).value();
  1208. RefPtr<Expression> init;
  1209. if (match(TokenType::Equals)) {
  1210. consume();
  1211. init = parse_expression(2);
  1212. }
  1213. declarations.append(create_ast_node<VariableDeclarator>(create_ast_node<Identifier>(move(id)), move(init)));
  1214. if (match(TokenType::Comma)) {
  1215. consume();
  1216. continue;
  1217. }
  1218. break;
  1219. }
  1220. if (with_semicolon)
  1221. consume_or_insert_semicolon();
  1222. auto declaration = create_ast_node<VariableDeclaration>(declaration_kind, move(declarations));
  1223. if (declaration_kind == DeclarationKind::Var)
  1224. m_parser_state.m_var_scopes.last().append(declaration);
  1225. else
  1226. m_parser_state.m_let_scopes.last().append(declaration);
  1227. return declaration;
  1228. }
  1229. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  1230. {
  1231. consume(TokenType::Throw);
  1232. // Automatic semicolon insertion: terminate statement when throw is followed by newline
  1233. if (m_parser_state.m_current_token.trivia_contains_line_terminator()) {
  1234. syntax_error("No line break is allowed between 'throw' and its expression");
  1235. return create_ast_node<ThrowStatement>(create_ast_node<ErrorExpression>());
  1236. }
  1237. auto expression = parse_expression(0);
  1238. consume_or_insert_semicolon();
  1239. return create_ast_node<ThrowStatement>(move(expression));
  1240. }
  1241. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  1242. {
  1243. consume(TokenType::Break);
  1244. FlyString target_label;
  1245. if (match(TokenType::Semicolon)) {
  1246. consume();
  1247. } else {
  1248. if (match(TokenType::Identifier) && !m_parser_state.m_current_token.trivia_contains_line_terminator()) {
  1249. target_label = consume().value();
  1250. if (!m_parser_state.m_labels_in_scope.contains(target_label))
  1251. syntax_error(String::formatted("Label '{}' not found", target_label));
  1252. }
  1253. consume_or_insert_semicolon();
  1254. }
  1255. if (target_label.is_null() && !m_parser_state.m_in_break_context)
  1256. syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement");
  1257. return create_ast_node<BreakStatement>(target_label);
  1258. }
  1259. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  1260. {
  1261. if (!m_parser_state.m_in_continue_context)
  1262. syntax_error("'continue' not allow outside of a loop");
  1263. consume(TokenType::Continue);
  1264. FlyString target_label;
  1265. if (match(TokenType::Semicolon)) {
  1266. consume();
  1267. return create_ast_node<ContinueStatement>(target_label);
  1268. }
  1269. if (match(TokenType::Identifier) && !m_parser_state.m_current_token.trivia_contains_line_terminator()) {
  1270. target_label = consume().value();
  1271. if (!m_parser_state.m_labels_in_scope.contains(target_label))
  1272. syntax_error(String::formatted("Label '{}' not found", target_label));
  1273. }
  1274. consume_or_insert_semicolon();
  1275. return create_ast_node<ContinueStatement>(target_label);
  1276. }
  1277. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test)
  1278. {
  1279. consume(TokenType::QuestionMark);
  1280. auto consequent = parse_expression(2);
  1281. consume(TokenType::Colon);
  1282. auto alternate = parse_expression(2);
  1283. return create_ast_node<ConditionalExpression>(move(test), move(consequent), move(alternate));
  1284. }
  1285. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  1286. {
  1287. consume(TokenType::Try);
  1288. auto block = parse_block_statement();
  1289. auto handler = parse_catch_clause();
  1290. RefPtr<BlockStatement> finalizer;
  1291. if (match(TokenType::Finally)) {
  1292. consume();
  1293. finalizer = parse_block_statement();
  1294. }
  1295. return create_ast_node<TryStatement>(move(block), move(handler), move(finalizer));
  1296. }
  1297. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  1298. {
  1299. consume(TokenType::Do);
  1300. auto body = [&]() -> NonnullRefPtr<Statement> {
  1301. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1302. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1303. return parse_statement();
  1304. }();
  1305. consume(TokenType::While);
  1306. consume(TokenType::ParenOpen);
  1307. auto test = parse_expression(0);
  1308. consume(TokenType::ParenClose);
  1309. consume_or_insert_semicolon();
  1310. return create_ast_node<DoWhileStatement>(move(test), move(body));
  1311. }
  1312. NonnullRefPtr<WhileStatement> Parser::parse_while_statement()
  1313. {
  1314. consume(TokenType::While);
  1315. consume(TokenType::ParenOpen);
  1316. auto test = parse_expression(0);
  1317. consume(TokenType::ParenClose);
  1318. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1319. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1320. auto body = parse_statement();
  1321. return create_ast_node<WhileStatement>(move(test), move(body));
  1322. }
  1323. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  1324. {
  1325. consume(TokenType::Switch);
  1326. consume(TokenType::ParenOpen);
  1327. auto determinant = parse_expression(0);
  1328. consume(TokenType::ParenClose);
  1329. consume(TokenType::CurlyOpen);
  1330. NonnullRefPtrVector<SwitchCase> cases;
  1331. auto has_default = false;
  1332. while (match(TokenType::Case) || match(TokenType::Default)) {
  1333. if (match(TokenType::Default)) {
  1334. if (has_default)
  1335. syntax_error("Multiple 'default' clauses in switch statement");
  1336. has_default = true;
  1337. }
  1338. cases.append(parse_switch_case());
  1339. }
  1340. consume(TokenType::CurlyClose);
  1341. return create_ast_node<SwitchStatement>(move(determinant), move(cases));
  1342. }
  1343. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  1344. {
  1345. RefPtr<Expression> test;
  1346. if (consume().type() == TokenType::Case) {
  1347. test = parse_expression(0);
  1348. }
  1349. consume(TokenType::Colon);
  1350. NonnullRefPtrVector<Statement> consequent;
  1351. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1352. for (;;) {
  1353. if (match_declaration())
  1354. consequent.append(parse_declaration());
  1355. else if (match_statement())
  1356. consequent.append(parse_statement());
  1357. else
  1358. break;
  1359. }
  1360. return create_ast_node<SwitchCase>(move(test), move(consequent));
  1361. }
  1362. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  1363. {
  1364. consume(TokenType::Catch);
  1365. String parameter;
  1366. if (match(TokenType::ParenOpen)) {
  1367. consume();
  1368. parameter = consume(TokenType::Identifier).value();
  1369. consume(TokenType::ParenClose);
  1370. }
  1371. auto body = parse_block_statement();
  1372. return create_ast_node<CatchClause>(parameter, move(body));
  1373. }
  1374. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  1375. {
  1376. consume(TokenType::If);
  1377. consume(TokenType::ParenOpen);
  1378. auto predicate = parse_expression(0);
  1379. consume(TokenType::ParenClose);
  1380. auto consequent = parse_statement();
  1381. RefPtr<Statement> alternate;
  1382. if (match(TokenType::Else)) {
  1383. consume(TokenType::Else);
  1384. alternate = parse_statement();
  1385. }
  1386. return create_ast_node<IfStatement>(move(predicate), move(consequent), move(alternate));
  1387. }
  1388. NonnullRefPtr<Statement> Parser::parse_for_statement()
  1389. {
  1390. auto match_for_in_of = [&]() {
  1391. return match(TokenType::In) || (match(TokenType::Identifier) && m_parser_state.m_current_token.value() == "of");
  1392. };
  1393. consume(TokenType::For);
  1394. consume(TokenType::ParenOpen);
  1395. bool in_scope = false;
  1396. RefPtr<ASTNode> init;
  1397. if (!match(TokenType::Semicolon)) {
  1398. if (match_expression()) {
  1399. init = parse_expression(0, Associativity::Right, { TokenType::In });
  1400. if (match_for_in_of())
  1401. return parse_for_in_of_statement(*init);
  1402. } else if (match_variable_declaration()) {
  1403. if (!match(TokenType::Var)) {
  1404. m_parser_state.m_let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  1405. in_scope = true;
  1406. }
  1407. init = parse_variable_declaration(false);
  1408. if (match_for_in_of())
  1409. return parse_for_in_of_statement(*init);
  1410. } else {
  1411. syntax_error("Unexpected token in for loop");
  1412. }
  1413. }
  1414. consume(TokenType::Semicolon);
  1415. RefPtr<Expression> test;
  1416. if (!match(TokenType::Semicolon))
  1417. test = parse_expression(0);
  1418. consume(TokenType::Semicolon);
  1419. RefPtr<Expression> update;
  1420. if (!match(TokenType::ParenClose))
  1421. update = parse_expression(0);
  1422. consume(TokenType::ParenClose);
  1423. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1424. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1425. auto body = parse_statement();
  1426. if (in_scope) {
  1427. m_parser_state.m_let_scopes.take_last();
  1428. }
  1429. return create_ast_node<ForStatement>(move(init), move(test), move(update), move(body));
  1430. }
  1431. NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs)
  1432. {
  1433. if (lhs->is_variable_declaration()) {
  1434. auto declarations = static_cast<VariableDeclaration*>(lhs.ptr())->declarations();
  1435. if (declarations.size() > 1) {
  1436. syntax_error("multiple declarations not allowed in for..in/of");
  1437. lhs = create_ast_node<ErrorExpression>();
  1438. }
  1439. if (declarations.first().init() != nullptr) {
  1440. syntax_error("variable initializer not allowed in for..in/of");
  1441. lhs = create_ast_node<ErrorExpression>();
  1442. }
  1443. }
  1444. auto in_or_of = consume();
  1445. auto rhs = parse_expression(0);
  1446. consume(TokenType::ParenClose);
  1447. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1448. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1449. auto body = parse_statement();
  1450. if (in_or_of.type() == TokenType::In)
  1451. return create_ast_node<ForInStatement>(move(lhs), move(rhs), move(body));
  1452. return create_ast_node<ForOfStatement>(move(lhs), move(rhs), move(body));
  1453. }
  1454. NonnullRefPtr<DebuggerStatement> Parser::parse_debugger_statement()
  1455. {
  1456. consume(TokenType::Debugger);
  1457. consume_or_insert_semicolon();
  1458. return create_ast_node<DebuggerStatement>();
  1459. }
  1460. bool Parser::match(TokenType type) const
  1461. {
  1462. return m_parser_state.m_current_token.type() == type;
  1463. }
  1464. bool Parser::match_expression() const
  1465. {
  1466. auto type = m_parser_state.m_current_token.type();
  1467. return type == TokenType::BoolLiteral
  1468. || type == TokenType::NumericLiteral
  1469. || type == TokenType::BigIntLiteral
  1470. || type == TokenType::StringLiteral
  1471. || type == TokenType::TemplateLiteralStart
  1472. || type == TokenType::NullLiteral
  1473. || type == TokenType::Identifier
  1474. || type == TokenType::New
  1475. || type == TokenType::CurlyOpen
  1476. || type == TokenType::BracketOpen
  1477. || type == TokenType::ParenOpen
  1478. || type == TokenType::Function
  1479. || type == TokenType::This
  1480. || type == TokenType::Super
  1481. || type == TokenType::RegexLiteral
  1482. || match_unary_prefixed_expression();
  1483. }
  1484. bool Parser::match_unary_prefixed_expression() const
  1485. {
  1486. auto type = m_parser_state.m_current_token.type();
  1487. return type == TokenType::PlusPlus
  1488. || type == TokenType::MinusMinus
  1489. || type == TokenType::ExclamationMark
  1490. || type == TokenType::Tilde
  1491. || type == TokenType::Plus
  1492. || type == TokenType::Minus
  1493. || type == TokenType::Typeof
  1494. || type == TokenType::Void
  1495. || type == TokenType::Delete;
  1496. }
  1497. bool Parser::match_secondary_expression(Vector<TokenType> forbidden) const
  1498. {
  1499. auto type = m_parser_state.m_current_token.type();
  1500. if (forbidden.contains_slow(type))
  1501. return false;
  1502. return type == TokenType::Plus
  1503. || type == TokenType::PlusEquals
  1504. || type == TokenType::Minus
  1505. || type == TokenType::MinusEquals
  1506. || type == TokenType::Asterisk
  1507. || type == TokenType::AsteriskEquals
  1508. || type == TokenType::Slash
  1509. || type == TokenType::SlashEquals
  1510. || type == TokenType::Percent
  1511. || type == TokenType::PercentEquals
  1512. || type == TokenType::DoubleAsterisk
  1513. || type == TokenType::DoubleAsteriskEquals
  1514. || type == TokenType::Equals
  1515. || type == TokenType::EqualsEqualsEquals
  1516. || type == TokenType::ExclamationMarkEqualsEquals
  1517. || type == TokenType::EqualsEquals
  1518. || type == TokenType::ExclamationMarkEquals
  1519. || type == TokenType::GreaterThan
  1520. || type == TokenType::GreaterThanEquals
  1521. || type == TokenType::LessThan
  1522. || type == TokenType::LessThanEquals
  1523. || type == TokenType::ParenOpen
  1524. || type == TokenType::Period
  1525. || type == TokenType::BracketOpen
  1526. || type == TokenType::PlusPlus
  1527. || type == TokenType::MinusMinus
  1528. || type == TokenType::In
  1529. || type == TokenType::Instanceof
  1530. || type == TokenType::QuestionMark
  1531. || type == TokenType::Ampersand
  1532. || type == TokenType::AmpersandEquals
  1533. || type == TokenType::Pipe
  1534. || type == TokenType::PipeEquals
  1535. || type == TokenType::Caret
  1536. || type == TokenType::CaretEquals
  1537. || type == TokenType::ShiftLeft
  1538. || type == TokenType::ShiftLeftEquals
  1539. || type == TokenType::ShiftRight
  1540. || type == TokenType::ShiftRightEquals
  1541. || type == TokenType::UnsignedShiftRight
  1542. || type == TokenType::UnsignedShiftRightEquals
  1543. || type == TokenType::DoubleAmpersand
  1544. || type == TokenType::DoubleAmpersandEquals
  1545. || type == TokenType::DoublePipe
  1546. || type == TokenType::DoublePipeEquals
  1547. || type == TokenType::DoubleQuestionMark
  1548. || type == TokenType::DoubleQuestionMarkEquals;
  1549. }
  1550. bool Parser::match_statement() const
  1551. {
  1552. auto type = m_parser_state.m_current_token.type();
  1553. return match_expression()
  1554. || type == TokenType::Return
  1555. || type == TokenType::Do
  1556. || type == TokenType::If
  1557. || type == TokenType::Throw
  1558. || type == TokenType::Try
  1559. || type == TokenType::While
  1560. || type == TokenType::For
  1561. || type == TokenType::CurlyOpen
  1562. || type == TokenType::Switch
  1563. || type == TokenType::Break
  1564. || type == TokenType::Continue
  1565. || type == TokenType::Var
  1566. || type == TokenType::Debugger
  1567. || type == TokenType::Semicolon;
  1568. }
  1569. bool Parser::match_declaration() const
  1570. {
  1571. auto type = m_parser_state.m_current_token.type();
  1572. return type == TokenType::Function
  1573. || type == TokenType::Class
  1574. || type == TokenType::Const
  1575. || type == TokenType::Let;
  1576. }
  1577. bool Parser::match_variable_declaration() const
  1578. {
  1579. auto type = m_parser_state.m_current_token.type();
  1580. return type == TokenType::Var
  1581. || type == TokenType::Let
  1582. || type == TokenType::Const;
  1583. }
  1584. bool Parser::match_identifier_name() const
  1585. {
  1586. return m_parser_state.m_current_token.is_identifier_name();
  1587. }
  1588. bool Parser::match_property_key() const
  1589. {
  1590. auto type = m_parser_state.m_current_token.type();
  1591. return match_identifier_name()
  1592. || type == TokenType::BracketOpen
  1593. || type == TokenType::StringLiteral
  1594. || type == TokenType::NumericLiteral
  1595. || type == TokenType::BigIntLiteral;
  1596. }
  1597. bool Parser::done() const
  1598. {
  1599. return match(TokenType::Eof);
  1600. }
  1601. Token Parser::consume()
  1602. {
  1603. auto old_token = m_parser_state.m_current_token;
  1604. m_parser_state.m_current_token = m_parser_state.m_lexer.next();
  1605. return old_token;
  1606. }
  1607. void Parser::consume_or_insert_semicolon()
  1608. {
  1609. // Semicolon was found and will be consumed
  1610. if (match(TokenType::Semicolon)) {
  1611. consume();
  1612. return;
  1613. }
  1614. // Insert semicolon if...
  1615. // ...token is preceded by one or more newlines
  1616. if (m_parser_state.m_current_token.trivia_contains_line_terminator())
  1617. return;
  1618. // ...token is a closing curly brace
  1619. if (match(TokenType::CurlyClose))
  1620. return;
  1621. // ...token is eof
  1622. if (match(TokenType::Eof))
  1623. return;
  1624. // No rule for semicolon insertion applies -> syntax error
  1625. expected("Semicolon");
  1626. }
  1627. Token Parser::consume(TokenType expected_type)
  1628. {
  1629. if (!match(expected_type)) {
  1630. expected(Token::name(expected_type));
  1631. }
  1632. return consume();
  1633. }
  1634. Token Parser::consume_and_validate_numeric_literal()
  1635. {
  1636. auto is_unprefixed_octal_number = [](const StringView& value) {
  1637. return value.length() > 1 && value[0] == '0' && isdigit(value[1]);
  1638. };
  1639. auto literal_start_line = m_parser_state.m_current_token.line_number();
  1640. auto literal_start_column = m_parser_state.m_current_token.line_column();
  1641. auto token = consume(TokenType::NumericLiteral);
  1642. if (m_parser_state.m_strict_mode && is_unprefixed_octal_number(token.value()))
  1643. syntax_error("Unprefixed octal number not allowed in strict mode", literal_start_line, literal_start_column);
  1644. if (match_identifier_name() && m_parser_state.m_current_token.trivia().is_empty())
  1645. syntax_error("Numeric literal must not be immediately followed by identifier");
  1646. return token;
  1647. }
  1648. void Parser::expected(const char* what)
  1649. {
  1650. syntax_error(String::formatted("Unexpected token {}. Expected {}", m_parser_state.m_current_token.name(), what));
  1651. }
  1652. void Parser::syntax_error(const String& message, size_t line, size_t column)
  1653. {
  1654. if (line == 0 || column == 0) {
  1655. line = m_parser_state.m_current_token.line_number();
  1656. column = m_parser_state.m_current_token.line_column();
  1657. }
  1658. m_parser_state.m_errors.append({ message, line, column });
  1659. }
  1660. void Parser::save_state()
  1661. {
  1662. m_saved_state.append(m_parser_state);
  1663. }
  1664. void Parser::load_state()
  1665. {
  1666. ASSERT(!m_saved_state.is_empty());
  1667. m_parser_state = m_saved_state.take_last();
  1668. }
  1669. }