Parser.cpp 53 KB

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