parser_impl.cpp 42 KB

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