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.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Underscore,
    token_type: crate::parser::token_type::TokenType::KwUnderscore,
}exp!(Underscore)) {
333            // A type to be inferred `_`
334            TyKind::Infer
335        } else if self.check_fn_front_matter(false, Case::Sensitive) {
336            // Function pointer type
337            self.parse_ty_fn_ptr(lo, ThinVec::new(), None, recover_return_sign)?
338        } 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)) {
339            // Function pointer type or bound list (trait object type) starting with a poly-trait.
340            //   `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
341            //   `for<'lt> Trait1<'lt> + Trait2 + 'a`
342            let (bound_vars, _) = self.parse_higher_ranked_binder()?;
343            if self.check_fn_front_matter(false, Case::Sensitive) {
344                self.parse_ty_fn_ptr(
345                    lo,
346                    bound_vars,
347                    Some(self.prev_token.span.shrink_to_lo()),
348                    recover_return_sign,
349                )?
350            } else {
351                // Try to recover `for<'a> dyn Trait` or `for<'a> impl Trait`.
352                if self.may_recover()
353                    && (self.eat_keyword_noexpect(kw::Impl) || self.eat_keyword_noexpect(kw::Dyn))
354                {
355                    let kw = self.prev_token.ident().unwrap().0;
356                    let removal_span = kw.span.with_hi(self.token.span.lo());
357                    let path = self.parse_path(PathStyle::Type)?;
358                    let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
359                    let kind = self.parse_remaining_bounds_path(
360                        bound_vars,
361                        path,
362                        lo,
363                        parse_plus,
364                        ast::Parens::No,
365                    )?;
366                    let err = self.dcx().create_err(errors::TransposeDynOrImpl {
367                        span: kw.span,
368                        kw: kw.name.as_str(),
369                        sugg: errors::TransposeDynOrImplSugg {
370                            removal_span,
371                            insertion_span: lo.shrink_to_lo(),
372                            kw: kw.name.as_str(),
373                        },
374                    });
375
376                    // Take the parsed bare trait object and turn it either
377                    // into a `dyn` object or an `impl Trait`.
378                    let kind = match (kind, kw.name) {
379                        (TyKind::TraitObject(bounds, _), kw::Dyn) => {
380                            TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
381                        }
382                        (TyKind::TraitObject(bounds, _), kw::Impl) => {
383                            TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
384                        }
385                        _ => return Err(err),
386                    };
387                    err.emit();
388                    kind
389                } else {
390                    let path = self.parse_path(PathStyle::Type)?;
391                    let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
392                    self.parse_remaining_bounds_path(
393                        bound_vars,
394                        path,
395                        lo,
396                        parse_plus,
397                        ast::Parens::No,
398                    )?
399                }
400            }
401        } 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)) {
402            self.parse_impl_ty(&mut impl_dyn_multi)?
403        } else if self.is_explicit_dyn_type() {
404            self.parse_dyn_ty(&mut impl_dyn_multi)?
405        } else if self.eat_lt() {
406            // Qualified path
407            let (qself, path) = self.parse_qpath(PathStyle::Type)?;
408            TyKind::Path(Some(qself), path)
409        } else if (self.token.is_keyword(kw::Const) || self.token.is_keyword(kw::Mut))
410            && self.look_ahead(1, |t| *t == token::Star)
411        {
412            self.parse_ty_c_style_pointer()?
413        } else if self.check_path() {
414            self.parse_path_start_ty(lo, allow_plus, ty_generics)?
415        } else if self.can_begin_bound() {
416            self.parse_bare_trait_object(lo, allow_plus)?
417        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::DotDotDot,
    token_type: crate::parser::token_type::TokenType::DotDotDot,
}exp!(DotDotDot)) {
418            match allow_c_variadic {
419                AllowCVariadic::Yes => TyKind::CVarArgs,
420                AllowCVariadic::No => {
421                    // FIXME(c_variadic): Should we just allow `...` syntactically
422                    // anywhere in a type and use semantic restrictions instead?
423                    // NOTE: This may regress certain MBE calls if done incorrectly.
424                    let guar = self.dcx().emit_err(NestedCVariadicType { span: lo });
425                    TyKind::Err(guar)
426                }
427            }
428        } 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))
429            && self.look_ahead(1, |tok| tok.kind == token::Lt)
430        {
431            self.parse_unsafe_binder_ty()?
432        } else {
433            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));
434            let mut err = self.dcx().struct_span_err(lo, msg);
435            err.span_label(lo, "expected type");
436            return Err(err);
437        };
438
439        let span = lo.to(self.prev_token.span);
440        let mut ty = self.mk_ty(span, kind);
441
442        // Try to recover from use of `+` with incorrect priority.
443        match allow_plus {
444            AllowPlus::Yes => self.maybe_recover_from_bad_type_plus(&ty)?,
445            AllowPlus::No => self.maybe_report_ambiguous_plus(impl_dyn_multi, &ty),
446        }
447        if let RecoverQuestionMark::Yes = recover_question_mark {
448            ty = self.maybe_recover_from_question_mark(ty);
449        }
450        if allow_qpath_recovery { self.maybe_recover_from_bad_qpath(ty) } else { Ok(ty) }
451    }
452
453    fn parse_unsafe_binder_ty(&mut self) -> PResult<'a, TyKind> {
454        let lo = self.token.span;
455        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)));
456        self.expect_lt()?;
457        let generic_params = self.parse_generic_params()?;
458        self.expect_gt()?;
459        let inner_ty = self.parse_ty()?;
460        let span = lo.to(self.prev_token.span);
461        self.psess.gated_spans.gate(sym::unsafe_binders, span);
462
463        Ok(TyKind::UnsafeBinder(Box::new(UnsafeBinderTy { generic_params, inner_ty })))
464    }
465
466    /// Parses either:
467    /// - `(TYPE)`, a parenthesized type.
468    /// - `(TYPE,)`, a tuple with a single field of type TYPE.
469    fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
470        let mut trailing_plus = false;
471        let (ts, trailing) = self.parse_paren_comma_seq(|p| {
472            let ty = p.parse_ty()?;
473            trailing_plus = p.prev_token == TokenKind::Plus;
474            Ok(ty)
475        })?;
476
477        if ts.len() == 1 && #[allow(non_exhaustive_omitted_patterns)] match trailing {
    Trailing::No => true,
    _ => false,
}matches!(trailing, Trailing::No) {
478            let ty = ts.into_iter().next().unwrap();
479            let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
480            match ty.kind {
481                // `"(" BareTraitBound ")" "+" Bound "+" ...`.
482                TyKind::Path(None, path) if maybe_bounds => self.parse_remaining_bounds_path(
483                    ThinVec::new(),
484                    path,
485                    lo,
486                    true,
487                    ast::Parens::Yes,
488                ),
489                // For `('a) + …`, we know that `'a` in type position already lead to an error being
490                // emitted. To reduce output, let's indirectly suppress E0178 (bad `+` in type) and
491                // other irrelevant consequential errors.
492                TyKind::TraitObject(bounds, TraitObjectSyntax::None)
493                    if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
494                {
495                    self.parse_remaining_bounds(bounds, true)
496                }
497                // `(TYPE)`
498                _ => Ok(TyKind::Paren(ty)),
499            }
500        } else {
501            Ok(TyKind::Tup(ts))
502        }
503    }
504
505    fn parse_bare_trait_object(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
506        // A lifetime only begins a bare trait object type if it is followed by `+`!
507        if self.token.is_lifetime() && !self.look_ahead(1, |t| t.is_like_plus()) {
508            // In Rust 2021 and beyond, we assume that the user didn't intend to write a bare trait
509            // object type with a leading lifetime bound since that seems very unlikely given the
510            // fact that `dyn`-less trait objects are *semantically* invalid.
511            if self.psess.edition.at_least_rust_2021() {
512                let lt = self.expect_lifetime();
513                let mut err = self.dcx().struct_span_err(lo, "expected type, found lifetime");
514                err.span_label(lo, "expected type");
515                return Ok(match self.maybe_recover_ref_ty_no_leading_ampersand(lt, lo, err) {
516                    Ok(ref_ty) => ref_ty,
517                    Err(err) => TyKind::Err(err.emit()),
518                });
519            }
520
521            self.dcx().emit_err(NeedPlusAfterTraitObjectLifetime {
522                span: lo,
523                suggestion: lo.shrink_to_hi(),
524            });
525        }
526        Ok(TyKind::TraitObject(
527            self.parse_generic_bounds_common(allow_plus)?,
528            TraitObjectSyntax::None,
529        ))
530    }
531
532    fn maybe_recover_ref_ty_no_leading_ampersand<'cx>(
533        &mut self,
534        lt: Lifetime,
535        lo: Span,
536        mut err: Diag<'cx>,
537    ) -> Result<TyKind, Diag<'cx>> {
538        if !self.may_recover() {
539            return Err(err);
540        }
541        let snapshot = self.create_snapshot_for_diagnostic();
542        let mutbl = self.parse_mutability();
543        match self.parse_ty_no_plus() {
544            Ok(ty) => {
545                err.span_suggestion_verbose(
546                    lo.shrink_to_lo(),
547                    "you might have meant to write a reference type here",
548                    "&",
549                    Applicability::MaybeIncorrect,
550                );
551                err.emit();
552                Ok(TyKind::Ref(Some(lt), MutTy { ty, mutbl }))
553            }
554            Err(diag) => {
555                diag.cancel();
556                self.restore_snapshot(snapshot);
557                Err(err)
558            }
559        }
560    }
561
562    fn parse_remaining_bounds_path(
563        &mut self,
564        generic_params: ThinVec<GenericParam>,
565        path: ast::Path,
566        lo: Span,
567        parse_plus: bool,
568        parens: ast::Parens,
569    ) -> PResult<'a, TyKind> {
570        let poly_trait_ref = PolyTraitRef::new(
571            generic_params,
572            path,
573            TraitBoundModifiers::NONE,
574            lo.to(self.prev_token.span),
575            parens,
576        );
577        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)];
578        self.parse_remaining_bounds(bounds, parse_plus)
579    }
580
581    /// Parse the remainder of a bare trait object type given an already parsed list.
582    fn parse_remaining_bounds(
583        &mut self,
584        mut bounds: GenericBounds,
585        plus: bool,
586    ) -> PResult<'a, TyKind> {
587        if plus {
588            self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
589            bounds.append(&mut self.parse_generic_bounds()?);
590        }
591        Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
592    }
593
594    /// Parses a raw pointer with a C-style typo
595    fn parse_ty_c_style_pointer(&mut self) -> PResult<'a, TyKind> {
596        let kw_span = self.token.span;
597        let mutbl = self.parse_const_or_mut();
598
599        if let Some(mutbl) = mutbl
600            && self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Star,
    token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star))
