Skip to main content

rustc_parse/parser/
diagnostics.rs

1use std::mem::take;
2use std::ops::{Deref, DerefMut};
3
4use ast::token::IdentKind;
5use rustc_ast::token::{self, Lit, LitKind, Token, TokenKind};
6use rustc_ast::util::parser::{AssocOp, ExprPrecedence};
7use rustc_ast::{
8    self as ast, AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingMode,
9    Block, BlockCheckMode, Expr, ExprKind, GenericArg, GenericArgs, Generics, Item, ItemKind,
10    Param, Pat, PatKind, Path, PathSegment, QSelf, Recovered, Ty, TyKind,
11};
12use rustc_ast_pretty::pprust;
13use rustc_data_structures::fx::FxHashSet;
14use rustc_errors::{
15    Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, PResult, Subdiagnostic, Suggestions, msg,
16    pluralize,
17};
18use rustc_span::symbol::used_keywords;
19use rustc_span::{BytePos, DUMMY_SP, Ident, Span, SpanSnippetError, Spanned, Symbol, kw, sym};
20use thin_vec::{ThinVec, thin_vec};
21use tracing::{debug, trace};
22
23use super::pat::Expected;
24use super::{
25    BlockMode, CommaRecoveryMode, ExpTokenPair, Parser, PathStyle, Restrictions, SemiColonMode,
26    SeqSep, TokenType,
27};
28use crate::diagnostics::{
29    AddParen, AmbiguousPlus, AsyncMoveBlockIn2015, AsyncUseBlockIn2015, AwaitSuggestion,
30    BadQPathStage2, BadTypePlus, BadTypePlusSub, ColonAsSemi, ComparisonOperatorsCannotBeChained,
31    ComparisonOperatorsCannotBeChainedSugg, DocCommentDoesNotDocumentAnything, DoubleColonInBound,
32    ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg, ExprParenthesesNeeded, FoundPathInGenerics,
33    GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg,
34    HelpIdentifierStartsWithNumber, HelpUseLatestEdition, InInTypo, IncorrectAwait,
35    IncorrectSemicolon, IncorrectUseOfAwait, IncorrectUseOfUse, MisspelledKw,
36    PatternMethodParamWithoutBody, QuestionMarkInType, QuestionMarkInTypeSugg, SelfParamNotFirst,
37    StructLiteralBodyWithoutPath, StructLiteralBodyWithoutPathSugg, SuggAddMissingLetStmt,
38    SuggEscapeIdentifier, SuggRemoveComma, SuggestBindTypeParameter, SuggestIntroduceTypeParameter,
39    TernaryOperator, TernaryOperatorSuggestion, UnexpectedConstInGenericParam,
40    UnexpectedConstParamDeclaration, UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets,
41    UseEqInstead, WrapType,
42};
43use crate::exp;
44use crate::parser::attr::InnerAttrPolicy;
45use crate::parser::{FnContext, IsDotDotDot};
46
47/// Creates a placeholder argument.
48pub(super) fn dummy_arg(ident: Ident, guar: ErrorGuaranteed) -> Param {
49    let pat = Box::new(Pat {
50        id: ast::DUMMY_NODE_ID,
51        kind: PatKind::Ident(BindingMode::NONE, ident, None),
52        span: ident.span,
53    });
54    let ty = Ty { kind: TyKind::Err(guar), span: ident.span, id: ast::DUMMY_NODE_ID };
55    Param {
56        attrs: AttrVec::default(),
57        id: ast::DUMMY_NODE_ID,
58        pat,
59        span: ident.span,
60        ty: Box::new(ty),
61        is_placeholder: false,
62    }
63}
64
65pub(super) trait RecoverQPath: Sized + 'static {
66    const PATH_STYLE: PathStyle = PathStyle::Expr;
67    fn to_ty(&self) -> Option<Box<Ty>>;
68    fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self;
69}
70
71impl<T: RecoverQPath> RecoverQPath for Box<T> {
72    const PATH_STYLE: PathStyle = T::PATH_STYLE;
73    fn to_ty(&self) -> Option<Box<Ty>> {
74        T::to_ty(self)
75    }
76    fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
77        Box::new(T::recovered(qself, path))
78    }
79}
80
81impl RecoverQPath for Ty {
82    const PATH_STYLE: PathStyle = PathStyle::Type;
83    fn to_ty(&self) -> Option<Box<Ty>> {
84        Some(Box::new(self.clone()))
85    }
86    fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
87        Self { span: path.span, kind: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
88    }
89}
90
91impl RecoverQPath for Pat {
92    const PATH_STYLE: PathStyle = PathStyle::Pat;
93    fn to_ty(&self) -> Option<Box<Ty>> {
94        self.to_ty()
95    }
96    fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
97        Self { span: path.span, kind: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
98    }
99}
100
101impl RecoverQPath for Expr {
102    fn to_ty(&self) -> Option<Box<Ty>> {
103        self.to_ty()
104    }
105    fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
106        Self {
107            span: path.span,
108            kind: ExprKind::Path(qself, path),
109            attrs: AttrVec::new(),
110            id: ast::DUMMY_NODE_ID,
111            tokens: None,
112        }
113    }
114}
115
116/// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
117pub(crate) enum ConsumeClosingDelim {
118    Yes,
119    No,
120}
121
122#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AttemptLocalParseRecovery { }
#[automatically_derived]
impl ::core::clone::Clone for AttemptLocalParseRecovery {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AttemptLocalParseRecovery { }Copy)]
123pub enum AttemptLocalParseRecovery {
124    Yes,
125    No,
126}
127
128impl AttemptLocalParseRecovery {
129    pub(super) fn yes(&self) -> bool {
130        match self {
131            AttemptLocalParseRecovery::Yes => true,
132            AttemptLocalParseRecovery::No => false,
133        }
134    }
135
136    pub(super) fn no(&self) -> bool {
137        match self {
138            AttemptLocalParseRecovery::Yes => false,
139            AttemptLocalParseRecovery::No => true,
140        }
141    }
142}
143
144/// Checks if the given `lookup` identifier is similar to any keyword symbol in `candidates`.
145///
146/// This is a specialized version of [`Symbol::find_similar`] that constructs an error when a
147/// candidate is found.
148fn find_similar_kw(lookup: Ident, candidates: &[Symbol]) -> Option<MisspelledKw> {
149    lookup.name.find_similar(candidates).map(|(similar_kw, is_incorrect_case)| MisspelledKw {
150        similar_kw: similar_kw.to_string(),
151        is_incorrect_case,
152        span: lookup.span,
153    })
154}
155
156/// SnapshotParser is used to create a snapshot of the parser
157/// without causing duplicate errors being emitted when the `Parser`
158/// is dropped.
159pub struct SnapshotParser<'a> {
160    parser: Parser<'a>,
161}
162
163impl<'a> Deref for SnapshotParser<'a> {
164    type Target = Parser<'a>;
165
166    fn deref(&self) -> &Self::Target {
167        &self.parser
168    }
169}
170
171impl<'a> DerefMut for SnapshotParser<'a> {
172    fn deref_mut(&mut self) -> &mut Self::Target {
173        &mut self.parser
174    }
175}
176
177impl<'a> Parser<'a> {
178    pub fn dcx(&self) -> DiagCtxtHandle<'a> {
179        self.psess.dcx()
180    }
181
182    /// Replace `self` with `snapshot.parser`.
183    pub fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
184        *self = snapshot.parser;
185    }
186
187    /// Create a snapshot of the `Parser`.
188    pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
189        let snapshot = self.clone();
190        SnapshotParser { parser: snapshot }
191    }
192
193    pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
194        self.psess.source_map().span_to_snippet(span)
195    }
196
197    /// Emits an error with suggestions if an identifier was expected but not found.
198    ///
199    /// Returns a possibly recovered identifier.
200    pub(super) fn expected_ident_found(
201        &mut self,
202        recover: bool,
203    ) -> PResult<'a, (Ident, IdentKind)> {
204        let valid_follow = &[
205            TokenKind::Eq,
206            TokenKind::Colon,
207            TokenKind::Comma,
208            TokenKind::Semi,
209            TokenKind::PathSep,
210            TokenKind::OpenBrace,
211            TokenKind::OpenParen,
212            TokenKind::CloseBrace,
213            TokenKind::CloseParen,
214        ];
215        if let TokenKind::DocComment(..) = self.prev_token.kind
216            && valid_follow.contains(&self.token.kind)
217        {
218            let err = self.dcx().create_err(DocCommentDoesNotDocumentAnything {
219                span: self.prev_token.span,
220                missing_comma: None,
221            });
222            return Err(err);
223        }
224
225        let mut recovered_ident = None;
226        // we take this here so that the correct original token is retained in
227        // the diagnostic, regardless of eager recovery.
228        let bad_token = self.token;
229
230        // suggest prepending a keyword in identifier position with `r#`
231        let suggest_raw = if let Some((ident, IdentKind::Normal)) = self.token.ident()
232            && ident.is_raw_guess()
233            && self.look_ahead(1, |t| valid_follow.contains(&t.kind))
234        {
235            recovered_ident = Some((ident, IdentKind::Raw));
236
237            // `Symbol::to_string()` is different from `Symbol::into_diag_arg()`,
238            // which uses `Symbol::to_ident_string()` and "helpfully" adds an implicit `r#`
239            let ident_name = ident.name.to_string();
240
241            Some(SuggEscapeIdentifier { span: ident.span.shrink_to_lo(), ident_name })
242        } else {
243            None
244        };
245
246        let suggest_remove_comma =
247            if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
248                if recover {
249                    self.bump();
250                    recovered_ident = self.ident_or_err(false).ok();
251                };
252
253                Some(SuggRemoveComma { span: bad_token.span })
254            } else {
255                None
256            };
257
258        let help_cannot_start_number = self.is_lit_bad_ident().map(|(len, valid_portion)| {
259            let (invalid, valid) = self.token.span.split_at(len as u32);
260
261            recovered_ident = Some((Ident::new(valid_portion, valid), IdentKind::Normal));
262
263            HelpIdentifierStartsWithNumber { num_span: invalid }
264        });
265
266        let mut err = self.dcx().create_err(ExpectedIdentifier {
267            span: bad_token.span,
268            token: bad_token,
269            suggest_raw,
270            suggest_remove_comma,
271            help_cannot_start_number,
272        });
273
274        // If the token we have is a `<` it *might* be a misplaced generic
275        // parameter list as in `fn <T>id(x: T) -> T { x }`.
276        // FIXME: Could we recover with this?
277        if self.token == token::Lt {
278            // Let's check if the previous token could denote the start of an item
279            // whose kind can have generics.
280            if let Some(Ident { name, .. }) = self.prev_token.non_raw_ident()
281                && let kw::Fn | kw::Type | kw::Struct | kw::Enum | kw::Union | kw::Trait = name
282            {
283                match self.parse_generics() {
284                    Ok(generics) => {
285                        if !self.look_ahead(1, |t| *t == token::Lt)
286                            && let Ok(snippet) =
287                                self.psess.source_map().span_to_snippet(generics.span)
288                        {
289                            err.multipart_suggestion(
290                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("place the generic parameter name after the {0} name",
                name))
    })format!("place the generic parameter name after the {name} name"),
291                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(self.token.span.shrink_to_hi(), snippet),
                (generics.span, String::new())]))vec![
292                                    (self.token.span.shrink_to_hi(), snippet),
293                                    (generics.span, String::new()),
294                                ],
295                                Applicability::MaybeIncorrect,
296                            );
297                        } else {
298                            err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("place the generic parameter name after the {0} name",
                name))
    })format!(
299                                "place the generic parameter name after the {name} name"
300                            ));
301                        }
302                    }
303                    // It's unlikely that the user meant to write a generic parameter list.
304                    // Let's not show them errors specific to generics.
305                    Err(err) => err.cancel(),
306                }
307            }
308        }
309
310        if let Some(recovered_ident) = recovered_ident
311            && recover
312        {
313            err.emit();
314            Ok(recovered_ident)
315        } else {
316            Err(err)
317        }
318    }
319
320    pub(super) fn expected_ident_found_err(&mut self) -> Diag<'a> {
321        self.expected_ident_found(false).unwrap_err()
322    }
323
324    /// Checks if the current token is a integer or float literal and looks like
325    /// it could be a invalid identifier with digits at the start.
326    ///
327    /// Returns the number of characters (bytes) composing the invalid portion
328    /// of the identifier and the valid portion of the identifier.
329    pub(super) fn is_lit_bad_ident(&mut self) -> Option<(usize, Symbol)> {
330        // ensure that the integer literal is followed by a *invalid*
331        // suffix: this is how we know that it is a identifier with an
332        // invalid beginning.
333        if let token::Literal(Lit {
334            kind: token::LitKind::Integer | token::LitKind::Float,
335            symbol,
336            suffix: Some(suffix), // no suffix makes it a valid literal
337        }) = self.token.kind
338            && rustc_ast::MetaItemLit::from_token(&self.token).is_none()
339        {
340            Some((symbol.as_str().len(), suffix))
341        } else {
342            None
343        }
344    }
345
346    pub(super) fn expected_one_of_not_found(
347        &mut self,
348        edible: &[ExpTokenPair],
349        inedible: &[ExpTokenPair],
350    ) -> PResult<'a, ErrorGuaranteed> {
351        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:351",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(351u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("expected_one_of_not_found(edible: {0:?}, inedible: {1:?})",
                                                    edible, inedible) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
