1use rustc_ast::token::{self, IdentKind, 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, MutTy, Mutability,
6 Path, Pinnedness, PolyTraitRef, PreciseCapturingArg, TraitBoundModifiers, TraitObjectSyntax,
7 Ty, TyKind, UnsafeBinderTy,
8};
9use rustc_errors::{Applicability, Diag, E0516, PResult};
10use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym};
11use thin_vec::{ThinVec, thin_vec};
12
13use super::{Parser, PathStyle, SeqSep, TokenType, Trailing};
14use crate::diagnostics::{
15 self, DynAfterMut, ExpectedFnPathFoundFnKeyword, ExpectedMutOrConstInRawPointerType,
16 FnPtrWithGenerics, FnPtrWithGenericsSugg, HelpUseLatestEdition, InvalidCVariadicType,
17 InvalidDynKeyword, LifetimeAfterMut, NeedPlusAfterTraitObjectLifetime, NestedCVariadicType,
18 ReturnTypesUseThinArrow,
19};
20use crate::parser::{FnContext, FnParseMode, FrontMatterParsingMode};
21use crate::{exp, maybe_recover_from_interpolated_ty_qpath};
22
23#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllowPlus { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AllowPlus { }
#[automatically_derived]
impl ::core::clone::Clone for AllowPlus {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AllowPlus { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AllowPlus {
#[inline]
fn eq(&self, other: &Self) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
29pub(super) enum AllowPlus {
30 Yes,
31 No,
32}
33
34#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for RecoverQPath { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RecoverQPath {
#[inline]
fn eq(&self, other: &Self) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
35pub(super) enum RecoverQPath {
36 Yes,
37 No,
38}
39
40pub(super) enum RecoverQuestionMark {
41 Yes,
42 No,
43}
44
45#[derive(#[automatically_derived]
impl ::core::marker::Copy for RecoverReturnSign { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RecoverReturnSign { }
#[automatically_derived]
impl ::core::clone::Clone for RecoverReturnSign {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for RecoverReturnSign { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RecoverReturnSign {
#[inline]
fn eq(&self, other: &Self) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
56pub(super) enum RecoverReturnSign {
57 Yes,
58 OnlyFatArrow,
59 No,
60}
61
62impl RecoverReturnSign {
63 fn can_recover(self, token: &TokenKind) -> bool {
68 match self {
69 Self::Yes => #[allow(non_exhaustive_omitted_patterns)] match token {
token::FatArrow | token::Colon => true,
_ => false,
}matches!(token, token::FatArrow | token::Colon),
70 Self::OnlyFatArrow => #[allow(non_exhaustive_omitted_patterns)] match token {
token::FatArrow => true,
_ => false,
}matches!(token, token::FatArrow),
71 Self::No => false,
72 }
73 }
74}
75
76#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for AllowCVariadic { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AllowCVariadic {
#[inline]
fn eq(&self, other: &Self) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
78enum AllowCVariadic {
79 Yes,
80 No,
81}
82
83fn can_begin_dyn_bound_in_edition_2015(t: Token) -> bool {
87 if t.is_path_start() {
88 return t != token::PathSep && t != token::Lt && t != token::Shl;
94 }
95
96 t == token::OpenParen || t == token::Question || t.is_lifetime() || t.is_keyword(kw::For)
101}
102
103impl<'a> Parser<'a> {
104 pub fn parse_ty(&mut self) -> PResult<'a, Box<Ty>> {
106 if self.token == token::DotDotDot {
107 let span = self.token.span;
111 self.bump();
112 let kind = TyKind::Err(self.dcx().emit_err(InvalidCVariadicType { span }));
113 return Ok(self.mk_ty(span, kind));
114 }
115 self.parse_ty_common(
116 AllowPlus::Yes,
117 AllowCVariadic::No,
118 RecoverQPath::Yes,
119 RecoverReturnSign::Yes,
120 None,
121 RecoverQuestionMark::Yes,
122 )
123 }
124
125 pub(super) fn parse_ty_with_generics_recovery(
126 &mut self,
127 ty_params: &Generics,
128 ) -> PResult<'a, Box<Ty>> {
129 self.parse_ty_common(
130 AllowPlus::Yes,
131 AllowCVariadic::No,
132 RecoverQPath::Yes,
133 RecoverReturnSign::Yes,
134 Some(ty_params),
135 RecoverQuestionMark::Yes,
136 )
137 }
138
139 pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, Box<Ty>> {
143 let ty = self.parse_ty_common(
144 AllowPlus::Yes,
145 AllowCVariadic::Yes,
146 RecoverQPath::Yes,
147 RecoverReturnSign::Yes,
148 None,
149 RecoverQuestionMark::Yes,
150 )?;
151
152 if self.may_recover()
154 && self.check_noexpect(&token::Eq)
155 && self.look_ahead(1, |tok| tok.can_begin_expr())
156 {
157 let snapshot = self.create_snapshot_for_diagnostic();
158 self.bump();
159 let eq_span = self.prev_token.span;
160 match self.parse_expr() {
161 Ok(e) => {
162 self.dcx()
163 .struct_span_err(eq_span.to(e.span), "parameter defaults are not supported")
164 .emit();
165 }
166 Err(diag) => {
167 diag.cancel();
168 self.restore_snapshot(snapshot);
169 }
170 }
171 }
172
173 Ok(ty)
174 }
175
176 pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, Box<Ty>> {
183 self.parse_ty_common(
184 AllowPlus::No,
185 AllowCVariadic::No,
186 RecoverQPath::Yes,
187 RecoverReturnSign::Yes,
188 None,
189 RecoverQuestionMark::Yes,
190 )
191 }
192
193 pub(super) fn parse_as_cast_ty(&mut self) -> PResult<'a, Box<Ty>> {
196 self.parse_ty_common(
197 AllowPlus::No,
198 AllowCVariadic::No,
199 RecoverQPath::Yes,
200 RecoverReturnSign::Yes,
201 None,
202 RecoverQuestionMark::No,
203 )
204 }
205
206 pub(super) fn parse_ty_no_question_mark_recover(&mut self) -> PResult<'a, Box<Ty>> {
207 self.parse_ty_common(
208 AllowPlus::Yes,
209 AllowCVariadic::No,
210 RecoverQPath::Yes,
211 RecoverReturnSign::Yes,
212 None,
213 RecoverQuestionMark::No,
214 )
215 }
216
217 pub(super) fn parse_ty_for_where_clause(&mut self) -> PResult<'a, Box<Ty>> {
220 self.parse_ty_common(
221 AllowPlus::Yes,
222 AllowCVariadic::No,
223 RecoverQPath::Yes,
224 RecoverReturnSign::OnlyFatArrow,
225 None,
226 RecoverQuestionMark::Yes,
227 )
228 }
229
230 pub(super) fn parse_ret_ty(
232 &mut self,
233 allow_plus: AllowPlus,
234 recover_qpath: RecoverQPath,
235 recover_return_sign: RecoverReturnSign,
236 ) -> PResult<'a, FnRetTy> {
237 let lo = self.prev_token.span;
238 Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::RArrow,
token_type: crate::parser::token_type::TokenType::RArrow,
}exp!(RArrow)) {
239 let ty = self.parse_ty_common(
241 allow_plus,
242 AllowCVariadic::No,
243 recover_qpath,
244 recover_return_sign,
245 None,
246 RecoverQuestionMark::Yes,
247 )?;
248 FnRetTy::Ty(ty)
249 } else if recover_return_sign.can_recover(&self.token.kind) {
250 self.bump();
253 self.dcx().emit_err(ReturnTypesUseThinArrow {
254 span: self.prev_token.span,
255 suggestion: lo.between(self.token.span),
256 });
257 let ty = self.parse_ty_common(
258 allow_plus,
259 AllowCVariadic::No,
260 recover_qpath,
261 recover_return_sign,
262 None,
263 RecoverQuestionMark::Yes,
264 )?;
265 FnRetTy::Ty(ty)
266 } else {
267 FnRetTy::Default(self.prev_token.span.shrink_to_hi())
268 })
269 }
270
271 fn parse_ty_common(
272 &mut self,
273 allow_plus: AllowPlus,
274 allow_c_variadic: AllowCVariadic,
275 recover_qpath: RecoverQPath,
276 recover_return_sign: RecoverReturnSign,
277 ty_generics: Option<&Generics>,
278 recover_question_mark: RecoverQuestionMark,
279 ) -> PResult<'a, Box<Ty>> {
280 let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes;
281 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);
282
283 if let Some(ty) = self.eat_metavar_seq_with_matcher(
284 |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
MetaVarKind::Ty { .. } => true,
_ => false,
}matches!(mv_kind, MetaVarKind::Ty { .. }),
285 |this| this.parse_ty_no_question_mark_recover(),
286 ) {
287 return Ok(ty);
288 }
289
290 self.recover_from_outer_attributes("types")?;
291
292 let lo = self.token.span;
293 let mut impl_dyn_multi = false;
294 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)) {
295 self.parse_paren_start_ty(lo, allow_plus)?
296 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
297 TyKind::Never
299 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Star,
token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star)) {
300 self.parse_ty_ptr()?
301 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBracket,
token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket)) {
302 self.parse_array_or_slice_ty()?
303 } 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)) {
304 self.expect_and()?;
306 self.parse_borrowed_pointee()?
307 } else if self.eat_keyword_noexpect(kw::Typeof) {
308 self.parse_typeof_ty(lo)?
309 } else if self.is_builtin() {
310 self.parse_builtin_ty()?
311 } 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)) {
312 TyKind::Infer
314 } else if self.check_fn_front_matter(false, Case::Sensitive) {
315 self.parse_ty_fn_ptr(lo, ThinVec::new(), None, recover_return_sign)?
317 } 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)) {
318 let (bound_vars, _) = self.parse_higher_ranked_binder()?;
322 if self.check_fn_front_matter(false, Case::Sensitive) {
323 self.parse_ty_fn_ptr(
324 lo,
325 bound_vars,
326 Some(self.prev_token.span.shrink_to_lo()),
327 recover_return_sign,
328 )?
329 } else {
330 if self.may_recover()
332 && (self.eat_keyword_noexpect(kw::Impl) || self.eat_keyword_noexpect(kw::Dyn))
333 {
334 let kw = self.prev_token.ident().unwrap().0;
335 let removal_span = kw.span.with_hi(self.token.span.lo());
336 let path = self.parse_path(PathStyle::Type)?;
337 let mut bounds = {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(GenericBound::Trait(PolyTraitRef::new(bound_vars, path,
TraitBoundModifiers::NONE, lo.to(self.prev_token.span),
ast::Parens::No)));
vec
}thin_vec![GenericBound::Trait(PolyTraitRef::new(
338 bound_vars,
339 path,
340 TraitBoundModifiers::NONE,
341 lo.to(self.prev_token.span),
342 ast::Parens::No,
343 ))];
344 if allow_plus == AllowPlus::Yes && self.check_plus() {
345 self.eat_plus();
346 bounds.append(&mut self.parse_generic_bounds()?);
347 }
348 self.dcx().emit_err(diagnostics::TransposeDynOrImpl {
349 span: kw.span,
350 kw: kw.name.as_str(),
351 sugg: diagnostics::TransposeDynOrImplSugg {
352 removal_span,
353 insertion_span: lo.shrink_to_lo(),
354 kw: kw.name.as_str(),
355 },
356 });
357 match kw.name {
358 kw::Dyn => TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn),
359 kw::Impl => TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds),
360 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
361 }
362 } else {
363 let path = self.parse_path(PathStyle::Type)?;
364 let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus();
365 self.finish_parsing_bare_trait_object_ty(
366 bound_vars,
367 path,
368 lo,
369 parse_plus,
370 ast::Parens::No,
371 )?
372 }
373 }
374 } 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)) {
375 self.parse_impl_ty(&mut impl_dyn_multi)?
376 } else if self.is_explicit_dyn_type() {
377 self.parse_dyn_ty(&mut impl_dyn_multi)?
378 } else if self.eat_lt() {
379 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
381 TyKind::Path(Some(qself), path)
382 } else if (self.token.is_keyword(kw::Const) || self.token.is_keyword(kw::Mut))
383 && self.look_ahead(1, |t| *t == token::Star)
384 {
385 self.parse_ty_c_style_pointer()?
386 } else if self.check_path() {
387 self.parse_path_start_ty(lo, allow_plus, ty_generics)?
388 } else if self.can_begin_bound() {
389 self.parse_bare_trait_object_ty(lo, allow_plus)?
390 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::DotDotDot,
token_type: crate::parser::token_type::TokenType::DotDotDot,
}exp!(DotDotDot)) {
391 match allow_c_variadic {
392 AllowCVariadic::Yes => TyKind::CVarArgs,
393 AllowCVariadic::No => {
394 let guar = self.dcx().emit_err(NestedCVariadicType { span: lo });
398 TyKind::Err(guar)
399 }
400 }
401 } 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))
402 && self.look_ahead(1, |tok| tok.kind == token::Lt)
403 {
404 self.parse_unsafe_binder_ty()?
405 } else {
406 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));
407 let mut err = self.dcx().struct_span_err(lo, msg);
408 err.span_label(lo, "expected type");
409 if self.may_recover()
410 && (self.eat_keyword_noexpect(kw::True) || self.eat_keyword_noexpect(kw::False))
411 {
412 err.span_suggestion(
413 self.prev_token.span,
414 "the type is called",
415 "bool",
416 Applicability::MachineApplicable,
417 );
418 err.emit();
419 TyKind::Path(
420 None,
421 Path::from_ident(Ident { span: self.prev_token.span, name: sym::bool }),
422 )
423 } else {
424 return Err(err);
425 }
426 };
427
428 let span = lo.to(self.prev_token.span);
429 let mut ty = self.mk_ty(span, kind);
430
431 match allow_plus {
433 AllowPlus::Yes => self.maybe_recover_from_bad_type_plus(&ty)?,
434 AllowPlus::No => self.maybe_report_ambiguous_plus(impl_dyn_multi, &ty),
435 }
436 if let RecoverQuestionMark::Yes = recover_question_mark {
437 ty = self.maybe_recover_from_question_mark(ty);
438 }
439 if allow_qpath_recovery { self.maybe_recover_from_bad_qpath(ty) } else { Ok(ty) }
440 }
441
442 fn parse_unsafe_binder_ty(&mut self) -> PResult<'a, TyKind> {
443 let lo = self.token.span;
444 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)));
445 self.expect_lt()?;
446 let generic_params = self.parse_generic_params()?;
447 self.expect_gt()?;
448 let inner_ty = self.parse_ty()?;
449 let span = lo.to(self.prev_token.span);
450 self.psess.gated_spans.gate(sym::unsafe_binders, span);
451
452 Ok(TyKind::UnsafeBinder(Box::new(UnsafeBinderTy { generic_params, inner_ty })))
453 }
454
455 fn parse_paren_start_ty(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
463 let mut trailing_plus = false;
464 let (ts, trailing) = self.parse_paren_comma_seq(|p| {
465 let ty = p.parse_ty()?;
466 trailing_plus = p.prev_token == TokenKind::Plus;
467 Ok(ty)
468 })?;
469
470 if ts.len() == 1 && #[allow(non_exhaustive_omitted_patterns)] match trailing {
Trailing::No => true,
_ => false,
}matches!(trailing, Trailing::No) {
471 let ty = ts.into_iter().next().unwrap();
472
473 let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus();
480 match ty.kind {
481 TyKind::Path(None, path) if maybe_bounds => self
483 .finish_parsing_bare_trait_object_ty(
484 ThinVec::new(),
485 path,
486 lo,
487 true,
488 ast::Parens::Yes,
489 ),
490 TyKind::TraitObject(mut bounds, TraitObjectSyntax::None)
501 if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
502 {
503 self.eat_plus();
504 bounds.append(&mut self.parse_generic_bounds()?);
505 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
506 }
507 _ => Ok(TyKind::Paren(ty)),
508 }
509 } else {
510 Ok(TyKind::Tup(ts))
511 }
512 }
513
514 fn parse_bare_trait_object_ty(
515 &mut self,
516 lo: Span,
517 allow_plus: AllowPlus,
518 ) -> PResult<'a, TyKind> {
519 if self.token.is_lifetime() && !self.look_ahead(1, |t| t.is_like_plus()) {
521 if self.psess.edition.at_least_rust_2021() {
525 let lt = self.expect_lifetime();
526 let mut err = self.dcx().struct_span_err(lo, "expected type, found lifetime");
527 err.span_label(lo, "expected type");
528 return Ok(match self.maybe_recover_ref_ty_no_leading_ampersand(lt, lo, err) {
529 Ok(ref_ty) => ref_ty,
530 Err(err) => TyKind::Err(err.emit_err()),
531 });
532 }
533
534 self.dcx().emit_err(NeedPlusAfterTraitObjectLifetime {
535 span: lo,
536 suggestion: lo.shrink_to_hi(),
537 });
538 }
539 Ok(TyKind::TraitObject(
540 self.parse_generic_bounds_common(allow_plus)?,
541 TraitObjectSyntax::None,
542 ))
543 }
544
545 fn maybe_recover_ref_ty_no_leading_ampersand<'cx>(
546 &mut self,
547 lt: Lifetime,
548 lo: Span,
549 mut err: Diag<'cx>,
550 ) -> Result<TyKind, Diag<'cx>> {
551 if !self.may_recover() {
552 return Err(err);
553 }
554 let snapshot = self.create_snapshot_for_diagnostic();
555 let mutbl = self.parse_mutability();
556 match self.parse_ty_no_plus() {
557 Ok(ty) => {
558 err.span_suggestion_verbose(
559 lo.shrink_to_lo(),
560 "you might have meant to write a reference type here",
561 "&",
562 Applicability::MaybeIncorrect,
563 );
564 err.emit();
565 Ok(TyKind::Ref(Some(lt), MutTy { ty, mutbl }))
566 }
567 Err(diag) => {
568 diag.cancel();
569 self.restore_snapshot(snapshot);
570 Err(err)
571 }
572 }
573 }
574
575 fn finish_parsing_bare_trait_object_ty(
576 &mut self,
577 generic_params: ThinVec<GenericParam>,
578 path: ast::Path,
579 lo: Span,
580 parse_plus: bool,
581 parens: ast::Parens,
582 ) -> PResult<'a, TyKind> {
583 let mut bounds = {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(GenericBound::Trait(PolyTraitRef::new(generic_params, path,
TraitBoundModifiers::NONE, lo.to(self.prev_token.span),
parens)));
vec
}thin_vec![GenericBound::Trait(PolyTraitRef::new(
584 generic_params,
585 path,
586 TraitBoundModifiers::NONE,
587 lo.to(self.prev_token.span),
588 parens,
589 ))];
590 if parse_plus {
591 self.eat_plus();
592 bounds.append(&mut self.parse_generic_bounds()?);
593 }
594 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
595 }
596
597 fn parse_ty_c_style_pointer(&mut self) -> PResult<'a, TyKind> {
599 let kw_span = self.token.span;
600 let mutbl = self.parse_mut_or_const();
601
602 if let Some(mutbl) = mutbl
603 && self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Star,
token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star))
604 {
605 let star_span = self.prev_token.span;
606
607 let mutability = match mutbl {
608 Mutability::Not => "const",
609 Mutability::Mut => "mut",
610 };
611
612 let ty = self.parse_ty_no_question_mark_recover()?;
613
614 self.dcx()
615 .struct_span_err(
616 kw_span,
617 ::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`"),
618 )
619 .with_multipart_suggestion(
620 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("put the `*` before `{0}`",
mutability))
})format!("put the `*` before `{mutability}`"),
621 ::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())],
622 Applicability::MachineApplicable,
623 )
624 .emit();
625
626 return Ok(TyKind::Ptr(MutTy { ty, mutbl }));
627 }
628 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("this could never happen")));
}unreachable!("this could never happen")
630 }
631
632 fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
634 let mutbl = self.parse_mut_or_const().unwrap_or_else(|| {
635 let span = self.prev_token.span;
636 self.dcx().emit_err(ExpectedMutOrConstInRawPointerType {
637 span,
638 after_asterisk: span.shrink_to_hi(),
639 });
640 Mutability::Not
641 });
642 let ty = self.parse_ty_no_plus()?;
643 Ok(TyKind::Ptr(MutTy { ty, mutbl }))
644 }
645
646 fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
649 let elt_ty = self.parse_ty()?;
650
651 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)) {
652 let mut length = self.parse_expr_anon_const()?;
653
654 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)) {
655 self.check_mistyped_turbofish_with_multiple_type_params(e, &mut length.value)?;
657 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBracket,
token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket))?;
658 }
659 TyKind::Array(elt_ty, length)
660 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBracket,
token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket)) {
661 TyKind::Slice(elt_ty)
662 } else {
663 self.maybe_recover_array_ty_without_semi(elt_ty)?
664 };
665
666 Ok(ty)
667 }
668
669 fn maybe_recover_array_ty_without_semi(&mut self, elt_ty: Box<Ty>) -> PResult<'a, TyKind> {
676 let span = self.token.span;
677 let token_descr = super::token_descr(&self.token);
678 let mut err =
679 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));
680 err.span_label(span, "expected `;` or `]`");
681
682 if !self.may_recover() {
684 return Err(err);
685 }
686
687 let snapshot = self.create_snapshot_for_diagnostic();
688
689 let hi = self.prev_token.span.hi();
691 _ = 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));
692 let suggestion_span = self.prev_token.span.with_lo(hi);
693
694 let length = match self.parse_expr_anon_const() {
697 Ok(length) => length,
698 Err(e) => {
699 e.cancel();
700 self.restore_snapshot(snapshot);
701 return Err(err);
702 }
703 };
704
705 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)) {
706 e.cancel();
707 self.restore_snapshot(snapshot);
708 return Err(err);
709 }
710
711 err.span_suggestion_verbose(
712 suggestion_span,
713 "you might have meant to use `;` as the separator",
714 ";",
715 Applicability::MaybeIncorrect,
716 );
717 err.emit();
718 Ok(TyKind::Array(elt_ty, length))
719 }
720
721 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
722 let and_span = self.prev_token.span;
723 let mut opt_lifetime = self.check_lifetime().then(|| self.expect_lifetime());
724 let (pinned, mut mutbl) = self.parse_pin_and_mut();
725 if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() {
726 if !self.look_ahead(1, |t| t.is_like_plus()) {
732 let lifetime_span = self.token.span;
733 let span = and_span.to(lifetime_span);
734
735 let (suggest_lifetime, snippet) =
736 if let Ok(lifetime_src) = self.span_to_snippet(lifetime_span) {
737 (Some(span), lifetime_src)
738 } else {
739 (None, String::new())
740 };
741 self.dcx().emit_err(LifetimeAfterMut { span, suggest_lifetime, snippet });
742
743 opt_lifetime = Some(self.expect_lifetime());
744 }
745 } else if self.token.is_keyword(kw::Dyn)
746 && mutbl == Mutability::Not
747 && self.look_ahead(1, |t| t.is_keyword(kw::Mut))
748 {
749 let span = and_span.to(self.look_ahead(1, |t| t.span));
751 self.dcx().emit_err(DynAfterMut { span });
752
753 mutbl = Mutability::Mut;
755 let (dyn_tok, dyn_tok_sp) = (self.token, self.token_spacing);
756 self.bump();
757 self.bump_with((dyn_tok, dyn_tok_sp));
758 }
759 let ty = self.parse_ty_no_plus()?;
760 Ok(match pinned {
761 Pinnedness::Not => TyKind::Ref(opt_lifetime, MutTy { ty, mutbl }),
762 Pinnedness::Pinned => TyKind::PinnedRef(opt_lifetime, MutTy { ty, mutbl }),
763 })
764 }
765
766 pub(crate) fn parse_pin_and_mut(&mut self) -> (Pinnedness, Mutability) {
772 if self.token.is_keyword(kw::Pin) && self.look_ahead(1, Token::is_mutability) {
773 self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
774 if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Pin,
token_type: crate::parser::token_type::TokenType::KwMut,
}) {
::core::panicking::panic("assertion failed: self.eat_keyword(exp!(Pin))")
};assert!(self.eat_keyword(exp!(Pin)));
775 let mutbl = self.parse_mut_or_const().unwrap();
776 (Pinnedness::Pinned, mutbl)
777 } else {
778 (Pinnedness::Not, self.parse_mutability())
779 }
780 }
781
782 fn parse_typeof_ty(&mut self, lo: Span) -> PResult<'a, TyKind> {
785 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
786 let _expr = self.parse_expr_anon_const()?;
787 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
788 let span = lo.to(self.prev_token.span);
789 let guar = self
790 .dcx()
791 .struct_span_err(span, "`typeof` is a reserved keyword but unimplemented")
792 .with_note("consider replacing `typeof(...)` with an actual type")
793 .with_code(E0516)
794 .emit_err();
795 Ok(TyKind::Err(guar))
796 }
797
798 fn parse_builtin_ty(&mut self) -> PResult<'a, TyKind> {
799 self.parse_builtin(|this, lo, ident| {
800 Ok(match ident.name {
801 sym::field_of => Some(this.parse_ty_field_of(lo)?),
802 _ => None,
803 })
804 })
805 }
806
807 pub(crate) fn parse_ty_field_of(&mut self, _lo: Span) -> PResult<'a, TyKind> {
808 let container = self.parse_ty()?;
809 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
810
811 let fields = self.parse_floating_field_access()?;
812 let trailing_comma = self.eat_noexpect(&TokenKind::Comma);
813
814 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)]) {
815 if trailing_comma {
816 e.note("unexpected third argument to field_of");
817 } else {
818 e.note("field_of expects dot-separated field and variant names");
819 }
820 e.emit();
821 }
822
823 if self.may_recover() {
825 while !self.token.kind.is_close_delim_or_eof() {
826 self.bump();
827 }
828 }
829
830 match *fields {
831 [] => Err(self.dcx().struct_span_err(
832 self.token.span,
833 "`field_of!` expects dot-separated field and variant names",
834 )),
835 [field] => Ok(TyKind::FieldOf(container, None, field)),
836 [variant, field] => Ok(TyKind::FieldOf(container, Some(variant), field)),
837 _ => Err(self.dcx().struct_span_err(
838 fields.iter().map(|f| f.span).collect::<Vec<_>>(),
839 "`field_of!` only supports a single field or a variant with a field",
840 )),
841 }
842 }
843
844 fn parse_ty_fn_ptr(
854 &mut self,
855 lo: Span,
856 mut params: ThinVec<GenericParam>,
857 param_insertion_point: Option<Span>,
858 recover_return_sign: RecoverReturnSign,
859 ) -> PResult<'a, TyKind> {
860 let inherited_vis = rustc_ast::Visibility {
861 span: rustc_span::DUMMY_SP,
862 kind: rustc_ast::VisibilityKind::Inherited,
863 };
864 let span_start = self.token.span;
865 let ast::FnHeader { ext, safety, .. } = self.parse_fn_front_matter(
866 &inherited_vis,
867 Case::Sensitive,
868 FrontMatterParsingMode::FunctionPtrType,
869 )?;
870 if self.may_recover() && self.token == TokenKind::Lt {
871 self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?;
872 }
873 let mode = crate::parser::FnParseMode {
874 req_name: |_, _| false,
875 context: FnContext::FunctionPtrType,
876 req_body: false,
877 };
878 let decl = self.parse_fn_decl(&mode, AllowPlus::No, recover_return_sign)?;
879
880 let decl_span = span_start.to(self.prev_token.span);
881 Ok(TyKind::FnPtr(Box::new(FnPtrTy {
882 ext,
883 safety,
884 generic_params: params,
885 decl,
886 decl_span,
887 })))
888 }
889
890 fn recover_fn_ptr_with_generics(
892 &mut self,
893 lo: Span,
894 params: &mut ThinVec<GenericParam>,
895 param_insertion_point: Option<Span>,
896 ) -> PResult<'a, ()> {
897 let generics = self.parse_generics()?;
898 let arity = generics.params.len();
899
900 let mut lifetimes: ThinVec<_> = generics
901 .params
902 .into_iter()
903 .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
ast::GenericParamKind::Lifetime => true,
_ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime))
904 .collect();
905
906 let sugg = if !lifetimes.is_empty() {
907 let snippet =
908 lifetimes.iter().map(|param| param.ident.as_str()).intersperse(", ").collect();
909
910 let (left, snippet) = if let Some(span) = param_insertion_point {
911 (span, if params.is_empty() { snippet } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", snippet))
})format!(", {snippet}") })
912 } else {
913 (lo.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("for<{0}> ", snippet))
})format!("for<{snippet}> "))
914 };
915
916 Some(FnPtrWithGenericsSugg {
917 left,
918 snippet,
919 right: generics.span,
920 arity,
921 for_param_list_exists: param_insertion_point.is_some(),
922 })
923 } else {
924 None
925 };
926
927 self.dcx().emit_err(FnPtrWithGenerics { span: generics.span, sugg });
928 params.append(&mut lifetimes);
929 Ok(())
930 }
931
932 fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
934 if self.token.is_lifetime()
936 && let Some(ident) = self.look_ahead(1, |t| t.non_reserved_ident())
937 {
938 self.dcx().emit_err(diagnostics::MissingPlusBounds {
939 span: self.token.span,
940 hi: self.token.span.shrink_to_hi(),
941 sym: ident.name,
942 });
943 }
944
945 let bounds = self.parse_generic_bounds()?;
947
948 *impl_dyn_multi = bounds.len() > 1 || self.prev_token == TokenKind::Plus;
949
950 Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
951 }
952
953 fn parse_use_bound(&mut self, lo: Span, parens: ast::Parens) -> PResult<'a, GenericBound> {
960 self.expect_lt()?;
961 let (args, _, _) = self.parse_seq_to_before_tokens(
962 &[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)],
963 &[&TokenKind::Ge, &TokenKind::Shr, &TokenKind::Shr],
964 SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
965 |self_| {
966 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)) {
967 self_.bump();
968 Ok(PreciseCapturingArg::Arg(
969 ast::Path::from_ident(self_.prev_token.ident().unwrap().0),
970 DUMMY_NODE_ID,
971 ))
972 } else if self_.check_ident() {
973 Ok(PreciseCapturingArg::Arg(
974 ast::Path::from_ident(self_.parse_ident()?),
975 DUMMY_NODE_ID,
976 ))
977 } else if self_.check_lifetime() {
978 Ok(PreciseCapturingArg::Lifetime(self_.expect_lifetime()))
979 } else {
980 self_.unexpected_any()
981 }
982 },
983 )?;
984 self.expect_gt()?;
985
986 if let ast::Parens::Yes = parens {
987 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
988 self.report_parenthesized_bound(lo, self.prev_token.span, "precise capturing lists");
989 }
990
991 Ok(GenericBound::Use(args, lo.to(self.prev_token.span)))
992 }
993
994 fn is_explicit_dyn_type(&mut self) -> bool {
996 self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Dyn,
token_type: crate::parser::token_type::TokenType::KwDyn,
}exp!(Dyn))
997 && (self.token_uninterpolated_span().at_least_rust_2018()
998 || self.look_ahead(1, |&t| can_begin_dyn_bound_in_edition_2015(t)))
999 }
1000
1001 fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
1005 self.bump(); let bounds = self.parse_generic_bounds()?;
1009 *impl_dyn_multi = bounds.len() > 1 || self.prev_token == TokenKind::Plus;
1010
1011 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn))
1012 }
1013
1014 fn parse_path_start_ty(
1021 &mut self,
1022 lo: Span,
1023 allow_plus: AllowPlus,
1024 ty_generics: Option<&Generics>,
1025 ) -> PResult<'a, TyKind> {
1026 let path = self.parse_path_inner(PathStyle::Type, ty_generics)?;
1028 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
1029 Ok(TyKind::MacCall(Box::new(MacCall { path, args: self.parse_delim_args()? })))
1031 } else if allow_plus == AllowPlus::Yes && self.check_plus() {
1032 self.finish_parsing_bare_trait_object_ty(
1034 ThinVec::new(),
1035 path,
1036 lo,
1037 true,
1038 ast::Parens::No,
1039 )
1040 } else {
1041 Ok(TyKind::Path(None, path))
1043 }
1044 }
1045
1046 pub(super) fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
1047 self.parse_generic_bounds_common(AllowPlus::Yes)
1048 }
1049
1050 fn parse_generic_bounds_common(&mut self, allow_plus: AllowPlus) -> PResult<'a, GenericBounds> {
1055 let mut bounds = ThinVec::new();
1056
1057 while self.can_begin_bound()
1063 || (self.may_recover()
1064 && (self.token.can_begin_type()
1065 || (self.token.is_reserved_ident() && !self.token.is_keyword(kw::Where))))
1066 {
1067 if self.token.is_keyword(kw::Dyn) && self.token.span.edition().at_least_rust_2018() {
1068 self.bump();
1070 self.dcx().emit_err(InvalidDynKeyword {
1071 span: self.prev_token.span,
1072 suggestion: self.prev_token.span.until(self.token.span),
1073 });
1074 }
1075 bounds.push(self.parse_generic_bound()?);
1076 if allow_plus == AllowPlus::No || !self.eat_plus() {
1077 break;
1078 }
1079 }
1080
1081 Ok(bounds)
1082 }
1083
1084 fn can_begin_bound(&mut self) -> bool {
1086 self.check_path()
1091 || self.check_lifetime()
1092 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))
1093 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Question,
token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question))
1094 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Tilde,
token_type: crate::parser::token_type::TokenType::Tilde,
}exp!(Tilde))
1095 || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::For,
token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For))
1096 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))
1097 || self.can_begin_maybe_const_bound()
1098 || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))
1099 || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Async,
token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async))
1100 || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Use,
token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use))
1101 }
1102
1103 fn can_begin_maybe_const_bound(&mut self) -> bool {
1104 self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBracket,
token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket))
1105 && self.look_ahead(1, |t| t.is_keyword(kw::Const))
1106 && self.look_ahead(2, |t| *t == token::CloseBracket)
1107 }
1108
1109 fn parse_generic_bound(&mut self) -> PResult<'a, GenericBound> {
1115 let leading_token = self.prev_token;
1116 let lo = self.token.span;
1117
1118 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 };
1124
1125 if self.token.is_lifetime() {
1126 self.parse_lifetime_bound(lo, parens)
1127 } 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)) {
1128 self.parse_use_bound(lo, parens)
1129 } else {
1130 self.parse_trait_bound(lo, parens, &leading_token)
1131 }
1132 }
1133
1134 fn parse_lifetime_bound(&mut self, lo: Span, parens: ast::Parens) -> PResult<'a, GenericBound> {
1140 let lt = self.expect_lifetime();
1141
1142 if let ast::Parens::Yes = parens {
1143 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1144 self.report_parenthesized_bound(lo, self.prev_token.span, "lifetime bounds");
1145 }
1146
1147 Ok(GenericBound::Outlives(lt))
1148 }
1149
1150 fn report_parenthesized_bound(&self, lo: Span, hi: Span, kind: &str) -> ErrorGuaranteed {
1151 let mut diag =
1152 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"));
1153 diag.multipart_suggestion(
1154 "remove the parentheses",
1155 ::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())],
1156 Applicability::MachineApplicable,
1157 );
1158 diag.emit_err()
1159 }
1160
1161 fn error_lt_bound_with_modifiers(
1163 &self,
1164 modifiers: TraitBoundModifiers,
1165 binder_span: Option<Span>,
1166 ) -> ErrorGuaranteed {
1167 let TraitBoundModifiers { constness, asyncness, polarity } = modifiers;
1168
1169 match constness {
1170 BoundConstness::Never => {}
1171 BoundConstness::Always(span) | BoundConstness::Maybe(span) => {
1172 return self.dcx().emit_err(diagnostics::ModifierLifetime {
1173 span,
1174 modifier: constness.as_str(),
1175 });
1176 }
1177 }
1178
1179 match polarity {
1180 BoundPolarity::Positive => {}
1181 BoundPolarity::Negative(span) | BoundPolarity::Maybe(span) => {
1182 return self
1183 .dcx()
1184 .emit_err(diagnostics::ModifierLifetime { span, modifier: polarity.as_str() });
1185 }
1186 }
1187
1188 match asyncness {
1189 BoundAsyncness::Normal => {}
1190 BoundAsyncness::Async(span) => {
1191 return self.dcx().emit_err(diagnostics::ModifierLifetime {
1192 span,
1193 modifier: asyncness.as_str(),
1194 });
1195 }
1196 }
1197
1198 if let Some(span) = binder_span {
1199 return self
1200 .dcx()
1201 .emit_err(diagnostics::ModifierLifetime { span, modifier: "for<...>" });
1202 }
1203
1204 {
::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?")
1205 }
1206
1207 fn parse_trait_bound_modifiers(&mut self) -> PResult<'a, TraitBoundModifiers> {
1219 let modifier_lo = self.token.span;
1220 let constness = self.parse_bound_constness()?;
1221
1222 let asyncness = if self.token_uninterpolated_span().at_least_rust_2018()
1223 && self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Async,
token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async))
1224 {
1225 self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
1226 BoundAsyncness::Async(self.prev_token.span)
1227 } else if self.may_recover()
1228 && self.token_uninterpolated_span().is_rust_2015()
1229 && self.is_kw_followed_by_ident(kw::Async)
1230 {
1231 self.bump(); self.dcx().emit_err(diagnostics::AsyncBoundModifierIn2015 {
1233 span: self.prev_token.span,
1234 help: HelpUseLatestEdition::new(),
1235 });
1236 self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
1237 BoundAsyncness::Async(self.prev_token.span)
1238 } else {
1239 BoundAsyncness::Normal
1240 };
1241 let modifier_hi = self.prev_token.span;
1242
1243 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)) {
1244 BoundPolarity::Maybe(self.prev_token.span)
1245 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
1246 self.psess.gated_spans.gate(sym::negative_bounds, self.prev_token.span);
1247 BoundPolarity::Negative(self.prev_token.span)
1248 } else {
1249 BoundPolarity::Positive
1250 };
1251
1252 match polarity {
1254 BoundPolarity::Positive => {
1255 }
1257 BoundPolarity::Maybe(polarity_span) | BoundPolarity::Negative(polarity_span) => {
1258 match (asyncness, constness) {
1259 (BoundAsyncness::Normal, BoundConstness::Never) => {
1260 }
1262 (_, _) => {
1263 let constness = constness.as_str();
1264 let asyncness = asyncness.as_str();
1265 let glue =
1266 if !constness.is_empty() && !asyncness.is_empty() { " " } else { "" };
1267 let modifiers_concatenated = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", constness, glue,
asyncness))
})format!("{constness}{glue}{asyncness}");
1268 self.dcx().emit_err(diagnostics::PolarityAndModifiers {
1269 polarity_span,
1270 polarity: polarity.as_str(),
1271 modifiers_span: modifier_lo.to(modifier_hi),
1272 modifiers_concatenated,
1273 });
1274 }
1275 }
1276 }
1277 }
1278
1279 Ok(TraitBoundModifiers { constness, asyncness, polarity })
1280 }
1281
1282 pub fn parse_bound_constness(&mut self) -> PResult<'a, BoundConstness> {
1283 Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Tilde,
token_type: crate::parser::token_type::TokenType::Tilde,
}exp!(Tilde)) {
1286 let tilde = self.prev_token.span;
1287 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1288 let span = tilde.to(self.prev_token.span);
1289 self.psess.gated_spans.gate(sym::const_trait_impl, span);
1290 BoundConstness::Maybe(span)
1291 } else if self.can_begin_maybe_const_bound() {
1292 let start = self.token.span;
1293 self.bump();
1294 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();
1295 self.bump();
1296 let span = start.to(self.prev_token.span);
1297 self.psess.gated_spans.gate(sym::const_trait_impl, span);
1298 BoundConstness::Maybe(span)
1299 } 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)) {
1300 self.psess.gated_spans.gate(sym::const_trait_impl, self.prev_token.span);
1301 BoundConstness::Always(self.prev_token.span)
1302 } else {
1303 BoundConstness::Never
1304 })
1305 }
1306
1307 fn parse_trait_bound(
1316 &mut self,
1317 lo: Span,
1318 parens: ast::Parens,
1319 leading_token: &Token,
1320 ) -> PResult<'a, GenericBound> {
1321 let (mut bound_vars, binder_span) = self.parse_higher_ranked_binder()?;
1322
1323 let modifiers_lo = self.token.span;
1324 let modifiers = self.parse_trait_bound_modifiers()?;
1325 let modifiers_span = modifiers_lo.to(self.prev_token.span);
1326
1327 if let Some(binder_span) = binder_span {
1328 match modifiers.polarity {
1329 BoundPolarity::Negative(polarity_span) | BoundPolarity::Maybe(polarity_span) => {
1330 self.dcx().emit_err(diagnostics::BinderAndPolarity {
1331 binder_span,
1332 polarity_span,
1333 polarity: modifiers.polarity.as_str(),
1334 });
1335 }
1336 BoundPolarity::Positive => {}
1337 }
1338 }
1339
1340 if self.token.is_lifetime() {
1343 let _: ErrorGuaranteed = self.error_lt_bound_with_modifiers(modifiers, binder_span);
1344 return self.parse_lifetime_bound(lo, parens);
1345 }
1346
1347 if let (more_bound_vars, Some(binder_span)) = self.parse_higher_ranked_binder()? {
1348 bound_vars.extend(more_bound_vars);
1349 self.dcx().emit_err(diagnostics::BinderBeforeModifiers { binder_span, modifiers_span });
1350 }
1351
1352 let mut path = if self.token.is_keyword(kw::Fn)
1353 && self.look_ahead(1, |t| *t == TokenKind::OpenParen)
1354 && let Some(path) = self.recover_path_from_fn()
1355 {
1356 path
1357 } else if !self.token.is_path_start() && self.token.can_begin_type() {
1358 let ty = self.parse_ty_no_plus()?;
1359 let mut err = self.dcx().struct_span_err(ty.span, "expected a trait, found type");
1361
1362 let path = if self.may_recover() {
1367 let (span, message, sugg, path, applicability) = match &ty.kind {
1368 TyKind::Ptr(..) | TyKind::Ref(..)
1369 if let TyKind::Path(_, path) = &ty.peel_refs().kind =>
1370 {
1371 (
1372 ty.span.until(path.span),
1373 "consider removing the indirection",
1374 "",
1375 path,
1376 Applicability::MaybeIncorrect,
1377 )
1378 }
1379 TyKind::ImplTrait(_, bounds)
1380 if let [GenericBound::Trait(tr, ..), ..] = bounds.as_slice() =>
1381 {
1382 (
1383 ty.span.until(tr.span),
1384 "use the trait bounds directly",
1385 "",
1386 &tr.trait_ref.path,
1387 Applicability::MachineApplicable,
1388 )
1389 }
1390 _ => return Err(err),
1391 };
1392
1393 err.span_suggestion_verbose(span, message, sugg, applicability);
1394
1395 path.clone()
1396 } else {
1397 return Err(err);
1398 };
1399
1400 err.emit();
1401
1402 path
1403 } else {
1404 self.parse_path(PathStyle::Type)?
1405 };
1406
1407 if self.may_recover() && self.token == TokenKind::OpenParen {
1408 self.recover_fn_trait_with_lifetime_params(&mut path, &mut bound_vars)?;
1409 }
1410
1411 if let ast::Parens::Yes = parens {
1412 if self.token.is_like_plus() && leading_token.is_keyword(kw::Dyn) {
1415 self.eat_plus();
1416 self.parse_generic_bounds()?;
1417 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1418
1419 self.dcx().emit_err(diagnostics::IncorrectParensTraitBounds {
1420 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],
1421 sugg: diagnostics::IncorrectParensTraitBoundsSugg {
1422 wrong_span: leading_token.span.shrink_to_hi().to(lo),
1423 new_span: leading_token.span.shrink_to_lo(),
1424 },
1425 });
1426 } else {
1427 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1428 }
1429 }
1430
1431 let poly_trait =
1432 PolyTraitRef::new(bound_vars, path, modifiers, lo.to(self.prev_token.span), parens);
1433 Ok(GenericBound::Trait(poly_trait))
1434 }
1435
1436 fn recover_path_from_fn(&mut self) -> Option<ast::Path> {
1438 let fn_token_span = self.token.span;
1439 self.bump();
1440 let args_lo = self.token.span;
1441 let snapshot = self.create_snapshot_for_diagnostic();
1442 let mode =
1443 FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false };
1444 match self.parse_fn_decl(&mode, AllowPlus::No, RecoverReturnSign::OnlyFatArrow) {
1445 Ok(decl) => {
1446 self.dcx().emit_err(ExpectedFnPathFoundFnKeyword { fn_token_span });
1447 Some(ast::Path {
1448 span: fn_token_span.to(self.prev_token.span),
1449 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.clone()).collect(),
inputs_span: args_lo.until(decl.output.span()),
output: decl.output.clone(),
}))),
});
vec
}thin_vec![ast::PathSegment {
1450 ident: Ident::new(sym::Fn, fn_token_span),
1451 id: DUMMY_NODE_ID,
1452 args: Some(Box::new(ast::GenericArgs::Parenthesized(
1453 ast::ParenthesizedArgs {
1454 span: args_lo.to(self.prev_token.span),
1455 inputs: decl.inputs.iter().map(|a| a.clone()).collect(),
1456 inputs_span: args_lo.until(decl.output.span()),
1457 output: decl.output.clone(),
1458 }
1459 ))),
1460 }],
1461 })
1462 }
1463 Err(diag) => {
1464 diag.cancel();
1465 self.restore_snapshot(snapshot);
1466 None
1467 }
1468 }
1469 }
1470
1471 pub(super) fn parse_higher_ranked_binder(
1477 &mut self,
1478 ) -> PResult<'a, (ThinVec<GenericParam>, Option<Span>)> {
1479 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)) {
1480 let lo = self.token.span;
1481 self.expect_lt()?;
1482 let params = self.parse_generic_params()?;
1483 self.expect_gt()?;
1484 Ok((params, Some(lo.to(self.prev_token.span))))
1487 } else {
1488 Ok((ThinVec::new(), None))
1489 }
1490 }
1491
1492 fn recover_fn_trait_with_lifetime_params(
1496 &mut self,
1497 fn_path: &mut ast::Path,
1498 lifetime_defs: &mut ThinVec<GenericParam>,
1499 ) -> PResult<'a, ()> {
1500 let fn_path_segment = fn_path.segments.last_mut().unwrap();
1501 let generic_args = if let Some(p_args) = &fn_path_segment.args {
1502 *p_args.clone()
1503 } else {
1504 return Ok(());
1507 };
1508 let lifetimes =
1509 if let ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { span: _, args }) =
1510 &generic_args
1511 {
1512 args.into_iter()
1513 .filter_map(|arg| {
1514 if let ast::AngleBracketedArg::Arg(generic_arg) = arg
1515 && let ast::GenericArg::Lifetime(lifetime) = generic_arg
1516 {
1517 Some(lifetime)
1518 } else {
1519 None
1520 }
1521 })
1522 .collect()
1523 } else {
1524 Vec::new()
1525 };
1526 if lifetimes.is_empty() {
1528 return Ok(());
1529 }
1530
1531 let snapshot = if self.parsing_generics {
1532 Some(self.create_snapshot_for_diagnostic())
1535 } else {
1536 None
1537 };
1538 let inputs_lo = self.token.span;
1540 let mode =
1541 FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false };
1542 let inputs = match self.parse_fn_params(&mode) {
1543 Ok(params) => params,
1544 Err(err) => {
1545 if let Some(snapshot) = snapshot {
1546 self.restore_snapshot(snapshot);
1547 err.cancel();
1548 return Ok(());
1549 } else {
1550 return Err(err);
1551 }
1552 }
1553 };
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: ThinVec::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, kind)) = self.token.lifetime() {
1632 if kind == IdentKind::Normal && ident.without_first_quote().is_reserved_lifetime() {
1633 self.dcx().emit_err(diagnostics::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 })
1645 }
1646}