Skip to main content

rustc_parse/parser/
ty.rs

1use rustc_ast::token::{self, IdentKind, MetaVarKind, Token, TokenKind};
2use rustc_ast::util::case::Case;
3use rustc_ast::{
4    self as ast, BoundAsyncness, BoundConstness, BoundPolarity, DUMMY_NODE_ID, FnPtrTy, FnRetTy,
5    GenericBound, GenericBounds, GenericParam, Generics, Lifetime, MacCall, MutTy, Mutability,
6    Path, Pinnedness, PolyTraitRef, PreciseCapturingArg, TraitBoundModifiers, TraitObjectSyntax,
7    Ty, TyKind, UnsafeBinderTy,
8};
9use rustc_errors::{Applicability, Diag, E0516, PResult};
10use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym};
11use thin_vec::{ThinVec, thin_vec};
12
13use super::{Parser, PathStyle, SeqSep, TokenType, Trailing};
14use crate::diagnostics::{
15    self, DynAfterMut, ExpectedFnPathFoundFnKeyword, ExpectedMutOrConstInRawPointerType,
16    FnPtrWithGenerics, FnPtrWithGenericsSugg, HelpUseLatestEdition, InvalidCVariadicType,
17    InvalidDynKeyword, LifetimeAfterMut, NeedPlusAfterTraitObjectLifetime, NestedCVariadicType,
18    ReturnTypesUseThinArrow,
19};
20use crate::parser::{FnContext, FnParseMode, FrontMatterParsingMode};
21use crate::{exp, maybe_recover_from_interpolated_ty_qpath};
22
23/// Signals whether parsing a type should allow `+`.
24///
25/// For example, let T be the type `impl Default + 'static`
26/// With `AllowPlus::Yes`, T will be parsed successfully
27/// With `AllowPlus::No`, parsing T will return a parse error
28#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllowPlus { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AllowPlus { }
#[automatically_derived]
impl ::core::clone::Clone for AllowPlus {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AllowPlus { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AllowPlus {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
29pub(super) enum AllowPlus {
30    Yes,
31    No,
32}
33
34#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for RecoverQPath { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RecoverQPath {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
35pub(super) enum RecoverQPath {
36    Yes,
37    No,
38}
39
40pub(super) enum RecoverQuestionMark {
41    Yes,
42    No,
43}
44
45/// Signals whether parsing a type should recover `->`.
46///
47/// More specifically, when parsing a function like:
48/// ```compile_fail
49/// fn foo() => u8 { 0 }
50/// fn bar(): u8 { 0 }
51/// ```
52/// The compiler will try to recover interpreting `foo() => u8` as `foo() -> u8` when calling
53/// `parse_ty` with anything except `RecoverReturnSign::No`, and it will try to recover `bar(): u8`
54/// as `bar() -> u8` when passing `RecoverReturnSign::Yes` to `parse_ty`
55#[derive(#[automatically_derived]
impl ::core::marker::Copy for RecoverReturnSign { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RecoverReturnSign { }
#[automatically_derived]
impl ::core::clone::Clone for RecoverReturnSign {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for RecoverReturnSign { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RecoverReturnSign {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
56pub(super) enum RecoverReturnSign {
57    Yes,
58    OnlyFatArrow,
59    No,
60}
61
62impl RecoverReturnSign {
63    /// [RecoverReturnSign::Yes] allows for recovering `fn foo() => u8` and `fn foo(): u8`,
64    /// [RecoverReturnSign::OnlyFatArrow] allows for recovering only `fn foo() => u8` (recovering
65    /// colons can cause problems when parsing where clauses), and
66    /// [RecoverReturnSign::No] doesn't allow for any recovery of the return type arrow
67    fn can_recover(self, token: &TokenKind) -> bool {
68        match self {
69            Self::Yes => #[allow(non_exhaustive_omitted_patterns)] match token {
    token::FatArrow | token::Colon => true,
    _ => false,
}matches!(token, token::FatArrow | token::Colon),
70            Self::OnlyFatArrow => #[allow(non_exhaustive_omitted_patterns)] match token {
    token::FatArrow => true,
    _ => false,
}matches!(token, token::FatArrow),
71            Self::No => false,
72        }
73    }
74}
75
76// Is `...` (`CVarArgs`) legal at this level of type parsing?
77#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for AllowCVariadic { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AllowCVariadic {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
78enum AllowCVariadic {
79    Yes,
80    No,
81}
82
83/// Determine if the given token can begin a bound assuming it follows Rust 2015 identifier `dyn`.
84///
85/// In Rust 2015, `dyn` is a contextual keyword, not a full one.
86fn can_begin_dyn_bound_in_rust_2015(t: Token) -> bool {
87    // In `dyn::x`, `dyn<X>` and `dyn<<X>::Y>`, `dyn` should (continue to) denote a regular path
88    // segment for backward compatibility. We make an exception for `dyn(X)` which used to be
89    // interpreted as a path with parenthesized generic arguments which can be semantically
90    // well-formed (consider: `use std::ops::Fn as dyn;`). Instead, we treat it as a trait
91    // object type whose first bound is parenthesized.
92
93    // Contrary to `Parser::can_begin_bound`, `!`, `const`, `[` and `async` are deliberately not
94    // part of this list to contain the number of potential regressions esp. in MBE code.
95    // `const` and `[` would regress UI test `macro-dyn-const-2015.rs` and
96    // `!` would regress `dyn!(...)` macro calls in Rust 2015 for example.
97
98    if t.is_path_start() {
99        return t != token::PathSep && t != token::Lt && t != token::Shl;
100    }
101
102    t == token::OpenParen || t == token::Question || t.is_lifetime() || t.is_keyword(kw::For)
103}
104
105impl<'a> Parser<'a> {
106    /// Parses a type.
107    pub fn parse_ty(&mut self) -> PResult<'a, Box<Ty>> {
108        if self.token == token::DotDotDot {
109            // We special case this so that we don't talk about "nested C-variadics" in types.
110            // We still pass in `AllowCVariadic::No` so that `parse_ty_common` can complain about
111            // things like `Vec<...>`.
112            let span = self.token.span;
113            self.bump();
114            let kind = TyKind::Err(self.dcx().emit_err(InvalidCVariadicType { span }));
115            return Ok(self.mk_ty(span, kind));
116        }
117        self.parse_ty_common(
118            AllowPlus::Yes,
119            AllowCVariadic::No,
120            RecoverQPath::Yes,
121            RecoverReturnSign::Yes,
122            None,
123            RecoverQuestionMark::Yes,
124        )
125    }
126
127    pub(super) fn parse_ty_with_generics_recovery(
128        &mut self,
129        ty_params: &Generics,
130    ) -> PResult<'a, Box<Ty>> {
131        self.parse_ty_common(
132            AllowPlus::Yes,
133            AllowCVariadic::No,
134            RecoverQPath::Yes,
135            RecoverReturnSign::Yes,
136            Some(ty_params),
137            RecoverQuestionMark::Yes,
138        )
139    }
140
141    /// Parse a type suitable for a function or function pointer parameter.
142    /// The difference from `parse_ty` is that this version allows `...`
143    /// (`CVarArgs`) at the top level of the type.
144    pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, Box<Ty>> {
145        let ty = self.parse_ty_common(
146            AllowPlus::Yes,
147            AllowCVariadic::Yes,
148            RecoverQPath::Yes,
149            RecoverReturnSign::Yes,
150            None,
151            RecoverQuestionMark::Yes,
152        )?;
153
154        // Recover a trailing `= EXPR` if present.
155        if self.may_recover()
156            && self.check_noexpect(&token::Eq)
157            && self.look_ahead(1, |tok| tok.can_begin_expr())
158        {
159            let snapshot = self.create_snapshot_for_diagnostic();
160            self.bump();
161            let eq_span = self.prev_token.span;
162            match self.parse_expr() {
163                Ok(e) => {
164                    self.dcx()
165                        .struct_span_err(eq_span.to(e.span), "parameter defaults are not supported")
166                        .emit();
167                }
168                Err(diag) => {
169                    diag.cancel();
170                    self.restore_snapshot(snapshot);
171                }
172            }
173        }
174
175        Ok(ty)
176    }
177
178    /// Parses a type in restricted contexts where `+` is not permitted.
179    ///
180    /// Example 1: `&'a TYPE`
181    ///     `+` is prohibited to maintain operator priority (P(+) < P(&)).
182    /// Example 2: `value1 as TYPE + value2`
183    ///     `+` is prohibited to avoid interactions with expression grammar.
184    pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, Box<Ty>> {
185        self.parse_ty_common(
186            AllowPlus::No,
187            AllowCVariadic::No,
188            RecoverQPath::Yes,
189            RecoverReturnSign::Yes,
190            None,
191            RecoverQuestionMark::Yes,
192        )
193    }
194
195    /// Parses a type following an `as` cast. Similar to `parse_ty_no_plus`, but signaling origin
196    /// for better diagnostics involving `?`.
197    pub(super) fn parse_as_cast_ty(&mut self) -> PResult<'a, Box<Ty>> {
198        self.parse_ty_common(
199            AllowPlus::No,
200            AllowCVariadic::No,
201            RecoverQPath::Yes,
202            RecoverReturnSign::Yes,
203            None,
204            RecoverQuestionMark::No,
205        )
206    }
207
208    pub(super) fn parse_ty_no_question_mark_recover(&mut self) -> PResult<'a, Box<Ty>> {
209        self.parse_ty_common(
210            AllowPlus::Yes,
211            AllowCVariadic::No,
212            RecoverQPath::Yes,
213            RecoverReturnSign::Yes,
214            None,
215            RecoverQuestionMark::No,
216        )
217    }
218
219    /// Parse a type without recovering `:` as `->` to avoid breaking code such
220    /// as `where fn() : for<'a>`.
221    pub(super) fn parse_ty_for_where_clause(&mut self) -> PResult<'a, Box<Ty>> {
222        self.parse_ty_common(
223            AllowPlus::Yes,
224            AllowCVariadic::No,
225            RecoverQPath::Yes,
226            RecoverReturnSign::OnlyFatArrow,
227            None,
228            RecoverQuestionMark::Yes,
229        )
230    }
231
232    /// Parses an optional return type `[ -> TY ]` in a function declaration.
233    pub(super) fn parse_ret_ty(
234        &mut self,
235        allow_plus: AllowPlus,
236        recover_qpath: RecoverQPath,
237        recover_return_sign: RecoverReturnSign,
238    ) -> PResult<'a, FnRetTy> {
239        let lo = self.prev_token.span;
240        Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::RArrow,
    token_type: crate::parser::token_type::TokenType::RArrow,
}exp!(RArrow)) {
241            // FIXME(Centril): Can we unconditionally `allow_plus`?
242            let ty = self.parse_ty_common(
243                allow_plus,
244                AllowCVariadic::No,
245                recover_qpath,
246                recover_return_sign,
247                None,
248                RecoverQuestionMark::Yes,
249            )?;
250            FnRetTy::Ty(ty)
251        } else if recover_return_sign.can_recover(&self.token.kind) {
252            // Don't `eat` to prevent `=>` from being added as an expected token which isn't
253            // actually expected and could only confuse users
254            self.bump();
255            self.dcx().emit_err(ReturnTypesUseThinArrow {
256                span: self.prev_token.span,
257                suggestion: lo.between(self.token.span),
258            });
259            let ty = self.parse_ty_common(
260                allow_plus,
261                AllowCVariadic::No,
262                recover_qpath,
263                recover_return_sign,
264                None,
265                RecoverQuestionMark::Yes,
266            )?;
267            FnRetTy::Ty(ty)
268        } else {
269            FnRetTy::Default(self.prev_token.span.shrink_to_hi())
270        })
271    }
272
273    fn parse_ty_common(
274        &mut self,
275        allow_plus: AllowPlus,
276        allow_c_variadic: AllowCVariadic,
277        recover_qpath: RecoverQPath,
278        recover_return_sign: RecoverReturnSign,
279        ty_generics: Option<&Generics>,
280        recover_question_mark: RecoverQuestionMark,
281    ) -> PResult<'a, Box<Ty>> {
282        let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes;
283        if allow_qpath_recovery && self.may_recover() &&
                let Some(mv_kind) = self.token.is_metavar_seq() &&
            let token::MetaVarKind::Ty { .. } = mv_kind &&
        self.check_noexpect_past_close_delim(&token::PathSep) {
    let ty =
        self.eat_metavar_seq(mv_kind,
                |this|
                    this.parse_ty_no_question_mark_recover()).expect("metavar seq ty");
    return self.maybe_recover_from_bad_qpath_stage_2(self.prev_token.span,
            ty);
};maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
284
285        if let Some(ty) = self.eat_metavar_seq_with_matcher(
286            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Ty { .. } => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Ty { .. }),
287            |this| this.parse_ty_no_question_mark_recover(),
288        ) {
289            return Ok(ty);
290        }
291
292        self.recover_from_outer_attributes("types")?;
293
294        let lo = self.token.span;
295        let mut impl_dyn_multi = false;
296        let kind = if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
297            self.parse_paren_start_ty(lo, allow_plus)?
298        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
299            // Never type `!`
300            TyKind::Never
301        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Star,
    token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star)) {
302            self.parse_ty_ptr()?
303        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBracket,
    token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket)) {
304            self.parse_array_or_slice_ty()?
305        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::And,
    token_type: crate::parser::token_type::TokenType::And,
}exp!(And)) || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::AndAnd,
    token_type: crate::parser::token_type::TokenType::AndAnd,
}exp!(AndAnd)) {
306            // Reference
307            self.expect_and()?;
308            self.parse_borrowed_pointee()?
309        } else if self.eat_keyword_noexpect(kw::Typeof) {
310            self.parse_typeof_ty(lo)?
311        } else if self.is_builtin() {
312            self.parse_builtin_ty()?
313        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Underscore,
    token_type: crate::parser::token_type::TokenType::KwUnderscore,
}exp!(Underscore)) {
314            // A type to be inferred `_`
315            TyKind::Infer
316        } else if self.check_fn_front_matter(false, Case::Sensitive) {
317            // Function pointer type
318            self.parse_ty_fn_ptr(lo, ThinVec::new(), None, recover_return_sign)?
319        } else if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::For,
    token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For)) {
320            // Function pointer type or bound list (trait object type) starting with a poly-trait.
321            //   `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
322            //   `for<'lt> Trait1<'lt> + Trait2 + 'a`
323            let (bound_vars, _) = self.parse_higher_ranked_binder()?;
324            if self.check_fn_front_matter(false, Case::Sensitive) {
325                self.parse_ty_fn_ptr(
326                    lo,
327                    bound_vars,
328                    Some(self.prev_token.span.shrink_to_lo()),
329                    recover_return_sign,
330                )?
331            } else {
332                // Try to recover `for<'a> dyn Trait` or `for<'a> impl Trait`.
333                if self.may_recover()
334                    && (self.token.is_keyword(kw::Impl) || self.can_begin_dyn_ty())
335                {
336                    self.bump();
337                    let (kw, _) = self.prev_token.ident().unwrap();
338                    let removal_span = kw.span.with_hi(self.token.span.lo());
339                    let path = self.parse_path(PathStyle::Type)?;
340                    let mut bounds = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(GenericBound::Trait(PolyTraitRef::new(bound_vars, path,
                TraitBoundModifiers::NONE, lo.to(self.prev_token.span),
                ast::Parens::No)));
    vec
}thin_vec![GenericBound::Trait(PolyTraitRef::new(
341                        bound_vars,
342                        path,
343                        TraitBoundModifiers::NONE,
344                        lo.to(self.prev_token.span),
345                        ast::Parens::No,
346                    ))];
347                    if allow_plus == AllowPlus::Yes && self.check_plus() {
348                        self.eat_plus();
349                        bounds.append(&mut self.parse_generic_bounds()?);
350                    }
351                    self.dcx().emit_err(diagnostics::TransposeDynOrImpl {
352                        span: kw.span,
353                        kw: kw.name.as_str(),
354                        sugg: diagnostics::TransposeDynOrImplSugg {
355                            removal_span,
356                            insertion_span: lo.shrink_to_lo(),
357                            kw: kw.name.as_str(),
358                        },
359                    });
360                    match kw.name {
361                        kw::Dyn => TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn),
362                        kw::Impl => TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds),
363                        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
364                    }
365                } else {
366                    let path = self.parse_path(PathStyle::Type)?;
367                    let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
368                    self.finish_parsing_bare_trait_object_ty(
369                        bound_vars,
370                        path,
371                        lo,
372                        parse_plus,
373                        ast::Parens::No,
374                    )?
375                }
376            }
377        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Impl,
    token_type: crate::parser::token_type::TokenType::KwImpl,
}exp!(Impl)) {
378            self.parse_impl_ty(&mut impl_dyn_multi)?
379        } else if self.can_begin_dyn_ty() {
380            self.parse_dyn_ty(&mut impl_dyn_multi)?
381        } else if self.eat_lt() {
382            // Qualified path
383            let (qself, path) = self.parse_qpath(PathStyle::Type)?;
384            TyKind::Path(Some(qself), path)
385        } else if (self.token.is_keyword(kw::Const) || self.token.is_keyword(kw::Mut))
386            && self.look_ahead(1, |t| *t == token::Star)
387        {
388            self.parse_ty_c_style_pointer()?
389        } else if self.check_path() {
390            self.parse_path_start_ty(lo, allow_plus, ty_generics)?
391        } else if self.can_begin_bound() {
392            self.parse_bare_trait_object_ty(lo, allow_plus)?
393        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::DotDotDot,
    token_type: crate::parser::token_type::TokenType::DotDotDot,
}exp!(DotDotDot)) {
394            match allow_c_variadic {
395                AllowCVariadic::Yes => TyKind::CVarArgs,
396                AllowCVariadic::No => {
397                    // FIXME(c_variadic): Should we just allow `...` syntactically
398                    // anywhere in a type and use semantic restrictions instead?
399                    // NOTE: This may regress certain MBE calls if done incorrectly.
400                    let guar = self.dcx().emit_err(NestedCVariadicType { span: lo });
401                    TyKind::Err(guar)
402                }
403            }
404        } else if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe))
405            && self.look_ahead(1, |tok| tok.kind == token::Lt)
406        {
407            self.parse_unsafe_binder_ty()?
408        } else {
409            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected type, found {0}",
                super::token_descr(&self.token)))
    })format!("expected type, found {}", super::token_descr(&self.token));