352        fn tokens_to_string(tokens: &[TokenType]) -> String {
353            let mut i = tokens.iter();
354            // This might be a sign we need a connect method on `Iterator`.
355            let b = i.next().map_or_else(String::new, |t| t.to_string());
356            i.enumerate().fold(b, |mut b, (i, a)| {
357                if tokens.len() > 2 && i == tokens.len() - 2 {
358                    b.push_str(", or ");
359                } else if tokens.len() == 2 && i == tokens.len() - 2 {
360                    b.push_str(" or ");
361                } else {
362                    b.push_str(", ");
363                }
364                b.push_str(&a.to_string());
365                b
366            })
367        }
368
369        for exp in edible.iter().chain(inedible.iter()) {
370            self.expected_token_types.insert(exp.token_type);
371        }
372        let mut expected: Vec<_> = self.expected_token_types.iter().collect();
373        expected.sort_by_cached_key(|x| x.to_string());
374        expected.dedup();
375
376        let sm = self.psess.source_map();
377
378        // Special-case "expected `;`" errors.
379        if expected.contains(&TokenType::Semi) {
380            // If the user is trying to write a ternary expression, recover it and
381            // return an Err to prevent a cascade of irrelevant diagnostics.
382            if self.prev_token == token::Question
383                && let Err(e) = self.maybe_recover_from_ternary_operator(None)
384            {
385                return Err(e);
386            }
387
388            if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
389                // Likely inside a macro, can't provide meaningful suggestions.
390            } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
391                // The current token is in the same line as the prior token, not recoverable.
392            } else if [token::Comma, token::Colon].contains(&self.token.kind)
393                && self.prev_token == token::CloseParen
394            {
395                // Likely typo: The current token is on a new line and is expected to be
396                // `.`, `;`, `?`, or an operator after a close delimiter token.
397                //
398                // let a = std::process::Command::new("echo")
399                //         .arg("1")
400                //         ,arg("2")
401                //         ^
402                // https://github.com/rust-lang/rust/issues/72253
403            } else if self.look_ahead(1, |t| {
404                t == &token::CloseBrace || t.can_begin_expr() && *t != token::Colon
405            }) && [token::Comma, token::Colon].contains(&self.token.kind)
406            {
407                // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
408                // either `,` or `:`, and the next token could either start a new statement or is a
409                // block close. For example:
410                //
411                //   let x = 32:
412                //   let y = 42;
413                let guar = self.dcx().emit_err(ExpectedSemi {
414                    span: self.token.span,
415                    token: self.token,
416                    unexpected_token_label: None,
417                    sugg: ExpectedSemiSugg::ChangeToSemi(self.token.span),
418                });
419                self.bump();
420                return Ok(guar);
421            } else if self.look_ahead(0, |t| {
422                t == &token::CloseBrace
423                    || ((t.can_begin_expr() || t.can_begin_item())
424                        && t != &token::Semi
425                        && t != &token::Pound)
426                    // Avoid triggering with too many trailing `#` in raw string.
427                    || (sm.is_multiline(
428                        self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
429                    ) && t == &token::Pound)
430            }) && !expected.contains(&TokenType::Comma)
431            {
432                // Missing semicolon typo. This is triggered if the next token could either start a
433                // new statement or is a block close. For example:
434                //
435                //   let x = 32
436                //   let y = 42;
437                let span = self.prev_token.span.shrink_to_hi();
438                let guar = self.dcx().emit_err(ExpectedSemi {
439                    span,
440                    token: self.token,
441                    unexpected_token_label: Some(self.token.span),
442                    sugg: ExpectedSemiSugg::AddSemi(span),
443                });
444                return Ok(guar);
445            }
446        }
447
448        if self.token == TokenKind::EqEq
449            && self.prev_token.is_ident()
450            && expected.contains(&TokenType::Eq)
451        {
452            // Likely typo: `=` → `==` in let expr or enum item
453            return Err(self.dcx().create_err(UseEqInstead { span: self.token.span }));
454        }
455
456        if (self.token.is_keyword(kw::Move) || self.token.is_keyword(kw::Use))
457            && self.prev_token.is_keyword(kw::Async)
458        {
459            // The 2015 edition is in use because parsing of `async move` or `async use` has failed.
460            let span = self.prev_token.span.to(self.token.span);
461            if self.token.is_keyword(kw::Move) {
462                return Err(self.dcx().create_err(AsyncMoveBlockIn2015 { span }));
463            } else {
464                // kw::Use
465                return Err(self.dcx().create_err(AsyncUseBlockIn2015 { span }));
466            }
467        }
468
469        let expect = tokens_to_string(&expected);
470        let actual = super::token_descr(&self.token);
471        let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
472            let fmt = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected one of {0}, found {1}",
                expect, actual))
    })format!("expected one of {expect}, found {actual}");
473            let short_expect = if expected.len() > 6 {
474                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} possible tokens",
                expected.len()))
    })format!("{} possible tokens", expected.len())
475            } else {
476                expect
477            };
478            (fmt, (self.prev_token.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected one of {0}",
                short_expect))
    })format!("expected one of {short_expect}")))
479        } else if expected.is_empty() {
480            (
481                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unexpected token: {0}", actual))
    })format!("unexpected token: {actual}"),
482                (self.prev_token.span, "unexpected token after this".to_string()),
483            )
484        } else {
485            (
486                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1}", expect,
                actual))
    })format!("expected {expect}, found {actual}"),
487                (self.prev_token.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}", expect))
    })format!("expected {expect}")),
488            )
489        };
490        self.last_unexpected_token_span = Some(self.token.span);
491        // FIXME: translation requires list formatting (for `expect`)
492        let mut err = self.dcx().struct_span_err(self.token.span, msg_exp);
493
494        self.label_expected_raw_ref(&mut err);
495
496        // Look for usages of '=>' where '>=' was probably intended
497        if self.token == token::FatArrow
498            && expected.iter().any(|tok| #[allow(non_exhaustive_omitted_patterns)] match tok {
    TokenType::Operator | TokenType::Le => true,
    _ => false,
}matches!(tok, TokenType::Operator | TokenType::Le))
499            && !expected
500                .iter()
501                .any(|tok| #[allow(non_exhaustive_omitted_patterns)] match tok {
    TokenType::FatArrow | TokenType::CloseBrace => true,
    _ => false,
}matches!(tok, TokenType::FatArrow | TokenType::CloseBrace))
502        {
503            err.span_suggestion_verbose(
504                self.token.span,
505                "you might have meant to write a \"greater than or equal to\" comparison",
506                ">=",
507                Applicability::MaybeIncorrect,
508            );
509        }
510
511        if let Some(ident) = self.prev_token.non_raw_ident()
512            && let "def" | "fun" | "func" | "function" = ident.name.as_str()
513        {
514            err.span_suggestion_short(
515                self.prev_token.span,
516                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("write `fn` instead of `{0}` to declare a function",
                ident.name))
    })format!("write `fn` instead of `{}` to declare a function", ident.name),
517                "fn",
518                Applicability::MachineApplicable,
519            );
520        }
521
522        if let TokenKind::Ident(prev, _) = &self.prev_token.kind
523            && let TokenKind::Ident(cur, _) = &self.token.kind
524        {
525            let concat = Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", prev, cur))
    })format!("{prev}{cur}"));
526            let ident = Ident::new(concat, DUMMY_SP);
527            if ident.is_used_keyword() || ident.is_reserved() || ident.is_raw_guess() {
528                let concat_span = self.prev_token.span.to(self.token.span);
529                err.span_suggestion_verbose(
530                    concat_span,
531                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing the space to spell keyword `{0}`",
                concat))
    })format!("consider removing the space to spell keyword `{concat}`"),
532                    concat,
533                    Applicability::MachineApplicable,
534                );
535            }
536        }
537
538        // Try to detect an intended c-string literal while using a pre-2021 edition. The heuristic
539        // here is to identify a cooked, uninterpolated `c` id immediately followed by a string, or
540        // a cooked, uninterpolated `cr` id immediately followed by a string or a `#`, in an edition
541        // where c-string literals are not allowed. There is the very slight possibility of a false
542        // positive for a `cr#` that wasn't intended to start a c-string literal, but identifying
543        // that in the parser requires unbounded lookahead, so we only add a hint to the existing
544        // error rather than replacing it entirely.
545        if ((self.prev_token == TokenKind::Ident(sym::character('c'), IdentKind::Normal)
546            && #[allow(non_exhaustive_omitted_patterns)] match &self.token.kind {
    TokenKind::Literal(token::Lit { kind: token::Str, .. }) => true,
    _ => false,
}matches!(&self.token.kind, TokenKind::Literal(token::Lit { kind: token::Str, .. })))
547            || (self.prev_token == TokenKind::Ident(sym::cr, IdentKind::Normal)
548                && #[allow(non_exhaustive_omitted_patterns)] match &self.token.kind {
    TokenKind::Literal(token::Lit { kind: token::Str, .. }) | token::Pound =>
        true,
    _ => false,
}matches!(
549                    &self.token.kind,
550                    TokenKind::Literal(token::Lit { kind: token::Str, .. }) | token::Pound
551                )))
552            && self.prev_token.span.hi() == self.token.span.lo()
553            && !self.token.span.at_least_rust_2021()
554        {
555            err.note("you may be trying to write a c-string literal");
556            err.note("c-string literals require Rust 2021 or later");
557            err.subdiagnostic(HelpUseLatestEdition::new());
558        }
559
560        // `pub` may be used for an item or `pub(crate)`
561        if self.prev_token.is_ident_named(sym::public)
562            && (self.token.can_begin_item() || self.token == TokenKind::OpenParen)
563        {
564            err.span_suggestion_short(
565                self.prev_token.span,
566                "write `pub` instead of `public` to make the item public",
567                "pub",
568                Applicability::MachineApplicable,
569            );
570        }
571
572        if let token::DocComment(kind, style, _) = self.token.kind {
573            // This is to avoid suggesting converting a doc comment to a regular comment
574            // when missing a comma before the doc comment in lists (#142311):
575            //
576            // ```
577            // enum Foo{
578            //     A /// xxxxxxx
579            //     B,
580            // }
581            // ```
582            if !expected.contains(&TokenType::Comma) {
583                // We have something like `expr //!val` where the user likely meant `expr // !val`
584                let pos = self.token.span.lo() + BytePos(2);
585                let span = self.token.span.with_lo(pos).with_hi(pos);
586                err.span_suggestion_verbose(
587                    span,
588                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add a space before {0} to write a regular comment",
                match (kind, style) {
                    (token::CommentKind::Line, ast::AttrStyle::Inner) => "`!`",
                    (token::CommentKind::Block, ast::AttrStyle::Inner) => "`!`",
                    (token::CommentKind::Line, ast::AttrStyle::Outer) =>
                        "the last `/`",
                    (token::CommentKind::Block, ast::AttrStyle::Outer) =>
                        "the last `*`",
                }))
    })format!(
589                        "add a space before {} to write a regular comment",
590                        match (kind, style) {
591                            (token::CommentKind::Line, ast::AttrStyle::Inner) => "`!`",
592                            (token::CommentKind::Block, ast::AttrStyle::Inner) => "`!`",
593                            (token::CommentKind::Line, ast::AttrStyle::Outer) => "the last `/`",
594                            (token::CommentKind::Block, ast::AttrStyle::Outer) => "the last `*`",
595                        },
596                    ),
597                    " ".to_string(),
598                    Applicability::MaybeIncorrect,
599                );
600            }
601        }
602
603        let sp = if self.token == token::Eof {
604            // This is EOF; don't want to point at the following char, but rather the last token.
605            self.prev_token.span
606        } else {
607            label_sp
608        };
609
610        if self.check_too_many_raw_str_terminators(&mut err) {
611            if expected.contains(&TokenType::Semi) && self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
612                let guar = err.emit_err();
613                return Ok(guar);
614            } else {
615                return Err(err);
616            }
617        }
618
619        if self.prev_token.span == DUMMY_SP {
620            // Account for macro context where the previous span might not be
621            // available to avoid incorrect output (#54841).
622            err.span_label(self.token.span, label_exp);
623        } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
624            // When the spans are in the same line, it means that the only content between
625            // them is whitespace, point at the found token in that case:
626            //
627            // X |     () => { syntax error };
628            //   |                    ^^^^^ expected one of 8 possible tokens here
629            //
630            // instead of having:
631            //
632            // X |     () => { syntax error };
633            //   |                   -^^^^^ unexpected token
634            //   |                   |
635            //   |                   expected one of 8 possible tokens here
636            err.span_label(self.token.span, label_exp);
637        } else {
638            err.span_label(sp, label_exp);
639            err.span_label(self.token.span, "unexpected token");
640        }
641
642        // Check for misspelled keywords if there are no suggestions added to the diagnostic.
643        if let Suggestions::Enabled(list) = &err.suggestions
644            && list.is_empty()
645        {
646            self.check_for_misspelled_kw(&mut err, &expected);
647        }
648        Err(err)
649    }
650
651    pub(super) fn is_expected_raw_ref_mut(&self) -> bool {
652        self.prev_token.is_keyword(kw::Raw)
653            && self.expected_token_types.contains(TokenType::KwMut)
654            && self.expected_token_types.contains(TokenType::KwConst)
655            && self.token.can_begin_expr()
656    }
657
658    /// Adds a label when `&raw EXPR` was written instead of `&raw const EXPR`/`&raw mut EXPR`.
659    ///
660    /// Given that not all parser diagnostics flow through `expected_one_of_not_found`, this
661    /// label may need added to other diagnostics emission paths as needed.
662    pub(super) fn label_expected_raw_ref(&mut self, err: &mut Diag<'_>) {
663        if self.is_expected_raw_ref_mut() {
664            err.span_suggestions(
665                self.prev_token.span.shrink_to_hi(),
666                "`&raw` must be followed by `const` or `mut` to be a raw reference expression",
667                [" const".to_string(), " mut".to_string()],
668                Applicability::MaybeIncorrect,
669            );
670        }
671    }
672
673    /// Checks if the current token or the previous token are misspelled keywords
674    /// and adds a helpful suggestion.
675    fn check_for_misspelled_kw(&self, err: &mut Diag<'_>, expected: &[TokenType]) {
676        let Some((curr_ident, _)) = self.token.ident() else {
677            return;
678        };
679        let expected_token_types: &[TokenType] =
680            expected.len().checked_sub(10).map_or(&expected, |index| &expected[index..]);
681        let expected_keywords: Vec<Symbol> =
682            expected_token_types.iter().filter_map(|token| token.is_keyword()).collect();
683
684        // When there are a few keywords in the last ten elements of `self.expected_token_types`
685        // and the current token is an identifier, it's probably a misspelled keyword. This handles
686        // code like `async Move {}`, misspelled `if` in match guard, misspelled `else` in
687        // `if`-`else` and misspelled `where` in a where clause.
688        if !expected_keywords.is_empty()
689            && !curr_ident.is_used_keyword()
690            && let Some(misspelled_kw) = find_similar_kw(curr_ident, &expected_keywords)
691        {
692            err.subdiagnostic(misspelled_kw);
693            // We don't want other suggestions to be added as they are most likely meaningless
694            // when there is a misspelled keyword.
695            err.seal_suggestions();
696        } else if let Some((prev_ident, _)) = self.prev_token.ident()
697            && !prev_ident.is_used_keyword()
698        {
699            // We generate a list of all keywords at runtime rather than at compile time
700            // so that it gets generated only when the diagnostic needs it.
701            // Also, it is unlikely that this list is generated multiple times because the
702            // parser halts after execution hits this path.
703            let all_keywords = used_keywords(|| prev_ident.span.edition());
704
705            // Otherwise, check the previous token with all the keywords as possible candidates.
706            // This handles code like `Struct Human;` and `While a < b {}`.
707            // We check the previous token only when the current token is an identifier to avoid
708            // false positives like suggesting keyword `for` for `extern crate foo {}`.
709            if let Some(misspelled_kw) = find_similar_kw(prev_ident, &all_keywords) {
710                err.subdiagnostic(misspelled_kw);
711                // We don't want other suggestions to be added as they are most likely meaningless
712                // when there is a misspelled keyword.
713                err.seal_suggestions();
714            }
715        }
716    }
717
718    /// The user has written `#[attr] expr` which is unsupported. (#106020)
719    pub(super) fn attr_on_non_tail_expr(&self, expr: &Expr) -> ErrorGuaranteed {
720        // Missing semicolon typo error.
721        let span = self.prev_token.span.shrink_to_hi();
722        let mut err = self.dcx().create_err(ExpectedSemi {
723            span,
724            token: self.token,
725            unexpected_token_label: Some(self.token.span),
726            sugg: ExpectedSemiSugg::AddSemi(span),
727        });
728        let attr_span = match &expr.attrs[..] {
729            [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
730            [only] => only.span,
731            [first, rest @ ..] => {
732                for attr in rest {
733                    err.span_label(attr.span, "");
734                }
735                first.span
736            }
737        };
738        err.span_label(
739            attr_span,
740            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("only `;` terminated statements or tail expressions are allowed after {0}",
                if expr.attrs.len() == 1 {
                    "this attribute"
                } else { "these attributes" }))
    })format!(
741                "only `;` terminated statements or tail expressions are allowed after {}",
742                if expr.attrs.len() == 1 { "this attribute" } else { "these attributes" },
743            ),
744        );
745        if self.token == token::Pound && self.look_ahead(1, |t| *t == token::OpenBracket) {
746            // We have
747            // #[attr]
748            // expr
749            // #[not_attr]
750            // other_expr
751            err.span_label(span, "expected `;` here");
752            err.multipart_suggestion(
753                "alternatively, consider surrounding the expression with a block",
754                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_lo(), "{ ".to_string()),
                (expr.span.shrink_to_hi(), " }".to_string())]))vec![
755                    (expr.span.shrink_to_lo(), "{ ".to_string()),
756                    (expr.span.shrink_to_hi(), " }".to_string()),
757                ],
758                Applicability::MachineApplicable,
759            );
760
761            // Special handling for `#[cfg(...)]` chains
762            let mut snapshot = self.create_snapshot_for_diagnostic();
763            if let [attr] = &expr.attrs[..]
764                && let ast::AttrKind::Normal(attr_kind) = &attr.kind
765                && let [segment] = &attr_kind.item.path.segments[..]
766                && segment.ident.name == sym::cfg
767                && let Some(args_span) = attr_kind.item.args.span()
768                && let next_attr = match snapshot.parse_attribute(InnerAttrPolicy::Forbidden(None))
769                {
770                    Ok(next_attr) => next_attr,
771                    Err(inner_err) => {
772                        inner_err.cancel();
773                        return err.emit_err();
774                    }
775                }
776                && let ast::AttrKind::Normal(next_attr_kind) = next_attr.kind
777                && let Some(next_attr_args_span) = next_attr_kind.item.args.span()
778                && let [next_segment] = &next_attr_kind.item.path.segments[..]
779                && next_segment.ident.name == sym::cfg
780            {
781                let next_expr = match snapshot.parse_expr() {
782                    Ok(next_expr) => next_expr,
783                    Err(inner_err) => {
784                        inner_err.cancel();
785                        return err.emit_err();
786                    }
787                };
788                // We have for sure
789                // #[cfg(..)]
790                // expr
791                // #[cfg(..)]
792                // other_expr
793                // So we suggest using `if cfg!(..) { expr } else if cfg!(..) { other_expr }`.
794                let margin = self.psess.source_map().span_to_margin(next_expr.span).unwrap_or(0);
795                let sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(attr.span.with_hi(segment.span().hi()), "if cfg!".to_string()),
                (args_span.shrink_to_hi().with_hi(attr.span.hi()),
                    " {".to_string()),
                (expr.span.shrink_to_lo(), "    ".to_string()),
                (next_attr.span.with_hi(next_segment.span().hi()),
                    "} else if cfg!".to_string()),
                (next_attr_args_span.shrink_to_hi().with_hi(next_attr.span.hi()),
                    " {".to_string()),
                (next_expr.span.shrink_to_lo(), "    ".to_string()),
                (next_expr.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("\n{0}}}",
                                    " ".repeat(margin)))
                        }))]))vec![
796                    (attr.span.with_hi(segment.span().hi()), "if cfg!".to_string()),
797                    (args_span.shrink_to_hi().with_hi(attr.span.hi()), " {".to_string()),
798                    (expr.span.shrink_to_lo(), "    ".to_string()),
799                    (
800                        next_attr.span.with_hi(next_segment.span().hi()),
801                        "} else if cfg!".to_string(),
802                    ),
803                    (
804                        next_attr_args_span.shrink_to_hi().with_hi(next_attr.span.hi()),
805                        " {".to_string(),
806                    ),
807                    (next_expr.span.shrink_to_lo(), "    ".to_string()),
808                    (next_expr.span.shrink_to_hi(), format!("\n{}}}", " ".repeat(margin))),
809                ];
810                err.multipart_suggestion(
811                    "it seems like you are trying to provide different expressions depending on \
812                     `cfg`, consider using `if cfg!(..)`",
813                    sugg,
814                    Applicability::MachineApplicable,
815                );
816            }
817        }
818
819        err.emit_err()
820    }
821
822    fn check_too_many_raw_str_terminators(&mut self, err: &mut Diag<'_>) -> bool {
823        let sm = self.psess.source_map();
824        match (&self.prev_token.kind, &self.token.kind) {
825            (
826                TokenKind::Literal(Lit {
827                    kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
828                    ..
829                }),
830                TokenKind::Pound,
831            ) if !sm.is_multiline(
832                self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
833            ) =>
834            {
835                let n_hashes: u8 = *n_hashes;
836                err.primary_message("too many `#` when terminating raw string");
837                let str_span = self.prev_token.span;
838                let mut span = self.token.span;
839                let mut count = 0;
840                while self.token == TokenKind::Pound
841                    && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
842                {
843                    span = span.with_hi(self.token.span.hi());
844                    self.bump();
845                    count += 1;
846                }
847                err.span(span);
848                err.span_suggestion_verbose(
849                    span,
850                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("remove the extra `#`{0}",
                if count == 1 { "" } else { "s" }))
    })format!("remove the extra `#`{}", pluralize!(count)),
851                    "",
852                    Applicability::MachineApplicable,
853                );
854                err.span_label(
855                    str_span,
856                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this raw string started with {1} `#`{0}",
                if n_hashes == 1 { "" } else { "s" }, n_hashes))
    })format!("this raw string started with {n_hashes} `#`{}", pluralize!(n_hashes)),
