Parser.cpp 116 KB

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