Parser.cpp 99 KB

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