parser_impl.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/parser/parser_impl.h"
  5. #include <cstdlib>
  6. #include "common/check.h"
  7. #include "llvm/ADT/Optional.h"
  8. #include "llvm/Support/FormatVariadic.h"
  9. #include "llvm/Support/raw_ostream.h"
  10. #include "toolchain/lexer/token_kind.h"
  11. #include "toolchain/lexer/tokenized_buffer.h"
  12. #include "toolchain/parser/parse_node_kind.h"
  13. #include "toolchain/parser/parse_tree.h"
  14. namespace Carbon {
  15. struct StackLimitExceeded : DiagnosticBase<StackLimitExceeded> {
  16. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  17. static auto Format() -> std::string {
  18. return llvm::formatv("Exceeded recursion limit ({0})",
  19. ParseTree::StackDepthLimit);
  20. }
  21. };
  22. // Manages the parser's stack depth, particularly decrementing on destruction.
  23. // This should only be instantiated through RETURN_IF_STACK_LIMITED.
  24. class ParseTree::Parser::ScopedStackStep {
  25. public:
  26. explicit ScopedStackStep(ParseTree::Parser* parser) : parser_(parser) {
  27. ++parser_->stack_depth_;
  28. }
  29. ~ScopedStackStep() { --parser_->stack_depth_; }
  30. auto VerifyUnderLimit() -> bool {
  31. if (parser_->stack_depth_ >= StackDepthLimit) {
  32. parser_->emitter_.EmitError<StackLimitExceeded>(*parser_->position_);
  33. return false;
  34. }
  35. return true;
  36. }
  37. private:
  38. ParseTree::Parser* parser_;
  39. };
  40. // Encapsulates checking the stack and erroring if needed. This should be called
  41. // at the start of every parse function.
  42. #define RETURN_IF_STACK_LIMITED(error_return_expr) \
  43. ScopedStackStep scoped_stack_step(this); \
  44. if (!scoped_stack_step.VerifyUnderLimit()) { \
  45. return (error_return_expr); \
  46. }
  47. struct UnexpectedTokenInCodeBlock : DiagnosticBase<UnexpectedTokenInCodeBlock> {
  48. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  49. static constexpr llvm::StringLiteral Message =
  50. "Unexpected token in code block.";
  51. };
  52. struct ExpectedFunctionName : DiagnosticBase<ExpectedFunctionName> {
  53. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  54. static constexpr llvm::StringLiteral Message =
  55. "Expected function name after `fn` keyword.";
  56. };
  57. struct ExpectedFunctionParams : DiagnosticBase<ExpectedFunctionParams> {
  58. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  59. static constexpr llvm::StringLiteral Message =
  60. "Expected `(` after function name.";
  61. };
  62. struct ExpectedFunctionBodyOrSemi : DiagnosticBase<ExpectedFunctionBodyOrSemi> {
  63. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  64. static constexpr llvm::StringLiteral Message =
  65. "Expected function definition or `;` after function declaration.";
  66. };
  67. struct ExpectedVariableName : DiagnosticBase<ExpectedVariableName> {
  68. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  69. static constexpr llvm::StringLiteral Message =
  70. "Expected pattern in `var` declaration.";
  71. };
  72. struct ExpectedParameterName : DiagnosticBase<ExpectedParameterName> {
  73. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  74. static constexpr llvm::StringLiteral Message =
  75. "Expected parameter declaration.";
  76. };
  77. struct ExpectedStructLiteralField : DiagnosticBase<ExpectedStructLiteralField> {
  78. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  79. auto Format() -> std::string {
  80. std::string result = "Expected ";
  81. if (can_be_type) {
  82. result += "`.field: type`";
  83. }
  84. if (can_be_type && can_be_value) {
  85. result += " or ";
  86. }
  87. if (can_be_value) {
  88. result += "`.field = value`";
  89. }
  90. result += ".";
  91. return result;
  92. }
  93. bool can_be_type;
  94. bool can_be_value;
  95. };
  96. struct UnrecognizedDeclaration : DiagnosticBase<UnrecognizedDeclaration> {
  97. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  98. static constexpr llvm::StringLiteral Message =
  99. "Unrecognized declaration introducer.";
  100. };
  101. struct ExpectedCodeBlock : DiagnosticBase<ExpectedCodeBlock> {
  102. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  103. static constexpr llvm::StringLiteral Message = "Expected braced code block.";
  104. };
  105. struct ExpectedExpression : DiagnosticBase<ExpectedExpression> {
  106. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  107. static constexpr llvm::StringLiteral Message = "Expected expression.";
  108. };
  109. struct ExpectedParenAfter : DiagnosticBase<ExpectedParenAfter> {
  110. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  111. static constexpr const char* Message = "Expected `(` after `{0}`.";
  112. auto Format() -> std::string {
  113. return llvm::formatv(Message, introducer.GetFixedSpelling()).str();
  114. }
  115. TokenKind introducer;
  116. };
  117. struct ExpectedCloseParen : DiagnosticBase<ExpectedCloseParen> {
  118. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  119. static constexpr llvm::StringLiteral Message =
  120. "Unexpected tokens before `)`.";
  121. // TODO: Include the location of the matching open paren in the diagnostic.
  122. TokenizedBuffer::Token open_paren;
  123. };
  124. struct ExpectedSemiAfterExpression
  125. : DiagnosticBase<ExpectedSemiAfterExpression> {
  126. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  127. static constexpr llvm::StringLiteral Message =
  128. "Expected `;` after expression.";
  129. };
  130. struct ExpectedSemiAfter : DiagnosticBase<ExpectedSemiAfter> {
  131. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  132. static constexpr const char* Message = "Expected `;` after `{0}`.";
  133. auto Format() -> std::string {
  134. return llvm::formatv(Message, preceding.GetFixedSpelling()).str();
  135. }
  136. TokenKind preceding;
  137. };
  138. struct ExpectedIdentifierAfterDot : DiagnosticBase<ExpectedIdentifierAfterDot> {
  139. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  140. static constexpr llvm::StringLiteral Message =
  141. "Expected identifier after `.`.";
  142. };
  143. struct UnexpectedTokenAfterListElement
  144. : DiagnosticBase<UnexpectedTokenAfterListElement> {
  145. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  146. static constexpr const char* Message = "Expected `,` or `{0}`.";
  147. auto Format() -> std::string {
  148. return llvm::formatv(Message, close.GetFixedSpelling()).str();
  149. }
  150. TokenKind close;
  151. };
  152. struct BinaryOperatorRequiresWhitespace
  153. : DiagnosticBase<BinaryOperatorRequiresWhitespace> {
  154. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  155. static constexpr const char* Message =
  156. "Whitespace missing {0} binary operator.";
  157. auto Format() -> std::string {
  158. const char* position = "around";
  159. if (has_leading_space) {
  160. position = "after";
  161. } else if (has_trailing_space) {
  162. position = "before";
  163. }
  164. return llvm::formatv(Message, position);
  165. }
  166. bool has_leading_space;
  167. bool has_trailing_space;
  168. };
  169. struct UnaryOperatorHasWhitespace : DiagnosticBase<UnaryOperatorHasWhitespace> {
  170. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  171. static constexpr const char* Message =
  172. "Whitespace is not allowed {0} this unary operator.";
  173. auto Format() -> std::string {
  174. return llvm::formatv(Message, prefix ? "after" : "before");
  175. }
  176. bool prefix;
  177. };
  178. struct UnaryOperatorRequiresWhitespace
  179. : DiagnosticBase<UnaryOperatorRequiresWhitespace> {
  180. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  181. static constexpr const char* Message =
  182. "Whitespace is required {0} this unary operator.";
  183. auto Format() -> std::string {
  184. return llvm::formatv(Message, prefix ? "before" : "after");
  185. }
  186. bool prefix;
  187. };
  188. struct OperatorRequiresParentheses
  189. : DiagnosticBase<OperatorRequiresParentheses> {
  190. static constexpr llvm::StringLiteral ShortName = "syntax-error";
  191. static constexpr llvm::StringLiteral Message =
  192. "Parentheses are required to disambiguate operator precedence.";
  193. };
  194. ParseTree::Parser::Parser(ParseTree& tree_arg, TokenizedBuffer& tokens_arg,
  195. TokenDiagnosticEmitter& emitter)
  196. : tree_(tree_arg),
  197. tokens_(tokens_arg),
  198. emitter_(emitter),
  199. position_(tokens_.Tokens().begin()),
  200. end_(tokens_.Tokens().end()) {
  201. CHECK(std::find_if(position_, end_,
  202. [&](TokenizedBuffer::Token t) {
  203. return tokens_.GetKind(t) == TokenKind::EndOfFile();
  204. }) != end_)
  205. << "No EndOfFileToken in token buffer.";
  206. }
  207. auto ParseTree::Parser::Parse(TokenizedBuffer& tokens,
  208. TokenDiagnosticEmitter& emitter) -> ParseTree {
  209. ParseTree tree(tokens);
  210. // We expect to have a 1:1 correspondence between tokens and tree nodes, so
  211. // reserve the space we expect to need here to avoid allocation and copying
  212. // overhead.
  213. tree.node_impls_.reserve(tokens.Size());
  214. Parser parser(tree, tokens, emitter);
  215. while (!parser.AtEndOfFile()) {
  216. if (!parser.ParseDeclaration()) {
  217. // We don't have an enclosing parse tree node to mark as erroneous, so
  218. // just mark the tree as a whole.
  219. tree.has_errors_ = true;
  220. }
  221. }
  222. parser.AddLeafNode(ParseNodeKind::FileEnd(), *parser.position_);
  223. CHECK(tree.Verify()) << "Parse tree built but does not verify!";
  224. return tree;
  225. }
  226. auto ParseTree::Parser::Consume(TokenKind kind) -> TokenizedBuffer::Token {
  227. CHECK(kind != TokenKind::EndOfFile()) << "Cannot consume the EOF token!";
  228. CHECK(NextTokenIs(kind)) << "The current token is the wrong kind!";
  229. TokenizedBuffer::Token t = *position_;
  230. ++position_;
  231. CHECK(position_ != end_)
  232. << "Reached end of tokens without finding EOF token.";
  233. return t;
  234. }
  235. auto ParseTree::Parser::ConsumeIf(TokenKind kind)
  236. -> llvm::Optional<TokenizedBuffer::Token> {
  237. if (!NextTokenIs(kind)) {
  238. return {};
  239. }
  240. return Consume(kind);
  241. }
  242. auto ParseTree::Parser::AddLeafNode(ParseNodeKind kind,
  243. TokenizedBuffer::Token token) -> Node {
  244. Node n(tree_.node_impls_.size());
  245. tree_.node_impls_.push_back(NodeImpl(kind, token, /*subtree_size_arg=*/1));
  246. return n;
  247. }
  248. auto ParseTree::Parser::ConsumeAndAddLeafNodeIf(TokenKind t_kind,
  249. ParseNodeKind n_kind)
  250. -> llvm::Optional<Node> {
  251. auto t = ConsumeIf(t_kind);
  252. if (!t) {
  253. return {};
  254. }
  255. return AddLeafNode(n_kind, *t);
  256. }
  257. auto ParseTree::Parser::MarkNodeError(Node n) -> void {
  258. tree_.node_impls_[n.index_].has_error = true;
  259. tree_.has_errors_ = true;
  260. }
  261. // A marker for the start of a node's subtree.
  262. //
  263. // This is used to track the size of the node's subtree. It can be used
  264. // repeatedly if multiple subtrees start at the same position.
  265. struct ParseTree::Parser::SubtreeStart {
  266. int tree_size;
  267. };
  268. auto ParseTree::Parser::GetSubtreeStartPosition() -> SubtreeStart {
  269. return {static_cast<int>(tree_.node_impls_.size())};
  270. }
  271. auto ParseTree::Parser::AddNode(ParseNodeKind n_kind, TokenizedBuffer::Token t,
  272. SubtreeStart start, bool has_error) -> Node {
  273. // The size of the subtree is the change in size from when we started this
  274. // subtree to now, but including the node we're about to add.
  275. int tree_stop_size = static_cast<int>(tree_.node_impls_.size()) + 1;
  276. int subtree_size = tree_stop_size - start.tree_size;
  277. Node n(tree_.node_impls_.size());
  278. tree_.node_impls_.push_back(NodeImpl(n_kind, t, subtree_size));
  279. if (has_error) {
  280. MarkNodeError(n);
  281. }
  282. return n;
  283. }
  284. auto ParseTree::Parser::SkipMatchingGroup() -> bool {
  285. TokenizedBuffer::Token t = *position_;
  286. TokenKind t_kind = tokens_.GetKind(t);
  287. if (!t_kind.IsOpeningSymbol()) {
  288. return false;
  289. }
  290. SkipTo(tokens_.GetMatchedClosingToken(t));
  291. Consume(t_kind.GetClosingSymbol());
  292. return true;
  293. }
  294. auto ParseTree::Parser::SkipTo(TokenizedBuffer::Token t) -> void {
  295. CHECK(t >= *position_) << "Tried to skip backwards.";
  296. position_ = TokenizedBuffer::TokenIterator(t);
  297. CHECK(position_ != end_) << "Skipped past EOF.";
  298. }
  299. auto ParseTree::Parser::FindNextOf(
  300. std::initializer_list<TokenKind> desired_kinds)
  301. -> llvm::Optional<TokenizedBuffer::Token> {
  302. auto new_position = position_;
  303. while (true) {
  304. TokenizedBuffer::Token token = *new_position;
  305. TokenKind kind = tokens_.GetKind(token);
  306. if (kind.IsOneOf(desired_kinds)) {
  307. return token;
  308. }
  309. // Step to the next token at the current bracketing level.
  310. if (kind.IsClosingSymbol() || kind == TokenKind::EndOfFile()) {
  311. // There are no more tokens at this level.
  312. return llvm::None;
  313. } else if (kind.IsOpeningSymbol()) {
  314. new_position =
  315. TokenizedBuffer::TokenIterator(tokens_.GetMatchedClosingToken(token));
  316. // Advance past the closing token.
  317. ++new_position;
  318. } else {
  319. ++new_position;
  320. }
  321. }
  322. }
  323. auto ParseTree::Parser::SkipPastLikelyEnd(TokenizedBuffer::Token skip_root,
  324. SemiHandler on_semi)
  325. -> llvm::Optional<Node> {
  326. if (AtEndOfFile()) {
  327. return llvm::None;
  328. }
  329. TokenizedBuffer::Line root_line = tokens_.GetLine(skip_root);
  330. int root_line_indent = tokens_.GetIndentColumnNumber(root_line);
  331. // We will keep scanning through tokens on the same line as the root or
  332. // lines with greater indentation than root's line.
  333. auto is_same_line_or_indent_greater_than_root =
  334. [&](TokenizedBuffer::Token t) {
  335. TokenizedBuffer::Line l = tokens_.GetLine(t);
  336. if (l == root_line) {
  337. return true;
  338. }
  339. return tokens_.GetIndentColumnNumber(l) > root_line_indent;
  340. };
  341. do {
  342. if (NextTokenKind() == TokenKind::CloseCurlyBrace()) {
  343. // Immediately bail out if we hit an unmatched close curly, this will
  344. // pop us up a level of the syntax grouping.
  345. return llvm::None;
  346. }
  347. // We assume that a semicolon is always intended to be the end of the
  348. // current construct.
  349. if (auto semi = ConsumeIf(TokenKind::Semi())) {
  350. return on_semi(*semi);
  351. }
  352. // Skip over any matching group of tokens_.
  353. if (SkipMatchingGroup()) {
  354. continue;
  355. }
  356. // Otherwise just step forward one token.
  357. Consume(NextTokenKind());
  358. } while (!AtEndOfFile() &&
  359. is_same_line_or_indent_greater_than_root(*position_));
  360. return llvm::None;
  361. }
  362. auto ParseTree::Parser::ParseCloseParen(TokenizedBuffer::Token open_paren,
  363. ParseNodeKind kind)
  364. -> llvm::Optional<Node> {
  365. if (auto close_paren =
  366. ConsumeAndAddLeafNodeIf(TokenKind::CloseParen(), kind)) {
  367. return close_paren;
  368. }
  369. emitter_.EmitError<ExpectedCloseParen>(*position_,
  370. {.open_paren = open_paren});
  371. SkipTo(tokens_.GetMatchedClosingToken(open_paren));
  372. AddLeafNode(kind, Consume(TokenKind::CloseParen()));
  373. return llvm::None;
  374. }
  375. template <typename ListElementParser, typename ListCompletionHandler>
  376. auto ParseTree::Parser::ParseList(TokenKind open, TokenKind close,
  377. ListElementParser list_element_parser,
  378. ParseNodeKind comma_kind,
  379. ListCompletionHandler list_handler,
  380. bool allow_trailing_comma)
  381. -> llvm::Optional<Node> {
  382. // `(` element-list[opt] `)`
  383. //
  384. // element-list ::= element
  385. // ::= element `,` element-list
  386. TokenizedBuffer::Token open_paren = Consume(open);
  387. bool has_errors = false;
  388. bool any_commas = false;
  389. int64_t num_elements = 0;
  390. // Parse elements, if any are specified.
  391. if (!NextTokenIs(close)) {
  392. while (true) {
  393. bool element_error = !list_element_parser();
  394. has_errors |= element_error;
  395. ++num_elements;
  396. if (!NextTokenIsOneOf({close, TokenKind::Comma()})) {
  397. if (!element_error) {
  398. emitter_.EmitError<UnexpectedTokenAfterListElement>(*position_,
  399. {.close = close});
  400. }
  401. has_errors = true;
  402. auto end_of_element = FindNextOf({TokenKind::Comma(), close});
  403. // The lexer guarantees that parentheses are balanced.
  404. CHECK(end_of_element) << "missing matching `)` for `(`";
  405. SkipTo(*end_of_element);
  406. }
  407. if (NextTokenIs(close)) {
  408. break;
  409. }
  410. AddLeafNode(comma_kind, Consume(TokenKind::Comma()));
  411. any_commas = true;
  412. if (allow_trailing_comma && NextTokenIs(close)) {
  413. break;
  414. }
  415. }
  416. }
  417. bool is_single_item = num_elements == 1 && !any_commas;
  418. return list_handler(open_paren, is_single_item, Consume(close), has_errors);
  419. }
  420. auto ParseTree::Parser::ParsePattern(PatternKind kind) -> llvm::Optional<Node> {
  421. RETURN_IF_STACK_LIMITED(llvm::None);
  422. if (NextTokenIs(TokenKind::Identifier()) &&
  423. tokens_.GetKind(*(position_ + 1)) == TokenKind::Colon()) {
  424. // identifier `:` type
  425. auto start = GetSubtreeStartPosition();
  426. AddLeafNode(ParseNodeKind::DeclaredName(),
  427. Consume(TokenKind::Identifier()));
  428. auto colon = Consume(TokenKind::Colon());
  429. auto type = ParseType();
  430. return AddNode(ParseNodeKind::PatternBinding(), colon, start,
  431. /*has_error=*/!type);
  432. }
  433. switch (kind) {
  434. case PatternKind::Parameter:
  435. emitter_.EmitError<ExpectedParameterName>(*position_);
  436. break;
  437. case PatternKind::Variable:
  438. emitter_.EmitError<ExpectedVariableName>(*position_);
  439. break;
  440. }
  441. return llvm::None;
  442. }
  443. auto ParseTree::Parser::ParseFunctionParameter() -> llvm::Optional<Node> {
  444. RETURN_IF_STACK_LIMITED(llvm::None);
  445. return ParsePattern(PatternKind::Parameter);
  446. }
  447. auto ParseTree::Parser::ParseFunctionSignature() -> bool {
  448. RETURN_IF_STACK_LIMITED(false);
  449. auto start = GetSubtreeStartPosition();
  450. auto params = ParseParenList(
  451. [&] { return ParseFunctionParameter(); },
  452. ParseNodeKind::ParameterListComma(),
  453. [&](TokenizedBuffer::Token open_paren, bool /*is_single_item*/,
  454. TokenizedBuffer::Token close_paren, bool has_errors) {
  455. AddLeafNode(ParseNodeKind::ParameterListEnd(), close_paren);
  456. return AddNode(ParseNodeKind::ParameterList(), open_paren, start,
  457. has_errors);
  458. });
  459. auto start_return_type = GetSubtreeStartPosition();
  460. if (auto arrow = ConsumeIf(TokenKind::MinusGreater())) {
  461. auto return_type = ParseType();
  462. AddNode(ParseNodeKind::ReturnType(), *arrow, start_return_type,
  463. /*has_error=*/!return_type);
  464. if (!return_type) {
  465. return false;
  466. }
  467. }
  468. return params.hasValue();
  469. }
  470. auto ParseTree::Parser::ParseCodeBlock() -> llvm::Optional<Node> {
  471. RETURN_IF_STACK_LIMITED(llvm::None);
  472. llvm::Optional<TokenizedBuffer::Token> maybe_open_curly =
  473. ConsumeIf(TokenKind::OpenCurlyBrace());
  474. if (!maybe_open_curly) {
  475. // Recover by parsing a single statement.
  476. emitter_.EmitError<ExpectedCodeBlock>(*position_);
  477. return ParseStatement();
  478. }
  479. TokenizedBuffer::Token open_curly = *maybe_open_curly;
  480. auto start = GetSubtreeStartPosition();
  481. bool has_errors = false;
  482. // Loop over all the different possibly nested elements in the code block.
  483. while (!NextTokenIs(TokenKind::CloseCurlyBrace())) {
  484. if (!ParseStatement()) {
  485. // We detected and diagnosed an error of some kind. We can trivially skip
  486. // to the actual close curly brace from here.
  487. // FIXME: It would be better to skip to the next semicolon, or the next
  488. // token at the start of a line with the same indent as this one.
  489. SkipTo(tokens_.GetMatchedClosingToken(open_curly));
  490. has_errors = true;
  491. break;
  492. }
  493. }
  494. // We always reach here having set our position in the token stream to the
  495. // close curly brace.
  496. AddLeafNode(ParseNodeKind::CodeBlockEnd(),
  497. Consume(TokenKind::CloseCurlyBrace()));
  498. return AddNode(ParseNodeKind::CodeBlock(), open_curly, start, has_errors);
  499. }
  500. auto ParseTree::Parser::ParseFunctionDeclaration() -> Node {
  501. TokenizedBuffer::Token function_intro_token = Consume(TokenKind::FnKeyword());
  502. auto start = GetSubtreeStartPosition();
  503. auto add_error_function_node = [&] {
  504. return AddNode(ParseNodeKind::FunctionDeclaration(), function_intro_token,
  505. start, /*has_error=*/true);
  506. };
  507. RETURN_IF_STACK_LIMITED(add_error_function_node());
  508. auto handle_semi_in_error_recovery = [&](TokenizedBuffer::Token semi) {
  509. return AddLeafNode(ParseNodeKind::DeclarationEnd(), semi);
  510. };
  511. auto name_n = ConsumeAndAddLeafNodeIf(TokenKind::Identifier(),
  512. ParseNodeKind::DeclaredName());
  513. if (!name_n) {
  514. emitter_.EmitError<ExpectedFunctionName>(*position_);
  515. // FIXME: We could change the lexer to allow us to synthesize certain
  516. // kinds of tokens and try to "recover" here, but unclear that this is
  517. // really useful.
  518. SkipPastLikelyEnd(function_intro_token, handle_semi_in_error_recovery);
  519. return add_error_function_node();
  520. }
  521. TokenizedBuffer::Token open_paren = *position_;
  522. if (tokens_.GetKind(open_paren) != TokenKind::OpenParen()) {
  523. emitter_.EmitError<ExpectedFunctionParams>(open_paren);
  524. SkipPastLikelyEnd(function_intro_token, handle_semi_in_error_recovery);
  525. return add_error_function_node();
  526. }
  527. TokenizedBuffer::Token close_paren =
  528. tokens_.GetMatchedClosingToken(open_paren);
  529. if (!ParseFunctionSignature()) {
  530. // Don't try to parse more of the function declaration, but consume a
  531. // declaration ending semicolon if found (without going to a new line).
  532. SkipPastLikelyEnd(function_intro_token, handle_semi_in_error_recovery);
  533. return add_error_function_node();
  534. }
  535. // See if we should parse a definition which is represented as a code block.
  536. if (NextTokenIs(TokenKind::OpenCurlyBrace())) {
  537. if (!ParseCodeBlock()) {
  538. return add_error_function_node();
  539. }
  540. } else if (!ConsumeAndAddLeafNodeIf(TokenKind::Semi(),
  541. ParseNodeKind::DeclarationEnd())) {
  542. emitter_.EmitError<ExpectedFunctionBodyOrSemi>(*position_);
  543. if (tokens_.GetLine(*position_) == tokens_.GetLine(close_paren)) {
  544. // Only need to skip if we've not already found a new line.
  545. SkipPastLikelyEnd(function_intro_token, handle_semi_in_error_recovery);
  546. }
  547. return add_error_function_node();
  548. }
  549. // Successfully parsed the function, add that node.
  550. return AddNode(ParseNodeKind::FunctionDeclaration(), function_intro_token,
  551. start);
  552. }
  553. auto ParseTree::Parser::ParseVariableDeclaration() -> Node {
  554. // `var` pattern [= expression] `;`
  555. TokenizedBuffer::Token var_token = Consume(TokenKind::VarKeyword());
  556. auto start = GetSubtreeStartPosition();
  557. RETURN_IF_STACK_LIMITED(AddNode(ParseNodeKind::VariableDeclaration(),
  558. var_token, start,
  559. /*has_error=*/true));
  560. auto pattern = ParsePattern(PatternKind::Variable);
  561. if (!pattern) {
  562. if (auto after_pattern =
  563. FindNextOf({TokenKind::Equal(), TokenKind::Semi()})) {
  564. SkipTo(*after_pattern);
  565. }
  566. }
  567. auto start_init = GetSubtreeStartPosition();
  568. if (auto equal_token = ConsumeIf(TokenKind::Equal())) {
  569. auto init = ParseExpression();
  570. AddNode(ParseNodeKind::VariableInitializer(), *equal_token, start_init,
  571. /*has_error=*/!init);
  572. }
  573. auto semi = ConsumeAndAddLeafNodeIf(TokenKind::Semi(),
  574. ParseNodeKind::DeclarationEnd());
  575. if (!semi) {
  576. emitter_.EmitError<ExpectedSemiAfterExpression>(*position_);
  577. SkipPastLikelyEnd(var_token, [&](TokenizedBuffer::Token semi) {
  578. return AddLeafNode(ParseNodeKind::DeclarationEnd(), semi);
  579. });
  580. }
  581. return AddNode(ParseNodeKind::VariableDeclaration(), var_token, start,
  582. /*has_error=*/!pattern || !semi);
  583. }
  584. auto ParseTree::Parser::ParseEmptyDeclaration() -> Node {
  585. return AddLeafNode(ParseNodeKind::EmptyDeclaration(),
  586. Consume(TokenKind::Semi()));
  587. }
  588. auto ParseTree::Parser::ParseDeclaration() -> llvm::Optional<Node> {
  589. RETURN_IF_STACK_LIMITED(llvm::None);
  590. switch (NextTokenKind()) {
  591. case TokenKind::FnKeyword():
  592. return ParseFunctionDeclaration();
  593. case TokenKind::VarKeyword():
  594. return ParseVariableDeclaration();
  595. case TokenKind::Semi():
  596. return ParseEmptyDeclaration();
  597. case TokenKind::EndOfFile():
  598. return llvm::None;
  599. default:
  600. // Errors are handled outside the switch.
  601. break;
  602. }
  603. // We didn't recognize an introducer for a valid declaration.
  604. emitter_.EmitError<UnrecognizedDeclaration>(*position_);
  605. // Skip forward past any end of a declaration we simply didn't understand so
  606. // that we can find the start of the next declaration or the end of a scope.
  607. if (auto found_semi_n =
  608. SkipPastLikelyEnd(*position_, [&](TokenizedBuffer::Token semi) {
  609. return AddLeafNode(ParseNodeKind::EmptyDeclaration(), semi);
  610. })) {
  611. MarkNodeError(*found_semi_n);
  612. return *found_semi_n;
  613. }
  614. // Nothing, not even a semicolon found.
  615. return llvm::None;
  616. }
  617. auto ParseTree::Parser::ParseParenExpression() -> llvm::Optional<Node> {
  618. RETURN_IF_STACK_LIMITED(llvm::None);
  619. // parenthesized-expression ::= `(` expression `)`
  620. // tuple-literal ::= `(` `)`
  621. // ::= `(` expression `,` [expression-list [`,`]] `)`
  622. //
  623. // Parse the union of these, `(` [expression-list [`,`]] `)`, and work out
  624. // whether it's a tuple or a parenthesized expression afterwards.
  625. auto start = GetSubtreeStartPosition();
  626. return ParseParenList(
  627. [&] { return ParseExpression(); }, ParseNodeKind::TupleLiteralComma(),
  628. [&](TokenizedBuffer::Token open_paren, bool is_single_item,
  629. TokenizedBuffer::Token close_paren, bool has_arg_errors) {
  630. AddLeafNode(is_single_item ? ParseNodeKind::ParenExpressionEnd()
  631. : ParseNodeKind::TupleLiteralEnd(),
  632. close_paren);
  633. return AddNode(is_single_item ? ParseNodeKind::ParenExpression()
  634. : ParseNodeKind::TupleLiteral(),
  635. open_paren, start, has_arg_errors);
  636. },
  637. /*allow_trailing_comma=*/true);
  638. }
  639. auto ParseTree::Parser::ParseBraceExpression() -> llvm::Optional<Node> {
  640. RETURN_IF_STACK_LIMITED(llvm::None);
  641. // braced-expression ::= `{` [field-value-list] `}`
  642. // ::= `{` field-type-list `}`
  643. // field-value-list ::= field-value [`,`]
  644. // ::= field-value `,` field-value-list
  645. // field-value ::= `.` identifier `=` expression
  646. // field-type-list ::= field-type [`,`]
  647. // ::= field-type `,` field-type-list
  648. // field-type ::= `.` identifier `:` type
  649. //
  650. // Note that `{` `}` is the first form (an empty struct), but that an empty
  651. // struct value also behaves as an empty struct type.
  652. auto start = GetSubtreeStartPosition();
  653. enum Kind { Unknown, Value, Type };
  654. Kind kind = Unknown;
  655. return ParseList(
  656. TokenKind::OpenCurlyBrace(), TokenKind::CloseCurlyBrace(),
  657. [&]() -> llvm::Optional<Node> {
  658. auto start_elem = GetSubtreeStartPosition();
  659. auto diagnose_invalid_syntax = [&] {
  660. emitter_.EmitError<ExpectedStructLiteralField>(
  661. *position_,
  662. {.can_be_type = kind != Value, .can_be_value = kind != Type});
  663. return llvm::None;
  664. };
  665. if (!NextTokenIs(TokenKind::Period())) {
  666. return diagnose_invalid_syntax();
  667. }
  668. auto designator = ParseDesignatorExpression(
  669. start_elem, ParseNodeKind::StructFieldDesignator(),
  670. /*has_errors=*/false);
  671. if (!designator) {
  672. auto recovery_pos = FindNextOf(
  673. {TokenKind::Equal(), TokenKind::Colon(), TokenKind::Comma()});
  674. if (!recovery_pos ||
  675. tokens_.GetKind(*recovery_pos) == TokenKind::Comma()) {
  676. return llvm::None;
  677. }
  678. SkipTo(*recovery_pos);
  679. }
  680. // Work out the kind of this element
  681. Kind elem_kind = (NextTokenIs(TokenKind::Equal()) ? Value
  682. : NextTokenIs(TokenKind::Colon()) ? Type
  683. : Unknown);
  684. if (elem_kind == Unknown || (kind != Unknown && elem_kind != kind)) {
  685. return diagnose_invalid_syntax();
  686. }
  687. kind = elem_kind;
  688. // Struct type fields and value fields use the same grammar except that
  689. // one has a `:` separator and the other has an `=` separator.
  690. auto equal_or_colon_token =
  691. Consume(kind == Type ? TokenKind::Colon() : TokenKind::Equal());
  692. auto type_or_value = ParseExpression();
  693. return AddNode(kind == Type ? ParseNodeKind::StructFieldType()
  694. : ParseNodeKind::StructFieldValue(),
  695. equal_or_colon_token, start_elem,
  696. /*has_error=*/!designator || !type_or_value);
  697. },
  698. ParseNodeKind::StructComma(),
  699. [&](TokenizedBuffer::Token open_brace, bool /*is_single_item*/,
  700. TokenizedBuffer::Token close_brace, bool has_errors) {
  701. AddLeafNode(ParseNodeKind::StructEnd(), close_brace);
  702. return AddNode(kind == Type ? ParseNodeKind::StructTypeLiteral()
  703. : ParseNodeKind::StructLiteral(),
  704. open_brace, start, has_errors);
  705. },
  706. /*allow_trailing_comma=*/true);
  707. }
  708. auto ParseTree::Parser::ParsePrimaryExpression() -> llvm::Optional<Node> {
  709. RETURN_IF_STACK_LIMITED(llvm::None);
  710. llvm::Optional<ParseNodeKind> kind;
  711. switch (NextTokenKind()) {
  712. case TokenKind::Identifier():
  713. kind = ParseNodeKind::NameReference();
  714. break;
  715. case TokenKind::IntegerLiteral():
  716. case TokenKind::RealLiteral():
  717. case TokenKind::StringLiteral():
  718. case TokenKind::IntegerTypeLiteral():
  719. case TokenKind::UnsignedIntegerTypeLiteral():
  720. case TokenKind::FloatingPointTypeLiteral():
  721. kind = ParseNodeKind::Literal();
  722. break;
  723. case TokenKind::OpenParen():
  724. return ParseParenExpression();
  725. case TokenKind::OpenCurlyBrace():
  726. return ParseBraceExpression();
  727. default:
  728. emitter_.EmitError<ExpectedExpression>(*position_);
  729. return llvm::None;
  730. }
  731. return AddLeafNode(*kind, Consume(NextTokenKind()));
  732. }
  733. auto ParseTree::Parser::ParseDesignatorExpression(SubtreeStart start,
  734. ParseNodeKind kind,
  735. bool has_errors)
  736. -> llvm::Optional<Node> {
  737. // `.` identifier
  738. auto dot = Consume(TokenKind::Period());
  739. auto name = ConsumeIf(TokenKind::Identifier());
  740. if (name) {
  741. AddLeafNode(ParseNodeKind::DesignatedName(), *name);
  742. } else {
  743. emitter_.EmitError<ExpectedIdentifierAfterDot>(*position_);
  744. // If we see a keyword, assume it was intended to be the designated name.
  745. // TODO: Should keywords be valid in designators?
  746. if (NextTokenKind().IsKeyword()) {
  747. name = Consume(NextTokenKind());
  748. auto name_node = AddLeafNode(ParseNodeKind::DesignatedName(), *name);
  749. MarkNodeError(name_node);
  750. } else {
  751. has_errors = true;
  752. }
  753. }
  754. Node result = AddNode(kind, dot, start, has_errors);
  755. return name ? result : llvm::Optional<Node>();
  756. }
  757. auto ParseTree::Parser::ParseCallExpression(SubtreeStart start, bool has_errors)
  758. -> llvm::Optional<Node> {
  759. RETURN_IF_STACK_LIMITED(llvm::None);
  760. // `(` expression-list[opt] `)`
  761. //
  762. // expression-list ::= expression
  763. // ::= expression `,` expression-list
  764. return ParseParenList(
  765. [&] { return ParseExpression(); }, ParseNodeKind::CallExpressionComma(),
  766. [&](TokenizedBuffer::Token open_paren, bool /*is_single_item*/,
  767. TokenizedBuffer::Token close_paren, bool has_arg_errors) {
  768. AddLeafNode(ParseNodeKind::CallExpressionEnd(), close_paren);
  769. return AddNode(ParseNodeKind::CallExpression(), open_paren, start,
  770. has_errors || has_arg_errors);
  771. });
  772. }
  773. auto ParseTree::Parser::ParsePostfixExpression() -> llvm::Optional<Node> {
  774. RETURN_IF_STACK_LIMITED(llvm::None);
  775. auto start = GetSubtreeStartPosition();
  776. llvm::Optional<Node> expression = ParsePrimaryExpression();
  777. while (true) {
  778. switch (NextTokenKind()) {
  779. case TokenKind::Period():
  780. expression = ParseDesignatorExpression(
  781. start, ParseNodeKind::DesignatorExpression(), !expression);
  782. break;
  783. case TokenKind::OpenParen():
  784. expression = ParseCallExpression(start, !expression);
  785. break;
  786. default: {
  787. return expression;
  788. }
  789. }
  790. }
  791. }
  792. // Determines whether the given token is considered to be the start of an
  793. // operand according to the rules for infix operator parsing.
  794. static auto IsAssumedStartOfOperand(TokenKind kind) -> bool {
  795. return kind.IsOneOf({TokenKind::OpenParen(), TokenKind::Identifier(),
  796. TokenKind::IntegerLiteral(), TokenKind::RealLiteral(),
  797. TokenKind::StringLiteral()});
  798. }
  799. // Determines whether the given token is considered to be the end of an operand
  800. // according to the rules for infix operator parsing.
  801. static auto IsAssumedEndOfOperand(TokenKind kind) -> bool {
  802. return kind.IsOneOf({TokenKind::CloseParen(), TokenKind::CloseCurlyBrace(),
  803. TokenKind::CloseSquareBracket(), TokenKind::Identifier(),
  804. TokenKind::IntegerLiteral(), TokenKind::RealLiteral(),
  805. TokenKind::StringLiteral()});
  806. }
  807. // Determines whether the given token could possibly be the start of an operand.
  808. // This is conservatively correct, and will never incorrectly return `false`,
  809. // but can incorrectly return `true`.
  810. static auto IsPossibleStartOfOperand(TokenKind kind) -> bool {
  811. return !kind.IsOneOf({TokenKind::CloseParen(), TokenKind::CloseCurlyBrace(),
  812. TokenKind::CloseSquareBracket(), TokenKind::Comma(),
  813. TokenKind::Semi(), TokenKind::Colon()});
  814. }
  815. auto ParseTree::Parser::IsLexicallyValidInfixOperator() -> bool {
  816. CHECK(!AtEndOfFile()) << "Expected an operator token.";
  817. bool leading_space = tokens_.HasLeadingWhitespace(*position_);
  818. bool trailing_space = tokens_.HasTrailingWhitespace(*position_);
  819. // If there's whitespace on both sides, it's an infix operator.
  820. if (leading_space && trailing_space) {
  821. return true;
  822. }
  823. // If there's whitespace on exactly one side, it's not an infix operator.
  824. if (leading_space || trailing_space) {
  825. return false;
  826. }
  827. // Otherwise, for an infix operator, the preceding token must be any close
  828. // bracket, identifier, or literal and the next token must be an open paren,
  829. // identifier, or literal.
  830. if (position_ == tokens_.Tokens().begin() ||
  831. !IsAssumedEndOfOperand(tokens_.GetKind(*(position_ - 1))) ||
  832. !IsAssumedStartOfOperand(tokens_.GetKind(*(position_ + 1)))) {
  833. return false;
  834. }
  835. return true;
  836. }
  837. auto ParseTree::Parser::DiagnoseOperatorFixity(OperatorFixity fixity) -> void {
  838. bool is_valid_as_infix = IsLexicallyValidInfixOperator();
  839. if (fixity == OperatorFixity::Infix) {
  840. // Infix operators must satisfy the infix operator rules.
  841. if (!is_valid_as_infix) {
  842. emitter_.EmitError<BinaryOperatorRequiresWhitespace>(
  843. *position_,
  844. {.has_leading_space = tokens_.HasLeadingWhitespace(*position_),
  845. .has_trailing_space = tokens_.HasTrailingWhitespace(*position_)});
  846. }
  847. } else {
  848. bool prefix = fixity == OperatorFixity::Prefix;
  849. // Whitespace is not permitted between a symbolic pre/postfix operator and
  850. // its operand.
  851. if (NextTokenKind().IsSymbol() &&
  852. (prefix ? tokens_.HasTrailingWhitespace(*position_)
  853. : tokens_.HasLeadingWhitespace(*position_))) {
  854. emitter_.EmitError<UnaryOperatorHasWhitespace>(*position_,
  855. {.prefix = prefix});
  856. }
  857. // Pre/postfix operators must not satisfy the infix operator rules.
  858. if (is_valid_as_infix) {
  859. emitter_.EmitError<UnaryOperatorRequiresWhitespace>(*position_,
  860. {.prefix = prefix});
  861. }
  862. }
  863. }
  864. auto ParseTree::Parser::IsTrailingOperatorInfix() -> bool {
  865. if (AtEndOfFile()) {
  866. return false;
  867. }
  868. // An operator that follows the infix operator rules is parsed as
  869. // infix, unless the next token means that it can't possibly be.
  870. if (IsLexicallyValidInfixOperator() &&
  871. IsPossibleStartOfOperand(tokens_.GetKind(*(position_ + 1)))) {
  872. return true;
  873. }
  874. // A trailing operator with leading whitespace that's not valid as infix is
  875. // not valid at all. If the next token looks like the start of an operand,
  876. // then parse as infix, otherwise as postfix. Either way we'll produce a
  877. // diagnostic later on.
  878. if (tokens_.HasLeadingWhitespace(*position_) &&
  879. IsAssumedStartOfOperand(tokens_.GetKind(*(position_ + 1)))) {
  880. return true;
  881. }
  882. return false;
  883. }
  884. auto ParseTree::Parser::ParseOperatorExpression(
  885. PrecedenceGroup ambient_precedence) -> llvm::Optional<Node> {
  886. RETURN_IF_STACK_LIMITED(llvm::None);
  887. auto start = GetSubtreeStartPosition();
  888. llvm::Optional<Node> lhs;
  889. PrecedenceGroup lhs_precedence = PrecedenceGroup::ForPostfixExpression();
  890. // Check for a prefix operator.
  891. if (auto operator_precedence = PrecedenceGroup::ForLeading(NextTokenKind());
  892. !operator_precedence) {
  893. lhs = ParsePostfixExpression();
  894. } else {
  895. if (PrecedenceGroup::GetPriority(ambient_precedence,
  896. *operator_precedence) !=
  897. OperatorPriority::RightFirst) {
  898. // The precedence rules don't permit this prefix operator in this
  899. // context. Diagnose this, but carry on and parse it anyway.
  900. emitter_.EmitError<OperatorRequiresParentheses>(*position_);
  901. } else {
  902. // Check that this operator follows the proper whitespace rules.
  903. DiagnoseOperatorFixity(OperatorFixity::Prefix);
  904. }
  905. auto operator_token = Consume(NextTokenKind());
  906. bool has_errors = !ParseOperatorExpression(*operator_precedence);
  907. lhs = AddNode(ParseNodeKind::PrefixOperator(), operator_token, start,
  908. has_errors);
  909. lhs_precedence = *operator_precedence;
  910. }
  911. // Consume a sequence of infix and postfix operators.
  912. while (auto trailing_operator = PrecedenceGroup::ForTrailing(
  913. NextTokenKind(), IsTrailingOperatorInfix())) {
  914. auto [operator_precedence, is_binary] = *trailing_operator;
  915. // FIXME: If this operator is ambiguous with either the ambient precedence
  916. // or the LHS precedence, and there's a variant with a different fixity
  917. // that would work, use that one instead for error recovery.
  918. if (PrecedenceGroup::GetPriority(ambient_precedence, operator_precedence) !=
  919. OperatorPriority::RightFirst) {
  920. // The precedence rules don't permit this operator in this context. Try
  921. // again in the enclosing expression context.
  922. return lhs;
  923. }
  924. if (PrecedenceGroup::GetPriority(lhs_precedence, operator_precedence) !=
  925. OperatorPriority::LeftFirst) {
  926. // Either the LHS operator and this operator are ambiguous, or the
  927. // LHS operaor is a unary operator that can't be nested within
  928. // this operator. Either way, parentheses are required.
  929. emitter_.EmitError<OperatorRequiresParentheses>(*position_);
  930. lhs = llvm::None;
  931. } else {
  932. DiagnoseOperatorFixity(is_binary ? OperatorFixity::Infix
  933. : OperatorFixity::Postfix);
  934. }
  935. auto operator_token = Consume(NextTokenKind());
  936. if (is_binary) {
  937. auto rhs = ParseOperatorExpression(operator_precedence);
  938. lhs = AddNode(ParseNodeKind::InfixOperator(), operator_token, start,
  939. /*has_error=*/!lhs || !rhs);
  940. } else {
  941. lhs = AddNode(ParseNodeKind::PostfixOperator(), operator_token, start,
  942. /*has_error=*/!lhs);
  943. }
  944. lhs_precedence = operator_precedence;
  945. }
  946. return lhs;
  947. }
  948. auto ParseTree::Parser::ParseExpression() -> llvm::Optional<Node> {
  949. RETURN_IF_STACK_LIMITED(llvm::None);
  950. return ParseOperatorExpression(PrecedenceGroup::ForTopLevelExpression());
  951. }
  952. auto ParseTree::Parser::ParseType() -> llvm::Optional<Node> {
  953. RETURN_IF_STACK_LIMITED(llvm::None);
  954. return ParseOperatorExpression(PrecedenceGroup::ForType());
  955. }
  956. auto ParseTree::Parser::ParseExpressionStatement() -> llvm::Optional<Node> {
  957. RETURN_IF_STACK_LIMITED(llvm::None);
  958. TokenizedBuffer::Token start_token = *position_;
  959. auto start = GetSubtreeStartPosition();
  960. bool has_errors = !ParseExpression();
  961. if (auto semi = ConsumeIf(TokenKind::Semi())) {
  962. return AddNode(ParseNodeKind::ExpressionStatement(), *semi, start,
  963. has_errors);
  964. }
  965. if (!has_errors) {
  966. emitter_.EmitError<ExpectedSemiAfterExpression>(*position_);
  967. }
  968. if (auto recovery_node =
  969. SkipPastLikelyEnd(start_token, [&](TokenizedBuffer::Token semi) {
  970. return AddNode(ParseNodeKind::ExpressionStatement(), semi, start,
  971. true);
  972. })) {
  973. return recovery_node;
  974. }
  975. // Found junk not even followed by a `;`.
  976. return llvm::None;
  977. }
  978. auto ParseTree::Parser::ParseParenCondition(TokenKind introducer)
  979. -> llvm::Optional<Node> {
  980. RETURN_IF_STACK_LIMITED(llvm::None);
  981. // `(` expression `)`
  982. auto start = GetSubtreeStartPosition();
  983. auto open_paren = ConsumeIf(TokenKind::OpenParen());
  984. if (!open_paren) {
  985. emitter_.EmitError<ExpectedParenAfter>(*position_,
  986. {.introducer = introducer});
  987. }
  988. auto expr = ParseExpression();
  989. if (!open_paren) {
  990. // Don't expect a matching closing paren if there wasn't an opening paren.
  991. return llvm::None;
  992. }
  993. auto close_paren =
  994. ParseCloseParen(*open_paren, ParseNodeKind::ConditionEnd());
  995. return AddNode(ParseNodeKind::Condition(), *open_paren, start,
  996. /*has_error=*/!expr || !close_paren);
  997. }
  998. auto ParseTree::Parser::ParseIfStatement() -> llvm::Optional<Node> {
  999. auto start = GetSubtreeStartPosition();
  1000. auto if_token = Consume(TokenKind::IfKeyword());
  1001. auto cond = ParseParenCondition(TokenKind::IfKeyword());
  1002. auto then_case = ParseCodeBlock();
  1003. bool else_has_errors = false;
  1004. if (ConsumeAndAddLeafNodeIf(TokenKind::ElseKeyword(),
  1005. ParseNodeKind::IfStatementElse())) {
  1006. // 'else if' is permitted as a special case.
  1007. if (NextTokenIs(TokenKind::IfKeyword())) {
  1008. else_has_errors = !ParseIfStatement();
  1009. } else {
  1010. else_has_errors = !ParseCodeBlock();
  1011. }
  1012. }
  1013. return AddNode(ParseNodeKind::IfStatement(), if_token, start,
  1014. /*has_error=*/!cond || !then_case || else_has_errors);
  1015. }
  1016. auto ParseTree::Parser::ParseWhileStatement() -> llvm::Optional<Node> {
  1017. RETURN_IF_STACK_LIMITED(llvm::None);
  1018. auto start = GetSubtreeStartPosition();
  1019. auto while_token = Consume(TokenKind::WhileKeyword());
  1020. auto cond = ParseParenCondition(TokenKind::WhileKeyword());
  1021. auto body = ParseCodeBlock();
  1022. return AddNode(ParseNodeKind::WhileStatement(), while_token, start,
  1023. /*has_error=*/!cond || !body);
  1024. }
  1025. auto ParseTree::Parser::ParseKeywordStatement(ParseNodeKind kind,
  1026. KeywordStatementArgument argument)
  1027. -> llvm::Optional<Node> {
  1028. RETURN_IF_STACK_LIMITED(llvm::None);
  1029. auto keyword_kind = NextTokenKind();
  1030. assert(keyword_kind.IsKeyword());
  1031. auto start = GetSubtreeStartPosition();
  1032. auto keyword = Consume(keyword_kind);
  1033. bool arg_error = false;
  1034. if ((argument == KeywordStatementArgument::Optional &&
  1035. NextTokenKind() != TokenKind::Semi()) ||
  1036. argument == KeywordStatementArgument::Mandatory) {
  1037. arg_error = !ParseExpression();
  1038. }
  1039. auto semi =
  1040. ConsumeAndAddLeafNodeIf(TokenKind::Semi(), ParseNodeKind::StatementEnd());
  1041. if (!semi) {
  1042. emitter_.EmitError<ExpectedSemiAfter>(*position_,
  1043. {.preceding = keyword_kind});
  1044. // FIXME: Try to skip to a semicolon to recover.
  1045. }
  1046. return AddNode(kind, keyword, start, /*has_error=*/!semi || arg_error);
  1047. }
  1048. auto ParseTree::Parser::ParseStatement() -> llvm::Optional<Node> {
  1049. RETURN_IF_STACK_LIMITED(llvm::None);
  1050. switch (NextTokenKind()) {
  1051. case TokenKind::VarKeyword():
  1052. return ParseVariableDeclaration();
  1053. case TokenKind::IfKeyword():
  1054. return ParseIfStatement();
  1055. case TokenKind::WhileKeyword():
  1056. return ParseWhileStatement();
  1057. case TokenKind::ContinueKeyword():
  1058. return ParseKeywordStatement(ParseNodeKind::ContinueStatement(),
  1059. KeywordStatementArgument::None);
  1060. case TokenKind::BreakKeyword():
  1061. return ParseKeywordStatement(ParseNodeKind::BreakStatement(),
  1062. KeywordStatementArgument::None);
  1063. case TokenKind::ReturnKeyword():
  1064. return ParseKeywordStatement(ParseNodeKind::ReturnStatement(),
  1065. KeywordStatementArgument::Optional);
  1066. default:
  1067. // A statement with no introducer token can only be an expression
  1068. // statement.
  1069. return ParseExpressionStatement();
  1070. }
  1071. }
  1072. } // namespace Carbon