Parser.cpp 116 KB

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