410            let mut err = self.dcx().struct_span_err(lo, msg);
411            err.span_label(lo, "expected type");
412            if self.may_recover()
413                && (self.eat_keyword_noexpect(kw::True) || self.eat_keyword_noexpect(kw::False))
414            {
415                err.span_suggestion(
416                    self.prev_token.span,
417                    "the type is called",
418                    "bool",
419                    Applicability::MachineApplicable,
420                );
421                err.emit();
422                TyKind::Path(
423                    None,
424                    Path::from_ident(Ident { span: self.prev_token.span, name: sym::bool }),
425                )
426            } else {
427                return Err(err);
428            }
429        };
430
431        let span = lo.to(self.prev_token.span);
432        let mut ty = self.mk_ty(span, kind);
433
434        // Try to recover from use of `+` with incorrect priority.
435        match allow_plus {
436            AllowPlus::Yes => self.maybe_recover_from_bad_type_plus(&ty)?,
437            AllowPlus::No => self.maybe_report_ambiguous_plus(impl_dyn_multi, &ty),
438        }
439        if let RecoverQuestionMark::Yes = recover_question_mark {
440            ty = self.maybe_recover_from_question_mark(ty);
441        }
442        if allow_qpath_recovery { self.maybe_recover_from_bad_qpath(ty) } else { Ok(ty) }
443    }
444
445    fn parse_unsafe_binder_ty(&mut self) -> PResult<'a, TyKind> {
446        let lo = self.token.span;
447        if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
                kw: rustc_span::symbol::kw::Unsafe,
                token_type: crate::parser::token_type::TokenType::KwUnsafe,
            }) {
    ::core::panicking::panic("assertion failed: self.eat_keyword(exp!(Unsafe))")
};assert!(self.eat_keyword(exp!(Unsafe)));
448        self.expect_lt()?;
449        let generic_params = self.parse_generic_params()?;
450        self.expect_gt()?;
451        let inner_ty = self.parse_ty()?;
452        let span = lo.to(self.prev_token.span);
453        self.psess.gated_spans.gate(sym::unsafe_binders, span);
454
455        Ok(TyKind::UnsafeBinder(Box::new(UnsafeBinderTy { generic_params, inner_ty })))
456    }
457
458    /// Parse a type that begins with an opening parenthesis `(`.
459    ///
460    /// More specifically, it parses one of the following:
461    ///
462    /// 1. parenthesized type
463    /// 2. tuple type
464    /// 3. bare trait object type where the first trait bound is parenthesized
465    fn parse_paren_start_ty(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
466        let mut trailing_plus = false;
467        let (ts, trailing) = self.parse_paren_comma_seq(|p| {
468            let ty = p.parse_ty()?;
469            trailing_plus = p.prev_token == TokenKind::Plus;
470            Ok(ty)
471        })?;
472
473        if ts.len() == 1 && #[allow(non_exhaustive_omitted_patterns)] match trailing {
    Trailing::No => true,
    _ => false,
}matches!(trailing, Trailing::No) {
474            let ty = ts.into_iter().next().unwrap();
475
476            // Let's check if we actually have a bare trait object type where the first trait bound
477            // is parenthesized. That's the case if the parentheses are followed by a `+` and if
478            // what's contained between the parentheses resembles a *BareTraitBound*.
479            //
480            // For context, looking at bounds in general (see *Bound*), only trait bounds are
481            // allowed to be wrapped in parentheses, not however lifetime and use bounds.
482            let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
483            match ty.kind {
484                // `"(" TypePath ")" "+"`
485                TyKind::Path(None, path) if maybe_bounds => self
486                    .finish_parsing_bare_trait_object_ty(
487                        ThinVec::new(),
488                        path,
489                        lo,
490                        true,
491                        ast::Parens::Yes,
492                    ),
493                // `"(" BareTraitBound\TypePath | UseBound ")" "+"`
494                //
495                // * FIXME: As alluded to above, only trait bounds are meant to allow parens.
496                //   Arguably, it's an accident that we're permitting *UseBound*s and thus types
497                //   like `(use<>)+`. Might need a T-lang FCP to change this.
498                // * We're checking `!trailing_plus` to prevent us from accepting code like
499                //   `(T+)+` or `('a+)+`.
500                // * While we could be looking at `('a)+` which we don't want to accept, we
501                //   know that the `parse_ty` above has already emitted an error since the
502                //   lifetime isn't immediately followed by a `+`.
503                TyKind::TraitObject(mut bounds, TraitObjectSyntax::None)
504                    if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
505                {
506                    self.eat_plus();
507                    bounds.append(&mut self.parse_generic_bounds()?);
508                    Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
509                }
510                _ => Ok(TyKind::Paren(ty)),
511            }
512        } else {
513            Ok(TyKind::Tup(ts))
514        }
515    }
516
517    fn parse_bare_trait_object_ty(
518        &mut self,
519        lo: Span,
520        allow_plus: AllowPlus,
521    ) -> PResult<'a, TyKind> {
522        // A lifetime only begins a bare trait object type if it is followed by `+`!
523        if self.token.is_lifetime() && !self.look_ahead(1, |t| t.is_like_plus()) {
524            // In Rust 2021 and beyond, we assume that the user didn't intend to write a bare trait
525            // object type with a leading lifetime bound since that seems very unlikely given the
526            // fact that `dyn`-less trait objects are *semantically* invalid.
527            if self.psess.edition.at_least_rust_2021() {
528                let lt = self.expect_lifetime();
529                let mut err = self.dcx().struct_span_err(lo, "expected type, found lifetime");
530                err.span_label(lo, "expected type");
531                return Ok(match self.maybe_recover_ref_ty_no_leading_ampersand(lt, lo, err) {
532                    Ok(ref_ty) => ref_ty,
533                    Err(err) => TyKind::Err(err.emit_err()),
534                });
535            }
536
537            self.dcx().emit_err(NeedPlusAfterTraitObjectLifetime {
538                span: lo,
539                suggestion: lo.shrink_to_hi(),
540            });
541        }
542        Ok(TyKind::TraitObject(
543            self.parse_generic_bounds_common(allow_plus)?,
544            TraitObjectSyntax::None,
545        ))
546    }
547
548    fn maybe_recover_ref_ty_no_leading_ampersand<'cx>(
549        &mut self,
550        lt: Lifetime,
551        lo: Span,
552        mut err: Diag<'cx>,
553    ) -> Result<TyKind, Diag<'cx>> {
554        if !self.may_recover() {
555            return Err(err);
556        }
557        let snapshot = self.create_snapshot_for_diagnostic();
558        let mutbl = self.parse_mutability();
559        match self.parse_ty_no_plus() {
560            Ok(ty) => {
561                err.span_suggestion_verbose(
562                    lo.shrink_to_lo(),
563                    "you might have meant to write a reference type here",
564                    "&",
565                    Applicability::MaybeIncorrect,
566                );
567                err.emit();
568                Ok(TyKind::Ref(Some(lt), MutTy { ty, mutbl }))
569            }
570            Err(diag) => {
571                diag.cancel();
572                self.restore_snapshot(snapshot);
573                Err(err)
574            }
575        }
576    }
577
578    fn finish_parsing_bare_trait_object_ty(
579        &mut self,
580        generic_params: ThinVec<GenericParam>,
581        path: ast::Path,
582        lo: Span,
583        parse_plus: bool,
584        parens: ast::Parens,
585    ) -> PResult<'a, TyKind> {
586        let mut bounds = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(GenericBound::Trait(PolyTraitRef::new(generic_params, path,
                TraitBoundModifiers::NONE, lo.to(self.prev_token.span),
                parens)));
    vec
}thin_vec![GenericBound::Trait(PolyTraitRef::new(
587            generic_params,
588            path,
589            TraitBoundModifiers::NONE,
590            lo.to(self.prev_token.span),
591            parens,
592        ))];
593        if parse_plus {
594            self.eat_plus();
595            bounds.append(&mut self.parse_generic_bounds()?);
596        }
597        Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
598    }
599
600    /// Parses a raw pointer with a C-style typo
601    fn parse_ty_c_style_pointer(&mut self) -> PResult<'a, TyKind> {
602        let kw_span = self.token.span;
603        let mutbl = self.parse_mut_or_const();
604
605        if let Some(mutbl) = mutbl
606            && self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Star,
    token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star))
