Parser.cpp 43 KB

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