1 use super::{Parser, PathStyle, TokenType};
3 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
5 use rustc_errors::{pluralize, struct_span_err, Applicability, PResult};
6 use rustc_span::source_map::Span;
7 use rustc_span::symbol::{kw, sym};
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::token::{self, Token, TokenKind};
18 /// Any `?` or `?const` modifiers that appear at the start of a bound.
19 struct BoundModifiers {
24 maybe_const: Option<Span>,
28 fn to_trait_bound_modifier(&self) -> TraitBoundModifier {
29 match (self.maybe, self.maybe_const) {
30 (None, None) => TraitBoundModifier::None,
31 (Some(_), None) => TraitBoundModifier::Maybe,
32 (None, Some(_)) => TraitBoundModifier::MaybeConst,
33 (Some(_), Some(_)) => TraitBoundModifier::MaybeConstMaybe,
38 #[derive(Copy, Clone, PartialEq)]
39 pub(super) enum AllowPlus {
45 pub(super) enum RecoverQPath {
50 // Is `...` (`CVarArgs`) legal at this level of type parsing?
57 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
58 /// `IDENT<<u8 as Trait>::AssocTy>`.
60 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
61 /// that `IDENT` is not the ident of a fn trait.
62 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
63 t == &token::ModSep || t == &token::Lt || t == &token::BinOp(token::Shl)
68 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
69 self.parse_ty_common(AllowPlus::Yes, RecoverQPath::Yes, AllowCVariadic::No)
72 /// Parse a type suitable for a function or function pointer parameter.
73 /// The difference from `parse_ty` is that this version allows `...`
74 /// (`CVarArgs`) at the top level of the the type.
75 pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, P<Ty>> {
76 self.parse_ty_common(AllowPlus::Yes, RecoverQPath::Yes, AllowCVariadic::Yes)
79 /// Parses a type in restricted contexts where `+` is not permitted.
81 /// Example 1: `&'a TYPE`
82 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
83 /// Example 2: `value1 as TYPE + value2`
84 /// `+` is prohibited to avoid interactions with expression grammar.
85 pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
86 self.parse_ty_common(AllowPlus::No, RecoverQPath::Yes, AllowCVariadic::No)
89 /// Parses an optional return type `[ -> TY ]` in a function declaration.
90 pub(super) fn parse_ret_ty(
92 allow_plus: AllowPlus,
93 recover_qpath: RecoverQPath,
94 ) -> PResult<'a, FunctionRetTy> {
95 Ok(if self.eat(&token::RArrow) {
96 // FIXME(Centril): Can we unconditionally `allow_plus`?
97 let ty = self.parse_ty_common(allow_plus, recover_qpath, AllowCVariadic::No)?;
100 FunctionRetTy::Default(self.token.span.shrink_to_lo())
106 allow_plus: AllowPlus,
107 recover_qpath: RecoverQPath,
108 allow_c_variadic: AllowCVariadic,
109 ) -> PResult<'a, P<Ty>> {
110 let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes;
111 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
112 maybe_whole!(self, NtTy, |x| x);
114 let lo = self.token.span;
115 let mut impl_dyn_multi = false;
116 let kind = if self.check(&token::OpenDelim(token::Paren)) {
117 self.parse_ty_tuple_or_parens(lo, allow_plus)?
118 } else if self.eat(&token::Not) {
121 } else if self.eat(&token::BinOp(token::Star)) {
123 } else if self.eat(&token::OpenDelim(token::Bracket)) {
124 self.parse_array_or_slice_ty()?
125 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
128 self.parse_borrowed_pointee()?
129 } else if self.eat_keyword_noexpect(kw::Typeof) {
130 self.parse_typeof_ty()?
131 } else if self.eat_keyword(kw::Underscore) {
132 // A type to be inferred `_`
134 } else if self.token_is_bare_fn_keyword() {
135 // Function pointer type
136 self.parse_ty_bare_fn(Vec::new())?
137 } else if self.check_keyword(kw::For) {
138 // Function pointer type or bound list (trait object type) starting with a poly-trait.
139 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
140 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
141 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
142 if self.token_is_bare_fn_keyword() {
143 self.parse_ty_bare_fn(lifetime_defs)?
145 let path = self.parse_path(PathStyle::Type)?;
146 let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
147 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
149 } else if self.eat_keyword(kw::Impl) {
150 self.parse_impl_ty(&mut impl_dyn_multi)?
151 } else if self.is_explicit_dyn_type() {
152 self.parse_dyn_ty(&mut impl_dyn_multi)?
153 } else if self.check(&token::Question)
154 || self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus())
156 // Bound list (trait object type)
157 let bounds = self.parse_generic_bounds_common(allow_plus, None)?;
158 TyKind::TraitObject(bounds, TraitObjectSyntax::None)
159 } else if self.eat_lt() {
161 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
162 TyKind::Path(Some(qself), path)
163 } else if self.token.is_path_start() {
164 self.parse_path_start_ty(lo, allow_plus)?
165 } else if self.eat(&token::DotDotDot) {
166 if allow_c_variadic == AllowCVariadic::Yes {
169 // FIXME(Centril): Should we just allow `...` syntactically
170 // anywhere in a type and use semantic restrictions instead?
171 self.error_illegal_c_varadic_ty(lo);
175 let msg = format!("expected type, found {}", super::token_descr(&self.token));
176 let mut err = self.struct_span_err(self.token.span, &msg);
177 err.span_label(self.token.span, "expected type");
178 self.maybe_annotate_with_ascription(&mut err, true);
182 let span = lo.to(self.prev_span);
183 let ty = self.mk_ty(span, kind);
185 // Try to recover from use of `+` with incorrect priority.
186 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
187 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
188 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
192 /// - `(TYPE)`, a parenthesized type.
193 /// - `(TYPE,)`, a tuple with a single field of type TYPE.
194 fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
195 let mut trailing_plus = false;
196 let (ts, trailing) = self.parse_paren_comma_seq(|p| {
197 let ty = p.parse_ty()?;
198 trailing_plus = p.prev_token.kind == TokenKind::BinOp(token::Plus);
202 if ts.len() == 1 && !trailing {
203 let ty = ts.into_iter().nth(0).unwrap().into_inner();
204 let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
206 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
207 TyKind::Path(None, path) if maybe_bounds => {
208 self.parse_remaining_bounds(Vec::new(), path, lo, true)
210 TyKind::TraitObject(mut bounds, TraitObjectSyntax::None)
211 if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
213 let path = match bounds.remove(0) {
214 GenericBound::Trait(pt, ..) => pt.trait_ref.path,
215 GenericBound::Outlives(..) => {
216 return Err(self.struct_span_err(
218 "expected trait bound, not lifetime bound",
222 self.parse_remaining_bounds(Vec::new(), path, lo, true)
225 _ => Ok(TyKind::Paren(P(ty))),
232 fn parse_remaining_bounds(
234 generic_params: Vec<GenericParam>,
238 ) -> PResult<'a, TyKind> {
239 assert_ne!(self.token, token::Question);
241 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
242 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
244 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
245 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
247 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
250 /// Parses a raw pointer type: `*[const | mut] $type`.
251 fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
252 let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
253 let span = self.prev_span;
254 let msg = "expected mut or const in raw pointer type";
255 self.struct_span_err(span, msg)
256 .span_label(span, msg)
257 .help("use `*mut T` or `*const T` as appropriate")
261 let ty = self.parse_ty_no_plus()?;
262 Ok(TyKind::Ptr(MutTy { ty, mutbl }))
265 /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
266 /// The opening `[` bracket is already eaten.
267 fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
268 let elt_ty = self.parse_ty()?;
269 let ty = if self.eat(&token::Semi) {
270 TyKind::Array(elt_ty, self.parse_anon_const_expr()?)
272 TyKind::Slice(elt_ty)
274 self.expect(&token::CloseDelim(token::Bracket))?;
278 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
279 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
280 let mutbl = self.parse_mutability();
281 let ty = self.parse_ty_no_plus()?;
282 Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }))
285 // Parses the `typeof(EXPR)`.
286 // To avoid ambiguity, the type is surrounded by parenthesis.
287 fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
288 self.expect(&token::OpenDelim(token::Paren))?;
289 let expr = self.parse_anon_const_expr()?;
290 self.expect(&token::CloseDelim(token::Paren))?;
291 Ok(TyKind::Typeof(expr))
294 /// Is the current token one of the keywords that signals a bare function type?
295 fn token_is_bare_fn_keyword(&mut self) -> bool {
296 self.check_keyword(kw::Fn)
297 || self.check_keyword(kw::Unsafe)
298 || self.check_keyword(kw::Extern)
301 /// Parses a function pointer type (`TyKind::BareFn`).
303 /// [unsafe] [extern "ABI"] fn (S) -> T
304 /// ^~~~~^ ^~~~^ ^~^ ^
306 /// | | | Return type
307 /// Function Style ABI Parameter types
309 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
310 let unsafety = self.parse_unsafety();
311 let ext = self.parse_extern()?;
312 self.expect_keyword(kw::Fn)?;
313 let decl = self.parse_fn_decl(|_| false, AllowPlus::No)?;
314 Ok(TyKind::BareFn(P(BareFnTy { ext, unsafety, generic_params, decl })))
317 /// Parses an `impl B0 + ... + Bn` type.
318 fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
319 // Always parse bounds greedily for better error recovery.
320 let bounds = self.parse_generic_bounds(None)?;
321 *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
322 Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
325 /// Is a `dyn B0 + ... + Bn` type allowed here?
326 fn is_explicit_dyn_type(&mut self) -> bool {
327 self.check_keyword(kw::Dyn)
328 && (self.token.span.rust_2018()
329 || self.look_ahead(1, |t| {
330 t.can_begin_bound() && !can_continue_type_after_non_fn_ident(t)
334 /// Parses a `dyn B0 + ... + Bn` type.
336 /// Note that this does *not* parse bare trait objects.
337 fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
338 self.bump(); // `dyn`
339 // Always parse bounds greedily for better error recovery.
340 let bounds = self.parse_generic_bounds(None)?;
341 *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
342 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn))
345 /// Parses a type starting with a path.
348 /// 1. a type macro, `mac!(...)`,
349 /// 2. a bare trait object, `B0 + ... + Bn`,
350 /// 3. or a path, `path::to::MyType`.
351 fn parse_path_start_ty(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
353 let path = self.parse_path(PathStyle::Type)?;
354 if self.eat(&token::Not) {
355 // Macro invocation in type position
358 args: self.parse_mac_args()?,
359 prior_type_ascription: self.last_type_ascription,
361 } else if allow_plus == AllowPlus::Yes && self.check_plus() {
362 // `Trait1 + Trait2 + 'a`
363 self.parse_remaining_bounds(Vec::new(), path, lo, true)
366 Ok(TyKind::Path(None, path))
370 fn error_illegal_c_varadic_ty(&self, lo: Span) {
372 self.sess.span_diagnostic,
373 lo.to(self.prev_span),
375 "C-variadic type `...` may not be nested inside another type",
380 pub(super) fn parse_generic_bounds(
382 colon_span: Option<Span>,
383 ) -> PResult<'a, GenericBounds> {
384 self.parse_generic_bounds_common(AllowPlus::Yes, colon_span)
387 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
389 /// See `parse_generic_bound` for the `BOUND` grammar.
390 fn parse_generic_bounds_common(
392 allow_plus: AllowPlus,
393 colon_span: Option<Span>,
394 ) -> PResult<'a, GenericBounds> {
395 let mut bounds = Vec::new();
396 let mut negative_bounds = Vec::new();
397 while self.can_begin_bound() {
398 match self.parse_generic_bound()? {
399 Ok(bound) => bounds.push(bound),
400 Err(neg_sp) => negative_bounds.push(neg_sp),
402 if allow_plus == AllowPlus::No || !self.eat_plus() {
407 if !negative_bounds.is_empty() {
408 self.error_negative_bounds(colon_span, &bounds, negative_bounds);
414 /// Can the current token begin a bound?
415 fn can_begin_bound(&mut self) -> bool {
416 // This needs to be synchronized with `TokenKind::can_begin_bound`.
418 || self.check_lifetime()
419 || self.check(&token::Not) // Used for error reporting only.
420 || self.check(&token::Question)
421 || self.check_keyword(kw::For)
422 || self.check(&token::OpenDelim(token::Paren))
425 fn error_negative_bounds(
427 colon_span: Option<Span>,
428 bounds: &[GenericBound],
429 negative_bounds: Vec<Span>,
431 let negative_bounds_len = negative_bounds.len();
432 let last_span = *negative_bounds.last().expect("no negative bounds, but still error?");
433 let mut err = self.struct_span_err(negative_bounds, "negative bounds are not supported");
434 err.span_label(last_span, "negative bounds are not supported");
435 if let Some(bound_list) = colon_span {
436 let bound_list = bound_list.to(self.prev_span);
437 let mut new_bound_list = String::new();
438 if !bounds.is_empty() {
439 let mut snippets = bounds.iter().map(|bound| self.span_to_snippet(bound.span()));
440 while let Some(Ok(snippet)) = snippets.next() {
441 new_bound_list.push_str(" + ");
442 new_bound_list.push_str(&snippet);
444 new_bound_list = new_bound_list.replacen(" +", ":", 1);
446 err.tool_only_span_suggestion(
448 &format!("remove the bound{}", pluralize!(negative_bounds_len)),
450 Applicability::MachineApplicable,
456 /// Parses a bound according to the grammar:
458 /// BOUND = TY_BOUND | LT_BOUND
460 fn parse_generic_bound(&mut self) -> PResult<'a, Result<GenericBound, Span>> {
461 let anchor_lo = self.prev_span;
462 let lo = self.token.span;
463 let has_parens = self.eat(&token::OpenDelim(token::Paren));
464 let inner_lo = self.token.span;
465 let is_negative = self.eat(&token::Not);
467 let modifiers = self.parse_ty_bound_modifiers();
468 let bound = if self.token.is_lifetime() {
469 self.error_lt_bound_with_modifiers(modifiers);
470 self.parse_generic_lt_bound(lo, inner_lo, has_parens)?
472 self.parse_generic_ty_bound(lo, has_parens, modifiers)?
475 Ok(if is_negative { Err(anchor_lo.to(self.prev_span)) } else { Ok(bound) })
478 /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to:
480 /// LT_BOUND = LIFETIME
482 fn parse_generic_lt_bound(
487 ) -> PResult<'a, GenericBound> {
488 let bound = GenericBound::Outlives(self.expect_lifetime());
490 // FIXME(Centril): Consider not erroring here and accepting `('lt)` instead,
491 // possibly introducing `GenericBound::Paren(P<GenericBound>)`?
492 self.recover_paren_lifetime(lo, inner_lo)?;
497 /// Emits an error if any trait bound modifiers were present.
498 fn error_lt_bound_with_modifiers(&self, modifiers: BoundModifiers) {
499 if let Some(span) = modifiers.maybe_const {
500 self.struct_span_err(
502 "`?const` may only modify trait bounds, not lifetime bounds",
507 if let Some(span) = modifiers.maybe {
508 self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds")
513 /// Recover on `('lifetime)` with `(` already eaten.
514 fn recover_paren_lifetime(&mut self, lo: Span, inner_lo: Span) -> PResult<'a, ()> {
515 let inner_span = inner_lo.to(self.prev_span);
516 self.expect(&token::CloseDelim(token::Paren))?;
517 let mut err = self.struct_span_err(
518 lo.to(self.prev_span),
519 "parenthesized lifetime bounds are not supported",
521 if let Ok(snippet) = self.span_to_snippet(inner_span) {
522 err.span_suggestion_short(
523 lo.to(self.prev_span),
524 "remove the parentheses",
526 Applicability::MachineApplicable,
533 /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `?const Trait`.
535 /// If no modifiers are present, this does not consume any tokens.
538 /// TY_BOUND_MODIFIERS = "?" ["const" ["?"]]
540 fn parse_ty_bound_modifiers(&mut self) -> BoundModifiers {
541 if !self.eat(&token::Question) {
542 return BoundModifiers { maybe: None, maybe_const: None };
546 let first_question = self.prev_span;
547 if !self.eat_keyword(kw::Const) {
548 return BoundModifiers { maybe: Some(first_question), maybe_const: None };
552 let maybe_const = first_question.to(self.prev_span);
553 self.sess.gated_spans.gate(sym::const_trait_bound_opt_out, maybe_const);
554 if !self.eat(&token::Question) {
555 return BoundModifiers { maybe: None, maybe_const: Some(maybe_const) };
559 let second_question = self.prev_span;
560 BoundModifiers { maybe: Some(second_question), maybe_const: Some(maybe_const) }
563 /// Parses a type bound according to:
565 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
566 /// TY_BOUND_NOPAREN = [TY_BOUND_MODIFIERS] [for<LT_PARAM_DEFS>] SIMPLE_PATH
569 /// For example, this grammar accepts `?const ?for<'a: 'b> m::Trait<'a>`.
570 fn parse_generic_ty_bound(
574 modifiers: BoundModifiers,
575 ) -> PResult<'a, GenericBound> {
576 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
577 let path = self.parse_path(PathStyle::Type)?;
579 self.expect(&token::CloseDelim(token::Paren))?;
582 let modifier = modifiers.to_trait_bound_modifier();
583 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
584 Ok(GenericBound::Trait(poly_trait, modifier))
587 /// Optionally parses `for<$generic_params>`.
588 pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
589 if self.eat_keyword(kw::For) {
591 let params = self.parse_generic_params()?;
593 // We rely on AST validation to rule out invalid cases: There must not be type
594 // parameters, and the lifetime parameters must not have bounds.
601 pub fn check_lifetime(&mut self) -> bool {
602 self.expected_tokens.push(TokenType::Lifetime);
603 self.token.is_lifetime()
606 /// Parses a single lifetime `'a` or panics.
607 pub fn expect_lifetime(&mut self) -> Lifetime {
608 if let Some(ident) = self.token.lifetime() {
609 let span = self.token.span;
611 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
613 self.span_bug(self.token.span, "not a lifetime")
617 pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
618 P(Ty { kind, span, id: ast::DUMMY_NODE_ID })