]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/ty.rs
Rollup merge of #68856 - Centril:or-pat-ref-pat, r=matthewjasper
[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_errors::{pluralize, struct_span_err, Applicability, PResult};
6 use rustc_span::source_map::Span;
7 use rustc_span::symbol::{kw, sym};
8 use syntax::ast::{
9     self, BareFnTy, FunctionRetTy, GenericParam, Ident, Lifetime, MutTy, Ty, TyKind,
10 };
11 use syntax::ast::{
12     GenericBound, GenericBounds, PolyTraitRef, TraitBoundModifier, TraitObjectSyntax,
13 };
14 use syntax::ast::{Mac, Mutability};
15 use syntax::ptr::P;
16 use syntax::token::{self, Token, TokenKind};
17
18 /// Any `?` or `?const` modifiers that appear at the start of a bound.
19 struct BoundModifiers {
20     /// `?Trait`.
21     maybe: Option<Span>,
22
23     /// `?const Trait`.
24     maybe_const: Option<Span>,
25 }
26
27 impl BoundModifiers {
28     fn to_trait_bound_modifier(&self) -> TraitBoundModifier {
29         match (self.maybe, self.maybe_const) {
30             (None, None) => TraitBoundModifier::None,
31             (Some(_), None) => TraitBoundModifier::Maybe,
32             (None, Some(_)) => TraitBoundModifier::MaybeConst,
33             (Some(_), Some(_)) => TraitBoundModifier::MaybeConstMaybe,
34         }
35     }
36 }
37
38 #[derive(Copy, Clone, PartialEq)]
39 pub(super) enum AllowPlus {
40     Yes,
41     No,
42 }
43
44 #[derive(PartialEq)]
45 pub(super) enum RecoverQPath {
46     Yes,
47     No,
48 }
49
50 // Is `...` (`CVarArgs`) legal at this level of type parsing?
51 #[derive(PartialEq)]
52 enum AllowCVariadic {
53     Yes,
54     No,
55 }
56
57 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
58 /// `IDENT<<u8 as Trait>::AssocTy>`.
59 ///
60 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
61 /// that `IDENT` is not the ident of a fn trait.
62 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
63     t == &token::ModSep || t == &token::Lt || t == &token::BinOp(token::Shl)
64 }
65
66 impl<'a> Parser<'a> {
67     /// Parses a type.
68     pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
69         self.parse_ty_common(AllowPlus::Yes, RecoverQPath::Yes, AllowCVariadic::No)
70     }
71
72     /// Parse a type suitable for a function or function pointer parameter.
73     /// The difference from `parse_ty` is that this version allows `...`
74     /// (`CVarArgs`) at the top level of the the type.
75     pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, P<Ty>> {
76         self.parse_ty_common(AllowPlus::Yes, RecoverQPath::Yes, AllowCVariadic::Yes)
77     }
78
79     /// Parses a type in restricted contexts where `+` is not permitted.
80     ///
81     /// Example 1: `&'a TYPE`
82     ///     `+` is prohibited to maintain operator priority (P(+) < P(&)).
83     /// Example 2: `value1 as TYPE + value2`
84     ///     `+` is prohibited to avoid interactions with expression grammar.
85     pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
86         self.parse_ty_common(AllowPlus::No, RecoverQPath::Yes, AllowCVariadic::No)
87     }
88
89     /// Parses an optional return type `[ -> TY ]` in a function declaration.
90     pub(super) fn parse_ret_ty(
91         &mut self,
92         allow_plus: AllowPlus,
93         recover_qpath: RecoverQPath,
94     ) -> PResult<'a, FunctionRetTy> {
95         Ok(if self.eat(&token::RArrow) {
96             // FIXME(Centril): Can we unconditionally `allow_plus`?
97             let ty = self.parse_ty_common(allow_plus, recover_qpath, AllowCVariadic::No)?;
98             FunctionRetTy::Ty(ty)
99         } else {
100             FunctionRetTy::Default(self.token.span.shrink_to_lo())
101         })
102     }
103
104     fn parse_ty_common(
105         &mut self,
106         allow_plus: AllowPlus,
107         recover_qpath: RecoverQPath,
108         allow_c_variadic: AllowCVariadic,
109     ) -> PResult<'a, P<Ty>> {
110         let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes;
111         maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
112         maybe_whole!(self, NtTy, |x| x);
113
114         let lo = self.token.span;
115         let mut impl_dyn_multi = false;
116         let kind = if self.check(&token::OpenDelim(token::Paren)) {
117             self.parse_ty_tuple_or_parens(lo, allow_plus)?
118         } else if self.eat(&token::Not) {
119             // Never type `!`
120             TyKind::Never
121         } else if self.eat(&token::BinOp(token::Star)) {
122             self.parse_ty_ptr()?
123         } else if self.eat(&token::OpenDelim(token::Bracket)) {
124             self.parse_array_or_slice_ty()?
125         } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
126             // Reference
127             self.expect_and()?;
128             self.parse_borrowed_pointee()?
129         } else if self.eat_keyword_noexpect(kw::Typeof) {
130             self.parse_typeof_ty()?
131         } else if self.eat_keyword(kw::Underscore) {
132             // A type to be inferred `_`
133             TyKind::Infer
134         } else if self.token_is_bare_fn_keyword() {
135             // Function pointer type
136             self.parse_ty_bare_fn(Vec::new())?
137         } else if self.check_keyword(kw::For) {
138             // Function pointer type or bound list (trait object type) starting with a poly-trait.
139             //   `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
140             //   `for<'lt> Trait1<'lt> + Trait2 + 'a`
141             let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
142             if self.token_is_bare_fn_keyword() {
143                 self.parse_ty_bare_fn(lifetime_defs)?
144             } else {
145                 let path = self.parse_path(PathStyle::Type)?;
146                 let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
147                 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
148             }
149         } else if self.eat_keyword(kw::Impl) {
150             self.parse_impl_ty(&mut impl_dyn_multi)?
151         } else if self.is_explicit_dyn_type() {
152             self.parse_dyn_ty(&mut impl_dyn_multi)?
153         } else if self.check(&token::Question)
154             || self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus())
155         {
156             // Bound list (trait object type)
157             let bounds = self.parse_generic_bounds_common(allow_plus, None)?;
158             TyKind::TraitObject(bounds, TraitObjectSyntax::None)
159         } else if self.eat_lt() {
160             // Qualified path
161             let (qself, path) = self.parse_qpath(PathStyle::Type)?;
162             TyKind::Path(Some(qself), path)
163         } else if self.token.is_path_start() {
164             self.parse_path_start_ty(lo, allow_plus)?
165         } else if self.eat(&token::DotDotDot) {
166             if allow_c_variadic == AllowCVariadic::Yes {
167                 TyKind::CVarArgs
168             } else {
169                 // FIXME(Centril): Should we just allow `...` syntactically
170                 // anywhere in a type and use semantic restrictions instead?
171                 self.error_illegal_c_varadic_ty(lo);
172                 TyKind::Err
173             }
174         } else {
175             let msg = format!("expected type, found {}", super::token_descr(&self.token));
176             let mut err = self.struct_span_err(self.token.span, &msg);
177             err.span_label(self.token.span, "expected type");
178             self.maybe_annotate_with_ascription(&mut err, true);
179             return Err(err);
180         };
181
182         let span = lo.to(self.prev_span);
183         let ty = self.mk_ty(span, kind);
184
185         // Try to recover from use of `+` with incorrect priority.
186         self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
187         self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
188         self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
189     }
190
191     /// Parses either:
192     /// - `(TYPE)`, a parenthesized type.
193     /// - `(TYPE,)`, a tuple with a single field of type TYPE.
194     fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
195         let mut trailing_plus = false;
196         let (ts, trailing) = self.parse_paren_comma_seq(|p| {
197             let ty = p.parse_ty()?;
198             trailing_plus = p.prev_token.kind == TokenKind::BinOp(token::Plus);
199             Ok(ty)
200         })?;
201
202         if ts.len() == 1 && !trailing {
203             let ty = ts.into_iter().nth(0).unwrap().into_inner();
204             let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
205             match ty.kind {
206                 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
207                 TyKind::Path(None, path) if maybe_bounds => {
208                     self.parse_remaining_bounds(Vec::new(), path, lo, true)
209                 }
210                 TyKind::TraitObject(mut bounds, TraitObjectSyntax::None)
211                     if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
212                 {
213                     let path = match bounds.remove(0) {
214                         GenericBound::Trait(pt, ..) => pt.trait_ref.path,
215                         GenericBound::Outlives(..) => {
216                             return Err(self.struct_span_err(
217                                 ty.span,
218                                 "expected trait bound, not lifetime bound",
219                             ));
220                         }
221                     };
222                     self.parse_remaining_bounds(Vec::new(), path, lo, true)
223                 }
224                 // `(TYPE)`
225                 _ => Ok(TyKind::Paren(P(ty))),
226             }
227         } else {
228             Ok(TyKind::Tup(ts))
229         }
230     }
231
232     fn parse_remaining_bounds(
233         &mut self,
234         generic_params: Vec<GenericParam>,
235         path: ast::Path,
236         lo: Span,
237         parse_plus: bool,
238     ) -> PResult<'a, TyKind> {
239         assert_ne!(self.token, token::Question);
240
241         let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
242         let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
243         if parse_plus {
244             self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
245             bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
246         }
247         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
248     }
249
250     /// Parses a raw pointer type: `*[const | mut] $type`.
251     fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
252         let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
253             let span = self.prev_span;
254             let msg = "expected mut or const in raw pointer type";
255             self.struct_span_err(span, msg)
256                 .span_label(span, msg)
257                 .help("use `*mut T` or `*const T` as appropriate")
258                 .emit();
259             Mutability::Not
260         });
261         let ty = self.parse_ty_no_plus()?;
262         Ok(TyKind::Ptr(MutTy { ty, mutbl }))
263     }
264
265     /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
266     /// The opening `[` bracket is already eaten.
267     fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
268         let elt_ty = self.parse_ty()?;
269         let ty = if self.eat(&token::Semi) {
270             TyKind::Array(elt_ty, self.parse_anon_const_expr()?)
271         } else {
272             TyKind::Slice(elt_ty)
273         };
274         self.expect(&token::CloseDelim(token::Bracket))?;
275         Ok(ty)
276     }
277
278     fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
279         let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
280         let mutbl = self.parse_mutability();
281         let ty = self.parse_ty_no_plus()?;
282         Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }))
283     }
284
285     // Parses the `typeof(EXPR)`.
286     // To avoid ambiguity, the type is surrounded by parenthesis.
287     fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
288         self.expect(&token::OpenDelim(token::Paren))?;
289         let expr = self.parse_anon_const_expr()?;
290         self.expect(&token::CloseDelim(token::Paren))?;
291         Ok(TyKind::Typeof(expr))
292     }
293
294     /// Is the current token one of the keywords that signals a bare function type?
295     fn token_is_bare_fn_keyword(&mut self) -> bool {
296         self.check_keyword(kw::Fn)
297             || self.check_keyword(kw::Unsafe)
298             || self.check_keyword(kw::Extern)
299     }
300
301     /// Parses a function pointer type (`TyKind::BareFn`).
302     /// ```
303     /// [unsafe] [extern "ABI"] fn (S) -> T
304     ///  ^~~~~^          ^~~~^     ^~^    ^
305     ///    |               |        |     |
306     ///    |               |        |   Return type
307     /// Function Style    ABI  Parameter types
308     /// ```
309     fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
310         let unsafety = self.parse_unsafety();
311         let ext = self.parse_extern()?;
312         self.expect_keyword(kw::Fn)?;
313         let decl = self.parse_fn_decl(|_| false, AllowPlus::No)?;
314         Ok(TyKind::BareFn(P(BareFnTy { ext, unsafety, generic_params, decl })))
315     }
316
317     /// Parses an `impl B0 + ... + Bn` type.
318     fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
319         // Always parse bounds greedily for better error recovery.
320         let bounds = self.parse_generic_bounds(None)?;
321         *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
322         Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
323     }
324
325     /// Is a `dyn B0 + ... + Bn` type allowed here?
326     fn is_explicit_dyn_type(&mut self) -> bool {
327         self.check_keyword(kw::Dyn)
328             && (self.token.span.rust_2018()
329                 || self.look_ahead(1, |t| {
330                     t.can_begin_bound() && !can_continue_type_after_non_fn_ident(t)
331                 }))
332     }
333
334     /// Parses a `dyn B0 + ... + Bn` type.
335     ///
336     /// Note that this does *not* parse bare trait objects.
337     fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
338         self.bump(); // `dyn`
339         // Always parse bounds greedily for better error recovery.
340         let bounds = self.parse_generic_bounds(None)?;
341         *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus);
342         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn))
343     }
344
345     /// Parses a type starting with a path.
346     ///
347     /// This can be:
348     /// 1. a type macro, `mac!(...)`,
349     /// 2. a bare trait object, `B0 + ... + Bn`,
350     /// 3. or a path, `path::to::MyType`.
351     fn parse_path_start_ty(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
352         // Simple path
353         let path = self.parse_path(PathStyle::Type)?;
354         if self.eat(&token::Not) {
355             // Macro invocation in type position
356             Ok(TyKind::Mac(Mac {
357                 path,
358                 args: self.parse_mac_args()?,
359                 prior_type_ascription: self.last_type_ascription,
360             }))
361         } else if allow_plus == AllowPlus::Yes && self.check_plus() {
362             // `Trait1 + Trait2 + 'a`
363             self.parse_remaining_bounds(Vec::new(), path, lo, true)
364         } else {
365             // Just a type path.
366             Ok(TyKind::Path(None, path))
367         }
368     }
369
370     fn error_illegal_c_varadic_ty(&self, lo: Span) {
371         struct_span_err!(
372             self.sess.span_diagnostic,
373             lo.to(self.prev_span),
374             E0743,
375             "C-variadic type `...` may not be nested inside another type",
376         )
377         .emit();
378     }
379
380     pub(super) fn parse_generic_bounds(
381         &mut self,
382         colon_span: Option<Span>,
383     ) -> PResult<'a, GenericBounds> {
384         self.parse_generic_bounds_common(AllowPlus::Yes, colon_span)
385     }
386
387     /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
388     ///
389     /// See `parse_generic_bound` for the `BOUND` grammar.
390     fn parse_generic_bounds_common(
391         &mut self,
392         allow_plus: AllowPlus,
393         colon_span: Option<Span>,
394     ) -> PResult<'a, GenericBounds> {
395         let mut bounds = Vec::new();
396         let mut negative_bounds = Vec::new();
397         while self.can_begin_bound() {
398             match self.parse_generic_bound()? {
399                 Ok(bound) => bounds.push(bound),
400                 Err(neg_sp) => negative_bounds.push(neg_sp),
401             }
402             if allow_plus == AllowPlus::No || !self.eat_plus() {
403                 break;
404             }
405         }
406
407         if !negative_bounds.is_empty() {
408             self.error_negative_bounds(colon_span, &bounds, negative_bounds);
409         }
410
411         Ok(bounds)
412     }
413
414     /// Can the current token begin a bound?
415     fn can_begin_bound(&mut self) -> bool {
416         // This needs to be synchronized with `TokenKind::can_begin_bound`.
417         self.check_path()
418         || self.check_lifetime()
419         || self.check(&token::Not) // Used for error reporting only.
420         || self.check(&token::Question)
421         || self.check_keyword(kw::For)
422         || self.check(&token::OpenDelim(token::Paren))
423     }
424
425     fn error_negative_bounds(
426         &self,
427         colon_span: Option<Span>,
428         bounds: &[GenericBound],
429         negative_bounds: Vec<Span>,
430     ) {
431         let negative_bounds_len = negative_bounds.len();
432         let last_span = *negative_bounds.last().expect("no negative bounds, but still error?");
433         let mut err = self.struct_span_err(negative_bounds, "negative bounds are not supported");
434         err.span_label(last_span, "negative bounds are not supported");
435         if let Some(bound_list) = colon_span {
436             let bound_list = bound_list.to(self.prev_span);
437             let mut new_bound_list = String::new();
438             if !bounds.is_empty() {
439                 let mut snippets = bounds.iter().map(|bound| self.span_to_snippet(bound.span()));
440                 while let Some(Ok(snippet)) = snippets.next() {
441                     new_bound_list.push_str(" + ");
442                     new_bound_list.push_str(&snippet);
443                 }
444                 new_bound_list = new_bound_list.replacen(" +", ":", 1);
445             }
446             err.tool_only_span_suggestion(
447                 bound_list,
448                 &format!("remove the bound{}", pluralize!(negative_bounds_len)),
449                 new_bound_list,
450                 Applicability::MachineApplicable,
451             );
452         }
453         err.emit();
454     }
455
456     /// Parses a bound according to the grammar:
457     /// ```
458     /// BOUND = TY_BOUND | LT_BOUND
459     /// ```
460     fn parse_generic_bound(&mut self) -> PResult<'a, Result<GenericBound, Span>> {
461         let anchor_lo = self.prev_span;
462         let lo = self.token.span;
463         let has_parens = self.eat(&token::OpenDelim(token::Paren));
464         let inner_lo = self.token.span;
465         let is_negative = self.eat(&token::Not);
466
467         let modifiers = self.parse_ty_bound_modifiers();
468         let bound = if self.token.is_lifetime() {
469             self.error_lt_bound_with_modifiers(modifiers);
470             self.parse_generic_lt_bound(lo, inner_lo, has_parens)?
471         } else {
472             self.parse_generic_ty_bound(lo, has_parens, modifiers)?
473         };
474
475         Ok(if is_negative { Err(anchor_lo.to(self.prev_span)) } else { Ok(bound) })
476     }
477
478     /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to:
479     /// ```
480     /// LT_BOUND = LIFETIME
481     /// ```
482     fn parse_generic_lt_bound(
483         &mut self,
484         lo: Span,
485         inner_lo: Span,
486         has_parens: bool,
487     ) -> PResult<'a, GenericBound> {
488         let bound = GenericBound::Outlives(self.expect_lifetime());
489         if has_parens {
490             // FIXME(Centril): Consider not erroring here and accepting `('lt)` instead,
491             // possibly introducing `GenericBound::Paren(P<GenericBound>)`?
492             self.recover_paren_lifetime(lo, inner_lo)?;
493         }
494         Ok(bound)
495     }
496
497     /// Emits an error if any trait bound modifiers were present.
498     fn error_lt_bound_with_modifiers(&self, modifiers: BoundModifiers) {
499         if let Some(span) = modifiers.maybe_const {
500             self.struct_span_err(
501                 span,
502                 "`?const` may only modify trait bounds, not lifetime bounds",
503             )
504             .emit();
505         }
506
507         if let Some(span) = modifiers.maybe {
508             self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds")
509                 .emit();
510         }
511     }
512
513     /// Recover on `('lifetime)` with `(` already eaten.
514     fn recover_paren_lifetime(&mut self, lo: Span, inner_lo: Span) -> PResult<'a, ()> {
515         let inner_span = inner_lo.to(self.prev_span);
516         self.expect(&token::CloseDelim(token::Paren))?;
517         let mut err = self.struct_span_err(
518             lo.to(self.prev_span),
519             "parenthesized lifetime bounds are not supported",
520         );
521         if let Ok(snippet) = self.span_to_snippet(inner_span) {
522             err.span_suggestion_short(
523                 lo.to(self.prev_span),
524                 "remove the parentheses",
525                 snippet,
526                 Applicability::MachineApplicable,
527             );
528         }
529         err.emit();
530         Ok(())
531     }
532
533     /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `?const Trait`.
534     ///
535     /// If no modifiers are present, this does not consume any tokens.
536     ///
537     /// ```
538     /// TY_BOUND_MODIFIERS = "?" ["const" ["?"]]
539     /// ```
540     fn parse_ty_bound_modifiers(&mut self) -> BoundModifiers {
541         if !self.eat(&token::Question) {
542             return BoundModifiers { maybe: None, maybe_const: None };
543         }
544
545         // `? ...`
546         let first_question = self.prev_span;
547         if !self.eat_keyword(kw::Const) {
548             return BoundModifiers { maybe: Some(first_question), maybe_const: None };
549         }
550
551         // `?const ...`
552         let maybe_const = first_question.to(self.prev_span);
553         self.sess.gated_spans.gate(sym::const_trait_bound_opt_out, maybe_const);
554         if !self.eat(&token::Question) {
555             return BoundModifiers { maybe: None, maybe_const: Some(maybe_const) };
556         }
557
558         // `?const ? ...`
559         let second_question = self.prev_span;
560         BoundModifiers { maybe: Some(second_question), maybe_const: Some(maybe_const) }
561     }
562
563     /// Parses a type bound according to:
564     /// ```
565     /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
566     /// TY_BOUND_NOPAREN = [TY_BOUND_MODIFIERS] [for<LT_PARAM_DEFS>] SIMPLE_PATH
567     /// ```
568     ///
569     /// For example, this grammar accepts `?const ?for<'a: 'b> m::Trait<'a>`.
570     fn parse_generic_ty_bound(
571         &mut self,
572         lo: Span,
573         has_parens: bool,
574         modifiers: BoundModifiers,
575     ) -> PResult<'a, GenericBound> {
576         let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
577         let path = self.parse_path(PathStyle::Type)?;
578         if has_parens {
579             self.expect(&token::CloseDelim(token::Paren))?;
580         }
581
582         let modifier = modifiers.to_trait_bound_modifier();
583         let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
584         Ok(GenericBound::Trait(poly_trait, modifier))
585     }
586
587     /// Optionally parses `for<$generic_params>`.
588     pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
589         if self.eat_keyword(kw::For) {
590             self.expect_lt()?;
591             let params = self.parse_generic_params()?;
592             self.expect_gt()?;
593             // We rely on AST validation to rule out invalid cases: There must not be type
594             // parameters, and the lifetime parameters must not have bounds.
595             Ok(params)
596         } else {
597             Ok(Vec::new())
598         }
599     }
600
601     pub fn check_lifetime(&mut self) -> bool {
602         self.expected_tokens.push(TokenType::Lifetime);
603         self.token.is_lifetime()
604     }
605
606     /// Parses a single lifetime `'a` or panics.
607     pub fn expect_lifetime(&mut self) -> Lifetime {
608         if let Some(ident) = self.token.lifetime() {
609             let span = self.token.span;
610             self.bump();
611             Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
612         } else {
613             self.span_bug(self.token.span, "not a lifetime")
614         }
615     }
616
617     pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
618         P(Ty { kind, span, id: ast::DUMMY_NODE_ID })
619     }
620 }