Parser.cpp 49 KB

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