Parser.cpp 138 KB

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