1 use super::{Parser, PathStyle, TokenType};
3 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
6 use rustc_ast::token::{self, Delimiter, Token, TokenKind};
7 use rustc_ast::util::case::Case;
9 self as ast, BareFnTy, FnRetTy, GenericBound, GenericBounds, GenericParam, Generics, Lifetime,
10 MacCall, MutTy, Mutability, PolyTraitRef, TraitBoundModifier, TraitObjectSyntax, Ty, TyKind,
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 pub(super) enum RecoverQuestionMark {
53 /// Signals whether parsing a type should recover `->`.
55 /// More specifically, when parsing a function like:
57 /// fn foo() => u8 { 0 }
58 /// fn bar(): u8 { 0 }
60 /// The compiler will try to recover interpreting `foo() => u8` as `foo() -> u8` when calling
61 /// `parse_ty` with anything except `RecoverReturnSign::No`, and it will try to recover `bar(): u8`
62 /// as `bar() -> u8` when passing `RecoverReturnSign::Yes` to `parse_ty`
63 #[derive(Copy, Clone, PartialEq)]
64 pub(super) enum RecoverReturnSign {
70 impl RecoverReturnSign {
71 /// [RecoverReturnSign::Yes] allows for recovering `fn foo() => u8` and `fn foo(): u8`,
72 /// [RecoverReturnSign::OnlyFatArrow] allows for recovering only `fn foo() => u8` (recovering
73 /// colons can cause problems when parsing where clauses), and
74 /// [RecoverReturnSign::No] doesn't allow for any recovery of the return type arrow
75 fn can_recover(self, token: &TokenKind) -> bool {
77 Self::Yes => matches!(token, token::FatArrow | token::Colon),
78 Self::OnlyFatArrow => matches!(token, token::FatArrow),
84 // Is `...` (`CVarArgs`) legal at this level of type parsing?
91 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
92 /// `IDENT<<u8 as Trait>::AssocTy>`.
94 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
95 /// that `IDENT` is not the ident of a fn trait.
96 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
97 t == &token::ModSep || t == &token::Lt || t == &token::BinOp(token::Shl)
100 impl<'a> Parser<'a> {
102 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
103 self.parse_ty_common(
107 RecoverReturnSign::Yes,
109 RecoverQuestionMark::Yes,
113 pub(super) fn parse_ty_with_generics_recovery(
115 ty_params: &Generics,
116 ) -> PResult<'a, P<Ty>> {
117 self.parse_ty_common(
121 RecoverReturnSign::Yes,
123 RecoverQuestionMark::Yes,
127 /// Parse a type suitable for a function or function pointer parameter.
128 /// The difference from `parse_ty` is that this version allows `...`
129 /// (`CVarArgs`) at the top level of the type.
130 pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, P<Ty>> {
131 self.parse_ty_common(
135 RecoverReturnSign::Yes,
137 RecoverQuestionMark::Yes,
141 /// Parses a type in restricted contexts where `+` is not permitted.
143 /// Example 1: `&'a TYPE`
144 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
145 /// Example 2: `value1 as TYPE + value2`
146 /// `+` is prohibited to avoid interactions with expression grammar.
147 pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
148 self.parse_ty_common(
152 RecoverReturnSign::Yes,
154 RecoverQuestionMark::Yes,
158 /// Parses a type following an `as` cast. Similar to `parse_ty_no_plus`, but signaling origin
159 /// for better diagnostics involving `?`.
160 pub(super) fn parse_as_cast_ty(&mut self) -> PResult<'a, P<Ty>> {
161 self.parse_ty_common(
165 RecoverReturnSign::Yes,
167 RecoverQuestionMark::No,
171 pub(super) fn parse_no_question_mark_recover(&mut self) -> PResult<'a, P<Ty>> {
172 self.parse_ty_common(
176 RecoverReturnSign::Yes,
178 RecoverQuestionMark::No,
182 /// Parse a type without recovering `:` as `->` to avoid breaking code such as `where fn() : for<'a>`
183 pub(super) fn parse_ty_for_where_clause(&mut self) -> PResult<'a, P<Ty>> {
184 self.parse_ty_common(
188 RecoverReturnSign::OnlyFatArrow,
190 RecoverQuestionMark::Yes,
194 /// Parses an optional return type `[ -> TY ]` in a function declaration.
195 pub(super) fn parse_ret_ty(
197 allow_plus: AllowPlus,
198 recover_qpath: RecoverQPath,
199 recover_return_sign: RecoverReturnSign,
200 ) -> PResult<'a, FnRetTy> {
201 Ok(if self.eat(&token::RArrow) {
202 // FIXME(Centril): Can we unconditionally `allow_plus`?
203 let ty = self.parse_ty_common(
209 RecoverQuestionMark::Yes,
212 } else if recover_return_sign.can_recover(&self.token.kind) {
213 // Don't `eat` to prevent `=>` from being added as an expected token which isn't
214 // actually expected and could only confuse users
216 self.struct_span_err(self.prev_token.span, "return types are denoted using `->`")
217 .span_suggestion_short(
218 self.prev_token.span,
221 Applicability::MachineApplicable,
224 let ty = self.parse_ty_common(
230 RecoverQuestionMark::Yes,
234 FnRetTy::Default(self.token.span.shrink_to_lo())
240 allow_plus: AllowPlus,
241 allow_c_variadic: AllowCVariadic,
242 recover_qpath: RecoverQPath,
243 recover_return_sign: RecoverReturnSign,
244 ty_generics: Option<&Generics>,
245 recover_question_mark: RecoverQuestionMark,
246 ) -> PResult<'a, P<Ty>> {
247 let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes;
248 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
249 maybe_whole!(self, NtTy, |x| x);
251 let lo = self.token.span;
252 let mut impl_dyn_multi = false;
253 let kind = if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
254 self.parse_ty_tuple_or_parens(lo, allow_plus)?
255 } else if self.eat(&token::Not) {
258 } else if self.eat(&token::BinOp(token::Star)) {
260 } else if self.eat(&token::OpenDelim(Delimiter::Bracket)) {
261 self.parse_array_or_slice_ty()?
262 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
265 self.parse_borrowed_pointee()?
266 } else if self.eat_keyword_noexpect(kw::Typeof) {
267 self.parse_typeof_ty()?
268 } else if self.eat_keyword(kw::Underscore) {
269 // A type to be inferred `_`
271 } else if self.check_fn_front_matter(false, Case::Sensitive) {
272 // Function pointer type
273 self.parse_ty_bare_fn(lo, Vec::new(), recover_return_sign)?
274 } else if self.check_keyword(kw::For) {
275 // Function pointer type or bound list (trait object type) starting with a poly-trait.
276 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
277 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
278 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
279 if self.check_fn_front_matter(false, Case::Sensitive) {
280 self.parse_ty_bare_fn(lo, lifetime_defs, recover_return_sign)?
282 let path = self.parse_path(PathStyle::Type)?;
283 let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
284 self.parse_remaining_bounds_path(lifetime_defs, path, lo, parse_plus)?
286 } else if self.eat_keyword(kw::Impl) {
287 self.parse_impl_ty(&mut impl_dyn_multi)?
288 } else if self.is_explicit_dyn_type() {
289 self.parse_dyn_ty(&mut impl_dyn_multi)?
290 } else if self.eat_lt() {
292 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
293 TyKind::Path(Some(qself), path)
294 } else if self.check_path() {
295 self.parse_path_start_ty(lo, allow_plus, ty_generics)?
296 } else if self.can_begin_bound() {
297 self.parse_bare_trait_object(lo, allow_plus)?
298 } else if self.eat(&token::DotDotDot) {
299 if allow_c_variadic == AllowCVariadic::Yes {
302 // FIXME(Centril): Should we just allow `...` syntactically
303 // anywhere in a type and use semantic restrictions instead?
304 self.error_illegal_c_varadic_ty(lo);
308 let msg = format!("expected type, found {}", super::token_descr(&self.token));
309 let mut err = self.struct_span_err(self.token.span, &msg);
310 err.span_label(self.token.span, "expected type");
311 self.maybe_annotate_with_ascription(&mut err, true);
315 let span = lo.to(self.prev_token.span);
316 let mut ty = self.mk_ty(span, kind);
318 // Try to recover from use of `+` with incorrect priority.
319 if matches!(allow_plus, AllowPlus::Yes) {
320 self.maybe_recover_from_bad_type_plus(&ty)?;
322 self.maybe_report_ambiguous_plus(impl_dyn_multi, &ty);
324 if let RecoverQuestionMark::Yes = recover_question_mark {
325 ty = self.maybe_recover_from_question_mark(ty);
327 if allow_qpath_recovery { self.maybe_recover_from_bad_qpath(ty) } else { Ok(ty) }
331 /// - `(TYPE)`, a parenthesized type.
332 /// - `(TYPE,)`, a tuple with a single field of type TYPE.
333 fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
334 let mut trailing_plus = false;
335 let (ts, trailing) = self.parse_paren_comma_seq(|p| {
336 let ty = p.parse_ty()?;
337 trailing_plus = p.prev_token.kind == TokenKind::BinOp(token::Plus);
341 if ts.len() == 1 && !trailing {
342 let ty = ts.into_iter().next().unwrap().into_inner();
343 let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
345 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
346 TyKind::Path(None, path) if maybe_bounds => {
347 self.parse_remaining_bounds_path(Vec::new(), path, lo, true)
349 TyKind::TraitObject(bounds, TraitObjectSyntax::None)
350 if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
352 self.parse_remaining_bounds(bounds, true)
355 _ => Ok(TyKind::Paren(P(ty))),
362 fn parse_bare_trait_object(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
363 let lt_no_plus = self.check_lifetime() && !self.look_ahead(1, |t| t.is_like_plus());
364 let bounds = self.parse_generic_bounds_common(allow_plus, None)?;
366 self.struct_span_err(lo, "lifetime in trait object type must be followed by `+`")
369 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
372 fn parse_remaining_bounds_path(
374 generic_params: Vec<GenericParam>,
378 ) -> PResult<'a, TyKind> {
379 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_token.span));
380 let bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
381 self.parse_remaining_bounds(bounds, parse_plus)
384 /// Parse the remainder of a bare trait object type given an already parsed list.
385 fn parse_remaining_bounds(
387 mut bounds: GenericBounds,
389 ) -> PResult<'a, TyKind> {
391 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
392 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_token.span))?);
394 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
397 /// Parses a raw pointer type: `*[const | mut] $type`.
398 fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
399 let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
400 let span = self.prev_token.span;
401 self.struct_span_err(span, "expected `mut` or `const` keyword in raw pointer type")
404 "add `mut` or `const` here",
405 ["mut ".to_string(), "const ".to_string()],
406 Applicability::HasPlaceholders,
411 let ty = self.parse_ty_no_plus()?;
412 Ok(TyKind::Ptr(MutTy { ty, mutbl }))
415 /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
416 /// The opening `[` bracket is already eaten.
417 fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
418 let elt_ty = match self.parse_ty() {
421 if self.look_ahead(1, |t| t.kind == token::CloseDelim(Delimiter::Bracket))
422 | self.look_ahead(1, |t| t.kind == token::Semi) =>
424 // Recover from `[LIT; EXPR]` and `[LIT]`
427 self.mk_ty(self.prev_token.span, TyKind::Err)
429 Err(err) => return Err(err),
432 let ty = if self.eat(&token::Semi) {
433 let mut length = self.parse_anon_const_expr()?;
434 if let Err(e) = self.expect(&token::CloseDelim(Delimiter::Bracket)) {
435 // Try to recover from `X<Y, ...>` when `X::<Y, ...>` works
436 self.check_mistyped_turbofish_with_multiple_type_params(e, &mut length.value)?;
437 self.expect(&token::CloseDelim(Delimiter::Bracket))?;
439 TyKind::Array(elt_ty, length)
441 self.expect(&token::CloseDelim(Delimiter::Bracket))?;
442 TyKind::Slice(elt_ty)
448 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
449 let and_span = self.prev_token.span;
450 let mut opt_lifetime =
451 if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
452 let mut mutbl = self.parse_mutability();
453 if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() {
454 // A lifetime is invalid here: it would be part of a bare trait bound, which requires
455 // it to be followed by a plus, but we disallow plus in the pointee type.
456 // So we can handle this case as an error here, and suggest `'a mut`.
457 // If there *is* a plus next though, handling the error later provides better suggestions
458 // (like adding parentheses)
459 if !self.look_ahead(1, |t| t.is_like_plus()) {
460 let lifetime_span = self.token.span;
461 let span = and_span.to(lifetime_span);
463 let mut err = self.struct_span_err(span, "lifetime must precede `mut`");
464 if let Ok(lifetime_src) = self.span_to_snippet(lifetime_span) {
467 "place the lifetime before `mut`",
468 format!("&{} mut", lifetime_src),
469 Applicability::MaybeIncorrect,
474 opt_lifetime = Some(self.expect_lifetime());
476 } else if self.token.is_keyword(kw::Dyn)
477 && mutbl == Mutability::Not
478 && self.look_ahead(1, |t| t.is_keyword(kw::Mut))
480 // We have `&dyn mut ...`, which is invalid and should be `&mut dyn ...`.
481 let span = and_span.to(self.look_ahead(1, |t| t.span));
482 let mut err = self.struct_span_err(span, "`mut` must precede `dyn`");
485 "place `mut` before `dyn`",
487 Applicability::MachineApplicable,
492 mutbl = Mutability::Mut;
493 let (dyn_tok, dyn_tok_sp) = (self.token.clone(), self.token_spacing);
495 self.bump_with((dyn_tok, dyn_tok_sp));
497 let ty = self.parse_ty_no_plus()?;
498 Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }))
501 // Parses the `typeof(EXPR)`.
502 // To avoid ambiguity, the type is surrounded by parentheses.
503 fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
504 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
505 let expr = self.parse_anon_const_expr()?;
506 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
507 Ok(TyKind::Typeof(expr))
510 /// Parses a function pointer type (`TyKind::BareFn`).
511 /// ```ignore (illustrative)
512 /// [unsafe] [extern "ABI"] fn (S) -> T
513 /// // ^~~~~^ ^~~~^ ^~^ ^
515 /// // | | | Return type
516 /// // Function Style ABI Parameter types
518 /// We actually parse `FnHeader FnDecl`, but we error on `const` and `async` qualifiers.
522 params: Vec<GenericParam>,
523 recover_return_sign: RecoverReturnSign,
524 ) -> PResult<'a, TyKind> {
525 let inherited_vis = rustc_ast::Visibility {
526 span: rustc_span::DUMMY_SP,
527 kind: rustc_ast::VisibilityKind::Inherited,
530 let span_start = self.token.span;
531 let ast::FnHeader { ext, unsafety, constness, asyncness } =
532 self.parse_fn_front_matter(&inherited_vis)?;
533 let decl = self.parse_fn_decl(|_| false, AllowPlus::No, recover_return_sign)?;
534 let whole_span = lo.to(self.prev_token.span);
535 if let ast::Const::Yes(span) = constness {
536 // If we ever start to allow `const fn()`, then update
537 // feature gating for `#![feature(const_extern_fn)]` to
539 self.error_fn_ptr_bad_qualifier(whole_span, span, "const");
541 if let ast::Async::Yes { span, .. } = asyncness {
542 self.error_fn_ptr_bad_qualifier(whole_span, span, "async");
544 let decl_span = span_start.to(self.token.span);
545 Ok(TyKind::BareFn(P(BareFnTy { ext, unsafety, generic_params: params, decl, decl_span })))
548 /// Emit an error for the given bad function pointer qualifier.
549 fn error_fn_ptr_bad_qualifier(&self, span: Span, qual_span: Span, qual: &str) {
550 self.struct_span_err(span, &format!("an `fn` pointer type cannot be `{}`", qual))
551 .span_label(qual_span, format!("`{}` because of this", qual))
552 .span_suggestion_short(
554 &format!("remove the `{}` qualifier", qual),
556 Applicability::MaybeIncorrect,
561 /// Parses an `impl B0 + ... + Bn` type.
562 fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
563 // Always parse bounds greedily for better error recovery.
564 let bounds = self.parse_generic_bounds(None)?;
565 *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
566 Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
569 /// Is a `dyn B0 + ... + Bn` type allowed here?
570 fn is_explicit_dyn_type(&mut self) -> bool {
571 self.check_keyword(kw::Dyn)
572 && (!self.token.uninterpolated_span().rust_2015()
573 || self.look_ahead(1, |t| {
574 (t.can_begin_bound() || t.kind == TokenKind::BinOp(token::Star))
575 && !can_continue_type_after_non_fn_ident(t)
579 /// Parses a `dyn B0 + ... + Bn` type.
581 /// Note that this does *not* parse bare trait objects.
582 fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
583 self.bump(); // `dyn`
586 let syntax = if self.eat(&TokenKind::BinOp(token::Star)) {
587 TraitObjectSyntax::DynStar
589 TraitObjectSyntax::Dyn
592 // Always parse bounds greedily for better error recovery.
593 let bounds = self.parse_generic_bounds(None)?;
594 *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
595 Ok(TyKind::TraitObject(bounds, syntax))
598 /// Parses a type starting with a path.
601 /// 1. a type macro, `mac!(...)`,
602 /// 2. a bare trait object, `B0 + ... + Bn`,
603 /// 3. or a path, `path::to::MyType`.
604 fn parse_path_start_ty(
607 allow_plus: AllowPlus,
608 ty_generics: Option<&Generics>,
609 ) -> PResult<'a, TyKind> {
611 let path = self.parse_path_inner(PathStyle::Type, ty_generics)?;
612 if self.eat(&token::Not) {
613 // Macro invocation in type position
614 Ok(TyKind::MacCall(P(MacCall {
616 args: self.parse_mac_args()?,
617 prior_type_ascription: self.last_type_ascription,
619 } else if allow_plus == AllowPlus::Yes && self.check_plus() {
620 // `Trait1 + Trait2 + 'a`
621 self.parse_remaining_bounds_path(Vec::new(), path, lo, true)
624 Ok(TyKind::Path(None, path))
628 fn error_illegal_c_varadic_ty(&self, lo: Span) {
630 self.sess.span_diagnostic,
631 lo.to(self.prev_token.span),
633 "C-variadic type `...` may not be nested inside another type",
638 pub(super) fn parse_generic_bounds(
640 colon_span: Option<Span>,
641 ) -> PResult<'a, GenericBounds> {
642 self.parse_generic_bounds_common(AllowPlus::Yes, colon_span)
645 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
647 /// See `parse_generic_bound` for the `BOUND` grammar.
648 fn parse_generic_bounds_common(
650 allow_plus: AllowPlus,
651 colon_span: Option<Span>,
652 ) -> PResult<'a, GenericBounds> {
653 let mut bounds = Vec::new();
654 let mut negative_bounds = Vec::new();
656 while self.can_begin_bound()
657 // Continue even if we find a keyword.
658 // This is necessary for error recover on, for example, `impl fn()`.
660 // The only keyword that can go after generic bounds is `where`, so stop if it's it.
661 || (self.token.is_reserved_ident() && !self.token.is_keyword(kw::Where))
663 if self.token.is_keyword(kw::Dyn) {
664 // Account for `&dyn Trait + dyn Other`.
665 self.struct_span_err(self.token.span, "invalid `dyn` keyword")
666 .help("`dyn` is only needed at the start of a trait `+`-separated list")
669 "remove this keyword",
671 Applicability::MachineApplicable,
676 match self.parse_generic_bound()? {
677 Ok(bound) => bounds.push(bound),
678 Err(neg_sp) => negative_bounds.push(neg_sp),
680 if allow_plus == AllowPlus::No || !self.eat_plus() {
685 if !negative_bounds.is_empty() {
686 self.error_negative_bounds(colon_span, &bounds, negative_bounds);
692 /// Can the current token begin a bound?
693 fn can_begin_bound(&mut self) -> bool {
694 // This needs to be synchronized with `TokenKind::can_begin_bound`.
696 || self.check_lifetime()
697 || self.check(&token::Not) // Used for error reporting only.
698 || self.check(&token::Question)
699 || self.check(&token::Tilde)
700 || self.check_keyword(kw::For)
701 || self.check(&token::OpenDelim(Delimiter::Parenthesis))
704 fn error_negative_bounds(
706 colon_span: Option<Span>,
707 bounds: &[GenericBound],
708 negative_bounds: Vec<Span>,
710 let negative_bounds_len = negative_bounds.len();
711 let last_span = *negative_bounds.last().expect("no negative bounds, but still error?");
712 let mut err = self.struct_span_err(negative_bounds, "negative bounds are not supported");
713 err.span_label(last_span, "negative bounds are not supported");
714 if let Some(bound_list) = colon_span {
715 let bound_list = bound_list.to(self.prev_token.span);
716 let mut new_bound_list = String::new();
717 if !bounds.is_empty() {
718 let mut snippets = bounds.iter().map(|bound| self.span_to_snippet(bound.span()));
719 while let Some(Ok(snippet)) = snippets.next() {
720 new_bound_list.push_str(" + ");
721 new_bound_list.push_str(&snippet);
723 new_bound_list = new_bound_list.replacen(" +", ":", 1);
725 err.tool_only_span_suggestion(
727 &format!("remove the bound{}", pluralize!(negative_bounds_len)),
729 Applicability::MachineApplicable,
735 /// Parses a bound according to the grammar:
737 /// BOUND = TY_BOUND | LT_BOUND
739 fn parse_generic_bound(&mut self) -> PResult<'a, Result<GenericBound, Span>> {
740 let anchor_lo = self.prev_token.span;
741 let lo = self.token.span;
742 let has_parens = self.eat(&token::OpenDelim(Delimiter::Parenthesis));
743 let inner_lo = self.token.span;
744 let is_negative = self.eat(&token::Not);
746 let modifiers = self.parse_ty_bound_modifiers()?;
747 let bound = if self.token.is_lifetime() {
748 self.error_lt_bound_with_modifiers(modifiers);
749 self.parse_generic_lt_bound(lo, inner_lo, has_parens)?
751 self.parse_generic_ty_bound(lo, has_parens, modifiers)?
754 Ok(if is_negative { Err(anchor_lo.to(self.prev_token.span)) } else { Ok(bound) })
757 /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to:
759 /// LT_BOUND = LIFETIME
761 fn parse_generic_lt_bound(
766 ) -> PResult<'a, GenericBound> {
767 let bound = GenericBound::Outlives(self.expect_lifetime());
769 // FIXME(Centril): Consider not erroring here and accepting `('lt)` instead,
770 // possibly introducing `GenericBound::Paren(P<GenericBound>)`?
771 self.recover_paren_lifetime(lo, inner_lo)?;
776 /// Emits an error if any trait bound modifiers were present.
777 fn error_lt_bound_with_modifiers(&self, modifiers: BoundModifiers) {
778 if let Some(span) = modifiers.maybe_const {
779 self.struct_span_err(
781 "`~const` may only modify trait bounds, not lifetime bounds",
786 if let Some(span) = modifiers.maybe {
787 self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds")
792 /// Recover on `('lifetime)` with `(` already eaten.
793 fn recover_paren_lifetime(&mut self, lo: Span, inner_lo: Span) -> PResult<'a, ()> {
794 let inner_span = inner_lo.to(self.prev_token.span);
795 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
796 let mut err = self.struct_span_err(
797 lo.to(self.prev_token.span),
798 "parenthesized lifetime bounds are not supported",
800 if let Ok(snippet) = self.span_to_snippet(inner_span) {
801 err.span_suggestion_short(
802 lo.to(self.prev_token.span),
803 "remove the parentheses",
805 Applicability::MachineApplicable,
812 /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `~const Trait`.
814 /// If no modifiers are present, this does not consume any tokens.
817 /// TY_BOUND_MODIFIERS = ["~const"] ["?"]
819 fn parse_ty_bound_modifiers(&mut self) -> PResult<'a, BoundModifiers> {
820 let maybe_const = if self.eat(&token::Tilde) {
821 let tilde = self.prev_token.span;
822 self.expect_keyword(kw::Const)?;
823 let span = tilde.to(self.prev_token.span);
824 self.sess.gated_spans.gate(sym::const_trait_impl, span);
826 } else if self.eat_keyword(kw::Const) {
827 let span = self.prev_token.span;
828 self.sess.gated_spans.gate(sym::const_trait_impl, span);
830 self.struct_span_err(span, "const bounds must start with `~`")
835 Applicability::MachineApplicable,
844 let maybe = if self.eat(&token::Question) { Some(self.prev_token.span) } else { None };
846 Ok(BoundModifiers { maybe, maybe_const })
849 /// Parses a type bound according to:
851 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
852 /// TY_BOUND_NOPAREN = [TY_BOUND_MODIFIERS] [for<LT_PARAM_DEFS>] SIMPLE_PATH
855 /// For example, this grammar accepts `~const ?for<'a: 'b> m::Trait<'a>`.
856 fn parse_generic_ty_bound(
860 modifiers: BoundModifiers,
861 ) -> PResult<'a, GenericBound> {
862 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
863 let path = self.parse_path(PathStyle::Type)?;
865 if self.token.is_like_plus() {
866 // Someone has written something like `&dyn (Trait + Other)`. The correct code
867 // would be `&(dyn Trait + Other)`, but we don't have access to the appropriate
868 // span to suggest that. When written as `&dyn Trait + Other`, an appropriate
869 // suggestion is given.
871 self.parse_remaining_bounds(bounds, true)?;
872 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
873 let sp = vec![lo, self.prev_token.span];
874 let sugg: Vec<_> = sp.iter().map(|sp| (*sp, String::new())).collect();
875 self.struct_span_err(sp, "incorrect braces around trait bounds")
876 .multipart_suggestion(
877 "remove the parentheses",
879 Applicability::MachineApplicable,
883 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
887 let modifier = modifiers.to_trait_bound_modifier();
888 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_token.span));
889 Ok(GenericBound::Trait(poly_trait, modifier))
892 /// Optionally parses `for<$generic_params>`.
893 pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
894 if self.eat_keyword(kw::For) {
896 let params = self.parse_generic_params()?;
898 // We rely on AST validation to rule out invalid cases: There must not be type
899 // parameters, and the lifetime parameters must not have bounds.
906 pub(super) fn check_lifetime(&mut self) -> bool {
907 self.expected_tokens.push(TokenType::Lifetime);
908 self.token.is_lifetime()
911 /// Parses a single lifetime `'a` or panics.
912 pub(super) fn expect_lifetime(&mut self) -> Lifetime {
913 if let Some(ident) = self.token.lifetime() {
915 Lifetime { ident, id: ast::DUMMY_NODE_ID }
917 self.span_bug(self.token.span, "not a lifetime")
921 pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
922 P(Ty { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })