1 use super::{Parser, PathStyle, TokenType};
3 use crate::errors::{FnPtrWithGenerics, FnPtrWithGenericsSugg};
4 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
7 use rustc_ast::token::{self, Delimiter, Token, TokenKind};
8 use rustc_ast::util::case::Case;
10 self as ast, BareFnTy, FnRetTy, GenericBound, GenericBounds, GenericParam, Generics, Lifetime,
11 MacCall, MutTy, Mutability, PolyTraitRef, TraitBoundModifier, TraitObjectSyntax, Ty, TyKind,
13 use rustc_errors::{pluralize, struct_span_err, Applicability, PResult};
14 use rustc_span::source_map::Span;
15 use rustc_span::symbol::{kw, sym};
17 /// Any `?` or `~const` modifiers that appear at the start of a bound.
18 struct BoundModifiers {
23 maybe_const: Option<Span>,
27 fn to_trait_bound_modifier(&self) -> TraitBoundModifier {
28 match (self.maybe, self.maybe_const) {
29 (None, None) => TraitBoundModifier::None,
30 (Some(_), None) => TraitBoundModifier::Maybe,
31 (None, Some(_)) => TraitBoundModifier::MaybeConst,
32 (Some(_), Some(_)) => TraitBoundModifier::MaybeConstMaybe,
37 #[derive(Copy, Clone, PartialEq)]
38 pub(super) enum AllowPlus {
44 pub(super) enum RecoverQPath {
49 pub(super) enum RecoverQuestionMark {
54 /// Signals whether parsing a type should recover `->`.
56 /// More specifically, when parsing a function like:
58 /// fn foo() => u8 { 0 }
59 /// fn bar(): u8 { 0 }
61 /// The compiler will try to recover interpreting `foo() => u8` as `foo() -> u8` when calling
62 /// `parse_ty` with anything except `RecoverReturnSign::No`, and it will try to recover `bar(): u8`
63 /// as `bar() -> u8` when passing `RecoverReturnSign::Yes` to `parse_ty`
64 #[derive(Copy, Clone, PartialEq)]
65 pub(super) enum RecoverReturnSign {
71 impl RecoverReturnSign {
72 /// [RecoverReturnSign::Yes] allows for recovering `fn foo() => u8` and `fn foo(): u8`,
73 /// [RecoverReturnSign::OnlyFatArrow] allows for recovering only `fn foo() => u8` (recovering
74 /// colons can cause problems when parsing where clauses), and
75 /// [RecoverReturnSign::No] doesn't allow for any recovery of the return type arrow
76 fn can_recover(self, token: &TokenKind) -> bool {
78 Self::Yes => matches!(token, token::FatArrow | token::Colon),
79 Self::OnlyFatArrow => matches!(token, token::FatArrow),
85 // Is `...` (`CVarArgs`) legal at this level of type parsing?
92 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
93 /// `IDENT<<u8 as Trait>::AssocTy>`.
95 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
96 /// that `IDENT` is not the ident of a fn trait.
97 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
98 t == &token::ModSep || t == &token::Lt || t == &token::BinOp(token::Shl)
101 impl<'a> Parser<'a> {
103 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
104 self.parse_ty_common(
108 RecoverReturnSign::Yes,
110 RecoverQuestionMark::Yes,
114 pub(super) fn parse_ty_with_generics_recovery(
116 ty_params: &Generics,
117 ) -> PResult<'a, P<Ty>> {
118 self.parse_ty_common(
122 RecoverReturnSign::Yes,
124 RecoverQuestionMark::Yes,
128 /// Parse a type suitable for a function or function pointer parameter.
129 /// The difference from `parse_ty` is that this version allows `...`
130 /// (`CVarArgs`) at the top level of the type.
131 pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, P<Ty>> {
132 self.parse_ty_common(
136 RecoverReturnSign::Yes,
138 RecoverQuestionMark::Yes,
142 /// Parses a type in restricted contexts where `+` is not permitted.
144 /// Example 1: `&'a TYPE`
145 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
146 /// Example 2: `value1 as TYPE + value2`
147 /// `+` is prohibited to avoid interactions with expression grammar.
148 pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
149 self.parse_ty_common(
153 RecoverReturnSign::Yes,
155 RecoverQuestionMark::Yes,
159 /// Parses a type following an `as` cast. Similar to `parse_ty_no_plus`, but signaling origin
160 /// for better diagnostics involving `?`.
161 pub(super) fn parse_as_cast_ty(&mut self) -> PResult<'a, P<Ty>> {
162 self.parse_ty_common(
166 RecoverReturnSign::Yes,
168 RecoverQuestionMark::No,
172 pub(super) fn parse_no_question_mark_recover(&mut self) -> PResult<'a, P<Ty>> {
173 self.parse_ty_common(
177 RecoverReturnSign::Yes,
179 RecoverQuestionMark::No,
183 /// Parse a type without recovering `:` as `->` to avoid breaking code such as `where fn() : for<'a>`
184 pub(super) fn parse_ty_for_where_clause(&mut self) -> PResult<'a, P<Ty>> {
185 self.parse_ty_common(
189 RecoverReturnSign::OnlyFatArrow,
191 RecoverQuestionMark::Yes,
195 /// Parses an optional return type `[ -> TY ]` in a function declaration.
196 pub(super) fn parse_ret_ty(
198 allow_plus: AllowPlus,
199 recover_qpath: RecoverQPath,
200 recover_return_sign: RecoverReturnSign,
201 ) -> PResult<'a, FnRetTy> {
202 Ok(if self.eat(&token::RArrow) {
203 // FIXME(Centril): Can we unconditionally `allow_plus`?
204 let ty = self.parse_ty_common(
210 RecoverQuestionMark::Yes,
213 } else if recover_return_sign.can_recover(&self.token.kind) {
214 // Don't `eat` to prevent `=>` from being added as an expected token which isn't
215 // actually expected and could only confuse users
217 self.struct_span_err(self.prev_token.span, "return types are denoted using `->`")
218 .span_suggestion_short(
219 self.prev_token.span,
222 Applicability::MachineApplicable,
225 let ty = self.parse_ty_common(
231 RecoverQuestionMark::Yes,
235 FnRetTy::Default(self.token.span.shrink_to_lo())
241 allow_plus: AllowPlus,
242 allow_c_variadic: AllowCVariadic,
243 recover_qpath: RecoverQPath,
244 recover_return_sign: RecoverReturnSign,
245 ty_generics: Option<&Generics>,
246 recover_question_mark: RecoverQuestionMark,
247 ) -> PResult<'a, P<Ty>> {
248 let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes;
249 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
250 maybe_whole!(self, NtTy, |x| x);
252 let lo = self.token.span;
253 let mut impl_dyn_multi = false;
254 let kind = if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
255 self.parse_ty_tuple_or_parens(lo, allow_plus)?
256 } else if self.eat(&token::Not) {
259 } else if self.eat(&token::BinOp(token::Star)) {
261 } else if self.eat(&token::OpenDelim(Delimiter::Bracket)) {
262 self.parse_array_or_slice_ty()?
263 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
266 self.parse_borrowed_pointee()?
267 } else if self.eat_keyword_noexpect(kw::Typeof) {
268 self.parse_typeof_ty()?
269 } else if self.eat_keyword(kw::Underscore) {
270 // A type to be inferred `_`
272 } else if self.check_fn_front_matter(false, Case::Sensitive) {
273 // Function pointer type
274 self.parse_ty_bare_fn(lo, Vec::new(), None, recover_return_sign)?
275 } else if self.check_keyword(kw::For) {
276 // Function pointer type or bound list (trait object type) starting with a poly-trait.
277 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
278 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
279 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
280 if self.check_fn_front_matter(false, Case::Sensitive) {
281 self.parse_ty_bare_fn(
284 Some(self.prev_token.span.shrink_to_lo()),
288 let path = self.parse_path(PathStyle::Type)?;
289 let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
290 self.parse_remaining_bounds_path(lifetime_defs, path, lo, parse_plus)?
292 } else if self.eat_keyword(kw::Impl) {
293 self.parse_impl_ty(&mut impl_dyn_multi)?
294 } else if self.is_explicit_dyn_type() {
295 self.parse_dyn_ty(&mut impl_dyn_multi)?
296 } else if self.eat_lt() {
298 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
299 TyKind::Path(Some(qself), path)
300 } else if self.check_path() {
301 self.parse_path_start_ty(lo, allow_plus, ty_generics)?
302 } else if self.can_begin_bound() {
303 self.parse_bare_trait_object(lo, allow_plus)?
304 } else if self.eat(&token::DotDotDot) {
305 if allow_c_variadic == AllowCVariadic::Yes {
308 // FIXME(Centril): Should we just allow `...` syntactically
309 // anywhere in a type and use semantic restrictions instead?
310 self.error_illegal_c_varadic_ty(lo);
314 let msg = format!("expected type, found {}", super::token_descr(&self.token));
315 let mut err = self.struct_span_err(self.token.span, &msg);
316 err.span_label(self.token.span, "expected type");
317 self.maybe_annotate_with_ascription(&mut err, true);
321 let span = lo.to(self.prev_token.span);
322 let mut ty = self.mk_ty(span, kind);
324 // Try to recover from use of `+` with incorrect priority.
325 if matches!(allow_plus, AllowPlus::Yes) {
326 self.maybe_recover_from_bad_type_plus(&ty)?;
328 self.maybe_report_ambiguous_plus(impl_dyn_multi, &ty);
330 if let RecoverQuestionMark::Yes = recover_question_mark {
331 ty = self.maybe_recover_from_question_mark(ty);
333 if allow_qpath_recovery { self.maybe_recover_from_bad_qpath(ty) } else { Ok(ty) }
337 /// - `(TYPE)`, a parenthesized type.
338 /// - `(TYPE,)`, a tuple with a single field of type TYPE.
339 fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
340 let mut trailing_plus = false;
341 let (ts, trailing) = self.parse_paren_comma_seq(|p| {
342 let ty = p.parse_ty()?;
343 trailing_plus = p.prev_token.kind == TokenKind::BinOp(token::Plus);
347 if ts.len() == 1 && !trailing {
348 let ty = ts.into_iter().next().unwrap().into_inner();
349 let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
351 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
352 TyKind::Path(None, path) if maybe_bounds => {
353 self.parse_remaining_bounds_path(Vec::new(), path, lo, true)
355 TyKind::TraitObject(bounds, TraitObjectSyntax::None)
356 if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
358 self.parse_remaining_bounds(bounds, true)
361 _ => Ok(TyKind::Paren(P(ty))),
368 fn parse_bare_trait_object(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
369 let lt_no_plus = self.check_lifetime() && !self.look_ahead(1, |t| t.is_like_plus());
370 let bounds = self.parse_generic_bounds_common(allow_plus, None)?;
372 self.struct_span_err(lo, "lifetime in trait object type must be followed by `+`")
375 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
378 fn parse_remaining_bounds_path(
380 generic_params: Vec<GenericParam>,
384 ) -> PResult<'a, TyKind> {
385 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_token.span));
386 let bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
387 self.parse_remaining_bounds(bounds, parse_plus)
390 /// Parse the remainder of a bare trait object type given an already parsed list.
391 fn parse_remaining_bounds(
393 mut bounds: GenericBounds,
395 ) -> PResult<'a, TyKind> {
397 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
398 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_token.span))?);
400 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
403 /// Parses a raw pointer type: `*[const | mut] $type`.
404 fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
405 let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
406 let span = self.prev_token.span;
407 self.struct_span_err(span, "expected `mut` or `const` keyword in raw pointer type")
410 "add `mut` or `const` here",
411 ["mut ".to_string(), "const ".to_string()],
412 Applicability::HasPlaceholders,
417 let ty = self.parse_ty_no_plus()?;
418 Ok(TyKind::Ptr(MutTy { ty, mutbl }))
421 /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
422 /// The opening `[` bracket is already eaten.
423 fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
424 let elt_ty = match self.parse_ty() {
427 if self.look_ahead(1, |t| t.kind == token::CloseDelim(Delimiter::Bracket))
428 | self.look_ahead(1, |t| t.kind == token::Semi) =>
430 // Recover from `[LIT; EXPR]` and `[LIT]`
433 self.mk_ty(self.prev_token.span, TyKind::Err)
435 Err(err) => return Err(err),
438 let ty = if self.eat(&token::Semi) {
439 let mut length = self.parse_anon_const_expr()?;
440 if let Err(e) = self.expect(&token::CloseDelim(Delimiter::Bracket)) {
441 // Try to recover from `X<Y, ...>` when `X::<Y, ...>` works
442 self.check_mistyped_turbofish_with_multiple_type_params(e, &mut length.value)?;
443 self.expect(&token::CloseDelim(Delimiter::Bracket))?;
445 TyKind::Array(elt_ty, length)
447 self.expect(&token::CloseDelim(Delimiter::Bracket))?;
448 TyKind::Slice(elt_ty)
454 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
455 let and_span = self.prev_token.span;
456 let mut opt_lifetime =
457 if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
458 let mut mutbl = self.parse_mutability();
459 if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() {
460 // A lifetime is invalid here: it would be part of a bare trait bound, which requires
461 // it to be followed by a plus, but we disallow plus in the pointee type.
462 // So we can handle this case as an error here, and suggest `'a mut`.
463 // If there *is* a plus next though, handling the error later provides better suggestions
464 // (like adding parentheses)
465 if !self.look_ahead(1, |t| t.is_like_plus()) {
466 let lifetime_span = self.token.span;
467 let span = and_span.to(lifetime_span);
469 let mut err = self.struct_span_err(span, "lifetime must precede `mut`");
470 if let Ok(lifetime_src) = self.span_to_snippet(lifetime_span) {
473 "place the lifetime before `mut`",
474 format!("&{} mut", lifetime_src),
475 Applicability::MaybeIncorrect,
480 opt_lifetime = Some(self.expect_lifetime());
482 } else if self.token.is_keyword(kw::Dyn)
483 && mutbl == Mutability::Not
484 && self.look_ahead(1, |t| t.is_keyword(kw::Mut))
486 // We have `&dyn mut ...`, which is invalid and should be `&mut dyn ...`.
487 let span = and_span.to(self.look_ahead(1, |t| t.span));
488 let mut err = self.struct_span_err(span, "`mut` must precede `dyn`");
491 "place `mut` before `dyn`",
493 Applicability::MachineApplicable,
498 mutbl = Mutability::Mut;
499 let (dyn_tok, dyn_tok_sp) = (self.token.clone(), self.token_spacing);
501 self.bump_with((dyn_tok, dyn_tok_sp));
503 let ty = self.parse_ty_no_plus()?;
504 Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }))
507 // Parses the `typeof(EXPR)`.
508 // To avoid ambiguity, the type is surrounded by parentheses.
509 fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
510 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
511 let expr = self.parse_anon_const_expr()?;
512 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
513 Ok(TyKind::Typeof(expr))
516 /// Parses a function pointer type (`TyKind::BareFn`).
517 /// ```ignore (illustrative)
518 /// [unsafe] [extern "ABI"] fn (S) -> T
519 /// // ^~~~~^ ^~~~^ ^~^ ^
521 /// // | | | Return type
522 /// // Function Style ABI Parameter types
524 /// We actually parse `FnHeader FnDecl`, but we error on `const` and `async` qualifiers.
528 mut params: Vec<GenericParam>,
529 param_insertion_point: Option<Span>,
530 recover_return_sign: RecoverReturnSign,
531 ) -> PResult<'a, TyKind> {
532 let inherited_vis = rustc_ast::Visibility {
533 span: rustc_span::DUMMY_SP,
534 kind: rustc_ast::VisibilityKind::Inherited,
537 let span_start = self.token.span;
538 let ast::FnHeader { ext, unsafety, constness, asyncness } =
539 self.parse_fn_front_matter(&inherited_vis)?;
540 if self.may_recover() && self.token.kind == TokenKind::Lt {
541 self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?;
543 let decl = self.parse_fn_decl(|_| false, AllowPlus::No, recover_return_sign)?;
544 let whole_span = lo.to(self.prev_token.span);
545 if let ast::Const::Yes(span) = constness {
546 // If we ever start to allow `const fn()`, then update
547 // feature gating for `#![feature(const_extern_fn)]` to
549 self.error_fn_ptr_bad_qualifier(whole_span, span, "const");
551 if let ast::Async::Yes { span, .. } = asyncness {
552 self.error_fn_ptr_bad_qualifier(whole_span, span, "async");
554 let decl_span = span_start.to(self.token.span);
555 Ok(TyKind::BareFn(P(BareFnTy { ext, unsafety, generic_params: params, decl, decl_span })))
558 /// Recover from function pointer types with a generic parameter list (e.g. `fn<'a>(&'a str)`).
559 fn recover_fn_ptr_with_generics(
562 params: &mut Vec<GenericParam>,
563 param_insertion_point: Option<Span>,
564 ) -> PResult<'a, ()> {
565 let generics = self.parse_generics()?;
566 let arity = generics.params.len();
568 let mut lifetimes: Vec<_> = generics
571 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime))
574 let sugg = if !lifetimes.is_empty() {
576 lifetimes.iter().map(|param| param.ident.as_str()).intersperse(", ").collect();
578 let (left, snippet) = if let Some(span) = param_insertion_point {
579 (span, if params.is_empty() { snippet } else { format!(", {snippet}") })
581 (lo.shrink_to_lo(), format!("for<{snippet}> "))
584 Some(FnPtrWithGenericsSugg {
587 right: generics.span,
589 for_param_list_exists: param_insertion_point.is_some(),
595 self.sess.emit_err(FnPtrWithGenerics { span: generics.span, sugg });
596 params.append(&mut lifetimes);
600 /// Emit an error for the given bad function pointer qualifier.
601 fn error_fn_ptr_bad_qualifier(&self, span: Span, qual_span: Span, qual: &str) {
602 self.struct_span_err(span, &format!("an `fn` pointer type cannot be `{}`", qual))
603 .span_label(qual_span, format!("`{}` because of this", qual))
604 .span_suggestion_short(
606 &format!("remove the `{}` qualifier", qual),
608 Applicability::MaybeIncorrect,
613 /// Parses an `impl B0 + ... + Bn` type.
614 fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
615 // Always parse bounds greedily for better error recovery.
616 let bounds = self.parse_generic_bounds(None)?;
617 *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
618 Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
621 /// Is a `dyn B0 + ... + Bn` type allowed here?
622 fn is_explicit_dyn_type(&mut self) -> bool {
623 self.check_keyword(kw::Dyn)
624 && (!self.token.uninterpolated_span().rust_2015()
625 || self.look_ahead(1, |t| {
626 (t.can_begin_bound() || t.kind == TokenKind::BinOp(token::Star))
627 && !can_continue_type_after_non_fn_ident(t)
631 /// Parses a `dyn B0 + ... + Bn` type.
633 /// Note that this does *not* parse bare trait objects.
634 fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
635 self.bump(); // `dyn`
638 let syntax = if self.eat(&TokenKind::BinOp(token::Star)) {
639 TraitObjectSyntax::DynStar
641 TraitObjectSyntax::Dyn
644 // Always parse bounds greedily for better error recovery.
645 let bounds = self.parse_generic_bounds(None)?;
646 *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
647 Ok(TyKind::TraitObject(bounds, syntax))
650 /// Parses a type starting with a path.
653 /// 1. a type macro, `mac!(...)`,
654 /// 2. a bare trait object, `B0 + ... + Bn`,
655 /// 3. or a path, `path::to::MyType`.
656 fn parse_path_start_ty(
659 allow_plus: AllowPlus,
660 ty_generics: Option<&Generics>,
661 ) -> PResult<'a, TyKind> {
663 let path = self.parse_path_inner(PathStyle::Type, ty_generics)?;
664 if self.eat(&token::Not) {
665 // Macro invocation in type position
666 Ok(TyKind::MacCall(P(MacCall {
668 args: self.parse_mac_args()?,
669 prior_type_ascription: self.last_type_ascription,
671 } else if allow_plus == AllowPlus::Yes && self.check_plus() {
672 // `Trait1 + Trait2 + 'a`
673 self.parse_remaining_bounds_path(Vec::new(), path, lo, true)
676 Ok(TyKind::Path(None, path))
680 fn error_illegal_c_varadic_ty(&self, lo: Span) {
682 self.sess.span_diagnostic,
683 lo.to(self.prev_token.span),
685 "C-variadic type `...` may not be nested inside another type",
690 pub(super) fn parse_generic_bounds(
692 colon_span: Option<Span>,
693 ) -> PResult<'a, GenericBounds> {
694 self.parse_generic_bounds_common(AllowPlus::Yes, colon_span)
697 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
699 /// See `parse_generic_bound` for the `BOUND` grammar.
700 fn parse_generic_bounds_common(
702 allow_plus: AllowPlus,
703 colon_span: Option<Span>,
704 ) -> PResult<'a, GenericBounds> {
705 let mut bounds = Vec::new();
706 let mut negative_bounds = Vec::new();
708 while self.can_begin_bound()
709 // Continue even if we find a keyword.
710 // This is necessary for error recover on, for example, `impl fn()`.
712 // The only keyword that can go after generic bounds is `where`, so stop if it's it.
713 || (self.token.is_reserved_ident() && !self.token.is_keyword(kw::Where))
715 if self.token.is_keyword(kw::Dyn) {
716 // Account for `&dyn Trait + dyn Other`.
717 self.struct_span_err(self.token.span, "invalid `dyn` keyword")
718 .help("`dyn` is only needed at the start of a trait `+`-separated list")
721 "remove this keyword",
723 Applicability::MachineApplicable,
728 match self.parse_generic_bound()? {
729 Ok(bound) => bounds.push(bound),
730 Err(neg_sp) => negative_bounds.push(neg_sp),
732 if allow_plus == AllowPlus::No || !self.eat_plus() {
737 if !negative_bounds.is_empty() {
738 self.error_negative_bounds(colon_span, &bounds, negative_bounds);
744 /// Can the current token begin a bound?
745 fn can_begin_bound(&mut self) -> bool {
746 // This needs to be synchronized with `TokenKind::can_begin_bound`.
748 || self.check_lifetime()
749 || self.check(&token::Not) // Used for error reporting only.
750 || self.check(&token::Question)
751 || self.check(&token::Tilde)
752 || self.check_keyword(kw::For)
753 || self.check(&token::OpenDelim(Delimiter::Parenthesis))
756 fn error_negative_bounds(
758 colon_span: Option<Span>,
759 bounds: &[GenericBound],
760 negative_bounds: Vec<Span>,
762 let negative_bounds_len = negative_bounds.len();
763 let last_span = *negative_bounds.last().expect("no negative bounds, but still error?");
764 let mut err = self.struct_span_err(negative_bounds, "negative bounds are not supported");
765 err.span_label(last_span, "negative bounds are not supported");
766 if let Some(bound_list) = colon_span {
767 let bound_list = bound_list.to(self.prev_token.span);
768 let mut new_bound_list = String::new();
769 if !bounds.is_empty() {
770 let mut snippets = bounds.iter().map(|bound| self.span_to_snippet(bound.span()));
771 while let Some(Ok(snippet)) = snippets.next() {
772 new_bound_list.push_str(" + ");
773 new_bound_list.push_str(&snippet);
775 new_bound_list = new_bound_list.replacen(" +", ":", 1);
777 err.tool_only_span_suggestion(
779 &format!("remove the bound{}", pluralize!(negative_bounds_len)),
781 Applicability::MachineApplicable,
787 /// Parses a bound according to the grammar:
789 /// BOUND = TY_BOUND | LT_BOUND
791 fn parse_generic_bound(&mut self) -> PResult<'a, Result<GenericBound, Span>> {
792 let anchor_lo = self.prev_token.span;
793 let lo = self.token.span;
794 let has_parens = self.eat(&token::OpenDelim(Delimiter::Parenthesis));
795 let inner_lo = self.token.span;
796 let is_negative = self.eat(&token::Not);
798 let modifiers = self.parse_ty_bound_modifiers()?;
799 let bound = if self.token.is_lifetime() {
800 self.error_lt_bound_with_modifiers(modifiers);
801 self.parse_generic_lt_bound(lo, inner_lo, has_parens)?
803 self.parse_generic_ty_bound(lo, has_parens, modifiers)?
806 Ok(if is_negative { Err(anchor_lo.to(self.prev_token.span)) } else { Ok(bound) })
809 /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to:
811 /// LT_BOUND = LIFETIME
813 fn parse_generic_lt_bound(
818 ) -> PResult<'a, GenericBound> {
819 let bound = GenericBound::Outlives(self.expect_lifetime());
821 // FIXME(Centril): Consider not erroring here and accepting `('lt)` instead,
822 // possibly introducing `GenericBound::Paren(P<GenericBound>)`?
823 self.recover_paren_lifetime(lo, inner_lo)?;
828 /// Emits an error if any trait bound modifiers were present.
829 fn error_lt_bound_with_modifiers(&self, modifiers: BoundModifiers) {
830 if let Some(span) = modifiers.maybe_const {
831 self.struct_span_err(
833 "`~const` may only modify trait bounds, not lifetime bounds",
838 if let Some(span) = modifiers.maybe {
839 self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds")
844 /// Recover on `('lifetime)` with `(` already eaten.
845 fn recover_paren_lifetime(&mut self, lo: Span, inner_lo: Span) -> PResult<'a, ()> {
846 let inner_span = inner_lo.to(self.prev_token.span);
847 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
848 let mut err = self.struct_span_err(
849 lo.to(self.prev_token.span),
850 "parenthesized lifetime bounds are not supported",
852 if let Ok(snippet) = self.span_to_snippet(inner_span) {
853 err.span_suggestion_short(
854 lo.to(self.prev_token.span),
855 "remove the parentheses",
857 Applicability::MachineApplicable,
864 /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `~const Trait`.
866 /// If no modifiers are present, this does not consume any tokens.
869 /// TY_BOUND_MODIFIERS = ["~const"] ["?"]
871 fn parse_ty_bound_modifiers(&mut self) -> PResult<'a, BoundModifiers> {
872 let maybe_const = if self.eat(&token::Tilde) {
873 let tilde = self.prev_token.span;
874 self.expect_keyword(kw::Const)?;
875 let span = tilde.to(self.prev_token.span);
876 self.sess.gated_spans.gate(sym::const_trait_impl, span);
878 } else if self.eat_keyword(kw::Const) {
879 let span = self.prev_token.span;
880 self.sess.gated_spans.gate(sym::const_trait_impl, span);
882 self.struct_span_err(span, "const bounds must start with `~`")
887 Applicability::MachineApplicable,
896 let maybe = if self.eat(&token::Question) { Some(self.prev_token.span) } else { None };
898 Ok(BoundModifiers { maybe, maybe_const })
901 /// Parses a type bound according to:
903 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
904 /// TY_BOUND_NOPAREN = [TY_BOUND_MODIFIERS] [for<LT_PARAM_DEFS>] SIMPLE_PATH
907 /// For example, this grammar accepts `~const ?for<'a: 'b> m::Trait<'a>`.
908 fn parse_generic_ty_bound(
912 modifiers: BoundModifiers,
913 ) -> PResult<'a, GenericBound> {
914 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
915 let path = self.parse_path(PathStyle::Type)?;
917 if self.token.is_like_plus() {
918 // Someone has written something like `&dyn (Trait + Other)`. The correct code
919 // would be `&(dyn Trait + Other)`, but we don't have access to the appropriate
920 // span to suggest that. When written as `&dyn Trait + Other`, an appropriate
921 // suggestion is given.
923 self.parse_remaining_bounds(bounds, true)?;
924 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
925 let sp = vec![lo, self.prev_token.span];
926 let sugg: Vec<_> = sp.iter().map(|sp| (*sp, String::new())).collect();
927 self.struct_span_err(sp, "incorrect braces around trait bounds")
928 .multipart_suggestion(
929 "remove the parentheses",
931 Applicability::MachineApplicable,
935 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
939 let modifier = modifiers.to_trait_bound_modifier();
940 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_token.span));
941 Ok(GenericBound::Trait(poly_trait, modifier))
944 /// Optionally parses `for<$generic_params>`.
945 pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
946 if self.eat_keyword(kw::For) {
948 let params = self.parse_generic_params()?;
950 // We rely on AST validation to rule out invalid cases: There must not be type
951 // parameters, and the lifetime parameters must not have bounds.
958 pub(super) fn check_lifetime(&mut self) -> bool {
959 self.expected_tokens.push(TokenType::Lifetime);
960 self.token.is_lifetime()
963 /// Parses a single lifetime `'a` or panics.
964 pub(super) fn expect_lifetime(&mut self) -> Lifetime {
965 if let Some(ident) = self.token.lifetime() {
967 Lifetime { ident, id: ast::DUMMY_NODE_ID }
969 self.span_bug(self.token.span, "not a lifetime")
973 pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
974 P(Ty { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })