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