parser_impl.cpp 37 KB

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