Skip to main content

rustc_parse/parser/
ty.rs

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