]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/ty.rs
Rollup merge of #69568 - JOE1994:patch-2, r=Dylan-DPC
[rust.git] / src / librustc_parse / parser / ty.rs
1 use super::{Parser, PathStyle, TokenType};
2
3 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
4
5 use rustc_ast::ast::{self, BareFnTy, FnRetTy, GenericParam, Lifetime, MutTy, Ty, TyKind};
6 use rustc_ast::ast::{
7     GenericBound, GenericBounds, PolyTraitRef, TraitBoundModifier, TraitObjectSyntax,
8 };
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};
15
16 /// Any `?` or `?const` modifiers that appear at the start of a bound.
17 struct BoundModifiers {
18     /// `?Trait`.
19     maybe: Option<Span>,
20
21     /// `?const Trait`.
22     maybe_const: Option<Span>,
23 }
24
25 impl BoundModifiers {
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,
32         }
33     }
34 }
35
36 #[derive(Copy, Clone, PartialEq)]
37 pub(super) enum AllowPlus {
38     Yes,
39     No,
40 }
41
42 #[derive(PartialEq)]
43 pub(super) enum RecoverQPath {
44     Yes,
45     No,
46 }
47
48 // Is `...` (`CVarArgs`) legal at this level of type parsing?
49 #[derive(PartialEq)]
50 enum AllowCVariadic {
51     Yes,
52     No,
53 }
54
55 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
56 /// `IDENT<<u8 as Trait>::AssocTy>`.
57 ///
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)
62 }
63
64 impl<'a> Parser<'a> {
65     /// Parses a type.
66     pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
67         self.parse_ty_common(AllowPlus::Yes, RecoverQPath::Yes, AllowCVariadic::No)
68     }
69
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)
75     }
76
77     /// Parses a type in restricted contexts where `+` is not permitted.
78     ///
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)
85     }
86
87     /// Parses an optional return type `[ -> TY ]` in a function declaration.
88     pub(super) fn parse_ret_ty(
89         &mut self,
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)?;
96             FnRetTy::Ty(ty)
97         } else {
98             FnRetTy::Default(self.token.span.shrink_to_lo())
99         })
100     }
101
102     fn parse_ty_common(
103         &mut self,
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);
111
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) {
117             // Never type `!`
118             TyKind::Never
119         } else if self.eat(&token::BinOp(token::Star)) {
120             self.parse_ty_ptr()?
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) {
124             // Reference
125             self.expect_and()?;
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 `_`
131             TyKind::Infer
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)?
142             } else {
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)?
146             }
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())
153         {
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() {
158             // Qualified path
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 {
165                 TyKind::CVarArgs
166             } else {
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);
170                 TyKind::Err
171             }
172         } else {
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);
177             return Err(err);
178         };
179
180         let span = lo.to(self.prev_token.span);
181         let ty = self.mk_ty(span, kind);
182
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)
187     }
188
189     /// Parses either:
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);
197             Ok(ty)
198         })?;
199
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();
203             match ty.kind {
204                 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
205                 TyKind::Path(None, path) if maybe_bounds => {
206                     self.parse_remaining_bounds(Vec::new(), path, lo, true)
207                 }
208                 TyKind::TraitObject(mut bounds, TraitObjectSyntax::None)
209                     if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
210                 {
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(
215                                 ty.span,
216                                 "expected trait bound, not lifetime bound",
217                             ));
218                         }
219                     };
220                     self.parse_remaining_bounds(Vec::new(), path, lo, true)
221                 }
222                 // `(TYPE)`
223                 _ => Ok(TyKind::Paren(P(ty))),
224             }
225         } else {
226             Ok(TyKind::Tup(ts))
227         }
228     }
229
230     fn parse_remaining_bounds(
231         &mut self,
232         generic_params: Vec<GenericParam>,
233         path: ast::Path,
234         lo: Span,
235         parse_plus: bool,
236     ) -> PResult<'a, TyKind> {
237         assert_ne!(self.token, token::Question);
238
239         let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_token.span));
240         let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
241         if parse_plus {
242             self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
243             bounds.append(&mut self.parse_generic_bounds(Some(self.prev_token.span))?);
244         }
245         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
246     }
247
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_token.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")
256                 .emit();
257             Mutability::Not
258         });
259         let ty = self.parse_ty_no_plus()?;
260         Ok(TyKind::Ptr(MutTy { ty, mutbl }))
261     }
262
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()?)
269         } else {
270             TyKind::Slice(elt_ty)
271         };
272         self.expect(&token::CloseDelim(token::Bracket))?;
273         Ok(ty)
274     }
275
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 }))
281     }
282
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))
290     }
291
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)
297     }
298
299     /// Parses a function pointer type (`TyKind::BareFn`).
300     /// ```
301     /// [unsafe] [extern "ABI"] fn (S) -> T
302     ///  ^~~~~^          ^~~~^     ^~^    ^
303     ///    |               |        |     |
304     ///    |               |        |   Return type
305     /// Function Style    ABI  Parameter types
306     /// ```
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 })))
313     }
314
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))
321     }
322
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)
329                 }))
330     }
331
332     /// Parses a `dyn B0 + ... + Bn` type.
333     ///
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))
341     }
342
343     /// Parses a type starting with a path.
344     ///
345     /// This can be:
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> {
350         // Simple path
351         let path = self.parse_path(PathStyle::Type)?;
352         if self.eat(&token::Not) {
353             // Macro invocation in type position
354             Ok(TyKind::Mac(Mac {
355                 path,
356                 args: self.parse_mac_args()?,
357                 prior_type_ascription: self.last_type_ascription,
358             }))
359         } else if allow_plus == AllowPlus::Yes && self.check_plus() {
360             // `Trait1 + Trait2 + 'a`
361             self.parse_remaining_bounds(Vec::new(), path, lo, true)
362         } else {
363             // Just a type path.
364             Ok(TyKind::Path(None, path))
365         }
366     }
367
368     fn error_illegal_c_varadic_ty(&self, lo: Span) {
369         struct_span_err!(
370             self.sess.span_diagnostic,
371             lo.to(self.prev_token.span),
372             E0743,
373             "C-variadic type `...` may not be nested inside another type",
374         )
375         .emit();
376     }
377
378     pub(super) fn parse_generic_bounds(
379         &mut self,
380         colon_span: Option<Span>,
381     ) -> PResult<'a, GenericBounds> {
382         self.parse_generic_bounds_common(AllowPlus::Yes, colon_span)
383     }
384
385     /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
386     ///
387     /// See `parse_generic_bound` for the `BOUND` grammar.
388     fn parse_generic_bounds_common(
389         &mut self,
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),
399             }
400             if allow_plus == AllowPlus::No || !self.eat_plus() {
401                 break;
402             }
403         }
404
405         if !negative_bounds.is_empty() {
406             self.error_negative_bounds(colon_span, &bounds, negative_bounds);
407         }
408
409         Ok(bounds)
410     }
411
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`.
415         self.check_path()
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))
421     }
422
423     fn error_negative_bounds(
424         &self,
425         colon_span: Option<Span>,
426         bounds: &[GenericBound],
427         negative_bounds: Vec<Span>,
428     ) {
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_token.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);
441                 }
442                 new_bound_list = new_bound_list.replacen(" +", ":", 1);
443             }
444             err.tool_only_span_suggestion(
445                 bound_list,
446                 &format!("remove the bound{}", pluralize!(negative_bounds_len)),
447                 new_bound_list,
448                 Applicability::MachineApplicable,
449             );
450         }
451         err.emit();
452     }
453
454     /// Parses a bound according to the grammar:
455     /// ```
456     /// BOUND = TY_BOUND | LT_BOUND
457     /// ```
458     fn parse_generic_bound(&mut self) -> PResult<'a, Result<GenericBound, Span>> {
459         let anchor_lo = self.prev_token.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);
464
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)?
469         } else {
470             self.parse_generic_ty_bound(lo, has_parens, modifiers)?
471         };
472
473         Ok(if is_negative { Err(anchor_lo.to(self.prev_token.span)) } else { Ok(bound) })
474     }
475
476     /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to:
477     /// ```
478     /// LT_BOUND = LIFETIME
479     /// ```
480     fn parse_generic_lt_bound(
481         &mut self,
482         lo: Span,
483         inner_lo: Span,
484         has_parens: bool,
485     ) -> PResult<'a, GenericBound> {
486         let bound = GenericBound::Outlives(self.expect_lifetime());
487         if has_parens {
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)?;
491         }
492         Ok(bound)
493     }
494
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(
499                 span,
500                 "`?const` may only modify trait bounds, not lifetime bounds",
501             )
502             .emit();
503         }
504
505         if let Some(span) = modifiers.maybe {
506             self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds")
507                 .emit();
508         }
509     }
510
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_token.span);
514         self.expect(&token::CloseDelim(token::Paren))?;
515         let mut err = self.struct_span_err(
516             lo.to(self.prev_token.span),
517             "parenthesized lifetime bounds are not supported",
518         );
519         if let Ok(snippet) = self.span_to_snippet(inner_span) {
520             err.span_suggestion_short(
521                 lo.to(self.prev_token.span),
522                 "remove the parentheses",
523                 snippet,
524                 Applicability::MachineApplicable,
525             );
526         }
527         err.emit();
528         Ok(())
529     }
530
531     /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `?const Trait`.
532     ///
533     /// If no modifiers are present, this does not consume any tokens.
534     ///
535     /// ```
536     /// TY_BOUND_MODIFIERS = "?" ["const" ["?"]]
537     /// ```
538     fn parse_ty_bound_modifiers(&mut self) -> BoundModifiers {
539         if !self.eat(&token::Question) {
540             return BoundModifiers { maybe: None, maybe_const: None };
541         }
542
543         // `? ...`
544         let first_question = self.prev_token.span;
545         if !self.eat_keyword(kw::Const) {
546             return BoundModifiers { maybe: Some(first_question), maybe_const: None };
547         }
548
549         // `?const ...`
550         let maybe_const = first_question.to(self.prev_token.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) };
554         }
555
556         // `?const ? ...`
557         let second_question = self.prev_token.span;
558         BoundModifiers { maybe: Some(second_question), maybe_const: Some(maybe_const) }
559     }
560
561     /// Parses a type bound according to:
562     /// ```
563     /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
564     /// TY_BOUND_NOPAREN = [TY_BOUND_MODIFIERS] [for<LT_PARAM_DEFS>] SIMPLE_PATH
565     /// ```
566     ///
567     /// For example, this grammar accepts `?const ?for<'a: 'b> m::Trait<'a>`.
568     fn parse_generic_ty_bound(
569         &mut self,
570         lo: Span,
571         has_parens: bool,
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)?;
576         if has_parens {
577             self.expect(&token::CloseDelim(token::Paren))?;
578         }
579
580         let modifier = modifiers.to_trait_bound_modifier();
581         let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_token.span));
582         Ok(GenericBound::Trait(poly_trait, modifier))
583     }
584
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) {
588             self.expect_lt()?;
589             let params = self.parse_generic_params()?;
590             self.expect_gt()?;
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.
593             Ok(params)
594         } else {
595             Ok(Vec::new())
596         }
597     }
598
599     pub fn check_lifetime(&mut self) -> bool {
600         self.expected_tokens.push(TokenType::Lifetime);
601         self.token.is_lifetime()
602     }
603
604     /// Parses a single lifetime `'a` or panics.
605     pub fn expect_lifetime(&mut self) -> Lifetime {
606         if let Some(ident) = self.token.lifetime() {
607             self.bump();
608             Lifetime { ident, id: ast::DUMMY_NODE_ID }
609         } else {
610             self.span_bug(self.token.span, "not a lifetime")
611         }
612     }
613
614     pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
615         P(Ty { kind, span, id: ast::DUMMY_NODE_ID })
616     }
617 }