context.cpp 16 KB

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