Parser.cpp 43 KB

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