Parser.cpp 37 KB

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