]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/ty.rs
Rollup merge of #102977 - lukas-code:is-sorted-hrtb, r=m-ou-se
[rust.git] / compiler / rustc_parse / src / parser / ty.rs
1 use super::{Parser, PathStyle, TokenType};
2
3 use crate::errors::{FnPtrWithGenerics, FnPtrWithGenericsSugg};
4 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
5
6 use rustc_ast::ptr::P;
7 use rustc_ast::token::{self, Delimiter, Token, TokenKind};
8 use rustc_ast::util::case::Case;
9 use rustc_ast::{
10     self as ast, BareFnTy, FnRetTy, GenericBound, GenericBounds, GenericParam, Generics, Lifetime,
11     MacCall, MutTy, Mutability, PolyTraitRef, TraitBoundModifier, TraitObjectSyntax, Ty, TyKind,
12 };
13 use rustc_errors::{pluralize, struct_span_err, Applicability, PResult};
14 use rustc_span::source_map::Span;
15 use rustc_span::symbol::{kw, sym};
16
17 /// Any `?` or `~const` modifiers that appear at the start of a bound.
18 struct BoundModifiers {
19     /// `?Trait`.
20     maybe: Option<Span>,
21
22     /// `~const Trait`.
23     maybe_const: Option<Span>,
24 }
25
26 impl BoundModifiers {
27     fn to_trait_bound_modifier(&self) -> TraitBoundModifier {
28         match (self.maybe, self.maybe_const) {
29             (None, None) => TraitBoundModifier::None,
30             (Some(_), None) => TraitBoundModifier::Maybe,
31             (None, Some(_)) => TraitBoundModifier::MaybeConst,
32             (Some(_), Some(_)) => TraitBoundModifier::MaybeConstMaybe,
33         }
34     }
35 }
36
37 #[derive(Copy, Clone, PartialEq)]
38 pub(super) enum AllowPlus {
39     Yes,
40     No,
41 }
42
43 #[derive(PartialEq)]
44 pub(super) enum RecoverQPath {
45     Yes,
46     No,
47 }
48
49 pub(super) enum RecoverQuestionMark {
50     Yes,
51     No,
52 }
53
54 /// Signals whether parsing a type should recover `->`.
55 ///
56 /// More specifically, when parsing a function like:
57 /// ```compile_fail
58 /// fn foo() => u8 { 0 }
59 /// fn bar(): u8 { 0 }
60 /// ```
61 /// The compiler will try to recover interpreting `foo() => u8` as `foo() -> u8` when calling
62 /// `parse_ty` with anything except `RecoverReturnSign::No`, and it will try to recover `bar(): u8`
63 /// as `bar() -> u8` when passing `RecoverReturnSign::Yes` to `parse_ty`
64 #[derive(Copy, Clone, PartialEq)]
65 pub(super) enum RecoverReturnSign {
66     Yes,
67     OnlyFatArrow,
68     No,
69 }
70
71 impl RecoverReturnSign {
72     /// [RecoverReturnSign::Yes] allows for recovering `fn foo() => u8` and `fn foo(): u8`,
73     /// [RecoverReturnSign::OnlyFatArrow] allows for recovering only `fn foo() => u8` (recovering
74     /// colons can cause problems when parsing where clauses), and
75     /// [RecoverReturnSign::No] doesn't allow for any recovery of the return type arrow
76     fn can_recover(self, token: &TokenKind) -> bool {
77         match self {
78             Self::Yes => matches!(token, token::FatArrow | token::Colon),
79             Self::OnlyFatArrow => matches!(token, token::FatArrow),
80             Self::No => false,
81         }
82     }
83 }
84
85 // Is `...` (`CVarArgs`) legal at this level of type parsing?
86 #[derive(PartialEq)]
87 enum AllowCVariadic {
88     Yes,
89     No,
90 }
91
92 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
93 /// `IDENT<<u8 as Trait>::AssocTy>`.
94 ///
95 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
96 /// that `IDENT` is not the ident of a fn trait.
97 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
98     t == &token::ModSep || t == &token::Lt || t == &token::BinOp(token::Shl)
99 }
100
101 impl<'a> Parser<'a> {
102     /// Parses a type.
103     pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
104         self.parse_ty_common(
105             AllowPlus::Yes,
106             AllowCVariadic::No,
107             RecoverQPath::Yes,
108             RecoverReturnSign::Yes,
109             None,
110             RecoverQuestionMark::Yes,
111         )
112     }
113
114     pub(super) fn parse_ty_with_generics_recovery(
115         &mut self,
116         ty_params: &Generics,
117     ) -> PResult<'a, P<Ty>> {
118         self.parse_ty_common(
119             AllowPlus::Yes,
120             AllowCVariadic::No,
121             RecoverQPath::Yes,
122             RecoverReturnSign::Yes,
123             Some(ty_params),
124             RecoverQuestionMark::Yes,
125         )
126     }
127
128     /// Parse a type suitable for a function or function pointer parameter.
129     /// The difference from `parse_ty` is that this version allows `...`
130     /// (`CVarArgs`) at the top level of the type.
131     pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, P<Ty>> {
132         self.parse_ty_common(
133             AllowPlus::Yes,
134             AllowCVariadic::Yes,
135             RecoverQPath::Yes,
136             RecoverReturnSign::Yes,
137             None,
138             RecoverQuestionMark::Yes,
139         )
140     }
141
142     /// Parses a type in restricted contexts where `+` is not permitted.
143     ///
144     /// Example 1: `&'a TYPE`
145     ///     `+` is prohibited to maintain operator priority (P(+) < P(&)).
146     /// Example 2: `value1 as TYPE + value2`
147     ///     `+` is prohibited to avoid interactions with expression grammar.
148     pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
149         self.parse_ty_common(
150             AllowPlus::No,
151             AllowCVariadic::No,
152             RecoverQPath::Yes,
153             RecoverReturnSign::Yes,
154             None,
155             RecoverQuestionMark::Yes,
156         )
157     }
158
159     /// Parses a type following an `as` cast. Similar to `parse_ty_no_plus`, but signaling origin
160     /// for better diagnostics involving `?`.
161     pub(super) fn parse_as_cast_ty(&mut self) -> PResult<'a, P<Ty>> {
162         self.parse_ty_common(
163             AllowPlus::No,
164             AllowCVariadic::No,
165             RecoverQPath::Yes,
166             RecoverReturnSign::Yes,
167             None,
168             RecoverQuestionMark::No,
169         )
170     }
171
172     pub(super) fn parse_no_question_mark_recover(&mut self) -> PResult<'a, P<Ty>> {
173         self.parse_ty_common(
174             AllowPlus::Yes,
175             AllowCVariadic::No,
176             RecoverQPath::Yes,
177             RecoverReturnSign::Yes,
178             None,
179             RecoverQuestionMark::No,
180         )
181     }
182
183     /// Parse a type without recovering `:` as `->` to avoid breaking code such as `where fn() : for<'a>`
184     pub(super) fn parse_ty_for_where_clause(&mut self) -> PResult<'a, P<Ty>> {
185         self.parse_ty_common(
186             AllowPlus::Yes,
187             AllowCVariadic::Yes,
188             RecoverQPath::Yes,
189             RecoverReturnSign::OnlyFatArrow,
190             None,
191             RecoverQuestionMark::Yes,
192         )
193     }
194
195     /// Parses an optional return type `[ -> TY ]` in a function declaration.
196     pub(super) fn parse_ret_ty(
197         &mut self,
198         allow_plus: AllowPlus,
199         recover_qpath: RecoverQPath,
200         recover_return_sign: RecoverReturnSign,
201     ) -> PResult<'a, FnRetTy> {
202         Ok(if self.eat(&token::RArrow) {
203             // FIXME(Centril): Can we unconditionally `allow_plus`?
204             let ty = self.parse_ty_common(
205                 allow_plus,
206                 AllowCVariadic::No,
207                 recover_qpath,
208                 recover_return_sign,
209                 None,
210                 RecoverQuestionMark::Yes,
211             )?;
212             FnRetTy::Ty(ty)
213         } else if recover_return_sign.can_recover(&self.token.kind) {
214             // Don't `eat` to prevent `=>` from being added as an expected token which isn't
215             // actually expected and could only confuse users
216             self.bump();
217             self.struct_span_err(self.prev_token.span, "return types are denoted using `->`")
218                 .span_suggestion_short(
219                     self.prev_token.span,
220                     "use `->` instead",
221                     "->",
222                     Applicability::MachineApplicable,
223                 )
224                 .emit();
225             let ty = self.parse_ty_common(
226                 allow_plus,
227                 AllowCVariadic::No,
228                 recover_qpath,
229                 recover_return_sign,
230                 None,
231                 RecoverQuestionMark::Yes,
232             )?;
233             FnRetTy::Ty(ty)
234         } else {
235             FnRetTy::Default(self.token.span.shrink_to_lo())
236         })
237     }
238
239     fn parse_ty_common(
240         &mut self,
241         allow_plus: AllowPlus,
242         allow_c_variadic: AllowCVariadic,
243         recover_qpath: RecoverQPath,
244         recover_return_sign: RecoverReturnSign,
245         ty_generics: Option<&Generics>,
246         recover_question_mark: RecoverQuestionMark,
247     ) -> PResult<'a, P<Ty>> {
248         let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes;
249         maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
250         maybe_whole!(self, NtTy, |x| x);
251
252         let lo = self.token.span;
253         let mut impl_dyn_multi = false;
254         let kind = if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
255             self.parse_ty_tuple_or_parens(lo, allow_plus)?
256         } else if self.eat(&token::Not) {
257             // Never type `!`
258             TyKind::Never
259         } else if self.eat(&token::BinOp(token::Star)) {
260             self.parse_ty_ptr()?
261         } else if self.eat(&token::OpenDelim(Delimiter::Bracket)) {
262             self.parse_array_or_slice_ty()?
263         } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
264             // Reference
265             self.expect_and()?;
266             self.parse_borrowed_pointee()?
267         } else if self.eat_keyword_noexpect(kw::Typeof) {
268             self.parse_typeof_ty()?
269         } else if self.eat_keyword(kw::Underscore) {
270             // A type to be inferred `_`
271             TyKind::Infer
272         } else if self.check_fn_front_matter(false, Case::Sensitive) {
273             // Function pointer type
274             self.parse_ty_bare_fn(lo, Vec::new(), None, recover_return_sign)?
275         } else if self.check_keyword(kw::For) {
276             // Function pointer type or bound list (trait object type) starting with a poly-trait.
277             //   `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
278             //   `for<'lt> Trait1<'lt> + Trait2 + 'a`
279             let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
280             if self.check_fn_front_matter(false, Case::Sensitive) {
281                 self.parse_ty_bare_fn(
282                     lo,
283                     lifetime_defs,
284                     Some(self.prev_token.span.shrink_to_lo()),
285                     recover_return_sign,
286                 )?
287             } else {
288                 let path = self.parse_path(PathStyle::Type)?;
289                 let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
290                 self.parse_remaining_bounds_path(lifetime_defs, path, lo, parse_plus)?
291             }
292         } else if self.eat_keyword(kw::Impl) {
293             self.parse_impl_ty(&mut impl_dyn_multi)?
294         } else if self.is_explicit_dyn_type() {
295             self.parse_dyn_ty(&mut impl_dyn_multi)?
296         } else if self.eat_lt() {
297             // Qualified path
298             let (qself, path) = self.parse_qpath(PathStyle::Type)?;
299             TyKind::Path(Some(qself), path)
300         } else if self.check_path() {
301             self.parse_path_start_ty(lo, allow_plus, ty_generics)?
302         } else if self.can_begin_bound() {
303             self.parse_bare_trait_object(lo, allow_plus)?
304         } else if self.eat(&token::DotDotDot) {
305             if allow_c_variadic == AllowCVariadic::Yes {
306                 TyKind::CVarArgs
307             } else {
308                 // FIXME(Centril): Should we just allow `...` syntactically
309                 // anywhere in a type and use semantic restrictions instead?
310                 self.error_illegal_c_varadic_ty(lo);
311                 TyKind::Err
312             }
313         } else {
314             let msg = format!("expected type, found {}", super::token_descr(&self.token));
315             let mut err = self.struct_span_err(self.token.span, &msg);
316             err.span_label(self.token.span, "expected type");
317             self.maybe_annotate_with_ascription(&mut err, true);
318             return Err(err);
319         };
320
321         let span = lo.to(self.prev_token.span);
322         let mut ty = self.mk_ty(span, kind);
323
324         // Try to recover from use of `+` with incorrect priority.
325         if matches!(allow_plus, AllowPlus::Yes) {
326             self.maybe_recover_from_bad_type_plus(&ty)?;
327         } else {
328             self.maybe_report_ambiguous_plus(impl_dyn_multi, &ty);
329         }
330         if let RecoverQuestionMark::Yes = recover_question_mark {
331             ty = self.maybe_recover_from_question_mark(ty);
332         }
333         if allow_qpath_recovery { self.maybe_recover_from_bad_qpath(ty) } else { Ok(ty) }
334     }
335
336     /// Parses either:
337     /// - `(TYPE)`, a parenthesized type.
338     /// - `(TYPE,)`, a tuple with a single field of type TYPE.
339     fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
340         let mut trailing_plus = false;
341         let (ts, trailing) = self.parse_paren_comma_seq(|p| {
342             let ty = p.parse_ty()?;
343             trailing_plus = p.prev_token.kind == TokenKind::BinOp(token::Plus);
344             Ok(ty)
345         })?;
346
347         if ts.len() == 1 && !trailing {
348             let ty = ts.into_iter().next().unwrap().into_inner();
349             let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
350             match ty.kind {
351                 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
352                 TyKind::Path(None, path) if maybe_bounds => {
353                     self.parse_remaining_bounds_path(Vec::new(), path, lo, true)
354                 }
355                 TyKind::TraitObject(bounds, TraitObjectSyntax::None)
356                     if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
357                 {
358                     self.parse_remaining_bounds(bounds, true)
359                 }
360                 // `(TYPE)`
361                 _ => Ok(TyKind::Paren(P(ty))),
362             }
363         } else {
364             Ok(TyKind::Tup(ts))
365         }
366     }
367
368     fn parse_bare_trait_object(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
369         let lt_no_plus = self.check_lifetime() && !self.look_ahead(1, |t| t.is_like_plus());
370         let bounds = self.parse_generic_bounds_common(allow_plus, None)?;
371         if lt_no_plus {
372             self.struct_span_err(lo, "lifetime in trait object type must be followed by `+`")
373                 .emit();
374         }
375         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
376     }
377
378     fn parse_remaining_bounds_path(
379         &mut self,
380         generic_params: Vec<GenericParam>,
381         path: ast::Path,
382         lo: Span,
383         parse_plus: bool,
384     ) -> PResult<'a, TyKind> {
385         let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_token.span));
386         let bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
387         self.parse_remaining_bounds(bounds, parse_plus)
388     }
389
390     /// Parse the remainder of a bare trait object type given an already parsed list.
391     fn parse_remaining_bounds(
392         &mut self,
393         mut bounds: GenericBounds,
394         plus: bool,
395     ) -> PResult<'a, TyKind> {
396         if plus {
397             self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
398             bounds.append(&mut self.parse_generic_bounds(Some(self.prev_token.span))?);
399         }
400         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
401     }
402
403     /// Parses a raw pointer type: `*[const | mut] $type`.
404     fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
405         let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
406             let span = self.prev_token.span;
407             self.struct_span_err(span, "expected `mut` or `const` keyword in raw pointer type")
408                 .span_suggestions(
409                     span.shrink_to_hi(),
410                     "add `mut` or `const` here",
411                     ["mut ".to_string(), "const ".to_string()],
412                     Applicability::HasPlaceholders,
413                 )
414                 .emit();
415             Mutability::Not
416         });
417         let ty = self.parse_ty_no_plus()?;
418         Ok(TyKind::Ptr(MutTy { ty, mutbl }))
419     }
420
421     /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
422     /// The opening `[` bracket is already eaten.
423     fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
424         let elt_ty = match self.parse_ty() {
425             Ok(ty) => ty,
426             Err(mut err)
427                 if self.look_ahead(1, |t| t.kind == token::CloseDelim(Delimiter::Bracket))
428                     | self.look_ahead(1, |t| t.kind == token::Semi) =>
429             {
430                 // Recover from `[LIT; EXPR]` and `[LIT]`
431                 self.bump();
432                 err.emit();
433                 self.mk_ty(self.prev_token.span, TyKind::Err)
434             }
435             Err(err) => return Err(err),
436         };
437
438         let ty = if self.eat(&token::Semi) {
439             let mut length = self.parse_anon_const_expr()?;
440             if let Err(e) = self.expect(&token::CloseDelim(Delimiter::Bracket)) {
441                 // Try to recover from `X<Y, ...>` when `X::<Y, ...>` works
442                 self.check_mistyped_turbofish_with_multiple_type_params(e, &mut length.value)?;
443                 self.expect(&token::CloseDelim(Delimiter::Bracket))?;
444             }
445             TyKind::Array(elt_ty, length)
446         } else {
447             self.expect(&token::CloseDelim(Delimiter::Bracket))?;
448             TyKind::Slice(elt_ty)
449         };
450
451         Ok(ty)
452     }
453
454     fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
455         let and_span = self.prev_token.span;
456         let mut opt_lifetime =
457             if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
458         let mut mutbl = self.parse_mutability();
459         if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() {
460             // A lifetime is invalid here: it would be part of a bare trait bound, which requires
461             // it to be followed by a plus, but we disallow plus in the pointee type.
462             // So we can handle this case as an error here, and suggest `'a mut`.
463             // If there *is* a plus next though, handling the error later provides better suggestions
464             // (like adding parentheses)
465             if !self.look_ahead(1, |t| t.is_like_plus()) {
466                 let lifetime_span = self.token.span;
467                 let span = and_span.to(lifetime_span);
468
469                 let mut err = self.struct_span_err(span, "lifetime must precede `mut`");
470                 if let Ok(lifetime_src) = self.span_to_snippet(lifetime_span) {
471                     err.span_suggestion(
472                         span,
473                         "place the lifetime before `mut`",
474                         format!("&{} mut", lifetime_src),
475                         Applicability::MaybeIncorrect,
476                     );
477                 }
478                 err.emit();
479
480                 opt_lifetime = Some(self.expect_lifetime());
481             }
482         } else if self.token.is_keyword(kw::Dyn)
483             && mutbl == Mutability::Not
484             && self.look_ahead(1, |t| t.is_keyword(kw::Mut))
485         {
486             // We have `&dyn mut ...`, which is invalid and should be `&mut dyn ...`.
487             let span = and_span.to(self.look_ahead(1, |t| t.span));
488             let mut err = self.struct_span_err(span, "`mut` must precede `dyn`");
489             err.span_suggestion(
490                 span,
491                 "place `mut` before `dyn`",
492                 "&mut dyn",
493                 Applicability::MachineApplicable,
494             );
495             err.emit();
496
497             // Recovery
498             mutbl = Mutability::Mut;
499             let (dyn_tok, dyn_tok_sp) = (self.token.clone(), self.token_spacing);
500             self.bump();
501             self.bump_with((dyn_tok, dyn_tok_sp));
502         }
503         let ty = self.parse_ty_no_plus()?;
504         Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }))
505     }
506
507     // Parses the `typeof(EXPR)`.
508     // To avoid ambiguity, the type is surrounded by parentheses.
509     fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
510         self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
511         let expr = self.parse_anon_const_expr()?;
512         self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
513         Ok(TyKind::Typeof(expr))
514     }
515
516     /// Parses a function pointer type (`TyKind::BareFn`).
517     /// ```ignore (illustrative)
518     ///    [unsafe] [extern "ABI"] fn (S) -> T
519     /// //  ^~~~~^          ^~~~^     ^~^    ^
520     /// //    |               |        |     |
521     /// //    |               |        |   Return type
522     /// // Function Style    ABI  Parameter types
523     /// ```
524     /// We actually parse `FnHeader FnDecl`, but we error on `const` and `async` qualifiers.
525     fn parse_ty_bare_fn(
526         &mut self,
527         lo: Span,
528         mut params: Vec<GenericParam>,
529         param_insertion_point: Option<Span>,
530         recover_return_sign: RecoverReturnSign,
531     ) -> PResult<'a, TyKind> {
532         let inherited_vis = rustc_ast::Visibility {
533             span: rustc_span::DUMMY_SP,
534             kind: rustc_ast::VisibilityKind::Inherited,
535             tokens: None,
536         };
537         let span_start = self.token.span;
538         let ast::FnHeader { ext, unsafety, constness, asyncness } =
539             self.parse_fn_front_matter(&inherited_vis)?;
540         if self.may_recover() && self.token.kind == TokenKind::Lt {
541             self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?;
542         }
543         let decl = self.parse_fn_decl(|_| false, AllowPlus::No, recover_return_sign)?;
544         let whole_span = lo.to(self.prev_token.span);
545         if let ast::Const::Yes(span) = constness {
546             // If we ever start to allow `const fn()`, then update
547             // feature gating for `#![feature(const_extern_fn)]` to
548             // cover it.
549             self.error_fn_ptr_bad_qualifier(whole_span, span, "const");
550         }
551         if let ast::Async::Yes { span, .. } = asyncness {
552             self.error_fn_ptr_bad_qualifier(whole_span, span, "async");
553         }
554         let decl_span = span_start.to(self.token.span);
555         Ok(TyKind::BareFn(P(BareFnTy { ext, unsafety, generic_params: params, decl, decl_span })))
556     }
557
558     /// Recover from function pointer types with a generic parameter list (e.g. `fn<'a>(&'a str)`).
559     fn recover_fn_ptr_with_generics(
560         &mut self,
561         lo: Span,
562         params: &mut Vec<GenericParam>,
563         param_insertion_point: Option<Span>,
564     ) -> PResult<'a, ()> {
565         let generics = self.parse_generics()?;
566         let arity = generics.params.len();
567
568         let mut lifetimes: Vec<_> = generics
569             .params
570             .into_iter()
571             .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime))
572             .collect();
573
574         let sugg = if !lifetimes.is_empty() {
575             let snippet =
576                 lifetimes.iter().map(|param| param.ident.as_str()).intersperse(", ").collect();
577
578             let (left, snippet) = if let Some(span) = param_insertion_point {
579                 (span, if params.is_empty() { snippet } else { format!(", {snippet}") })
580             } else {
581                 (lo.shrink_to_lo(), format!("for<{snippet}> "))
582             };
583
584             Some(FnPtrWithGenericsSugg {
585                 left,
586                 snippet,
587                 right: generics.span,
588                 arity,
589                 for_param_list_exists: param_insertion_point.is_some(),
590             })
591         } else {
592             None
593         };
594
595         self.sess.emit_err(FnPtrWithGenerics { span: generics.span, sugg });
596         params.append(&mut lifetimes);
597         Ok(())
598     }
599
600     /// Emit an error for the given bad function pointer qualifier.
601     fn error_fn_ptr_bad_qualifier(&self, span: Span, qual_span: Span, qual: &str) {
602         self.struct_span_err(span, &format!("an `fn` pointer type cannot be `{}`", qual))
603             .span_label(qual_span, format!("`{}` because of this", qual))
604             .span_suggestion_short(
605                 qual_span,
606                 &format!("remove the `{}` qualifier", qual),
607                 "",
608                 Applicability::MaybeIncorrect,
609             )
610             .emit();
611     }
612
613     /// Parses an `impl B0 + ... + Bn` type.
614     fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
615         // Always parse bounds greedily for better error recovery.
616         let bounds = self.parse_generic_bounds(None)?;
617         *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
618         Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
619     }
620
621     /// Is a `dyn B0 + ... + Bn` type allowed here?
622     fn is_explicit_dyn_type(&mut self) -> bool {
623         self.check_keyword(kw::Dyn)
624             && (!self.token.uninterpolated_span().rust_2015()
625                 || self.look_ahead(1, |t| {
626                     (t.can_begin_bound() || t.kind == TokenKind::BinOp(token::Star))
627                         && !can_continue_type_after_non_fn_ident(t)
628                 }))
629     }
630
631     /// Parses a `dyn B0 + ... + Bn` type.
632     ///
633     /// Note that this does *not* parse bare trait objects.
634     fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
635         self.bump(); // `dyn`
636
637         // parse dyn* types
638         let syntax = if self.eat(&TokenKind::BinOp(token::Star)) {
639             TraitObjectSyntax::DynStar
640         } else {
641             TraitObjectSyntax::Dyn
642         };
643
644         // Always parse bounds greedily for better error recovery.
645         let bounds = self.parse_generic_bounds(None)?;
646         *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
647         Ok(TyKind::TraitObject(bounds, syntax))
648     }
649
650     /// Parses a type starting with a path.
651     ///
652     /// This can be:
653     /// 1. a type macro, `mac!(...)`,
654     /// 2. a bare trait object, `B0 + ... + Bn`,
655     /// 3. or a path, `path::to::MyType`.
656     fn parse_path_start_ty(
657         &mut self,
658         lo: Span,
659         allow_plus: AllowPlus,
660         ty_generics: Option<&Generics>,
661     ) -> PResult<'a, TyKind> {
662         // Simple path
663         let path = self.parse_path_inner(PathStyle::Type, ty_generics)?;
664         if self.eat(&token::Not) {
665             // Macro invocation in type position
666             Ok(TyKind::MacCall(P(MacCall {
667                 path,
668                 args: self.parse_mac_args()?,
669                 prior_type_ascription: self.last_type_ascription,
670             })))
671         } else if allow_plus == AllowPlus::Yes && self.check_plus() {
672             // `Trait1 + Trait2 + 'a`
673             self.parse_remaining_bounds_path(Vec::new(), path, lo, true)
674         } else {
675             // Just a type path.
676             Ok(TyKind::Path(None, path))
677         }
678     }
679
680     fn error_illegal_c_varadic_ty(&self, lo: Span) {
681         struct_span_err!(
682             self.sess.span_diagnostic,
683             lo.to(self.prev_token.span),
684             E0743,
685             "C-variadic type `...` may not be nested inside another type",
686         )
687         .emit();
688     }
689
690     pub(super) fn parse_generic_bounds(
691         &mut self,
692         colon_span: Option<Span>,
693     ) -> PResult<'a, GenericBounds> {
694         self.parse_generic_bounds_common(AllowPlus::Yes, colon_span)
695     }
696
697     /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
698     ///
699     /// See `parse_generic_bound` for the `BOUND` grammar.
700     fn parse_generic_bounds_common(
701         &mut self,
702         allow_plus: AllowPlus,
703         colon_span: Option<Span>,
704     ) -> PResult<'a, GenericBounds> {
705         let mut bounds = Vec::new();
706         let mut negative_bounds = Vec::new();
707
708         while self.can_begin_bound()
709             // Continue even if we find a keyword.
710             // This is necessary for error recover on, for example, `impl fn()`.
711             //
712             // The only keyword that can go after generic bounds is `where`, so stop if it's it.
713             || (self.token.is_reserved_ident() && !self.token.is_keyword(kw::Where))
714         {
715             if self.token.is_keyword(kw::Dyn) {
716                 // Account for `&dyn Trait + dyn Other`.
717                 self.struct_span_err(self.token.span, "invalid `dyn` keyword")
718                     .help("`dyn` is only needed at the start of a trait `+`-separated list")
719                     .span_suggestion(
720                         self.token.span,
721                         "remove this keyword",
722                         "",
723                         Applicability::MachineApplicable,
724                     )
725                     .emit();
726                 self.bump();
727             }
728             match self.parse_generic_bound()? {
729                 Ok(bound) => bounds.push(bound),
730                 Err(neg_sp) => negative_bounds.push(neg_sp),
731             }
732             if allow_plus == AllowPlus::No || !self.eat_plus() {
733                 break;
734             }
735         }
736
737         if !negative_bounds.is_empty() {
738             self.error_negative_bounds(colon_span, &bounds, negative_bounds);
739         }
740
741         Ok(bounds)
742     }
743
744     /// Can the current token begin a bound?
745     fn can_begin_bound(&mut self) -> bool {
746         // This needs to be synchronized with `TokenKind::can_begin_bound`.
747         self.check_path()
748         || self.check_lifetime()
749         || self.check(&token::Not) // Used for error reporting only.
750         || self.check(&token::Question)
751         || self.check(&token::Tilde)
752         || self.check_keyword(kw::For)
753         || self.check(&token::OpenDelim(Delimiter::Parenthesis))
754     }
755
756     fn error_negative_bounds(
757         &self,
758         colon_span: Option<Span>,
759         bounds: &[GenericBound],
760         negative_bounds: Vec<Span>,
761     ) {
762         let negative_bounds_len = negative_bounds.len();
763         let last_span = *negative_bounds.last().expect("no negative bounds, but still error?");
764         let mut err = self.struct_span_err(negative_bounds, "negative bounds are not supported");
765         err.span_label(last_span, "negative bounds are not supported");
766         if let Some(bound_list) = colon_span {
767             let bound_list = bound_list.to(self.prev_token.span);
768             let mut new_bound_list = String::new();
769             if !bounds.is_empty() {
770                 let mut snippets = bounds.iter().map(|bound| self.span_to_snippet(bound.span()));
771                 while let Some(Ok(snippet)) = snippets.next() {
772                     new_bound_list.push_str(" + ");
773                     new_bound_list.push_str(&snippet);
774                 }
775                 new_bound_list = new_bound_list.replacen(" +", ":", 1);
776             }
777             err.tool_only_span_suggestion(
778                 bound_list,
779                 &format!("remove the bound{}", pluralize!(negative_bounds_len)),
780                 new_bound_list,
781                 Applicability::MachineApplicable,
782             );
783         }
784         err.emit();
785     }
786
787     /// Parses a bound according to the grammar:
788     /// ```ebnf
789     /// BOUND = TY_BOUND | LT_BOUND
790     /// ```
791     fn parse_generic_bound(&mut self) -> PResult<'a, Result<GenericBound, Span>> {
792         let anchor_lo = self.prev_token.span;
793         let lo = self.token.span;
794         let has_parens = self.eat(&token::OpenDelim(Delimiter::Parenthesis));
795         let inner_lo = self.token.span;
796         let is_negative = self.eat(&token::Not);
797
798         let modifiers = self.parse_ty_bound_modifiers()?;
799         let bound = if self.token.is_lifetime() {
800             self.error_lt_bound_with_modifiers(modifiers);
801             self.parse_generic_lt_bound(lo, inner_lo, has_parens)?
802         } else {
803             self.parse_generic_ty_bound(lo, has_parens, modifiers)?
804         };
805
806         Ok(if is_negative { Err(anchor_lo.to(self.prev_token.span)) } else { Ok(bound) })
807     }
808
809     /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to:
810     /// ```ebnf
811     /// LT_BOUND = LIFETIME
812     /// ```
813     fn parse_generic_lt_bound(
814         &mut self,
815         lo: Span,
816         inner_lo: Span,
817         has_parens: bool,
818     ) -> PResult<'a, GenericBound> {
819         let bound = GenericBound::Outlives(self.expect_lifetime());
820         if has_parens {
821             // FIXME(Centril): Consider not erroring here and accepting `('lt)` instead,
822             // possibly introducing `GenericBound::Paren(P<GenericBound>)`?
823             self.recover_paren_lifetime(lo, inner_lo)?;
824         }
825         Ok(bound)
826     }
827
828     /// Emits an error if any trait bound modifiers were present.
829     fn error_lt_bound_with_modifiers(&self, modifiers: BoundModifiers) {
830         if let Some(span) = modifiers.maybe_const {
831             self.struct_span_err(
832                 span,
833                 "`~const` may only modify trait bounds, not lifetime bounds",
834             )
835             .emit();
836         }
837
838         if let Some(span) = modifiers.maybe {
839             self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds")
840                 .emit();
841         }
842     }
843
844     /// Recover on `('lifetime)` with `(` already eaten.
845     fn recover_paren_lifetime(&mut self, lo: Span, inner_lo: Span) -> PResult<'a, ()> {
846         let inner_span = inner_lo.to(self.prev_token.span);
847         self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
848         let mut err = self.struct_span_err(
849             lo.to(self.prev_token.span),
850             "parenthesized lifetime bounds are not supported",
851         );
852         if let Ok(snippet) = self.span_to_snippet(inner_span) {
853             err.span_suggestion_short(
854                 lo.to(self.prev_token.span),
855                 "remove the parentheses",
856                 snippet,
857                 Applicability::MachineApplicable,
858             );
859         }
860         err.emit();
861         Ok(())
862     }
863
864     /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `~const Trait`.
865     ///
866     /// If no modifiers are present, this does not consume any tokens.
867     ///
868     /// ```ebnf
869     /// TY_BOUND_MODIFIERS = ["~const"] ["?"]
870     /// ```
871     fn parse_ty_bound_modifiers(&mut self) -> PResult<'a, BoundModifiers> {
872         let maybe_const = if self.eat(&token::Tilde) {
873             let tilde = self.prev_token.span;
874             self.expect_keyword(kw::Const)?;
875             let span = tilde.to(self.prev_token.span);
876             self.sess.gated_spans.gate(sym::const_trait_impl, span);
877             Some(span)
878         } else if self.eat_keyword(kw::Const) {
879             let span = self.prev_token.span;
880             self.sess.gated_spans.gate(sym::const_trait_impl, span);
881
882             self.struct_span_err(span, "const bounds must start with `~`")
883                 .span_suggestion(
884                     span.shrink_to_lo(),
885                     "add `~`",
886                     "~",
887                     Applicability::MachineApplicable,
888                 )
889                 .emit();
890
891             Some(span)
892         } else {
893             None
894         };
895
896         let maybe = if self.eat(&token::Question) { Some(self.prev_token.span) } else { None };
897
898         Ok(BoundModifiers { maybe, maybe_const })
899     }
900
901     /// Parses a type bound according to:
902     /// ```ebnf
903     /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
904     /// TY_BOUND_NOPAREN = [TY_BOUND_MODIFIERS] [for<LT_PARAM_DEFS>] SIMPLE_PATH
905     /// ```
906     ///
907     /// For example, this grammar accepts `~const ?for<'a: 'b> m::Trait<'a>`.
908     fn parse_generic_ty_bound(
909         &mut self,
910         lo: Span,
911         has_parens: bool,
912         modifiers: BoundModifiers,
913     ) -> PResult<'a, GenericBound> {
914         let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
915         let path = self.parse_path(PathStyle::Type)?;
916         if has_parens {
917             if self.token.is_like_plus() {
918                 // Someone has written something like `&dyn (Trait + Other)`. The correct code
919                 // would be `&(dyn Trait + Other)`, but we don't have access to the appropriate
920                 // span to suggest that. When written as `&dyn Trait + Other`, an appropriate
921                 // suggestion is given.
922                 let bounds = vec![];
923                 self.parse_remaining_bounds(bounds, true)?;
924                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
925                 let sp = vec![lo, self.prev_token.span];
926                 let sugg: Vec<_> = sp.iter().map(|sp| (*sp, String::new())).collect();
927                 self.struct_span_err(sp, "incorrect braces around trait bounds")
928                     .multipart_suggestion(
929                         "remove the parentheses",
930                         sugg,
931                         Applicability::MachineApplicable,
932                     )
933                     .emit();
934             } else {
935                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
936             }
937         }
938
939         let modifier = modifiers.to_trait_bound_modifier();
940         let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_token.span));
941         Ok(GenericBound::Trait(poly_trait, modifier))
942     }
943
944     /// Optionally parses `for<$generic_params>`.
945     pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
946         if self.eat_keyword(kw::For) {
947             self.expect_lt()?;
948             let params = self.parse_generic_params()?;
949             self.expect_gt()?;
950             // We rely on AST validation to rule out invalid cases: There must not be type
951             // parameters, and the lifetime parameters must not have bounds.
952             Ok(params)
953         } else {
954             Ok(Vec::new())
955         }
956     }
957
958     pub(super) fn check_lifetime(&mut self) -> bool {
959         self.expected_tokens.push(TokenType::Lifetime);
960         self.token.is_lifetime()
961     }
962
963     /// Parses a single lifetime `'a` or panics.
964     pub(super) fn expect_lifetime(&mut self) -> Lifetime {
965         if let Some(ident) = self.token.lifetime() {
966             self.bump();
967             Lifetime { ident, id: ast::DUMMY_NODE_ID }
968         } else {
969             self.span_bug(self.token.span, "not a lifetime")
970         }
971     }
972
973     pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
974         P(Ty { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })
975     }
976 }