Parser.cpp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@gmx.de>
  3. * Copyright (c) 2020, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "Parser.h"
  28. #include <AK/ScopeGuard.h>
  29. #include <AK/StdLibExtras.h>
  30. #include <AK/TemporaryChange.h>
  31. #include <ctype.h>
  32. namespace JS {
  33. static bool statement_is_use_strict_directive(NonnullRefPtr<Statement> statement)
  34. {
  35. if (!is<ExpressionStatement>(*statement))
  36. return false;
  37. auto& expression_statement = static_cast<ExpressionStatement&>(*statement);
  38. auto& expression = expression_statement.expression();
  39. if (!is<StringLiteral>(expression))
  40. return false;
  41. return static_cast<const StringLiteral&>(expression).is_use_strict_directive();
  42. }
  43. class ScopePusher {
  44. public:
  45. enum Type {
  46. Var = 1,
  47. Let = 2,
  48. Function = 3,
  49. };
  50. ScopePusher(Parser& parser, unsigned mask)
  51. : m_parser(parser)
  52. , m_mask(mask)
  53. {
  54. if (m_mask & Var)
  55. m_parser.m_parser_state.m_var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  56. if (m_mask & Let)
  57. m_parser.m_parser_state.m_let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  58. if (m_mask & Function)
  59. m_parser.m_parser_state.m_function_scopes.append(NonnullRefPtrVector<FunctionDeclaration>());
  60. }
  61. ~ScopePusher()
  62. {
  63. if (m_mask & Var)
  64. m_parser.m_parser_state.m_var_scopes.take_last();
  65. if (m_mask & Let)
  66. m_parser.m_parser_state.m_let_scopes.take_last();
  67. if (m_mask & Function)
  68. m_parser.m_parser_state.m_function_scopes.take_last();
  69. }
  70. Parser& m_parser;
  71. unsigned m_mask { 0 };
  72. };
  73. class OperatorPrecedenceTable {
  74. public:
  75. constexpr OperatorPrecedenceTable()
  76. : m_token_precedence()
  77. {
  78. for (size_t i = 0; i < array_size(m_operator_precedence); ++i) {
  79. auto& op = m_operator_precedence[i];
  80. m_token_precedence[static_cast<size_t>(op.token)] = op.precedence;
  81. }
  82. }
  83. constexpr int get(TokenType token) const
  84. {
  85. int p = m_token_precedence[static_cast<size_t>(token)];
  86. if (p == 0) {
  87. warnln("Internal Error: No precedence for operator {}", Token::name(token));
  88. ASSERT_NOT_REACHED();
  89. return -1;
  90. }
  91. return p;
  92. }
  93. private:
  94. int m_token_precedence[cs_num_of_js_tokens];
  95. struct OperatorPrecedence {
  96. TokenType token;
  97. int precedence;
  98. };
  99. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  100. static constexpr const OperatorPrecedence m_operator_precedence[] = {
  101. { TokenType::Period, 20 },
  102. { TokenType::BracketOpen, 20 },
  103. { TokenType::ParenOpen, 20 },
  104. { TokenType::QuestionMarkPeriod, 20 },
  105. { TokenType::New, 19 },
  106. { TokenType::PlusPlus, 18 },
  107. { TokenType::MinusMinus, 18 },
  108. { TokenType::ExclamationMark, 17 },
  109. { TokenType::Tilde, 17 },
  110. { TokenType::Typeof, 17 },
  111. { TokenType::Void, 17 },
  112. { TokenType::Delete, 17 },
  113. { TokenType::Await, 17 },
  114. { TokenType::DoubleAsterisk, 16 },
  115. { TokenType::Asterisk, 15 },
  116. { TokenType::Slash, 15 },
  117. { TokenType::Percent, 15 },
  118. { TokenType::Plus, 14 },
  119. { TokenType::Minus, 14 },
  120. { TokenType::ShiftLeft, 13 },
  121. { TokenType::ShiftRight, 13 },
  122. { TokenType::UnsignedShiftRight, 13 },
  123. { TokenType::LessThan, 12 },
  124. { TokenType::LessThanEquals, 12 },
  125. { TokenType::GreaterThan, 12 },
  126. { TokenType::GreaterThanEquals, 12 },
  127. { TokenType::In, 12 },
  128. { TokenType::Instanceof, 12 },
  129. { TokenType::EqualsEquals, 11 },
  130. { TokenType::ExclamationMarkEquals, 11 },
  131. { TokenType::EqualsEqualsEquals, 11 },
  132. { TokenType::ExclamationMarkEqualsEquals, 11 },
  133. { TokenType::Ampersand, 10 },
  134. { TokenType::Caret, 9 },
  135. { TokenType::Pipe, 8 },
  136. { TokenType::DoubleQuestionMark, 7 },
  137. { TokenType::DoubleAmpersand, 6 },
  138. { TokenType::DoublePipe, 5 },
  139. { TokenType::QuestionMark, 4 },
  140. { TokenType::Equals, 3 },
  141. { TokenType::PlusEquals, 3 },
  142. { TokenType::MinusEquals, 3 },
  143. { TokenType::DoubleAsteriskEquals, 3 },
  144. { TokenType::AsteriskEquals, 3 },
  145. { TokenType::SlashEquals, 3 },
  146. { TokenType::PercentEquals, 3 },
  147. { TokenType::ShiftLeftEquals, 3 },
  148. { TokenType::ShiftRightEquals, 3 },
  149. { TokenType::UnsignedShiftRightEquals, 3 },
  150. { TokenType::AmpersandEquals, 3 },
  151. { TokenType::CaretEquals, 3 },
  152. { TokenType::PipeEquals, 3 },
  153. { TokenType::DoubleAmpersandEquals, 3 },
  154. { TokenType::DoublePipeEquals, 3 },
  155. { TokenType::DoubleQuestionMarkEquals, 3 },
  156. { TokenType::Yield, 2 },
  157. { TokenType::Comma, 1 },
  158. };
  159. };
  160. constexpr OperatorPrecedenceTable g_operator_precedence;
  161. Parser::ParserState::ParserState(Lexer lexer)
  162. : m_lexer(move(lexer))
  163. , m_current_token(m_lexer.next())
  164. {
  165. }
  166. Parser::Parser(Lexer lexer)
  167. : m_parser_state(move(lexer))
  168. {
  169. }
  170. Associativity Parser::operator_associativity(TokenType type) const
  171. {
  172. switch (type) {
  173. case TokenType::Period:
  174. case TokenType::BracketOpen:
  175. case TokenType::ParenOpen:
  176. case TokenType::QuestionMarkPeriod:
  177. case TokenType::Asterisk:
  178. case TokenType::Slash:
  179. case TokenType::Percent:
  180. case TokenType::Plus:
  181. case TokenType::Minus:
  182. case TokenType::ShiftLeft:
  183. case TokenType::ShiftRight:
  184. case TokenType::UnsignedShiftRight:
  185. case TokenType::LessThan:
  186. case TokenType::LessThanEquals:
  187. case TokenType::GreaterThan:
  188. case TokenType::GreaterThanEquals:
  189. case TokenType::In:
  190. case TokenType::Instanceof:
  191. case TokenType::EqualsEquals:
  192. case TokenType::ExclamationMarkEquals:
  193. case TokenType::EqualsEqualsEquals:
  194. case TokenType::ExclamationMarkEqualsEquals:
  195. case TokenType::Typeof:
  196. case TokenType::Void:
  197. case TokenType::Delete:
  198. case TokenType::Ampersand:
  199. case TokenType::Caret:
  200. case TokenType::Pipe:
  201. case TokenType::DoubleQuestionMark:
  202. case TokenType::DoubleAmpersand:
  203. case TokenType::DoublePipe:
  204. case TokenType::Comma:
  205. return Associativity::Left;
  206. default:
  207. return Associativity::Right;
  208. }
  209. }
  210. NonnullRefPtr<Program> Parser::parse_program()
  211. {
  212. auto rule_start = push_start();
  213. ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Let | ScopePusher::Function);
  214. auto program = adopt(*new Program({ rule_start.position(), position() }));
  215. bool first = true;
  216. while (!done()) {
  217. if (match_declaration()) {
  218. program->append(parse_declaration());
  219. } else if (match_statement()) {
  220. auto statement = parse_statement();
  221. program->append(statement);
  222. if (statement_is_use_strict_directive(statement)) {
  223. if (first) {
  224. program->set_strict_mode();
  225. m_parser_state.m_strict_mode = true;
  226. }
  227. if (m_parser_state.m_string_legacy_octal_escape_sequence_in_scope)
  228. syntax_error("Octal escape sequence in string literal not allowed in strict mode");
  229. }
  230. } else {
  231. expected("statement or declaration");
  232. consume();
  233. }
  234. first = false;
  235. }
  236. if (m_parser_state.m_var_scopes.size() == 1) {
  237. program->add_variables(m_parser_state.m_var_scopes.last());
  238. program->add_variables(m_parser_state.m_let_scopes.last());
  239. program->add_functions(m_parser_state.m_function_scopes.last());
  240. } else {
  241. syntax_error("Unclosed scope");
  242. }
  243. program->source_range().end = position();
  244. return program;
  245. }
  246. NonnullRefPtr<Declaration> Parser::parse_declaration()
  247. {
  248. auto rule_start = push_start();
  249. switch (m_parser_state.m_current_token.type()) {
  250. case TokenType::Class:
  251. return parse_class_declaration();
  252. case TokenType::Function: {
  253. auto declaration = parse_function_node<FunctionDeclaration>();
  254. m_parser_state.m_function_scopes.last().append(declaration);
  255. return declaration;
  256. }
  257. case TokenType::Let:
  258. case TokenType::Const:
  259. return parse_variable_declaration();
  260. default:
  261. expected("declaration");
  262. consume();
  263. return create_ast_node<ErrorDeclaration>({ rule_start.position(), position() });
  264. }
  265. }
  266. NonnullRefPtr<Statement> Parser::parse_statement()
  267. {
  268. auto rule_start = push_start();
  269. switch (m_parser_state.m_current_token.type()) {
  270. case TokenType::CurlyOpen:
  271. return parse_block_statement();
  272. case TokenType::Return:
  273. return parse_return_statement();
  274. case TokenType::Var:
  275. return parse_variable_declaration();
  276. case TokenType::For:
  277. return parse_for_statement();
  278. case TokenType::If:
  279. return parse_if_statement();
  280. case TokenType::Throw:
  281. return parse_throw_statement();
  282. case TokenType::Try:
  283. return parse_try_statement();
  284. case TokenType::Break:
  285. return parse_break_statement();
  286. case TokenType::Continue:
  287. return parse_continue_statement();
  288. case TokenType::Switch:
  289. return parse_switch_statement();
  290. case TokenType::Do:
  291. return parse_do_while_statement();
  292. case TokenType::While:
  293. return parse_while_statement();
  294. case TokenType::With:
  295. if (m_parser_state.m_strict_mode)
  296. syntax_error("'with' statement not allowed in strict mode");
  297. return parse_with_statement();
  298. case TokenType::Debugger:
  299. return parse_debugger_statement();
  300. case TokenType::Semicolon:
  301. consume();
  302. return create_ast_node<EmptyStatement>({ rule_start.position(), position() });
  303. default:
  304. if (match(TokenType::Identifier)) {
  305. auto result = try_parse_labelled_statement();
  306. if (!result.is_null())
  307. return result.release_nonnull();
  308. }
  309. if (match_expression()) {
  310. if (match(TokenType::Function))
  311. syntax_error("Function declaration not allowed in single-statement context");
  312. auto expr = parse_expression(0);
  313. consume_or_insert_semicolon();
  314. return create_ast_node<ExpressionStatement>({ rule_start.position(), position() }, move(expr));
  315. }
  316. expected("statement");
  317. consume();
  318. return create_ast_node<ErrorStatement>({ rule_start.position(), position() });
  319. }
  320. }
  321. RefPtr<FunctionExpression> Parser::try_parse_arrow_function_expression(bool expect_parens)
  322. {
  323. save_state();
  324. m_parser_state.m_var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  325. auto rule_start = push_start();
  326. ArmedScopeGuard state_rollback_guard = [&] {
  327. m_parser_state.m_var_scopes.take_last();
  328. load_state();
  329. };
  330. Vector<FunctionNode::Parameter> parameters;
  331. i32 function_length = -1;
  332. if (expect_parens) {
  333. // We have parens around the function parameters and can re-use the same parsing
  334. // logic used for regular functions: multiple parameters, default values, rest
  335. // parameter, maybe a trailing comma. If we have a new syntax error afterwards we
  336. // check if it's about a wrong token (something like duplicate parameter name must
  337. // not abort), know parsing failed and rollback the parser state.
  338. auto previous_syntax_errors = m_parser_state.m_errors.size();
  339. parameters = parse_function_parameters(function_length, FunctionNodeParseOptions::IsArrowFunction);
  340. if (m_parser_state.m_errors.size() > previous_syntax_errors && m_parser_state.m_errors[previous_syntax_errors].message.starts_with("Unexpected token"))
  341. return nullptr;
  342. if (!match(TokenType::ParenClose))
  343. return nullptr;
  344. consume();
  345. } else {
  346. // No parens - this must be an identifier followed by arrow. That's it.
  347. if (!match(TokenType::Identifier))
  348. return nullptr;
  349. parameters.append({ consume().value(), {} });
  350. }
  351. // If there's a newline between the closing paren and arrow it's not a valid arrow function,
  352. // ASI should kick in instead (it'll then fail with "Unexpected token Arrow")
  353. if (m_parser_state.m_current_token.trivia_contains_line_terminator())
  354. return nullptr;
  355. if (!match(TokenType::Arrow))
  356. return nullptr;
  357. consume();
  358. if (function_length == -1)
  359. function_length = parameters.size();
  360. auto old_labels_in_scope = move(m_parser_state.m_labels_in_scope);
  361. ScopeGuard guard([&]() {
  362. m_parser_state.m_labels_in_scope = move(old_labels_in_scope);
  363. });
  364. bool is_strict = false;
  365. auto function_body_result = [&]() -> RefPtr<BlockStatement> {
  366. TemporaryChange change(m_parser_state.m_in_arrow_function_context, true);
  367. if (match(TokenType::CurlyOpen)) {
  368. // Parse a function body with statements
  369. return parse_block_statement(is_strict);
  370. }
  371. if (match_expression()) {
  372. // Parse a function body which returns a single expression
  373. // FIXME: We synthesize a block with a return statement
  374. // for arrow function bodies which are a single expression.
  375. // Esprima generates a single "ArrowFunctionExpression"
  376. // with a "body" property.
  377. auto return_expression = parse_expression(2);
  378. auto return_block = create_ast_node<BlockStatement>({ rule_start.position(), position() });
  379. return_block->append<ReturnStatement>({ rule_start.position(), position() }, move(return_expression));
  380. return return_block;
  381. }
  382. // Invalid arrow function body
  383. return nullptr;
  384. }();
  385. if (!function_body_result.is_null()) {
  386. state_rollback_guard.disarm();
  387. discard_saved_state();
  388. auto body = function_body_result.release_nonnull();
  389. return create_ast_node<FunctionExpression>({ rule_start.position(), position() }, "", move(body), move(parameters), function_length, m_parser_state.m_var_scopes.take_last(), is_strict, true);
  390. }
  391. return nullptr;
  392. }
  393. RefPtr<Statement> Parser::try_parse_labelled_statement()
  394. {
  395. save_state();
  396. auto rule_start = push_start();
  397. ArmedScopeGuard state_rollback_guard = [&] {
  398. load_state();
  399. };
  400. auto identifier = consume(TokenType::Identifier).value();
  401. if (!match(TokenType::Colon))
  402. return {};
  403. consume(TokenType::Colon);
  404. if (!match_statement())
  405. return {};
  406. m_parser_state.m_labels_in_scope.set(identifier);
  407. auto statement = parse_statement();
  408. m_parser_state.m_labels_in_scope.remove(identifier);
  409. statement->set_label(identifier);
  410. state_rollback_guard.disarm();
  411. discard_saved_state();
  412. return statement;
  413. }
  414. RefPtr<MetaProperty> Parser::try_parse_new_target_expression()
  415. {
  416. save_state();
  417. auto rule_start = push_start();
  418. ArmedScopeGuard state_rollback_guard = [&] {
  419. load_state();
  420. };
  421. consume(TokenType::New);
  422. if (!match(TokenType::Period))
  423. return {};
  424. consume();
  425. if (!match(TokenType::Identifier))
  426. return {};
  427. if (consume().value() != "target")
  428. return {};
  429. state_rollback_guard.disarm();
  430. discard_saved_state();
  431. return create_ast_node<MetaProperty>({ rule_start.position(), position() }, MetaProperty::Type::NewTarget);
  432. }
  433. NonnullRefPtr<ClassDeclaration> Parser::parse_class_declaration()
  434. {
  435. auto rule_start = push_start();
  436. return create_ast_node<ClassDeclaration>({ rule_start.position(), position() }, parse_class_expression(true));
  437. }
  438. NonnullRefPtr<ClassExpression> Parser::parse_class_expression(bool expect_class_name)
  439. {
  440. auto rule_start = push_start();
  441. // Classes are always in strict mode.
  442. TemporaryChange strict_mode_rollback(m_parser_state.m_strict_mode, true);
  443. consume(TokenType::Class);
  444. NonnullRefPtrVector<ClassMethod> methods;
  445. RefPtr<Expression> super_class;
  446. RefPtr<FunctionExpression> constructor;
  447. String class_name = expect_class_name || match(TokenType::Identifier) ? consume(TokenType::Identifier).value().to_string() : "";
  448. if (match(TokenType::Extends)) {
  449. consume();
  450. super_class = parse_primary_expression();
  451. }
  452. consume(TokenType::CurlyOpen);
  453. while (!done() && !match(TokenType::CurlyClose)) {
  454. RefPtr<Expression> property_key;
  455. bool is_static = false;
  456. bool is_constructor = false;
  457. auto method_kind = ClassMethod::Kind::Method;
  458. if (match(TokenType::Semicolon)) {
  459. consume();
  460. continue;
  461. }
  462. if (match_property_key()) {
  463. StringView name;
  464. if (match(TokenType::Identifier) && m_parser_state.m_current_token.value() == "static") {
  465. consume();
  466. is_static = true;
  467. }
  468. if (match(TokenType::Identifier)) {
  469. auto identifier_name = m_parser_state.m_current_token.value();
  470. if (identifier_name == "get") {
  471. method_kind = ClassMethod::Kind::Getter;
  472. consume();
  473. } else if (identifier_name == "set") {
  474. method_kind = ClassMethod::Kind::Setter;
  475. consume();
  476. }
  477. }
  478. if (match_property_key()) {
  479. switch (m_parser_state.m_current_token.type()) {
  480. case TokenType::Identifier:
  481. name = consume().value();
  482. property_key = create_ast_node<StringLiteral>({ rule_start.position(), position() }, name);
  483. break;
  484. case TokenType::StringLiteral: {
  485. auto string_literal = parse_string_literal(consume());
  486. name = string_literal->value();
  487. property_key = move(string_literal);
  488. break;
  489. }
  490. default:
  491. property_key = parse_property_key();
  492. break;
  493. }
  494. } else {
  495. expected("property key");
  496. }
  497. // Constructor may be a StringLiteral or an Identifier.
  498. if (!is_static && name == "constructor") {
  499. if (method_kind != ClassMethod::Kind::Method)
  500. syntax_error("Class constructor may not be an accessor");
  501. if (!constructor.is_null())
  502. syntax_error("Classes may not have more than one constructor");
  503. is_constructor = true;
  504. }
  505. }
  506. if (match(TokenType::ParenOpen)) {
  507. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  508. if (!super_class.is_null())
  509. parse_options |= FunctionNodeParseOptions::AllowSuperConstructorCall;
  510. if (method_kind == ClassMethod::Kind::Getter)
  511. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  512. if (method_kind == ClassMethod::Kind::Setter)
  513. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  514. auto function = parse_function_node<FunctionExpression>(parse_options);
  515. if (is_constructor) {
  516. constructor = move(function);
  517. } else if (!property_key.is_null()) {
  518. methods.append(create_ast_node<ClassMethod>({ rule_start.position(), position() }, property_key.release_nonnull(), move(function), method_kind, is_static));
  519. } else {
  520. syntax_error("No key for class method");
  521. }
  522. } else {
  523. expected("ParenOpen");
  524. consume();
  525. }
  526. }
  527. consume(TokenType::CurlyClose);
  528. if (constructor.is_null()) {
  529. auto constructor_body = create_ast_node<BlockStatement>({ rule_start.position(), position() });
  530. if (!super_class.is_null()) {
  531. // Set constructor to the result of parsing the source text
  532. // constructor(... args){ super (...args);}
  533. auto super_call = create_ast_node<CallExpression>({ rule_start.position(), position() }, create_ast_node<SuperExpression>({ rule_start.position(), position() }), Vector { CallExpression::Argument { create_ast_node<Identifier>({ rule_start.position(), position() }, "args"), true } });
  534. constructor_body->append(create_ast_node<ExpressionStatement>({ rule_start.position(), position() }, move(super_call)));
  535. constructor_body->add_variables(m_parser_state.m_var_scopes.last());
  536. constructor = create_ast_node<FunctionExpression>({ rule_start.position(), position() }, class_name, move(constructor_body), Vector { FunctionNode::Parameter { "args", nullptr, true } }, 0, NonnullRefPtrVector<VariableDeclaration>(), true);
  537. } else {
  538. constructor = create_ast_node<FunctionExpression>({ rule_start.position(), position() }, class_name, move(constructor_body), Vector<FunctionNode::Parameter> {}, 0, NonnullRefPtrVector<VariableDeclaration>(), true);
  539. }
  540. }
  541. return create_ast_node<ClassExpression>({ rule_start.position(), position() }, move(class_name), move(constructor), move(super_class), move(methods));
  542. }
  543. NonnullRefPtr<Expression> Parser::parse_primary_expression()
  544. {
  545. auto rule_start = push_start();
  546. if (match_unary_prefixed_expression())
  547. return parse_unary_prefixed_expression();
  548. switch (m_parser_state.m_current_token.type()) {
  549. case TokenType::ParenOpen: {
  550. consume(TokenType::ParenOpen);
  551. if (match(TokenType::ParenClose) || match(TokenType::Identifier) || match(TokenType::TripleDot)) {
  552. auto arrow_function_result = try_parse_arrow_function_expression(true);
  553. if (!arrow_function_result.is_null())
  554. return arrow_function_result.release_nonnull();
  555. }
  556. auto expression = parse_expression(0);
  557. consume(TokenType::ParenClose);
  558. return expression;
  559. }
  560. case TokenType::This:
  561. consume();
  562. return create_ast_node<ThisExpression>({ rule_start.position(), position() });
  563. case TokenType::Class:
  564. return parse_class_expression(false);
  565. case TokenType::Super:
  566. consume();
  567. if (!m_parser_state.m_allow_super_property_lookup)
  568. syntax_error("'super' keyword unexpected here");
  569. return create_ast_node<SuperExpression>({ rule_start.position(), position() });
  570. case TokenType::Identifier: {
  571. auto arrow_function_result = try_parse_arrow_function_expression(false);
  572. if (!arrow_function_result.is_null())
  573. return arrow_function_result.release_nonnull();
  574. return create_ast_node<Identifier>({ rule_start.position(), position() }, consume().value());
  575. }
  576. case TokenType::NumericLiteral:
  577. return create_ast_node<NumericLiteral>({ rule_start.position(), position() }, consume_and_validate_numeric_literal().double_value());
  578. case TokenType::BigIntLiteral:
  579. return create_ast_node<BigIntLiteral>({ rule_start.position(), position() }, consume().value());
  580. case TokenType::BoolLiteral:
  581. return create_ast_node<BooleanLiteral>({ rule_start.position(), position() }, consume().bool_value());
  582. case TokenType::StringLiteral:
  583. return parse_string_literal(consume());
  584. case TokenType::NullLiteral:
  585. consume();
  586. return create_ast_node<NullLiteral>({ rule_start.position(), position() });
  587. case TokenType::CurlyOpen:
  588. return parse_object_expression();
  589. case TokenType::Function:
  590. return parse_function_node<FunctionExpression>();
  591. case TokenType::BracketOpen:
  592. return parse_array_expression();
  593. case TokenType::RegexLiteral:
  594. return parse_regexp_literal();
  595. case TokenType::TemplateLiteralStart:
  596. return parse_template_literal(false);
  597. case TokenType::New: {
  598. auto new_start = position();
  599. auto new_target_result = try_parse_new_target_expression();
  600. if (!new_target_result.is_null()) {
  601. if (!m_parser_state.m_in_function_context)
  602. syntax_error("'new.target' not allowed outside of a function", new_start);
  603. return new_target_result.release_nonnull();
  604. }
  605. return parse_new_expression();
  606. }
  607. default:
  608. expected("primary expression");
  609. consume();
  610. return create_ast_node<ErrorExpression>({ rule_start.position(), position() });
  611. }
  612. }
  613. NonnullRefPtr<RegExpLiteral> Parser::parse_regexp_literal()
  614. {
  615. auto rule_start = push_start();
  616. auto content = consume().value();
  617. auto flags = match(TokenType::RegexFlags) ? consume().value() : "";
  618. return create_ast_node<RegExpLiteral>({ rule_start.position(), position() }, content.substring_view(1, content.length() - 2), flags);
  619. }
  620. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  621. {
  622. auto rule_start = push_start();
  623. auto precedence = g_operator_precedence.get(m_parser_state.m_current_token.type());
  624. auto associativity = operator_associativity(m_parser_state.m_current_token.type());
  625. switch (m_parser_state.m_current_token.type()) {
  626. case TokenType::PlusPlus: {
  627. consume();
  628. auto rhs_start = position();
  629. auto rhs = parse_expression(precedence, associativity);
  630. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  631. // other engines throw ReferenceError for ++foo()
  632. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  633. syntax_error(String::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  634. return create_ast_node<UpdateExpression>({ rule_start.position(), position() }, UpdateOp::Increment, move(rhs), true);
  635. }
  636. case TokenType::MinusMinus: {
  637. consume();
  638. auto rhs_start = position();
  639. auto rhs = parse_expression(precedence, associativity);
  640. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  641. // other engines throw ReferenceError for --foo()
  642. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  643. syntax_error(String::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  644. return create_ast_node<UpdateExpression>({ rule_start.position(), position() }, UpdateOp::Decrement, move(rhs), true);
  645. }
  646. case TokenType::ExclamationMark:
  647. consume();
  648. return create_ast_node<UnaryExpression>({ rule_start.position(), position() }, UnaryOp::Not, parse_expression(precedence, associativity));
  649. case TokenType::Tilde:
  650. consume();
  651. return create_ast_node<UnaryExpression>({ rule_start.position(), position() }, UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  652. case TokenType::Plus:
  653. consume();
  654. return create_ast_node<UnaryExpression>({ rule_start.position(), position() }, UnaryOp::Plus, parse_expression(precedence, associativity));
  655. case TokenType::Minus:
  656. consume();
  657. return create_ast_node<UnaryExpression>({ rule_start.position(), position() }, UnaryOp::Minus, parse_expression(precedence, associativity));
  658. case TokenType::Typeof:
  659. consume();
  660. return create_ast_node<UnaryExpression>({ rule_start.position(), position() }, UnaryOp::Typeof, parse_expression(precedence, associativity));
  661. case TokenType::Void:
  662. consume();
  663. return create_ast_node<UnaryExpression>({ rule_start.position(), position() }, UnaryOp::Void, parse_expression(precedence, associativity));
  664. case TokenType::Delete:
  665. consume();
  666. return create_ast_node<UnaryExpression>({ rule_start.position(), position() }, UnaryOp::Delete, parse_expression(precedence, associativity));
  667. default:
  668. expected("primary expression");
  669. consume();
  670. return create_ast_node<ErrorExpression>({ rule_start.position(), position() });
  671. }
  672. }
  673. NonnullRefPtr<Expression> Parser::parse_property_key()
  674. {
  675. auto rule_start = push_start();
  676. if (match(TokenType::StringLiteral)) {
  677. return parse_string_literal(consume());
  678. } else if (match(TokenType::NumericLiteral)) {
  679. return create_ast_node<NumericLiteral>({ rule_start.position(), position() }, consume().double_value());
  680. } else if (match(TokenType::BigIntLiteral)) {
  681. return create_ast_node<BigIntLiteral>({ rule_start.position(), position() }, consume().value());
  682. } else if (match(TokenType::BracketOpen)) {
  683. consume(TokenType::BracketOpen);
  684. auto result = parse_expression(0);
  685. consume(TokenType::BracketClose);
  686. return result;
  687. } else {
  688. if (!match_identifier_name())
  689. expected("IdentifierName");
  690. return create_ast_node<StringLiteral>({ rule_start.position(), position() }, consume().value());
  691. }
  692. }
  693. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  694. {
  695. auto rule_start = push_start();
  696. consume(TokenType::CurlyOpen);
  697. NonnullRefPtrVector<ObjectProperty> properties;
  698. ObjectProperty::Type property_type;
  699. auto skip_to_next_property = [&] {
  700. while (!done() && !match(TokenType::Comma) && !match(TokenType::CurlyOpen))
  701. consume();
  702. };
  703. while (!done() && !match(TokenType::CurlyClose)) {
  704. property_type = ObjectProperty::Type::KeyValue;
  705. RefPtr<Expression> property_name;
  706. RefPtr<Expression> property_value;
  707. if (match(TokenType::TripleDot)) {
  708. consume();
  709. property_name = parse_expression(4);
  710. properties.append(create_ast_node<ObjectProperty>({ rule_start.position(), position() }, *property_name, nullptr, ObjectProperty::Type::Spread, false));
  711. if (!match(TokenType::Comma))
  712. break;
  713. consume(TokenType::Comma);
  714. continue;
  715. }
  716. if (match(TokenType::Identifier)) {
  717. auto identifier = consume().value();
  718. if (identifier == "get" && match_property_key()) {
  719. property_type = ObjectProperty::Type::Getter;
  720. property_name = parse_property_key();
  721. } else if (identifier == "set" && match_property_key()) {
  722. property_type = ObjectProperty::Type::Setter;
  723. property_name = parse_property_key();
  724. } else {
  725. property_name = create_ast_node<StringLiteral>({ rule_start.position(), position() }, identifier);
  726. property_value = create_ast_node<Identifier>({ rule_start.position(), position() }, identifier);
  727. }
  728. } else {
  729. property_name = parse_property_key();
  730. }
  731. if (property_type == ObjectProperty::Type::Getter || property_type == ObjectProperty::Type::Setter) {
  732. if (!match(TokenType::ParenOpen)) {
  733. syntax_error("Expected '(' for object getter or setter property");
  734. skip_to_next_property();
  735. continue;
  736. }
  737. }
  738. if (match(TokenType::ParenOpen)) {
  739. ASSERT(property_name);
  740. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  741. if (property_type == ObjectProperty::Type::Getter)
  742. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  743. if (property_type == ObjectProperty::Type::Setter)
  744. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  745. auto function = parse_function_node<FunctionExpression>(parse_options);
  746. properties.append(create_ast_node<ObjectProperty>({ rule_start.position(), position() }, *property_name, function, property_type, true));
  747. } else if (match(TokenType::Colon)) {
  748. if (!property_name) {
  749. syntax_error("Expected a property name");
  750. skip_to_next_property();
  751. continue;
  752. }
  753. consume();
  754. properties.append(create_ast_node<ObjectProperty>({ rule_start.position(), position() }, *property_name, parse_expression(2), property_type, false));
  755. } else if (property_name && property_value) {
  756. properties.append(create_ast_node<ObjectProperty>({ rule_start.position(), position() }, *property_name, *property_value, property_type, false));
  757. } else {
  758. syntax_error("Expected a property");
  759. skip_to_next_property();
  760. continue;
  761. }
  762. if (!match(TokenType::Comma))
  763. break;
  764. consume(TokenType::Comma);
  765. }
  766. consume(TokenType::CurlyClose);
  767. return create_ast_node<ObjectExpression>({ rule_start.position(), position() }, properties);
  768. }
  769. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  770. {
  771. auto rule_start = push_start();
  772. consume(TokenType::BracketOpen);
  773. Vector<RefPtr<Expression>> elements;
  774. while (match_expression() || match(TokenType::TripleDot) || match(TokenType::Comma)) {
  775. RefPtr<Expression> expression;
  776. if (match(TokenType::TripleDot)) {
  777. consume(TokenType::TripleDot);
  778. expression = create_ast_node<SpreadExpression>({ rule_start.position(), position() }, parse_expression(2));
  779. } else if (match_expression()) {
  780. expression = parse_expression(2);
  781. }
  782. elements.append(expression);
  783. if (!match(TokenType::Comma))
  784. break;
  785. consume(TokenType::Comma);
  786. }
  787. consume(TokenType::BracketClose);
  788. return create_ast_node<ArrayExpression>({ rule_start.position(), position() }, move(elements));
  789. }
  790. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(Token token, bool in_template_literal)
  791. {
  792. auto rule_start = push_start();
  793. auto status = Token::StringValueStatus::Ok;
  794. auto string = token.string_value(status);
  795. if (status != Token::StringValueStatus::Ok) {
  796. String message;
  797. if (status == Token::StringValueStatus::LegacyOctalEscapeSequence) {
  798. m_parser_state.m_string_legacy_octal_escape_sequence_in_scope = true;
  799. if (in_template_literal)
  800. message = "Octal escape sequence not allowed in template literal";
  801. else if (m_parser_state.m_strict_mode)
  802. message = "Octal escape sequence in string literal not allowed in strict mode";
  803. } else if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) {
  804. auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal";
  805. message = String::formatted("Malformed {} escape sequence", type);
  806. } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) {
  807. message = "Unicode code_point must not be greater than 0x10ffff in escape sequence";
  808. } else {
  809. ASSERT_NOT_REACHED();
  810. }
  811. if (!message.is_empty())
  812. syntax_error(message, Position { token.line_number(), token.line_column() });
  813. }
  814. auto is_use_strict_directive = !in_template_literal && (token.value() == "'use strict'" || token.value() == "\"use strict\"");
  815. return create_ast_node<StringLiteral>({ rule_start.position(), position() }, string, is_use_strict_directive);
  816. }
  817. NonnullRefPtr<TemplateLiteral> Parser::parse_template_literal(bool is_tagged)
  818. {
  819. auto rule_start = push_start();
  820. consume(TokenType::TemplateLiteralStart);
  821. NonnullRefPtrVector<Expression> expressions;
  822. NonnullRefPtrVector<Expression> raw_strings;
  823. auto append_empty_string = [this, &rule_start, &expressions, &raw_strings, is_tagged]() {
  824. auto string_literal = create_ast_node<StringLiteral>({ rule_start.position(), position() }, "");
  825. expressions.append(string_literal);
  826. if (is_tagged)
  827. raw_strings.append(string_literal);
  828. };
  829. if (!match(TokenType::TemplateLiteralString))
  830. append_empty_string();
  831. while (!done() && !match(TokenType::TemplateLiteralEnd) && !match(TokenType::UnterminatedTemplateLiteral)) {
  832. if (match(TokenType::TemplateLiteralString)) {
  833. auto token = consume();
  834. expressions.append(parse_string_literal(token, true));
  835. if (is_tagged)
  836. raw_strings.append(create_ast_node<StringLiteral>({ rule_start.position(), position() }, token.value()));
  837. } else if (match(TokenType::TemplateLiteralExprStart)) {
  838. consume(TokenType::TemplateLiteralExprStart);
  839. if (match(TokenType::TemplateLiteralExprEnd)) {
  840. syntax_error("Empty template literal expression block");
  841. return create_ast_node<TemplateLiteral>({ rule_start.position(), position() }, expressions);
  842. }
  843. expressions.append(parse_expression(0));
  844. if (match(TokenType::UnterminatedTemplateLiteral)) {
  845. syntax_error("Unterminated template literal");
  846. return create_ast_node<TemplateLiteral>({ rule_start.position(), position() }, expressions);
  847. }
  848. consume(TokenType::TemplateLiteralExprEnd);
  849. if (!match(TokenType::TemplateLiteralString))
  850. append_empty_string();
  851. } else {
  852. expected("Template literal string or expression");
  853. break;
  854. }
  855. }
  856. if (match(TokenType::UnterminatedTemplateLiteral)) {
  857. syntax_error("Unterminated template literal");
  858. } else {
  859. consume(TokenType::TemplateLiteralEnd);
  860. }
  861. if (is_tagged)
  862. return create_ast_node<TemplateLiteral>({ rule_start.position(), position() }, expressions, raw_strings);
  863. return create_ast_node<TemplateLiteral>({ rule_start.position(), position() }, expressions);
  864. }
  865. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity, Vector<TokenType> forbidden)
  866. {
  867. auto rule_start = push_start();
  868. auto expression = parse_primary_expression();
  869. while (match(TokenType::TemplateLiteralStart)) {
  870. auto template_literal = parse_template_literal(true);
  871. expression = create_ast_node<TaggedTemplateLiteral>({ rule_start.position(), position() }, move(expression), move(template_literal));
  872. }
  873. while (match_secondary_expression(forbidden)) {
  874. int new_precedence = g_operator_precedence.get(m_parser_state.m_current_token.type());
  875. if (new_precedence < min_precedence)
  876. break;
  877. if (new_precedence == min_precedence && associativity == Associativity::Left)
  878. break;
  879. Associativity new_associativity = operator_associativity(m_parser_state.m_current_token.type());
  880. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  881. while (match(TokenType::TemplateLiteralStart)) {
  882. auto template_literal = parse_template_literal(true);
  883. expression = create_ast_node<TaggedTemplateLiteral>({ rule_start.position(), position() }, move(expression), move(template_literal));
  884. }
  885. }
  886. if (match(TokenType::Comma) && min_precedence <= 1) {
  887. NonnullRefPtrVector<Expression> expressions;
  888. expressions.append(expression);
  889. while (match(TokenType::Comma)) {
  890. consume();
  891. expressions.append(parse_expression(2));
  892. }
  893. expression = create_ast_node<SequenceExpression>({ rule_start.position(), position() }, move(expressions));
  894. }
  895. return expression;
  896. }
  897. NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  898. {
  899. auto rule_start = push_start();
  900. switch (m_parser_state.m_current_token.type()) {
  901. case TokenType::Plus:
  902. consume();
  903. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity));
  904. case TokenType::PlusEquals:
  905. return parse_assignment_expression(AssignmentOp::AdditionAssignment, move(lhs), min_precedence, associativity);
  906. case TokenType::Minus:
  907. consume();
  908. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity));
  909. case TokenType::MinusEquals:
  910. return parse_assignment_expression(AssignmentOp::SubtractionAssignment, move(lhs), min_precedence, associativity);
  911. case TokenType::Asterisk:
  912. consume();
  913. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity));
  914. case TokenType::AsteriskEquals:
  915. return parse_assignment_expression(AssignmentOp::MultiplicationAssignment, move(lhs), min_precedence, associativity);
  916. case TokenType::Slash:
  917. consume();
  918. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity));
  919. case TokenType::SlashEquals:
  920. return parse_assignment_expression(AssignmentOp::DivisionAssignment, move(lhs), min_precedence, associativity);
  921. case TokenType::Percent:
  922. consume();
  923. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity));
  924. case TokenType::PercentEquals:
  925. return parse_assignment_expression(AssignmentOp::ModuloAssignment, move(lhs), min_precedence, associativity);
  926. case TokenType::DoubleAsterisk:
  927. consume();
  928. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity));
  929. case TokenType::DoubleAsteriskEquals:
  930. return parse_assignment_expression(AssignmentOp::ExponentiationAssignment, move(lhs), min_precedence, associativity);
  931. case TokenType::GreaterThan:
  932. consume();
  933. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  934. case TokenType::GreaterThanEquals:
  935. consume();
  936. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  937. case TokenType::LessThan:
  938. consume();
  939. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  940. case TokenType::LessThanEquals:
  941. consume();
  942. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  943. case TokenType::EqualsEqualsEquals:
  944. consume();
  945. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::TypedEquals, move(lhs), parse_expression(min_precedence, associativity));
  946. case TokenType::ExclamationMarkEqualsEquals:
  947. consume();
  948. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::TypedInequals, move(lhs), parse_expression(min_precedence, associativity));
  949. case TokenType::EqualsEquals:
  950. consume();
  951. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::AbstractEquals, move(lhs), parse_expression(min_precedence, associativity));
  952. case TokenType::ExclamationMarkEquals:
  953. consume();
  954. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::AbstractInequals, move(lhs), parse_expression(min_precedence, associativity));
  955. case TokenType::In:
  956. consume();
  957. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::In, move(lhs), parse_expression(min_precedence, associativity));
  958. case TokenType::Instanceof:
  959. consume();
  960. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity));
  961. case TokenType::Ampersand:
  962. consume();
  963. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity));
  964. case TokenType::AmpersandEquals:
  965. return parse_assignment_expression(AssignmentOp::BitwiseAndAssignment, move(lhs), min_precedence, associativity);
  966. case TokenType::Pipe:
  967. consume();
  968. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity));
  969. case TokenType::PipeEquals:
  970. return parse_assignment_expression(AssignmentOp::BitwiseOrAssignment, move(lhs), min_precedence, associativity);
  971. case TokenType::Caret:
  972. consume();
  973. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity));
  974. case TokenType::CaretEquals:
  975. return parse_assignment_expression(AssignmentOp::BitwiseXorAssignment, move(lhs), min_precedence, associativity);
  976. case TokenType::ShiftLeft:
  977. consume();
  978. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::LeftShift, move(lhs), parse_expression(min_precedence, associativity));
  979. case TokenType::ShiftLeftEquals:
  980. return parse_assignment_expression(AssignmentOp::LeftShiftAssignment, move(lhs), min_precedence, associativity);
  981. case TokenType::ShiftRight:
  982. consume();
  983. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::RightShift, move(lhs), parse_expression(min_precedence, associativity));
  984. case TokenType::ShiftRightEquals:
  985. return parse_assignment_expression(AssignmentOp::RightShiftAssignment, move(lhs), min_precedence, associativity);
  986. case TokenType::UnsignedShiftRight:
  987. consume();
  988. return create_ast_node<BinaryExpression>({ rule_start.position(), position() }, BinaryOp::UnsignedRightShift, move(lhs), parse_expression(min_precedence, associativity));
  989. case TokenType::UnsignedShiftRightEquals:
  990. return parse_assignment_expression(AssignmentOp::UnsignedRightShiftAssignment, move(lhs), min_precedence, associativity);
  991. case TokenType::ParenOpen:
  992. return parse_call_expression(move(lhs));
  993. case TokenType::Equals:
  994. return parse_assignment_expression(AssignmentOp::Assignment, move(lhs), min_precedence, associativity);
  995. case TokenType::Period:
  996. consume();
  997. if (!match_identifier_name())
  998. expected("IdentifierName");
  999. return create_ast_node<MemberExpression>({ rule_start.position(), position() }, move(lhs), create_ast_node<Identifier>({ rule_start.position(), position() }, consume().value()));
  1000. case TokenType::BracketOpen: {
  1001. consume(TokenType::BracketOpen);
  1002. auto expression = create_ast_node<MemberExpression>({ rule_start.position(), position() }, move(lhs), parse_expression(0), true);
  1003. consume(TokenType::BracketClose);
  1004. return expression;
  1005. }
  1006. case TokenType::PlusPlus:
  1007. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1008. // other engines throw ReferenceError for foo()++
  1009. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1010. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1011. consume();
  1012. return create_ast_node<UpdateExpression>({ rule_start.position(), position() }, UpdateOp::Increment, move(lhs));
  1013. case TokenType::MinusMinus:
  1014. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1015. // other engines throw ReferenceError for foo()--
  1016. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1017. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1018. consume();
  1019. return create_ast_node<UpdateExpression>({ rule_start.position(), position() }, UpdateOp::Decrement, move(lhs));
  1020. case TokenType::DoubleAmpersand:
  1021. consume();
  1022. return create_ast_node<LogicalExpression>({ rule_start.position(), position() }, LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity));
  1023. case TokenType::DoubleAmpersandEquals:
  1024. return parse_assignment_expression(AssignmentOp::AndAssignment, move(lhs), min_precedence, associativity);
  1025. case TokenType::DoublePipe:
  1026. consume();
  1027. return create_ast_node<LogicalExpression>({ rule_start.position(), position() }, LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity));
  1028. case TokenType::DoublePipeEquals:
  1029. return parse_assignment_expression(AssignmentOp::OrAssignment, move(lhs), min_precedence, associativity);
  1030. case TokenType::DoubleQuestionMark:
  1031. consume();
  1032. return create_ast_node<LogicalExpression>({ rule_start.position(), position() }, LogicalOp::NullishCoalescing, move(lhs), parse_expression(min_precedence, associativity));
  1033. case TokenType::DoubleQuestionMarkEquals:
  1034. return parse_assignment_expression(AssignmentOp::NullishAssignment, move(lhs), min_precedence, associativity);
  1035. case TokenType::QuestionMark:
  1036. return parse_conditional_expression(move(lhs));
  1037. default:
  1038. expected("secondary expression");
  1039. consume();
  1040. return create_ast_node<ErrorExpression>({ rule_start.position(), position() });
  1041. }
  1042. }
  1043. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(AssignmentOp assignment_op, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  1044. {
  1045. auto rule_start = push_start();
  1046. ASSERT(match(TokenType::Equals)
  1047. || match(TokenType::PlusEquals)
  1048. || match(TokenType::MinusEquals)
  1049. || match(TokenType::AsteriskEquals)
  1050. || match(TokenType::SlashEquals)
  1051. || match(TokenType::PercentEquals)
  1052. || match(TokenType::DoubleAsteriskEquals)
  1053. || match(TokenType::AmpersandEquals)
  1054. || match(TokenType::PipeEquals)
  1055. || match(TokenType::CaretEquals)
  1056. || match(TokenType::ShiftLeftEquals)
  1057. || match(TokenType::ShiftRightEquals)
  1058. || match(TokenType::UnsignedShiftRightEquals)
  1059. || match(TokenType::DoubleAmpersandEquals)
  1060. || match(TokenType::DoublePipeEquals)
  1061. || match(TokenType::DoubleQuestionMarkEquals));
  1062. consume();
  1063. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs) && !is<CallExpression>(*lhs)) {
  1064. syntax_error("Invalid left-hand side in assignment");
  1065. } else if (m_parser_state.m_strict_mode && is<Identifier>(*lhs)) {
  1066. auto name = static_cast<const Identifier&>(*lhs).string();
  1067. if (name == "eval" || name == "arguments")
  1068. syntax_error(String::formatted("'{}' cannot be assigned to in strict mode code", name));
  1069. } else if (m_parser_state.m_strict_mode && is<CallExpression>(*lhs)) {
  1070. syntax_error("Cannot assign to function call");
  1071. }
  1072. return create_ast_node<AssignmentExpression>({ rule_start.position(), position() }, assignment_op, move(lhs), parse_expression(min_precedence, associativity));
  1073. }
  1074. NonnullRefPtr<CallExpression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  1075. {
  1076. auto rule_start = push_start();
  1077. if (!m_parser_state.m_allow_super_constructor_call && is<SuperExpression>(*lhs))
  1078. syntax_error("'super' keyword unexpected here");
  1079. consume(TokenType::ParenOpen);
  1080. Vector<CallExpression::Argument> arguments;
  1081. while (match_expression() || match(TokenType::TripleDot)) {
  1082. if (match(TokenType::TripleDot)) {
  1083. consume();
  1084. arguments.append({ parse_expression(2), true });
  1085. } else {
  1086. arguments.append({ parse_expression(2), false });
  1087. }
  1088. if (!match(TokenType::Comma))
  1089. break;
  1090. consume();
  1091. }
  1092. consume(TokenType::ParenClose);
  1093. return create_ast_node<CallExpression>({ rule_start.position(), position() }, move(lhs), move(arguments));
  1094. }
  1095. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  1096. {
  1097. auto rule_start = push_start();
  1098. consume(TokenType::New);
  1099. auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen });
  1100. Vector<CallExpression::Argument> arguments;
  1101. if (match(TokenType::ParenOpen)) {
  1102. consume(TokenType::ParenOpen);
  1103. while (match_expression() || match(TokenType::TripleDot)) {
  1104. if (match(TokenType::TripleDot)) {
  1105. consume();
  1106. arguments.append({ parse_expression(2), true });
  1107. } else {
  1108. arguments.append({ parse_expression(2), false });
  1109. }
  1110. if (!match(TokenType::Comma))
  1111. break;
  1112. consume();
  1113. }
  1114. consume(TokenType::ParenClose);
  1115. }
  1116. return create_ast_node<NewExpression>({ rule_start.position(), position() }, move(callee), move(arguments));
  1117. }
  1118. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  1119. {
  1120. auto rule_start = push_start();
  1121. if (!m_parser_state.m_in_function_context && !m_parser_state.m_in_arrow_function_context)
  1122. syntax_error("'return' not allowed outside of a function");
  1123. consume(TokenType::Return);
  1124. // Automatic semicolon insertion: terminate statement when return is followed by newline
  1125. if (m_parser_state.m_current_token.trivia_contains_line_terminator())
  1126. return create_ast_node<ReturnStatement>({ rule_start.position(), position() }, nullptr);
  1127. if (match_expression()) {
  1128. auto expression = parse_expression(0);
  1129. consume_or_insert_semicolon();
  1130. return create_ast_node<ReturnStatement>({ rule_start.position(), position() }, move(expression));
  1131. }
  1132. consume_or_insert_semicolon();
  1133. return create_ast_node<ReturnStatement>({ rule_start.position(), position() }, nullptr);
  1134. }
  1135. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  1136. {
  1137. auto rule_start = push_start();
  1138. bool dummy = false;
  1139. return parse_block_statement(dummy);
  1140. }
  1141. NonnullRefPtr<BlockStatement> Parser::parse_block_statement(bool& is_strict)
  1142. {
  1143. auto rule_start = push_start();
  1144. ScopePusher scope(*this, ScopePusher::Let);
  1145. auto block = create_ast_node<BlockStatement>({ rule_start.position(), position() });
  1146. consume(TokenType::CurlyOpen);
  1147. bool first = true;
  1148. bool initial_strict_mode_state = m_parser_state.m_strict_mode;
  1149. if (initial_strict_mode_state)
  1150. is_strict = true;
  1151. while (!done() && !match(TokenType::CurlyClose)) {
  1152. if (match_declaration()) {
  1153. block->append(parse_declaration());
  1154. } else if (match_statement()) {
  1155. auto statement = parse_statement();
  1156. block->append(statement);
  1157. if (statement_is_use_strict_directive(statement)) {
  1158. if (first && !initial_strict_mode_state) {
  1159. is_strict = true;
  1160. m_parser_state.m_strict_mode = true;
  1161. }
  1162. if (m_parser_state.m_string_legacy_octal_escape_sequence_in_scope)
  1163. syntax_error("Octal escape sequence in string literal not allowed in strict mode");
  1164. }
  1165. } else {
  1166. expected("statement or declaration");
  1167. consume();
  1168. }
  1169. first = false;
  1170. }
  1171. m_parser_state.m_strict_mode = initial_strict_mode_state;
  1172. m_parser_state.m_string_legacy_octal_escape_sequence_in_scope = false;
  1173. consume(TokenType::CurlyClose);
  1174. block->add_variables(m_parser_state.m_let_scopes.last());
  1175. block->add_functions(m_parser_state.m_function_scopes.last());
  1176. return block;
  1177. }
  1178. template<typename FunctionNodeType>
  1179. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(u8 parse_options)
  1180. {
  1181. auto rule_start = push_start();
  1182. ASSERT(!(parse_options & FunctionNodeParseOptions::IsGetterFunction && parse_options & FunctionNodeParseOptions::IsSetterFunction));
  1183. TemporaryChange super_property_access_rollback(m_parser_state.m_allow_super_property_lookup, !!(parse_options & FunctionNodeParseOptions::AllowSuperPropertyLookup));
  1184. TemporaryChange super_constructor_call_rollback(m_parser_state.m_allow_super_constructor_call, !!(parse_options & FunctionNodeParseOptions::AllowSuperConstructorCall));
  1185. ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Function);
  1186. String name;
  1187. if (parse_options & FunctionNodeParseOptions::CheckForFunctionAndName) {
  1188. consume(TokenType::Function);
  1189. if (FunctionNodeType::must_have_name() || match(TokenType::Identifier))
  1190. name = consume(TokenType::Identifier).value();
  1191. }
  1192. consume(TokenType::ParenOpen);
  1193. i32 function_length = -1;
  1194. auto parameters = parse_function_parameters(function_length, parse_options);
  1195. consume(TokenType::ParenClose);
  1196. if (function_length == -1)
  1197. function_length = parameters.size();
  1198. TemporaryChange change(m_parser_state.m_in_function_context, true);
  1199. auto old_labels_in_scope = move(m_parser_state.m_labels_in_scope);
  1200. ScopeGuard guard([&]() {
  1201. m_parser_state.m_labels_in_scope = move(old_labels_in_scope);
  1202. });
  1203. bool is_strict = false;
  1204. auto body = parse_block_statement(is_strict);
  1205. body->add_variables(m_parser_state.m_var_scopes.last());
  1206. body->add_functions(m_parser_state.m_function_scopes.last());
  1207. return create_ast_node<FunctionNodeType>({ rule_start.position(), position() }, name, move(body), move(parameters), function_length, NonnullRefPtrVector<VariableDeclaration>(), is_strict);
  1208. }
  1209. Vector<FunctionNode::Parameter> Parser::parse_function_parameters(int& function_length, u8 parse_options)
  1210. {
  1211. auto rule_start = push_start();
  1212. bool has_default_parameter = false;
  1213. bool has_rest_parameter = false;
  1214. Vector<FunctionNode::Parameter> parameters;
  1215. auto consume_and_validate_identifier = [&]() -> Token {
  1216. auto token = consume(TokenType::Identifier);
  1217. auto parameter_name = token.value();
  1218. for (auto& parameter : parameters) {
  1219. if (parameter_name != parameter.name)
  1220. continue;
  1221. String message;
  1222. if (parse_options & FunctionNodeParseOptions::IsArrowFunction)
  1223. message = String::formatted("Duplicate parameter '{}' not allowed in arrow function", parameter_name);
  1224. else if (m_parser_state.m_strict_mode)
  1225. message = String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name);
  1226. else if (has_default_parameter || match(TokenType::Equals))
  1227. message = String::formatted("Duplicate parameter '{}' not allowed in function with default parameter", parameter_name);
  1228. else if (has_rest_parameter)
  1229. message = String::formatted("Duplicate parameter '{}' not allowed in function with rest parameter", parameter_name);
  1230. if (!message.is_empty())
  1231. syntax_error(message, Position { token.line_number(), token.line_column() });
  1232. break;
  1233. }
  1234. return token;
  1235. };
  1236. while (match(TokenType::Identifier) || match(TokenType::TripleDot)) {
  1237. if (parse_options & FunctionNodeParseOptions::IsGetterFunction)
  1238. syntax_error("Getter function must have no arguments");
  1239. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && (parameters.size() >= 1 || match(TokenType::TripleDot)))
  1240. syntax_error("Setter function must have one argument");
  1241. if (match(TokenType::TripleDot)) {
  1242. consume();
  1243. has_rest_parameter = true;
  1244. auto parameter_name = consume_and_validate_identifier().value();
  1245. function_length = parameters.size();
  1246. parameters.append({ parameter_name, nullptr, true });
  1247. break;
  1248. }
  1249. auto parameter_name = consume_and_validate_identifier().value();
  1250. RefPtr<Expression> default_value;
  1251. if (match(TokenType::Equals)) {
  1252. consume();
  1253. has_default_parameter = true;
  1254. function_length = parameters.size();
  1255. default_value = parse_expression(2);
  1256. }
  1257. parameters.append({ parameter_name, default_value });
  1258. if (match(TokenType::ParenClose))
  1259. break;
  1260. consume(TokenType::Comma);
  1261. }
  1262. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && parameters.is_empty())
  1263. syntax_error("Setter function must have one argument");
  1264. return parameters;
  1265. }
  1266. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool for_loop_variable_declaration)
  1267. {
  1268. auto rule_start = push_start();
  1269. DeclarationKind declaration_kind;
  1270. switch (m_parser_state.m_current_token.type()) {
  1271. case TokenType::Var:
  1272. declaration_kind = DeclarationKind::Var;
  1273. break;
  1274. case TokenType::Let:
  1275. declaration_kind = DeclarationKind::Let;
  1276. break;
  1277. case TokenType::Const:
  1278. declaration_kind = DeclarationKind::Const;
  1279. break;
  1280. default:
  1281. ASSERT_NOT_REACHED();
  1282. }
  1283. consume();
  1284. NonnullRefPtrVector<VariableDeclarator> declarations;
  1285. for (;;) {
  1286. auto id = consume(TokenType::Identifier).value();
  1287. RefPtr<Expression> init;
  1288. if (match(TokenType::Equals)) {
  1289. consume();
  1290. init = parse_expression(2);
  1291. } else if (!for_loop_variable_declaration && declaration_kind == DeclarationKind::Const) {
  1292. syntax_error("Missing initializer in 'const' variable declaration");
  1293. }
  1294. declarations.append(create_ast_node<VariableDeclarator>({ rule_start.position(), position() }, create_ast_node<Identifier>({ rule_start.position(), position() }, move(id)), move(init)));
  1295. if (match(TokenType::Comma)) {
  1296. consume();
  1297. continue;
  1298. }
  1299. break;
  1300. }
  1301. if (!for_loop_variable_declaration)
  1302. consume_or_insert_semicolon();
  1303. auto declaration = create_ast_node<VariableDeclaration>({ rule_start.position(), position() }, declaration_kind, move(declarations));
  1304. if (declaration_kind == DeclarationKind::Var)
  1305. m_parser_state.m_var_scopes.last().append(declaration);
  1306. else
  1307. m_parser_state.m_let_scopes.last().append(declaration);
  1308. return declaration;
  1309. }
  1310. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  1311. {
  1312. auto rule_start = push_start();
  1313. consume(TokenType::Throw);
  1314. // Automatic semicolon insertion: terminate statement when throw is followed by newline
  1315. if (m_parser_state.m_current_token.trivia_contains_line_terminator()) {
  1316. syntax_error("No line break is allowed between 'throw' and its expression");
  1317. return create_ast_node<ThrowStatement>({ rule_start.position(), position() }, create_ast_node<ErrorExpression>({ rule_start.position(), position() }));
  1318. }
  1319. auto expression = parse_expression(0);
  1320. consume_or_insert_semicolon();
  1321. return create_ast_node<ThrowStatement>({ rule_start.position(), position() }, move(expression));
  1322. }
  1323. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  1324. {
  1325. auto rule_start = push_start();
  1326. consume(TokenType::Break);
  1327. FlyString target_label;
  1328. if (match(TokenType::Semicolon)) {
  1329. consume();
  1330. } else {
  1331. if (match(TokenType::Identifier) && !m_parser_state.m_current_token.trivia_contains_line_terminator()) {
  1332. target_label = consume().value();
  1333. if (!m_parser_state.m_labels_in_scope.contains(target_label))
  1334. syntax_error(String::formatted("Label '{}' not found", target_label));
  1335. }
  1336. consume_or_insert_semicolon();
  1337. }
  1338. if (target_label.is_null() && !m_parser_state.m_in_break_context)
  1339. syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement");
  1340. return create_ast_node<BreakStatement>({ rule_start.position(), position() }, target_label);
  1341. }
  1342. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  1343. {
  1344. auto rule_start = push_start();
  1345. if (!m_parser_state.m_in_continue_context)
  1346. syntax_error("'continue' not allow outside of a loop");
  1347. consume(TokenType::Continue);
  1348. FlyString target_label;
  1349. if (match(TokenType::Semicolon)) {
  1350. consume();
  1351. return create_ast_node<ContinueStatement>({ rule_start.position(), position() }, target_label);
  1352. }
  1353. if (match(TokenType::Identifier) && !m_parser_state.m_current_token.trivia_contains_line_terminator()) {
  1354. target_label = consume().value();
  1355. if (!m_parser_state.m_labels_in_scope.contains(target_label))
  1356. syntax_error(String::formatted("Label '{}' not found", target_label));
  1357. }
  1358. consume_or_insert_semicolon();
  1359. return create_ast_node<ContinueStatement>({ rule_start.position(), position() }, target_label);
  1360. }
  1361. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test)
  1362. {
  1363. auto rule_start = push_start();
  1364. consume(TokenType::QuestionMark);
  1365. auto consequent = parse_expression(2);
  1366. consume(TokenType::Colon);
  1367. auto alternate = parse_expression(2);
  1368. return create_ast_node<ConditionalExpression>({ rule_start.position(), position() }, move(test), move(consequent), move(alternate));
  1369. }
  1370. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  1371. {
  1372. auto rule_start = push_start();
  1373. consume(TokenType::Try);
  1374. auto block = parse_block_statement();
  1375. RefPtr<CatchClause> handler;
  1376. if (match(TokenType::Catch))
  1377. handler = parse_catch_clause();
  1378. RefPtr<BlockStatement> finalizer;
  1379. if (match(TokenType::Finally)) {
  1380. consume();
  1381. finalizer = parse_block_statement();
  1382. }
  1383. if (!handler && !finalizer)
  1384. syntax_error("try statement must have a 'catch' or 'finally' clause");
  1385. return create_ast_node<TryStatement>({ rule_start.position(), position() }, move(block), move(handler), move(finalizer));
  1386. }
  1387. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  1388. {
  1389. auto rule_start = push_start();
  1390. consume(TokenType::Do);
  1391. auto body = [&]() -> NonnullRefPtr<Statement> {
  1392. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1393. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1394. return parse_statement();
  1395. }();
  1396. consume(TokenType::While);
  1397. consume(TokenType::ParenOpen);
  1398. auto test = parse_expression(0);
  1399. consume(TokenType::ParenClose);
  1400. // Since ES 2015 a missing semicolon is inserted here, despite the regular ASI rules not applying
  1401. if (match(TokenType::Semicolon))
  1402. consume();
  1403. return create_ast_node<DoWhileStatement>({ rule_start.position(), position() }, move(test), move(body));
  1404. }
  1405. NonnullRefPtr<WhileStatement> Parser::parse_while_statement()
  1406. {
  1407. auto rule_start = push_start();
  1408. consume(TokenType::While);
  1409. consume(TokenType::ParenOpen);
  1410. auto test = parse_expression(0);
  1411. consume(TokenType::ParenClose);
  1412. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1413. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1414. auto body = parse_statement();
  1415. return create_ast_node<WhileStatement>({ rule_start.position(), position() }, move(test), move(body));
  1416. }
  1417. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  1418. {
  1419. auto rule_start = push_start();
  1420. consume(TokenType::Switch);
  1421. consume(TokenType::ParenOpen);
  1422. auto determinant = parse_expression(0);
  1423. consume(TokenType::ParenClose);
  1424. consume(TokenType::CurlyOpen);
  1425. NonnullRefPtrVector<SwitchCase> cases;
  1426. auto has_default = false;
  1427. while (match(TokenType::Case) || match(TokenType::Default)) {
  1428. if (match(TokenType::Default)) {
  1429. if (has_default)
  1430. syntax_error("Multiple 'default' clauses in switch statement");
  1431. has_default = true;
  1432. }
  1433. cases.append(parse_switch_case());
  1434. }
  1435. consume(TokenType::CurlyClose);
  1436. return create_ast_node<SwitchStatement>({ rule_start.position(), position() }, move(determinant), move(cases));
  1437. }
  1438. NonnullRefPtr<WithStatement> Parser::parse_with_statement()
  1439. {
  1440. auto rule_start = push_start();
  1441. consume(TokenType::With);
  1442. consume(TokenType::ParenOpen);
  1443. auto object = parse_expression(0);
  1444. consume(TokenType::ParenClose);
  1445. auto body = parse_statement();
  1446. return create_ast_node<WithStatement>({ rule_start.position(), position() }, move(object), move(body));
  1447. }
  1448. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  1449. {
  1450. auto rule_start = push_start();
  1451. RefPtr<Expression> test;
  1452. if (consume().type() == TokenType::Case) {
  1453. test = parse_expression(0);
  1454. }
  1455. consume(TokenType::Colon);
  1456. NonnullRefPtrVector<Statement> consequent;
  1457. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1458. for (;;) {
  1459. if (match_declaration())
  1460. consequent.append(parse_declaration());
  1461. else if (match_statement())
  1462. consequent.append(parse_statement());
  1463. else
  1464. break;
  1465. }
  1466. return create_ast_node<SwitchCase>({ rule_start.position(), position() }, move(test), move(consequent));
  1467. }
  1468. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  1469. {
  1470. auto rule_start = push_start();
  1471. consume(TokenType::Catch);
  1472. String parameter;
  1473. if (match(TokenType::ParenOpen)) {
  1474. consume();
  1475. parameter = consume(TokenType::Identifier).value();
  1476. consume(TokenType::ParenClose);
  1477. }
  1478. auto body = parse_block_statement();
  1479. return create_ast_node<CatchClause>({ rule_start.position(), position() }, parameter, move(body));
  1480. }
  1481. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  1482. {
  1483. auto rule_start = push_start();
  1484. auto parse_function_declaration_as_block_statement = [&] {
  1485. // https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses
  1486. // Code matching this production is processed as if each matching occurrence of
  1487. // FunctionDeclaration[?Yield, ?Await, ~Default] was the sole StatementListItem
  1488. // of a BlockStatement occupying that position in the source code.
  1489. ScopePusher scope(*this, ScopePusher::Let);
  1490. auto block = create_ast_node<BlockStatement>({ rule_start.position(), position() });
  1491. block->append(parse_declaration());
  1492. block->add_functions(m_parser_state.m_function_scopes.last());
  1493. return block;
  1494. };
  1495. consume(TokenType::If);
  1496. consume(TokenType::ParenOpen);
  1497. auto predicate = parse_expression(0);
  1498. consume(TokenType::ParenClose);
  1499. RefPtr<Statement> consequent;
  1500. if (!m_parser_state.m_strict_mode && match(TokenType::Function))
  1501. consequent = parse_function_declaration_as_block_statement();
  1502. else
  1503. consequent = parse_statement();
  1504. RefPtr<Statement> alternate;
  1505. if (match(TokenType::Else)) {
  1506. consume();
  1507. if (!m_parser_state.m_strict_mode && match(TokenType::Function))
  1508. alternate = parse_function_declaration_as_block_statement();
  1509. else
  1510. alternate = parse_statement();
  1511. }
  1512. return create_ast_node<IfStatement>({ rule_start.position(), position() }, move(predicate), move(*consequent), move(alternate));
  1513. }
  1514. NonnullRefPtr<Statement> Parser::parse_for_statement()
  1515. {
  1516. auto rule_start = push_start();
  1517. auto match_for_in_of = [&]() {
  1518. return match(TokenType::In) || (match(TokenType::Identifier) && m_parser_state.m_current_token.value() == "of");
  1519. };
  1520. consume(TokenType::For);
  1521. consume(TokenType::ParenOpen);
  1522. bool in_scope = false;
  1523. RefPtr<ASTNode> init;
  1524. if (!match(TokenType::Semicolon)) {
  1525. if (match_expression()) {
  1526. init = parse_expression(0, Associativity::Right, { TokenType::In });
  1527. if (match_for_in_of())
  1528. return parse_for_in_of_statement(*init);
  1529. } else if (match_variable_declaration()) {
  1530. if (!match(TokenType::Var)) {
  1531. m_parser_state.m_let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  1532. in_scope = true;
  1533. }
  1534. init = parse_variable_declaration(true);
  1535. if (match_for_in_of())
  1536. return parse_for_in_of_statement(*init);
  1537. if (static_cast<VariableDeclaration&>(*init).declaration_kind() == DeclarationKind::Const) {
  1538. for (auto& declaration : static_cast<VariableDeclaration&>(*init).declarations()) {
  1539. if (!declaration.init())
  1540. syntax_error("Missing initializer in 'const' variable declaration");
  1541. }
  1542. }
  1543. } else {
  1544. syntax_error("Unexpected token in for loop");
  1545. }
  1546. }
  1547. consume(TokenType::Semicolon);
  1548. RefPtr<Expression> test;
  1549. if (!match(TokenType::Semicolon))
  1550. test = parse_expression(0);
  1551. consume(TokenType::Semicolon);
  1552. RefPtr<Expression> update;
  1553. if (!match(TokenType::ParenClose))
  1554. update = parse_expression(0);
  1555. consume(TokenType::ParenClose);
  1556. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1557. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1558. auto body = parse_statement();
  1559. if (in_scope) {
  1560. m_parser_state.m_let_scopes.take_last();
  1561. }
  1562. return create_ast_node<ForStatement>({ rule_start.position(), position() }, move(init), move(test), move(update), move(body));
  1563. }
  1564. NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs)
  1565. {
  1566. auto rule_start = push_start();
  1567. if (is<VariableDeclaration>(*lhs)) {
  1568. auto declarations = static_cast<VariableDeclaration&>(*lhs).declarations();
  1569. if (declarations.size() > 1)
  1570. syntax_error("multiple declarations not allowed in for..in/of");
  1571. if (declarations.first().init() != nullptr)
  1572. syntax_error("variable initializer not allowed in for..in/of");
  1573. }
  1574. auto in_or_of = consume();
  1575. auto rhs = parse_expression(0);
  1576. consume(TokenType::ParenClose);
  1577. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1578. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1579. auto body = parse_statement();
  1580. if (in_or_of.type() == TokenType::In)
  1581. return create_ast_node<ForInStatement>({ rule_start.position(), position() }, move(lhs), move(rhs), move(body));
  1582. return create_ast_node<ForOfStatement>({ rule_start.position(), position() }, move(lhs), move(rhs), move(body));
  1583. }
  1584. NonnullRefPtr<DebuggerStatement> Parser::parse_debugger_statement()
  1585. {
  1586. auto rule_start = push_start();
  1587. consume(TokenType::Debugger);
  1588. consume_or_insert_semicolon();
  1589. return create_ast_node<DebuggerStatement>({ rule_start.position(), position() });
  1590. }
  1591. bool Parser::match(TokenType type) const
  1592. {
  1593. return m_parser_state.m_current_token.type() == type;
  1594. }
  1595. bool Parser::match_expression() const
  1596. {
  1597. auto type = m_parser_state.m_current_token.type();
  1598. return type == TokenType::BoolLiteral
  1599. || type == TokenType::NumericLiteral
  1600. || type == TokenType::BigIntLiteral
  1601. || type == TokenType::StringLiteral
  1602. || type == TokenType::TemplateLiteralStart
  1603. || type == TokenType::NullLiteral
  1604. || type == TokenType::Identifier
  1605. || type == TokenType::New
  1606. || type == TokenType::CurlyOpen
  1607. || type == TokenType::BracketOpen
  1608. || type == TokenType::ParenOpen
  1609. || type == TokenType::Function
  1610. || type == TokenType::This
  1611. || type == TokenType::Super
  1612. || type == TokenType::RegexLiteral
  1613. || match_unary_prefixed_expression();
  1614. }
  1615. bool Parser::match_unary_prefixed_expression() const
  1616. {
  1617. auto type = m_parser_state.m_current_token.type();
  1618. return type == TokenType::PlusPlus
  1619. || type == TokenType::MinusMinus
  1620. || type == TokenType::ExclamationMark
  1621. || type == TokenType::Tilde
  1622. || type == TokenType::Plus
  1623. || type == TokenType::Minus
  1624. || type == TokenType::Typeof
  1625. || type == TokenType::Void
  1626. || type == TokenType::Delete;
  1627. }
  1628. bool Parser::match_secondary_expression(Vector<TokenType> forbidden) const
  1629. {
  1630. auto type = m_parser_state.m_current_token.type();
  1631. if (forbidden.contains_slow(type))
  1632. return false;
  1633. return type == TokenType::Plus
  1634. || type == TokenType::PlusEquals
  1635. || type == TokenType::Minus
  1636. || type == TokenType::MinusEquals
  1637. || type == TokenType::Asterisk
  1638. || type == TokenType::AsteriskEquals
  1639. || type == TokenType::Slash
  1640. || type == TokenType::SlashEquals
  1641. || type == TokenType::Percent
  1642. || type == TokenType::PercentEquals
  1643. || type == TokenType::DoubleAsterisk
  1644. || type == TokenType::DoubleAsteriskEquals
  1645. || type == TokenType::Equals
  1646. || type == TokenType::EqualsEqualsEquals
  1647. || type == TokenType::ExclamationMarkEqualsEquals
  1648. || type == TokenType::EqualsEquals
  1649. || type == TokenType::ExclamationMarkEquals
  1650. || type == TokenType::GreaterThan
  1651. || type == TokenType::GreaterThanEquals
  1652. || type == TokenType::LessThan
  1653. || type == TokenType::LessThanEquals
  1654. || type == TokenType::ParenOpen
  1655. || type == TokenType::Period
  1656. || type == TokenType::BracketOpen
  1657. || type == TokenType::PlusPlus
  1658. || type == TokenType::MinusMinus
  1659. || type == TokenType::In
  1660. || type == TokenType::Instanceof
  1661. || type == TokenType::QuestionMark
  1662. || type == TokenType::Ampersand
  1663. || type == TokenType::AmpersandEquals
  1664. || type == TokenType::Pipe
  1665. || type == TokenType::PipeEquals
  1666. || type == TokenType::Caret
  1667. || type == TokenType::CaretEquals
  1668. || type == TokenType::ShiftLeft
  1669. || type == TokenType::ShiftLeftEquals
  1670. || type == TokenType::ShiftRight
  1671. || type == TokenType::ShiftRightEquals
  1672. || type == TokenType::UnsignedShiftRight
  1673. || type == TokenType::UnsignedShiftRightEquals
  1674. || type == TokenType::DoubleAmpersand
  1675. || type == TokenType::DoubleAmpersandEquals
  1676. || type == TokenType::DoublePipe
  1677. || type == TokenType::DoublePipeEquals
  1678. || type == TokenType::DoubleQuestionMark
  1679. || type == TokenType::DoubleQuestionMarkEquals;
  1680. }
  1681. bool Parser::match_statement() const
  1682. {
  1683. auto type = m_parser_state.m_current_token.type();
  1684. return match_expression()
  1685. || type == TokenType::Return
  1686. || type == TokenType::Do
  1687. || type == TokenType::If
  1688. || type == TokenType::Throw
  1689. || type == TokenType::Try
  1690. || type == TokenType::While
  1691. || type == TokenType::With
  1692. || type == TokenType::For
  1693. || type == TokenType::CurlyOpen
  1694. || type == TokenType::Switch
  1695. || type == TokenType::Break
  1696. || type == TokenType::Continue
  1697. || type == TokenType::Var
  1698. || type == TokenType::Debugger
  1699. || type == TokenType::Semicolon;
  1700. }
  1701. bool Parser::match_declaration() const
  1702. {
  1703. auto type = m_parser_state.m_current_token.type();
  1704. return type == TokenType::Function
  1705. || type == TokenType::Class
  1706. || type == TokenType::Const
  1707. || type == TokenType::Let;
  1708. }
  1709. bool Parser::match_variable_declaration() const
  1710. {
  1711. auto type = m_parser_state.m_current_token.type();
  1712. return type == TokenType::Var
  1713. || type == TokenType::Let
  1714. || type == TokenType::Const;
  1715. }
  1716. bool Parser::match_identifier_name() const
  1717. {
  1718. return m_parser_state.m_current_token.is_identifier_name();
  1719. }
  1720. bool Parser::match_property_key() const
  1721. {
  1722. auto type = m_parser_state.m_current_token.type();
  1723. return match_identifier_name()
  1724. || type == TokenType::BracketOpen
  1725. || type == TokenType::StringLiteral
  1726. || type == TokenType::NumericLiteral
  1727. || type == TokenType::BigIntLiteral;
  1728. }
  1729. bool Parser::done() const
  1730. {
  1731. return match(TokenType::Eof);
  1732. }
  1733. Token Parser::consume()
  1734. {
  1735. auto old_token = m_parser_state.m_current_token;
  1736. m_parser_state.m_current_token = m_parser_state.m_lexer.next();
  1737. return old_token;
  1738. }
  1739. void Parser::consume_or_insert_semicolon()
  1740. {
  1741. // Semicolon was found and will be consumed
  1742. if (match(TokenType::Semicolon)) {
  1743. consume();
  1744. return;
  1745. }
  1746. // Insert semicolon if...
  1747. // ...token is preceded by one or more newlines
  1748. if (m_parser_state.m_current_token.trivia_contains_line_terminator())
  1749. return;
  1750. // ...token is a closing curly brace
  1751. if (match(TokenType::CurlyClose))
  1752. return;
  1753. // ...token is eof
  1754. if (match(TokenType::Eof))
  1755. return;
  1756. // No rule for semicolon insertion applies -> syntax error
  1757. expected("Semicolon");
  1758. }
  1759. Token Parser::consume(TokenType expected_type)
  1760. {
  1761. if (!match(expected_type)) {
  1762. expected(Token::name(expected_type));
  1763. }
  1764. return consume();
  1765. }
  1766. Token Parser::consume_and_validate_numeric_literal()
  1767. {
  1768. auto is_unprefixed_octal_number = [](const StringView& value) {
  1769. return value.length() > 1 && value[0] == '0' && isdigit(value[1]);
  1770. };
  1771. auto literal_start = position();
  1772. auto token = consume(TokenType::NumericLiteral);
  1773. if (m_parser_state.m_strict_mode && is_unprefixed_octal_number(token.value()))
  1774. syntax_error("Unprefixed octal number not allowed in strict mode", literal_start);
  1775. if (match_identifier_name() && m_parser_state.m_current_token.trivia().is_empty())
  1776. syntax_error("Numeric literal must not be immediately followed by identifier");
  1777. return token;
  1778. }
  1779. void Parser::expected(const char* what)
  1780. {
  1781. auto message = m_parser_state.m_current_token.message();
  1782. if (message.is_empty())
  1783. message = String::formatted("Unexpected token {}. Expected {}", m_parser_state.m_current_token.name(), what);
  1784. syntax_error(message);
  1785. }
  1786. Position Parser::position() const
  1787. {
  1788. return {
  1789. m_parser_state.m_current_token.line_number(),
  1790. m_parser_state.m_current_token.line_column()
  1791. };
  1792. }
  1793. void Parser::syntax_error(const String& message, Optional<Position> position)
  1794. {
  1795. if (!position.has_value())
  1796. position = this->position();
  1797. m_parser_state.m_errors.append({ message, position });
  1798. }
  1799. void Parser::save_state()
  1800. {
  1801. m_saved_state.append(m_parser_state);
  1802. }
  1803. void Parser::load_state()
  1804. {
  1805. ASSERT(!m_saved_state.is_empty());
  1806. m_parser_state = m_saved_state.take_last();
  1807. }
  1808. void Parser::discard_saved_state()
  1809. {
  1810. m_saved_state.take_last();
  1811. }
  1812. }