Parser.cpp 43 KB

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