Parser.cpp 42 KB

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