Parser.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. /*
  2. * Copyright (c) 2021, Itamar S. <itamar8910@gmail.com>
  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. // #define CPP_DEBUG
  27. #ifdef CPP_DEBUG
  28. # define DEBUG_SPAM
  29. #endif
  30. #include "Parser.h"
  31. #include "AK/LogStream.h"
  32. #include "AST.h"
  33. #include <AK/ScopeGuard.h>
  34. #include <AK/ScopeLogger.h>
  35. #include <LibCpp/Lexer.h>
  36. namespace Cpp {
  37. Parser::Parser(const StringView& program)
  38. : m_program(program)
  39. , m_lines(m_program.split_view("\n", true))
  40. {
  41. Lexer lexer(m_program);
  42. for (auto& token : lexer.lex()) {
  43. if (token.m_type == Token::Type::Whitespace)
  44. continue;
  45. m_tokens.append(move(token));
  46. }
  47. #ifdef CPP_DEBUG
  48. dbgln("Program:");
  49. dbgln("{}", m_program);
  50. dbgln("Tokens:");
  51. for (auto& token : m_tokens) {
  52. dbgln("{}", token.to_string());
  53. }
  54. #endif
  55. }
  56. NonnullRefPtr<TranslationUnit> Parser::parse()
  57. {
  58. SCOPE_LOGGER();
  59. auto unit = create_root_ast_node(m_tokens.first().m_start, m_tokens.last().m_end);
  60. while (!done()) {
  61. if (match_comment()) {
  62. consume(Token::Type::Comment);
  63. continue;
  64. }
  65. if (match_preprocessor()) {
  66. consume_preprocessor();
  67. continue;
  68. }
  69. auto declaration = match_declaration();
  70. if (declaration.has_value()) {
  71. unit->append(parse_declaration(*unit, declaration.value()));
  72. continue;
  73. }
  74. error("unexpected token");
  75. consume();
  76. }
  77. return unit;
  78. }
  79. Optional<Parser::DeclarationType> Parser::match_declaration()
  80. {
  81. switch (m_state.context) {
  82. case Context::InTranslationUnit:
  83. return match_declaration_in_translation_unit();
  84. case Context::InFunctionDefinition:
  85. return match_declaration_in_function_definition();
  86. default:
  87. error("unexpected context");
  88. return {};
  89. }
  90. }
  91. NonnullRefPtr<Declaration> Parser::parse_declaration(ASTNode& parent, DeclarationType declaration_type)
  92. {
  93. switch (declaration_type) {
  94. case DeclarationType::Function:
  95. return parse_function_declaration(parent);
  96. case DeclarationType::Variable:
  97. return parse_variable_declaration(parent);
  98. case DeclarationType::Enum:
  99. return parse_enum_declaration(parent);
  100. case DeclarationType::Struct:
  101. return parse_struct_or_class_declaration(parent, StructOrClassDeclaration::Type::Struct);
  102. default:
  103. error("unexpected declaration type");
  104. return create_ast_node<InvalidDeclaration>(parent, position(), position());
  105. }
  106. }
  107. NonnullRefPtr<FunctionDeclaration> Parser::parse_function_declaration(ASTNode& parent)
  108. {
  109. auto func = create_ast_node<FunctionDeclaration>(parent, position(), {});
  110. auto return_type_token = consume(Token::Type::KnownType);
  111. auto function_name = consume(Token::Type::Identifier);
  112. consume(Token::Type::LeftParen);
  113. auto parameters = parse_parameter_list(*func);
  114. consume(Token::Type::RightParen);
  115. RefPtr<FunctionDefinition> body;
  116. Position func_end {};
  117. if (peek(Token::Type::LeftCurly).has_value()) {
  118. body = parse_function_definition(*func);
  119. func_end = body->end();
  120. } else {
  121. func_end = position();
  122. consume(Token::Type::Semicolon);
  123. }
  124. func->m_name = text_of_token(function_name);
  125. func->m_return_type = create_ast_node<Type>(*func, return_type_token.m_start, return_type_token.m_end, text_of_token(return_type_token));
  126. if (parameters.has_value())
  127. func->m_parameters = move(parameters.value());
  128. func->m_definition = move(body);
  129. func->set_end(func_end);
  130. return func;
  131. }
  132. NonnullRefPtr<FunctionDefinition> Parser::parse_function_definition(ASTNode& parent)
  133. {
  134. SCOPE_LOGGER();
  135. auto func = create_ast_node<FunctionDefinition>(parent, position(), {});
  136. consume(Token::Type::LeftCurly);
  137. while (!eof() && peek().m_type != Token::Type::RightCurly) {
  138. func->statements().append(parse_statement(func));
  139. }
  140. func->set_end(position());
  141. if (!eof())
  142. consume(Token::Type::RightCurly);
  143. return func;
  144. }
  145. NonnullRefPtr<Statement> Parser::parse_statement(ASTNode& parent)
  146. {
  147. SCOPE_LOGGER();
  148. ArmedScopeGuard consume_semicolumn([this]() {
  149. consume(Token::Type::Semicolon);
  150. });
  151. if (match_block_statement()) {
  152. consume_semicolumn.disarm();
  153. return parse_block_statement(parent);
  154. }
  155. if (match_comment()) {
  156. consume_semicolumn.disarm();
  157. return parse_comment(parent);
  158. }
  159. if (match_variable_declaration()) {
  160. return parse_variable_declaration(parent);
  161. }
  162. if (match_expression()) {
  163. return parse_expression(parent);
  164. }
  165. if (match_keyword("return")) {
  166. return parse_return_statement(parent);
  167. }
  168. if (match_keyword("for")) {
  169. consume_semicolumn.disarm();
  170. return parse_for_statement(parent);
  171. } else {
  172. error("unexpected statement type");
  173. consume_semicolumn.disarm();
  174. consume();
  175. return create_ast_node<InvalidStatement>(parent, position(), position());
  176. }
  177. }
  178. NonnullRefPtr<Comment> Parser::parse_comment(ASTNode& parent)
  179. {
  180. auto comment = create_ast_node<Comment>(parent, position(), {});
  181. consume(Token::Type::Comment);
  182. comment->set_end(position());
  183. return comment;
  184. }
  185. bool Parser::match_block_statement()
  186. {
  187. return peek().type() == Token::Type::LeftCurly;
  188. }
  189. NonnullRefPtr<BlockStatement> Parser::parse_block_statement(ASTNode& parent)
  190. {
  191. SCOPE_LOGGER();
  192. auto block_statement = create_ast_node<BlockStatement>(parent, position(), {});
  193. consume(Token::Type::LeftCurly);
  194. while (peek().type() != Token::Type::RightCurly) {
  195. block_statement->m_statements.append(parse_statement(*block_statement));
  196. }
  197. consume(Token::Type::RightCurly);
  198. block_statement->set_end(position());
  199. return block_statement;
  200. }
  201. bool Parser::match_variable_declaration()
  202. {
  203. save_state();
  204. ScopeGuard state_guard = [this] { load_state(); };
  205. if (!peek(Token::Type::KnownType).has_value() && !peek(Token::Type::Identifier).has_value())
  206. return false;
  207. consume();
  208. if (!peek(Token::Type::Identifier).has_value())
  209. return false;
  210. consume();
  211. if (match(Token::Type::Equals)) {
  212. consume(Token::Type::Equals);
  213. if (!match_expression()) {
  214. error("initial value of variable is not an expression");
  215. return false;
  216. }
  217. }
  218. return true;
  219. }
  220. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(ASTNode& parent)
  221. {
  222. SCOPE_LOGGER();
  223. auto var = create_ast_node<VariableDeclaration>(parent, position(), {});
  224. auto type_token = consume();
  225. if (type_token.type() != Token::Type::KnownType && type_token.type() != Token::Type::Identifier) {
  226. error("unexpected token for variable type");
  227. var->set_end(type_token.end());
  228. return var;
  229. }
  230. auto identifier_token = consume(Token::Type::Identifier);
  231. RefPtr<Expression> initial_value;
  232. if (match(Token::Type::Equals)) {
  233. consume(Token::Type::Equals);
  234. initial_value = parse_expression(var);
  235. }
  236. var->set_end(position());
  237. var->m_type = create_ast_node<Type>(var, type_token.m_start, type_token.m_end, text_of_token(type_token));
  238. var->m_name = text_of_token(identifier_token);
  239. var->m_initial_value = move(initial_value);
  240. return var;
  241. }
  242. NonnullRefPtr<Expression> Parser::parse_expression(ASTNode& parent)
  243. {
  244. SCOPE_LOGGER();
  245. auto expression = parse_primary_expression(parent);
  246. // TODO: remove eof() logic, should still work without it
  247. if (eof() || match(Token::Type::Semicolon)) {
  248. return expression;
  249. }
  250. NonnullRefPtrVector<Expression> secondary_expressions;
  251. while (match_secondary_expression()) {
  252. // FIXME: Handle operator precedence
  253. expression = parse_secondary_expression(parent, expression);
  254. secondary_expressions.append(expression);
  255. }
  256. for (size_t i = 0; secondary_expressions.size() != 0 && i < secondary_expressions.size() - 1; ++i) {
  257. secondary_expressions[i].set_parent(secondary_expressions[i + 1]);
  258. }
  259. return expression;
  260. }
  261. bool Parser::match_secondary_expression()
  262. {
  263. auto type = peek().type();
  264. return type == Token::Type::Plus
  265. || type == Token::Type::PlusEquals
  266. || type == Token::Type::Minus
  267. || type == Token::Type::MinusEquals
  268. || type == Token::Type::Asterisk
  269. || type == Token::Type::AsteriskEquals
  270. || type == Token::Type::Percent
  271. || type == Token::Type::PercentEquals
  272. || type == Token::Type::Equals
  273. || type == Token::Type::Greater
  274. || type == Token::Type::Greater
  275. || type == Token::Type::Less
  276. || type == Token::Type::LessEquals
  277. || type == Token::Type::Dot
  278. || type == Token::Type::PlusPlus
  279. || type == Token::Type::MinusMinus
  280. || type == Token::Type::And
  281. || type == Token::Type::AndEquals
  282. || type == Token::Type::Pipe
  283. || type == Token::Type::PipeEquals
  284. || type == Token::Type::Caret
  285. || type == Token::Type::CaretEquals
  286. || type == Token::Type::LessLess
  287. || type == Token::Type::LessLessEquals
  288. || type == Token::Type::GreaterGreater
  289. || type == Token::Type::GreaterGreaterEquals
  290. || type == Token::Type::AndAnd
  291. || type == Token::Type::PipePipe;
  292. }
  293. NonnullRefPtr<Expression> Parser::parse_primary_expression(ASTNode& parent)
  294. {
  295. SCOPE_LOGGER();
  296. // TODO: remove eof() logic, should still work without it
  297. if (eof()) {
  298. auto node = create_ast_node<Identifier>(parent, position(), position());
  299. return node;
  300. }
  301. if (match_unary_expression())
  302. return parse_unary_expression(parent);
  303. if (match_literal()) {
  304. return parse_literal(parent);
  305. }
  306. switch (peek().type()) {
  307. case Token::Type::Identifier: {
  308. if (match_function_call())
  309. return parse_function_call(parent);
  310. auto token = consume();
  311. return create_ast_node<Identifier>(parent, token.m_start, token.m_end, text_of_token(token));
  312. }
  313. default: {
  314. error("could not parse primary expression");
  315. auto token = consume();
  316. return create_ast_node<InvalidExpression>(parent, token.m_start, token.m_end);
  317. }
  318. }
  319. }
  320. bool Parser::match_literal()
  321. {
  322. switch (peek().type()) {
  323. case Token::Type::Integer:
  324. return true;
  325. case Token::Type::DoubleQuotedString:
  326. return true;
  327. case Token::Type::Keyword: {
  328. return match_boolean_literal();
  329. }
  330. default:
  331. return false;
  332. }
  333. }
  334. bool Parser::match_unary_expression()
  335. {
  336. auto type = peek().type();
  337. return type == Token::Type::PlusPlus
  338. || type == Token::Type::MinusMinus
  339. || type == Token::Type::ExclamationMark
  340. || type == Token::Type::Tilde
  341. || type == Token::Type::Plus
  342. || type == Token::Type::Minus;
  343. }
  344. NonnullRefPtr<UnaryExpression> Parser::parse_unary_expression(ASTNode& parent)
  345. {
  346. auto unary_exp = create_ast_node<UnaryExpression>(parent, position(), {});
  347. auto op_token = consume();
  348. UnaryOp op { UnaryOp::Invalid };
  349. switch (op_token.type()) {
  350. case Token::Type::Minus:
  351. op = UnaryOp::Minus;
  352. break;
  353. case Token::Type::Plus:
  354. op = UnaryOp::Plus;
  355. break;
  356. case Token::Type::ExclamationMark:
  357. op = UnaryOp::Not;
  358. break;
  359. case Token::Type::Tilde:
  360. op = UnaryOp::BitwiseNot;
  361. break;
  362. case Token::Type::PlusPlus:
  363. op = UnaryOp::PlusPlus;
  364. break;
  365. default:
  366. break;
  367. }
  368. unary_exp->m_op = op;
  369. auto lhs = parse_expression(*unary_exp);
  370. unary_exp->m_lhs = lhs;
  371. unary_exp->set_end(lhs->end());
  372. return unary_exp;
  373. }
  374. NonnullRefPtr<Expression> Parser::parse_literal(ASTNode& parent)
  375. {
  376. switch (peek().type()) {
  377. case Token::Type::Integer: {
  378. auto token = consume();
  379. return create_ast_node<NumericLiteral>(parent, token.m_start, token.m_end, text_of_token(token));
  380. }
  381. case Token::Type::DoubleQuotedString: {
  382. return parse_string_literal(parent);
  383. }
  384. case Token::Type::Keyword: {
  385. if (match_boolean_literal())
  386. return parse_boolean_literal(parent);
  387. [[fallthrough]];
  388. }
  389. default: {
  390. error("could not parse literal");
  391. auto token = consume();
  392. return create_ast_node<InvalidExpression>(parent, token.m_start, token.m_end);
  393. }
  394. }
  395. }
  396. NonnullRefPtr<Expression> Parser::parse_secondary_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs)
  397. {
  398. SCOPE_LOGGER();
  399. switch (peek().m_type) {
  400. case Token::Type::Plus:
  401. return parse_binary_expression(parent, lhs, BinaryOp::Addition);
  402. case Token::Type::Less:
  403. return parse_binary_expression(parent, lhs, BinaryOp::LessThan);
  404. case Token::Type::Equals:
  405. return parse_assignment_expression(parent, lhs, AssignmentOp::Assignment);
  406. case Token::Type::Dot: {
  407. consume();
  408. auto exp = create_ast_node<MemberExpression>(parent, lhs->start(), {});
  409. lhs->set_parent(*exp);
  410. exp->m_object = move(lhs);
  411. auto property_token = consume(Token::Type::Identifier);
  412. exp->m_property = create_ast_node<Identifier>(*exp, property_token.start(), property_token.end(), text_of_token(property_token));
  413. exp->set_end(property_token.end());
  414. return exp;
  415. }
  416. default: {
  417. error(String::formatted("unexpected operator for expression. operator: {}", peek().to_string()));
  418. auto token = consume();
  419. return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
  420. }
  421. }
  422. }
  423. NonnullRefPtr<BinaryExpression> Parser::parse_binary_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs, BinaryOp op)
  424. {
  425. consume(); // Operator
  426. auto exp = create_ast_node<BinaryExpression>(parent, lhs->start(), {});
  427. lhs->set_parent(*exp);
  428. exp->m_op = op;
  429. exp->m_lhs = move(lhs);
  430. auto rhs = parse_expression(exp);
  431. exp->set_end(rhs->end());
  432. exp->m_rhs = move(rhs);
  433. return exp;
  434. }
  435. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs, AssignmentOp op)
  436. {
  437. consume(); // Operator
  438. auto exp = create_ast_node<AssignmentExpression>(parent, lhs->start(), {});
  439. lhs->set_parent(*exp);
  440. exp->m_op = op;
  441. exp->m_lhs = move(lhs);
  442. auto rhs = parse_expression(exp);
  443. exp->set_end(rhs->end());
  444. exp->m_rhs = move(rhs);
  445. return exp;
  446. }
  447. Optional<Parser::DeclarationType> Parser::match_declaration_in_translation_unit()
  448. {
  449. if (match_function_declaration())
  450. return DeclarationType::Function;
  451. if (match_enum_declaration())
  452. return DeclarationType::Enum;
  453. if (match_struct_declaration())
  454. return DeclarationType::Struct;
  455. return {};
  456. }
  457. bool Parser::match_enum_declaration()
  458. {
  459. return peek().type() == Token::Type::Keyword && text_of_token(peek()) == "enum";
  460. }
  461. bool Parser::match_struct_declaration()
  462. {
  463. return peek().type() == Token::Type::Keyword && text_of_token(peek()) == "struct";
  464. }
  465. bool Parser::match_function_declaration()
  466. {
  467. save_state();
  468. ScopeGuard state_guard = [this] { load_state(); };
  469. if (!peek(Token::Type::KnownType).has_value())
  470. return false;
  471. consume();
  472. if (!peek(Token::Type::Identifier).has_value())
  473. return false;
  474. consume();
  475. if (!peek(Token::Type::LeftParen).has_value())
  476. return false;
  477. consume();
  478. while (consume().m_type != Token::Type::RightParen && !eof()) { };
  479. if (peek(Token::Type::Semicolon).has_value() || peek(Token::Type::LeftCurly).has_value())
  480. return true;
  481. return false;
  482. }
  483. Optional<NonnullRefPtrVector<Parameter>> Parser::parse_parameter_list(ASTNode& parent)
  484. {
  485. SCOPE_LOGGER();
  486. NonnullRefPtrVector<Parameter> parameters;
  487. while (peek().m_type != Token::Type::RightParen && !eof()) {
  488. auto type = parse_type(parent);
  489. auto name_identifier = peek(Token::Type::Identifier);
  490. if (name_identifier.has_value())
  491. consume(Token::Type::Identifier);
  492. StringView name;
  493. if (name_identifier.has_value())
  494. name = text_of_token(name_identifier.value());
  495. auto param = create_ast_node<Parameter>(parent, type->start(), name_identifier.has_value() ? name_identifier.value().m_end : type->end(), name);
  496. param->m_type = move(type);
  497. parameters.append(move(param));
  498. if (peek(Token::Type::Comma).has_value())
  499. consume(Token::Type::Comma);
  500. }
  501. return parameters;
  502. }
  503. bool Parser::match_comment()
  504. {
  505. return match(Token::Type::Comment);
  506. }
  507. bool Parser::match_whitespace()
  508. {
  509. return match(Token::Type::Whitespace);
  510. }
  511. bool Parser::match_preprocessor()
  512. {
  513. return match(Token::Type::PreprocessorStatement) || match(Token::Type::IncludeStatement);
  514. }
  515. void Parser::consume_preprocessor()
  516. {
  517. SCOPE_LOGGER();
  518. switch (peek().type()) {
  519. case Token::Type::PreprocessorStatement:
  520. consume();
  521. break;
  522. case Token::Type::IncludeStatement:
  523. consume();
  524. consume(Token::Type::IncludePath);
  525. break;
  526. default:
  527. error("unexpected token while parsing preprocessor statement");
  528. consume();
  529. }
  530. }
  531. Optional<Token> Parser::consume_whitespace()
  532. {
  533. SCOPE_LOGGER();
  534. return consume(Token::Type::Whitespace);
  535. }
  536. Token Parser::consume(Token::Type type)
  537. {
  538. auto token = consume();
  539. if (token.type() != type)
  540. error(String::formatted("expected {} at {}:{}, found: {}", Token::type_to_string(type), token.start().line, token.start().column, Token::type_to_string(token.type())));
  541. return token;
  542. }
  543. bool Parser::match(Token::Type type)
  544. {
  545. return peek().m_type == type;
  546. }
  547. Token Parser::consume()
  548. {
  549. if (eof()) {
  550. error("C++ Parser: out of tokens");
  551. return { Token::Type::EOF_TOKEN, position(), position() };
  552. }
  553. return m_tokens[m_state.token_index++];
  554. }
  555. Token Parser::peek() const
  556. {
  557. if (eof()) {
  558. return { Token::Type::EOF_TOKEN, position(), position() };
  559. }
  560. return m_tokens[m_state.token_index];
  561. }
  562. Optional<Token> Parser::peek(Token::Type type) const
  563. {
  564. auto token = peek();
  565. if (token.m_type == type)
  566. return token;
  567. return {};
  568. }
  569. void Parser::save_state()
  570. {
  571. m_saved_states.append(m_state);
  572. }
  573. void Parser::load_state()
  574. {
  575. m_state = m_saved_states.take_last();
  576. }
  577. Optional<Parser::DeclarationType> Parser::match_declaration_in_function_definition()
  578. {
  579. ASSERT_NOT_REACHED();
  580. }
  581. bool Parser::done()
  582. {
  583. return m_state.token_index == m_tokens.size();
  584. }
  585. StringView Parser::text_of_token(const Cpp::Token& token)
  586. {
  587. ASSERT(token.m_start.line == token.m_end.line);
  588. ASSERT(token.m_start.column <= token.m_end.column);
  589. return m_lines[token.m_start.line].substring_view(token.m_start.column, token.m_end.column - token.m_start.column + 1);
  590. }
  591. StringView Parser::text_of_node(const ASTNode& node) const
  592. {
  593. if (node.start().line == node.end().line) {
  594. ASSERT(node.start().column <= node.end().column);
  595. return m_lines[node.start().line].substring_view(node.start().column, node.end().column - node.start().column + 1);
  596. }
  597. auto index_of_position([this](auto position) {
  598. size_t start_index = 0;
  599. for (size_t line = 0; line < position.line; ++line) {
  600. start_index += m_lines[line].length() + 1;
  601. }
  602. start_index += position.column;
  603. return start_index;
  604. });
  605. auto start_index = index_of_position(node.start());
  606. auto end_index = index_of_position(node.end());
  607. ASSERT(end_index >= start_index);
  608. return m_program.substring_view(start_index, end_index - start_index);
  609. }
  610. void Parser::error(StringView message)
  611. {
  612. SCOPE_LOGGER();
  613. if (message.is_null() || message.is_empty())
  614. message = "<empty>";
  615. String formatted_message;
  616. if (m_state.token_index >= m_tokens.size()) {
  617. formatted_message = String::formatted("C++ Parsed error on EOF.{}", message);
  618. } else {
  619. formatted_message = String::formatted("C++ Parser error: {}. token: {} ({}:{})",
  620. message,
  621. m_state.token_index < m_tokens.size() ? text_of_token(m_tokens[m_state.token_index]) : "EOF",
  622. m_tokens[m_state.token_index].m_start.line,
  623. m_tokens[m_state.token_index].m_start.column);
  624. }
  625. m_errors.append(formatted_message);
  626. dbgln("{}", formatted_message);
  627. }
  628. bool Parser::match_expression()
  629. {
  630. auto token_type = peek().m_type;
  631. return token_type == Token::Type::Integer
  632. || token_type == Token::Type::Float
  633. || token_type == Token::Type::Identifier
  634. || match_unary_expression();
  635. }
  636. bool Parser::eof() const
  637. {
  638. return m_state.token_index >= m_tokens.size();
  639. }
  640. Position Parser::position() const
  641. {
  642. if (eof())
  643. return m_tokens.last().m_end;
  644. return peek().m_start;
  645. }
  646. RefPtr<ASTNode> Parser::eof_node() const
  647. {
  648. ASSERT(m_tokens.size());
  649. return node_at(m_tokens.last().m_end);
  650. }
  651. RefPtr<ASTNode> Parser::node_at(Position pos) const
  652. {
  653. ASSERT(!m_tokens.is_empty());
  654. RefPtr<ASTNode> match_node;
  655. for (auto& node : m_nodes) {
  656. if (node.start() > pos || node.end() < pos)
  657. continue;
  658. if (!match_node)
  659. match_node = node;
  660. else if (node_span_size(node) < node_span_size(*match_node))
  661. match_node = node;
  662. }
  663. return match_node;
  664. }
  665. Optional<Token> Parser::token_at(Position pos) const
  666. {
  667. for (auto& token : m_tokens) {
  668. if (token.start() > pos || token.end() < pos)
  669. continue;
  670. return token;
  671. }
  672. return {};
  673. }
  674. size_t Parser::node_span_size(const ASTNode& node) const
  675. {
  676. if (node.start().line == node.end().line)
  677. return node.end().column - node.start().column;
  678. size_t span_size = m_lines[node.start().line].length() - node.start().column;
  679. for (size_t line = node.start().line + 1; line < node.end().line; ++line) {
  680. span_size += m_lines[line].length();
  681. }
  682. return span_size + m_lines[node.end().line].length() - node.end().column;
  683. }
  684. void Parser::print_tokens() const
  685. {
  686. for (auto& token : m_tokens) {
  687. dbgln("{}", token.to_string());
  688. }
  689. }
  690. bool Parser::match_function_call()
  691. {
  692. save_state();
  693. ScopeGuard state_guard = [this] { load_state(); };
  694. if (!match(Token::Type::Identifier))
  695. return false;
  696. consume();
  697. return match(Token::Type::LeftParen);
  698. }
  699. NonnullRefPtr<FunctionCall> Parser::parse_function_call(ASTNode& parent)
  700. {
  701. SCOPE_LOGGER();
  702. auto call = create_ast_node<FunctionCall>(parent, position(), {});
  703. auto name_identifier = consume(Token::Type::Identifier);
  704. call->m_name = text_of_token(name_identifier);
  705. NonnullRefPtrVector<Expression> args;
  706. consume(Token::Type::LeftParen);
  707. while (peek().type() != Token::Type::RightParen && !eof()) {
  708. args.append(parse_expression(*call));
  709. if (peek().type() == Token::Type::Comma)
  710. consume(Token::Type::Comma);
  711. }
  712. consume(Token::Type::RightParen);
  713. call->m_arguments = move(args);
  714. call->set_end(position());
  715. return call;
  716. }
  717. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(ASTNode& parent)
  718. {
  719. SCOPE_LOGGER();
  720. Optional<size_t> start_token_index;
  721. Optional<size_t> end_token_index;
  722. while (!eof()) {
  723. auto token = peek();
  724. if (token.type() != Token::Type::DoubleQuotedString && token.type() != Token::Type::EscapeSequence) {
  725. ASSERT(start_token_index.has_value());
  726. // TODO: don't consume
  727. end_token_index = m_state.token_index - 1;
  728. break;
  729. }
  730. if (!start_token_index.has_value())
  731. start_token_index = m_state.token_index;
  732. consume();
  733. }
  734. ASSERT(start_token_index.has_value());
  735. ASSERT(end_token_index.has_value());
  736. Token start_token = m_tokens[start_token_index.value()];
  737. Token end_token = m_tokens[end_token_index.value()];
  738. ASSERT(start_token.start().line == end_token.start().line);
  739. auto text = m_lines[start_token.start().line].substring_view(start_token.start().column, end_token.end().column - start_token.start().column + 1);
  740. auto string_literal = create_ast_node<StringLiteral>(parent, start_token.start(), end_token.end());
  741. string_literal->m_value = text;
  742. return string_literal;
  743. }
  744. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement(ASTNode& parent)
  745. {
  746. SCOPE_LOGGER();
  747. auto return_statement = create_ast_node<ReturnStatement>(parent, position(), {});
  748. consume(Token::Type::Keyword);
  749. auto expression = parse_expression(*return_statement);
  750. return_statement->m_value = expression;
  751. return_statement->set_end(expression->end());
  752. return return_statement;
  753. }
  754. NonnullRefPtr<EnumDeclaration> Parser::parse_enum_declaration(ASTNode& parent)
  755. {
  756. SCOPE_LOGGER();
  757. auto enum_decl = create_ast_node<EnumDeclaration>(parent, position(), {});
  758. consume_keyword("enum");
  759. auto name_token = consume(Token::Type::Identifier);
  760. enum_decl->m_name = text_of_token(name_token);
  761. consume(Token::Type::LeftCurly);
  762. while (peek().type() != Token::Type::RightCurly && !eof()) {
  763. enum_decl->m_entries.append(text_of_token(consume(Token::Type::Identifier)));
  764. if (peek().type() != Token::Type::Comma) {
  765. break;
  766. }
  767. consume(Token::Type::Comma);
  768. }
  769. consume(Token::Type::RightCurly);
  770. consume(Token::Type::Semicolon);
  771. enum_decl->set_end(position());
  772. return enum_decl;
  773. }
  774. Token Parser::consume_keyword(const String& keyword)
  775. {
  776. auto token = consume();
  777. if (token.type() != Token::Type::Keyword) {
  778. error(String::formatted("unexpected token: {}, expected Keyword", token.to_string()));
  779. return token;
  780. }
  781. if (text_of_token(token) != keyword) {
  782. error(String::formatted("unexpected keyword: {}, expected {}", text_of_token(token), keyword));
  783. return token;
  784. }
  785. return token;
  786. }
  787. bool Parser::match_keyword(const String& keyword)
  788. {
  789. auto token = peek();
  790. if (token.type() != Token::Type::Keyword) {
  791. return false;
  792. }
  793. if (text_of_token(token) != keyword) {
  794. return false;
  795. }
  796. return true;
  797. }
  798. NonnullRefPtr<StructOrClassDeclaration> Parser::parse_struct_or_class_declaration(ASTNode& parent, StructOrClassDeclaration::Type type)
  799. {
  800. SCOPE_LOGGER();
  801. auto decl = create_ast_node<StructOrClassDeclaration>(parent, position(), {}, type);
  802. switch (type) {
  803. case StructOrClassDeclaration::Type::Struct:
  804. consume_keyword("struct");
  805. break;
  806. case StructOrClassDeclaration::Type::Class:
  807. consume_keyword("class");
  808. break;
  809. }
  810. auto name_token = consume(Token::Type::Identifier);
  811. decl->m_name = text_of_token(name_token);
  812. consume(Token::Type::LeftCurly);
  813. while (peek().type() != Token::Type::RightCurly && !eof()) {
  814. decl->m_members.append(parse_member_declaration(*decl));
  815. }
  816. consume(Token::Type::RightCurly);
  817. consume(Token::Type::Semicolon);
  818. decl->set_end(position());
  819. return decl;
  820. }
  821. NonnullRefPtr<MemberDeclaration> Parser::parse_member_declaration(ASTNode& parent)
  822. {
  823. SCOPE_LOGGER();
  824. auto member_decl = create_ast_node<MemberDeclaration>(parent, position(), {});
  825. auto type_token = consume();
  826. auto identifier_token = consume(Token::Type::Identifier);
  827. RefPtr<Expression> initial_value;
  828. if (match(Token::Type::LeftCurly)) {
  829. consume(Token::Type::LeftCurly);
  830. initial_value = parse_expression(*member_decl);
  831. consume(Token::Type::RightCurly);
  832. }
  833. member_decl->m_type = create_ast_node<Type>(*member_decl, type_token.m_start, type_token.m_end, text_of_token(type_token));
  834. member_decl->m_name = text_of_token(identifier_token);
  835. member_decl->m_initial_value = move(initial_value);
  836. consume(Token::Type::Semicolon);
  837. member_decl->set_end(position());
  838. return member_decl;
  839. }
  840. NonnullRefPtr<BooleanLiteral> Parser::parse_boolean_literal(ASTNode& parent)
  841. {
  842. SCOPE_LOGGER();
  843. auto token = consume(Token::Type::Keyword);
  844. auto text = text_of_token(token);
  845. // text == "true" || text == "false";
  846. bool value = (text == "true");
  847. return create_ast_node<BooleanLiteral>(parent, token.start(), token.end(), value);
  848. }
  849. bool Parser::match_boolean_literal()
  850. {
  851. auto token = peek();
  852. if (token.type() != Token::Type::Keyword)
  853. return false;
  854. auto text = text_of_token(token);
  855. return text == "true" || text == "false";
  856. }
  857. NonnullRefPtr<Type> Parser::parse_type(ASTNode& parent)
  858. {
  859. SCOPE_LOGGER();
  860. auto token = consume();
  861. auto type = create_ast_node<Type>(parent, token.start(), token.end(), text_of_token(token));
  862. if (token.type() != Token::Type::KnownType && token.type() != Token::Type::Identifier) {
  863. error(String::formatted("unexpected token for type: {}", token.to_string()));
  864. return type;
  865. }
  866. while (peek().type() == Token::Type::Asterisk) {
  867. auto asterisk = consume();
  868. auto ptr = create_ast_node<Pointer>(type, asterisk.start(), asterisk.end());
  869. ptr->m_pointee = type;
  870. type = ptr;
  871. }
  872. return type;
  873. }
  874. NonnullRefPtr<ForStatement> Parser::parse_for_statement(ASTNode& parent)
  875. {
  876. SCOPE_LOGGER();
  877. auto for_statement = create_ast_node<ForStatement>(parent, position(), {});
  878. consume(Token::Type::Keyword);
  879. consume(Token::Type::LeftParen);
  880. for_statement->m_init = parse_variable_declaration(*for_statement);
  881. consume(Token::Type::Semicolon);
  882. for_statement->m_test = parse_expression(*for_statement);
  883. consume(Token::Type::Semicolon);
  884. for_statement->m_update = parse_expression(*for_statement);
  885. consume(Token::Type::RightParen);
  886. for_statement->m_body = parse_statement(*for_statement);
  887. for_statement->set_end(for_statement->m_body->end());
  888. return for_statement;
  889. }
  890. }