Parser.cpp 51 KB

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