1 use super::{Parser, PathStyle, TokenType};
3 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
5 use rustc_ast::ast::{self, BareFnTy, FnRetTy, GenericParam, Lifetime, MutTy, Ty, TyKind};
7 GenericBound, GenericBounds, PolyTraitRef, TraitBoundModifier, TraitObjectSyntax,
9 use rustc_ast::ast::{Mac, Mutability};
10 use rustc_ast::ptr::P;
11 use rustc_ast::token::{self, Token, TokenKind};
12 use rustc_errors::{pluralize, struct_span_err, Applicability, PResult};
13 use rustc_span::source_map::Span;
14 use rustc_span::symbol::{kw, sym};
16 /// Any `?` or `?const` modifiers that appear at the start of a bound.
17 struct BoundModifiers {
22 maybe_const: Option<Span>,
26 fn to_trait_bound_modifier(&self) -> TraitBoundModifier {
27 match (self.maybe, self.maybe_const) {
28 (None, None) => TraitBoundModifier::None,
29 (Some(_), None) => TraitBoundModifier::Maybe,
30 (None, Some(_)) => TraitBoundModifier::MaybeConst,
31 (Some(_), Some(_)) => TraitBoundModifier::MaybeConstMaybe,
36 #[derive(Copy, Clone, PartialEq)]
37 pub(super) enum AllowPlus {
43 pub(super) enum RecoverQPath {
48 // Is `...` (`CVarArgs`) legal at this level of type parsing?
55 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
56 /// `IDENT<<u8 as Trait>::AssocTy>`.
58 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
59 /// that `IDENT` is not the ident of a fn trait.
60 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
61 t == &token::ModSep || t == &token::Lt || t == &token::BinOp(token::Shl)
66 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
67 self.parse_ty_common(AllowPlus::Yes, RecoverQPath::Yes, AllowCVariadic::No)
70 /// Parse a type suitable for a function or function pointer parameter.
71 /// The difference from `parse_ty` is that this version allows `...`
72 /// (`CVarArgs`) at the top level of the the type.
73 pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, P<Ty>> {
74 self.parse_ty_common(AllowPlus::Yes, RecoverQPath::Yes, AllowCVariadic::Yes)
77 /// Parses a type in restricted contexts where `+` is not permitted.
79 /// Example 1: `&'a TYPE`
80 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
81 /// Example 2: `value1 as TYPE + value2`
82 /// `+` is prohibited to avoid interactions with expression grammar.
83 pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
84 self.parse_ty_common(AllowPlus::No, RecoverQPath::Yes, AllowCVariadic::No)
87 /// Parses an optional return type `[ -> TY ]` in a function declaration.
88 pub(super) fn parse_ret_ty(
90 allow_plus: AllowPlus,
91 recover_qpath: RecoverQPath,
92 ) -> PResult<'a, FnRetTy> {
93 Ok(if self.eat(&token::RArrow) {
94 // FIXME(Centril): Can we unconditionally `allow_plus`?
95 let ty = self.parse_ty_common(allow_plus, recover_qpath, AllowCVariadic::No)?;
98 FnRetTy::Default(self.token.span.shrink_to_lo())
104 allow_plus: AllowPlus,
105 recover_qpath: RecoverQPath,
106 allow_c_variadic: AllowCVariadic,
107 ) -> PResult<'a, P<Ty>> {
108 let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes;
109 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
110 maybe_whole!(self, NtTy, |x| x);
112 let lo = self.token.span;
113 let mut impl_dyn_multi = false;
114 let kind = if self.check(&token::OpenDelim(token::Paren)) {
115 self.parse_ty_tuple_or_parens(lo, allow_plus)?
116 } else if self.eat(&token::Not) {
119 } else if self.eat(&token::BinOp(token::Star)) {
121 } else if self.eat(&token::OpenDelim(token::Bracket)) {
122 self.parse_array_or_slice_ty()?
123 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
126 self.parse_borrowed_pointee()?
127 } else if self.eat_keyword_noexpect(kw::Typeof) {
128 self.parse_typeof_ty()?
129 } else if self.eat_keyword(kw::Underscore) {
130 // A type to be inferred `_`
132 } else if self.token_is_bare_fn_keyword() {
133 // Function pointer type
134 self.parse_ty_bare_fn(Vec::new())?
135 } else if self.check_keyword(kw::For) {
136 // Function pointer type or bound list (trait object type) starting with a poly-trait.
137 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
138 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
139 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
140 if self.token_is_bare_fn_keyword() {
141 self.parse_ty_bare_fn(lifetime_defs)?
143 let path = self.parse_path(PathStyle::Type)?;
144 let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
145 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
147 } else if self.eat_keyword(kw::Impl) {
148 self.parse_impl_ty(&mut impl_dyn_multi)?
149 } else if self.is_explicit_dyn_type() {
150 self.parse_dyn_ty(&mut impl_dyn_multi)?
151 } else if self.check(&token::Question)
152 || self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus())
154 // Bound list (trait object type)
155 let bounds = self.parse_generic_bounds_common(allow_plus, None)?;
156 TyKind::TraitObject(bounds, TraitObjectSyntax::None)
157 } else if self.eat_lt() {
159 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
160 TyKind::Path(Some(qself), path)
161 } else if self.token.is_path_start() {
162 self.parse_path_start_ty(lo, allow_plus)?
163 } else if self.eat(&token::DotDotDot) {
164 if allow_c_variadic == AllowCVariadic::Yes {
167 // FIXME(Centril): Should we just allow `...` syntactically
168 // anywhere in a type and use semantic restrictions instead?
169 self.error_illegal_c_varadic_ty(lo);
173 let msg = format!("expected type, found {}", super::token_descr(&self.token));
174 let mut err = self.struct_span_err(self.token.span, &msg);
175 err.span_label(self.token.span, "expected type");
176 self.maybe_annotate_with_ascription(&mut err, true);
180 let span = lo.to(self.prev_span);
181 let ty = self.mk_ty(span, kind);
183 // Try to recover from use of `+` with incorrect priority.
184 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
185 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
186 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
190 /// - `(TYPE)`, a parenthesized type.
191 /// - `(TYPE,)`, a tuple with a single field of type TYPE.
192 fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
193 let mut trailing_plus = false;
194 let (ts, trailing) = self.parse_paren_comma_seq(|p| {
195 let ty = p.parse_ty()?;
196 trailing_plus = p.prev_token.kind == TokenKind::BinOp(token::Plus);
200 if ts.len() == 1 && !trailing {
201 let ty = ts.into_iter().nth(0).unwrap().into_inner();
202 let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
204 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
205 TyKind::Path(None, path) if maybe_bounds => {
206 self.parse_remaining_bounds(Vec::new(), path, lo, true)
208 TyKind::TraitObject(mut bounds, TraitObjectSyntax::None)
209 if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
211 let path = match bounds.remove(0) {
212 GenericBound::Trait(pt, ..) => pt.trait_ref.path,
213 GenericBound::Outlives(..) => {
214 return Err(self.struct_span_err(
216 "expected trait bound, not lifetime bound",
220 self.parse_remaining_bounds(Vec::new(), path, lo, true)
223 _ => Ok(TyKind::Paren(P(ty))),
230 fn parse_remaining_bounds(
232 generic_params: Vec<GenericParam>,
236 ) -> PResult<'a, TyKind> {
237 assert_ne!(self.token, token::Question);
239 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
240 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
242 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
243 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
245 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
248 /// Parses a raw pointer type: `*[const | mut] $type`.
249 fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
250 let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
251 let span = self.prev_span;
252 let msg = "expected mut or const in raw pointer type";
253 self.struct_span_err(span, msg)
254 .span_label(span, msg)
255 .help("use `*mut T` or `*const T` as appropriate")
259 let ty = self.parse_ty_no_plus()?;
260 Ok(TyKind::Ptr(MutTy { ty, mutbl }))
263 /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
264 /// The opening `[` bracket is already eaten.
265 fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
266 let elt_ty = self.parse_ty()?;
267 let ty = if self.eat(&token::Semi) {
268 TyKind::Array(elt_ty, self.parse_anon_const_expr()?)
270 TyKind::Slice(elt_ty)
272 self.expect(&token::CloseDelim(token::Bracket))?;
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 Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }))
283 // Parses the `typeof(EXPR)`.
284 // To avoid ambiguity, the type is surrounded by parenthesis.
285 fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
286 self.expect(&token::OpenDelim(token::Paren))?;
287 let expr = self.parse_anon_const_expr()?;
288 self.expect(&token::CloseDelim(token::Paren))?;
289 Ok(TyKind::Typeof(expr))
292 /// Is the current token one of the keywords that signals a bare function type?
293 fn token_is_bare_fn_keyword(&mut self) -> bool {
294 self.check_keyword(kw::Fn)
295 || self.check_keyword(kw::Unsafe)
296 || self.check_keyword(kw::Extern)
299 /// Parses a function pointer type (`TyKind::BareFn`).
301 /// [unsafe] [extern "ABI"] fn (S) -> T
302 /// ^~~~~^ ^~~~^ ^~^ ^
304 /// | | | Return type
305 /// Function Style ABI Parameter types
307 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
308 let unsafety = self.parse_unsafety();
309 let ext = self.parse_extern()?;
310 self.expect_keyword(kw::Fn)?;
311 let decl = self.parse_fn_decl(|_| false, AllowPlus::No)?;
312 Ok(TyKind::BareFn(P(BareFnTy { ext, unsafety, generic_params, decl })))
315 /// Parses an `impl B0 + ... + Bn` type.
316 fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
317 // Always parse bounds greedily for better error recovery.
318 let bounds = self.parse_generic_bounds(None)?;
319 *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
320 Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
323 /// Is a `dyn B0 + ... + Bn` type allowed here?
324 fn is_explicit_dyn_type(&mut self) -> bool {
325 self.check_keyword(kw::Dyn)
326 && (self.normalized_token.span.rust_2018()
327 || self.look_ahead(1, |t| {
328 t.can_begin_bound() && !can_continue_type_after_non_fn_ident(t)
332 /// Parses a `dyn B0 + ... + Bn` type.
334 /// Note that this does *not* parse bare trait objects.
335 fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
336 self.bump(); // `dyn`
337 // Always parse bounds greedily for better error recovery.
338 let bounds = self.parse_generic_bounds(None)?;
339 *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
340 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn))
343 /// Parses a type starting with a path.
346 /// 1. a type macro, `mac!(...)`,
347 /// 2. a bare trait object, `B0 + ... + Bn`,
348 /// 3. or a path, `path::to::MyType`.
349 fn parse_path_start_ty(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
351 let path = self.parse_path(PathStyle::Type)?;
352 if self.eat(&token::Not) {
353 // Macro invocation in type position
356 args: self.parse_mac_args()?,
357 prior_type_ascription: self.last_type_ascription,
359 } else if allow_plus == AllowPlus::Yes && self.check_plus() {
360 // `Trait1 + Trait2 + 'a`
361 self.parse_remaining_bounds(Vec::new(), path, lo, true)
364 Ok(TyKind::Path(None, path))
368 fn error_illegal_c_varadic_ty(&self, lo: Span) {
370 self.sess.span_diagnostic,
371 lo.to(self.prev_span),
373 "C-variadic type `...` may not be nested inside another type",
378 pub(super) fn parse_generic_bounds(
380 colon_span: Option<Span>,
381 ) -> PResult<'a, GenericBounds> {
382 self.parse_generic_bounds_common(AllowPlus::Yes, colon_span)
385 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
387 /// See `parse_generic_bound` for the `BOUND` grammar.
388 fn parse_generic_bounds_common(
390 allow_plus: AllowPlus,
391 colon_span: Option<Span>,
392 ) -> PResult<'a, GenericBounds> {
393 let mut bounds = Vec::new();
394 let mut negative_bounds = Vec::new();
395 while self.can_begin_bound() {
396 match self.parse_generic_bound()? {
397 Ok(bound) => bounds.push(bound),
398 Err(neg_sp) => negative_bounds.push(neg_sp),
400 if allow_plus == AllowPlus::No || !self.eat_plus() {
405 if !negative_bounds.is_empty() {
406 self.error_negative_bounds(colon_span, &bounds, negative_bounds);
412 /// Can the current token begin a bound?
413 fn can_begin_bound(&mut self) -> bool {
414 // This needs to be synchronized with `TokenKind::can_begin_bound`.
416 || self.check_lifetime()
417 || self.check(&token::Not) // Used for error reporting only.
418 || self.check(&token::Question)
419 || self.check_keyword(kw::For)
420 || self.check(&token::OpenDelim(token::Paren))
423 fn error_negative_bounds(
425 colon_span: Option<Span>,
426 bounds: &[GenericBound],
427 negative_bounds: Vec<Span>,
429 let negative_bounds_len = negative_bounds.len();
430 let last_span = *negative_bounds.last().expect("no negative bounds, but still error?");
431 let mut err = self.struct_span_err(negative_bounds, "negative bounds are not supported");
432 err.span_label(last_span, "negative bounds are not supported");
433 if let Some(bound_list) = colon_span {
434 let bound_list = bound_list.to(self.prev_span);
435 let mut new_bound_list = String::new();
436 if !bounds.is_empty() {
437 let mut snippets = bounds.iter().map(|bound| self.span_to_snippet(bound.span()));
438 while let Some(Ok(snippet)) = snippets.next() {
439 new_bound_list.push_str(" + ");
440 new_bound_list.push_str(&snippet);
442 new_bound_list = new_bound_list.replacen(" +", ":", 1);
444 err.tool_only_span_suggestion(
446 &format!("remove the bound{}", pluralize!(negative_bounds_len)),
448 Applicability::MachineApplicable,
454 /// Parses a bound according to the grammar:
456 /// BOUND = TY_BOUND | LT_BOUND
458 fn parse_generic_bound(&mut self) -> PResult<'a, Result<GenericBound, Span>> {
459 let anchor_lo = self.prev_span;
460 let lo = self.token.span;
461 let has_parens = self.eat(&token::OpenDelim(token::Paren));
462 let inner_lo = self.token.span;
463 let is_negative = self.eat(&token::Not);
465 let modifiers = self.parse_ty_bound_modifiers();
466 let bound = if self.token.is_lifetime() {
467 self.error_lt_bound_with_modifiers(modifiers);
468 self.parse_generic_lt_bound(lo, inner_lo, has_parens)?
470 self.parse_generic_ty_bound(lo, has_parens, modifiers)?
473 Ok(if is_negative { Err(anchor_lo.to(self.prev_span)) } else { Ok(bound) })
476 /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to:
478 /// LT_BOUND = LIFETIME
480 fn parse_generic_lt_bound(
485 ) -> PResult<'a, GenericBound> {
486 let bound = GenericBound::Outlives(self.expect_lifetime());
488 // FIXME(Centril): Consider not erroring here and accepting `('lt)` instead,
489 // possibly introducing `GenericBound::Paren(P<GenericBound>)`?
490 self.recover_paren_lifetime(lo, inner_lo)?;
495 /// Emits an error if any trait bound modifiers were present.
496 fn error_lt_bound_with_modifiers(&self, modifiers: BoundModifiers) {
497 if let Some(span) = modifiers.maybe_const {
498 self.struct_span_err(
500 "`?const` may only modify trait bounds, not lifetime bounds",
505 if let Some(span) = modifiers.maybe {
506 self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds")
511 /// Recover on `('lifetime)` with `(` already eaten.
512 fn recover_paren_lifetime(&mut self, lo: Span, inner_lo: Span) -> PResult<'a, ()> {
513 let inner_span = inner_lo.to(self.prev_span);
514 self.expect(&token::CloseDelim(token::Paren))?;
515 let mut err = self.struct_span_err(
516 lo.to(self.prev_span),
517 "parenthesized lifetime bounds are not supported",
519 if let Ok(snippet) = self.span_to_snippet(inner_span) {
520 err.span_suggestion_short(
521 lo.to(self.prev_span),
522 "remove the parentheses",
524 Applicability::MachineApplicable,
531 /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `?const Trait`.
533 /// If no modifiers are present, this does not consume any tokens.
536 /// TY_BOUND_MODIFIERS = "?" ["const" ["?"]]
538 fn parse_ty_bound_modifiers(&mut self) -> BoundModifiers {
539 if !self.eat(&token::Question) {
540 return BoundModifiers { maybe: None, maybe_const: None };
544 let first_question = self.prev_span;
545 if !self.eat_keyword(kw::Const) {
546 return BoundModifiers { maybe: Some(first_question), maybe_const: None };
550 let maybe_const = first_question.to(self.prev_span);
551 self.sess.gated_spans.gate(sym::const_trait_bound_opt_out, maybe_const);
552 if !self.eat(&token::Question) {
553 return BoundModifiers { maybe: None, maybe_const: Some(maybe_const) };
557 let second_question = self.prev_span;
558 BoundModifiers { maybe: Some(second_question), maybe_const: Some(maybe_const) }
561 /// Parses a type bound according to:
563 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
564 /// TY_BOUND_NOPAREN = [TY_BOUND_MODIFIERS] [for<LT_PARAM_DEFS>] SIMPLE_PATH
567 /// For example, this grammar accepts `?const ?for<'a: 'b> m::Trait<'a>`.
568 fn parse_generic_ty_bound(
572 modifiers: BoundModifiers,
573 ) -> PResult<'a, GenericBound> {
574 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
575 let path = self.parse_path(PathStyle::Type)?;
577 self.expect(&token::CloseDelim(token::Paren))?;
580 let modifier = modifiers.to_trait_bound_modifier();
581 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
582 Ok(GenericBound::Trait(poly_trait, modifier))
585 /// Optionally parses `for<$generic_params>`.
586 pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
587 if self.eat_keyword(kw::For) {
589 let params = self.parse_generic_params()?;
591 // We rely on AST validation to rule out invalid cases: There must not be type
592 // parameters, and the lifetime parameters must not have bounds.
599 pub fn check_lifetime(&mut self) -> bool {
600 self.expected_tokens.push(TokenType::Lifetime);
601 self.token.is_lifetime()
604 /// Parses a single lifetime `'a` or panics.
605 pub fn expect_lifetime(&mut self) -> Lifetime {
606 if let Some(ident) = self.token.lifetime() {
608 Lifetime { ident, id: ast::DUMMY_NODE_ID }
610 self.span_bug(self.token.span, "not a lifetime")
614 pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
615 P(Ty { kind, span, id: ast::DUMMY_NODE_ID })