Parser.cpp 51 KB

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