Parser.cpp 45 KB

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