607        {
608            let star_span = self.prev_token.span;
609
610            let mutability = match mutbl {
611                Mutability::Not => "const",
612                Mutability::Mut => "mut",
613            };
614
615            let ty = self.parse_ty_no_question_mark_recover()?;
616
617            self.dcx()
618                .struct_span_err(
619                    kw_span,
620                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("raw pointer types must be written as `*{0} T`",
                mutability))
    })format!("raw pointer types must be written as `*{mutability} T`"),
621                )
622                .with_multipart_suggestion(
623                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("put the `*` before `{0}`",
                mutability))
    })format!("put the `*` before `{mutability}`"),
624                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(star_span, String::new()),
                (kw_span.shrink_to_lo(), "*".to_string())]))vec![(star_span, String::new()), (kw_span.shrink_to_lo(), "*".to_string())],
625                    Applicability::MachineApplicable,
626                )
627                .emit();
628
629            return Ok(TyKind::Ptr(MutTy { ty, mutbl }));
630        }
631        // This is unreachable because we always get into if above and return from it
632        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("this could never happen")));
}unreachable!("this could never happen")
633    }
634
635    /// Parses a raw pointer type: `*[const | mut] $type`.
636    fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
637        let mutbl = self.parse_mut_or_const().unwrap_or_else(|| {
638            let span = self.prev_token.span;
639            self.dcx().emit_err(ExpectedMutOrConstInRawPointerType {
640                span,
641                after_asterisk: span.shrink_to_hi(),
642            });
643            Mutability::Not
644        });
645        let ty = self.parse_ty_no_plus()?;
646        Ok(TyKind::Ptr(MutTy { ty, mutbl }))
647    }
648
649    /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
650    /// The opening `[` bracket is already eaten.
651    fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
652        let elt_ty = self.parse_ty()?;
653
654        let ty = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
655            let mut length = self.parse_expr_anon_const()?;
656
657            if let Err(e) = self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket)) {
658                // Try to recover from `X<Y, ...>` when `X::<Y, ...>` works
659                self.check_mistyped_turbofish_with_multiple_type_params(e, &mut length.value)?;
660                self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket))?;
661            }
662            TyKind::Array(elt_ty, length)
663        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket)) {
664            TyKind::Slice(elt_ty)
665        } else {
666            self.maybe_recover_array_ty_without_semi(elt_ty)?
667        };
668
669        Ok(ty)
670    }
671
672    /// Recover from malformed array type syntax.
673    ///
674    /// This method attempts to recover from cases like:
675    /// - `[u8, 5]` → suggests using `;`, return a Array type
676    /// - `[u8 5]` → suggests using `;`, return a Array type
677    /// Consider to add more cases in the future.
678    fn maybe_recover_array_ty_without_semi(&mut self, elt_ty: Box<Ty>) -> PResult<'a, TyKind> {
679        let span = self.token.span;
680        let token_descr = super::token_descr(&self.token);
681        let mut err =
682            self.dcx().struct_span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `;` or `]`, found {0}",
                token_descr))
    })format!("expected `;` or `]`, found {}", token_descr));
