Parser.cpp 47 KB

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