857                );
858                true
859            }
860            _ => false,
861        }
862    }
863
864    pub(super) fn maybe_suggest_struct_literal(
865        &mut self,
866        lo: Span,
867        s: BlockCheckMode,
868        maybe_struct_name: token::Token,
869    ) -> Option<PResult<'a, Box<Block>>> {
870        if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
871            // We might be having a struct literal where people forgot to include the path:
872            // fn foo() -> Foo {
873            //     field: value,
874            // }
875            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:875",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(875u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("maybe_struct_name")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("maybe_struct_name");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("self.token")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("self.token");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&maybe_struct_name)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.token)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?maybe_struct_name, ?self.token);
876            let mut snapshot = self.create_snapshot_for_diagnostic();
877            let path = Path { segments: ThinVec::new(), span: self.prev_token.span.shrink_to_lo() };
878            let struct_expr = snapshot.parse_expr_struct(None, path, false);
879            let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
880            return Some(match (struct_expr, block_tail) {
881                (Ok(expr), Err(err)) => {
882                    // We have encountered the following:
883                    // fn foo() -> Foo {
884                    //     field: value,
885                    // }
886                    // Suggest:
887                    // fn foo() -> Foo { Path {
888                    //     field: value,
889                    // } }
890                    err.cancel();
891                    self.restore_snapshot(snapshot);
892                    let guar = self.dcx().emit_err(StructLiteralBodyWithoutPath {
893                        span: expr.span,
894                        sugg: StructLiteralBodyWithoutPathSugg {
895                            before: expr.span.shrink_to_lo(),
896                            after: expr.span.shrink_to_hi(),
897                        },
898                    });
899                    Ok(self.mk_block(
900                        {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(self.mk_stmt_err(expr.span, guar));
    vec
}thin_vec![self.mk_stmt_err(expr.span, guar)],
901                        s,
902                        lo.to(self.prev_token.span),
903                    ))
904                }
905                (Err(err), Ok(tail)) => {
906                    // We have a block tail that contains a somehow valid expr.
907                    err.cancel();
908                    Ok(tail)
909                }
910                (Err(snapshot_err), Err(err)) => {
911                    // We don't know what went wrong, emit the normal error.
912                    snapshot_err.cancel();
913                    self.consume_block(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace), crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace), ConsumeClosingDelim::Yes);
914                    Err(err)
915                }
916                (Ok(_), Ok(tail)) => Ok(tail),
917            });
918        }
919        None
920    }
921
922    pub(super) fn recover_closure_body(
923        &mut self,
924        mut err: Diag<'a>,
925        before: token::Token,
926        prev: token::Token,
927        token: token::Token,
928        lo: Span,
929        decl_hi: Span,
930    ) -> PResult<'a, Box<Expr>> {
931        err.span_label(lo.to(decl_hi), "while parsing the body of this closure");
932        let guar = match before.kind {
933            token::OpenBrace if token.kind != token::OpenBrace => {
934                // `{ || () }` should have been `|| { () }`
935                err.multipart_suggestion(
936                    "you might have meant to open the body of the closure, instead of enclosing \
937                     the closure in a block",
938                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(before.span, String::new()),
                (prev.span.shrink_to_hi(), " {".to_string())]))vec![
939                        (before.span, String::new()),
940                        (prev.span.shrink_to_hi(), " {".to_string()),
941                    ],
942                    Applicability::MaybeIncorrect,
943                );
944                let guar = err.emit_err();
945                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
946                guar
947            }
948            token::OpenParen if token.kind != token::OpenBrace => {
949                // We are within a function call or tuple, we can emit the error
950                // and recover.
951                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen), crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)]);
952
953                err.multipart_suggestion(
954                    "you might have meant to open the body of the closure",
955                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(prev.span.shrink_to_hi(), " {".to_string()),
                (self.token.span.shrink_to_lo(), "}".to_string())]))vec![
956                        (prev.span.shrink_to_hi(), " {".to_string()),
957                        (self.token.span.shrink_to_lo(), "}".to_string()),
958                    ],
959                    Applicability::MaybeIncorrect,
960                );
961                err.emit_err()
962            }
963            _ if token.kind != token::OpenBrace => {
964                // We don't have a heuristic to correctly identify where the block
965                // should be closed.
966                err.multipart_suggestion(
967                    "you might have meant to open the body of the closure",
968                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(prev.span.shrink_to_hi(), " {".to_string())]))vec![(prev.span.shrink_to_hi(), " {".to_string())],
969                    Applicability::HasPlaceholders,
970                );
971                return Err(err);
972            }
973            _ => return Err(err),
974        };
975        Ok(self.mk_expr_err(lo.to(self.token.span), guar))
976    }
977
978    /// Eats and discards tokens until one of `closes` is encountered. Respects token trees,
979    /// passes through any errors encountered. Used for error recovery.
980    pub(super) fn eat_to_tokens(&mut self, closes: &[ExpTokenPair]) {
981        if let Err(err) = self
982            .parse_seq_to_before_tokens(closes, &[], SeqSep::none(), |p| Ok(p.parse_token_tree()))
983        {
984            err.cancel();
985        }
986    }
987
988    /// This function checks if there are trailing angle brackets and produces
989    /// a diagnostic to suggest removing them.
990    ///
991    /// ```ignore (diagnostic)
992    /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
993    ///                                                    ^^ help: remove extra angle brackets
994    /// ```
995    ///
996    /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
997    /// up until one of the tokens in 'end' was encountered, and an error was emitted.
998    pub(super) fn check_trailing_angle_brackets(
999        &mut self,
1000        segment: &PathSegment,
1001        end: &[ExpTokenPair],
1002    ) -> Option<ErrorGuaranteed> {
1003        if !self.may_recover() {
1004            return None;
1005        }
1006
1007        // This function is intended to be invoked after parsing a path segment where there are two
1008        // cases:
1009        //
1010        // 1. A specific token is expected after the path segment.
1011        //    eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
1012        //        `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
1013        // 2. No specific token is expected after the path segment.
1014        //    eg. `x.foo` (field access)
1015        //
1016        // This function is called after parsing `.foo` and before parsing the token `end` (if
1017        // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
1018        // `Foo::<Bar>`.
1019
1020        // We only care about trailing angle brackets if we previously parsed angle bracket
1021        // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
1022        // removed in this case:
1023        //
1024        // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
1025        //
1026        // This case is particularly tricky as we won't notice it just looking at the tokens -
1027        // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
1028        // have already been parsed):
1029        //
1030        // `x.foo::<u32>>>(3)`
1031        let parsed_angle_bracket_args =
1032            segment.args.as_ref().is_some_and(|args| args.is_angle_bracketed());
1033
1034        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:1034",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1034u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_trailing_angle_brackets: parsed_angle_bracket_args={0:?}",
                                                    parsed_angle_bracket_args) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1035            "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
