context.cpp 17 KB

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