Parser.cpp 19 KB

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