Parser.cpp 36 KB

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