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]
    #[rustc_trivial_field_reads]
    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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:350",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:876",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:1035",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:1058",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:1073",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:1084",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:1930",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:1932",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:1948",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:1954",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:1966",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_parse/src/parser/diagnostics.rs:1975",
                        "rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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 let Some((ident, kind)) = self.token.ident()
2012            && (ident.name == kw::SelfLower || !token::ident_of_kind_is_reserved(ident, kind))
2013            && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseParen)
2014        {
2015            // `fn foo(String s) {}`
2016            self.bump(); // ident
2017            let span = pat.span.with_hi(ident.span.hi());
2018
2019            err.span_suggestion_verbose(
2020                span,
2021                "declare the type after the parameter binding",
2022                "<identifier>: <type>",
2023                Applicability::HasPlaceholders,
2024            );
2025            return Some(ident);
2026        } else if require_name
2027            && (self.token == token::Comma
2028                || self.token == token::Lt
2029                || self.token == token::CloseParen)
2030        {
2031            let maybe_emit_anon_params_note = |this: &mut Self, err: &mut Diag<'_>| {
2032                let ed = this.token.span.with_neighbor(this.prev_token.span).edition();
2033                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)
2034                    && (fn_parse_mode.req_name)(ed, IsDotDotDot::No)
2035                {
2036                    err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
2037                }
2038            };
2039
2040            let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
2041                match pat.kind {
2042                    PatKind::Ident(_, ident, _) => (
2043                        ident,
2044                        "self: ",
2045                        ": TypeName".to_string(),
2046                        "_: ",
2047                        pat.span.shrink_to_lo(),
2048                        pat.span.shrink_to_hi(),
2049                        pat.span.shrink_to_lo(),
2050                    ),
2051                    PatKind::Ref(ref inner_pat, _, _)
2052                    // Fix suggestions for multi-reference `self` parameters (e.g. `&&&self`)
2053                    // cc: https://github.com/rust-lang/rust/pull/146305
2054                        if let PatKind::Ref(_, _, _) = &inner_pat.kind
2055                            && let PatKind::Path(_, path) = &pat.peel_refs().kind
2056                            && let [a, ..] = path.segments.as_slice()
2057                            && a.ident.name == kw::SelfLower =>
2058                    {
2059                        let mut inner = inner_pat;
2060                        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];
2061
2062                        while let PatKind::Ref(ref inner_type, _, _) = inner.kind {
2063                            inner = inner_type;
2064                            span_vec.push(inner.span.shrink_to_lo());
2065                        }
2066
2067                        let span = match span_vec.len() {
2068                            // Should be unreachable: match guard ensures at least 2 references
2069                            0 | 1 => ::core::panicking::unreachable_default_msg()unreachable!(),
2070                            2 => span_vec[0].until(inner_pat.span.shrink_to_lo()),
2071                            _ => span_vec[0].until(span_vec[span_vec.len() - 2].shrink_to_lo()),
2072                        };
2073
2074                        err.span_suggestion_verbose(
2075                            span,
2076                            "`self` should be `self`, `&self` or `&mut self`, consider removing extra references",
2077                            "".to_string(),
2078                            Applicability::MachineApplicable,
2079                        );
2080
2081                        return None;
2082                    }
2083                    // Also catches `fn foo(&a)`.
2084                    PatKind::Ref(ref inner_pat, pinned, mutab)
2085                        if let PatKind::Ident(_, ident, _) = inner_pat.clone().kind =>
2086                    {
2087                        let mutab = pinned.prefix_str(mutab);
2088                        (
2089                            ident,
2090                            "self: ",
2091                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: &{1}TypeName", ident, mutab))
    })format!("{ident}: &{mutab}TypeName"),