1036            parsed_angle_bracket_args,
1037        );
1038        if !parsed_angle_bracket_args {
1039            return None;
1040        }
1041
1042        // Keep the span at the start so we can highlight the sequence of `>` characters to be
1043        // removed.
1044        let lo = self.token.span;
1045
1046        // We need to look-ahead to see if we have `>` characters without moving the cursor forward
1047        // (since we might have the field access case and the characters we're eating are
1048        // actual operators and not trailing characters - ie `x.foo >> 3`).
1049        let mut position = 0;
1050
1051        // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
1052        // many of each (so we can correctly pluralize our error messages) and continue to
1053        // advance.
1054        let mut number_of_shr = 0;
1055        let mut number_of_gt = 0;
1056        while self.look_ahead(position, |t| {
1057            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:1057",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1057u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_trailing_angle_brackets: t={0:?}",
                                                    t) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("check_trailing_angle_brackets: t={:?}", t);
1058            if *t == token::Shr {
1059                number_of_shr += 1;
1060                true
1061            } else if *t == token::Gt {
1062                number_of_gt += 1;
1063                true
1064            } else {
1065                false
1066            }
1067        }) {
1068            position += 1;
1069        }
1070
1071        // If we didn't find any trailing `>` characters, then we have nothing to error about.
1072        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:1072",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1072u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_trailing_angle_brackets: number_of_gt={0:?} number_of_shr={1:?}",
                                                    number_of_gt, number_of_shr) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1073            "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
1074            number_of_gt, number_of_shr,
1075        );
1076        if number_of_gt < 1 && number_of_shr < 1 {
1077            return None;
1078        }
1079
1080        // Finally, double check that we have our end token as otherwise this is the
1081        // second case.
1082        if self.look_ahead(position, |t| {
1083            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:1083",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1083u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_trailing_angle_brackets: t={0:?}",
                                                    t) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("check_trailing_angle_brackets: t={:?}", t);
1084            end.iter().any(|exp| exp.tok == t.kind)
1085        }) {
1086            // Eat from where we started until the end token so that parsing can continue
1087            // as if we didn't have those extra angle brackets.
1088            self.eat_to_tokens(end);
1089            let span = lo.to(self.prev_token.span);
1090
1091            let num_extra_brackets = number_of_gt + number_of_shr * 2;
1092            return Some(self.dcx().emit_err(UnmatchedAngleBrackets { span, num_extra_brackets }));
1093        }
1094        None
1095    }
1096
1097    /// Check if a method call with an intended turbofish has been written without surrounding
1098    /// angle brackets.
1099    pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
1100        if !self.may_recover() {
1101            return;
1102        }
1103
1104        if self.token == token::PathSep && segment.args.is_none() {
1105            let snapshot = self.create_snapshot_for_diagnostic();
1106            self.bump();
1107            let lo = self.token.span;
1108            match self.parse_angle_args(None) {
1109                Ok(args) => {
1110                    let span = lo.to(self.prev_token.span);
1111                    // Detect trailing `>` like in `x.collect::Vec<_>>()`.
1112                    let mut trailing_span = self.prev_token.span.shrink_to_hi();
1113                    while self.token == token::Shr || self.token == token::Gt {
1114                        trailing_span = trailing_span.to(self.token.span);
1115                        self.bump();
1116                    }
1117                    if self.token == token::OpenParen {
1118                        // Recover from bad turbofish: `foo.collect::Vec<_>()`.
1119                        segment.args = Some(AngleBracketedArgs { args, span }.into());
1120
1121                        self.dcx().emit_err(GenericParamsWithoutAngleBrackets {
1122                            span,
1123                            sugg: GenericParamsWithoutAngleBracketsSugg {
1124                                left: span.shrink_to_lo(),
1125                                right: trailing_span,
1126                            },
1127                        });
1128                    } else {
1129                        // This doesn't look like an invalid turbofish, can't recover parse state.
1130                        self.restore_snapshot(snapshot);
1131                    }
1132                }
1133                Err(err) => {
1134                    // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
1135                    // generic parse error instead.
1136                    err.cancel();
1137                    self.restore_snapshot(snapshot);
1138                }
1139            }
1140        }
1141    }
1142
1143    /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
1144    /// encounter a parse error when encountering the first `,`.
1145    pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
1146        &mut self,
1147        mut e: Diag<'a>,
1148        expr: &mut Box<Expr>,
1149    ) -> PResult<'a, ErrorGuaranteed> {
1150        if let ExprKind::Binary(binop, _, _) = &expr.kind
1151            && let ast::BinOpKind::Lt = binop.node
1152            && self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))
1153        {
1154            let x = self.parse_seq_to_before_end(
1155                crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt),
1156                SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
1157                |p| match p.parse_generic_arg(None)? {
1158                    Some(arg) => Ok(arg),
1159                    // If we didn't eat a generic arg, then we should error.
1160                    None => p.unexpected_any(),
1161                },
1162            );
1163            match x {
1164                Ok((_, _, Recovered::No)) => {
1165                    if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)) {
1166                        // We made sense of it. Improve the error message.
1167                        e.span_suggestion_verbose(
1168                            binop.span.shrink_to_lo(),
1169                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments"))msg!("use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments"),
1170                            "::",
1171                            Applicability::MaybeIncorrect,
1172                        );
1173                        match self.parse_expr() {
1174                            Ok(_) => {
1175                                // The subsequent expression is valid. Mark
1176                                // `expr` as erroneous and emit `e` now, but
1177                                // return `Ok` so parsing can continue.
1178                                let guar = e.emit_err();
1179                                *expr = self.mk_expr_err(expr.span.to(self.prev_token.span), guar);
1180                                return Ok(guar);
1181                            }
1182                            Err(err) => {
1183                                err.cancel();
1184                            }
1185                        }
1186                    }
1187                }
1188                Ok((_, _, Recovered::Yes(_))) => {}
1189                Err(err) => {
1190                    err.cancel();
1191                }
1192            }
1193        }
1194        Err(e)
1195    }
1196
1197    /// Suggest add the missing `let` before the identifier in stmt
1198    /// `a: Ty = 1` -> `let a: Ty = 1`
1199    pub(super) fn suggest_add_missing_let_for_stmt(&mut self, err: &mut Diag<'a>) {
1200        if self.token == token::Colon {
1201            let prev_span = self.prev_token.span.shrink_to_lo();
1202            let snapshot = self.create_snapshot_for_diagnostic();
1203            self.bump();
1204            match self.parse_ty() {
1205                Ok(_) => {
1206                    if self.token == token::Eq {
1207                        let sugg = SuggAddMissingLetStmt { span: prev_span };
1208                        sugg.add_to_diag(err);
1209                    }
1210                }
1211                Err(e) => {
1212                    e.cancel();
1213                }
1214            }
1215            self.restore_snapshot(snapshot);
1216        }
1217    }
1218
1219    /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
1220    /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
1221    /// parenthesising the leftmost comparison. The return value indicates if recovery happened.
1222    fn attempt_chained_comparison_suggestion(
1223        &mut self,
1224        err: &mut ComparisonOperatorsCannotBeChained,
1225        inner_op: &Expr,
1226        outer_op: &Spanned<AssocOp>,
1227    ) -> bool {
1228        if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
1229            if let ExprKind::Field(_, ident) = l1.kind
1230                && !ident.is_numeric()
1231                && !#[allow(non_exhaustive_omitted_patterns)] match r1.kind {
    ExprKind::Lit(_) => true,
    _ => false,
}matches!(r1.kind, ExprKind::Lit(_))
1232            {
1233                // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
1234                // suggestion being the only one to apply is high.
1235                return false;
1236            }
1237            return match (op.node, &outer_op.node) {
1238                // `x == y == z`
1239                (BinOpKind::Eq, AssocOp::Binary(BinOpKind::Eq)) |
1240                // `x < y < z` and friends.
1241                (BinOpKind::Lt, AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le)) |
1242                (BinOpKind::Le, AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le)) |
1243                // `x > y > z` and friends.
1244                (BinOpKind::Gt, AssocOp::Binary(BinOpKind::Gt | BinOpKind::Ge)) |
1245                (BinOpKind::Ge, AssocOp::Binary(BinOpKind::Gt | BinOpKind::Ge)) => {
1246                    let expr_to_str = |e: &Expr| {
1247                        self.span_to_snippet(e.span).unwrap_or_else(|_| pprust::expr_to_string(e))
1248                    };
1249                    err.chaining_sugg =
1250                        Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison {
1251                            span: inner_op.span.shrink_to_hi(),
1252                            middle_term: expr_to_str(r1),
1253                        });
1254                    false // Keep the current parse behavior, where the AST is `(x < y) < z`.
1255                }
1256                // `x == y < z`
1257                (
1258                    BinOpKind::Eq,
1259                    AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge),
1260                ) => {
1261                    // Consume `z`/outer-op-rhs.
1262                    let snapshot = self.create_snapshot_for_diagnostic();
1263                    match self.parse_expr() {
1264                        Ok(r2) => {
1265                            // We are sure that outer-op-rhs could be consumed, the suggestion is
1266                            // likely correct.
1267                            err.chaining_sugg =
1268                                Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1269                                    left: r1.span.shrink_to_lo(),
1270                                    right: r2.span.shrink_to_hi(),
1271                                });
1272                            true
1273                        }
1274                        Err(expr_err) => {
1275                            expr_err.cancel();
1276                            self.restore_snapshot(snapshot);
1277                            true
1278                        }
1279                    }
1280                }
1281                // `x > y == z`
1282                (
1283                    BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge,
1284                    AssocOp::Binary(BinOpKind::Eq),
1285                ) => {
1286                    let snapshot = self.create_snapshot_for_diagnostic();
1287                    // At this point it is always valid to enclose the lhs in parentheses, no
1288                    // further checks are necessary.
1289                    match self.parse_expr() {
1290                        Ok(_) => {
1291                            err.chaining_sugg =
1292                                Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1293                                    left: l1.span.shrink_to_lo(),
1294                                    right: r1.span.shrink_to_hi(),
1295                                });
1296                            true
1297                        }
1298                        Err(expr_err) => {
1299                            expr_err.cancel();
1300                            self.restore_snapshot(snapshot);
1301                            false
1302                        }
1303                    }
1304                }
1305                _ => false,
1306            };
1307        }
1308        false
1309    }
1310
1311    /// Produces an error if comparison operators are chained (RFC #558).
1312    /// We only need to check the LHS, not the RHS, because all comparison ops have same
1313    /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
1314    ///
1315    /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
1316    /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
1317    /// case.
1318    ///
1319    /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
1320    /// associative we can infer that we have:
1321    ///
1322    /// ```text
1323    ///           outer_op
1324    ///           /   \
1325    ///     inner_op   r2
1326    ///        /  \
1327    ///      l1    r1
1328    /// ```
1329    pub(super) fn check_no_chained_comparison(
1330        &mut self,
1331        inner_op: &Expr,
1332        outer_op: &Spanned<AssocOp>,
1333    ) -> PResult<'a, Option<Box<Expr>>> {
1334        if true {
    if !outer_op.node.is_comparison() {
        {
            ::core::panicking::panic_fmt(format_args!("check_no_chained_comparison: {0:?} is not comparison",
                    outer_op.node));
        }
    };
};debug_assert!(
1335            outer_op.node.is_comparison(),
1336            "check_no_chained_comparison: {:?} is not comparison",
1337            outer_op.node,
1338        );
1339
1340        let mk_err_expr =
1341            |this: &Self, span, guar| Ok(Some(this.mk_expr(span, ExprKind::Err(guar))));
1342
1343        match &inner_op.kind {
1344            ExprKind::Binary(op, l1, r1) if op.node.is_comparison() => {
1345                let mut err = ComparisonOperatorsCannotBeChained {
1346                    span: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [op.span, self.prev_token.span]))vec![op.span, self.prev_token.span],
1347                    suggest_turbofish: None,
1348                    help_turbofish: false,
1349                    chaining_sugg: None,
1350                };
1351
1352                // Include `<` to provide this recommendation even in a case like
1353                // `Foo<Bar<Baz<Qux, ()>>>`
1354                if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Binary(BinOpKind::Lt)
1355                    || outer_op.node == AssocOp::Binary(BinOpKind::Gt)
1356                {
1357                    if outer_op.node == AssocOp::Binary(BinOpKind::Lt) {
1358                        let snapshot = self.create_snapshot_for_diagnostic();
1359                        self.bump();
1360                        // So far we have parsed `foo<bar<`, consume the rest of the type args.
1361                        let modifiers = [(token::Lt, 1), (token::Gt, -1), (token::Shr, -2)];
1362                        self.consume_tts(1, &modifiers);
1363
1364                        if !#[allow(non_exhaustive_omitted_patterns)] match self.token.kind {
    token::OpenParen | token::PathSep => true,
    _ => false,
}matches!(self.token.kind, token::OpenParen | token::PathSep) {
1365                            // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
1366                            // parser and bail out.
1367                            self.restore_snapshot(snapshot);
1368                        }
1369                    }
1370                    return if self.token == token::PathSep {
1371                        // We have some certainty that this was a bad turbofish at this point.
1372                        // `foo< bar >::`
1373                        if let ExprKind::Binary(o, ..) = inner_op.kind
1374                            && o.node == BinOpKind::Lt
1375                        {
1376                            err.suggest_turbofish = Some(op.span.shrink_to_lo());
1377                        } else {
1378                            err.help_turbofish = true;
1379                        }
1380
1381                        let snapshot = self.create_snapshot_for_diagnostic();
1382                        self.bump(); // `::`
1383
1384                        // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
1385                        match self.parse_expr() {
1386                            Ok(_) => {
1387                                // 99% certain that the suggestion is correct, continue parsing.
1388                                let guar = self.dcx().emit_err(err);
1389                                // FIXME: actually check that the two expressions in the binop are
1390                                // paths and resynthesize new fn call expression instead of using
1391                                // `ExprKind::Err` placeholder.
1392                                mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1393                            }
1394                            Err(expr_err) => {
1395                                expr_err.cancel();
1396                                // Not entirely sure now, but we bubble the error up with the
1397                                // suggestion.
1398                                self.restore_snapshot(snapshot);
1399                                Err(self.dcx().create_err(err))
1400                            }
1401                        }
1402                    } else if self.token == token::OpenParen {
1403                        // We have high certainty that this was a bad turbofish at this point.
1404                        // `foo< bar >(`
1405                        if let ExprKind::Binary(o, ..) = inner_op.kind
1406                            && o.node == BinOpKind::Lt
1407                        {
1408                            err.suggest_turbofish = Some(op.span.shrink_to_lo());
1409                        } else {
1410                            err.help_turbofish = true;
1411                        }
1412                        // Consume the fn call arguments.
1413                        match self.consume_fn_args() {
1414                            Err(()) => Err(self.dcx().create_err(err)),
1415                            Ok(()) => {
1416                                let guar = self.dcx().emit_err(err);
1417                                // FIXME: actually check that the two expressions in the binop are
1418                                // paths and resynthesize new fn call expression instead of using
1419                                // `ExprKind::Err` placeholder.
1420                                mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1421                            }
1422                        }
1423                    } else {
1424                        if !#[allow(non_exhaustive_omitted_patterns)] match l1.kind {
    ExprKind::Lit(_) => true,
    _ => false,
}matches!(l1.kind, ExprKind::Lit(_))
1425                            && !#[allow(non_exhaustive_omitted_patterns)] match r1.kind {
    ExprKind::Lit(_) => true,
    _ => false,
}matches!(r1.kind, ExprKind::Lit(_))
1426                        {
1427                            // All we know is that this is `foo < bar >` and *nothing* else. Try to
1428                            // be helpful, but don't attempt to recover.
1429                            err.help_turbofish = true;
1430                        }
1431
1432                        // If it looks like a genuine attempt to chain operators (as opposed to a
1433                        // misformatted turbofish, for instance), suggest a correct form.
1434                        let recovered = self
1435                            .attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1436                        if recovered {
1437                            let guar = self.dcx().emit_err(err);
1438                            mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1439                        } else {
1440                            // These cases cause too many knock-down errors, bail out (#61329).
1441                            Err(self.dcx().create_err(err))
1442                        }
1443                    };
1444                }
1445                let recovered =
1446                    self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1447                let guar = self.dcx().emit_err(err);
1448                if recovered {
1449                    return mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar);
1450                }
1451            }
1452            _ => {}
1453        }
1454        Ok(None)
1455    }
1456
1457    fn consume_fn_args(&mut self) -> Result<(), ()> {
1458        let snapshot = self.create_snapshot_for_diagnostic();
1459        self.bump(); // `(`
1460
1461        // Consume the fn call arguments.
1462        let modifiers = [(token::OpenParen, 1), (token::CloseParen, -1)];
1463        self.consume_tts(1, &modifiers);
1464
1465        if self.token == token::Eof {
1466            // Not entirely sure that what we consumed were fn arguments, rollback.
1467            self.restore_snapshot(snapshot);
1468            Err(())
1469        } else {
1470            // 99% certain that the suggestion is correct, continue parsing.
1471            Ok(())
1472        }
1473    }
1474
1475    pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1476        if impl_dyn_multi {
1477            self.dcx().emit_err(AmbiguousPlus {
1478                span: ty.span,
1479                suggestion: AddParen { lo: ty.span.shrink_to_lo(), hi: ty.span.shrink_to_hi() },
1480            });
1481        }
1482    }
1483
1484    /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1485    pub(super) fn maybe_recover_from_question_mark(&mut self, ty: Box<Ty>) -> Box<Ty> {
1486        if self.token == token::Question {
1487            self.bump();
1488            let guar = self.dcx().emit_err(QuestionMarkInType {
1489                span: self.prev_token.span,
1490                sugg: QuestionMarkInTypeSugg {
1491                    left: ty.span.shrink_to_lo(),
1492                    right: self.prev_token.span,
1493                },
1494            });
1495            self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err(guar))
1496        } else {
1497            ty
1498        }
1499    }
1500
1501    /// Rust has no ternary operator (`cond ? then : else`). Parse it and try
1502    /// to recover from it if `then` and `else` are valid expressions. Returns
1503    /// an err if this appears to be a ternary expression.
1504    /// If we have the span of the condition, we can provide a better error span
1505    /// and code suggestion.
1506    pub(super) fn maybe_recover_from_ternary_operator(
1507        &mut self,
1508        cond: Option<Span>,
1509    ) -> PResult<'a, ()> {
1510        if self.prev_token != token::Question {
1511            return PResult::Ok(());
1512        }
1513
1514        let question = self.prev_token.span;
1515        let lo = cond.unwrap_or(question).lo();
1516        let snapshot = self.create_snapshot_for_diagnostic();
1517
1518        if match self.parse_expr() {
1519            Ok(_) => true,
1520            Err(err) => {
1521                err.cancel();
1522                // The colon can sometimes be mistaken for type
1523                // ascription. Catch when this happens and continue.
1524                self.token == token::Colon
1525            }
1526        } {
1527            if self.eat_noexpect(&token::Colon) {
1528                let colon = self.prev_token.span;
1529                match self.parse_expr() {
1530                    Ok(expr) => {
1531                        let sugg = cond.map(|cond| TernaryOperatorSuggestion {
1532                            before_cond: cond.shrink_to_lo(),
1533                            question,
1534                            colon,
1535                            end: expr.span.shrink_to_hi(),
1536                        });
1537                        return Err(self.dcx().create_err(TernaryOperator {
1538                            span: self.prev_token.span.with_lo(lo),
1539                            sugg,
1540                            no_sugg: sugg.is_none(),
1541                        }));
1542                    }
1543                    Err(err) => {
1544                        err.cancel();
1545                    }
1546                };
1547            }
1548        }
1549        self.restore_snapshot(snapshot);
1550        Ok(())
1551    }
1552
1553    pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
1554        // Do not add `+` to expected tokens.
1555        if !self.token.is_like_plus() {
1556            return Ok(());
1557        }
1558
1559        self.bump(); // `+`
1560        let _bounds = self.parse_generic_bounds()?;
1561        let sub = match &ty.kind {
1562            TyKind::Ref(_lifetime, mut_ty) => {
1563                let lo = mut_ty.ty.span.shrink_to_lo();
1564                let hi = self.prev_token.span.shrink_to_hi();
1565                BadTypePlusSub::AddParen { suggestion: AddParen { lo, hi } }
1566            }
1567            TyKind::Ptr(..) | TyKind::FnPtr(..) => {
1568                BadTypePlusSub::ForgotParen { span: ty.span.to(self.prev_token.span) }
1569            }
1570            _ => BadTypePlusSub::ExpectPath { span: ty.span },
1571        };
1572
1573        self.dcx().emit_err(BadTypePlus { span: ty.span, sub });
1574
1575        Ok(())
1576    }
1577
1578    /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1579    /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1580    /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1581    pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1582        &mut self,
1583        base: T,
1584    ) -> PResult<'a, T> {
1585        // Do not add `::` to expected tokens.
1586        if self.may_recover() && self.token == token::PathSep {
1587            return self.recover_from_bad_qpath(base);
1588        }
1589        Ok(base)
1590    }
1591
1592    #[cold]
1593    fn recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T) -> PResult<'a, T> {
1594        if let Some(ty) = base.to_ty() {
1595            return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1596        }
1597        Ok(base)
1598    }
1599
1600    /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1601    /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1602    pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1603        &mut self,
1604        ty_span: Span,
1605        ty: Box<Ty>,
1606    ) -> PResult<'a, T> {
1607        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::PathSep,
    token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep))?;
