Parser.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  1. /*
  2. * Copyright (c) 2021, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #ifdef CPP_DEBUG
  7. # define DEBUG_SPAM
  8. #endif
  9. #include "Parser.h"
  10. #include "AST.h"
  11. #include <AK/Debug.h>
  12. #include <AK/ScopeGuard.h>
  13. #include <AK/ScopeLogger.h>
  14. #include <LibCpp/Lexer.h>
  15. namespace Cpp {
  16. Parser::Parser(const StringView& program, const String& filename, Preprocessor::Definitions&& definitions)
  17. : m_definitions(move(definitions))
  18. , m_filename(filename)
  19. {
  20. initialize_program_tokens(program);
  21. if constexpr (CPP_DEBUG) {
  22. dbgln("Tokens:");
  23. for (auto& token : m_tokens) {
  24. StringView text;
  25. if (token.start().line != token.end().line || token.start().column > token.end().column)
  26. text = {};
  27. else
  28. text = text_of_token(token);
  29. dbgln("{} {}:{}-{}:{} ({})", token.to_string(), token.start().line, token.start().column, token.end().line, token.end().column, text);
  30. }
  31. }
  32. }
  33. void Parser::initialize_program_tokens(const StringView& program)
  34. {
  35. Lexer lexer(program);
  36. for (auto& token : lexer.lex()) {
  37. if (token.type() == Token::Type::Whitespace)
  38. continue;
  39. if (token.type() == Token::Type::Identifier) {
  40. if (auto defined_value = m_definitions.find(text_of_token(token)); defined_value != m_definitions.end()) {
  41. add_tokens_for_preprocessor(token, defined_value->value);
  42. m_replaced_preprocessor_tokens.append({ token, defined_value->value });
  43. continue;
  44. }
  45. }
  46. m_tokens.append(move(token));
  47. }
  48. }
  49. NonnullRefPtr<TranslationUnit> Parser::parse()
  50. {
  51. ScopeLogger logger {};
  52. if (m_tokens.is_empty())
  53. return create_root_ast_node({}, {});
  54. auto unit = create_root_ast_node(m_tokens.first().start(), m_tokens.last().end());
  55. unit->m_declarations = parse_declarations_in_translation_unit(*unit);
  56. return unit;
  57. }
  58. NonnullRefPtrVector<Declaration> Parser::parse_declarations_in_translation_unit(ASTNode& parent)
  59. {
  60. NonnullRefPtrVector<Declaration> declarations;
  61. while (!eof()) {
  62. auto declaration = parse_single_declaration_in_translation_unit(parent);
  63. if (declaration) {
  64. declarations.append(declaration.release_nonnull());
  65. } else {
  66. error("unexpected token");
  67. consume();
  68. }
  69. }
  70. return declarations;
  71. }
  72. RefPtr<Declaration> Parser::parse_single_declaration_in_translation_unit(ASTNode& parent)
  73. {
  74. while (!eof()) {
  75. if (match_comment()) {
  76. consume(Token::Type::Comment);
  77. continue;
  78. }
  79. if (match_preprocessor()) {
  80. consume_preprocessor();
  81. continue;
  82. }
  83. auto declaration = match_declaration_in_translation_unit();
  84. if (declaration.has_value()) {
  85. return parse_declaration(parent, declaration.value());
  86. }
  87. return {};
  88. }
  89. return {};
  90. }
  91. NonnullRefPtr<Declaration> Parser::parse_declaration(ASTNode& parent, DeclarationType declaration_type)
  92. {
  93. switch (declaration_type) {
  94. case DeclarationType::Function:
  95. return parse_function_declaration(parent);
  96. case DeclarationType::Variable:
  97. return parse_variable_declaration(parent);
  98. case DeclarationType::Enum:
  99. return parse_enum_declaration(parent);
  100. case DeclarationType::Class:
  101. return parse_struct_or_class_declaration(parent, StructOrClassDeclaration::Type::Class);
  102. case DeclarationType::Struct:
  103. return parse_struct_or_class_declaration(parent, StructOrClassDeclaration::Type::Struct);
  104. case DeclarationType::Namespace:
  105. return parse_namespace_declaration(parent);
  106. default:
  107. error("unexpected declaration type");
  108. return create_ast_node<InvalidDeclaration>(parent, position(), position());
  109. }
  110. }
  111. NonnullRefPtr<FunctionDeclaration> Parser::parse_function_declaration(ASTNode& parent)
  112. {
  113. auto func = create_ast_node<FunctionDeclaration>(parent, position(), {});
  114. func->m_qualifiers = parse_function_qualifiers();
  115. func->m_return_type = parse_type(*func);
  116. auto function_name = consume(Token::Type::Identifier);
  117. func->m_name = text_of_token(function_name);
  118. consume(Token::Type::LeftParen);
  119. auto parameters = parse_parameter_list(*func);
  120. if (parameters.has_value())
  121. func->m_parameters = move(parameters.value());
  122. consume(Token::Type::RightParen);
  123. RefPtr<FunctionDefinition> body;
  124. Position func_end {};
  125. if (peek(Token::Type::LeftCurly).has_value()) {
  126. body = parse_function_definition(*func);
  127. func_end = body->end();
  128. } else {
  129. func_end = position();
  130. if (match_attribute_specification())
  131. consume_attribute_specification(); // we don't use the value of __attribute__
  132. consume(Token::Type::Semicolon);
  133. }
  134. func->m_definition = move(body);
  135. func->set_end(func_end);
  136. return func;
  137. }
  138. NonnullRefPtr<FunctionDefinition> Parser::parse_function_definition(ASTNode& parent)
  139. {
  140. ScopeLogger logger {};
  141. auto func = create_ast_node<FunctionDefinition>(parent, position(), {});
  142. consume(Token::Type::LeftCurly);
  143. while (!eof() && peek().type() != Token::Type::RightCurly) {
  144. func->statements().append(parse_statement(func));
  145. }
  146. func->set_end(position());
  147. if (!eof())
  148. consume(Token::Type::RightCurly);
  149. return func;
  150. }
  151. NonnullRefPtr<Statement> Parser::parse_statement(ASTNode& parent)
  152. {
  153. ScopeLogger logger {};
  154. ArmedScopeGuard consume_semicolon([this]() {
  155. consume(Token::Type::Semicolon);
  156. });
  157. if (match_block_statement()) {
  158. consume_semicolon.disarm();
  159. return parse_block_statement(parent);
  160. }
  161. if (match_comment()) {
  162. consume_semicolon.disarm();
  163. return parse_comment(parent);
  164. }
  165. if (match_variable_declaration()) {
  166. return parse_variable_declaration(parent, false);
  167. }
  168. if (match_expression()) {
  169. return parse_expression(parent);
  170. }
  171. if (match_keyword("return")) {
  172. return parse_return_statement(parent);
  173. }
  174. if (match_keyword("for")) {
  175. consume_semicolon.disarm();
  176. return parse_for_statement(parent);
  177. }
  178. if (match_keyword("if")) {
  179. consume_semicolon.disarm();
  180. return parse_if_statement(parent);
  181. } else {
  182. error("unexpected statement type");
  183. consume_semicolon.disarm();
  184. consume();
  185. return create_ast_node<InvalidStatement>(parent, position(), position());
  186. }
  187. }
  188. NonnullRefPtr<Comment> Parser::parse_comment(ASTNode& parent)
  189. {
  190. auto comment = create_ast_node<Comment>(parent, position(), {});
  191. consume(Token::Type::Comment);
  192. comment->set_end(position());
  193. return comment;
  194. }
  195. bool Parser::match_block_statement()
  196. {
  197. return peek().type() == Token::Type::LeftCurly;
  198. }
  199. NonnullRefPtr<BlockStatement> Parser::parse_block_statement(ASTNode& parent)
  200. {
  201. ScopeLogger logger {};
  202. auto block_statement = create_ast_node<BlockStatement>(parent, position(), {});
  203. consume(Token::Type::LeftCurly);
  204. while (!eof() && peek().type() != Token::Type::RightCurly) {
  205. block_statement->m_statements.append(parse_statement(*block_statement));
  206. }
  207. consume(Token::Type::RightCurly);
  208. block_statement->set_end(position());
  209. return block_statement;
  210. }
  211. bool Parser::match_type()
  212. {
  213. save_state();
  214. ScopeGuard state_guard = [this] { load_state(); };
  215. parse_type_qualifiers();
  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 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 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 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 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 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 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 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 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 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 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. auto token_type = peek().type();
  746. return match_literal()
  747. || token_type == Token::Type::Identifier
  748. || match_unary_expression()
  749. || match_cpp_cast_expression()
  750. || match_c_style_cast_expression()
  751. || match_sizeof_expression()
  752. || match_braced_init_list();
  753. }
  754. bool Parser::eof() const
  755. {
  756. return m_state.token_index >= m_tokens.size();
  757. }
  758. Position Parser::position() const
  759. {
  760. if (eof())
  761. return m_tokens.last().end();
  762. return peek().start();
  763. }
  764. RefPtr<ASTNode> Parser::eof_node() const
  765. {
  766. VERIFY(m_tokens.size());
  767. return node_at(m_tokens.last().end());
  768. }
  769. RefPtr<ASTNode> Parser::node_at(Position pos) const
  770. {
  771. auto index = index_of_node_at(pos);
  772. if (!index.has_value())
  773. return nullptr;
  774. return m_state.nodes[index.value()];
  775. }
  776. Optional<size_t> Parser::index_of_node_at(Position pos) const
  777. {
  778. VERIFY(!m_tokens.is_empty());
  779. Optional<size_t> match_node_index;
  780. auto node_span = [](const ASTNode& node) {
  781. VERIFY(node.end().line >= node.start().line);
  782. VERIFY((node.end().line > node.start().line) || (node.end().column >= node.start().column));
  783. return Position { node.end().line - node.start().line, node.start().line != node.end().line ? 0 : node.end().column - node.start().column };
  784. };
  785. for (size_t node_index = 0; node_index < m_state.nodes.size(); ++node_index) {
  786. auto& node = m_state.nodes[node_index];
  787. if (node.start() > pos || node.end() < pos)
  788. continue;
  789. if (!match_node_index.has_value() || (node_span(node) < node_span(m_state.nodes[match_node_index.value()])))
  790. match_node_index = node_index;
  791. }
  792. return match_node_index;
  793. }
  794. Optional<Token> Parser::token_at(Position pos) const
  795. {
  796. auto index = index_of_token_at(pos);
  797. if (!index.has_value())
  798. return {};
  799. return m_tokens[index.value()];
  800. }
  801. Optional<size_t> Parser::index_of_token_at(Position pos) const
  802. {
  803. for (size_t token_index = 0; token_index < m_tokens.size(); ++token_index) {
  804. auto token = m_tokens[token_index];
  805. if (token.start() > pos || token.end() < pos)
  806. continue;
  807. return token_index;
  808. }
  809. return {};
  810. }
  811. void Parser::print_tokens() const
  812. {
  813. for (auto& token : m_tokens) {
  814. dbgln("{}", token.to_string());
  815. }
  816. }
  817. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(ASTNode& parent)
  818. {
  819. ScopeLogger logger {};
  820. Optional<size_t> start_token_index;
  821. Optional<size_t> end_token_index;
  822. while (!eof()) {
  823. auto token = peek();
  824. if (token.type() != Token::Type::DoubleQuotedString && token.type() != Token::Type::SingleQuotedString && token.type() != Token::Type::EscapeSequence) {
  825. VERIFY(start_token_index.has_value());
  826. end_token_index = m_state.token_index - 1;
  827. break;
  828. }
  829. if (!start_token_index.has_value())
  830. start_token_index = m_state.token_index;
  831. consume();
  832. }
  833. // String was not terminated
  834. if (!end_token_index.has_value()) {
  835. end_token_index = m_tokens.size() - 1;
  836. }
  837. VERIFY(start_token_index.has_value());
  838. VERIFY(end_token_index.has_value());
  839. Token start_token = m_tokens[start_token_index.value()];
  840. Token end_token = m_tokens[end_token_index.value()];
  841. auto text = text_in_range(start_token.start(), end_token.end());
  842. auto string_literal = create_ast_node<StringLiteral>(parent, start_token.start(), end_token.end());
  843. string_literal->m_value = text;
  844. return string_literal;
  845. }
  846. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement(ASTNode& parent)
  847. {
  848. ScopeLogger logger {};
  849. auto return_statement = create_ast_node<ReturnStatement>(parent, position(), {});
  850. consume(Token::Type::Keyword);
  851. if (!peek(Token::Type::Semicolon).has_value()) {
  852. auto expression = parse_expression(*return_statement);
  853. return_statement->m_value = expression;
  854. }
  855. return_statement->set_end(position());
  856. return return_statement;
  857. }
  858. NonnullRefPtr<EnumDeclaration> Parser::parse_enum_declaration(ASTNode& parent)
  859. {
  860. ScopeLogger logger {};
  861. auto enum_decl = create_ast_node<EnumDeclaration>(parent, position(), {});
  862. consume_keyword("enum");
  863. auto name_token = consume(Token::Type::Identifier);
  864. enum_decl->m_name = text_of_token(name_token);
  865. consume(Token::Type::LeftCurly);
  866. while (!eof() && peek().type() != Token::Type::RightCurly) {
  867. enum_decl->m_entries.append(text_of_token(consume(Token::Type::Identifier)));
  868. if (peek().type() != Token::Type::Comma) {
  869. break;
  870. }
  871. consume(Token::Type::Comma);
  872. }
  873. consume(Token::Type::RightCurly);
  874. consume(Token::Type::Semicolon);
  875. enum_decl->set_end(position());
  876. return enum_decl;
  877. }
  878. Token Parser::consume_keyword(const String& keyword)
  879. {
  880. auto token = consume();
  881. if (token.type() != Token::Type::Keyword) {
  882. error(String::formatted("unexpected token: {}, expected Keyword", token.to_string()));
  883. return token;
  884. }
  885. if (text_of_token(token) != keyword) {
  886. error(String::formatted("unexpected keyword: {}, expected {}", text_of_token(token), keyword));
  887. return token;
  888. }
  889. return token;
  890. }
  891. bool Parser::match_keyword(const String& keyword)
  892. {
  893. auto token = peek();
  894. if (token.type() != Token::Type::Keyword) {
  895. return false;
  896. }
  897. if (text_of_token(token) != keyword) {
  898. return false;
  899. }
  900. return true;
  901. }
  902. NonnullRefPtr<StructOrClassDeclaration> Parser::parse_struct_or_class_declaration(ASTNode& parent, StructOrClassDeclaration::Type type)
  903. {
  904. ScopeLogger logger {};
  905. auto decl = create_ast_node<StructOrClassDeclaration>(parent, position(), {}, type);
  906. switch (type) {
  907. case StructOrClassDeclaration::Type::Struct:
  908. consume_keyword("struct");
  909. break;
  910. case StructOrClassDeclaration::Type::Class:
  911. consume_keyword("class");
  912. break;
  913. }
  914. auto name_token = consume(Token::Type::Identifier);
  915. decl->m_name = text_of_token(name_token);
  916. consume(Token::Type::LeftCurly);
  917. while (!eof() && peek().type() != Token::Type::RightCurly) {
  918. decl->m_members.append(parse_member_declaration(*decl));
  919. }
  920. consume(Token::Type::RightCurly);
  921. consume(Token::Type::Semicolon);
  922. decl->set_end(position());
  923. return decl;
  924. }
  925. NonnullRefPtr<MemberDeclaration> Parser::parse_member_declaration(ASTNode& parent)
  926. {
  927. ScopeLogger logger {};
  928. auto member_decl = create_ast_node<MemberDeclaration>(parent, position(), {});
  929. member_decl->m_type = parse_type(*member_decl);
  930. auto identifier_token = consume(Token::Type::Identifier);
  931. member_decl->m_name = text_of_token(identifier_token);
  932. if (match_braced_init_list()) {
  933. member_decl->m_initial_value = parse_braced_init_list(*member_decl);
  934. }
  935. consume(Token::Type::Semicolon);
  936. member_decl->set_end(position());
  937. return member_decl;
  938. }
  939. NonnullRefPtr<BooleanLiteral> Parser::parse_boolean_literal(ASTNode& parent)
  940. {
  941. ScopeLogger logger {};
  942. auto token = consume(Token::Type::Keyword);
  943. auto text = text_of_token(token);
  944. // text == "true" || text == "false";
  945. bool value = (text == "true");
  946. return create_ast_node<BooleanLiteral>(parent, token.start(), token.end(), value);
  947. }
  948. bool Parser::match_boolean_literal()
  949. {
  950. auto token = peek();
  951. if (token.type() != Token::Type::Keyword)
  952. return false;
  953. auto text = text_of_token(token);
  954. return text == "true" || text == "false";
  955. }
  956. NonnullRefPtr<Type> Parser::parse_type(ASTNode& parent)
  957. {
  958. ScopeLogger logger {};
  959. if (!match_type()) {
  960. auto token = consume();
  961. return create_ast_node<Type>(parent, token.start(), token.end());
  962. }
  963. auto type = create_ast_node<Type>(parent, position(), {});
  964. auto qualifiers = parse_type_qualifiers();
  965. type->m_qualifiers = move(qualifiers);
  966. if (match_keyword("struct")) {
  967. consume(Token::Type::Keyword); // Consume struct prefix
  968. }
  969. if (!match_name()) {
  970. type->set_end(position());
  971. error(String::formatted("expected name instead of: {}", peek().text()));
  972. return type;
  973. }
  974. type->m_name = parse_name(*type);
  975. while (!eof() && peek().type() == Token::Type::Asterisk) {
  976. type->set_end(position());
  977. auto asterisk = consume();
  978. auto ptr = create_ast_node<Pointer>(parent, asterisk.start(), asterisk.end());
  979. type->set_parent(*ptr);
  980. ptr->m_pointee = type;
  981. type = ptr;
  982. }
  983. type->set_end(position());
  984. return type;
  985. }
  986. NonnullRefPtr<ForStatement> Parser::parse_for_statement(ASTNode& parent)
  987. {
  988. ScopeLogger logger {};
  989. auto for_statement = create_ast_node<ForStatement>(parent, position(), {});
  990. consume(Token::Type::Keyword);
  991. consume(Token::Type::LeftParen);
  992. if (peek().type() != Token::Type::Semicolon)
  993. for_statement->m_init = parse_variable_declaration(*for_statement, false);
  994. consume(Token::Type::Semicolon);
  995. if (peek().type() != Token::Type::Semicolon)
  996. for_statement->m_test = parse_expression(*for_statement);
  997. consume(Token::Type::Semicolon);
  998. if (peek().type() != Token::Type::RightParen)
  999. for_statement->m_update = parse_expression(*for_statement);
  1000. consume(Token::Type::RightParen);
  1001. for_statement->m_body = parse_statement(*for_statement);
  1002. for_statement->set_end(for_statement->m_body->end());
  1003. return for_statement;
  1004. }
  1005. NonnullRefPtr<IfStatement> Parser::parse_if_statement(ASTNode& parent)
  1006. {
  1007. ScopeLogger logger {};
  1008. auto if_statement = create_ast_node<IfStatement>(parent, position(), {});
  1009. consume(Token::Type::Keyword);
  1010. consume(Token::Type::LeftParen);
  1011. if_statement->m_predicate = parse_expression(*if_statement);
  1012. consume(Token::Type::RightParen);
  1013. if_statement->m_then = parse_statement(*if_statement);
  1014. if (match_keyword("else")) {
  1015. consume(Token::Type::Keyword);
  1016. if_statement->m_else = parse_statement(*if_statement);
  1017. if_statement->set_end(if_statement->m_else->end());
  1018. } else {
  1019. if_statement->set_end(if_statement->m_then->end());
  1020. }
  1021. return if_statement;
  1022. }
  1023. Vector<StringView> Parser::parse_type_qualifiers()
  1024. {
  1025. ScopeLogger logger {};
  1026. Vector<StringView> qualifiers;
  1027. while (!eof()) {
  1028. auto token = peek();
  1029. if (token.type() != Token::Type::Keyword)
  1030. break;
  1031. auto text = text_of_token(token);
  1032. if (text == "static" || text == "const") {
  1033. qualifiers.append(text);
  1034. consume();
  1035. } else {
  1036. break;
  1037. }
  1038. }
  1039. return qualifiers;
  1040. }
  1041. Vector<StringView> Parser::parse_function_qualifiers()
  1042. {
  1043. ScopeLogger logger {};
  1044. Vector<StringView> qualifiers;
  1045. while (!eof()) {
  1046. auto token = peek();
  1047. if (token.type() != Token::Type::Keyword)
  1048. break;
  1049. auto text = text_of_token(token);
  1050. if (text == "static" || text == "inline") {
  1051. qualifiers.append(text);
  1052. consume();
  1053. } else {
  1054. break;
  1055. }
  1056. }
  1057. return qualifiers;
  1058. }
  1059. bool Parser::match_attribute_specification()
  1060. {
  1061. return text_of_token(peek()) == "__attribute__";
  1062. }
  1063. void Parser::consume_attribute_specification()
  1064. {
  1065. consume(); // __attribute__
  1066. consume(Token::Type::LeftParen);
  1067. size_t left_count = 1;
  1068. while (!eof()) {
  1069. auto token = consume();
  1070. if (token.type() == Token::Type::LeftParen) {
  1071. ++left_count;
  1072. }
  1073. if (token.type() == Token::Type::RightParen) {
  1074. --left_count;
  1075. }
  1076. if (left_count == 0)
  1077. return;
  1078. }
  1079. }
  1080. bool Parser::match_ellipsis()
  1081. {
  1082. if (m_state.token_index > m_tokens.size() - 3)
  1083. return false;
  1084. return peek().type() == Token::Type::Dot && peek().type() == Token::Type::Dot && peek().type() == Token::Type::Dot;
  1085. }
  1086. void Parser::add_tokens_for_preprocessor(Token& replaced_token, Preprocessor::DefinedValue& definition)
  1087. {
  1088. if (!definition.value.has_value())
  1089. return;
  1090. Lexer lexer(definition.value.value());
  1091. for (auto token : lexer.lex()) {
  1092. if (token.type() == Token::Type::Whitespace)
  1093. continue;
  1094. token.set_start(replaced_token.start());
  1095. token.set_end(replaced_token.end());
  1096. m_tokens.append(move(token));
  1097. }
  1098. }
  1099. NonnullRefPtr<NamespaceDeclaration> Parser::parse_namespace_declaration(ASTNode& parent, bool is_nested_namespace)
  1100. {
  1101. auto namespace_decl = create_ast_node<NamespaceDeclaration>(parent, position(), {});
  1102. if (!is_nested_namespace)
  1103. consume(Token::Type::Keyword);
  1104. auto name_token = consume(Token::Type::Identifier);
  1105. namespace_decl->m_name = name_token.text();
  1106. if (peek().type() == Token::Type::ColonColon) {
  1107. consume(Token::Type::ColonColon);
  1108. namespace_decl->m_declarations.append(parse_namespace_declaration(*namespace_decl, true));
  1109. namespace_decl->set_end(position());
  1110. return namespace_decl;
  1111. }
  1112. consume(Token::Type::LeftCurly);
  1113. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1114. auto declaration = parse_single_declaration_in_translation_unit(*namespace_decl);
  1115. if (declaration) {
  1116. namespace_decl->m_declarations.append(declaration.release_nonnull());
  1117. } else {
  1118. error("unexpected token");
  1119. consume();
  1120. }
  1121. }
  1122. consume(Token::Type::RightCurly);
  1123. namespace_decl->set_end(position());
  1124. return namespace_decl;
  1125. }
  1126. bool Parser::match_name()
  1127. {
  1128. auto type = peek().type();
  1129. return type == Token::Type::Identifier || type == Token::Type::KnownType;
  1130. }
  1131. NonnullRefPtr<Name> Parser::parse_name(ASTNode& parent)
  1132. {
  1133. NonnullRefPtr<Name> name_node = create_ast_node<Name>(parent, position(), {});
  1134. while (!eof() && (peek().type() == Token::Type::Identifier || peek().type() == Token::Type::KnownType)) {
  1135. auto token = consume();
  1136. name_node->m_scope.append(create_ast_node<Identifier>(*name_node, token.start(), token.end(), token.text()));
  1137. if (peek().type() == Token::Type::ColonColon)
  1138. consume();
  1139. else
  1140. break;
  1141. }
  1142. VERIFY(!name_node->m_scope.is_empty());
  1143. name_node->m_name = name_node->m_scope.take_last();
  1144. if (match_template_arguments()) {
  1145. consume(Token::Type::Less);
  1146. NonnullRefPtr<TemplatizedName> templatized_name = create_ast_node<TemplatizedName>(parent, name_node->start(), {});
  1147. templatized_name->m_name = move(name_node->m_name);
  1148. templatized_name->m_scope = move(name_node->m_scope);
  1149. name_node->set_end(position());
  1150. name_node = templatized_name;
  1151. while (peek().type() != Token::Type::Greater && !eof()) {
  1152. templatized_name->m_template_arguments.append(parse_type(*templatized_name));
  1153. if (peek().type() == Token::Type::Comma)
  1154. consume(Token::Type::Comma);
  1155. }
  1156. consume(Token::Type::Greater);
  1157. }
  1158. name_node->set_end(position());
  1159. return name_node;
  1160. }
  1161. bool Parser::match_cpp_cast_expression()
  1162. {
  1163. save_state();
  1164. ScopeGuard state_guard = [this] { load_state(); };
  1165. auto token = consume();
  1166. if (token.type() != Token::Type::Keyword)
  1167. return false;
  1168. auto text = token.text();
  1169. if (text == "static_cast" || text == "reinterpret_cast" || text == "dynamic_cast" || text == "const_cast")
  1170. return true;
  1171. return false;
  1172. }
  1173. bool Parser::match_c_style_cast_expression()
  1174. {
  1175. save_state();
  1176. ScopeGuard state_guard = [this] { load_state(); };
  1177. if (consume().type() != Token::Type::LeftParen)
  1178. return false;
  1179. if (!match_type())
  1180. return false;
  1181. parse_type(get_dummy_node());
  1182. if (consume().type() != Token::Type::RightParen)
  1183. return false;
  1184. if (!match_expression())
  1185. return false;
  1186. return true;
  1187. }
  1188. NonnullRefPtr<CStyleCastExpression> Parser::parse_c_style_cast_expression(ASTNode& parent)
  1189. {
  1190. auto parse_exp = create_ast_node<CStyleCastExpression>(parent, position(), {});
  1191. consume(Token::Type::LeftParen);
  1192. parse_exp->m_type = parse_type(*parse_exp);
  1193. consume(Token::Type::RightParen);
  1194. parse_exp->m_expression = parse_expression(*parse_exp);
  1195. parse_exp->set_end(position());
  1196. return parse_exp;
  1197. }
  1198. NonnullRefPtr<CppCastExpression> Parser::parse_cpp_cast_expression(ASTNode& parent)
  1199. {
  1200. auto cast_expression = create_ast_node<CppCastExpression>(parent, position(), {});
  1201. cast_expression->m_cast_type = consume(Token::Type::Keyword).text();
  1202. consume(Token::Type::Less);
  1203. cast_expression->m_type = parse_type(*cast_expression);
  1204. consume(Token::Type::Greater);
  1205. consume(Token::Type::LeftParen);
  1206. cast_expression->m_expression = parse_expression(*cast_expression);
  1207. consume(Token::Type::RightParen);
  1208. cast_expression->set_end(position());
  1209. return cast_expression;
  1210. }
  1211. bool Parser::match_sizeof_expression()
  1212. {
  1213. return match_keyword("sizeof");
  1214. }
  1215. NonnullRefPtr<SizeofExpression> Parser::parse_sizeof_expression(ASTNode& parent)
  1216. {
  1217. auto exp = create_ast_node<SizeofExpression>(parent, position(), {});
  1218. consume(Token::Type::Keyword);
  1219. consume(Token::Type::LeftParen);
  1220. exp->m_type = parse_type(parent);
  1221. consume(Token::Type::RightParen);
  1222. exp->set_end(position());
  1223. return exp;
  1224. }
  1225. bool Parser::match_braced_init_list()
  1226. {
  1227. return match(Token::Type::LeftCurly);
  1228. }
  1229. NonnullRefPtr<BracedInitList> Parser::parse_braced_init_list(ASTNode& parent)
  1230. {
  1231. auto init_list = create_ast_node<BracedInitList>(parent, position(), {});
  1232. consume(Token::Type::LeftCurly);
  1233. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1234. init_list->m_expressions.append(parse_expression(*init_list));
  1235. }
  1236. consume(Token::Type::RightCurly);
  1237. init_list->set_end(position());
  1238. return init_list;
  1239. }
  1240. }