1 use super::item::ParamCfg;
2 use super::{Parser, PathStyle, PrevTokenKind, TokenType};
4 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
6 use rustc_error_codes::*;
7 use rustc_errors::{pluralize, Applicability, PResult};
9 self, BareFnTy, FunctionRetTy, GenericParam, Ident, Lifetime, MutTy, Ty, TyKind,
12 GenericBound, GenericBounds, PolyTraitRef, TraitBoundModifier, TraitObjectSyntax,
14 use syntax::ast::{Mac, Mutability};
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;
21 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
22 /// `IDENT<<u8 as Trait>::AssocTy>`.
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)
32 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
33 self.parse_ty_common(true, true, false)
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)
43 /// Parses a type in restricted contexts where `+` is not permitted.
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)
53 /// Parses an optional return type `[ -> TY ]` in a function declaration.
54 pub(super) fn parse_ret_ty(
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)?)
63 FunctionRetTy::Default(self.token.span.shrink_to_lo())
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);
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) {
84 } else if self.eat(&token::BinOp(token::Star)) {
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) {
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 `_`
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)?
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)?
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())
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() {
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 {
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);
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);
145 let span = lo.to(self.prev_span);
146 let ty = self.mk_ty(span, kind);
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)
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;
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();
169 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
170 TyKind::Path(None, path) if maybe_bounds => {
171 self.parse_remaining_bounds(Vec::new(), path, lo, true)
173 TyKind::TraitObject(mut bounds, TraitObjectSyntax::None)
174 if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
176 let path = match bounds.remove(0) {
177 GenericBound::Trait(pt, ..) => pt.trait_ref.path,
178 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
180 self.parse_remaining_bounds(Vec::new(), path, lo, true)
183 _ => Ok(TyKind::Paren(P(ty))),
190 fn parse_remaining_bounds(
192 generic_params: Vec<GenericParam>,
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)];
200 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
201 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
203 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
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")
217 let ty = self.parse_ty_no_plus()?;
218 Ok(TyKind::Ptr(MutTy { ty, mutbl }))
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()?)
228 TyKind::Slice(elt_ty)
230 self.expect(&token::CloseDelim(token::Bracket))?;
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 }))
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))
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)
257 /// Parses a function pointer type (`TyKind::BareFn`).
259 /// [unsafe] [extern "ABI"] fn (S) -> T
260 /// ^~~~~^ ^~~~^ ^~^ ^
262 /// | | | Return type
263 /// Function Style ABI Parameter types
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 })))
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))
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)
291 /// Parses a `dyn B0 + ... + Bn` type.
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))
302 /// Parses a type starting with a path.
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> {
310 let path = self.parse_path(PathStyle::Type)?;
311 if self.eat(&token::Not) {
312 // Macro invocation in type position
315 args: self.parse_mac_args()?,
316 prior_type_ascription: self.last_type_ascription,
318 } else if allow_plus && self.check_plus() {
319 // `Trait1 + Trait2 + 'a`
320 self.parse_remaining_bounds(Vec::new(), path, lo, true)
323 Ok(TyKind::Path(None, path))
327 fn error_illegal_c_varadic_ty(&self, lo: Span) {
329 self.sess.span_diagnostic,
330 lo.to(self.prev_span),
332 "C-variadic type `...` may not be nested inside another type",
337 pub(super) fn parse_generic_bounds(
339 colon_span: Option<Span>,
340 ) -> PResult<'a, GenericBounds> {
341 self.parse_generic_bounds_common(true, colon_span)
344 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
346 /// See `parse_generic_bound` for the `BOUND` grammar.
347 fn parse_generic_bounds_common(
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),
359 if !allow_plus || !self.eat_plus() {
364 if !negative_bounds.is_empty() {
365 self.error_negative_bounds(colon_span, &bounds, negative_bounds);
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`.
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))
382 fn error_negative_bounds(
384 colon_span: Option<Span>,
385 bounds: &[GenericBound],
386 negative_bounds: Vec<Span>,
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);
401 new_bound_list = new_bound_list.replacen(" +", ":", 1);
403 err.tool_only_span_suggestion(
405 &format!("remove the bound{}", pluralize!(negative_bounds_len)),
407 Applicability::MachineApplicable,
413 /// Parses a bound according to the grammar:
415 /// BOUND = TY_BOUND | LT_BOUND
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)?
427 self.parse_generic_ty_bound(lo, has_parens, question)?
429 Ok(if is_negative { Err(anchor_lo.to(self.prev_span)) } else { Ok(bound) })
432 /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to:
434 /// LT_BOUND = LIFETIME
436 fn parse_generic_lt_bound(
441 question: Option<Span>,
442 ) -> PResult<'a, GenericBound> {
443 self.error_opt_out_lifetime(question);
444 let bound = GenericBound::Outlives(self.expect_lifetime());
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)?;
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")
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",
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",
473 Applicability::MachineApplicable,
480 /// Parses a type bound according to:
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>`)
485 fn parse_generic_ty_bound(
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)?;
494 self.expect(&token::CloseDelim(token::Paren))?;
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))
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) {
505 let params = self.parse_generic_params()?;
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.
515 pub fn check_lifetime(&mut self) -> bool {
516 self.expected_tokens.push(TokenType::Lifetime);
517 self.token.is_lifetime()
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;
525 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
527 self.span_bug(self.token.span, "not a lifetime")
531 pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
532 P(Ty { kind, span, id: ast::DUMMY_NODE_ID })