1608
1609        let mut path = ast::Path { segments: ThinVec::new(), span: DUMMY_SP };
1610        self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1611        path.span = ty_span.to(self.prev_token.span);
1612
1613        self.dcx().emit_err(BadQPathStage2 {
1614            span: ty_span,
1615            wrap: WrapType { lo: ty_span.shrink_to_lo(), hi: ty_span.shrink_to_hi() },
1616        });
1617
1618        let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1619        Ok(T::recovered(Some(Box::new(QSelf { ty, path_span, position: 0 })), path))
1620    }
1621
1622    /// This function gets called in places where a semicolon is NOT expected and if there's a
1623    /// semicolon it emits the appropriate error and returns true.
1624    pub fn maybe_consume_incorrect_semicolon(&mut self, previous_item: Option<&Item>) -> bool {
1625        if self.token != TokenKind::Semi {
1626            return false;
1627        }
1628
1629        // Check previous item to add it to the diagnostic, for example to say
1630        // `enum declarations are not followed by a semicolon`
1631        let err = match previous_item {
1632            Some(previous_item) => {
1633                let name = match previous_item.kind {
1634                    // Say "braced struct" because tuple-structs and
1635                    // braceless-empty-struct declarations do take a semicolon.
1636                    ItemKind::Struct(..) => "braced struct",
1637                    _ => previous_item.kind.descr(),
1638                };
1639                IncorrectSemicolon { span: self.token.span, name, show_help: true }
1640            }
1641            None => IncorrectSemicolon { span: self.token.span, name: "", show_help: false },
1642        };
1643        self.dcx().emit_err(err);
1644
1645        self.bump();
1646        true
1647    }
1648
1649    /// Creates a `Diag` for an unexpected token `t`
1650    pub(super) fn unexpected_err(&mut self, t: &TokenKind) -> Diag<'a> {
1651        let token_str = pprust::token_kind_to_string(t);
1652        let this_token_str = super::token_descr(&self.token);
1653        let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1654            // Point at the end of the macro call when reaching end of macro arguments.
1655            (token::Eof, Some(_)) => {
1656                let sp = self.prev_token.span.shrink_to_hi();
1657                (sp, sp)
1658            }
1659            // We don't want to point at the following span after DUMMY_SP.
1660            // This happens when the parser finds an empty TokenStream.
1661            _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1662            // EOF, don't want to point at the following char, but rather the last token.
1663            (token::Eof, None) => (self.prev_token.span, self.token.span),
1664            _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1665        };
1666        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`, found {1}",
                token_str,
                match (&self.token.kind, self.subparser_name) {
                    (token::Eof, Some(origin)) =>
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("end of {0}", origin))
                            }),
                    _ => this_token_str,
                }))
    })format!(
1667            "expected `{}`, found {}",
1668            token_str,
1669            match (&self.token.kind, self.subparser_name) {
1670                (token::Eof, Some(origin)) => format!("end of {origin}"),
1671                _ => this_token_str,
1672            },
1673        );
1674        let mut err = self.dcx().struct_span_err(sp, msg);
1675        let label_exp = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`", token_str))
    })format!("expected `{token_str}`");
1676        let sm = self.psess.source_map();
1677        if !sm.is_multiline(prev_sp.until(sp)) {
1678            // When the spans are in the same line, it means that the only content
1679            // between them is whitespace, point only at the found token.
1680            err.span_label(sp, label_exp);
1681        } else {
1682            err.span_label(prev_sp, label_exp);
1683            err.span_label(sp, "unexpected token");
1684        }
1685        err
1686    }
1687
1688    pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1689        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) || self.recover_colon_as_semi() {
1690            return Ok(());
1691        }
1692        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)).map(drop) // Error unconditionally
1693    }
1694
1695    pub(super) fn recover_colon_as_semi(&mut self) -> bool {
1696        let line_idx = |span: Span| {
1697            self.psess
1698                .source_map()
1699                .span_to_lines(span)
1700                .ok()
1701                .and_then(|lines| Some(lines.lines.get(0)?.line_index))
1702        };
1703
1704        if self.may_recover()
1705            && self.token == token::Colon
1706            && self.look_ahead(1, |next| line_idx(self.token.span) < line_idx(next.span))
1707        {
1708            self.dcx().emit_err(ColonAsSemi { span: self.token.span });
1709            self.bump();
1710            return true;
1711        }
1712
1713        false
1714    }
1715
1716    /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1717    /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1718    pub(super) fn recover_incorrect_await_syntax(
1719        &mut self,
1720        await_sp: Span,
1721    ) -> PResult<'a, Box<Expr>> {
1722        let (hi, expr_span, is_question) = if self.token == token::Bang {
1723            // Handle `await!(<expr>)`.
1724            self.recover_await_macro()?
1725        } else {
1726            self.recover_await_prefix(await_sp)?
1727        };
1728        let (sp, guar) = self.error_on_incorrect_await(await_sp, hi, expr_span, is_question);
1729        let expr = self.mk_expr_err(await_sp.to(sp), guar);
1730        self.maybe_recover_from_bad_qpath(expr)
1731    }
1732
1733    fn recover_await_macro(&mut self) -> PResult<'a, (Span, Span, bool)> {
1734        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?;
1735        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
1736        let open = self.prev_token.span;
1737        let expr = self.parse_expr()?;
1738        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1739        let close = self.prev_token.span;
1740        // Keep parentheses when needed for `.await`, e.g. `(&mut future).await`.
1741        // Use the delimiters to preserve any comments around the operand.
1742        let expr_span = if expr.precedence() < ExprPrecedence::Unambiguous {
1743            open.to(close)
1744        } else {
1745            open.shrink_to_hi().to(close.shrink_to_lo())
1746        };
1747        Ok((close, expr_span, false))
1748    }
1749
1750    fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, Span, bool)> {
1751        let is_question = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Question,
    token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question)); // Handle `await? <expr>`.
1752        let expr = if self.token == token::OpenBrace {
1753            // Handle `await { <expr> }`.
1754            // This needs to be handled separately from the next arm to avoid
1755            // interpreting `await { <expr> }?` as `<expr>?.await`.
1756            self.parse_expr_block(None, self.token.span, BlockCheckMode::Default)
1757        } else {
1758            self.parse_expr()
1759        }
1760        .map_err(|mut err| {
1761            err.span_label(await_sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("while parsing this incorrect await expression"))
    })format!("while parsing this incorrect await expression"));
