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