Parser.cpp 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319
  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. #include <LibJS/Runtime/RegExpObject.h>
  15. #include <LibRegex/Regex.h>
  16. namespace JS {
  17. static bool statement_is_use_strict_directive(NonnullRefPtr<Statement> statement)
  18. {
  19. if (!is<ExpressionStatement>(*statement))
  20. return false;
  21. auto& expression_statement = static_cast<ExpressionStatement&>(*statement);
  22. auto& expression = expression_statement.expression();
  23. if (!is<StringLiteral>(expression))
  24. return false;
  25. return static_cast<const StringLiteral&>(expression).is_use_strict_directive();
  26. }
  27. class ScopePusher {
  28. public:
  29. enum Type {
  30. Var = 1,
  31. Let = 2,
  32. };
  33. ScopePusher(Parser& parser, unsigned mask, Parser::Scope::Type scope_type)
  34. : m_parser(parser)
  35. , m_mask(mask)
  36. {
  37. if (m_mask & Var)
  38. m_parser.m_state.var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  39. if (m_mask & Let)
  40. m_parser.m_state.let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  41. m_parser.m_state.current_scope = create<Parser::Scope>(scope_type, m_parser.m_state.current_scope);
  42. }
  43. ~ScopePusher()
  44. {
  45. if (m_mask & Var)
  46. m_parser.m_state.var_scopes.take_last();
  47. if (m_mask & Let)
  48. m_parser.m_state.let_scopes.take_last();
  49. auto& popped = m_parser.m_state.current_scope;
  50. // Manual clear required to resolve circular references
  51. popped->hoisted_function_declarations.clear();
  52. m_parser.m_state.current_scope = popped->parent;
  53. }
  54. void add_to_scope_node(NonnullRefPtr<ScopeNode> scope_node)
  55. {
  56. if (m_mask & Var)
  57. scope_node->add_variables(m_parser.m_state.var_scopes.last());
  58. if (m_mask & Let)
  59. scope_node->add_variables(m_parser.m_state.let_scopes.last());
  60. auto& scope = m_parser.m_state.current_scope;
  61. scope_node->add_functions(scope->function_declarations);
  62. for (auto& hoistable_function : scope->hoisted_function_declarations) {
  63. if (is_hoistable(hoistable_function)) {
  64. scope_node->add_hoisted_function(hoistable_function.declaration);
  65. }
  66. }
  67. }
  68. static bool is_hoistable(Parser::Scope::HoistableDeclaration& declaration)
  69. {
  70. auto& name = declaration.declaration->name();
  71. // See if we find any conflicting lexical declaration on the way up
  72. for (RefPtr<Parser::Scope> scope = declaration.scope; !scope.is_null(); scope = scope->parent) {
  73. if (scope->lexical_declarations.contains(name)) {
  74. return false;
  75. }
  76. }
  77. return true;
  78. }
  79. Parser& m_parser;
  80. unsigned m_mask { 0 };
  81. };
  82. class OperatorPrecedenceTable {
  83. public:
  84. constexpr OperatorPrecedenceTable()
  85. : m_token_precedence()
  86. {
  87. for (size_t i = 0; i < array_size(m_operator_precedence); ++i) {
  88. auto& op = m_operator_precedence[i];
  89. m_token_precedence[static_cast<size_t>(op.token)] = op.precedence;
  90. }
  91. }
  92. constexpr int get(TokenType token) const
  93. {
  94. int p = m_token_precedence[static_cast<size_t>(token)];
  95. if (p == 0) {
  96. warnln("Internal Error: No precedence for operator {}", Token::name(token));
  97. VERIFY_NOT_REACHED();
  98. return -1;
  99. }
  100. return p;
  101. }
  102. private:
  103. int m_token_precedence[cs_num_of_js_tokens];
  104. struct OperatorPrecedence {
  105. TokenType token;
  106. int precedence;
  107. };
  108. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  109. static constexpr const OperatorPrecedence m_operator_precedence[] = {
  110. { TokenType::Period, 20 },
  111. { TokenType::BracketOpen, 20 },
  112. { TokenType::ParenOpen, 20 },
  113. { TokenType::QuestionMarkPeriod, 20 },
  114. { TokenType::New, 19 },
  115. { TokenType::PlusPlus, 18 },
  116. { TokenType::MinusMinus, 18 },
  117. { TokenType::ExclamationMark, 17 },
  118. { TokenType::Tilde, 17 },
  119. { TokenType::Typeof, 17 },
  120. { TokenType::Void, 17 },
  121. { TokenType::Delete, 17 },
  122. { TokenType::Await, 17 },
  123. { TokenType::DoubleAsterisk, 16 },
  124. { TokenType::Asterisk, 15 },
  125. { TokenType::Slash, 15 },
  126. { TokenType::Percent, 15 },
  127. { TokenType::Plus, 14 },
  128. { TokenType::Minus, 14 },
  129. { TokenType::ShiftLeft, 13 },
  130. { TokenType::ShiftRight, 13 },
  131. { TokenType::UnsignedShiftRight, 13 },
  132. { TokenType::LessThan, 12 },
  133. { TokenType::LessThanEquals, 12 },
  134. { TokenType::GreaterThan, 12 },
  135. { TokenType::GreaterThanEquals, 12 },
  136. { TokenType::In, 12 },
  137. { TokenType::Instanceof, 12 },
  138. { TokenType::EqualsEquals, 11 },
  139. { TokenType::ExclamationMarkEquals, 11 },
  140. { TokenType::EqualsEqualsEquals, 11 },
  141. { TokenType::ExclamationMarkEqualsEquals, 11 },
  142. { TokenType::Ampersand, 10 },
  143. { TokenType::Caret, 9 },
  144. { TokenType::Pipe, 8 },
  145. { TokenType::DoubleQuestionMark, 7 },
  146. { TokenType::DoubleAmpersand, 6 },
  147. { TokenType::DoublePipe, 5 },
  148. { TokenType::QuestionMark, 4 },
  149. { TokenType::Equals, 3 },
  150. { TokenType::PlusEquals, 3 },
  151. { TokenType::MinusEquals, 3 },
  152. { TokenType::DoubleAsteriskEquals, 3 },
  153. { TokenType::AsteriskEquals, 3 },
  154. { TokenType::SlashEquals, 3 },
  155. { TokenType::PercentEquals, 3 },
  156. { TokenType::ShiftLeftEquals, 3 },
  157. { TokenType::ShiftRightEquals, 3 },
  158. { TokenType::UnsignedShiftRightEquals, 3 },
  159. { TokenType::AmpersandEquals, 3 },
  160. { TokenType::CaretEquals, 3 },
  161. { TokenType::PipeEquals, 3 },
  162. { TokenType::DoubleAmpersandEquals, 3 },
  163. { TokenType::DoublePipeEquals, 3 },
  164. { TokenType::DoubleQuestionMarkEquals, 3 },
  165. { TokenType::Yield, 2 },
  166. { TokenType::Comma, 1 },
  167. };
  168. };
  169. constexpr OperatorPrecedenceTable g_operator_precedence;
  170. Parser::ParserState::ParserState(Lexer l, Program::Type program_type)
  171. : lexer(move(l))
  172. , current_token(TokenType::Invalid, {}, {}, {}, {}, 0, 0, 0)
  173. {
  174. if (program_type == Program::Type::Module)
  175. lexer.disallow_html_comments();
  176. current_token = lexer.next();
  177. }
  178. Parser::Scope::Scope(Parser::Scope::Type type, RefPtr<Parser::Scope> parent_scope)
  179. : type(type)
  180. , parent(move(parent_scope))
  181. {
  182. }
  183. RefPtr<Parser::Scope> Parser::Scope::get_current_function_scope()
  184. {
  185. if (this->type == Parser::Scope::Function) {
  186. return *this;
  187. }
  188. auto result = this->parent;
  189. while (result->type != Parser::Scope::Function) {
  190. result = result->parent;
  191. }
  192. return result;
  193. }
  194. Parser::Parser(Lexer lexer, Program::Type program_type)
  195. : m_state(move(lexer), program_type)
  196. , m_program_type(program_type)
  197. {
  198. }
  199. Associativity Parser::operator_associativity(TokenType type) const
  200. {
  201. switch (type) {
  202. case TokenType::Period:
  203. case TokenType::BracketOpen:
  204. case TokenType::ParenOpen:
  205. case TokenType::QuestionMarkPeriod:
  206. case TokenType::Asterisk:
  207. case TokenType::Slash:
  208. case TokenType::Percent:
  209. case TokenType::Plus:
  210. case TokenType::Minus:
  211. case TokenType::ShiftLeft:
  212. case TokenType::ShiftRight:
  213. case TokenType::UnsignedShiftRight:
  214. case TokenType::LessThan:
  215. case TokenType::LessThanEquals:
  216. case TokenType::GreaterThan:
  217. case TokenType::GreaterThanEquals:
  218. case TokenType::In:
  219. case TokenType::Instanceof:
  220. case TokenType::EqualsEquals:
  221. case TokenType::ExclamationMarkEquals:
  222. case TokenType::EqualsEqualsEquals:
  223. case TokenType::ExclamationMarkEqualsEquals:
  224. case TokenType::Typeof:
  225. case TokenType::Void:
  226. case TokenType::Delete:
  227. case TokenType::Ampersand:
  228. case TokenType::Caret:
  229. case TokenType::Pipe:
  230. case TokenType::DoubleQuestionMark:
  231. case TokenType::DoubleAmpersand:
  232. case TokenType::DoublePipe:
  233. case TokenType::Comma:
  234. return Associativity::Left;
  235. default:
  236. return Associativity::Right;
  237. }
  238. }
  239. NonnullRefPtr<Program> Parser::parse_program(bool starts_in_strict_mode)
  240. {
  241. auto rule_start = push_start();
  242. ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Let, Scope::Function);
  243. auto program = adopt_ref(*new Program({ m_filename, rule_start.position(), position() }, m_program_type));
  244. if (starts_in_strict_mode || m_program_type == Program::Type::Module) {
  245. program->set_strict_mode();
  246. m_state.strict_mode = true;
  247. }
  248. bool parsing_directives = true;
  249. while (!done()) {
  250. if (match_declaration()) {
  251. program->append(parse_declaration());
  252. parsing_directives = false;
  253. } else if (match_statement()) {
  254. auto statement = parse_statement(AllowLabelledFunction::Yes);
  255. program->append(statement);
  256. if (statement_is_use_strict_directive(statement)) {
  257. if (parsing_directives) {
  258. program->set_strict_mode();
  259. m_state.strict_mode = true;
  260. }
  261. if (m_state.string_legacy_octal_escape_sequence_in_scope)
  262. syntax_error("Octal escape sequence in string literal not allowed in strict mode");
  263. }
  264. if (parsing_directives && is<ExpressionStatement>(*statement)) {
  265. auto& expression_statement = static_cast<ExpressionStatement&>(*statement);
  266. auto& expression = expression_statement.expression();
  267. parsing_directives = is<StringLiteral>(expression);
  268. } else {
  269. parsing_directives = false;
  270. }
  271. } else if (match_export_or_import()) {
  272. VERIFY(m_state.current_token.type() == TokenType::Export || m_state.current_token.type() == TokenType::Import);
  273. if (m_state.current_token.type() == TokenType::Export)
  274. program->append_export(parse_export_statement(*program));
  275. else
  276. program->append_import(parse_import_statement(*program));
  277. parsing_directives = false;
  278. } else {
  279. expected("statement or declaration");
  280. consume();
  281. parsing_directives = false;
  282. }
  283. }
  284. if (m_state.var_scopes.size() == 1) {
  285. scope.add_to_scope_node(program);
  286. } else {
  287. syntax_error("Unclosed lexical_environment");
  288. }
  289. program->source_range().end = position();
  290. return program;
  291. }
  292. NonnullRefPtr<Declaration> Parser::parse_declaration()
  293. {
  294. auto rule_start = push_start();
  295. switch (m_state.current_token.type()) {
  296. case TokenType::Class:
  297. return parse_class_declaration();
  298. case TokenType::Function: {
  299. auto declaration = parse_function_node<FunctionDeclaration>();
  300. m_state.current_scope->function_declarations.append(declaration);
  301. auto hoisting_target = m_state.current_scope->get_current_function_scope();
  302. hoisting_target->hoisted_function_declarations.append({ declaration, *m_state.current_scope });
  303. return declaration;
  304. }
  305. case TokenType::Let:
  306. case TokenType::Const:
  307. return parse_variable_declaration();
  308. default:
  309. expected("declaration");
  310. consume();
  311. return create_ast_node<ErrorDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() });
  312. }
  313. }
  314. NonnullRefPtr<Statement> Parser::parse_statement(AllowLabelledFunction allow_labelled_function)
  315. {
  316. auto rule_start = push_start();
  317. switch (m_state.current_token.type()) {
  318. case TokenType::CurlyOpen:
  319. return parse_block_statement();
  320. case TokenType::Return:
  321. return parse_return_statement();
  322. case TokenType::Var:
  323. return parse_variable_declaration();
  324. case TokenType::For:
  325. return parse_for_statement();
  326. case TokenType::If:
  327. return parse_if_statement();
  328. case TokenType::Throw:
  329. return parse_throw_statement();
  330. case TokenType::Try:
  331. return parse_try_statement();
  332. case TokenType::Break:
  333. return parse_break_statement();
  334. case TokenType::Continue:
  335. return parse_continue_statement();
  336. case TokenType::Switch:
  337. return parse_switch_statement();
  338. case TokenType::Do:
  339. return parse_do_while_statement();
  340. case TokenType::While:
  341. return parse_while_statement();
  342. case TokenType::With:
  343. if (m_state.strict_mode)
  344. syntax_error("'with' statement not allowed in strict mode");
  345. return parse_with_statement();
  346. case TokenType::Debugger:
  347. return parse_debugger_statement();
  348. case TokenType::Semicolon:
  349. consume();
  350. return create_ast_node<EmptyStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  351. case TokenType::Slash:
  352. case TokenType::SlashEquals:
  353. m_state.current_token = m_state.lexer.force_slash_as_regex();
  354. [[fallthrough]];
  355. default:
  356. if (match_identifier_name()) {
  357. auto result = try_parse_labelled_statement(allow_labelled_function);
  358. if (!result.is_null())
  359. return result.release_nonnull();
  360. }
  361. if (match_expression()) {
  362. if (match(TokenType::Function))
  363. syntax_error("Function declaration not allowed in single-statement context");
  364. auto expr = parse_expression(0);
  365. consume_or_insert_semicolon();
  366. return create_ast_node<ExpressionStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expr));
  367. }
  368. expected("statement");
  369. consume();
  370. return create_ast_node<ErrorStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  371. }
  372. }
  373. static constexpr AK::Array<StringView, 9> strict_reserved_words = { "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield" };
  374. static bool is_strict_reserved_word(StringView str)
  375. {
  376. return any_of(strict_reserved_words, [&str](StringView const& word) {
  377. return word == str;
  378. });
  379. }
  380. RefPtr<FunctionExpression> Parser::try_parse_arrow_function_expression(bool expect_parens)
  381. {
  382. save_state();
  383. auto rule_start = push_start();
  384. ArmedScopeGuard state_rollback_guard = [&] {
  385. load_state();
  386. };
  387. Vector<FunctionNode::Parameter> parameters;
  388. i32 function_length = -1;
  389. if (expect_parens) {
  390. // We have parens around the function parameters and can re-use the same parsing
  391. // logic used for regular functions: multiple parameters, default values, rest
  392. // parameter, maybe a trailing comma. If we have a new syntax error afterwards we
  393. // check if it's about a wrong token (something like duplicate parameter name must
  394. // not abort), know parsing failed and rollback the parser state.
  395. auto previous_syntax_errors = m_state.errors.size();
  396. parameters = parse_formal_parameters(function_length, FunctionNodeParseOptions::IsArrowFunction);
  397. if (m_state.errors.size() > previous_syntax_errors && m_state.errors[previous_syntax_errors].message.starts_with("Unexpected token"))
  398. return nullptr;
  399. if (!match(TokenType::ParenClose))
  400. return nullptr;
  401. consume();
  402. } else {
  403. // No parens - this must be an identifier followed by arrow. That's it.
  404. if (!match_identifier() && !match(TokenType::Yield) && !match(TokenType::Await))
  405. return nullptr;
  406. auto token = consume_identifier_reference();
  407. if (m_state.strict_mode && token.value().is_one_of("arguments"sv, "eval"sv))
  408. syntax_error("BindingIdentifier may not be 'arguments' or 'eval' in strict mode");
  409. parameters.append({ FlyString { token.value() }, {} });
  410. }
  411. // If there's a newline between the closing paren and arrow it's not a valid arrow function,
  412. // ASI should kick in instead (it'll then fail with "Unexpected token Arrow")
  413. if (m_state.current_token.trivia_contains_line_terminator())
  414. return nullptr;
  415. if (!match(TokenType::Arrow))
  416. return nullptr;
  417. consume();
  418. if (function_length == -1)
  419. function_length = parameters.size();
  420. m_state.function_parameters.append(parameters);
  421. auto old_labels_in_scope = move(m_state.labels_in_scope);
  422. ScopeGuard guard([&]() {
  423. m_state.labels_in_scope = move(old_labels_in_scope);
  424. });
  425. bool is_strict = false;
  426. auto function_body_result = [&]() -> RefPtr<BlockStatement> {
  427. TemporaryChange change(m_state.in_arrow_function_context, true);
  428. if (match(TokenType::CurlyOpen)) {
  429. // Parse a function body with statements
  430. ScopePusher scope(*this, ScopePusher::Var, Scope::Function);
  431. bool has_binding = any_of(parameters, [](FunctionNode::Parameter const& parameter) {
  432. return parameter.binding.has<NonnullRefPtr<BindingPattern>>();
  433. });
  434. auto body = parse_block_statement(is_strict, has_binding);
  435. scope.add_to_scope_node(body);
  436. return body;
  437. }
  438. if (match_expression()) {
  439. // Parse a function body which returns a single expression
  440. // FIXME: We synthesize a block with a return statement
  441. // for arrow function bodies which are a single expression.
  442. // Esprima generates a single "ArrowFunctionExpression"
  443. // with a "body" property.
  444. auto return_expression = parse_expression(2);
  445. auto return_block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  446. return_block->append<ReturnStatement>({ m_filename, rule_start.position(), position() }, move(return_expression));
  447. return return_block;
  448. }
  449. // Invalid arrow function body
  450. return nullptr;
  451. }();
  452. m_state.function_parameters.take_last();
  453. if (function_body_result.is_null())
  454. return nullptr;
  455. state_rollback_guard.disarm();
  456. discard_saved_state();
  457. auto body = function_body_result.release_nonnull();
  458. if (is_strict) {
  459. for (auto& parameter : parameters) {
  460. parameter.binding.visit(
  461. [&](FlyString const& name) {
  462. check_identifier_name_for_assignment_validity(name, true);
  463. },
  464. [&](auto const&) {});
  465. }
  466. }
  467. return create_ast_node<FunctionExpression>(
  468. { m_state.current_token.filename(), rule_start.position(), position() }, "", move(body),
  469. move(parameters), function_length, FunctionKind::Regular, is_strict, true);
  470. }
  471. RefPtr<Statement> Parser::try_parse_labelled_statement(AllowLabelledFunction allow_function)
  472. {
  473. save_state();
  474. auto rule_start = push_start();
  475. ArmedScopeGuard state_rollback_guard = [&] {
  476. load_state();
  477. };
  478. if (match(TokenType::Yield) && (m_state.strict_mode || m_state.in_generator_function_context)) {
  479. syntax_error("'yield' label not allowed in this context");
  480. return {};
  481. }
  482. auto identifier = consume_identifier_reference().value();
  483. if (!match(TokenType::Colon))
  484. return {};
  485. consume(TokenType::Colon);
  486. if (!match_statement())
  487. return {};
  488. if (match(TokenType::Function) && (allow_function == AllowLabelledFunction::No || m_state.strict_mode)) {
  489. syntax_error("Not allowed to declare a function here");
  490. return {};
  491. }
  492. if (m_state.labels_in_scope.contains(identifier))
  493. syntax_error(String::formatted("Label '{}' has already been declared", identifier));
  494. m_state.labels_in_scope.set(identifier);
  495. RefPtr<Statement> labelled_statement;
  496. if (match(TokenType::Function)) {
  497. auto function_declaration = parse_function_node<FunctionDeclaration>();
  498. m_state.current_scope->function_declarations.append(function_declaration);
  499. auto hoisting_target = m_state.current_scope->get_current_function_scope();
  500. hoisting_target->hoisted_function_declarations.append({ function_declaration, *m_state.current_scope });
  501. if (function_declaration->kind() == FunctionKind::Generator)
  502. syntax_error("Generator functions cannot be defined in labelled statements");
  503. labelled_statement = move(function_declaration);
  504. } else {
  505. labelled_statement = parse_statement();
  506. }
  507. m_state.labels_in_scope.remove(identifier);
  508. labelled_statement->set_label(identifier);
  509. state_rollback_guard.disarm();
  510. discard_saved_state();
  511. return labelled_statement.release_nonnull();
  512. }
  513. RefPtr<MetaProperty> Parser::try_parse_new_target_expression()
  514. {
  515. save_state();
  516. auto rule_start = push_start();
  517. ArmedScopeGuard state_rollback_guard = [&] {
  518. load_state();
  519. };
  520. consume(TokenType::New);
  521. if (!match(TokenType::Period))
  522. return {};
  523. consume();
  524. if (!match(TokenType::Identifier))
  525. return {};
  526. if (consume().value() != "target")
  527. return {};
  528. state_rollback_guard.disarm();
  529. discard_saved_state();
  530. return create_ast_node<MetaProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, MetaProperty::Type::NewTarget);
  531. }
  532. NonnullRefPtr<ClassDeclaration> Parser::parse_class_declaration()
  533. {
  534. auto rule_start = push_start();
  535. return create_ast_node<ClassDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() }, parse_class_expression(true));
  536. }
  537. NonnullRefPtr<ClassExpression> Parser::parse_class_expression(bool expect_class_name)
  538. {
  539. auto rule_start = push_start();
  540. // Classes are always in strict mode.
  541. TemporaryChange strict_mode_rollback(m_state.strict_mode, true);
  542. consume(TokenType::Class);
  543. NonnullRefPtrVector<ClassMethod> methods;
  544. RefPtr<Expression> super_class;
  545. RefPtr<FunctionExpression> constructor;
  546. String class_name = expect_class_name || match_identifier() || match(TokenType::Yield) || match(TokenType::Await)
  547. ? consume_identifier_reference().value().to_string()
  548. : "";
  549. check_identifier_name_for_assignment_validity(class_name, true);
  550. if (match(TokenType::Extends)) {
  551. consume();
  552. auto [expression, should_continue_parsing] = parse_primary_expression();
  553. // Basically a (much) simplified parse_secondary_expression().
  554. for (;;) {
  555. if (match(TokenType::TemplateLiteralStart)) {
  556. auto template_literal = parse_template_literal(true);
  557. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  558. continue;
  559. }
  560. if (match(TokenType::BracketOpen) || match(TokenType::Period) || match(TokenType::ParenOpen)) {
  561. auto precedence = g_operator_precedence.get(m_state.current_token.type());
  562. expression = parse_secondary_expression(move(expression), precedence);
  563. continue;
  564. }
  565. break;
  566. }
  567. super_class = move(expression);
  568. (void)should_continue_parsing;
  569. }
  570. consume(TokenType::CurlyOpen);
  571. while (!done() && !match(TokenType::CurlyClose)) {
  572. RefPtr<Expression> property_key;
  573. bool is_static = false;
  574. bool is_constructor = false;
  575. bool is_generator = false;
  576. auto method_kind = ClassMethod::Kind::Method;
  577. if (match(TokenType::Semicolon)) {
  578. consume();
  579. continue;
  580. }
  581. if (match(TokenType::Asterisk)) {
  582. consume();
  583. is_generator = true;
  584. }
  585. if (match_property_key()) {
  586. StringView name;
  587. if (!is_generator && m_state.current_token.value() == "static"sv) {
  588. if (match(TokenType::Identifier)) {
  589. consume();
  590. is_static = true;
  591. if (match(TokenType::Asterisk)) {
  592. consume();
  593. is_generator = true;
  594. }
  595. }
  596. }
  597. if (match(TokenType::Identifier)) {
  598. auto identifier_name = m_state.current_token.value();
  599. if (identifier_name == "get") {
  600. method_kind = ClassMethod::Kind::Getter;
  601. consume();
  602. } else if (identifier_name == "set") {
  603. method_kind = ClassMethod::Kind::Setter;
  604. consume();
  605. }
  606. }
  607. if (match_property_key()) {
  608. switch (m_state.current_token.type()) {
  609. case TokenType::Identifier:
  610. name = consume().value();
  611. property_key = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, name);
  612. break;
  613. case TokenType::StringLiteral: {
  614. auto string_literal = parse_string_literal(consume());
  615. name = string_literal->value();
  616. property_key = move(string_literal);
  617. break;
  618. }
  619. default:
  620. property_key = parse_property_key();
  621. break;
  622. }
  623. //https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors
  624. // ClassElement : static MethodDefinition
  625. // It is a Syntax Error if PropName of MethodDefinition is "prototype".
  626. if (is_static && name == "prototype"sv)
  627. syntax_error("Classes may not have a static property named 'prototype'");
  628. } else if (match(TokenType::ParenOpen) && (is_static || method_kind != ClassMethod::Kind::Method)) {
  629. switch (method_kind) {
  630. case ClassMethod::Kind::Method:
  631. VERIFY(is_static);
  632. name = "static";
  633. is_static = false;
  634. break;
  635. case ClassMethod::Kind::Getter:
  636. name = "get";
  637. method_kind = ClassMethod::Kind::Method;
  638. break;
  639. case ClassMethod::Kind::Setter:
  640. name = "set";
  641. method_kind = ClassMethod::Kind::Method;
  642. break;
  643. }
  644. property_key = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, name);
  645. } else {
  646. expected("property key");
  647. }
  648. // Constructor may be a StringLiteral or an Identifier.
  649. if (!is_static && name == "constructor") {
  650. if (method_kind != ClassMethod::Kind::Method)
  651. syntax_error("Class constructor may not be an accessor");
  652. if (!constructor.is_null())
  653. syntax_error("Classes may not have more than one constructor");
  654. if (is_generator)
  655. syntax_error("Class constructor may not be a generator");
  656. is_constructor = true;
  657. }
  658. }
  659. if (match(TokenType::ParenOpen)) {
  660. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  661. if (!super_class.is_null() && !is_static && is_constructor)
  662. parse_options |= FunctionNodeParseOptions::AllowSuperConstructorCall;
  663. if (method_kind == ClassMethod::Kind::Getter)
  664. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  665. if (method_kind == ClassMethod::Kind::Setter)
  666. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  667. if (is_generator)
  668. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  669. auto function = parse_function_node<FunctionExpression>(parse_options);
  670. if (is_constructor) {
  671. constructor = move(function);
  672. } else if (!property_key.is_null()) {
  673. 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));
  674. } else {
  675. syntax_error("No key for class method");
  676. }
  677. } else {
  678. expected("ParenOpen");
  679. consume();
  680. }
  681. }
  682. consume(TokenType::CurlyClose);
  683. if (constructor.is_null()) {
  684. auto constructor_body = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  685. if (!super_class.is_null()) {
  686. // Set constructor to the result of parsing the source text
  687. // constructor(... args){ super (...args);}
  688. auto super_call = create_ast_node<SuperCall>(
  689. { m_state.current_token.filename(), rule_start.position(), position() },
  690. Vector { CallExpression::Argument { create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, "args"), true } });
  691. constructor_body->append(create_ast_node<ExpressionStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(super_call)));
  692. constructor_body->add_variables(m_state.var_scopes.last());
  693. constructor = create_ast_node<FunctionExpression>(
  694. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, move(constructor_body),
  695. Vector { FunctionNode::Parameter { FlyString { "args" }, nullptr, true } }, 0, FunctionKind::Regular, true);
  696. } else {
  697. constructor = create_ast_node<FunctionExpression>(
  698. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, move(constructor_body),
  699. Vector<FunctionNode::Parameter> {}, 0, FunctionKind::Regular, true);
  700. }
  701. }
  702. return create_ast_node<ClassExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(class_name), move(constructor), move(super_class), move(methods));
  703. }
  704. Parser::PrimaryExpressionParseResult Parser::parse_primary_expression()
  705. {
  706. auto rule_start = push_start();
  707. if (match_unary_prefixed_expression())
  708. return { parse_unary_prefixed_expression() };
  709. switch (m_state.current_token.type()) {
  710. case TokenType::ParenOpen: {
  711. auto paren_position = position();
  712. consume(TokenType::ParenOpen);
  713. if ((match(TokenType::ParenClose) || match_identifier() || match(TokenType::TripleDot) || match(TokenType::CurlyOpen) || match(TokenType::BracketOpen))
  714. && !try_parse_arrow_function_expression_failed_at_position(paren_position)) {
  715. auto arrow_function_result = try_parse_arrow_function_expression(true);
  716. if (!arrow_function_result.is_null())
  717. return { arrow_function_result.release_nonnull(), false };
  718. set_try_parse_arrow_function_expression_failed_at_position(paren_position, true);
  719. }
  720. auto expression = parse_expression(0);
  721. consume(TokenType::ParenClose);
  722. if (is<FunctionExpression>(*expression)) {
  723. auto& function = static_cast<FunctionExpression&>(*expression);
  724. function.set_cannot_auto_rename();
  725. if (function.kind() == FunctionKind::Generator && function.name() == "yield"sv)
  726. syntax_error("function is not allowed to be called 'yield' in this context", function.source_range().start);
  727. }
  728. return { move(expression) };
  729. }
  730. case TokenType::This:
  731. consume();
  732. return { create_ast_node<ThisExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  733. case TokenType::Class:
  734. return { parse_class_expression(false) };
  735. case TokenType::Super:
  736. consume();
  737. if (!m_state.allow_super_property_lookup)
  738. syntax_error("'super' keyword unexpected here");
  739. return { create_ast_node<SuperExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  740. case TokenType::Identifier: {
  741. read_as_identifier:;
  742. if (!try_parse_arrow_function_expression_failed_at_position(position())) {
  743. auto arrow_function_result = try_parse_arrow_function_expression(false);
  744. if (!arrow_function_result.is_null())
  745. return { arrow_function_result.release_nonnull(), false };
  746. set_try_parse_arrow_function_expression_failed_at_position(position(), true);
  747. }
  748. auto string = consume().value();
  749. // This could be 'eval' or 'arguments' and thus needs a custom check (`eval[1] = true`)
  750. if (m_state.strict_mode && (string == "let" || is_strict_reserved_word(string)))
  751. syntax_error(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", string));
  752. return { create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, string) };
  753. }
  754. case TokenType::NumericLiteral:
  755. return { create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume_and_validate_numeric_literal().double_value()) };
  756. case TokenType::BigIntLiteral:
  757. return { create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()) };
  758. case TokenType::BoolLiteral:
  759. return { create_ast_node<BooleanLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().bool_value()) };
  760. case TokenType::StringLiteral:
  761. return { parse_string_literal(consume()) };
  762. case TokenType::NullLiteral:
  763. consume();
  764. return { create_ast_node<NullLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  765. case TokenType::CurlyOpen:
  766. return { parse_object_expression() };
  767. case TokenType::Function:
  768. return { parse_function_node<FunctionExpression>() };
  769. case TokenType::BracketOpen:
  770. return { parse_array_expression() };
  771. case TokenType::RegexLiteral:
  772. return { parse_regexp_literal() };
  773. case TokenType::TemplateLiteralStart:
  774. return { parse_template_literal(false) };
  775. case TokenType::New: {
  776. auto new_start = position();
  777. auto new_target_result = try_parse_new_target_expression();
  778. if (!new_target_result.is_null()) {
  779. if (!m_state.in_function_context)
  780. syntax_error("'new.target' not allowed outside of a function", new_start);
  781. return { new_target_result.release_nonnull() };
  782. }
  783. return { parse_new_expression() };
  784. }
  785. case TokenType::Yield:
  786. if (!m_state.in_generator_function_context)
  787. goto read_as_identifier;
  788. return { parse_yield_expression(), false };
  789. default:
  790. if (match_identifier_name())
  791. goto read_as_identifier;
  792. expected("primary expression");
  793. consume();
  794. return { create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  795. }
  796. }
  797. NonnullRefPtr<RegExpLiteral> Parser::parse_regexp_literal()
  798. {
  799. auto rule_start = push_start();
  800. auto pattern = consume().value();
  801. // Remove leading and trailing slash.
  802. pattern = pattern.substring_view(1, pattern.length() - 2);
  803. auto flags = String::empty();
  804. auto parsed_flags = RegExpObject::default_flags;
  805. if (match(TokenType::RegexFlags)) {
  806. auto flags_start = position();
  807. flags = consume().value();
  808. auto parsed_flags_or_error = regex_flags_from_string(flags);
  809. if (parsed_flags_or_error.is_error())
  810. syntax_error(parsed_flags_or_error.release_error(), flags_start);
  811. else
  812. parsed_flags = parsed_flags_or_error.release_value();
  813. }
  814. auto parsed_pattern = parse_regex_pattern(pattern, parsed_flags.has_flag_set(ECMAScriptFlags::Unicode));
  815. auto parsed_regex = Regex<ECMA262>::parse_pattern(parsed_pattern, parsed_flags);
  816. if (parsed_regex.error != regex::Error::NoError)
  817. syntax_error(String::formatted("RegExp compile error: {}", Regex<ECMA262>(parsed_regex, parsed_pattern, parsed_flags).error_string()), rule_start.position());
  818. SourceRange range { m_state.current_token.filename(), rule_start.position(), position() };
  819. return create_ast_node<RegExpLiteral>(move(range), move(parsed_regex), move(parsed_pattern), move(parsed_flags), pattern.to_string(), move(flags));
  820. }
  821. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  822. {
  823. auto rule_start = push_start();
  824. auto precedence = g_operator_precedence.get(m_state.current_token.type());
  825. auto associativity = operator_associativity(m_state.current_token.type());
  826. switch (m_state.current_token.type()) {
  827. case TokenType::PlusPlus: {
  828. consume();
  829. auto rhs_start = position();
  830. auto rhs = parse_expression(precedence, associativity);
  831. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  832. // other engines throw ReferenceError for ++foo()
  833. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  834. syntax_error(String::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  835. if (m_state.strict_mode && is<Identifier>(*rhs)) {
  836. auto& identifier = static_cast<Identifier&>(*rhs);
  837. auto& name = identifier.string();
  838. check_identifier_name_for_assignment_validity(name);
  839. }
  840. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(rhs), true);
  841. }
  842. case TokenType::MinusMinus: {
  843. consume();
  844. auto rhs_start = position();
  845. auto rhs = parse_expression(precedence, associativity);
  846. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  847. // other engines throw ReferenceError for --foo()
  848. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  849. syntax_error(String::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  850. if (m_state.strict_mode && is<Identifier>(*rhs)) {
  851. auto& identifier = static_cast<Identifier&>(*rhs);
  852. auto& name = identifier.string();
  853. check_identifier_name_for_assignment_validity(name);
  854. }
  855. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(rhs), true);
  856. }
  857. case TokenType::ExclamationMark:
  858. consume();
  859. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Not, parse_expression(precedence, associativity));
  860. case TokenType::Tilde:
  861. consume();
  862. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  863. case TokenType::Plus:
  864. consume();
  865. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Plus, parse_expression(precedence, associativity));
  866. case TokenType::Minus:
  867. consume();
  868. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Minus, parse_expression(precedence, associativity));
  869. case TokenType::Typeof:
  870. consume();
  871. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Typeof, parse_expression(precedence, associativity));
  872. case TokenType::Void:
  873. consume();
  874. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Void, parse_expression(precedence, associativity));
  875. case TokenType::Delete: {
  876. consume();
  877. auto rhs_start = position();
  878. auto rhs = parse_expression(precedence, associativity);
  879. if (is<Identifier>(*rhs) && m_state.strict_mode) {
  880. syntax_error("Delete of an unqualified identifier in strict mode.", rhs_start);
  881. }
  882. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Delete, move(rhs));
  883. }
  884. default:
  885. expected("primary expression");
  886. consume();
  887. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  888. }
  889. }
  890. NonnullRefPtr<Expression> Parser::parse_property_key()
  891. {
  892. auto rule_start = push_start();
  893. if (match(TokenType::StringLiteral)) {
  894. return parse_string_literal(consume());
  895. } else if (match(TokenType::NumericLiteral)) {
  896. return create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().double_value());
  897. } else if (match(TokenType::BigIntLiteral)) {
  898. return create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  899. } else if (match(TokenType::BracketOpen)) {
  900. consume(TokenType::BracketOpen);
  901. auto result = parse_expression(2);
  902. consume(TokenType::BracketClose);
  903. return result;
  904. } else {
  905. if (!match_identifier_name())
  906. expected("IdentifierName");
  907. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  908. }
  909. }
  910. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  911. {
  912. auto rule_start = push_start();
  913. consume(TokenType::CurlyOpen);
  914. NonnullRefPtrVector<ObjectProperty> properties;
  915. ObjectProperty::Type property_type;
  916. Optional<SourceRange> invalid_object_literal_property_range;
  917. auto skip_to_next_property = [&] {
  918. while (!done() && !match(TokenType::Comma) && !match(TokenType::CurlyOpen))
  919. consume();
  920. };
  921. // It is a Syntax Error if PropertyNameList of PropertyDefinitionList contains any duplicate
  922. // entries for "__proto__" and at least two of those entries were obtained from productions of
  923. // the form PropertyDefinition : PropertyName : AssignmentExpression .
  924. bool has_direct_proto_property = false;
  925. while (!done() && !match(TokenType::CurlyClose)) {
  926. property_type = ObjectProperty::Type::KeyValue;
  927. RefPtr<Expression> property_name;
  928. RefPtr<Expression> property_value;
  929. FunctionKind function_kind { FunctionKind::Regular };
  930. if (match(TokenType::TripleDot)) {
  931. consume();
  932. property_name = parse_expression(4);
  933. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, nullptr, ObjectProperty::Type::Spread, false));
  934. if (!match(TokenType::Comma))
  935. break;
  936. consume(TokenType::Comma);
  937. continue;
  938. }
  939. auto type = m_state.current_token.type();
  940. if (match(TokenType::Asterisk)) {
  941. consume();
  942. property_type = ObjectProperty::Type::KeyValue;
  943. property_name = parse_property_key();
  944. function_kind = FunctionKind ::Generator;
  945. } else if (match_identifier()) {
  946. auto identifier = consume().value();
  947. if (identifier == "get" && match_property_key()) {
  948. property_type = ObjectProperty::Type::Getter;
  949. property_name = parse_property_key();
  950. } else if (identifier == "set" && match_property_key()) {
  951. property_type = ObjectProperty::Type::Setter;
  952. property_name = parse_property_key();
  953. } else {
  954. property_name = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier);
  955. property_value = create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier);
  956. }
  957. } else {
  958. property_name = parse_property_key();
  959. }
  960. bool is_proto = (type == TokenType::StringLiteral || type == TokenType::Identifier) && is<StringLiteral>(*property_name) && static_cast<StringLiteral const&>(*property_name).value() == "__proto__";
  961. if (property_type == ObjectProperty::Type::Getter || property_type == ObjectProperty::Type::Setter) {
  962. if (!match(TokenType::ParenOpen)) {
  963. expected("'(' for object getter or setter property");
  964. skip_to_next_property();
  965. continue;
  966. }
  967. }
  968. if (match(TokenType::Equals)) {
  969. // Not a valid object literal, but a valid assignment target
  970. consume();
  971. // Parse the expression and throw it away
  972. auto expression = parse_expression(2);
  973. if (!invalid_object_literal_property_range.has_value())
  974. invalid_object_literal_property_range = expression->source_range();
  975. } else if (match(TokenType::ParenOpen)) {
  976. VERIFY(property_name);
  977. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  978. if (property_type == ObjectProperty::Type::Getter)
  979. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  980. if (property_type == ObjectProperty::Type::Setter)
  981. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  982. if (function_kind == FunctionKind::Generator)
  983. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  984. auto function = parse_function_node<FunctionExpression>(parse_options);
  985. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, function, property_type, true));
  986. } else if (match(TokenType::Colon)) {
  987. if (!property_name) {
  988. expected("a property name");
  989. skip_to_next_property();
  990. continue;
  991. }
  992. consume();
  993. if (is_proto) {
  994. if (has_direct_proto_property)
  995. syntax_error("Property name '__proto__' must not appear more than once in object literal");
  996. has_direct_proto_property = true;
  997. }
  998. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, parse_expression(2), property_type, false));
  999. } else if (property_name && property_value) {
  1000. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, *property_value, property_type, false));
  1001. } else {
  1002. expected("a property");
  1003. skip_to_next_property();
  1004. continue;
  1005. }
  1006. if (!match(TokenType::Comma))
  1007. break;
  1008. consume(TokenType::Comma);
  1009. }
  1010. consume(TokenType::CurlyClose);
  1011. return create_ast_node<ObjectExpression>(
  1012. { m_state.current_token.filename(), rule_start.position(), position() },
  1013. move(properties),
  1014. move(invalid_object_literal_property_range));
  1015. }
  1016. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  1017. {
  1018. auto rule_start = push_start();
  1019. consume(TokenType::BracketOpen);
  1020. Vector<RefPtr<Expression>> elements;
  1021. while (match_expression() || match(TokenType::TripleDot) || match(TokenType::Comma)) {
  1022. RefPtr<Expression> expression;
  1023. if (match(TokenType::TripleDot)) {
  1024. consume(TokenType::TripleDot);
  1025. expression = create_ast_node<SpreadExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, parse_expression(2));
  1026. } else if (match_expression()) {
  1027. expression = parse_expression(2);
  1028. }
  1029. elements.append(expression);
  1030. if (!match(TokenType::Comma))
  1031. break;
  1032. consume(TokenType::Comma);
  1033. }
  1034. consume(TokenType::BracketClose);
  1035. return create_ast_node<ArrayExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(elements));
  1036. }
  1037. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(const Token& token, bool in_template_literal)
  1038. {
  1039. auto rule_start = push_start();
  1040. auto status = Token::StringValueStatus::Ok;
  1041. auto string = token.string_value(status);
  1042. if (status != Token::StringValueStatus::Ok) {
  1043. String message;
  1044. if (status == Token::StringValueStatus::LegacyOctalEscapeSequence) {
  1045. m_state.string_legacy_octal_escape_sequence_in_scope = true;
  1046. if (in_template_literal)
  1047. message = "Octal escape sequence not allowed in template literal";
  1048. else if (m_state.strict_mode)
  1049. message = "Octal escape sequence in string literal not allowed in strict mode";
  1050. } else if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) {
  1051. auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal";
  1052. message = String::formatted("Malformed {} escape sequence", type);
  1053. } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) {
  1054. message = "Unicode code_point must not be greater than 0x10ffff in escape sequence";
  1055. } else {
  1056. VERIFY_NOT_REACHED();
  1057. }
  1058. if (!message.is_empty())
  1059. syntax_error(message, Position { token.line_number(), token.line_column() });
  1060. }
  1061. auto is_use_strict_directive = !in_template_literal && (token.value() == "'use strict'" || token.value() == "\"use strict\"");
  1062. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, string, is_use_strict_directive);
  1063. }
  1064. NonnullRefPtr<TemplateLiteral> Parser::parse_template_literal(bool is_tagged)
  1065. {
  1066. auto rule_start = push_start();
  1067. consume(TokenType::TemplateLiteralStart);
  1068. NonnullRefPtrVector<Expression> expressions;
  1069. NonnullRefPtrVector<Expression> raw_strings;
  1070. auto append_empty_string = [this, &rule_start, &expressions, &raw_strings, is_tagged]() {
  1071. auto string_literal = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, "");
  1072. expressions.append(string_literal);
  1073. if (is_tagged)
  1074. raw_strings.append(string_literal);
  1075. };
  1076. if (!match(TokenType::TemplateLiteralString))
  1077. append_empty_string();
  1078. while (!done() && !match(TokenType::TemplateLiteralEnd) && !match(TokenType::UnterminatedTemplateLiteral)) {
  1079. if (match(TokenType::TemplateLiteralString)) {
  1080. auto token = consume();
  1081. expressions.append(parse_string_literal(token, true));
  1082. if (is_tagged)
  1083. raw_strings.append(create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, token.value()));
  1084. } else if (match(TokenType::TemplateLiteralExprStart)) {
  1085. consume(TokenType::TemplateLiteralExprStart);
  1086. if (match(TokenType::TemplateLiteralExprEnd)) {
  1087. syntax_error("Empty template literal expression block");
  1088. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1089. }
  1090. expressions.append(parse_expression(0));
  1091. if (match(TokenType::UnterminatedTemplateLiteral)) {
  1092. syntax_error("Unterminated template literal");
  1093. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1094. }
  1095. consume(TokenType::TemplateLiteralExprEnd);
  1096. if (!match(TokenType::TemplateLiteralString))
  1097. append_empty_string();
  1098. } else {
  1099. expected("Template literal string or expression");
  1100. break;
  1101. }
  1102. }
  1103. if (match(TokenType::UnterminatedTemplateLiteral)) {
  1104. syntax_error("Unterminated template literal");
  1105. } else {
  1106. consume(TokenType::TemplateLiteralEnd);
  1107. }
  1108. if (is_tagged)
  1109. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions, raw_strings);
  1110. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1111. }
  1112. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity, const Vector<TokenType>& forbidden)
  1113. {
  1114. auto rule_start = push_start();
  1115. auto [expression, should_continue_parsing] = parse_primary_expression();
  1116. auto check_for_invalid_object_property = [&](auto& expression) {
  1117. if (is<ObjectExpression>(*expression)) {
  1118. if (auto range = static_cast<ObjectExpression&>(*expression).invalid_property_range(); range.has_value())
  1119. syntax_error("Invalid property in object literal", range->start);
  1120. }
  1121. };
  1122. while (match(TokenType::TemplateLiteralStart)) {
  1123. auto template_literal = parse_template_literal(true);
  1124. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  1125. }
  1126. if (should_continue_parsing) {
  1127. while (match_secondary_expression(forbidden)) {
  1128. int new_precedence = g_operator_precedence.get(m_state.current_token.type());
  1129. if (new_precedence < min_precedence)
  1130. break;
  1131. if (new_precedence == min_precedence && associativity == Associativity::Left)
  1132. break;
  1133. check_for_invalid_object_property(expression);
  1134. Associativity new_associativity = operator_associativity(m_state.current_token.type());
  1135. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  1136. while (match(TokenType::TemplateLiteralStart) && !is<UpdateExpression>(*expression)) {
  1137. auto template_literal = parse_template_literal(true);
  1138. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  1139. }
  1140. }
  1141. }
  1142. check_for_invalid_object_property(expression);
  1143. if (match(TokenType::Comma) && min_precedence <= 1) {
  1144. NonnullRefPtrVector<Expression> expressions;
  1145. expressions.append(expression);
  1146. while (match(TokenType::Comma)) {
  1147. consume();
  1148. expressions.append(parse_expression(2));
  1149. }
  1150. expression = create_ast_node<SequenceExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expressions));
  1151. }
  1152. return expression;
  1153. }
  1154. NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  1155. {
  1156. auto rule_start = push_start();
  1157. switch (m_state.current_token.type()) {
  1158. case TokenType::Plus:
  1159. consume();
  1160. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity));
  1161. case TokenType::PlusEquals:
  1162. return parse_assignment_expression(AssignmentOp::AdditionAssignment, move(lhs), min_precedence, associativity);
  1163. case TokenType::Minus:
  1164. consume();
  1165. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity));
  1166. case TokenType::MinusEquals:
  1167. return parse_assignment_expression(AssignmentOp::SubtractionAssignment, move(lhs), min_precedence, associativity);
  1168. case TokenType::Asterisk:
  1169. consume();
  1170. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity));
  1171. case TokenType::AsteriskEquals:
  1172. return parse_assignment_expression(AssignmentOp::MultiplicationAssignment, move(lhs), min_precedence, associativity);
  1173. case TokenType::Slash:
  1174. consume();
  1175. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity));
  1176. case TokenType::SlashEquals:
  1177. return parse_assignment_expression(AssignmentOp::DivisionAssignment, move(lhs), min_precedence, associativity);
  1178. case TokenType::Percent:
  1179. consume();
  1180. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity));
  1181. case TokenType::PercentEquals:
  1182. return parse_assignment_expression(AssignmentOp::ModuloAssignment, move(lhs), min_precedence, associativity);
  1183. case TokenType::DoubleAsterisk:
  1184. consume();
  1185. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity));
  1186. case TokenType::DoubleAsteriskEquals:
  1187. return parse_assignment_expression(AssignmentOp::ExponentiationAssignment, move(lhs), min_precedence, associativity);
  1188. case TokenType::GreaterThan:
  1189. consume();
  1190. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  1191. case TokenType::GreaterThanEquals:
  1192. consume();
  1193. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  1194. case TokenType::LessThan:
  1195. consume();
  1196. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  1197. case TokenType::LessThanEquals:
  1198. consume();
  1199. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  1200. case TokenType::EqualsEqualsEquals:
  1201. consume();
  1202. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::TypedEquals, move(lhs), parse_expression(min_precedence, associativity));
  1203. case TokenType::ExclamationMarkEqualsEquals:
  1204. consume();
  1205. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::TypedInequals, move(lhs), parse_expression(min_precedence, associativity));
  1206. case TokenType::EqualsEquals:
  1207. consume();
  1208. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::AbstractEquals, move(lhs), parse_expression(min_precedence, associativity));
  1209. case TokenType::ExclamationMarkEquals:
  1210. consume();
  1211. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::AbstractInequals, move(lhs), parse_expression(min_precedence, associativity));
  1212. case TokenType::In:
  1213. consume();
  1214. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::In, move(lhs), parse_expression(min_precedence, associativity));
  1215. case TokenType::Instanceof:
  1216. consume();
  1217. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity));
  1218. case TokenType::Ampersand:
  1219. consume();
  1220. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity));
  1221. case TokenType::AmpersandEquals:
  1222. return parse_assignment_expression(AssignmentOp::BitwiseAndAssignment, move(lhs), min_precedence, associativity);
  1223. case TokenType::Pipe:
  1224. consume();
  1225. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity));
  1226. case TokenType::PipeEquals:
  1227. return parse_assignment_expression(AssignmentOp::BitwiseOrAssignment, move(lhs), min_precedence, associativity);
  1228. case TokenType::Caret:
  1229. consume();
  1230. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity));
  1231. case TokenType::CaretEquals:
  1232. return parse_assignment_expression(AssignmentOp::BitwiseXorAssignment, move(lhs), min_precedence, associativity);
  1233. case TokenType::ShiftLeft:
  1234. consume();
  1235. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LeftShift, move(lhs), parse_expression(min_precedence, associativity));
  1236. case TokenType::ShiftLeftEquals:
  1237. return parse_assignment_expression(AssignmentOp::LeftShiftAssignment, move(lhs), min_precedence, associativity);
  1238. case TokenType::ShiftRight:
  1239. consume();
  1240. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::RightShift, move(lhs), parse_expression(min_precedence, associativity));
  1241. case TokenType::ShiftRightEquals:
  1242. return parse_assignment_expression(AssignmentOp::RightShiftAssignment, move(lhs), min_precedence, associativity);
  1243. case TokenType::UnsignedShiftRight:
  1244. consume();
  1245. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::UnsignedRightShift, move(lhs), parse_expression(min_precedence, associativity));
  1246. case TokenType::UnsignedShiftRightEquals:
  1247. return parse_assignment_expression(AssignmentOp::UnsignedRightShiftAssignment, move(lhs), min_precedence, associativity);
  1248. case TokenType::ParenOpen:
  1249. return parse_call_expression(move(lhs));
  1250. case TokenType::Equals:
  1251. return parse_assignment_expression(AssignmentOp::Assignment, move(lhs), min_precedence, associativity);
  1252. case TokenType::Period:
  1253. consume();
  1254. if (!match_identifier_name())
  1255. expected("IdentifierName");
  1256. 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()));
  1257. case TokenType::BracketOpen: {
  1258. consume(TokenType::BracketOpen);
  1259. auto expression = create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), parse_expression(0), true);
  1260. consume(TokenType::BracketClose);
  1261. return expression;
  1262. }
  1263. case TokenType::PlusPlus:
  1264. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1265. // other engines throw ReferenceError for foo()++
  1266. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1267. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1268. if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1269. auto& identifier = static_cast<Identifier&>(*lhs);
  1270. auto& name = identifier.string();
  1271. check_identifier_name_for_assignment_validity(name);
  1272. }
  1273. consume();
  1274. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(lhs));
  1275. case TokenType::MinusMinus:
  1276. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1277. // other engines throw ReferenceError for foo()--
  1278. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1279. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1280. if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1281. auto& identifier = static_cast<Identifier&>(*lhs);
  1282. auto& name = identifier.string();
  1283. check_identifier_name_for_assignment_validity(name);
  1284. }
  1285. consume();
  1286. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(lhs));
  1287. case TokenType::DoubleAmpersand:
  1288. consume();
  1289. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity));
  1290. case TokenType::DoubleAmpersandEquals:
  1291. return parse_assignment_expression(AssignmentOp::AndAssignment, move(lhs), min_precedence, associativity);
  1292. case TokenType::DoublePipe:
  1293. consume();
  1294. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity));
  1295. case TokenType::DoublePipeEquals:
  1296. return parse_assignment_expression(AssignmentOp::OrAssignment, move(lhs), min_precedence, associativity);
  1297. case TokenType::DoubleQuestionMark:
  1298. consume();
  1299. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::NullishCoalescing, move(lhs), parse_expression(min_precedence, associativity));
  1300. case TokenType::DoubleQuestionMarkEquals:
  1301. return parse_assignment_expression(AssignmentOp::NullishAssignment, move(lhs), min_precedence, associativity);
  1302. case TokenType::QuestionMark:
  1303. return parse_conditional_expression(move(lhs));
  1304. default:
  1305. expected("secondary expression");
  1306. consume();
  1307. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  1308. }
  1309. }
  1310. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(AssignmentOp assignment_op, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  1311. {
  1312. auto rule_start = push_start();
  1313. VERIFY(match(TokenType::Equals)
  1314. || match(TokenType::PlusEquals)
  1315. || match(TokenType::MinusEquals)
  1316. || match(TokenType::AsteriskEquals)
  1317. || match(TokenType::SlashEquals)
  1318. || match(TokenType::PercentEquals)
  1319. || match(TokenType::DoubleAsteriskEquals)
  1320. || match(TokenType::AmpersandEquals)
  1321. || match(TokenType::PipeEquals)
  1322. || match(TokenType::CaretEquals)
  1323. || match(TokenType::ShiftLeftEquals)
  1324. || match(TokenType::ShiftRightEquals)
  1325. || match(TokenType::UnsignedShiftRightEquals)
  1326. || match(TokenType::DoubleAmpersandEquals)
  1327. || match(TokenType::DoublePipeEquals)
  1328. || match(TokenType::DoubleQuestionMarkEquals));
  1329. consume();
  1330. if (assignment_op == AssignmentOp::Assignment) {
  1331. auto synthesize_binding_pattern = [this](Expression const& expression) -> RefPtr<BindingPattern> {
  1332. // Clear any syntax error that has occurred in the range that 'expression' spans.
  1333. m_state.errors.remove_all_matching([range = expression.source_range()](auto const& error) {
  1334. return error.position.has_value() && range.contains(*error.position);
  1335. });
  1336. // Make a parser and parse the source for this expression as a binding pattern.
  1337. auto source = m_state.lexer.source().substring_view(expression.source_range().start.offset - 2, expression.source_range().end.offset - expression.source_range().start.offset);
  1338. Lexer lexer { source, m_state.lexer.filename(), expression.source_range().start.line, expression.source_range().start.column };
  1339. Parser parser { lexer };
  1340. parser.m_state.strict_mode = m_state.strict_mode;
  1341. parser.m_state.allow_super_property_lookup = m_state.allow_super_property_lookup;
  1342. parser.m_state.allow_super_constructor_call = m_state.allow_super_constructor_call;
  1343. parser.m_state.in_function_context = m_state.in_function_context;
  1344. parser.m_state.in_generator_function_context = m_state.in_generator_function_context;
  1345. parser.m_state.in_arrow_function_context = m_state.in_arrow_function_context;
  1346. parser.m_state.in_break_context = m_state.in_break_context;
  1347. parser.m_state.in_continue_context = m_state.in_continue_context;
  1348. parser.m_state.string_legacy_octal_escape_sequence_in_scope = m_state.string_legacy_octal_escape_sequence_in_scope;
  1349. auto result = parser.parse_binding_pattern();
  1350. if (parser.has_errors())
  1351. m_state.errors.extend(parser.errors());
  1352. return result;
  1353. };
  1354. if (is<ArrayExpression>(*lhs) || is<ObjectExpression>(*lhs)) {
  1355. auto binding_pattern = synthesize_binding_pattern(*lhs);
  1356. if (binding_pattern) {
  1357. auto rhs = parse_expression(min_precedence, associativity);
  1358. return create_ast_node<AssignmentExpression>(
  1359. { m_state.current_token.filename(), rule_start.position(), position() },
  1360. assignment_op,
  1361. binding_pattern.release_nonnull(),
  1362. move(rhs));
  1363. }
  1364. }
  1365. }
  1366. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs) && !is<CallExpression>(*lhs)) {
  1367. syntax_error("Invalid left-hand side in assignment");
  1368. } else if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1369. auto name = static_cast<const Identifier&>(*lhs).string();
  1370. check_identifier_name_for_assignment_validity(name);
  1371. } else if (m_state.strict_mode && is<CallExpression>(*lhs)) {
  1372. syntax_error("Cannot assign to function call");
  1373. }
  1374. auto rhs = parse_expression(min_precedence, associativity);
  1375. if (assignment_op == AssignmentOp::Assignment && is<FunctionExpression>(*rhs)) {
  1376. auto ident = lhs;
  1377. if (is<MemberExpression>(*lhs)) {
  1378. ident = static_cast<MemberExpression&>(*lhs).property();
  1379. }
  1380. if (is<Identifier>(*ident))
  1381. static_cast<FunctionExpression&>(*rhs).set_name_if_possible(static_cast<Identifier&>(*ident).string());
  1382. }
  1383. return create_ast_node<AssignmentExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, assignment_op, move(lhs), move(rhs));
  1384. }
  1385. NonnullRefPtr<Identifier> Parser::parse_identifier()
  1386. {
  1387. auto identifier_start = position();
  1388. auto token = consume_identifier();
  1389. return create_ast_node<Identifier>(
  1390. { m_state.current_token.filename(), identifier_start, position() },
  1391. token.value());
  1392. }
  1393. NonnullRefPtr<CallExpression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  1394. {
  1395. auto rule_start = push_start();
  1396. if (!m_state.allow_super_constructor_call && is<SuperExpression>(*lhs))
  1397. syntax_error("'super' keyword unexpected here");
  1398. consume(TokenType::ParenOpen);
  1399. Vector<CallExpression::Argument> arguments;
  1400. while (match_expression() || match(TokenType::TripleDot)) {
  1401. if (match(TokenType::TripleDot)) {
  1402. consume();
  1403. arguments.append({ parse_expression(2), true });
  1404. } else {
  1405. arguments.append({ parse_expression(2), false });
  1406. }
  1407. if (!match(TokenType::Comma))
  1408. break;
  1409. consume();
  1410. }
  1411. consume(TokenType::ParenClose);
  1412. if (is<SuperExpression>(*lhs))
  1413. return create_ast_node<SuperCall>({ m_state.current_token.filename(), rule_start.position(), position() }, move(arguments));
  1414. return create_ast_node<CallExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), move(arguments));
  1415. }
  1416. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  1417. {
  1418. auto rule_start = push_start();
  1419. consume(TokenType::New);
  1420. auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen });
  1421. Vector<CallExpression::Argument> arguments;
  1422. if (match(TokenType::ParenOpen)) {
  1423. consume(TokenType::ParenOpen);
  1424. while (match_expression() || match(TokenType::TripleDot)) {
  1425. if (match(TokenType::TripleDot)) {
  1426. consume();
  1427. arguments.append({ parse_expression(2), true });
  1428. } else {
  1429. arguments.append({ parse_expression(2), false });
  1430. }
  1431. if (!match(TokenType::Comma))
  1432. break;
  1433. consume();
  1434. }
  1435. consume(TokenType::ParenClose);
  1436. }
  1437. return create_ast_node<NewExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(callee), move(arguments));
  1438. }
  1439. NonnullRefPtr<YieldExpression> Parser::parse_yield_expression()
  1440. {
  1441. auto rule_start = push_start();
  1442. consume(TokenType::Yield);
  1443. RefPtr<Expression> argument;
  1444. bool yield_from = false;
  1445. if (!m_state.current_token.trivia_contains_line_terminator()) {
  1446. if (match(TokenType::Asterisk)) {
  1447. consume();
  1448. yield_from = true;
  1449. }
  1450. if (yield_from || match_expression() || match(TokenType::Class))
  1451. argument = parse_expression(0);
  1452. }
  1453. return create_ast_node<YieldExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument), yield_from);
  1454. }
  1455. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  1456. {
  1457. auto rule_start = push_start();
  1458. if (!m_state.in_function_context && !m_state.in_arrow_function_context)
  1459. syntax_error("'return' not allowed outside of a function");
  1460. consume(TokenType::Return);
  1461. // Automatic semicolon insertion: terminate statement when return is followed by newline
  1462. if (m_state.current_token.trivia_contains_line_terminator())
  1463. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  1464. if (match_expression()) {
  1465. auto expression = parse_expression(0);
  1466. consume_or_insert_semicolon();
  1467. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  1468. }
  1469. consume_or_insert_semicolon();
  1470. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  1471. }
  1472. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  1473. {
  1474. auto rule_start = push_start();
  1475. bool dummy = false;
  1476. return parse_block_statement(dummy);
  1477. }
  1478. NonnullRefPtr<BlockStatement> Parser::parse_block_statement(bool& is_strict, bool error_on_binding)
  1479. {
  1480. auto rule_start = push_start();
  1481. ScopePusher scope(*this, ScopePusher::Let, Parser::Scope::Block);
  1482. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  1483. consume(TokenType::CurlyOpen);
  1484. bool initial_strict_mode_state = m_state.strict_mode;
  1485. if (initial_strict_mode_state)
  1486. is_strict = true;
  1487. bool parsing_directives = true;
  1488. while (!done() && !match(TokenType::CurlyClose)) {
  1489. if (match_declaration()) {
  1490. block->append(parse_declaration());
  1491. parsing_directives = false;
  1492. } else if (match_statement()) {
  1493. auto statement = parse_statement(AllowLabelledFunction::Yes);
  1494. block->append(statement);
  1495. if (statement_is_use_strict_directive(statement)) {
  1496. if (parsing_directives) {
  1497. if (!initial_strict_mode_state) {
  1498. is_strict = true;
  1499. m_state.strict_mode = true;
  1500. }
  1501. }
  1502. if (m_state.string_legacy_octal_escape_sequence_in_scope)
  1503. syntax_error("Octal escape sequence in string literal not allowed in strict mode");
  1504. if (error_on_binding) {
  1505. syntax_error("Illegal 'use strict' directive in function with non-simple parameter list");
  1506. }
  1507. }
  1508. if (parsing_directives && is<ExpressionStatement>(*statement)) {
  1509. auto& expression_statement = static_cast<ExpressionStatement&>(*statement);
  1510. auto& expression = expression_statement.expression();
  1511. parsing_directives = is<StringLiteral>(expression);
  1512. } else {
  1513. parsing_directives = false;
  1514. }
  1515. } else {
  1516. expected("statement or declaration");
  1517. consume();
  1518. parsing_directives = false;
  1519. }
  1520. }
  1521. m_state.strict_mode = initial_strict_mode_state;
  1522. m_state.string_legacy_octal_escape_sequence_in_scope = false;
  1523. consume(TokenType::CurlyClose);
  1524. scope.add_to_scope_node(block);
  1525. return block;
  1526. }
  1527. template<typename FunctionNodeType>
  1528. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(u8 parse_options)
  1529. {
  1530. auto rule_start = push_start();
  1531. VERIFY(!(parse_options & FunctionNodeParseOptions::IsGetterFunction && parse_options & FunctionNodeParseOptions::IsSetterFunction));
  1532. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, !!(parse_options & FunctionNodeParseOptions::AllowSuperPropertyLookup));
  1533. TemporaryChange super_constructor_call_rollback(m_state.allow_super_constructor_call, !!(parse_options & FunctionNodeParseOptions::AllowSuperConstructorCall));
  1534. TemporaryChange break_context_rollback(m_state.in_break_context, false);
  1535. TemporaryChange continue_context_rollback(m_state.in_continue_context, false);
  1536. ScopePusher scope(*this, ScopePusher::Var, Parser::Scope::Function);
  1537. constexpr auto is_function_expression = IsSame<FunctionNodeType, FunctionExpression>;
  1538. auto is_generator = (parse_options & FunctionNodeParseOptions::IsGeneratorFunction) != 0;
  1539. String name;
  1540. if (parse_options & FunctionNodeParseOptions::CheckForFunctionAndName) {
  1541. consume(TokenType::Function);
  1542. if (!is_generator) {
  1543. is_generator = match(TokenType::Asterisk);
  1544. if (is_generator) {
  1545. consume(TokenType::Asterisk);
  1546. parse_options = parse_options | FunctionNodeParseOptions::IsGeneratorFunction;
  1547. }
  1548. }
  1549. if (FunctionNodeType::must_have_name() || match_identifier())
  1550. name = consume_identifier().value();
  1551. else if (is_function_expression && (match(TokenType::Yield) || match(TokenType::Await)))
  1552. name = consume().value();
  1553. check_identifier_name_for_assignment_validity(name);
  1554. }
  1555. TemporaryChange generator_change(m_state.in_generator_function_context, is_generator);
  1556. consume(TokenType::ParenOpen);
  1557. i32 function_length = -1;
  1558. auto parameters = parse_formal_parameters(function_length, parse_options);
  1559. consume(TokenType::ParenClose);
  1560. if (function_length == -1)
  1561. function_length = parameters.size();
  1562. TemporaryChange change(m_state.in_function_context, true);
  1563. auto old_labels_in_scope = move(m_state.labels_in_scope);
  1564. ScopeGuard guard([&]() {
  1565. m_state.labels_in_scope = move(old_labels_in_scope);
  1566. });
  1567. m_state.function_parameters.append(parameters);
  1568. bool has_binding = any_of(parameters, [](FunctionNode::Parameter const& parameter) {
  1569. return parameter.binding.has<NonnullRefPtr<BindingPattern>>();
  1570. });
  1571. bool is_strict = false;
  1572. auto body = parse_block_statement(is_strict, has_binding);
  1573. // If the function contains 'use strict' we need to check the parameters (again).
  1574. if (is_strict || is_generator) {
  1575. Vector<StringView> parameter_names;
  1576. for (auto& parameter : parameters) {
  1577. parameter.binding.visit(
  1578. [&](FlyString const& parameter_name) {
  1579. check_identifier_name_for_assignment_validity(parameter_name, is_strict);
  1580. if (is_generator && parameter_name == "yield"sv)
  1581. syntax_error("Parameter name 'yield' not allowed in this context");
  1582. for (auto& previous_name : parameter_names) {
  1583. if (previous_name == parameter_name) {
  1584. syntax_error(String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name));
  1585. }
  1586. }
  1587. parameter_names.append(parameter_name);
  1588. },
  1589. [&](NonnullRefPtr<BindingPattern> const& binding) {
  1590. binding->for_each_bound_name([&](auto& bound_name) {
  1591. if (is_generator && bound_name == "yield"sv)
  1592. syntax_error("Parameter name 'yield' not allowed in this context");
  1593. for (auto& previous_name : parameter_names) {
  1594. if (previous_name == bound_name) {
  1595. syntax_error(String::formatted("Duplicate parameter '{}' not allowed in strict mode", bound_name));
  1596. break;
  1597. }
  1598. }
  1599. parameter_names.append(bound_name);
  1600. });
  1601. });
  1602. }
  1603. check_identifier_name_for_assignment_validity(name, is_strict);
  1604. }
  1605. m_state.function_parameters.take_last();
  1606. scope.add_to_scope_node(body);
  1607. return create_ast_node<FunctionNodeType>(
  1608. { m_state.current_token.filename(), rule_start.position(), position() },
  1609. name, move(body), move(parameters), function_length,
  1610. is_generator ? FunctionKind::Generator : FunctionKind::Regular, is_strict);
  1611. }
  1612. Vector<FunctionNode::Parameter> Parser::parse_formal_parameters(int& function_length, u8 parse_options)
  1613. {
  1614. auto rule_start = push_start();
  1615. bool has_default_parameter = false;
  1616. bool has_rest_parameter = false;
  1617. Vector<FunctionNode::Parameter> parameters;
  1618. auto consume_identifier_or_binding_pattern = [&]() -> Variant<FlyString, NonnullRefPtr<BindingPattern>> {
  1619. if (auto pattern = parse_binding_pattern(true))
  1620. return pattern.release_nonnull();
  1621. auto token = consume_identifier();
  1622. auto parameter_name = token.value();
  1623. check_identifier_name_for_assignment_validity(parameter_name);
  1624. for (auto& parameter : parameters) {
  1625. bool has_same_name = parameter.binding.visit(
  1626. [&](FlyString const& name) {
  1627. return name == parameter_name;
  1628. },
  1629. [&](NonnullRefPtr<BindingPattern> const& bindings) {
  1630. bool found_duplicate = false;
  1631. bindings->for_each_bound_name([&](auto& bound_name) {
  1632. if (bound_name == parameter_name)
  1633. found_duplicate = true;
  1634. });
  1635. return found_duplicate;
  1636. });
  1637. if (!has_same_name)
  1638. continue;
  1639. String message;
  1640. if (parse_options & FunctionNodeParseOptions::IsArrowFunction)
  1641. message = String::formatted("Duplicate parameter '{}' not allowed in arrow function", parameter_name);
  1642. else if (m_state.strict_mode)
  1643. message = String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name);
  1644. else if (has_default_parameter || match(TokenType::Equals))
  1645. message = String::formatted("Duplicate parameter '{}' not allowed in function with default parameter", parameter_name);
  1646. else if (has_rest_parameter)
  1647. message = String::formatted("Duplicate parameter '{}' not allowed in function with rest parameter", parameter_name);
  1648. if (!message.is_empty())
  1649. syntax_error(message, Position { token.line_number(), token.line_column() });
  1650. break;
  1651. }
  1652. return FlyString { token.value() };
  1653. };
  1654. while (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen) || match_identifier() || match(TokenType::TripleDot)) {
  1655. if (parse_options & FunctionNodeParseOptions::IsGetterFunction)
  1656. syntax_error("Getter function must have no arguments");
  1657. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && (parameters.size() >= 1 || match(TokenType::TripleDot)))
  1658. syntax_error("Setter function must have one argument");
  1659. auto is_rest = false;
  1660. if (match(TokenType::TripleDot)) {
  1661. consume();
  1662. has_rest_parameter = true;
  1663. function_length = parameters.size();
  1664. is_rest = true;
  1665. }
  1666. auto parameter = consume_identifier_or_binding_pattern();
  1667. RefPtr<Expression> default_value;
  1668. if (match(TokenType::Equals)) {
  1669. consume();
  1670. if (is_rest)
  1671. syntax_error("Rest parameter may not have a default initializer");
  1672. TemporaryChange change(m_state.in_function_context, true);
  1673. has_default_parameter = true;
  1674. function_length = parameters.size();
  1675. default_value = parse_expression(2);
  1676. bool is_generator = parse_options & FunctionNodeParseOptions::IsGeneratorFunction;
  1677. if ((is_generator || m_state.strict_mode) && default_value && default_value->fast_is<Identifier>() && static_cast<Identifier&>(*default_value).string() == "yield"sv)
  1678. syntax_error("Generator function parameter initializer cannot contain a reference to an identifier named \"yield\"");
  1679. if (default_value && is<YieldExpression>(*default_value))
  1680. syntax_error("Yield expression not allowed in formal parameter");
  1681. }
  1682. parameters.append({ move(parameter), default_value, is_rest });
  1683. if (match(TokenType::ParenClose))
  1684. break;
  1685. consume(TokenType::Comma);
  1686. if (is_rest)
  1687. break;
  1688. }
  1689. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && parameters.is_empty())
  1690. syntax_error("Setter function must have one argument");
  1691. return parameters;
  1692. }
  1693. 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" };
  1694. RefPtr<BindingPattern> Parser::parse_binding_pattern(bool strict_checks)
  1695. {
  1696. auto rule_start = push_start();
  1697. TokenType closing_token;
  1698. bool is_object = true;
  1699. if (match(TokenType::BracketOpen)) {
  1700. consume();
  1701. closing_token = TokenType::BracketClose;
  1702. is_object = false;
  1703. } else if (match(TokenType::CurlyOpen)) {
  1704. consume();
  1705. closing_token = TokenType::CurlyClose;
  1706. } else {
  1707. return {};
  1708. }
  1709. Vector<BindingPattern::BindingEntry> entries;
  1710. while (!match(closing_token)) {
  1711. if (!is_object && match(TokenType::Comma)) {
  1712. consume();
  1713. entries.append(BindingPattern::BindingEntry {});
  1714. continue;
  1715. }
  1716. auto is_rest = false;
  1717. if (match(TokenType::TripleDot)) {
  1718. consume();
  1719. is_rest = true;
  1720. }
  1721. decltype(BindingPattern::BindingEntry::name) name = Empty {};
  1722. decltype(BindingPattern::BindingEntry::alias) alias = Empty {};
  1723. RefPtr<Expression> initializer = {};
  1724. if (is_object) {
  1725. if (match_identifier_name()) {
  1726. name = create_ast_node<Identifier>(
  1727. { m_state.current_token.filename(), rule_start.position(), position() },
  1728. consume().value());
  1729. } else if (match(TokenType::BracketOpen)) {
  1730. consume();
  1731. auto expression = parse_expression(0);
  1732. if (strict_checks && m_state.in_generator_function_context && is<YieldExpression>(*expression))
  1733. syntax_error("Yield expression not allowed in formal parameter within generator context");
  1734. name = move(expression);
  1735. consume(TokenType::BracketClose);
  1736. } else {
  1737. expected("identifier or computed property name");
  1738. return {};
  1739. }
  1740. if (!is_rest && match(TokenType::Colon)) {
  1741. consume();
  1742. if (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen)) {
  1743. auto binding_pattern = parse_binding_pattern(strict_checks);
  1744. if (!binding_pattern)
  1745. return {};
  1746. alias = binding_pattern.release_nonnull();
  1747. } else if (match_identifier_name()) {
  1748. alias = create_ast_node<Identifier>(
  1749. { m_state.current_token.filename(), rule_start.position(), position() },
  1750. consume_identifier().value());
  1751. if (strict_checks && match(TokenType::BracketOpen))
  1752. syntax_error("Illegal property in declaration context");
  1753. } else {
  1754. expected("identifier or binding pattern");
  1755. return {};
  1756. }
  1757. }
  1758. } else {
  1759. if (match_identifier_name()) {
  1760. // BindingElement must always have an Empty name field
  1761. auto identifier_name = consume_identifier().value();
  1762. alias = create_ast_node<Identifier>(
  1763. { m_state.current_token.filename(), rule_start.position(), position() },
  1764. identifier_name);
  1765. if (strict_checks) {
  1766. for (auto& entry : entries) {
  1767. if (entry.alias.has<NonnullRefPtr<Identifier>>()) {
  1768. if (entry.alias.get<NonnullRefPtr<Identifier>>()->string() == identifier_name)
  1769. syntax_error("Duplicate parameter names in bindings");
  1770. }
  1771. }
  1772. }
  1773. } else if (match(TokenType::BracketOpen) || match(TokenType::CurlyOpen)) {
  1774. auto pattern = parse_binding_pattern(strict_checks);
  1775. if (!pattern) {
  1776. expected("binding pattern");
  1777. return {};
  1778. }
  1779. alias = pattern.release_nonnull();
  1780. } else {
  1781. expected("identifier or binding pattern");
  1782. return {};
  1783. }
  1784. }
  1785. if (match(TokenType::Equals)) {
  1786. if (is_rest) {
  1787. syntax_error("Unexpected initializer after rest element");
  1788. return {};
  1789. }
  1790. consume();
  1791. initializer = parse_expression(2);
  1792. if (!initializer) {
  1793. expected("initialization expression");
  1794. return {};
  1795. }
  1796. if (strict_checks && is<YieldExpression>(*initializer))
  1797. syntax_error("Yield expression is not allow in formal parameter");
  1798. }
  1799. entries.append(BindingPattern::BindingEntry { move(name), move(alias), move(initializer), is_rest });
  1800. if (match(TokenType::Comma)) {
  1801. if (is_rest) {
  1802. syntax_error("Rest element may not be followed by a comma");
  1803. return {};
  1804. }
  1805. consume();
  1806. }
  1807. }
  1808. while (!is_object && match(TokenType::Comma))
  1809. consume();
  1810. consume(closing_token);
  1811. auto kind = is_object ? BindingPattern::Kind::Object : BindingPattern::Kind::Array;
  1812. auto pattern = adopt_ref(*new BindingPattern);
  1813. pattern->entries = move(entries);
  1814. pattern->kind = kind;
  1815. Vector<StringView> bound_names;
  1816. pattern->for_each_bound_name([&](auto& name) {
  1817. if (strict_checks) {
  1818. if (bound_names.contains_slow(name))
  1819. syntax_error("Duplicate parameter names in bindings");
  1820. bound_names.append(name);
  1821. }
  1822. check_identifier_name_for_assignment_validity(name);
  1823. });
  1824. return pattern;
  1825. }
  1826. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool for_loop_variable_declaration)
  1827. {
  1828. auto rule_start = push_start();
  1829. DeclarationKind declaration_kind;
  1830. switch (m_state.current_token.type()) {
  1831. case TokenType::Var:
  1832. declaration_kind = DeclarationKind::Var;
  1833. break;
  1834. case TokenType::Let:
  1835. declaration_kind = DeclarationKind::Let;
  1836. break;
  1837. case TokenType::Const:
  1838. declaration_kind = DeclarationKind::Const;
  1839. break;
  1840. default:
  1841. VERIFY_NOT_REACHED();
  1842. }
  1843. consume();
  1844. NonnullRefPtrVector<VariableDeclarator> declarations;
  1845. for (;;) {
  1846. Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>, Empty> target { Empty() };
  1847. if (match_identifier()) {
  1848. auto identifier_start = push_start();
  1849. auto name = consume_identifier().value();
  1850. target = create_ast_node<Identifier>(
  1851. { m_state.current_token.filename(), rule_start.position(), position() },
  1852. name);
  1853. check_identifier_name_for_assignment_validity(name);
  1854. if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const) && name == "let"sv)
  1855. syntax_error("Lexical binding may not be called 'let'");
  1856. // Check we do not have duplicates
  1857. auto check_declarations = [&](VariableDeclarator const& declarator) {
  1858. declarator.target().visit([&](NonnullRefPtr<Identifier> const& identifier) {
  1859. if (identifier->string() == name)
  1860. syntax_error(String::formatted("Identifier '{}' has already been declared", name), identifier_start.position()); },
  1861. [&](auto const&) {});
  1862. };
  1863. // In any previous let scope
  1864. if (!m_state.let_scopes.is_empty()) {
  1865. for (auto& decls : m_state.let_scopes.last()) {
  1866. for (auto& decl : decls.declarations()) {
  1867. check_declarations(decl);
  1868. }
  1869. }
  1870. }
  1871. // or this declaration
  1872. if (declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const) {
  1873. // FIXME: We should check the var_scopes here as well however this has edges cases with for loops.
  1874. // See duplicated-variable-declarations.js.
  1875. if (!m_state.function_parameters.is_empty() && m_state.current_scope->parent->type == Scope::Function) {
  1876. for (auto& parameter : m_state.function_parameters.last()) {
  1877. parameter.binding.visit(
  1878. [&](FlyString const& parameter_name) {
  1879. if (parameter_name == name)
  1880. syntax_error(String::formatted("Identifier '{}' has already been declared", name), identifier_start.position());
  1881. },
  1882. [&](NonnullRefPtr<BindingPattern> const& binding) {
  1883. binding->for_each_bound_name([&](auto& bound_name) {
  1884. if (bound_name == name)
  1885. syntax_error(String::formatted("Identifier '{}' has already been declared", name), identifier_start.position());
  1886. });
  1887. });
  1888. }
  1889. }
  1890. for (auto& declaration : declarations) {
  1891. check_declarations(declaration);
  1892. }
  1893. }
  1894. } else if (auto pattern = parse_binding_pattern(declaration_kind != DeclarationKind::Var)) {
  1895. target = pattern.release_nonnull();
  1896. if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const)) {
  1897. target.get<NonnullRefPtr<BindingPattern>>()->for_each_bound_name([this, &declarations](auto& name) {
  1898. if (name == "let"sv)
  1899. syntax_error("Lexical binding may not be called 'let'");
  1900. // FIXME: Again we do not check everything here see for example the parameter check above.
  1901. // However a more sustainable solution should be used since these checks are now spread over multiple sites.
  1902. for (auto& declaration : declarations) {
  1903. declaration.target().visit(
  1904. [&](NonnullRefPtr<Identifier> const& identifier) {
  1905. if (identifier->string() == name)
  1906. syntax_error(String::formatted("Identifier '{}' has already been declared", name));
  1907. },
  1908. [&](auto const&) {});
  1909. }
  1910. });
  1911. }
  1912. } else if (!m_state.in_generator_function_context && match(TokenType::Yield)) {
  1913. if (m_state.strict_mode)
  1914. syntax_error("Identifier must not be a reserved word in strict mode ('yield')");
  1915. target = create_ast_node<Identifier>(
  1916. { m_state.current_token.filename(), rule_start.position(), position() },
  1917. consume().value());
  1918. }
  1919. if (target.has<Empty>()) {
  1920. expected("identifier or a binding pattern");
  1921. if (match(TokenType::Comma)) {
  1922. consume();
  1923. continue;
  1924. }
  1925. break;
  1926. }
  1927. RefPtr<Expression> init;
  1928. if (match(TokenType::Equals)) {
  1929. consume();
  1930. init = parse_expression(2);
  1931. } else if (!for_loop_variable_declaration && declaration_kind == DeclarationKind::Const) {
  1932. syntax_error("Missing initializer in 'const' variable declaration");
  1933. } else if (!for_loop_variable_declaration && target.has<NonnullRefPtr<BindingPattern>>()) {
  1934. syntax_error("Missing initializer in destructuring assignment");
  1935. }
  1936. if (init && is<FunctionExpression>(*init) && target.has<NonnullRefPtr<Identifier>>()) {
  1937. static_cast<FunctionExpression&>(*init).set_name_if_possible(target.get<NonnullRefPtr<Identifier>>()->string());
  1938. }
  1939. declarations.append(create_ast_node<VariableDeclarator>(
  1940. { m_state.current_token.filename(), rule_start.position(), position() },
  1941. move(target).downcast<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>(),
  1942. move(init)));
  1943. if (match(TokenType::Comma)) {
  1944. consume();
  1945. continue;
  1946. }
  1947. break;
  1948. }
  1949. if (!for_loop_variable_declaration)
  1950. consume_or_insert_semicolon();
  1951. auto declaration = create_ast_node<VariableDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() }, declaration_kind, move(declarations));
  1952. if (declaration_kind == DeclarationKind::Var) {
  1953. m_state.var_scopes.last().append(declaration);
  1954. } else {
  1955. m_state.let_scopes.last().append(declaration);
  1956. for (auto& declarator : declaration->declarations()) {
  1957. declarator.target().visit(
  1958. [&](const NonnullRefPtr<Identifier>& id) {
  1959. m_state.current_scope->lexical_declarations.set(id->string());
  1960. },
  1961. [&](const NonnullRefPtr<BindingPattern>& binding) {
  1962. binding->for_each_bound_name([&](const auto& name) {
  1963. m_state.current_scope->lexical_declarations.set(name);
  1964. });
  1965. });
  1966. }
  1967. }
  1968. return declaration;
  1969. }
  1970. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  1971. {
  1972. auto rule_start = push_start();
  1973. consume(TokenType::Throw);
  1974. // Automatic semicolon insertion: terminate statement when throw is followed by newline
  1975. if (m_state.current_token.trivia_contains_line_terminator()) {
  1976. syntax_error("No line break is allowed between 'throw' and its expression");
  1977. 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() }));
  1978. }
  1979. auto expression = parse_expression(0);
  1980. consume_or_insert_semicolon();
  1981. return create_ast_node<ThrowStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  1982. }
  1983. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  1984. {
  1985. auto rule_start = push_start();
  1986. consume(TokenType::Break);
  1987. FlyString target_label;
  1988. if (match(TokenType::Semicolon)) {
  1989. consume();
  1990. } else {
  1991. if (match(TokenType::Identifier) && !m_state.current_token.trivia_contains_line_terminator()) {
  1992. target_label = consume().value();
  1993. if (!m_state.labels_in_scope.contains(target_label))
  1994. syntax_error(String::formatted("Label '{}' not found", target_label));
  1995. }
  1996. consume_or_insert_semicolon();
  1997. }
  1998. if (target_label.is_null() && !m_state.in_break_context)
  1999. syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement");
  2000. return create_ast_node<BreakStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2001. }
  2002. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  2003. {
  2004. auto rule_start = push_start();
  2005. if (!m_state.in_continue_context)
  2006. syntax_error("'continue' not allow outside of a loop");
  2007. consume(TokenType::Continue);
  2008. FlyString target_label;
  2009. if (match(TokenType::Semicolon)) {
  2010. consume();
  2011. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2012. }
  2013. if (match(TokenType::Identifier) && !m_state.current_token.trivia_contains_line_terminator()) {
  2014. target_label = consume().value();
  2015. if (!m_state.labels_in_scope.contains(target_label))
  2016. syntax_error(String::formatted("Label '{}' not found", target_label));
  2017. }
  2018. consume_or_insert_semicolon();
  2019. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2020. }
  2021. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test)
  2022. {
  2023. auto rule_start = push_start();
  2024. consume(TokenType::QuestionMark);
  2025. auto consequent = parse_expression(2);
  2026. consume(TokenType::Colon);
  2027. auto alternate = parse_expression(2);
  2028. return create_ast_node<ConditionalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(consequent), move(alternate));
  2029. }
  2030. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  2031. {
  2032. auto rule_start = push_start();
  2033. consume(TokenType::Try);
  2034. auto block = parse_block_statement();
  2035. RefPtr<CatchClause> handler;
  2036. if (match(TokenType::Catch))
  2037. handler = parse_catch_clause();
  2038. RefPtr<BlockStatement> finalizer;
  2039. if (match(TokenType::Finally)) {
  2040. consume();
  2041. finalizer = parse_block_statement();
  2042. }
  2043. if (!handler && !finalizer)
  2044. syntax_error("try statement must have a 'catch' or 'finally' clause");
  2045. return create_ast_node<TryStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(block), move(handler), move(finalizer));
  2046. }
  2047. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  2048. {
  2049. auto rule_start = push_start();
  2050. consume(TokenType::Do);
  2051. auto body = [&]() -> NonnullRefPtr<Statement> {
  2052. TemporaryChange break_change(m_state.in_break_context, true);
  2053. TemporaryChange continue_change(m_state.in_continue_context, true);
  2054. return parse_statement();
  2055. }();
  2056. consume(TokenType::While);
  2057. consume(TokenType::ParenOpen);
  2058. auto test = parse_expression(0);
  2059. consume(TokenType::ParenClose);
  2060. // Since ES 2015 a missing semicolon is inserted here, despite the regular ASI rules not applying
  2061. if (match(TokenType::Semicolon))
  2062. consume();
  2063. return create_ast_node<DoWhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  2064. }
  2065. NonnullRefPtr<WhileStatement> Parser::parse_while_statement()
  2066. {
  2067. auto rule_start = push_start();
  2068. consume(TokenType::While);
  2069. consume(TokenType::ParenOpen);
  2070. auto test = parse_expression(0);
  2071. consume(TokenType::ParenClose);
  2072. TemporaryChange break_change(m_state.in_break_context, true);
  2073. TemporaryChange continue_change(m_state.in_continue_context, true);
  2074. auto body = parse_statement();
  2075. return create_ast_node<WhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  2076. }
  2077. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  2078. {
  2079. auto rule_start = push_start();
  2080. consume(TokenType::Switch);
  2081. consume(TokenType::ParenOpen);
  2082. auto determinant = parse_expression(0);
  2083. consume(TokenType::ParenClose);
  2084. consume(TokenType::CurlyOpen);
  2085. NonnullRefPtrVector<SwitchCase> cases;
  2086. auto has_default = false;
  2087. while (match(TokenType::Case) || match(TokenType::Default)) {
  2088. if (match(TokenType::Default)) {
  2089. if (has_default)
  2090. syntax_error("Multiple 'default' clauses in switch statement");
  2091. has_default = true;
  2092. }
  2093. cases.append(parse_switch_case());
  2094. }
  2095. consume(TokenType::CurlyClose);
  2096. return create_ast_node<SwitchStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(determinant), move(cases));
  2097. }
  2098. NonnullRefPtr<WithStatement> Parser::parse_with_statement()
  2099. {
  2100. auto rule_start = push_start();
  2101. consume(TokenType::With);
  2102. consume(TokenType::ParenOpen);
  2103. auto object = parse_expression(0);
  2104. consume(TokenType::ParenClose);
  2105. auto body = parse_statement();
  2106. return create_ast_node<WithStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(object), move(body));
  2107. }
  2108. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  2109. {
  2110. auto rule_start = push_start();
  2111. RefPtr<Expression> test;
  2112. if (consume().type() == TokenType::Case) {
  2113. test = parse_expression(0);
  2114. }
  2115. consume(TokenType::Colon);
  2116. NonnullRefPtrVector<Statement> consequent;
  2117. TemporaryChange break_change(m_state.in_break_context, true);
  2118. for (;;) {
  2119. if (match_declaration())
  2120. consequent.append(parse_declaration());
  2121. else if (match_statement())
  2122. consequent.append(parse_statement());
  2123. else
  2124. break;
  2125. }
  2126. return create_ast_node<SwitchCase>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(consequent));
  2127. }
  2128. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  2129. {
  2130. auto rule_start = push_start();
  2131. consume(TokenType::Catch);
  2132. FlyString parameter;
  2133. RefPtr<BindingPattern> pattern_parameter;
  2134. auto should_expect_parameter = false;
  2135. if (match(TokenType::ParenOpen)) {
  2136. should_expect_parameter = true;
  2137. consume();
  2138. if (match_identifier_name() && (!match(TokenType::Yield) || !m_state.in_generator_function_context))
  2139. parameter = consume().value();
  2140. else
  2141. pattern_parameter = parse_binding_pattern(true);
  2142. consume(TokenType::ParenClose);
  2143. }
  2144. if (should_expect_parameter && parameter.is_empty() && !pattern_parameter)
  2145. expected("an identifier or a binding pattern");
  2146. if (pattern_parameter)
  2147. pattern_parameter->for_each_bound_name([this](auto& name) { check_identifier_name_for_assignment_validity(name); });
  2148. if (!parameter.is_empty())
  2149. check_identifier_name_for_assignment_validity(parameter);
  2150. auto body = parse_block_statement();
  2151. if (pattern_parameter) {
  2152. return create_ast_node<CatchClause>(
  2153. { m_state.current_token.filename(), rule_start.position(), position() },
  2154. pattern_parameter.release_nonnull(),
  2155. move(body));
  2156. }
  2157. return create_ast_node<CatchClause>(
  2158. { m_state.current_token.filename(), rule_start.position(), position() },
  2159. move(parameter),
  2160. move(body));
  2161. }
  2162. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  2163. {
  2164. auto rule_start = push_start();
  2165. auto parse_function_declaration_as_block_statement = [&] {
  2166. // https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses
  2167. // Code matching this production is processed as if each matching occurrence of
  2168. // FunctionDeclaration[?Yield, ?Await, ~Default] was the sole StatementListItem
  2169. // of a BlockStatement occupying that position in the source code.
  2170. ScopePusher scope(*this, ScopePusher::Let, Parser::Scope::Block);
  2171. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  2172. block->append(parse_declaration());
  2173. scope.add_to_scope_node(block);
  2174. return block;
  2175. };
  2176. consume(TokenType::If);
  2177. consume(TokenType::ParenOpen);
  2178. auto predicate = parse_expression(0);
  2179. consume(TokenType::ParenClose);
  2180. RefPtr<Statement> consequent;
  2181. if (!m_state.strict_mode && match(TokenType::Function))
  2182. consequent = parse_function_declaration_as_block_statement();
  2183. else
  2184. consequent = parse_statement();
  2185. RefPtr<Statement> alternate;
  2186. if (match(TokenType::Else)) {
  2187. consume();
  2188. if (!m_state.strict_mode && match(TokenType::Function))
  2189. alternate = parse_function_declaration_as_block_statement();
  2190. else
  2191. alternate = parse_statement();
  2192. }
  2193. return create_ast_node<IfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(predicate), move(*consequent), move(alternate));
  2194. }
  2195. NonnullRefPtr<Statement> Parser::parse_for_statement()
  2196. {
  2197. auto rule_start = push_start();
  2198. auto match_for_in_of = [&]() {
  2199. return match(TokenType::In) || (match(TokenType::Identifier) && m_state.current_token.value() == "of");
  2200. };
  2201. consume(TokenType::For);
  2202. consume(TokenType::ParenOpen);
  2203. bool in_scope = false;
  2204. ScopeGuard guard([&]() {
  2205. if (in_scope)
  2206. m_state.let_scopes.take_last();
  2207. });
  2208. RefPtr<ASTNode> init;
  2209. if (!match(TokenType::Semicolon)) {
  2210. if (match_variable_declaration()) {
  2211. if (!match(TokenType::Var)) {
  2212. m_state.let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  2213. in_scope = true;
  2214. }
  2215. init = parse_variable_declaration(true);
  2216. if (match_for_in_of())
  2217. return parse_for_in_of_statement(*init);
  2218. if (static_cast<VariableDeclaration&>(*init).declaration_kind() == DeclarationKind::Const) {
  2219. for (auto& declaration : static_cast<VariableDeclaration&>(*init).declarations()) {
  2220. if (!declaration.init())
  2221. syntax_error("Missing initializer in 'const' variable declaration");
  2222. }
  2223. }
  2224. } else if (match_expression()) {
  2225. init = parse_expression(0, Associativity::Right, { TokenType::In });
  2226. if (match_for_in_of())
  2227. return parse_for_in_of_statement(*init);
  2228. } else {
  2229. syntax_error("Unexpected token in for loop");
  2230. }
  2231. }
  2232. consume(TokenType::Semicolon);
  2233. RefPtr<Expression> test;
  2234. if (!match(TokenType::Semicolon))
  2235. test = parse_expression(0);
  2236. consume(TokenType::Semicolon);
  2237. RefPtr<Expression> update;
  2238. if (!match(TokenType::ParenClose))
  2239. update = parse_expression(0);
  2240. consume(TokenType::ParenClose);
  2241. TemporaryChange break_change(m_state.in_break_context, true);
  2242. TemporaryChange continue_change(m_state.in_continue_context, true);
  2243. auto body = parse_statement();
  2244. return create_ast_node<ForStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(init), move(test), move(update), move(body));
  2245. }
  2246. NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs)
  2247. {
  2248. auto rule_start = push_start();
  2249. if (is<VariableDeclaration>(*lhs)) {
  2250. auto declarations = static_cast<VariableDeclaration&>(*lhs).declarations();
  2251. if (declarations.size() > 1)
  2252. syntax_error("multiple declarations not allowed in for..in/of");
  2253. if (declarations.size() < 1)
  2254. syntax_error("need exactly one variable declaration in for..in/of");
  2255. else if (declarations.first().init() != nullptr)
  2256. syntax_error("variable initializer not allowed in for..in/of");
  2257. } else if (!lhs->is_identifier() && !is<ObjectExpression>(*lhs) && !is<MemberExpression>(*lhs) && !is<ArrayExpression>(*lhs)) {
  2258. syntax_error(String::formatted("Invalid left-hand side in for-loop ('{}')", lhs->class_name()));
  2259. }
  2260. auto in_or_of = consume();
  2261. if (in_or_of.type() != TokenType::In) {
  2262. if (is<MemberExpression>(*lhs)) {
  2263. auto& member = static_cast<MemberExpression const&>(*lhs);
  2264. if (member.object().is_identifier() && static_cast<Identifier const&>(member.object()).string() == "let"sv)
  2265. syntax_error("For of statement may not start with let.");
  2266. }
  2267. }
  2268. auto rhs = parse_expression(0);
  2269. consume(TokenType::ParenClose);
  2270. TemporaryChange break_change(m_state.in_break_context, true);
  2271. TemporaryChange continue_change(m_state.in_continue_context, true);
  2272. auto body = parse_statement();
  2273. if (in_or_of.type() == TokenType::In)
  2274. return create_ast_node<ForInStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), move(rhs), move(body));
  2275. return create_ast_node<ForOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), move(rhs), move(body));
  2276. }
  2277. NonnullRefPtr<DebuggerStatement> Parser::parse_debugger_statement()
  2278. {
  2279. auto rule_start = push_start();
  2280. consume(TokenType::Debugger);
  2281. consume_or_insert_semicolon();
  2282. return create_ast_node<DebuggerStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  2283. }
  2284. bool Parser::match(TokenType type) const
  2285. {
  2286. return m_state.current_token.type() == type;
  2287. }
  2288. bool Parser::match_expression() const
  2289. {
  2290. auto type = m_state.current_token.type();
  2291. return type == TokenType::BoolLiteral
  2292. || type == TokenType::NumericLiteral
  2293. || type == TokenType::BigIntLiteral
  2294. || type == TokenType::StringLiteral
  2295. || type == TokenType::TemplateLiteralStart
  2296. || type == TokenType::NullLiteral
  2297. || match_identifier()
  2298. || type == TokenType::New
  2299. || type == TokenType::CurlyOpen
  2300. || type == TokenType::BracketOpen
  2301. || type == TokenType::ParenOpen
  2302. || type == TokenType::Function
  2303. || type == TokenType::This
  2304. || type == TokenType::Super
  2305. || type == TokenType::RegexLiteral
  2306. || type == TokenType::Slash // Wrongly recognized regex by lexer
  2307. || type == TokenType::SlashEquals // Wrongly recognized regex by lexer (/=a/ is a valid regex)
  2308. || type == TokenType::Yield
  2309. || match_unary_prefixed_expression();
  2310. }
  2311. bool Parser::match_unary_prefixed_expression() const
  2312. {
  2313. auto type = m_state.current_token.type();
  2314. return type == TokenType::PlusPlus
  2315. || type == TokenType::MinusMinus
  2316. || type == TokenType::ExclamationMark
  2317. || type == TokenType::Tilde
  2318. || type == TokenType::Plus
  2319. || type == TokenType::Minus
  2320. || type == TokenType::Typeof
  2321. || type == TokenType::Void
  2322. || type == TokenType::Delete;
  2323. }
  2324. bool Parser::match_secondary_expression(const Vector<TokenType>& forbidden) const
  2325. {
  2326. auto type = m_state.current_token.type();
  2327. if (forbidden.contains_slow(type))
  2328. return false;
  2329. return type == TokenType::Plus
  2330. || type == TokenType::PlusEquals
  2331. || type == TokenType::Minus
  2332. || type == TokenType::MinusEquals
  2333. || type == TokenType::Asterisk
  2334. || type == TokenType::AsteriskEquals
  2335. || type == TokenType::Slash
  2336. || type == TokenType::SlashEquals
  2337. || type == TokenType::Percent
  2338. || type == TokenType::PercentEquals
  2339. || type == TokenType::DoubleAsterisk
  2340. || type == TokenType::DoubleAsteriskEquals
  2341. || type == TokenType::Equals
  2342. || type == TokenType::EqualsEqualsEquals
  2343. || type == TokenType::ExclamationMarkEqualsEquals
  2344. || type == TokenType::EqualsEquals
  2345. || type == TokenType::ExclamationMarkEquals
  2346. || type == TokenType::GreaterThan
  2347. || type == TokenType::GreaterThanEquals
  2348. || type == TokenType::LessThan
  2349. || type == TokenType::LessThanEquals
  2350. || type == TokenType::ParenOpen
  2351. || type == TokenType::Period
  2352. || type == TokenType::BracketOpen
  2353. || (type == TokenType::PlusPlus && !m_state.current_token.trivia_contains_line_terminator())
  2354. || (type == TokenType::MinusMinus && !m_state.current_token.trivia_contains_line_terminator())
  2355. || type == TokenType::In
  2356. || type == TokenType::Instanceof
  2357. || type == TokenType::QuestionMark
  2358. || type == TokenType::Ampersand
  2359. || type == TokenType::AmpersandEquals
  2360. || type == TokenType::Pipe
  2361. || type == TokenType::PipeEquals
  2362. || type == TokenType::Caret
  2363. || type == TokenType::CaretEquals
  2364. || type == TokenType::ShiftLeft
  2365. || type == TokenType::ShiftLeftEquals
  2366. || type == TokenType::ShiftRight
  2367. || type == TokenType::ShiftRightEquals
  2368. || type == TokenType::UnsignedShiftRight
  2369. || type == TokenType::UnsignedShiftRightEquals
  2370. || type == TokenType::DoubleAmpersand
  2371. || type == TokenType::DoubleAmpersandEquals
  2372. || type == TokenType::DoublePipe
  2373. || type == TokenType::DoublePipeEquals
  2374. || type == TokenType::DoubleQuestionMark
  2375. || type == TokenType::DoubleQuestionMarkEquals;
  2376. }
  2377. bool Parser::match_statement() const
  2378. {
  2379. auto type = m_state.current_token.type();
  2380. return match_expression()
  2381. || type == TokenType::Return
  2382. || type == TokenType::Yield
  2383. || type == TokenType::Do
  2384. || type == TokenType::If
  2385. || type == TokenType::Throw
  2386. || type == TokenType::Try
  2387. || type == TokenType::While
  2388. || type == TokenType::With
  2389. || type == TokenType::For
  2390. || type == TokenType::CurlyOpen
  2391. || type == TokenType::Switch
  2392. || type == TokenType::Break
  2393. || type == TokenType::Continue
  2394. || type == TokenType::Var
  2395. || type == TokenType::Debugger
  2396. || type == TokenType::Semicolon;
  2397. }
  2398. bool Parser::match_export_or_import() const
  2399. {
  2400. auto type = m_state.current_token.type();
  2401. return type == TokenType::Export
  2402. || type == TokenType::Import;
  2403. }
  2404. bool Parser::match_declaration()
  2405. {
  2406. auto type = m_state.current_token.type();
  2407. if (type == TokenType::Let && !m_state.strict_mode) {
  2408. return try_match_let_declaration();
  2409. }
  2410. return type == TokenType::Function
  2411. || type == TokenType::Class
  2412. || type == TokenType::Const
  2413. || type == TokenType::Let;
  2414. }
  2415. bool Parser::try_match_let_declaration()
  2416. {
  2417. VERIFY(m_state.current_token.type() == TokenType::Let);
  2418. save_state();
  2419. ScopeGuard state_rollback = [&] {
  2420. load_state();
  2421. };
  2422. consume(TokenType::Let);
  2423. if (match_identifier_name() && m_state.current_token.value() != "in"sv)
  2424. return true;
  2425. if (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen))
  2426. return true;
  2427. return false;
  2428. }
  2429. bool Parser::match_variable_declaration()
  2430. {
  2431. auto type = m_state.current_token.type();
  2432. if (type == TokenType::Let && !m_state.strict_mode) {
  2433. return try_match_let_declaration();
  2434. }
  2435. return type == TokenType::Var
  2436. || type == TokenType::Let
  2437. || type == TokenType::Const;
  2438. }
  2439. bool Parser::match_identifier() const
  2440. {
  2441. return m_state.current_token.type() == TokenType::Identifier
  2442. || (m_state.current_token.type() == TokenType::Let && !m_state.strict_mode)
  2443. || (m_state.current_token.type() == TokenType::Yield && !m_state.in_generator_function_context && !m_state.strict_mode); // See note in Parser::parse_identifier().
  2444. }
  2445. bool Parser::match_identifier_name() const
  2446. {
  2447. return m_state.current_token.is_identifier_name();
  2448. }
  2449. bool Parser::match_property_key() const
  2450. {
  2451. auto type = m_state.current_token.type();
  2452. return match_identifier_name()
  2453. || type == TokenType::BracketOpen
  2454. || type == TokenType::StringLiteral
  2455. || type == TokenType::NumericLiteral
  2456. || type == TokenType::BigIntLiteral;
  2457. }
  2458. bool Parser::done() const
  2459. {
  2460. return match(TokenType::Eof);
  2461. }
  2462. Token Parser::consume()
  2463. {
  2464. auto old_token = m_state.current_token;
  2465. m_state.current_token = m_state.lexer.next();
  2466. return old_token;
  2467. }
  2468. void Parser::consume_or_insert_semicolon()
  2469. {
  2470. // Semicolon was found and will be consumed
  2471. if (match(TokenType::Semicolon)) {
  2472. consume();
  2473. return;
  2474. }
  2475. // Insert semicolon if...
  2476. // ...token is preceded by one or more newlines
  2477. if (m_state.current_token.trivia_contains_line_terminator())
  2478. return;
  2479. // ...token is a closing curly brace
  2480. if (match(TokenType::CurlyClose))
  2481. return;
  2482. // ...token is eof
  2483. if (match(TokenType::Eof))
  2484. return;
  2485. // No rule for semicolon insertion applies -> syntax error
  2486. expected("Semicolon");
  2487. }
  2488. Token Parser::consume_identifier()
  2489. {
  2490. if (match(TokenType::Identifier))
  2491. return consume(TokenType::Identifier);
  2492. // Note that 'let' is not a reserved keyword, but our lexer considers it such
  2493. // As it's pretty nice to have that (for syntax highlighting and such), we'll
  2494. // special-case it here instead.
  2495. if (match(TokenType::Let)) {
  2496. if (m_state.strict_mode)
  2497. syntax_error("'let' is not allowed as an identifier in strict mode");
  2498. return consume();
  2499. }
  2500. if (match(TokenType::Yield)) {
  2501. if (m_state.strict_mode || m_state.in_generator_function_context)
  2502. syntax_error("Identifier must not be a reserved word in strict mode ('yield')");
  2503. return consume();
  2504. }
  2505. expected("Identifier");
  2506. return consume();
  2507. }
  2508. // https://tc39.es/ecma262/#prod-IdentifierReference
  2509. Token Parser::consume_identifier_reference()
  2510. {
  2511. if (match(TokenType::Identifier))
  2512. return consume(TokenType::Identifier);
  2513. // See note in Parser::parse_identifier().
  2514. if (match(TokenType::Let)) {
  2515. if (m_state.strict_mode)
  2516. syntax_error("'let' is not allowed as an identifier in strict mode");
  2517. return consume();
  2518. }
  2519. if (match(TokenType::Yield)) {
  2520. if (m_state.strict_mode)
  2521. syntax_error("Identifier reference may not be 'yield' in strict mode");
  2522. return consume();
  2523. }
  2524. if (match(TokenType::Await)) {
  2525. syntax_error("Identifier reference may not be 'await'");
  2526. return consume();
  2527. }
  2528. expected(Token::name(TokenType::Identifier));
  2529. return consume();
  2530. }
  2531. Token Parser::consume(TokenType expected_type)
  2532. {
  2533. if (!match(expected_type)) {
  2534. expected(Token::name(expected_type));
  2535. }
  2536. auto token = consume();
  2537. if (expected_type == TokenType::Identifier) {
  2538. if (m_state.strict_mode && is_strict_reserved_word(token.value()))
  2539. syntax_error(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", token.value()));
  2540. }
  2541. return token;
  2542. }
  2543. Token Parser::consume_and_validate_numeric_literal()
  2544. {
  2545. auto is_unprefixed_octal_number = [](const StringView& value) {
  2546. return value.length() > 1 && value[0] == '0' && is_ascii_digit(value[1]);
  2547. };
  2548. auto literal_start = position();
  2549. auto token = consume(TokenType::NumericLiteral);
  2550. if (m_state.strict_mode && is_unprefixed_octal_number(token.value()))
  2551. syntax_error("Unprefixed octal number not allowed in strict mode", literal_start);
  2552. if (match_identifier_name() && m_state.current_token.trivia().is_empty())
  2553. syntax_error("Numeric literal must not be immediately followed by identifier");
  2554. return token;
  2555. }
  2556. void Parser::expected(const char* what)
  2557. {
  2558. auto message = m_state.current_token.message();
  2559. if (message.is_empty())
  2560. message = String::formatted("Unexpected token {}. Expected {}", m_state.current_token.name(), what);
  2561. syntax_error(message);
  2562. }
  2563. Position Parser::position() const
  2564. {
  2565. return {
  2566. m_state.current_token.line_number(),
  2567. m_state.current_token.line_column(),
  2568. m_state.current_token.offset(),
  2569. };
  2570. }
  2571. bool Parser::try_parse_arrow_function_expression_failed_at_position(const Position& position) const
  2572. {
  2573. auto it = m_token_memoizations.find(position);
  2574. if (it == m_token_memoizations.end())
  2575. return false;
  2576. return (*it).value.try_parse_arrow_function_expression_failed;
  2577. }
  2578. void Parser::set_try_parse_arrow_function_expression_failed_at_position(const Position& position, bool failed)
  2579. {
  2580. m_token_memoizations.set(position, { failed });
  2581. }
  2582. void Parser::syntax_error(const String& message, Optional<Position> position)
  2583. {
  2584. if (!position.has_value())
  2585. position = this->position();
  2586. m_state.errors.append({ message, position });
  2587. }
  2588. void Parser::save_state()
  2589. {
  2590. m_saved_state.append(m_state);
  2591. }
  2592. void Parser::load_state()
  2593. {
  2594. VERIFY(!m_saved_state.is_empty());
  2595. m_state = m_saved_state.take_last();
  2596. }
  2597. void Parser::discard_saved_state()
  2598. {
  2599. m_saved_state.take_last();
  2600. }
  2601. void Parser::check_identifier_name_for_assignment_validity(StringView name, bool force_strict)
  2602. {
  2603. // FIXME: this is now called from multiple places maybe the error message should be dynamic?
  2604. if (any_of(s_reserved_words, [&](auto& value) { return name == value; })) {
  2605. syntax_error("Binding pattern target may not be a reserved word");
  2606. } else if (m_state.strict_mode || force_strict) {
  2607. if (name.is_one_of("arguments"sv, "eval"sv))
  2608. syntax_error("Binding pattern target may not be called 'arguments' or 'eval' in strict mode");
  2609. else if (is_strict_reserved_word(name))
  2610. syntax_error(String::formatted("Binding pattern target may not be called '{}' in strict mode", name));
  2611. }
  2612. }
  2613. NonnullRefPtr<ImportStatement> Parser::parse_import_statement(Program& program)
  2614. {
  2615. auto rule_start = push_start();
  2616. if (program.type() != Program::Type::Module)
  2617. syntax_error("Cannot use import statement outside a module");
  2618. consume(TokenType::Import);
  2619. if (match(TokenType::StringLiteral)) {
  2620. auto module_name = consume(TokenType::StringLiteral).value();
  2621. return create_ast_node<ImportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, module_name);
  2622. }
  2623. auto match_imported_binding = [&] {
  2624. return match_identifier() || match(TokenType::Yield) || match(TokenType::Await);
  2625. };
  2626. auto match_as = [&] {
  2627. return match(TokenType::Identifier) && m_state.current_token.value() == "as"sv;
  2628. };
  2629. bool continue_parsing = true;
  2630. struct ImportWithLocation {
  2631. ImportStatement::ImportEntry entry;
  2632. Position position;
  2633. };
  2634. Vector<ImportWithLocation> entries_with_location;
  2635. if (match_imported_binding()) {
  2636. auto id_position = position();
  2637. auto bound_name = consume().value();
  2638. entries_with_location.append({ { "default", bound_name }, id_position });
  2639. if (match(TokenType::Comma)) {
  2640. consume(TokenType::Comma);
  2641. } else {
  2642. continue_parsing = false;
  2643. }
  2644. }
  2645. if (!continue_parsing) {
  2646. // skip the rest
  2647. } else if (match(TokenType::Asterisk)) {
  2648. consume(TokenType::Asterisk);
  2649. if (!match_as())
  2650. syntax_error(String::formatted("Unexpected token: {}", m_state.current_token.name()));
  2651. consume(TokenType::Identifier);
  2652. if (match_imported_binding()) {
  2653. auto namespace_position = position();
  2654. auto namespace_name = consume().value();
  2655. entries_with_location.append({ { "*", namespace_name }, namespace_position });
  2656. } else {
  2657. syntax_error(String::formatted("Unexpected token: {}", m_state.current_token.name()));
  2658. }
  2659. } else if (match(TokenType::CurlyOpen)) {
  2660. consume(TokenType::CurlyOpen);
  2661. while (!done() && !match(TokenType::CurlyClose)) {
  2662. if (match_identifier_name()) {
  2663. auto require_as = !match_imported_binding();
  2664. auto name_position = position();
  2665. auto name = consume().value();
  2666. if (match_as()) {
  2667. consume(TokenType::Identifier);
  2668. auto alias_position = position();
  2669. auto alias = consume_identifier().value();
  2670. check_identifier_name_for_assignment_validity(alias);
  2671. entries_with_location.append({ { name, alias }, alias_position });
  2672. } else if (require_as) {
  2673. syntax_error(String::formatted("Unexpected reserved word '{}'", name));
  2674. } else {
  2675. check_identifier_name_for_assignment_validity(name);
  2676. entries_with_location.append({ { name, name }, name_position });
  2677. }
  2678. } else {
  2679. expected("identifier");
  2680. break;
  2681. }
  2682. if (!match(TokenType::Comma))
  2683. break;
  2684. consume(TokenType::Comma);
  2685. }
  2686. consume(TokenType::CurlyClose);
  2687. } else {
  2688. expected("import clauses");
  2689. }
  2690. auto from_statement = consume(TokenType::Identifier).value();
  2691. if (from_statement != "from"sv)
  2692. syntax_error(String::formatted("Expected 'from' got {}", from_statement));
  2693. auto module_name = consume(TokenType::StringLiteral).value();
  2694. Vector<ImportStatement::ImportEntry> entries;
  2695. entries.ensure_capacity(entries_with_location.size());
  2696. for (auto& entry : entries_with_location) {
  2697. for (auto& import_statement : program.imports()) {
  2698. if (import_statement.has_bound_name(entry.entry.local_name))
  2699. syntax_error(String::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position);
  2700. }
  2701. for (auto& new_entry : entries) {
  2702. if (new_entry.local_name == entry.entry.local_name)
  2703. syntax_error(String::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position);
  2704. }
  2705. entries.append(move(entry.entry));
  2706. }
  2707. return create_ast_node<ImportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, module_name, move(entries));
  2708. }
  2709. NonnullRefPtr<ExportStatement> Parser::parse_export_statement(Program& program)
  2710. {
  2711. auto rule_start = push_start();
  2712. if (program.type() != Program::Type::Module)
  2713. syntax_error("Cannot use export statement outside a module");
  2714. auto match_as = [&] {
  2715. return match(TokenType::Identifier) && m_state.current_token.value() == "as"sv;
  2716. };
  2717. auto match_from = [&] {
  2718. return match(TokenType::Identifier) && m_state.current_token.value() == "from"sv;
  2719. };
  2720. consume(TokenType::Export);
  2721. struct EntryAndLocation {
  2722. ExportStatement::ExportEntry entry;
  2723. Position position;
  2724. void to_module_request(String from_module)
  2725. {
  2726. entry.kind = ExportStatement::ExportEntry::Kind::ModuleRequest;
  2727. entry.module_request = from_module;
  2728. }
  2729. };
  2730. Vector<EntryAndLocation> entries_with_location;
  2731. RefPtr<ASTNode> expression = {};
  2732. if (match(TokenType::Default)) {
  2733. auto default_position = position();
  2734. consume(TokenType::Default);
  2735. String local_name;
  2736. if (match(TokenType::Class)) {
  2737. auto class_expression = parse_class_expression(false);
  2738. local_name = class_expression->name();
  2739. expression = move(class_expression);
  2740. } else if (match(TokenType::Function)) {
  2741. auto func_expr = parse_function_node<FunctionExpression>();
  2742. local_name = func_expr->name();
  2743. expression = move(func_expr);
  2744. // TODO: Allow async function
  2745. } else if (match_expression()) {
  2746. expression = parse_expression(2);
  2747. consume_or_insert_semicolon();
  2748. local_name = "*default*";
  2749. } else {
  2750. expected("Declaration or assignment expression");
  2751. }
  2752. entries_with_location.append({ { "default", local_name }, default_position });
  2753. } else {
  2754. enum FromSpecifier {
  2755. NotAllowed,
  2756. Optional,
  2757. Required
  2758. } check_for_from { NotAllowed };
  2759. if (match(TokenType::Asterisk)) {
  2760. auto asterisk_position = position();
  2761. consume(TokenType::Asterisk);
  2762. if (match_as()) {
  2763. consume(TokenType::Identifier);
  2764. if (match_identifier_name()) {
  2765. auto namespace_position = position();
  2766. auto exported_name = consume().value();
  2767. entries_with_location.append({ { exported_name, "*" }, namespace_position });
  2768. } else {
  2769. expected("identifier");
  2770. }
  2771. } else {
  2772. entries_with_location.append({ { {}, "*" }, asterisk_position });
  2773. }
  2774. check_for_from = Required;
  2775. } else if (match_declaration()) {
  2776. auto decl_position = position();
  2777. auto declaration = parse_declaration();
  2778. if (is<FunctionDeclaration>(*declaration)) {
  2779. auto& func = static_cast<FunctionDeclaration&>(*declaration);
  2780. entries_with_location.append({ { func.name(), func.name() }, func.source_range().start });
  2781. } else if (is<ClassDeclaration>(*declaration)) {
  2782. auto& class_declaration = static_cast<ClassDeclaration&>(*declaration);
  2783. entries_with_location.append({ { class_declaration.class_name(), class_declaration.class_name() }, class_declaration.source_range().start });
  2784. } else {
  2785. VERIFY(is<VariableDeclaration>(*declaration));
  2786. auto& variables = static_cast<VariableDeclaration&>(*declaration);
  2787. for (auto& decl : variables.declarations()) {
  2788. decl.target().visit(
  2789. [&](NonnullRefPtr<Identifier> const& identifier) {
  2790. entries_with_location.append({ { identifier->string(), identifier->string() }, identifier->source_range().start });
  2791. },
  2792. [&](NonnullRefPtr<BindingPattern> const& binding) {
  2793. binding->for_each_bound_name([&](auto& name) {
  2794. entries_with_location.append({ { name, name }, decl_position });
  2795. });
  2796. });
  2797. }
  2798. }
  2799. expression = declaration;
  2800. } else if (match(TokenType::Var)) {
  2801. auto variable_position = position();
  2802. auto variable_declaration = parse_variable_declaration();
  2803. for (auto& decl : variable_declaration->declarations()) {
  2804. decl.target().visit(
  2805. [&](NonnullRefPtr<Identifier> const& identifier) {
  2806. entries_with_location.append({ { identifier->string(), identifier->string() }, identifier->source_range().start });
  2807. },
  2808. [&](NonnullRefPtr<BindingPattern> const& binding) {
  2809. binding->for_each_bound_name([&](auto& name) {
  2810. entries_with_location.append({ { name, name }, variable_position });
  2811. });
  2812. });
  2813. }
  2814. expression = variable_declaration;
  2815. } else if (match(TokenType::CurlyOpen)) {
  2816. consume(TokenType::CurlyOpen);
  2817. while (!done() && !match(TokenType::CurlyClose)) {
  2818. if (match_identifier_name()) {
  2819. auto identifier_position = position();
  2820. auto identifier = consume().value();
  2821. if (match_as()) {
  2822. consume(TokenType::Identifier);
  2823. if (match_identifier_name()) {
  2824. auto export_name = consume().value();
  2825. entries_with_location.append({ { export_name, identifier }, identifier_position });
  2826. } else {
  2827. expected("identifier name");
  2828. }
  2829. } else {
  2830. entries_with_location.append({ { identifier, identifier }, identifier_position });
  2831. }
  2832. } else {
  2833. expected("identifier");
  2834. break;
  2835. }
  2836. if (!match(TokenType::Comma))
  2837. break;
  2838. consume(TokenType::Comma);
  2839. }
  2840. consume(TokenType::CurlyClose);
  2841. check_for_from = Optional;
  2842. } else {
  2843. syntax_error("Unexpected token 'export'", rule_start.position());
  2844. }
  2845. if (check_for_from != NotAllowed && match_from()) {
  2846. consume(TokenType::Identifier);
  2847. if (match(TokenType::StringLiteral)) {
  2848. auto from_specifier = consume().value();
  2849. for (auto& entry : entries_with_location)
  2850. entry.to_module_request(from_specifier);
  2851. } else {
  2852. expected("ModuleSpecifier");
  2853. }
  2854. } else if (check_for_from == Required) {
  2855. expected("from");
  2856. }
  2857. if (check_for_from != NotAllowed)
  2858. consume_or_insert_semicolon();
  2859. }
  2860. Vector<ExportStatement::ExportEntry> entries;
  2861. entries.ensure_capacity(entries_with_location.size());
  2862. for (auto& entry : entries_with_location) {
  2863. for (auto& export_statement : program.exports()) {
  2864. if (export_statement.has_export(entry.entry.export_name))
  2865. syntax_error(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position);
  2866. }
  2867. for (auto& new_entry : entries) {
  2868. if (new_entry.export_name == entry.entry.export_name)
  2869. syntax_error(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position);
  2870. }
  2871. entries.append(move(entry.entry));
  2872. }
  2873. return create_ast_node<ExportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(entries));
  2874. }
  2875. }