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