1762            err
1763        })?;
1764        Ok((expr.span, expr.span, is_question))
1765    }
1766
1767    fn error_on_incorrect_await(
1768        &self,
1769        lo: Span,
1770        hi: Span,
1771        expr_span: Span,
1772        is_question: bool,
1773    ) -> (Span, ErrorGuaranteed) {
1774        let span = lo.to(hi);
1775        let guar = self.dcx().emit_err(IncorrectAwait {
1776            span,
1777            suggestion: AwaitSuggestion {
1778                removal: lo.until(expr_span),
1779                dot_await: expr_span.shrink_to_hi().to(hi.shrink_to_hi()),
1780                question_mark: if is_question { "?" } else { "" },
1781            },
1782        });
1783        (span, guar)
1784    }
1785
1786    /// If encountering `future.await()`, consumes and emits an error.
1787    pub(super) fn recover_from_await_method_call(&mut self) {
1788        if self.token == token::OpenParen && self.look_ahead(1, |t| t == &token::CloseParen) {
1789            // future.await()
1790            let lo = self.token.span;
1791            self.bump(); // (
1792            let span = lo.to(self.token.span);
1793            self.bump(); // )
1794
1795            self.dcx().emit_err(IncorrectUseOfAwait { span });
1796        }
1797    }
1798    ///
1799    /// If encountering `x.use()`, consumes and emits an error.
1800    pub(super) fn recover_from_use(&mut self) {
1801        if self.token == token::OpenParen && self.look_ahead(1, |t| t == &token::CloseParen) {
1802            // var.use()
1803            let lo = self.token.span;
1804            self.bump(); // (
1805            let span = lo.to(self.token.span);
1806            self.bump(); // )
1807
1808            self.dcx().emit_err(IncorrectUseOfUse { span });
1809        }
1810    }
1811
1812    pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, Box<Expr>> {
1813        let is_try = self.token.is_keyword(kw::Try);
1814        let is_questionmark = self.look_ahead(1, |t| t == &token::Bang); //check for !
1815        let is_open = self.look_ahead(2, |t| t == &token::OpenParen); //check for (
1816
1817        if is_try && is_questionmark && is_open {
1818            let lo = self.token.span;
1819            self.bump(); //remove try
1820            self.bump(); //remove !
1821            let try_span = lo.to(self.token.span); //we take the try!( span
1822            self.bump(); //remove (
1823            let is_empty = self.token == token::CloseParen; //check if the block is empty
1824            self.consume_block(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen), crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen), ConsumeClosingDelim::No); //eat the block
1825            let hi = self.token.span;
1826            self.bump(); //remove )
1827            let mut err = self.dcx().struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1828            err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1829            let prefix = if is_empty { "" } else { "alternatively, " };
1830            if !is_empty {
1831                err.multipart_suggestion(
1832                    "you can use the `?` operator instead",
1833                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(try_span, "".to_owned()), (hi, "?".to_owned())]))vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1834                    Applicability::MachineApplicable,
1835                );
1836            }
1837            err.span_suggestion_verbose(
1838                lo.shrink_to_lo(),
1839                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}you can still access the deprecated `try!()` macro using the \"raw identifier\" syntax",
                prefix))
    })format!(
1840                    "{prefix}you can still access the deprecated `try!()` macro using the \
1841                     \"raw identifier\" syntax"
1842                ),
1843                "r#",
1844                Applicability::MachineApplicable,
1845            );
1846            let guar = err.emit_err();
1847            Ok(self.mk_expr_err(lo.to(hi), guar))
1848        } else {
1849            Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1850        }
1851    }
1852
1853    /// When trying to close a generics list and encountering code like
1854    /// ```text
1855    /// impl<S: Into<std::borrow::Cow<'static, str>> From<S> for Canonical {}
1856    ///                                          // ^ missing > here
1857    /// ```
1858    /// we provide a structured suggestion on the error from `expect_gt`.
1859    pub(super) fn expect_gt_or_maybe_suggest_closing_generics(
1860        &mut self,
1861        params: &[ast::GenericParam],
1862    ) -> PResult<'a, ()> {
1863        let Err(mut err) = self.expect_gt() else {
1864            return Ok(());
1865        };
1866        // Attempt to find places where a missing `>` might belong.
1867        if let [.., ast::GenericParam { bounds, .. }] = params
1868            && let Some(poly) = bounds
1869                .iter()
1870                .filter_map(|bound| match bound {
1871                    ast::GenericBound::Trait(poly) => Some(poly),
1872                    _ => None,
1873                })
1874                .next_back()
1875        {
1876            err.span_suggestion_verbose(
1877                poly.span.shrink_to_hi(),
1878                "you might have meant to end the type parameters here",
1879                ">",
1880                Applicability::MaybeIncorrect,
1881            );
1882        }
1883        Err(err)
1884    }
1885
1886    pub(super) fn recover_seq_parse_error(
1887        &mut self,
1888        open: ExpTokenPair,
1889        close: ExpTokenPair,
1890        lo: Span,
1891        err: Diag<'a>,
1892    ) -> Box<Expr> {
1893        let guar = err.emit_err();
1894        // Recover from parse error, callers expect the closing delim to be consumed.
1895        self.consume_block(open, close, ConsumeClosingDelim::Yes);
1896        self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err(guar))
1897    }
1898
1899    /// Eats tokens until we can be relatively sure we reached the end of the
1900    /// statement. This is something of a best-effort heuristic.
1901    ///
1902    /// We terminate when we find an unmatched `}` (without consuming it).
1903    pub(super) fn recover_stmt(&mut self) {
1904        self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1905    }
1906
1907    /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1908    /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1909    /// approximate -- it can mean we break too early due to macros, but that
1910    /// should only lead to sub-optimal recovery, not inaccurate parsing).
1911    ///
1912    /// If `break_on_block` is `Break`, then we will stop consuming tokens
1913    /// after finding (and consuming) a brace-delimited block.
1914    pub(super) fn recover_stmt_(
1915        &mut self,
1916        break_on_semi: SemiColonMode,
1917        break_on_block: BlockMode,
1918    ) {
1919        let mut brace_depth = 0;
1920        let mut bracket_depth = 0;
1921        let mut in_block = false;
1922        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:1922",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1922u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ enter loop (semi={0:?}, block={1:?})",
                                                    break_on_semi, break_on_block) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1923        loop {
1924            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:1924",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1924u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ loop {0:?}",
                                                    self.token) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("recover_stmt_ loop {:?}", self.token);
1925            match self.token.kind {
1926                token::OpenBrace => {
1927                    brace_depth += 1;
1928                    self.bump();
1929                    if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1930                    {
1931                        in_block = true;
1932                    }
1933                }
1934                token::OpenBracket => {
1935                    bracket_depth += 1;
1936                    self.bump();
1937                }
1938                token::CloseBrace => {
1939                    if brace_depth == 0 {
1940                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:1940",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1940u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ return - close delim {0:?}",
                                                    self.token) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("recover_stmt_ return - close delim {:?}", self.token);
1941                        break;
1942                    }
1943                    brace_depth -= 1;
1944                    self.bump();
1945                    if in_block && bracket_depth == 0 && brace_depth == 0 {
1946                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:1946",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1946u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ return - block end {0:?}",
                                                    self.token) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("recover_stmt_ return - block end {:?}", self.token);
1947                        break;
1948                    }
1949                }
1950                token::CloseBracket => {
1951                    bracket_depth -= 1;
1952                    if bracket_depth < 0 {
1953                        bracket_depth = 0;
1954                    }
1955                    self.bump();
1956                }
1957                token::Eof => {
1958                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:1958",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1958u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ return - Eof")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("recover_stmt_ return - Eof");
1959                    break;
1960                }
1961                token::Semi => {
1962                    self.bump();
1963                    if break_on_semi == SemiColonMode::Break
1964                        && brace_depth == 0
1965                        && bracket_depth == 0
1966                    {
1967                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs:1967",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_parse/src/parser/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1967u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ return - Semi")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("recover_stmt_ return - Semi");
1968                        break;
1969                    }
1970                }
1971                token::Comma
1972                    if break_on_semi == SemiColonMode::Comma
1973                        && brace_depth == 0
1974                        && bracket_depth == 0 =>
1975                {
1976                    break;
1977                }
1978                _ => self.bump(),
1979            }
1980        }
1981    }
1982
1983    pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1984        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::In,
    token_type: crate::parser::token_type::TokenType::KwIn,
}exp!(In)) {
1985            // a common typo: `for _ in in bar {}`
1986            self.dcx().emit_err(InInTypo {
1987                span: self.prev_token.span,
1988                sugg_span: in_span.until(self.prev_token.span),
1989            });
1990        }
1991    }
1992
1993    pub(super) fn parameter_without_type(
1994        &mut self,
1995        err: &mut Diag<'_>,
1996        pat: Box<ast::Pat>,
1997        require_name: bool,
1998        first_param: bool,
1999        fn_parse_mode: &crate::parser::FnParseMode,
2000    ) -> Option<Ident> {
2001        // If we find a pattern followed by an identifier, it could be an (incorrect)
2002        // C-style parameter declaration.
2003        if self.check_ident()
2004            && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseParen)
2005        {
2006            // `fn foo(String s) {}`
2007            let ident = self.parse_ident_common(true).unwrap();
2008            let span = pat.span.with_hi(ident.span.hi());
2009
2010            err.span_suggestion_verbose(
2011                span,
2012                "declare the type after the parameter binding",
2013                "<identifier>: <type>",
2014                Applicability::HasPlaceholders,
2015            );
2016            return Some(ident);
2017        } else if require_name
2018            && (self.token == token::Comma
2019                || self.token == token::Lt
2020                || self.token == token::CloseParen)
2021        {
2022            let maybe_emit_anon_params_note = |this: &mut Self, err: &mut Diag<'_>| {
2023                let ed = this.token.span.with_neighbor(this.prev_token.span).edition();
2024                if #[allow(non_exhaustive_omitted_patterns)] match fn_parse_mode.context {
    crate::parser::FnContext::Trait => true,
    _ => false,
}matches!(fn_parse_mode.context, crate::parser::FnContext::Trait)
2025                    && (fn_parse_mode.req_name)(ed, IsDotDotDot::No)
2026                {
2027                    err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
2028                }
2029            };
2030
2031            let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
2032                match pat.kind {
2033                    PatKind::Ident(_, ident, _) => (
2034                        ident,
2035                        "self: ",
2036                        ": TypeName".to_string(),
2037                        "_: ",
2038                        pat.span.shrink_to_lo(),
2039                        pat.span.shrink_to_hi(),
2040                        pat.span.shrink_to_lo(),
2041                    ),
2042                    PatKind::Ref(ref inner_pat, _, _)
2043                    // Fix suggestions for multi-reference `self` parameters (e.g. `&&&self`)
2044                    // cc: https://github.com/rust-lang/rust/pull/146305
2045                        if let PatKind::Ref(_, _, _) = &inner_pat.kind
2046                            && let PatKind::Path(_, path) = &pat.peel_refs().kind
2047                            && let [a, ..] = path.segments.as_slice()
2048                            && a.ident.name == kw::SelfLower =>
2049                    {
2050                        let mut inner = inner_pat;
2051                        let mut span_vec = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [pat.span]))vec![pat.span];
2052
2053                        while let PatKind::Ref(ref inner_type, _, _) = inner.kind {
2054                            inner = inner_type;
2055                            span_vec.push(inner.span.shrink_to_lo());
2056                        }
2057
2058                        let span = match span_vec.len() {
2059                            // Should be unreachable: match guard ensures at least 2 references
2060                            0 | 1 => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2061                            2 => span_vec[0].until(inner_pat.span.shrink_to_lo()),
2062                            _ => span_vec[0].until(span_vec[span_vec.len() - 2].shrink_to_lo()),
2063                        };
2064
2065                        err.span_suggestion_verbose(
2066                            span,
2067                            "`self` should be `self`, `&self` or `&mut self`, consider removing extra references",
2068                            "".to_string(),
2069                            Applicability::MachineApplicable,
2070                        );
2071
2072                        return None;
2073                    }
2074                    // Also catches `fn foo(&a)`.
2075                    PatKind::Ref(ref inner_pat, pinned, mutab)
2076                        if let PatKind::Ident(_, ident, _) = inner_pat.clone().kind =>
2077                    {
2078                        let mutab = pinned.prefix_str(mutab);
2079                        (
2080                            ident,
2081                            "self: ",
2082                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: &{1}TypeName", ident, mutab))
    })format!("{ident}: &{mutab}TypeName"),
2083                            "_: ",
2084                            pat.span.shrink_to_lo(),
2085                            pat.span,
2086                            pat.span.shrink_to_lo(),
2087                        )
2088                    }
2089                    _ => {
2090                        // Otherwise, try to get a type and emit a suggestion.
2091                        if let Some(_) = pat.to_ty() {
2092                            err.span_suggestion_verbose(
2093                                pat.span.shrink_to_lo(),
2094                                "explicitly ignore the parameter name",
2095                                "_: ".to_string(),
2096                                Applicability::MachineApplicable,
2097                            );
2098                            maybe_emit_anon_params_note(self, err);
2099                        }
2100
2101                        return None;
2102                    }
2103                };
2104
2105            // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
2106            if first_param
2107                // Only when the fn is a method, we emit this suggestion.
2108                && #[allow(non_exhaustive_omitted_patterns)] match fn_parse_mode.context {
    FnContext::Trait | FnContext::Impl => true,
    _ => false,
}matches!(
2109                    fn_parse_mode.context,
2110                    FnContext::Trait | FnContext::Impl
2111                )
2112            {
2113                err.span_suggestion_verbose(
2114                    self_span,
2115                    "if this is a `self` type, give it a parameter name",
2116                    self_sugg,
2117                    Applicability::MaybeIncorrect,
2118                );
2119            }
2120            // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
2121            // `fn foo(HashMap: TypeName<u32>)`.
2122            if self.token != token::Lt {
2123                err.span_suggestion_verbose(
2124                    param_span,
2125                    "if this is a parameter name, give it a type",
2126                    param_sugg,
2127                    Applicability::HasPlaceholders,
2128                );
2129            }
2130            err.span_suggestion_verbose(
2131                type_span,
2132                "if this is a type, explicitly ignore the parameter name",
2133                type_sugg,
2134                Applicability::MachineApplicable,
2135            );
2136            maybe_emit_anon_params_note(self, err);
2137
2138            // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
2139            return if self.token == token::Lt { None } else { Some(ident) };
2140        }
2141        None
2142    }
2143
2144    #[cold]
2145    pub(super) fn recover_arg_parse(
2146        &mut self,
2147        context: FnContext,
2148    ) -> PResult<'a, (Box<ast::Pat>, Box<ast::Ty>)> {
2149        let pat = self.parse_pat_no_top_alt(Some(Expected::ArgumentName), None)?;
2150        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon))?;
2151        let ty = self.parse_ty()?;
2152        match context {
2153            FnContext::Trait
2154            | FnContext::FunctionPtrType
2155            | FnContext::ParenthesizedArgumentList => {
2156                self.dcx().emit_err(PatternMethodParamWithoutBody {
2157                    span: pat.span,
2158                    target: if context == FnContext::Trait {
2159                        "methods without bodies"
2160                    } else if context == FnContext::FunctionPtrType {
2161                        "function pointer types"
2162                    } else {
2163                        "parenthesized argument list"
2164                    },
2165                });
2166            }
2167            FnContext::Free | FnContext::Impl => {
2168                self.dcx().span_delayed_bug(
2169                    pat.span,
2170                    if context == FnContext::Free {
2171                        "This method is not called in free functions, as patterns are always allowed there"
2172                    } else {
2173                        "This method is not called in impls, as patterns are always allowed there"
2174                    },
2175                );
2176            }
2177        }
2178
2179        // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2180        let pat = Box::new(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID });
2181        Ok((pat, ty))
2182    }
2183
2184    pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2185        let span = param.pat.span;
2186        let guar = self.dcx().emit_err(SelfParamNotFirst { span });
2187        param.ty.kind = TyKind::Err(guar);
2188        Ok(param)
2189    }
2190
2191    pub(super) fn consume_block(
2192        &mut self,
2193        open: ExpTokenPair,
2194        close: ExpTokenPair,
2195        consume_close: ConsumeClosingDelim,
2196    ) {
2197        let mut brace_depth = 0;
2198        loop {
2199            if self.eat(open) {
2200                brace_depth += 1;
2201            } else if self.check(close) {
2202                if brace_depth == 0 {
2203                    if let ConsumeClosingDelim::Yes = consume_close {
2204                        // Some of the callers of this method expect to be able to parse the
2205                        // closing delimiter themselves, so we leave it alone. Otherwise we advance
2206                        // the parser.
2207                        self.bump();
2208                    }
2209                    return;
2210                } else {
2211                    self.bump();
2212                    brace_depth -= 1;
2213                    continue;
2214                }
2215            } else if self.token == token::Eof {
2216                return;
2217            } else {
2218                self.bump();
2219            }
2220        }
2221    }
2222
2223    pub(super) fn expected_expression_found(&self) -> Diag<'a> {
2224        let (span, msg) = match (&self.token.kind, self.subparser_name) {
2225            (&token::Eof, Some(origin)) => {
2226                let sp = self.prev_token.span.shrink_to_hi();
2227                (sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected expression, found end of {0}",
                origin))
    })format!("expected expression, found end of {origin}"))
