Parser.cpp 31 KB

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