Skip to main content

rustc_parse/parser/
ty.rs

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