context.cpp 18 KB

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