Parser.cpp 54 KB

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