Skip to main content

rustc_parse/parser/
diagnostics.rs

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