]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/ty.rs
6f7ab0542d5fab75aa482f633150e32ec8541d2b
[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, AnonConst, 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.eat(&token::OpenDelim(token::Paren)) {
77             // `(TYPE)` is a parenthesized type.
78             // `(TYPE,)` is a tuple with a single field of type TYPE.
79             let mut ts = vec![];
80             let mut last_comma = false;
81             while self.token != token::CloseDelim(token::Paren) {
82                 ts.push(self.parse_ty()?);
83                 if self.eat(&token::Comma) {
84                     last_comma = true;
85                 } else {
86                     last_comma = false;
87                     break;
88                 }
89             }
90             let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
91             self.expect(&token::CloseDelim(token::Paren))?;
92
93             if ts.len() == 1 && !last_comma {
94                 let ty = ts.into_iter().nth(0).unwrap().into_inner();
95                 let maybe_bounds = allow_plus && self.token.is_like_plus();
96                 match ty.kind {
97                     // `(TY_BOUND_NOPAREN) + BOUND + ...`.
98                     TyKind::Path(None, ref path) if maybe_bounds => {
99                         self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
100                     }
101                     TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
102                             if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
103                         let path = match bounds[0] {
104                             GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
105                             GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
106                         };
107                         self.parse_remaining_bounds(Vec::new(), path, lo, true)?
108                     }
109                     // `(TYPE)`
110                     _ => TyKind::Paren(P(ty))
111                 }
112             } else {
113                 TyKind::Tup(ts)
114             }
115         } else if self.eat(&token::Not) {
116             // Never type `!`
117             TyKind::Never
118         } else if self.eat(&token::BinOp(token::Star)) {
119             // Raw pointer
120             TyKind::Ptr(self.parse_ptr()?)
121         } else if self.eat(&token::OpenDelim(token::Bracket)) {
122             // Array or slice
123             let t = self.parse_ty()?;
124             // Parse optional `; EXPR` in `[TYPE; EXPR]`
125             let t = match self.maybe_parse_fixed_length_of_vec()? {
126                 None => TyKind::Slice(t),
127                 Some(length) => TyKind::Array(t, AnonConst {
128                     id: ast::DUMMY_NODE_ID,
129                     value: length,
130                 }),
131             };
132             self.expect(&token::CloseDelim(token::Bracket))?;
133             t
134         } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
135             // Reference
136             self.expect_and()?;
137             self.parse_borrowed_pointee()?
138         } else if self.eat_keyword_noexpect(kw::Typeof) {
139             // `typeof(EXPR)`
140             // In order to not be ambiguous, the type must be surrounded by parens.
141             self.expect(&token::OpenDelim(token::Paren))?;
142             let e = AnonConst {
143                 id: ast::DUMMY_NODE_ID,
144                 value: self.parse_expr()?,
145             };
146             self.expect(&token::CloseDelim(token::Paren))?;
147             TyKind::Typeof(e)
148         } else if self.eat_keyword(kw::Underscore) {
149             // A type to be inferred `_`
150             TyKind::Infer
151         } else if self.token_is_bare_fn_keyword() {
152             // Function pointer type
153             self.parse_ty_bare_fn(Vec::new())?
154         } else if self.check_keyword(kw::For) {
155             // Function pointer type or bound list (trait object type) starting with a poly-trait.
156             //   `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
157             //   `for<'lt> Trait1<'lt> + Trait2 + 'a`
158             let lo = self.token.span;
159             let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
160             if self.token_is_bare_fn_keyword() {
161                 self.parse_ty_bare_fn(lifetime_defs)?
162             } else {
163                 let path = self.parse_path(PathStyle::Type)?;
164                 let parse_plus = allow_plus && self.check_plus();
165                 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
166             }
167         } else if self.eat_keyword(kw::Impl) {
168             // Always parse bounds greedily for better error recovery.
169             let bounds = self.parse_generic_bounds(None)?;
170             impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
171             TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
172         } else if self.check_keyword(kw::Dyn) &&
173                   (self.token.span.rust_2018() ||
174                    self.look_ahead(1, |t| t.can_begin_bound() &&
175                                           !can_continue_type_after_non_fn_ident(t))) {
176             self.bump(); // `dyn`
177             // Always parse bounds greedily for better error recovery.
178             let bounds = self.parse_generic_bounds(None)?;
179             impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
180             TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
181         } else if self.check(&token::Question) ||
182                   self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
183             // Bound list (trait object type)
184             TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
185                                 TraitObjectSyntax::None)
186         } else if self.eat_lt() {
187             // Qualified path
188             let (qself, path) = self.parse_qpath(PathStyle::Type)?;
189             TyKind::Path(Some(qself), path)
190         } else if self.token.is_path_start() {
191             // Simple path
192             let path = self.parse_path(PathStyle::Type)?;
193             if self.eat(&token::Not) {
194                 // Macro invocation in type position
195                 let args = self.parse_mac_args()?;
196                 let mac = Mac {
197                     path,
198                     args,
199                     prior_type_ascription: self.last_type_ascription,
200                 };
201                 TyKind::Mac(mac)
202             } else {
203                 // Just a type path or bound list (trait object type) starting with a trait.
204                 //   `Type`
205                 //   `Trait1 + Trait2 + 'a`
206                 if allow_plus && self.check_plus() {
207                     self.parse_remaining_bounds(Vec::new(), path, lo, true)?
208                 } else {
209                     TyKind::Path(None, path)
210                 }
211             }
212         } else if self.eat(&token::DotDotDot) {
213             if allow_c_variadic {
214                 TyKind::CVarArgs
215             } else {
216                 // FIXME(Centril): Should we just allow `...` syntactically
217                 // anywhere in a type and use semantic restrictions instead?
218                 struct_span_err!(
219                     self.sess.span_diagnostic,
220                     lo.to(self.prev_span),
221                     E0743,
222                     "C-variadic type `...` may not be nested inside another type",
223                 )
224                 .emit();
225
226                 TyKind::Err
227             }
228         } else {
229             let msg = format!("expected type, found {}", self.this_token_descr());
230             let mut err = self.fatal(&msg);
231             err.span_label(self.token.span, "expected type");
232             self.maybe_annotate_with_ascription(&mut err, true);
233             return Err(err);
234         };
235
236         let span = lo.to(self.prev_span);
237         let ty = self.mk_ty(span, kind);
238
239         // Try to recover from use of `+` with incorrect priority.
240         self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
241         self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
242         self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
243     }
244
245     fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
246                               lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
247         let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
248         let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
249         if parse_plus {
250             self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
251             bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
252         }
253         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
254     }
255
256     fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
257         let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
258             let span = self.prev_span;
259             let msg = "expected mut or const in raw pointer type";
260             self.struct_span_err(span, msg)
261                 .span_label(span, msg)
262                 .help("use `*mut T` or `*const T` as appropriate")
263                 .emit();
264             Mutability::Immutable
265         });
266         let t = self.parse_ty_no_plus()?;
267         Ok(MutTy { ty: t, mutbl })
268     }
269
270     fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
271         if self.eat(&token::Semi) {
272             Ok(Some(self.parse_expr()?))
273         } else {
274             Ok(None)
275         }
276     }
277
278     fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
279         let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
280         let mutbl = self.parse_mutability();
281         let ty = self.parse_ty_no_plus()?;
282         return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }));
283     }
284
285     /// Is the current token one of the keywords that signals a bare function type?
286     fn token_is_bare_fn_keyword(&mut self) -> bool {
287         self.check_keyword(kw::Fn) ||
288             self.check_keyword(kw::Unsafe) ||
289             self.check_keyword(kw::Extern)
290     }
291
292     /// Parses a `TyKind::BareFn` type.
293     fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
294         /*
295
296         [unsafe] [extern "ABI"] fn (S) -> T
297          ^~~~^           ^~~~^     ^~^    ^
298            |               |        |     |
299            |               |        |   Return type
300            |               |      Argument types
301            |               |
302            |              ABI
303         Function Style
304         */
305
306         let unsafety = self.parse_unsafety();
307         let ext = self.parse_extern()?;
308         self.expect_keyword(kw::Fn)?;
309         let cfg = ParamCfg {
310             is_self_allowed: false,
311             is_name_required: |_| false,
312         };
313         let decl = self.parse_fn_decl(cfg, false)?;
314         Ok(TyKind::BareFn(P(BareFnTy {
315             ext,
316             unsafety,
317             generic_params,
318             decl,
319         })))
320     }
321
322     pub(super) fn parse_generic_bounds(&mut self,
323                                   colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
324         self.parse_generic_bounds_common(true, colon_span)
325     }
326
327     /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
328     ///
329     /// ```
330     /// BOUND = TY_BOUND | LT_BOUND
331     /// LT_BOUND = LIFETIME (e.g., `'a`)
332     /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
333     /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
334     /// ```
335     fn parse_generic_bounds_common(&mut self,
336                                    allow_plus: bool,
337                                    colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
338         let mut bounds = Vec::new();
339         let mut negative_bounds = Vec::new();
340         let mut last_plus_span = None;
341         let mut was_negative = false;
342         loop {
343             // This needs to be synchronized with `TokenKind::can_begin_bound`.
344             let is_bound_start = self.check_path() || self.check_lifetime() ||
345                                  self.check(&token::Not) || // used for error reporting only
346                                  self.check(&token::Question) ||
347                                  self.check_keyword(kw::For) ||
348                                  self.check(&token::OpenDelim(token::Paren));
349             if is_bound_start {
350                 let lo = self.token.span;
351                 let has_parens = self.eat(&token::OpenDelim(token::Paren));
352                 let inner_lo = self.token.span;
353                 let is_negative = self.eat(&token::Not);
354                 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
355                 if self.token.is_lifetime() {
356                     if let Some(question_span) = question {
357                         self.span_err(question_span,
358                                       "`?` may only modify trait bounds, not lifetime bounds");
359                     }
360                     bounds.push(GenericBound::Outlives(self.expect_lifetime()));
361                     if has_parens {
362                         let inner_span = inner_lo.to(self.prev_span);
363                         self.expect(&token::CloseDelim(token::Paren))?;
364                         let mut err = self.struct_span_err(
365                             lo.to(self.prev_span),
366                             "parenthesized lifetime bounds are not supported"
367                         );
368                         if let Ok(snippet) = self.span_to_snippet(inner_span) {
369                             err.span_suggestion_short(
370                                 lo.to(self.prev_span),
371                                 "remove the parentheses",
372                                 snippet.to_owned(),
373                                 Applicability::MachineApplicable
374                             );
375                         }
376                         err.emit();
377                     }
378                 } else {
379                     let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
380                     let path = self.parse_path(PathStyle::Type)?;
381                     if has_parens {
382                         self.expect(&token::CloseDelim(token::Paren))?;
383                     }
384                     let poly_span = lo.to(self.prev_span);
385                     if is_negative {
386                         was_negative = true;
387                         if let Some(sp) = last_plus_span.or(colon_span) {
388                             negative_bounds.push(sp.to(poly_span));
389                         }
390                     } else {
391                         let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
392                         let modifier = if question.is_some() {
393                             TraitBoundModifier::Maybe
394                         } else {
395                             TraitBoundModifier::None
396                         };
397                         bounds.push(GenericBound::Trait(poly_trait, modifier));
398                     }
399                 }
400             } else {
401                 break
402             }
403
404             if !allow_plus || !self.eat_plus() {
405                 break
406             } else {
407                 last_plus_span = Some(self.prev_span);
408             }
409         }
410
411         if !negative_bounds.is_empty() || was_negative {
412             let negative_bounds_len = negative_bounds.len();
413             let last_span = negative_bounds.last().map(|sp| *sp);
414             let mut err = self.struct_span_err(
415                 negative_bounds,
416                 "negative trait bounds are not supported",
417             );
418             if let Some(sp) = last_span {
419                 err.span_label(sp, "negative trait bounds are not supported");
420             }
421             if let Some(bound_list) = colon_span {
422                 let bound_list = bound_list.to(self.prev_span);
423                 let mut new_bound_list = String::new();
424                 if !bounds.is_empty() {
425                     let mut snippets = bounds.iter().map(|bound| bound.span())
426                         .map(|span| self.span_to_snippet(span));
427                     while let Some(Ok(snippet)) = snippets.next() {
428                         new_bound_list.push_str(" + ");
429                         new_bound_list.push_str(&snippet);
430                     }
431                     new_bound_list = new_bound_list.replacen(" +", ":", 1);
432                 }
433                 err.span_suggestion_hidden(
434                     bound_list,
435                     &format!("remove the trait bound{}", pluralize!(negative_bounds_len)),
436                     new_bound_list,
437                     Applicability::MachineApplicable,
438                 );
439             }
440             err.emit();
441         }
442
443         return Ok(bounds);
444     }
445
446     pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
447         if self.eat_keyword(kw::For) {
448             self.expect_lt()?;
449             let params = self.parse_generic_params()?;
450             self.expect_gt()?;
451             // We rely on AST validation to rule out invalid cases: There must not be type
452             // parameters, and the lifetime parameters must not have bounds.
453             Ok(params)
454         } else {
455             Ok(Vec::new())
456         }
457     }
458
459     pub fn check_lifetime(&mut self) -> bool {
460         self.expected_tokens.push(TokenType::Lifetime);
461         self.token.is_lifetime()
462     }
463
464     /// Parses a single lifetime `'a` or panics.
465     pub fn expect_lifetime(&mut self) -> Lifetime {
466         if let Some(ident) = self.token.lifetime() {
467             let span = self.token.span;
468             self.bump();
469             Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
470         } else {
471             self.span_bug(self.token.span, "not a lifetime")
472         }
473     }
474
475     pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
476         P(Ty { kind, span, id: ast::DUMMY_NODE_ID })
477     }
478 }