Parser.cpp 50 KB

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