]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/ty.rs
parser: bug -> span_bug
[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(..) => {
179                             self.span_bug(ty.span, "unexpected lifetime bound")
180                         }
181                     };
182                     self.parse_remaining_bounds(Vec::new(), path, lo, true)
183                 }
184                 // `(TYPE)`
185                 _ => Ok(TyKind::Paren(P(ty))),
186             }
187         } else {
188             Ok(TyKind::Tup(ts))
189         }
190     }
191
192     fn parse_remaining_bounds(
193         &mut self,
194         generic_params: Vec<GenericParam>,
195         path: ast::Path,
196         lo: Span,
197         parse_plus: bool,
198     ) -> PResult<'a, TyKind> {
199         let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
200         let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
201         if parse_plus {
202             self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
203             bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
204         }
205         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
206     }
207
208     /// Parses a raw pointer type: `*[const | mut] $type`.
209     fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
210         let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
211             let span = self.prev_span;
212             let msg = "expected mut or const in raw pointer type";
213             self.struct_span_err(span, msg)
214                 .span_label(span, msg)
215                 .help("use `*mut T` or `*const T` as appropriate")
216                 .emit();
217             Mutability::Not
218         });
219         let ty = self.parse_ty_no_plus()?;
220         Ok(TyKind::Ptr(MutTy { ty, mutbl }))
221     }
222
223     /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
224     /// The opening `[` bracket is already eaten.
225     fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
226         let elt_ty = self.parse_ty()?;
227         let ty = if self.eat(&token::Semi) {
228             TyKind::Array(elt_ty, self.parse_anon_const_expr()?)
229         } else {
230             TyKind::Slice(elt_ty)
231         };
232         self.expect(&token::CloseDelim(token::Bracket))?;
233         Ok(ty)
234     }
235
236     fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
237         let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
238         let mutbl = self.parse_mutability();
239         let ty = self.parse_ty_no_plus()?;
240         Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }))
241     }
242
243     // Parses the `typeof(EXPR)`.
244     // To avoid ambiguity, the type is surrounded by parenthesis.
245     fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
246         self.expect(&token::OpenDelim(token::Paren))?;
247         let expr = self.parse_anon_const_expr()?;
248         self.expect(&token::CloseDelim(token::Paren))?;
249         Ok(TyKind::Typeof(expr))
250     }
251
252     /// Is the current token one of the keywords that signals a bare function type?
253     fn token_is_bare_fn_keyword(&mut self) -> bool {
254         self.check_keyword(kw::Fn)
255             || self.check_keyword(kw::Unsafe)
256             || self.check_keyword(kw::Extern)
257     }
258
259     /// Parses a function pointer type (`TyKind::BareFn`).
260     /// ```
261     /// [unsafe] [extern "ABI"] fn (S) -> T
262     ///  ^~~~~^          ^~~~^     ^~^    ^
263     ///    |               |        |     |
264     ///    |               |        |   Return type
265     /// Function Style    ABI  Parameter types
266     /// ```
267     fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
268         let unsafety = self.parse_unsafety();
269         let ext = self.parse_extern()?;
270         self.expect_keyword(kw::Fn)?;
271         let cfg = ParamCfg { is_self_allowed: false, is_name_required: |_| false };
272         let decl = self.parse_fn_decl(cfg, false)?;
273         Ok(TyKind::BareFn(P(BareFnTy { ext, unsafety, generic_params, decl })))
274     }
275
276     /// Parses an `impl B0 + ... + Bn` type.
277     fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
278         // Always parse bounds greedily for better error recovery.
279         let bounds = self.parse_generic_bounds(None)?;
280         *impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
281         Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
282     }
283
284     /// Is a `dyn B0 + ... + Bn` type allowed here?
285     fn is_explicit_dyn_type(&mut self) -> bool {
286         self.check_keyword(kw::Dyn)
287             && (self.token.span.rust_2018()
288                 || self.look_ahead(1, |t| {
289                     t.can_begin_bound() && !can_continue_type_after_non_fn_ident(t)
290                 }))
291     }
292
293     /// Parses a `dyn B0 + ... + Bn` type.
294     ///
295     /// Note that this does *not* parse bare trait objects.
296     fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
297         self.bump(); // `dyn`
298         // Always parse bounds greedily for better error recovery.
299         let bounds = self.parse_generic_bounds(None)?;
300         *impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
301         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn))
302     }
303
304     /// Parses a type starting with a path.
305     ///
306     /// This can be:
307     /// 1. a type macro, `mac!(...)`,
308     /// 2. a bare trait object, `B0 + ... + Bn`,
309     /// 3. or a path, `path::to::MyType`.
310     fn parse_path_start_ty(&mut self, lo: Span, allow_plus: bool) -> PResult<'a, TyKind> {
311         // Simple path
312         let path = self.parse_path(PathStyle::Type)?;
313         if self.eat(&token::Not) {
314             // Macro invocation in type position
315             Ok(TyKind::Mac(Mac {
316                 path,
317                 args: self.parse_mac_args()?,
318                 prior_type_ascription: self.last_type_ascription,
319             }))
320         } else if allow_plus && self.check_plus() {
321             // `Trait1 + Trait2 + 'a`
322             self.parse_remaining_bounds(Vec::new(), path, lo, true)
323         } else {
324             // Just a type path.
325             Ok(TyKind::Path(None, path))
326         }
327     }
328
329     fn error_illegal_c_varadic_ty(&self, lo: Span) {
330         struct_span_err!(
331             self.sess.span_diagnostic,
332             lo.to(self.prev_span),
333             E0743,
334             "C-variadic type `...` may not be nested inside another type",
335         )
336         .emit();
337     }
338
339     pub(super) fn parse_generic_bounds(
340         &mut self,
341         colon_span: Option<Span>,
342     ) -> PResult<'a, GenericBounds> {
343         self.parse_generic_bounds_common(true, colon_span)
344     }
345
346     /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
347     ///
348     /// See `parse_generic_bound` for the `BOUND` grammar.
349     fn parse_generic_bounds_common(
350         &mut self,
351         allow_plus: bool,
352         colon_span: Option<Span>,
353     ) -> PResult<'a, GenericBounds> {
354         let mut bounds = Vec::new();
355         let mut negative_bounds = Vec::new();
356         while self.can_begin_bound() {
357             match self.parse_generic_bound()? {
358                 Ok(bound) => bounds.push(bound),
359                 Err(neg_sp) => negative_bounds.push(neg_sp),
360             }
361             if !allow_plus || !self.eat_plus() {
362                 break;
363             }
364         }
365
366         if !negative_bounds.is_empty() {
367             self.error_negative_bounds(colon_span, &bounds, negative_bounds);
368         }
369
370         Ok(bounds)
371     }
372
373     /// Can the current token begin a bound?
374     fn can_begin_bound(&mut self) -> bool {
375         // This needs to be synchronized with `TokenKind::can_begin_bound`.
376         self.check_path()
377         || self.check_lifetime()
378         || self.check(&token::Not) // Used for error reporting only.
379         || self.check(&token::Question)
380         || self.check_keyword(kw::For)
381         || self.check(&token::OpenDelim(token::Paren))
382     }
383
384     fn error_negative_bounds(
385         &self,
386         colon_span: Option<Span>,
387         bounds: &[GenericBound],
388         negative_bounds: Vec<Span>,
389     ) {
390         let negative_bounds_len = negative_bounds.len();
391         let last_span = *negative_bounds.last().expect("no negative bounds, but still error?");
392         let mut err = self.struct_span_err(negative_bounds, "negative bounds are not supported");
393         err.span_label(last_span, "negative bounds are not supported");
394         if let Some(bound_list) = colon_span {
395             let bound_list = bound_list.to(self.prev_span);
396             let mut new_bound_list = String::new();
397             if !bounds.is_empty() {
398                 let mut snippets = bounds.iter().map(|bound| self.span_to_snippet(bound.span()));
399                 while let Some(Ok(snippet)) = snippets.next() {
400                     new_bound_list.push_str(" + ");
401                     new_bound_list.push_str(&snippet);
402                 }
403                 new_bound_list = new_bound_list.replacen(" +", ":", 1);
404             }
405             err.tool_only_span_suggestion(
406                 bound_list,
407                 &format!("remove the bound{}", pluralize!(negative_bounds_len)),
408                 new_bound_list,
409                 Applicability::MachineApplicable,
410             );
411         }
412         err.emit();
413     }
414
415     /// Parses a bound according to the grammar:
416     /// ```
417     /// BOUND = TY_BOUND | LT_BOUND
418     /// ```
419     fn parse_generic_bound(&mut self) -> PResult<'a, Result<GenericBound, Span>> {
420         let anchor_lo = self.prev_span;
421         let lo = self.token.span;
422         let has_parens = self.eat(&token::OpenDelim(token::Paren));
423         let inner_lo = self.token.span;
424         let is_negative = self.eat(&token::Not);
425         let question = self.eat(&token::Question).then_some(self.prev_span);
426         let bound = if self.token.is_lifetime() {
427             self.parse_generic_lt_bound(lo, inner_lo, has_parens, question)?
428         } else {
429             self.parse_generic_ty_bound(lo, has_parens, question)?
430         };
431         Ok(if is_negative { Err(anchor_lo.to(self.prev_span)) } else { Ok(bound) })
432     }
433
434     /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to:
435     /// ```
436     /// LT_BOUND = LIFETIME
437     /// ```
438     fn parse_generic_lt_bound(
439         &mut self,
440         lo: Span,
441         inner_lo: Span,
442         has_parens: bool,
443         question: Option<Span>,
444     ) -> PResult<'a, GenericBound> {
445         self.error_opt_out_lifetime(question);
446         let bound = GenericBound::Outlives(self.expect_lifetime());
447         if has_parens {
448             // FIXME(Centril): Consider not erroring here and accepting `('lt)` instead,
449             // possibly introducing `GenericBound::Paren(P<GenericBound>)`?
450             self.recover_paren_lifetime(lo, inner_lo)?;
451         }
452         Ok(bound)
453     }
454
455     fn error_opt_out_lifetime(&self, question: Option<Span>) {
456         if let Some(span) = question {
457             self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds")
458                 .emit();
459         }
460     }
461
462     /// Recover on `('lifetime)` with `(` already eaten.
463     fn recover_paren_lifetime(&mut self, lo: Span, inner_lo: Span) -> PResult<'a, ()> {
464         let inner_span = inner_lo.to(self.prev_span);
465         self.expect(&token::CloseDelim(token::Paren))?;
466         let mut err = self.struct_span_err(
467             lo.to(self.prev_span),
468             "parenthesized lifetime bounds are not supported",
469         );
470         if let Ok(snippet) = self.span_to_snippet(inner_span) {
471             err.span_suggestion_short(
472                 lo.to(self.prev_span),
473                 "remove the parentheses",
474                 snippet.to_owned(),
475                 Applicability::MachineApplicable,
476             );
477         }
478         err.emit();
479         Ok(())
480     }
481
482     /// Parses a type bound according to:
483     /// ```
484     /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
485     /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
486     /// ```
487     fn parse_generic_ty_bound(
488         &mut self,
489         lo: Span,
490         has_parens: bool,
491         question: Option<Span>,
492     ) -> PResult<'a, GenericBound> {
493         let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
494         let path = self.parse_path(PathStyle::Type)?;
495         if has_parens {
496             self.expect(&token::CloseDelim(token::Paren))?;
497         }
498         let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
499         let modifier = question.map_or(TraitBoundModifier::None, |_| TraitBoundModifier::Maybe);
500         Ok(GenericBound::Trait(poly_trait, modifier))
501     }
502
503     /// Optionally parses `for<$generic_params>`.
504     pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
505         if self.eat_keyword(kw::For) {
506             self.expect_lt()?;
507             let params = self.parse_generic_params()?;
508             self.expect_gt()?;
509             // We rely on AST validation to rule out invalid cases: There must not be type
510             // parameters, and the lifetime parameters must not have bounds.
511             Ok(params)
512         } else {
513             Ok(Vec::new())
514         }
515     }
516
517     pub fn check_lifetime(&mut self) -> bool {
518         self.expected_tokens.push(TokenType::Lifetime);
519         self.token.is_lifetime()
520     }
521
522     /// Parses a single lifetime `'a` or panics.
523     pub fn expect_lifetime(&mut self) -> Lifetime {
524         if let Some(ident) = self.token.lifetime() {
525             let span = self.token.span;
526             self.bump();
527             Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
528         } else {
529             self.span_bug(self.token.span, "not a lifetime")
530         }
531     }
532
533     pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
534         P(Ty { kind, span, id: ast::DUMMY_NODE_ID })
535     }
536 }