Parser.cpp 50 KB

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