Parser.cpp 109 KB

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