context.cpp 18 KB

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