Parser.cpp 36 KB

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