Parser.cpp 51 KB

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