Parser.cpp 139 KB

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