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