2092                            "_: ",
2093                            pat.span.shrink_to_lo(),
2094                            pat.span,
2095                            pat.span.shrink_to_lo(),
2096                        )
2097                    }
2098                    _ => {
2099                        // Otherwise, try to get a type and emit a suggestion.
2100                        if let Some(_) = pat.to_ty() {
2101                            err.span_suggestion_verbose(
2102                                pat.span.shrink_to_lo(),
2103                                "explicitly ignore the parameter name",
2104                                "_: ".to_string(),
2105                                Applicability::MachineApplicable,
2106                            );
2107                            maybe_emit_anon_params_note(self, err);
2108                        }
2109
2110                        return None;
2111                    }
2112                };
2113
2114            // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
2115            if first_param
2116                // Only when the fn is a method, we emit this suggestion.
2117                && #[allow(non_exhaustive_omitted_patterns)] match fn_parse_mode.context {
    FnContext::Trait | FnContext::Impl => true,
    _ => false,
}matches!(
2118                    fn_parse_mode.context,
2119                    FnContext::Trait | FnContext::Impl
2120                )
2121            {
2122                err.span_suggestion_verbose(
2123                    self_span,
2124                    "if this is a `self` type, give it a parameter name",
2125                    self_sugg,
2126                    Applicability::MaybeIncorrect,
2127                );
2128            }
2129            // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
2130            // `fn foo(HashMap: TypeName<u32>)`.
2131            if self.token != token::Lt {
2132                err.span_suggestion_verbose(
2133                    param_span,
2134                    "if this is a parameter name, give it a type",
2135                    param_sugg,
2136                    Applicability::HasPlaceholders,
2137                );
2138            }
2139            err.span_suggestion_verbose(
2140                type_span,
2141                "if this is a type, explicitly ignore the parameter name",
2142                type_sugg,
2143                Applicability::MachineApplicable,
2144            );
2145            maybe_emit_anon_params_note(self, err);
2146
2147            // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
2148            return if self.token == token::Lt { None } else { Some(ident) };
2149        }
2150        None
2151    }
2152
2153    #[cold]
2154    pub(super) fn recover_arg_parse(
2155        &mut self,
2156        context: FnContext,
2157    ) -> PResult<'a, (Box<ast::Pat>, Box<ast::Ty>)> {
2158        let pat = self.parse_pat_no_top_alt(Some(Expected::ArgumentName), None)?;
2159        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon))?;
2160        let ty = self.parse_ty()?;
2161        match context {
2162            FnContext::Trait
2163            | FnContext::FunctionPtrType
2164            | FnContext::ParenthesizedArgumentList => {
2165                self.dcx().emit_err(PatternMethodParamWithoutBody {
2166                    span: pat.span,
2167                    target: if context == FnContext::Trait {
2168                        "methods without bodies"
2169                    } else if context == FnContext::FunctionPtrType {
2170                        "function pointer types"
2171                    } else {
2172                        "parenthesized argument list"
2173                    },
2174                });
2175            }
2176            FnContext::Free | FnContext::Impl => {
2177                self.dcx().span_delayed_bug(
2178                    pat.span,
2179                    if context == FnContext::Free {
2180                        "This method is not called in free functions, as patterns are always allowed there"
2181                    } else {
2182                        "This method is not called in impls, as patterns are always allowed there"
2183                    },
2184                );
2185            }
2186        }
2187
2188        // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2189        let pat = Box::new(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID });
2190        Ok((pat, ty))
2191    }
2192
2193    pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2194        let span = param.pat.span;
2195        let guar = self.dcx().emit_err(SelfParamNotFirst { span });
2196        param.ty.kind = TyKind::Err(guar);
2197        Ok(param)
2198    }
2199
2200    pub(super) fn consume_block(
2201        &mut self,
2202        open: ExpTokenPair,
2203        close: ExpTokenPair,
2204        consume_close: ConsumeClosingDelim,
2205    ) {
2206        let mut brace_depth = 0;
2207        loop {
2208            if self.eat(open) {
2209                brace_depth += 1;
2210            } else if self.check(close) {
2211                if brace_depth == 0 {
2212                    if let ConsumeClosingDelim::Yes = consume_close {
2213                        // Some of the callers of this method expect to be able to parse the
2214                        // closing delimiter themselves, so we leave it alone. Otherwise we advance
2215                        // the parser.
2216                        self.bump();
2217                    }
2218                    return;
2219                } else {
2220                    self.bump();
2221                    brace_depth -= 1;
2222                    continue;
2223                }
2224            } else if self.token == token::Eof {
2225                return;
2226            } else {
2227                self.bump();
2228            }
2229        }
2230    }
2231
2232    pub(super) fn expected_expression_found(&self) -> Diag<'a> {
2233        let (span, msg) = match (&self.token.kind, self.subparser_name) {
2234            (&token::Eof, Some(origin)) => {
2235                let sp = self.prev_token.span.shrink_to_hi();
2236                (sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected expression, found end of {0}",
                origin))
    })format!("expected expression, found end of {origin}"))
