Parser.cpp 47 KB

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