parser_context.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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_context.h"
  5. #include <cstdlib>
  6. #include <memory>
  7. #include <optional>
  8. #include "common/check.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. // A relative location for characters in errors.
  15. enum class RelativeLocation : int8_t {
  16. Around,
  17. After,
  18. Before,
  19. };
  20. // Adapts RelativeLocation for use with formatv.
  21. static auto operator<<(llvm::raw_ostream& out, RelativeLocation loc)
  22. -> llvm::raw_ostream& {
  23. switch (loc) {
  24. case RelativeLocation::Around:
  25. out << "around";
  26. break;
  27. case RelativeLocation::After:
  28. out << "after";
  29. break;
  30. case RelativeLocation::Before:
  31. out << "before";
  32. break;
  33. }
  34. return out;
  35. }
  36. ParserContext::ParserContext(ParseTree& tree, TokenizedBuffer& tokens,
  37. TokenDiagnosticEmitter& emitter,
  38. llvm::raw_ostream* vlog_stream)
  39. : tree_(&tree),
  40. tokens_(&tokens),
  41. emitter_(&emitter),
  42. vlog_stream_(vlog_stream),
  43. position_(tokens_->tokens().begin()),
  44. end_(tokens_->tokens().end()) {
  45. CARBON_CHECK(position_ != end_) << "Empty TokenizedBuffer";
  46. --end_;
  47. CARBON_CHECK(tokens_->GetKind(*end_) == TokenKind::EndOfFile)
  48. << "TokenizedBuffer should end with EndOfFile, ended with "
  49. << tokens_->GetKind(*end_);
  50. }
  51. auto ParserContext::AddLeafNode(ParseNodeKind kind,
  52. TokenizedBuffer::Token token, bool has_error)
  53. -> void {
  54. tree_->node_impls_.push_back(
  55. ParseTree::NodeImpl(kind, has_error, token, /*subtree_size=*/1));
  56. if (has_error) {
  57. tree_->has_errors_ = true;
  58. }
  59. }
  60. auto ParserContext::AddNode(ParseNodeKind kind, TokenizedBuffer::Token token,
  61. int subtree_start, bool has_error) -> void {
  62. int subtree_size = tree_->size() - subtree_start + 1;
  63. tree_->node_impls_.push_back(
  64. ParseTree::NodeImpl(kind, has_error, token, subtree_size));
  65. if (has_error) {
  66. tree_->has_errors_ = true;
  67. }
  68. }
  69. auto ParserContext::ConsumeAndAddOpenParen(TokenizedBuffer::Token default_token,
  70. ParseNodeKind start_kind) -> void {
  71. if (auto open_paren = ConsumeIf(TokenKind::OpenParen)) {
  72. AddLeafNode(start_kind, *open_paren, /*has_error=*/false);
  73. } else {
  74. CARBON_DIAGNOSTIC(ExpectedParenAfter, Error, "Expected `(` after `{0}`.",
  75. TokenKind);
  76. emitter_->Emit(*position_, ExpectedParenAfter,
  77. tokens().GetKind(default_token));
  78. AddLeafNode(start_kind, default_token, /*has_error=*/true);
  79. }
  80. }
  81. auto ParserContext::ConsumeAndAddCloseSymbol(
  82. TokenizedBuffer::Token expected_open, StateStackEntry state,
  83. ParseNodeKind close_kind) -> void {
  84. TokenKind open_token_kind = tokens().GetKind(expected_open);
  85. if (!open_token_kind.is_opening_symbol()) {
  86. AddNode(close_kind, state.token, state.subtree_start, /*has_error=*/true);
  87. } else if (auto close_token = ConsumeIf(open_token_kind.closing_symbol())) {
  88. AddNode(close_kind, *close_token, state.subtree_start, state.has_error);
  89. } else {
  90. // TODO: Include the location of the matching opening delimiter in the
  91. // diagnostic.
  92. CARBON_DIAGNOSTIC(ExpectedCloseSymbol, Error,
  93. "Unexpected tokens before `{0}`.", llvm::StringRef);
  94. emitter_->Emit(*position_, ExpectedCloseSymbol,
  95. open_token_kind.closing_symbol().fixed_spelling());
  96. SkipTo(tokens().GetMatchedClosingToken(expected_open));
  97. AddNode(close_kind, Consume(), state.subtree_start, /*has_error=*/true);
  98. }
  99. }
  100. auto ParserContext::ConsumeAndAddLeafNodeIf(TokenKind token_kind,
  101. ParseNodeKind node_kind) -> bool {
  102. auto token = ConsumeIf(token_kind);
  103. if (!token) {
  104. return false;
  105. }
  106. AddLeafNode(node_kind, *token);
  107. return true;
  108. }
  109. auto ParserContext::ConsumeChecked(TokenKind kind) -> TokenizedBuffer::Token {
  110. CARBON_CHECK(PositionIs(kind))
  111. << "Required " << kind << ", found " << PositionKind();
  112. return Consume();
  113. }
  114. auto ParserContext::ConsumeIf(TokenKind kind)
  115. -> std::optional<TokenizedBuffer::Token> {
  116. if (!PositionIs(kind)) {
  117. return std::nullopt;
  118. }
  119. return Consume();
  120. }
  121. auto ParserContext::ConsumeIfPatternKeyword(TokenKind keyword_token,
  122. ParserState keyword_state,
  123. int subtree_start) -> void {
  124. if (auto token = ConsumeIf(keyword_token)) {
  125. PushState(ParserContext::StateStackEntry(
  126. keyword_state, PrecedenceGroup::ForTopLevelExpression(),
  127. PrecedenceGroup::ForTopLevelExpression(), *token, subtree_start));
  128. }
  129. }
  130. auto ParserContext::FindNextOf(std::initializer_list<TokenKind> desired_kinds)
  131. -> std::optional<TokenizedBuffer::Token> {
  132. auto new_position = position_;
  133. while (true) {
  134. TokenizedBuffer::Token token = *new_position;
  135. TokenKind kind = tokens().GetKind(token);
  136. if (kind.IsOneOf(desired_kinds)) {
  137. return token;
  138. }
  139. // Step to the next token at the current bracketing level.
  140. if (kind.is_closing_symbol() || kind == TokenKind::EndOfFile) {
  141. // There are no more tokens at this level.
  142. return std::nullopt;
  143. } else if (kind.is_opening_symbol()) {
  144. new_position = TokenizedBuffer::TokenIterator(
  145. tokens().GetMatchedClosingToken(token));
  146. // Advance past the closing token.
  147. ++new_position;
  148. } else {
  149. ++new_position;
  150. }
  151. }
  152. }
  153. auto ParserContext::SkipMatchingGroup() -> bool {
  154. if (!PositionKind().is_opening_symbol()) {
  155. return false;
  156. }
  157. SkipTo(tokens().GetMatchedClosingToken(*position_));
  158. ++position_;
  159. return true;
  160. }
  161. auto ParserContext::SkipPastLikelyEnd(TokenizedBuffer::Token skip_root)
  162. -> std::optional<TokenizedBuffer::Token> {
  163. if (position_ == end_) {
  164. return std::nullopt;
  165. }
  166. TokenizedBuffer::Line root_line = tokens().GetLine(skip_root);
  167. int root_line_indent = tokens().GetIndentColumnNumber(root_line);
  168. // We will keep scanning through tokens on the same line as the root or
  169. // lines with greater indentation than root's line.
  170. auto is_same_line_or_indent_greater_than_root =
  171. [&](TokenizedBuffer::Token t) {
  172. TokenizedBuffer::Line l = tokens().GetLine(t);
  173. if (l == root_line) {
  174. return true;
  175. }
  176. return tokens().GetIndentColumnNumber(l) > root_line_indent;
  177. };
  178. do {
  179. if (PositionIs(TokenKind::CloseCurlyBrace)) {
  180. // Immediately bail out if we hit an unmatched close curly, this will
  181. // pop us up a level of the syntax grouping.
  182. return std::nullopt;
  183. }
  184. // We assume that a semicolon is always intended to be the end of the
  185. // current construct.
  186. if (auto semi = ConsumeIf(TokenKind::Semi)) {
  187. return semi;
  188. }
  189. // Skip over any matching group of tokens().
  190. if (SkipMatchingGroup()) {
  191. continue;
  192. }
  193. // Otherwise just step forward one token.
  194. ++position_;
  195. } while (position_ != end_ &&
  196. is_same_line_or_indent_greater_than_root(*position_));
  197. return std::nullopt;
  198. }
  199. auto ParserContext::SkipTo(TokenizedBuffer::Token t) -> void {
  200. CARBON_CHECK(t >= *position_) << "Tried to skip backwards from " << position_
  201. << " to " << TokenizedBuffer::TokenIterator(t);
  202. position_ = TokenizedBuffer::TokenIterator(t);
  203. CARBON_CHECK(position_ != end_) << "Skipped past EOF.";
  204. }
  205. // Determines whether the given token is considered to be the start of an
  206. // operand according to the rules for infix operator parsing.
  207. static auto IsAssumedStartOfOperand(TokenKind kind) -> bool {
  208. return kind.IsOneOf({TokenKind::OpenParen, TokenKind::Identifier,
  209. TokenKind::IntegerLiteral, TokenKind::RealLiteral,
  210. TokenKind::StringLiteral});
  211. }
  212. // Determines whether the given token is considered to be the end of an
  213. // operand according to the rules for infix operator parsing.
  214. static auto IsAssumedEndOfOperand(TokenKind kind) -> bool {
  215. return kind.IsOneOf({TokenKind::CloseParen, TokenKind::CloseCurlyBrace,
  216. TokenKind::CloseSquareBracket, TokenKind::Identifier,
  217. TokenKind::IntegerLiteral, TokenKind::RealLiteral,
  218. TokenKind::StringLiteral});
  219. }
  220. // Determines whether the given token could possibly be the start of an
  221. // operand. This is conservatively correct, and will never incorrectly return
  222. // `false`, but can incorrectly return `true`.
  223. static auto IsPossibleStartOfOperand(TokenKind kind) -> bool {
  224. return !kind.IsOneOf({TokenKind::CloseParen, TokenKind::CloseCurlyBrace,
  225. TokenKind::CloseSquareBracket, TokenKind::Comma,
  226. TokenKind::Semi, TokenKind::Colon});
  227. }
  228. auto ParserContext::IsLexicallyValidInfixOperator() -> bool {
  229. CARBON_CHECK(position_ != end_) << "Expected an operator token.";
  230. bool leading_space = tokens().HasLeadingWhitespace(*position_);
  231. bool trailing_space = tokens().HasTrailingWhitespace(*position_);
  232. // If there's whitespace on both sides, it's an infix operator.
  233. if (leading_space && trailing_space) {
  234. return true;
  235. }
  236. // If there's whitespace on exactly one side, it's not an infix operator.
  237. if (leading_space || trailing_space) {
  238. return false;
  239. }
  240. // Otherwise, for an infix operator, the preceding token must be any close
  241. // bracket, identifier, or literal and the next token must be an open paren,
  242. // identifier, or literal.
  243. if (position_ == tokens().tokens().begin() ||
  244. !IsAssumedEndOfOperand(tokens().GetKind(*(position_ - 1))) ||
  245. !IsAssumedStartOfOperand(tokens().GetKind(*(position_ + 1)))) {
  246. return false;
  247. }
  248. return true;
  249. }
  250. auto ParserContext::IsTrailingOperatorInfix() -> bool {
  251. if (position_ == end_) {
  252. return false;
  253. }
  254. // An operator that follows the infix operator rules is parsed as
  255. // infix, unless the next token means that it can't possibly be.
  256. if (IsLexicallyValidInfixOperator() &&
  257. IsPossibleStartOfOperand(tokens().GetKind(*(position_ + 1)))) {
  258. return true;
  259. }
  260. // A trailing operator with leading whitespace that's not valid as infix is
  261. // not valid at all. If the next token looks like the start of an operand,
  262. // then parse as infix, otherwise as postfix. Either way we'll produce a
  263. // diagnostic later on.
  264. if (tokens().HasLeadingWhitespace(*position_) &&
  265. IsAssumedStartOfOperand(tokens().GetKind(*(position_ + 1)))) {
  266. return true;
  267. }
  268. return false;
  269. }
  270. auto ParserContext::DiagnoseOperatorFixity(OperatorFixity fixity) -> void {
  271. if (!PositionKind().is_symbol()) {
  272. // Whitespace-based fixity rules only apply to symbolic operators.
  273. return;
  274. }
  275. if (fixity == OperatorFixity::Infix) {
  276. // Infix operators must satisfy the infix operator rules.
  277. if (!IsLexicallyValidInfixOperator()) {
  278. CARBON_DIAGNOSTIC(BinaryOperatorRequiresWhitespace, Error,
  279. "Whitespace missing {0} binary operator.",
  280. RelativeLocation);
  281. emitter_->Emit(*position_, BinaryOperatorRequiresWhitespace,
  282. tokens().HasLeadingWhitespace(*position_)
  283. ? RelativeLocation::After
  284. : (tokens().HasTrailingWhitespace(*position_)
  285. ? RelativeLocation::Before
  286. : RelativeLocation::Around));
  287. }
  288. } else {
  289. bool prefix = fixity == OperatorFixity::Prefix;
  290. // Whitespace is not permitted between a symbolic pre/postfix operator and
  291. // its operand.
  292. if ((prefix ? tokens().HasTrailingWhitespace(*position_)
  293. : tokens().HasLeadingWhitespace(*position_))) {
  294. CARBON_DIAGNOSTIC(UnaryOperatorHasWhitespace, Error,
  295. "Whitespace is not allowed {0} this unary operator.",
  296. RelativeLocation);
  297. emitter_->Emit(
  298. *position_, UnaryOperatorHasWhitespace,
  299. prefix ? RelativeLocation::After : RelativeLocation::Before);
  300. } else if (IsLexicallyValidInfixOperator()) {
  301. // Pre/postfix operators must not satisfy the infix operator rules.
  302. CARBON_DIAGNOSTIC(UnaryOperatorRequiresWhitespace, Error,
  303. "Whitespace is required {0} this unary operator.",
  304. RelativeLocation);
  305. emitter_->Emit(
  306. *position_, UnaryOperatorRequiresWhitespace,
  307. prefix ? RelativeLocation::Before : RelativeLocation::After);
  308. }
  309. }
  310. }
  311. auto ParserContext::ConsumeListToken(ParseNodeKind comma_kind,
  312. TokenKind close_kind,
  313. bool already_has_error) -> ListTokenKind {
  314. if (!PositionIs(TokenKind::Comma) && !PositionIs(close_kind)) {
  315. // Don't error a second time on the same element.
  316. if (!already_has_error) {
  317. CARBON_DIAGNOSTIC(UnexpectedTokenAfterListElement, Error,
  318. "Expected `,` or `{0}`.", TokenKind);
  319. emitter_->Emit(*position_, UnexpectedTokenAfterListElement, close_kind);
  320. ReturnErrorOnState();
  321. }
  322. // Recover from the invalid token.
  323. auto end_of_element = FindNextOf({TokenKind::Comma, close_kind});
  324. // The lexer guarantees that parentheses are balanced.
  325. CARBON_CHECK(end_of_element)
  326. << "missing matching `" << close_kind.opening_symbol() << "` for `"
  327. << close_kind << "`";
  328. SkipTo(*end_of_element);
  329. }
  330. if (PositionIs(close_kind)) {
  331. return ListTokenKind::Close;
  332. } else {
  333. AddLeafNode(comma_kind, Consume());
  334. return PositionIs(close_kind) ? ListTokenKind::CommaClose
  335. : ListTokenKind::Comma;
  336. }
  337. }
  338. auto ParserContext::GetDeclarationContext() -> DeclarationContext {
  339. // i == 0 is the file-level DeclarationScopeLoop. Additionally, i == 1 can be
  340. // skipped because it will never be a DeclarationScopeLoop.
  341. for (int i = state_stack_.size() - 1; i > 1; --i) {
  342. // The declaration context is always the state _above_ a
  343. // DeclarationScopeLoop.
  344. if (state_stack_[i].state == ParserState::DeclarationScopeLoop) {
  345. switch (state_stack_[i - 1].state) {
  346. case ParserState::TypeDefinitionFinishAsClass:
  347. return DeclarationContext::Class;
  348. case ParserState::TypeDefinitionFinishAsInterface:
  349. return DeclarationContext::Interface;
  350. case ParserState::TypeDefinitionFinishAsNamedConstraint:
  351. return DeclarationContext::NamedConstraint;
  352. default:
  353. llvm_unreachable("Missing handling for a declaration scope");
  354. }
  355. }
  356. }
  357. CARBON_CHECK(!state_stack_.empty() &&
  358. state_stack_[0].state == ParserState::DeclarationScopeLoop);
  359. return DeclarationContext::File;
  360. }
  361. auto ParserContext::RecoverFromDeclarationError(StateStackEntry state,
  362. ParseNodeKind parse_node_kind,
  363. bool skip_past_likely_end)
  364. -> void {
  365. auto token = state.token;
  366. if (skip_past_likely_end) {
  367. if (auto semi = SkipPastLikelyEnd(token)) {
  368. token = *semi;
  369. }
  370. }
  371. AddNode(parse_node_kind, token, state.subtree_start,
  372. /*has_error=*/true);
  373. }
  374. auto ParserContext::EmitExpectedDeclarationSemi(TokenKind expected_kind)
  375. -> void {
  376. CARBON_DIAGNOSTIC(ExpectedDeclarationSemi, Error,
  377. "`{0}` declarations must end with a `;`.", TokenKind);
  378. emitter().Emit(*position(), ExpectedDeclarationSemi, expected_kind);
  379. }
  380. auto ParserContext::EmitExpectedDeclarationSemiOrDefinition(
  381. TokenKind expected_kind) -> void {
  382. CARBON_DIAGNOSTIC(ExpectedDeclarationSemiOrDefinition, Error,
  383. "`{0}` declarations must either end with a `;` or "
  384. "have a `{{ ... }` block for a definition.",
  385. TokenKind);
  386. emitter().Emit(*position(), ExpectedDeclarationSemiOrDefinition,
  387. expected_kind);
  388. }
  389. auto ParserContext::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  390. output << "Parser stack:\n";
  391. for (int i = 0; i < static_cast<int>(state_stack_.size()); ++i) {
  392. const auto& entry = state_stack_[i];
  393. output << "\t" << i << ".\t" << entry.state;
  394. PrintTokenForStackDump(output, entry.token);
  395. }
  396. output << "\tcursor\tposition_";
  397. PrintTokenForStackDump(output, *position_);
  398. }
  399. auto ParserContext::PrintTokenForStackDump(llvm::raw_ostream& output,
  400. TokenizedBuffer::Token token) const
  401. -> void {
  402. output << " @ " << tokens_->GetLineNumber(tokens_->GetLine(token)) << ":"
  403. << tokens_->GetColumnNumber(token) << ": token " << token << " : "
  404. << tokens_->GetKind(token) << "\n";
  405. }
  406. } // namespace Carbon