Parser.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. /*
  2. * Copyright (c) 2021, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Parser.h"
  7. #include "AST.h"
  8. #include <AK/Debug.h>
  9. #include <AK/ScopeGuard.h>
  10. #include <AK/ScopeLogger.h>
  11. #include <LibCpp/Lexer.h>
  12. #define LOG_SCOPE() ScopeLogger<CPP_DEBUG> logger(String::formatted("'{}' - {} ({})", peek().text(), peek().type_as_string(), m_state.token_index))
  13. namespace Cpp {
  14. Parser::Parser(const StringView& program, const String& filename, Preprocessor::Definitions&& definitions)
  15. : m_preprocessor_definitions(move(definitions))
  16. , m_filename(filename)
  17. {
  18. initialize_program_tokens(program);
  19. if constexpr (CPP_DEBUG) {
  20. dbgln("Tokens:");
  21. for (size_t i = 0; i < m_tokens.size(); ++i) {
  22. dbgln("{}- {}", i, m_tokens[i].to_string());
  23. }
  24. }
  25. }
  26. void Parser::initialize_program_tokens(const StringView& program)
  27. {
  28. Lexer lexer(program);
  29. for (auto& token : lexer.lex()) {
  30. if (token.type() == Token::Type::Whitespace)
  31. continue;
  32. if (token.type() == Token::Type::Identifier) {
  33. if (auto defined_value = m_preprocessor_definitions.find(text_of_token(token)); defined_value != m_preprocessor_definitions.end()) {
  34. add_tokens_for_preprocessor(token, defined_value->value);
  35. m_replaced_preprocessor_tokens.append({ token, defined_value->value });
  36. continue;
  37. }
  38. }
  39. m_tokens.append(move(token));
  40. }
  41. }
  42. NonnullRefPtr<TranslationUnit> Parser::parse()
  43. {
  44. LOG_SCOPE();
  45. if (m_tokens.is_empty())
  46. return create_root_ast_node({}, {});
  47. auto unit = create_root_ast_node(m_tokens.first().start(), m_tokens.last().end());
  48. unit->set_declarations(parse_declarations_in_translation_unit(*unit));
  49. return unit;
  50. }
  51. NonnullRefPtrVector<Declaration> Parser::parse_declarations_in_translation_unit(ASTNode& parent)
  52. {
  53. NonnullRefPtrVector<Declaration> declarations;
  54. while (!eof()) {
  55. auto declaration = parse_single_declaration_in_translation_unit(parent);
  56. if (declaration) {
  57. declarations.append(declaration.release_nonnull());
  58. } else {
  59. error("unexpected token");
  60. consume();
  61. }
  62. }
  63. return declarations;
  64. }
  65. RefPtr<Declaration> Parser::parse_single_declaration_in_translation_unit(ASTNode& parent)
  66. {
  67. while (!eof()) {
  68. if (match_comment()) {
  69. consume(Token::Type::Comment);
  70. continue;
  71. }
  72. if (match_preprocessor()) {
  73. consume_preprocessor();
  74. continue;
  75. }
  76. auto declaration = match_declaration_in_translation_unit();
  77. if (declaration.has_value()) {
  78. return parse_declaration(parent, declaration.value());
  79. }
  80. return {};
  81. }
  82. return {};
  83. }
  84. NonnullRefPtr<Declaration> Parser::parse_declaration(ASTNode& parent, DeclarationType declaration_type)
  85. {
  86. switch (declaration_type) {
  87. case DeclarationType::Function:
  88. return parse_function_declaration(parent);
  89. case DeclarationType::Variable:
  90. return parse_variable_declaration(parent);
  91. case DeclarationType::Enum:
  92. return parse_enum_declaration(parent);
  93. case DeclarationType::Class:
  94. return parse_class_declaration(parent);
  95. case DeclarationType::Namespace:
  96. return parse_namespace_declaration(parent);
  97. case DeclarationType::Constructor:
  98. return parse_constructor(parent);
  99. case DeclarationType::Destructor:
  100. return parse_destructor(parent);
  101. default:
  102. error("unexpected declaration type");
  103. return create_ast_node<InvalidDeclaration>(parent, position(), position());
  104. }
  105. }
  106. NonnullRefPtr<FunctionDeclaration> Parser::parse_function_declaration(ASTNode& parent)
  107. {
  108. auto func = create_ast_node<FunctionDeclaration>(parent, position(), {});
  109. func->set_qualifiers(parse_function_qualifiers());
  110. func->set_return_type(parse_type(*func));
  111. auto function_name = consume(Token::Type::Identifier);
  112. func->set_name(text_of_token(function_name));
  113. consume(Token::Type::LeftParen);
  114. auto parameters = parse_parameter_list(*func);
  115. if (parameters.has_value())
  116. func->set_parameters(parameters.value());
  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. if (match_attribute_specification())
  126. consume_attribute_specification(); // we don't use the value of __attribute__
  127. consume(Token::Type::Semicolon);
  128. }
  129. func->set_definition(move(body));
  130. func->set_end(func_end);
  131. return func;
  132. }
  133. NonnullRefPtr<FunctionDefinition> Parser::parse_function_definition(ASTNode& parent)
  134. {
  135. LOG_SCOPE();
  136. auto func = create_ast_node<FunctionDefinition>(parent, position(), {});
  137. consume(Token::Type::LeftCurly);
  138. while (!eof() && peek().type() != Token::Type::RightCurly) {
  139. func->add_statement(parse_statement(func));
  140. }
  141. func->set_end(position());
  142. if (!eof())
  143. consume(Token::Type::RightCurly);
  144. return func;
  145. }
  146. NonnullRefPtr<Statement> Parser::parse_statement(ASTNode& parent)
  147. {
  148. LOG_SCOPE();
  149. ArmedScopeGuard consume_semicolon([this]() {
  150. consume(Token::Type::Semicolon);
  151. });
  152. if (match_block_statement()) {
  153. consume_semicolon.disarm();
  154. return parse_block_statement(parent);
  155. }
  156. if (match_comment()) {
  157. consume_semicolon.disarm();
  158. return parse_comment(parent);
  159. }
  160. if (match_variable_declaration()) {
  161. return parse_variable_declaration(parent, false);
  162. }
  163. if (match_expression()) {
  164. return parse_expression(parent);
  165. }
  166. if (match_keyword("return")) {
  167. return parse_return_statement(parent);
  168. }
  169. if (match_keyword("for")) {
  170. consume_semicolon.disarm();
  171. return parse_for_statement(parent);
  172. }
  173. if (match_keyword("if")) {
  174. consume_semicolon.disarm();
  175. return parse_if_statement(parent);
  176. } else {
  177. error("unexpected statement type");
  178. consume_semicolon.disarm();
  179. consume();
  180. return create_ast_node<InvalidStatement>(parent, position(), position());
  181. }
  182. }
  183. NonnullRefPtr<Comment> Parser::parse_comment(ASTNode& parent)
  184. {
  185. auto comment = create_ast_node<Comment>(parent, position(), {});
  186. consume(Token::Type::Comment);
  187. comment->set_end(position());
  188. return comment;
  189. }
  190. bool Parser::match_block_statement()
  191. {
  192. return peek().type() == Token::Type::LeftCurly;
  193. }
  194. NonnullRefPtr<BlockStatement> Parser::parse_block_statement(ASTNode& parent)
  195. {
  196. LOG_SCOPE();
  197. auto block_statement = create_ast_node<BlockStatement>(parent, position(), {});
  198. consume(Token::Type::LeftCurly);
  199. while (!eof() && peek().type() != Token::Type::RightCurly) {
  200. block_statement->add_statement(parse_statement(*block_statement));
  201. }
  202. consume(Token::Type::RightCurly);
  203. block_statement->set_end(position());
  204. return block_statement;
  205. }
  206. bool Parser::match_type()
  207. {
  208. return match_named_type();
  209. }
  210. bool Parser::match_named_type()
  211. {
  212. save_state();
  213. ScopeGuard state_guard = [this] { load_state(); };
  214. parse_type_qualifiers();
  215. if (match_keyword("auto")) {
  216. return true;
  217. }
  218. if (match_keyword("struct")) {
  219. consume(Token::Type::Keyword); // Consume struct prefix
  220. }
  221. if (!match_name())
  222. return false;
  223. return true;
  224. }
  225. bool Parser::match_template_arguments()
  226. {
  227. save_state();
  228. ScopeGuard state_guard = [this] { load_state(); };
  229. if (!peek(Token::Type::Less).has_value())
  230. return false;
  231. consume();
  232. while (!eof() && peek().type() != Token::Type::Greater) {
  233. if (!match_named_type())
  234. return false;
  235. parse_type(get_dummy_node());
  236. }
  237. return peek().type() == Token::Type::Greater;
  238. }
  239. NonnullRefPtrVector<Type> Parser::parse_template_arguments(ASTNode& parent)
  240. {
  241. LOG_SCOPE();
  242. consume(Token::Type::Less);
  243. NonnullRefPtrVector<Type> template_arguments;
  244. while (!eof() && peek().type() != Token::Type::Greater) {
  245. template_arguments.append(parse_type(parent));
  246. }
  247. consume(Token::Type::Greater);
  248. return template_arguments;
  249. }
  250. bool Parser::match_variable_declaration()
  251. {
  252. LOG_SCOPE();
  253. save_state();
  254. ScopeGuard state_guard = [this] { load_state(); };
  255. if (!match_type()) {
  256. return false;
  257. }
  258. VERIFY(m_root_node);
  259. parse_type(get_dummy_node());
  260. // Identifier
  261. if (!peek(Token::Type::Identifier).has_value()) {
  262. return false;
  263. }
  264. consume();
  265. if (match(Token::Type::Equals)) {
  266. consume(Token::Type::Equals);
  267. if (!match_expression()) {
  268. error("initial value of variable is not an expression");
  269. return false;
  270. }
  271. return true;
  272. }
  273. if (match_braced_init_list())
  274. parse_braced_init_list(get_dummy_node());
  275. return match(Token::Type::Semicolon);
  276. }
  277. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(ASTNode& parent, bool expect_semicolon)
  278. {
  279. LOG_SCOPE();
  280. auto var = create_ast_node<VariableDeclaration>(parent, position(), {});
  281. if (!match_variable_declaration()) {
  282. error("unexpected token for variable type");
  283. var->set_end(position());
  284. return var;
  285. }
  286. var->set_type(parse_type(var));
  287. auto identifier_token = consume(Token::Type::Identifier);
  288. RefPtr<Expression> initial_value;
  289. if (match(Token::Type::Equals)) {
  290. consume(Token::Type::Equals);
  291. initial_value = parse_expression(var);
  292. }
  293. if (match_braced_init_list()) {
  294. initial_value = parse_braced_init_list(var);
  295. }
  296. if (expect_semicolon)
  297. consume(Token::Type::Semicolon);
  298. var->set_end(position());
  299. var->set_name(text_of_token(identifier_token));
  300. var->set_initial_value(move(initial_value));
  301. return var;
  302. }
  303. NonnullRefPtr<Expression> Parser::parse_expression(ASTNode& parent)
  304. {
  305. LOG_SCOPE();
  306. auto expression = parse_primary_expression(parent);
  307. // TODO: remove eof() logic, should still work without it
  308. if (eof() || match(Token::Type::Semicolon)) {
  309. return expression;
  310. }
  311. NonnullRefPtrVector<Expression> secondary_expressions;
  312. while (match_secondary_expression()) {
  313. // FIXME: Handle operator precedence
  314. expression = parse_secondary_expression(parent, expression);
  315. secondary_expressions.append(expression);
  316. }
  317. for (size_t i = 0; secondary_expressions.size() != 0 && i < secondary_expressions.size() - 1; ++i) {
  318. secondary_expressions[i].set_parent(secondary_expressions[i + 1]);
  319. }
  320. return expression;
  321. }
  322. bool Parser::match_secondary_expression()
  323. {
  324. auto type = peek().type();
  325. return type == Token::Type::Plus
  326. || type == Token::Type::PlusEquals
  327. || type == Token::Type::Minus
  328. || type == Token::Type::MinusEquals
  329. || type == Token::Type::Asterisk
  330. || type == Token::Type::AsteriskEquals
  331. || type == Token::Type::Percent
  332. || type == Token::Type::PercentEquals
  333. || type == Token::Type::Equals
  334. || type == Token::Type::Greater
  335. || type == Token::Type::Greater
  336. || type == Token::Type::Less
  337. || type == Token::Type::LessEquals
  338. || type == Token::Type::Dot
  339. || type == Token::Type::PlusPlus
  340. || type == Token::Type::MinusMinus
  341. || type == Token::Type::And
  342. || type == Token::Type::AndEquals
  343. || type == Token::Type::Pipe
  344. || type == Token::Type::PipeEquals
  345. || type == Token::Type::Caret
  346. || type == Token::Type::CaretEquals
  347. || type == Token::Type::LessLess
  348. || type == Token::Type::LessLessEquals
  349. || type == Token::Type::GreaterGreater
  350. || type == Token::Type::GreaterGreaterEquals
  351. || type == Token::Type::EqualsEquals
  352. || type == Token::Type::AndAnd
  353. || type == Token::Type::PipePipe
  354. || type == Token::Type::ExclamationMarkEquals
  355. || type == Token::Type::PipePipe
  356. || type == Token::Type::Arrow
  357. || type == Token::Type::LeftParen;
  358. }
  359. NonnullRefPtr<Expression> Parser::parse_primary_expression(ASTNode& parent)
  360. {
  361. LOG_SCOPE();
  362. // TODO: remove eof() logic, should still work without it
  363. if (eof()) {
  364. auto node = create_ast_node<Identifier>(parent, position(), position());
  365. return node;
  366. }
  367. if (match_unary_expression())
  368. return parse_unary_expression(parent);
  369. if (match_literal()) {
  370. return parse_literal(parent);
  371. }
  372. if (match_cpp_cast_expression())
  373. return parse_cpp_cast_expression(parent);
  374. if (match_c_style_cast_expression())
  375. return parse_c_style_cast_expression(parent);
  376. if (match_sizeof_expression())
  377. return parse_sizeof_expression(parent);
  378. if (match_braced_init_list())
  379. return parse_braced_init_list(parent);
  380. if (match_name()) {
  381. return parse_name(parent);
  382. }
  383. error("could not parse primary expression");
  384. auto token = consume();
  385. return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
  386. }
  387. bool Parser::match_literal()
  388. {
  389. switch (peek().type()) {
  390. case Token::Type::Integer:
  391. return true;
  392. case Token::Type::SingleQuotedString:
  393. return true;
  394. case Token::Type::DoubleQuotedString:
  395. return true;
  396. case Token::Type::Float:
  397. return true;
  398. case Token::Type::Keyword: {
  399. return match_boolean_literal() || peek().text() == "nullptr";
  400. }
  401. default:
  402. return false;
  403. }
  404. }
  405. bool Parser::match_unary_expression()
  406. {
  407. auto type = peek().type();
  408. return type == Token::Type::PlusPlus
  409. || type == Token::Type::MinusMinus
  410. || type == Token::Type::ExclamationMark
  411. || type == Token::Type::Tilde
  412. || type == Token::Type::Plus
  413. || type == Token::Type::Minus
  414. || type == Token::Type::And;
  415. }
  416. NonnullRefPtr<UnaryExpression> Parser::parse_unary_expression(ASTNode& parent)
  417. {
  418. auto unary_exp = create_ast_node<UnaryExpression>(parent, position(), {});
  419. auto op_token = consume();
  420. UnaryOp op { UnaryOp::Invalid };
  421. switch (op_token.type()) {
  422. case Token::Type::Minus:
  423. op = UnaryOp::Minus;
  424. break;
  425. case Token::Type::Plus:
  426. op = UnaryOp::Plus;
  427. break;
  428. case Token::Type::ExclamationMark:
  429. op = UnaryOp::Not;
  430. break;
  431. case Token::Type::Tilde:
  432. op = UnaryOp::BitwiseNot;
  433. break;
  434. case Token::Type::PlusPlus:
  435. op = UnaryOp::PlusPlus;
  436. break;
  437. case Token::Type::And:
  438. op = UnaryOp::Address;
  439. break;
  440. default:
  441. break;
  442. }
  443. unary_exp->set_op(op);
  444. auto lhs = parse_expression(*unary_exp);
  445. unary_exp->set_lhs(lhs);
  446. unary_exp->set_end(lhs->end());
  447. return unary_exp;
  448. }
  449. NonnullRefPtr<Expression> Parser::parse_literal(ASTNode& parent)
  450. {
  451. switch (peek().type()) {
  452. case Token::Type::Integer: {
  453. auto token = consume();
  454. return create_ast_node<NumericLiteral>(parent, token.start(), token.end(), text_of_token(token));
  455. }
  456. case Token::Type::SingleQuotedString:
  457. [[fallthrough]];
  458. case Token::Type::DoubleQuotedString:
  459. return parse_string_literal(parent);
  460. case Token::Type::Keyword: {
  461. if (match_boolean_literal())
  462. return parse_boolean_literal(parent);
  463. if (peek().text() == "nullptr") {
  464. auto token = consume();
  465. return create_ast_node<NullPointerLiteral>(parent, token.start(), token.end());
  466. }
  467. [[fallthrough]];
  468. }
  469. default: {
  470. error("could not parse literal");
  471. auto token = consume();
  472. return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
  473. }
  474. }
  475. }
  476. NonnullRefPtr<Expression> Parser::parse_secondary_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs)
  477. {
  478. LOG_SCOPE();
  479. switch (peek().type()) {
  480. case Token::Type::Plus:
  481. return parse_binary_expression(parent, lhs, BinaryOp::Addition);
  482. case Token::Type::Less:
  483. return parse_binary_expression(parent, lhs, BinaryOp::LessThan);
  484. case Token::Type::EqualsEquals:
  485. return parse_binary_expression(parent, lhs, BinaryOp::EqualsEquals);
  486. case Token::Type::ExclamationMarkEquals:
  487. return parse_binary_expression(parent, lhs, BinaryOp::NotEqual);
  488. case Token::Type::And:
  489. return parse_binary_expression(parent, lhs, BinaryOp::BitwiseAnd);
  490. case Token::Type::AndAnd:
  491. return parse_binary_expression(parent, lhs, BinaryOp::LogicalAnd);
  492. case Token::Type::Pipe:
  493. return parse_binary_expression(parent, lhs, BinaryOp::BitwiseOr);
  494. case Token::Type::PipePipe:
  495. return parse_binary_expression(parent, lhs, BinaryOp::LogicalOr);
  496. case Token::Type::Arrow:
  497. return parse_binary_expression(parent, lhs, BinaryOp::Arrow);
  498. case Token::Type::Equals:
  499. return parse_assignment_expression(parent, lhs, AssignmentOp::Assignment);
  500. case Token::Type::Dot: {
  501. consume();
  502. auto exp = create_ast_node<MemberExpression>(parent, lhs->start(), {});
  503. lhs->set_parent(*exp);
  504. exp->set_object(move(lhs));
  505. auto identifier_token = consume(Token::Type::Identifier);
  506. exp->set_property(create_ast_node<Identifier>(*exp, identifier_token.start(), identifier_token.end(), identifier_token.text()));
  507. exp->set_end(position());
  508. return exp;
  509. }
  510. case Token::Type::LeftParen: {
  511. consume();
  512. auto func = create_ast_node<FunctionCall>(parent, lhs->start(), {});
  513. lhs->set_parent(*func);
  514. func->set_callee(move(lhs));
  515. while (peek().type() != Token::Type::RightParen && !eof()) {
  516. func->add_argument(parse_expression(*func));
  517. if (peek().type() == Token::Type::Comma)
  518. consume(Token::Type::Comma);
  519. }
  520. consume(Token::Type::RightParen);
  521. func->set_end(position());
  522. return func;
  523. }
  524. default: {
  525. error(String::formatted("unexpected operator for expression. operator: {}", peek().to_string()));
  526. auto token = consume();
  527. return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
  528. }
  529. }
  530. }
  531. NonnullRefPtr<BinaryExpression> Parser::parse_binary_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs, BinaryOp op)
  532. {
  533. consume(); // Operator
  534. auto exp = create_ast_node<BinaryExpression>(parent, lhs->start(), {});
  535. lhs->set_parent(*exp);
  536. exp->set_op(op);
  537. exp->set_lhs(move(lhs));
  538. auto rhs = parse_expression(exp);
  539. exp->set_end(rhs->end());
  540. exp->set_rhs(move(rhs));
  541. return exp;
  542. }
  543. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs, AssignmentOp op)
  544. {
  545. consume(); // Operator
  546. auto exp = create_ast_node<AssignmentExpression>(parent, lhs->start(), {});
  547. lhs->set_parent(*exp);
  548. exp->set_op(op);
  549. exp->set_lhs(move(lhs));
  550. auto rhs = parse_expression(exp);
  551. exp->set_end(rhs->end());
  552. exp->set_rhs(move(rhs));
  553. return exp;
  554. }
  555. Optional<Parser::DeclarationType> Parser::match_declaration_in_translation_unit()
  556. {
  557. if (match_function_declaration())
  558. return DeclarationType::Function;
  559. if (match_enum_declaration())
  560. return DeclarationType::Enum;
  561. if (match_class_declaration())
  562. return DeclarationType::Class;
  563. if (match_namespace_declaration())
  564. return DeclarationType::Namespace;
  565. if (match_variable_declaration())
  566. return DeclarationType::Variable;
  567. return {};
  568. }
  569. Optional<Parser::DeclarationType> Parser::match_class_member(const StringView& class_name)
  570. {
  571. if (match_function_declaration())
  572. return DeclarationType::Function;
  573. if (match_enum_declaration())
  574. return DeclarationType::Enum;
  575. if (match_class_declaration())
  576. return DeclarationType::Class;
  577. if (match_variable_declaration())
  578. return DeclarationType::Variable;
  579. if (match_constructor(class_name))
  580. return DeclarationType::Constructor;
  581. if (match_destructor(class_name))
  582. return DeclarationType::Destructor;
  583. return {};
  584. }
  585. bool Parser::match_enum_declaration()
  586. {
  587. save_state();
  588. ScopeGuard state_guard = [this] { load_state(); };
  589. if (!match_keyword("enum"))
  590. return false;
  591. consume(Token::Type::Keyword);
  592. if (match_keyword("class"))
  593. consume(Token::Type::Keyword);
  594. if (!match(Token::Type::Identifier))
  595. return false;
  596. consume(Token::Type::Identifier);
  597. return match(Token::Type::LeftCurly);
  598. }
  599. bool Parser::match_class_declaration()
  600. {
  601. save_state();
  602. ScopeGuard state_guard = [this] { load_state(); };
  603. if (!match_keyword("struct") && !match_keyword("class"))
  604. return false;
  605. consume(Token::Type::Keyword);
  606. if (!match(Token::Type::Identifier))
  607. return false;
  608. consume(Token::Type::Identifier);
  609. return match(Token::Type::LeftCurly);
  610. }
  611. bool Parser::match_namespace_declaration()
  612. {
  613. return match_keyword("namespace");
  614. }
  615. bool Parser::match_function_declaration()
  616. {
  617. save_state();
  618. ScopeGuard state_guard = [this] { load_state(); };
  619. parse_function_qualifiers();
  620. if (!match_type())
  621. return false;
  622. VERIFY(m_root_node);
  623. parse_type(get_dummy_node());
  624. if (!peek(Token::Type::Identifier).has_value())
  625. return false;
  626. consume();
  627. if (!peek(Token::Type::LeftParen).has_value())
  628. return false;
  629. consume();
  630. while (consume().type() != Token::Type::RightParen && !eof()) { };
  631. if (peek(Token::Type::Semicolon).has_value() || peek(Token::Type::LeftCurly).has_value())
  632. return true;
  633. if (match_attribute_specification()) {
  634. consume_attribute_specification();
  635. return peek(Token::Type::Semicolon).has_value();
  636. }
  637. return false;
  638. }
  639. Optional<NonnullRefPtrVector<Parameter>> Parser::parse_parameter_list(ASTNode& parent)
  640. {
  641. LOG_SCOPE();
  642. NonnullRefPtrVector<Parameter> parameters;
  643. while (peek().type() != Token::Type::RightParen && !eof()) {
  644. if (match_ellipsis()) {
  645. auto param = create_ast_node<Parameter>(parent, position(), {}, StringView {});
  646. consume(Token::Type::Dot);
  647. consume(Token::Type::Dot);
  648. auto last_dot = consume(Token::Type::Dot);
  649. param->set_ellipsis(true);
  650. param->set_end(last_dot.end());
  651. parameters.append(move(param));
  652. } else {
  653. auto type = parse_type(parent);
  654. auto name_identifier = peek(Token::Type::Identifier);
  655. if (name_identifier.has_value())
  656. consume(Token::Type::Identifier);
  657. StringView name;
  658. if (name_identifier.has_value())
  659. name = text_of_token(name_identifier.value());
  660. auto param = create_ast_node<Parameter>(parent, type->start(), name_identifier.has_value() ? name_identifier.value().end() : type->end(), name);
  661. param->set_type(move(type));
  662. parameters.append(move(param));
  663. }
  664. if (peek(Token::Type::Comma).has_value())
  665. consume(Token::Type::Comma);
  666. }
  667. return parameters;
  668. }
  669. bool Parser::match_comment()
  670. {
  671. return match(Token::Type::Comment);
  672. }
  673. bool Parser::match_whitespace()
  674. {
  675. return match(Token::Type::Whitespace);
  676. }
  677. bool Parser::match_preprocessor()
  678. {
  679. return match(Token::Type::PreprocessorStatement) || match(Token::Type::IncludeStatement);
  680. }
  681. void Parser::consume_preprocessor()
  682. {
  683. LOG_SCOPE();
  684. switch (peek().type()) {
  685. case Token::Type::PreprocessorStatement:
  686. consume();
  687. break;
  688. case Token::Type::IncludeStatement:
  689. consume();
  690. consume(Token::Type::IncludePath);
  691. break;
  692. default:
  693. error("unexpected token while parsing preprocessor statement");
  694. consume();
  695. }
  696. }
  697. Optional<Token> Parser::consume_whitespace()
  698. {
  699. LOG_SCOPE();
  700. return consume(Token::Type::Whitespace);
  701. }
  702. Token Parser::consume(Token::Type type)
  703. {
  704. auto token = consume();
  705. if (token.type() != type)
  706. error(String::formatted("expected {} at {}:{}, found: {}", Token::type_to_string(type), token.start().line, token.start().column, Token::type_to_string(token.type())));
  707. return token;
  708. }
  709. bool Parser::match(Token::Type type)
  710. {
  711. return peek().type() == type;
  712. }
  713. Token Parser::consume()
  714. {
  715. if (eof()) {
  716. error("C++ Parser: out of tokens");
  717. return { Token::Type::EOF_TOKEN, position(), position(), {} };
  718. }
  719. return m_tokens[m_state.token_index++];
  720. }
  721. Token Parser::peek(size_t offset) const
  722. {
  723. if (m_state.token_index + offset >= m_tokens.size())
  724. return { Token::Type::EOF_TOKEN, position(), position(), {} };
  725. return m_tokens[m_state.token_index + offset];
  726. }
  727. Optional<Token> Parser::peek(Token::Type type) const
  728. {
  729. auto token = peek();
  730. if (token.type() == type)
  731. return token;
  732. return {};
  733. }
  734. void Parser::save_state()
  735. {
  736. m_saved_states.append(m_state);
  737. }
  738. void Parser::load_state()
  739. {
  740. m_state = m_saved_states.take_last();
  741. }
  742. StringView Parser::text_of_token(const Cpp::Token& token) const
  743. {
  744. return token.text();
  745. }
  746. String Parser::text_of_node(const ASTNode& node) const
  747. {
  748. return text_in_range(node.start(), node.end());
  749. }
  750. String Parser::text_in_range(Position start, Position end) const
  751. {
  752. StringBuilder builder;
  753. for (auto token : tokens_in_range(start, end)) {
  754. builder.append(token.text());
  755. }
  756. return builder.to_string();
  757. }
  758. Vector<Token> Parser::tokens_in_range(Position start, Position end) const
  759. {
  760. auto start_token_index = index_of_token_at(start);
  761. auto end_node_index = index_of_token_at(end);
  762. VERIFY(start_token_index.has_value());
  763. VERIFY(end_node_index.has_value());
  764. Vector<Token> tokens;
  765. for (size_t i = start_token_index.value(); i <= end_node_index.value(); ++i) {
  766. tokens.append(m_tokens[i]);
  767. }
  768. return tokens;
  769. }
  770. void Parser::error(StringView message)
  771. {
  772. LOG_SCOPE();
  773. if (message.is_null() || message.is_empty())
  774. message = "<empty>";
  775. String formatted_message;
  776. if (m_state.token_index >= m_tokens.size()) {
  777. formatted_message = String::formatted("C++ Parsed error on EOF.{}", message);
  778. } else {
  779. formatted_message = String::formatted("C++ Parser error: {}. token: {} ({}:{})",
  780. message,
  781. m_state.token_index < m_tokens.size() ? text_of_token(m_tokens[m_state.token_index]) : "EOF",
  782. m_tokens[m_state.token_index].start().line,
  783. m_tokens[m_state.token_index].start().column);
  784. }
  785. m_state.errors.append(formatted_message);
  786. }
  787. bool Parser::match_expression()
  788. {
  789. return match_literal()
  790. || match_name()
  791. || match_unary_expression()
  792. || match_cpp_cast_expression()
  793. || match_c_style_cast_expression()
  794. || match_sizeof_expression()
  795. || match_braced_init_list();
  796. }
  797. bool Parser::eof() const
  798. {
  799. return m_state.token_index >= m_tokens.size();
  800. }
  801. Position Parser::position() const
  802. {
  803. if (m_tokens.is_empty())
  804. return {};
  805. if (eof())
  806. return m_tokens.last().end();
  807. return peek().start();
  808. }
  809. RefPtr<ASTNode> Parser::eof_node() const
  810. {
  811. VERIFY(m_tokens.size());
  812. return node_at(m_tokens.last().end());
  813. }
  814. RefPtr<ASTNode> Parser::node_at(Position pos) const
  815. {
  816. auto index = index_of_node_at(pos);
  817. if (!index.has_value())
  818. return nullptr;
  819. return m_state.nodes[index.value()];
  820. }
  821. Optional<size_t> Parser::index_of_node_at(Position pos) const
  822. {
  823. VERIFY(!m_tokens.is_empty());
  824. Optional<size_t> match_node_index;
  825. auto node_span = [](const ASTNode& node) {
  826. VERIFY(node.end().line >= node.start().line);
  827. VERIFY((node.end().line > node.start().line) || (node.end().column >= node.start().column));
  828. return Position { node.end().line - node.start().line, node.start().line != node.end().line ? 0 : node.end().column - node.start().column };
  829. };
  830. for (size_t node_index = 0; node_index < m_state.nodes.size(); ++node_index) {
  831. auto& node = m_state.nodes[node_index];
  832. if (node.start() > pos || node.end() < pos)
  833. continue;
  834. if (!match_node_index.has_value() || (node_span(node) <= node_span(m_state.nodes[match_node_index.value()])))
  835. match_node_index = node_index;
  836. }
  837. return match_node_index;
  838. }
  839. Optional<Token> Parser::token_at(Position pos) const
  840. {
  841. auto index = index_of_token_at(pos);
  842. if (!index.has_value())
  843. return {};
  844. return m_tokens[index.value()];
  845. }
  846. Optional<size_t> Parser::index_of_token_at(Position pos) const
  847. {
  848. for (size_t token_index = 0; token_index < m_tokens.size(); ++token_index) {
  849. auto token = m_tokens[token_index];
  850. if (token.start() > pos || token.end() < pos)
  851. continue;
  852. return token_index;
  853. }
  854. return {};
  855. }
  856. void Parser::print_tokens() const
  857. {
  858. for (auto& token : m_tokens) {
  859. outln("{}", token.to_string());
  860. }
  861. }
  862. Vector<Parser::TodoEntry> Parser::get_todo_entries() const
  863. {
  864. Vector<TodoEntry> ret;
  865. for (auto& token : m_tokens) {
  866. if (token.type() == Token::Type::Comment) {
  867. if (token.text().contains("TODO")) {
  868. ret.append({ token.text(), m_filename, token.start().line, token.start().column });
  869. }
  870. }
  871. }
  872. return ret;
  873. }
  874. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(ASTNode& parent)
  875. {
  876. LOG_SCOPE();
  877. Optional<size_t> start_token_index;
  878. Optional<size_t> end_token_index;
  879. while (!eof()) {
  880. auto token = peek();
  881. if (token.type() != Token::Type::DoubleQuotedString && token.type() != Token::Type::SingleQuotedString && token.type() != Token::Type::EscapeSequence) {
  882. VERIFY(start_token_index.has_value());
  883. end_token_index = m_state.token_index - 1;
  884. break;
  885. }
  886. if (!start_token_index.has_value())
  887. start_token_index = m_state.token_index;
  888. consume();
  889. }
  890. // String was not terminated
  891. if (!end_token_index.has_value()) {
  892. end_token_index = m_tokens.size() - 1;
  893. }
  894. VERIFY(start_token_index.has_value());
  895. VERIFY(end_token_index.has_value());
  896. Token start_token = m_tokens[start_token_index.value()];
  897. Token end_token = m_tokens[end_token_index.value()];
  898. auto text = text_in_range(start_token.start(), end_token.end());
  899. auto string_literal = create_ast_node<StringLiteral>(parent, start_token.start(), end_token.end());
  900. string_literal->set_value(move(text));
  901. return string_literal;
  902. }
  903. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement(ASTNode& parent)
  904. {
  905. LOG_SCOPE();
  906. auto return_statement = create_ast_node<ReturnStatement>(parent, position(), {});
  907. consume(Token::Type::Keyword);
  908. if (!peek(Token::Type::Semicolon).has_value()) {
  909. return_statement->set_value(parse_expression(*return_statement));
  910. }
  911. return_statement->set_end(position());
  912. return return_statement;
  913. }
  914. NonnullRefPtr<EnumDeclaration> Parser::parse_enum_declaration(ASTNode& parent)
  915. {
  916. LOG_SCOPE();
  917. auto enum_decl = create_ast_node<EnumDeclaration>(parent, position(), {});
  918. consume_keyword("enum");
  919. if (match_keyword("class")) {
  920. consume(Token::Type::Keyword);
  921. enum_decl->set_type(EnumDeclaration::Type::EnumClass);
  922. } else {
  923. enum_decl->set_type(EnumDeclaration::Type::RegularEnum);
  924. }
  925. auto name_token = consume(Token::Type::Identifier);
  926. enum_decl->set_name(text_of_token(name_token));
  927. consume(Token::Type::LeftCurly);
  928. while (!eof() && peek().type() != Token::Type::RightCurly) {
  929. enum_decl->add_entry(text_of_token(consume(Token::Type::Identifier)));
  930. if (peek().type() != Token::Type::Comma) {
  931. break;
  932. }
  933. consume(Token::Type::Comma);
  934. }
  935. consume(Token::Type::RightCurly);
  936. consume(Token::Type::Semicolon);
  937. enum_decl->set_end(position());
  938. return enum_decl;
  939. }
  940. Token Parser::consume_keyword(const String& keyword)
  941. {
  942. auto token = consume();
  943. if (token.type() != Token::Type::Keyword) {
  944. error(String::formatted("unexpected token: {}, expected Keyword", token.to_string()));
  945. return token;
  946. }
  947. if (text_of_token(token) != keyword) {
  948. error(String::formatted("unexpected keyword: {}, expected {}", text_of_token(token), keyword));
  949. return token;
  950. }
  951. return token;
  952. }
  953. bool Parser::match_keyword(const String& keyword)
  954. {
  955. auto token = peek();
  956. if (token.type() != Token::Type::Keyword) {
  957. return false;
  958. }
  959. if (text_of_token(token) != keyword) {
  960. return false;
  961. }
  962. return true;
  963. }
  964. NonnullRefPtr<StructOrClassDeclaration> Parser::parse_class_declaration(ASTNode& parent)
  965. {
  966. LOG_SCOPE();
  967. auto type_token = consume(Token::Type::Keyword);
  968. StructOrClassDeclaration::Type type {};
  969. if (type_token.text() == "struct")
  970. type = StructOrClassDeclaration::Type::Struct;
  971. if (type_token.text() == "class")
  972. type = StructOrClassDeclaration::Type::Class;
  973. auto decl = create_ast_node<StructOrClassDeclaration>(parent, position(), {}, type);
  974. auto name_token = consume(Token::Type::Identifier);
  975. decl->set_name(text_of_token(name_token));
  976. consume(Token::Type::LeftCurly);
  977. while (!eof() && peek().type() != Token::Type::RightCurly) {
  978. decl->set_members(parse_class_members(*decl));
  979. }
  980. consume(Token::Type::RightCurly);
  981. consume(Token::Type::Semicolon);
  982. decl->set_end(position());
  983. return decl;
  984. }
  985. NonnullRefPtr<BooleanLiteral> Parser::parse_boolean_literal(ASTNode& parent)
  986. {
  987. LOG_SCOPE();
  988. auto token = consume(Token::Type::Keyword);
  989. auto text = text_of_token(token);
  990. // text == "true" || text == "false";
  991. bool value = (text == "true");
  992. return create_ast_node<BooleanLiteral>(parent, token.start(), token.end(), value);
  993. }
  994. bool Parser::match_boolean_literal()
  995. {
  996. auto token = peek();
  997. if (token.type() != Token::Type::Keyword)
  998. return false;
  999. auto text = text_of_token(token);
  1000. return text == "true" || text == "false";
  1001. }
  1002. NonnullRefPtr<Type> Parser::parse_type(ASTNode& parent)
  1003. {
  1004. LOG_SCOPE();
  1005. if (!match_named_type()) {
  1006. error("expected named named_type");
  1007. auto token = consume();
  1008. return create_ast_node<NamedType>(parent, token.start(), token.end());
  1009. }
  1010. auto named_type = create_ast_node<NamedType>(parent, position(), {});
  1011. auto qualifiers = parse_type_qualifiers();
  1012. named_type->set_qualifiers(move(qualifiers));
  1013. if (match_keyword("auto")) {
  1014. consume(Token::Type::Keyword);
  1015. named_type->set_auto(true);
  1016. named_type->set_end(position());
  1017. return named_type;
  1018. }
  1019. if (match_keyword("struct")) {
  1020. consume(Token::Type::Keyword); // Consume struct prefix
  1021. }
  1022. if (!match_name()) {
  1023. named_type->set_end(position());
  1024. error(String::formatted("expected name instead of: {}", peek().text()));
  1025. return named_type;
  1026. }
  1027. named_type->set_name(parse_name(*named_type));
  1028. NonnullRefPtr<Type> type = named_type;
  1029. while (!eof() && peek().type() == Token::Type::Asterisk) {
  1030. type->set_end(position());
  1031. auto asterisk = consume();
  1032. auto ptr = create_ast_node<Pointer>(parent, type->start(), asterisk.end());
  1033. type->set_parent(*ptr);
  1034. ptr->set_pointee(type);
  1035. ptr->set_end(position());
  1036. type = ptr;
  1037. }
  1038. type->set_end(position());
  1039. return type;
  1040. }
  1041. NonnullRefPtr<ForStatement> Parser::parse_for_statement(ASTNode& parent)
  1042. {
  1043. LOG_SCOPE();
  1044. auto for_statement = create_ast_node<ForStatement>(parent, position(), {});
  1045. consume(Token::Type::Keyword);
  1046. consume(Token::Type::LeftParen);
  1047. if (peek().type() != Token::Type::Semicolon)
  1048. for_statement->set_init(parse_variable_declaration(*for_statement, false));
  1049. consume(Token::Type::Semicolon);
  1050. if (peek().type() != Token::Type::Semicolon)
  1051. for_statement->set_test(parse_expression(*for_statement));
  1052. consume(Token::Type::Semicolon);
  1053. if (peek().type() != Token::Type::RightParen)
  1054. for_statement->set_update(parse_expression(*for_statement));
  1055. consume(Token::Type::RightParen);
  1056. for_statement->set_body(parse_statement(*for_statement));
  1057. for_statement->set_end(for_statement->body()->end());
  1058. return for_statement;
  1059. }
  1060. NonnullRefPtr<IfStatement> Parser::parse_if_statement(ASTNode& parent)
  1061. {
  1062. LOG_SCOPE();
  1063. auto if_statement = create_ast_node<IfStatement>(parent, position(), {});
  1064. consume(Token::Type::Keyword);
  1065. consume(Token::Type::LeftParen);
  1066. if_statement->set_predicate(parse_expression(*if_statement));
  1067. consume(Token::Type::RightParen);
  1068. if_statement->set_then_statement(parse_statement(*if_statement));
  1069. if (match_keyword("else")) {
  1070. consume(Token::Type::Keyword);
  1071. if_statement->set_else_statement(parse_statement(*if_statement));
  1072. if_statement->set_end(if_statement->else_statement()->end());
  1073. } else {
  1074. if_statement->set_end(if_statement->then_statement()->end());
  1075. }
  1076. return if_statement;
  1077. }
  1078. Vector<StringView> Parser::parse_type_qualifiers()
  1079. {
  1080. LOG_SCOPE();
  1081. Vector<StringView> qualifiers;
  1082. while (!eof()) {
  1083. auto token = peek();
  1084. if (token.type() != Token::Type::Keyword)
  1085. break;
  1086. auto text = text_of_token(token);
  1087. if (text == "static" || text == "const") {
  1088. qualifiers.append(text);
  1089. consume();
  1090. } else {
  1091. break;
  1092. }
  1093. }
  1094. return qualifiers;
  1095. }
  1096. Vector<StringView> Parser::parse_function_qualifiers()
  1097. {
  1098. LOG_SCOPE();
  1099. Vector<StringView> qualifiers;
  1100. while (!eof()) {
  1101. auto token = peek();
  1102. if (token.type() != Token::Type::Keyword)
  1103. break;
  1104. auto text = text_of_token(token);
  1105. if (text == "static" || text == "inline") {
  1106. qualifiers.append(text);
  1107. consume();
  1108. } else {
  1109. break;
  1110. }
  1111. }
  1112. return qualifiers;
  1113. }
  1114. bool Parser::match_attribute_specification()
  1115. {
  1116. return text_of_token(peek()) == "__attribute__";
  1117. }
  1118. void Parser::consume_attribute_specification()
  1119. {
  1120. consume(); // __attribute__
  1121. consume(Token::Type::LeftParen);
  1122. size_t left_count = 1;
  1123. while (!eof()) {
  1124. auto token = consume();
  1125. if (token.type() == Token::Type::LeftParen) {
  1126. ++left_count;
  1127. }
  1128. if (token.type() == Token::Type::RightParen) {
  1129. --left_count;
  1130. }
  1131. if (left_count == 0)
  1132. return;
  1133. }
  1134. }
  1135. bool Parser::match_ellipsis()
  1136. {
  1137. if (m_state.token_index > m_tokens.size() - 3)
  1138. return false;
  1139. return peek().type() == Token::Type::Dot && peek(1).type() == Token::Type::Dot && peek(2).type() == Token::Type::Dot;
  1140. }
  1141. void Parser::add_tokens_for_preprocessor(Token& replaced_token, Preprocessor::DefinedValue& definition)
  1142. {
  1143. if (!definition.value.has_value())
  1144. return;
  1145. Lexer lexer(definition.value.value());
  1146. for (auto token : lexer.lex()) {
  1147. if (token.type() == Token::Type::Whitespace)
  1148. continue;
  1149. token.set_start(replaced_token.start());
  1150. token.set_end(replaced_token.end());
  1151. m_tokens.append(move(token));
  1152. }
  1153. }
  1154. NonnullRefPtr<NamespaceDeclaration> Parser::parse_namespace_declaration(ASTNode& parent, bool is_nested_namespace)
  1155. {
  1156. auto namespace_decl = create_ast_node<NamespaceDeclaration>(parent, position(), {});
  1157. if (!is_nested_namespace)
  1158. consume(Token::Type::Keyword);
  1159. auto name_token = consume(Token::Type::Identifier);
  1160. namespace_decl->set_name(name_token.text());
  1161. if (peek().type() == Token::Type::ColonColon) {
  1162. consume(Token::Type::ColonColon);
  1163. namespace_decl->add_declaration(parse_namespace_declaration(*namespace_decl, true));
  1164. namespace_decl->set_end(position());
  1165. return namespace_decl;
  1166. }
  1167. consume(Token::Type::LeftCurly);
  1168. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1169. auto declaration = parse_single_declaration_in_translation_unit(*namespace_decl);
  1170. if (declaration) {
  1171. namespace_decl->add_declaration(declaration.release_nonnull());
  1172. } else {
  1173. error("unexpected token");
  1174. consume();
  1175. }
  1176. }
  1177. consume(Token::Type::RightCurly);
  1178. namespace_decl->set_end(position());
  1179. return namespace_decl;
  1180. }
  1181. bool Parser::match_name()
  1182. {
  1183. auto type = peek().type();
  1184. return type == Token::Type::Identifier || type == Token::Type::KnownType;
  1185. }
  1186. NonnullRefPtr<Name> Parser::parse_name(ASTNode& parent)
  1187. {
  1188. LOG_SCOPE();
  1189. NonnullRefPtr<Name> name_node = create_ast_node<Name>(parent, position(), {});
  1190. while (!eof() && (peek().type() == Token::Type::Identifier || peek().type() == Token::Type::KnownType) && peek(1).type() == Token::Type::ColonColon) {
  1191. auto token = consume();
  1192. name_node->add_to_scope(create_ast_node<Identifier>(*name_node, token.start(), token.end(), token.text()));
  1193. consume(Token::Type::ColonColon);
  1194. }
  1195. if (peek().type() == Token::Type::Identifier || peek().type() == Token::Type::KnownType) {
  1196. auto token = consume();
  1197. name_node->set_name(create_ast_node<Identifier>(*name_node, token.start(), token.end(), token.text()));
  1198. } else {
  1199. name_node->set_end(position());
  1200. return name_node;
  1201. }
  1202. if (match_template_arguments()) {
  1203. consume(Token::Type::Less);
  1204. NonnullRefPtr<TemplatizedName> templatized_name = create_ast_node<TemplatizedName>(parent, name_node->start(), {});
  1205. templatized_name->set_name(name_node->name());
  1206. templatized_name->set_scope(name_node->scope());
  1207. name_node->set_end(position());
  1208. name_node = templatized_name;
  1209. while (peek().type() != Token::Type::Greater && !eof()) {
  1210. templatized_name->add_template_argument(parse_type(*templatized_name));
  1211. if (peek().type() == Token::Type::Comma)
  1212. consume(Token::Type::Comma);
  1213. }
  1214. consume(Token::Type::Greater);
  1215. }
  1216. name_node->set_end(position());
  1217. return name_node;
  1218. }
  1219. bool Parser::match_cpp_cast_expression()
  1220. {
  1221. save_state();
  1222. ScopeGuard state_guard = [this] { load_state(); };
  1223. auto token = consume();
  1224. if (token.type() != Token::Type::Keyword)
  1225. return false;
  1226. auto text = token.text();
  1227. if (text == "static_cast" || text == "reinterpret_cast" || text == "dynamic_cast" || text == "const_cast")
  1228. return true;
  1229. return false;
  1230. }
  1231. bool Parser::match_c_style_cast_expression()
  1232. {
  1233. save_state();
  1234. ScopeGuard state_guard = [this] { load_state(); };
  1235. if (consume().type() != Token::Type::LeftParen)
  1236. return false;
  1237. if (!match_type())
  1238. return false;
  1239. parse_type(get_dummy_node());
  1240. if (consume().type() != Token::Type::RightParen)
  1241. return false;
  1242. if (!match_expression())
  1243. return false;
  1244. return true;
  1245. }
  1246. NonnullRefPtr<CStyleCastExpression> Parser::parse_c_style_cast_expression(ASTNode& parent)
  1247. {
  1248. auto parse_exp = create_ast_node<CStyleCastExpression>(parent, position(), {});
  1249. consume(Token::Type::LeftParen);
  1250. parse_exp->set_type(parse_type(*parse_exp));
  1251. consume(Token::Type::RightParen);
  1252. parse_exp->set_expression(parse_expression(*parse_exp));
  1253. parse_exp->set_end(position());
  1254. return parse_exp;
  1255. }
  1256. NonnullRefPtr<CppCastExpression> Parser::parse_cpp_cast_expression(ASTNode& parent)
  1257. {
  1258. auto cast_expression = create_ast_node<CppCastExpression>(parent, position(), {});
  1259. cast_expression->set_cast_type(consume(Token::Type::Keyword).text());
  1260. consume(Token::Type::Less);
  1261. cast_expression->set_type(parse_type(*cast_expression));
  1262. consume(Token::Type::Greater);
  1263. consume(Token::Type::LeftParen);
  1264. cast_expression->set_expression(parse_expression(*cast_expression));
  1265. consume(Token::Type::RightParen);
  1266. cast_expression->set_end(position());
  1267. return cast_expression;
  1268. }
  1269. bool Parser::match_sizeof_expression()
  1270. {
  1271. return match_keyword("sizeof");
  1272. }
  1273. NonnullRefPtr<SizeofExpression> Parser::parse_sizeof_expression(ASTNode& parent)
  1274. {
  1275. auto exp = create_ast_node<SizeofExpression>(parent, position(), {});
  1276. consume(Token::Type::Keyword);
  1277. consume(Token::Type::LeftParen);
  1278. exp->set_type(parse_type(parent));
  1279. consume(Token::Type::RightParen);
  1280. exp->set_end(position());
  1281. return exp;
  1282. }
  1283. bool Parser::match_braced_init_list()
  1284. {
  1285. return match(Token::Type::LeftCurly);
  1286. }
  1287. NonnullRefPtr<BracedInitList> Parser::parse_braced_init_list(ASTNode& parent)
  1288. {
  1289. auto init_list = create_ast_node<BracedInitList>(parent, position(), {});
  1290. consume(Token::Type::LeftCurly);
  1291. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1292. init_list->add_expression(parse_expression(*init_list));
  1293. }
  1294. consume(Token::Type::RightCurly);
  1295. init_list->set_end(position());
  1296. return init_list;
  1297. }
  1298. NonnullRefPtrVector<Declaration> Parser::parse_class_members(StructOrClassDeclaration& parent)
  1299. {
  1300. auto& class_name = parent.name();
  1301. NonnullRefPtrVector<Declaration> members;
  1302. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1303. if (match_access_specifier())
  1304. consume_access_specifier(); // FIXME: Do not ignore access specifiers
  1305. auto member_type = match_class_member(class_name);
  1306. if (member_type.has_value()) {
  1307. members.append(parse_declaration(parent, member_type.value()));
  1308. } else {
  1309. error("Expected class member");
  1310. consume();
  1311. }
  1312. }
  1313. return members;
  1314. }
  1315. bool Parser::match_access_specifier()
  1316. {
  1317. if (peek(1).type() != Token::Type::Colon)
  1318. return false;
  1319. return match_keyword("private") || match_keyword("protected") || match_keyword("public");
  1320. }
  1321. void Parser::consume_access_specifier()
  1322. {
  1323. consume(Token::Type::Keyword);
  1324. consume(Token::Type::Colon);
  1325. }
  1326. bool Parser::match_constructor(const StringView& class_name)
  1327. {
  1328. save_state();
  1329. ScopeGuard state_guard = [this] { load_state(); };
  1330. auto token = consume();
  1331. if (token.text() != class_name)
  1332. return false;
  1333. if (!peek(Token::Type::LeftParen).has_value())
  1334. return false;
  1335. consume();
  1336. while (consume().type() != Token::Type::RightParen && !eof()) { };
  1337. return (peek(Token::Type::Semicolon).has_value() || peek(Token::Type::LeftCurly).has_value());
  1338. }
  1339. bool Parser::match_destructor(const StringView& class_name)
  1340. {
  1341. save_state();
  1342. ScopeGuard state_guard = [this] { load_state(); };
  1343. if (!match(Token::Type::Tilde))
  1344. return false;
  1345. consume();
  1346. auto token = peek();
  1347. if (token.text() != class_name)
  1348. return false;
  1349. consume();
  1350. if (!peek(Token::Type::LeftParen).has_value())
  1351. return false;
  1352. consume();
  1353. while (consume().type() != Token::Type::RightParen && !eof()) { };
  1354. return (peek(Token::Type::Semicolon).has_value() || peek(Token::Type::LeftCurly).has_value());
  1355. }
  1356. void Parser::parse_constructor_or_destructor_impl(FunctionDeclaration& func, CtorOrDtor type)
  1357. {
  1358. if (type == CtorOrDtor::Dtor)
  1359. consume(Token::Type::Tilde);
  1360. auto name_token = consume();
  1361. if (name_token.type() != Token::Type::Identifier && name_token.type() != Token::Type::KnownType) {
  1362. error("Unexpected constructor name");
  1363. }
  1364. func.set_name(name_token.text());
  1365. consume(Token::Type::LeftParen);
  1366. auto parameters = parse_parameter_list(func);
  1367. if (parameters.has_value()) {
  1368. if (type == CtorOrDtor::Dtor && !parameters->is_empty())
  1369. error("Destructor declaration that takes parameters");
  1370. else
  1371. func.set_parameters(parameters.value());
  1372. }
  1373. consume(Token::Type::RightParen);
  1374. // TODO: Parse =default, =delete.
  1375. RefPtr<FunctionDefinition> body;
  1376. Position ctor_end {};
  1377. if (peek(Token::Type::LeftCurly).has_value()) {
  1378. body = parse_function_definition(func);
  1379. ctor_end = body->end();
  1380. } else {
  1381. ctor_end = position();
  1382. if (match_attribute_specification())
  1383. consume_attribute_specification(); // we don't use the value of __attribute__
  1384. consume(Token::Type::Semicolon);
  1385. }
  1386. func.set_definition(move(body));
  1387. func.set_end(ctor_end);
  1388. }
  1389. NonnullRefPtr<Constructor> Parser::parse_constructor(ASTNode& parent)
  1390. {
  1391. auto ctor = create_ast_node<Constructor>(parent, position(), {});
  1392. parse_constructor_or_destructor_impl(*ctor, CtorOrDtor::Ctor);
  1393. return ctor;
  1394. }
  1395. NonnullRefPtr<Destructor> Parser::parse_destructor(ASTNode& parent)
  1396. {
  1397. auto ctor = create_ast_node<Destructor>(parent, position(), {});
  1398. parse_constructor_or_destructor_impl(*ctor, CtorOrDtor::Dtor);
  1399. return ctor;
  1400. }
  1401. }