683        err.span_label(span, "expected `;` or `]`");
684
685        // If we cannot recover, return the error immediately.
686        if !self.may_recover() {
687            return Err(err);
688        }
689
690        let snapshot = self.create_snapshot_for_diagnostic();
691
692        // Consume common erroneous separators.
693        let hi = self.prev_token.span.hi();
694        _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) || self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)) || self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Star,
    token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star));
695        let suggestion_span = self.prev_token.span.with_lo(hi);
696
697        // FIXME(mgca): recovery is broken for `const {` args
698        // we first try to parse pattern like `[u8 5]`
699        let length = match self.parse_expr_anon_const() {
700            Ok(length) => length,
701            Err(e) => {
702                e.cancel();
703                self.restore_snapshot(snapshot);
704                return Err(err);
705            }
706        };
707
708        if let Err(e) = self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket)) {
709            e.cancel();
710            self.restore_snapshot(snapshot);
711            return Err(err);
712        }
713
714        err.span_suggestion_verbose(
715            suggestion_span,
716            "you might have meant to use `;` as the separator",
717            ";",
718            Applicability::MaybeIncorrect,
719        );
720        err.emit();
721        Ok(TyKind::Array(elt_ty, length))
722    }
723
724    fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
725        let and_span = self.prev_token.span;
726        let mut opt_lifetime = self.check_lifetime().then(|| self.expect_lifetime());
727        let (pinned, mut mutbl) = self.parse_pin_and_mut();
728        if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() {
729            // A lifetime is invalid here: it would be part of a bare trait bound, which requires
730            // it to be followed by a plus, but we disallow plus in the pointee type.
731            // So we can handle this case as an error here, and suggest `'a mut`.
732            // If there *is* a plus next though, handling the error later provides better suggestions
733            // (like adding parentheses)
734            if !self.look_ahead(1, |t| t.is_like_plus()) {
735                let lifetime_span = self.token.span;
736                let span = and_span.to(lifetime_span);
737
738                let (suggest_lifetime, snippet) =
739                    if let Ok(lifetime_src) = self.span_to_snippet(lifetime_span) {
740                        (Some(span), lifetime_src)
741                    } else {
742                        (None, String::new())
743                    };
744                self.dcx().emit_err(LifetimeAfterMut { span, suggest_lifetime, snippet });
745
746                opt_lifetime = Some(self.expect_lifetime());
747            }
748        } else if self.token.is_keyword(kw::Dyn)
749            && mutbl == Mutability::Not
750            && self.look_ahead(1, |t| t.is_keyword(kw::Mut))
751        {
752            // We have `&dyn mut ...`, which is invalid and should be `&mut dyn ...`.
753            let span = and_span.to(self.look_ahead(1, |t| t.span));
754            self.dcx().emit_err(DynAfterMut { span });
755
756            // Recovery
757            mutbl = Mutability::Mut;
758            let (dyn_tok, dyn_tok_sp) = (self.token, self.token_spacing);
759            self.bump();
760            self.bump_with((dyn_tok, dyn_tok_sp));
761        }
762        let ty = self.parse_ty_no_plus()?;
763        Ok(match pinned {
764            Pinnedness::Not => TyKind::Ref(opt_lifetime, MutTy { ty, mutbl }),
765            Pinnedness::Pinned => TyKind::PinnedRef(opt_lifetime, MutTy { ty, mutbl }),
766        })
767    }
768
769    /// Parse nothing, mutability or `pin` followed by "explicit" mutability.
770    ///
771    /// ```ebnf
772    /// PinAndMut = "pin" MutOrConst | "mut"
773    /// ```
774    pub(crate) fn parse_pin_and_mut(&mut self) -> (Pinnedness, Mutability) {
775        if self.token.is_keyword(kw::Pin) && self.look_ahead(1, Token::is_mutability) {
776            self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
777            if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
                kw: rustc_span::symbol::kw::Pin,
                token_type: crate::parser::token_type::TokenType::KwMut,
            }) {
    ::core::panicking::panic("assertion failed: self.eat_keyword(exp!(Pin))")
};assert!(self.eat_keyword(exp!(Pin)));
778            let mutbl = self.parse_mut_or_const().unwrap();
779            (Pinnedness::Pinned, mutbl)
780        } else {
781            (Pinnedness::Not, self.parse_mutability())
782        }
783    }
784
785    /// Parses the `typeof(EXPR)` for better diagnostics before returning
786    /// an error type.
787    fn parse_typeof_ty(&mut self, lo: Span) -> PResult<'a, TyKind> {
788        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
789        let _expr = self.parse_expr_anon_const()?;
790        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
791        let span = lo.to(self.prev_token.span);
792        let guar = self
793            .dcx()
794            .struct_span_err(span, "`typeof` is a reserved keyword but unimplemented")
795            .with_note("consider replacing `typeof(...)` with an actual type")
796            .with_code(E0516)
797            .emit_err();
798        Ok(TyKind::Err(guar))
799    }
800
801    fn parse_builtin_ty(&mut self) -> PResult<'a, TyKind> {
802        self.parse_builtin(|this, lo, ident| {
803            Ok(match ident.name {
804                sym::field_of => Some(this.parse_ty_field_of(lo)?),
805                _ => None,
806            })
807        })
808    }
809
810    pub(crate) fn parse_ty_field_of(&mut self, _lo: Span) -> PResult<'a, TyKind> {
811        let container = self.parse_ty()?;
812        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
813
814        let fields = self.parse_floating_field_access()?;
815        let trailing_comma = self.eat_noexpect(&TokenKind::Comma);
816
817        if let Err(mut e) = self.expect_one_of(&[], &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]) {
818            if trailing_comma {
819                e.note("unexpected third argument to field_of");
820            } else {
821                e.note("field_of expects dot-separated field and variant names");
822            }
823            e.emit();
824        }
825
826        // Eat tokens until the macro call ends.
827        if self.may_recover() {
828            while !self.token.kind.is_close_delim_or_eof() {
829                self.bump();
830            }
831        }
832
833        match *fields {
834            [] => Err(self.dcx().struct_span_err(
835                self.token.span,
836                "`field_of!` expects dot-separated field and variant names",
837            )),
838            [field] => Ok(TyKind::FieldOf(container, None, field)),
839            [variant, field] => Ok(TyKind::FieldOf(container, Some(variant), field)),
840            _ => Err(self.dcx().struct_span_err(
841                fields.iter().map(|f| f.span).collect::<Vec<_>>(),
842                "`field_of!` only supports a single field or a variant with a field",
843            )),
844        }
845    }
846
847    /// Parses a function pointer type (`TyKind::FnPtr`).
848    /// ```ignore (illustrative)
849    ///    [unsafe] [extern "ABI"] fn (S) -> T
850    /// //  ^~~~~^          ^~~~^     ^~^    ^
851    /// //    |               |        |     |
852    /// //    |               |        |   Return type
853    /// // Function Style    ABI  Parameter types
854    /// ```
855    /// We actually parse `FnHeader FnDecl`, but we error on `const` and `async` qualifiers.
856    fn parse_ty_fn_ptr(
857        &mut self,
858        lo: Span,
859        mut params: ThinVec<GenericParam>,
860        param_insertion_point: Option<Span>,
861        recover_return_sign: RecoverReturnSign,
862    ) -> PResult<'a, TyKind> {
863        let inherited_vis = rustc_ast::Visibility {
864            span: rustc_span::DUMMY_SP,
865            kind: rustc_ast::VisibilityKind::Inherited,
866        };
867        let span_start = self.token.span;
868        let ast::FnHeader { ext, safety, .. } = self.parse_fn_front_matter(
869            &inherited_vis,
870            Case::Sensitive,
871            FrontMatterParsingMode::FunctionPtrType,
872        )?;
873        if self.may_recover() && self.token == TokenKind::Lt {
874            self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?;
875        }
876        let mode = crate::parser::FnParseMode {
877            req_name: |_, _| false,
878            context: FnContext::FunctionPtrType,
879            req_body: false,
880        };
881        let decl = self.parse_fn_decl(&mode, AllowPlus::No, recover_return_sign)?;
882
883        let decl_span = span_start.to(self.prev_token.span);
884        Ok(TyKind::FnPtr(Box::new(FnPtrTy {
885            ext,
886            safety,
887            generic_params: params,
888            decl,
889            decl_span,
890        })))
891    }
892
893    /// Recover from function pointer types with a generic parameter list (e.g. `fn<'a>(&'a str)`).
894    fn recover_fn_ptr_with_generics(
895        &mut self,
896        lo: Span,
897        params: &mut ThinVec<GenericParam>,
898        param_insertion_point: Option<Span>,
899    ) -> PResult<'a, ()> {
900        let generics = self.parse_generics()?;
901        let arity = generics.params.len();
902
903        let mut lifetimes: ThinVec<_> = generics
904            .params
905            .into_iter()
906            .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ast::GenericParamKind::Lifetime => true,
    _ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime))
