Parser.cpp 48 KB

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