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