601        {
602            let star_span = self.prev_token.span;
603
604            let mutability = match mutbl {
605                Mutability::Not => "const",
606                Mutability::Mut => "mut",
607            };
608
609            let ty = self.parse_ty_no_question_mark_recover()?;
610
611            self.dcx()
612                .struct_span_err(
613                    kw_span,
614                    ::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`"),
615                )
616                .with_multipart_suggestion(
617                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("put the `*` before `{0}`",
                mutability))
    })format!("put the `*` before `{mutability}`"),
618                    ::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())],
619                    Applicability::MachineApplicable,
620                )
621                .emit();
622
623            return Ok(TyKind::Ptr(MutTy { ty, mutbl }));
624        }
625        // This is unreachable because we always get into if above and return from it
626        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("this could never happen")));
}unreachable!("this could never happen")
627    }
628
629    /// Parses a raw pointer type: `*[const | mut] $type`.
630    fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
631        let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
632            let span = self.prev_token.span;
633            self.dcx().emit_err(ExpectedMutOrConstInRawPointerType {
634                span,
635                after_asterisk: span.shrink_to_hi(),
636            });
637            Mutability::Not
638        });
639        let ty = self.parse_ty_no_plus()?;
640        Ok(TyKind::Ptr(MutTy { ty, mutbl }))
641    }
642
643    /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
644    /// The opening `[` bracket is already eaten.
645    fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
646        let elt_ty = match self.parse_ty() {
647            Ok(ty) => ty,
648            Err(err)
649                if self.look_ahead(1, |t| *t == token::CloseBracket)
650                    | self.look_ahead(1, |t| *t == token::Semi) =>
651            {
652                // Recover from `[LIT; EXPR]` and `[LIT]`
653                self.bump();
654                let guar = err.emit();
655                self.mk_ty(self.prev_token.span, TyKind::Err(guar))
656            }
657            Err(err) => return Err(err),
658        };
659
660        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)) {
661            let mut length = self.parse_expr_anon_const(|_, _| MgcaDisambiguation::Direct)?;
662
663            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)) {
664                // Try to recover from `X<Y, ...>` when `X::<Y, ...>` works
665                self.check_mistyped_turbofish_with_multiple_type_params(e, &mut length.value)?;
666                self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket))?;
667            }
668            TyKind::Array(elt_ty, length)
669        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket)) {
670            TyKind::Slice(elt_ty)
671        } else {
672            self.maybe_recover_array_ty_without_semi(elt_ty)?
673        };
674
675        Ok(ty)
676    }
677
678    /// Recover from malformed array type syntax.
679    ///
680    /// This method attempts to recover from cases like:
681    /// - `[u8, 5]` → suggests using `;`, return a Array type
682    /// - `[u8 5]` → suggests using `;`, return a Array type
683    /// Consider to add more cases in the future.
684    fn maybe_recover_array_ty_without_semi(&mut self, elt_ty: Box<Ty>) -> PResult<'a, TyKind> {
685        let span = self.token.span;
686        let token_descr = super::token_descr(&self.token);
687        let mut err =
688            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));
689        err.span_label(span, "expected `;` or `]`");
690
691        // If we cannot recover, return the error immediately.
692        if !self.may_recover() {
693            return Err(err);
694        }
695
696        let snapshot = self.create_snapshot_for_diagnostic();
697
698        // Consume common erroneous separators.
699        let hi = self.prev_token.span.hi();
700        _ = 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));
701        let suggestion_span = self.prev_token.span.with_lo(hi);
702
703        // FIXME(mgca): recovery is broken for `const {` args
704        // we first try to parse pattern like `[u8 5]`
705        let length = match self.parse_expr_anon_const(|_, _| MgcaDisambiguation::Direct) {
706            Ok(length) => length,
707            Err(e) => {
708                e.cancel();
709                self.restore_snapshot(snapshot);
710                return Err(err);
711            }
712        };
713
714        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)) {
715            e.cancel();
716            self.restore_snapshot(snapshot);
717            return Err(err);
718        }
719
720        err.span_suggestion_verbose(
721            suggestion_span,
722            "you might have meant to use `;` as the separator",
723            ";",
724            Applicability::MaybeIncorrect,
725        );
726        err.emit();
727        Ok(TyKind::Array(elt_ty, length))
728    }
729
730    fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
731        let and_span = self.prev_token.span;
732        let mut opt_lifetime = self.check_lifetime().then(|| self.expect_lifetime());
733        let (pinned, mut mutbl) = self.parse_pin_and_mut();
734        if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() {
735            // A lifetime is invalid here: it would be part of a bare trait bound, which requires
736            // it to be followed by a plus, but we disallow plus in the pointee type.
737            // So we can handle this case as an error here, and suggest `'a mut`.
738            // If there *is* a plus next though, handling the error later provides better suggestions
739            // (like adding parentheses)
740            if !self.look_ahead(1, |t| t.is_like_plus()) {
741                let lifetime_span = self.token.span;
742                let span = and_span.to(lifetime_span);
743
744                let (suggest_lifetime, snippet) =
745                    if let Ok(lifetime_src) = self.span_to_snippet(lifetime_span) {
746                        (Some(span), lifetime_src)
747                    } else {
748                        (None, String::new())
749                    };
750                self.dcx().emit_err(LifetimeAfterMut { span, suggest_lifetime, snippet });
751
752                opt_lifetime = Some(self.expect_lifetime());
753            }
754        } else if self.token.is_keyword(kw::Dyn)
755            && mutbl == Mutability::Not
756            && self.look_ahead(1, |t| t.is_keyword(kw::Mut))
757        {
758            // We have `&dyn mut ...`, which is invalid and should be `&mut dyn ...`.
759            let span = and_span.to(self.look_ahead(1, |t| t.span));
760            self.dcx().emit_err(DynAfterMut { span });
761
762            // Recovery
763            mutbl = Mutability::Mut;
764            let (dyn_tok, dyn_tok_sp) = (self.token, self.token_spacing);
765            self.bump();
766            self.bump_with((dyn_tok, dyn_tok_sp));
767        }
768        let ty = self.parse_ty_no_plus()?;
769        Ok(match pinned {
770            Pinnedness::Not => TyKind::Ref(opt_lifetime, MutTy { ty, mutbl }),
771            Pinnedness::Pinned => TyKind::PinnedRef(opt_lifetime, MutTy { ty, mutbl }),
772        })
773    }
774
775    /// Parses `pin` and `mut` annotations on references, patterns, or borrow modifiers.
776    ///
777    /// It must be either `pin const`, `pin mut`, `mut`, or nothing (immutable).
778    pub(crate) fn parse_pin_and_mut(&mut self) -> (Pinnedness, Mutability) {
779        if self.token.is_ident_named(sym::pin) && self.look_ahead(1, Token::is_mutability) {
780            self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
781            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)));
782            let mutbl = self.parse_const_or_mut().unwrap();
783            (Pinnedness::Pinned, mutbl)
784        } else {
785            (Pinnedness::Not, self.parse_mutability())
786        }
787    }
788
789    /// Parses the `typeof(EXPR)` for better diagnostics before returning
790    /// an error type.
791    fn parse_typeof_ty(&mut self, lo: Span) -> PResult<'a, TyKind> {
792        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
793        let _expr = self.parse_expr_anon_const(|_, _| MgcaDisambiguation::AnonConst)?;
794        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
795        let span = lo.to(self.prev_token.span);
796        let guar = self
797            .dcx()
798            .struct_span_err(span, "`typeof` is a reserved keyword but unimplemented")
799            .with_note("consider replacing `typeof(...)` with an actual type")
800            .with_code(E0516)
801            .emit();
802        Ok(TyKind::Err(guar))
803    }
804
805    /// Parses a function pointer type (`TyKind::FnPtr`).
806    /// ```ignore (illustrative)
807    ///    [unsafe] [extern "ABI"] fn (S) -> T
808    /// //  ^~~~~^          ^~~~^     ^~^    ^
809    /// //    |               |        |     |
810    /// //    |               |        |   Return type
811    /// // Function Style    ABI  Parameter types
812    /// ```
813    /// We actually parse `FnHeader FnDecl`, but we error on `const` and `async` qualifiers.
814    fn parse_ty_fn_ptr(
815        &mut self,
816        lo: Span,
817        mut params: ThinVec<GenericParam>,
818        param_insertion_point: Option<Span>,
819        recover_return_sign: RecoverReturnSign,
820    ) -> PResult<'a, TyKind> {
821        let inherited_vis = rustc_ast::Visibility {
822            span: rustc_span::DUMMY_SP,
823            kind: rustc_ast::VisibilityKind::Inherited,
824            tokens: None,
825        };
826        let span_start = self.token.span;
827        let ast::FnHeader { ext, safety, .. } = self.parse_fn_front_matter(
828            &inherited_vis,
829            Case::Sensitive,
830            FrontMatterParsingMode::FunctionPtrType,
831        )?;
832        if self.may_recover() && self.token == TokenKind::Lt {
833            self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?;
834        }
835        let mode = crate::parser::item::FnParseMode {
836            req_name: |_, _| false,
837            context: FnContext::Free,
838            req_body: false,
839        };
840        let decl = self.parse_fn_decl(&mode, AllowPlus::No, recover_return_sign)?;
841
842        let decl_span = span_start.to(self.prev_token.span);
843        Ok(TyKind::FnPtr(Box::new(FnPtrTy {
844            ext,
845            safety,
846            generic_params: params,
847            decl,
848            decl_span,
849        })))
850    }
851
852    /// Recover from function pointer types with a generic parameter list (e.g. `fn<'a>(&'a str)`).
853    fn recover_fn_ptr_with_generics(
854        &mut self,
855        lo: Span,
856        params: &mut ThinVec<GenericParam>,
857        param_insertion_point: Option<Span>,
858    ) -> PResult<'a, ()> {
859        let generics = self.parse_generics()?;
860        let arity = generics.params.len();
861
862        let mut lifetimes: ThinVec<_> = generics
863            .params
864            .into_iter()
865            .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ast::GenericParamKind::Lifetime => true,
    _ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime))
