1 use super::pat::Expected;
3 BlockMode, CommaRecoveryMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep,
4 TokenExpectType, TokenType,
7 AmbiguousPlus, AttributeOnParamType, BadQPathStage2, BadTypePlus, BadTypePlusSub,
8 ComparisonOperatorsCannotBeChained, ComparisonOperatorsCannotBeChainedSugg,
9 ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, DocCommentOnParamType,
10 DoubleColonInBound, ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg,
11 GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg, InInTypo,
12 IncorrectAwait, IncorrectSemicolon, IncorrectUseOfAwait, ParenthesesInForHead,
13 ParenthesesInForHeadSugg, PatternMethodParamWithoutBody, QuestionMarkInType,
14 QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath,
15 StructLiteralBodyWithoutPathSugg, StructLiteralNeedingParens, StructLiteralNeedingParensSugg,
16 SuggEscapeToUseAsIdentifier, SuggRemoveComma, UnexpectedConstInGenericParam,
17 UnexpectedConstParamDeclaration, UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets,
21 use crate::lexer::UnmatchedBrace;
24 use rustc_ast::ptr::P;
25 use rustc_ast::token::{self, Delimiter, Lit, LitKind, TokenKind};
26 use rustc_ast::util::parser::AssocOp;
28 AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingAnnotation, Block,
29 BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Param, Pat, PatKind,
30 Path, PathSegment, QSelf, Ty, TyKind,
32 use rustc_ast_pretty::pprust;
33 use rustc_data_structures::fx::FxHashSet;
35 fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, FatalError, Handler, MultiSpan,
38 use rustc_errors::{pluralize, Diagnostic, ErrorGuaranteed, IntoDiagnostic};
39 use rustc_session::errors::ExprParenthesesNeeded;
40 use rustc_span::source_map::Spanned;
41 use rustc_span::symbol::{kw, sym, Ident};
42 use rustc_span::{Span, SpanSnippetError, DUMMY_SP};
44 use std::ops::{Deref, DerefMut};
45 use thin_vec::{thin_vec, ThinVec};
47 /// Creates a placeholder argument.
48 pub(super) fn dummy_arg(ident: Ident) -> Param {
50 id: ast::DUMMY_NODE_ID,
51 kind: PatKind::Ident(BindingAnnotation::NONE, ident, None),
55 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
57 attrs: AttrVec::default(),
58 id: ast::DUMMY_NODE_ID,
62 is_placeholder: false,
66 pub(super) trait RecoverQPath: Sized + 'static {
67 const PATH_STYLE: PathStyle = PathStyle::Expr;
68 fn to_ty(&self) -> Option<P<Ty>>;
69 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self;
72 impl RecoverQPath for Ty {
73 const PATH_STYLE: PathStyle = PathStyle::Type;
74 fn to_ty(&self) -> Option<P<Ty>> {
77 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
80 kind: TyKind::Path(qself, path),
81 id: ast::DUMMY_NODE_ID,
87 impl RecoverQPath for Pat {
88 fn to_ty(&self) -> Option<P<Ty>> {
91 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
94 kind: PatKind::Path(qself, path),
95 id: ast::DUMMY_NODE_ID,
101 impl RecoverQPath for Expr {
102 fn to_ty(&self) -> Option<P<Ty>> {
105 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
108 kind: ExprKind::Path(qself, path),
109 attrs: AttrVec::new(),
110 id: ast::DUMMY_NODE_ID,
116 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
117 pub(crate) enum ConsumeClosingDelim {
122 #[derive(Clone, Copy)]
123 pub enum AttemptLocalParseRecovery {
128 impl AttemptLocalParseRecovery {
129 pub fn yes(&self) -> bool {
131 AttemptLocalParseRecovery::Yes => true,
132 AttemptLocalParseRecovery::No => false,
136 pub fn no(&self) -> bool {
138 AttemptLocalParseRecovery::Yes => false,
139 AttemptLocalParseRecovery::No => true,
144 /// Information for emitting suggestions and recovering from
145 /// C-style `i++`, `--i`, etc.
146 #[derive(Debug, Copy, Clone)]
147 struct IncDecRecovery {
148 /// Is this increment/decrement its own statement?
149 standalone: IsStandalone,
150 /// Is this an increment or decrement?
152 /// Is this pre- or postfix?
156 /// Is an increment or decrement expression its own statement?
157 #[derive(Debug, Copy, Clone)]
159 /// It's standalone, i.e., its own statement.
161 /// It's a subexpression, i.e., *not* standalone.
165 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
168 // FIXME: `i--` recovery isn't implemented yet
173 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
180 fn chr(&self) -> char {
187 fn name(&self) -> &'static str {
189 Self::Inc => "increment",
190 Self::Dec => "decrement",
195 impl std::fmt::Display for UnaryFixity {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198 Self::Pre => write!(f, "prefix"),
199 Self::Post => write!(f, "postfix"),
206 patches: Vec<(Span, String)>,
207 applicability: Applicability,
211 fn emit(self, err: &mut Diagnostic) {
212 err.multipart_suggestion(&self.msg, self.patches, self.applicability);
215 fn emit_verbose(self, err: &mut Diagnostic) {
216 err.multipart_suggestion_verbose(&self.msg, self.patches, self.applicability);
220 /// SnapshotParser is used to create a snapshot of the parser
221 /// without causing duplicate errors being emitted when the `Parser`
223 pub struct SnapshotParser<'a> {
225 unclosed_delims: Vec<UnmatchedBrace>,
228 impl<'a> Deref for SnapshotParser<'a> {
229 type Target = Parser<'a>;
231 fn deref(&self) -> &Self::Target {
236 impl<'a> DerefMut for SnapshotParser<'a> {
237 fn deref_mut(&mut self) -> &mut Self::Target {
242 impl<'a> Parser<'a> {
243 #[rustc_lint_diagnostics]
244 pub fn struct_span_err<S: Into<MultiSpan>>(
247 m: impl Into<DiagnosticMessage>,
248 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
249 self.sess.span_diagnostic.struct_span_err(sp, m)
252 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: impl Into<DiagnosticMessage>) -> ! {
253 self.sess.span_diagnostic.span_bug(sp, m)
256 pub(super) fn diagnostic(&self) -> &'a Handler {
257 &self.sess.span_diagnostic
260 /// Replace `self` with `snapshot.parser` and extend `unclosed_delims` with `snapshot.unclosed_delims`.
261 /// This is to avoid losing unclosed delims errors `create_snapshot_for_diagnostic` clears.
262 pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
263 *self = snapshot.parser;
264 self.unclosed_delims.extend(snapshot.unclosed_delims);
267 pub fn unclosed_delims(&self) -> &[UnmatchedBrace] {
268 &self.unclosed_delims
271 /// Create a snapshot of the `Parser`.
272 pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
273 let mut snapshot = self.clone();
274 let unclosed_delims = self.unclosed_delims.clone();
275 // Clear `unclosed_delims` in snapshot to avoid
276 // duplicate errors being emitted when the `Parser`
277 // is dropped (which may or may not happen, depending
278 // if the parsing the snapshot is created for is successful)
279 snapshot.unclosed_delims.clear();
280 SnapshotParser { parser: snapshot, unclosed_delims }
283 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
284 self.sess.source_map().span_to_snippet(span)
287 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
288 let valid_follow = &[
294 TokenKind::OpenDelim(Delimiter::Brace),
295 TokenKind::OpenDelim(Delimiter::Parenthesis),
296 TokenKind::CloseDelim(Delimiter::Brace),
297 TokenKind::CloseDelim(Delimiter::Parenthesis),
299 let suggest_raw = match self.token.ident() {
301 if ident.is_raw_guess()
302 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
304 Some(SuggEscapeToUseAsIdentifier {
305 span: ident.span.shrink_to_lo(),
306 // `Symbol::to_string()` is different from `Symbol::into_diagnostic_arg()`,
307 // which uses `Symbol::to_ident_string()` and "helpfully" adds an implicit `r#`
308 ident_name: ident.name.to_string(),
314 let suggest_remove_comma =
315 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
316 Some(SuggRemoveComma { span: self.token.span })
321 let err = ExpectedIdentifier {
322 span: self.token.span,
323 token: self.token.clone(),
325 suggest_remove_comma,
327 err.into_diagnostic(&self.sess.span_diagnostic)
330 pub(super) fn expected_one_of_not_found(
332 edible: &[TokenKind],
333 inedible: &[TokenKind],
334 ) -> PResult<'a, bool /* recovered */> {
335 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
336 fn tokens_to_string(tokens: &[TokenType]) -> String {
337 let mut i = tokens.iter();
338 // This might be a sign we need a connect method on `Iterator`.
339 let b = i.next().map_or_else(String::new, |t| t.to_string());
340 i.enumerate().fold(b, |mut b, (i, a)| {
341 if tokens.len() > 2 && i == tokens.len() - 2 {
343 } else if tokens.len() == 2 && i == tokens.len() - 2 {
348 b.push_str(&a.to_string());
353 let mut expected = edible
355 .map(|x| TokenType::Token(x.clone()))
356 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
357 .chain(self.expected_tokens.iter().cloned())
358 .filter_map(|token| {
359 // filter out suggestions which suggest the same token which was found and deemed incorrect
360 fn is_ident_eq_keyword(found: &TokenKind, expected: &TokenType) -> bool {
361 if let TokenKind::Ident(current_sym, _) = found {
362 if let TokenType::Keyword(suggested_sym) = expected {
363 return current_sym == suggested_sym;
368 if token != parser::TokenType::Token(self.token.kind.clone()) {
369 let eq = is_ident_eq_keyword(&self.token.kind, &token);
370 // if the suggestion is a keyword and the found token is an ident,
371 // the content of which are equal to the suggestion's content,
372 // we can remove that suggestion (see the return None statement below)
374 // if this isn't the case however, and the suggestion is a token the
375 // content of which is the same as the found token's, we remove it as well
377 if let TokenType::Token(kind) = &token {
378 if kind == &self.token.kind {
387 .collect::<Vec<_>>();
388 expected.sort_by_cached_key(|x| x.to_string());
391 let sm = self.sess.source_map();
393 // Special-case "expected `;`" errors
394 if expected.contains(&TokenType::Token(token::Semi)) {
395 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
396 // Likely inside a macro, can't provide meaningful suggestions.
397 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
398 // The current token is in the same line as the prior token, not recoverable.
399 } else if [token::Comma, token::Colon].contains(&self.token.kind)
400 && self.prev_token.kind == token::CloseDelim(Delimiter::Parenthesis)
402 // Likely typo: The current token is on a new line and is expected to be
403 // `.`, `;`, `?`, or an operator after a close delimiter token.
405 // let a = std::process::Command::new("echo")
409 // https://github.com/rust-lang/rust/issues/72253
410 } else if self.look_ahead(1, |t| {
411 t == &token::CloseDelim(Delimiter::Brace)
412 || t.can_begin_expr() && t.kind != token::Colon
413 }) && [token::Comma, token::Colon].contains(&self.token.kind)
415 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
416 // either `,` or `:`, and the next token could either start a new statement or is a
417 // block close. For example:
421 self.sess.emit_err(ExpectedSemi {
422 span: self.token.span,
423 token: self.token.clone(),
424 unexpected_token_label: None,
425 sugg: ExpectedSemiSugg::ChangeToSemi(self.token.span),
429 } else if self.look_ahead(0, |t| {
430 t == &token::CloseDelim(Delimiter::Brace)
431 || ((t.can_begin_expr() || t.can_begin_item())
433 && t != &token::Pound)
434 // Avoid triggering with too many trailing `#` in raw string.
436 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
437 ) && t == &token::Pound)
438 }) && !expected.contains(&TokenType::Token(token::Comma))
440 // Missing semicolon typo. This is triggered if the next token could either start a
441 // new statement or is a block close. For example:
445 let span = self.prev_token.span.shrink_to_hi();
446 self.sess.emit_err(ExpectedSemi {
448 token: self.token.clone(),
449 unexpected_token_label: Some(self.token.span),
450 sugg: ExpectedSemiSugg::AddSemi(span),
456 if self.token.kind == TokenKind::EqEq
457 && self.prev_token.is_ident()
458 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Eq)))
460 // Likely typo: `=` → `==` in let expr or enum item
461 return Err(self.sess.create_err(UseEqInstead { span: self.token.span }));
464 let expect = tokens_to_string(&expected);
465 let actual = super::token_descr(&self.token);
466 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
467 let short_expect = if expected.len() > 6 {
468 format!("{} possible tokens", expected.len())
473 format!("expected one of {expect}, found {actual}"),
474 (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")),
476 } else if expected.is_empty() {
478 format!("unexpected token: {actual}"),
479 (self.prev_token.span, "unexpected token after this".to_string()),
483 format!("expected {expect}, found {actual}"),
484 (self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
487 self.last_unexpected_token_span = Some(self.token.span);
488 // FIXME: translation requires list formatting (for `expect`)
489 let mut err = self.struct_span_err(self.token.span, &msg_exp);
491 if let TokenKind::Ident(symbol, _) = &self.prev_token.kind {
492 if ["def", "fun", "func", "function"].contains(&symbol.as_str()) {
493 err.span_suggestion_short(
494 self.prev_token.span,
495 &format!("write `fn` instead of `{symbol}` to declare a function"),
497 Applicability::MachineApplicable,
502 // `pub` may be used for an item or `pub(crate)`
503 if self.prev_token.is_ident_named(sym::public)
504 && (self.token.can_begin_item()
505 || self.token.kind == TokenKind::OpenDelim(Delimiter::Parenthesis))
507 err.span_suggestion_short(
508 self.prev_token.span,
509 "write `pub` instead of `public` to make the item public",
511 Applicability::MachineApplicable,
515 // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
516 // there are unclosed angle brackets
517 if self.unmatched_angle_bracket_count > 0
518 && self.token.kind == TokenKind::Eq
519 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
521 err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
524 let sp = if self.token == token::Eof {
525 // This is EOF; don't want to point at the following char, but rather the last token.
530 match self.recover_closing_delimiter(
533 .filter_map(|tt| match tt {
534 TokenType::Token(t) => Some(t.clone()),
537 .collect::<Vec<_>>(),
542 return Ok(recovered);
546 if self.check_too_many_raw_str_terminators(&mut err) {
547 if expected.contains(&TokenType::Token(token::Semi)) && self.eat(&token::Semi) {
555 if self.prev_token.span == DUMMY_SP {
556 // Account for macro context where the previous span might not be
557 // available to avoid incorrect output (#54841).
558 err.span_label(self.token.span, label_exp);
559 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
560 // When the spans are in the same line, it means that the only content between
561 // them is whitespace, point at the found token in that case:
563 // X | () => { syntax error };
564 // | ^^^^^ expected one of 8 possible tokens here
566 // instead of having:
568 // X | () => { syntax error };
569 // | -^^^^^ unexpected token
571 // | expected one of 8 possible tokens here
572 err.span_label(self.token.span, label_exp);
574 err.span_label(sp, label_exp);
575 err.span_label(self.token.span, "unexpected token");
577 self.maybe_annotate_with_ascription(&mut err, false);
581 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
582 let sm = self.sess.source_map();
583 match (&self.prev_token.kind, &self.token.kind) {
585 TokenKind::Literal(Lit {
586 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
590 ) if !sm.is_multiline(
591 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
594 let n_hashes: u8 = *n_hashes;
595 err.set_primary_message("too many `#` when terminating raw string");
596 let str_span = self.prev_token.span;
597 let mut span = self.token.span;
599 while self.token.kind == TokenKind::Pound
600 && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
602 span = span.with_hi(self.token.span.hi());
609 &format!("remove the extra `#`{}", pluralize!(count)),
611 Applicability::MachineApplicable,
615 &format!("this raw string started with {n_hashes} `#`{}", pluralize!(n_hashes)),
623 pub fn maybe_suggest_struct_literal(
627 maybe_struct_name: token::Token,
628 can_be_struct_literal: bool,
629 ) -> Option<PResult<'a, P<Block>>> {
630 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
631 // We might be having a struct literal where people forgot to include the path:
635 info!(?maybe_struct_name, ?self.token);
636 let mut snapshot = self.create_snapshot_for_diagnostic();
638 segments: ThinVec::new(),
639 span: self.prev_token.span.shrink_to_lo(),
642 let struct_expr = snapshot.parse_struct_expr(None, path, false);
643 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
644 return Some(match (struct_expr, block_tail) {
645 (Ok(expr), Err(mut err)) => {
646 // We have encountered the following:
651 // fn foo() -> Foo { Path {
655 self.restore_snapshot(snapshot);
656 let mut tail = self.mk_block(
657 vec![self.mk_stmt_err(expr.span)],
659 lo.to(self.prev_token.span),
661 tail.could_be_bare_literal = true;
662 if maybe_struct_name.is_ident() && can_be_struct_literal {
663 // Account for `if Example { a: one(), }.is_pos() {}`.
664 Err(self.sess.create_err(StructLiteralNeedingParens {
665 span: maybe_struct_name.span.to(expr.span),
666 sugg: StructLiteralNeedingParensSugg {
667 before: maybe_struct_name.span.shrink_to_lo(),
668 after: expr.span.shrink_to_hi(),
672 self.sess.emit_err(StructLiteralBodyWithoutPath {
674 sugg: StructLiteralBodyWithoutPathSugg {
675 before: expr.span.shrink_to_lo(),
676 after: expr.span.shrink_to_hi(),
682 (Err(err), Ok(tail)) => {
683 // We have a block tail that contains a somehow valid type ascription expr.
687 (Err(snapshot_err), Err(err)) => {
688 // We don't know what went wrong, emit the normal error.
689 snapshot_err.cancel();
690 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
693 (Ok(_), Ok(mut tail)) => {
694 tail.could_be_bare_literal = true;
702 pub fn maybe_annotate_with_ascription(
704 err: &mut Diagnostic,
705 maybe_expected_semicolon: bool,
707 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
708 let sm = self.sess.source_map();
709 let next_pos = sm.lookup_char_pos(self.token.span.lo());
710 let op_pos = sm.lookup_char_pos(sp.hi());
712 let allow_unstable = self.sess.unstable_features.is_nightly_build();
717 "maybe write a path separator here",
720 Applicability::MaybeIncorrect
722 Applicability::MachineApplicable
725 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
726 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
729 "try using a semicolon",
731 Applicability::MaybeIncorrect,
733 } else if allow_unstable {
734 err.span_label(sp, "tried to parse a type due to this type ascription");
736 err.span_label(sp, "tried to parse a type due to this");
739 // Give extra information about type ascription only if it's a nightly compiler.
741 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
745 // Avoid giving too much info when it was likely an unrelated typo.
747 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
748 for more information",
755 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
756 /// passes through any errors encountered. Used for error recovery.
757 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
759 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
760 Ok(p.parse_token_tree())
767 /// This function checks if there are trailing angle brackets and produces
768 /// a diagnostic to suggest removing them.
770 /// ```ignore (diagnostic)
771 /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
772 /// ^^ help: remove extra angle brackets
775 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
776 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
777 pub(super) fn check_trailing_angle_brackets(
779 segment: &PathSegment,
782 if !self.may_recover() {
786 // This function is intended to be invoked after parsing a path segment where there are two
789 // 1. A specific token is expected after the path segment.
790 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
791 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
792 // 2. No specific token is expected after the path segment.
793 // eg. `x.foo` (field access)
795 // This function is called after parsing `.foo` and before parsing the token `end` (if
796 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
799 // We only care about trailing angle brackets if we previously parsed angle bracket
800 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
801 // removed in this case:
803 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
805 // This case is particularly tricky as we won't notice it just looking at the tokens -
806 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
807 // have already been parsed):
809 // `x.foo::<u32>>>(3)`
810 let parsed_angle_bracket_args =
811 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
814 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
815 parsed_angle_bracket_args,
817 if !parsed_angle_bracket_args {
821 // Keep the span at the start so we can highlight the sequence of `>` characters to be
823 let lo = self.token.span;
825 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
826 // (since we might have the field access case and the characters we're eating are
827 // actual operators and not trailing characters - ie `x.foo >> 3`).
828 let mut position = 0;
830 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
831 // many of each (so we can correctly pluralize our error messages) and continue to
833 let mut number_of_shr = 0;
834 let mut number_of_gt = 0;
835 while self.look_ahead(position, |t| {
836 trace!("check_trailing_angle_brackets: t={:?}", t);
837 if *t == token::BinOp(token::BinOpToken::Shr) {
840 } else if *t == token::Gt {
850 // If we didn't find any trailing `>` characters, then we have nothing to error about.
852 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
853 number_of_gt, number_of_shr,
855 if number_of_gt < 1 && number_of_shr < 1 {
859 // Finally, double check that we have our end token as otherwise this is the
861 if self.look_ahead(position, |t| {
862 trace!("check_trailing_angle_brackets: t={:?}", t);
863 end.contains(&&t.kind)
865 // Eat from where we started until the end token so that parsing can continue
866 // as if we didn't have those extra angle brackets.
867 self.eat_to_tokens(end);
868 let span = lo.until(self.token.span);
870 let num_extra_brackets = number_of_gt + number_of_shr * 2;
871 self.sess.emit_err(UnmatchedAngleBrackets { span, num_extra_brackets });
877 /// Check if a method call with an intended turbofish has been written without surrounding
879 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
880 if !self.may_recover() {
884 if token::ModSep == self.token.kind && segment.args.is_none() {
885 let snapshot = self.create_snapshot_for_diagnostic();
887 let lo = self.token.span;
888 match self.parse_angle_args(None) {
890 let span = lo.to(self.prev_token.span);
891 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
892 let mut trailing_span = self.prev_token.span.shrink_to_hi();
893 while self.token.kind == token::BinOp(token::Shr)
894 || self.token.kind == token::Gt
896 trailing_span = trailing_span.to(self.token.span);
899 if self.token.kind == token::OpenDelim(Delimiter::Parenthesis) {
900 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
901 let args = AngleBracketedArgs { args, span }.into();
904 self.sess.emit_err(GenericParamsWithoutAngleBrackets {
906 sugg: GenericParamsWithoutAngleBracketsSugg {
907 left: span.shrink_to_lo(),
908 right: trailing_span,
912 // This doesn't look like an invalid turbofish, can't recover parse state.
913 self.restore_snapshot(snapshot);
917 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
918 // generic parse error instead.
920 self.restore_snapshot(snapshot);
926 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
927 /// encounter a parse error when encountering the first `,`.
928 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
930 mut e: DiagnosticBuilder<'a, ErrorGuaranteed>,
932 ) -> PResult<'a, ()> {
933 if let ExprKind::Binary(binop, _, _) = &expr.kind
934 && let ast::BinOpKind::Lt = binop.node
935 && self.eat(&token::Comma)
937 let x = self.parse_seq_to_before_end(
939 SeqSep::trailing_allowed(token::Comma),
940 |p| p.parse_generic_arg(None),
943 Ok((_, _, false)) => {
944 if self.eat(&token::Gt) {
945 e.span_suggestion_verbose(
946 binop.span.shrink_to_lo(),
947 fluent::parse_sugg_turbofish_syntax,
949 Applicability::MaybeIncorrect,
952 match self.parse_expr() {
955 self.mk_expr_err(expr.span.to(self.prev_token.span));
959 *expr = self.mk_expr_err(expr.span);
974 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
975 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
976 /// parenthesising the leftmost comparison.
977 fn attempt_chained_comparison_suggestion(
979 err: &mut ComparisonOperatorsCannotBeChained,
981 outer_op: &Spanned<AssocOp>,
982 ) -> bool /* advanced the cursor */ {
983 if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
984 if let ExprKind::Field(_, ident) = l1.kind
985 && ident.as_str().parse::<i32>().is_err()
986 && !matches!(r1.kind, ExprKind::Lit(_))
988 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
989 // suggestion being the only one to apply is high.
992 return match (op.node, &outer_op.node) {
994 (BinOpKind::Eq, AssocOp::Equal) |
995 // `x < y < z` and friends.
996 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
997 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
998 // `x > y > z` and friends.
999 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
1000 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
1001 let expr_to_str = |e: &Expr| {
1002 self.span_to_snippet(e.span)
1003 .unwrap_or_else(|_| pprust::expr_to_string(&e))
1005 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison {
1006 span: inner_op.span.shrink_to_hi(),
1007 middle_term: expr_to_str(&r1),
1009 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
1012 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
1013 // Consume `z`/outer-op-rhs.
1014 let snapshot = self.create_snapshot_for_diagnostic();
1015 match self.parse_expr() {
1017 // We are sure that outer-op-rhs could be consumed, the suggestion is
1019 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1020 left: r1.span.shrink_to_lo(),
1021 right: r2.span.shrink_to_hi(),
1027 self.restore_snapshot(snapshot);
1033 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
1034 let snapshot = self.create_snapshot_for_diagnostic();
1035 // At this point it is always valid to enclose the lhs in parentheses, no
1036 // further checks are necessary.
1037 match self.parse_expr() {
1039 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1040 left: l1.span.shrink_to_lo(),
1041 right: r1.span.shrink_to_hi(),
1047 self.restore_snapshot(snapshot);
1058 /// Produces an error if comparison operators are chained (RFC #558).
1059 /// We only need to check the LHS, not the RHS, because all comparison ops have same
1060 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
1062 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
1063 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
1066 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
1067 /// associative we can infer that we have:
1076 pub(super) fn check_no_chained_comparison(
1079 outer_op: &Spanned<AssocOp>,
1080 ) -> PResult<'a, Option<P<Expr>>> {
1082 outer_op.node.is_comparison(),
1083 "check_no_chained_comparison: {:?} is not comparison",
1087 let mk_err_expr = |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err)));
1089 match &inner_op.kind {
1090 ExprKind::Binary(op, l1, r1) if op.node.is_comparison() => {
1091 let mut err = ComparisonOperatorsCannotBeChained {
1092 span: vec![op.span, self.prev_token.span],
1093 suggest_turbofish: None,
1094 help_turbofish: None,
1095 chaining_sugg: None,
1098 // Include `<` to provide this recommendation even in a case like
1099 // `Foo<Bar<Baz<Qux, ()>>>`
1100 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
1101 || outer_op.node == AssocOp::Greater
1103 if outer_op.node == AssocOp::Less {
1104 let snapshot = self.create_snapshot_for_diagnostic();
1106 // So far we have parsed `foo<bar<`, consume the rest of the type args.
1108 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
1109 self.consume_tts(1, &modifiers);
1111 if !&[token::OpenDelim(Delimiter::Parenthesis), token::ModSep]
1112 .contains(&self.token.kind)
1114 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
1115 // parser and bail out.
1116 self.restore_snapshot(snapshot);
1119 return if token::ModSep == self.token.kind {
1120 // We have some certainty that this was a bad turbofish at this point.
1122 if let ExprKind::Binary(o, ..) = inner_op.kind && o.node == BinOpKind::Lt {
1123 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1125 err.help_turbofish = Some(());
1128 let snapshot = self.create_snapshot_for_diagnostic();
1129 self.bump(); // `::`
1131 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
1132 match self.parse_expr() {
1134 // 99% certain that the suggestion is correct, continue parsing.
1135 self.sess.emit_err(err);
1136 // FIXME: actually check that the two expressions in the binop are
1137 // paths and resynthesize new fn call expression instead of using
1138 // `ExprKind::Err` placeholder.
1139 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1143 // Not entirely sure now, but we bubble the error up with the
1145 self.restore_snapshot(snapshot);
1146 Err(err.into_diagnostic(&self.sess.span_diagnostic))
1149 } else if token::OpenDelim(Delimiter::Parenthesis) == self.token.kind {
1150 // We have high certainty that this was a bad turbofish at this point.
1152 if let ExprKind::Binary(o, ..) = inner_op.kind && o.node == BinOpKind::Lt {
1153 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1155 err.help_turbofish = Some(());
1157 // Consume the fn call arguments.
1158 match self.consume_fn_args() {
1159 Err(()) => Err(err.into_diagnostic(&self.sess.span_diagnostic)),
1161 self.sess.emit_err(err);
1162 // FIXME: actually check that the two expressions in the binop are
1163 // paths and resynthesize new fn call expression instead of using
1164 // `ExprKind::Err` placeholder.
1165 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1169 if !matches!(l1.kind, ExprKind::Lit(_))
1170 && !matches!(r1.kind, ExprKind::Lit(_))
1172 // All we know is that this is `foo < bar >` and *nothing* else. Try to
1173 // be helpful, but don't attempt to recover.
1174 err.help_turbofish = Some(());
1177 // If it looks like a genuine attempt to chain operators (as opposed to a
1178 // misformatted turbofish, for instance), suggest a correct form.
1179 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
1181 self.sess.emit_err(err);
1182 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1184 // These cases cause too many knock-down errors, bail out (#61329).
1185 Err(err.into_diagnostic(&self.sess.span_diagnostic))
1190 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1191 self.sess.emit_err(err);
1193 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
1201 fn consume_fn_args(&mut self) -> Result<(), ()> {
1202 let snapshot = self.create_snapshot_for_diagnostic();
1205 // Consume the fn call arguments.
1207 (token::OpenDelim(Delimiter::Parenthesis), 1),
1208 (token::CloseDelim(Delimiter::Parenthesis), -1),
1210 self.consume_tts(1, &modifiers);
1212 if self.token.kind == token::Eof {
1213 // Not entirely sure that what we consumed were fn arguments, rollback.
1214 self.restore_snapshot(snapshot);
1217 // 99% certain that the suggestion is correct, continue parsing.
1222 pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1224 self.sess.emit_err(AmbiguousPlus { sum_ty: pprust::ty_to_string(&ty), span: ty.span });
1228 /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1229 pub(super) fn maybe_recover_from_question_mark(&mut self, ty: P<Ty>) -> P<Ty> {
1230 if self.token == token::Question {
1232 self.sess.emit_err(QuestionMarkInType {
1233 span: self.prev_token.span,
1234 sugg: QuestionMarkInTypeSugg {
1235 left: ty.span.shrink_to_lo(),
1236 right: self.prev_token.span,
1239 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1245 pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
1246 // Do not add `+` to expected tokens.
1247 if !self.token.is_like_plus() {
1252 let bounds = self.parse_generic_bounds(None)?;
1253 let sum_span = ty.span.to(self.prev_token.span);
1255 let sub = match &ty.kind {
1256 TyKind::Ref(lifetime, mut_ty) => {
1257 let sum_with_parens = pprust::to_string(|s| {
1259 s.print_opt_lifetime(lifetime);
1260 s.print_mutability(mut_ty.mutbl, false);
1262 s.print_type(&mut_ty.ty);
1263 if !bounds.is_empty() {
1265 s.print_type_bounds(&bounds);
1270 BadTypePlusSub::AddParen { sum_with_parens, span: sum_span }
1272 TyKind::Ptr(..) | TyKind::BareFn(..) => BadTypePlusSub::ForgotParen { span: sum_span },
1273 _ => BadTypePlusSub::ExpectPath { span: sum_span },
1276 self.sess.emit_err(BadTypePlus { ty: pprust::ty_to_string(ty), span: sum_span, sub });
1281 pub(super) fn recover_from_prefix_increment(
1283 operand_expr: P<Expr>,
1286 ) -> PResult<'a, P<Expr>> {
1287 let standalone = if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr };
1288 let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
1289 self.recover_from_inc_dec(operand_expr, kind, op_span)
1292 pub(super) fn recover_from_postfix_increment(
1294 operand_expr: P<Expr>,
1297 ) -> PResult<'a, P<Expr>> {
1298 let kind = IncDecRecovery {
1299 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1301 fixity: UnaryFixity::Post,
1303 self.recover_from_inc_dec(operand_expr, kind, op_span)
1306 fn recover_from_inc_dec(
1309 kind: IncDecRecovery,
1311 ) -> PResult<'a, P<Expr>> {
1312 let mut err = self.struct_span_err(
1314 &format!("Rust has no {} {} operator", kind.fixity, kind.op.name()),
1316 err.span_label(op_span, &format!("not a valid {} operator", kind.fixity));
1318 let help_base_case = |mut err: DiagnosticBuilder<'_, _>, base| {
1319 err.help(&format!("use `{}= 1` instead", kind.op.chr()));
1325 let spans = match kind.fixity {
1326 UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1327 UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1330 match kind.standalone {
1331 IsStandalone::Standalone => {
1332 self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err)
1334 IsStandalone::Subexpr => {
1335 let Ok(base_src) = self.span_to_snippet(base.span)
1336 else { return help_base_case(err, base) };
1338 UnaryFixity::Pre => {
1339 self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1341 UnaryFixity::Post => {
1342 // won't suggest since we can not handle the precedences
1343 // for example: `a + b++` has been parsed (a + b)++ and we can not suggest here
1344 if !matches!(base.kind, ExprKind::Binary(_, _, _)) {
1345 self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1354 fn prefix_inc_dec_suggest(
1357 kind: IncDecRecovery,
1358 (pre_span, post_span): (Span, Span),
1361 msg: format!("use `{}= 1` instead", kind.op.chr()),
1363 (pre_span, "{ ".to_string()),
1364 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1366 applicability: Applicability::MachineApplicable,
1370 fn postfix_inc_dec_suggest(
1373 kind: IncDecRecovery,
1374 (pre_span, post_span): (Span, Span),
1376 let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1378 msg: format!("use `{}= 1` instead", kind.op.chr()),
1380 (pre_span, format!("{{ let {tmp_var} = ")),
1381 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1383 applicability: Applicability::HasPlaceholders,
1387 fn inc_dec_standalone_suggest(
1389 kind: IncDecRecovery,
1390 (pre_span, post_span): (Span, Span),
1392 let mut patches = Vec::new();
1394 if !pre_span.is_empty() {
1395 patches.push((pre_span, String::new()));
1398 patches.push((post_span, format!(" {}= 1", kind.op.chr())));
1400 msg: format!("use `{}= 1` instead", kind.op.chr()),
1402 applicability: Applicability::MachineApplicable,
1406 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1407 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1408 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1409 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1412 ) -> PResult<'a, P<T>> {
1413 if !self.may_recover() {
1417 // Do not add `::` to expected tokens.
1418 if self.token == token::ModSep {
1419 if let Some(ty) = base.to_ty() {
1420 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1426 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1427 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1428 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1432 ) -> PResult<'a, P<T>> {
1433 self.expect(&token::ModSep)?;
1435 let mut path = ast::Path { segments: ThinVec::new(), span: DUMMY_SP, tokens: None };
1436 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1437 path.span = ty_span.to(self.prev_token.span);
1439 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1440 self.sess.emit_err(BadQPathStage2 {
1442 ty: format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1445 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1446 Ok(P(T::recovered(Some(P(QSelf { ty, path_span, position: 0 })), path)))
1449 pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1450 if self.token.kind == TokenKind::Semi {
1454 IncorrectSemicolon { span: self.prev_token.span, opt_help: None, name: "" };
1456 if !items.is_empty() {
1457 let previous_item = &items[items.len() - 1];
1458 let previous_item_kind_name = match previous_item.kind {
1459 // Say "braced struct" because tuple-structs and
1460 // braceless-empty-struct declarations do take a semicolon.
1461 ItemKind::Struct(..) => Some("braced struct"),
1462 ItemKind::Enum(..) => Some("enum"),
1463 ItemKind::Trait(..) => Some("trait"),
1464 ItemKind::Union(..) => Some("union"),
1467 if let Some(name) = previous_item_kind_name {
1468 err.opt_help = Some(());
1472 self.sess.emit_err(err);
1479 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1480 /// closing delimiter.
1481 pub(super) fn unexpected_try_recover(
1484 ) -> PResult<'a, bool /* recovered */> {
1485 let token_str = pprust::token_kind_to_string(t);
1486 let this_token_str = super::token_descr(&self.token);
1487 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1488 // Point at the end of the macro call when reaching end of macro arguments.
1489 (token::Eof, Some(_)) => {
1490 let sp = self.prev_token.span.shrink_to_hi();
1493 // We don't want to point at the following span after DUMMY_SP.
1494 // This happens when the parser finds an empty TokenStream.
1495 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1496 // EOF, don't want to point at the following char, but rather the last token.
1497 (token::Eof, None) => (self.prev_token.span, self.token.span),
1498 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1501 "expected `{}`, found {}",
1503 match (&self.token.kind, self.subparser_name) {
1504 (token::Eof, Some(origin)) => format!("end of {origin}"),
1505 _ => this_token_str,
1508 let mut err = self.struct_span_err(sp, &msg);
1509 let label_exp = format!("expected `{token_str}`");
1510 match self.recover_closing_delimiter(&[t.clone()], err) {
1513 return Ok(recovered);
1516 let sm = self.sess.source_map();
1517 if !sm.is_multiline(prev_sp.until(sp)) {
1518 // When the spans are in the same line, it means that the only content
1519 // between them is whitespace, point only at the found token.
1520 err.span_label(sp, label_exp);
1522 err.span_label(prev_sp, label_exp);
1523 err.span_label(sp, "unexpected token");
1528 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1529 if self.eat(&token::Semi) {
1532 self.expect(&token::Semi).map(drop) // Error unconditionally
1535 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1536 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1537 pub(super) fn recover_incorrect_await_syntax(
1541 ) -> PResult<'a, P<Expr>> {
1542 let (hi, expr, is_question) = if self.token == token::Not {
1543 // Handle `await!(<expr>)`.
1544 self.recover_await_macro()?
1546 self.recover_await_prefix(await_sp)?
1548 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1549 let kind = match expr.kind {
1550 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1551 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1552 ExprKind::Try(_) => ExprKind::Err,
1553 _ => ExprKind::Await(expr),
1555 let expr = self.mk_expr(lo.to(sp), kind);
1556 self.maybe_recover_from_bad_qpath(expr)
1559 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1560 self.expect(&token::Not)?;
1561 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1562 let expr = self.parse_expr()?;
1563 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
1564 Ok((self.prev_token.span, expr, false))
1567 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1568 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1569 let expr = if self.token == token::OpenDelim(Delimiter::Brace) {
1570 // Handle `await { <expr> }`.
1571 // This needs to be handled separately from the next arm to avoid
1572 // interpreting `await { <expr> }?` as `<expr>?.await`.
1573 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default)
1577 .map_err(|mut err| {
1578 err.span_label(await_sp, "while parsing this incorrect await expression");
1581 Ok((expr.span, expr, is_question))
1584 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1585 let span = lo.to(hi);
1586 let applicability = match expr.kind {
1587 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1588 _ => Applicability::MachineApplicable,
1591 self.sess.emit_err(IncorrectAwait {
1593 sugg_span: (span, applicability),
1594 expr: self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr)),
1595 question_mark: if is_question { "?" } else { "" },
1601 /// If encountering `future.await()`, consumes and emits an error.
1602 pub(super) fn recover_from_await_method_call(&mut self) {
1603 if self.token == token::OpenDelim(Delimiter::Parenthesis)
1604 && self.look_ahead(1, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1607 let lo = self.token.span;
1609 let span = lo.to(self.token.span);
1612 self.sess.emit_err(IncorrectUseOfAwait { span });
1616 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1617 let is_try = self.token.is_keyword(kw::Try);
1618 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1619 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(Delimiter::Parenthesis)); //check for (
1621 if is_try && is_questionmark && is_open {
1622 let lo = self.token.span;
1623 self.bump(); //remove try
1624 self.bump(); //remove !
1625 let try_span = lo.to(self.token.span); //we take the try!( span
1626 self.bump(); //remove (
1627 let is_empty = self.token == token::CloseDelim(Delimiter::Parenthesis); //check if the block is empty
1628 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::No); //eat the block
1629 let hi = self.token.span;
1630 self.bump(); //remove )
1631 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1632 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1633 let prefix = if is_empty { "" } else { "alternatively, " };
1635 err.multipart_suggestion(
1636 "you can use the `?` operator instead",
1637 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1638 Applicability::MachineApplicable,
1641 err.span_suggestion(lo.shrink_to_lo(), &format!("{prefix}you can still access the deprecated `try!()` macro using the \"raw identifier\" syntax"), "r#", Applicability::MachineApplicable);
1643 Ok(self.mk_expr_err(lo.to(hi)))
1645 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1649 /// Recovers a situation like `for ( $pat in $expr )`
1650 /// and suggest writing `for $pat in $expr` instead.
1652 /// This should be called before parsing the `$block`.
1653 pub(super) fn recover_parens_around_for_head(
1656 begin_paren: Option<Span>,
1658 match (&self.token.kind, begin_paren) {
1659 (token::CloseDelim(Delimiter::Parenthesis), Some(begin_par_sp)) => {
1662 let sm = self.sess.source_map();
1663 let left = begin_par_sp;
1664 let right = self.prev_token.span;
1665 let left_snippet = if let Ok(snip) = sm.span_to_prev_source(left) &&
1666 !snip.ends_with(' ') {
1672 let right_snippet = if let Ok(snip) = sm.span_to_next_source(right) &&
1673 !snip.starts_with(' ') {
1679 self.sess.emit_err(ParenthesesInForHead {
1680 span: vec![left, right],
1681 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1682 // with `x) in y)` which is syntactically invalid.
1683 // However, this is prevented before we get here.
1684 sugg: ParenthesesInForHeadSugg { left, right, left_snippet, right_snippet },
1687 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1688 pat.and_then(|pat| match pat.kind {
1689 PatKind::Paren(pat) => pat,
1697 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1698 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1699 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1700 || self.token.is_ident() &&
1701 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1702 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1703 self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Parenthesis))
1704 || self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace)) // `foo:bar {`
1705 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1706 self.look_ahead(2, |t| t == &token::Lt) &&
1707 self.look_ahead(3, |t| t.is_ident())
1708 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1709 self.look_ahead(2, |t| t.is_ident())
1710 || self.look_ahead(1, |t| t == &token::ModSep)
1711 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1712 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1715 pub(super) fn recover_seq_parse_error(
1719 result: PResult<'a, P<Expr>>,
1725 // Recover from parse error, callers expect the closing delim to be consumed.
1726 self.consume_block(delim, ConsumeClosingDelim::Yes);
1727 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err)
1732 pub(super) fn recover_closing_delimiter(
1734 tokens: &[TokenKind],
1735 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
1736 ) -> PResult<'a, bool> {
1738 // We want to use the last closing delim that would apply.
1739 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1740 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1741 && Some(self.token.span) > unmatched.unclosed_span
1748 // Recover and assume that the detected unclosed delimiter was meant for
1749 // this location. Emit the diagnostic and act as if the delimiter was
1750 // present for the parser's sake.
1752 // Don't attempt to recover from this unclosed delimiter more than once.
1753 let unmatched = self.unclosed_delims.remove(pos);
1754 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1755 if unmatched.found_delim.is_none() {
1756 // We encountered `Eof`, set this fact here to avoid complaining about missing
1757 // `fn main()` when we found place to suggest the closing brace.
1758 *self.sess.reached_eof.borrow_mut() = true;
1761 // We want to suggest the inclusion of the closing delimiter where it makes
1762 // the most sense, which is immediately after the last token:
1767 // | help: `)` may belong here
1769 // unclosed delimiter
1770 if let Some(sp) = unmatched.unclosed_span {
1771 let mut primary_span: Vec<Span> =
1772 err.span.primary_spans().iter().cloned().collect();
1773 primary_span.push(sp);
1774 let mut primary_span: MultiSpan = primary_span.into();
1775 for span_label in err.span.span_labels() {
1776 if let Some(label) = span_label.label {
1777 primary_span.push_span_label(span_label.span, label);
1780 err.set_span(primary_span);
1781 err.span_label(sp, "unclosed delimiter");
1783 // Backticks should be removed to apply suggestions.
1784 let mut delim = delim.to_string();
1785 delim.retain(|c| c != '`');
1786 err.span_suggestion_short(
1787 self.prev_token.span.shrink_to_hi(),
1788 &format!("`{delim}` may belong here"),
1790 Applicability::MaybeIncorrect,
1792 if unmatched.found_delim.is_none() {
1793 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1794 // errors which would be emitted elsewhere in the parser and let other error
1795 // recovery consume the rest of the file.
1799 self.expected_tokens.clear(); // Reduce the number of errors.
1807 /// Eats tokens until we can be relatively sure we reached the end of the
1808 /// statement. This is something of a best-effort heuristic.
1810 /// We terminate when we find an unmatched `}` (without consuming it).
1811 pub(super) fn recover_stmt(&mut self) {
1812 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1815 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1816 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1817 /// approximate -- it can mean we break too early due to macros, but that
1818 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1820 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1821 /// after finding (and consuming) a brace-delimited block.
1822 pub(super) fn recover_stmt_(
1824 break_on_semi: SemiColonMode,
1825 break_on_block: BlockMode,
1827 let mut brace_depth = 0;
1828 let mut bracket_depth = 0;
1829 let mut in_block = false;
1830 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1832 debug!("recover_stmt_ loop {:?}", self.token);
1833 match self.token.kind {
1834 token::OpenDelim(Delimiter::Brace) => {
1837 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1842 token::OpenDelim(Delimiter::Bracket) => {
1846 token::CloseDelim(Delimiter::Brace) => {
1847 if brace_depth == 0 {
1848 debug!("recover_stmt_ return - close delim {:?}", self.token);
1853 if in_block && bracket_depth == 0 && brace_depth == 0 {
1854 debug!("recover_stmt_ return - block end {:?}", self.token);
1858 token::CloseDelim(Delimiter::Bracket) => {
1860 if bracket_depth < 0 {
1866 debug!("recover_stmt_ return - Eof");
1871 if break_on_semi == SemiColonMode::Break
1873 && bracket_depth == 0
1875 debug!("recover_stmt_ return - Semi");
1880 if break_on_semi == SemiColonMode::Comma
1882 && bracket_depth == 0 =>
1884 debug!("recover_stmt_ return - Semi");
1892 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1893 if self.eat_keyword(kw::In) {
1894 // a common typo: `for _ in in bar {}`
1895 self.sess.emit_err(InInTypo {
1896 span: self.prev_token.span,
1897 sugg_span: in_span.until(self.prev_token.span),
1902 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1903 if let token::DocComment(..) = self.token.kind {
1904 self.sess.emit_err(DocCommentOnParamType { span: self.token.span });
1906 } else if self.token == token::Pound
1907 && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Bracket))
1909 let lo = self.token.span;
1910 // Skip every token until next possible arg.
1911 while self.token != token::CloseDelim(Delimiter::Bracket) {
1914 let sp = lo.to(self.token.span);
1916 self.sess.emit_err(AttributeOnParamType { span: sp });
1920 pub(super) fn parameter_without_type(
1922 err: &mut Diagnostic,
1926 ) -> Option<Ident> {
1927 // If we find a pattern followed by an identifier, it could be an (incorrect)
1928 // C-style parameter declaration.
1929 if self.check_ident()
1930 && self.look_ahead(1, |t| {
1931 *t == token::Comma || *t == token::CloseDelim(Delimiter::Parenthesis)
1934 // `fn foo(String s) {}`
1935 let ident = self.parse_ident().unwrap();
1936 let span = pat.span.with_hi(ident.span.hi());
1938 err.span_suggestion(
1940 "declare the type after the parameter binding",
1941 "<identifier>: <type>",
1942 Applicability::HasPlaceholders,
1945 } else if require_name
1946 && (self.token == token::Comma
1947 || self.token == token::Lt
1948 || self.token == token::CloseDelim(Delimiter::Parenthesis))
1950 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1952 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1954 PatKind::Ident(_, ident, _) => (
1957 ": TypeName".to_string(),
1959 pat.span.shrink_to_lo(),
1960 pat.span.shrink_to_hi(),
1961 pat.span.shrink_to_lo(),
1963 // Also catches `fn foo(&a)`.
1964 PatKind::Ref(ref inner_pat, mutab)
1965 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1967 match inner_pat.clone().into_inner().kind {
1968 PatKind::Ident(_, ident, _) => {
1969 let mutab = mutab.prefix_str();
1973 format!("{ident}: &{mutab}TypeName"),
1975 pat.span.shrink_to_lo(),
1977 pat.span.shrink_to_lo(),
1980 _ => unreachable!(),
1984 // Otherwise, try to get a type and emit a suggestion.
1985 if let Some(ty) = pat.to_ty() {
1986 err.span_suggestion_verbose(
1988 "explicitly ignore the parameter name",
1989 format!("_: {}", pprust::ty_to_string(&ty)),
1990 Applicability::MachineApplicable,
1999 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
2001 err.span_suggestion(
2003 "if this is a `self` type, give it a parameter name",
2005 Applicability::MaybeIncorrect,
2008 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
2009 // `fn foo(HashMap: TypeName<u32>)`.
2010 if self.token != token::Lt {
2011 err.span_suggestion(
2013 "if this is a parameter name, give it a type",
2015 Applicability::HasPlaceholders,
2018 err.span_suggestion(
2020 "if this is a type, explicitly ignore the parameter name",
2022 Applicability::MachineApplicable,
2026 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
2027 return if self.token == token::Lt { None } else { Some(ident) };
2032 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
2033 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
2034 self.expect(&token::Colon)?;
2035 let ty = self.parse_ty()?;
2037 self.sess.emit_err(PatternMethodParamWithoutBody { span: pat.span });
2039 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2041 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
2045 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2046 let span = param.pat.span;
2047 param.ty.kind = TyKind::Err;
2048 self.sess.emit_err(SelfParamNotFirst { span });
2052 pub(super) fn consume_block(&mut self, delim: Delimiter, consume_close: ConsumeClosingDelim) {
2053 let mut brace_depth = 0;
2055 if self.eat(&token::OpenDelim(delim)) {
2057 } else if self.check(&token::CloseDelim(delim)) {
2058 if brace_depth == 0 {
2059 if let ConsumeClosingDelim::Yes = consume_close {
2060 // Some of the callers of this method expect to be able to parse the
2061 // closing delimiter themselves, so we leave it alone. Otherwise we advance
2071 } else if self.token == token::Eof {
2079 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2080 let (span, msg) = match (&self.token.kind, self.subparser_name) {
2081 (&token::Eof, Some(origin)) => {
2082 let sp = self.prev_token.span.shrink_to_hi();
2083 (sp, format!("expected expression, found end of {origin}"))
2087 format!("expected expression, found {}", super::token_descr(&self.token),),
2090 let mut err = self.struct_span_err(span, &msg);
2091 let sp = self.sess.source_map().start_point(self.token.span);
2092 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
2093 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
2095 err.span_label(span, "expected expression");
2101 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
2102 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
2103 modifier: &[(token::TokenKind, i64)],
2106 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
2109 if self.token.kind == token::Eof {
2116 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
2118 /// This is necessary because at this point we don't know whether we parsed a function with
2119 /// anonymous parameters or a function with names but no types. In order to minimize
2120 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
2121 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
2122 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
2123 /// we deduplicate them to not complain about duplicated parameter names.
2124 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
2125 let mut seen_inputs = FxHashSet::default();
2126 for input in fn_inputs.iter_mut() {
2127 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
2128 (&input.pat.kind, &input.ty.kind)
2134 if let Some(ident) = opt_ident {
2135 if seen_inputs.contains(&ident) {
2136 input.pat.kind = PatKind::Wild;
2138 seen_inputs.insert(ident);
2143 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
2144 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
2145 /// like the user has forgotten them.
2146 pub fn handle_ambiguous_unbraced_const_arg(
2148 args: &mut Vec<AngleBracketedArg>,
2149 ) -> PResult<'a, bool> {
2150 // If we haven't encountered a closing `>`, then the argument is malformed.
2151 // It's likely that the user has written a const expression without enclosing it
2152 // in braces, so we try to recover here.
2153 let arg = args.pop().unwrap();
2154 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
2155 // adverse side-effects to subsequent errors and seems to advance the parser.
2156 // We are causing this error here exclusively in case that a `const` expression
2157 // could be recovered from the current parser state, even if followed by more
2158 // arguments after a comma.
2159 let mut err = self.struct_span_err(
2161 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2163 err.span_label(self.token.span, "expected one of `,` or `>`");
2164 match self.recover_const_arg(arg.span(), err) {
2166 args.push(AngleBracketedArg::Arg(arg));
2167 if self.eat(&token::Comma) {
2168 return Ok(true); // Continue
2173 // We will emit a more generic error later.
2177 return Ok(false); // Don't continue.
2180 /// Attempt to parse a generic const argument that has not been enclosed in braces.
2181 /// There are a limited number of expressions that are permitted without being encoded
2184 /// - Single-segment paths (i.e. standalone generic const parameters).
2185 /// All other expressions that can be parsed will emit an error suggesting the expression be
2186 /// wrapped in braces.
2187 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
2188 let start = self.token.span;
2189 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
2191 start.shrink_to_lo(),
2192 "while parsing a const generic argument starting here",
2196 if !self.expr_is_valid_const_arg(&expr) {
2197 self.sess.emit_err(ConstGenericWithoutBraces {
2199 sugg: ConstGenericWithoutBracesSugg {
2200 left: expr.span.shrink_to_lo(),
2201 right: expr.span.shrink_to_hi(),
2208 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2209 let snapshot = self.create_snapshot_for_diagnostic();
2210 let param = match self.parse_const_param(AttrVec::new()) {
2214 self.restore_snapshot(snapshot);
2219 let ident = param.ident.to_string();
2220 let sugg = match (ty_generics, self.sess.source_map().span_to_snippet(param.span())) {
2221 (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2222 Some(match ¶ms[..] {
2223 [] => UnexpectedConstParamDeclarationSugg::AddParam {
2224 impl_generics: *impl_generics,
2225 incorrect_decl: param.span(),
2229 [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2230 impl_generics_end: generic.span().shrink_to_hi(),
2231 incorrect_decl: param.span(),
2239 self.sess.emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2241 let value = self.mk_expr_err(param.span());
2242 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2245 pub fn recover_const_param_declaration(
2247 ty_generics: Option<&Generics>,
2248 ) -> PResult<'a, Option<GenericArg>> {
2249 // We have to check for a few different cases.
2250 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2251 return Ok(Some(arg));
2254 // We haven't consumed `const` yet.
2255 let start = self.token.span;
2256 self.bump(); // `const`
2258 // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2259 let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
2260 if self.check_const_arg() {
2261 err.to_remove = Some(start.until(self.token.span));
2262 self.sess.emit_err(err);
2263 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2265 let after_kw_const = self.token.span;
2266 self.recover_const_arg(after_kw_const, err.into_diagnostic(&self.sess.span_diagnostic))
2271 /// Try to recover from possible generic const argument without `{` and `}`.
2273 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2274 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2275 /// if we think that the resulting expression would be well formed.
2276 pub fn recover_const_arg(
2279 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2280 ) -> PResult<'a, GenericArg> {
2281 let is_op_or_dot = AssocOp::from_token(&self.token)
2283 if let AssocOp::Greater
2285 | AssocOp::ShiftRight
2286 | AssocOp::GreaterEqual
2287 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2288 // assign a value to a defaulted generic parameter.
2290 | AssocOp::AssignOp(_) = op
2298 || self.token.kind == TokenKind::Dot;
2299 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2300 // type params has been parsed.
2302 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
2303 if !is_op_or_dot && !was_op {
2304 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2307 let snapshot = self.create_snapshot_for_diagnostic();
2311 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2313 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2314 if token::EqEq == snapshot.token.kind {
2315 err.span_suggestion(
2316 snapshot.token.span,
2317 "if you meant to use an associated type binding, replace `==` with `=`",
2319 Applicability::MaybeIncorrect,
2321 let value = self.mk_expr_err(start.to(expr.span));
2323 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2324 } else if token::Colon == snapshot.token.kind
2325 && expr.span.lo() == snapshot.token.span.hi()
2326 && matches!(expr.kind, ExprKind::Path(..))
2328 // Find a mistake like "foo::var:A".
2329 err.span_suggestion(
2330 snapshot.token.span,
2331 "write a path separator here",
2333 Applicability::MaybeIncorrect,
2336 return Ok(GenericArg::Type(self.mk_ty(start.to(expr.span), TyKind::Err)));
2337 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2339 // Avoid the following output by checking that we consumed a full const arg:
2340 // help: expressions must be enclosed in braces to be used as const generic
2343 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
2345 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2352 self.restore_snapshot(snapshot);
2356 /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2357 pub fn dummy_const_arg_needs_braces(
2359 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2362 err.multipart_suggestion(
2363 "expressions must be enclosed in braces to be used as const generic \
2365 vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2366 Applicability::MaybeIncorrect,
2368 let value = self.mk_expr_err(span);
2370 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2373 /// Some special error handling for the "top-level" patterns in a match arm,
2374 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2375 pub(crate) fn maybe_recover_colon_colon_in_pat_typo(
2377 mut first_pat: P<Pat>,
2380 if token::Colon != self.token.kind {
2383 if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2384 || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2388 // The pattern looks like it might be a path with a `::` -> `:` typo:
2389 // `match foo { bar:baz => {} }`
2390 let span = self.token.span;
2391 // We only emit "unexpected `:`" error here if we can successfully parse the
2392 // whole pattern correctly in that case.
2393 let snapshot = self.create_snapshot_for_diagnostic();
2395 // Create error for "unexpected `:`".
2396 match self.expected_one_of_not_found(&[], &[]) {
2398 self.bump(); // Skip the `:`.
2399 match self.parse_pat_no_top_alt(expected) {
2401 // Carry on as if we had not done anything, callers will emit a
2402 // reasonable error.
2405 self.restore_snapshot(snapshot);
2408 // We've parsed the rest of the pattern.
2409 let new_span = first_pat.span.to(pat.span);
2410 let mut show_sugg = false;
2411 // Try to construct a recovered pattern.
2412 match &mut pat.kind {
2413 PatKind::Struct(qself @ None, path, ..)
2414 | PatKind::TupleStruct(qself @ None, path, _)
2415 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2416 PatKind::Ident(_, ident, _) => {
2417 path.segments.insert(0, PathSegment::from_ident(*ident));
2418 path.span = new_span;
2422 PatKind::Path(old_qself, old_path) => {
2423 path.segments = old_path
2427 .chain(take(&mut path.segments))
2429 path.span = new_span;
2430 *qself = old_qself.clone();
2436 PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
2437 match &first_pat.kind {
2438 PatKind::Ident(_, old_ident, _) => {
2439 let path = PatKind::Path(
2443 segments: thin_vec![
2444 PathSegment::from_ident(*old_ident),
2445 PathSegment::from_ident(*ident),
2450 first_pat = self.mk_pat(new_span, path);
2453 PatKind::Path(old_qself, old_path) => {
2454 let mut segments = old_path.segments.clone();
2455 segments.push(PathSegment::from_ident(*ident));
2456 let path = PatKind::Path(
2458 Path { span: new_span, segments, tokens: None },
2460 first_pat = self.mk_pat(new_span, path);
2469 err.span_suggestion(
2471 "maybe write a path separator here",
2473 Applicability::MaybeIncorrect,
2476 first_pat = self.mk_pat(new_span, PatKind::Wild);
2483 // Carry on as if we had not done anything. This should be unreachable.
2484 self.restore_snapshot(snapshot);
2490 pub(crate) fn maybe_recover_unexpected_block_label(&mut self) -> bool {
2491 // Check for `'a : {`
2492 if !(self.check_lifetime()
2493 && self.look_ahead(1, |tok| tok.kind == token::Colon)
2494 && self.look_ahead(2, |tok| tok.kind == token::OpenDelim(Delimiter::Brace)))
2498 let label = self.eat_label().expect("just checked if a label exists");
2499 self.bump(); // eat `:`
2500 let span = label.ident.span.to(self.prev_token.span);
2501 let mut err = self.struct_span_err(span, "block label not supported here");
2502 err.span_label(span, "not supported here");
2503 err.tool_only_span_suggestion(
2504 label.ident.span.until(self.token.span),
2505 "remove this block label",
2507 Applicability::MachineApplicable,
2513 /// Some special error handling for the "top-level" patterns in a match arm,
2514 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2515 pub(crate) fn maybe_recover_unexpected_comma(
2518 rt: CommaRecoveryMode,
2519 ) -> PResult<'a, ()> {
2520 if self.token != token::Comma {
2524 // An unexpected comma after a top-level pattern is a clue that the
2525 // user (perhaps more accustomed to some other language) forgot the
2526 // parentheses in what should have been a tuple pattern; return a
2527 // suggestion-enhanced error here rather than choking on the comma later.
2528 let comma_span = self.token.span;
2530 if let Err(err) = self.skip_pat_list() {
2531 // We didn't expect this to work anyway; we just wanted to advance to the
2532 // end of the comma-sequence so we know the span to suggest parenthesizing.
2535 let seq_span = lo.to(self.prev_token.span);
2536 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2537 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2538 err.multipart_suggestion(
2540 "try adding parentheses to match on a tuple{}",
2541 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2544 (seq_span.shrink_to_lo(), "(".to_string()),
2545 (seq_span.shrink_to_hi(), ")".to_string()),
2547 Applicability::MachineApplicable,
2549 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2550 err.span_suggestion(
2552 "...or a vertical bar to match on multiple alternatives",
2553 seq_snippet.replace(',', " |"),
2554 Applicability::MachineApplicable,
2561 pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2562 let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2563 let qself_position = qself.as_ref().map(|qself| qself.position);
2564 for (i, segments) in path.segments.windows(2).enumerate() {
2565 if qself_position.map(|pos| i < pos).unwrap_or(false) {
2568 if let [a, b] = segments {
2569 let (a_span, b_span) = (a.span(), b.span());
2570 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2571 if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2572 return Err(DoubleColonInBound {
2573 span: path.span.shrink_to_hi(),
2574 between: between_span,
2576 .into_diagnostic(&self.sess.span_diagnostic));
2583 pub fn is_diff_marker(&mut self, long_kind: &TokenKind, short_kind: &TokenKind) -> bool {
2584 (0..3).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2585 && self.look_ahead(3, |tok| tok == short_kind)
2588 fn diff_marker(&mut self, long_kind: &TokenKind, short_kind: &TokenKind) -> Option<Span> {
2589 if self.is_diff_marker(long_kind, short_kind) {
2590 let lo = self.token.span;
2594 return Some(lo.to(self.prev_token.span));
2599 pub fn recover_diff_marker(&mut self) {
2600 let Some(start) = self.diff_marker(&TokenKind::BinOp(token::Shl), &TokenKind::Lt) else {
2603 let mut spans = Vec::with_capacity(3);
2605 let mut middlediff3 = None;
2606 let mut middle = None;
2609 if self.token.kind == TokenKind::Eof {
2612 if let Some(span) = self.diff_marker(&TokenKind::OrOr, &TokenKind::BinOp(token::Or)) {
2613 middlediff3 = Some(span);
2615 if let Some(span) = self.diff_marker(&TokenKind::EqEq, &TokenKind::Eq) {
2616 middle = Some(span);
2618 if let Some(span) = self.diff_marker(&TokenKind::BinOp(token::Shr), &TokenKind::Gt) {
2625 let mut err = self.struct_span_err(spans, "encountered diff marker");
2626 err.span_label(start, "after this is the code before the merge");
2627 if let Some(middle) = middlediff3 {
2628 err.span_label(middle, "");
2630 if let Some(middle) = middle {
2631 err.span_label(middle, "");
2633 if let Some(end) = end {
2634 err.span_label(end, "above this are the incoming code changes");
2637 "if you're having merge conflicts after pulling new code, the top section is the code \
2638 you already had and the bottom section is the remote code",
2641 "if you're in the middle of a rebase, the top section is the code being rebased onto \
2642 and the bottom section is the code coming from the current commit being rebased",
2645 "for an explanation on these markers from the `git` documentation, visit \
2646 <https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_checking_out_conflicts>",
2652 /// Parse and throw away a parenthesized comma separated
2653 /// sequence of patterns until `)` is reached.
2654 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2655 while !self.check(&token::CloseDelim(Delimiter::Parenthesis)) {
2656 self.parse_pat_no_top_alt(None)?;
2657 if !self.eat(&token::Comma) {