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