Parser.cpp 43 KB

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