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