Parser.cpp 137 KB

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