context.cpp 18 KB

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