]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/ty.rs
ca8dd62cc6a023b82c7b3e2ed1378e764e7661ae
[rust.git] / src / librustc_parse / parser / ty.rs
1 use super::{Parser, PathStyle, PrevTokenKind, TokenType};
2 use super::item::ParamCfg;
3
4 use crate::{maybe_whole, maybe_recover_from_interpolated_ty_qpath};
5
6 use rustc_errors::{PResult, Applicability, pluralize};
7 use rustc_error_codes::*;
8 use syntax::ptr::P;
9 use syntax::ast::{self, Ty, TyKind, MutTy, BareFnTy, FunctionRetTy, GenericParam, Lifetime, Ident};
10 use syntax::ast::{TraitBoundModifier, TraitObjectSyntax, GenericBound, GenericBounds, PolyTraitRef};
11 use syntax::ast::{Mutability, Mac};
12 use syntax::token::{self, Token};
13 use syntax::struct_span_err;
14 use syntax_pos::source_map::Span;
15 use syntax_pos::symbol::kw;
16
17 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
18 /// `IDENT<<u8 as Trait>::AssocTy>`.
19 ///
20 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
21 /// that `IDENT` is not the ident of a fn trait.
22 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
23     t == &token::ModSep || t == &token::Lt ||
24     t == &token::BinOp(token::Shl)
25 }
26
27 impl<'a> Parser<'a> {
28     /// Parses a type.
29     pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
30         self.parse_ty_common(true, true, false)
31     }
32
33     /// Parse a type suitable for a function or function pointer parameter.
34     /// The difference from `parse_ty` is that this version allows `...`
35     /// (`CVarArgs`) at the top level of the the type.
36     pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, P<Ty>> {
37         self.parse_ty_common(true, true, true)
38     }
39
40     /// Parses a type in restricted contexts where `+` is not permitted.
41     ///
42     /// Example 1: `&'a TYPE`
43     ///     `+` is prohibited to maintain operator priority (P(+) < P(&)).
44     /// Example 2: `value1 as TYPE + value2`
45     ///     `+` is prohibited to avoid interactions with expression grammar.
46     pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
47         self.parse_ty_common(false, true, false)
48     }
49
50     /// Parses an optional return type `[ -> TY ]` in a function declaration.
51     pub(super) fn parse_ret_ty(
52         &mut self,
53         allow_plus: bool,
54         allow_qpath_recovery: bool,
55     ) -> PResult<'a, FunctionRetTy> {
56         Ok(if self.eat(&token::RArrow) {
57             // FIXME(Centril): Can we unconditionally `allow_plus`?
58             FunctionRetTy::Ty(self.parse_ty_common(allow_plus, allow_qpath_recovery, false)?)
59         } else {
60             FunctionRetTy::Default(self.token.span.shrink_to_lo())
61         })
62     }
63
64     fn parse_ty_common(
65         &mut self,
66         allow_plus: bool,
67         allow_qpath_recovery: bool,
68         // Is `...` (`CVarArgs`) legal in the immediate top level call?
69         allow_c_variadic: bool,
70     ) -> PResult<'a, P<Ty>> {
71         maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
72         maybe_whole!(self, NtTy, |x| x);
73
74         let lo = self.token.span;
75         let mut impl_dyn_multi = false;
76         let kind = if self.check(&token::OpenDelim(token::Paren)) {
77             self.parse_ty_tuple_or_parens(lo, allow_plus)?
78         } else if self.eat(&token::Not) {
79             // Never type `!`
80             TyKind::Never
81         } else if self.eat(&token::BinOp(token::Star)) {
82             self.parse_ty_ptr()?
83         } else if self.eat(&token::OpenDelim(token::Bracket)) {
84             self.parse_array_or_slice_ty()?
85         } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
86             // Reference
87             self.expect_and()?;
88             self.parse_borrowed_pointee()?
89         } else if self.eat_keyword_noexpect(kw::Typeof) {
90             self.parse_typeof_ty()?
91         } else if self.eat_keyword(kw::Underscore) {
92             // A type to be inferred `_`
93             TyKind::Infer
94         } else if self.token_is_bare_fn_keyword() {
95             // Function pointer type
96             self.parse_ty_bare_fn(Vec::new())?
97         } else if self.check_keyword(kw::For) {
98             // Function pointer type or bound list (trait object type) starting with a poly-trait.
99             //   `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
100             //   `for<'lt> Trait1<'lt> + Trait2 + 'a`
101             let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
102             if self.token_is_bare_fn_keyword() {
103                 self.parse_ty_bare_fn(lifetime_defs)?
104             } else {
105                 let path = self.parse_path(PathStyle::Type)?;
106                 let parse_plus = allow_plus && self.check_plus();
107                 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
108             }
109         } else if self.eat_keyword(kw::Impl) {
110             self.parse_impl_ty(&mut impl_dyn_multi)?
111         } else if self.is_explicit_dyn_type() {
112             self.parse_dyn_ty(&mut impl_dyn_multi)?
113         } else if self.check(&token::Question)
114             || self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus())
115         {
116             // Bound list (trait object type)
117             let bounds = self.parse_generic_bounds_common(allow_plus, None)?;
118             TyKind::TraitObject(bounds, TraitObjectSyntax::None)
119         } else if self.eat_lt() {
120             // Qualified path
121             let (qself, path) = self.parse_qpath(PathStyle::Type)?;
122             TyKind::Path(Some(qself), path)
123         } else if self.token.is_path_start() {
124             self.parse_path_start_ty(lo, allow_plus)?
125         } else if self.eat(&token::DotDotDot) {
126             if allow_c_variadic {
127                 TyKind::CVarArgs
128             } else {
129                 // FIXME(Centril): Should we just allow `...` syntactically
130                 // anywhere in a type and use semantic restrictions instead?
131                 self.error_illegal_c_varadic_ty(lo);
132                 TyKind::Err
133             }
134         } else {
135             let msg = format!("expected type, found {}", self.this_token_descr());
136             let mut err = self.struct_span_err(self.token.span, &msg);
137             err.span_label(self.token.span, "expected type");
138             self.maybe_annotate_with_ascription(&mut err, true);
139             return Err(err);
140         };
141
142         let span = lo.to(self.prev_span);
143         let ty = self.mk_ty(span, kind);
144
145         // Try to recover from use of `+` with incorrect priority.
146         self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
147         self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
148         self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
149     }
150
151     /// Parses either:
152     /// - `(TYPE)`, a parenthesized type.
153     /// - `(TYPE,)`, a tuple with a single field of type TYPE.
154     fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: bool) -> PResult<'a, TyKind> {
155         let mut trailing_plus = false;
156         let (ts, trailing) = self.parse_paren_comma_seq(|p| {
157             let ty = p.parse_ty()?;
158             trailing_plus = p.prev_token_kind == PrevTokenKind::Plus;
159             Ok(ty)
160         })?;
161
162         if ts.len() == 1 && !trailing {
163             let ty = ts.into_iter().nth(0).unwrap().into_inner();
164             let maybe_bounds = allow_plus && self.token.is_like_plus();
165             match ty.kind {
166                 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
167                 TyKind::Path(None, path) if maybe_bounds => {
168                     self.parse_remaining_bounds(Vec::new(), path, lo, true)
169                 }
170                 TyKind::TraitObject(mut bounds, TraitObjectSyntax::None)
171                 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
172                     let path = match bounds.remove(0) {
173                         GenericBound::Trait(pt, ..) => pt.trait_ref.path,
174                         GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
175                     };
176                     self.parse_remaining_bounds(Vec::new(), path, lo, true)
177                 }
178                 // `(TYPE)`
179                 _ => Ok(TyKind::Paren(P(ty)))
180             }
181         } else {
182             Ok(TyKind::Tup(ts))
183         }
184     }
185
186     fn parse_remaining_bounds(
187         &mut self,
188         generic_params: Vec<GenericParam>,
189         path: ast::Path,
190         lo: Span,
191         parse_plus: bool,
192     ) -> PResult<'a, TyKind> {
193         let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
194         let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
195         if parse_plus {
196             self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
197             bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
198         }
199         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
200     }
201
202     /// Parses a raw pointer type: `*[const | mut] $type`.
203     fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
204         let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
205             let span = self.prev_span;
206             let msg = "expected mut or const in raw pointer type";
207             self.struct_span_err(span, msg)
208                 .span_label(span, msg)
209                 .help("use `*mut T` or `*const T` as appropriate")
210                 .emit();
211             Mutability::Immutable
212         });
213         let ty = self.parse_ty_no_plus()?;
214         Ok(TyKind::Ptr(MutTy { ty, mutbl }))
215     }
216
217     /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
218     /// The opening `[` bracket is already eaten.
219     fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
220         let elt_ty = self.parse_ty()?;
221         let ty = if self.eat(&token::Semi) {
222             TyKind::Array(elt_ty, self.parse_anon_const_expr()?)
223         } else {
224             TyKind::Slice(elt_ty)
225         };
226         self.expect(&token::CloseDelim(token::Bracket))?;
227         Ok(ty)
228     }
229
230     fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
231         let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
232         let mutbl = self.parse_mutability();
233         let ty = self.parse_ty_no_plus()?;
234         Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }))
235     }
236
237     // Parses the `typeof(EXPR)`.
238     // To avoid ambiguity, the type is surrounded by parenthesis.
239     fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
240         self.expect(&token::OpenDelim(token::Paren))?;
241         let expr = self.parse_anon_const_expr()?;
242         self.expect(&token::CloseDelim(token::Paren))?;
243         Ok(TyKind::Typeof(expr))
244     }
245
246     /// Is the current token one of the keywords that signals a bare function type?
247     fn token_is_bare_fn_keyword(&mut self) -> bool {
248         self.check_keyword(kw::Fn) ||
249             self.check_keyword(kw::Unsafe) ||
250             self.check_keyword(kw::Extern)
251     }
252
253     /// Parses a `TyKind::BareFn` type.
254     fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
255         /*
256
257         [unsafe] [extern "ABI"] fn (S) -> T
258          ^~~~^           ^~~~^     ^~^    ^
259            |               |        |     |
260            |               |        |   Return type
261            |               |      Argument types
262            |               |
263            |              ABI
264         Function Style
265         */
266
267         let unsafety = self.parse_unsafety();
268         let ext = self.parse_extern()?;
269         self.expect_keyword(kw::Fn)?;
270         let cfg = ParamCfg {
271             is_self_allowed: false,
272             is_name_required: |_| false,
273         };
274         let decl = self.parse_fn_decl(cfg, false)?;
275         Ok(TyKind::BareFn(P(BareFnTy {
276             ext,
277             unsafety,
278             generic_params,
279             decl,
280         })))
281     }
282
283     /// Parses an `impl B0 + ... + Bn` type.
284     fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
285         // Always parse bounds greedily for better error recovery.
286         let bounds = self.parse_generic_bounds(None)?;
287         *impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
288         Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
289     }
290
291     /// Is a `dyn B0 + ... + Bn` type allowed here?
292     fn is_explicit_dyn_type(&mut self) -> bool {
293         self.check_keyword(kw::Dyn)
294             && (self.token.span.rust_2018()
295                 || self.look_ahead(1, |t| {
296                     t.can_begin_bound() && !can_continue_type_after_non_fn_ident(t)
297                 }))
298     }
299
300     /// Parses a `dyn B0 + ... + Bn` type.
301     ///
302     /// Note that this does *not* parse bare trait objects.
303     fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
304         self.bump(); // `dyn`
305         // Always parse bounds greedily for better error recovery.
306         let bounds = self.parse_generic_bounds(None)?;
307         *impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
308         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn))
309     }
310
311     /// Parses a type starting with a path.
312     ///
313     /// This can be:
314     /// 1. a type macro, `mac!(...)`,
315     /// 2. a bare trait object, `B0 + ... + Bn`,
316     /// 3. or a path, `path::to::MyType`.
317     fn parse_path_start_ty(&mut self, lo: Span, allow_plus: bool) -> PResult<'a, TyKind> {
318         // Simple path
319         let path = self.parse_path(PathStyle::Type)?;
320         if self.eat(&token::Not) {
321             // Macro invocation in type position
322             Ok(TyKind::Mac(Mac {
323                 path,
324                 args: self.parse_mac_args()?,
325                 prior_type_ascription: self.last_type_ascription,
326             }))
327         } else if allow_plus && self.check_plus() {
328             // `Trait1 + Trait2 + 'a`
329             self.parse_remaining_bounds(Vec::new(), path, lo, true)
330         } else {
331             // Just a type path.
332             Ok(TyKind::Path(None, path))
333         }
334     }
335
336     fn error_illegal_c_varadic_ty(&self, lo: Span) {
337         struct_span_err!(
338             self.sess.span_diagnostic,
339             lo.to(self.prev_span),
340             E0743,
341             "C-variadic type `...` may not be nested inside another type",
342         )
343         .emit();
344     }
345
346     pub(super) fn parse_generic_bounds(
347         &mut self,
348         colon_span: Option<Span>,
349     ) -> PResult<'a, GenericBounds> {
350         self.parse_generic_bounds_common(true, colon_span)
351     }
352
353     /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
354     ///
355     /// ```
356     /// BOUND = TY_BOUND | LT_BOUND
357     /// LT_BOUND = LIFETIME (e.g., `'a`)
358     /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
359     /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
360     /// ```
361     fn parse_generic_bounds_common(
362         &mut self,
363         allow_plus: bool,
364         colon_span: Option<Span>,
365     ) -> PResult<'a, GenericBounds> {
366         let mut bounds = Vec::new();
367         let mut negative_bounds = Vec::new();
368         let mut last_plus_span = None;
369         let mut was_negative = false;
370         while self.can_begin_bound() {
371             let lo = self.token.span;
372             let has_parens = self.eat(&token::OpenDelim(token::Paren));
373             let inner_lo = self.token.span;
374             let is_negative = self.eat(&token::Not);
375             let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
376             if self.token.is_lifetime() {
377                 self.error_opt_out_lifetime(question);
378                 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
379                 if has_parens {
380                     self.recover_paren_lifetime(lo, inner_lo)?;
381                 }
382             } else {
383                 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
384                 let path = self.parse_path(PathStyle::Type)?;
385                 if has_parens {
386                     self.expect(&token::CloseDelim(token::Paren))?;
387                 }
388                 let poly_span = lo.to(self.prev_span);
389                 if is_negative {
390                     was_negative = true;
391                     if let Some(sp) = last_plus_span.or(colon_span) {
392                         negative_bounds.push(sp.to(poly_span));
393                     }
394                 } else {
395                     let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
396                     let modifier = if question.is_some() {
397                         TraitBoundModifier::Maybe
398                     } else {
399                         TraitBoundModifier::None
400                     };
401                     bounds.push(GenericBound::Trait(poly_trait, modifier));
402                 }
403             }
404
405             if !allow_plus || !self.eat_plus() {
406                 break
407             } else {
408                 last_plus_span = Some(self.prev_span);
409             }
410         }
411
412         if !negative_bounds.is_empty() || was_negative {
413             let negative_bounds_len = negative_bounds.len();
414             let last_span = negative_bounds.last().map(|sp| *sp);
415             let mut err = self.struct_span_err(
416                 negative_bounds,
417                 "negative trait bounds are not supported",
418             );
419             if let Some(sp) = last_span {
420                 err.span_label(sp, "negative trait bounds are not supported");
421             }
422             if let Some(bound_list) = colon_span {
423                 let bound_list = bound_list.to(self.prev_span);
424                 let mut new_bound_list = String::new();
425                 if !bounds.is_empty() {
426                     let mut snippets = bounds.iter().map(|bound| bound.span())
427                         .map(|span| self.span_to_snippet(span));
428                     while let Some(Ok(snippet)) = snippets.next() {
429                         new_bound_list.push_str(" + ");
430                         new_bound_list.push_str(&snippet);
431                     }
432                     new_bound_list = new_bound_list.replacen(" +", ":", 1);
433                 }
434                 err.span_suggestion_hidden(
435                     bound_list,
436                     &format!("remove the trait bound{}", pluralize!(negative_bounds_len)),
437                     new_bound_list,
438                     Applicability::MachineApplicable,
439                 );
440             }
441             err.emit();
442         }
443
444         return Ok(bounds);
445     }
446
447     /// Can the current token begin a bound?
448     fn can_begin_bound(&mut self) -> bool {
449         // This needs to be synchronized with `TokenKind::can_begin_bound`.
450         self.check_path()
451         || self.check_lifetime()
452         || self.check(&token::Not) // Used for error reporting only.
453         || self.check(&token::Question)
454         || self.check_keyword(kw::For)
455         || self.check(&token::OpenDelim(token::Paren))
456     }
457
458     fn error_opt_out_lifetime(&self, question: Option<Span>) {
459         if let Some(span) = question {
460             self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds")
461                 .emit();
462         }
463     }
464
465     /// Recover on `('lifetime)` with `(` already eaten.
466     fn recover_paren_lifetime(&mut self, lo: Span, inner_lo: Span) -> PResult<'a, ()> {
467         let inner_span = inner_lo.to(self.prev_span);
468         self.expect(&token::CloseDelim(token::Paren))?;
469         let mut err = self.struct_span_err(
470             lo.to(self.prev_span),
471             "parenthesized lifetime bounds are not supported"
472         );
473         if let Ok(snippet) = self.span_to_snippet(inner_span) {
474             err.span_suggestion_short(
475                 lo.to(self.prev_span),
476                 "remove the parentheses",
477                 snippet.to_owned(),
478                 Applicability::MachineApplicable
479             );
480         }
481         err.emit();
482         Ok(())
483     }
484
485     pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
486         if self.eat_keyword(kw::For) {
487             self.expect_lt()?;
488             let params = self.parse_generic_params()?;
489             self.expect_gt()?;
490             // We rely on AST validation to rule out invalid cases: There must not be type
491             // parameters, and the lifetime parameters must not have bounds.
492             Ok(params)
493         } else {
494             Ok(Vec::new())
495         }
496     }
497
498     pub fn check_lifetime(&mut self) -> bool {
499         self.expected_tokens.push(TokenType::Lifetime);
500         self.token.is_lifetime()
501     }
502
503     /// Parses a single lifetime `'a` or panics.
504     pub fn expect_lifetime(&mut self) -> Lifetime {
505         if let Some(ident) = self.token.lifetime() {
506             let span = self.token.span;
507             self.bump();
508             Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
509         } else {
510             self.span_bug(self.token.span, "not a lifetime")
511         }
512     }
513
514     pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
515         P(Ty { kind, span, id: ast::DUMMY_NODE_ID })
516     }
517 }