context.cpp 19 KB

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