907            .collect();
908
909        let sugg = if !lifetimes.is_empty() {
910            let snippet =
911                lifetimes.iter().map(|param| param.ident.as_str()).intersperse(", ").collect();
912
913            let (left, snippet) = if let Some(span) = param_insertion_point {
914                (span, if params.is_empty() { snippet } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", snippet))
    })format!(", {snippet}") })
915            } else {
916                (lo.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("for<{0}> ", snippet))
    })format!("for<{snippet}> "))
917            };
918
919            Some(FnPtrWithGenericsSugg {
920                left,
921                snippet,
922                right: generics.span,
923                arity,
924                for_param_list_exists: param_insertion_point.is_some(),
925            })
926        } else {
927            None
928        };
929
930        self.dcx().emit_err(FnPtrWithGenerics { span: generics.span, sugg });
931        params.append(&mut lifetimes);
932        Ok(())
933    }
934
935    /// Parses an `impl B0 + ... + Bn` type.
936    fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
937        // If we encounter a type like `impl 'a Sized`, suggest `impl 'a + Sized`.
938        if self.token.is_lifetime()
939            && let Some(ident) = self.look_ahead(1, |t| t.non_reserved_ident())
940        {
941            self.dcx().emit_err(diagnostics::MissingPlusBounds {
942                span: self.token.span,
943                hi: self.token.span.shrink_to_hi(),
944                sym: ident.name,
945            });
946        }
947
948        // Always parse bounds greedily for better error recovery.
949        let bounds = self.parse_generic_bounds()?;
950
951        *impl_dyn_multi = bounds.len() > 1 || self.prev_token == TokenKind::Plus;
952
953        Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
954    }
955
956    /// Parse a use-bound aka precise capturing list.
957    ///
958    /// ```ebnf
959    /// UseBound = "use" "<" (PreciseCapture ("," PreciseCapture)* ","?)? ">"
960    /// PreciseCapture = "Self" | Ident | Lifetime
961    /// ```
962    fn parse_use_bound(&mut self, lo: Span, parens: ast::Parens) -> PResult<'a, GenericBound> {
963        self.expect_lt()?;
964        let (args, _, _) = self.parse_seq_to_before_tokens(
965            &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)],
966            &[&TokenKind::Ge, &TokenKind::Shr, &TokenKind::Shr],
967            SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
968            |self_| {
969                if self_.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::SelfUpper,
    token_type: crate::parser::token_type::TokenType::KwSelfUpper,
}exp!(SelfUpper)) {
970                    self_.bump();
971                    Ok(PreciseCapturingArg::Arg(
972                        ast::Path::from_ident(self_.prev_token.ident().unwrap().0),
973                        DUMMY_NODE_ID,
974                    ))
975                } else if self_.check_ident() {
976                    Ok(PreciseCapturingArg::Arg(
977                        ast::Path::from_ident(self_.parse_ident()?),
978                        DUMMY_NODE_ID,
979                    ))
980                } else if self_.check_lifetime() {
981                    Ok(PreciseCapturingArg::Lifetime(self_.expect_lifetime()))
982                } else {
983                    self_.unexpected_any()
984                }
985            },
986        )?;
987        self.expect_gt()?;
988
989        if let ast::Parens::Yes = parens {
990            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
991            self.report_parenthesized_bound(lo, self.prev_token.span, "precise capturing lists");
992        }
993
994        Ok(GenericBound::Use(args, lo.to(self.prev_token.span)))
995    }
996
997    /// Can the current token begin a `dyn`-prefixed trait object type?
998    fn can_begin_dyn_ty(&mut self) -> bool {
999        self.token.is_keyword(kw::Dyn)
1000            && (self.token_uninterpolated_span().at_least_rust_2018()
1001                || self.look_ahead(1, |&t| can_begin_dyn_bound_in_rust_2015(t)))
1002    }
1003
1004    /// Parse a `dyn`-prefixed trait object type.
1005    fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
1006        self.bump(); // `dyn`
1007
1008        // Always parse bounds greedily for better error recovery.
1009        let bounds = self.parse_generic_bounds()?;
1010        *impl_dyn_multi = bounds.len() > 1 || self.prev_token == TokenKind::Plus;
1011
1012        Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn))
1013    }
1014
1015    /// Parse a type that begins with a path.
1016    ///
1017    /// This can be:
1018    /// 1. a type macro, `mac!(...)`,
1019    /// 2. a bare trait object type, `B0 + ... + Bn`,
1020    /// 3. or a path, `path::to::MyType`.
1021    fn parse_path_start_ty(
1022        &mut self,
1023        lo: Span,
1024        allow_plus: AllowPlus,
1025        ty_generics: Option<&Generics>,
1026    ) -> PResult<'a, TyKind> {
1027        // Simple path
1028        let path = self.parse_path_inner(PathStyle::Type, ty_generics)?;
1029        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
1030            // Macro invocation in type position
1031            Ok(TyKind::MacCall(Box::new(MacCall { path, args: self.parse_delim_args()? })))
1032        } else if allow_plus == AllowPlus::Yes && self.check_plus() {
1033            // `Trait1 + Trait2 + 'a`
1034            self.finish_parsing_bare_trait_object_ty(
1035                ThinVec::new(),
1036                path,
1037                lo,
1038                true,
1039                ast::Parens::No,
1040            )
1041        } else {
1042            // Just a type path.
1043            Ok(TyKind::Path(None, path))
1044        }
1045    }
1046
1047    pub(super) fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
1048        self.parse_generic_bounds_common(AllowPlus::Yes)
1049    }
1050
1051    /// Parse generic bounds.
1052    ///
1053    /// Only if `allow_plus` this parses a `+`-separated list of bounds (trailing `+` is admitted).
1054    /// Otherwise, this only parses a single bound or none.
1055    fn parse_generic_bounds_common(&mut self, allow_plus: AllowPlus) -> PResult<'a, GenericBounds> {
1056        let mut bounds = ThinVec::new();
1057
1058        // In addition to looping while we find generic bounds:
1059        // We continue even if we find a keyword. This is necessary for error recovery on,
1060        // for example, `impl fn()`. The only keyword that can go after generic bounds is
1061        // `where`, so stop if it's it.
1062        // We also continue if we find types (not traits), again for error recovery.
1063        while self.can_begin_bound()
1064            || (self.may_recover()
1065                && (self.token.can_begin_type()
1066                    || (self.token.is_reserved_ident() && !self.token.is_keyword(kw::Where))))
1067        {
1068            // Account for `&dyn Trait + dyn Other`.
1069            if self.can_begin_dyn_ty() {
1070                self.bump();
1071                self.dcx().emit_err(InvalidDynKeyword {
1072                    span: self.prev_token.span,
1073                    suggestion: self.prev_token.span.until(self.token.span),
1074                });
1075            }
1076            bounds.push(self.parse_generic_bound()?);
1077            if allow_plus == AllowPlus::No || !self.eat_plus() {
1078                break;
1079            }
1080        }
1081
1082        Ok(bounds)
1083    }
1084
1085    /// Can the current token begin a bound?
1086    fn can_begin_bound(&mut self) -> bool {
1087        // NOTE: Tokens `!`, `~`, `const` & `async` which represent the start of currently unstable
1088        //       trait bound modifiers are intentionally not included in `Token::can_begin_type` to
1089        //       avoid affecting stable macro matching behavior.
1090
1091        self.check_path()
1092            || self.check_lifetime()
1093            || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))
1094            || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Question,
    token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question))