866            .collect();
867
868        let sugg = if !lifetimes.is_empty() {
869            let snippet =
870                lifetimes.iter().map(|param| param.ident.as_str()).intersperse(", ").collect();
871
872            let (left, snippet) = if let Some(span) = param_insertion_point {
873                (span, if params.is_empty() { snippet } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", snippet))
    })format!(", {snippet}") })
874            } else {
875                (lo.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("for<{0}> ", snippet))
    })format!("for<{snippet}> "))
876            };
877
878            Some(FnPtrWithGenericsSugg {
879                left,
880                snippet,
881                right: generics.span,
882                arity,
883                for_param_list_exists: param_insertion_point.is_some(),
884            })
885        } else {
886            None
887        };
888
889        self.dcx().emit_err(FnPtrWithGenerics { span: generics.span, sugg });
890        params.append(&mut lifetimes);
891        Ok(())
892    }
893
894    /// Parses an `impl B0 + ... + Bn` type.
895    fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
896        if self.token.is_lifetime() {
897            self.look_ahead(1, |t| {
898                if let token::Ident(sym, _) = t.kind {
899                    // parse pattern with "'a Sized" we're supposed to give suggestion like
900                    // "'a + Sized"
901                    self.dcx().emit_err(errors::MissingPlusBounds {
902                        span: self.token.span,
903                        hi: self.token.span.shrink_to_hi(),
904                        sym,
905                    });
906                }
907            })
908        }
909
910        // Always parse bounds greedily for better error recovery.
911        let bounds = self.parse_generic_bounds()?;
912
913        *impl_dyn_multi = bounds.len() > 1 || self.prev_token == TokenKind::Plus;
914
915        Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
916    }
917
918    /// Parse a use-bound aka precise capturing list.
919    ///
920    /// ```ebnf
921    /// UseBound = "use" "<" (PreciseCapture ("," PreciseCapture)* ","?)? ">"
922    /// PreciseCapture = "Self" | Ident | Lifetime
923    /// ```
924    fn parse_use_bound(&mut self, lo: Span, parens: ast::Parens) -> PResult<'a, GenericBound> {
925        self.expect_lt()?;
926        let (args, _, _) = self.parse_seq_to_before_tokens(
927            &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)],
928            &[&TokenKind::Ge, &TokenKind::Shr, &TokenKind::Shr],
929            SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
930            |self_| {
931                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)) {
932                    self_.bump();
933                    Ok(PreciseCapturingArg::Arg(
934                        ast::Path::from_ident(self_.prev_token.ident().unwrap().0),
935                        DUMMY_NODE_ID,
936                    ))
937                } else if self_.check_ident() {
938                    Ok(PreciseCapturingArg::Arg(
939                        ast::Path::from_ident(self_.parse_ident()?),
940                        DUMMY_NODE_ID,
941                    ))
942                } else if self_.check_lifetime() {
943                    Ok(PreciseCapturingArg::Lifetime(self_.expect_lifetime()))
944                } else {
945                    self_.unexpected_any()
946                }
947            },
948        )?;
949        self.expect_gt()?;
950
951        if let ast::Parens::Yes = parens {
952            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
953            self.report_parenthesized_bound(lo, self.prev_token.span, "precise capturing lists");
954        }
955
956        Ok(GenericBound::Use(args, lo.to(self.prev_token.span)))
957    }
958
959    /// Is a `dyn B0 + ... + Bn` type allowed here?
960    fn is_explicit_dyn_type(&mut self) -> bool {
961        self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Dyn,
    token_type: crate::parser::token_type::TokenType::KwDyn,
}exp!(Dyn))
962            && (self.token_uninterpolated_span().at_least_rust_2018()
963                || self.look_ahead(1, |&t| can_begin_dyn_bound_in_edition_2015(t)))
964    }
965
966    /// Parses a `dyn B0 + ... + Bn` type.
967    ///
968    /// Note that this does *not* parse bare trait objects.
969    fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
970        self.bump(); // `dyn`
971
972        // Always parse bounds greedily for better error recovery.
973        let bounds = self.parse_generic_bounds()?;
974        *impl_dyn_multi = bounds.len() > 1 || self.prev_token == TokenKind::Plus;
975
976        Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn))
977    }
978
979    /// Parses a type starting with a path.
980    ///
981    /// This can be:
982    /// 1. a type macro, `mac!(...)`,
983    /// 2. a bare trait object, `B0 + ... + Bn`,
984    /// 3. or a path, `path::to::MyType`.
985    fn parse_path_start_ty(
986        &mut self,
987        lo: Span,
988        allow_plus: AllowPlus,
989        ty_generics: Option<&Generics>,
990    ) -> PResult<'a, TyKind> {
991        // Simple path
992        let path = self.parse_path_inner(PathStyle::Type, ty_generics)?;
993        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
994            // Macro invocation in type position
995            Ok(TyKind::MacCall(Box::new(MacCall { path, args: self.parse_delim_args()? })))
996        } else if allow_plus == AllowPlus::Yes && self.check_plus() {
997            // `Trait1 + Trait2 + 'a`
998            self.parse_remaining_bounds_path(ThinVec::new(), path, lo, true, ast::Parens::No)
999        } else {
1000            // Just a type path.
1001            Ok(TyKind::Path(None, path))
1002        }
1003    }
1004
1005    pub(super) fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
1006        self.parse_generic_bounds_common(AllowPlus::Yes)
1007    }
1008
1009    /// Parse generic bounds.
1010    ///
1011    /// Only if `allow_plus` this parses a `+`-separated list of bounds (trailing `+` is admitted).
1012    /// Otherwise, this only parses a single bound or none.
1013    fn parse_generic_bounds_common(&mut self, allow_plus: AllowPlus) -> PResult<'a, GenericBounds> {
1014        let mut bounds = Vec::new();
1015
1016        // In addition to looping while we find generic bounds:
1017        // We continue even if we find a keyword. This is necessary for error recovery on,
1018        // for example, `impl fn()`. The only keyword that can go after generic bounds is
1019        // `where`, so stop if it's it.
1020        // We also continue if we find types (not traits), again for error recovery.
1021        while self.can_begin_bound()
1022            || (self.may_recover()
1023                && (self.token.can_begin_type()
1024                    || (self.token.is_reserved_ident() && !self.token.is_keyword(kw::Where))))
1025        {
1026            if self.token.is_keyword(kw::Dyn) {
1027                // Account for `&dyn Trait + dyn Other`.
1028                self.bump();
1029                self.dcx().emit_err(InvalidDynKeyword {
1030                    span: self.prev_token.span,
1031                    suggestion: self.prev_token.span.until(self.token.span),
1032                });
1033            }
1034            bounds.push(self.parse_generic_bound()?);
1035            if allow_plus == AllowPlus::No || !self.eat_plus() {
1036                break;
1037            }
1038        }
1039
1040        Ok(bounds)
1041    }
1042
1043    /// Can the current token begin a bound?
1044    fn can_begin_bound(&mut self) -> bool {
1045        self.check_path()
1046            || self.check_lifetime()
1047            || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))
1048            || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Question,
    token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question))
