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