Parser.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. NonnullOwnPtr<Program> Parser::parse_program()
  140. {
  141. auto program = make<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. NonnullOwnPtr<Statement> Parser::parse_statement()
  155. {
  156. if (match_expression()) {
  157. return make<JS::ExpressionStatement>(parse_expression(0));
  158. }
  159. switch (m_current_token.type()) {
  160. case TokenType::Function:
  161. return parse_function_declaration();
  162. case TokenType::CurlyOpen:
  163. return parse_block_statement();
  164. case TokenType::Return:
  165. return parse_return_statement();
  166. case TokenType::Var:
  167. case TokenType::Let:
  168. case TokenType::Const:
  169. return parse_variable_declaration();
  170. case TokenType::For:
  171. return parse_for_statement();
  172. default:
  173. m_has_errors = true;
  174. expected("statement (missing switch case)");
  175. consume();
  176. return make<ErrorStatement>();
  177. }
  178. }
  179. NonnullOwnPtr<Expression> Parser::parse_primary_expression()
  180. {
  181. switch (m_current_token.type()) {
  182. case TokenType::ParenOpen: {
  183. consume(TokenType::ParenOpen);
  184. auto expression = parse_expression(0);
  185. consume(TokenType::ParenClose);
  186. return expression;
  187. }
  188. case TokenType::Identifier:
  189. return make<Identifier>(consume().value());
  190. case TokenType::NumericLiteral:
  191. return make<NumericLiteral>(consume().double_value());
  192. case TokenType::BoolLiteral:
  193. return make<BooleanLiteral>(consume().bool_value());
  194. case TokenType::StringLiteral:
  195. return make<StringLiteral>(consume().string_value());
  196. case TokenType::CurlyOpen:
  197. return parse_object_expression();
  198. default:
  199. m_has_errors = true;
  200. expected("primary expression (missing switch case)");
  201. consume();
  202. return make<ErrorExpression>();
  203. }
  204. }
  205. NonnullOwnPtr<Expression> Parser::parse_unary_prefixed_expression()
  206. {
  207. switch (m_current_token.type()) {
  208. case TokenType::PlusPlus:
  209. consume();
  210. return make<UpdateExpression>(UpdateOp::Increment, parse_primary_expression(), true);
  211. case TokenType::MinusMinus:
  212. consume();
  213. return make<UpdateExpression>(UpdateOp::Decrement, parse_primary_expression(), true);
  214. case TokenType::ExclamationMark:
  215. consume();
  216. return make<UnaryExpression>(UnaryOp::Not, parse_primary_expression());
  217. case TokenType::Tilde:
  218. consume();
  219. return make<UnaryExpression>(UnaryOp::BitwiseNot, parse_primary_expression());
  220. default:
  221. m_has_errors = true;
  222. expected("primary expression (missing switch case)");
  223. consume();
  224. return make<ErrorExpression>();
  225. }
  226. }
  227. NonnullOwnPtr<ObjectExpression> Parser::parse_object_expression()
  228. {
  229. // FIXME: Parse actual object expression
  230. consume(TokenType::CurlyOpen);
  231. consume(TokenType::CurlyClose);
  232. return make<ObjectExpression>();
  233. }
  234. NonnullOwnPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity)
  235. {
  236. if (match_unary_prefixed_expression())
  237. return parse_unary_prefixed_expression();
  238. auto expression = parse_primary_expression();
  239. while (match_secondary_expression()) {
  240. int new_precedence = operator_precedence(m_current_token.type());
  241. if (new_precedence < min_precedence)
  242. break;
  243. if (new_precedence == min_precedence && associativity == Associativity::Left)
  244. break;
  245. Associativity new_associativity = operator_associativity(m_current_token.type());
  246. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  247. }
  248. return expression;
  249. }
  250. NonnullOwnPtr<Expression> Parser::parse_secondary_expression(NonnullOwnPtr<Expression> lhs, int min_precedence, Associativity associativity)
  251. {
  252. switch (m_current_token.type()) {
  253. case TokenType::Plus:
  254. consume();
  255. return make<BinaryExpression>(BinaryOp::Plus, move(lhs), parse_expression(min_precedence, associativity));
  256. case TokenType::PlusEquals:
  257. consume();
  258. return make<AssignmentExpression>(AssignmentOp::AdditionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  259. case TokenType::Minus:
  260. consume();
  261. return make<BinaryExpression>(BinaryOp::Minus, move(lhs), parse_expression(min_precedence, associativity));
  262. case TokenType::MinusEquals:
  263. consume();
  264. return make<AssignmentExpression>(AssignmentOp::SubtractionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  265. case TokenType::Asterisk:
  266. consume();
  267. return make<BinaryExpression>(BinaryOp::Asterisk, move(lhs), parse_expression(min_precedence, associativity));
  268. case TokenType::AsteriskEquals:
  269. consume();
  270. return make<AssignmentExpression>(AssignmentOp::MultiplicationAssignment, move(lhs), parse_expression(min_precedence, associativity));
  271. case TokenType::Slash:
  272. consume();
  273. return make<BinaryExpression>(BinaryOp::Slash, move(lhs), parse_expression(min_precedence, associativity));
  274. case TokenType::SlashEquals:
  275. consume();
  276. return make<AssignmentExpression>(AssignmentOp::DivisionAssignment, move(lhs), parse_expression(min_precedence, associativity));
  277. case TokenType::GreaterThan:
  278. consume();
  279. return make<BinaryExpression>(BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  280. case TokenType::GreaterThanEquals:
  281. consume();
  282. return make<BinaryExpression>(BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  283. case TokenType::LessThan:
  284. consume();
  285. return make<BinaryExpression>(BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  286. case TokenType::LessThanEquals:
  287. consume();
  288. return make<BinaryExpression>(BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  289. case TokenType::EqualsEqualsEquals:
  290. consume();
  291. return make<BinaryExpression>(BinaryOp::TypedEquals, move(lhs), parse_expression(min_precedence, associativity));
  292. case TokenType::ExclamationMarkEqualsEquals:
  293. consume();
  294. return make<BinaryExpression>(BinaryOp::TypedInequals, move(lhs), parse_expression(min_precedence, associativity));
  295. case TokenType::ParenOpen:
  296. return parse_call_expression(move(lhs));
  297. case TokenType::Equals:
  298. consume();
  299. return make<AssignmentExpression>(AssignmentOp::Assignment, move(lhs), parse_expression(min_precedence, associativity));
  300. case TokenType::Period:
  301. consume();
  302. return make<MemberExpression>(move(lhs), parse_expression(min_precedence, associativity));
  303. case TokenType::PlusPlus:
  304. consume();
  305. return make<UpdateExpression>(UpdateOp::Increment, move(lhs));
  306. case TokenType::MinusMinus:
  307. consume();
  308. return make<UpdateExpression>(UpdateOp::Decrement, move(lhs));
  309. default:
  310. m_has_errors = true;
  311. expected("secondary expression (missing switch case)");
  312. consume();
  313. return make<ErrorExpression>();
  314. }
  315. }
  316. NonnullOwnPtr<CallExpression> Parser::parse_call_expression(NonnullOwnPtr<Expression> lhs)
  317. {
  318. consume(TokenType::ParenOpen);
  319. NonnullOwnPtrVector<Expression> arguments;
  320. while (match_expression()) {
  321. arguments.append(parse_expression(0));
  322. if (!match(TokenType::Comma))
  323. break;
  324. consume();
  325. }
  326. consume(TokenType::ParenClose);
  327. return make<CallExpression>(move(lhs), move(arguments));
  328. }
  329. NonnullOwnPtr<ReturnStatement> Parser::parse_return_statement()
  330. {
  331. consume(TokenType::Return);
  332. if (match_expression()) {
  333. return make<ReturnStatement>(parse_expression(0));
  334. }
  335. return make<ReturnStatement>(nullptr);
  336. }
  337. NonnullOwnPtr<BlockStatement> Parser::parse_block_statement()
  338. {
  339. auto block = make<BlockStatement>();
  340. consume(TokenType::CurlyOpen);
  341. while (!done() && !match(TokenType::CurlyClose)) {
  342. if (match(TokenType::Semicolon)) {
  343. consume();
  344. } else if (match_statement()) {
  345. block->append(parse_statement());
  346. } else {
  347. expected("statement");
  348. consume();
  349. }
  350. }
  351. consume(TokenType::CurlyClose);
  352. return block;
  353. }
  354. NonnullOwnPtr<FunctionDeclaration> Parser::parse_function_declaration()
  355. {
  356. consume(TokenType::Function);
  357. auto name = consume(TokenType::Identifier).value();
  358. consume(TokenType::ParenOpen);
  359. Vector<String> parameters;
  360. while (match(TokenType::Identifier)) {
  361. auto parameter = consume(TokenType::Identifier).value();
  362. parameters.append(parameter);
  363. if (match(TokenType::ParenClose)) {
  364. break;
  365. }
  366. consume(TokenType::Comma);
  367. }
  368. consume(TokenType::ParenClose);
  369. auto body = parse_block_statement();
  370. return make<FunctionDeclaration>(name, move(body), move(parameters));
  371. }
  372. NonnullOwnPtr<VariableDeclaration> Parser::parse_variable_declaration()
  373. {
  374. DeclarationType declaration_type;
  375. switch (m_current_token.type()) {
  376. case TokenType::Var:
  377. declaration_type = DeclarationType::Var;
  378. consume(TokenType::Var);
  379. break;
  380. case TokenType::Let:
  381. declaration_type = DeclarationType::Let;
  382. consume(TokenType::Let);
  383. break;
  384. case TokenType::Const:
  385. declaration_type = DeclarationType::Const;
  386. consume(TokenType::Const);
  387. break;
  388. default:
  389. ASSERT_NOT_REACHED();
  390. }
  391. auto name = consume(TokenType::Identifier).value();
  392. OwnPtr<Expression> initializer;
  393. if (match(TokenType::Equals)) {
  394. consume();
  395. initializer = parse_expression(0);
  396. }
  397. return make<VariableDeclaration>(make<Identifier>(name), move(initializer), declaration_type);
  398. }
  399. NonnullOwnPtr<ForStatement> Parser::parse_for_statement()
  400. {
  401. consume(TokenType::For);
  402. consume(TokenType::ParenOpen);
  403. OwnPtr<Statement> init = nullptr;
  404. switch (m_current_token.type()) {
  405. case TokenType::Semicolon:
  406. break;
  407. default:
  408. init = parse_statement();
  409. break;
  410. }
  411. consume(TokenType::Semicolon);
  412. OwnPtr<Expression> test = nullptr;
  413. switch (m_current_token.type()) {
  414. case TokenType::Semicolon:
  415. break;
  416. default:
  417. test = parse_expression(0);
  418. break;
  419. }
  420. consume(TokenType::Semicolon);
  421. OwnPtr<Expression> update = nullptr;
  422. switch (m_current_token.type()) {
  423. case TokenType::Semicolon:
  424. break;
  425. default:
  426. update = parse_expression(0);
  427. break;
  428. }
  429. consume(TokenType::ParenClose);
  430. auto body = parse_block_statement();
  431. return make<ForStatement>(move(init), move(test), move(update), move(body));
  432. }
  433. bool Parser::match(TokenType type) const
  434. {
  435. return m_current_token.type() == type;
  436. }
  437. bool Parser::match_expression() const
  438. {
  439. auto type = m_current_token.type();
  440. return type == TokenType::BoolLiteral
  441. || type == TokenType::NumericLiteral
  442. || type == TokenType::StringLiteral
  443. || type == TokenType::NullLiteral
  444. || type == TokenType::Identifier
  445. || type == TokenType::New
  446. || type == TokenType::CurlyOpen
  447. || type == TokenType::BracketOpen
  448. || type == TokenType::ParenOpen
  449. || match_unary_prefixed_expression();
  450. }
  451. bool Parser::match_unary_prefixed_expression() const
  452. {
  453. auto type = m_current_token.type();
  454. return type == TokenType::PlusPlus
  455. || type == TokenType::MinusMinus
  456. || type == TokenType::ExclamationMark
  457. || type == TokenType::Tilde;
  458. }
  459. bool Parser::match_secondary_expression() const
  460. {
  461. auto type = m_current_token.type();
  462. return type == TokenType::Plus
  463. || type == TokenType::PlusEquals
  464. || type == TokenType::Minus
  465. || type == TokenType::MinusEquals
  466. || type == TokenType::Asterisk
  467. || type == TokenType::AsteriskEquals
  468. || type == TokenType::Slash
  469. || type == TokenType::SlashEquals
  470. || type == TokenType::Equals
  471. || type == TokenType::EqualsEqualsEquals
  472. || type == TokenType::ExclamationMarkEqualsEquals
  473. || type == TokenType::GreaterThan
  474. || type == TokenType::GreaterThanEquals
  475. || type == TokenType::LessThan
  476. || type == TokenType::LessThanEquals
  477. || type == TokenType::ParenOpen
  478. || type == TokenType::Period
  479. || type == TokenType::PlusPlus
  480. || type == TokenType::MinusMinus;
  481. }
  482. bool Parser::match_statement() const
  483. {
  484. auto type = m_current_token.type();
  485. return match_expression()
  486. || type == TokenType::Function
  487. || type == TokenType::Return
  488. || type == TokenType::Let
  489. || type == TokenType::Catch
  490. || type == TokenType::Class
  491. || type == TokenType::Delete
  492. || type == TokenType::Do
  493. || type == TokenType::If
  494. || type == TokenType::Try
  495. || type == TokenType::While
  496. || type == TokenType::For
  497. || type == TokenType::Const
  498. || type == TokenType::CurlyOpen
  499. || type == TokenType::Var;
  500. }
  501. bool Parser::done() const
  502. {
  503. return match(TokenType::Eof);
  504. }
  505. Token Parser::consume()
  506. {
  507. auto old_token = m_current_token;
  508. m_current_token = m_lexer.next();
  509. return old_token;
  510. }
  511. Token Parser::consume(TokenType type)
  512. {
  513. if (m_current_token.type() != type) {
  514. m_has_errors = true;
  515. fprintf(stderr, "Error: Unexpected token %s. Expected %s\n", m_current_token.name(), Token::name(type));
  516. }
  517. return consume();
  518. }
  519. void Parser::expected(const char* what)
  520. {
  521. m_has_errors = true;
  522. fprintf(stderr, "Error: Unexpected token %s. Expected %s\n", m_current_token.name(), what);
  523. }
  524. }