Parser.cpp 107 KB

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