2228            }
2229            _ => (
2230                self.token.span,
2231                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected expression, found {0}",
                super::token_descr(&self.token)))
    })format!("expected expression, found {}", super::token_descr(&self.token)),
2232            ),
2233        };
2234        let mut err = self.dcx().struct_span_err(span, msg);
2235        let sp = self.psess.source_map().start_point(self.token.span);
2236        if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
2237            err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
2238        }
2239        err.span_label(span, "expected expression");
2240        err
2241    }
2242
2243    fn consume_tts(
2244        &mut self,
2245        mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
2246        // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
2247        modifier: &[(token::TokenKind, i64)],
2248    ) {
2249        while acc > 0 {
2250            if let Some((_, val)) = modifier.iter().find(|(t, _)| self.token == *t) {
2251                acc += *val;
2252            }
2253            if self.token == token::Eof {
2254                break;
2255            }
2256            self.bump();
2257        }
2258    }
2259
2260    /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
2261    ///
2262    /// This is necessary because at this point we don't know whether we parsed a function with
2263    /// anonymous parameters or a function with names but no types. In order to minimize
2264    /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
2265    /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
2266    /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
2267    /// we deduplicate them to not complain about duplicated parameter names.
2268    pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut ThinVec<Param>) {
2269        let mut seen_inputs = FxHashSet::default();
2270        for input in fn_inputs.iter_mut() {
2271            let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err(_)) =
2272                (&input.pat.kind, &input.ty.kind)
2273            {
2274                Some(*ident)
2275            } else {
2276                None
2277            };
2278            if let Some(ident) = opt_ident {
2279                if seen_inputs.contains(&ident) {
2280                    input.pat.kind = PatKind::Wild;
2281                }
2282                seen_inputs.insert(ident);
2283            }
2284        }
2285    }
2286
2287    /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
2288    /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
2289    /// like the user has forgotten them.
2290    pub(super) fn handle_ambiguous_unbraced_const_arg(
2291        &mut self,
2292        args: &mut ThinVec<AngleBracketedArg>,
2293    ) -> PResult<'a, bool> {
2294        // If we haven't encountered a closing `>`, then the argument is malformed.
2295        // It's likely that the user has written a const expression without enclosing it
2296        // in braces, so we try to recover here.
2297        let arg = args.pop().unwrap();
2298        // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
2299        // adverse side-effects to subsequent errors and seems to advance the parser.
2300        // We are causing this error here exclusively in case that a `const` expression
2301        // could be recovered from the current parser state, even if followed by more
2302        // arguments after a comma.
2303        let mut err = self.dcx().struct_span_err(
2304            self.token.span,
2305            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected one of `,` or `>`, found {0}",
                super::token_descr(&self.token)))
    })format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2306        );
2307        err.span_label(self.token.span, "expected one of `,` or `>`");
2308        match self.recover_const_arg(arg.span(), err) {
2309            Ok(arg) => {
2310                args.push(AngleBracketedArg::Arg(arg));
2311                if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
2312                    return Ok(true); // Continue
2313                }
2314            }
2315            Err(err) => {
2316                args.push(arg);
2317                // We will emit a more generic error later.
2318                err.delay_as_bug();
2319            }
2320        }
2321        Ok(false) // Don't continue.
2322    }
2323
2324    fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2325        let snapshot = self.create_snapshot_for_diagnostic();
2326        let param = match self.parse_const_param(AttrVec::new()) {
2327            Ok(param) => param,
2328            Err(err) => {
2329                err.cancel();
2330                self.restore_snapshot(snapshot);
2331                return None;
2332            }
2333        };
2334
2335        let ident = param.ident.to_string();
2336        let sugg = match (ty_generics, self.psess.source_map().span_to_snippet(param.span())) {
2337            (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2338                Some(match &params[..] {
2339                    [] => UnexpectedConstParamDeclarationSugg::AddParam {
2340                        impl_generics: *impl_generics,
2341                        incorrect_decl: param.span(),
2342                        snippet,
2343                        ident,
2344                    },
2345                    [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2346                        impl_generics_end: generic.span().shrink_to_hi(),
2347                        incorrect_decl: param.span(),
2348                        snippet,
2349                        ident,
2350                    },
2351                })
2352            }
2353            _ => None,
2354        };
2355        let guar =
2356            self.dcx().emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2357
2358        let value = self.mk_expr_err(param.span(), guar);
2359        Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2360    }
2361
2362    pub(super) fn recover_const_param_declaration(
2363        &mut self,
2364        ty_generics: Option<&Generics>,
2365    ) -> PResult<'a, Option<GenericArg>> {
2366        // We have to check for a few different cases.
2367        if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2368            return Ok(Some(arg));
2369        }
2370
2371        // We haven't consumed `const` yet.
2372        let start = self.token.span;
2373        self.bump(); // `const`
2374
2375        // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2376        let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
2377        if self.check_const_arg() {
2378            err.to_remove = Some(start.until(self.token.span));
2379            self.dcx().emit_err(err);
2380            Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2381        } else {
2382            let after_kw_const = self.token.span;
2383            self.recover_const_arg(after_kw_const, self.dcx().create_err(err)).map(Some)
2384        }
2385    }
2386
2387    /// Try to recover from possible generic const argument without `{` and `}`.
2388    ///
2389    /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2390    /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2391    /// if we think that the resulting expression would be well formed.
2392    pub(super) fn recover_const_arg(
2393        &mut self,
2394        start: Span,
2395        mut err: Diag<'a>,
2396    ) -> PResult<'a, GenericArg> {
2397        let is_op_or_dot = AssocOp::from_token(&self.token)
2398            .and_then(|op| {
2399                if let AssocOp::Binary(
2400                    BinOpKind::Gt
2401                    | BinOpKind::Lt
2402                    | BinOpKind::Shr
2403                    | BinOpKind::Ge
2404                )
2405                // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2406                // assign a value to a defaulted generic parameter.
2407                | AssocOp::Assign
2408                | AssocOp::AssignOp(_) = op
2409                {
2410                    None
2411                } else {
2412                    Some(op)
2413                }
2414            })
2415            .is_some()
2416            || self.token == TokenKind::Dot;
2417        // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2418        // type params has been parsed.
2419        let was_op = #[allow(non_exhaustive_omitted_patterns)] match self.prev_token.kind {
    token::Plus | token::Shr | token::Gt => true,
    _ => false,
}matches!(self.prev_token.kind, token::Plus | token::Shr | token::Gt);
2420        if !is_op_or_dot && !was_op {
2421            // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2422            return Err(err);
2423        }
2424        let snapshot = self.create_snapshot_for_diagnostic();
2425        if is_op_or_dot {
2426            self.bump();
2427        }
2428        match (|| self.parse_expr_res(Restrictions::CONST_EXPR))() {
2429            Ok(expr) => {
2430                // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2431                if snapshot.token == token::EqEq {
2432                    err.span_suggestion_verbose(
2433                        snapshot.token.span,
2434                        "if you meant to use an associated type binding, replace `==` with `=`",
2435                        "=",
2436                        Applicability::MaybeIncorrect,
2437                    );
2438                    let guar = err.emit_err();
2439                    let value = self.mk_expr_err(start.to(expr.span), guar);
2440                    return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2441                } else if snapshot.token == token::Colon
2442                    && expr.span.lo() == snapshot.token.span.hi()
2443                    && #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::Path(..) => true,
    _ => false,
}matches!(expr.kind, ExprKind::Path(..))
2444                {
2445                    // Find a mistake like "foo::var:A".
2446                    err.span_suggestion_verbose(
2447                        snapshot.token.span,
2448                        "write a path separator here",
2449                        "::",
2450                        Applicability::MaybeIncorrect,
2451                    );
2452                    let guar = err.emit_err();
2453                    return Ok(GenericArg::Type(
2454                        self.mk_ty(start.to(expr.span), TyKind::Err(guar)),
2455                    ));
2456                } else if self.token == token::Comma || self.token.kind.should_end_const_arg() {
2457                    // Avoid the following output by checking that we consumed a full const arg:
2458                    // help: expressions must be enclosed in braces to be used as const generic
2459                    //       arguments
2460                    //    |
2461                    // LL |     let sr: Vec<{ (u32, _, _) = vec![] };
2462                    //    |                 ^                      ^
2463                    return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2464                }
2465            }
2466            Err(err) => {
2467                err.cancel();
2468            }
2469        }
2470        self.restore_snapshot(snapshot);
2471        Err(err)
2472    }
2473
2474    /// Try to recover from an unbraced const argument whose first token [could begin a type][ty].
2475    ///
2476    /// [ty]: token::Token::can_begin_type
2477    pub(crate) fn recover_unbraced_const_arg_that_can_begin_ty(
2478        &mut self,
2479        mut snapshot: SnapshotParser<'a>,
2480    ) -> Option<Box<ast::Expr>> {
2481        match (|| snapshot.parse_expr_res(Restrictions::CONST_EXPR))() {
2482            // Since we don't know the exact reason why we failed to parse the type or the
2483            // expression, employ a simple heuristic to weed out some pathological cases.
2484            Ok(expr) if let token::Comma | token::Gt = snapshot.token.kind => {
2485                self.restore_snapshot(snapshot);
2486                Some(expr)
2487            }
2488            Ok(_) => None,
2489            Err(err) => {
2490                err.cancel();
2491                None
2492            }
2493        }
2494    }
2495
2496    /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2497    pub(super) fn dummy_const_arg_needs_braces(&self, mut err: Diag<'a>, span: Span) -> GenericArg {
2498        err.multipart_suggestion(
2499            "expressions must be enclosed in braces to be used as const generic \
2500             arguments",
2501            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "{ ".to_string()),
                (span.shrink_to_hi(), " }".to_string())]))vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2502            Applicability::MaybeIncorrect,
