Parser.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  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->m_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->m_qualifiers = parse_function_qualifiers();
  110. func->m_return_type = parse_type(*func);
  111. auto function_name = consume(Token::Type::Identifier);
  112. func->m_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->m_parameters = move(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->m_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->statements().append(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->m_statements.append(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->m_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->m_name = text_of_token(identifier_token);
  300. var->m_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->m_op = op;
  444. auto lhs = parse_expression(*unary_exp);
  445. unary_exp->m_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->m_object = move(lhs);
  505. auto identifier_token = consume(Token::Type::Identifier);
  506. exp->m_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->m_callee = lhs;
  515. while (peek().type() != Token::Type::RightParen && !eof()) {
  516. func->m_arguments.append(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->m_op = op;
  537. exp->m_lhs = move(lhs);
  538. auto rhs = parse_expression(exp);
  539. exp->set_end(rhs->end());
  540. exp->m_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->m_op = op;
  549. exp->m_lhs = move(lhs);
  550. auto rhs = parse_expression(exp);
  551. exp->set_end(rhs->end());
  552. exp->m_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->m_is_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->m_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. auto start_token_index = index_of_token_at(start);
  753. auto end_node_index = index_of_token_at(end);
  754. VERIFY(start_token_index.has_value());
  755. VERIFY(end_node_index.has_value());
  756. StringBuilder text;
  757. for (size_t i = start_token_index.value(); i <= end_node_index.value(); ++i) {
  758. text.append(m_tokens[i].text());
  759. }
  760. return text.build();
  761. }
  762. void Parser::error(StringView message)
  763. {
  764. LOG_SCOPE();
  765. if (message.is_null() || message.is_empty())
  766. message = "<empty>";
  767. String formatted_message;
  768. if (m_state.token_index >= m_tokens.size()) {
  769. formatted_message = String::formatted("C++ Parsed error on EOF.{}", message);
  770. } else {
  771. formatted_message = String::formatted("C++ Parser error: {}. token: {} ({}:{})",
  772. message,
  773. m_state.token_index < m_tokens.size() ? text_of_token(m_tokens[m_state.token_index]) : "EOF",
  774. m_tokens[m_state.token_index].start().line,
  775. m_tokens[m_state.token_index].start().column);
  776. }
  777. m_state.errors.append(formatted_message);
  778. }
  779. bool Parser::match_expression()
  780. {
  781. return match_literal()
  782. || match_name()
  783. || match_unary_expression()
  784. || match_cpp_cast_expression()
  785. || match_c_style_cast_expression()
  786. || match_sizeof_expression()
  787. || match_braced_init_list();
  788. }
  789. bool Parser::eof() const
  790. {
  791. return m_state.token_index >= m_tokens.size();
  792. }
  793. Position Parser::position() const
  794. {
  795. if (m_tokens.is_empty())
  796. return {};
  797. if (eof())
  798. return m_tokens.last().end();
  799. return peek().start();
  800. }
  801. RefPtr<ASTNode> Parser::eof_node() const
  802. {
  803. VERIFY(m_tokens.size());
  804. return node_at(m_tokens.last().end());
  805. }
  806. RefPtr<ASTNode> Parser::node_at(Position pos) const
  807. {
  808. auto index = index_of_node_at(pos);
  809. if (!index.has_value())
  810. return nullptr;
  811. return m_state.nodes[index.value()];
  812. }
  813. Optional<size_t> Parser::index_of_node_at(Position pos) const
  814. {
  815. VERIFY(!m_tokens.is_empty());
  816. Optional<size_t> match_node_index;
  817. auto node_span = [](const ASTNode& node) {
  818. VERIFY(node.end().line >= node.start().line);
  819. VERIFY((node.end().line > node.start().line) || (node.end().column >= node.start().column));
  820. return Position { node.end().line - node.start().line, node.start().line != node.end().line ? 0 : node.end().column - node.start().column };
  821. };
  822. for (size_t node_index = 0; node_index < m_state.nodes.size(); ++node_index) {
  823. auto& node = m_state.nodes[node_index];
  824. if (node.start() > pos || node.end() < pos)
  825. continue;
  826. if (!match_node_index.has_value() || (node_span(node) <= node_span(m_state.nodes[match_node_index.value()])))
  827. match_node_index = node_index;
  828. }
  829. return match_node_index;
  830. }
  831. Optional<Token> Parser::token_at(Position pos) const
  832. {
  833. auto index = index_of_token_at(pos);
  834. if (!index.has_value())
  835. return {};
  836. return m_tokens[index.value()];
  837. }
  838. Optional<size_t> Parser::index_of_token_at(Position pos) const
  839. {
  840. for (size_t token_index = 0; token_index < m_tokens.size(); ++token_index) {
  841. auto token = m_tokens[token_index];
  842. if (token.start() > pos || token.end() < pos)
  843. continue;
  844. return token_index;
  845. }
  846. return {};
  847. }
  848. void Parser::print_tokens() const
  849. {
  850. for (auto& token : m_tokens) {
  851. outln("{}", token.to_string());
  852. }
  853. }
  854. Vector<Parser::TodoEntry> Parser::get_todo_entries() const
  855. {
  856. Vector<TodoEntry> ret;
  857. for (auto& token : m_tokens) {
  858. if (token.type() == Token::Type::Comment) {
  859. if (token.text().contains("TODO")) {
  860. ret.append({ token.text(), m_filename, token.start().line, token.start().column });
  861. }
  862. }
  863. }
  864. return ret;
  865. }
  866. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(ASTNode& parent)
  867. {
  868. LOG_SCOPE();
  869. Optional<size_t> start_token_index;
  870. Optional<size_t> end_token_index;
  871. while (!eof()) {
  872. auto token = peek();
  873. if (token.type() != Token::Type::DoubleQuotedString && token.type() != Token::Type::SingleQuotedString && token.type() != Token::Type::EscapeSequence) {
  874. VERIFY(start_token_index.has_value());
  875. end_token_index = m_state.token_index - 1;
  876. break;
  877. }
  878. if (!start_token_index.has_value())
  879. start_token_index = m_state.token_index;
  880. consume();
  881. }
  882. // String was not terminated
  883. if (!end_token_index.has_value()) {
  884. end_token_index = m_tokens.size() - 1;
  885. }
  886. VERIFY(start_token_index.has_value());
  887. VERIFY(end_token_index.has_value());
  888. Token start_token = m_tokens[start_token_index.value()];
  889. Token end_token = m_tokens[end_token_index.value()];
  890. auto text = text_in_range(start_token.start(), end_token.end());
  891. auto string_literal = create_ast_node<StringLiteral>(parent, start_token.start(), end_token.end());
  892. string_literal->m_value = text;
  893. return string_literal;
  894. }
  895. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement(ASTNode& parent)
  896. {
  897. LOG_SCOPE();
  898. auto return_statement = create_ast_node<ReturnStatement>(parent, position(), {});
  899. consume(Token::Type::Keyword);
  900. if (!peek(Token::Type::Semicolon).has_value()) {
  901. auto expression = parse_expression(*return_statement);
  902. return_statement->m_value = expression;
  903. }
  904. return_statement->set_end(position());
  905. return return_statement;
  906. }
  907. NonnullRefPtr<EnumDeclaration> Parser::parse_enum_declaration(ASTNode& parent)
  908. {
  909. LOG_SCOPE();
  910. auto enum_decl = create_ast_node<EnumDeclaration>(parent, position(), {});
  911. consume_keyword("enum");
  912. if (match_keyword("class")) {
  913. consume(Token::Type::Keyword);
  914. enum_decl->type = EnumDeclaration::Type::EnumClass;
  915. } else {
  916. enum_decl->type = EnumDeclaration::Type::RegularEnum;
  917. }
  918. auto name_token = consume(Token::Type::Identifier);
  919. enum_decl->m_name = text_of_token(name_token);
  920. consume(Token::Type::LeftCurly);
  921. while (!eof() && peek().type() != Token::Type::RightCurly) {
  922. enum_decl->m_entries.append(text_of_token(consume(Token::Type::Identifier)));
  923. if (peek().type() != Token::Type::Comma) {
  924. break;
  925. }
  926. consume(Token::Type::Comma);
  927. }
  928. consume(Token::Type::RightCurly);
  929. consume(Token::Type::Semicolon);
  930. enum_decl->set_end(position());
  931. return enum_decl;
  932. }
  933. Token Parser::consume_keyword(const String& keyword)
  934. {
  935. auto token = consume();
  936. if (token.type() != Token::Type::Keyword) {
  937. error(String::formatted("unexpected token: {}, expected Keyword", token.to_string()));
  938. return token;
  939. }
  940. if (text_of_token(token) != keyword) {
  941. error(String::formatted("unexpected keyword: {}, expected {}", text_of_token(token), keyword));
  942. return token;
  943. }
  944. return token;
  945. }
  946. bool Parser::match_keyword(const String& keyword)
  947. {
  948. auto token = peek();
  949. if (token.type() != Token::Type::Keyword) {
  950. return false;
  951. }
  952. if (text_of_token(token) != keyword) {
  953. return false;
  954. }
  955. return true;
  956. }
  957. NonnullRefPtr<StructOrClassDeclaration> Parser::parse_class_declaration(ASTNode& parent)
  958. {
  959. LOG_SCOPE();
  960. auto type_token = consume(Token::Type::Keyword);
  961. StructOrClassDeclaration::Type type {};
  962. if (type_token.text() == "struct")
  963. type = StructOrClassDeclaration::Type::Struct;
  964. if (type_token.text() == "class")
  965. type = StructOrClassDeclaration::Type::Class;
  966. auto decl = create_ast_node<StructOrClassDeclaration>(parent, position(), {}, type);
  967. auto name_token = consume(Token::Type::Identifier);
  968. decl->m_name = text_of_token(name_token);
  969. consume(Token::Type::LeftCurly);
  970. while (!eof() && peek().type() != Token::Type::RightCurly) {
  971. decl->m_members = parse_class_members(*decl);
  972. }
  973. consume(Token::Type::RightCurly);
  974. consume(Token::Type::Semicolon);
  975. decl->set_end(position());
  976. return decl;
  977. }
  978. NonnullRefPtr<BooleanLiteral> Parser::parse_boolean_literal(ASTNode& parent)
  979. {
  980. LOG_SCOPE();
  981. auto token = consume(Token::Type::Keyword);
  982. auto text = text_of_token(token);
  983. // text == "true" || text == "false";
  984. bool value = (text == "true");
  985. return create_ast_node<BooleanLiteral>(parent, token.start(), token.end(), value);
  986. }
  987. bool Parser::match_boolean_literal()
  988. {
  989. auto token = peek();
  990. if (token.type() != Token::Type::Keyword)
  991. return false;
  992. auto text = text_of_token(token);
  993. return text == "true" || text == "false";
  994. }
  995. NonnullRefPtr<Type> Parser::parse_type(ASTNode& parent)
  996. {
  997. LOG_SCOPE();
  998. if (!match_named_type()) {
  999. error("expected named named_type");
  1000. auto token = consume();
  1001. return create_ast_node<NamedType>(parent, token.start(), token.end());
  1002. }
  1003. auto named_type = create_ast_node<NamedType>(parent, position(), {});
  1004. auto qualifiers = parse_type_qualifiers();
  1005. named_type->m_qualifiers = move(qualifiers);
  1006. if (match_keyword("auto")) {
  1007. consume(Token::Type::Keyword);
  1008. named_type->m_is_auto = true;
  1009. named_type->set_end(position());
  1010. return named_type;
  1011. }
  1012. if (match_keyword("struct")) {
  1013. consume(Token::Type::Keyword); // Consume struct prefix
  1014. }
  1015. if (!match_name()) {
  1016. named_type->set_end(position());
  1017. error(String::formatted("expected name instead of: {}", peek().text()));
  1018. return named_type;
  1019. }
  1020. named_type->m_name = parse_name(*named_type);
  1021. NonnullRefPtr<Type> type = named_type;
  1022. while (!eof() && peek().type() == Token::Type::Asterisk) {
  1023. type->set_end(position());
  1024. auto asterisk = consume();
  1025. auto ptr = create_ast_node<Pointer>(parent, type->start(), asterisk.end());
  1026. type->set_parent(*ptr);
  1027. ptr->m_pointee = type;
  1028. ptr->set_end(position());
  1029. type = ptr;
  1030. }
  1031. type->set_end(position());
  1032. return type;
  1033. }
  1034. NonnullRefPtr<ForStatement> Parser::parse_for_statement(ASTNode& parent)
  1035. {
  1036. LOG_SCOPE();
  1037. auto for_statement = create_ast_node<ForStatement>(parent, position(), {});
  1038. consume(Token::Type::Keyword);
  1039. consume(Token::Type::LeftParen);
  1040. if (peek().type() != Token::Type::Semicolon)
  1041. for_statement->m_init = parse_variable_declaration(*for_statement, false);
  1042. consume(Token::Type::Semicolon);
  1043. if (peek().type() != Token::Type::Semicolon)
  1044. for_statement->m_test = parse_expression(*for_statement);
  1045. consume(Token::Type::Semicolon);
  1046. if (peek().type() != Token::Type::RightParen)
  1047. for_statement->m_update = parse_expression(*for_statement);
  1048. consume(Token::Type::RightParen);
  1049. for_statement->m_body = parse_statement(*for_statement);
  1050. for_statement->set_end(for_statement->m_body->end());
  1051. return for_statement;
  1052. }
  1053. NonnullRefPtr<IfStatement> Parser::parse_if_statement(ASTNode& parent)
  1054. {
  1055. LOG_SCOPE();
  1056. auto if_statement = create_ast_node<IfStatement>(parent, position(), {});
  1057. consume(Token::Type::Keyword);
  1058. consume(Token::Type::LeftParen);
  1059. if_statement->m_predicate = parse_expression(*if_statement);
  1060. consume(Token::Type::RightParen);
  1061. if_statement->m_then = parse_statement(*if_statement);
  1062. if (match_keyword("else")) {
  1063. consume(Token::Type::Keyword);
  1064. if_statement->m_else = parse_statement(*if_statement);
  1065. if_statement->set_end(if_statement->m_else->end());
  1066. } else {
  1067. if_statement->set_end(if_statement->m_then->end());
  1068. }
  1069. return if_statement;
  1070. }
  1071. Vector<StringView> Parser::parse_type_qualifiers()
  1072. {
  1073. LOG_SCOPE();
  1074. Vector<StringView> qualifiers;
  1075. while (!eof()) {
  1076. auto token = peek();
  1077. if (token.type() != Token::Type::Keyword)
  1078. break;
  1079. auto text = text_of_token(token);
  1080. if (text == "static" || text == "const") {
  1081. qualifiers.append(text);
  1082. consume();
  1083. } else {
  1084. break;
  1085. }
  1086. }
  1087. return qualifiers;
  1088. }
  1089. Vector<StringView> Parser::parse_function_qualifiers()
  1090. {
  1091. LOG_SCOPE();
  1092. Vector<StringView> qualifiers;
  1093. while (!eof()) {
  1094. auto token = peek();
  1095. if (token.type() != Token::Type::Keyword)
  1096. break;
  1097. auto text = text_of_token(token);
  1098. if (text == "static" || text == "inline") {
  1099. qualifiers.append(text);
  1100. consume();
  1101. } else {
  1102. break;
  1103. }
  1104. }
  1105. return qualifiers;
  1106. }
  1107. bool Parser::match_attribute_specification()
  1108. {
  1109. return text_of_token(peek()) == "__attribute__";
  1110. }
  1111. void Parser::consume_attribute_specification()
  1112. {
  1113. consume(); // __attribute__
  1114. consume(Token::Type::LeftParen);
  1115. size_t left_count = 1;
  1116. while (!eof()) {
  1117. auto token = consume();
  1118. if (token.type() == Token::Type::LeftParen) {
  1119. ++left_count;
  1120. }
  1121. if (token.type() == Token::Type::RightParen) {
  1122. --left_count;
  1123. }
  1124. if (left_count == 0)
  1125. return;
  1126. }
  1127. }
  1128. bool Parser::match_ellipsis()
  1129. {
  1130. if (m_state.token_index > m_tokens.size() - 3)
  1131. return false;
  1132. return peek().type() == Token::Type::Dot && peek(1).type() == Token::Type::Dot && peek(2).type() == Token::Type::Dot;
  1133. }
  1134. void Parser::add_tokens_for_preprocessor(Token& replaced_token, Preprocessor::DefinedValue& definition)
  1135. {
  1136. if (!definition.value.has_value())
  1137. return;
  1138. Lexer lexer(definition.value.value());
  1139. for (auto token : lexer.lex()) {
  1140. if (token.type() == Token::Type::Whitespace)
  1141. continue;
  1142. token.set_start(replaced_token.start());
  1143. token.set_end(replaced_token.end());
  1144. m_tokens.append(move(token));
  1145. }
  1146. }
  1147. NonnullRefPtr<NamespaceDeclaration> Parser::parse_namespace_declaration(ASTNode& parent, bool is_nested_namespace)
  1148. {
  1149. auto namespace_decl = create_ast_node<NamespaceDeclaration>(parent, position(), {});
  1150. if (!is_nested_namespace)
  1151. consume(Token::Type::Keyword);
  1152. auto name_token = consume(Token::Type::Identifier);
  1153. namespace_decl->m_name = name_token.text();
  1154. if (peek().type() == Token::Type::ColonColon) {
  1155. consume(Token::Type::ColonColon);
  1156. namespace_decl->m_declarations.append(parse_namespace_declaration(*namespace_decl, true));
  1157. namespace_decl->set_end(position());
  1158. return namespace_decl;
  1159. }
  1160. consume(Token::Type::LeftCurly);
  1161. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1162. auto declaration = parse_single_declaration_in_translation_unit(*namespace_decl);
  1163. if (declaration) {
  1164. namespace_decl->m_declarations.append(declaration.release_nonnull());
  1165. } else {
  1166. error("unexpected token");
  1167. consume();
  1168. }
  1169. }
  1170. consume(Token::Type::RightCurly);
  1171. namespace_decl->set_end(position());
  1172. return namespace_decl;
  1173. }
  1174. bool Parser::match_name()
  1175. {
  1176. auto type = peek().type();
  1177. return type == Token::Type::Identifier || type == Token::Type::KnownType;
  1178. }
  1179. NonnullRefPtr<Name> Parser::parse_name(ASTNode& parent)
  1180. {
  1181. LOG_SCOPE();
  1182. NonnullRefPtr<Name> name_node = create_ast_node<Name>(parent, position(), {});
  1183. while (!eof() && (peek().type() == Token::Type::Identifier || peek().type() == Token::Type::KnownType) && peek(1).type() == Token::Type::ColonColon) {
  1184. auto token = consume();
  1185. name_node->m_scope.append(create_ast_node<Identifier>(*name_node, token.start(), token.end(), token.text()));
  1186. consume(Token::Type::ColonColon);
  1187. }
  1188. if (peek().type() == Token::Type::Identifier || peek().type() == Token::Type::KnownType) {
  1189. auto token = consume();
  1190. name_node->m_name = create_ast_node<Identifier>(*name_node, token.start(), token.end(), token.text());
  1191. } else {
  1192. name_node->set_end(position());
  1193. return name_node;
  1194. }
  1195. if (match_template_arguments()) {
  1196. consume(Token::Type::Less);
  1197. NonnullRefPtr<TemplatizedName> templatized_name = create_ast_node<TemplatizedName>(parent, name_node->start(), {});
  1198. templatized_name->m_name = move(name_node->m_name);
  1199. templatized_name->m_scope = move(name_node->m_scope);
  1200. name_node->set_end(position());
  1201. name_node = templatized_name;
  1202. while (peek().type() != Token::Type::Greater && !eof()) {
  1203. templatized_name->m_template_arguments.append(parse_type(*templatized_name));
  1204. if (peek().type() == Token::Type::Comma)
  1205. consume(Token::Type::Comma);
  1206. }
  1207. consume(Token::Type::Greater);
  1208. }
  1209. name_node->set_end(position());
  1210. return name_node;
  1211. }
  1212. bool Parser::match_cpp_cast_expression()
  1213. {
  1214. save_state();
  1215. ScopeGuard state_guard = [this] { load_state(); };
  1216. auto token = consume();
  1217. if (token.type() != Token::Type::Keyword)
  1218. return false;
  1219. auto text = token.text();
  1220. if (text == "static_cast" || text == "reinterpret_cast" || text == "dynamic_cast" || text == "const_cast")
  1221. return true;
  1222. return false;
  1223. }
  1224. bool Parser::match_c_style_cast_expression()
  1225. {
  1226. save_state();
  1227. ScopeGuard state_guard = [this] { load_state(); };
  1228. if (consume().type() != Token::Type::LeftParen)
  1229. return false;
  1230. if (!match_type())
  1231. return false;
  1232. parse_type(get_dummy_node());
  1233. if (consume().type() != Token::Type::RightParen)
  1234. return false;
  1235. if (!match_expression())
  1236. return false;
  1237. return true;
  1238. }
  1239. NonnullRefPtr<CStyleCastExpression> Parser::parse_c_style_cast_expression(ASTNode& parent)
  1240. {
  1241. auto parse_exp = create_ast_node<CStyleCastExpression>(parent, position(), {});
  1242. consume(Token::Type::LeftParen);
  1243. parse_exp->m_type = parse_type(*parse_exp);
  1244. consume(Token::Type::RightParen);
  1245. parse_exp->m_expression = parse_expression(*parse_exp);
  1246. parse_exp->set_end(position());
  1247. return parse_exp;
  1248. }
  1249. NonnullRefPtr<CppCastExpression> Parser::parse_cpp_cast_expression(ASTNode& parent)
  1250. {
  1251. auto cast_expression = create_ast_node<CppCastExpression>(parent, position(), {});
  1252. cast_expression->m_cast_type = consume(Token::Type::Keyword).text();
  1253. consume(Token::Type::Less);
  1254. cast_expression->m_type = parse_type(*cast_expression);
  1255. consume(Token::Type::Greater);
  1256. consume(Token::Type::LeftParen);
  1257. cast_expression->m_expression = parse_expression(*cast_expression);
  1258. consume(Token::Type::RightParen);
  1259. cast_expression->set_end(position());
  1260. return cast_expression;
  1261. }
  1262. bool Parser::match_sizeof_expression()
  1263. {
  1264. return match_keyword("sizeof");
  1265. }
  1266. NonnullRefPtr<SizeofExpression> Parser::parse_sizeof_expression(ASTNode& parent)
  1267. {
  1268. auto exp = create_ast_node<SizeofExpression>(parent, position(), {});
  1269. consume(Token::Type::Keyword);
  1270. consume(Token::Type::LeftParen);
  1271. exp->m_type = parse_type(parent);
  1272. consume(Token::Type::RightParen);
  1273. exp->set_end(position());
  1274. return exp;
  1275. }
  1276. bool Parser::match_braced_init_list()
  1277. {
  1278. return match(Token::Type::LeftCurly);
  1279. }
  1280. NonnullRefPtr<BracedInitList> Parser::parse_braced_init_list(ASTNode& parent)
  1281. {
  1282. auto init_list = create_ast_node<BracedInitList>(parent, position(), {});
  1283. consume(Token::Type::LeftCurly);
  1284. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1285. init_list->m_expressions.append(parse_expression(*init_list));
  1286. }
  1287. consume(Token::Type::RightCurly);
  1288. init_list->set_end(position());
  1289. return init_list;
  1290. }
  1291. NonnullRefPtrVector<Declaration> Parser::parse_class_members(StructOrClassDeclaration& parent)
  1292. {
  1293. auto& class_name = parent.name();
  1294. NonnullRefPtrVector<Declaration> members;
  1295. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1296. if (match_access_specifier())
  1297. consume_access_specifier(); // FIXME: Do not ignore access specifiers
  1298. auto member_type = match_class_member(class_name);
  1299. if (member_type.has_value()) {
  1300. members.append(parse_declaration(parent, member_type.value()));
  1301. } else {
  1302. error("Expected class member");
  1303. consume();
  1304. }
  1305. }
  1306. return members;
  1307. }
  1308. bool Parser::match_access_specifier()
  1309. {
  1310. if (peek(1).type() != Token::Type::Colon)
  1311. return false;
  1312. return match_keyword("private") || match_keyword("protected") || match_keyword("public");
  1313. }
  1314. void Parser::consume_access_specifier()
  1315. {
  1316. consume(Token::Type::Keyword);
  1317. consume(Token::Type::Colon);
  1318. }
  1319. bool Parser::match_constructor(const StringView& class_name)
  1320. {
  1321. save_state();
  1322. ScopeGuard state_guard = [this] { load_state(); };
  1323. auto token = consume();
  1324. if (token.text() != class_name)
  1325. return false;
  1326. if (!peek(Token::Type::LeftParen).has_value())
  1327. return false;
  1328. consume();
  1329. while (consume().type() != Token::Type::RightParen && !eof()) { };
  1330. return (peek(Token::Type::Semicolon).has_value() || peek(Token::Type::LeftCurly).has_value());
  1331. }
  1332. bool Parser::match_destructor(const StringView& class_name)
  1333. {
  1334. save_state();
  1335. ScopeGuard state_guard = [this] { load_state(); };
  1336. if (!match(Token::Type::Tilde))
  1337. return false;
  1338. consume();
  1339. auto token = peek();
  1340. if (token.text() != class_name)
  1341. return false;
  1342. consume();
  1343. if (!peek(Token::Type::LeftParen).has_value())
  1344. return false;
  1345. consume();
  1346. while (consume().type() != Token::Type::RightParen && !eof()) { };
  1347. return (peek(Token::Type::Semicolon).has_value() || peek(Token::Type::LeftCurly).has_value());
  1348. }
  1349. void Parser::parse_constructor_or_destructor_impl(FunctionDeclaration& func, CtorOrDtor type)
  1350. {
  1351. if (type == CtorOrDtor::Dtor)
  1352. consume(Token::Type::Tilde);
  1353. auto name_token = consume();
  1354. if (name_token.type() != Token::Type::Identifier && name_token.type() != Token::Type::KnownType) {
  1355. error("Unexpected constructor name");
  1356. }
  1357. func.m_name = name_token.text();
  1358. consume(Token::Type::LeftParen);
  1359. auto parameters = parse_parameter_list(func);
  1360. if (parameters.has_value()) {
  1361. if (type == CtorOrDtor::Dtor && !parameters->is_empty())
  1362. error("Destructor declaration that takes parameters");
  1363. else
  1364. func.m_parameters = move(parameters.value());
  1365. }
  1366. consume(Token::Type::RightParen);
  1367. // TODO: Parse =default, =delete.
  1368. RefPtr<FunctionDefinition> body;
  1369. Position ctor_end {};
  1370. if (peek(Token::Type::LeftCurly).has_value()) {
  1371. body = parse_function_definition(func);
  1372. ctor_end = body->end();
  1373. } else {
  1374. ctor_end = position();
  1375. if (match_attribute_specification())
  1376. consume_attribute_specification(); // we don't use the value of __attribute__
  1377. consume(Token::Type::Semicolon);
  1378. }
  1379. func.m_definition = move(body);
  1380. func.set_end(ctor_end);
  1381. }
  1382. NonnullRefPtr<Constructor> Parser::parse_constructor(ASTNode& parent)
  1383. {
  1384. auto ctor = create_ast_node<Constructor>(parent, position(), {});
  1385. parse_constructor_or_destructor_impl(*ctor, CtorOrDtor::Ctor);
  1386. return ctor;
  1387. }
  1388. NonnullRefPtr<Destructor> Parser::parse_destructor(ASTNode& parent)
  1389. {
  1390. auto ctor = create_ast_node<Destructor>(parent, position(), {});
  1391. parse_constructor_or_destructor_impl(*ctor, CtorOrDtor::Dtor);
  1392. return ctor;
  1393. }
  1394. }