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