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