1049            || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Tilde,
    token_type: crate::parser::token_type::TokenType::Tilde,
}exp!(Tilde))
1050            || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::For,
    token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For))
1051            || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))
1052            || self.can_begin_maybe_const_bound()
1053            || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))
1054            || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async))
1055            || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Use,
    token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use))
1056    }
1057
1058    fn can_begin_maybe_const_bound(&mut self) -> bool {
1059        self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBracket,
    token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket))
1060            && self.look_ahead(1, |t| t.is_keyword(kw::Const))
1061            && self.look_ahead(2, |t| *t == token::CloseBracket)
1062    }
1063
1064    /// Parse a bound.
1065    ///
1066    /// ```ebnf
1067    /// Bound = LifetimeBound | UseBound | TraitBound
1068    /// ```
1069    fn parse_generic_bound(&mut self) -> PResult<'a, GenericBound> {
1070        let leading_token = self.prev_token;
1071        let lo = self.token.span;
1072
1073        // We only admit parenthesized *trait* bounds. However, we want to gracefully recover from
1074        // other kinds of parenthesized bounds, so parse the opening parenthesis *here*.
1075        //
1076        // In the future we might want to lift this syntactic restriction and
1077        // introduce "`GenericBound::Paren(Box<GenericBound>)`".
1078        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 };
1079
1080        if self.token.is_lifetime() {
1081            self.parse_lifetime_bound(lo, parens)
1082        } 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)) {
1083            self.parse_use_bound(lo, parens)
1084        } else {
1085            self.parse_trait_bound(lo, parens, &leading_token)
1086        }
1087    }
1088
1089    /// Parse a lifetime-bound aka outlives-bound.
1090    ///
1091    /// ```ebnf
1092    /// LifetimeBound = Lifetime
1093    /// ```
1094    fn parse_lifetime_bound(&mut self, lo: Span, parens: ast::Parens) -> PResult<'a, GenericBound> {
1095        let lt = self.expect_lifetime();
1096
1097        if let ast::Parens::Yes = parens {
1098            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1099            self.report_parenthesized_bound(lo, self.prev_token.span, "lifetime bounds");
1100        }
1101
1102        Ok(GenericBound::Outlives(lt))
1103    }
1104
1105    fn report_parenthesized_bound(&self, lo: Span, hi: Span, kind: &str) -> ErrorGuaranteed {
1106        let mut diag =
1107            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"));
1108        diag.multipart_suggestion(
1109            "remove the parentheses",
1110            ::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())],
1111            Applicability::MachineApplicable,
1112        );
1113        diag.emit()
1114    }
1115
1116    /// Emits an error if any trait bound modifiers were present.
1117    fn error_lt_bound_with_modifiers(
1118        &self,
1119        modifiers: TraitBoundModifiers,
1120        binder_span: Option<Span>,
1121    ) -> ErrorGuaranteed {
1122        let TraitBoundModifiers { constness, asyncness, polarity } = modifiers;
1123
1124        match constness {
1125            BoundConstness::Never => {}
1126            BoundConstness::Always(span) | BoundConstness::Maybe(span) => {
1127                return self
1128                    .dcx()
1129                    .emit_err(errors::ModifierLifetime { span, modifier: constness.as_str() });
1130            }
1131        }
1132
1133        match polarity {
1134            BoundPolarity::Positive => {}
1135            BoundPolarity::Negative(span) | BoundPolarity::Maybe(span) => {
1136                return self
1137                    .dcx()
1138                    .emit_err(errors::ModifierLifetime { span, modifier: polarity.as_str() });
1139            }
1140        }
1141
1142        match asyncness {
1143            BoundAsyncness::Normal => {}
1144            BoundAsyncness::Async(span) => {
1145                return self
1146                    .dcx()
1147                    .emit_err(errors::ModifierLifetime { span, modifier: asyncness.as_str() });
1148            }
1149        }
1150
1151        if let Some(span) = binder_span {
1152            return self.dcx().emit_err(errors::ModifierLifetime { span, modifier: "for<...>" });
1153        }
1154
1155        {
    ::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?")
1156    }
1157
1158    /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `[const] Trait`.
1159    ///
1160    /// If no modifiers are present, this does not consume any tokens.
1161    ///
1162    /// ```ebnf
1163    /// Constness = ("const" | "[" "const" "]")?
1164    /// Asyncness = "async"?
1165    /// Polarity = ("?" | "!")?
1166    /// ```
1167    ///
1168    /// See `parse_trait_bound` for more context.
1169    fn parse_trait_bound_modifiers(&mut self) -> PResult<'a, TraitBoundModifiers> {
1170        let modifier_lo = self.token.span;
1171        let constness = self.parse_bound_constness()?;
1172
1173        let asyncness = if self.token_uninterpolated_span().at_least_rust_2018()
1174            && self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async))
1175        {
1176            self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
1177            BoundAsyncness::Async(self.prev_token.span)
1178        } else if self.may_recover()
1179            && self.token_uninterpolated_span().is_rust_2015()
1180            && self.is_kw_followed_by_ident(kw::Async)
1181        {
1182            self.bump(); // eat `async`
1183            self.dcx().emit_err(errors::AsyncBoundModifierIn2015 {
1184                span: self.prev_token.span,
1185                help: HelpUseLatestEdition::new(),
1186            });
1187            self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
1188            BoundAsyncness::Async(self.prev_token.span)
1189        } else {
1190            BoundAsyncness::Normal
1191        };
1192        let modifier_hi = self.prev_token.span;
1193
1194        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)) {
1195            BoundPolarity::Maybe(self.prev_token.span)
1196        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
1197            self.psess.gated_spans.gate(sym::negative_bounds, self.prev_token.span);
1198            BoundPolarity::Negative(self.prev_token.span)
1199        } else {
1200            BoundPolarity::Positive
1201        };
1202
1203        // Enforce the mutual-exclusivity of `const`/`async` and `?`/`!`.
1204        match polarity {
1205            BoundPolarity::Positive => {
1206                // All trait bound modifiers allowed to combine with positive polarity
1207            }
1208            BoundPolarity::Maybe(polarity_span) | BoundPolarity::Negative(polarity_span) => {
1209                match (asyncness, constness) {
1210                    (BoundAsyncness::Normal, BoundConstness::Never) => {
1211                        // Ok, no modifiers.
1212                    }
1213                    (_, _) => {
1214                        let constness = constness.as_str();
1215                        let asyncness = asyncness.as_str();
1216                        let glue =
1217                            if !constness.is_empty() && !asyncness.is_empty() { " " } else { "" };
1218                        let modifiers_concatenated = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}", constness, glue,
                asyncness))
    })format!("{constness}{glue}{asyncness}");
