context.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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_ids.h"
  12. #include "toolchain/parse/node_kind.h"
  13. #include "toolchain/parse/state.h"
  14. #include "toolchain/parse/tree.h"
  15. #include "toolchain/parse/typed_nodes.h"
  16. namespace Carbon::Parse {
  17. // A relative location for characters in errors.
  18. enum class RelativeLoc : int8_t {
  19. Around,
  20. After,
  21. Before,
  22. };
  23. } // namespace Carbon::Parse
  24. // Adapts RelativeLoc for use with formatv.
  25. template <>
  26. struct llvm::format_provider<Carbon::Parse::RelativeLoc> {
  27. using RelativeLoc = Carbon::Parse::RelativeLoc;
  28. static void format(const RelativeLoc& loc, raw_ostream& out,
  29. StringRef /*style*/) {
  30. switch (loc) {
  31. case RelativeLoc::Around:
  32. out << "around";
  33. break;
  34. case RelativeLoc::After:
  35. out << "after";
  36. break;
  37. case RelativeLoc::Before:
  38. out << "before";
  39. break;
  40. }
  41. }
  42. };
  43. namespace Carbon::Parse {
  44. Context::Context(Tree& tree, Lex::TokenizedBuffer& tokens,
  45. Lex::TokenDiagnosticEmitter& emitter,
  46. llvm::raw_ostream* vlog_stream)
  47. : tree_(&tree),
  48. tokens_(&tokens),
  49. emitter_(&emitter),
  50. vlog_stream_(vlog_stream),
  51. position_(tokens_->tokens().begin()),
  52. end_(tokens_->tokens().end()) {
  53. CARBON_CHECK(position_ != end_) << "Empty TokenizedBuffer";
  54. --end_;
  55. CARBON_CHECK(tokens_->GetKind(*end_) == Lex::TokenKind::FileEnd)
  56. << "TokenizedBuffer should end with FileEnd, ended with "
  57. << tokens_->GetKind(*end_);
  58. }
  59. auto Context::AddLeafNode(NodeKind kind, Lex::TokenIndex token, bool has_error)
  60. -> void {
  61. kind.CheckMatchesTokenKind(tokens_->GetKind(token), has_error);
  62. tree_->node_impls_.push_back(
  63. Tree::NodeImpl(kind, has_error, token, /*subtree_size=*/1));
  64. if (has_error) {
  65. tree_->has_errors_ = true;
  66. }
  67. }
  68. auto Context::AddNode(NodeKind kind, Lex::TokenIndex token, int subtree_start,
  69. bool has_error) -> void {
  70. kind.CheckMatchesTokenKind(tokens_->GetKind(token), has_error);
  71. int subtree_size = tree_->size() - subtree_start + 1;
  72. tree_->node_impls_.push_back(
  73. Tree::NodeImpl(kind, has_error, token, subtree_size));
  74. if (has_error) {
  75. tree_->has_errors_ = true;
  76. }
  77. }
  78. auto Context::ReplacePlaceholderNode(int32_t position, NodeKind kind,
  79. Lex::TokenIndex token, bool has_error)
  80. -> void {
  81. CARBON_CHECK(position >= 0 && position < tree_->size())
  82. << "position: " << position << " size: " << tree_->size();
  83. auto* node_impl = &tree_->node_impls_[position];
  84. CARBON_CHECK(node_impl->subtree_size == 1);
  85. CARBON_CHECK(node_impl->kind == NodeKind::Placeholder);
  86. node_impl->kind = kind;
  87. node_impl->has_error = has_error;
  88. node_impl->token = token;
  89. if (has_error) {
  90. tree_->has_errors_ = true;
  91. }
  92. }
  93. auto Context::ConsumeAndAddOpenParen(Lex::TokenIndex default_token,
  94. NodeKind start_kind)
  95. -> std::optional<Lex::TokenIndex> {
  96. if (auto open_paren = ConsumeIf(Lex::TokenKind::OpenParen)) {
  97. AddLeafNode(start_kind, *open_paren, /*has_error=*/false);
  98. return open_paren;
  99. } else {
  100. CARBON_DIAGNOSTIC(ExpectedParenAfter, Error, "Expected `(` after `{0}`.",
  101. Lex::TokenKind);
  102. emitter_->Emit(*position_, ExpectedParenAfter,
  103. tokens().GetKind(default_token));
  104. AddLeafNode(start_kind, default_token, /*has_error=*/true);
  105. return std::nullopt;
  106. }
  107. }
  108. auto Context::ConsumeAndAddCloseSymbol(Lex::TokenIndex expected_open,
  109. StateStackEntry state,
  110. NodeKind close_kind) -> void {
  111. Lex::TokenKind open_token_kind = tokens().GetKind(expected_open);
  112. if (!open_token_kind.is_opening_symbol()) {
  113. AddNode(close_kind, state.token, state.subtree_start, /*has_error=*/true);
  114. } else if (auto close_token = ConsumeIf(open_token_kind.closing_symbol())) {
  115. AddNode(close_kind, *close_token, state.subtree_start, state.has_error);
  116. } else {
  117. // TODO: Include the location of the matching opening delimiter in the
  118. // diagnostic.
  119. CARBON_DIAGNOSTIC(ExpectedCloseSymbol, Error,
  120. "Unexpected tokens before `{0}`.", llvm::StringLiteral);
  121. emitter_->Emit(*position_, ExpectedCloseSymbol,
  122. open_token_kind.closing_symbol().fixed_spelling());
  123. SkipTo(tokens().GetMatchedClosingToken(expected_open));
  124. AddNode(close_kind, Consume(), state.subtree_start, /*has_error=*/true);
  125. }
  126. }
  127. auto Context::ConsumeAndAddLeafNodeIf(Lex::TokenKind token_kind,
  128. NodeKind node_kind) -> bool {
  129. auto token = ConsumeIf(token_kind);
  130. if (!token) {
  131. return false;
  132. }
  133. AddLeafNode(node_kind, *token);
  134. return true;
  135. }
  136. auto Context::ConsumeChecked(Lex::TokenKind kind) -> Lex::TokenIndex {
  137. CARBON_CHECK(PositionIs(kind))
  138. << "Required " << kind << ", found " << PositionKind();
  139. return Consume();
  140. }
  141. auto Context::ConsumeIf(Lex::TokenKind kind) -> std::optional<Lex::TokenIndex> {
  142. if (!PositionIs(kind)) {
  143. return std::nullopt;
  144. }
  145. return Consume();
  146. }
  147. auto Context::FindNextOf(std::initializer_list<Lex::TokenKind> desired_kinds)
  148. -> std::optional<Lex::TokenIndex> {
  149. auto new_position = position_;
  150. while (true) {
  151. Lex::TokenIndex token = *new_position;
  152. Lex::TokenKind kind = tokens().GetKind(token);
  153. if (kind.IsOneOf(desired_kinds)) {
  154. return token;
  155. }
  156. // Step to the next token at the current bracketing level.
  157. if (kind.is_closing_symbol() || kind == Lex::TokenKind::FileEnd) {
  158. // There are no more tokens at this level.
  159. return std::nullopt;
  160. } else if (kind.is_opening_symbol()) {
  161. new_position = Lex::TokenIterator(tokens().GetMatchedClosingToken(token));
  162. // Advance past the closing token.
  163. ++new_position;
  164. } else {
  165. ++new_position;
  166. }
  167. }
  168. }
  169. auto Context::SkipMatchingGroup() -> bool {
  170. if (!PositionKind().is_opening_symbol()) {
  171. return false;
  172. }
  173. SkipTo(tokens().GetMatchedClosingToken(*position_));
  174. ++position_;
  175. return true;
  176. }
  177. auto Context::SkipPastLikelyEnd(Lex::TokenIndex skip_root) -> Lex::TokenIndex {
  178. if (position_ == end_) {
  179. return *(position_ - 1);
  180. }
  181. Lex::LineIndex root_line = tokens().GetLine(skip_root);
  182. int root_line_indent = tokens().GetIndentColumnNumber(root_line);
  183. // We will keep scanning through tokens on the same line as the root or
  184. // lines with greater indentation than root's line.
  185. auto is_same_line_or_indent_greater_than_root = [&](Lex::TokenIndex t) {
  186. Lex::LineIndex l = tokens().GetLine(t);
  187. if (l == root_line) {
  188. return true;
  189. }
  190. return tokens().GetIndentColumnNumber(l) > root_line_indent;
  191. };
  192. do {
  193. if (PositionIs(Lex::TokenKind::CloseCurlyBrace)) {
  194. // Immediately bail out if we hit an unmatched close curly, this will
  195. // pop us up a level of the syntax grouping.
  196. return *(position_ - 1);
  197. }
  198. // We assume that a semicolon is always intended to be the end of the
  199. // current construct.
  200. if (auto semi = ConsumeIf(Lex::TokenKind::Semi)) {
  201. return *semi;
  202. }
  203. // Skip over any matching group of tokens().
  204. if (SkipMatchingGroup()) {
  205. continue;
  206. }
  207. // Otherwise just step forward one token.
  208. ++position_;
  209. } while (position_ != end_ &&
  210. is_same_line_or_indent_greater_than_root(*position_));
  211. return *(position_ - 1);
  212. }
  213. auto Context::SkipTo(Lex::TokenIndex t) -> void {
  214. CARBON_CHECK(t >= *position_) << "Tried to skip backwards from " << position_
  215. << " to " << Lex::TokenIterator(t);
  216. position_ = Lex::TokenIterator(t);
  217. CARBON_CHECK(position_ != end_) << "Skipped past EOF.";
  218. }
  219. // Determines whether the given token is considered to be the start of an
  220. // operand according to the rules for infix operator parsing.
  221. static auto IsAssumedStartOfOperand(Lex::TokenKind kind) -> bool {
  222. return kind.IsOneOf({Lex::TokenKind::OpenParen, Lex::TokenKind::Identifier,
  223. Lex::TokenKind::IntLiteral, Lex::TokenKind::RealLiteral,
  224. Lex::TokenKind::StringLiteral});
  225. }
  226. // Determines whether the given token is considered to be the end of an
  227. // operand according to the rules for infix operator parsing.
  228. static auto IsAssumedEndOfOperand(Lex::TokenKind kind) -> bool {
  229. return kind.IsOneOf(
  230. {Lex::TokenKind::CloseParen, Lex::TokenKind::CloseCurlyBrace,
  231. Lex::TokenKind::CloseSquareBracket, Lex::TokenKind::Identifier,
  232. Lex::TokenKind::IntLiteral, Lex::TokenKind::RealLiteral,
  233. Lex::TokenKind::StringLiteral});
  234. }
  235. // Determines whether the given token could possibly be the start of an
  236. // operand. This is conservatively correct, and will never incorrectly return
  237. // `false`, but can incorrectly return `true`.
  238. static auto IsPossibleStartOfOperand(Lex::TokenKind kind) -> bool {
  239. return !kind.IsOneOf(
  240. {Lex::TokenKind::CloseParen, Lex::TokenKind::CloseCurlyBrace,
  241. Lex::TokenKind::CloseSquareBracket, Lex::TokenKind::Comma,
  242. Lex::TokenKind::Semi, Lex::TokenKind::Colon});
  243. }
  244. auto Context::IsLexicallyValidInfixOperator() -> bool {
  245. CARBON_CHECK(position_ != end_) << "Expected an operator token.";
  246. bool leading_space = tokens().HasLeadingWhitespace(*position_);
  247. bool trailing_space = tokens().HasTrailingWhitespace(*position_);
  248. // If there's whitespace on both sides, it's an infix operator.
  249. if (leading_space && trailing_space) {
  250. return true;
  251. }
  252. // If there's whitespace on exactly one side, it's not an infix operator.
  253. if (leading_space || trailing_space) {
  254. return false;
  255. }
  256. // Otherwise, for an infix operator, the preceding token must be any close
  257. // bracket, identifier, or literal and the next token must be an open paren,
  258. // identifier, or literal.
  259. if (position_ == tokens().tokens().begin() ||
  260. !IsAssumedEndOfOperand(tokens().GetKind(*(position_ - 1))) ||
  261. !IsAssumedStartOfOperand(tokens().GetKind(*(position_ + 1)))) {
  262. return false;
  263. }
  264. return true;
  265. }
  266. auto Context::IsTrailingOperatorInfix() -> bool {
  267. if (position_ == end_) {
  268. return false;
  269. }
  270. // An operator that follows the infix operator rules is parsed as
  271. // infix, unless the next token means that it can't possibly be.
  272. if (IsLexicallyValidInfixOperator() &&
  273. IsPossibleStartOfOperand(tokens().GetKind(*(position_ + 1)))) {
  274. return true;
  275. }
  276. // A trailing operator with leading whitespace that's not valid as infix is
  277. // not valid at all. If the next token looks like the start of an operand,
  278. // then parse as infix, otherwise as postfix. Either way we'll produce a
  279. // diagnostic later on.
  280. if (tokens().HasLeadingWhitespace(*position_) &&
  281. IsAssumedStartOfOperand(tokens().GetKind(*(position_ + 1)))) {
  282. return true;
  283. }
  284. return false;
  285. }
  286. auto Context::DiagnoseOperatorFixity(OperatorFixity fixity) -> void {
  287. if (!PositionKind().is_symbol()) {
  288. // Whitespace-based fixity rules only apply to symbolic operators.
  289. return;
  290. }
  291. if (fixity == OperatorFixity::Infix) {
  292. // Infix operators must satisfy the infix operator rules.
  293. if (!IsLexicallyValidInfixOperator()) {
  294. CARBON_DIAGNOSTIC(BinaryOperatorRequiresWhitespace, Error,
  295. "Whitespace missing {0} binary operator.", RelativeLoc);
  296. emitter_->Emit(*position_, BinaryOperatorRequiresWhitespace,
  297. tokens().HasLeadingWhitespace(*position_)
  298. ? RelativeLoc::After
  299. : (tokens().HasTrailingWhitespace(*position_)
  300. ? RelativeLoc::Before
  301. : RelativeLoc::Around));
  302. }
  303. } else {
  304. bool prefix = fixity == OperatorFixity::Prefix;
  305. // Whitespace is not permitted between a symbolic pre/postfix operator and
  306. // its operand.
  307. if ((prefix ? tokens().HasTrailingWhitespace(*position_)
  308. : tokens().HasLeadingWhitespace(*position_))) {
  309. CARBON_DIAGNOSTIC(UnaryOperatorHasWhitespace, Error,
  310. "Whitespace is not allowed {0} this unary operator.",
  311. RelativeLoc);
  312. emitter_->Emit(*position_, UnaryOperatorHasWhitespace,
  313. prefix ? RelativeLoc::After : RelativeLoc::Before);
  314. } else if (IsLexicallyValidInfixOperator()) {
  315. // Pre/postfix operators must not satisfy the infix operator rules.
  316. CARBON_DIAGNOSTIC(UnaryOperatorRequiresWhitespace, Error,
  317. "Whitespace is required {0} this unary operator.",
  318. RelativeLoc);
  319. emitter_->Emit(*position_, UnaryOperatorRequiresWhitespace,
  320. prefix ? RelativeLoc::Before : RelativeLoc::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::AddNodeExpectingDeclSemi(StateStackEntry state,
  351. NodeKind node_kind,
  352. Lex::TokenKind decl_kind,
  353. bool is_def_allowed) -> void {
  354. // TODO: This could better handle things like:
  355. // base: { }
  356. // var n: i32;
  357. // ^ Ends up at `n`, instead of `var`.
  358. if (state.has_error) {
  359. RecoverFromDeclError(state, node_kind,
  360. /*skip_past_likely_end=*/true);
  361. return;
  362. }
  363. if (auto semi = ConsumeIf(Lex::TokenKind::Semi)) {
  364. AddNode(node_kind, *semi, state.subtree_start, /*has_error=*/false);
  365. } else {
  366. if (is_def_allowed) {
  367. DiagnoseExpectedDeclSemiOrDefinition(decl_kind);
  368. } else {
  369. DiagnoseExpectedDeclSemi(decl_kind);
  370. }
  371. RecoverFromDeclError(state, node_kind,
  372. /*skip_past_likely_end=*/true);
  373. }
  374. }
  375. auto Context::RecoverFromDeclError(StateStackEntry state, NodeKind node_kind,
  376. bool skip_past_likely_end) -> void {
  377. auto token = state.token;
  378. if (skip_past_likely_end) {
  379. token = SkipPastLikelyEnd(token);
  380. }
  381. AddNode(node_kind, token, state.subtree_start,
  382. /*has_error=*/true);
  383. }
  384. auto Context::DiagnoseExpectedDeclSemi(Lex::TokenKind expected_kind) -> void {
  385. CARBON_DIAGNOSTIC(ExpectedDeclSemi, Error,
  386. "`{0}` declarations must end with a `;`.", Lex::TokenKind);
  387. emitter().Emit(*position(), ExpectedDeclSemi, expected_kind);
  388. }
  389. auto Context::DiagnoseExpectedDeclSemiOrDefinition(Lex::TokenKind expected_kind)
  390. -> void {
  391. CARBON_DIAGNOSTIC(ExpectedDeclSemiOrDefinition, Error,
  392. "`{0}` declarations must either end with a `;` or "
  393. "have a `{{ ... }` block for a definition.",
  394. Lex::TokenKind);
  395. emitter().Emit(*position(), ExpectedDeclSemiOrDefinition, expected_kind);
  396. }
  397. // Returns whether we are currently parsing in a scope in which function
  398. // definitions are deferred, such as a class or interface.
  399. static auto ParsingInDeferredDefinitionScope(Context& context) -> bool {
  400. auto& stack = context.state_stack();
  401. if (stack.size() < 2 || stack.back().state != State::DeclScopeLoop) {
  402. return false;
  403. }
  404. auto state = stack[stack.size() - 2].state;
  405. return state == State::DeclDefinitionFinishAsClass ||
  406. state == State::DeclDefinitionFinishAsImpl ||
  407. state == State::DeclDefinitionFinishAsInterface ||
  408. state == State::DeclDefinitionFinishAsNamedConstraint;
  409. }
  410. auto Context::AddFunctionDefinitionStart(Lex::TokenIndex token,
  411. int subtree_start, bool has_error)
  412. -> void {
  413. if (ParsingInDeferredDefinitionScope(*this)) {
  414. enclosing_deferred_definition_stack_.push_back(
  415. tree_->deferred_definitions_.Add(
  416. {.start_id = FunctionDefinitionStartId(
  417. NodeId(tree_->node_impls_.size()))}));
  418. }
  419. AddNode(NodeKind::FunctionDefinitionStart, token, subtree_start, has_error);
  420. }
  421. auto Context::AddFunctionDefinition(Lex::TokenIndex token, int subtree_start,
  422. bool has_error) -> void {
  423. if (ParsingInDeferredDefinitionScope(*this)) {
  424. auto definition_index = enclosing_deferred_definition_stack_.pop_back_val();
  425. auto& definition = tree_->deferred_definitions_.Get(definition_index);
  426. definition.definition_id =
  427. FunctionDefinitionId(NodeId(tree_->node_impls_.size()));
  428. definition.next_definition_index =
  429. DeferredDefinitionIndex(tree_->deferred_definitions().size());
  430. }
  431. AddNode(NodeKind::FunctionDefinition, token, subtree_start, has_error);
  432. }
  433. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  434. output << "Parser stack:\n";
  435. for (auto [i, entry] : llvm::enumerate(state_stack_)) {
  436. output << "\t" << i << ".\t" << entry.state;
  437. PrintTokenForStackDump(output, entry.token);
  438. }
  439. output << "\tcursor\tposition_";
  440. PrintTokenForStackDump(output, *position_);
  441. }
  442. auto Context::PrintTokenForStackDump(llvm::raw_ostream& output,
  443. Lex::TokenIndex token) const -> void {
  444. output << " @ " << tokens_->GetLineNumber(tokens_->GetLine(token)) << ":"
  445. << tokens_->GetColumnNumber(token) << ": token " << token << " : "
  446. << tokens_->GetKind(token) << "\n";
  447. }
  448. } // namespace Carbon::Parse