Parser.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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::Ampersand:
  159. case TokenType::Caret:
  160. case TokenType::Pipe:
  161. case TokenType::DoubleQuestionMark:
  162. case TokenType::DoubleAmpersand:
  163. case TokenType::DoublePipe:
  164. case TokenType::Comma:
  165. return Associativity::Left;
  166. default:
  167. return Associativity::Right;
  168. }
  169. }
  170. NonnullRefPtr<Program> Parser::parse_program()
  171. {
  172. ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Let);
  173. auto program = adopt(*new Program);
  174. while (!done()) {
  175. if (match(TokenType::Semicolon)) {
  176. consume();
  177. } else if (match_statement()) {
  178. program->append(parse_statement());
  179. } else {
  180. expected("statement");
  181. consume();
  182. }
  183. }
  184. ASSERT(m_parser_state.m_var_scopes.size() == 1);
  185. program->add_variables(m_parser_state.m_var_scopes.last());
  186. program->add_variables(m_parser_state.m_let_scopes.last());
  187. return program;
  188. }
  189. NonnullRefPtr<Statement> Parser::parse_statement()
  190. {
  191. auto statement = [this]() -> NonnullRefPtr<Statement> {
  192. switch (m_parser_state.m_current_token.type()) {
  193. case TokenType::Function:
  194. return parse_function_node<FunctionDeclaration>();
  195. case TokenType::CurlyOpen:
  196. return parse_block_statement();
  197. case TokenType::Return:
  198. return parse_return_statement();
  199. case TokenType::Var:
  200. case TokenType::Let:
  201. case TokenType::Const:
  202. return parse_variable_declaration();
  203. case TokenType::For:
  204. return parse_for_statement();
  205. case TokenType::If:
  206. return parse_if_statement();
  207. case TokenType::Throw:
  208. return parse_throw_statement();
  209. case TokenType::Try:
  210. return parse_try_statement();
  211. case TokenType::Break:
  212. return parse_break_statement();
  213. case TokenType::Continue:
  214. return parse_continue_statement();
  215. case TokenType::Switch:
  216. return parse_switch_statement();
  217. case TokenType::Do:
  218. return parse_do_while_statement();
  219. default:
  220. if (match_expression())
  221. return adopt(*new ExpressionStatement(parse_expression(0)));
  222. m_parser_state.m_has_errors = true;
  223. expected("statement (missing switch case)");
  224. consume();
  225. return create_ast_node<ErrorStatement>();
  226. } }();
  227. if (match(TokenType::Semicolon))
  228. consume();
  229. return statement;
  230. }
  231. RefPtr<FunctionExpression> Parser::try_parse_arrow_function_expression(bool expect_parens)
  232. {
  233. save_state();
  234. m_parser_state.m_var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  235. ArmedScopeGuard state_rollback_guard = [&] {
  236. m_parser_state.m_var_scopes.take_last();
  237. load_state();
  238. };
  239. Vector<FlyString> parameters;
  240. bool parse_failed = false;
  241. while (true) {
  242. if (match(TokenType::Comma)) {
  243. consume(TokenType::Comma);
  244. } else if (match(TokenType::Identifier)) {
  245. auto token = consume(TokenType::Identifier);
  246. parameters.append(token.value());
  247. } else if (match(TokenType::ParenClose)) {
  248. if (expect_parens) {
  249. consume(TokenType::ParenClose);
  250. if (match(TokenType::Arrow)) {
  251. consume(TokenType::Arrow);
  252. } else {
  253. parse_failed = true;
  254. }
  255. break;
  256. }
  257. parse_failed = true;
  258. break;
  259. } else if (match(TokenType::Arrow)) {
  260. if (!expect_parens) {
  261. consume(TokenType::Arrow);
  262. break;
  263. }
  264. parse_failed = true;
  265. break;
  266. } else {
  267. parse_failed = true;
  268. break;
  269. }
  270. }
  271. if (parse_failed)
  272. return nullptr;
  273. auto function_body_result = [this]() -> RefPtr<BlockStatement> {
  274. if (match(TokenType::CurlyOpen)) {
  275. // Parse a function body with statements
  276. return parse_block_statement();
  277. }
  278. if (match_expression()) {
  279. // Parse a function body which returns a single expression
  280. // FIXME: We synthesize a block with a return statement
  281. // for arrow function bodies which are a single expression.
  282. // Esprima generates a single "ArrowFunctionExpression"
  283. // with a "body" property.
  284. auto return_expression = parse_expression(0);
  285. auto return_block = create_ast_node<BlockStatement>();
  286. return_block->append<ReturnStatement>(move(return_expression));
  287. return return_block;
  288. }
  289. // Invalid arrow function body
  290. return nullptr;
  291. }();
  292. if (!function_body_result.is_null()) {
  293. state_rollback_guard.disarm();
  294. auto body = function_body_result.release_nonnull();
  295. return create_ast_node<FunctionExpression>("", move(body), move(parameters), m_parser_state.m_var_scopes.take_last());
  296. }
  297. return nullptr;
  298. }
  299. NonnullRefPtr<Expression> Parser::parse_primary_expression()
  300. {
  301. if (match_unary_prefixed_expression())
  302. return parse_unary_prefixed_expression();
  303. switch (m_parser_state.m_current_token.type()) {
  304. case TokenType::ParenOpen: {
  305. consume(TokenType::ParenOpen);
  306. if (match(TokenType::ParenClose) || match(TokenType::Identifier)) {
  307. auto arrow_function_result = try_parse_arrow_function_expression(true);
  308. if (!arrow_function_result.is_null()) {
  309. return arrow_function_result.release_nonnull();
  310. }
  311. }
  312. auto expression = parse_expression(0);
  313. consume(TokenType::ParenClose);
  314. return expression;
  315. }
  316. case TokenType::This:
  317. consume();
  318. return create_ast_node<ThisExpression>();
  319. case TokenType::Identifier: {
  320. auto arrow_function_result = try_parse_arrow_function_expression(false);
  321. if (!arrow_function_result.is_null()) {
  322. return arrow_function_result.release_nonnull();
  323. }
  324. return create_ast_node<Identifier>(consume().value());
  325. }
  326. case TokenType::NumericLiteral:
  327. return create_ast_node<NumericLiteral>(consume().double_value());
  328. case TokenType::BoolLiteral:
  329. return create_ast_node<BooleanLiteral>(consume().bool_value());
  330. case TokenType::StringLiteral:
  331. return create_ast_node<StringLiteral>(consume().string_value());
  332. case TokenType::NullLiteral:
  333. consume();
  334. return create_ast_node<NullLiteral>();
  335. case TokenType::CurlyOpen:
  336. return parse_object_expression();
  337. case TokenType::Function:
  338. return parse_function_node<FunctionExpression>();
  339. case TokenType::BracketOpen:
  340. return parse_array_expression();
  341. case TokenType::New:
  342. return parse_new_expression();
  343. default:
  344. m_parser_state.m_has_errors = true;
  345. expected("primary expression (missing switch case)");
  346. consume();
  347. return create_ast_node<ErrorExpression>();
  348. }
  349. }
  350. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  351. {
  352. auto precedence = operator_precedence(m_parser_state.m_current_token.type());
  353. auto associativity = operator_associativity(m_parser_state.m_current_token.type());
  354. switch (m_parser_state.m_current_token.type()) {
  355. case TokenType::PlusPlus:
  356. consume();
  357. return create_ast_node<UpdateExpression>(UpdateOp::Increment, parse_expression(precedence, associativity), true);
  358. case TokenType::MinusMinus:
  359. consume();
  360. return create_ast_node<UpdateExpression>(UpdateOp::Decrement, parse_expression(precedence, associativity), true);
  361. case TokenType::ExclamationMark:
  362. consume();
  363. return create_ast_node<UnaryExpression>(UnaryOp::Not, parse_expression(precedence, associativity));
  364. case TokenType::Tilde:
  365. consume();
  366. return create_ast_node<UnaryExpression>(UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  367. case TokenType::Plus:
  368. consume();
  369. return create_ast_node<UnaryExpression>(UnaryOp::Plus, parse_expression(precedence, associativity));
  370. case TokenType::Minus:
  371. consume();
  372. return create_ast_node<UnaryExpression>(UnaryOp::Minus, parse_expression(precedence, associativity));
  373. case TokenType::Typeof:
  374. consume();
  375. return create_ast_node<UnaryExpression>(UnaryOp::Typeof, parse_expression(precedence, associativity));
  376. default:
  377. m_parser_state.m_has_errors = true;
  378. expected("primary expression (missing switch case)");
  379. consume();
  380. return create_ast_node<ErrorExpression>();
  381. }
  382. }
  383. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  384. {
  385. HashMap<FlyString, NonnullRefPtr<Expression>> properties;
  386. consume(TokenType::CurlyOpen);
  387. while (!done() && !match(TokenType::CurlyClose)) {
  388. FlyString property_name;
  389. if (match(TokenType::Identifier)) {
  390. property_name = consume(TokenType::Identifier).value();
  391. } else if (match(TokenType::StringLiteral)) {
  392. property_name = consume(TokenType::StringLiteral).string_value();
  393. } else if (match(TokenType::NumericLiteral)) {
  394. property_name = consume(TokenType::NumericLiteral).value();
  395. } else {
  396. m_parser_state.m_has_errors = true;
  397. auto& current_token = m_parser_state.m_current_token;
  398. fprintf(stderr, "Error: Unexpected token %s as member in object initialization. Expected a numeric literal, string literal or identifier (line: %zu, column: %zu))\n",
  399. current_token.name(),
  400. current_token.line_number(),
  401. current_token.line_column());
  402. consume();
  403. continue;
  404. }
  405. if (match(TokenType::Colon)) {
  406. consume(TokenType::Colon);
  407. properties.set(property_name, parse_expression(0));
  408. } else {
  409. properties.set(property_name, create_ast_node<Identifier>(property_name));
  410. }
  411. if (!match(TokenType::Comma))
  412. break;
  413. consume(TokenType::Comma);
  414. }
  415. consume(TokenType::CurlyClose);
  416. return create_ast_node<ObjectExpression>(properties);
  417. }
  418. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  419. {
  420. consume(TokenType::BracketOpen);
  421. NonnullRefPtrVector<Expression> elements;
  422. while (match_expression()) {
  423. elements.append(parse_expression(0));
  424. if (!match(TokenType::Comma))
  425. break;
  426. consume(TokenType::Comma);
  427. }
  428. consume(TokenType::BracketClose);
  429. return create_ast_node<ArrayExpression>(move(elements));
  430. }
  431. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity)
  432. {
  433. auto expression = parse_primary_expression();
  434. while (match_secondary_expression()) {
  435. int new_precedence = operator_precedence(m_parser_state.m_current_token.type());
  436. if (new_precedence < min_precedence)
  437. break;
  438. if (new_precedence == min_precedence && associativity == Associativity::Left)
  439. break;
  440. Associativity new_associativity = operator_associativity(m_parser_state.m_current_token.type());
  441. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  442. }
  443. return expression;
  444. }
  445. NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  446. {
  447. switch (m_parser_state.m_current_token.type()) {
  448. case TokenType::Plus:
  449. consume();
  450. return create_ast_node<BinaryExpression>(BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity));
  451. case TokenType::PlusEquals:
  452. consume();
  453. return create_ast_node<AssignmentExpression>(AssignmentOp::AdditionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  454. case TokenType::Minus:
  455. consume();
  456. return create_ast_node<BinaryExpression>(BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity));
  457. case TokenType::MinusEquals:
  458. consume();
  459. return create_ast_node<AssignmentExpression>(AssignmentOp::SubtractionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  460. case TokenType::Asterisk:
  461. consume();
  462. return create_ast_node<BinaryExpression>(BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity));
  463. case TokenType::AsteriskEquals:
  464. consume();
  465. return create_ast_node<AssignmentExpression>(AssignmentOp::MultiplicationAssignment, move(lhs), parse_expression(min_precedence, associativity));
  466. case TokenType::Slash:
  467. consume();
  468. return create_ast_node<BinaryExpression>(BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity));
  469. case TokenType::SlashEquals:
  470. consume();
  471. return create_ast_node<AssignmentExpression>(AssignmentOp::DivisionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  472. case TokenType::Percent:
  473. consume();
  474. return create_ast_node<BinaryExpression>(BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity));
  475. case TokenType::DoubleAsterisk:
  476. consume();
  477. return create_ast_node<BinaryExpression>(BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity));
  478. case TokenType::GreaterThan:
  479. consume();
  480. return create_ast_node<BinaryExpression>(BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  481. case TokenType::GreaterThanEquals:
  482. consume();
  483. return create_ast_node<BinaryExpression>(BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  484. case TokenType::LessThan:
  485. consume();
  486. return create_ast_node<BinaryExpression>(BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  487. case TokenType::LessThanEquals:
  488. consume();
  489. return create_ast_node<BinaryExpression>(BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  490. case TokenType::EqualsEqualsEquals:
  491. consume();
  492. return create_ast_node<BinaryExpression>(BinaryOp::TypedEquals, move(lhs), parse_expression(min_precedence, associativity));
  493. case TokenType::ExclamationMarkEqualsEquals:
  494. consume();
  495. return create_ast_node<BinaryExpression>(BinaryOp::TypedInequals, move(lhs), parse_expression(min_precedence, associativity));
  496. case TokenType::EqualsEquals:
  497. consume();
  498. return create_ast_node<BinaryExpression>(BinaryOp::AbstractEquals, move(lhs), parse_expression(min_precedence, associativity));
  499. case TokenType::ExclamationMarkEquals:
  500. consume();
  501. return create_ast_node<BinaryExpression>(BinaryOp::AbstractInequals, move(lhs), parse_expression(min_precedence, associativity));
  502. case TokenType::Instanceof:
  503. consume();
  504. return create_ast_node<BinaryExpression>(BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity));
  505. case TokenType::Ampersand:
  506. consume();
  507. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity));
  508. case TokenType::Pipe:
  509. consume();
  510. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity));
  511. case TokenType::Caret:
  512. consume();
  513. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity));
  514. case TokenType::ParenOpen:
  515. return parse_call_expression(move(lhs));
  516. case TokenType::Equals:
  517. consume();
  518. return create_ast_node<AssignmentExpression>(AssignmentOp::Assignment, move(lhs), parse_expression(min_precedence, associativity));
  519. case TokenType::Period:
  520. consume();
  521. return create_ast_node<MemberExpression>(move(lhs), parse_expression(min_precedence, associativity));
  522. case TokenType::BracketOpen: {
  523. consume(TokenType::BracketOpen);
  524. auto expression = create_ast_node<MemberExpression>(move(lhs), parse_expression(0), true);
  525. consume(TokenType::BracketClose);
  526. return expression;
  527. }
  528. case TokenType::PlusPlus:
  529. consume();
  530. return create_ast_node<UpdateExpression>(UpdateOp::Increment, move(lhs));
  531. case TokenType::MinusMinus:
  532. consume();
  533. return create_ast_node<UpdateExpression>(UpdateOp::Decrement, move(lhs));
  534. case TokenType::DoubleAmpersand:
  535. consume();
  536. return create_ast_node<LogicalExpression>(LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity));
  537. case TokenType::DoublePipe:
  538. consume();
  539. return create_ast_node<LogicalExpression>(LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity));
  540. case TokenType::QuestionMark:
  541. return parse_conditional_expression(move(lhs));
  542. default:
  543. m_parser_state.m_has_errors = true;
  544. expected("secondary expression (missing switch case)");
  545. consume();
  546. return create_ast_node<ErrorExpression>();
  547. }
  548. }
  549. NonnullRefPtr<CallExpression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  550. {
  551. consume(TokenType::ParenOpen);
  552. NonnullRefPtrVector<Expression> arguments;
  553. while (match_expression()) {
  554. arguments.append(parse_expression(0));
  555. if (!match(TokenType::Comma))
  556. break;
  557. consume();
  558. }
  559. consume(TokenType::ParenClose);
  560. return create_ast_node<CallExpression>(move(lhs), move(arguments));
  561. }
  562. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  563. {
  564. consume(TokenType::New);
  565. // FIXME: Support full expressions as the callee as well.
  566. auto callee = create_ast_node<Identifier>(consume(TokenType::Identifier).value());
  567. NonnullRefPtrVector<Expression> arguments;
  568. if (match(TokenType::ParenOpen)) {
  569. consume(TokenType::ParenOpen);
  570. while (match_expression()) {
  571. arguments.append(parse_expression(0));
  572. if (!match(TokenType::Comma))
  573. break;
  574. consume();
  575. }
  576. consume(TokenType::ParenClose);
  577. }
  578. return create_ast_node<NewExpression>(move(callee), move(arguments));
  579. }
  580. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  581. {
  582. consume(TokenType::Return);
  583. if (match_expression()) {
  584. return create_ast_node<ReturnStatement>(parse_expression(0));
  585. }
  586. return create_ast_node<ReturnStatement>(nullptr);
  587. }
  588. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  589. {
  590. ScopePusher scope(*this, ScopePusher::Let);
  591. auto block = create_ast_node<BlockStatement>();
  592. consume(TokenType::CurlyOpen);
  593. while (!done() && !match(TokenType::CurlyClose)) {
  594. if (match(TokenType::Semicolon)) {
  595. consume();
  596. } else if (match_statement()) {
  597. block->append(parse_statement());
  598. } else {
  599. expected("statement");
  600. consume();
  601. }
  602. }
  603. consume(TokenType::CurlyClose);
  604. block->add_variables(m_parser_state.m_let_scopes.last());
  605. return block;
  606. }
  607. template<typename FunctionNodeType>
  608. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node()
  609. {
  610. ScopePusher scope(*this, ScopePusher::Var);
  611. consume(TokenType::Function);
  612. String name;
  613. if (FunctionNodeType::must_have_name()) {
  614. name = consume(TokenType::Identifier).value();
  615. } else {
  616. if (match(TokenType::Identifier))
  617. name = consume(TokenType::Identifier).value();
  618. }
  619. consume(TokenType::ParenOpen);
  620. Vector<FlyString> parameters;
  621. while (match(TokenType::Identifier)) {
  622. auto parameter = consume(TokenType::Identifier).value();
  623. parameters.append(parameter);
  624. if (match(TokenType::ParenClose)) {
  625. break;
  626. }
  627. consume(TokenType::Comma);
  628. }
  629. consume(TokenType::ParenClose);
  630. auto body = parse_block_statement();
  631. body->add_variables(m_parser_state.m_var_scopes.last());
  632. return create_ast_node<FunctionNodeType>(name, move(body), move(parameters), NonnullRefPtrVector<VariableDeclaration>());
  633. }
  634. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration()
  635. {
  636. DeclarationKind declaration_kind;
  637. switch (m_parser_state.m_current_token.type()) {
  638. case TokenType::Var:
  639. declaration_kind = DeclarationKind::Var;
  640. consume(TokenType::Var);
  641. break;
  642. case TokenType::Let:
  643. declaration_kind = DeclarationKind::Let;
  644. consume(TokenType::Let);
  645. break;
  646. case TokenType::Const:
  647. declaration_kind = DeclarationKind::Const;
  648. consume(TokenType::Const);
  649. break;
  650. default:
  651. ASSERT_NOT_REACHED();
  652. }
  653. NonnullRefPtrVector<VariableDeclarator> declarations;
  654. for (;;) {
  655. auto id = consume(TokenType::Identifier).value();
  656. RefPtr<Expression> init;
  657. if (match(TokenType::Equals)) {
  658. consume();
  659. init = parse_expression(0);
  660. }
  661. declarations.append(create_ast_node<VariableDeclarator>(create_ast_node<Identifier>(move(id)), move(init)));
  662. if (match(TokenType::Comma)) {
  663. consume();
  664. continue;
  665. }
  666. break;
  667. }
  668. auto declaration = create_ast_node<VariableDeclaration>(declaration_kind, move(declarations));
  669. if (declaration->declaration_kind() == DeclarationKind::Var)
  670. m_parser_state.m_var_scopes.last().append(declaration);
  671. else
  672. m_parser_state.m_let_scopes.last().append(declaration);
  673. return declaration;
  674. }
  675. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  676. {
  677. consume(TokenType::Throw);
  678. return create_ast_node<ThrowStatement>(parse_expression(0));
  679. }
  680. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  681. {
  682. consume(TokenType::Break);
  683. // FIXME: Handle labels.
  684. return create_ast_node<BreakStatement>();
  685. }
  686. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  687. {
  688. consume(TokenType::Continue);
  689. // FIXME: Handle labels.
  690. return create_ast_node<ContinueStatement>();
  691. }
  692. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test)
  693. {
  694. consume(TokenType::QuestionMark);
  695. auto consequent = parse_expression(0);
  696. consume(TokenType::Colon);
  697. auto alternate = parse_expression(0);
  698. return create_ast_node<ConditionalExpression>(move(test), move(consequent), move(alternate));
  699. }
  700. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  701. {
  702. consume(TokenType::Try);
  703. auto block = parse_block_statement();
  704. RefPtr<CatchClause> handler;
  705. if (match(TokenType::Catch))
  706. handler = parse_catch_clause();
  707. RefPtr<BlockStatement> finalizer;
  708. if (match(TokenType::Finally)) {
  709. consume();
  710. finalizer = parse_block_statement();
  711. }
  712. return create_ast_node<TryStatement>(move(block), move(handler), move(finalizer));
  713. }
  714. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  715. {
  716. consume(TokenType::Do);
  717. auto body = parse_statement();
  718. consume(TokenType::While);
  719. consume(TokenType::ParenOpen);
  720. auto test = parse_expression(0);
  721. consume(TokenType::ParenClose);
  722. return create_ast_node<DoWhileStatement>(move(test), move(body));
  723. }
  724. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  725. {
  726. consume(TokenType::Switch);
  727. consume(TokenType::ParenOpen);
  728. auto determinant = parse_expression(0);
  729. consume(TokenType::ParenClose);
  730. consume(TokenType::CurlyOpen);
  731. NonnullRefPtrVector<SwitchCase> cases;
  732. while (match(TokenType::Case) || match(TokenType::Default))
  733. cases.append(parse_switch_case());
  734. consume(TokenType::CurlyClose);
  735. return create_ast_node<SwitchStatement>(move(determinant), move(cases));
  736. }
  737. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  738. {
  739. RefPtr<Expression> test;
  740. if (consume().type() == TokenType::Case) {
  741. test = parse_expression(0);
  742. }
  743. consume(TokenType::Colon);
  744. NonnullRefPtrVector<Statement> consequent;
  745. while (match_statement())
  746. consequent.append(parse_statement());
  747. return create_ast_node<SwitchCase>(move(test), move(consequent));
  748. }
  749. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  750. {
  751. consume(TokenType::Catch);
  752. String parameter;
  753. if (match(TokenType::ParenOpen)) {
  754. consume();
  755. parameter = consume(TokenType::Identifier).value();
  756. consume(TokenType::ParenClose);
  757. }
  758. auto body = parse_block_statement();
  759. return create_ast_node<CatchClause>(parameter, move(body));
  760. }
  761. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  762. {
  763. consume(TokenType::If);
  764. consume(TokenType::ParenOpen);
  765. auto predicate = parse_expression(0);
  766. consume(TokenType::ParenClose);
  767. auto consequent = parse_statement();
  768. RefPtr<Statement> alternate;
  769. if (match(TokenType::Else)) {
  770. consume(TokenType::Else);
  771. alternate = parse_statement();
  772. }
  773. return create_ast_node<IfStatement>(move(predicate), move(consequent), move(alternate));
  774. }
  775. NonnullRefPtr<ForStatement> Parser::parse_for_statement()
  776. {
  777. consume(TokenType::For);
  778. consume(TokenType::ParenOpen);
  779. RefPtr<ASTNode> init;
  780. switch (m_parser_state.m_current_token.type()) {
  781. case TokenType::Semicolon:
  782. break;
  783. default:
  784. if (match_expression())
  785. init = parse_expression(0);
  786. else if (match_variable_declaration())
  787. init = parse_variable_declaration();
  788. else
  789. ASSERT_NOT_REACHED();
  790. break;
  791. }
  792. consume(TokenType::Semicolon);
  793. RefPtr<Expression> test;
  794. switch (m_parser_state.m_current_token.type()) {
  795. case TokenType::Semicolon:
  796. break;
  797. default:
  798. test = parse_expression(0);
  799. break;
  800. }
  801. consume(TokenType::Semicolon);
  802. RefPtr<Expression> update;
  803. switch (m_parser_state.m_current_token.type()) {
  804. case TokenType::ParenClose:
  805. break;
  806. default:
  807. update = parse_expression(0);
  808. break;
  809. }
  810. consume(TokenType::ParenClose);
  811. auto body = parse_statement();
  812. return create_ast_node<ForStatement>(move(init), move(test), move(update), move(body));
  813. }
  814. bool Parser::match(TokenType type) const
  815. {
  816. return m_parser_state.m_current_token.type() == type;
  817. }
  818. bool Parser::match_variable_declaration() const
  819. {
  820. switch (m_parser_state.m_current_token.type()) {
  821. case TokenType::Var:
  822. case TokenType::Let:
  823. case TokenType::Const:
  824. return true;
  825. default:
  826. return false;
  827. }
  828. }
  829. bool Parser::match_expression() const
  830. {
  831. auto type = m_parser_state.m_current_token.type();
  832. return type == TokenType::BoolLiteral
  833. || type == TokenType::NumericLiteral
  834. || type == TokenType::StringLiteral
  835. || type == TokenType::NullLiteral
  836. || type == TokenType::Identifier
  837. || type == TokenType::New
  838. || type == TokenType::CurlyOpen
  839. || type == TokenType::BracketOpen
  840. || type == TokenType::ParenOpen
  841. || type == TokenType::Function
  842. || type == TokenType::This
  843. || match_unary_prefixed_expression();
  844. }
  845. bool Parser::match_unary_prefixed_expression() const
  846. {
  847. auto type = m_parser_state.m_current_token.type();
  848. return type == TokenType::PlusPlus
  849. || type == TokenType::MinusMinus
  850. || type == TokenType::ExclamationMark
  851. || type == TokenType::Tilde
  852. || type == TokenType::Plus
  853. || type == TokenType::Minus
  854. || type == TokenType::Typeof;
  855. }
  856. bool Parser::match_secondary_expression() const
  857. {
  858. auto type = m_parser_state.m_current_token.type();
  859. return type == TokenType::Plus
  860. || type == TokenType::PlusEquals
  861. || type == TokenType::Minus
  862. || type == TokenType::MinusEquals
  863. || type == TokenType::Asterisk
  864. || type == TokenType::AsteriskEquals
  865. || type == TokenType::Slash
  866. || type == TokenType::SlashEquals
  867. || type == TokenType::Percent
  868. || type == TokenType::DoubleAsterisk
  869. || type == TokenType::Equals
  870. || type == TokenType::EqualsEqualsEquals
  871. || type == TokenType::ExclamationMarkEqualsEquals
  872. || type == TokenType::EqualsEquals
  873. || type == TokenType::ExclamationMarkEquals
  874. || type == TokenType::GreaterThan
  875. || type == TokenType::GreaterThanEquals
  876. || type == TokenType::LessThan
  877. || type == TokenType::LessThanEquals
  878. || type == TokenType::ParenOpen
  879. || type == TokenType::Period
  880. || type == TokenType::BracketOpen
  881. || type == TokenType::PlusPlus
  882. || type == TokenType::MinusMinus
  883. || type == TokenType::Instanceof
  884. || type == TokenType::QuestionMark
  885. || type == TokenType::Ampersand
  886. || type == TokenType::Pipe
  887. || type == TokenType::Caret
  888. || type == TokenType::DoubleAmpersand
  889. || type == TokenType::DoublePipe;
  890. }
  891. bool Parser::match_statement() const
  892. {
  893. auto type = m_parser_state.m_current_token.type();
  894. return match_expression()
  895. || type == TokenType::Function
  896. || type == TokenType::Return
  897. || type == TokenType::Let
  898. || type == TokenType::Class
  899. || type == TokenType::Delete
  900. || type == TokenType::Do
  901. || type == TokenType::If
  902. || type == TokenType::Throw
  903. || type == TokenType::Try
  904. || type == TokenType::While
  905. || type == TokenType::For
  906. || type == TokenType::Const
  907. || type == TokenType::CurlyOpen
  908. || type == TokenType::Switch
  909. || type == TokenType::Break
  910. || type == TokenType::Continue
  911. || type == TokenType::Var;
  912. }
  913. bool Parser::done() const
  914. {
  915. return match(TokenType::Eof);
  916. }
  917. Token Parser::consume()
  918. {
  919. auto old_token = m_parser_state.m_current_token;
  920. m_parser_state.m_current_token = m_parser_state.m_lexer.next();
  921. return old_token;
  922. }
  923. Token Parser::consume(TokenType type)
  924. {
  925. if (m_parser_state.m_current_token.type() != type) {
  926. m_parser_state.m_has_errors = true;
  927. auto& current_token = m_parser_state.m_current_token;
  928. fprintf(stderr, "Error: Unexpected token %s. Expected %s (line: %zu, column: %zu))\n",
  929. current_token.name(),
  930. Token::name(type),
  931. current_token.line_number(),
  932. current_token.line_column());
  933. }
  934. return consume();
  935. }
  936. void Parser::expected(const char* what)
  937. {
  938. m_parser_state.m_has_errors = true;
  939. auto& current_token = m_parser_state.m_current_token;
  940. fprintf(stderr, "Error: Unexpected token %s. Expected %s (line: %zu, column: %zu)\n",
  941. current_token.name(),
  942. what,
  943. current_token.line_number(),
  944. current_token.line_column());
  945. }
  946. void Parser::save_state()
  947. {
  948. m_saved_state = m_parser_state;
  949. }
  950. void Parser::load_state()
  951. {
  952. ASSERT(m_saved_state.has_value());
  953. m_parser_state = m_saved_state.value();
  954. m_saved_state.clear();
  955. }
  956. }