2503        );
2504        let guar = err.emit_err();
2505        let value = self.mk_expr_err(span, guar);
2506        GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2507    }
2508
2509    /// Some special error handling for the "top-level" patterns in a match arm,
2510    /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2511    #[cold]
2512    pub(crate) fn recover_colon_colon_in_pat_typo(
2513        &mut self,
2514        mut first_pat: Pat,
2515        expected: Option<Expected>,
2516    ) -> Pat {
2517        if token::Colon != self.token.kind {
2518            return first_pat;
2519        }
2520
2521        // The pattern looks like it might be a path with a `::` -> `:` typo:
2522        // `match foo { bar:baz => {} }`
2523        let colon_span = self.token.span;
2524        // We only emit "unexpected `:`" error here if we can successfully parse the
2525        // whole pattern correctly in that case.
2526        let mut snapshot_pat = self.create_snapshot_for_diagnostic();
2527        let mut snapshot_type = self.create_snapshot_for_diagnostic();
2528
2529        // Create error for "unexpected `:`".
2530        match self.expected_one_of_not_found(&[], &[]) {
2531            Err(mut err) => {
2532                // Skip the `:`.
2533                snapshot_pat.bump();
2534                snapshot_type.bump();
2535                match snapshot_pat.parse_pat_no_top_alt(expected, None) {
2536                    Err(inner_err) => {
2537                        inner_err.cancel();
2538                    }
2539                    Ok(mut pat) => {
2540                        // We've parsed the rest of the pattern.
2541                        let new_span = first_pat.span.to(pat.span);
2542                        let mut show_sugg = false;
2543                        // Try to construct a recovered pattern.
2544                        match &mut pat.kind {
2545                            PatKind::Struct(qself @ None, path, ..)
2546                            | PatKind::TupleStruct(qself @ None, path, _)
2547                            | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2548                                PatKind::Ident(_, ident, _) => {
2549                                    path.segments.insert(0, PathSegment::from_ident(*ident));
2550                                    path.span = new_span;
2551                                    show_sugg = true;
2552                                    first_pat = pat;
2553                                }
2554                                PatKind::Path(old_qself, old_path) => {
2555                                    path.segments = old_path
2556                                        .segments
2557                                        .iter()
2558                                        .cloned()
2559                                        .chain(take(&mut path.segments))
2560                                        .collect();
2561                                    path.span = new_span;
2562                                    *qself = old_qself.clone();
2563                                    first_pat = pat;
2564                                    show_sugg = true;
2565                                }
2566                                _ => {}
2567                            },
2568                            PatKind::Ident(BindingMode::NONE, ident, None) => {
2569                                match &first_pat.kind {
2570                                    PatKind::Ident(_, old_ident, _) => {
2571                                        let path = PatKind::Path(
2572                                            None,
2573                                            Path {
2574                                                span: new_span,
2575                                                segments: {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(PathSegment::from_ident(*old_ident));
    vec.push(PathSegment::from_ident(*ident));
    vec
}thin_vec![
2576                                                    PathSegment::from_ident(*old_ident),
2577                                                    PathSegment::from_ident(*ident),
2578                                                ],
2579                                            },
2580                                        );
2581                                        first_pat = self.mk_pat(new_span, path);
2582                                        show_sugg = true;
2583                                    }
2584                                    PatKind::Path(old_qself, old_path) => {
2585                                        let mut segments = old_path.segments.clone();
2586                                        segments.push(PathSegment::from_ident(*ident));
2587                                        let path = PatKind::Path(
2588                                            old_qself.clone(),
2589                                            Path { span: new_span, segments },
2590                                        );
2591                                        first_pat = self.mk_pat(new_span, path);
2592                                        show_sugg = true;
2593                                    }
2594                                    _ => {}
2595                                }
2596                            }
2597                            _ => {}
2598                        }
2599                        if show_sugg {
2600                            err.span_suggestion_verbose(
2601                                colon_span.until(self.look_ahead(1, |t| t.span)),
2602                                "maybe write a path separator here",
2603                                "::",
2604                                Applicability::MaybeIncorrect,
2605                            );
2606                        } else {
2607                            first_pat = self.mk_pat(
2608                                new_span,
2609                                PatKind::Err(
2610                                    self.dcx()
2611                                        .span_delayed_bug(colon_span, "recovered bad path pattern"),
2612                                ),
2613                            );
2614                        }
2615                        self.restore_snapshot(snapshot_pat);
2616                    }
2617                }
2618                match snapshot_type.parse_ty() {
2619                    Err(inner_err) => {
2620                        inner_err.cancel();
2621                    }
2622                    Ok(ty) => {
2623                        err.span_label(ty.span, "specifying the type of a pattern isn't supported");
2624                        self.restore_snapshot(snapshot_type);
2625                        let new_span = first_pat.span.to(ty.span);
2626                        first_pat =
2627                            self.mk_pat(
2628                                new_span,
2629                                PatKind::Err(self.dcx().span_delayed_bug(
2630                                    colon_span,
2631                                    "recovered bad pattern with type",
2632                                )),
2633                            );
2634                    }
2635                }
2636                err.emit();
2637            }
2638            _ => {
2639                // Carry on as if we had not done anything. This should be unreachable.
2640            }
2641        };
2642        first_pat
2643    }
2644
2645    /// If `loop_header` is `Some` and an unexpected block label is encountered,
2646    /// it is suggested to be moved just before `loop_header`, else it is suggested to be removed.
2647    pub(crate) fn maybe_recover_unexpected_block_label(
2648        &mut self,
2649        loop_header: Option<Span>,
2650    ) -> bool {
2651        // Check for `'a : {`
2652        if !(self.check_lifetime()
2653            && self.look_ahead(1, |t| *t == token::Colon)
2654            && self.look_ahead(2, |t| *t == token::OpenBrace))
2655        {
2656            return false;
2657        }
2658        let label = self.eat_label().expect("just checked if a label exists");
2659        self.bump(); // eat `:`
2660        let span = label.ident.span.to(self.prev_token.span);
2661        let mut diag = self
2662            .dcx()
2663            .struct_span_err(span, "block label not supported here")
2664            .with_span_label(span, "not supported here");
2665        if let Some(loop_header) = loop_header {
2666            diag.multipart_suggestion(
2667                "if you meant to label the loop, move this label before the loop",
2668                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(label.ident.span.until(self.token.span), String::from("")),
                (loop_header.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}: ", label.ident))
                        }))]))vec![
2669                    (label.ident.span.until(self.token.span), String::from("")),
2670                    (loop_header.shrink_to_lo(), format!("{}: ", label.ident)),
2671                ],
2672                Applicability::MachineApplicable,
2673            );
2674        } else {
2675            diag.tool_only_span_suggestion(
2676                label.ident.span.until(self.token.span),
2677                "remove this block label",
2678                "",
2679                Applicability::MachineApplicable,
2680            );
2681        }
2682        diag.emit();
2683        true
2684    }
2685
2686    /// Some special error handling for the "top-level" patterns in a match arm,
2687    /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2688    pub(crate) fn maybe_recover_unexpected_comma(
2689        &mut self,
2690        lo: Span,
2691        rt: CommaRecoveryMode,
2692    ) -> PResult<'a, ()> {
2693        if self.token != token::Comma {
2694            return Ok(());
2695        }
2696        self.recover_unexpected_comma(lo, rt)
2697    }
2698
2699    #[cold]
2700    fn recover_unexpected_comma(&mut self, lo: Span, rt: CommaRecoveryMode) -> PResult<'a, ()> {
2701        // An unexpected comma after a top-level pattern is a clue that the
2702        // user (perhaps more accustomed to some other language) forgot the
2703        // parentheses in what should have been a tuple pattern; return a
2704        // suggestion-enhanced error here rather than choking on the comma later.
2705        let comma_span = self.token.span;
2706        self.bump();
2707        if let Err(err) = self.skip_pat_list() {
2708            // We didn't expect this to work anyway; we just wanted to advance to the
2709            // end of the comma-sequence so we know the span to suggest parenthesizing.
2710            err.cancel();
2711        }
2712        let seq_span = lo.to(self.prev_token.span);
2713        let mut err = self.dcx().struct_span_err(comma_span, "unexpected `,` in pattern");
2714        err.multipart_suggestion(
2715            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try adding parentheses to match on a tuple{0}",
                if let CommaRecoveryMode::LikelyTuple = rt {
                    ""
                } else { "..." }))
    })format!(
2716                "try adding parentheses to match on a tuple{}",
2717                if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2718            ),
2719            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(seq_span.shrink_to_lo(), "(".to_string()),
                (seq_span.shrink_to_hi(), ")".to_string())]))vec![
2720                (seq_span.shrink_to_lo(), "(".to_string()),
2721                (seq_span.shrink_to_hi(), ")".to_string()),
2722            ],
2723            Applicability::MachineApplicable,
2724        );
2725        if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2726            err.span_suggestion_verbose(
2727                comma_span,
2728                "...or a vertical bar to match on alternatives",
2729                " |",
2730                Applicability::MachineApplicable,
2731            );
2732        }
2733        Err(err)
2734    }
2735
2736    pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2737        let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2738        let qself_position = qself.as_ref().map(|qself| qself.position);
2739        for (i, segments) in path.segments.windows(2).enumerate() {
2740            if qself_position.is_some_and(|pos| i < pos) {
2741                continue;
2742            }
2743            if let [a, b] = segments {
2744                let (a_span, b_span) = (a.span(), b.span());
2745                let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2746                if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2747                    return Err(self.dcx().create_err(DoubleColonInBound {
2748                        span: path.span.shrink_to_hi(),
2749                        between: between_span,
2750                    }));
2751                }
2752            }
2753        }
2754        Ok(())
2755    }
2756
2757    /// Check for exclusive ranges written as `..<`
2758    pub(crate) fn maybe_err_dotdotlt_syntax(&self, maybe_lt: Token, mut err: Diag<'a>) -> Diag<'a> {
2759        if maybe_lt == token::Lt
2760            && (self.expected_token_types.contains(TokenType::Gt)
2761                || #[allow(non_exhaustive_omitted_patterns)] match self.token.kind {
    token::Literal(..) => true,
    _ => false,
}matches!(self.token.kind, token::Literal(..)))
2762        {
2763            err.span_suggestion_verbose(
2764                maybe_lt.span,
2765                "remove the `<` to write an exclusive range",
2766                "",
2767                Applicability::MachineApplicable,
2768            );
2769        }
2770        err
2771    }
2772
2773    /// This checks if this is a conflict marker, depending of the parameter passed.
2774    ///
2775    /// * `<<<<<<<`
2776    /// * `|||||||`
2777    /// * `=======`
2778    /// * `>>>>>>>`
2779    ///
2780    pub(super) fn is_vcs_conflict_marker(
2781        &mut self,
2782        long_kind: &TokenKind,
2783        short_kind: &TokenKind,
2784    ) -> bool {
2785        if long_kind == short_kind {
2786            // For conflict marker chars like `%` and `\`.
2787            (0..7).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2788        } else {
2789            // For conflict marker chars like `<` and `|`.
2790            (0..3).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2791                && self.look_ahead(3, |tok| tok == short_kind || tok == long_kind)
2792        }
2793    }
2794
2795    fn conflict_marker(
2796        &mut self,
2797        long_kind: &TokenKind,
2798        short_kind: &TokenKind,
2799        expected: Option<usize>,
2800    ) -> Option<(Span, usize)> {
2801        if self.is_vcs_conflict_marker(long_kind, short_kind) {
2802            let lo = self.token.span;
2803            if self.psess.source_map().span_to_margin(lo) != Some(0) {
2804                return None;
2805            }
2806            let mut len = 0;
2807            while self.token.kind == *long_kind || self.token.kind == *short_kind {
2808                if self.token.kind.break_two_token_op(1).is_some() {
2809                    len += 2;
2810                } else {
2811                    len += 1;
2812                }
2813                self.bump();
2814                if expected == Some(len) {
2815                    break;
2816                }
2817            }
2818            if expected.is_some() && expected != Some(len) {
2819                return None;
2820            }
2821            return Some((lo.to(self.prev_token.span), len));
2822        }
2823        None
2824    }
2825
2826    pub(super) fn recover_vcs_conflict_marker(&mut self) {
2827        // <<<<<<<
2828        let Some((start, len)) = self.conflict_marker(&TokenKind::Shl, &TokenKind::Lt, None) else {
2829            return;
2830        };
2831        let mut spans = Vec::with_capacity(2);
2832        spans.push(start);
2833        // |||||||
2834        let mut middlediff3 = None;
2835        // =======
2836        let mut middle = None;
2837        // >>>>>>>
2838        let mut end = None;
2839        loop {
2840            if self.token == TokenKind::Eof {
2841                break;
2842            }
2843            if let Some((span, _)) =
2844                self.conflict_marker(&TokenKind::OrOr, &TokenKind::Or, Some(len))
2845            {
2846                middlediff3 = Some(span);
2847            }
2848            if let Some((span, _)) =
2849                self.conflict_marker(&TokenKind::EqEq, &TokenKind::Eq, Some(len))
2850            {
2851                middle = Some(span);
2852            }
2853            if let Some((span, _)) =
2854                self.conflict_marker(&TokenKind::Shr, &TokenKind::Gt, Some(len))
2855            {
2856                spans.push(span);
2857                end = Some(span);
2858                break;
2859            }
2860            self.bump();
2861        }
2862
2863        let mut err = self.dcx().struct_span_fatal(spans, "encountered diff marker");
2864        let middle_marker = match middlediff3 {
2865            // We're using diff3
2866            Some(middlediff3) => {
2867                err.span_label(
2868                    middlediff3,
2869                    "between this marker and `=======` is the base code (what the two refs \
2870                     diverged from)",
2871                );
2872                "|||||||"
2873            }
2874            None => "=======",
2875        };
2876        err.span_label(
2877            start,
2878            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("between this marker and `{0}` is the code that you are merging into",
                middle_marker))
    })format!(
2879                "between this marker and `{middle_marker}` is the code that you are merging into",
2880            ),
2881        );
2882
2883        if let Some(middle) = middle {
2884            err.span_label(middle, "between this marker and `>>>>>>>` is the incoming code");
2885        }
2886        if let Some(end) = end {
2887            err.span_label(end, "this marker concludes the conflict region");
2888        }
2889        err.note(
2890            "conflict markers indicate that a merge was started but could not be completed due \
2891             to merge conflicts\n\
2892             to resolve a conflict, keep only the code you want and then delete the lines \
2893             containing conflict markers",
2894        );
2895        err.help(
2896            "if you are in a merge, the top section is the code you already had checked out and \
2897             the bottom section is the new code\n\
2898             if you are in a rebase, the top section is the code being rebased onto and the bottom \
2899             section is the code you had checked out which is being rebased",
2900        );
2901
2902        err.note(
2903            "for an explanation on these markers from the `git` documentation, visit \
2904             <https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_checking_out_conflicts>",
2905        );
2906
2907        err.emit();
2908    }
2909
2910    /// Parse and throw away a parenthesized comma separated
2911    /// sequence of patterns until `)` is reached.
2912    fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2913        while !self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)) {
2914            self.parse_pat_no_top_alt(None, None)?;
2915            if !self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
2916                return Ok(());
2917            }
2918        }
2919        Ok(())
2920    }
2921    pub(super) fn maybe_type_in_generic_parameter(&mut self, origin_error: Diag<'a>) -> Diag<'a> {
2922        if !self.may_recover() {
2923            return origin_error;
2924        }
2925        self.with_recovery(super::Recovery::Forbidden, |snapshot| {
2926            snapshot.bump();
2927            let lo = snapshot.token.span.shrink_to_lo();
2928
2929            let ty = match snapshot.parse_ty() {
2930                Ok(t) => t,
2931                Err(err) => {
2932                    err.cancel();
2933                    return origin_error;
2934                }
2935            };
2936            let TyKind::Path(_, path) = ty.kind else {
2937                return origin_error;
2938            };
2939            let Some(GenericArgs::AngleBracketed(AngleBracketedArgs { span: _, ref args })) =
2940                path.segments[0].args
2941            else {
2942                return origin_error;
2943            };
2944
2945            let path_span = path.span;
2946            let mut new_error = snapshot.dcx().create_err(FoundPathInGenerics {
2947                span: path_span,
2948                path: snapshot.span_to_snippet(path_span).unwrap(),
2949            });
2950            new_error.subdiagnostic(SuggestBindTypeParameter { span: lo });
2951            origin_error.cancel();
2952
2953            let params = args
2954                .iter()
2955                .map(|arg| snapshot.span_to_snippet(arg.span()).unwrap())
2956                .collect::<Vec<_>>()
2957                .join(", ");
2958            new_error.subdiagnostic(SuggestIntroduceTypeParameter {
2959                span: path_span,
2960                parameters: params,
2961            });
2962            new_error
2963        })
2964    }
2965}