Parser.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@gmx.de>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Parser.h"
  27. #include <AK/HashMap.h>
  28. #include <AK/ScopeGuard.h>
  29. #include <AK/StdLibExtras.h>
  30. #include <stdio.h>
  31. namespace JS {
  32. class ScopePusher {
  33. public:
  34. enum Type {
  35. Var = 1,
  36. Let = 2,
  37. };
  38. ScopePusher(Parser& parser, unsigned mask)
  39. : m_parser(parser)
  40. , m_mask(mask)
  41. {
  42. if (m_mask & Var)
  43. m_parser.m_parser_state.m_var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  44. if (m_mask & Let)
  45. m_parser.m_parser_state.m_let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  46. }
  47. ~ScopePusher()
  48. {
  49. if (m_mask & Var)
  50. m_parser.m_parser_state.m_var_scopes.take_last();
  51. if (m_mask & Let)
  52. m_parser.m_parser_state.m_let_scopes.take_last();
  53. }
  54. Parser& m_parser;
  55. unsigned m_mask { 0 };
  56. };
  57. static HashMap<TokenType, int> g_operator_precedence;
  58. Parser::ParserState::ParserState(Lexer lexer)
  59. : m_lexer(move(lexer))
  60. , m_current_token(m_lexer.next())
  61. {
  62. }
  63. Parser::Parser(Lexer lexer)
  64. : m_parser_state(move(lexer))
  65. {
  66. if (g_operator_precedence.is_empty()) {
  67. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  68. g_operator_precedence.set(TokenType::Period, 20);
  69. g_operator_precedence.set(TokenType::BracketOpen, 20);
  70. g_operator_precedence.set(TokenType::ParenOpen, 20);
  71. g_operator_precedence.set(TokenType::QuestionMarkPeriod, 20);
  72. g_operator_precedence.set(TokenType::New, 19);
  73. g_operator_precedence.set(TokenType::PlusPlus, 18);
  74. g_operator_precedence.set(TokenType::MinusMinus, 18);
  75. g_operator_precedence.set(TokenType::ExclamationMark, 17);
  76. g_operator_precedence.set(TokenType::Tilde, 17);
  77. g_operator_precedence.set(TokenType::Typeof, 17);
  78. g_operator_precedence.set(TokenType::Void, 17);
  79. g_operator_precedence.set(TokenType::Delete, 17);
  80. g_operator_precedence.set(TokenType::Await, 17);
  81. g_operator_precedence.set(TokenType::DoubleAsterisk, 16);
  82. g_operator_precedence.set(TokenType::Asterisk, 15);
  83. g_operator_precedence.set(TokenType::Slash, 15);
  84. g_operator_precedence.set(TokenType::Percent, 15);
  85. g_operator_precedence.set(TokenType::Plus, 14);
  86. g_operator_precedence.set(TokenType::Minus, 14);
  87. g_operator_precedence.set(TokenType::ShiftLeft, 13);
  88. g_operator_precedence.set(TokenType::ShiftRight, 13);
  89. g_operator_precedence.set(TokenType::UnsignedShiftRight, 13);
  90. g_operator_precedence.set(TokenType::LessThan, 12);
  91. g_operator_precedence.set(TokenType::LessThanEquals, 12);
  92. g_operator_precedence.set(TokenType::GreaterThan, 12);
  93. g_operator_precedence.set(TokenType::GreaterThanEquals, 12);
  94. g_operator_precedence.set(TokenType::In, 12);
  95. g_operator_precedence.set(TokenType::Instanceof, 12);
  96. g_operator_precedence.set(TokenType::EqualsEquals, 11);
  97. g_operator_precedence.set(TokenType::ExclamationMarkEquals, 11);
  98. g_operator_precedence.set(TokenType::EqualsEqualsEquals, 11);
  99. g_operator_precedence.set(TokenType::ExclamationMarkEqualsEquals, 11);
  100. g_operator_precedence.set(TokenType::Ampersand, 10);
  101. g_operator_precedence.set(TokenType::Caret, 9);
  102. g_operator_precedence.set(TokenType::Pipe, 8);
  103. g_operator_precedence.set(TokenType::DoubleQuestionMark, 7);
  104. g_operator_precedence.set(TokenType::DoubleAmpersand, 6);
  105. g_operator_precedence.set(TokenType::DoublePipe, 5);
  106. g_operator_precedence.set(TokenType::QuestionMark, 4);
  107. g_operator_precedence.set(TokenType::Equals, 3);
  108. g_operator_precedence.set(TokenType::PlusEquals, 3);
  109. g_operator_precedence.set(TokenType::MinusEquals, 3);
  110. g_operator_precedence.set(TokenType::AsteriskAsteriskEquals, 3);
  111. g_operator_precedence.set(TokenType::AsteriskEquals, 3);
  112. g_operator_precedence.set(TokenType::SlashEquals, 3);
  113. g_operator_precedence.set(TokenType::PercentEquals, 3);
  114. g_operator_precedence.set(TokenType::ShiftLeftEquals, 3);
  115. g_operator_precedence.set(TokenType::ShiftRightEquals, 3);
  116. g_operator_precedence.set(TokenType::UnsignedShiftRightEquals, 3);
  117. g_operator_precedence.set(TokenType::PipeEquals, 3);
  118. g_operator_precedence.set(TokenType::Yield, 2);
  119. g_operator_precedence.set(TokenType::Comma, 1);
  120. }
  121. }
  122. int Parser::operator_precedence(TokenType type) const
  123. {
  124. auto it = g_operator_precedence.find(type);
  125. if (it == g_operator_precedence.end()) {
  126. fprintf(stderr, "No precedence for operator %s\n", Token::name(type));
  127. ASSERT_NOT_REACHED();
  128. return -1;
  129. }
  130. return it->value;
  131. }
  132. Associativity Parser::operator_associativity(TokenType type) const
  133. {
  134. switch (type) {
  135. case TokenType::Period:
  136. case TokenType::BracketOpen:
  137. case TokenType::ParenOpen:
  138. case TokenType::QuestionMarkPeriod:
  139. case TokenType::Asterisk:
  140. case TokenType::Slash:
  141. case TokenType::Percent:
  142. case TokenType::Plus:
  143. case TokenType::Minus:
  144. case TokenType::ShiftLeft:
  145. case TokenType::ShiftRight:
  146. case TokenType::UnsignedShiftRight:
  147. case TokenType::LessThan:
  148. case TokenType::LessThanEquals:
  149. case TokenType::GreaterThan:
  150. case TokenType::GreaterThanEquals:
  151. case TokenType::In:
  152. case TokenType::Instanceof:
  153. case TokenType::EqualsEquals:
  154. case TokenType::ExclamationMarkEquals:
  155. case TokenType::EqualsEqualsEquals:
  156. case TokenType::ExclamationMarkEqualsEquals:
  157. case TokenType::Typeof:
  158. case TokenType::Void:
  159. case TokenType::Ampersand:
  160. case TokenType::Caret:
  161. case TokenType::Pipe:
  162. case TokenType::DoubleQuestionMark:
  163. case TokenType::DoubleAmpersand:
  164. case TokenType::DoublePipe:
  165. case TokenType::Comma:
  166. return Associativity::Left;
  167. default:
  168. return Associativity::Right;
  169. }
  170. }
  171. NonnullRefPtr<Program> Parser::parse_program()
  172. {
  173. ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Let);
  174. auto program = adopt(*new Program);
  175. while (!done()) {
  176. if (match(TokenType::Semicolon)) {
  177. consume();
  178. } else if (match_statement()) {
  179. program->append(parse_statement());
  180. } else {
  181. expected("statement");
  182. consume();
  183. }
  184. }
  185. ASSERT(m_parser_state.m_var_scopes.size() == 1);
  186. program->add_variables(m_parser_state.m_var_scopes.last());
  187. program->add_variables(m_parser_state.m_let_scopes.last());
  188. return program;
  189. }
  190. NonnullRefPtr<Statement> Parser::parse_statement()
  191. {
  192. auto statement = [this]() -> NonnullRefPtr<Statement> {
  193. switch (m_parser_state.m_current_token.type()) {
  194. case TokenType::Function:
  195. return parse_function_node<FunctionDeclaration>();
  196. case TokenType::CurlyOpen:
  197. return parse_block_statement();
  198. case TokenType::Return:
  199. return parse_return_statement();
  200. case TokenType::Var:
  201. case TokenType::Let:
  202. case TokenType::Const:
  203. return parse_variable_declaration();
  204. case TokenType::For:
  205. return parse_for_statement();
  206. case TokenType::If:
  207. return parse_if_statement();
  208. case TokenType::Throw:
  209. return parse_throw_statement();
  210. case TokenType::Try:
  211. return parse_try_statement();
  212. case TokenType::Break:
  213. return parse_break_statement();
  214. case TokenType::Continue:
  215. return parse_continue_statement();
  216. case TokenType::Switch:
  217. return parse_switch_statement();
  218. case TokenType::Do:
  219. return parse_do_while_statement();
  220. default:
  221. if (match_expression())
  222. return adopt(*new ExpressionStatement(parse_expression(0)));
  223. m_parser_state.m_has_errors = true;
  224. expected("statement (missing switch case)");
  225. consume();
  226. return create_ast_node<ErrorStatement>();
  227. } }();
  228. if (match(TokenType::Semicolon))
  229. consume();
  230. return statement;
  231. }
  232. RefPtr<FunctionExpression> Parser::try_parse_arrow_function_expression(bool expect_parens)
  233. {
  234. save_state();
  235. m_parser_state.m_var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  236. ArmedScopeGuard state_rollback_guard = [&] {
  237. m_parser_state.m_var_scopes.take_last();
  238. load_state();
  239. };
  240. Vector<FlyString> parameters;
  241. bool parse_failed = false;
  242. while (true) {
  243. if (match(TokenType::Comma)) {
  244. consume(TokenType::Comma);
  245. } else if (match(TokenType::Identifier)) {
  246. auto token = consume(TokenType::Identifier);
  247. parameters.append(token.value());
  248. } else if (match(TokenType::ParenClose)) {
  249. if (expect_parens) {
  250. consume(TokenType::ParenClose);
  251. if (match(TokenType::Arrow)) {
  252. consume(TokenType::Arrow);
  253. } else {
  254. parse_failed = true;
  255. }
  256. break;
  257. }
  258. parse_failed = true;
  259. break;
  260. } else if (match(TokenType::Arrow)) {
  261. if (!expect_parens) {
  262. consume(TokenType::Arrow);
  263. break;
  264. }
  265. parse_failed = true;
  266. break;
  267. } else {
  268. parse_failed = true;
  269. break;
  270. }
  271. }
  272. if (parse_failed)
  273. return nullptr;
  274. auto function_body_result = [this]() -> RefPtr<BlockStatement> {
  275. if (match(TokenType::CurlyOpen)) {
  276. // Parse a function body with statements
  277. return parse_block_statement();
  278. }
  279. if (match_expression()) {
  280. // Parse a function body which returns a single expression
  281. // FIXME: We synthesize a block with a return statement
  282. // for arrow function bodies which are a single expression.
  283. // Esprima generates a single "ArrowFunctionExpression"
  284. // with a "body" property.
  285. auto return_expression = parse_expression(0);
  286. auto return_block = create_ast_node<BlockStatement>();
  287. return_block->append<ReturnStatement>(move(return_expression));
  288. return return_block;
  289. }
  290. // Invalid arrow function body
  291. return nullptr;
  292. }();
  293. if (!function_body_result.is_null()) {
  294. state_rollback_guard.disarm();
  295. auto body = function_body_result.release_nonnull();
  296. return create_ast_node<FunctionExpression>("", move(body), move(parameters), m_parser_state.m_var_scopes.take_last());
  297. }
  298. return nullptr;
  299. }
  300. NonnullRefPtr<Expression> Parser::parse_primary_expression()
  301. {
  302. if (match_unary_prefixed_expression())
  303. return parse_unary_prefixed_expression();
  304. switch (m_parser_state.m_current_token.type()) {
  305. case TokenType::ParenOpen: {
  306. consume(TokenType::ParenOpen);
  307. if (match(TokenType::ParenClose) || match(TokenType::Identifier)) {
  308. auto arrow_function_result = try_parse_arrow_function_expression(true);
  309. if (!arrow_function_result.is_null()) {
  310. return arrow_function_result.release_nonnull();
  311. }
  312. }
  313. auto expression = parse_expression(0);
  314. consume(TokenType::ParenClose);
  315. return expression;
  316. }
  317. case TokenType::This:
  318. consume();
  319. return create_ast_node<ThisExpression>();
  320. case TokenType::Identifier: {
  321. auto arrow_function_result = try_parse_arrow_function_expression(false);
  322. if (!arrow_function_result.is_null()) {
  323. return arrow_function_result.release_nonnull();
  324. }
  325. return create_ast_node<Identifier>(consume().value());
  326. }
  327. case TokenType::NumericLiteral:
  328. return create_ast_node<NumericLiteral>(consume().double_value());
  329. case TokenType::BoolLiteral:
  330. return create_ast_node<BooleanLiteral>(consume().bool_value());
  331. case TokenType::StringLiteral:
  332. return create_ast_node<StringLiteral>(consume().string_value());
  333. case TokenType::NullLiteral:
  334. consume();
  335. return create_ast_node<NullLiteral>();
  336. case TokenType::CurlyOpen:
  337. return parse_object_expression();
  338. case TokenType::Function:
  339. return parse_function_node<FunctionExpression>();
  340. case TokenType::BracketOpen:
  341. return parse_array_expression();
  342. case TokenType::New:
  343. return parse_new_expression();
  344. default:
  345. m_parser_state.m_has_errors = true;
  346. expected("primary expression (missing switch case)");
  347. consume();
  348. return create_ast_node<ErrorExpression>();
  349. }
  350. }
  351. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  352. {
  353. auto precedence = operator_precedence(m_parser_state.m_current_token.type());
  354. auto associativity = operator_associativity(m_parser_state.m_current_token.type());
  355. switch (m_parser_state.m_current_token.type()) {
  356. case TokenType::PlusPlus:
  357. consume();
  358. return create_ast_node<UpdateExpression>(UpdateOp::Increment, parse_expression(precedence, associativity), true);
  359. case TokenType::MinusMinus:
  360. consume();
  361. return create_ast_node<UpdateExpression>(UpdateOp::Decrement, parse_expression(precedence, associativity), true);
  362. case TokenType::ExclamationMark:
  363. consume();
  364. return create_ast_node<UnaryExpression>(UnaryOp::Not, parse_expression(precedence, associativity));
  365. case TokenType::Tilde:
  366. consume();
  367. return create_ast_node<UnaryExpression>(UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  368. case TokenType::Plus:
  369. consume();
  370. return create_ast_node<UnaryExpression>(UnaryOp::Plus, parse_expression(precedence, associativity));
  371. case TokenType::Minus:
  372. consume();
  373. return create_ast_node<UnaryExpression>(UnaryOp::Minus, parse_expression(precedence, associativity));
  374. case TokenType::Typeof:
  375. consume();
  376. return create_ast_node<UnaryExpression>(UnaryOp::Typeof, parse_expression(precedence, associativity));
  377. case TokenType::Void:
  378. consume();
  379. return create_ast_node<UnaryExpression>(UnaryOp::Void, parse_expression(precedence, associativity));
  380. default:
  381. m_parser_state.m_has_errors = true;
  382. expected("primary expression (missing switch case)");
  383. consume();
  384. return create_ast_node<ErrorExpression>();
  385. }
  386. }
  387. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  388. {
  389. HashMap<FlyString, NonnullRefPtr<Expression>> properties;
  390. consume(TokenType::CurlyOpen);
  391. while (!done() && !match(TokenType::CurlyClose)) {
  392. FlyString property_name;
  393. if (match(TokenType::Identifier)) {
  394. property_name = consume(TokenType::Identifier).value();
  395. } else if (match(TokenType::StringLiteral)) {
  396. property_name = consume(TokenType::StringLiteral).string_value();
  397. } else if (match(TokenType::NumericLiteral)) {
  398. property_name = consume(TokenType::NumericLiteral).value();
  399. } else {
  400. m_parser_state.m_has_errors = true;
  401. auto& current_token = m_parser_state.m_current_token;
  402. fprintf(stderr, "Error: Unexpected token %s as member in object initialization. Expected a numeric literal, string literal or identifier (line: %zu, column: %zu))\n",
  403. current_token.name(),
  404. current_token.line_number(),
  405. current_token.line_column());
  406. consume();
  407. continue;
  408. }
  409. if (match(TokenType::Colon)) {
  410. consume(TokenType::Colon);
  411. properties.set(property_name, parse_expression(0));
  412. } else {
  413. properties.set(property_name, create_ast_node<Identifier>(property_name));
  414. }
  415. if (!match(TokenType::Comma))
  416. break;
  417. consume(TokenType::Comma);
  418. }
  419. consume(TokenType::CurlyClose);
  420. return create_ast_node<ObjectExpression>(properties);
  421. }
  422. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  423. {
  424. consume(TokenType::BracketOpen);
  425. Vector<RefPtr<Expression>> elements;
  426. while (match_expression() || match(TokenType::Comma)) {
  427. RefPtr<Expression> expression;
  428. if (match_expression())
  429. expression = parse_expression(0);
  430. elements.append(expression);
  431. if (!match(TokenType::Comma))
  432. break;
  433. consume(TokenType::Comma);
  434. }
  435. consume(TokenType::BracketClose);
  436. return create_ast_node<ArrayExpression>(move(elements));
  437. }
  438. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity)
  439. {
  440. auto expression = parse_primary_expression();
  441. while (match_secondary_expression()) {
  442. int new_precedence = operator_precedence(m_parser_state.m_current_token.type());
  443. if (new_precedence < min_precedence)
  444. break;
  445. if (new_precedence == min_precedence && associativity == Associativity::Left)
  446. break;
  447. Associativity new_associativity = operator_associativity(m_parser_state.m_current_token.type());
  448. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  449. }
  450. return expression;
  451. }
  452. NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  453. {
  454. switch (m_parser_state.m_current_token.type()) {
  455. case TokenType::Plus:
  456. consume();
  457. return create_ast_node<BinaryExpression>(BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity));
  458. case TokenType::PlusEquals:
  459. consume();
  460. return create_ast_node<AssignmentExpression>(AssignmentOp::AdditionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  461. case TokenType::Minus:
  462. consume();
  463. return create_ast_node<BinaryExpression>(BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity));
  464. case TokenType::MinusEquals:
  465. consume();
  466. return create_ast_node<AssignmentExpression>(AssignmentOp::SubtractionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  467. case TokenType::Asterisk:
  468. consume();
  469. return create_ast_node<BinaryExpression>(BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity));
  470. case TokenType::AsteriskEquals:
  471. consume();
  472. return create_ast_node<AssignmentExpression>(AssignmentOp::MultiplicationAssignment, move(lhs), parse_expression(min_precedence, associativity));
  473. case TokenType::Slash:
  474. consume();
  475. return create_ast_node<BinaryExpression>(BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity));
  476. case TokenType::SlashEquals:
  477. consume();
  478. return create_ast_node<AssignmentExpression>(AssignmentOp::DivisionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  479. case TokenType::Percent:
  480. consume();
  481. return create_ast_node<BinaryExpression>(BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity));
  482. case TokenType::DoubleAsterisk:
  483. consume();
  484. return create_ast_node<BinaryExpression>(BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity));
  485. case TokenType::GreaterThan:
  486. consume();
  487. return create_ast_node<BinaryExpression>(BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  488. case TokenType::GreaterThanEquals:
  489. consume();
  490. return create_ast_node<BinaryExpression>(BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  491. case TokenType::LessThan:
  492. consume();
  493. return create_ast_node<BinaryExpression>(BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  494. case TokenType::LessThanEquals:
  495. consume();
  496. return create_ast_node<BinaryExpression>(BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  497. case TokenType::EqualsEqualsEquals:
  498. consume();
  499. return create_ast_node<BinaryExpression>(BinaryOp::TypedEquals, move(lhs), parse_expression(min_precedence, associativity));
  500. case TokenType::ExclamationMarkEqualsEquals:
  501. consume();
  502. return create_ast_node<BinaryExpression>(BinaryOp::TypedInequals, move(lhs), parse_expression(min_precedence, associativity));
  503. case TokenType::EqualsEquals:
  504. consume();
  505. return create_ast_node<BinaryExpression>(BinaryOp::AbstractEquals, move(lhs), parse_expression(min_precedence, associativity));
  506. case TokenType::ExclamationMarkEquals:
  507. consume();
  508. return create_ast_node<BinaryExpression>(BinaryOp::AbstractInequals, move(lhs), parse_expression(min_precedence, associativity));
  509. case TokenType::Instanceof:
  510. consume();
  511. return create_ast_node<BinaryExpression>(BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity));
  512. case TokenType::Ampersand:
  513. consume();
  514. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity));
  515. case TokenType::Pipe:
  516. consume();
  517. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity));
  518. case TokenType::Caret:
  519. consume();
  520. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity));
  521. case TokenType::ParenOpen:
  522. return parse_call_expression(move(lhs));
  523. case TokenType::Equals:
  524. consume();
  525. return create_ast_node<AssignmentExpression>(AssignmentOp::Assignment, move(lhs), parse_expression(min_precedence, associativity));
  526. case TokenType::Period:
  527. consume();
  528. return create_ast_node<MemberExpression>(move(lhs), parse_expression(min_precedence, associativity));
  529. case TokenType::BracketOpen: {
  530. consume(TokenType::BracketOpen);
  531. auto expression = create_ast_node<MemberExpression>(move(lhs), parse_expression(0), true);
  532. consume(TokenType::BracketClose);
  533. return expression;
  534. }
  535. case TokenType::PlusPlus:
  536. consume();
  537. return create_ast_node<UpdateExpression>(UpdateOp::Increment, move(lhs));
  538. case TokenType::MinusMinus:
  539. consume();
  540. return create_ast_node<UpdateExpression>(UpdateOp::Decrement, move(lhs));
  541. case TokenType::DoubleAmpersand:
  542. consume();
  543. return create_ast_node<LogicalExpression>(LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity));
  544. case TokenType::DoublePipe:
  545. consume();
  546. return create_ast_node<LogicalExpression>(LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity));
  547. case TokenType::QuestionMark:
  548. return parse_conditional_expression(move(lhs));
  549. default:
  550. m_parser_state.m_has_errors = true;
  551. expected("secondary expression (missing switch case)");
  552. consume();
  553. return create_ast_node<ErrorExpression>();
  554. }
  555. }
  556. NonnullRefPtr<CallExpression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  557. {
  558. consume(TokenType::ParenOpen);
  559. NonnullRefPtrVector<Expression> arguments;
  560. while (match_expression()) {
  561. arguments.append(parse_expression(0));
  562. if (!match(TokenType::Comma))
  563. break;
  564. consume();
  565. }
  566. consume(TokenType::ParenClose);
  567. return create_ast_node<CallExpression>(move(lhs), move(arguments));
  568. }
  569. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  570. {
  571. consume(TokenType::New);
  572. // FIXME: Support full expressions as the callee as well.
  573. auto callee = create_ast_node<Identifier>(consume(TokenType::Identifier).value());
  574. NonnullRefPtrVector<Expression> arguments;
  575. if (match(TokenType::ParenOpen)) {
  576. consume(TokenType::ParenOpen);
  577. while (match_expression()) {
  578. arguments.append(parse_expression(0));
  579. if (!match(TokenType::Comma))
  580. break;
  581. consume();
  582. }
  583. consume(TokenType::ParenClose);
  584. }
  585. return create_ast_node<NewExpression>(move(callee), move(arguments));
  586. }
  587. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  588. {
  589. consume(TokenType::Return);
  590. if (match_expression()) {
  591. return create_ast_node<ReturnStatement>(parse_expression(0));
  592. }
  593. return create_ast_node<ReturnStatement>(nullptr);
  594. }
  595. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  596. {
  597. ScopePusher scope(*this, ScopePusher::Let);
  598. auto block = create_ast_node<BlockStatement>();
  599. consume(TokenType::CurlyOpen);
  600. while (!done() && !match(TokenType::CurlyClose)) {
  601. if (match(TokenType::Semicolon)) {
  602. consume();
  603. } else if (match_statement()) {
  604. block->append(parse_statement());
  605. } else {
  606. expected("statement");
  607. consume();
  608. }
  609. }
  610. consume(TokenType::CurlyClose);
  611. block->add_variables(m_parser_state.m_let_scopes.last());
  612. return block;
  613. }
  614. template<typename FunctionNodeType>
  615. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node()
  616. {
  617. ScopePusher scope(*this, ScopePusher::Var);
  618. consume(TokenType::Function);
  619. String name;
  620. if (FunctionNodeType::must_have_name()) {
  621. name = consume(TokenType::Identifier).value();
  622. } else {
  623. if (match(TokenType::Identifier))
  624. name = consume(TokenType::Identifier).value();
  625. }
  626. consume(TokenType::ParenOpen);
  627. Vector<FlyString> parameters;
  628. while (match(TokenType::Identifier)) {
  629. auto parameter = consume(TokenType::Identifier).value();
  630. parameters.append(parameter);
  631. if (match(TokenType::ParenClose)) {
  632. break;
  633. }
  634. consume(TokenType::Comma);
  635. }
  636. consume(TokenType::ParenClose);
  637. auto body = parse_block_statement();
  638. body->add_variables(m_parser_state.m_var_scopes.last());
  639. return create_ast_node<FunctionNodeType>(name, move(body), move(parameters), NonnullRefPtrVector<VariableDeclaration>());
  640. }
  641. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration()
  642. {
  643. DeclarationKind declaration_kind;
  644. switch (m_parser_state.m_current_token.type()) {
  645. case TokenType::Var:
  646. declaration_kind = DeclarationKind::Var;
  647. consume(TokenType::Var);
  648. break;
  649. case TokenType::Let:
  650. declaration_kind = DeclarationKind::Let;
  651. consume(TokenType::Let);
  652. break;
  653. case TokenType::Const:
  654. declaration_kind = DeclarationKind::Const;
  655. consume(TokenType::Const);
  656. break;
  657. default:
  658. ASSERT_NOT_REACHED();
  659. }
  660. NonnullRefPtrVector<VariableDeclarator> declarations;
  661. for (;;) {
  662. auto id = consume(TokenType::Identifier).value();
  663. RefPtr<Expression> init;
  664. if (match(TokenType::Equals)) {
  665. consume();
  666. init = parse_expression(0);
  667. }
  668. declarations.append(create_ast_node<VariableDeclarator>(create_ast_node<Identifier>(move(id)), move(init)));
  669. if (match(TokenType::Comma)) {
  670. consume();
  671. continue;
  672. }
  673. break;
  674. }
  675. auto declaration = create_ast_node<VariableDeclaration>(declaration_kind, move(declarations));
  676. if (declaration->declaration_kind() == DeclarationKind::Var)
  677. m_parser_state.m_var_scopes.last().append(declaration);
  678. else
  679. m_parser_state.m_let_scopes.last().append(declaration);
  680. return declaration;
  681. }
  682. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  683. {
  684. consume(TokenType::Throw);
  685. return create_ast_node<ThrowStatement>(parse_expression(0));
  686. }
  687. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  688. {
  689. consume(TokenType::Break);
  690. // FIXME: Handle labels.
  691. return create_ast_node<BreakStatement>();
  692. }
  693. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  694. {
  695. consume(TokenType::Continue);
  696. // FIXME: Handle labels.
  697. return create_ast_node<ContinueStatement>();
  698. }
  699. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test)
  700. {
  701. consume(TokenType::QuestionMark);
  702. auto consequent = parse_expression(0);
  703. consume(TokenType::Colon);
  704. auto alternate = parse_expression(0);
  705. return create_ast_node<ConditionalExpression>(move(test), move(consequent), move(alternate));
  706. }
  707. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  708. {
  709. consume(TokenType::Try);
  710. auto block = parse_block_statement();
  711. RefPtr<CatchClause> handler;
  712. if (match(TokenType::Catch))
  713. handler = parse_catch_clause();
  714. RefPtr<BlockStatement> finalizer;
  715. if (match(TokenType::Finally)) {
  716. consume();
  717. finalizer = parse_block_statement();
  718. }
  719. return create_ast_node<TryStatement>(move(block), move(handler), move(finalizer));
  720. }
  721. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  722. {
  723. consume(TokenType::Do);
  724. auto body = parse_statement();
  725. consume(TokenType::While);
  726. consume(TokenType::ParenOpen);
  727. auto test = parse_expression(0);
  728. consume(TokenType::ParenClose);
  729. return create_ast_node<DoWhileStatement>(move(test), move(body));
  730. }
  731. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  732. {
  733. consume(TokenType::Switch);
  734. consume(TokenType::ParenOpen);
  735. auto determinant = parse_expression(0);
  736. consume(TokenType::ParenClose);
  737. consume(TokenType::CurlyOpen);
  738. NonnullRefPtrVector<SwitchCase> cases;
  739. while (match(TokenType::Case) || match(TokenType::Default))
  740. cases.append(parse_switch_case());
  741. consume(TokenType::CurlyClose);
  742. return create_ast_node<SwitchStatement>(move(determinant), move(cases));
  743. }
  744. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  745. {
  746. RefPtr<Expression> test;
  747. if (consume().type() == TokenType::Case) {
  748. test = parse_expression(0);
  749. }
  750. consume(TokenType::Colon);
  751. NonnullRefPtrVector<Statement> consequent;
  752. while (match_statement())
  753. consequent.append(parse_statement());
  754. return create_ast_node<SwitchCase>(move(test), move(consequent));
  755. }
  756. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  757. {
  758. consume(TokenType::Catch);
  759. String parameter;
  760. if (match(TokenType::ParenOpen)) {
  761. consume();
  762. parameter = consume(TokenType::Identifier).value();
  763. consume(TokenType::ParenClose);
  764. }
  765. auto body = parse_block_statement();
  766. return create_ast_node<CatchClause>(parameter, move(body));
  767. }
  768. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  769. {
  770. consume(TokenType::If);
  771. consume(TokenType::ParenOpen);
  772. auto predicate = parse_expression(0);
  773. consume(TokenType::ParenClose);
  774. auto consequent = parse_statement();
  775. RefPtr<Statement> alternate;
  776. if (match(TokenType::Else)) {
  777. consume(TokenType::Else);
  778. alternate = parse_statement();
  779. }
  780. return create_ast_node<IfStatement>(move(predicate), move(consequent), move(alternate));
  781. }
  782. NonnullRefPtr<ForStatement> Parser::parse_for_statement()
  783. {
  784. consume(TokenType::For);
  785. consume(TokenType::ParenOpen);
  786. RefPtr<ASTNode> init;
  787. switch (m_parser_state.m_current_token.type()) {
  788. case TokenType::Semicolon:
  789. break;
  790. default:
  791. if (match_expression())
  792. init = parse_expression(0);
  793. else if (match_variable_declaration())
  794. init = parse_variable_declaration();
  795. else
  796. ASSERT_NOT_REACHED();
  797. break;
  798. }
  799. consume(TokenType::Semicolon);
  800. RefPtr<Expression> test;
  801. switch (m_parser_state.m_current_token.type()) {
  802. case TokenType::Semicolon:
  803. break;
  804. default:
  805. test = parse_expression(0);
  806. break;
  807. }
  808. consume(TokenType::Semicolon);
  809. RefPtr<Expression> update;
  810. switch (m_parser_state.m_current_token.type()) {
  811. case TokenType::ParenClose:
  812. break;
  813. default:
  814. update = parse_expression(0);
  815. break;
  816. }
  817. consume(TokenType::ParenClose);
  818. auto body = parse_statement();
  819. return create_ast_node<ForStatement>(move(init), move(test), move(update), move(body));
  820. }
  821. bool Parser::match(TokenType type) const
  822. {
  823. return m_parser_state.m_current_token.type() == type;
  824. }
  825. bool Parser::match_variable_declaration() const
  826. {
  827. switch (m_parser_state.m_current_token.type()) {
  828. case TokenType::Var:
  829. case TokenType::Let:
  830. case TokenType::Const:
  831. return true;
  832. default:
  833. return false;
  834. }
  835. }
  836. bool Parser::match_expression() const
  837. {
  838. auto type = m_parser_state.m_current_token.type();
  839. return type == TokenType::BoolLiteral
  840. || type == TokenType::NumericLiteral
  841. || type == TokenType::StringLiteral
  842. || type == TokenType::NullLiteral
  843. || type == TokenType::Identifier
  844. || type == TokenType::New
  845. || type == TokenType::CurlyOpen
  846. || type == TokenType::BracketOpen
  847. || type == TokenType::ParenOpen
  848. || type == TokenType::Function
  849. || type == TokenType::This
  850. || match_unary_prefixed_expression();
  851. }
  852. bool Parser::match_unary_prefixed_expression() const
  853. {
  854. auto type = m_parser_state.m_current_token.type();
  855. return type == TokenType::PlusPlus
  856. || type == TokenType::MinusMinus
  857. || type == TokenType::ExclamationMark
  858. || type == TokenType::Tilde
  859. || type == TokenType::Plus
  860. || type == TokenType::Minus
  861. || type == TokenType::Typeof
  862. || type == TokenType::Void;
  863. }
  864. bool Parser::match_secondary_expression() const
  865. {
  866. auto type = m_parser_state.m_current_token.type();
  867. return type == TokenType::Plus
  868. || type == TokenType::PlusEquals
  869. || type == TokenType::Minus
  870. || type == TokenType::MinusEquals
  871. || type == TokenType::Asterisk
  872. || type == TokenType::AsteriskEquals
  873. || type == TokenType::Slash
  874. || type == TokenType::SlashEquals
  875. || type == TokenType::Percent
  876. || type == TokenType::DoubleAsterisk
  877. || type == TokenType::Equals
  878. || type == TokenType::EqualsEqualsEquals
  879. || type == TokenType::ExclamationMarkEqualsEquals
  880. || type == TokenType::EqualsEquals
  881. || type == TokenType::ExclamationMarkEquals
  882. || type == TokenType::GreaterThan
  883. || type == TokenType::GreaterThanEquals
  884. || type == TokenType::LessThan
  885. || type == TokenType::LessThanEquals
  886. || type == TokenType::ParenOpen
  887. || type == TokenType::Period
  888. || type == TokenType::BracketOpen
  889. || type == TokenType::PlusPlus
  890. || type == TokenType::MinusMinus
  891. || type == TokenType::Instanceof
  892. || type == TokenType::QuestionMark
  893. || type == TokenType::Ampersand
  894. || type == TokenType::Pipe
  895. || type == TokenType::Caret
  896. || type == TokenType::DoubleAmpersand
  897. || type == TokenType::DoublePipe;
  898. }
  899. bool Parser::match_statement() const
  900. {
  901. auto type = m_parser_state.m_current_token.type();
  902. return match_expression()
  903. || type == TokenType::Function
  904. || type == TokenType::Return
  905. || type == TokenType::Let
  906. || type == TokenType::Class
  907. || type == TokenType::Delete
  908. || type == TokenType::Do
  909. || type == TokenType::If
  910. || type == TokenType::Throw
  911. || type == TokenType::Try
  912. || type == TokenType::While
  913. || type == TokenType::For
  914. || type == TokenType::Const
  915. || type == TokenType::CurlyOpen
  916. || type == TokenType::Switch
  917. || type == TokenType::Break
  918. || type == TokenType::Continue
  919. || type == TokenType::Var;
  920. }
  921. bool Parser::done() const
  922. {
  923. return match(TokenType::Eof);
  924. }
  925. Token Parser::consume()
  926. {
  927. auto old_token = m_parser_state.m_current_token;
  928. m_parser_state.m_current_token = m_parser_state.m_lexer.next();
  929. return old_token;
  930. }
  931. Token Parser::consume(TokenType type)
  932. {
  933. if (m_parser_state.m_current_token.type() != type) {
  934. m_parser_state.m_has_errors = true;
  935. auto& current_token = m_parser_state.m_current_token;
  936. fprintf(stderr, "Error: Unexpected token %s. Expected %s (line: %zu, column: %zu))\n",
  937. current_token.name(),
  938. Token::name(type),
  939. current_token.line_number(),
  940. current_token.line_column());
  941. }
  942. return consume();
  943. }
  944. void Parser::expected(const char* what)
  945. {
  946. m_parser_state.m_has_errors = true;
  947. auto& current_token = m_parser_state.m_current_token;
  948. fprintf(stderr, "Error: Unexpected token %s. Expected %s (line: %zu, column: %zu)\n",
  949. current_token.name(),
  950. what,
  951. current_token.line_number(),
  952. current_token.line_column());
  953. }
  954. void Parser::save_state()
  955. {
  956. m_saved_state = m_parser_state;
  957. }
  958. void Parser::load_state()
  959. {
  960. ASSERT(m_saved_state.has_value());
  961. m_parser_state = m_saved_state.value();
  962. m_saved_state.clear();
  963. }
  964. }