2237            }
2238            _ => (
2239                self.token.span,
2240                ::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)),
2241            ),
2242        };
2243        let mut err = self.dcx().struct_span_err(span, msg);
2244        let sp = self.psess.source_map().start_point(self.token.span);
2245        if let Some(sp) = self.psess.complete_stmt_exprs_before_bin_op_lookalike.borrow().get(&sp) {
2246            err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
2247        }
2248        err.span_label(span, "expected expression");
2249        err
2250    }
2251
2252    fn consume_tts(
2253        &mut self,
2254        mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
2255        // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
2256        modifier: &[(token::TokenKind, i64)],
2257    ) {
2258        while acc > 0 {
2259            if let Some((_, val)) = modifier.iter().find(|(t, _)| self.token == *t) {
2260                acc += *val;
2261            }
2262            if self.token == token::Eof {
2263                break;
2264            }
2265            self.bump();
2266        }
2267    }
2268
2269    /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
2270    ///
2271    /// This is necessary because at this point we don't know whether we parsed a function with
2272    /// anonymous parameters or a function with names but no types. In order to minimize
2273    /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
2274    /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
2275    /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
2276    /// we deduplicate them to not complain about duplicated parameter names.
2277    pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut ThinVec<Param>) {
2278        let mut seen_inputs = FxHashSet::default();
2279        for input in fn_inputs.iter_mut() {
2280            let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err(_)) =
2281                (&input.pat.kind, &input.ty.kind)
2282            {
2283                Some(*ident)
2284            } else {
2285                None
2286            };
2287            if let Some(ident) = opt_ident {
2288                if seen_inputs.contains(&ident) {
2289                    input.pat.kind = PatKind::Wild;
2290                }
2291                seen_inputs.insert(ident);
2292            }
2293        }
2294    }
2295
2296    /// Handle encountering a lifetime in a generic argument list that is not
2297    /// followed by a `,` or `>`.
2298    /// We emit an error and check if the lifetime is followed by a type
2299    /// in, e.g. `Foo<'a T>`.
2300    /// In this case, it is likely the user meant either `Foo<&'a T>` or `Foo<'a, T>`.
2301    /// We give both suggestions, then emit an error. Note that we do not try to recover,
2302    /// since we cannot know which of the two suggestions is correct and emitting either
2303    /// of the two types could cause confusing errors further on.
2304    pub(super) fn handle_lifetime_arg_preceding_type(&mut self, span: Span) -> PResult<'a, ()> {
2305        let snapshot = self.create_snapshot_for_diagnostic();
2306        let (mutbl, ty) = self.parse_ref_ty_no_leading_ampersand();
2307        self.restore_snapshot(snapshot);
2308        if ty.is_none() {
2309            // The lifetime is not followed by a type, do nothing.
2310            return Ok(());
2311        }
2312        // If we find `'a mut T`, suggesting to add a comma is wrong.
2313        let suggest_comma = mutbl.is_not();
2314        // Add `>` to the list of expected tokens.
2315        self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt));
2316        let mut err = self.unexpected().unwrap_err();
2317        err.span_suggestion_verbose(
2318            span.shrink_to_lo(),
2319            "you might have meant to write a reference type here",
2320            "&",
2321            Applicability::MaybeIncorrect,
2322        );
2323        if suggest_comma {
2324            err.span_suggestion_verbose(
2325                span.shrink_to_hi(),
2326                "use a comma to separate type parameters",
2327                ",",
2328                Applicability::MaybeIncorrect,
2329            );
2330        }
2331        Err(err)
2332    }
2333
2334    /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
2335    /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
2336    /// like the user has forgotten them.
2337    pub(super) fn handle_ambiguous_unbraced_const_arg(
2338        &mut self,
2339        args: &mut ThinVec<AngleBracketedArg>,
2340    ) -> PResult<'a, bool> {
2341        // If we haven't encountered a closing `>`, then the argument is malformed.
2342        // It's likely that the user has written a const expression without enclosing it
2343        // in braces, so we try to recover here.
2344        let arg = args.pop().unwrap();
2345        // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
2346        // adverse side-effects to subsequent errors and seems to advance the parser.
2347        // We are causing this error here exclusively in case that a `const` expression
2348        // could be recovered from the current parser state, even if followed by more
2349        // arguments after a comma.
2350        let mut err = self.dcx().struct_span_err(
2351            self.token.span,
2352            ::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)),
2353        );
2354        err.span_label(self.token.span, "expected one of `,` or `>`");
2355        match self.recover_const_arg(arg.span(), err) {
2356            Ok(arg) => {
2357                args.push(AngleBracketedArg::Arg(arg));
2358                if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
2359                    return Ok(true); // Continue
2360                }
2361            }
2362            Err(err) => {
2363                args.push(arg);
2364                // We will emit a more generic error later.
2365                err.delay_as_bug();
2366            }
2367        }
2368        Ok(false) // Don't continue.
2369    }
2370
2371    fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2372        let snapshot = self.create_snapshot_for_diagnostic();
2373        let param = match self.parse_const_param(AttrVec::new()) {
2374            Ok(param) => param,
2375            Err(err) => {
2376                err.cancel();
2377                self.restore_snapshot(snapshot);
2378                return None;
2379            }
2380        };
2381
2382        let ident = param.ident.to_string();
2383        let sugg = match (ty_generics, self.psess.source_map().span_to_snippet(param.span())) {
2384            (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2385                Some(match &params[..] {
2386                    [] => UnexpectedConstParamDeclarationSugg::AddParam {
2387                        impl_generics: *impl_generics,
2388                        incorrect_decl: param.span(),
2389                        snippet,
2390                        ident,
2391                    },
2392                    [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2393                        impl_generics_end: generic.span().shrink_to_hi(),
2394                        incorrect_decl: param.span(),
2395                        snippet,
2396                        ident,
2397                    },
2398                })
2399            }
2400            _ => None,
2401        };
2402        let guar =
2403            self.dcx().emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2404
2405        let value = self.mk_expr_err(param.span(), guar);
2406        Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2407    }
2408
2409    pub(super) fn recover_const_param_declaration(
2410        &mut self,
2411        ty_generics: Option<&Generics>,
2412    ) -> PResult<'a, Option<GenericArg>> {
2413        // We have to check for a few different cases.
2414        if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2415            return Ok(Some(arg));
2416        }
2417
2418        // We haven't consumed `const` yet.
2419        let start = self.token.span;
2420        self.bump(); // `const`
2421
2422        // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2423        let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
2424        if self.check_const_arg() {
2425            err.to_remove = Some(start.until(self.token.span));
2426            self.dcx().emit_err(err);
2427            Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2428        } else {
2429            let after_kw_const = self.token.span;
2430            self.recover_const_arg(after_kw_const, self.dcx().create_err(err)).map(Some)
2431        }
2432    }
2433
2434    /// Try to recover from possible generic const argument without `{` and `}`.
2435    ///
2436    /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2437    /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2438    /// if we think that the resulting expression would be well formed.
2439    pub(super) fn recover_const_arg(
2440        &mut self,
2441        start: Span,
2442        mut err: Diag<'a>,
2443    ) -> PResult<'a, GenericArg> {
2444        let is_op_or_dot = AssocOp::from_token(&self.token)
2445            .and_then(|op| {
2446                if let AssocOp::Binary(
2447                    BinOpKind::Gt
2448                    | BinOpKind::Lt
2449                    | BinOpKind::Shr
2450                    | BinOpKind::Ge
2451                )
2452                // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2453                // assign a value to a defaulted generic parameter.
2454                | AssocOp::Assign
2455                | AssocOp::AssignOp(_) = op
2456                {
2457                    None
2458                } else {
2459                    Some(op)
2460                }
2461            })
2462            .is_some()
2463            || self.token == TokenKind::Dot;
2464        // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2465        // type params has been parsed.
2466        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);
2467        if !is_op_or_dot && !was_op {
2468            // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2469            return Err(err);
2470        }
2471        let snapshot = self.create_snapshot_for_diagnostic();
2472        if is_op_or_dot {
2473            self.bump();
2474        }
2475        match (|| self.parse_expr_res(Restrictions::CONST_EXPR))() {
2476            Ok(expr) => {
2477                // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2478                if snapshot.token == token::EqEq {
2479                    err.span_suggestion_verbose(
2480                        snapshot.token.span,
2481                        "if you meant to use an associated type binding, replace `==` with `=`",
2482                        "=",
2483                        Applicability::MaybeIncorrect,
2484                    );
2485                    let guar = err.emit_err();
2486                    let value = self.mk_expr_err(start.to(expr.span), guar);
2487                    return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2488                } else if snapshot.token == token::Colon
2489                    && expr.span.lo() == snapshot.token.span.hi()
2490                    && #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::Path(..) => true,
    _ => false,
}matches!(expr.kind, ExprKind::Path(..))
2491                {
2492                    // Find a mistake like "foo::var:A".
2493                    err.span_suggestion_verbose(
2494                        snapshot.token.span,
2495                        "write a path separator here",
2496                        "::",
2497                        Applicability::MaybeIncorrect,
2498                    );
2499                    let guar = err.emit_err();
2500                    return Ok(GenericArg::Type(
2501                        self.mk_ty(start.to(expr.span), TyKind::Err(guar)),
2502                    ));
2503                } else if self.token == token::Comma || self.token.kind.should_end_const_arg() {
2504                    // Avoid the following output by checking that we consumed a full const arg:
2505                    // help: expressions must be enclosed in braces to be used as const generic
2506                    //       arguments
2507                    //    |
2508                    // LL |     let sr: Vec<{ (u32, _, _) = vec![] };
2509                    //    |                 ^                      ^
2510                    return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2511                }
2512            }
2513            Err(err) => {
2514                err.cancel();
2515            }
2516        }
2517        self.restore_snapshot(snapshot);
2518        Err(err)
2519    }
2520
2521    /// Try to recover from an unbraced const argument whose first token [could begin a type][ty].
2522    ///
2523    /// [ty]: token::Token::can_begin_type
2524    pub(crate) fn recover_unbraced_const_arg_that_can_begin_ty(
2525        &mut self,
2526        mut snapshot: SnapshotParser<'a>,
2527    ) -> Option<Box<ast::Expr>> {
2528        match (|| snapshot.parse_expr_res(Restrictions::CONST_EXPR))() {
2529            // Since we don't know the exact reason why we failed to parse the type or the
2530            // expression, employ a simple heuristic to weed out some pathological cases.
2531            Ok(expr) if let token::Comma | token::Gt = snapshot.token.kind => {
2532                self.restore_snapshot(snapshot);
2533                Some(expr)
2534            }
2535            Ok(_) => None,
2536            Err(err) => {
2537                err.cancel();
2538                None
2539            }
2540        }
2541    }
2542
2543    /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2544    pub(super) fn dummy_const_arg_needs_braces(&self, mut err: Diag<'a>, span: Span) -> GenericArg {
2545        err.multipart_suggestion(
2546            "expressions must be enclosed in braces to be used as const generic \
2547             arguments",
2548            ::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())],
2549            Applicability::MaybeIncorrect,
2550        );
2551        let guar = err.emit_err();
2552        let value = self.mk_expr_err(span, guar);
2553        GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2554    }
2555
2556    /// Some special error handling for the "top-level" patterns in a match arm,
2557    /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2558    #[cold]
2559    pub(crate) fn recover_colon_colon_in_pat_typo(
2560        &mut self,
2561        mut first_pat: Pat,
2562        expected: Option<Expected>,
2563    ) -> Pat {
2564        if token::Colon != self.token.kind {
2565            return first_pat;
2566        }
2567
2568        // The pattern looks like it might be a path with a `::` -> `:` typo:
2569        // `match foo { bar:baz => {} }`
2570        let colon_span = self.token.span;
2571        // We only emit "unexpected `:`" error here if we can successfully parse the
2572        // whole pattern correctly in that case.
2573        let mut snapshot_pat = self.create_snapshot_for_diagnostic();
2574        let mut snapshot_type = self.create_snapshot_for_diagnostic();
2575
2576        // Create error for "unexpected `:`".
2577        match self.expected_one_of_not_found(&[], &[]) {
2578            Err(mut err) => {
2579                // Skip the `:`.
2580                snapshot_pat.bump();
2581                snapshot_type.bump();
2582                match snapshot_pat.parse_pat_no_top_alt(expected, None) {
2583                    Err(inner_err) => {
2584                        inner_err.cancel();
2585                    }
2586                    Ok(mut pat) => {
2587                        // We've parsed the rest of the pattern.
2588                        let new_span = first_pat.span.to(pat.span);
2589                        let mut show_sugg = false;
2590                        // Try to construct a recovered pattern.
2591                        match &mut pat.kind {
2592                            PatKind::Struct(qself @ None, path, ..)
2593                            | PatKind::TupleStruct(qself @ None, path, _)
2594                            | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2595                                PatKind::Ident(_, ident, _) => {
2596                                    path.segments.insert(0, PathSegment::from_ident(*ident));
2597                                    path.span = new_span;
2598                                    show_sugg = true;
2599                                    first_pat = pat;
2600                                }
2601                                PatKind::Path(old_qself, old_path) => {
2602                                    path.segments = old_path
2603                                        .segments
2604                                        .iter()
2605                                        .cloned()
2606                                        .chain(take(&mut path.segments))
2607                                        .collect();
2608                                    path.span = new_span;
2609                                    *qself = old_qself.clone();
2610                                    first_pat = pat;
2611                                    show_sugg = true;
2612                                }
2613                                _ => {}
2614                            },
2615                            PatKind::Ident(BindingMode::NONE, ident, None) => {
2616                                match &first_pat.kind {
2617                                    PatKind::Ident(_, old_ident, _) => {
2618                                        let path = PatKind::Path(
2619                                            None,
2620                                            Path {
2621                                                span: new_span,
2622                                                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![
2623                                                    PathSegment::from_ident(*old_ident),
2624                                                    PathSegment::from_ident(*ident),
2625                                                ],
2626                                            },
2627                                        );
2628                                        first_pat = self.mk_pat(new_span, path);
2629                                        show_sugg = true;
2630                                    }
2631                                    PatKind::Path(old_qself, old_path) => {
2632                                        let mut segments = old_path.segments.clone();
2633                                        segments.push(PathSegment::from_ident(*ident));
2634                                        let path = PatKind::Path(
2635                                            old_qself.clone(),
2636                                            Path { span: new_span, segments },
2637                                        );
2638                                        first_pat = self.mk_pat(new_span, path);
2639                                        show_sugg = true;
2640                                    }
2641                                    _ => {}
2642                                }
2643                            }
2644                            _ => {}
2645                        }
2646                        if show_sugg {
2647                            err.span_suggestion_verbose(
2648                                colon_span.until(self.look_ahead(1, |t| t.span)),
2649                                "maybe write a path separator here",
2650                                "::",
2651                                Applicability::MaybeIncorrect,
2652                            );
2653                        } else {
2654                            first_pat = self.mk_pat(
2655                                new_span,
2656                                PatKind::Err(
2657                                    self.dcx()
2658                                        .span_delayed_bug(colon_span, "recovered bad path pattern"),
2659                                ),
2660                            );
2661                        }
2662                        self.restore_snapshot(snapshot_pat);
2663                    }
2664                }
2665                match snapshot_type.parse_ty() {
2666                    Err(inner_err) => {
2667                        inner_err.cancel();
2668                    }
2669                    Ok(ty) => {
2670                        err.span_label(ty.span, "specifying the type of a pattern isn't supported");
2671                        self.restore_snapshot(snapshot_type);
2672                        let new_span = first_pat.span.to(ty.span);
2673                        first_pat =
2674                            self.mk_pat(
2675                                new_span,
2676                                PatKind::Err(self.dcx().span_delayed_bug(
2677                                    colon_span,
2678                                    "recovered bad pattern with type",
2679                                )),
2680                            );
2681                    }
2682                }
2683                err.emit();
2684            }
2685            _ => {
2686                // Carry on as if we had not done anything. This should be unreachable.
2687            }
2688        };
2689        first_pat
2690    }
2691
2692    /// If `loop_header` is `Some` and an unexpected block label is encountered,
2693    /// it is suggested to be moved just before `loop_header`, else it is suggested to be removed.
2694    pub(crate) fn maybe_recover_unexpected_block_label(
2695        &mut self,
2696        loop_header: Option<Span>,
2697    ) -> bool {
2698        // Check for `'a : {`
2699        if !(self.check_lifetime()
2700            && self.look_ahead(1, |t| *t == token::Colon)
2701            && self.look_ahead(2, |t| *t == token::OpenBrace))
2702        {
2703            return false;
2704        }
2705        let label = self.eat_label().expect("just checked if a label exists");
2706        self.bump(); // eat `:`
2707        let span = label.ident.span.to(self.prev_token.span);
2708        let mut diag = self
2709            .dcx()
2710            .struct_span_err(span, "block label not supported here")
2711            .with_span_label(span, "not supported here");
2712        if let Some(loop_header) = loop_header {
2713            diag.multipart_suggestion(
2714                "if you meant to label the loop, move this label before the loop",
2715                ::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![
2716                    (label.ident.span.until(self.token.span), String::from("")),
2717                    (loop_header.shrink_to_lo(), format!("{}: ", label.ident)),
2718                ],
2719                Applicability::MachineApplicable,
2720            );
2721        } else {
2722            diag.tool_only_span_suggestion(
2723                label.ident.span.until(self.token.span),
2724                "remove this block label",
2725                "",
2726                Applicability::MachineApplicable,
2727            );
2728        }
2729        diag.emit();
2730        true
2731    }
2732
2733    /// Some special error handling for the "top-level" patterns in a match arm,
2734    /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2735    pub(crate) fn maybe_recover_unexpected_comma(
2736        &mut self,
2737        lo: Span,
2738        rt: CommaRecoveryMode,
2739    ) -> PResult<'a, ()> {
2740        if self.token != token::Comma {
2741            return Ok(());
2742        }
2743        self.recover_unexpected_comma(lo, rt)
2744    }
2745
2746    #[cold]
2747    fn recover_unexpected_comma(&mut self, lo: Span, rt: CommaRecoveryMode) -> PResult<'a, ()> {
2748        // An unexpected comma after a top-level pattern is a clue that the
2749        // user (perhaps more accustomed to some other language) forgot the
2750        // parentheses in what should have been a tuple pattern; return a
2751        // suggestion-enhanced error here rather than choking on the comma later.
2752        let comma_span = self.token.span;
2753        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];
2754        self.bump();
2755        if let Err(err) = self.skip_pat_list(&mut comma_spans) {
2756            // We didn't expect this to work anyway; we just wanted to advance to the
2757            // end of the comma-sequence so we know the span to suggest parenthesizing.
2758            err.cancel();
2759        }
2760        let seq_span = lo.to(self.prev_token.span);
2761        let mut err = self.dcx().struct_span_err(comma_span, "unexpected `,` in pattern");
2762        err.multipart_suggestion(
2763            ::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!(
2764                "try adding parentheses to match on a tuple{}",
2765                if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2766            ),
2767            ::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![
2768                (seq_span.shrink_to_lo(), "(".to_string()),
2769                (seq_span.shrink_to_hi(), ")".to_string()),
2770            ],
2771            Applicability::MachineApplicable,
2772        );
2773        if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2774            err.multipart_suggestion(
2775                "...or a vertical bar to match on alternatives",
2776                comma_spans.into_iter().map(|span| (span, " |".to_string())).collect(),
2777                Applicability::MachineApplicable,
2778            );
2779        }
2780        Err(err)
2781    }
2782
2783    pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2784        let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2785        let qself_position = qself.as_ref().map(|qself| qself.position);
2786        for (i, segments) in path.segments.windows(2).enumerate() {
2787            if qself_position.is_some_and(|pos| i < pos) {
2788                continue;
2789            }
2790            if let [a, b] = segments {
2791                let (a_span, b_span) = (a.span(), b.span());
2792                let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2793                if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2794                    return Err(self.dcx().create_err(DoubleColonInBound {
2795                        span: path.span.shrink_to_hi(),
2796                        between: between_span,
2797                    }));
2798                }
2799            }
2800        }
2801        Ok(())
2802    }
2803
2804    /// Check for exclusive ranges written as `..<`
2805    pub(crate) fn maybe_err_dotdotlt_syntax(&self, maybe_lt: Token, mut err: Diag<'a>) -> Diag<'a> {
2806        if maybe_lt == token::Lt
2807            && (self.expected_token_types.contains(TokenType::Gt)
2808                || #[allow(non_exhaustive_omitted_patterns)] match self.token.kind {
    token::Literal(..) => true,
    _ => false,
}matches!(self.token.kind, token::Literal(..)))
2809        {
2810            err.span_suggestion_verbose(
2811                maybe_lt.span,
2812                "remove the `<` to write an exclusive range",
2813                "",
2814                Applicability::MachineApplicable,
2815            );
2816        }
2817        err
2818    }
2819
2820    /// This checks if this is a conflict marker, depending of the parameter passed.
2821    ///
2822    /// * `<<<<<<<`
2823    /// * `|||||||`
2824    /// * `=======`
2825    /// * `>>>>>>>`
2826    ///
2827    pub(super) fn is_vcs_conflict_marker(
2828        &mut self,
2829        long_kind: &TokenKind,
2830        short_kind: &TokenKind,
2831    ) -> bool {
2832        if long_kind == short_kind {
2833            // For conflict marker chars like `%` and `\`.
2834            (0..7).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2835        } else {
2836            // For conflict marker chars like `<` and `|`.
2837            (0..3).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2838                && self.look_ahead(3, |tok| tok == short_kind || tok == long_kind)
2839        }
2840    }
2841
2842    fn conflict_marker(
2843        &mut self,
2844        long_kind: &TokenKind,
2845        short_kind: &TokenKind,
2846        expected: Option<usize>,
2847    ) -> Option<(Span, usize)> {
2848        if self.is_vcs_conflict_marker(long_kind, short_kind) {
2849            let lo = self.token.span;
2850            if self.psess.source_map().span_to_margin(lo) != Some(0) {
2851                return None;
2852            }
2853            let mut len = 0;
2854            while self.token.kind == *long_kind || self.token.kind == *short_kind {
2855                if self.token.kind.break_two_token_op(1).is_some() {
2856                    len += 2;
2857                } else {
2858                    len += 1;
2859                }
2860                self.bump();
2861                if expected == Some(len) {
2862                    break;
2863                }
2864            }
2865            if expected.is_some() && expected != Some(len) {
2866                return None;
2867            }
2868            return Some((lo.to(self.prev_token.span), len));
2869        }
2870        None
2871    }
2872
2873    pub(super) fn recover_vcs_conflict_marker(&mut self) {
2874        // <<<<<<<
2875        let Some((start, len)) = self.conflict_marker(&TokenKind::Shl, &TokenKind::Lt, None) else {
2876            return;
2877        };
2878        let mut spans = Vec::with_capacity(2);
2879        spans.push(start);
2880        // |||||||
2881        let mut middlediff3 = None;
2882        // =======
2883        let mut middle = None;
2884        // >>>>>>>
2885        let mut end = None;
2886        loop {
2887            if self.token == TokenKind::Eof {
2888                break;
2889            }
2890            if let Some((span, _)) =
2891                self.conflict_marker(&TokenKind::OrOr, &TokenKind::Or, Some(len))
2892            {
2893                middlediff3 = Some(span);
2894            }
2895            if let Some((span, _)) =
2896                self.conflict_marker(&TokenKind::EqEq, &TokenKind::Eq, Some(len))
2897            {
2898                middle = Some(span);
2899            }
2900            if let Some((span, _)) =
2901                self.conflict_marker(&TokenKind::Shr, &TokenKind::Gt, Some(len))
2902            {
2903                spans.push(span);
2904                end = Some(span);
2905                break;
2906            }
2907            self.bump();
2908        }
2909
2910        let mut err = self.dcx().struct_span_fatal(spans, "encountered diff marker");
2911        let middle_marker = match middlediff3 {
2912            // We're using diff3
2913            Some(middlediff3) => {
2914                err.span_label(
2915                    middlediff3,
2916                    "between this marker and `=======` is the base code (what the two refs \
2917                     diverged from)",
2918                );
2919                "|||||||"
2920            }
2921            None => "=======",
2922        };
2923        err.span_label(
2924            start,
2925            ::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!(
2926                "between this marker and `{middle_marker}` is the code that you are merging into",
2927            ),
2928        );
2929
2930        if let Some(middle) = middle {
2931            err.span_label(middle, "between this marker and `>>>>>>>` is the incoming code");
2932        }
2933        if let Some(end) = end {
2934            err.span_label(end, "this marker concludes the conflict region");
2935        }
2936        err.note(
2937            "conflict markers indicate that a merge was started but could not be completed due \
2938             to merge conflicts\n\
2939             to resolve a conflict, keep only the code you want and then delete the lines \
2940             containing conflict markers",
2941        );
2942        err.help(
2943            "if you are in a merge, the top section is the code you already had checked out and \
2944             the bottom section is the new code\n\
2945             if you are in a rebase, the top section is the code being rebased onto and the bottom \
2946             section is the code you had checked out which is being rebased",
2947        );
2948
2949        err.note(
2950            "for an explanation on these markers from the `git` documentation, visit \
2951             <https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_checking_out_conflicts>",
2952        );
2953
2954        err.emit();
2955    }
2956
2957    /// Parse and throw away a parenthesized comma separated
2958    /// sequence of patterns until `)` is reached.
2959    fn skip_pat_list(&mut self, comma_spans: &mut Vec<Span>) -> PResult<'a, ()> {
2960        while !self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)) {
2961            self.parse_pat_no_top_alt(None, None)?;
2962            if !self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
2963                return Ok(());
2964            }
2965            comma_spans.push(self.prev_token.span);
2966        }
2967        Ok(())
2968    }
2969    pub(super) fn maybe_type_in_generic_parameter(&mut self, origin_error: Diag<'a>) -> Diag<'a> {
2970        if !self.may_recover() {
2971            return origin_error;
2972        }
2973        self.with_recovery(super::Recovery::Forbidden, |snapshot| {
2974            snapshot.bump();
2975            let lo = snapshot.token.span.shrink_to_lo();
2976
2977            let ty = match snapshot.parse_ty() {
2978                Ok(t) => t,
2979                Err(err) => {
2980                    err.cancel();
2981                    return origin_error;
2982                }
2983            };
2984            let TyKind::Path(_, path) = ty.kind else {
2985                return origin_error;
2986            };
2987            let Some(GenericArgs::AngleBracketed(AngleBracketedArgs { span: _, ref args })) =
2988                path.segments[0].args
2989            else {
2990                return origin_error;
2991            };
2992
2993            let path_span = path.span;
2994            let mut new_error = snapshot.dcx().create_err(FoundPathInGenerics {
2995                span: path_span,
2996                path: snapshot.span_to_snippet(path_span).unwrap(),
2997            });
2998            new_error.subdiagnostic(SuggestBindTypeParameter { span: lo });
2999            origin_error.cancel();
3000
3001            let params = args
3002                .iter()
3003                .map(|arg| snapshot.span_to_snippet(arg.span()).unwrap())
3004                .collect::<Vec<_>>()
3005                .join(", ");
3006            new_error.subdiagnostic(SuggestIntroduceTypeParameter {
3007                span: path_span,
3008                parameters: params,
3009            });
3010            new_error
3011        })
3012    }
3013}