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