Parser.cpp 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  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 "Parser.h"
  8. #include <AK/Array.h>
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/HashTable.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <AK/StdLibExtras.h>
  13. #include <AK/TemporaryChange.h>
  14. namespace JS {
  15. static bool statement_is_use_strict_directive(NonnullRefPtr<Statement> statement)
  16. {
  17. if (!is<ExpressionStatement>(*statement))
  18. return false;
  19. auto& expression_statement = static_cast<ExpressionStatement&>(*statement);
  20. auto& expression = expression_statement.expression();
  21. if (!is<StringLiteral>(expression))
  22. return false;
  23. return static_cast<const StringLiteral&>(expression).is_use_strict_directive();
  24. }
  25. class ScopePusher {
  26. public:
  27. enum Type {
  28. Var = 1,
  29. Let = 2,
  30. };
  31. ScopePusher(Parser& parser, unsigned mask, Parser::Scope::Type scope_type)
  32. : m_parser(parser)
  33. , m_mask(mask)
  34. {
  35. if (m_mask & Var)
  36. m_parser.m_state.var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  37. if (m_mask & Let)
  38. m_parser.m_state.let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  39. m_parser.m_state.current_scope = create<Parser::Scope>(scope_type, m_parser.m_state.current_scope);
  40. }
  41. ~ScopePusher()
  42. {
  43. if (m_mask & Var)
  44. m_parser.m_state.var_scopes.take_last();
  45. if (m_mask & Let)
  46. m_parser.m_state.let_scopes.take_last();
  47. auto& popped = m_parser.m_state.current_scope;
  48. m_parser.m_state.current_scope = popped->parent;
  49. }
  50. void add_to_scope_node(NonnullRefPtr<ScopeNode> scope_node)
  51. {
  52. if (m_mask & Var)
  53. scope_node->add_variables(m_parser.m_state.var_scopes.last());
  54. if (m_mask & Let)
  55. scope_node->add_variables(m_parser.m_state.let_scopes.last());
  56. scope_node->add_functions(m_parser.m_state.current_scope->function_declarations);
  57. scope_node->add_hoisted_functions(m_parser.m_state.current_scope->hoisted_function_declarations);
  58. }
  59. Parser& m_parser;
  60. unsigned m_mask { 0 };
  61. };
  62. class OperatorPrecedenceTable {
  63. public:
  64. constexpr OperatorPrecedenceTable()
  65. : m_token_precedence()
  66. {
  67. for (size_t i = 0; i < array_size(m_operator_precedence); ++i) {
  68. auto& op = m_operator_precedence[i];
  69. m_token_precedence[static_cast<size_t>(op.token)] = op.precedence;
  70. }
  71. }
  72. constexpr int get(TokenType token) const
  73. {
  74. int p = m_token_precedence[static_cast<size_t>(token)];
  75. if (p == 0) {
  76. warnln("Internal Error: No precedence for operator {}", Token::name(token));
  77. VERIFY_NOT_REACHED();
  78. return -1;
  79. }
  80. return p;
  81. }
  82. private:
  83. int m_token_precedence[cs_num_of_js_tokens];
  84. struct OperatorPrecedence {
  85. TokenType token;
  86. int precedence;
  87. };
  88. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  89. static constexpr const OperatorPrecedence m_operator_precedence[] = {
  90. { TokenType::Period, 20 },
  91. { TokenType::BracketOpen, 20 },
  92. { TokenType::ParenOpen, 20 },
  93. { TokenType::QuestionMarkPeriod, 20 },
  94. { TokenType::New, 19 },
  95. { TokenType::PlusPlus, 18 },
  96. { TokenType::MinusMinus, 18 },
  97. { TokenType::ExclamationMark, 17 },
  98. { TokenType::Tilde, 17 },
  99. { TokenType::Typeof, 17 },
  100. { TokenType::Void, 17 },
  101. { TokenType::Delete, 17 },
  102. { TokenType::Await, 17 },
  103. { TokenType::DoubleAsterisk, 16 },
  104. { TokenType::Asterisk, 15 },
  105. { TokenType::Slash, 15 },
  106. { TokenType::Percent, 15 },
  107. { TokenType::Plus, 14 },
  108. { TokenType::Minus, 14 },
  109. { TokenType::ShiftLeft, 13 },
  110. { TokenType::ShiftRight, 13 },
  111. { TokenType::UnsignedShiftRight, 13 },
  112. { TokenType::LessThan, 12 },
  113. { TokenType::LessThanEquals, 12 },
  114. { TokenType::GreaterThan, 12 },
  115. { TokenType::GreaterThanEquals, 12 },
  116. { TokenType::In, 12 },
  117. { TokenType::Instanceof, 12 },
  118. { TokenType::EqualsEquals, 11 },
  119. { TokenType::ExclamationMarkEquals, 11 },
  120. { TokenType::EqualsEqualsEquals, 11 },
  121. { TokenType::ExclamationMarkEqualsEquals, 11 },
  122. { TokenType::Ampersand, 10 },
  123. { TokenType::Caret, 9 },
  124. { TokenType::Pipe, 8 },
  125. { TokenType::DoubleQuestionMark, 7 },
  126. { TokenType::DoubleAmpersand, 6 },
  127. { TokenType::DoublePipe, 5 },
  128. { TokenType::QuestionMark, 4 },
  129. { TokenType::Equals, 3 },
  130. { TokenType::PlusEquals, 3 },
  131. { TokenType::MinusEquals, 3 },
  132. { TokenType::DoubleAsteriskEquals, 3 },
  133. { TokenType::AsteriskEquals, 3 },
  134. { TokenType::SlashEquals, 3 },
  135. { TokenType::PercentEquals, 3 },
  136. { TokenType::ShiftLeftEquals, 3 },
  137. { TokenType::ShiftRightEquals, 3 },
  138. { TokenType::UnsignedShiftRightEquals, 3 },
  139. { TokenType::AmpersandEquals, 3 },
  140. { TokenType::CaretEquals, 3 },
  141. { TokenType::PipeEquals, 3 },
  142. { TokenType::DoubleAmpersandEquals, 3 },
  143. { TokenType::DoublePipeEquals, 3 },
  144. { TokenType::DoubleQuestionMarkEquals, 3 },
  145. { TokenType::Yield, 2 },
  146. { TokenType::Comma, 1 },
  147. };
  148. };
  149. constexpr OperatorPrecedenceTable g_operator_precedence;
  150. Parser::ParserState::ParserState(Lexer l)
  151. : lexer(move(l))
  152. , current_token(lexer.next())
  153. {
  154. }
  155. Parser::Scope::Scope(Parser::Scope::Type type, RefPtr<Parser::Scope> parent_scope)
  156. : type(type)
  157. , parent(move(parent_scope))
  158. {
  159. }
  160. RefPtr<Parser::Scope> Parser::Scope::get_current_function_scope()
  161. {
  162. if (this->type == Parser::Scope::Function) {
  163. return *this;
  164. }
  165. auto result = this->parent;
  166. while (result->type != Parser::Scope::Function) {
  167. result = result->parent;
  168. }
  169. return result;
  170. }
  171. Parser::Parser(Lexer lexer)
  172. : m_state(move(lexer))
  173. {
  174. }
  175. Associativity Parser::operator_associativity(TokenType type) const
  176. {
  177. switch (type) {
  178. case TokenType::Period:
  179. case TokenType::BracketOpen:
  180. case TokenType::ParenOpen:
  181. case TokenType::QuestionMarkPeriod:
  182. case TokenType::Asterisk:
  183. case TokenType::Slash:
  184. case TokenType::Percent:
  185. case TokenType::Plus:
  186. case TokenType::Minus:
  187. case TokenType::ShiftLeft:
  188. case TokenType::ShiftRight:
  189. case TokenType::UnsignedShiftRight:
  190. case TokenType::LessThan:
  191. case TokenType::LessThanEquals:
  192. case TokenType::GreaterThan:
  193. case TokenType::GreaterThanEquals:
  194. case TokenType::In:
  195. case TokenType::Instanceof:
  196. case TokenType::EqualsEquals:
  197. case TokenType::ExclamationMarkEquals:
  198. case TokenType::EqualsEqualsEquals:
  199. case TokenType::ExclamationMarkEqualsEquals:
  200. case TokenType::Typeof:
  201. case TokenType::Void:
  202. case TokenType::Delete:
  203. case TokenType::Ampersand:
  204. case TokenType::Caret:
  205. case TokenType::Pipe:
  206. case TokenType::DoubleQuestionMark:
  207. case TokenType::DoubleAmpersand:
  208. case TokenType::DoublePipe:
  209. case TokenType::Comma:
  210. return Associativity::Left;
  211. default:
  212. return Associativity::Right;
  213. }
  214. }
  215. NonnullRefPtr<Program> Parser::parse_program(bool starts_in_strict_mode)
  216. {
  217. auto rule_start = push_start();
  218. ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Let, Scope::Function);
  219. auto program = adopt_ref(*new Program({ m_filename, rule_start.position(), position() }));
  220. if (starts_in_strict_mode) {
  221. program->set_strict_mode();
  222. m_state.strict_mode = true;
  223. }
  224. bool first = true;
  225. while (!done()) {
  226. if (match_declaration()) {
  227. program->append(parse_declaration());
  228. } else if (match_statement()) {
  229. auto statement = parse_statement();
  230. program->append(statement);
  231. if (statement_is_use_strict_directive(statement)) {
  232. if (first) {
  233. program->set_strict_mode();
  234. m_state.strict_mode = true;
  235. }
  236. if (m_state.string_legacy_octal_escape_sequence_in_scope)
  237. syntax_error("Octal escape sequence in string literal not allowed in strict mode");
  238. }
  239. } else {
  240. expected("statement or declaration");
  241. consume();
  242. }
  243. first = false;
  244. }
  245. if (m_state.var_scopes.size() == 1) {
  246. scope.add_to_scope_node(program);
  247. } else {
  248. syntax_error("Unclosed lexical_environment");
  249. }
  250. program->source_range().end = position();
  251. return program;
  252. }
  253. NonnullRefPtr<Declaration> Parser::parse_declaration()
  254. {
  255. auto rule_start = push_start();
  256. switch (m_state.current_token.type()) {
  257. case TokenType::Class:
  258. return parse_class_declaration();
  259. case TokenType::Function: {
  260. auto declaration = parse_function_node<FunctionDeclaration>();
  261. m_state.current_scope->function_declarations.append(declaration);
  262. m_state.current_scope->get_current_function_scope()->hoisted_function_declarations.append(declaration);
  263. return declaration;
  264. }
  265. case TokenType::Let:
  266. case TokenType::Const:
  267. return parse_variable_declaration();
  268. default:
  269. expected("declaration");
  270. consume();
  271. return create_ast_node<ErrorDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() });
  272. }
  273. }
  274. NonnullRefPtr<Statement> Parser::parse_statement()
  275. {
  276. auto rule_start = push_start();
  277. switch (m_state.current_token.type()) {
  278. case TokenType::CurlyOpen:
  279. return parse_block_statement();
  280. case TokenType::Return:
  281. return parse_return_statement();
  282. case TokenType::Var:
  283. return parse_variable_declaration();
  284. case TokenType::For:
  285. return parse_for_statement();
  286. case TokenType::If:
  287. return parse_if_statement();
  288. case TokenType::Throw:
  289. return parse_throw_statement();
  290. case TokenType::Try:
  291. return parse_try_statement();
  292. case TokenType::Break:
  293. return parse_break_statement();
  294. case TokenType::Continue:
  295. return parse_continue_statement();
  296. case TokenType::Switch:
  297. return parse_switch_statement();
  298. case TokenType::Do:
  299. return parse_do_while_statement();
  300. case TokenType::While:
  301. return parse_while_statement();
  302. case TokenType::With:
  303. if (m_state.strict_mode)
  304. syntax_error("'with' statement not allowed in strict mode");
  305. return parse_with_statement();
  306. case TokenType::Debugger:
  307. return parse_debugger_statement();
  308. case TokenType::Semicolon:
  309. consume();
  310. return create_ast_node<EmptyStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  311. default:
  312. if (match(TokenType::Identifier)) {
  313. auto result = try_parse_labelled_statement();
  314. if (!result.is_null())
  315. return result.release_nonnull();
  316. }
  317. if (match_expression()) {
  318. if (match(TokenType::Function))
  319. syntax_error("Function declaration not allowed in single-statement context");
  320. auto expr = parse_expression(0);
  321. consume_or_insert_semicolon();
  322. return create_ast_node<ExpressionStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expr));
  323. }
  324. expected("statement");
  325. consume();
  326. return create_ast_node<ErrorStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  327. }
  328. }
  329. RefPtr<FunctionExpression> Parser::try_parse_arrow_function_expression(bool expect_parens)
  330. {
  331. save_state();
  332. auto rule_start = push_start();
  333. ArmedScopeGuard state_rollback_guard = [&] {
  334. load_state();
  335. };
  336. Vector<FunctionNode::Parameter> parameters;
  337. i32 function_length = -1;
  338. if (expect_parens) {
  339. // We have parens around the function parameters and can re-use the same parsing
  340. // logic used for regular functions: multiple parameters, default values, rest
  341. // parameter, maybe a trailing comma. If we have a new syntax error afterwards we
  342. // check if it's about a wrong token (something like duplicate parameter name must
  343. // not abort), know parsing failed and rollback the parser state.
  344. auto previous_syntax_errors = m_state.errors.size();
  345. parameters = parse_formal_parameters(function_length, FunctionNodeParseOptions::IsArrowFunction);
  346. if (m_state.errors.size() > previous_syntax_errors && m_state.errors[previous_syntax_errors].message.starts_with("Unexpected token"))
  347. return nullptr;
  348. if (!match(TokenType::ParenClose))
  349. return nullptr;
  350. consume();
  351. } else {
  352. // No parens - this must be an identifier followed by arrow. That's it.
  353. if (!match(TokenType::Identifier))
  354. return nullptr;
  355. parameters.append({ FlyString { consume().value() }, {} });
  356. }
  357. // If there's a newline between the closing paren and arrow it's not a valid arrow function,
  358. // ASI should kick in instead (it'll then fail with "Unexpected token Arrow")
  359. if (m_state.current_token.trivia_contains_line_terminator())
  360. return nullptr;
  361. if (!match(TokenType::Arrow))
  362. return nullptr;
  363. consume();
  364. if (function_length == -1)
  365. function_length = parameters.size();
  366. m_state.function_parameters.append(parameters);
  367. auto old_labels_in_scope = move(m_state.labels_in_scope);
  368. ScopeGuard guard([&]() {
  369. m_state.labels_in_scope = move(old_labels_in_scope);
  370. });
  371. bool is_strict = false;
  372. auto function_body_result = [&]() -> RefPtr<BlockStatement> {
  373. TemporaryChange change(m_state.in_arrow_function_context, true);
  374. if (match(TokenType::CurlyOpen)) {
  375. // Parse a function body with statements
  376. ScopePusher scope(*this, ScopePusher::Var, Scope::Function);
  377. auto body = parse_block_statement(is_strict);
  378. scope.add_to_scope_node(body);
  379. return body;
  380. }
  381. if (match_expression()) {
  382. // Parse a function body which returns a single expression
  383. // FIXME: We synthesize a block with a return statement
  384. // for arrow function bodies which are a single expression.
  385. // Esprima generates a single "ArrowFunctionExpression"
  386. // with a "body" property.
  387. auto return_expression = parse_expression(2);
  388. auto return_block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  389. return_block->append<ReturnStatement>({ m_filename, rule_start.position(), position() }, move(return_expression));
  390. return return_block;
  391. }
  392. // Invalid arrow function body
  393. return nullptr;
  394. }();
  395. m_state.function_parameters.take_last();
  396. if (!function_body_result.is_null()) {
  397. state_rollback_guard.disarm();
  398. discard_saved_state();
  399. auto body = function_body_result.release_nonnull();
  400. return create_ast_node<FunctionExpression>(
  401. { m_state.current_token.filename(), rule_start.position(), position() }, "", move(body),
  402. move(parameters), function_length, FunctionKind::Regular, is_strict, true);
  403. }
  404. return nullptr;
  405. }
  406. RefPtr<Statement> Parser::try_parse_labelled_statement()
  407. {
  408. save_state();
  409. auto rule_start = push_start();
  410. ArmedScopeGuard state_rollback_guard = [&] {
  411. load_state();
  412. };
  413. auto identifier = consume(TokenType::Identifier).value();
  414. if (!match(TokenType::Colon))
  415. return {};
  416. consume(TokenType::Colon);
  417. if (!match_statement())
  418. return {};
  419. m_state.labels_in_scope.set(identifier);
  420. auto statement = parse_statement();
  421. m_state.labels_in_scope.remove(identifier);
  422. statement->set_label(identifier);
  423. state_rollback_guard.disarm();
  424. discard_saved_state();
  425. return statement;
  426. }
  427. RefPtr<MetaProperty> Parser::try_parse_new_target_expression()
  428. {
  429. save_state();
  430. auto rule_start = push_start();
  431. ArmedScopeGuard state_rollback_guard = [&] {
  432. load_state();
  433. };
  434. consume(TokenType::New);
  435. if (!match(TokenType::Period))
  436. return {};
  437. consume();
  438. if (!match(TokenType::Identifier))
  439. return {};
  440. if (consume().value() != "target")
  441. return {};
  442. state_rollback_guard.disarm();
  443. discard_saved_state();
  444. return create_ast_node<MetaProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, MetaProperty::Type::NewTarget);
  445. }
  446. NonnullRefPtr<ClassDeclaration> Parser::parse_class_declaration()
  447. {
  448. auto rule_start = push_start();
  449. return create_ast_node<ClassDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() }, parse_class_expression(true));
  450. }
  451. NonnullRefPtr<ClassExpression> Parser::parse_class_expression(bool expect_class_name)
  452. {
  453. auto rule_start = push_start();
  454. // Classes are always in strict mode.
  455. TemporaryChange strict_mode_rollback(m_state.strict_mode, true);
  456. consume(TokenType::Class);
  457. NonnullRefPtrVector<ClassMethod> methods;
  458. RefPtr<Expression> super_class;
  459. RefPtr<FunctionExpression> constructor;
  460. String class_name = expect_class_name || match(TokenType::Identifier) ? consume(TokenType::Identifier).value().to_string() : "";
  461. if (match(TokenType::Extends)) {
  462. consume();
  463. auto [expression, should_continue_parsing] = parse_primary_expression();
  464. super_class = move(expression);
  465. (void)should_continue_parsing;
  466. }
  467. consume(TokenType::CurlyOpen);
  468. while (!done() && !match(TokenType::CurlyClose)) {
  469. RefPtr<Expression> property_key;
  470. bool is_static = false;
  471. bool is_constructor = false;
  472. bool is_generator = false;
  473. auto method_kind = ClassMethod::Kind::Method;
  474. if (match(TokenType::Semicolon)) {
  475. consume();
  476. continue;
  477. }
  478. if (match(TokenType::Asterisk)) {
  479. consume();
  480. is_generator = true;
  481. }
  482. if (match_property_key()) {
  483. StringView name;
  484. if (!is_generator && m_state.current_token.value() == "static"sv) {
  485. if (match(TokenType::Identifier)) {
  486. consume();
  487. is_static = true;
  488. if (match(TokenType::Asterisk)) {
  489. consume();
  490. is_generator = true;
  491. }
  492. }
  493. }
  494. if (match(TokenType::Identifier)) {
  495. auto identifier_name = m_state.current_token.value();
  496. if (identifier_name == "get") {
  497. method_kind = ClassMethod::Kind::Getter;
  498. consume();
  499. } else if (identifier_name == "set") {
  500. method_kind = ClassMethod::Kind::Setter;
  501. consume();
  502. }
  503. }
  504. if (match_property_key()) {
  505. switch (m_state.current_token.type()) {
  506. case TokenType::Identifier:
  507. name = consume().value();
  508. property_key = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, name);
  509. break;
  510. case TokenType::StringLiteral: {
  511. auto string_literal = parse_string_literal(consume());
  512. name = string_literal->value();
  513. property_key = move(string_literal);
  514. break;
  515. }
  516. default:
  517. property_key = parse_property_key();
  518. break;
  519. }
  520. } else {
  521. expected("property key");
  522. }
  523. // Constructor may be a StringLiteral or an Identifier.
  524. if (!is_static && name == "constructor") {
  525. if (method_kind != ClassMethod::Kind::Method)
  526. syntax_error("Class constructor may not be an accessor");
  527. if (!constructor.is_null())
  528. syntax_error("Classes may not have more than one constructor");
  529. if (is_generator)
  530. syntax_error("Class constructor may not be a generator");
  531. is_constructor = true;
  532. }
  533. }
  534. if (match(TokenType::ParenOpen)) {
  535. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  536. if (!super_class.is_null())
  537. parse_options |= FunctionNodeParseOptions::AllowSuperConstructorCall;
  538. if (method_kind == ClassMethod::Kind::Getter)
  539. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  540. if (method_kind == ClassMethod::Kind::Setter)
  541. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  542. if (is_generator)
  543. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  544. auto function = parse_function_node<FunctionExpression>(parse_options);
  545. if (is_constructor) {
  546. constructor = move(function);
  547. } else if (!property_key.is_null()) {
  548. methods.append(create_ast_node<ClassMethod>({ m_state.current_token.filename(), rule_start.position(), position() }, property_key.release_nonnull(), move(function), method_kind, is_static));
  549. } else {
  550. syntax_error("No key for class method");
  551. }
  552. } else {
  553. expected("ParenOpen");
  554. consume();
  555. }
  556. }
  557. consume(TokenType::CurlyClose);
  558. if (constructor.is_null()) {
  559. auto constructor_body = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  560. if (!super_class.is_null()) {
  561. // Set constructor to the result of parsing the source text
  562. // constructor(... args){ super (...args);}
  563. auto super_call = create_ast_node<SuperCall>(
  564. { m_state.current_token.filename(), rule_start.position(), position() },
  565. Vector { CallExpression::Argument { create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, "args"), true } });
  566. constructor_body->append(create_ast_node<ExpressionStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(super_call)));
  567. constructor_body->add_variables(m_state.var_scopes.last());
  568. constructor = create_ast_node<FunctionExpression>(
  569. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, move(constructor_body),
  570. Vector { FunctionNode::Parameter { FlyString { "args" }, nullptr, true } }, 0, FunctionKind::Regular, true);
  571. } else {
  572. constructor = create_ast_node<FunctionExpression>(
  573. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, move(constructor_body),
  574. Vector<FunctionNode::Parameter> {}, 0, FunctionKind::Regular, true);
  575. }
  576. }
  577. return create_ast_node<ClassExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(class_name), move(constructor), move(super_class), move(methods));
  578. }
  579. Parser::PrimaryExpressionParseResult Parser::parse_primary_expression()
  580. {
  581. auto rule_start = push_start();
  582. if (match_unary_prefixed_expression())
  583. return { parse_unary_prefixed_expression() };
  584. switch (m_state.current_token.type()) {
  585. case TokenType::ParenOpen: {
  586. auto paren_position = position();
  587. consume(TokenType::ParenOpen);
  588. if ((match(TokenType::ParenClose) || match(TokenType::Identifier) || match(TokenType::TripleDot) || match(TokenType::CurlyOpen) || match(TokenType::BracketOpen))
  589. && !try_parse_arrow_function_expression_failed_at_position(paren_position)) {
  590. auto arrow_function_result = try_parse_arrow_function_expression(true);
  591. if (!arrow_function_result.is_null())
  592. return { arrow_function_result.release_nonnull() };
  593. set_try_parse_arrow_function_expression_failed_at_position(paren_position, true);
  594. }
  595. auto expression = parse_expression(0);
  596. consume(TokenType::ParenClose);
  597. if (is<FunctionExpression>(*expression)) {
  598. static_cast<FunctionExpression&>(*expression).set_cannot_auto_rename();
  599. }
  600. return { move(expression) };
  601. }
  602. case TokenType::This:
  603. consume();
  604. return { create_ast_node<ThisExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  605. case TokenType::Class:
  606. return { parse_class_expression(false) };
  607. case TokenType::Super:
  608. consume();
  609. if (!m_state.allow_super_property_lookup)
  610. syntax_error("'super' keyword unexpected here");
  611. return { create_ast_node<SuperExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  612. case TokenType::Identifier: {
  613. read_as_identifier:;
  614. if (!try_parse_arrow_function_expression_failed_at_position(position())) {
  615. auto arrow_function_result = try_parse_arrow_function_expression(false);
  616. if (!arrow_function_result.is_null())
  617. return { arrow_function_result.release_nonnull() };
  618. set_try_parse_arrow_function_expression_failed_at_position(position(), true);
  619. }
  620. auto string = consume().value();
  621. return { create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, string) };
  622. }
  623. case TokenType::NumericLiteral:
  624. return { create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume_and_validate_numeric_literal().double_value()) };
  625. case TokenType::BigIntLiteral:
  626. return { create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()) };
  627. case TokenType::BoolLiteral:
  628. return { create_ast_node<BooleanLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().bool_value()) };
  629. case TokenType::StringLiteral:
  630. return { parse_string_literal(consume()) };
  631. case TokenType::NullLiteral:
  632. consume();
  633. return { create_ast_node<NullLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  634. case TokenType::CurlyOpen:
  635. return { parse_object_expression() };
  636. case TokenType::Function:
  637. return { parse_function_node<FunctionExpression>() };
  638. case TokenType::BracketOpen:
  639. return { parse_array_expression() };
  640. case TokenType::RegexLiteral:
  641. return { parse_regexp_literal() };
  642. case TokenType::TemplateLiteralStart:
  643. return { parse_template_literal(false) };
  644. case TokenType::New: {
  645. auto new_start = position();
  646. auto new_target_result = try_parse_new_target_expression();
  647. if (!new_target_result.is_null()) {
  648. if (!m_state.in_function_context)
  649. syntax_error("'new.target' not allowed outside of a function", new_start);
  650. return { new_target_result.release_nonnull() };
  651. }
  652. return { parse_new_expression() };
  653. }
  654. case TokenType::Yield:
  655. if (!m_state.in_generator_function_context)
  656. goto read_as_identifier;
  657. return { parse_yield_expression(), false };
  658. default:
  659. expected("primary expression");
  660. consume();
  661. return { create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  662. }
  663. }
  664. NonnullRefPtr<RegExpLiteral> Parser::parse_regexp_literal()
  665. {
  666. auto rule_start = push_start();
  667. auto pattern = consume().value();
  668. // Remove leading and trailing slash.
  669. pattern = pattern.substring_view(1, pattern.length() - 2);
  670. auto flags = String::empty();
  671. if (match(TokenType::RegexFlags)) {
  672. auto flags_start = position();
  673. flags = consume().value();
  674. HashTable<char> seen_flags;
  675. for (size_t i = 0; i < flags.length(); ++i) {
  676. auto flag = flags.substring_view(i, 1);
  677. if (!flag.is_one_of("g", "i", "m", "s", "u", "y"))
  678. syntax_error(String::formatted("Invalid RegExp flag '{}'", flag), Position { flags_start.line, flags_start.column + i });
  679. if (seen_flags.contains(*flag.characters_without_null_termination()))
  680. syntax_error(String::formatted("Repeated RegExp flag '{}'", flag), Position { flags_start.line, flags_start.column + i });
  681. seen_flags.set(*flag.characters_without_null_termination());
  682. }
  683. }
  684. return create_ast_node<RegExpLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, pattern, flags);
  685. }
  686. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  687. {
  688. auto rule_start = push_start();
  689. auto precedence = g_operator_precedence.get(m_state.current_token.type());
  690. auto associativity = operator_associativity(m_state.current_token.type());
  691. switch (m_state.current_token.type()) {
  692. case TokenType::PlusPlus: {
  693. consume();
  694. auto rhs_start = position();
  695. auto rhs = parse_expression(precedence, associativity);
  696. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  697. // other engines throw ReferenceError for ++foo()
  698. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  699. syntax_error(String::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  700. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(rhs), true);
  701. }
  702. case TokenType::MinusMinus: {
  703. consume();
  704. auto rhs_start = position();
  705. auto rhs = parse_expression(precedence, associativity);
  706. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  707. // other engines throw ReferenceError for --foo()
  708. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  709. syntax_error(String::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  710. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(rhs), true);
  711. }
  712. case TokenType::ExclamationMark:
  713. consume();
  714. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Not, parse_expression(precedence, associativity));
  715. case TokenType::Tilde:
  716. consume();
  717. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  718. case TokenType::Plus:
  719. consume();
  720. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Plus, parse_expression(precedence, associativity));
  721. case TokenType::Minus:
  722. consume();
  723. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Minus, parse_expression(precedence, associativity));
  724. case TokenType::Typeof:
  725. consume();
  726. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Typeof, parse_expression(precedence, associativity));
  727. case TokenType::Void:
  728. consume();
  729. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Void, parse_expression(precedence, associativity));
  730. case TokenType::Delete:
  731. consume();
  732. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Delete, parse_expression(precedence, associativity));
  733. default:
  734. expected("primary expression");
  735. consume();
  736. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  737. }
  738. }
  739. NonnullRefPtr<Expression> Parser::parse_property_key()
  740. {
  741. auto rule_start = push_start();
  742. if (match(TokenType::StringLiteral)) {
  743. return parse_string_literal(consume());
  744. } else if (match(TokenType::NumericLiteral)) {
  745. return create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().double_value());
  746. } else if (match(TokenType::BigIntLiteral)) {
  747. return create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  748. } else if (match(TokenType::BracketOpen)) {
  749. consume(TokenType::BracketOpen);
  750. auto result = parse_expression(2);
  751. consume(TokenType::BracketClose);
  752. return result;
  753. } else {
  754. if (!match_identifier_name())
  755. expected("IdentifierName");
  756. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  757. }
  758. }
  759. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  760. {
  761. auto rule_start = push_start();
  762. consume(TokenType::CurlyOpen);
  763. NonnullRefPtrVector<ObjectProperty> properties;
  764. ObjectProperty::Type property_type;
  765. auto skip_to_next_property = [&] {
  766. while (!done() && !match(TokenType::Comma) && !match(TokenType::CurlyOpen))
  767. consume();
  768. };
  769. while (!done() && !match(TokenType::CurlyClose)) {
  770. property_type = ObjectProperty::Type::KeyValue;
  771. RefPtr<Expression> property_name;
  772. RefPtr<Expression> property_value;
  773. FunctionKind function_kind { FunctionKind::Regular };
  774. if (match(TokenType::TripleDot)) {
  775. consume();
  776. property_name = parse_expression(4);
  777. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, nullptr, ObjectProperty::Type::Spread, false));
  778. if (!match(TokenType::Comma))
  779. break;
  780. consume(TokenType::Comma);
  781. continue;
  782. }
  783. if (match(TokenType::Asterisk)) {
  784. consume();
  785. property_type = ObjectProperty::Type::KeyValue;
  786. property_name = parse_property_key();
  787. function_kind = FunctionKind ::Generator;
  788. } else if (match(TokenType::Identifier)) {
  789. auto identifier = consume().value();
  790. if (identifier == "get" && match_property_key()) {
  791. property_type = ObjectProperty::Type::Getter;
  792. property_name = parse_property_key();
  793. } else if (identifier == "set" && match_property_key()) {
  794. property_type = ObjectProperty::Type::Setter;
  795. property_name = parse_property_key();
  796. } else {
  797. property_name = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier);
  798. property_value = create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier);
  799. }
  800. } else {
  801. property_name = parse_property_key();
  802. }
  803. if (property_type == ObjectProperty::Type::Getter || property_type == ObjectProperty::Type::Setter) {
  804. if (!match(TokenType::ParenOpen)) {
  805. syntax_error("Expected '(' for object getter or setter property");
  806. skip_to_next_property();
  807. continue;
  808. }
  809. }
  810. if (match(TokenType::ParenOpen)) {
  811. VERIFY(property_name);
  812. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  813. if (property_type == ObjectProperty::Type::Getter)
  814. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  815. if (property_type == ObjectProperty::Type::Setter)
  816. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  817. if (function_kind == FunctionKind::Generator)
  818. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  819. auto function = parse_function_node<FunctionExpression>(parse_options);
  820. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, function, property_type, true));
  821. } else if (match(TokenType::Colon)) {
  822. if (!property_name) {
  823. syntax_error("Expected a property name");
  824. skip_to_next_property();
  825. continue;
  826. }
  827. consume();
  828. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, parse_expression(2), property_type, false));
  829. } else if (property_name && property_value) {
  830. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, *property_value, property_type, false));
  831. } else {
  832. syntax_error("Expected a property");
  833. skip_to_next_property();
  834. continue;
  835. }
  836. if (!match(TokenType::Comma))
  837. break;
  838. consume(TokenType::Comma);
  839. }
  840. consume(TokenType::CurlyClose);
  841. return create_ast_node<ObjectExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, properties);
  842. }
  843. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  844. {
  845. auto rule_start = push_start();
  846. consume(TokenType::BracketOpen);
  847. Vector<RefPtr<Expression>> elements;
  848. while (match_expression() || match(TokenType::TripleDot) || match(TokenType::Comma)) {
  849. RefPtr<Expression> expression;
  850. if (match(TokenType::TripleDot)) {
  851. consume(TokenType::TripleDot);
  852. expression = create_ast_node<SpreadExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, parse_expression(2));
  853. } else if (match_expression()) {
  854. expression = parse_expression(2);
  855. }
  856. elements.append(expression);
  857. if (!match(TokenType::Comma))
  858. break;
  859. consume(TokenType::Comma);
  860. }
  861. consume(TokenType::BracketClose);
  862. return create_ast_node<ArrayExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(elements));
  863. }
  864. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(const Token& token, bool in_template_literal)
  865. {
  866. auto rule_start = push_start();
  867. auto status = Token::StringValueStatus::Ok;
  868. auto string = token.string_value(status);
  869. if (status != Token::StringValueStatus::Ok) {
  870. String message;
  871. if (status == Token::StringValueStatus::LegacyOctalEscapeSequence) {
  872. m_state.string_legacy_octal_escape_sequence_in_scope = true;
  873. if (in_template_literal)
  874. message = "Octal escape sequence not allowed in template literal";
  875. else if (m_state.strict_mode)
  876. message = "Octal escape sequence in string literal not allowed in strict mode";
  877. } else if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) {
  878. auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal";
  879. message = String::formatted("Malformed {} escape sequence", type);
  880. } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) {
  881. message = "Unicode code_point must not be greater than 0x10ffff in escape sequence";
  882. } else {
  883. VERIFY_NOT_REACHED();
  884. }
  885. if (!message.is_empty())
  886. syntax_error(message, Position { token.line_number(), token.line_column() });
  887. }
  888. auto is_use_strict_directive = !in_template_literal && (token.value() == "'use strict'" || token.value() == "\"use strict\"");
  889. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, string, is_use_strict_directive);
  890. }
  891. NonnullRefPtr<TemplateLiteral> Parser::parse_template_literal(bool is_tagged)
  892. {
  893. auto rule_start = push_start();
  894. consume(TokenType::TemplateLiteralStart);
  895. NonnullRefPtrVector<Expression> expressions;
  896. NonnullRefPtrVector<Expression> raw_strings;
  897. auto append_empty_string = [this, &rule_start, &expressions, &raw_strings, is_tagged]() {
  898. auto string_literal = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, "");
  899. expressions.append(string_literal);
  900. if (is_tagged)
  901. raw_strings.append(string_literal);
  902. };
  903. if (!match(TokenType::TemplateLiteralString))
  904. append_empty_string();
  905. while (!done() && !match(TokenType::TemplateLiteralEnd) && !match(TokenType::UnterminatedTemplateLiteral)) {
  906. if (match(TokenType::TemplateLiteralString)) {
  907. auto token = consume();
  908. expressions.append(parse_string_literal(token, true));
  909. if (is_tagged)
  910. raw_strings.append(create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, token.value()));
  911. } else if (match(TokenType::TemplateLiteralExprStart)) {
  912. consume(TokenType::TemplateLiteralExprStart);
  913. if (match(TokenType::TemplateLiteralExprEnd)) {
  914. syntax_error("Empty template literal expression block");
  915. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  916. }
  917. expressions.append(parse_expression(0));
  918. if (match(TokenType::UnterminatedTemplateLiteral)) {
  919. syntax_error("Unterminated template literal");
  920. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  921. }
  922. consume(TokenType::TemplateLiteralExprEnd);
  923. if (!match(TokenType::TemplateLiteralString))
  924. append_empty_string();
  925. } else {
  926. expected("Template literal string or expression");
  927. break;
  928. }
  929. }
  930. if (match(TokenType::UnterminatedTemplateLiteral)) {
  931. syntax_error("Unterminated template literal");
  932. } else {
  933. consume(TokenType::TemplateLiteralEnd);
  934. }
  935. if (is_tagged)
  936. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions, raw_strings);
  937. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  938. }
  939. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity, const Vector<TokenType>& forbidden)
  940. {
  941. auto rule_start = push_start();
  942. auto [expression, should_continue_parsing] = parse_primary_expression();
  943. while (match(TokenType::TemplateLiteralStart)) {
  944. auto template_literal = parse_template_literal(true);
  945. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  946. }
  947. if (should_continue_parsing) {
  948. while (match_secondary_expression(forbidden)) {
  949. int new_precedence = g_operator_precedence.get(m_state.current_token.type());
  950. if (new_precedence < min_precedence)
  951. break;
  952. if (new_precedence == min_precedence && associativity == Associativity::Left)
  953. break;
  954. Associativity new_associativity = operator_associativity(m_state.current_token.type());
  955. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  956. while (match(TokenType::TemplateLiteralStart)) {
  957. auto template_literal = parse_template_literal(true);
  958. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  959. }
  960. }
  961. }
  962. if (match(TokenType::Comma) && min_precedence <= 1) {
  963. NonnullRefPtrVector<Expression> expressions;
  964. expressions.append(expression);
  965. while (match(TokenType::Comma)) {
  966. consume();
  967. expressions.append(parse_expression(2));
  968. }
  969. expression = create_ast_node<SequenceExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expressions));
  970. }
  971. return expression;
  972. }
  973. NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  974. {
  975. auto rule_start = push_start();
  976. switch (m_state.current_token.type()) {
  977. case TokenType::Plus:
  978. consume();
  979. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity));
  980. case TokenType::PlusEquals:
  981. return parse_assignment_expression(AssignmentOp::AdditionAssignment, move(lhs), min_precedence, associativity);
  982. case TokenType::Minus:
  983. consume();
  984. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity));
  985. case TokenType::MinusEquals:
  986. return parse_assignment_expression(AssignmentOp::SubtractionAssignment, move(lhs), min_precedence, associativity);
  987. case TokenType::Asterisk:
  988. consume();
  989. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity));
  990. case TokenType::AsteriskEquals:
  991. return parse_assignment_expression(AssignmentOp::MultiplicationAssignment, move(lhs), min_precedence, associativity);
  992. case TokenType::Slash:
  993. consume();
  994. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity));
  995. case TokenType::SlashEquals:
  996. return parse_assignment_expression(AssignmentOp::DivisionAssignment, move(lhs), min_precedence, associativity);
  997. case TokenType::Percent:
  998. consume();
  999. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity));
  1000. case TokenType::PercentEquals:
  1001. return parse_assignment_expression(AssignmentOp::ModuloAssignment, move(lhs), min_precedence, associativity);
  1002. case TokenType::DoubleAsterisk:
  1003. consume();
  1004. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity));
  1005. case TokenType::DoubleAsteriskEquals:
  1006. return parse_assignment_expression(AssignmentOp::ExponentiationAssignment, move(lhs), min_precedence, associativity);
  1007. case TokenType::GreaterThan:
  1008. consume();
  1009. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  1010. case TokenType::GreaterThanEquals:
  1011. consume();
  1012. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  1013. case TokenType::LessThan:
  1014. consume();
  1015. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  1016. case TokenType::LessThanEquals:
  1017. consume();
  1018. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  1019. case TokenType::EqualsEqualsEquals:
  1020. consume();
  1021. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::TypedEquals, move(lhs), parse_expression(min_precedence, associativity));
  1022. case TokenType::ExclamationMarkEqualsEquals:
  1023. consume();
  1024. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::TypedInequals, move(lhs), parse_expression(min_precedence, associativity));
  1025. case TokenType::EqualsEquals:
  1026. consume();
  1027. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::AbstractEquals, move(lhs), parse_expression(min_precedence, associativity));
  1028. case TokenType::ExclamationMarkEquals:
  1029. consume();
  1030. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::AbstractInequals, move(lhs), parse_expression(min_precedence, associativity));
  1031. case TokenType::In:
  1032. consume();
  1033. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::In, move(lhs), parse_expression(min_precedence, associativity));
  1034. case TokenType::Instanceof:
  1035. consume();
  1036. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity));
  1037. case TokenType::Ampersand:
  1038. consume();
  1039. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity));
  1040. case TokenType::AmpersandEquals:
  1041. return parse_assignment_expression(AssignmentOp::BitwiseAndAssignment, move(lhs), min_precedence, associativity);
  1042. case TokenType::Pipe:
  1043. consume();
  1044. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity));
  1045. case TokenType::PipeEquals:
  1046. return parse_assignment_expression(AssignmentOp::BitwiseOrAssignment, move(lhs), min_precedence, associativity);
  1047. case TokenType::Caret:
  1048. consume();
  1049. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity));
  1050. case TokenType::CaretEquals:
  1051. return parse_assignment_expression(AssignmentOp::BitwiseXorAssignment, move(lhs), min_precedence, associativity);
  1052. case TokenType::ShiftLeft:
  1053. consume();
  1054. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LeftShift, move(lhs), parse_expression(min_precedence, associativity));
  1055. case TokenType::ShiftLeftEquals:
  1056. return parse_assignment_expression(AssignmentOp::LeftShiftAssignment, move(lhs), min_precedence, associativity);
  1057. case TokenType::ShiftRight:
  1058. consume();
  1059. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::RightShift, move(lhs), parse_expression(min_precedence, associativity));
  1060. case TokenType::ShiftRightEquals:
  1061. return parse_assignment_expression(AssignmentOp::RightShiftAssignment, move(lhs), min_precedence, associativity);
  1062. case TokenType::UnsignedShiftRight:
  1063. consume();
  1064. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::UnsignedRightShift, move(lhs), parse_expression(min_precedence, associativity));
  1065. case TokenType::UnsignedShiftRightEquals:
  1066. return parse_assignment_expression(AssignmentOp::UnsignedRightShiftAssignment, move(lhs), min_precedence, associativity);
  1067. case TokenType::ParenOpen:
  1068. return parse_call_expression(move(lhs));
  1069. case TokenType::Equals:
  1070. return parse_assignment_expression(AssignmentOp::Assignment, move(lhs), min_precedence, associativity);
  1071. case TokenType::Period:
  1072. consume();
  1073. if (!match_identifier_name())
  1074. expected("IdentifierName");
  1075. return create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()));
  1076. case TokenType::BracketOpen: {
  1077. consume(TokenType::BracketOpen);
  1078. auto expression = create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), parse_expression(0), true);
  1079. consume(TokenType::BracketClose);
  1080. return expression;
  1081. }
  1082. case TokenType::PlusPlus:
  1083. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1084. // other engines throw ReferenceError for foo()++
  1085. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1086. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1087. consume();
  1088. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(lhs));
  1089. case TokenType::MinusMinus:
  1090. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1091. // other engines throw ReferenceError for foo()--
  1092. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1093. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1094. consume();
  1095. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(lhs));
  1096. case TokenType::DoubleAmpersand:
  1097. consume();
  1098. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity));
  1099. case TokenType::DoubleAmpersandEquals:
  1100. return parse_assignment_expression(AssignmentOp::AndAssignment, move(lhs), min_precedence, associativity);
  1101. case TokenType::DoublePipe:
  1102. consume();
  1103. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity));
  1104. case TokenType::DoublePipeEquals:
  1105. return parse_assignment_expression(AssignmentOp::OrAssignment, move(lhs), min_precedence, associativity);
  1106. case TokenType::DoubleQuestionMark:
  1107. consume();
  1108. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::NullishCoalescing, move(lhs), parse_expression(min_precedence, associativity));
  1109. case TokenType::DoubleQuestionMarkEquals:
  1110. return parse_assignment_expression(AssignmentOp::NullishAssignment, move(lhs), min_precedence, associativity);
  1111. case TokenType::QuestionMark:
  1112. return parse_conditional_expression(move(lhs));
  1113. default:
  1114. expected("secondary expression");
  1115. consume();
  1116. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  1117. }
  1118. }
  1119. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(AssignmentOp assignment_op, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  1120. {
  1121. auto rule_start = push_start();
  1122. VERIFY(match(TokenType::Equals)
  1123. || match(TokenType::PlusEquals)
  1124. || match(TokenType::MinusEquals)
  1125. || match(TokenType::AsteriskEquals)
  1126. || match(TokenType::SlashEquals)
  1127. || match(TokenType::PercentEquals)
  1128. || match(TokenType::DoubleAsteriskEquals)
  1129. || match(TokenType::AmpersandEquals)
  1130. || match(TokenType::PipeEquals)
  1131. || match(TokenType::CaretEquals)
  1132. || match(TokenType::ShiftLeftEquals)
  1133. || match(TokenType::ShiftRightEquals)
  1134. || match(TokenType::UnsignedShiftRightEquals)
  1135. || match(TokenType::DoubleAmpersandEquals)
  1136. || match(TokenType::DoublePipeEquals)
  1137. || match(TokenType::DoubleQuestionMarkEquals));
  1138. consume();
  1139. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs) && !is<CallExpression>(*lhs)) {
  1140. syntax_error("Invalid left-hand side in assignment");
  1141. } else if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1142. auto name = static_cast<const Identifier&>(*lhs).string();
  1143. if (name == "eval" || name == "arguments")
  1144. syntax_error(String::formatted("'{}' cannot be assigned to in strict mode code", name));
  1145. } else if (m_state.strict_mode && is<CallExpression>(*lhs)) {
  1146. syntax_error("Cannot assign to function call");
  1147. }
  1148. auto rhs = parse_expression(min_precedence, associativity);
  1149. if (assignment_op == AssignmentOp::Assignment && is<FunctionExpression>(*rhs)) {
  1150. auto ident = lhs;
  1151. if (is<MemberExpression>(*lhs)) {
  1152. ident = static_cast<MemberExpression&>(*lhs).property();
  1153. }
  1154. if (is<Identifier>(*ident))
  1155. static_cast<FunctionExpression&>(*rhs).set_name_if_possible(static_cast<Identifier&>(*ident).string());
  1156. }
  1157. return create_ast_node<AssignmentExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, assignment_op, move(lhs), move(rhs));
  1158. }
  1159. NonnullRefPtr<Identifier> Parser::parse_identifier()
  1160. {
  1161. auto identifier_start = position();
  1162. auto token = consume(TokenType::Identifier);
  1163. return create_ast_node<Identifier>(
  1164. { m_state.current_token.filename(), identifier_start, position() },
  1165. token.value());
  1166. }
  1167. NonnullRefPtr<CallExpression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  1168. {
  1169. auto rule_start = push_start();
  1170. if (!m_state.allow_super_constructor_call && is<SuperExpression>(*lhs))
  1171. syntax_error("'super' keyword unexpected here");
  1172. consume(TokenType::ParenOpen);
  1173. Vector<CallExpression::Argument> arguments;
  1174. while (match_expression() || match(TokenType::TripleDot)) {
  1175. if (match(TokenType::TripleDot)) {
  1176. consume();
  1177. arguments.append({ parse_expression(2), true });
  1178. } else {
  1179. arguments.append({ parse_expression(2), false });
  1180. }
  1181. if (!match(TokenType::Comma))
  1182. break;
  1183. consume();
  1184. }
  1185. consume(TokenType::ParenClose);
  1186. if (is<SuperExpression>(*lhs))
  1187. return create_ast_node<SuperCall>({ m_state.current_token.filename(), rule_start.position(), position() }, move(arguments));
  1188. return create_ast_node<CallExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), move(arguments));
  1189. }
  1190. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  1191. {
  1192. auto rule_start = push_start();
  1193. consume(TokenType::New);
  1194. auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen });
  1195. Vector<CallExpression::Argument> arguments;
  1196. if (match(TokenType::ParenOpen)) {
  1197. consume(TokenType::ParenOpen);
  1198. while (match_expression() || match(TokenType::TripleDot)) {
  1199. if (match(TokenType::TripleDot)) {
  1200. consume();
  1201. arguments.append({ parse_expression(2), true });
  1202. } else {
  1203. arguments.append({ parse_expression(2), false });
  1204. }
  1205. if (!match(TokenType::Comma))
  1206. break;
  1207. consume();
  1208. }
  1209. consume(TokenType::ParenClose);
  1210. }
  1211. return create_ast_node<NewExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(callee), move(arguments));
  1212. }
  1213. NonnullRefPtr<YieldExpression> Parser::parse_yield_expression()
  1214. {
  1215. auto rule_start = push_start();
  1216. consume(TokenType::Yield);
  1217. RefPtr<Expression> argument;
  1218. bool yield_from = false;
  1219. if (!m_state.current_token.trivia_contains_line_terminator()) {
  1220. if (match(TokenType::Asterisk)) {
  1221. consume();
  1222. yield_from = true;
  1223. }
  1224. if (yield_from || match_expression())
  1225. argument = parse_expression(0);
  1226. }
  1227. return create_ast_node<YieldExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument), yield_from);
  1228. }
  1229. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  1230. {
  1231. auto rule_start = push_start();
  1232. if (!m_state.in_function_context && !m_state.in_arrow_function_context)
  1233. syntax_error("'return' not allowed outside of a function");
  1234. consume(TokenType::Return);
  1235. // Automatic semicolon insertion: terminate statement when return is followed by newline
  1236. if (m_state.current_token.trivia_contains_line_terminator())
  1237. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  1238. if (match_expression()) {
  1239. auto expression = parse_expression(0);
  1240. consume_or_insert_semicolon();
  1241. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  1242. }
  1243. consume_or_insert_semicolon();
  1244. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  1245. }
  1246. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  1247. {
  1248. auto rule_start = push_start();
  1249. bool dummy = false;
  1250. return parse_block_statement(dummy);
  1251. }
  1252. NonnullRefPtr<BlockStatement> Parser::parse_block_statement(bool& is_strict)
  1253. {
  1254. auto rule_start = push_start();
  1255. ScopePusher scope(*this, ScopePusher::Let, Parser::Scope::Block);
  1256. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  1257. consume(TokenType::CurlyOpen);
  1258. bool first = true;
  1259. bool initial_strict_mode_state = m_state.strict_mode;
  1260. if (initial_strict_mode_state)
  1261. is_strict = true;
  1262. while (!done() && !match(TokenType::CurlyClose)) {
  1263. if (match_declaration()) {
  1264. block->append(parse_declaration());
  1265. } else if (match_statement()) {
  1266. auto statement = parse_statement();
  1267. block->append(statement);
  1268. if (statement_is_use_strict_directive(statement)) {
  1269. if (first && !initial_strict_mode_state) {
  1270. is_strict = true;
  1271. m_state.strict_mode = true;
  1272. }
  1273. if (m_state.string_legacy_octal_escape_sequence_in_scope)
  1274. syntax_error("Octal escape sequence in string literal not allowed in strict mode");
  1275. }
  1276. } else {
  1277. expected("statement or declaration");
  1278. consume();
  1279. }
  1280. first = false;
  1281. }
  1282. m_state.strict_mode = initial_strict_mode_state;
  1283. m_state.string_legacy_octal_escape_sequence_in_scope = false;
  1284. consume(TokenType::CurlyClose);
  1285. scope.add_to_scope_node(block);
  1286. return block;
  1287. }
  1288. template<typename FunctionNodeType>
  1289. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(u8 parse_options)
  1290. {
  1291. auto rule_start = push_start();
  1292. VERIFY(!(parse_options & FunctionNodeParseOptions::IsGetterFunction && parse_options & FunctionNodeParseOptions::IsSetterFunction));
  1293. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, !!(parse_options & FunctionNodeParseOptions::AllowSuperPropertyLookup));
  1294. TemporaryChange super_constructor_call_rollback(m_state.allow_super_constructor_call, !!(parse_options & FunctionNodeParseOptions::AllowSuperConstructorCall));
  1295. ScopePusher scope(*this, ScopePusher::Var, Parser::Scope::Function);
  1296. constexpr auto is_function_expression = IsSame<FunctionNodeType, FunctionExpression>;
  1297. auto is_generator = (parse_options & FunctionNodeParseOptions::IsGeneratorFunction) != 0;
  1298. String name;
  1299. if (parse_options & FunctionNodeParseOptions::CheckForFunctionAndName) {
  1300. consume(TokenType::Function);
  1301. if (!is_generator) {
  1302. is_generator = match(TokenType::Asterisk);
  1303. if (is_generator) {
  1304. consume(TokenType::Asterisk);
  1305. parse_options = parse_options | FunctionNodeParseOptions::IsGeneratorFunction;
  1306. }
  1307. }
  1308. if (FunctionNodeType::must_have_name() || match(TokenType::Identifier))
  1309. name = consume(TokenType::Identifier).value();
  1310. else if (is_function_expression && (match(TokenType::Yield) || match(TokenType::Await)))
  1311. name = consume().value();
  1312. }
  1313. consume(TokenType::ParenOpen);
  1314. i32 function_length = -1;
  1315. auto parameters = parse_formal_parameters(function_length, parse_options);
  1316. consume(TokenType::ParenClose);
  1317. if (function_length == -1)
  1318. function_length = parameters.size();
  1319. TemporaryChange change(m_state.in_function_context, true);
  1320. TemporaryChange generator_change(m_state.in_generator_function_context, m_state.in_generator_function_context || is_generator);
  1321. auto old_labels_in_scope = move(m_state.labels_in_scope);
  1322. ScopeGuard guard([&]() {
  1323. m_state.labels_in_scope = move(old_labels_in_scope);
  1324. });
  1325. m_state.function_parameters.append(parameters);
  1326. bool is_strict = false;
  1327. auto body = parse_block_statement(is_strict);
  1328. m_state.function_parameters.take_last();
  1329. scope.add_to_scope_node(body);
  1330. return create_ast_node<FunctionNodeType>(
  1331. { m_state.current_token.filename(), rule_start.position(), position() },
  1332. name, move(body), move(parameters), function_length,
  1333. is_generator ? FunctionKind::Generator : FunctionKind::Regular, is_strict);
  1334. }
  1335. Vector<FunctionNode::Parameter> Parser::parse_formal_parameters(int& function_length, u8 parse_options)
  1336. {
  1337. auto rule_start = push_start();
  1338. bool has_default_parameter = false;
  1339. bool has_rest_parameter = false;
  1340. Vector<FunctionNode::Parameter> parameters;
  1341. auto consume_identifier_or_binding_pattern = [&]() -> Variant<FlyString, NonnullRefPtr<BindingPattern>> {
  1342. if (auto pattern = parse_binding_pattern())
  1343. return pattern.release_nonnull();
  1344. auto token = consume(TokenType::Identifier);
  1345. auto parameter_name = token.value();
  1346. for (auto& parameter : parameters) {
  1347. if (auto* ptr = parameter.binding.get_pointer<FlyString>(); !ptr || parameter_name != *ptr)
  1348. continue;
  1349. String message;
  1350. if (parse_options & FunctionNodeParseOptions::IsArrowFunction)
  1351. message = String::formatted("Duplicate parameter '{}' not allowed in arrow function", parameter_name);
  1352. else if (m_state.strict_mode)
  1353. message = String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name);
  1354. else if (has_default_parameter || match(TokenType::Equals))
  1355. message = String::formatted("Duplicate parameter '{}' not allowed in function with default parameter", parameter_name);
  1356. else if (has_rest_parameter)
  1357. message = String::formatted("Duplicate parameter '{}' not allowed in function with rest parameter", parameter_name);
  1358. if (!message.is_empty())
  1359. syntax_error(message, Position { token.line_number(), token.line_column() });
  1360. break;
  1361. }
  1362. return FlyString { token.value() };
  1363. };
  1364. while (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen) || match(TokenType::Identifier) || match(TokenType::TripleDot)) {
  1365. if (parse_options & FunctionNodeParseOptions::IsGetterFunction)
  1366. syntax_error("Getter function must have no arguments");
  1367. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && (parameters.size() >= 1 || match(TokenType::TripleDot)))
  1368. syntax_error("Setter function must have one argument");
  1369. auto is_rest = false;
  1370. if (match(TokenType::TripleDot)) {
  1371. consume();
  1372. has_rest_parameter = true;
  1373. function_length = parameters.size();
  1374. is_rest = true;
  1375. }
  1376. auto parameter = consume_identifier_or_binding_pattern();
  1377. RefPtr<Expression> default_value;
  1378. if (match(TokenType::Equals)) {
  1379. consume();
  1380. has_default_parameter = true;
  1381. function_length = parameters.size();
  1382. default_value = parse_expression(2);
  1383. bool is_generator = parse_options & FunctionNodeParseOptions::IsGeneratorFunction;
  1384. if (is_generator && default_value && default_value->fast_is<Identifier>() && static_cast<Identifier&>(*default_value).string() == "yield"sv)
  1385. syntax_error("Generator function parameter initializer cannot contain a reference to an identifier named \"yield\"");
  1386. }
  1387. parameters.append({ move(parameter), default_value, is_rest });
  1388. if (match(TokenType::ParenClose))
  1389. break;
  1390. consume(TokenType::Comma);
  1391. if (is_rest)
  1392. break;
  1393. }
  1394. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && parameters.is_empty())
  1395. syntax_error("Setter function must have one argument");
  1396. return parameters;
  1397. }
  1398. RefPtr<BindingPattern> Parser::parse_binding_pattern()
  1399. {
  1400. auto rule_start = push_start();
  1401. TokenType closing_token;
  1402. bool is_object = true;
  1403. if (match(TokenType::BracketOpen)) {
  1404. consume();
  1405. closing_token = TokenType::BracketClose;
  1406. is_object = false;
  1407. } else if (match(TokenType::CurlyOpen)) {
  1408. consume();
  1409. closing_token = TokenType::CurlyClose;
  1410. } else {
  1411. return {};
  1412. }
  1413. Vector<BindingPattern::BindingEntry> entries;
  1414. while (!match(closing_token)) {
  1415. if (!is_object && match(TokenType::Comma)) {
  1416. consume();
  1417. entries.append(BindingPattern::BindingEntry {});
  1418. continue;
  1419. }
  1420. auto is_rest = false;
  1421. if (match(TokenType::TripleDot)) {
  1422. consume();
  1423. is_rest = true;
  1424. }
  1425. decltype(BindingPattern::BindingEntry::name) name = Empty {};
  1426. decltype(BindingPattern::BindingEntry::alias) alias = Empty {};
  1427. RefPtr<Expression> initializer = {};
  1428. if (is_object) {
  1429. if (match(TokenType::Identifier)) {
  1430. name = parse_identifier();
  1431. } else if (match(TokenType::BracketOpen)) {
  1432. consume();
  1433. name = parse_expression(0);
  1434. consume(TokenType::BracketOpen);
  1435. } else {
  1436. syntax_error("Expected identifier or computed property name");
  1437. return {};
  1438. }
  1439. if (!is_rest && match(TokenType::Colon)) {
  1440. consume();
  1441. if (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen)) {
  1442. auto binding_pattern = parse_binding_pattern();
  1443. if (!binding_pattern)
  1444. return {};
  1445. alias = binding_pattern.release_nonnull();
  1446. } else if (match_identifier_name()) {
  1447. alias = parse_identifier();
  1448. } else {
  1449. syntax_error("Expected identifier or binding pattern");
  1450. return {};
  1451. }
  1452. }
  1453. } else {
  1454. if (match(TokenType::Identifier)) {
  1455. // BindingElement must always have an Empty name field
  1456. alias = parse_identifier();
  1457. } else if (match(TokenType::BracketOpen) || match(TokenType::CurlyOpen)) {
  1458. auto pattern = parse_binding_pattern();
  1459. if (!pattern) {
  1460. syntax_error("Expected binding pattern");
  1461. return {};
  1462. }
  1463. alias = pattern.release_nonnull();
  1464. } else {
  1465. syntax_error("Expected identifier or binding pattern");
  1466. return {};
  1467. }
  1468. }
  1469. if (match(TokenType::Equals)) {
  1470. if (is_rest) {
  1471. syntax_error("Unexpected initializer after rest element");
  1472. return {};
  1473. }
  1474. consume();
  1475. initializer = parse_expression(2);
  1476. if (!initializer) {
  1477. syntax_error("Expected initialization expression");
  1478. return {};
  1479. }
  1480. }
  1481. entries.append(BindingPattern::BindingEntry { move(name), move(alias), move(initializer), is_rest });
  1482. if (match(TokenType::Comma)) {
  1483. if (is_rest) {
  1484. syntax_error("Rest element may not be followed by a comma");
  1485. return {};
  1486. }
  1487. consume();
  1488. }
  1489. }
  1490. while (!is_object && match(TokenType::Comma))
  1491. consume();
  1492. consume(closing_token);
  1493. auto kind = is_object ? BindingPattern::Kind::Object : BindingPattern::Kind::Array;
  1494. auto pattern = adopt_ref(*new BindingPattern);
  1495. pattern->entries = move(entries);
  1496. pattern->kind = kind;
  1497. return pattern;
  1498. }
  1499. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool for_loop_variable_declaration)
  1500. {
  1501. auto rule_start = push_start();
  1502. DeclarationKind declaration_kind;
  1503. switch (m_state.current_token.type()) {
  1504. case TokenType::Var:
  1505. declaration_kind = DeclarationKind::Var;
  1506. break;
  1507. case TokenType::Let:
  1508. declaration_kind = DeclarationKind::Let;
  1509. break;
  1510. case TokenType::Const:
  1511. declaration_kind = DeclarationKind::Const;
  1512. break;
  1513. default:
  1514. VERIFY_NOT_REACHED();
  1515. }
  1516. consume();
  1517. NonnullRefPtrVector<VariableDeclarator> declarations;
  1518. for (;;) {
  1519. Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>, Empty> target { Empty() };
  1520. if (match(TokenType::Identifier)) {
  1521. target = create_ast_node<Identifier>(
  1522. { m_state.current_token.filename(), rule_start.position(), position() },
  1523. consume(TokenType::Identifier).value());
  1524. } else if (auto pattern = parse_binding_pattern()) {
  1525. target = pattern.release_nonnull();
  1526. } else if (!m_state.in_generator_function_context && match(TokenType::Yield)) {
  1527. target = create_ast_node<Identifier>(
  1528. { m_state.current_token.filename(), rule_start.position(), position() },
  1529. consume().value());
  1530. }
  1531. if (target.has<Empty>()) {
  1532. syntax_error("Expected an identifier or a binding pattern");
  1533. if (match(TokenType::Comma)) {
  1534. consume();
  1535. continue;
  1536. }
  1537. break;
  1538. }
  1539. RefPtr<Expression> init;
  1540. if (match(TokenType::Equals)) {
  1541. consume();
  1542. init = parse_expression(2);
  1543. } else if (!for_loop_variable_declaration && declaration_kind == DeclarationKind::Const) {
  1544. syntax_error("Missing initializer in 'const' variable declaration");
  1545. } else if (!for_loop_variable_declaration && target.has<NonnullRefPtr<BindingPattern>>()) {
  1546. syntax_error("Missing initializer in destructuring assignment");
  1547. }
  1548. if (init && is<FunctionExpression>(*init) && target.has<NonnullRefPtr<Identifier>>()) {
  1549. static_cast<FunctionExpression&>(*init).set_name_if_possible(target.get<NonnullRefPtr<Identifier>>()->string());
  1550. }
  1551. declarations.append(create_ast_node<VariableDeclarator>(
  1552. { m_state.current_token.filename(), rule_start.position(), position() },
  1553. move(target).downcast<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>(),
  1554. move(init)));
  1555. if (match(TokenType::Comma)) {
  1556. consume();
  1557. continue;
  1558. }
  1559. break;
  1560. }
  1561. if (!for_loop_variable_declaration)
  1562. consume_or_insert_semicolon();
  1563. auto declaration = create_ast_node<VariableDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() }, declaration_kind, move(declarations));
  1564. if (declaration_kind == DeclarationKind::Var)
  1565. m_state.var_scopes.last().append(declaration);
  1566. else
  1567. m_state.let_scopes.last().append(declaration);
  1568. return declaration;
  1569. }
  1570. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  1571. {
  1572. auto rule_start = push_start();
  1573. consume(TokenType::Throw);
  1574. // Automatic semicolon insertion: terminate statement when throw is followed by newline
  1575. if (m_state.current_token.trivia_contains_line_terminator()) {
  1576. syntax_error("No line break is allowed between 'throw' and its expression");
  1577. return create_ast_node<ThrowStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }));
  1578. }
  1579. auto expression = parse_expression(0);
  1580. consume_or_insert_semicolon();
  1581. return create_ast_node<ThrowStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  1582. }
  1583. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  1584. {
  1585. auto rule_start = push_start();
  1586. consume(TokenType::Break);
  1587. FlyString target_label;
  1588. if (match(TokenType::Semicolon)) {
  1589. consume();
  1590. } else {
  1591. if (match(TokenType::Identifier) && !m_state.current_token.trivia_contains_line_terminator()) {
  1592. target_label = consume().value();
  1593. if (!m_state.labels_in_scope.contains(target_label))
  1594. syntax_error(String::formatted("Label '{}' not found", target_label));
  1595. }
  1596. consume_or_insert_semicolon();
  1597. }
  1598. if (target_label.is_null() && !m_state.in_break_context)
  1599. syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement");
  1600. return create_ast_node<BreakStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  1601. }
  1602. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  1603. {
  1604. auto rule_start = push_start();
  1605. if (!m_state.in_continue_context)
  1606. syntax_error("'continue' not allow outside of a loop");
  1607. consume(TokenType::Continue);
  1608. FlyString target_label;
  1609. if (match(TokenType::Semicolon)) {
  1610. consume();
  1611. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  1612. }
  1613. if (match(TokenType::Identifier) && !m_state.current_token.trivia_contains_line_terminator()) {
  1614. target_label = consume().value();
  1615. if (!m_state.labels_in_scope.contains(target_label))
  1616. syntax_error(String::formatted("Label '{}' not found", target_label));
  1617. }
  1618. consume_or_insert_semicolon();
  1619. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  1620. }
  1621. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test)
  1622. {
  1623. auto rule_start = push_start();
  1624. consume(TokenType::QuestionMark);
  1625. auto consequent = parse_expression(2);
  1626. consume(TokenType::Colon);
  1627. auto alternate = parse_expression(2);
  1628. return create_ast_node<ConditionalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(consequent), move(alternate));
  1629. }
  1630. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  1631. {
  1632. auto rule_start = push_start();
  1633. consume(TokenType::Try);
  1634. auto block = parse_block_statement();
  1635. RefPtr<CatchClause> handler;
  1636. if (match(TokenType::Catch))
  1637. handler = parse_catch_clause();
  1638. RefPtr<BlockStatement> finalizer;
  1639. if (match(TokenType::Finally)) {
  1640. consume();
  1641. finalizer = parse_block_statement();
  1642. }
  1643. if (!handler && !finalizer)
  1644. syntax_error("try statement must have a 'catch' or 'finally' clause");
  1645. return create_ast_node<TryStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(block), move(handler), move(finalizer));
  1646. }
  1647. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  1648. {
  1649. auto rule_start = push_start();
  1650. consume(TokenType::Do);
  1651. auto body = [&]() -> NonnullRefPtr<Statement> {
  1652. TemporaryChange break_change(m_state.in_break_context, true);
  1653. TemporaryChange continue_change(m_state.in_continue_context, true);
  1654. return parse_statement();
  1655. }();
  1656. consume(TokenType::While);
  1657. consume(TokenType::ParenOpen);
  1658. auto test = parse_expression(0);
  1659. consume(TokenType::ParenClose);
  1660. // Since ES 2015 a missing semicolon is inserted here, despite the regular ASI rules not applying
  1661. if (match(TokenType::Semicolon))
  1662. consume();
  1663. return create_ast_node<DoWhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  1664. }
  1665. NonnullRefPtr<WhileStatement> Parser::parse_while_statement()
  1666. {
  1667. auto rule_start = push_start();
  1668. consume(TokenType::While);
  1669. consume(TokenType::ParenOpen);
  1670. auto test = parse_expression(0);
  1671. consume(TokenType::ParenClose);
  1672. TemporaryChange break_change(m_state.in_break_context, true);
  1673. TemporaryChange continue_change(m_state.in_continue_context, true);
  1674. auto body = parse_statement();
  1675. return create_ast_node<WhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  1676. }
  1677. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  1678. {
  1679. auto rule_start = push_start();
  1680. consume(TokenType::Switch);
  1681. consume(TokenType::ParenOpen);
  1682. auto determinant = parse_expression(0);
  1683. consume(TokenType::ParenClose);
  1684. consume(TokenType::CurlyOpen);
  1685. NonnullRefPtrVector<SwitchCase> cases;
  1686. auto has_default = false;
  1687. while (match(TokenType::Case) || match(TokenType::Default)) {
  1688. if (match(TokenType::Default)) {
  1689. if (has_default)
  1690. syntax_error("Multiple 'default' clauses in switch statement");
  1691. has_default = true;
  1692. }
  1693. cases.append(parse_switch_case());
  1694. }
  1695. consume(TokenType::CurlyClose);
  1696. return create_ast_node<SwitchStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(determinant), move(cases));
  1697. }
  1698. NonnullRefPtr<WithStatement> Parser::parse_with_statement()
  1699. {
  1700. auto rule_start = push_start();
  1701. consume(TokenType::With);
  1702. consume(TokenType::ParenOpen);
  1703. auto object = parse_expression(0);
  1704. consume(TokenType::ParenClose);
  1705. auto body = parse_statement();
  1706. return create_ast_node<WithStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(object), move(body));
  1707. }
  1708. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  1709. {
  1710. auto rule_start = push_start();
  1711. RefPtr<Expression> test;
  1712. if (consume().type() == TokenType::Case) {
  1713. test = parse_expression(0);
  1714. }
  1715. consume(TokenType::Colon);
  1716. NonnullRefPtrVector<Statement> consequent;
  1717. TemporaryChange break_change(m_state.in_break_context, true);
  1718. for (;;) {
  1719. if (match_declaration())
  1720. consequent.append(parse_declaration());
  1721. else if (match_statement())
  1722. consequent.append(parse_statement());
  1723. else
  1724. break;
  1725. }
  1726. return create_ast_node<SwitchCase>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(consequent));
  1727. }
  1728. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  1729. {
  1730. auto rule_start = push_start();
  1731. consume(TokenType::Catch);
  1732. String parameter;
  1733. if (match(TokenType::ParenOpen)) {
  1734. consume();
  1735. parameter = consume(TokenType::Identifier).value();
  1736. consume(TokenType::ParenClose);
  1737. }
  1738. auto body = parse_block_statement();
  1739. return create_ast_node<CatchClause>({ m_state.current_token.filename(), rule_start.position(), position() }, parameter, move(body));
  1740. }
  1741. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  1742. {
  1743. auto rule_start = push_start();
  1744. auto parse_function_declaration_as_block_statement = [&] {
  1745. // https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses
  1746. // Code matching this production is processed as if each matching occurrence of
  1747. // FunctionDeclaration[?Yield, ?Await, ~Default] was the sole StatementListItem
  1748. // of a BlockStatement occupying that position in the source code.
  1749. ScopePusher scope(*this, ScopePusher::Let, Parser::Scope::Block);
  1750. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  1751. block->append(parse_declaration());
  1752. scope.add_to_scope_node(block);
  1753. return block;
  1754. };
  1755. consume(TokenType::If);
  1756. consume(TokenType::ParenOpen);
  1757. auto predicate = parse_expression(0);
  1758. consume(TokenType::ParenClose);
  1759. RefPtr<Statement> consequent;
  1760. if (!m_state.strict_mode && match(TokenType::Function))
  1761. consequent = parse_function_declaration_as_block_statement();
  1762. else
  1763. consequent = parse_statement();
  1764. RefPtr<Statement> alternate;
  1765. if (match(TokenType::Else)) {
  1766. consume();
  1767. if (!m_state.strict_mode && match(TokenType::Function))
  1768. alternate = parse_function_declaration_as_block_statement();
  1769. else
  1770. alternate = parse_statement();
  1771. }
  1772. return create_ast_node<IfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(predicate), move(*consequent), move(alternate));
  1773. }
  1774. NonnullRefPtr<Statement> Parser::parse_for_statement()
  1775. {
  1776. auto rule_start = push_start();
  1777. auto match_for_in_of = [&]() {
  1778. return match(TokenType::In) || (match(TokenType::Identifier) && m_state.current_token.value() == "of");
  1779. };
  1780. consume(TokenType::For);
  1781. consume(TokenType::ParenOpen);
  1782. bool in_scope = false;
  1783. RefPtr<ASTNode> init;
  1784. if (!match(TokenType::Semicolon)) {
  1785. if (match_expression()) {
  1786. init = parse_expression(0, Associativity::Right, { TokenType::In });
  1787. if (match_for_in_of())
  1788. return parse_for_in_of_statement(*init);
  1789. } else if (match_variable_declaration()) {
  1790. if (!match(TokenType::Var)) {
  1791. m_state.let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  1792. in_scope = true;
  1793. }
  1794. init = parse_variable_declaration(true);
  1795. if (match_for_in_of())
  1796. return parse_for_in_of_statement(*init);
  1797. if (static_cast<VariableDeclaration&>(*init).declaration_kind() == DeclarationKind::Const) {
  1798. for (auto& declaration : static_cast<VariableDeclaration&>(*init).declarations()) {
  1799. if (!declaration.init())
  1800. syntax_error("Missing initializer in 'const' variable declaration");
  1801. }
  1802. }
  1803. } else {
  1804. syntax_error("Unexpected token in for loop");
  1805. }
  1806. }
  1807. consume(TokenType::Semicolon);
  1808. RefPtr<Expression> test;
  1809. if (!match(TokenType::Semicolon))
  1810. test = parse_expression(0);
  1811. consume(TokenType::Semicolon);
  1812. RefPtr<Expression> update;
  1813. if (!match(TokenType::ParenClose))
  1814. update = parse_expression(0);
  1815. consume(TokenType::ParenClose);
  1816. TemporaryChange break_change(m_state.in_break_context, true);
  1817. TemporaryChange continue_change(m_state.in_continue_context, true);
  1818. auto body = parse_statement();
  1819. if (in_scope) {
  1820. m_state.let_scopes.take_last();
  1821. }
  1822. return create_ast_node<ForStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(init), move(test), move(update), move(body));
  1823. }
  1824. NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs)
  1825. {
  1826. auto rule_start = push_start();
  1827. if (is<VariableDeclaration>(*lhs)) {
  1828. auto declarations = static_cast<VariableDeclaration&>(*lhs).declarations();
  1829. if (declarations.size() > 1)
  1830. syntax_error("multiple declarations not allowed in for..in/of");
  1831. if (declarations.size() < 1)
  1832. syntax_error("need exactly one variable declaration in for..in/of");
  1833. else if (declarations.first().init() != nullptr)
  1834. syntax_error("variable initializer not allowed in for..in/of");
  1835. }
  1836. auto in_or_of = consume();
  1837. auto rhs = parse_expression(0);
  1838. consume(TokenType::ParenClose);
  1839. TemporaryChange break_change(m_state.in_break_context, true);
  1840. TemporaryChange continue_change(m_state.in_continue_context, true);
  1841. auto body = parse_statement();
  1842. if (in_or_of.type() == TokenType::In)
  1843. return create_ast_node<ForInStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), move(rhs), move(body));
  1844. return create_ast_node<ForOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), move(rhs), move(body));
  1845. }
  1846. NonnullRefPtr<DebuggerStatement> Parser::parse_debugger_statement()
  1847. {
  1848. auto rule_start = push_start();
  1849. consume(TokenType::Debugger);
  1850. consume_or_insert_semicolon();
  1851. return create_ast_node<DebuggerStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  1852. }
  1853. bool Parser::match(TokenType type) const
  1854. {
  1855. return m_state.current_token.type() == type;
  1856. }
  1857. bool Parser::match_expression() const
  1858. {
  1859. auto type = m_state.current_token.type();
  1860. return type == TokenType::BoolLiteral
  1861. || type == TokenType::NumericLiteral
  1862. || type == TokenType::BigIntLiteral
  1863. || type == TokenType::StringLiteral
  1864. || type == TokenType::TemplateLiteralStart
  1865. || type == TokenType::NullLiteral
  1866. || type == TokenType::Identifier
  1867. || type == TokenType::New
  1868. || type == TokenType::CurlyOpen
  1869. || type == TokenType::BracketOpen
  1870. || type == TokenType::ParenOpen
  1871. || type == TokenType::Function
  1872. || type == TokenType::This
  1873. || type == TokenType::Super
  1874. || type == TokenType::RegexLiteral
  1875. || type == TokenType::Yield
  1876. || match_unary_prefixed_expression();
  1877. }
  1878. bool Parser::match_unary_prefixed_expression() const
  1879. {
  1880. auto type = m_state.current_token.type();
  1881. return type == TokenType::PlusPlus
  1882. || type == TokenType::MinusMinus
  1883. || type == TokenType::ExclamationMark
  1884. || type == TokenType::Tilde
  1885. || type == TokenType::Plus
  1886. || type == TokenType::Minus
  1887. || type == TokenType::Typeof
  1888. || type == TokenType::Void
  1889. || type == TokenType::Delete;
  1890. }
  1891. bool Parser::match_secondary_expression(const Vector<TokenType>& forbidden) const
  1892. {
  1893. auto type = m_state.current_token.type();
  1894. if (forbidden.contains_slow(type))
  1895. return false;
  1896. return type == TokenType::Plus
  1897. || type == TokenType::PlusEquals
  1898. || type == TokenType::Minus
  1899. || type == TokenType::MinusEquals
  1900. || type == TokenType::Asterisk
  1901. || type == TokenType::AsteriskEquals
  1902. || type == TokenType::Slash
  1903. || type == TokenType::SlashEquals
  1904. || type == TokenType::Percent
  1905. || type == TokenType::PercentEquals
  1906. || type == TokenType::DoubleAsterisk
  1907. || type == TokenType::DoubleAsteriskEquals
  1908. || type == TokenType::Equals
  1909. || type == TokenType::EqualsEqualsEquals
  1910. || type == TokenType::ExclamationMarkEqualsEquals
  1911. || type == TokenType::EqualsEquals
  1912. || type == TokenType::ExclamationMarkEquals
  1913. || type == TokenType::GreaterThan
  1914. || type == TokenType::GreaterThanEquals
  1915. || type == TokenType::LessThan
  1916. || type == TokenType::LessThanEquals
  1917. || type == TokenType::ParenOpen
  1918. || type == TokenType::Period
  1919. || type == TokenType::BracketOpen
  1920. || type == TokenType::PlusPlus
  1921. || type == TokenType::MinusMinus
  1922. || type == TokenType::In
  1923. || type == TokenType::Instanceof
  1924. || type == TokenType::QuestionMark
  1925. || type == TokenType::Ampersand
  1926. || type == TokenType::AmpersandEquals
  1927. || type == TokenType::Pipe
  1928. || type == TokenType::PipeEquals
  1929. || type == TokenType::Caret
  1930. || type == TokenType::CaretEquals
  1931. || type == TokenType::ShiftLeft
  1932. || type == TokenType::ShiftLeftEquals
  1933. || type == TokenType::ShiftRight
  1934. || type == TokenType::ShiftRightEquals
  1935. || type == TokenType::UnsignedShiftRight
  1936. || type == TokenType::UnsignedShiftRightEquals
  1937. || type == TokenType::DoubleAmpersand
  1938. || type == TokenType::DoubleAmpersandEquals
  1939. || type == TokenType::DoublePipe
  1940. || type == TokenType::DoublePipeEquals
  1941. || type == TokenType::DoubleQuestionMark
  1942. || type == TokenType::DoubleQuestionMarkEquals;
  1943. }
  1944. bool Parser::match_statement() const
  1945. {
  1946. auto type = m_state.current_token.type();
  1947. return match_expression()
  1948. || type == TokenType::Return
  1949. || type == TokenType::Yield
  1950. || type == TokenType::Do
  1951. || type == TokenType::If
  1952. || type == TokenType::Throw
  1953. || type == TokenType::Try
  1954. || type == TokenType::While
  1955. || type == TokenType::With
  1956. || type == TokenType::For
  1957. || type == TokenType::CurlyOpen
  1958. || type == TokenType::Switch
  1959. || type == TokenType::Break
  1960. || type == TokenType::Continue
  1961. || type == TokenType::Var
  1962. || type == TokenType::Debugger
  1963. || type == TokenType::Semicolon;
  1964. }
  1965. bool Parser::match_declaration() const
  1966. {
  1967. auto type = m_state.current_token.type();
  1968. return type == TokenType::Function
  1969. || type == TokenType::Class
  1970. || type == TokenType::Const
  1971. || type == TokenType::Let;
  1972. }
  1973. bool Parser::match_variable_declaration() const
  1974. {
  1975. auto type = m_state.current_token.type();
  1976. return type == TokenType::Var
  1977. || type == TokenType::Let
  1978. || type == TokenType::Const;
  1979. }
  1980. bool Parser::match_identifier_name() const
  1981. {
  1982. return m_state.current_token.is_identifier_name();
  1983. }
  1984. bool Parser::match_property_key() const
  1985. {
  1986. auto type = m_state.current_token.type();
  1987. return match_identifier_name()
  1988. || type == TokenType::BracketOpen
  1989. || type == TokenType::StringLiteral
  1990. || type == TokenType::NumericLiteral
  1991. || type == TokenType::BigIntLiteral;
  1992. }
  1993. bool Parser::done() const
  1994. {
  1995. return match(TokenType::Eof);
  1996. }
  1997. Token Parser::consume()
  1998. {
  1999. auto old_token = m_state.current_token;
  2000. m_state.current_token = m_state.lexer.next();
  2001. return old_token;
  2002. }
  2003. void Parser::consume_or_insert_semicolon()
  2004. {
  2005. // Semicolon was found and will be consumed
  2006. if (match(TokenType::Semicolon)) {
  2007. consume();
  2008. return;
  2009. }
  2010. // Insert semicolon if...
  2011. // ...token is preceded by one or more newlines
  2012. if (m_state.current_token.trivia_contains_line_terminator())
  2013. return;
  2014. // ...token is a closing curly brace
  2015. if (match(TokenType::CurlyClose))
  2016. return;
  2017. // ...token is eof
  2018. if (match(TokenType::Eof))
  2019. return;
  2020. // No rule for semicolon insertion applies -> syntax error
  2021. expected("Semicolon");
  2022. }
  2023. static constexpr AK::Array<StringView, 38> reserved_words = { "await", "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with", "yield" };
  2024. static constexpr AK::Array<StringView, 9> strict_reserved_words = { "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield" };
  2025. Token Parser::consume(TokenType expected_type)
  2026. {
  2027. if (!match(expected_type)) {
  2028. expected(Token::name(expected_type));
  2029. }
  2030. auto token = consume();
  2031. if (expected_type == TokenType::Identifier) {
  2032. if (any_of(reserved_words.begin(), reserved_words.end(), [&](auto const& word) { return word == token.value(); }))
  2033. syntax_error("Identifier must not be a reserved word");
  2034. if (m_state.strict_mode && any_of(strict_reserved_words.begin(), strict_reserved_words.end(), [&](auto const& word) { return word == token.value(); }))
  2035. syntax_error("Identifier must not be a class-related reserved word in strict mode");
  2036. }
  2037. return token;
  2038. }
  2039. Token Parser::consume_and_validate_numeric_literal()
  2040. {
  2041. auto is_unprefixed_octal_number = [](const StringView& value) {
  2042. return value.length() > 1 && value[0] == '0' && is_ascii_digit(value[1]);
  2043. };
  2044. auto literal_start = position();
  2045. auto token = consume(TokenType::NumericLiteral);
  2046. if (m_state.strict_mode && is_unprefixed_octal_number(token.value()))
  2047. syntax_error("Unprefixed octal number not allowed in strict mode", literal_start);
  2048. if (match_identifier_name() && m_state.current_token.trivia().is_empty())
  2049. syntax_error("Numeric literal must not be immediately followed by identifier");
  2050. return token;
  2051. }
  2052. void Parser::expected(const char* what)
  2053. {
  2054. auto message = m_state.current_token.message();
  2055. if (message.is_empty())
  2056. message = String::formatted("Unexpected token {}. Expected {}", m_state.current_token.name(), what);
  2057. syntax_error(message);
  2058. }
  2059. Position Parser::position() const
  2060. {
  2061. return {
  2062. m_state.current_token.line_number(),
  2063. m_state.current_token.line_column()
  2064. };
  2065. }
  2066. bool Parser::try_parse_arrow_function_expression_failed_at_position(const Position& position) const
  2067. {
  2068. auto it = m_token_memoizations.find(position);
  2069. if (it == m_token_memoizations.end())
  2070. return false;
  2071. return (*it).value.try_parse_arrow_function_expression_failed;
  2072. }
  2073. void Parser::set_try_parse_arrow_function_expression_failed_at_position(const Position& position, bool failed)
  2074. {
  2075. m_token_memoizations.set(position, { failed });
  2076. }
  2077. void Parser::syntax_error(const String& message, Optional<Position> position)
  2078. {
  2079. if (!position.has_value())
  2080. position = this->position();
  2081. m_state.errors.append({ message, position });
  2082. }
  2083. void Parser::save_state()
  2084. {
  2085. m_saved_state.append(m_state);
  2086. }
  2087. void Parser::load_state()
  2088. {
  2089. VERIFY(!m_saved_state.is_empty());
  2090. m_state = m_saved_state.take_last();
  2091. }
  2092. void Parser::discard_saved_state()
  2093. {
  2094. m_saved_state.take_last();
  2095. }
  2096. }