Parser.cpp 39 KB

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