1095            || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Tilde,
    token_type: crate::parser::token_type::TokenType::Tilde,
}exp!(Tilde))
1096            || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::For,
    token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For))
1097            || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))
1098            || self.can_begin_maybe_const_bound()
1099            || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))
1100            || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async))
1101            || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Use,
    token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use))
1102    }
1103
1104    fn can_begin_maybe_const_bound(&mut self) -> bool {
1105        self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBracket,
    token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket))
1106            && self.look_ahead(1, |t| t.is_keyword(kw::Const))
1107            && self.look_ahead(2, |t| *t == token::CloseBracket)
1108    }
1109
1110    /// Parse a bound.
1111    ///
1112    /// ```ebnf
1113    /// Bound = LifetimeBound | UseBound | TraitBound
1114    /// ```
1115    fn parse_generic_bound(&mut self) -> PResult<'a, GenericBound> {
1116        let leading_token = self.prev_token;
1117        let lo = self.token.span;
1118
1119        // We only admit parenthesized *trait* bounds. However, we want to gracefully recover from
1120        // other kinds of parenthesized bounds, so parse the opening parenthesis *here*.
1121        //
1122        // In the future we might want to lift this syntactic restriction and
1123        // introduce "`GenericBound::Paren(Box<GenericBound>)`".
1124        let parens = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) { ast::Parens::Yes } else { ast::Parens::No };
1125
1126        if self.token.is_lifetime() {
1127            self.parse_lifetime_bound(lo, parens)
1128        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Use,
    token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use)) {
1129            self.parse_use_bound(lo, parens)
1130        } else {
1131            self.parse_trait_bound(lo, parens, &leading_token)
1132        }
1133    }
1134
1135    /// Parse a lifetime-bound aka outlives-bound.
1136    ///
1137    /// ```ebnf
1138    /// LifetimeBound = Lifetime
1139    /// ```
1140    fn parse_lifetime_bound(&mut self, lo: Span, parens: ast::Parens) -> PResult<'a, GenericBound> {
1141        let lt = self.expect_lifetime();
1142
1143        if let ast::Parens::Yes = parens {
1144            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1145            self.report_parenthesized_bound(lo, self.prev_token.span, "lifetime bounds");
1146        }
1147
1148        Ok(GenericBound::Outlives(lt))
1149    }
1150
1151    fn report_parenthesized_bound(&self, lo: Span, hi: Span, kind: &str) -> ErrorGuaranteed {
1152        let mut diag =
1153            self.dcx().struct_span_err(lo.to(hi), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} may not be parenthesized",
                kind))
    })format!("{kind} may not be parenthesized"));
1154        diag.multipart_suggestion(
1155            "remove the parentheses",
1156            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(lo, String::new()), (hi, String::new())]))vec![(lo, String::new()), (hi, String::new())],
1157            Applicability::MachineApplicable,
1158        );
1159        diag.emit_err()
1160    }
1161
1162    /// Emits an error if any trait bound modifiers were present.
1163    fn error_lt_bound_with_modifiers(
1164        &self,
1165        modifiers: TraitBoundModifiers,
1166        binder_span: Option<Span>,
1167    ) -> ErrorGuaranteed {
1168        let TraitBoundModifiers { constness, asyncness, polarity } = modifiers;
1169
1170        match constness {
1171            BoundConstness::Never => {}
1172            BoundConstness::Always(span) | BoundConstness::Maybe(span) => {
1173                return self.dcx().emit_err(diagnostics::ModifierLifetime {
1174                    span,
1175                    modifier: constness.as_str(),
1176                });
1177            }
1178        }
1179
1180        match polarity {
1181            BoundPolarity::Positive => {}
1182            BoundPolarity::Negative(span) | BoundPolarity::Maybe(span) => {
1183                return self
1184                    .dcx()
1185                    .emit_err(diagnostics::ModifierLifetime { span, modifier: polarity.as_str() });
1186            }
1187        }
1188
1189        match asyncness {
1190            BoundAsyncness::Normal => {}
1191            BoundAsyncness::Async(span) => {
1192                return self.dcx().emit_err(diagnostics::ModifierLifetime {
1193                    span,
1194                    modifier: asyncness.as_str(),
1195                });
1196            }
1197        }
1198
1199        if let Some(span) = binder_span {
1200            return self
1201                .dcx()
1202                .emit_err(diagnostics::ModifierLifetime { span, modifier: "for<...>" });
1203        }
1204
1205        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("lifetime bound intercepted in `parse_generic_ty_bound` but no modifiers?")));
}unreachable!("lifetime bound intercepted in `parse_generic_ty_bound` but no modifiers?")
1206    }
1207
1208    /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `[const] Trait`.
1209    ///
1210    /// If no modifiers are present, this does not consume any tokens.
1211    ///
1212    /// ```ebnf
1213    /// Constness = ("const" | "[" "const" "]")?
1214    /// Asyncness = "async"?
1215    /// Polarity = ("?" | "!")?
1216    /// ```
1217    ///
1218    /// See `parse_trait_bound` for more context.
1219    fn parse_trait_bound_modifiers(&mut self) -> PResult<'a, TraitBoundModifiers> {
1220        let modifier_lo = self.token.span;
1221        let constness = self.parse_bound_constness()?;
1222
1223        let asyncness = if self.token_uninterpolated_span().at_least_rust_2018()
1224            && self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async))
1225        {
1226            self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
1227            BoundAsyncness::Async(self.prev_token.span)
1228        } else if self.may_recover()
1229            && self.token_uninterpolated_span().is_rust_2015()
1230            && self.is_kw_followed_by_ident(kw::Async)
1231        {
1232            self.bump(); // eat `async`
1233            self.dcx().emit_err(diagnostics::AsyncBoundModifierIn2015 {
1234                span: self.prev_token.span,
1235                help: HelpUseLatestEdition::new(),
1236            });
1237            self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
1238            BoundAsyncness::Async(self.prev_token.span)
1239        } else {
1240            BoundAsyncness::Normal
1241        };
1242        let modifier_hi = self.prev_token.span;
1243
1244        let polarity = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Question,
    token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question)) {
1245            BoundPolarity::Maybe(self.prev_token.span)
1246        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
1247            self.psess.gated_spans.gate(sym::negative_bounds, self.prev_token.span);
1248            BoundPolarity::Negative(self.prev_token.span)
1249        } else {
1250            BoundPolarity::Positive
1251        };
1252
1253        // Enforce the mutual-exclusivity of `const`/`async` and `?`/`!`.
1254        match polarity {
1255            BoundPolarity::Positive => {
1256                // All trait bound modifiers allowed to combine with positive polarity
1257            }
1258            BoundPolarity::Maybe(polarity_span) | BoundPolarity::Negative(polarity_span) => {
1259                match (asyncness, constness) {
1260                    (BoundAsyncness::Normal, BoundConstness::Never) => {
1261                        // Ok, no modifiers.
1262                    }
1263                    (_, _) => {
1264                        let constness = constness.as_str();
1265                        let asyncness = asyncness.as_str();
1266                        let glue =
1267                            if !constness.is_empty() && !asyncness.is_empty() { " " } else { "" };
1268                        let modifiers_concatenated = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}", constness, glue,
                asyncness))
    })format!("{constness}{glue}{asyncness}");
