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