Parser.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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. Parser::TemplatizedMatchResult Parser::match_type()
  230. {
  231. save_state();
  232. ScopeGuard state_guard = [this] { load_state(); };
  233. parse_type_qualifiers();
  234. if (!match_name())
  235. return TemplatizedMatchResult::NoMatch;
  236. parse_name(*m_root_node);
  237. if (peek(Token::Type::Less).has_value()) {
  238. if (match_template_arguments()) {
  239. return TemplatizedMatchResult::Templatized;
  240. }
  241. return TemplatizedMatchResult::NoMatch;
  242. }
  243. return TemplatizedMatchResult::Regular;
  244. }
  245. bool Parser::match_template_arguments()
  246. {
  247. save_state();
  248. ScopeGuard state_guard = [this] { load_state(); };
  249. if (!peek(Token::Type::Less).has_value())
  250. return false;
  251. consume();
  252. while (!eof() && peek().type() != Token::Type::Greater) {
  253. if (match_type() == TemplatizedMatchResult::NoMatch)
  254. return false;
  255. parse_type(*m_root_node);
  256. }
  257. return peek().type() == Token::Type::Greater;
  258. }
  259. NonnullRefPtrVector<Type> Parser::parse_template_arguments(ASTNode& parent)
  260. {
  261. SCOPE_LOGGER();
  262. consume(Token::Type::Less);
  263. NonnullRefPtrVector<Type> template_arguments;
  264. while (!eof() && peek().type() != Token::Type::Greater) {
  265. template_arguments.append(parse_type(parent));
  266. }
  267. consume(Token::Type::Greater);
  268. return template_arguments;
  269. }
  270. bool Parser::match_variable_declaration()
  271. {
  272. SCOPE_LOGGER();
  273. save_state();
  274. ScopeGuard state_guard = [this] { load_state(); };
  275. if (match_type() == TemplatizedMatchResult::NoMatch) {
  276. return false;
  277. }
  278. VERIFY(m_root_node);
  279. parse_type(*m_root_node);
  280. // Identifier
  281. if (!peek(Token::Type::Identifier).has_value()) {
  282. return false;
  283. }
  284. consume();
  285. if (match(Token::Type::Equals)) {
  286. consume(Token::Type::Equals);
  287. if (!match_expression()) {
  288. error("initial value of variable is not an expression");
  289. return false;
  290. }
  291. return true;
  292. }
  293. return match(Token::Type::Semicolon);
  294. }
  295. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(ASTNode& parent, bool expect_semicolon)
  296. {
  297. SCOPE_LOGGER();
  298. auto var = create_ast_node<VariableDeclaration>(parent, position(), {});
  299. if (!match_variable_declaration()) {
  300. error("unexpected token for variable type");
  301. var->set_end(position());
  302. return var;
  303. }
  304. var->m_type = parse_type(var);
  305. auto identifier_token = consume(Token::Type::Identifier);
  306. RefPtr<Expression> initial_value;
  307. if (match(Token::Type::Equals)) {
  308. consume(Token::Type::Equals);
  309. initial_value = parse_expression(var);
  310. }
  311. if (expect_semicolon)
  312. consume(Token::Type::Semicolon);
  313. var->set_end(position());
  314. var->m_name = text_of_token(identifier_token);
  315. var->m_initial_value = move(initial_value);
  316. return var;
  317. }
  318. NonnullRefPtr<Expression> Parser::parse_expression(ASTNode& parent)
  319. {
  320. SCOPE_LOGGER();
  321. auto expression = parse_primary_expression(parent);
  322. // TODO: remove eof() logic, should still work without it
  323. if (eof() || match(Token::Type::Semicolon)) {
  324. return expression;
  325. }
  326. NonnullRefPtrVector<Expression> secondary_expressions;
  327. while (match_secondary_expression()) {
  328. // FIXME: Handle operator precedence
  329. expression = parse_secondary_expression(parent, expression);
  330. secondary_expressions.append(expression);
  331. }
  332. for (size_t i = 0; secondary_expressions.size() != 0 && i < secondary_expressions.size() - 1; ++i) {
  333. secondary_expressions[i].set_parent(secondary_expressions[i + 1]);
  334. }
  335. return expression;
  336. }
  337. bool Parser::match_secondary_expression()
  338. {
  339. auto type = peek().type();
  340. return type == Token::Type::Plus
  341. || type == Token::Type::PlusEquals
  342. || type == Token::Type::Minus
  343. || type == Token::Type::MinusEquals
  344. || type == Token::Type::Asterisk
  345. || type == Token::Type::AsteriskEquals
  346. || type == Token::Type::Percent
  347. || type == Token::Type::PercentEquals
  348. || type == Token::Type::Equals
  349. || type == Token::Type::Greater
  350. || type == Token::Type::Greater
  351. || type == Token::Type::Less
  352. || type == Token::Type::LessEquals
  353. || type == Token::Type::Dot
  354. || type == Token::Type::PlusPlus
  355. || type == Token::Type::MinusMinus
  356. || type == Token::Type::And
  357. || type == Token::Type::AndEquals
  358. || type == Token::Type::Pipe
  359. || type == Token::Type::PipeEquals
  360. || type == Token::Type::Caret
  361. || type == Token::Type::CaretEquals
  362. || type == Token::Type::LessLess
  363. || type == Token::Type::LessLessEquals
  364. || type == Token::Type::GreaterGreater
  365. || type == Token::Type::GreaterGreaterEquals
  366. || type == Token::Type::EqualsEquals
  367. || type == Token::Type::AndAnd
  368. || type == Token::Type::PipePipe
  369. || type == Token::Type::ExclamationMarkEquals;
  370. }
  371. NonnullRefPtr<Expression> Parser::parse_primary_expression(ASTNode& parent)
  372. {
  373. SCOPE_LOGGER();
  374. // TODO: remove eof() logic, should still work without it
  375. if (eof()) {
  376. auto node = create_ast_node<Identifier>(parent, position(), position());
  377. return node;
  378. }
  379. if (match_unary_expression())
  380. return parse_unary_expression(parent);
  381. if (match_literal()) {
  382. return parse_literal(parent);
  383. }
  384. if (match_cpp_cast_expression())
  385. return parse_cpp_cast_expression(parent);
  386. if (match_name()) {
  387. if (match_function_call() != TemplatizedMatchResult::NoMatch)
  388. return parse_function_call(parent);
  389. return parse_name(parent);
  390. }
  391. error("could not parse primary expression");
  392. auto token = consume();
  393. return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
  394. }
  395. bool Parser::match_literal()
  396. {
  397. switch (peek().type()) {
  398. case Token::Type::Integer:
  399. return true;
  400. case Token::Type::SingleQuotedString:
  401. return true;
  402. case Token::Type::DoubleQuotedString:
  403. return true;
  404. case Token::Type::Float:
  405. return true;
  406. case Token::Type::Keyword: {
  407. return match_boolean_literal() || peek().text() == "nullptr";
  408. }
  409. default:
  410. return false;
  411. }
  412. }
  413. bool Parser::match_unary_expression()
  414. {
  415. auto type = peek().type();
  416. return type == Token::Type::PlusPlus
  417. || type == Token::Type::MinusMinus
  418. || type == Token::Type::ExclamationMark
  419. || type == Token::Type::Tilde
  420. || type == Token::Type::Plus
  421. || type == Token::Type::Minus;
  422. }
  423. NonnullRefPtr<UnaryExpression> Parser::parse_unary_expression(ASTNode& parent)
  424. {
  425. auto unary_exp = create_ast_node<UnaryExpression>(parent, position(), {});
  426. auto op_token = consume();
  427. UnaryOp op { UnaryOp::Invalid };
  428. switch (op_token.type()) {
  429. case Token::Type::Minus:
  430. op = UnaryOp::Minus;
  431. break;
  432. case Token::Type::Plus:
  433. op = UnaryOp::Plus;
  434. break;
  435. case Token::Type::ExclamationMark:
  436. op = UnaryOp::Not;
  437. break;
  438. case Token::Type::Tilde:
  439. op = UnaryOp::BitwiseNot;
  440. break;
  441. case Token::Type::PlusPlus:
  442. op = UnaryOp::PlusPlus;
  443. break;
  444. default:
  445. break;
  446. }
  447. unary_exp->m_op = op;
  448. auto lhs = parse_expression(*unary_exp);
  449. unary_exp->m_lhs = lhs;
  450. unary_exp->set_end(lhs->end());
  451. return unary_exp;
  452. }
  453. NonnullRefPtr<Expression> Parser::parse_literal(ASTNode& parent)
  454. {
  455. switch (peek().type()) {
  456. case Token::Type::Integer: {
  457. auto token = consume();
  458. return create_ast_node<NumericLiteral>(parent, token.start(), token.end(), text_of_token(token));
  459. }
  460. case Token::Type::SingleQuotedString:
  461. [[fallthrough]];
  462. case Token::Type::DoubleQuotedString:
  463. return parse_string_literal(parent);
  464. case Token::Type::Keyword: {
  465. if (match_boolean_literal())
  466. return parse_boolean_literal(parent);
  467. if (peek().text() == "nullptr") {
  468. auto token = consume();
  469. return create_ast_node<NullPointerLiteral>(parent, token.start(), token.end());
  470. }
  471. [[fallthrough]];
  472. }
  473. default: {
  474. error("could not parse literal");
  475. auto token = consume();
  476. return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
  477. }
  478. }
  479. }
  480. NonnullRefPtr<Expression> Parser::parse_secondary_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs)
  481. {
  482. SCOPE_LOGGER();
  483. switch (peek().type()) {
  484. case Token::Type::Plus:
  485. return parse_binary_expression(parent, lhs, BinaryOp::Addition);
  486. case Token::Type::Less:
  487. return parse_binary_expression(parent, lhs, BinaryOp::LessThan);
  488. case Token::Type::EqualsEquals:
  489. return parse_binary_expression(parent, lhs, BinaryOp::EqualsEquals);
  490. case Token::Type::ExclamationMarkEquals:
  491. return parse_binary_expression(parent, lhs, BinaryOp::NotEqual);
  492. case Token::Type::Equals:
  493. return parse_assignment_expression(parent, lhs, AssignmentOp::Assignment);
  494. case Token::Type::Dot: {
  495. consume();
  496. auto exp = create_ast_node<MemberExpression>(parent, lhs->start(), {});
  497. lhs->set_parent(*exp);
  498. exp->m_object = move(lhs);
  499. exp->m_property = parse_expression(*exp);
  500. exp->set_end(position());
  501. return exp;
  502. }
  503. default: {
  504. error(String::formatted("unexpected operator for expression. operator: {}", peek().to_string()));
  505. auto token = consume();
  506. return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
  507. }
  508. }
  509. }
  510. NonnullRefPtr<BinaryExpression> Parser::parse_binary_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs, BinaryOp op)
  511. {
  512. consume(); // Operator
  513. auto exp = create_ast_node<BinaryExpression>(parent, lhs->start(), {});
  514. lhs->set_parent(*exp);
  515. exp->m_op = op;
  516. exp->m_lhs = move(lhs);
  517. auto rhs = parse_expression(exp);
  518. exp->set_end(rhs->end());
  519. exp->m_rhs = move(rhs);
  520. return exp;
  521. }
  522. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs, AssignmentOp op)
  523. {
  524. consume(); // Operator
  525. auto exp = create_ast_node<AssignmentExpression>(parent, lhs->start(), {});
  526. lhs->set_parent(*exp);
  527. exp->m_op = op;
  528. exp->m_lhs = move(lhs);
  529. auto rhs = parse_expression(exp);
  530. exp->set_end(rhs->end());
  531. exp->m_rhs = move(rhs);
  532. return exp;
  533. }
  534. Optional<Parser::DeclarationType> Parser::match_declaration_in_translation_unit()
  535. {
  536. if (match_function_declaration())
  537. return DeclarationType::Function;
  538. if (match_enum_declaration())
  539. return DeclarationType::Enum;
  540. if (match_struct_declaration())
  541. return DeclarationType::Struct;
  542. if (match_namespace_declaration())
  543. return DeclarationType::Namespace;
  544. if (match_variable_declaration())
  545. return DeclarationType::Variable;
  546. return {};
  547. }
  548. bool Parser::match_enum_declaration()
  549. {
  550. return match_keyword("enum");
  551. }
  552. bool Parser::match_struct_declaration()
  553. {
  554. return match_keyword("struct");
  555. }
  556. bool Parser::match_namespace_declaration()
  557. {
  558. return match_keyword("namespace");
  559. }
  560. bool Parser::match_function_declaration()
  561. {
  562. save_state();
  563. ScopeGuard state_guard = [this] { load_state(); };
  564. parse_function_qualifiers();
  565. if (match_type() == TemplatizedMatchResult::NoMatch)
  566. return false;
  567. VERIFY(m_root_node);
  568. parse_type(*m_root_node);
  569. if (!peek(Token::Type::Identifier).has_value())
  570. return false;
  571. consume();
  572. if (!peek(Token::Type::LeftParen).has_value())
  573. return false;
  574. consume();
  575. while (consume().type() != Token::Type::RightParen && !eof()) { };
  576. if (peek(Token::Type::Semicolon).has_value() || peek(Token::Type::LeftCurly).has_value())
  577. return true;
  578. if (match_attribute_specification()) {
  579. consume_attribute_specification();
  580. return peek(Token::Type::Semicolon).has_value();
  581. }
  582. return false;
  583. }
  584. Optional<NonnullRefPtrVector<Parameter>> Parser::parse_parameter_list(ASTNode& parent)
  585. {
  586. SCOPE_LOGGER();
  587. NonnullRefPtrVector<Parameter> parameters;
  588. while (peek().type() != Token::Type::RightParen && !eof()) {
  589. if (match_ellipsis()) {
  590. auto last_dot = consume();
  591. while (peek().type() == Token::Type::Dot)
  592. last_dot = consume();
  593. auto param = create_ast_node<Parameter>(parent, position(), last_dot.end(), StringView {});
  594. param->m_is_ellipsis = true;
  595. parameters.append(move(param));
  596. } else {
  597. auto type = parse_type(parent);
  598. auto name_identifier = peek(Token::Type::Identifier);
  599. if (name_identifier.has_value())
  600. consume(Token::Type::Identifier);
  601. StringView name;
  602. if (name_identifier.has_value())
  603. name = text_of_token(name_identifier.value());
  604. auto param = create_ast_node<Parameter>(parent, type->start(), name_identifier.has_value() ? name_identifier.value().end() : type->end(), name);
  605. param->m_type = move(type);
  606. parameters.append(move(param));
  607. }
  608. if (peek(Token::Type::Comma).has_value())
  609. consume(Token::Type::Comma);
  610. }
  611. return parameters;
  612. }
  613. bool Parser::match_comment()
  614. {
  615. return match(Token::Type::Comment);
  616. }
  617. bool Parser::match_whitespace()
  618. {
  619. return match(Token::Type::Whitespace);
  620. }
  621. bool Parser::match_preprocessor()
  622. {
  623. return match(Token::Type::PreprocessorStatement) || match(Token::Type::IncludeStatement);
  624. }
  625. void Parser::consume_preprocessor()
  626. {
  627. SCOPE_LOGGER();
  628. switch (peek().type()) {
  629. case Token::Type::PreprocessorStatement:
  630. consume();
  631. break;
  632. case Token::Type::IncludeStatement:
  633. consume();
  634. consume(Token::Type::IncludePath);
  635. break;
  636. default:
  637. error("unexpected token while parsing preprocessor statement");
  638. consume();
  639. }
  640. }
  641. Optional<Token> Parser::consume_whitespace()
  642. {
  643. SCOPE_LOGGER();
  644. return consume(Token::Type::Whitespace);
  645. }
  646. Token Parser::consume(Token::Type type)
  647. {
  648. auto token = consume();
  649. if (token.type() != type)
  650. error(String::formatted("expected {} at {}:{}, found: {}", Token::type_to_string(type), token.start().line, token.start().column, Token::type_to_string(token.type())));
  651. return token;
  652. }
  653. bool Parser::match(Token::Type type)
  654. {
  655. return peek().type() == type;
  656. }
  657. Token Parser::consume()
  658. {
  659. if (eof()) {
  660. error("C++ Parser: out of tokens");
  661. return { Token::Type::EOF_TOKEN, position(), position(), {} };
  662. }
  663. return m_tokens[m_state.token_index++];
  664. }
  665. Token Parser::peek(size_t offset) const
  666. {
  667. if (m_state.token_index + offset >= m_tokens.size())
  668. return { Token::Type::EOF_TOKEN, position(), position(), {} };
  669. return m_tokens[m_state.token_index + offset];
  670. }
  671. Optional<Token> Parser::peek(Token::Type type) const
  672. {
  673. auto token = peek();
  674. if (token.type() == type)
  675. return token;
  676. return {};
  677. }
  678. void Parser::save_state()
  679. {
  680. m_saved_states.append(m_state);
  681. }
  682. void Parser::load_state()
  683. {
  684. m_state = m_saved_states.take_last();
  685. }
  686. StringView Parser::text_of_token(const Cpp::Token& token) const
  687. {
  688. return token.text();
  689. }
  690. String Parser::text_of_node(const ASTNode& node) const
  691. {
  692. return text_in_range(node.start(), node.end());
  693. }
  694. String Parser::text_in_range(Position start, Position end) const
  695. {
  696. auto start_token_index = index_of_token_at(start);
  697. auto end_node_index = index_of_token_at(end);
  698. VERIFY(start_token_index.has_value());
  699. VERIFY(end_node_index.has_value());
  700. StringBuilder text;
  701. for (size_t i = start_token_index.value(); i <= end_node_index.value(); ++i) {
  702. text.append(m_tokens[i].text());
  703. }
  704. return text.build();
  705. }
  706. void Parser::error(StringView message)
  707. {
  708. SCOPE_LOGGER();
  709. if (message.is_null() || message.is_empty())
  710. message = "<empty>";
  711. String formatted_message;
  712. if (m_state.token_index >= m_tokens.size()) {
  713. formatted_message = String::formatted("C++ Parsed error on EOF.{}", message);
  714. } else {
  715. formatted_message = String::formatted("C++ Parser error: {}. token: {} ({}:{})",
  716. message,
  717. m_state.token_index < m_tokens.size() ? text_of_token(m_tokens[m_state.token_index]) : "EOF",
  718. m_tokens[m_state.token_index].start().line,
  719. m_tokens[m_state.token_index].start().column);
  720. }
  721. m_state.errors.append(formatted_message);
  722. }
  723. bool Parser::match_expression()
  724. {
  725. auto token_type = peek().type();
  726. return match_literal()
  727. || token_type == Token::Type::Identifier
  728. || match_unary_expression()
  729. || match_cpp_cast_expression();
  730. }
  731. bool Parser::eof() const
  732. {
  733. return m_state.token_index >= m_tokens.size();
  734. }
  735. Position Parser::position() const
  736. {
  737. if (eof())
  738. return m_tokens.last().end();
  739. return peek().start();
  740. }
  741. RefPtr<ASTNode> Parser::eof_node() const
  742. {
  743. VERIFY(m_tokens.size());
  744. return node_at(m_tokens.last().end());
  745. }
  746. RefPtr<ASTNode> Parser::node_at(Position pos) const
  747. {
  748. auto index = index_of_node_at(pos);
  749. if (!index.has_value())
  750. return nullptr;
  751. return m_nodes[index.value()];
  752. }
  753. Optional<size_t> Parser::index_of_node_at(Position pos) const
  754. {
  755. VERIFY(!m_tokens.is_empty());
  756. Optional<size_t> match_node_index;
  757. auto node_span = [](const ASTNode& node) {
  758. VERIFY(node.end().line >= node.start().line);
  759. VERIFY((node.end().line > node.start().line) || (node.end().column >= node.start().column));
  760. return Position { node.end().line - node.start().line, node.start().line != node.end().line ? 0 : node.end().column - node.start().column };
  761. };
  762. for (size_t node_index = 0; node_index < m_nodes.size(); ++node_index) {
  763. auto& node = m_nodes[node_index];
  764. if (node.start() > pos || node.end() < pos)
  765. continue;
  766. if (!match_node_index.has_value() || (node_span(node) < node_span(m_nodes[match_node_index.value()])))
  767. match_node_index = node_index;
  768. }
  769. return match_node_index;
  770. }
  771. Optional<Token> Parser::token_at(Position pos) const
  772. {
  773. auto index = index_of_token_at(pos);
  774. if (!index.has_value())
  775. return {};
  776. return m_tokens[index.value()];
  777. }
  778. Optional<size_t> Parser::index_of_token_at(Position pos) const
  779. {
  780. for (size_t token_index = 0; token_index < m_tokens.size(); ++token_index) {
  781. auto token = m_tokens[token_index];
  782. if (token.start() > pos || token.end() < pos)
  783. continue;
  784. return token_index;
  785. }
  786. return {};
  787. }
  788. void Parser::print_tokens() const
  789. {
  790. for (auto& token : m_tokens) {
  791. dbgln("{}", token.to_string());
  792. }
  793. }
  794. Parser::TemplatizedMatchResult Parser::match_function_call()
  795. {
  796. save_state();
  797. ScopeGuard state_guard = [this] { load_state(); };
  798. if (!match_name())
  799. return TemplatizedMatchResult::NoMatch;
  800. parse_name(*m_root_node);
  801. bool is_templatized = false;
  802. if (match_template_arguments()) {
  803. is_templatized = true;
  804. parse_template_arguments(*m_root_node);
  805. }
  806. if (!match(Token::Type::LeftParen))
  807. return TemplatizedMatchResult::NoMatch;
  808. return is_templatized ? TemplatizedMatchResult::Templatized : TemplatizedMatchResult::Regular;
  809. }
  810. NonnullRefPtr<FunctionCall> Parser::parse_function_call(ASTNode& parent)
  811. {
  812. SCOPE_LOGGER();
  813. auto match_result = match_type();
  814. if (match_result == TemplatizedMatchResult::NoMatch) {
  815. error("expected type");
  816. return create_ast_node<FunctionCall>(parent, position(), position());
  817. }
  818. bool is_templatized = match_result == TemplatizedMatchResult::Templatized;
  819. RefPtr<FunctionCall> call;
  820. if (is_templatized) {
  821. call = create_ast_node<TemplatizedFunctionCall>(parent, position(), {});
  822. } else {
  823. call = create_ast_node<FunctionCall>(parent, position(), {});
  824. }
  825. call->m_name = parse_name(*call);
  826. if (is_templatized) {
  827. static_cast<TemplatizedFunctionCall&>(*call).m_template_arguments = parse_template_arguments(*call);
  828. }
  829. NonnullRefPtrVector<Expression> args;
  830. consume(Token::Type::LeftParen);
  831. while (peek().type() != Token::Type::RightParen && !eof()) {
  832. args.append(parse_expression(*call));
  833. if (peek().type() == Token::Type::Comma)
  834. consume(Token::Type::Comma);
  835. }
  836. consume(Token::Type::RightParen);
  837. call->m_arguments = move(args);
  838. call->set_end(position());
  839. return call.release_nonnull();
  840. }
  841. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(ASTNode& parent)
  842. {
  843. SCOPE_LOGGER();
  844. Optional<size_t> start_token_index;
  845. Optional<size_t> end_token_index;
  846. while (!eof()) {
  847. auto token = peek();
  848. if (token.type() != Token::Type::DoubleQuotedString && token.type() != Token::Type::SingleQuotedString && token.type() != Token::Type::EscapeSequence) {
  849. VERIFY(start_token_index.has_value());
  850. end_token_index = m_state.token_index - 1;
  851. break;
  852. }
  853. if (!start_token_index.has_value())
  854. start_token_index = m_state.token_index;
  855. consume();
  856. }
  857. // String was not terminated
  858. if (!end_token_index.has_value()) {
  859. end_token_index = m_tokens.size() - 1;
  860. }
  861. VERIFY(start_token_index.has_value());
  862. VERIFY(end_token_index.has_value());
  863. Token start_token = m_tokens[start_token_index.value()];
  864. Token end_token = m_tokens[end_token_index.value()];
  865. auto text = text_in_range(start_token.start(), end_token.end());
  866. auto string_literal = create_ast_node<StringLiteral>(parent, start_token.start(), end_token.end());
  867. string_literal->m_value = text;
  868. return string_literal;
  869. }
  870. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement(ASTNode& parent)
  871. {
  872. SCOPE_LOGGER();
  873. auto return_statement = create_ast_node<ReturnStatement>(parent, position(), {});
  874. consume(Token::Type::Keyword);
  875. if (!peek(Token::Type::Semicolon).has_value()) {
  876. auto expression = parse_expression(*return_statement);
  877. return_statement->m_value = expression;
  878. }
  879. return_statement->set_end(position());
  880. return return_statement;
  881. }
  882. NonnullRefPtr<EnumDeclaration> Parser::parse_enum_declaration(ASTNode& parent)
  883. {
  884. SCOPE_LOGGER();
  885. auto enum_decl = create_ast_node<EnumDeclaration>(parent, position(), {});
  886. consume_keyword("enum");
  887. auto name_token = consume(Token::Type::Identifier);
  888. enum_decl->m_name = text_of_token(name_token);
  889. consume(Token::Type::LeftCurly);
  890. while (!eof() && peek().type() != Token::Type::RightCurly) {
  891. enum_decl->m_entries.append(text_of_token(consume(Token::Type::Identifier)));
  892. if (peek().type() != Token::Type::Comma) {
  893. break;
  894. }
  895. consume(Token::Type::Comma);
  896. }
  897. consume(Token::Type::RightCurly);
  898. consume(Token::Type::Semicolon);
  899. enum_decl->set_end(position());
  900. return enum_decl;
  901. }
  902. Token Parser::consume_keyword(const String& keyword)
  903. {
  904. auto token = consume();
  905. if (token.type() != Token::Type::Keyword) {
  906. error(String::formatted("unexpected token: {}, expected Keyword", token.to_string()));
  907. return token;
  908. }
  909. if (text_of_token(token) != keyword) {
  910. error(String::formatted("unexpected keyword: {}, expected {}", text_of_token(token), keyword));
  911. return token;
  912. }
  913. return token;
  914. }
  915. bool Parser::match_keyword(const String& keyword)
  916. {
  917. auto token = peek();
  918. if (token.type() != Token::Type::Keyword) {
  919. return false;
  920. }
  921. if (text_of_token(token) != keyword) {
  922. return false;
  923. }
  924. return true;
  925. }
  926. NonnullRefPtr<StructOrClassDeclaration> Parser::parse_struct_or_class_declaration(ASTNode& parent, StructOrClassDeclaration::Type type)
  927. {
  928. SCOPE_LOGGER();
  929. auto decl = create_ast_node<StructOrClassDeclaration>(parent, position(), {}, type);
  930. switch (type) {
  931. case StructOrClassDeclaration::Type::Struct:
  932. consume_keyword("struct");
  933. break;
  934. case StructOrClassDeclaration::Type::Class:
  935. consume_keyword("class");
  936. break;
  937. }
  938. auto name_token = consume(Token::Type::Identifier);
  939. decl->m_name = text_of_token(name_token);
  940. consume(Token::Type::LeftCurly);
  941. while (!eof() && peek().type() != Token::Type::RightCurly) {
  942. decl->m_members.append(parse_member_declaration(*decl));
  943. }
  944. consume(Token::Type::RightCurly);
  945. consume(Token::Type::Semicolon);
  946. decl->set_end(position());
  947. return decl;
  948. }
  949. NonnullRefPtr<MemberDeclaration> Parser::parse_member_declaration(ASTNode& parent)
  950. {
  951. SCOPE_LOGGER();
  952. auto member_decl = create_ast_node<MemberDeclaration>(parent, position(), {});
  953. member_decl->m_type = parse_type(*member_decl);
  954. auto identifier_token = consume(Token::Type::Identifier);
  955. member_decl->m_name = text_of_token(identifier_token);
  956. RefPtr<Expression> initial_value;
  957. if (match(Token::Type::LeftCurly)) {
  958. consume(Token::Type::LeftCurly);
  959. initial_value = parse_expression(*member_decl);
  960. consume(Token::Type::RightCurly);
  961. }
  962. member_decl->m_initial_value = move(initial_value);
  963. consume(Token::Type::Semicolon);
  964. member_decl->set_end(position());
  965. return member_decl;
  966. }
  967. NonnullRefPtr<BooleanLiteral> Parser::parse_boolean_literal(ASTNode& parent)
  968. {
  969. SCOPE_LOGGER();
  970. auto token = consume(Token::Type::Keyword);
  971. auto text = text_of_token(token);
  972. // text == "true" || text == "false";
  973. bool value = (text == "true");
  974. return create_ast_node<BooleanLiteral>(parent, token.start(), token.end(), value);
  975. }
  976. bool Parser::match_boolean_literal()
  977. {
  978. auto token = peek();
  979. if (token.type() != Token::Type::Keyword)
  980. return false;
  981. auto text = text_of_token(token);
  982. return text == "true" || text == "false";
  983. }
  984. NonnullRefPtr<Type> Parser::parse_type(ASTNode& parent)
  985. {
  986. SCOPE_LOGGER();
  987. auto match_result = match_type();
  988. if (match_result == TemplatizedMatchResult::NoMatch) {
  989. auto token = consume();
  990. return create_ast_node<Type>(parent, token.start(), token.end());
  991. }
  992. bool is_templatized = match_result == TemplatizedMatchResult::Templatized;
  993. RefPtr<Type> type;
  994. if (is_templatized) {
  995. type = create_ast_node<TemplatizedType>(parent, position(), {});
  996. } else {
  997. type = create_ast_node<Type>(parent, position(), {});
  998. }
  999. auto qualifiers = parse_type_qualifiers();
  1000. type->m_qualifiers = move(qualifiers);
  1001. if (!match_name()) {
  1002. type->set_end(position());
  1003. error(String::formatted("expected name instead of: {}", peek().text()));
  1004. return type.release_nonnull();
  1005. }
  1006. type->m_name = parse_name(*type);
  1007. if (is_templatized) {
  1008. static_cast<TemplatizedType&>(*type).m_template_arguments = parse_template_arguments(*type);
  1009. }
  1010. while (!eof() && peek().type() == Token::Type::Asterisk) {
  1011. type->set_end(position());
  1012. auto asterisk = consume();
  1013. auto ptr = create_ast_node<Pointer>(parent, asterisk.start(), asterisk.end());
  1014. type->set_parent(*ptr);
  1015. ptr->m_pointee = type;
  1016. type = ptr;
  1017. }
  1018. type->set_end(position());
  1019. return type.release_nonnull();
  1020. }
  1021. NonnullRefPtr<ForStatement> Parser::parse_for_statement(ASTNode& parent)
  1022. {
  1023. SCOPE_LOGGER();
  1024. auto for_statement = create_ast_node<ForStatement>(parent, position(), {});
  1025. consume(Token::Type::Keyword);
  1026. consume(Token::Type::LeftParen);
  1027. for_statement->m_init = parse_variable_declaration(*for_statement);
  1028. consume(Token::Type::Semicolon);
  1029. for_statement->m_test = parse_expression(*for_statement);
  1030. consume(Token::Type::Semicolon);
  1031. for_statement->m_update = parse_expression(*for_statement);
  1032. consume(Token::Type::RightParen);
  1033. for_statement->m_body = parse_statement(*for_statement);
  1034. for_statement->set_end(for_statement->m_body->end());
  1035. return for_statement;
  1036. }
  1037. NonnullRefPtr<IfStatement> Parser::parse_if_statement(ASTNode& parent)
  1038. {
  1039. SCOPE_LOGGER();
  1040. auto if_statement = create_ast_node<IfStatement>(parent, position(), {});
  1041. consume(Token::Type::Keyword);
  1042. consume(Token::Type::LeftParen);
  1043. if_statement->m_predicate = parse_expression(*if_statement);
  1044. consume(Token::Type::RightParen);
  1045. if_statement->m_then = parse_statement(*if_statement);
  1046. if (match_keyword("else")) {
  1047. consume(Token::Type::Keyword);
  1048. if_statement->m_else = parse_statement(*if_statement);
  1049. if_statement->set_end(if_statement->m_else->end());
  1050. } else {
  1051. if_statement->set_end(if_statement->m_then->end());
  1052. }
  1053. return if_statement;
  1054. }
  1055. Vector<StringView> Parser::parse_type_qualifiers()
  1056. {
  1057. SCOPE_LOGGER();
  1058. Vector<StringView> qualifiers;
  1059. while (!eof()) {
  1060. auto token = peek();
  1061. if (token.type() != Token::Type::Keyword)
  1062. break;
  1063. auto text = text_of_token(token);
  1064. if (text == "static" || text == "const") {
  1065. qualifiers.append(text);
  1066. consume();
  1067. } else {
  1068. break;
  1069. }
  1070. }
  1071. return qualifiers;
  1072. }
  1073. Vector<StringView> Parser::parse_function_qualifiers()
  1074. {
  1075. SCOPE_LOGGER();
  1076. Vector<StringView> qualifiers;
  1077. while (!eof()) {
  1078. auto token = peek();
  1079. if (token.type() != Token::Type::Keyword)
  1080. break;
  1081. auto text = text_of_token(token);
  1082. if (text == "static" || text == "inline") {
  1083. qualifiers.append(text);
  1084. consume();
  1085. } else {
  1086. break;
  1087. }
  1088. }
  1089. return qualifiers;
  1090. }
  1091. bool Parser::match_attribute_specification()
  1092. {
  1093. return text_of_token(peek()) == "__attribute__";
  1094. }
  1095. void Parser::consume_attribute_specification()
  1096. {
  1097. consume(); // __attribute__
  1098. consume(Token::Type::LeftParen);
  1099. size_t left_count = 1;
  1100. while (!eof()) {
  1101. auto token = consume();
  1102. if (token.type() == Token::Type::LeftParen) {
  1103. ++left_count;
  1104. }
  1105. if (token.type() == Token::Type::RightParen) {
  1106. --left_count;
  1107. }
  1108. if (left_count == 0)
  1109. return;
  1110. }
  1111. }
  1112. bool Parser::match_ellipsis()
  1113. {
  1114. if (m_state.token_index > m_tokens.size() - 3)
  1115. return false;
  1116. return peek().type() == Token::Type::Dot && peek().type() == Token::Type::Dot && peek().type() == Token::Type::Dot;
  1117. }
  1118. void Parser::add_tokens_for_preprocessor(Token& replaced_token, Preprocessor::DefinedValue& definition)
  1119. {
  1120. if (!definition.value.has_value())
  1121. return;
  1122. Lexer lexer(definition.value.value());
  1123. for (auto token : lexer.lex()) {
  1124. if (token.type() == Token::Type::Whitespace)
  1125. continue;
  1126. token.set_start(replaced_token.start());
  1127. token.set_end(replaced_token.end());
  1128. m_tokens.append(move(token));
  1129. }
  1130. }
  1131. NonnullRefPtr<NamespaceDeclaration> Parser::parse_namespace_declaration(ASTNode& parent, bool is_nested_namespace)
  1132. {
  1133. auto namespace_decl = create_ast_node<NamespaceDeclaration>(parent, position(), {});
  1134. if (!is_nested_namespace)
  1135. consume(Token::Type::Keyword);
  1136. auto name_token = consume(Token::Type::Identifier);
  1137. namespace_decl->m_name = name_token.text();
  1138. if (peek().type() == Token::Type::ColonColon) {
  1139. consume(Token::Type::ColonColon);
  1140. namespace_decl->m_declarations.append(parse_namespace_declaration(*namespace_decl, true));
  1141. namespace_decl->set_end(position());
  1142. return namespace_decl;
  1143. }
  1144. consume(Token::Type::LeftCurly);
  1145. while (!eof() && peek().type() != Token::Type::RightCurly) {
  1146. auto declaration = parse_single_declaration_in_translation_unit(*namespace_decl);
  1147. if (declaration) {
  1148. namespace_decl->m_declarations.append(declaration.release_nonnull());
  1149. } else {
  1150. error("unexpected token");
  1151. consume();
  1152. }
  1153. }
  1154. consume(Token::Type::RightCurly);
  1155. namespace_decl->set_end(position());
  1156. return namespace_decl;
  1157. }
  1158. bool Parser::match_name()
  1159. {
  1160. auto type = peek().type();
  1161. return type == Token::Type::Identifier || type == Token::Type::KnownType;
  1162. }
  1163. NonnullRefPtr<Name> Parser::parse_name(ASTNode& parent)
  1164. {
  1165. auto name_node = create_ast_node<Name>(parent, position(), {});
  1166. while (!eof() && (peek().type() == Token::Type::Identifier || peek().type() == Token::Type::KnownType)) {
  1167. auto token = consume();
  1168. name_node->m_scope.append(create_ast_node<Identifier>(*name_node, token.start(), token.end(), token.text()));
  1169. if (peek().type() == Token::Type::ColonColon)
  1170. consume();
  1171. else
  1172. break;
  1173. }
  1174. VERIFY(!name_node->m_scope.is_empty());
  1175. name_node->m_name = name_node->m_scope.take_last();
  1176. name_node->set_end(position());
  1177. return name_node;
  1178. }
  1179. bool Parser::match_cpp_cast_expression()
  1180. {
  1181. save_state();
  1182. ScopeGuard state_guard = [this] { load_state(); };
  1183. auto token = consume();
  1184. if (token.type() != Token::Type::Keyword)
  1185. return false;
  1186. auto text = token.text();
  1187. if (text == "static_cast" || text == "reinterpret_cast" || text == "dynamic_cast" || text == "const_cast")
  1188. return true;
  1189. return false;
  1190. }
  1191. NonnullRefPtr<CppCastExpression> Parser::parse_cpp_cast_expression(ASTNode& parent)
  1192. {
  1193. auto cast_expression = create_ast_node<CppCastExpression>(parent, position(), {});
  1194. cast_expression->m_cast_type = consume(Token::Type::Keyword).text();
  1195. consume(Token::Type::Less);
  1196. cast_expression->m_type = parse_type(*cast_expression);
  1197. consume(Token::Type::Greater);
  1198. consume(Token::Type::LeftParen);
  1199. cast_expression->m_expression = parse_expression(*cast_expression);
  1200. consume(Token::Type::RightParen);
  1201. cast_expression->set_end(position());
  1202. return cast_expression;
  1203. }
  1204. }