Parser.cpp 43 KB

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