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