Parser.cpp 32 KB

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