context.cpp 18 KB

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