Skip to main content

rustc_parse/parser/
diagnostics.rs

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