Parser.cpp 75 KB

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