rustc_parse/parser/
ty.rs

1use rustc_ast::ptr::P;
2use rustc_ast::token::{self, Delimiter, IdentIsRaw, MetaVarKind, Token, TokenKind};
3use rustc_ast::util::case::Case;
4use rustc_ast::{
5    self as ast, BareFnTy, BoundAsyncness, BoundConstness, BoundPolarity, DUMMY_NODE_ID, FnRetTy,
6    GenericBound, GenericBounds, GenericParam, Generics, Lifetime, MacCall, MutTy, Mutability,
7    Pinnedness, PolyTraitRef, PreciseCapturingArg, TraitBoundModifiers, TraitObjectSyntax, Ty,
8    TyKind, UnsafeBinderTy,
9};
10use rustc_errors::{Applicability, 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, DynAfterMut, ExpectedFnPathFoundFnKeyword, ExpectedMutOrConstInRawPointerType,
17    FnPointerCannotBeAsync, FnPointerCannotBeConst, FnPtrWithGenerics, FnPtrWithGenericsSugg,
18    HelpUseLatestEdition, InvalidDynKeyword, LifetimeAfterMut, NeedPlusAfterTraitObjectLifetime,
19    NestedCVariadicType, ReturnTypesUseThinArrow,
20};
21use crate::{exp, maybe_recover_from_interpolated_ty_qpath};
22
23/// Signals whether parsing a type should allow `+`.
24///
25/// For example, let T be the type `impl Default + 'static`
26/// With `AllowPlus::Yes`, T will be parsed successfully
27/// With `AllowPlus::No`, parsing T will return a parse error
28#[derive(Copy, Clone, PartialEq)]
29pub(super) enum AllowPlus {
30    Yes,
31    No,
32}
33
34#[derive(PartialEq)]
35pub(super) enum RecoverQPath {
36    Yes,
37    No,
38}
39
40pub(super) enum RecoverQuestionMark {
41    Yes,
42    No,
43}
44
45/// Signals whether parsing a type should recover `->`.
46///
47/// More specifically, when parsing a function like:
48/// ```compile_fail
49/// fn foo() => u8 { 0 }
50/// fn bar(): u8 { 0 }
51/// ```
52/// The compiler will try to recover interpreting `foo() => u8` as `foo() -> u8` when calling
53/// `parse_ty` with anything except `RecoverReturnSign::No`, and it will try to recover `bar(): u8`
54/// as `bar() -> u8` when passing `RecoverReturnSign::Yes` to `parse_ty`
55#[derive(Copy, Clone, PartialEq)]
56pub(super) enum RecoverReturnSign {
57    Yes,
58    OnlyFatArrow,
59    No,
60}
61
62impl RecoverReturnSign {
63    /// [RecoverReturnSign::Yes] allows for recovering `fn foo() => u8` and `fn foo(): u8`,
64    /// [RecoverReturnSign::OnlyFatArrow] allows for recovering only `fn foo() => u8` (recovering
65    /// colons can cause problems when parsing where clauses), and
66    /// [RecoverReturnSign::No] doesn't allow for any recovery of the return type arrow
67    fn can_recover(self, token: &TokenKind) -> bool {
68        match self {
69            Self::Yes => matches!(token, token::FatArrow | token::Colon),
70            Self::OnlyFatArrow => matches!(token, token::FatArrow),
71            Self::No => false,
72        }
73    }
74}
75
76// Is `...` (`CVarArgs`) legal at this level of type parsing?
77#[derive(PartialEq)]
78enum AllowCVariadic {
79    Yes,
80    No,
81}
82
83/// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
84/// `IDENT<<u8 as Trait>::AssocTy>`.
85///
86/// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
87/// that `IDENT` is not the ident of a fn trait.
88fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
89    t == &token::PathSep || t == &token::Lt || t == &token::Shl
90}
91
92fn can_begin_dyn_bound_in_edition_2015(t: &Token) -> bool {
93    // `Not`, `Tilde` & `Const` are deliberately not part of this list to
94    // contain the number of potential regressions esp. in MBE code.
95    // `Const` would regress `rfc-2632-const-trait-impl/mbe-dyn-const-2015.rs`.
96    // `Not` would regress `dyn!(...)` macro calls in Rust 2015.
97    t.is_path_start()
98        || t.is_lifetime()
99        || t == &TokenKind::Question
100        || t.is_keyword(kw::For)
101        || t == &TokenKind::OpenDelim(Delimiter::Parenthesis)
102}
103
104impl<'a> Parser<'a> {
105    /// Parses a type.
106    pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
107        self.parse_ty_common(
108            AllowPlus::Yes,
109            AllowCVariadic::No,
110            RecoverQPath::Yes,
111            RecoverReturnSign::Yes,
112            None,
113            RecoverQuestionMark::Yes,
114        )
115    }
116
117    pub(super) fn parse_ty_with_generics_recovery(
118        &mut self,
119        ty_params: &Generics,
120    ) -> PResult<'a, P<Ty>> {
121        self.parse_ty_common(
122            AllowPlus::Yes,
123            AllowCVariadic::No,
124            RecoverQPath::Yes,
125            RecoverReturnSign::Yes,
126            Some(ty_params),
127            RecoverQuestionMark::Yes,
128        )
129    }
130
131    /// Parse a type suitable for a function or function pointer parameter.
132    /// The difference from `parse_ty` is that this version allows `...`
133    /// (`CVarArgs`) at the top level of the type.
134    pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, P<Ty>> {
135        self.parse_ty_common(
136            AllowPlus::Yes,
137            AllowCVariadic::Yes,
138            RecoverQPath::Yes,
139            RecoverReturnSign::Yes,
140            None,
141            RecoverQuestionMark::Yes,
142        )
143    }
144
145    /// Parses a type in restricted contexts where `+` is not permitted.
146    ///
147    /// Example 1: `&'a TYPE`
148    ///     `+` is prohibited to maintain operator priority (P(+) < P(&)).
149    /// Example 2: `value1 as TYPE + value2`
150    ///     `+` is prohibited to avoid interactions with expression grammar.
151    pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
152        self.parse_ty_common(
153            AllowPlus::No,
154            AllowCVariadic::No,
155            RecoverQPath::Yes,
156            RecoverReturnSign::Yes,
157            None,
158            RecoverQuestionMark::Yes,
159        )
160    }
161
162    /// Parses a type following an `as` cast. Similar to `parse_ty_no_plus`, but signaling origin
163    /// for better diagnostics involving `?`.
164    pub(super) fn parse_as_cast_ty(&mut self) -> PResult<'a, P<Ty>> {
165        self.parse_ty_common(
166            AllowPlus::No,
167            AllowCVariadic::No,
168            RecoverQPath::Yes,
169            RecoverReturnSign::Yes,
170            None,
171            RecoverQuestionMark::No,
172        )
173    }
174
175    pub(super) fn parse_ty_no_question_mark_recover(&mut self) -> PResult<'a, P<Ty>> {
176        self.parse_ty_common(
177            AllowPlus::Yes,
178            AllowCVariadic::No,
179            RecoverQPath::Yes,
180            RecoverReturnSign::Yes,
181            None,
182            RecoverQuestionMark::No,
183        )
184    }
185
186    /// Parse a type without recovering `:` as `->` to avoid breaking code such
187    /// as `where fn() : for<'a>`.
188    pub(super) fn parse_ty_for_where_clause(&mut self) -> PResult<'a, P<Ty>> {
189        self.parse_ty_common(
190            AllowPlus::Yes,
191            AllowCVariadic::No,
192            RecoverQPath::Yes,
193            RecoverReturnSign::OnlyFatArrow,
194            None,
195            RecoverQuestionMark::Yes,
196        )
197    }
198
199    /// Parses an optional return type `[ -> TY ]` in a function declaration.
200    pub(super) fn parse_ret_ty(
201        &mut self,
202        allow_plus: AllowPlus,
203        recover_qpath: RecoverQPath,
204        recover_return_sign: RecoverReturnSign,
205    ) -> PResult<'a, FnRetTy> {
206        let lo = self.prev_token.span;
207        Ok(if self.eat(exp!(RArrow)) {
208            // FIXME(Centril): Can we unconditionally `allow_plus`?
209            let ty = self.parse_ty_common(
210                allow_plus,
211                AllowCVariadic::No,
212                recover_qpath,
213                recover_return_sign,
214                None,
215                RecoverQuestionMark::Yes,
216            )?;
217            FnRetTy::Ty(ty)
218        } else if recover_return_sign.can_recover(&self.token.kind) {
219            // Don't `eat` to prevent `=>` from being added as an expected token which isn't
220            // actually expected and could only confuse users
221            self.bump();
222            self.dcx().emit_err(ReturnTypesUseThinArrow {
223                span: self.prev_token.span,
224                suggestion: lo.between(self.token.span),
225            });
226            let ty = self.parse_ty_common(
227                allow_plus,
228                AllowCVariadic::No,
229                recover_qpath,
230                recover_return_sign,
231                None,
232                RecoverQuestionMark::Yes,
233            )?;
234            FnRetTy::Ty(ty)
235        } else {
236            FnRetTy::Default(self.prev_token.span.shrink_to_hi())
237        })
238    }
239
240    fn parse_ty_common(
241        &mut self,
242        allow_plus: AllowPlus,
243        allow_c_variadic: AllowCVariadic,
244        recover_qpath: RecoverQPath,
245        recover_return_sign: RecoverReturnSign,
246        ty_generics: Option<&Generics>,
247        recover_question_mark: RecoverQuestionMark,
248    ) -> PResult<'a, P<Ty>> {
249        let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes;
250        maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
251
252        if let Some(ty) = self.eat_metavar_seq_with_matcher(
253            |mv_kind| matches!(mv_kind, MetaVarKind::Ty { .. }),
254            |this| this.parse_ty_no_question_mark_recover(),
255        ) {
256            return Ok(ty);
257        }
258
259        let lo = self.token.span;
260        let mut impl_dyn_multi = false;
261        let kind = if self.check(exp!(OpenParen)) {
262            self.parse_ty_tuple_or_parens(lo, allow_plus)?
263        } else if self.eat(exp!(Bang)) {
264            // Never type `!`
265            TyKind::Never
266        } else if self.eat(exp!(Star)) {
267            self.parse_ty_ptr()?
268        } else if self.eat(exp!(OpenBracket)) {
269            self.parse_array_or_slice_ty()?
270        } else if self.check(exp!(And)) || self.check(exp!(AndAnd)) {
271            // Reference
272            self.expect_and()?;
273            self.parse_borrowed_pointee()?
274        } else if self.eat_keyword_noexpect(kw::Typeof) {
275            self.parse_typeof_ty()?
276        } else if self.eat_keyword(exp!(Underscore)) {
277            // A type to be inferred `_`
278            TyKind::Infer
279        } else if self.check_fn_front_matter(false, Case::Sensitive) {
280            // Function pointer type
281            self.parse_ty_bare_fn(lo, ThinVec::new(), None, recover_return_sign)?
282        } else if self.check_keyword(exp!(For)) {
283            // Function pointer type or bound list (trait object type) starting with a poly-trait.
284            //   `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
285            //   `for<'lt> Trait1<'lt> + Trait2 + 'a`
286            let (lifetime_defs, _) = self.parse_late_bound_lifetime_defs()?;
287            if self.check_fn_front_matter(false, Case::Sensitive) {
288                self.parse_ty_bare_fn(
289                    lo,
290                    lifetime_defs,
291                    Some(self.prev_token.span.shrink_to_lo()),
292                    recover_return_sign,
293                )?
294            } else {
295                // Try to recover `for<'a> dyn Trait` or `for<'a> impl Trait`.
296                if self.may_recover()
297                    && (self.eat_keyword_noexpect(kw::Impl) || self.eat_keyword_noexpect(kw::Dyn))
298                {
299                    let kw = self.prev_token.ident().unwrap().0;
300                    let removal_span = kw.span.with_hi(self.token.span.lo());
301                    let path = self.parse_path(PathStyle::Type)?;
302                    let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
303                    let kind =
304                        self.parse_remaining_bounds_path(lifetime_defs, path, lo, parse_plus)?;
305                    let err = self.dcx().create_err(errors::TransposeDynOrImpl {
306                        span: kw.span,
307                        kw: kw.name.as_str(),
308                        sugg: errors::TransposeDynOrImplSugg {
309                            removal_span,
310                            insertion_span: lo.shrink_to_lo(),
311                            kw: kw.name.as_str(),
312                        },
313                    });
314
315                    // Take the parsed bare trait object and turn it either
316                    // into a `dyn` object or an `impl Trait`.
317                    let kind = match (kind, kw.name) {
318                        (TyKind::TraitObject(bounds, _), kw::Dyn) => {
319                            TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
320                        }
321                        (TyKind::TraitObject(bounds, _), kw::Impl) => {
322                            TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
323                        }
324                        _ => return Err(err),
325                    };
326                    err.emit();
327                    kind
328                } else {
329                    let path = self.parse_path(PathStyle::Type)?;
330                    let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
331                    self.parse_remaining_bounds_path(lifetime_defs, path, lo, parse_plus)?
332                }
333            }
334        } else if self.eat_keyword(exp!(Impl)) {
335            self.parse_impl_ty(&mut impl_dyn_multi)?
336        } else if self.is_explicit_dyn_type() {
337            self.parse_dyn_ty(&mut impl_dyn_multi)?
338        } else if self.eat_lt() {
339            // Qualified path
340            let (qself, path) = self.parse_qpath(PathStyle::Type)?;
341            TyKind::Path(Some(qself), path)
342        } else if self.check_path() {
343            self.parse_path_start_ty(lo, allow_plus, ty_generics)?
344        } else if self.can_begin_bound() {
345            self.parse_bare_trait_object(lo, allow_plus)?
346        } else if self.eat(exp!(DotDotDot)) {
347            match allow_c_variadic {
348                AllowCVariadic::Yes => TyKind::CVarArgs,
349                AllowCVariadic::No => {
350                    // FIXME(c_variadic): Should we just allow `...` syntactically
351                    // anywhere in a type and use semantic restrictions instead?
352                    // NOTE: This may regress certain MBE calls if done incorrectly.
353                    let guar = self.dcx().emit_err(NestedCVariadicType { span: lo });
354                    TyKind::Err(guar)
355                }
356            }
357        } else if self.check_keyword(exp!(Unsafe))
358            && self.look_ahead(1, |tok| matches!(tok.kind, token::Lt))
359        {
360            self.parse_unsafe_binder_ty()?
361        } else {
362            let msg = format!("expected type, found {}", super::token_descr(&self.token));
363            let mut err = self.dcx().struct_span_err(lo, msg);
364            err.span_label(lo, "expected type");
365            return Err(err);
366        };
367
368        let span = lo.to(self.prev_token.span);
369        let mut ty = self.mk_ty(span, kind);
370
371        // Try to recover from use of `+` with incorrect priority.
372        match allow_plus {
373            AllowPlus::Yes => self.maybe_recover_from_bad_type_plus(&ty)?,
374            AllowPlus::No => self.maybe_report_ambiguous_plus(impl_dyn_multi, &ty),
375        }
376        if let RecoverQuestionMark::Yes = recover_question_mark {
377            ty = self.maybe_recover_from_question_mark(ty);
378        }
379        if allow_qpath_recovery { self.maybe_recover_from_bad_qpath(ty) } else { Ok(ty) }
380    }
381
382    fn parse_unsafe_binder_ty(&mut self) -> PResult<'a, TyKind> {
383        let lo = self.token.span;
384        assert!(self.eat_keyword(exp!(Unsafe)));
385        self.expect_lt()?;
386        let generic_params = self.parse_generic_params()?;
387        self.expect_gt()?;
388        let inner_ty = self.parse_ty()?;
389        let span = lo.to(self.prev_token.span);
390        self.psess.gated_spans.gate(sym::unsafe_binders, span);
391
392        Ok(TyKind::UnsafeBinder(P(UnsafeBinderTy { generic_params, inner_ty })))
393    }
394
395    /// Parses either:
396    /// - `(TYPE)`, a parenthesized type.
397    /// - `(TYPE,)`, a tuple with a single field of type TYPE.
398    fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
399        let mut trailing_plus = false;
400        let (ts, trailing) = self.parse_paren_comma_seq(|p| {
401            let ty = p.parse_ty()?;
402            trailing_plus = p.prev_token == TokenKind::Plus;
403            Ok(ty)
404        })?;
405
406        if ts.len() == 1 && matches!(trailing, Trailing::No) {
407            let ty = ts.into_iter().next().unwrap().into_inner();
408            let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
409            match ty.kind {
410                // `(TY_BOUND_NOPAREN) + BOUND + ...`.
411                TyKind::Path(None, path) if maybe_bounds => {
412                    self.parse_remaining_bounds_path(ThinVec::new(), path, lo, true)
413                }
414                TyKind::TraitObject(bounds, TraitObjectSyntax::None)
415                    if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
416                {
417                    self.parse_remaining_bounds(bounds, true)
418                }
419                // `(TYPE)`
420                _ => Ok(TyKind::Paren(P(ty))),
421            }
422        } else {
423            Ok(TyKind::Tup(ts))
424        }
425    }
426
427    fn parse_bare_trait_object(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
428        let lt_no_plus = self.check_lifetime() && !self.look_ahead(1, |t| t.is_like_plus());
429        let bounds = self.parse_generic_bounds_common(allow_plus)?;
430        if lt_no_plus {
431            self.dcx().emit_err(NeedPlusAfterTraitObjectLifetime { span: lo });
432        }
433        Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
434    }
435
436    fn parse_remaining_bounds_path(
437        &mut self,
438        generic_params: ThinVec<GenericParam>,
439        path: ast::Path,
440        lo: Span,
441        parse_plus: bool,
442    ) -> PResult<'a, TyKind> {
443        let poly_trait_ref = PolyTraitRef::new(
444            generic_params,
445            path,
446            TraitBoundModifiers::NONE,
447            lo.to(self.prev_token.span),
448        );
449        let bounds = vec![GenericBound::Trait(poly_trait_ref)];
450        self.parse_remaining_bounds(bounds, parse_plus)
451    }
452
453    /// Parse the remainder of a bare trait object type given an already parsed list.
454    fn parse_remaining_bounds(
455        &mut self,
456        mut bounds: GenericBounds,
457        plus: bool,
458    ) -> PResult<'a, TyKind> {
459        if plus {
460            self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
461            bounds.append(&mut self.parse_generic_bounds()?);
462        }
463        Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
464    }
465
466    /// Parses a raw pointer type: `*[const | mut] $type`.
467    fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
468        let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
469            let span = self.prev_token.span;
470            self.dcx().emit_err(ExpectedMutOrConstInRawPointerType {
471                span,
472                after_asterisk: span.shrink_to_hi(),
473            });
474            Mutability::Not
475        });
476        let ty = self.parse_ty_no_plus()?;
477        Ok(TyKind::Ptr(MutTy { ty, mutbl }))
478    }
479
480    /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
481    /// The opening `[` bracket is already eaten.
482    fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
483        let elt_ty = match self.parse_ty() {
484            Ok(ty) => ty,
485            Err(err)
486                if self.look_ahead(1, |t| *t == token::CloseDelim(Delimiter::Bracket))
487                    | self.look_ahead(1, |t| *t == token::Semi) =>
488            {
489                // Recover from `[LIT; EXPR]` and `[LIT]`
490                self.bump();
491                let guar = err.emit();
492                self.mk_ty(self.prev_token.span, TyKind::Err(guar))
493            }
494            Err(err) => return Err(err),
495        };
496
497        let ty = if self.eat(exp!(Semi)) {
498            let mut length = self.parse_expr_anon_const()?;
499            if let Err(e) = self.expect(exp!(CloseBracket)) {
500                // Try to recover from `X<Y, ...>` when `X::<Y, ...>` works
501                self.check_mistyped_turbofish_with_multiple_type_params(e, &mut length.value)?;
502                self.expect(exp!(CloseBracket))?;
503            }
504            TyKind::Array(elt_ty, length)
505        } else {
506            self.expect(exp!(CloseBracket))?;
507            TyKind::Slice(elt_ty)
508        };
509
510        Ok(ty)
511    }
512
513    fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
514        let and_span = self.prev_token.span;
515        let mut opt_lifetime = self.check_lifetime().then(|| self.expect_lifetime());
516        let (pinned, mut mutbl) = match self.parse_pin_and_mut() {
517            Some(pin_mut) => pin_mut,
518            None => (Pinnedness::Not, self.parse_mutability()),
519        };
520        if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() {
521            // A lifetime is invalid here: it would be part of a bare trait bound, which requires
522            // it to be followed by a plus, but we disallow plus in the pointee type.
523            // So we can handle this case as an error here, and suggest `'a mut`.
524            // If there *is* a plus next though, handling the error later provides better suggestions
525            // (like adding parentheses)
526            if !self.look_ahead(1, |t| t.is_like_plus()) {
527                let lifetime_span = self.token.span;
528                let span = and_span.to(lifetime_span);
529
530                let (suggest_lifetime, snippet) =
531                    if let Ok(lifetime_src) = self.span_to_snippet(lifetime_span) {
532                        (Some(span), lifetime_src)
533                    } else {
534                        (None, String::new())
535                    };
536                self.dcx().emit_err(LifetimeAfterMut { span, suggest_lifetime, snippet });
537
538                opt_lifetime = Some(self.expect_lifetime());
539            }
540        } else if self.token.is_keyword(kw::Dyn)
541            && mutbl == Mutability::Not
542            && self.look_ahead(1, |t| t.is_keyword(kw::Mut))
543        {
544            // We have `&dyn mut ...`, which is invalid and should be `&mut dyn ...`.
545            let span = and_span.to(self.look_ahead(1, |t| t.span));
546            self.dcx().emit_err(DynAfterMut { span });
547
548            // Recovery
549            mutbl = Mutability::Mut;
550            let (dyn_tok, dyn_tok_sp) = (self.token.clone(), self.token_spacing);
551            self.bump();
552            self.bump_with((dyn_tok, dyn_tok_sp));
553        }
554        let ty = self.parse_ty_no_plus()?;
555        Ok(match pinned {
556            Pinnedness::Not => TyKind::Ref(opt_lifetime, MutTy { ty, mutbl }),
557            Pinnedness::Pinned => TyKind::PinnedRef(opt_lifetime, MutTy { ty, mutbl }),
558        })
559    }
560
561    /// Parses `pin` and `mut` annotations on references.
562    ///
563    /// It must be either `pin const` or `pin mut`.
564    pub(crate) fn parse_pin_and_mut(&mut self) -> Option<(Pinnedness, Mutability)> {
565        if self.token.is_ident_named(sym::pin) {
566            let result = self.look_ahead(1, |token| {
567                if token.is_keyword(kw::Const) {
568                    Some((Pinnedness::Pinned, Mutability::Not))
569                } else if token.is_keyword(kw::Mut) {
570                    Some((Pinnedness::Pinned, Mutability::Mut))
571                } else {
572                    None
573                }
574            });
575            if result.is_some() {
576                self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
577                self.bump();
578                self.bump();
579            }
580            result
581        } else {
582            None
583        }
584    }
585
586    // Parses the `typeof(EXPR)`.
587    // To avoid ambiguity, the type is surrounded by parentheses.
588    fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
589        self.expect(exp!(OpenParen))?;
590        let expr = self.parse_expr_anon_const()?;
591        self.expect(exp!(CloseParen))?;
592        Ok(TyKind::Typeof(expr))
593    }
594
595    /// Parses a function pointer type (`TyKind::BareFn`).
596    /// ```ignore (illustrative)
597    ///    [unsafe] [extern "ABI"] fn (S) -> T
598    /// //  ^~~~~^          ^~~~^     ^~^    ^
599    /// //    |               |        |     |
600    /// //    |               |        |   Return type
601    /// // Function Style    ABI  Parameter types
602    /// ```
603    /// We actually parse `FnHeader FnDecl`, but we error on `const` and `async` qualifiers.
604    fn parse_ty_bare_fn(
605        &mut self,
606        lo: Span,
607        mut params: ThinVec<GenericParam>,
608        param_insertion_point: Option<Span>,
609        recover_return_sign: RecoverReturnSign,
610    ) -> PResult<'a, TyKind> {
611        let inherited_vis = rustc_ast::Visibility {
612            span: rustc_span::DUMMY_SP,
613            kind: rustc_ast::VisibilityKind::Inherited,
614            tokens: None,
615        };
616        let span_start = self.token.span;
617        let ast::FnHeader { ext, safety, constness, coroutine_kind } =
618            self.parse_fn_front_matter(&inherited_vis, Case::Sensitive)?;
619        let fn_start_lo = self.prev_token.span.lo();
620        if self.may_recover() && self.token == TokenKind::Lt {
621            self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?;
622        }
623        let decl = self.parse_fn_decl(|_| false, AllowPlus::No, recover_return_sign)?;
624        let whole_span = lo.to(self.prev_token.span);
625
626        // Order/parsing of "front matter" follows:
627        // `<constness> <coroutine_kind> <safety> <extern> fn()`
628        //  ^           ^                ^        ^        ^
629        //  |           |                |        |        fn_start_lo
630        //  |           |                |        ext_sp.lo
631        //  |           |                safety_sp.lo
632        //  |           coroutine_sp.lo
633        //  const_sp.lo
634        if let ast::Const::Yes(const_span) = constness {
635            let next_token_lo = if let Some(
636                ast::CoroutineKind::Async { span, .. }
637                | ast::CoroutineKind::Gen { span, .. }
638                | ast::CoroutineKind::AsyncGen { span, .. },
639            ) = coroutine_kind
640            {
641                span.lo()
642            } else if let ast::Safety::Unsafe(span) | ast::Safety::Safe(span) = safety {
643                span.lo()
644            } else if let ast::Extern::Implicit(span) | ast::Extern::Explicit(_, span) = ext {
645                span.lo()
646            } else {
647                fn_start_lo
648            };
649            let sugg_span = const_span.with_hi(next_token_lo);
650            self.dcx().emit_err(FnPointerCannotBeConst {
651                span: whole_span,
652                qualifier: const_span,
653                suggestion: sugg_span,
654            });
655        }
656        if let Some(ast::CoroutineKind::Async { span: async_span, .. }) = coroutine_kind {
657            let next_token_lo = if let ast::Safety::Unsafe(span) | ast::Safety::Safe(span) = safety
658            {
659                span.lo()
660            } else if let ast::Extern::Implicit(span) | ast::Extern::Explicit(_, span) = ext {
661                span.lo()
662            } else {
663                fn_start_lo
664            };
665            let sugg_span = async_span.with_hi(next_token_lo);
666            self.dcx().emit_err(FnPointerCannotBeAsync {
667                span: whole_span,
668                qualifier: async_span,
669                suggestion: sugg_span,
670            });
671        }
672        // FIXME(gen_blocks): emit a similar error for `gen fn()`
673        let decl_span = span_start.to(self.prev_token.span);
674        Ok(TyKind::BareFn(P(BareFnTy { ext, safety, generic_params: params, decl, decl_span })))
675    }
676
677    /// Recover from function pointer types with a generic parameter list (e.g. `fn<'a>(&'a str)`).
678    fn recover_fn_ptr_with_generics(
679        &mut self,
680        lo: Span,
681        params: &mut ThinVec<GenericParam>,
682        param_insertion_point: Option<Span>,
683    ) -> PResult<'a, ()> {
684        let generics = self.parse_generics()?;
685        let arity = generics.params.len();
686
687        let mut lifetimes: ThinVec<_> = generics
688            .params
689            .into_iter()
690            .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime))
691            .collect();
692
693        let sugg = if !lifetimes.is_empty() {
694            let snippet =
695                lifetimes.iter().map(|param| param.ident.as_str()).intersperse(", ").collect();
696
697            let (left, snippet) = if let Some(span) = param_insertion_point {
698                (span, if params.is_empty() { snippet } else { format!(", {snippet}") })
699            } else {
700                (lo.shrink_to_lo(), format!("for<{snippet}> "))
701            };
702
703            Some(FnPtrWithGenericsSugg {
704                left,
705                snippet,
706                right: generics.span,
707                arity,
708                for_param_list_exists: param_insertion_point.is_some(),
709            })
710        } else {
711            None
712        };
713
714        self.dcx().emit_err(FnPtrWithGenerics { span: generics.span, sugg });
715        params.append(&mut lifetimes);
716        Ok(())
717    }
718
719    /// Parses an `impl B0 + ... + Bn` type.
720    fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
721        if self.token.is_lifetime() {
722            self.look_ahead(1, |t| {
723                if let token::Ident(sym, _) = t.kind {
724                    // parse pattern with "'a Sized" we're supposed to give suggestion like
725                    // "'a + Sized"
726                    self.dcx().emit_err(errors::MissingPlusBounds {
727                        span: self.token.span,
728                        hi: self.token.span.shrink_to_hi(),
729                        sym,
730                    });
731                }
732            })
733        }
734
735        // Always parse bounds greedily for better error recovery.
736        let bounds = self.parse_generic_bounds()?;
737
738        *impl_dyn_multi = bounds.len() > 1 || self.prev_token == TokenKind::Plus;
739
740        Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
741    }
742
743    fn parse_precise_capturing_args(
744        &mut self,
745    ) -> PResult<'a, (ThinVec<PreciseCapturingArg>, Span)> {
746        let lo = self.token.span;
747        self.expect_lt()?;
748        let (args, _, _) = self.parse_seq_to_before_tokens(
749            &[exp!(Gt)],
750            &[&TokenKind::Ge, &TokenKind::Shr, &TokenKind::Shr],
751            SeqSep::trailing_allowed(exp!(Comma)),
752            |self_| {
753                if self_.check_keyword(exp!(SelfUpper)) {
754                    self_.bump();
755                    Ok(PreciseCapturingArg::Arg(
756                        ast::Path::from_ident(self_.prev_token.ident().unwrap().0),
757                        DUMMY_NODE_ID,
758                    ))
759                } else if self_.check_ident() {
760                    Ok(PreciseCapturingArg::Arg(
761                        ast::Path::from_ident(self_.parse_ident()?),
762                        DUMMY_NODE_ID,
763                    ))
764                } else if self_.check_lifetime() {
765                    Ok(PreciseCapturingArg::Lifetime(self_.expect_lifetime()))
766                } else {
767                    self_.unexpected_any()
768                }
769            },
770        )?;
771        self.expect_gt()?;
772        Ok((args, lo.to(self.prev_token.span)))
773    }
774
775    /// Is a `dyn B0 + ... + Bn` type allowed here?
776    fn is_explicit_dyn_type(&mut self) -> bool {
777        self.check_keyword(exp!(Dyn))
778            && (self.token.uninterpolated_span().at_least_rust_2018()
779                || self.look_ahead(1, |t| {
780                    (can_begin_dyn_bound_in_edition_2015(t) || *t == TokenKind::Star)
781                        && !can_continue_type_after_non_fn_ident(t)
782                }))
783    }
784
785    /// Parses a `dyn B0 + ... + Bn` type.
786    ///
787    /// Note that this does *not* parse bare trait objects.
788    fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
789        let lo = self.token.span;
790        self.bump(); // `dyn`
791
792        // parse dyn* types
793        let syntax = if self.eat(exp!(Star)) {
794            self.psess.gated_spans.gate(sym::dyn_star, lo.to(self.prev_token.span));
795            TraitObjectSyntax::DynStar
796        } else {
797            TraitObjectSyntax::Dyn
798        };
799
800        // Always parse bounds greedily for better error recovery.
801        let bounds = self.parse_generic_bounds()?;
802        *impl_dyn_multi = bounds.len() > 1 || self.prev_token == TokenKind::Plus;
803        Ok(TyKind::TraitObject(bounds, syntax))
804    }
805
806    /// Parses a type starting with a path.
807    ///
808    /// This can be:
809    /// 1. a type macro, `mac!(...)`,
810    /// 2. a bare trait object, `B0 + ... + Bn`,
811    /// 3. or a path, `path::to::MyType`.
812    fn parse_path_start_ty(
813        &mut self,
814        lo: Span,
815        allow_plus: AllowPlus,
816        ty_generics: Option<&Generics>,
817    ) -> PResult<'a, TyKind> {
818        // Simple path
819        let path = self.parse_path_inner(PathStyle::Type, ty_generics)?;
820        if self.eat(exp!(Bang)) {
821            // Macro invocation in type position
822            Ok(TyKind::MacCall(P(MacCall { path, args: self.parse_delim_args()? })))
823        } else if allow_plus == AllowPlus::Yes && self.check_plus() {
824            // `Trait1 + Trait2 + 'a`
825            self.parse_remaining_bounds_path(ThinVec::new(), path, lo, true)
826        } else {
827            // Just a type path.
828            Ok(TyKind::Path(None, path))
829        }
830    }
831
832    pub(super) fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
833        self.parse_generic_bounds_common(AllowPlus::Yes)
834    }
835
836    /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
837    ///
838    /// See `parse_generic_bound` for the `BOUND` grammar.
839    fn parse_generic_bounds_common(&mut self, allow_plus: AllowPlus) -> PResult<'a, GenericBounds> {
840        let mut bounds = Vec::new();
841
842        // In addition to looping while we find generic bounds:
843        // We continue even if we find a keyword. This is necessary for error recovery on,
844        // for example, `impl fn()`. The only keyword that can go after generic bounds is
845        // `where`, so stop if it's it.
846        // We also continue if we find types (not traits), again for error recovery.
847        while self.can_begin_bound()
848            || (self.may_recover()
849                && (self.token.can_begin_type()
850                    || (self.token.is_reserved_ident() && !self.token.is_keyword(kw::Where))))
851        {
852            if self.token.is_keyword(kw::Dyn) {
853                // Account for `&dyn Trait + dyn Other`.
854                self.bump();
855                self.dcx().emit_err(InvalidDynKeyword {
856                    span: self.prev_token.span,
857                    suggestion: self.prev_token.span.until(self.token.span),
858                });
859            }
860            bounds.push(self.parse_generic_bound()?);
861            if allow_plus == AllowPlus::No || !self.eat_plus() {
862                break;
863            }
864        }
865
866        Ok(bounds)
867    }
868
869    /// Can the current token begin a bound?
870    fn can_begin_bound(&mut self) -> bool {
871        self.check_path()
872            || self.check_lifetime()
873            || self.check(exp!(Bang))
874            || self.check(exp!(Question))
875            || self.check(exp!(Tilde))
876            || self.check_keyword(exp!(For))
877            || self.check(exp!(OpenParen))
878            || self.check_keyword(exp!(Const))
879            || self.check_keyword(exp!(Async))
880            || self.check_keyword(exp!(Use))
881    }
882
883    /// Parses a bound according to the grammar:
884    /// ```ebnf
885    /// BOUND = TY_BOUND | LT_BOUND
886    /// ```
887    fn parse_generic_bound(&mut self) -> PResult<'a, GenericBound> {
888        let lo = self.token.span;
889        let leading_token = self.prev_token.clone();
890        let has_parens = self.eat(exp!(OpenParen));
891
892        let bound = if self.token.is_lifetime() {
893            self.parse_generic_lt_bound(lo, has_parens)?
894        } else if self.eat_keyword(exp!(Use)) {
895            // parse precise captures, if any. This is `use<'lt, 'lt, P, P>`; a list of
896            // lifetimes and ident params (including SelfUpper). These are validated later
897            // for order, duplication, and whether they actually reference params.
898            let use_span = self.prev_token.span;
899            let (args, args_span) = self.parse_precise_capturing_args()?;
900            GenericBound::Use(args, use_span.to(args_span))
901        } else {
902            self.parse_generic_ty_bound(lo, has_parens, &leading_token)?
903        };
904
905        Ok(bound)
906    }
907
908    /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to:
909    /// ```ebnf
910    /// LT_BOUND = LIFETIME
911    /// ```
912    fn parse_generic_lt_bound(&mut self, lo: Span, has_parens: bool) -> PResult<'a, GenericBound> {
913        let lt = self.expect_lifetime();
914        let bound = GenericBound::Outlives(lt);
915        if has_parens {
916            // FIXME(Centril): Consider not erroring here and accepting `('lt)` instead,
917            // possibly introducing `GenericBound::Paren(P<GenericBound>)`?
918            self.recover_paren_lifetime(lo)?;
919        }
920        Ok(bound)
921    }
922
923    /// Emits an error if any trait bound modifiers were present.
924    fn error_lt_bound_with_modifiers(
925        &self,
926        modifiers: TraitBoundModifiers,
927        binder_span: Option<Span>,
928    ) -> ErrorGuaranteed {
929        let TraitBoundModifiers { constness, asyncness, polarity } = modifiers;
930
931        match constness {
932            BoundConstness::Never => {}
933            BoundConstness::Always(span) | BoundConstness::Maybe(span) => {
934                return self
935                    .dcx()
936                    .emit_err(errors::ModifierLifetime { span, modifier: constness.as_str() });
937            }
938        }
939
940        match polarity {
941            BoundPolarity::Positive => {}
942            BoundPolarity::Negative(span) | BoundPolarity::Maybe(span) => {
943                return self
944                    .dcx()
945                    .emit_err(errors::ModifierLifetime { span, modifier: polarity.as_str() });
946            }
947        }
948
949        match asyncness {
950            BoundAsyncness::Normal => {}
951            BoundAsyncness::Async(span) => {
952                return self
953                    .dcx()
954                    .emit_err(errors::ModifierLifetime { span, modifier: asyncness.as_str() });
955            }
956        }
957
958        if let Some(span) = binder_span {
959            return self.dcx().emit_err(errors::ModifierLifetime { span, modifier: "for<...>" });
960        }
961
962        unreachable!("lifetime bound intercepted in `parse_generic_ty_bound` but no modifiers?")
963    }
964
965    /// Recover on `('lifetime)` with `(` already eaten.
966    fn recover_paren_lifetime(&mut self, lo: Span) -> PResult<'a, ()> {
967        self.expect(exp!(CloseParen))?;
968        let span = lo.to(self.prev_token.span);
969        let sugg = errors::RemoveParens { lo, hi: self.prev_token.span };
970
971        self.dcx().emit_err(errors::ParenthesizedLifetime { span, sugg });
972        Ok(())
973    }
974
975    /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `~const Trait`.
976    ///
977    /// If no modifiers are present, this does not consume any tokens.
978    ///
979    /// ```ebnf
980    /// CONSTNESS = [["~"] "const"]
981    /// ASYNCNESS = ["async"]
982    /// POLARITY = ["?" | "!"]
983    /// ```
984    ///
985    /// See `parse_generic_ty_bound` for the complete grammar of trait bound modifiers.
986    fn parse_trait_bound_modifiers(&mut self) -> PResult<'a, TraitBoundModifiers> {
987        let modifier_lo = self.token.span;
988        let constness = if self.eat(exp!(Tilde)) {
989            let tilde = self.prev_token.span;
990            self.expect_keyword(exp!(Const))?;
991            let span = tilde.to(self.prev_token.span);
992            self.psess.gated_spans.gate(sym::const_trait_impl, span);
993            BoundConstness::Maybe(span)
994        } else if self.eat_keyword(exp!(Const)) {
995            self.psess.gated_spans.gate(sym::const_trait_impl, self.prev_token.span);
996            BoundConstness::Always(self.prev_token.span)
997        } else {
998            BoundConstness::Never
999        };
1000
1001        let asyncness = if self.token.uninterpolated_span().at_least_rust_2018()
1002            && self.eat_keyword(exp!(Async))
1003        {
1004            self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
1005            BoundAsyncness::Async(self.prev_token.span)
1006        } else if self.may_recover()
1007            && self.token.uninterpolated_span().is_rust_2015()
1008            && self.is_kw_followed_by_ident(kw::Async)
1009        {
1010            self.bump(); // eat `async`
1011            self.dcx().emit_err(errors::AsyncBoundModifierIn2015 {
1012                span: self.prev_token.span,
1013                help: HelpUseLatestEdition::new(),
1014            });
1015            self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
1016            BoundAsyncness::Async(self.prev_token.span)
1017        } else {
1018            BoundAsyncness::Normal
1019        };
1020        let modifier_hi = self.prev_token.span;
1021
1022        let polarity = if self.eat(exp!(Question)) {
1023            BoundPolarity::Maybe(self.prev_token.span)
1024        } else if self.eat(exp!(Bang)) {
1025            self.psess.gated_spans.gate(sym::negative_bounds, self.prev_token.span);
1026            BoundPolarity::Negative(self.prev_token.span)
1027        } else {
1028            BoundPolarity::Positive
1029        };
1030
1031        // Enforce the mutual-exclusivity of `const`/`async` and `?`/`!`.
1032        match polarity {
1033            BoundPolarity::Positive => {
1034                // All trait bound modifiers allowed to combine with positive polarity
1035            }
1036            BoundPolarity::Maybe(polarity_span) | BoundPolarity::Negative(polarity_span) => {
1037                match (asyncness, constness) {
1038                    (BoundAsyncness::Normal, BoundConstness::Never) => {
1039                        // Ok, no modifiers.
1040                    }
1041                    (_, _) => {
1042                        let constness = constness.as_str();
1043                        let asyncness = asyncness.as_str();
1044                        let glue =
1045                            if !constness.is_empty() && !asyncness.is_empty() { " " } else { "" };
1046                        let modifiers_concatenated = format!("{constness}{glue}{asyncness}");
1047                        self.dcx().emit_err(errors::PolarityAndModifiers {
1048                            polarity_span,
1049                            polarity: polarity.as_str(),
1050                            modifiers_span: modifier_lo.to(modifier_hi),
1051                            modifiers_concatenated,
1052                        });
1053                    }
1054                }
1055            }
1056        }
1057
1058        Ok(TraitBoundModifiers { constness, asyncness, polarity })
1059    }
1060
1061    /// Parses a type bound according to:
1062    /// ```ebnf
1063    /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
1064    /// TY_BOUND_NOPAREN = [for<GENERIC_PARAMS> CONSTNESS ASYNCNESS | POLARITY] SIMPLE_PATH
1065    /// ```
1066    ///
1067    /// For example, this grammar accepts `for<'a: 'b> ~const ?m::Trait<'a>`.
1068    fn parse_generic_ty_bound(
1069        &mut self,
1070        lo: Span,
1071        has_parens: bool,
1072        leading_token: &Token,
1073    ) -> PResult<'a, GenericBound> {
1074        let (mut lifetime_defs, binder_span) = self.parse_late_bound_lifetime_defs()?;
1075
1076        let modifiers_lo = self.token.span;
1077        let modifiers = self.parse_trait_bound_modifiers()?;
1078        let modifiers_span = modifiers_lo.to(self.prev_token.span);
1079
1080        if let Some(binder_span) = binder_span {
1081            match modifiers.polarity {
1082                BoundPolarity::Negative(polarity_span) | BoundPolarity::Maybe(polarity_span) => {
1083                    self.dcx().emit_err(errors::BinderAndPolarity {
1084                        binder_span,
1085                        polarity_span,
1086                        polarity: modifiers.polarity.as_str(),
1087                    });
1088                }
1089                BoundPolarity::Positive => {}
1090            }
1091        }
1092
1093        // Recover erroneous lifetime bound with modifiers or binder.
1094        // e.g. `T: for<'a> 'a` or `T: ~const 'a`.
1095        if self.token.is_lifetime() {
1096            let _: ErrorGuaranteed = self.error_lt_bound_with_modifiers(modifiers, binder_span);
1097            return self.parse_generic_lt_bound(lo, has_parens);
1098        }
1099
1100        if let (more_lifetime_defs, Some(binder_span)) = self.parse_late_bound_lifetime_defs()? {
1101            lifetime_defs.extend(more_lifetime_defs);
1102            self.dcx().emit_err(errors::BinderBeforeModifiers { binder_span, modifiers_span });
1103        }
1104
1105        let mut path = if self.token.is_keyword(kw::Fn)
1106            && self.look_ahead(1, |t| *t == TokenKind::OpenDelim(Delimiter::Parenthesis))
1107            && let Some(path) = self.recover_path_from_fn()
1108        {
1109            path
1110        } else if !self.token.is_path_start() && self.token.can_begin_type() {
1111            let ty = self.parse_ty_no_plus()?;
1112            // Instead of finding a path (a trait), we found a type.
1113            let mut err = self.dcx().struct_span_err(ty.span, "expected a trait, found type");
1114
1115            // If we can recover, try to extract a path from the type. Note
1116            // that we do not use the try operator when parsing the type because
1117            // if it fails then we get a parser error which we don't want (we're trying
1118            // to recover from errors, not make more).
1119            let path = if self.may_recover() {
1120                let (span, message, sugg, path, applicability) = match &ty.kind {
1121                    TyKind::Ptr(..) | TyKind::Ref(..)
1122                        if let TyKind::Path(_, path) = &ty.peel_refs().kind =>
1123                    {
1124                        (
1125                            ty.span.until(path.span),
1126                            "consider removing the indirection",
1127                            "",
1128                            path,
1129                            Applicability::MaybeIncorrect,
1130                        )
1131                    }
1132                    TyKind::ImplTrait(_, bounds)
1133                        if let [GenericBound::Trait(tr, ..), ..] = bounds.as_slice() =>
1134                    {
1135                        (
1136                            ty.span.until(tr.span),
1137                            "use the trait bounds directly",
1138                            "",
1139                            &tr.trait_ref.path,
1140                            Applicability::MachineApplicable,
1141                        )
1142                    }
1143                    _ => return Err(err),
1144                };
1145
1146                err.span_suggestion_verbose(span, message, sugg, applicability);
1147
1148                path.clone()
1149            } else {
1150                return Err(err);
1151            };
1152
1153            err.emit();
1154
1155            path
1156        } else {
1157            self.parse_path(PathStyle::Type)?
1158        };
1159
1160        if self.may_recover() && self.token == TokenKind::OpenDelim(Delimiter::Parenthesis) {
1161            self.recover_fn_trait_with_lifetime_params(&mut path, &mut lifetime_defs)?;
1162        }
1163
1164        if has_parens {
1165            // Someone has written something like `&dyn (Trait + Other)`. The correct code
1166            // would be `&(dyn Trait + Other)`
1167            if self.token.is_like_plus() && leading_token.is_keyword(kw::Dyn) {
1168                let bounds = vec![];
1169                self.parse_remaining_bounds(bounds, true)?;
1170                self.expect(exp!(CloseParen))?;
1171                self.dcx().emit_err(errors::IncorrectParensTraitBounds {
1172                    span: vec![lo, self.prev_token.span],
1173                    sugg: errors::IncorrectParensTraitBoundsSugg {
1174                        wrong_span: leading_token.span.shrink_to_hi().to(lo),
1175                        new_span: leading_token.span.shrink_to_lo(),
1176                    },
1177                });
1178            } else {
1179                self.expect(exp!(CloseParen))?;
1180            }
1181        }
1182
1183        let poly_trait =
1184            PolyTraitRef::new(lifetime_defs, path, modifiers, lo.to(self.prev_token.span));
1185        Ok(GenericBound::Trait(poly_trait))
1186    }
1187
1188    // recovers a `Fn(..)` parenthesized-style path from `fn(..)`
1189    fn recover_path_from_fn(&mut self) -> Option<ast::Path> {
1190        let fn_token_span = self.token.span;
1191        self.bump();
1192        let args_lo = self.token.span;
1193        let snapshot = self.create_snapshot_for_diagnostic();
1194        match self.parse_fn_decl(|_| false, AllowPlus::No, RecoverReturnSign::OnlyFatArrow) {
1195            Ok(decl) => {
1196                self.dcx().emit_err(ExpectedFnPathFoundFnKeyword { fn_token_span });
1197                Some(ast::Path {
1198                    span: fn_token_span.to(self.prev_token.span),
1199                    segments: thin_vec![ast::PathSegment {
1200                        ident: Ident::new(sym::Fn, fn_token_span),
1201                        id: DUMMY_NODE_ID,
1202                        args: Some(P(ast::GenericArgs::Parenthesized(ast::ParenthesizedArgs {
1203                            span: args_lo.to(self.prev_token.span),
1204                            inputs: decl.inputs.iter().map(|a| a.ty.clone()).collect(),
1205                            inputs_span: args_lo.until(decl.output.span()),
1206                            output: decl.output.clone(),
1207                        }))),
1208                    }],
1209                    tokens: None,
1210                })
1211            }
1212            Err(diag) => {
1213                diag.cancel();
1214                self.restore_snapshot(snapshot);
1215                None
1216            }
1217        }
1218    }
1219
1220    /// Optionally parses `for<$generic_params>`.
1221    pub(super) fn parse_late_bound_lifetime_defs(
1222        &mut self,
1223    ) -> PResult<'a, (ThinVec<GenericParam>, Option<Span>)> {
1224        if self.eat_keyword(exp!(For)) {
1225            let lo = self.token.span;
1226            self.expect_lt()?;
1227            let params = self.parse_generic_params()?;
1228            self.expect_gt()?;
1229            // We rely on AST validation to rule out invalid cases: There must not be
1230            // type or const parameters, and parameters must not have bounds.
1231            Ok((params, Some(lo.to(self.prev_token.span))))
1232        } else {
1233            Ok((ThinVec::new(), None))
1234        }
1235    }
1236
1237    /// Recover from `Fn`-family traits (Fn, FnMut, FnOnce) with lifetime arguments
1238    /// (e.g. `FnOnce<'a>(&'a str) -> bool`). Up to generic arguments have already
1239    /// been eaten.
1240    fn recover_fn_trait_with_lifetime_params(
1241        &mut self,
1242        fn_path: &mut ast::Path,
1243        lifetime_defs: &mut ThinVec<GenericParam>,
1244    ) -> PResult<'a, ()> {
1245        let fn_path_segment = fn_path.segments.last_mut().unwrap();
1246        let generic_args = if let Some(p_args) = &fn_path_segment.args {
1247            p_args.clone().into_inner()
1248        } else {
1249            // Normally it wouldn't come here because the upstream should have parsed
1250            // generic parameters (otherwise it's impossible to call this function).
1251            return Ok(());
1252        };
1253        let lifetimes =
1254            if let ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { span: _, args }) =
1255                &generic_args
1256            {
1257                args.into_iter()
1258                    .filter_map(|arg| {
1259                        if let ast::AngleBracketedArg::Arg(generic_arg) = arg
1260                            && let ast::GenericArg::Lifetime(lifetime) = generic_arg
1261                        {
1262                            Some(lifetime)
1263                        } else {
1264                            None
1265                        }
1266                    })
1267                    .collect()
1268            } else {
1269                Vec::new()
1270            };
1271        // Only try to recover if the trait has lifetime params.
1272        if lifetimes.is_empty() {
1273            return Ok(());
1274        }
1275
1276        // Parse `(T, U) -> R`.
1277        let inputs_lo = self.token.span;
1278        let inputs: ThinVec<_> =
1279            self.parse_fn_params(|_| false)?.into_iter().map(|input| input.ty).collect();
1280        let inputs_span = inputs_lo.to(self.prev_token.span);
1281        let output = self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?;
1282        let args = ast::ParenthesizedArgs {
1283            span: fn_path_segment.span().to(self.prev_token.span),
1284            inputs,
1285            inputs_span,
1286            output,
1287        }
1288        .into();
1289        *fn_path_segment = ast::PathSegment {
1290            ident: fn_path_segment.ident,
1291            args: Some(args),
1292            id: ast::DUMMY_NODE_ID,
1293        };
1294
1295        // Convert parsed `<'a>` in `Fn<'a>` into `for<'a>`.
1296        let mut generic_params = lifetimes
1297            .iter()
1298            .map(|lt| GenericParam {
1299                id: lt.id,
1300                ident: lt.ident,
1301                attrs: ast::AttrVec::new(),
1302                bounds: Vec::new(),
1303                is_placeholder: false,
1304                kind: ast::GenericParamKind::Lifetime,
1305                colon_span: None,
1306            })
1307            .collect::<ThinVec<GenericParam>>();
1308        lifetime_defs.append(&mut generic_params);
1309
1310        let generic_args_span = generic_args.span();
1311        let snippet = format!(
1312            "for<{}> ",
1313            lifetimes.iter().map(|lt| lt.ident.as_str()).intersperse(", ").collect::<String>(),
1314        );
1315        let before_fn_path = fn_path.span.shrink_to_lo();
1316        self.dcx()
1317            .struct_span_err(generic_args_span, "`Fn` traits cannot take lifetime parameters")
1318            .with_multipart_suggestion(
1319                "consider using a higher-ranked trait bound instead",
1320                vec![(generic_args_span, "".to_owned()), (before_fn_path, snippet)],
1321                Applicability::MaybeIncorrect,
1322            )
1323            .emit();
1324        Ok(())
1325    }
1326
1327    pub(super) fn check_lifetime(&mut self) -> bool {
1328        self.expected_token_types.insert(TokenType::Lifetime);
1329        self.token.is_lifetime()
1330    }
1331
1332    /// Parses a single lifetime `'a` or panics.
1333    pub(super) fn expect_lifetime(&mut self) -> Lifetime {
1334        if let Some((ident, is_raw)) = self.token.lifetime() {
1335            if matches!(is_raw, IdentIsRaw::No)
1336                && ident.without_first_quote().is_reserved()
1337                && ![kw::UnderscoreLifetime, kw::StaticLifetime].contains(&ident.name)
1338            {
1339                self.dcx().emit_err(errors::KeywordLifetime { span: ident.span });
1340            }
1341
1342            self.bump();
1343            Lifetime { ident, id: ast::DUMMY_NODE_ID }
1344        } else {
1345            self.dcx().span_bug(self.token.span, "not a lifetime")
1346        }
1347    }
1348
1349    pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
1350        P(Ty { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })
1351    }
1352}