Parser.cpp 72 KB

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