1269                        self.dcx().emit_err(diagnostics::PolarityAndModifiers {
1270                            polarity_span,
1271                            polarity: polarity.as_str(),
1272                            modifiers_span: modifier_lo.to(modifier_hi),
1273                            modifiers_concatenated,
1274                        });
1275                    }
1276                }
1277            }
1278        }
1279
1280        Ok(TraitBoundModifiers { constness, asyncness, polarity })
1281    }
1282
1283    pub fn parse_bound_constness(&mut self) -> PResult<'a, BoundConstness> {
1284        // FIXME(const_trait_impl): remove `~const` parser support once bootstrap has the new syntax
1285        // in rustfmt
1286        Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Tilde,
    token_type: crate::parser::token_type::TokenType::Tilde,
}exp!(Tilde)) {
1287            let tilde = self.prev_token.span;
1288            self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1289            let span = tilde.to(self.prev_token.span);
1290            self.psess.gated_spans.gate(sym::const_trait_impl, span);
1291            BoundConstness::Maybe(span)
1292        } else if self.can_begin_maybe_const_bound() {
1293            let start = self.token.span;
1294            self.bump();
1295            self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const)).unwrap();
1296            self.bump();
1297            let span = start.to(self.prev_token.span);
1298            self.psess.gated_spans.gate(sym::const_trait_impl, span);
1299            BoundConstness::Maybe(span)
1300        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const)) {
1301            self.psess.gated_spans.gate(sym::const_trait_impl, self.prev_token.span);
1302            BoundConstness::Always(self.prev_token.span)
1303        } else {
1304            BoundConstness::Never
1305        })
1306    }
1307
1308    /// Parse a trait bound.
1309    ///
1310    /// ```ebnf
1311    /// TraitBound = BareTraitBound | "(" BareTraitBound ")"
1312    /// BareTraitBound =
1313    ///     (HigherRankedBinder Constness Asyncness | Polarity)
1314    ///     TypePath
1315    /// ```
1316    fn parse_trait_bound(
1317        &mut self,
1318        lo: Span,
1319        parens: ast::Parens,
1320        leading_token: &Token,
1321    ) -> PResult<'a, GenericBound> {
1322        let (mut bound_vars, binder_span) = self.parse_higher_ranked_binder()?;
1323
1324        let modifiers_lo = self.token.span;
1325        let modifiers = self.parse_trait_bound_modifiers()?;
1326        let modifiers_span = modifiers_lo.to(self.prev_token.span);
1327
1328        if let Some(binder_span) = binder_span {
1329            match modifiers.polarity {
1330                BoundPolarity::Negative(polarity_span) | BoundPolarity::Maybe(polarity_span) => {
1331                    self.dcx().emit_err(diagnostics::BinderAndPolarity {
1332                        binder_span,
1333                        polarity_span,
1334                        polarity: modifiers.polarity.as_str(),
1335                    });
1336                }
1337                BoundPolarity::Positive => {}
1338            }
1339        }
1340
1341        // Recover erroneous lifetime bound with modifiers or binder.
1342        // e.g. `T: for<'a> 'a` or `T: [const] 'a`.
1343        if self.token.is_lifetime() {
1344            let _: ErrorGuaranteed = self.error_lt_bound_with_modifiers(modifiers, binder_span);
1345            return self.parse_lifetime_bound(lo, parens);
1346        }
1347
1348        if let (more_bound_vars, Some(binder_span)) = self.parse_higher_ranked_binder()? {
1349            bound_vars.extend(more_bound_vars);
1350            self.dcx().emit_err(diagnostics::BinderBeforeModifiers { binder_span, modifiers_span });
1351        }
1352
1353        let mut path = if self.token.is_keyword(kw::Fn)
1354            && self.look_ahead(1, |t| *t == TokenKind::OpenParen)
1355            && let Some(path) = self.recover_path_from_fn()
1356        {
1357            path
1358        } else if !self.token.is_path_start() && self.token.can_begin_type() {
1359            let ty = self.parse_ty_no_plus()?;
1360            // Instead of finding a path (a trait), we found a type.
1361            let mut err = self.dcx().struct_span_err(ty.span, "expected a trait, found type");
1362
1363            // If we can recover, try to extract a path from the type. Note
1364            // that we do not use the try operator when parsing the type because
1365            // if it fails then we get a parser error which we don't want (we're trying
1366            // to recover from errors, not make more).
1367            let path = if self.may_recover() {
1368                let (span, message, sugg, path, applicability) = match &ty.kind {
1369                    TyKind::Ptr(..) | TyKind::Ref(..)
1370                        if let TyKind::Path(_, path) = &ty.peel_refs().kind =>
1371                    {
1372                        (
1373                            ty.span.until(path.span),
1374                            "consider removing the indirection",
1375                            "",
1376                            path,
1377                            Applicability::MaybeIncorrect,
1378                        )
1379                    }
1380                    TyKind::ImplTrait(_, bounds)
1381                        if let [GenericBound::Trait(tr, ..), ..] = bounds.as_slice() =>
1382                    {
1383                        (
1384                            ty.span.until(tr.span),
1385                            "use the trait bounds directly",
1386                            "",
1387                            &tr.trait_ref.path,
1388                            Applicability::MachineApplicable,
1389                        )
1390                    }
1391                    _ => return Err(err),
1392                };
1393
1394                err.span_suggestion_verbose(span, message, sugg, applicability);
1395
1396                path.clone()
1397            } else {
1398                return Err(err);
1399            };
1400
1401            err.emit();
1402
1403            path
1404        } else {
1405            self.parse_path(PathStyle::Type)?
1406        };
1407
1408        if self.may_recover() && self.token == TokenKind::OpenParen {
1409            self.recover_fn_trait_with_lifetime_params(&mut path, &mut bound_vars)?;
1410        }
1411
1412        if let ast::Parens::Yes = parens {
1413            // Someone has written something like `&dyn (Trait + Other)`. The correct code
1414            // would be `&(dyn Trait + Other)`
1415            if self.token.is_like_plus() && leading_token.is_keyword(kw::Dyn) {
1416                self.eat_plus();
1417                self.parse_generic_bounds()?;
1418                self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1419
1420                self.dcx().emit_err(diagnostics::IncorrectParensTraitBounds {
1421                    span: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [lo, self.prev_token.span]))vec![lo, self.prev_token.span],
1422                    sugg: diagnostics::IncorrectParensTraitBoundsSugg {
1423                        wrong_span: leading_token.span.shrink_to_hi().to(lo),
1424                        new_span: leading_token.span.shrink_to_lo(),
1425                    },
1426                });
1427            } else {
1428                self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1429            }
1430        }
1431
1432        let poly_trait =
1433            PolyTraitRef::new(bound_vars, path, modifiers, lo.to(self.prev_token.span), parens);
1434        Ok(GenericBound::Trait(poly_trait))
1435    }
1436
1437    // recovers a `Fn(..)` parenthesized-style path from `fn(..)`
1438    fn recover_path_from_fn(&mut self) -> Option<ast::Path> {
1439        let fn_token_span = self.token.span;
1440        self.bump();
1441        let args_lo = self.token.span;
1442        let snapshot = self.create_snapshot_for_diagnostic();
1443        let mode =
1444            FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false };
1445        match self.parse_fn_decl(&mode, AllowPlus::No, RecoverReturnSign::OnlyFatArrow) {
1446            Ok(decl) => {
1447                self.dcx().emit_err(ExpectedFnPathFoundFnKeyword { fn_token_span });
1448                Some(ast::Path {
1449                    span: fn_token_span.to(self.prev_token.span),
1450                    segments: {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(ast::PathSegment {
            ident: Ident::new(sym::Fn, fn_token_span),
            id: DUMMY_NODE_ID,
            args: Some(Box::new(ast::GenericArgs::Parenthesized(ast::ParenthesizedArgs {
                            span: args_lo.to(self.prev_token.span),
                            inputs: decl.inputs.iter().map(|a| a.clone()).collect(),
                            inputs_span: args_lo.until(decl.output.span()),
                            output: decl.output.clone(),
                        }))),
        });
    vec
}thin_vec![ast::PathSegment {
1451                        ident: Ident::new(sym::Fn, fn_token_span),
1452                        id: DUMMY_NODE_ID,
1453                        args: Some(Box::new(ast::GenericArgs::Parenthesized(
1454                            ast::ParenthesizedArgs {
1455                                span: args_lo.to(self.prev_token.span),
1456                                inputs: decl.inputs.iter().map(|a| a.clone()).collect(),
1457                                inputs_span: args_lo.until(decl.output.span()),
1458                                output: decl.output.clone(),
1459                            }
1460                        ))),
1461                    }],
1462                })
1463            }
1464            Err(diag) => {
1465                diag.cancel();
1466                self.restore_snapshot(snapshot);
1467                None
1468            }
1469        }
1470    }
1471
1472    /// Parse an optional higher-ranked binder.
1473    ///
1474    /// ```ebnf
1475    /// HigherRankedBinder = ("for" "<" GenericParams ">")?
1476    /// ```
1477    pub(super) fn parse_higher_ranked_binder(
1478        &mut self,
1479    ) -> PResult<'a, (ThinVec<GenericParam>, Option<Span>)> {
1480        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::For,
    token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For)) {
1481            let lo = self.token.span;
1482            self.expect_lt()?;
1483            let params = self.parse_generic_params()?;
1484            self.expect_gt()?;
1485            // We rely on AST validation to rule out invalid cases: There must not be
1486            // type or const parameters, and parameters must not have bounds.
1487            Ok((params, Some(lo.to(self.prev_token.span))))
1488        } else {
1489            Ok((ThinVec::new(), None))
1490        }
1491    }
1492
1493    /// Recover from `Fn`-family traits (Fn, FnMut, FnOnce) with lifetime arguments
1494    /// (e.g. `FnOnce<'a>(&'a str) -> bool`). Up to generic arguments have already
1495    /// been eaten.
1496    fn recover_fn_trait_with_lifetime_params(
1497        &mut self,
1498        fn_path: &mut ast::Path,
1499        lifetime_defs: &mut ThinVec<GenericParam>,
1500    ) -> PResult<'a, ()> {
1501        let fn_path_segment = fn_path.segments.last_mut().unwrap();
1502        let generic_args = if let Some(p_args) = &fn_path_segment.args {
1503            *p_args.clone()
1504        } else {
1505            // Normally it wouldn't come here because the upstream should have parsed
1506            // generic parameters (otherwise it's impossible to call this function).
1507            return Ok(());
1508        };
1509        let lifetimes =
1510            if let ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { span: _, args }) =
1511                &generic_args
1512            {
1513                args.into_iter()
1514                    .filter_map(|arg| {
1515                        if let ast::AngleBracketedArg::Arg(generic_arg) = arg
1516                            && let ast::GenericArg::Lifetime(lifetime) = generic_arg
1517                        {
1518                            Some(lifetime)
1519                        } else {
1520                            None
1521                        }
1522                    })
1523                    .collect()
1524            } else {
1525                Vec::new()
1526            };
1527        // Only try to recover if the trait has lifetime params.
1528        if lifetimes.is_empty() {
1529            return Ok(());
1530        }
1531
1532        let snapshot = if self.parsing_generics {
1533            // The snapshot is only relevant if we're parsing the generics of an `fn` to avoid
1534            // incorrect recovery.
1535            Some(self.create_snapshot_for_diagnostic())
1536        } else {
1537            None
1538        };
1539        // Parse `(T, U) -> R`.
1540        let inputs_lo = self.token.span;
1541        let mode =
1542            FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false };
1543        let inputs = match self.parse_fn_params(&mode) {
1544            Ok(params) => params,
1545            Err(err) => {
1546                if let Some(snapshot) = snapshot {
1547                    self.restore_snapshot(snapshot);
1548                    err.cancel();
1549                    return Ok(());
1550                } else {
1551                    return Err(err);
1552                }
1553            }
1554        };
1555        let inputs_span = inputs_lo.to(self.prev_token.span);
1556        let output = match self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)
1557        {
1558            Ok(output) => output,
1559            Err(err) => {
1560                if let Some(snapshot) = snapshot {
1561                    self.restore_snapshot(snapshot);
1562                    err.cancel();
1563                    return Ok(());
1564                } else {
1565                    return Err(err);
1566                }
1567            }
1568        };
1569        let args = ast::ParenthesizedArgs {
1570            span: fn_path_segment.span().to(self.prev_token.span),
1571            inputs,
1572            inputs_span,
1573            output,
1574        }
1575        .into();
1576
1577        if let Some(snapshot) = snapshot
1578            && ![token::Comma, token::Gt, token::Plus].contains(&self.token.kind)
1579        {
1580            // We would expect another bound or the end of type params by now. Most likely we've
1581            // encountered a `(` *not* representing `Trait()`, but rather the start of the `fn`'s
1582            // argument list where the generic param list wasn't properly closed.
1583            self.restore_snapshot(snapshot);
1584            return Ok(());
1585        }
1586
1587        *fn_path_segment = ast::PathSegment {
1588            ident: fn_path_segment.ident,
1589            args: Some(args),
1590            id: ast::DUMMY_NODE_ID,
1591        };
1592
1593        // Convert parsed `<'a>` in `Fn<'a>` into `for<'a>`.
1594        let mut generic_params = lifetimes
1595            .iter()
1596            .map(|lt| GenericParam {
1597                id: lt.id,
1598                ident: lt.ident,
1599                attrs: ast::AttrVec::new(),
1600                bounds: ThinVec::new(),
1601                is_placeholder: false,
1602                kind: ast::GenericParamKind::Lifetime,
1603                colon_span: None,
1604            })
1605            .collect::<ThinVec<GenericParam>>();
1606        lifetime_defs.append(&mut generic_params);
1607
1608        let generic_args_span = generic_args.span();
1609        let snippet = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("for<{0}> ",
                lifetimes.iter().map(|lt|
                                lt.ident.as_str()).intersperse(", ").collect::<String>()))
    })format!(
1610            "for<{}> ",
1611            lifetimes.iter().map(|lt| lt.ident.as_str()).intersperse(", ").collect::<String>(),
1612        );
1613        let before_fn_path = fn_path.span.shrink_to_lo();
1614        self.dcx()
1615            .struct_span_err(generic_args_span, "`Fn` traits cannot take lifetime parameters")
1616            .with_multipart_suggestion(
1617                "consider using a higher-ranked trait bound instead",
1618                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(generic_args_span, "".to_owned()), (before_fn_path, snippet)]))vec![(generic_args_span, "".to_owned()), (before_fn_path, snippet)],
1619                Applicability::MaybeIncorrect,
1620            )
1621            .emit();
1622        Ok(())
1623    }
1624
1625    pub(super) fn check_lifetime(&mut self) -> bool {
1626        self.expected_token_types.insert(TokenType::Lifetime);
1627        self.token.is_lifetime()
1628    }
1629
1630    /// Parses a single lifetime `'a` or panics.
1631    pub(super) fn expect_lifetime(&mut self) -> Lifetime {
1632        if let Some((ident, kind)) = self.token.lifetime() {
1633            if kind == IdentKind::Normal && ident.without_first_quote().is_reserved_lifetime() {
1634                self.dcx().emit_err(diagnostics::KeywordLifetime { span: ident.span });
1635            }
1636
1637            self.bump();
1638            Lifetime { ident, id: ast::DUMMY_NODE_ID }
1639        } else {
1640            self.dcx().span_bug(self.token.span, "not a lifetime")
1641        }
1642    }
1643
1644    pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> Box<Ty> {
1645        Box::new(Ty { kind, span, id: ast::DUMMY_NODE_ID })
1646    }
1647}