Parser.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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/StdLibExtras.h>
  29. #include <stdio.h>
  30. namespace JS {
  31. static HashMap<TokenType, int> g_operator_precedence;
  32. Parser::Parser(Lexer lexer)
  33. : m_lexer(move(lexer))
  34. , m_current_token(m_lexer.next())
  35. {
  36. if (g_operator_precedence.is_empty()) {
  37. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  38. g_operator_precedence.set(TokenType::Period, 20);
  39. g_operator_precedence.set(TokenType::BracketOpen, 20);
  40. g_operator_precedence.set(TokenType::ParenOpen, 20);
  41. g_operator_precedence.set(TokenType::QuestionMarkPeriod, 20);
  42. g_operator_precedence.set(TokenType::New, 19);
  43. g_operator_precedence.set(TokenType::PlusPlus, 18);
  44. g_operator_precedence.set(TokenType::MinusMinus, 18);
  45. g_operator_precedence.set(TokenType::ExclamationMark, 17);
  46. g_operator_precedence.set(TokenType::Tilde, 17);
  47. g_operator_precedence.set(TokenType::Typeof, 17);
  48. g_operator_precedence.set(TokenType::Void, 17);
  49. g_operator_precedence.set(TokenType::Delete, 17);
  50. g_operator_precedence.set(TokenType::Await, 17);
  51. g_operator_precedence.set(TokenType::DoubleAsterisk, 16);
  52. g_operator_precedence.set(TokenType::Asterisk, 15);
  53. g_operator_precedence.set(TokenType::Slash, 15);
  54. g_operator_precedence.set(TokenType::Percent, 15);
  55. g_operator_precedence.set(TokenType::Plus, 14);
  56. g_operator_precedence.set(TokenType::Minus, 14);
  57. g_operator_precedence.set(TokenType::ShiftLeft, 13);
  58. g_operator_precedence.set(TokenType::ShiftRight, 13);
  59. g_operator_precedence.set(TokenType::UnsignedShiftRight, 13);
  60. g_operator_precedence.set(TokenType::LessThan, 12);
  61. g_operator_precedence.set(TokenType::LessThanEquals, 12);
  62. g_operator_precedence.set(TokenType::GreaterThan, 12);
  63. g_operator_precedence.set(TokenType::GreaterThanEquals, 12);
  64. g_operator_precedence.set(TokenType::In, 12);
  65. g_operator_precedence.set(TokenType::Instanceof, 12);
  66. g_operator_precedence.set(TokenType::EqualsEquals, 11);
  67. g_operator_precedence.set(TokenType::ExclamationMarkEquals, 11);
  68. g_operator_precedence.set(TokenType::EqualsEqualsEquals, 11);
  69. g_operator_precedence.set(TokenType::ExclamationMarkEqualsEquals, 11);
  70. g_operator_precedence.set(TokenType::Ampersand, 10);
  71. g_operator_precedence.set(TokenType::Caret, 9);
  72. g_operator_precedence.set(TokenType::Pipe, 8);
  73. g_operator_precedence.set(TokenType::DoubleQuestionMark, 7);
  74. g_operator_precedence.set(TokenType::DoubleAmpersand, 6);
  75. g_operator_precedence.set(TokenType::DoublePipe, 5);
  76. g_operator_precedence.set(TokenType::QuestionMark, 4);
  77. g_operator_precedence.set(TokenType::Equals, 3);
  78. g_operator_precedence.set(TokenType::PlusEquals, 3);
  79. g_operator_precedence.set(TokenType::MinusEquals, 3);
  80. g_operator_precedence.set(TokenType::AsteriskAsteriskEquals, 3);
  81. g_operator_precedence.set(TokenType::AsteriskEquals, 3);
  82. g_operator_precedence.set(TokenType::SlashEquals, 3);
  83. g_operator_precedence.set(TokenType::PercentEquals, 3);
  84. g_operator_precedence.set(TokenType::ShiftLeftEquals, 3);
  85. g_operator_precedence.set(TokenType::ShiftRightEquals, 3);
  86. g_operator_precedence.set(TokenType::UnsignedShiftRightEquals, 3);
  87. g_operator_precedence.set(TokenType::PipeEquals, 3);
  88. g_operator_precedence.set(TokenType::Yield, 2);
  89. g_operator_precedence.set(TokenType::Comma, 1);
  90. }
  91. }
  92. int Parser::operator_precedence(TokenType type) const
  93. {
  94. auto it = g_operator_precedence.find(type);
  95. if (it == g_operator_precedence.end()) {
  96. fprintf(stderr, "No precedence for operator %s\n", Token::name(type));
  97. ASSERT_NOT_REACHED();
  98. return -1;
  99. }
  100. return it->value;
  101. }
  102. Associativity Parser::operator_associativity(TokenType type) const
  103. {
  104. switch (type) {
  105. case TokenType::Period:
  106. case TokenType::BracketOpen:
  107. case TokenType::ParenOpen:
  108. case TokenType::QuestionMarkPeriod:
  109. case TokenType::Asterisk:
  110. case TokenType::Slash:
  111. case TokenType::Percent:
  112. case TokenType::Plus:
  113. case TokenType::Minus:
  114. case TokenType::ShiftLeft:
  115. case TokenType::ShiftRight:
  116. case TokenType::UnsignedShiftRight:
  117. case TokenType::LessThan:
  118. case TokenType::LessThanEquals:
  119. case TokenType::GreaterThan:
  120. case TokenType::GreaterThanEquals:
  121. case TokenType::In:
  122. case TokenType::Instanceof:
  123. case TokenType::EqualsEquals:
  124. case TokenType::ExclamationMarkEquals:
  125. case TokenType::EqualsEqualsEquals:
  126. case TokenType::ExclamationMarkEqualsEquals:
  127. case TokenType::Ampersand:
  128. case TokenType::Caret:
  129. case TokenType::Pipe:
  130. case TokenType::DoubleQuestionMark:
  131. case TokenType::DoubleAmpersand:
  132. case TokenType::DoublePipe:
  133. case TokenType::Comma:
  134. return Associativity::Left;
  135. default:
  136. return Associativity::Right;
  137. }
  138. }
  139. NonnullRefPtr<Program> Parser::parse_program()
  140. {
  141. auto program = adopt(*new Program);
  142. while (!done()) {
  143. if (match(TokenType::Semicolon)) {
  144. consume();
  145. } else if (match_statement()) {
  146. program->append(parse_statement());
  147. } else {
  148. expected("statement");
  149. consume();
  150. }
  151. }
  152. return program;
  153. }
  154. NonnullRefPtr<Statement> Parser::parse_statement()
  155. {
  156. auto statement = [this]() -> NonnullRefPtr<Statement> {
  157. switch (m_current_token.type()) {
  158. case TokenType::Function:
  159. return parse_function_node<FunctionDeclaration>();
  160. case TokenType::CurlyOpen:
  161. return parse_block_statement();
  162. case TokenType::Return:
  163. return parse_return_statement();
  164. case TokenType::Var:
  165. case TokenType::Let:
  166. case TokenType::Const:
  167. return parse_variable_declaration();
  168. case TokenType::For:
  169. return parse_for_statement();
  170. case TokenType::If:
  171. return parse_if_statement();
  172. default:
  173. if (match_expression())
  174. return adopt(*new ExpressionStatement(parse_expression(0)));
  175. m_has_errors = true;
  176. expected("statement (missing switch case)");
  177. consume();
  178. return create_ast_node<ErrorStatement>();
  179. } }();
  180. if (match(TokenType::Semicolon))
  181. consume();
  182. return statement;
  183. }
  184. NonnullRefPtr<Expression> Parser::parse_primary_expression()
  185. {
  186. switch (m_current_token.type()) {
  187. case TokenType::ParenOpen: {
  188. consume(TokenType::ParenOpen);
  189. auto expression = parse_expression(0);
  190. consume(TokenType::ParenClose);
  191. return expression;
  192. }
  193. case TokenType::Identifier:
  194. return create_ast_node<Identifier>(consume().value());
  195. case TokenType::NumericLiteral:
  196. return create_ast_node<NumericLiteral>(consume().double_value());
  197. case TokenType::BoolLiteral:
  198. return create_ast_node<BooleanLiteral>(consume().bool_value());
  199. case TokenType::StringLiteral:
  200. return create_ast_node<StringLiteral>(consume().string_value());
  201. case TokenType::NullLiteral:
  202. consume();
  203. return create_ast_node<NullLiteral>();
  204. case TokenType::UndefinedLiteral:
  205. consume();
  206. return create_ast_node<UndefinedLiteral>();
  207. case TokenType::CurlyOpen:
  208. return parse_object_expression();
  209. case TokenType::Function:
  210. return parse_function_node<FunctionExpression>();
  211. case TokenType::BracketOpen:
  212. return parse_array_expression();
  213. default:
  214. m_has_errors = true;
  215. expected("primary expression (missing switch case)");
  216. consume();
  217. return create_ast_node<ErrorExpression>();
  218. }
  219. }
  220. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  221. {
  222. switch (m_current_token.type()) {
  223. case TokenType::PlusPlus:
  224. consume();
  225. return create_ast_node<UpdateExpression>(UpdateOp::Increment, parse_primary_expression(), true);
  226. case TokenType::MinusMinus:
  227. consume();
  228. return create_ast_node<UpdateExpression>(UpdateOp::Decrement, parse_primary_expression(), true);
  229. case TokenType::ExclamationMark:
  230. consume();
  231. return create_ast_node<UnaryExpression>(UnaryOp::Not, parse_primary_expression());
  232. case TokenType::Tilde:
  233. consume();
  234. return create_ast_node<UnaryExpression>(UnaryOp::BitwiseNot, parse_primary_expression());
  235. case TokenType::Typeof:
  236. consume();
  237. return create_ast_node<UnaryExpression>(UnaryOp::Typeof, parse_primary_expression());
  238. default:
  239. m_has_errors = true;
  240. expected("primary expression (missing switch case)");
  241. consume();
  242. return create_ast_node<ErrorExpression>();
  243. }
  244. }
  245. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  246. {
  247. HashMap<FlyString, NonnullRefPtr<Expression>> properties;
  248. consume(TokenType::CurlyOpen);
  249. while (!match(TokenType::CurlyClose)) {
  250. auto identifier = create_ast_node<Identifier>(consume(TokenType::Identifier).value());
  251. if (match(TokenType::Colon)) {
  252. consume(TokenType::Colon);
  253. properties.set(identifier->string(), parse_expression(0));
  254. } else {
  255. properties.set(identifier->string(), identifier);
  256. }
  257. if (!match(TokenType::Comma))
  258. break;
  259. consume(TokenType::Comma);
  260. }
  261. consume(TokenType::CurlyClose);
  262. return create_ast_node<ObjectExpression>(properties);
  263. }
  264. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  265. {
  266. consume(TokenType::BracketOpen);
  267. NonnullRefPtrVector<Expression> elements;
  268. while (match_expression()) {
  269. elements.append(parse_expression(0));
  270. if (!match(TokenType::Comma))
  271. break;
  272. consume(TokenType::Comma);
  273. }
  274. consume(TokenType::BracketClose);
  275. return create_ast_node<ArrayExpression>(move(elements));
  276. }
  277. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity)
  278. {
  279. if (match_unary_prefixed_expression())
  280. return parse_unary_prefixed_expression();
  281. auto expression = parse_primary_expression();
  282. while (match_secondary_expression()) {
  283. int new_precedence = operator_precedence(m_current_token.type());
  284. if (new_precedence < min_precedence)
  285. break;
  286. if (new_precedence == min_precedence && associativity == Associativity::Left)
  287. break;
  288. Associativity new_associativity = operator_associativity(m_current_token.type());
  289. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  290. }
  291. return expression;
  292. }
  293. NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  294. {
  295. switch (m_current_token.type()) {
  296. case TokenType::Plus:
  297. consume();
  298. return create_ast_node<BinaryExpression>(BinaryOp::Plus, move(lhs), parse_expression(min_precedence, associativity));
  299. case TokenType::PlusEquals:
  300. consume();
  301. return create_ast_node<AssignmentExpression>(AssignmentOp::AdditionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  302. case TokenType::Minus:
  303. consume();
  304. return create_ast_node<BinaryExpression>(BinaryOp::Minus, move(lhs), parse_expression(min_precedence, associativity));
  305. case TokenType::MinusEquals:
  306. consume();
  307. return create_ast_node<AssignmentExpression>(AssignmentOp::SubtractionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  308. case TokenType::Asterisk:
  309. consume();
  310. return create_ast_node<BinaryExpression>(BinaryOp::Asterisk, move(lhs), parse_expression(min_precedence, associativity));
  311. case TokenType::AsteriskEquals:
  312. consume();
  313. return create_ast_node<AssignmentExpression>(AssignmentOp::MultiplicationAssignment, move(lhs), parse_expression(min_precedence, associativity));
  314. case TokenType::Slash:
  315. consume();
  316. return create_ast_node<BinaryExpression>(BinaryOp::Slash, move(lhs), parse_expression(min_precedence, associativity));
  317. case TokenType::SlashEquals:
  318. consume();
  319. return create_ast_node<AssignmentExpression>(AssignmentOp::DivisionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  320. case TokenType::GreaterThan:
  321. consume();
  322. return create_ast_node<BinaryExpression>(BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  323. case TokenType::GreaterThanEquals:
  324. consume();
  325. return create_ast_node<BinaryExpression>(BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  326. case TokenType::LessThan:
  327. consume();
  328. return create_ast_node<BinaryExpression>(BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  329. case TokenType::LessThanEquals:
  330. consume();
  331. return create_ast_node<BinaryExpression>(BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  332. case TokenType::EqualsEqualsEquals:
  333. consume();
  334. return create_ast_node<BinaryExpression>(BinaryOp::TypedEquals, move(lhs), parse_expression(min_precedence, associativity));
  335. case TokenType::ExclamationMarkEqualsEquals:
  336. consume();
  337. return create_ast_node<BinaryExpression>(BinaryOp::TypedInequals, move(lhs), parse_expression(min_precedence, associativity));
  338. case TokenType::EqualsEquals:
  339. consume();
  340. return create_ast_node<BinaryExpression>(BinaryOp::AbstractEquals, move(lhs), parse_expression(min_precedence, associativity));
  341. case TokenType::ExclamationMarkEquals:
  342. consume();
  343. return create_ast_node<BinaryExpression>(BinaryOp::AbstractInequals, move(lhs), parse_expression(min_precedence, associativity));
  344. case TokenType::ParenOpen:
  345. return parse_call_expression(move(lhs));
  346. case TokenType::Equals:
  347. consume();
  348. return create_ast_node<AssignmentExpression>(AssignmentOp::Assignment, move(lhs), parse_expression(min_precedence, associativity));
  349. case TokenType::Period:
  350. consume();
  351. return create_ast_node<MemberExpression>(move(lhs), parse_expression(min_precedence, associativity));
  352. case TokenType::BracketOpen: {
  353. consume(TokenType::BracketOpen);
  354. auto expression = create_ast_node<MemberExpression>(move(lhs), parse_expression(0), true);
  355. consume(TokenType::BracketClose);
  356. return expression;
  357. }
  358. case TokenType::PlusPlus:
  359. consume();
  360. return create_ast_node<UpdateExpression>(UpdateOp::Increment, move(lhs));
  361. case TokenType::MinusMinus:
  362. consume();
  363. return create_ast_node<UpdateExpression>(UpdateOp::Decrement, move(lhs));
  364. case TokenType::DoubleAmpersand:
  365. consume();
  366. return create_ast_node<LogicalExpression>(LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity));
  367. case TokenType::DoublePipe:
  368. consume();
  369. return create_ast_node<LogicalExpression>(LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity));
  370. default:
  371. m_has_errors = true;
  372. expected("secondary expression (missing switch case)");
  373. consume();
  374. return create_ast_node<ErrorExpression>();
  375. }
  376. }
  377. NonnullRefPtr<CallExpression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  378. {
  379. consume(TokenType::ParenOpen);
  380. NonnullRefPtrVector<Expression> arguments;
  381. while (match_expression()) {
  382. arguments.append(parse_expression(0));
  383. if (!match(TokenType::Comma))
  384. break;
  385. consume();
  386. }
  387. consume(TokenType::ParenClose);
  388. return create_ast_node<CallExpression>(move(lhs), move(arguments));
  389. }
  390. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  391. {
  392. consume(TokenType::Return);
  393. if (match_expression()) {
  394. return create_ast_node<ReturnStatement>(parse_expression(0));
  395. }
  396. return create_ast_node<ReturnStatement>(nullptr);
  397. }
  398. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  399. {
  400. auto block = create_ast_node<BlockStatement>();
  401. consume(TokenType::CurlyOpen);
  402. while (!done() && !match(TokenType::CurlyClose)) {
  403. if (match(TokenType::Semicolon)) {
  404. consume();
  405. } else if (match_statement()) {
  406. block->append(parse_statement());
  407. } else {
  408. expected("statement");
  409. consume();
  410. }
  411. }
  412. consume(TokenType::CurlyClose);
  413. return block;
  414. }
  415. template<typename FunctionNodeType>
  416. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node()
  417. {
  418. consume(TokenType::Function);
  419. String name;
  420. if (FunctionNodeType::must_have_name()) {
  421. name = consume(TokenType::Identifier).value();
  422. } else {
  423. if (match(TokenType::Identifier))
  424. name = consume(TokenType::Identifier).value();
  425. }
  426. consume(TokenType::ParenOpen);
  427. Vector<FlyString> parameters;
  428. while (match(TokenType::Identifier)) {
  429. auto parameter = consume(TokenType::Identifier).value();
  430. parameters.append(parameter);
  431. if (match(TokenType::ParenClose)) {
  432. break;
  433. }
  434. consume(TokenType::Comma);
  435. }
  436. consume(TokenType::ParenClose);
  437. auto body = parse_block_statement();
  438. return create_ast_node<FunctionNodeType>(name, move(body), move(parameters));
  439. }
  440. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration()
  441. {
  442. DeclarationType declaration_type;
  443. switch (m_current_token.type()) {
  444. case TokenType::Var:
  445. declaration_type = DeclarationType::Var;
  446. consume(TokenType::Var);
  447. break;
  448. case TokenType::Let:
  449. declaration_type = DeclarationType::Let;
  450. consume(TokenType::Let);
  451. break;
  452. case TokenType::Const:
  453. declaration_type = DeclarationType::Const;
  454. consume(TokenType::Const);
  455. break;
  456. default:
  457. ASSERT_NOT_REACHED();
  458. }
  459. auto name = consume(TokenType::Identifier).value();
  460. RefPtr<Expression> initializer;
  461. if (match(TokenType::Equals)) {
  462. consume();
  463. initializer = parse_expression(0);
  464. }
  465. return create_ast_node<VariableDeclaration>(create_ast_node<Identifier>(name), move(initializer), declaration_type);
  466. }
  467. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  468. {
  469. consume(TokenType::If);
  470. consume(TokenType::ParenOpen);
  471. auto predicate = parse_expression(0);
  472. consume(TokenType::ParenClose);
  473. auto consequent = parse_statement();
  474. RefPtr<Statement> alternate;
  475. if (match(TokenType::Else)) {
  476. consume(TokenType::Else);
  477. alternate = parse_statement();
  478. }
  479. return create_ast_node<IfStatement>(move(predicate), move(consequent), move(alternate));
  480. }
  481. NonnullRefPtr<ForStatement> Parser::parse_for_statement()
  482. {
  483. consume(TokenType::For);
  484. consume(TokenType::ParenOpen);
  485. RefPtr<ASTNode> init;
  486. switch (m_current_token.type()) {
  487. case TokenType::Semicolon:
  488. break;
  489. default:
  490. if (match_expression())
  491. init = parse_expression(0);
  492. else if (match_variable_declaration())
  493. init = parse_variable_declaration();
  494. else
  495. ASSERT_NOT_REACHED();
  496. break;
  497. }
  498. consume(TokenType::Semicolon);
  499. RefPtr<Expression> test;
  500. switch (m_current_token.type()) {
  501. case TokenType::Semicolon:
  502. break;
  503. default:
  504. test = parse_expression(0);
  505. break;
  506. }
  507. consume(TokenType::Semicolon);
  508. RefPtr<Expression> update;
  509. switch (m_current_token.type()) {
  510. case TokenType::Semicolon:
  511. break;
  512. default:
  513. update = parse_expression(0);
  514. break;
  515. }
  516. consume(TokenType::ParenClose);
  517. auto body = parse_block_statement();
  518. return create_ast_node<ForStatement>(move(init), move(test), move(update), move(body));
  519. }
  520. bool Parser::match(TokenType type) const
  521. {
  522. return m_current_token.type() == type;
  523. }
  524. bool Parser::match_variable_declaration() const
  525. {
  526. switch (m_current_token.type()) {
  527. case TokenType::Var:
  528. case TokenType::Let:
  529. case TokenType::Const:
  530. return true;
  531. default:
  532. return false;
  533. }
  534. }
  535. bool Parser::match_expression() const
  536. {
  537. auto type = m_current_token.type();
  538. return type == TokenType::BoolLiteral
  539. || type == TokenType::NumericLiteral
  540. || type == TokenType::StringLiteral
  541. || type == TokenType::UndefinedLiteral
  542. || type == TokenType::NullLiteral
  543. || type == TokenType::Identifier
  544. || type == TokenType::New
  545. || type == TokenType::CurlyOpen
  546. || type == TokenType::BracketOpen
  547. || type == TokenType::ParenOpen
  548. || type == TokenType::Function
  549. || match_unary_prefixed_expression();
  550. }
  551. bool Parser::match_unary_prefixed_expression() const
  552. {
  553. auto type = m_current_token.type();
  554. return type == TokenType::PlusPlus
  555. || type == TokenType::MinusMinus
  556. || type == TokenType::ExclamationMark
  557. || type == TokenType::Tilde
  558. || type == TokenType::Typeof;
  559. }
  560. bool Parser::match_secondary_expression() const
  561. {
  562. auto type = m_current_token.type();
  563. return type == TokenType::Plus
  564. || type == TokenType::PlusEquals
  565. || type == TokenType::Minus
  566. || type == TokenType::MinusEquals
  567. || type == TokenType::Asterisk
  568. || type == TokenType::AsteriskEquals
  569. || type == TokenType::Slash
  570. || type == TokenType::SlashEquals
  571. || type == TokenType::Equals
  572. || type == TokenType::EqualsEqualsEquals
  573. || type == TokenType::ExclamationMarkEqualsEquals
  574. || type == TokenType::EqualsEquals
  575. || type == TokenType::ExclamationMarkEquals
  576. || type == TokenType::GreaterThan
  577. || type == TokenType::GreaterThanEquals
  578. || type == TokenType::LessThan
  579. || type == TokenType::LessThanEquals
  580. || type == TokenType::ParenOpen
  581. || type == TokenType::Period
  582. || type == TokenType::BracketOpen
  583. || type == TokenType::PlusPlus
  584. || type == TokenType::MinusMinus;
  585. }
  586. bool Parser::match_statement() const
  587. {
  588. auto type = m_current_token.type();
  589. return match_expression()
  590. || type == TokenType::Function
  591. || type == TokenType::Return
  592. || type == TokenType::Let
  593. || type == TokenType::Catch
  594. || type == TokenType::Class
  595. || type == TokenType::Delete
  596. || type == TokenType::Do
  597. || type == TokenType::If
  598. || type == TokenType::Try
  599. || type == TokenType::While
  600. || type == TokenType::For
  601. || type == TokenType::Const
  602. || type == TokenType::CurlyOpen
  603. || type == TokenType::Var;
  604. }
  605. bool Parser::done() const
  606. {
  607. return match(TokenType::Eof);
  608. }
  609. Token Parser::consume()
  610. {
  611. auto old_token = m_current_token;
  612. m_current_token = m_lexer.next();
  613. return old_token;
  614. }
  615. Token Parser::consume(TokenType type)
  616. {
  617. if (m_current_token.type() != type) {
  618. m_has_errors = true;
  619. fprintf(stderr, "Error: Unexpected token %s. Expected %s\n", m_current_token.name(), Token::name(type));
  620. }
  621. return consume();
  622. }
  623. void Parser::expected(const char* what)
  624. {
  625. m_has_errors = true;
  626. fprintf(stderr, "Error: Unexpected token %s. Expected %s\n", m_current_token.name(), what);
  627. }
  628. }