1use rustc_ast::token::{self, IdentIsRaw, MetaVarKind, Token, TokenKind};
2use rustc_ast::util::case::Case;
3use rustc_ast::{
4 self as ast, BoundAsyncness, BoundConstness, BoundPolarity, DUMMY_NODE_ID, FnPtrTy, FnRetTy,
5 GenericBound, GenericBounds, GenericParam, Generics, Lifetime, MacCall, MgcaDisambiguation,
6 MutTy, Mutability, Pinnedness, PolyTraitRef, PreciseCapturingArg, TraitBoundModifiers,
7 TraitObjectSyntax, Ty, TyKind, UnsafeBinderTy,
8};
9use rustc_data_structures::stack::ensure_sufficient_stack;
10use rustc_errors::{Applicability, Diag, E0516, PResult};
11use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym};
12use thin_vec::{ThinVec, thin_vec};
13
14use super::{Parser, PathStyle, SeqSep, TokenType, Trailing};
15use crate::errors::{
16 self, AttributeOnEmptyType, AttributeOnType, DynAfterMut, ExpectedFnPathFoundFnKeyword,
17 ExpectedMutOrConstInRawPointerType, FnPtrWithGenerics, FnPtrWithGenericsSugg,
18 HelpUseLatestEdition, InvalidCVariadicType, InvalidDynKeyword, LifetimeAfterMut,
19 NeedPlusAfterTraitObjectLifetime, NestedCVariadicType, ReturnTypesUseThinArrow,
20};
21use crate::parser::item::FrontMatterParsingMode;
22use crate::parser::{FnContext, FnParseMode};
23use crate::{exp, maybe_recover_from_interpolated_ty_qpath};
24
25#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllowPlus { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AllowPlus {
#[inline]
fn clone(&self) -> AllowPlus { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for AllowPlus {
#[inline]
fn eq(&self, other: &AllowPlus) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
31pub(super) enum AllowPlus {
32 Yes,
33 No,
34}
35
36#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for RecoverQPath {
#[inline]
fn eq(&self, other: &RecoverQPath) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
37pub(super) enum RecoverQPath {
38 Yes,
39 No,
40}
41
42pub(super) enum RecoverQuestionMark {
43 Yes,
44 No,
45}
46
47#[derive(#[automatically_derived]
impl ::core::marker::Copy for RecoverReturnSign { }Copy, #[automatically_derived]
impl ::core::clone::Clone for RecoverReturnSign {
#[inline]
fn clone(&self) -> RecoverReturnSign { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for RecoverReturnSign {
#[inline]
fn eq(&self, other: &RecoverReturnSign) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
58pub(super) enum RecoverReturnSign {
59 Yes,
60 OnlyFatArrow,
61 No,
62}
63
64impl RecoverReturnSign {
65 fn can_recover(self, token: &TokenKind) -> bool {
70 match self {
71 Self::Yes => #[allow(non_exhaustive_omitted_patterns)] match token {
token::FatArrow | token::Colon => true,
_ => false,
}matches!(token, token::FatArrow | token::Colon),
72 Self::OnlyFatArrow => #[allow(non_exhaustive_omitted_patterns)] match token {
token::FatArrow => true,
_ => false,
}matches!(token, token::FatArrow),
73 Self::No => false,
74 }
75 }
76}
77
78#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for AllowCVariadic {
#[inline]
fn eq(&self, other: &AllowCVariadic) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
80enum AllowCVariadic {
81 Yes,
82 No,
83}
84
85fn can_begin_dyn_bound_in_edition_2015(t: Token) -> bool {
89 if t.is_path_start() {
90 return t != token::PathSep && t != token::Lt && t != token::Shl;
96 }
97
98 t == token::OpenParen || t == token::Question || t.is_lifetime() || t.is_keyword(kw::For)
103}
104
105impl<'a> Parser<'a> {
106 pub fn parse_ty(&mut self) -> PResult<'a, Box<Ty>> {
108 if self.token == token::DotDotDot {
109 let span = self.token.span;
113 self.bump();
114 let kind = TyKind::Err(self.dcx().emit_err(InvalidCVariadicType { span }));
115 return Ok(self.mk_ty(span, kind));
116 }
117 ensure_sufficient_stack(|| {
119 self.parse_ty_common(
120 AllowPlus::Yes,
121 AllowCVariadic::No,
122 RecoverQPath::Yes,
123 RecoverReturnSign::Yes,
124 None,
125 RecoverQuestionMark::Yes,
126 )
127 })
128 }
129
130 pub(super) fn parse_ty_with_generics_recovery(
131 &mut self,
132 ty_params: &Generics,
133 ) -> PResult<'a, Box<Ty>> {
134 self.parse_ty_common(
135 AllowPlus::Yes,
136 AllowCVariadic::No,
137 RecoverQPath::Yes,
138 RecoverReturnSign::Yes,
139 Some(ty_params),
140 RecoverQuestionMark::Yes,
141 )
142 }
143
144 pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, Box<Ty>> {
148 let ty = self.parse_ty_common(
149 AllowPlus::Yes,
150 AllowCVariadic::Yes,
151 RecoverQPath::Yes,
152 RecoverReturnSign::Yes,
153 None,
154 RecoverQuestionMark::Yes,
155 )?;
156
157 if self.may_recover()
159 && self.check_noexpect(&token::Eq)
160 && self.look_ahead(1, |tok| tok.can_begin_expr())
161 {
162 let snapshot = self.create_snapshot_for_diagnostic();
163 self.bump();
164 let eq_span = self.prev_token.span;
165 match self.parse_expr() {
166 Ok(e) => {
167 self.dcx()
168 .struct_span_err(eq_span.to(e.span), "parameter defaults are not supported")
169 .emit();
170 }
171 Err(diag) => {
172 diag.cancel();
173 self.restore_snapshot(snapshot);
174 }
175 }
176 }
177
178 Ok(ty)
179 }
180
181 pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, Box<Ty>> {
188 self.parse_ty_common(
189 AllowPlus::No,
190 AllowCVariadic::No,
191 RecoverQPath::Yes,
192 RecoverReturnSign::Yes,
193 None,
194 RecoverQuestionMark::Yes,
195 )
196 }
197
198 pub(super) fn parse_as_cast_ty(&mut self) -> PResult<'a, Box<Ty>> {
201 self.parse_ty_common(
202 AllowPlus::No,
203 AllowCVariadic::No,
204 RecoverQPath::Yes,
205 RecoverReturnSign::Yes,
206 None,
207 RecoverQuestionMark::No,
208 )
209 }
210
211 pub(super) fn parse_ty_no_question_mark_recover(&mut self) -> PResult<'a, Box<Ty>> {
212 self.parse_ty_common(
213 AllowPlus::Yes,
214 AllowCVariadic::No,
215 RecoverQPath::Yes,
216 RecoverReturnSign::Yes,
217 None,
218 RecoverQuestionMark::No,
219 )
220 }
221
222 pub(super) fn parse_ty_for_where_clause(&mut self) -> PResult<'a, Box<Ty>> {
225 self.parse_ty_common(
226 AllowPlus::Yes,
227 AllowCVariadic::No,
228 RecoverQPath::Yes,
229 RecoverReturnSign::OnlyFatArrow,
230 None,
231 RecoverQuestionMark::Yes,
232 )
233 }
234
235 pub(super) fn parse_ret_ty(
237 &mut self,
238 allow_plus: AllowPlus,
239 recover_qpath: RecoverQPath,
240 recover_return_sign: RecoverReturnSign,
241 ) -> PResult<'a, FnRetTy> {
242 let lo = self.prev_token.span;
243 Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::RArrow,
token_type: crate::parser::token_type::TokenType::RArrow,
}exp!(RArrow)) {
244 let ty = self.parse_ty_common(
246 allow_plus,
247 AllowCVariadic::No,
248 recover_qpath,
249 recover_return_sign,
250 None,
251 RecoverQuestionMark::Yes,
252 )?;
253 FnRetTy::Ty(ty)
254 } else if recover_return_sign.can_recover(&self.token.kind) {
255 self.bump();
258 self.dcx().emit_err(ReturnTypesUseThinArrow {
259 span: self.prev_token.span,
260 suggestion: lo.between(self.token.span),
261 });
262 let ty = self.parse_ty_common(
263 allow_plus,
264 AllowCVariadic::No,
265 recover_qpath,
266 recover_return_sign,
267 None,
268 RecoverQuestionMark::Yes,
269 )?;
270 FnRetTy::Ty(ty)
271 } else {
272 FnRetTy::Default(self.prev_token.span.shrink_to_hi())
273 })
274 }
275
276 fn parse_ty_common(
277 &mut self,
278 allow_plus: AllowPlus,
279 allow_c_variadic: AllowCVariadic,
280 recover_qpath: RecoverQPath,
281 recover_return_sign: RecoverReturnSign,
282 ty_generics: Option<&Generics>,
283 recover_question_mark: RecoverQuestionMark,
284 ) -> PResult<'a, Box<Ty>> {
285 let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes;
286 if allow_qpath_recovery && self.may_recover() &&
let Some(mv_kind) = self.token.is_metavar_seq() &&
let token::MetaVarKind::Ty { .. } = mv_kind &&
self.check_noexpect_past_close_delim(&token::PathSep) {
let ty =
self.eat_metavar_seq(mv_kind,
|this|
this.parse_ty_no_question_mark_recover()).expect("metavar seq ty");
return self.maybe_recover_from_bad_qpath_stage_2(self.prev_token.span,
ty);
};maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
287 if self.token == token::Pound && self.look_ahead(1, |t| *t == token::OpenBracket) {
288 let attrs_wrapper = self.parse_outer_attributes()?;
289 let raw_attrs = attrs_wrapper.take_for_recovery(self.psess);
290 let attr_span = raw_attrs[0].span.to(raw_attrs.last().unwrap().span);
291 let (full_span, guar) = match self.parse_ty() {
292 Ok(ty) => {
293 let full_span = attr_span.until(ty.span);
294 let guar = self
295 .dcx()
296 .emit_err(AttributeOnType { span: attr_span, fix_span: full_span });
297 (attr_span, guar)
298 }
299 Err(err) => {
300 err.cancel();
301 let guar = self.dcx().emit_err(AttributeOnEmptyType { span: attr_span });
302 (attr_span, guar)
303 }
304 };
305
306 return Ok(self.mk_ty(full_span, TyKind::Err(guar)));
307 }
308 if let Some(ty) = self.eat_metavar_seq_with_matcher(
309 |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
MetaVarKind::Ty { .. } => true,
_ => false,
}matches!(mv_kind, MetaVarKind::Ty { .. }),
310 |this| this.parse_ty_no_question_mark_recover(),
311 ) {
312 return Ok(ty);
313 }
314
315 let lo = self.token.span;
316 let mut impl_dyn_multi = false;
317 let kind = if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
318 self.parse_ty_tuple_or_parens(lo, allow_plus)?
319 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
320 TyKind::Never
322 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Star,
token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star)) {
323 self.parse_ty_ptr()?
324 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBracket,
token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket)) {
325 self.parse_array_or_slice_ty()?
326 } else if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::And,
token_type: crate::parser::token_type::TokenType::And,
}exp!(And)) || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::AndAnd,
token_type: crate::parser::token_type::TokenType::AndAnd,
}exp!(AndAnd)) {
327 self.expect_and()?;
329 self.parse_borrowed_pointee()?
330 } else if self.eat_keyword_noexpect(kw::Typeof) {
331 self.parse_typeof_ty(lo)?
332 } else if self.is_builtin() {
333 self.parse_builtin_ty()?
334 } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Underscore,
token_type: crate::parser::token_type::TokenType::KwUnderscore,
}exp!(Underscore)) {
335 TyKind::Infer
337 } else if self.check_fn_front_matter(false, Case::Sensitive) {
338 self.parse_ty_fn_ptr(lo, ThinVec::new(), None, recover_return_sign)?
340 } else if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::For,
token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For)) {
341 let (bound_vars, _) = self.parse_higher_ranked_binder()?;
345 if self.check_fn_front_matter(false, Case::Sensitive) {
346 self.parse_ty_fn_ptr(
347 lo,
348 bound_vars,
349 Some(self.prev_token.span.shrink_to_lo()),
350 recover_return_sign,
351 )?
352 } else {
353 if self.may_recover()
355 && (self.eat_keyword_noexpect(kw::Impl) || self.eat_keyword_noexpect(kw::Dyn))
356 {
357 let kw = self.prev_token.ident().unwrap().0;
358 let removal_span = kw.span.with_hi(self.token.span.lo());
359 let path = self.parse_path(PathStyle::Type)?;
360 let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
361 let kind = self.parse_remaining_bounds_path(
362 bound_vars,
363 path,
364 lo,
365 parse_plus,
366 ast::Parens::No,
367 )?;
368 let err = self.dcx().create_err(errors::TransposeDynOrImpl {
369 span: kw.span,
370 kw: kw.name.as_str(),
371 sugg: errors::TransposeDynOrImplSugg {
372 removal_span,
373 insertion_span: lo.shrink_to_lo(),
374 kw: kw.name.as_str(),
375 },
376 });
377
378 let kind = match (kind, kw.name) {
381 (TyKind::TraitObject(bounds, _), kw::Dyn) => {
382 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
383 }
384 (TyKind::TraitObject(bounds, _), kw::Impl) => {
385 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
386 }
387 _ => return Err(err),
388 };
389 err.emit();
390 kind
391 } else {
392 let path = self.parse_path(PathStyle::Type)?;
393 let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
394 self.parse_remaining_bounds_path(
395 bound_vars,
396 path,
397 lo,
398 parse_plus,
399 ast::Parens::No,
400 )?
401 }
402 }
403 } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Impl,
token_type: crate::parser::token_type::TokenType::KwImpl,
}exp!(Impl)) {
404 self.parse_impl_ty(&mut impl_dyn_multi)?
405 } else if self.is_explicit_dyn_type() {
406 self.parse_dyn_ty(&mut impl_dyn_multi)?
407 } else if self.eat_lt() {
408 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
410 TyKind::Path(Some(qself), path)
411 } else if (self.token.is_keyword(kw::Const) || self.token.is_keyword(kw::Mut))
412 && self.look_ahead(1, |t| *t == token::Star)
413 {
414 self.parse_ty_c_style_pointer()?
415 } else if self.check_path() {
416 self.parse_path_start_ty(lo, allow_plus, ty_generics)?
417 } else if self.can_begin_bound() {
418 self.parse_bare_trait_object(lo, allow_plus)?
419 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::DotDotDot,
token_type: crate::parser::token_type::TokenType::DotDotDot,
}exp!(DotDotDot)) {
420 match allow_c_variadic {
421 AllowCVariadic::Yes => TyKind::CVarArgs,
422 AllowCVariadic::No => {
423 let guar = self.dcx().emit_err(NestedCVariadicType { span: lo });
427 TyKind::Err(guar)
428 }
429 }
430 } else if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Unsafe,
token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe))
431 && self.look_ahead(1, |tok| tok.kind == token::Lt)
432 {
433 self.parse_unsafe_binder_ty()?
434 } else {
435 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected type, found {0}",
super::token_descr(&self.token)))
})format!("expected type, found {}", super::token_descr(&self.token));
436 let mut err = self.dcx().struct_span_err(lo, msg);
437 err.span_label(lo, "expected type");
438 return Err(err);
439 };
440
441 let span = lo.to(self.prev_token.span);
442 let mut ty = self.mk_ty(span, kind);
443
444 match allow_plus {
446 AllowPlus::Yes => self.maybe_recover_from_bad_type_plus(&ty)?,
447 AllowPlus::No => self.maybe_report_ambiguous_plus(impl_dyn_multi, &ty),
448 }
449 if let RecoverQuestionMark::Yes = recover_question_mark {
450 ty = self.maybe_recover_from_question_mark(ty);
451 }
452 if allow_qpath_recovery { self.maybe_recover_from_bad_qpath(ty) } else { Ok(ty) }
453 }
454
455 fn parse_unsafe_binder_ty(&mut self) -> PResult<'a, TyKind> {
456 let lo = self.token.span;
457 if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Unsafe,
token_type: crate::parser::token_type::TokenType::KwUnsafe,
}) {
::core::panicking::panic("assertion failed: self.eat_keyword(exp!(Unsafe))")
};assert!(self.eat_keyword(exp!(Unsafe)));
458 self.expect_lt()?;
459 let generic_params = self.parse_generic_params()?;
460 self.expect_gt()?;
461 let inner_ty = self.parse_ty()?;
462 let span = lo.to(self.prev_token.span);
463 self.psess.gated_spans.gate(sym::unsafe_binders, span);
464
465 Ok(TyKind::UnsafeBinder(Box::new(UnsafeBinderTy { generic_params, inner_ty })))
466 }
467
468 fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
472 let mut trailing_plus = false;
473 let (ts, trailing) = self.parse_paren_comma_seq(|p| {
474 let ty = p.parse_ty()?;
475 trailing_plus = p.prev_token == TokenKind::Plus;
476 Ok(ty)
477 })?;
478
479 if ts.len() == 1 && #[allow(non_exhaustive_omitted_patterns)] match trailing {
Trailing::No => true,
_ => false,
}matches!(trailing, Trailing::No) {
480 let ty = ts.into_iter().next().unwrap();
481 let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
482 match ty.kind {
483 TyKind::Path(None, path) if maybe_bounds => self.parse_remaining_bounds_path(
485 ThinVec::new(),
486 path,
487 lo,
488 true,
489 ast::Parens::Yes,
490 ),
491 TyKind::TraitObject(bounds, TraitObjectSyntax::None)
495 if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
496 {
497 self.parse_remaining_bounds(bounds, true)
498 }
499 _ => Ok(TyKind::Paren(ty)),
501 }
502 } else {
503 Ok(TyKind::Tup(ts))
504 }
505 }
506
507 fn parse_bare_trait_object(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
508 if self.token.is_lifetime() && !self.look_ahead(1, |t| t.is_like_plus()) {
510 if self.psess.edition.at_least_rust_2021() {
514 let lt = self.expect_lifetime();
515 let mut err = self.dcx().struct_span_err(lo, "expected type, found lifetime");
516 err.span_label(lo, "expected type");
517 return Ok(match self.maybe_recover_ref_ty_no_leading_ampersand(lt, lo, err) {
518 Ok(ref_ty) => ref_ty,
519 Err(err) => TyKind::Err(err.emit()),
520 });
521 }
522
523 self.dcx().emit_err(NeedPlusAfterTraitObjectLifetime {
524 span: lo,
525 suggestion: lo.shrink_to_hi(),
526 });
527 }
528 Ok(TyKind::TraitObject(
529 self.parse_generic_bounds_common(allow_plus)?,
530 TraitObjectSyntax::None,
531 ))
532 }
533
534 fn maybe_recover_ref_ty_no_leading_ampersand<'cx>(
535 &mut self,
536 lt: Lifetime,
537 lo: Span,
538 mut err: Diag<'cx>,
539 ) -> Result<TyKind, Diag<'cx>> {
540 if !self.may_recover() {
541 return Err(err);
542 }
543 let snapshot = self.create_snapshot_for_diagnostic();
544 let mutbl = self.parse_mutability();
545 match self.parse_ty_no_plus() {
546 Ok(ty) => {
547 err.span_suggestion_verbose(
548 lo.shrink_to_lo(),
549 "you might have meant to write a reference type here",
550 "&",
551 Applicability::MaybeIncorrect,
552 );
553 err.emit();
554 Ok(TyKind::Ref(Some(lt), MutTy { ty, mutbl }))
555 }
556 Err(diag) => {
557 diag.cancel();
558 self.restore_snapshot(snapshot);
559 Err(err)
560 }
561 }
562 }
563
564 fn parse_remaining_bounds_path(
565 &mut self,
566 generic_params: ThinVec<GenericParam>,
567 path: ast::Path,
568 lo: Span,
569 parse_plus: bool,
570 parens: ast::Parens,
571 ) -> PResult<'a, TyKind> {
572 let poly_trait_ref = PolyTraitRef::new(
573 generic_params,
574 path,
575 TraitBoundModifiers::NONE,
576 lo.to(self.prev_token.span),
577 parens,
578 );
579 let bounds = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[GenericBound::Trait(poly_trait_ref)]))vec![GenericBound::Trait(poly_trait_ref)];
580 self.parse_remaining_bounds(bounds, parse_plus)
581 }
582
583 fn parse_remaining_bounds(
585 &mut self,
586 mut bounds: GenericBounds,
587 plus: bool,
588 ) -> PResult<'a, TyKind> {
589 if plus {
590 self.eat_plus(); bounds.append(&mut self.parse_generic_bounds()?);
592 }
593 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
594 }
595
596 fn parse_ty_c_style_pointer(&mut self) -> PResult<'a, TyKind> {
598 let kw_span = self.token.span;
599 let mutbl = self.parse_const_or_mut();
600
601 if let Some(mutbl) = mutbl
602 && self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Star,
token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star))
603 {
604 let star_span = self.prev_token.span;
605
606 let mutability = match mutbl {
607 Mutability::Not => "const",
608 Mutability::Mut => "mut",
609 };
610
611 let ty = self.parse_ty_no_question_mark_recover()?;
612
613 self.dcx()
614 .struct_span_err(
615 kw_span,
616 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("raw pointer types must be written as `*{0} T`",
mutability))
})format!("raw pointer types must be written as `*{mutability} T`"),
617 )
618 .with_multipart_suggestion(
619 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("put the `*` before `{0}`",
mutability))
})format!("put the `*` before `{mutability}`"),
620 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(star_span, String::new()),
(kw_span.shrink_to_lo(), "*".to_string())]))vec![(star_span, String::new()), (kw_span.shrink_to_lo(), "*".to_string())],
621 Applicability::MachineApplicable,
622 )
623 .emit();
624
625 return Ok(TyKind::Ptr(MutTy { ty, mutbl }));
626 }
627 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("this could never happen")));
}unreachable!("this could never happen")
629 }
630
631 fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
633 let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
634 let span = self.prev_token.span;
635 self.dcx().emit_err(ExpectedMutOrConstInRawPointerType {
636 span,
637 after_asterisk: span.shrink_to_hi(),
638 });
639 Mutability::Not
640 });
641 let ty = self.parse_ty_no_plus()?;
642 Ok(TyKind::Ptr(MutTy { ty, mutbl }))
643 }
644
645 fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
648 let elt_ty = match self.parse_ty() {
649 Ok(ty) => ty,
650 Err(err)
651 if self.look_ahead(1, |t| *t == token::CloseBracket)
652 | self.look_ahead(1, |t| *t == token::Semi) =>
653 {
654 self.bump();
656 let guar = err.emit();
657 self.mk_ty(self.prev_token.span, TyKind::Err(guar))
658 }
659 Err(err) => return Err(err),
660 };
661
662 let ty = if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
663 let mut length = self.parse_expr_anon_const(|_, _| MgcaDisambiguation::Direct)?;
664
665 if let Err(e) = self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBracket,
token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket)) {
666 self.check_mistyped_turbofish_with_multiple_type_params(e, &mut length.value)?;
668 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBracket,
token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket))?;
669 }
670 TyKind::Array(elt_ty, length)
671 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBracket,
token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket)) {
672 TyKind::Slice(elt_ty)
673 } else {
674 self.maybe_recover_array_ty_without_semi(elt_ty)?
675 };
676
677 Ok(ty)
678 }
679
680 fn maybe_recover_array_ty_without_semi(&mut self, elt_ty: Box<Ty>) -> PResult<'a, TyKind> {
687 let span = self.token.span;
688 let token_descr = super::token_descr(&self.token);
689 let mut err =
690 self.dcx().struct_span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `;` or `]`, found {0}",
token_descr))
})format!("expected `;` or `]`, found {}", token_descr));
691 err.span_label(span, "expected `;` or `]`");
692
693 if !self.may_recover() {
695 return Err(err);
696 }
697
698 let snapshot = self.create_snapshot_for_diagnostic();
699
700 let hi = self.prev_token.span.hi();
702 _ = self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) || self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)) || self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Star,
token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star));
703 let suggestion_span = self.prev_token.span.with_lo(hi);
704
705 let length = match self.parse_expr_anon_const(|_, _| MgcaDisambiguation::Direct) {
708 Ok(length) => length,
709 Err(e) => {
710 e.cancel();
711 self.restore_snapshot(snapshot);
712 return Err(err);
713 }
714 };
715
716 if let Err(e) = self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBracket,
token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket)) {
717 e.cancel();
718 self.restore_snapshot(snapshot);
719 return Err(err);
720 }
721
722 err.span_suggestion_verbose(
723 suggestion_span,
724 "you might have meant to use `;` as the separator",
725 ";",
726 Applicability::MaybeIncorrect,
727 );
728 err.emit();
729 Ok(TyKind::Array(elt_ty, length))
730 }
731
732 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
733 let and_span = self.prev_token.span;
734 let mut opt_lifetime = self.check_lifetime().then(|| self.expect_lifetime());
735 let (pinned, mut mutbl) = self.parse_pin_and_mut();
736 if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() {
737 if !self.look_ahead(1, |t| t.is_like_plus()) {
743 let lifetime_span = self.token.span;
744 let span = and_span.to(lifetime_span);
745
746 let (suggest_lifetime, snippet) =
747 if let Ok(lifetime_src) = self.span_to_snippet(lifetime_span) {
748 (Some(span), lifetime_src)
749 } else {
750 (None, String::new())
751 };
752 self.dcx().emit_err(LifetimeAfterMut { span, suggest_lifetime, snippet });
753
754 opt_lifetime = Some(self.expect_lifetime());
755 }
756 } else if self.token.is_keyword(kw::Dyn)
757 && mutbl == Mutability::Not
758 && self.look_ahead(1, |t| t.is_keyword(kw::Mut))
759 {
760 let span = and_span.to(self.look_ahead(1, |t| t.span));
762 self.dcx().emit_err(DynAfterMut { span });
763
764 mutbl = Mutability::Mut;
766 let (dyn_tok, dyn_tok_sp) = (self.token, self.token_spacing);
767 self.bump();
768 self.bump_with((dyn_tok, dyn_tok_sp));
769 }
770 let ty = self.parse_ty_no_plus()?;
771 Ok(match pinned {
772 Pinnedness::Not => TyKind::Ref(opt_lifetime, MutTy { ty, mutbl }),
773 Pinnedness::Pinned => TyKind::PinnedRef(opt_lifetime, MutTy { ty, mutbl }),
774 })
775 }
776
777 pub(crate) fn parse_pin_and_mut(&mut self) -> (Pinnedness, Mutability) {
781 if self.token.is_ident_named(sym::pin) && self.look_ahead(1, Token::is_mutability) {
782 self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
783 if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::sym::pin,
token_type: crate::parser::token_type::TokenType::SymPin,
}) {
::core::panicking::panic("assertion failed: self.eat_keyword(exp!(Pin))")
};assert!(self.eat_keyword(exp!(Pin)));
784 let mutbl = self.parse_const_or_mut().unwrap();
785 (Pinnedness::Pinned, mutbl)
786 } else {
787 (Pinnedness::Not, self.parse_mutability())
788 }
789 }
790
791 fn parse_typeof_ty(&mut self, lo: Span) -> PResult<'a, TyKind> {
794 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
795 let _expr = self.parse_expr_anon_const(|_, _| MgcaDisambiguation::AnonConst)?;
796 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
797 let span = lo.to(self.prev_token.span);
798 let guar = self
799 .dcx()
800 .struct_span_err(span, "`typeof` is a reserved keyword but unimplemented")
801 .with_note("consider replacing `typeof(...)` with an actual type")
802 .with_code(E0516)
803 .emit();
804 Ok(TyKind::Err(guar))
805 }
806
807 fn parse_builtin_ty(&mut self) -> PResult<'a, TyKind> {
808 self.parse_builtin(|this, lo, ident| {
809 Ok(match ident.name {
810 sym::field_of => Some(this.parse_ty_field_of(lo)?),
811 _ => None,
812 })
813 })
814 }
815
816 pub(crate) fn parse_ty_field_of(&mut self, _lo: Span) -> PResult<'a, TyKind> {
817 let container = self.parse_ty()?;
818 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
819
820 let fields = self.parse_floating_field_access()?;
821 let trailing_comma = self.eat_noexpect(&TokenKind::Comma);
822
823 if let Err(mut e) = self.expect_one_of(&[], &[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]) {
824 if trailing_comma {
825 e.note("unexpected third argument to field_of");
826 } else {
827 e.note("field_of expects dot-separated field and variant names");
828 }
829 e.emit();
830 }
831
832 if self.may_recover() {
834 while !self.token.kind.is_close_delim_or_eof() {
835 self.bump();
836 }
837 }
838
839 match *fields {
840 [] => Err(self.dcx().struct_span_err(
841 self.token.span,
842 "`field_of!` expects dot-separated field and variant names",
843 )),
844 [field] => Ok(TyKind::FieldOf(container, None, field)),
845 [variant, field] => Ok(TyKind::FieldOf(container, Some(variant), field)),
846 _ => Err(self.dcx().struct_span_err(
847 fields.iter().map(|f| f.span).collect::<Vec<_>>(),
848 "`field_of!` only supports a single field or a variant with a field",
849 )),
850 }
851 }
852
853 fn parse_ty_fn_ptr(
863 &mut self,
864 lo: Span,
865 mut params: ThinVec<GenericParam>,
866 param_insertion_point: Option<Span>,
867 recover_return_sign: RecoverReturnSign,
868 ) -> PResult<'a, TyKind> {
869 let inherited_vis = rustc_ast::Visibility {
870 span: rustc_span::DUMMY_SP,
871 kind: rustc_ast::VisibilityKind::Inherited,
872 tokens: None,
873 };
874 let span_start = self.token.span;
875 let ast::FnHeader { ext, safety, .. } = self.parse_fn_front_matter(
876 &inherited_vis,
877 Case::Sensitive,
878 FrontMatterParsingMode::FunctionPtrType,
879 )?;
880 if self.may_recover() && self.token == TokenKind::Lt {
881 self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?;
882 }
883 let mode = crate::parser::item::FnParseMode {
884 req_name: |_, _| false,
885 context: FnContext::Free,
886 req_body: false,
887 };
888 let decl = self.parse_fn_decl(&mode, AllowPlus::No, recover_return_sign)?;
889
890 let decl_span = span_start.to(self.prev_token.span);
891 Ok(TyKind::FnPtr(Box::new(FnPtrTy {
892 ext,
893 safety,
894 generic_params: params,
895 decl,
896 decl_span,
897 })))
898 }
899
900 fn recover_fn_ptr_with_generics(
902 &mut self,
903 lo: Span,
904 params: &mut ThinVec<GenericParam>,
905 param_insertion_point: Option<Span>,
906 ) -> PResult<'a, ()> {
907 let generics = self.parse_generics()?;
908 let arity = generics.params.len();
909
910 let mut lifetimes: ThinVec<_> = generics
911 .params
912 .into_iter()
913 .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
ast::GenericParamKind::Lifetime => true,
_ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime))
914 .collect();
915
916 let sugg = if !lifetimes.is_empty() {
917 let snippet =
918 lifetimes.iter().map(|param| param.ident.as_str()).intersperse(", ").collect();
919
920 let (left, snippet) = if let Some(span) = param_insertion_point {
921 (span, if params.is_empty() { snippet } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", snippet))
})format!(", {snippet}") })
922 } else {
923 (lo.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("for<{0}> ", snippet))
})format!("for<{snippet}> "))
924 };
925
926 Some(FnPtrWithGenericsSugg {
927 left,
928 snippet,
929 right: generics.span,
930 arity,
931 for_param_list_exists: param_insertion_point.is_some(),
932 })
933 } else {
934 None
935 };
936
937 self.dcx().emit_err(FnPtrWithGenerics { span: generics.span, sugg });
938 params.append(&mut lifetimes);
939 Ok(())
940 }
941
942 fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
944 if self.token.is_lifetime() {
945 self.look_ahead(1, |t| {
946 if let token::Ident(sym, _) = t.kind {
947 self.dcx().emit_err(errors::MissingPlusBounds {
950 span: self.token.span,
951 hi: self.token.span.shrink_to_hi(),
952 sym,
953 });
954 }
955 })
956 }
957
958 let bounds = self.parse_generic_bounds()?;
960
961 *impl_dyn_multi = bounds.len() > 1 || self.prev_token == TokenKind::Plus;
962
963 Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
964 }
965
966 fn parse_use_bound(&mut self, lo: Span, parens: ast::Parens) -> PResult<'a, GenericBound> {
973 self.expect_lt()?;
974 let (args, _, _) = self.parse_seq_to_before_tokens(
975 &[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)],
976 &[&TokenKind::Ge, &TokenKind::Shr, &TokenKind::Shr],
977 SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
978 |self_| {
979 if self_.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::SelfUpper,
token_type: crate::parser::token_type::TokenType::KwSelfUpper,
}exp!(SelfUpper)) {
980 self_.bump();
981 Ok(PreciseCapturingArg::Arg(
982 ast::Path::from_ident(self_.prev_token.ident().unwrap().0),
983 DUMMY_NODE_ID,
984 ))
985 } else if self_.check_ident() {
986 Ok(PreciseCapturingArg::Arg(
987 ast::Path::from_ident(self_.parse_ident()?),
988 DUMMY_NODE_ID,
989 ))
990 } else if self_.check_lifetime() {
991 Ok(PreciseCapturingArg::Lifetime(self_.expect_lifetime()))
992 } else {
993 self_.unexpected_any()
994 }
995 },
996 )?;
997 self.expect_gt()?;
998
999 if let ast::Parens::Yes = parens {
1000 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1001 self.report_parenthesized_bound(lo, self.prev_token.span, "precise capturing lists");
1002 }
1003
1004 Ok(GenericBound::Use(args, lo.to(self.prev_token.span)))
1005 }
1006
1007 fn is_explicit_dyn_type(&mut self) -> bool {
1009 self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Dyn,
token_type: crate::parser::token_type::TokenType::KwDyn,
}exp!(Dyn))
1010 && (self.token_uninterpolated_span().at_least_rust_2018()
1011 || self.look_ahead(1, |&t| can_begin_dyn_bound_in_edition_2015(t)))
1012 }
1013
1014 fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
1018 self.bump(); let bounds = self.parse_generic_bounds()?;
1022 *impl_dyn_multi = bounds.len() > 1 || self.prev_token == TokenKind::Plus;
1023
1024 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn))
1025 }
1026
1027 fn parse_path_start_ty(
1034 &mut self,
1035 lo: Span,
1036 allow_plus: AllowPlus,
1037 ty_generics: Option<&Generics>,
1038 ) -> PResult<'a, TyKind> {
1039 let path = self.parse_path_inner(PathStyle::Type, ty_generics)?;
1041 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
1042 Ok(TyKind::MacCall(Box::new(MacCall { path, args: self.parse_delim_args()? })))
1044 } else if allow_plus == AllowPlus::Yes && self.check_plus() {
1045 self.parse_remaining_bounds_path(ThinVec::new(), path, lo, true, ast::Parens::No)
1047 } else {
1048 Ok(TyKind::Path(None, path))
1050 }
1051 }
1052
1053 pub(super) fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
1054 self.parse_generic_bounds_common(AllowPlus::Yes)
1055 }
1056
1057 fn parse_generic_bounds_common(&mut self, allow_plus: AllowPlus) -> PResult<'a, GenericBounds> {
1062 let mut bounds = Vec::new();
1063
1064 while self.can_begin_bound()
1070 || (self.may_recover()
1071 && (self.token.can_begin_type()
1072 || (self.token.is_reserved_ident() && !self.token.is_keyword(kw::Where))))
1073 {
1074 if self.token.is_keyword(kw::Dyn) {
1075 self.bump();
1077 self.dcx().emit_err(InvalidDynKeyword {
1078 span: self.prev_token.span,
1079 suggestion: self.prev_token.span.until(self.token.span),
1080 });
1081 }
1082 bounds.push(self.parse_generic_bound()?);
1083 if allow_plus == AllowPlus::No || !self.eat_plus() {
1084 break;
1085 }
1086 }
1087
1088 Ok(bounds)
1089 }
1090
1091 fn can_begin_bound(&mut self) -> bool {
1093 self.check_path()
1094 || self.check_lifetime()
1095 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))
1096 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Question,
token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question))
1097 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Tilde,
token_type: crate::parser::token_type::TokenType::Tilde,
}exp!(Tilde))
1098 || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::For,
token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For))
1099 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))
1100 || self.can_begin_maybe_const_bound()
1101 || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))
1102 || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Async,
token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async))
1103 || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Use,
token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use))
1104 }
1105
1106 fn can_begin_maybe_const_bound(&mut self) -> bool {
1107 self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBracket,
token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket))
1108 && self.look_ahead(1, |t| t.is_keyword(kw::Const))
1109 && self.look_ahead(2, |t| *t == token::CloseBracket)
1110 }
1111
1112 fn parse_generic_bound(&mut self) -> PResult<'a, GenericBound> {
1118 let leading_token = self.prev_token;
1119 let lo = self.token.span;
1120
1121 let parens = if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) { ast::Parens::Yes } else { ast::Parens::No };
1127
1128 if self.token.is_lifetime() {
1129 self.parse_lifetime_bound(lo, parens)
1130 } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Use,
token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use)) {
1131 self.parse_use_bound(lo, parens)
1132 } else {
1133 self.parse_trait_bound(lo, parens, &leading_token)
1134 }
1135 }
1136
1137 fn parse_lifetime_bound(&mut self, lo: Span, parens: ast::Parens) -> PResult<'a, GenericBound> {
1143 let lt = self.expect_lifetime();
1144
1145 if let ast::Parens::Yes = parens {
1146 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1147 self.report_parenthesized_bound(lo, self.prev_token.span, "lifetime bounds");
1148 }
1149
1150 Ok(GenericBound::Outlives(lt))
1151 }
1152
1153 fn report_parenthesized_bound(&self, lo: Span, hi: Span, kind: &str) -> ErrorGuaranteed {
1154 let mut diag =
1155 self.dcx().struct_span_err(lo.to(hi), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} may not be parenthesized",
kind))
})format!("{kind} may not be parenthesized"));
1156 diag.multipart_suggestion(
1157 "remove the parentheses",
1158 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lo, String::new()), (hi, String::new())]))vec![(lo, String::new()), (hi, String::new())],
1159 Applicability::MachineApplicable,
1160 );
1161 diag.emit()
1162 }
1163
1164 fn error_lt_bound_with_modifiers(
1166 &self,
1167 modifiers: TraitBoundModifiers,
1168 binder_span: Option<Span>,
1169 ) -> ErrorGuaranteed {
1170 let TraitBoundModifiers { constness, asyncness, polarity } = modifiers;
1171
1172 match constness {
1173 BoundConstness::Never => {}
1174 BoundConstness::Always(span) | BoundConstness::Maybe(span) => {
1175 return self
1176 .dcx()
1177 .emit_err(errors::ModifierLifetime { span, modifier: constness.as_str() });
1178 }
1179 }
1180
1181 match polarity {
1182 BoundPolarity::Positive => {}
1183 BoundPolarity::Negative(span) | BoundPolarity::Maybe(span) => {
1184 return self
1185 .dcx()
1186 .emit_err(errors::ModifierLifetime { span, modifier: polarity.as_str() });
1187 }
1188 }
1189
1190 match asyncness {
1191 BoundAsyncness::Normal => {}
1192 BoundAsyncness::Async(span) => {
1193 return self
1194 .dcx()
1195 .emit_err(errors::ModifierLifetime { span, modifier: asyncness.as_str() });
1196 }
1197 }
1198
1199 if let Some(span) = binder_span {
1200 return self.dcx().emit_err(errors::ModifierLifetime { span, modifier: "for<...>" });
1201 }
1202
1203 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("lifetime bound intercepted in `parse_generic_ty_bound` but no modifiers?")));
}unreachable!("lifetime bound intercepted in `parse_generic_ty_bound` but no modifiers?")
1204 }
1205
1206 fn parse_trait_bound_modifiers(&mut self) -> PResult<'a, TraitBoundModifiers> {
1218 let modifier_lo = self.token.span;
1219 let constness = self.parse_bound_constness()?;
1220
1221 let asyncness = if self.token_uninterpolated_span().at_least_rust_2018()
1222 && self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Async,
token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async))
1223 {
1224 self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
1225 BoundAsyncness::Async(self.prev_token.span)
1226 } else if self.may_recover()
1227 && self.token_uninterpolated_span().is_rust_2015()
1228 && self.is_kw_followed_by_ident(kw::Async)
1229 {
1230 self.bump(); self.dcx().emit_err(errors::AsyncBoundModifierIn2015 {
1232 span: self.prev_token.span,
1233 help: HelpUseLatestEdition::new(),
1234 });
1235 self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
1236 BoundAsyncness::Async(self.prev_token.span)
1237 } else {
1238 BoundAsyncness::Normal
1239 };
1240 let modifier_hi = self.prev_token.span;
1241
1242 let polarity = if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Question,
token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question)) {
1243 BoundPolarity::Maybe(self.prev_token.span)
1244 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
1245 self.psess.gated_spans.gate(sym::negative_bounds, self.prev_token.span);
1246 BoundPolarity::Negative(self.prev_token.span)
1247 } else {
1248 BoundPolarity::Positive
1249 };
1250
1251 match polarity {
1253 BoundPolarity::Positive => {
1254 }
1256 BoundPolarity::Maybe(polarity_span) | BoundPolarity::Negative(polarity_span) => {
1257 match (asyncness, constness) {
1258 (BoundAsyncness::Normal, BoundConstness::Never) => {
1259 }
1261 (_, _) => {
1262 let constness = constness.as_str();
1263 let asyncness = asyncness.as_str();
1264 let glue =
1265 if !constness.is_empty() && !asyncness.is_empty() { " " } else { "" };
1266 let modifiers_concatenated = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", constness, glue,
asyncness))
})format!("{constness}{glue}{asyncness}");
1267 self.dcx().emit_err(errors::PolarityAndModifiers {
1268 polarity_span,
1269 polarity: polarity.as_str(),
1270 modifiers_span: modifier_lo.to(modifier_hi),
1271 modifiers_concatenated,
1272 });
1273 }
1274 }
1275 }
1276 }
1277
1278 Ok(TraitBoundModifiers { constness, asyncness, polarity })
1279 }
1280
1281 pub fn parse_bound_constness(&mut self) -> PResult<'a, BoundConstness> {
1282 Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Tilde,
token_type: crate::parser::token_type::TokenType::Tilde,
}exp!(Tilde)) {
1285 let tilde = self.prev_token.span;
1286 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1287 let span = tilde.to(self.prev_token.span);
1288 self.psess.gated_spans.gate(sym::const_trait_impl, span);
1289 BoundConstness::Maybe(span)
1290 } else if self.can_begin_maybe_const_bound() {
1291 let start = self.token.span;
1292 self.bump();
1293 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const)).unwrap();
1294 self.bump();
1295 let span = start.to(self.prev_token.span);
1296 self.psess.gated_spans.gate(sym::const_trait_impl, span);
1297 BoundConstness::Maybe(span)
1298 } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const)) {
1299 self.psess.gated_spans.gate(sym::const_trait_impl, self.prev_token.span);
1300 BoundConstness::Always(self.prev_token.span)
1301 } else {
1302 BoundConstness::Never
1303 })
1304 }
1305
1306 fn parse_trait_bound(
1315 &mut self,
1316 lo: Span,
1317 parens: ast::Parens,
1318 leading_token: &Token,
1319 ) -> PResult<'a, GenericBound> {
1320 let (mut bound_vars, binder_span) = self.parse_higher_ranked_binder()?;
1321
1322 let modifiers_lo = self.token.span;
1323 let modifiers = self.parse_trait_bound_modifiers()?;
1324 let modifiers_span = modifiers_lo.to(self.prev_token.span);
1325
1326 if let Some(binder_span) = binder_span {
1327 match modifiers.polarity {
1328 BoundPolarity::Negative(polarity_span) | BoundPolarity::Maybe(polarity_span) => {
1329 self.dcx().emit_err(errors::BinderAndPolarity {
1330 binder_span,
1331 polarity_span,
1332 polarity: modifiers.polarity.as_str(),
1333 });
1334 }
1335 BoundPolarity::Positive => {}
1336 }
1337 }
1338
1339 if self.token.is_lifetime() {
1342 let _: ErrorGuaranteed = self.error_lt_bound_with_modifiers(modifiers, binder_span);
1343 return self.parse_lifetime_bound(lo, parens);
1344 }
1345
1346 if let (more_bound_vars, Some(binder_span)) = self.parse_higher_ranked_binder()? {
1347 bound_vars.extend(more_bound_vars);
1348 self.dcx().emit_err(errors::BinderBeforeModifiers { binder_span, modifiers_span });
1349 }
1350
1351 let mut path = if self.token.is_keyword(kw::Fn)
1352 && self.look_ahead(1, |t| *t == TokenKind::OpenParen)
1353 && let Some(path) = self.recover_path_from_fn()
1354 {
1355 path
1356 } else if !self.token.is_path_start() && self.token.can_begin_type() {
1357 let ty = self.parse_ty_no_plus()?;
1358 let mut err = self.dcx().struct_span_err(ty.span, "expected a trait, found type");
1360
1361 let path = if self.may_recover() {
1366 let (span, message, sugg, path, applicability) = match &ty.kind {
1367 TyKind::Ptr(..) | TyKind::Ref(..)
1368 if let TyKind::Path(_, path) = &ty.peel_refs().kind =>
1369 {
1370 (
1371 ty.span.until(path.span),
1372 "consider removing the indirection",
1373 "",
1374 path,
1375 Applicability::MaybeIncorrect,
1376 )
1377 }
1378 TyKind::ImplTrait(_, bounds)
1379 if let [GenericBound::Trait(tr, ..), ..] = bounds.as_slice() =>
1380 {
1381 (
1382 ty.span.until(tr.span),
1383 "use the trait bounds directly",
1384 "",
1385 &tr.trait_ref.path,
1386 Applicability::MachineApplicable,
1387 )
1388 }
1389 _ => return Err(err),
1390 };
1391
1392 err.span_suggestion_verbose(span, message, sugg, applicability);
1393
1394 path.clone()
1395 } else {
1396 return Err(err);
1397 };
1398
1399 err.emit();
1400
1401 path
1402 } else {
1403 self.parse_path(PathStyle::Type)?
1404 };
1405
1406 if self.may_recover() && self.token == TokenKind::OpenParen {
1407 self.recover_fn_trait_with_lifetime_params(&mut path, &mut bound_vars)?;
1408 }
1409
1410 if let ast::Parens::Yes = parens {
1411 if self.token.is_like_plus() && leading_token.is_keyword(kw::Dyn) {
1414 let bounds = ::alloc::vec::Vec::new()vec![];
1415 self.parse_remaining_bounds(bounds, true)?;
1416 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1417 self.dcx().emit_err(errors::IncorrectParensTraitBounds {
1418 span: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[lo, self.prev_token.span]))vec![lo, self.prev_token.span],
1419 sugg: errors::IncorrectParensTraitBoundsSugg {
1420 wrong_span: leading_token.span.shrink_to_hi().to(lo),
1421 new_span: leading_token.span.shrink_to_lo(),
1422 },
1423 });
1424 } else {
1425 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1426 }
1427 }
1428
1429 let poly_trait =
1430 PolyTraitRef::new(bound_vars, path, modifiers, lo.to(self.prev_token.span), parens);
1431 Ok(GenericBound::Trait(poly_trait))
1432 }
1433
1434 fn recover_path_from_fn(&mut self) -> Option<ast::Path> {
1436 let fn_token_span = self.token.span;
1437 self.bump();
1438 let args_lo = self.token.span;
1439 let snapshot = self.create_snapshot_for_diagnostic();
1440 let mode =
1441 FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false };
1442 match self.parse_fn_decl(&mode, AllowPlus::No, RecoverReturnSign::OnlyFatArrow) {
1443 Ok(decl) => {
1444 self.dcx().emit_err(ExpectedFnPathFoundFnKeyword { fn_token_span });
1445 Some(ast::Path {
1446 span: fn_token_span.to(self.prev_token.span),
1447 segments: {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(ast::PathSegment {
ident: Ident::new(sym::Fn, fn_token_span),
id: DUMMY_NODE_ID,
args: Some(Box::new(ast::GenericArgs::Parenthesized(ast::ParenthesizedArgs {
span: args_lo.to(self.prev_token.span),
inputs: decl.inputs.iter().map(|a| a.ty.clone()).collect(),
inputs_span: args_lo.until(decl.output.span()),
output: decl.output.clone(),
}))),
});
vec
}thin_vec![ast::PathSegment {
1448 ident: Ident::new(sym::Fn, fn_token_span),
1449 id: DUMMY_NODE_ID,
1450 args: Some(Box::new(ast::GenericArgs::Parenthesized(
1451 ast::ParenthesizedArgs {
1452 span: args_lo.to(self.prev_token.span),
1453 inputs: decl.inputs.iter().map(|a| a.ty.clone()).collect(),
1454 inputs_span: args_lo.until(decl.output.span()),
1455 output: decl.output.clone(),
1456 }
1457 ))),
1458 }],
1459 tokens: None,
1460 })
1461 }
1462 Err(diag) => {
1463 diag.cancel();
1464 self.restore_snapshot(snapshot);
1465 None
1466 }
1467 }
1468 }
1469
1470 pub(super) fn parse_higher_ranked_binder(
1476 &mut self,
1477 ) -> PResult<'a, (ThinVec<GenericParam>, Option<Span>)> {
1478 if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::For,
token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For)) {
1479 let lo = self.token.span;
1480 self.expect_lt()?;
1481 let params = self.parse_generic_params()?;
1482 self.expect_gt()?;
1483 Ok((params, Some(lo.to(self.prev_token.span))))
1486 } else {
1487 Ok((ThinVec::new(), None))
1488 }
1489 }
1490
1491 fn recover_fn_trait_with_lifetime_params(
1495 &mut self,
1496 fn_path: &mut ast::Path,
1497 lifetime_defs: &mut ThinVec<GenericParam>,
1498 ) -> PResult<'a, ()> {
1499 let fn_path_segment = fn_path.segments.last_mut().unwrap();
1500 let generic_args = if let Some(p_args) = &fn_path_segment.args {
1501 *p_args.clone()
1502 } else {
1503 return Ok(());
1506 };
1507 let lifetimes =
1508 if let ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { span: _, args }) =
1509 &generic_args
1510 {
1511 args.into_iter()
1512 .filter_map(|arg| {
1513 if let ast::AngleBracketedArg::Arg(generic_arg) = arg
1514 && let ast::GenericArg::Lifetime(lifetime) = generic_arg
1515 {
1516 Some(lifetime)
1517 } else {
1518 None
1519 }
1520 })
1521 .collect()
1522 } else {
1523 Vec::new()
1524 };
1525 if lifetimes.is_empty() {
1527 return Ok(());
1528 }
1529
1530 let snapshot = if self.parsing_generics {
1531 Some(self.create_snapshot_for_diagnostic())
1534 } else {
1535 None
1536 };
1537 let inputs_lo = self.token.span;
1539 let mode =
1540 FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false };
1541 let params = match self.parse_fn_params(&mode) {
1542 Ok(params) => params,
1543 Err(err) => {
1544 if let Some(snapshot) = snapshot {
1545 self.restore_snapshot(snapshot);
1546 err.cancel();
1547 return Ok(());
1548 } else {
1549 return Err(err);
1550 }
1551 }
1552 };
1553 let inputs: ThinVec<_> = params.into_iter().map(|input| input.ty).collect();
1554 let inputs_span = inputs_lo.to(self.prev_token.span);
1555 let output = match self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)
1556 {
1557 Ok(output) => output,
1558 Err(err) => {
1559 if let Some(snapshot) = snapshot {
1560 self.restore_snapshot(snapshot);
1561 err.cancel();
1562 return Ok(());
1563 } else {
1564 return Err(err);
1565 }
1566 }
1567 };
1568 let args = ast::ParenthesizedArgs {
1569 span: fn_path_segment.span().to(self.prev_token.span),
1570 inputs,
1571 inputs_span,
1572 output,
1573 }
1574 .into();
1575
1576 if let Some(snapshot) = snapshot
1577 && ![token::Comma, token::Gt, token::Plus].contains(&self.token.kind)
1578 {
1579 self.restore_snapshot(snapshot);
1583 return Ok(());
1584 }
1585
1586 *fn_path_segment = ast::PathSegment {
1587 ident: fn_path_segment.ident,
1588 args: Some(args),
1589 id: ast::DUMMY_NODE_ID,
1590 };
1591
1592 let mut generic_params = lifetimes
1594 .iter()
1595 .map(|lt| GenericParam {
1596 id: lt.id,
1597 ident: lt.ident,
1598 attrs: ast::AttrVec::new(),
1599 bounds: Vec::new(),
1600 is_placeholder: false,
1601 kind: ast::GenericParamKind::Lifetime,
1602 colon_span: None,
1603 })
1604 .collect::<ThinVec<GenericParam>>();
1605 lifetime_defs.append(&mut generic_params);
1606
1607 let generic_args_span = generic_args.span();
1608 let snippet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("for<{0}> ",
lifetimes.iter().map(|lt|
lt.ident.as_str()).intersperse(", ").collect::<String>()))
})format!(
1609 "for<{}> ",
1610 lifetimes.iter().map(|lt| lt.ident.as_str()).intersperse(", ").collect::<String>(),
1611 );
1612 let before_fn_path = fn_path.span.shrink_to_lo();
1613 self.dcx()
1614 .struct_span_err(generic_args_span, "`Fn` traits cannot take lifetime parameters")
1615 .with_multipart_suggestion(
1616 "consider using a higher-ranked trait bound instead",
1617 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(generic_args_span, "".to_owned()), (before_fn_path, snippet)]))vec![(generic_args_span, "".to_owned()), (before_fn_path, snippet)],
1618 Applicability::MaybeIncorrect,
1619 )
1620 .emit();
1621 Ok(())
1622 }
1623
1624 pub(super) fn check_lifetime(&mut self) -> bool {
1625 self.expected_token_types.insert(TokenType::Lifetime);
1626 self.token.is_lifetime()
1627 }
1628
1629 pub(super) fn expect_lifetime(&mut self) -> Lifetime {
1631 if let Some((ident, is_raw)) = self.token.lifetime() {
1632 if is_raw == IdentIsRaw::No && ident.without_first_quote().is_reserved_lifetime() {
1633 self.dcx().emit_err(errors::KeywordLifetime { span: ident.span });
1634 }
1635
1636 self.bump();
1637 Lifetime { ident, id: ast::DUMMY_NODE_ID }
1638 } else {
1639 self.dcx().span_bug(self.token.span, "not a lifetime")
1640 }
1641 }
1642
1643 pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> Box<Ty> {
1644 Box::new(Ty { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })
1645 }
1646}