Parser.cpp 43 KB

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