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