Parser.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  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(*m_root_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(*m_root_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(*m_root_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. exp->m_property = parse_expression(*exp);
  525. exp->set_end(position());
  526. return exp;
  527. }
  528. default: {
  529. error(String::formatted("unexpected operator for expression. operator: {}", peek().to_string()));
  530. auto token = consume();
  531. return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
  532. }
  533. }
  534. }
  535. NonnullRefPtr<BinaryExpression> Parser::parse_binary_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs, BinaryOp op)
  536. {
  537. consume(); // Operator
  538. auto exp = create_ast_node<BinaryExpression>(parent, lhs->start(), {});
  539. lhs->set_parent(*exp);
  540. exp->m_op = op;
  541. exp->m_lhs = move(lhs);
  542. auto rhs = parse_expression(exp);
  543. exp->set_end(rhs->end());
  544. exp->m_rhs = move(rhs);
  545. return exp;
  546. }
  547. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs, AssignmentOp op)
  548. {
  549. consume(); // Operator
  550. auto exp = create_ast_node<AssignmentExpression>(parent, lhs->start(), {});
  551. lhs->set_parent(*exp);
  552. exp->m_op = op;
  553. exp->m_lhs = move(lhs);
  554. auto rhs = parse_expression(exp);
  555. exp->set_end(rhs->end());
  556. exp->m_rhs = move(rhs);
  557. return exp;
  558. }
  559. Optional<Parser::DeclarationType> Parser::match_declaration_in_translation_unit()
  560. {
  561. if (match_function_declaration())
  562. return DeclarationType::Function;
  563. if (match_enum_declaration())
  564. return DeclarationType::Enum;
  565. if (match_struct_declaration())
  566. return DeclarationType::Struct;
  567. if (match_namespace_declaration())
  568. return DeclarationType::Namespace;
  569. if (match_variable_declaration())
  570. return DeclarationType::Variable;
  571. return {};
  572. }
  573. bool Parser::match_enum_declaration()
  574. {
  575. return match_keyword("enum");
  576. }
  577. bool Parser::match_struct_declaration()
  578. {
  579. return match_keyword("struct");
  580. }
  581. bool Parser::match_namespace_declaration()
  582. {
  583. return match_keyword("namespace");
  584. }
  585. bool Parser::match_function_declaration()
  586. {
  587. save_state();
  588. ScopeGuard state_guard = [this] { load_state(); };
  589. parse_function_qualifiers();
  590. if (match_type() == TemplatizedMatchResult::NoMatch)
  591. return false;
  592. VERIFY(m_root_node);
  593. parse_type(*m_root_node);
  594. if (!peek(Token::Type::Identifier).has_value())
  595. return false;
  596. consume();
  597. if (!peek(Token::Type::LeftParen).has_value())
  598. return false;
  599. consume();
  600. while (consume().type() != Token::Type::RightParen && !eof()) { };
  601. if (peek(Token::Type::Semicolon).has_value() || peek(Token::Type::LeftCurly).has_value())
  602. return true;
  603. if (match_attribute_specification()) {
  604. consume_attribute_specification();
  605. return peek(Token::Type::Semicolon).has_value();
  606. }
  607. return false;
  608. }
  609. Optional<NonnullRefPtrVector<Parameter>> Parser::parse_parameter_list(ASTNode& parent)
  610. {
  611. SCOPE_LOGGER();
  612. NonnullRefPtrVector<Parameter> parameters;
  613. while (peek().type() != Token::Type::RightParen && !eof()) {
  614. if (match_ellipsis()) {
  615. auto last_dot = consume();
  616. while (peek().type() == Token::Type::Dot)
  617. last_dot = consume();
  618. auto param = create_ast_node<Parameter>(parent, position(), last_dot.end(), StringView {});
  619. param->m_is_ellipsis = true;
  620. parameters.append(move(param));
  621. } else {
  622. auto type = parse_type(parent);
  623. auto name_identifier = peek(Token::Type::Identifier);
  624. if (name_identifier.has_value())
  625. consume(Token::Type::Identifier);
  626. StringView name;
  627. if (name_identifier.has_value())
  628. name = text_of_token(name_identifier.value());
  629. auto param = create_ast_node<Parameter>(parent, type->start(), name_identifier.has_value() ? name_identifier.value().end() : type->end(), name);
  630. param->m_type = move(type);
  631. parameters.append(move(param));
  632. }
  633. if (peek(Token::Type::Comma).has_value())
  634. consume(Token::Type::Comma);
  635. }
  636. return parameters;
  637. }
  638. bool Parser::match_comment()
  639. {
  640. return match(Token::Type::Comment);
  641. }
  642. bool Parser::match_whitespace()
  643. {
  644. return match(Token::Type::Whitespace);
  645. }
  646. bool Parser::match_preprocessor()
  647. {
  648. return match(Token::Type::PreprocessorStatement) || match(Token::Type::IncludeStatement);
  649. }
  650. void Parser::consume_preprocessor()
  651. {
  652. SCOPE_LOGGER();
  653. switch (peek().type()) {
  654. case Token::Type::PreprocessorStatement:
  655. consume();
  656. break;
  657. case Token::Type::IncludeStatement:
  658. consume();
  659. consume(Token::Type::IncludePath);
  660. break;
  661. default:
  662. error("unexpected token while parsing preprocessor statement");
  663. consume();
  664. }
  665. }
  666. Optional<Token> Parser::consume_whitespace()
  667. {
  668. SCOPE_LOGGER();
  669. return consume(Token::Type::Whitespace);
  670. }
  671. Token Parser::consume(Token::Type type)
  672. {
  673. auto token = consume();
  674. if (token.type() != type)
  675. error(String::formatted("expected {} at {}:{}, found: {}", Token::type_to_string(type), token.start().line, token.start().column, Token::type_to_string(token.type())));
  676. return token;
  677. }
  678. bool Parser::match(Token::Type type)
  679. {
  680. return peek().type() == type;
  681. }
  682. Token Parser::consume()
  683. {
  684. if (eof()) {
  685. error("C++ Parser: out of tokens");
  686. return { Token::Type::EOF_TOKEN, position(), position(), {} };
  687. }
  688. return m_tokens[m_state.token_index++];
  689. }
  690. Token Parser::peek(size_t offset) const
  691. {
  692. if (m_state.token_index + offset >= m_tokens.size())
  693. return { Token::Type::EOF_TOKEN, position(), position(), {} };
  694. return m_tokens[m_state.token_index + offset];
  695. }
  696. Optional<Token> Parser::peek(Token::Type type) const
  697. {
  698. auto token = peek();
  699. if (token.type() == type)
  700. return token;
  701. return {};
  702. }
  703. void Parser::save_state()
  704. {
  705. m_saved_states.append(m_state);
  706. }
  707. void Parser::load_state()
  708. {
  709. m_state = m_saved_states.take_last();
  710. }
  711. StringView Parser::text_of_token(const Cpp::Token& token) const
  712. {
  713. return token.text();
  714. }
  715. String Parser::text_of_node(const ASTNode& node) const
  716. {
  717. return text_in_range(node.start(), node.end());
  718. }
  719. String Parser::text_in_range(Position start, Position end) const
  720. {
  721. auto start_token_index = index_of_token_at(start);
  722. auto end_node_index = index_of_token_at(end);
  723. VERIFY(start_token_index.has_value());
  724. VERIFY(end_node_index.has_value());
  725. StringBuilder text;
  726. for (size_t i = start_token_index.value(); i <= end_node_index.value(); ++i) {
  727. text.append(m_tokens[i].text());
  728. }
  729. return text.build();
  730. }
  731. void Parser::error(StringView message)
  732. {
  733. SCOPE_LOGGER();
  734. if (message.is_null() || message.is_empty())
  735. message = "<empty>";
  736. String formatted_message;
  737. if (m_state.token_index >= m_tokens.size()) {
  738. formatted_message = String::formatted("C++ Parsed error on EOF.{}", message);
  739. } else {
  740. formatted_message = String::formatted("C++ Parser error: {}. token: {} ({}:{})",
  741. message,
  742. m_state.token_index < m_tokens.size() ? text_of_token(m_tokens[m_state.token_index]) : "EOF",
  743. m_tokens[m_state.token_index].start().line,
  744. m_tokens[m_state.token_index].start().column);
  745. }
  746. m_state.errors.append(formatted_message);
  747. }
  748. bool Parser::match_expression()
  749. {
  750. auto token_type = peek().type();
  751. return match_literal()
  752. || token_type == Token::Type::Identifier
  753. || match_unary_expression()
  754. || match_cpp_cast_expression()
  755. || match_c_style_cast_expression()
  756. || match_sizeof_expression()
  757. || match_braced_init_list();
  758. }
  759. bool Parser::eof() const
  760. {
  761. return m_state.token_index >= m_tokens.size();
  762. }
  763. Position Parser::position() const
  764. {
  765. if (eof())
  766. return m_tokens.last().end();
  767. return peek().start();
  768. }
  769. RefPtr<ASTNode> Parser::eof_node() const
  770. {
  771. VERIFY(m_tokens.size());
  772. return node_at(m_tokens.last().end());
  773. }
  774. RefPtr<ASTNode> Parser::node_at(Position pos) const
  775. {
  776. auto index = index_of_node_at(pos);
  777. if (!index.has_value())
  778. return nullptr;
  779. return m_nodes[index.value()];
  780. }
  781. Optional<size_t> Parser::index_of_node_at(Position pos) const
  782. {
  783. VERIFY(!m_tokens.is_empty());
  784. Optional<size_t> match_node_index;
  785. auto node_span = [](const ASTNode& node) {
  786. VERIFY(node.end().line >= node.start().line);
  787. VERIFY((node.end().line > node.start().line) || (node.end().column >= node.start().column));
  788. return Position { node.end().line - node.start().line, node.start().line != node.end().line ? 0 : node.end().column - node.start().column };
  789. };
  790. for (size_t node_index = 0; node_index < m_nodes.size(); ++node_index) {
  791. auto& node = m_nodes[node_index];
  792. if (node.start() > pos || node.end() < pos)
  793. continue;
  794. if (!match_node_index.has_value() || (node_span(node) < node_span(m_nodes[match_node_index.value()])))
  795. match_node_index = node_index;
  796. }
  797. return match_node_index;
  798. }
  799. Optional<Token> Parser::token_at(Position pos) const
  800. {
  801. auto index = index_of_token_at(pos);
  802. if (!index.has_value())
  803. return {};
  804. return m_tokens[index.value()];
  805. }
  806. Optional<size_t> Parser::index_of_token_at(Position pos) const
  807. {
  808. for (size_t token_index = 0; token_index < m_tokens.size(); ++token_index) {
  809. auto token = m_tokens[token_index];
  810. if (token.start() > pos || token.end() < pos)
  811. continue;
  812. return token_index;
  813. }
  814. return {};
  815. }
  816. void Parser::print_tokens() const
  817. {
  818. for (auto& token : m_tokens) {
  819. dbgln("{}", token.to_string());
  820. }
  821. }
  822. Parser::TemplatizedMatchResult Parser::match_function_call()
  823. {
  824. save_state();
  825. ScopeGuard state_guard = [this] { load_state(); };
  826. if (!match_name())
  827. return TemplatizedMatchResult::NoMatch;
  828. parse_name(*m_root_node);
  829. bool is_templatized = false;
  830. if (match_template_arguments()) {
  831. is_templatized = true;
  832. parse_template_arguments(*m_root_node);
  833. }
  834. if (!match(Token::Type::LeftParen))
  835. return TemplatizedMatchResult::NoMatch;
  836. return is_templatized ? TemplatizedMatchResult::Templatized : TemplatizedMatchResult::Regular;
  837. }
  838. NonnullRefPtr<FunctionCall> Parser::parse_function_call(ASTNode& parent)
  839. {
  840. SCOPE_LOGGER();
  841. auto match_result = match_type();
  842. if (match_result == TemplatizedMatchResult::NoMatch) {
  843. error("expected type");
  844. return create_ast_node<FunctionCall>(parent, position(), position());
  845. }
  846. bool is_templatized = match_result == TemplatizedMatchResult::Templatized;
  847. RefPtr<FunctionCall> call;
  848. if (is_templatized) {
  849. call = create_ast_node<TemplatizedFunctionCall>(parent, position(), {});
  850. } else {
  851. call = create_ast_node<FunctionCall>(parent, position(), {});
  852. }
  853. call->m_name = parse_name(*call);
  854. if (is_templatized) {
  855. static_cast<TemplatizedFunctionCall&>(*call).m_template_arguments = parse_template_arguments(*call);
  856. }
  857. NonnullRefPtrVector<Expression> args;
  858. consume(Token::Type::LeftParen);
  859. while (peek().type() != Token::Type::RightParen && !eof()) {
  860. args.append(parse_expression(*call));
  861. if (peek().type() == Token::Type::Comma)
  862. consume(Token::Type::Comma);
  863. }
  864. consume(Token::Type::RightParen);
  865. call->m_arguments = move(args);
  866. call->set_end(position());
  867. return call.release_nonnull();
  868. }
  869. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(ASTNode& parent)
  870. {
  871. SCOPE_LOGGER();
  872. Optional<size_t> start_token_index;
  873. Optional<size_t> end_token_index;
  874. while (!eof()) {
  875. auto token = peek();
  876. if (token.type() != Token::Type::DoubleQuotedString && token.type() != Token::Type::SingleQuotedString && token.type() != Token::Type::EscapeSequence) {
  877. VERIFY(start_token_index.has_value());
  878. end_token_index = m_state.token_index - 1;
  879. break;
  880. }
  881. if (!start_token_index.has_value())
  882. start_token_index = m_state.token_index;
  883. consume();
  884. }
  885. // String was not terminated
  886. if (!end_token_index.has_value()) {
  887. end_token_index = m_tokens.size() - 1;
  888. }
  889. VERIFY(start_token_index.has_value());
  890. VERIFY(end_token_index.has_value());
  891. Token start_token = m_tokens[start_token_index.value()];
  892. Token end_token = m_tokens[end_token_index.value()];
  893. auto text = text_in_range(start_token.start(), end_token.end());
  894. auto string_literal = create_ast_node<StringLiteral>(parent, start_token.start(), end_token.end());
  895. string_literal->m_value = text;
  896. return string_literal;
  897. }
  898. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement(ASTNode& parent)
  899. {
  900. SCOPE_LOGGER();
  901. auto return_statement = create_ast_node<ReturnStatement>(parent, position(), {});
  902. consume(Token::Type::Keyword);
  903. if (!peek(Token::Type::Semicolon).has_value()) {
  904. auto expression = parse_expression(*return_statement);
  905. return_statement->m_value = expression;
  906. }
  907. return_statement->set_end(position());
  908. return return_statement;
  909. }
  910. NonnullRefPtr<EnumDeclaration> Parser::parse_enum_declaration(ASTNode& parent)
  911. {
  912. SCOPE_LOGGER();
  913. auto enum_decl = create_ast_node<EnumDeclaration>(parent, position(), {});
  914. consume_keyword("enum");
  915. auto name_token = consume(Token::Type::Identifier);
  916. enum_decl->m_name = text_of_token(name_token);
  917. consume(Token::Type::LeftCurly);
  918. while (!eof() && peek().type() != Token::Type::RightCurly) {
  919. enum_decl->m_entries.append(text_of_token(consume(Token::Type::Identifier)));
  920. if (peek().type() != Token::Type::Comma) {
  921. break;
  922. }
  923. consume(Token::Type::Comma);
  924. }
  925. consume(Token::Type::RightCurly);
  926. consume(Token::Type::Semicolon);
  927. enum_decl->set_end(position());
  928. return enum_decl;
  929. }
  930. Token Parser::consume_keyword(const String& keyword)
  931. {
  932. auto token = consume();
  933. if (token.type() != Token::Type::Keyword) {
  934. error(String::formatted("unexpected token: {}, expected Keyword", token.to_string()));
  935. return token;
  936. }
  937. if (text_of_token(token) != keyword) {
  938. error(String::formatted("unexpected keyword: {}, expected {}", text_of_token(token), keyword));
  939. return token;
  940. }
  941. return token;
  942. }
  943. bool Parser::match_keyword(const String& keyword)
  944. {
  945. auto token = peek();
  946. if (token.type() != Token::Type::Keyword) {
  947. return false;
  948. }
  949. if (text_of_token(token) != keyword) {
  950. return false;
  951. }
  952. return true;
  953. }
  954. NonnullRefPtr<StructOrClassDeclaration> Parser::parse_struct_or_class_declaration(ASTNode& parent, StructOrClassDeclaration::Type type)
  955. {
  956. SCOPE_LOGGER();
  957. auto decl = create_ast_node<StructOrClassDeclaration>(parent, position(), {}, type);
  958. switch (type) {
  959. case StructOrClassDeclaration::Type::Struct:
  960. consume_keyword("struct");
  961. break;
  962. case StructOrClassDeclaration::Type::Class:
  963. consume_keyword("class");
  964. break;
  965. }
  966. auto name_token = consume(Token::Type::Identifier);
  967. decl->m_name = text_of_token(name_token);
  968. consume(Token::Type::LeftCurly);
  969. while (!eof() && peek().type() != Token::Type::RightCurly) {
  970. decl->m_members.append(parse_member_declaration(*decl));
  971. }
  972. consume(Token::Type::RightCurly);
  973. consume(Token::Type::Semicolon);
  974. decl->set_end(position());
  975. return decl;
  976. }
  977. NonnullRefPtr<MemberDeclaration> Parser::parse_member_declaration(ASTNode& parent)
  978. {
  979. SCOPE_LOGGER();
  980. auto member_decl = create_ast_node<MemberDeclaration>(parent, position(), {});
  981. member_decl->m_type = parse_type(*member_decl);
  982. auto identifier_token = consume(Token::Type::Identifier);
  983. member_decl->m_name = text_of_token(identifier_token);
  984. if (match_braced_init_list()) {
  985. member_decl->m_initial_value = parse_braced_init_list(*member_decl);
  986. }
  987. consume(Token::Type::Semicolon);
  988. member_decl->set_end(position());
  989. return member_decl;
  990. }
  991. NonnullRefPtr<BooleanLiteral> Parser::parse_boolean_literal(ASTNode& parent)
  992. {
  993. SCOPE_LOGGER();
  994. auto token = consume(Token::Type::Keyword);
  995. auto text = text_of_token(token);
  996. // text == "true" || text == "false";
  997. bool value = (text == "true");
  998. return create_ast_node<BooleanLiteral>(parent, token.start(), token.end(), value);
  999. }
  1000. bool Parser::match_boolean_literal()
  1001. {
  1002. auto token = peek();
  1003. if (token.type() != Token::Type::Keyword)
  1004. return false;
  1005. auto text = text_of_token(token);
  1006. return text == "true" || text == "false";
  1007. }
  1008. NonnullRefPtr<Type> Parser::parse_type(ASTNode& parent)
  1009. {
  1010. SCOPE_LOGGER();
  1011. auto match_result = match_type();
  1012. if (match_result == TemplatizedMatchResult::NoMatch) {
  1013. auto token = consume();
  1014. return create_ast_node<Type>(parent, token.start(), token.end());
  1015. }
  1016. bool is_templatized = match_result == TemplatizedMatchResult::Templatized;
  1017. RefPtr<Type> type;
  1018. if (is_templatized) {
  1019. type = create_ast_node<TemplatizedType>(parent, position(), {});
  1020. } else {
  1021. type = create_ast_node<Type>(parent, position(), {});
  1022. }
  1023. auto qualifiers = parse_type_qualifiers();
  1024. type->m_qualifiers = move(qualifiers);
  1025. if (match_keyword("struct")) {
  1026. consume(Token::Type::Keyword); // Consume struct prefix
  1027. }
  1028. if (!match_name()) {
  1029. type->set_end(position());
  1030. error(String::formatted("expected name instead of: {}", peek().text()));
  1031. return type.release_nonnull();
  1032. }
  1033. type->m_name = parse_name(*type);
  1034. if (is_templatized) {
  1035. static_cast<TemplatizedType&>(*type).m_template_arguments = parse_template_arguments(*type);
  1036. }
  1037. while (!eof() && peek().type() == Token::Type::Asterisk) {
  1038. type->set_end(position());
  1039. auto asterisk = consume();
  1040. auto ptr = create_ast_node<Pointer>(parent, asterisk.start(), asterisk.end());
  1041. type->set_parent(*ptr);
  1042. ptr->m_pointee = type;
  1043. type = ptr;
  1044. }
  1045. type->set_end(position());
  1046. return type.release_nonnull();
  1047. }
  1048. NonnullRefPtr<ForStatement> Parser::parse_for_statement(ASTNode& parent)
  1049. {
  1050. SCOPE_LOGGER();
  1051. auto for_statement = create_ast_node<ForStatement>(parent, position(), {});
  1052. consume(Token::Type::Keyword);
  1053. consume(Token::Type::LeftParen);
  1054. if (peek().type() != Token::Type::Semicolon)
  1055. for_statement->m_init = parse_variable_declaration(*for_statement, false);
  1056. consume(Token::Type::Semicolon);
  1057. if (peek().type() != Token::Type::Semicolon)
  1058. for_statement->m_test = parse_expression(*for_statement);
  1059. consume(Token::Type::Semicolon);
  1060. if (peek().type() != Token::Type::RightParen)
  1061. for_statement->m_update = parse_expression(*for_statement);
  1062. consume(Token::Type::RightParen);
  1063. for_statement->m_body = parse_statement(*for_statement);
  1064. for_statement->set_end(for_statement->m_body->end());
  1065. return for_statement;
  1066. }
  1067. NonnullRefPtr<IfStatement> Parser::parse_if_statement(ASTNode& parent)
  1068. {
  1069. SCOPE_LOGGER();
  1070. auto if_statement = create_ast_node<IfStatement>(parent, position(), {});
  1071. consume(Token::Type::Keyword);
  1072. consume(Token::Type::LeftParen);
  1073. if_statement->m_predicate = parse_expression(*if_statement);
  1074. consume(Token::Type::RightParen);
  1075. if_statement->m_then = parse_statement(*if_statement);
  1076. if (match_keyword("else")) {
  1077. consume(Token::Type::Keyword);
  1078. if_statement->m_else = parse_statement(*if_statement);
  1079. if_statement->set_end(if_statement->m_else->end());
  1080. } else {
  1081. if_statement->set_end(if_statement->m_then->end());
  1082. }
  1083. return if_statement;
  1084. }
  1085. Vector<StringView> Parser::parse_type_qualifiers()
  1086. {
  1087. SCOPE_LOGGER();
  1088. Vector<StringView> qualifiers;
  1089. while (!eof()) {
  1090. auto token = peek();
  1091. if (token.type() != Token::Type::Keyword)
  1092. break;
  1093. auto text = text_of_token(token);
  1094. if (text == "static" || text == "const") {
  1095. qualifiers.append(text);
  1096. consume();
  1097. } else {
  1098. break;
  1099. }
  1100. }
  1101. return qualifiers;
  1102. }
  1103. Vector<StringView> Parser::parse_function_qualifiers()
  1104. {
  1105. SCOPE_LOGGER();
  1106. Vector<StringView> qualifiers;
  1107. while (!eof()) {
  1108. auto token = peek();
  1109. if (token.type() != Token::Type::Keyword)
  1110. break;
  1111. auto text = text_of_token(token);
  1112. if (text == "static" || text == "inline") {
  1113. qualifiers.append(text);
  1114. consume();
  1115. } else {
  1116. break;
  1117. }
  1118. }
  1119. return qualifiers;
  1120. }
  1121. bool Parser::match_attribute_specification()
  1122. {
  1123. return text_of_token(peek()) == "__attribute__";
  1124. }
  1125. void Parser::consume_attribute_specification()
  1126. {
  1127. consume(); // __attribute__
  1128. consume(Token::Type::LeftParen);
  1129. size_t left_count = 1;
  1130. while (!eof()) {
  1131. auto token = consume();
  1132. if (token.type() == Token::Type::LeftParen) {
  1133. ++left_count;
  1134. }
  1135. if (token.type() == Token::Type::RightParen) {
  1136. --left_count;
  1137. }
  1138. if (left_count == 0)
  1139. return;
  1140. }
  1141. }
  1142. bool Parser::match_ellipsis()
  1143. {
  1144. if (m_state.token_index > m_tokens.size() - 3)
  1145. return false;
  1146. return peek().type() == Token::Type::Dot && peek().type() == Token::Type::Dot && peek().type() == Token::Type::Dot;
  1147. }
  1148. void Parser::add_tokens_for_preprocessor(Token& replaced_token, Preprocessor::DefinedValue& definition)
  1149. {
  1150. if (!definition.value.has_value())
  1151. return;
  1152. Lexer lexer(definition.value.value());
  1153. for (auto token : lexer.lex()) {
  1154. if (token.type() == Token::Type::Whitespace)
  1155. continue;
  1156. token.set_start(replaced_token.start());
  1157. token.set_end(replaced_token.end());
  1158. m_tokens.append(move(token));
  1159. }
  1160. }
  1161. NonnullRefPtr<NamespaceDeclaration> Parser::parse_namespace_declaration(ASTNode& parent, bool is_nested_namespace)
  1162. {
  1163. auto namespace_decl = create_ast_node<NamespaceDeclaration>(parent, position(), {});
  1164. if (!is_nested_namespace)
  1165. consume(Token::Type::Keyword);
  1166. auto name_token = consume(Token::Type::Identifier);
  1167. namespace_decl->m_name = name_token.text();
  1168. if (peek().type() == Token::Type::ColonColon) {
  1169. consume(Token::Type::ColonColon);
  1170. namespace_decl->m_declarations.append(parse_namespace_declaration(*namespace_decl, true));
  1171. namespace_decl->set_end(position());
  1172. return namespace_decl;
  1173. }
  1174. consume(Token::Type::LeftCurly);
  1175. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1176. auto declaration = parse_single_declaration_in_translation_unit(*namespace_decl);
  1177. if (declaration) {
  1178. namespace_decl->m_declarations.append(declaration.release_nonnull());
  1179. } else {
  1180. error("unexpected token");
  1181. consume();
  1182. }
  1183. }
  1184. consume(Token::Type::RightCurly);
  1185. namespace_decl->set_end(position());
  1186. return namespace_decl;
  1187. }
  1188. bool Parser::match_name()
  1189. {
  1190. auto type = peek().type();
  1191. return type == Token::Type::Identifier || type == Token::Type::KnownType;
  1192. }
  1193. NonnullRefPtr<Name> Parser::parse_name(ASTNode& parent)
  1194. {
  1195. auto name_node = create_ast_node<Name>(parent, position(), {});
  1196. while (!eof() && (peek().type() == Token::Type::Identifier || peek().type() == Token::Type::KnownType)) {
  1197. auto token = consume();
  1198. name_node->m_scope.append(create_ast_node<Identifier>(*name_node, token.start(), token.end(), token.text()));
  1199. if (peek().type() == Token::Type::ColonColon)
  1200. consume();
  1201. else
  1202. break;
  1203. }
  1204. VERIFY(!name_node->m_scope.is_empty());
  1205. name_node->m_name = name_node->m_scope.take_last();
  1206. name_node->set_end(position());
  1207. return name_node;
  1208. }
  1209. bool Parser::match_cpp_cast_expression()
  1210. {
  1211. save_state();
  1212. ScopeGuard state_guard = [this] { load_state(); };
  1213. auto token = consume();
  1214. if (token.type() != Token::Type::Keyword)
  1215. return false;
  1216. auto text = token.text();
  1217. if (text == "static_cast" || text == "reinterpret_cast" || text == "dynamic_cast" || text == "const_cast")
  1218. return true;
  1219. return false;
  1220. }
  1221. bool Parser::match_c_style_cast_expression()
  1222. {
  1223. save_state();
  1224. ScopeGuard state_guard = [this] { load_state(); };
  1225. if (consume().type() != Token::Type::LeftParen)
  1226. return false;
  1227. if (match_type() == TemplatizedMatchResult::NoMatch)
  1228. return false;
  1229. parse_type(*m_root_node);
  1230. if (consume().type() != Token::Type::RightParen)
  1231. return false;
  1232. if (!match_expression())
  1233. return false;
  1234. return true;
  1235. }
  1236. NonnullRefPtr<CStyleCastExpression> Parser::parse_c_style_cast_expression(ASTNode& parent)
  1237. {
  1238. auto parse_exp = create_ast_node<CStyleCastExpression>(parent, position(), {});
  1239. consume(Token::Type::LeftParen);
  1240. parse_exp->m_type = parse_type(*parse_exp);
  1241. consume(Token::Type::RightParen);
  1242. parse_exp->m_expression = parse_expression(*parse_exp);
  1243. parse_exp->set_end(position());
  1244. return parse_exp;
  1245. }
  1246. NonnullRefPtr<CppCastExpression> Parser::parse_cpp_cast_expression(ASTNode& parent)
  1247. {
  1248. auto cast_expression = create_ast_node<CppCastExpression>(parent, position(), {});
  1249. cast_expression->m_cast_type = consume(Token::Type::Keyword).text();
  1250. consume(Token::Type::Less);
  1251. cast_expression->m_type = parse_type(*cast_expression);
  1252. consume(Token::Type::Greater);
  1253. consume(Token::Type::LeftParen);
  1254. cast_expression->m_expression = parse_expression(*cast_expression);
  1255. consume(Token::Type::RightParen);
  1256. cast_expression->set_end(position());
  1257. return cast_expression;
  1258. }
  1259. bool Parser::match_sizeof_expression()
  1260. {
  1261. return match_keyword("sizeof");
  1262. }
  1263. NonnullRefPtr<SizeofExpression> Parser::parse_sizeof_expression(ASTNode& parent)
  1264. {
  1265. auto exp = create_ast_node<SizeofExpression>(parent, position(), {});
  1266. consume(Token::Type::Keyword);
  1267. consume(Token::Type::LeftParen);
  1268. exp->m_type = parse_type(parent);
  1269. consume(Token::Type::RightParen);
  1270. exp->set_end(position());
  1271. return exp;
  1272. }
  1273. bool Parser::match_braced_init_list()
  1274. {
  1275. return match(Token::Type::LeftCurly);
  1276. }
  1277. NonnullRefPtr<BracedInitList> Parser::parse_braced_init_list(ASTNode& parent)
  1278. {
  1279. auto init_list = create_ast_node<BracedInitList>(parent, position(), {});
  1280. consume(Token::Type::LeftCurly);
  1281. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1282. init_list->m_expressions.append(parse_expression(*init_list));
  1283. }
  1284. consume(Token::Type::RightCurly);
  1285. init_list->set_end(position());
  1286. return init_list;
  1287. }
  1288. }