1219                        self.dcx().emit_err(errors::PolarityAndModifiers {
1220                            polarity_span,
1221                            polarity: polarity.as_str(),
1222                            modifiers_span: modifier_lo.to(modifier_hi),
1223                            modifiers_concatenated,
1224                        });
1225                    }
1226                }
1227            }
1228        }
1229
1230        Ok(TraitBoundModifiers { constness, asyncness, polarity })
1231    }
1232
1233    pub fn parse_bound_constness(&mut self) -> PResult<'a, BoundConstness> {
1234        // FIXME(const_trait_impl): remove `~const` parser support once bootstrap has the new syntax
1235        // in rustfmt
1236        Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Tilde,
    token_type: crate::parser::token_type::TokenType::Tilde,
}exp!(Tilde)) {
1237            let tilde = self.prev_token.span;
1238            self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1239            let span = tilde.to(self.prev_token.span);
1240            self.psess.gated_spans.gate(sym::const_trait_impl, span);
1241            BoundConstness::Maybe(span)
1242        } else if self.can_begin_maybe_const_bound() {
1243            let start = self.token.span;
1244            self.bump();
1245            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();
1246            self.bump();
1247            let span = start.to(self.prev_token.span);
1248            self.psess.gated_spans.gate(sym::const_trait_impl, span);
1249            BoundConstness::Maybe(span)
1250        } 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)) {
1251            self.psess.gated_spans.gate(sym::const_trait_impl, self.prev_token.span);
1252            BoundConstness::Always(self.prev_token.span)
1253        } else {
1254            BoundConstness::Never
1255        })
1256    }
1257
1258    /// Parse a trait bound.
1259    ///
1260    /// ```ebnf
1261    /// TraitBound = BareTraitBound | "(" BareTraitBound ")"
1262    /// BareTraitBound =
1263    ///     (HigherRankedBinder Constness Asyncness | Polarity)
1264    ///     TypePath
1265    /// ```
1266    fn parse_trait_bound(
1267        &mut self,
1268        lo: Span,
1269        parens: ast::Parens,
1270        leading_token: &Token,
1271    ) -> PResult<'a, GenericBound> {
1272        let (mut bound_vars, binder_span) = self.parse_higher_ranked_binder()?;
1273
1274        let modifiers_lo = self.token.span;
1275        let modifiers = self.parse_trait_bound_modifiers()?;
1276        let modifiers_span = modifiers_lo.to(self.prev_token.span);
1277
1278        if let Some(binder_span) = binder_span {
1279            match modifiers.polarity {
1280                BoundPolarity::Negative(polarity_span) | BoundPolarity::Maybe(polarity_span) => {
1281                    self.dcx().emit_err(errors::BinderAndPolarity {
1282                        binder_span,
1283                        polarity_span,
1284                        polarity: modifiers.polarity.as_str(),
1285                    });
1286                }
1287                BoundPolarity::Positive => {}
1288            }
1289        }
1290
1291        // Recover erroneous lifetime bound with modifiers or binder.
1292        // e.g. `T: for<'a> 'a` or `T: [const] 'a`.
1293        if self.token.is_lifetime() {
1294            let _: ErrorGuaranteed = self.error_lt_bound_with_modifiers(modifiers, binder_span);
1295            return self.parse_lifetime_bound(lo, parens);
1296        }
1297
1298        if let (more_bound_vars, Some(binder_span)) = self.parse_higher_ranked_binder()? {
1299            bound_vars.extend(more_bound_vars);
1300            self.dcx().emit_err(errors::BinderBeforeModifiers { binder_span, modifiers_span });
1301        }
1302
1303        let mut path = if self.token.is_keyword(kw::Fn)
1304            && self.look_ahead(1, |t| *t == TokenKind::OpenParen)
1305            && let Some(path) = self.recover_path_from_fn()
1306        {
1307            path
1308        } else if !self.token.is_path_start() && self.token.can_begin_type() {
1309            let ty = self.parse_ty_no_plus()?;
1310            // Instead of finding a path (a trait), we found a type.
1311            let mut err = self.dcx().struct_span_err(ty.span, "expected a trait, found type");
1312
1313            // If we can recover, try to extract a path from the type. Note
1314            // that we do not use the try operator when parsing the type because
1315            // if it fails then we get a parser error which we don't want (we're trying
1316            // to recover from errors, not make more).
1317            let path = if self.may_recover() {
1318                let (span, message, sugg, path, applicability) = match &ty.kind {
1319                    TyKind::Ptr(..) | TyKind::Ref(..)
1320                        if let TyKind::Path(_, path) = &ty.peel_refs().kind =>
1321                    {
1322                        (
1323                            ty.span.until(path.span),
1324                            "consider removing the indirection",
1325                            "",
1326                            path,
1327                            Applicability::MaybeIncorrect,
1328                        )
1329                    }
1330                    TyKind::ImplTrait(_, bounds)
1331                        if let [GenericBound::Trait(tr, ..), ..] = bounds.as_slice() =>
1332                    {
1333                        (
1334                            ty.span.until(tr.span),
1335                            "use the trait bounds directly",
1336                            "",
1337                            &tr.trait_ref.path,
1338                            Applicability::MachineApplicable,
1339                        )
1340                    }
1341                    _ => return Err(err),
1342                };
1343
1344                err.span_suggestion_verbose(span, message, sugg, applicability);
1345
1346                path.clone()
1347            } else {
1348                return Err(err);
1349            };
1350
1351            err.emit();
1352
1353            path
1354        } else {
1355            self.parse_path(PathStyle::Type)?
1356        };
1357
1358        if self.may_recover() && self.token == TokenKind::OpenParen {
1359            self.recover_fn_trait_with_lifetime_params(&mut path, &mut bound_vars)?;
1360        }
1361
1362        if let ast::Parens::Yes = parens {
1363            // Someone has written something like `&dyn (Trait + Other)`. The correct code
1364            // would be `&(dyn Trait + Other)`
1365            if self.token.is_like_plus() && leading_token.is_keyword(kw::Dyn) {
1366                let bounds = ::alloc::vec::Vec::new()vec![];
1367                self.parse_remaining_bounds(bounds, true)?;
1368                self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1369                self.dcx().emit_err(errors::IncorrectParensTraitBounds {
1370                    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],
1371                    sugg: errors::IncorrectParensTraitBoundsSugg {
1372                        wrong_span: leading_token.span.shrink_to_hi().to(lo),
1373                        new_span: leading_token.span.shrink_to_lo(),
1374                    },
1375                });
1376            } else {
1377                self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1378            }
1379        }
1380
1381        let poly_trait =
1382            PolyTraitRef::new(bound_vars, path, modifiers, lo.to(self.prev_token.span), parens);
1383        Ok(GenericBound::Trait(poly_trait))
1384    }
1385
1386    // recovers a `Fn(..)` parenthesized-style path from `fn(..)`
1387    fn recover_path_from_fn(&mut self) -> Option<ast::Path> {
1388        let fn_token_span = self.token.span;
1389        self.bump();
1390        let args_lo = self.token.span;
1391        let snapshot = self.create_snapshot_for_diagnostic();
1392        let mode =
1393            FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false };
1394        match self.parse_fn_decl(&mode, AllowPlus::No, RecoverReturnSign::OnlyFatArrow) {
1395            Ok(decl) => {
1396                self.dcx().emit_err(ExpectedFnPathFoundFnKeyword { fn_token_span });
1397                Some(ast::Path {
1398                    span: fn_token_span.to(self.prev_token.span),
1399                    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 {
1400                        ident: Ident::new(sym::Fn, fn_token_span),
1401                        id: DUMMY_NODE_ID,
1402                        args: Some(Box::new(ast::GenericArgs::Parenthesized(
1403                            ast::ParenthesizedArgs {
1404                                span: args_lo.to(self.prev_token.span),
1405                                inputs: decl.inputs.iter().map(|a| a.ty.clone()).collect(),
1406                                inputs_span: args_lo.until(decl.output.span()),
1407                                output: decl.output.clone(),
1408                            }
1409                        ))),
1410                    }],
1411                    tokens: None,
1412                })
1413            }
1414            Err(diag) => {
1415                diag.cancel();
1416                self.restore_snapshot(snapshot);
1417                None
1418            }
1419        }
1420    }
1421
1422    /// Parse an optional higher-ranked binder.
1423    ///
1424    /// ```ebnf
1425    /// HigherRankedBinder = ("for" "<" GenericParams ">")?
1426    /// ```
1427    pub(super) fn parse_higher_ranked_binder(
1428        &mut self,
1429    ) -> PResult<'a, (ThinVec<GenericParam>, Option<Span>)> {
1430        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)) {
1431            let lo = self.token.span;
1432            self.expect_lt()?;
1433            let params = self.parse_generic_params()?;
1434            self.expect_gt()?;
1435            // We rely on AST validation to rule out invalid cases: There must not be
1436            // type or const parameters, and parameters must not have bounds.
1437            Ok((params, Some(lo.to(self.prev_token.span))))
1438        } else {
1439            Ok((ThinVec::new(), None))
1440        }
1441    }
1442
1443    /// Recover from `Fn`-family traits (Fn, FnMut, FnOnce) with lifetime arguments
1444    /// (e.g. `FnOnce<'a>(&'a str) -> bool`). Up to generic arguments have already
1445    /// been eaten.
1446    fn recover_fn_trait_with_lifetime_params(
1447        &mut self,
1448        fn_path: &mut ast::Path,
1449        lifetime_defs: &mut ThinVec<GenericParam>,
1450    ) -> PResult<'a, ()> {
1451        let fn_path_segment = fn_path.segments.last_mut().unwrap();
1452        let generic_args = if let Some(p_args) = &fn_path_segment.args {
1453            *p_args.clone()
1454        } else {
1455            // Normally it wouldn't come here because the upstream should have parsed
1456            // generic parameters (otherwise it's impossible to call this function).
1457            return Ok(());
1458        };
1459        let lifetimes =
1460            if let ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { span: _, args }) =
1461                &generic_args
1462            {
1463                args.into_iter()
1464                    .filter_map(|arg| {
1465                        if let ast::AngleBracketedArg::Arg(generic_arg) = arg
1466                            && let ast::GenericArg::Lifetime(lifetime) = generic_arg
1467                        {
1468                            Some(lifetime)
1469                        } else {
1470                            None
1471                        }
1472                    })
1473                    .collect()
1474            } else {
1475                Vec::new()
1476            };
1477        // Only try to recover if the trait has lifetime params.
1478        if lifetimes.is_empty() {
1479            return Ok(());
1480        }
1481
1482        let snapshot = if self.parsing_generics {
1483            // The snapshot is only relevant if we're parsing the generics of an `fn` to avoid
1484            // incorrect recovery.
1485            Some(self.create_snapshot_for_diagnostic())
1486        } else {
1487            None
1488        };
1489        // Parse `(T, U) -> R`.
1490        let inputs_lo = self.token.span;
1491        let mode =
1492            FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false };
1493        let params = match self.parse_fn_params(&mode) {
1494            Ok(params) => params,
1495            Err(err) => {
1496                if let Some(snapshot) = snapshot {
1497                    self.restore_snapshot(snapshot);
1498                    err.cancel();
1499                    return Ok(());
1500                } else {
1501                    return Err(err);
1502                }
1503            }
1504        };
1505        let inputs: ThinVec<_> = params.into_iter().map(|input| input.ty).collect();
1506        let inputs_span = inputs_lo.to(self.prev_token.span);
1507        let output = match self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)
1508        {
1509            Ok(output) => output,
1510            Err(err) => {
1511                if let Some(snapshot) = snapshot {
1512                    self.restore_snapshot(snapshot);
1513                    err.cancel();
1514                    return Ok(());
1515                } else {
1516                    return Err(err);
1517                }
1518            }
1519        };
1520        let args = ast::ParenthesizedArgs {
1521            span: fn_path_segment.span().to(self.prev_token.span),
1522            inputs,
1523            inputs_span,
1524            output,
1525        }
1526        .into();
1527
1528        if let Some(snapshot) = snapshot
1529            && ![token::Comma, token::Gt, token::Plus].contains(&self.token.kind)
1530        {
1531            // We would expect another bound or the end of type params by now. Most likely we've
1532            // encountered a `(` *not* representing `Trait()`, but rather the start of the `fn`'s
1533            // argument list where the generic param list wasn't properly closed.
1534            self.restore_snapshot(snapshot);
1535            return Ok(());
1536        }
1537
1538        *fn_path_segment = ast::PathSegment {
1539            ident: fn_path_segment.ident,
1540            args: Some(args),
1541            id: ast::DUMMY_NODE_ID,
1542        };
1543
1544        // Convert parsed `<'a>` in `Fn<'a>` into `for<'a>`.
1545        let mut generic_params = lifetimes
1546            .iter()
1547            .map(|lt| GenericParam {
1548                id: lt.id,
1549                ident: lt.ident,
1550                attrs: ast::AttrVec::new(),
1551                bounds: Vec::new(),
1552                is_placeholder: false,
1553                kind: ast::GenericParamKind::Lifetime,
1554                colon_span: None,
1555            })
1556            .collect::<ThinVec<GenericParam>>();
1557        lifetime_defs.append(&mut generic_params);
1558
1559        let generic_args_span = generic_args.span();
1560        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!(
1561            "for<{}> ",
1562            lifetimes.iter().map(|lt| lt.ident.as_str()).intersperse(", ").collect::<String>(),
1563        );
1564        let before_fn_path = fn_path.span.shrink_to_lo();
1565        self.dcx()
1566            .struct_span_err(generic_args_span, "`Fn` traits cannot take lifetime parameters")
1567            .with_multipart_suggestion(
1568                "consider using a higher-ranked trait bound instead",
1569                ::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)],
1570                Applicability::MaybeIncorrect,
1571            )
1572            .emit();
1573        Ok(())
1574    }
1575
1576    pub(super) fn check_lifetime(&mut self) -> bool {
1577        self.expected_token_types.insert(TokenType::Lifetime);
1578        self.token.is_lifetime()
1579    }
1580
1581    /// Parses a single lifetime `'a` or panics.
1582    pub(super) fn expect_lifetime(&mut self) -> Lifetime {
1583        if let Some((ident, is_raw)) = self.token.lifetime() {
1584            if is_raw == IdentIsRaw::No && ident.without_first_quote().is_reserved_lifetime() {
1585                self.dcx().emit_err(errors::KeywordLifetime { span: ident.span });
1586            }
1587
1588            self.bump();
1589            Lifetime { ident, id: ast::DUMMY_NODE_ID }
1590        } else {
1591            self.dcx().span_bug(self.token.span, "not a lifetime")
1592        }
1593    }
1594
1595    pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> Box<Ty> {
1596        Box::new(Ty { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })
1597    }
1598}