context.cpp 16 KB

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