1 use crate::check::intrinsicck::InlineAsmCtxt;
3 use super::coercion::CoerceMany;
4 use super::compare_method::check_type_bounds;
5 use super::compare_method::{compare_impl_method, compare_ty_impl};
7 use rustc_attr as attr;
8 use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan};
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::{DefId, LocalDefId};
12 use rustc_hir::intravisit::Visitor;
13 use rustc_hir::lang_items::LangItem;
14 use rustc_hir::{ItemKind, Node, PathSegment};
15 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
16 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
17 use rustc_infer::infer::{DefiningAnchor, RegionVariableOrigin, TyCtxtInferExt};
18 use rustc_infer::traits::Obligation;
19 use rustc_lint::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS;
20 use rustc_middle::hir::nested_filter;
21 use rustc_middle::middle::stability::EvalResult;
22 use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
23 use rustc_middle::ty::subst::GenericArgKind;
24 use rustc_middle::ty::util::{Discr, IntTypeExt};
25 use rustc_middle::ty::{
26 self, ParamEnv, ToPredicate, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
28 use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
29 use rustc_span::symbol::sym;
30 use rustc_span::{self, Span};
31 use rustc_target::spec::abi::Abi;
32 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
33 use rustc_trait_selection::traits::{self, ObligationCtxt};
35 use std::ops::ControlFlow;
37 pub(super) fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
38 match tcx.sess.target.is_abi_supported(abi) {
45 "`{abi}` is not a supported ABI for the current target",
50 tcx.struct_span_lint_hir(
51 UNSUPPORTED_CALLING_CONVENTIONS,
54 "use of calling convention not supported on this target",
60 // This ABI is only allowed on function pointers
61 if abi == Abi::CCmseNonSecureCall {
66 "the `\"C-cmse-nonsecure-call\"` ABI is only allowed on function pointers"
72 /// Helper used for fns and closures. Does the grungy work of checking a function
73 /// body and returns the function context used for that purpose, since in the case of a fn item
74 /// there is still a bit more to do.
77 /// * inherited: other fields inherited from the enclosing fn (if any)
78 #[instrument(skip(inherited, body), level = "debug")]
79 pub(super) fn check_fn<'a, 'tcx>(
80 inherited: &'a Inherited<'tcx>,
81 param_env: ty::ParamEnv<'tcx>,
82 fn_sig: ty::FnSig<'tcx>,
83 decl: &'tcx hir::FnDecl<'tcx>,
85 body: &'tcx hir::Body<'tcx>,
86 can_be_generator: Option<hir::Movability>,
87 return_type_pre_known: bool,
88 ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) {
89 // Create the function context. This is either derived from scratch or,
90 // in the case of closures, based on the outer context.
91 let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id);
92 fcx.ps.set(UnsafetyState::function(fn_sig.unsafety, fn_id));
93 fcx.return_type_pre_known = return_type_pre_known;
98 let declared_ret_ty = fn_sig.output();
101 fcx.register_infer_ok_obligations(fcx.infcx.replace_opaque_types_with_inference_vars(
107 // If we replaced declared_ret_ty with infer vars, then we must be inferring
108 // an opaque type, so set a flag so we can improve diagnostics.
109 fcx.return_type_has_opaque = ret_ty != declared_ret_ty;
111 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
113 let span = body.value.span;
115 fn_maybe_err(tcx, span, fn_sig.abi);
117 if fn_sig.abi == Abi::RustCall {
118 let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 };
121 let item = match tcx.hir().get(fn_id) {
122 Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header),
123 Node::ImplItem(hir::ImplItem {
124 kind: hir::ImplItemKind::Fn(header, ..), ..
126 Node::TraitItem(hir::TraitItem {
127 kind: hir::TraitItemKind::Fn(header, ..),
130 // Closures are RustCall, but they tuple their arguments, so shouldn't be checked
131 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => None,
132 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
135 if let Some(header) = item {
136 tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple");
140 if fn_sig.inputs().len() != expected_args {
143 // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on
144 // This will probably require wide-scale changes to support a TupleKind obligation
145 // We can't resolve this without knowing the type of the param
146 if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) {
152 if body.generator_kind.is_some() && can_be_generator.is_some() {
154 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
155 fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
157 // Resume type defaults to `()` if the generator has no argument.
158 let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
160 fcx.resume_yield_tys = Some((resume_ty, yield_ty));
163 GatherLocalsVisitor::new(&fcx).visit_body(body);
165 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
166 // (as it's created inside the body itself, not passed in from outside).
167 let maybe_va_list = if fn_sig.c_variadic {
168 let span = body.params.last().unwrap().span;
169 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
170 let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
172 Some(tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()]))
177 // Add formal parameters.
178 let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
179 let inputs_fn = fn_sig.inputs().iter().copied();
180 for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
181 // Check the pattern.
182 let ty_span = try { inputs_hir?.get(idx)?.span };
183 fcx.check_pat_top(¶m.pat, param_ty, ty_span, false);
185 // Check that argument is Sized.
186 // The check for a non-trivial pattern is a hack to avoid duplicate warnings
187 // for simple cases like `fn foo(x: Trait)`,
188 // where we would error once on the parameter as a whole, and once on the binding `x`.
189 if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
190 fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
193 fcx.write_ty(param.hir_id, param_ty);
196 inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
198 fcx.in_tail_expr = true;
199 if let ty::Dynamic(..) = declared_ret_ty.kind() {
200 // FIXME: We need to verify that the return type is `Sized` after the return expression has
201 // been evaluated so that we have types available for all the nodes being returned, but that
202 // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
203 // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
204 // while keeping the current ordering we will ignore the tail expression's type because we
205 // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
206 // because we will trigger "unreachable expression" lints unconditionally.
207 // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
208 // case that a newcomer might make, returning a bare trait, and in that case we populate
209 // the tail expression's type so that the suggestion will be correct, but ignore all other
211 fcx.check_expr(&body.value);
212 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
214 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
215 fcx.check_return_expr(&body.value, false);
217 fcx.in_tail_expr = false;
219 // We insert the deferred_generator_interiors entry after visiting the body.
220 // This ensures that all nested generators appear before the entry of this generator.
221 // resolve_generator_interiors relies on this property.
222 let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
224 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
225 fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
227 let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
228 Some(GeneratorTypes {
232 movability: can_be_generator.unwrap(),
238 // Finalize the return check by taking the LUB of the return types
239 // we saw and assigning it to the expected return type. This isn't
240 // really expected to fail, since the coercions would have failed
241 // earlier when trying to find a LUB.
242 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
243 let mut actual_return_ty = coercion.complete(&fcx);
244 debug!("actual_return_ty = {:?}", actual_return_ty);
245 if let ty::Dynamic(..) = declared_ret_ty.kind() {
246 // We have special-cased the case where the function is declared
247 // `-> dyn Foo` and we don't actually relate it to the
248 // `fcx.ret_coercion`, so just substitute a type variable.
250 fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::DynReturnFn, span });
251 debug!("actual_return_ty replaced with {:?}", actual_return_ty);
254 // HACK(oli-obk, compiler-errors): We should be comparing this against
255 // `declared_ret_ty`, but then anything uninferred would be inferred to
256 // the opaque type itself. That again would cause writeback to assume
257 // we have a recursive call site and do the sadly stabilized fallback to `()`.
258 fcx.demand_suptype(span, ret_ty, actual_return_ty);
260 // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
261 if let Some(panic_impl_did) = tcx.lang_items().panic_impl()
262 && panic_impl_did == hir.local_def_id(fn_id).to_def_id()
264 check_panic_info_fn(tcx, panic_impl_did.expect_local(), fn_sig, decl, declared_ret_ty);
267 // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
268 if let Some(alloc_error_handler_did) = tcx.lang_items().oom()
269 && alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id()
271 check_alloc_error_fn(tcx, alloc_error_handler_did.expect_local(), fn_sig, decl, declared_ret_ty);
277 fn check_panic_info_fn(
280 fn_sig: ty::FnSig<'_>,
281 decl: &hir::FnDecl<'_>,
282 declared_ret_ty: Ty<'_>,
284 let Some(panic_info_did) = tcx.lang_items().panic_info() else {
285 tcx.sess.err("language item required, but not found: `panic_info`");
289 if *declared_ret_ty.kind() != ty::Never {
290 tcx.sess.span_err(decl.output.span(), "return type should be `!`");
293 let inputs = fn_sig.inputs();
294 if inputs.len() != 1 {
295 tcx.sess.span_err(tcx.def_span(fn_id), "function should have one argument");
299 let arg_is_panic_info = match *inputs[0].kind() {
300 ty::Ref(region, ty, mutbl) => match *ty.kind() {
301 ty::Adt(ref adt, _) => {
302 adt.did() == panic_info_did && mutbl == hir::Mutability::Not && !region.is_static()
309 if !arg_is_panic_info {
310 tcx.sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
313 let DefKind::Fn = tcx.def_kind(fn_id) else {
314 let span = tcx.def_span(fn_id);
315 tcx.sess.span_err(span, "should be a function");
319 let generic_counts = tcx.generics_of(fn_id).own_counts();
320 if generic_counts.types != 0 {
321 let span = tcx.def_span(fn_id);
322 tcx.sess.span_err(span, "should have no type parameters");
324 if generic_counts.consts != 0 {
325 let span = tcx.def_span(fn_id);
326 tcx.sess.span_err(span, "should have no const parameters");
330 fn check_alloc_error_fn(
333 fn_sig: ty::FnSig<'_>,
334 decl: &hir::FnDecl<'_>,
335 declared_ret_ty: Ty<'_>,
337 let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() else {
338 tcx.sess.err("language item required, but not found: `alloc_layout`");
342 if *declared_ret_ty.kind() != ty::Never {
343 tcx.sess.span_err(decl.output.span(), "return type should be `!`");
346 let inputs = fn_sig.inputs();
347 if inputs.len() != 1 {
348 tcx.sess.span_err(tcx.def_span(fn_id), "function should have one argument");
352 let arg_is_alloc_layout = match inputs[0].kind() {
353 ty::Adt(ref adt, _) => adt.did() == alloc_layout_did,
357 if !arg_is_alloc_layout {
358 tcx.sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
361 let DefKind::Fn = tcx.def_kind(fn_id) else {
362 let span = tcx.def_span(fn_id);
363 tcx.sess.span_err(span, "`#[alloc_error_handler]` should be a function");
367 let generic_counts = tcx.generics_of(fn_id).own_counts();
368 if generic_counts.types != 0 {
369 let span = tcx.def_span(fn_id);
370 tcx.sess.span_err(span, "`#[alloc_error_handler]` function should have no type parameters");
372 if generic_counts.consts != 0 {
373 let span = tcx.def_span(fn_id);
375 .span_err(span, "`#[alloc_error_handler]` function should have no const parameters");
379 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) {
380 let def = tcx.adt_def(def_id);
381 let span = tcx.def_span(def_id);
382 def.destructor(tcx); // force the destructor to be evaluated
383 let _ = tcx.representability(def_id);
385 if def.repr().simd() {
386 check_simd(tcx, span, def_id);
389 check_transparent(tcx, span, def);
390 check_packed(tcx, span, def);
393 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) {
394 let def = tcx.adt_def(def_id);
395 let span = tcx.def_span(def_id);
396 def.destructor(tcx); // force the destructor to be evaluated
397 let _ = tcx.representability(def_id);
398 check_transparent(tcx, span, def);
399 check_union_fields(tcx, span, def_id);
400 check_packed(tcx, span, def);
403 /// Check that the fields of the `union` do not need dropping.
404 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
405 let item_type = tcx.type_of(item_def_id);
406 if let ty::Adt(def, substs) = item_type.kind() {
407 assert!(def.is_union());
409 fn allowed_union_field<'tcx>(
412 param_env: ty::ParamEnv<'tcx>,
415 // We don't just accept all !needs_drop fields, due to semver concerns.
417 ty::Ref(..) => true, // references never drop (even mutable refs, which are non-Copy and hence fail the later check)
419 // allow tuples of allowed types
420 tys.iter().all(|ty| allowed_union_field(ty, tcx, param_env, span))
422 ty::Array(elem, _len) => {
423 // Like `Copy`, we do *not* special-case length 0.
424 allowed_union_field(*elem, tcx, param_env, span)
427 // Fallback case: allow `ManuallyDrop` and things that are `Copy`.
428 ty.ty_adt_def().is_some_and(|adt_def| adt_def.is_manually_drop())
429 || ty.is_copy_modulo_regions(tcx.at(span), param_env)
434 let param_env = tcx.param_env(item_def_id);
435 for field in &def.non_enum_variant().fields {
436 let field_ty = field.ty(tcx, substs);
438 if !allowed_union_field(field_ty, tcx, param_env, span) {
439 let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
440 // We are currently checking the type this field came from, so it must be local.
441 Some(Node::Field(field)) => (field.span, field.ty.span),
442 _ => unreachable!("mir field has to correspond to hir field"),
448 "unions cannot contain fields that may need dropping"
451 "a type is guaranteed not to need dropping \
452 when it implements `Copy`, or when it is the special `ManuallyDrop<_>` type",
454 .multipart_suggestion_verbose(
455 "when the type does not implement `Copy`, \
456 wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped",
458 (ty_span.shrink_to_lo(), "std::mem::ManuallyDrop<".into()),
459 (ty_span.shrink_to_hi(), ">".into()),
461 Applicability::MaybeIncorrect,
465 } else if field_ty.needs_drop(tcx, param_env) {
466 // This should never happen. But we can get here e.g. in case of name resolution errors.
467 tcx.sess.delay_span_bug(span, "we should never accept maybe-dropping union fields");
471 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
476 /// Check that a `static` is inhabited.
477 fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
478 // Make sure statics are inhabited.
479 // Other parts of the compiler assume that there are no uninhabited places. In principle it
480 // would be enough to check this for `extern` statics, as statics with an initializer will
481 // have UB during initialization if they are uninhabited, but there also seems to be no good
482 // reason to allow any statics to be uninhabited.
483 let ty = tcx.type_of(def_id);
484 let span = tcx.def_span(def_id);
485 let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
487 // Foreign statics that overflow their allowed size should emit an error
488 Err(LayoutError::SizeOverflow(_))
490 let node = tcx.hir().get_by_def_id(def_id);
493 hir::Node::ForeignItem(hir::ForeignItem {
494 kind: hir::ForeignItemKind::Static(..),
501 .struct_span_err(span, "extern static is too large for the current architecture")
505 // Generic statics are rejected, but we still reach this case.
507 tcx.sess.delay_span_bug(span, &e.to_string());
511 if layout.abi.is_uninhabited() {
512 tcx.struct_span_lint_hir(
514 tcx.hir().local_def_id_to_hir_id(def_id),
516 "static of uninhabited type",
519 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
525 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
526 /// projections that would result in "inheriting lifetimes".
527 pub(super) fn check_opaque<'tcx>(
530 substs: SubstsRef<'tcx>,
531 origin: &hir::OpaqueTyOrigin,
533 let span = tcx.def_span(def_id);
534 check_opaque_for_inheriting_lifetimes(tcx, def_id, span);
535 if tcx.type_of(def_id).references_error() {
538 if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() {
541 check_opaque_meets_bounds(tcx, def_id, substs, span, origin);
544 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
545 /// in "inheriting lifetimes".
546 #[instrument(level = "debug", skip(tcx, span))]
547 pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>(
552 let item = tcx.hir().expect_item(def_id);
553 debug!(?item, ?span);
555 struct FoundParentLifetime;
556 struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
557 impl<'tcx> ty::visit::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
558 type BreakTy = FoundParentLifetime;
560 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
561 debug!("FindParentLifetimeVisitor: r={:?}", r);
562 if let ty::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = *r {
563 if index < self.0.parent_count as u32 {
564 return ControlFlow::Break(FoundParentLifetime);
566 return ControlFlow::CONTINUE;
570 r.super_visit_with(self)
573 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
574 if let ty::ConstKind::Unevaluated(..) = c.kind() {
575 // FIXME(#72219) We currently don't detect lifetimes within substs
576 // which would violate this check. Even though the particular substitution is not used
577 // within the const, this should still be fixed.
578 return ControlFlow::CONTINUE;
580 c.super_visit_with(self)
584 struct ProhibitOpaqueVisitor<'tcx> {
586 opaque_identity_ty: Ty<'tcx>,
587 generics: &'tcx ty::Generics,
588 selftys: Vec<(Span, Option<String>)>,
591 impl<'tcx> ty::visit::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
592 type BreakTy = Ty<'tcx>;
594 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
595 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
596 if t == self.opaque_identity_ty {
597 ControlFlow::CONTINUE
599 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
600 .map_break(|FoundParentLifetime| t)
605 impl<'tcx> Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
606 type NestedFilter = nested_filter::OnlyBodies;
608 fn nested_visit_map(&mut self) -> Self::Map {
612 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
614 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
615 [PathSegment { res: Res::SelfTyParam { .. }, .. }] => {
616 let impl_ty_name = None;
617 self.selftys.push((path.span, impl_ty_name));
619 [PathSegment { res: Res::SelfTyAlias { alias_to: def_id, .. }, .. }] => {
620 let impl_ty_name = Some(self.tcx.def_path_str(*def_id));
621 self.selftys.push((path.span, impl_ty_name));
627 hir::intravisit::walk_ty(self, arg);
631 if let ItemKind::OpaqueTy(hir::OpaqueTy {
632 origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..),
636 let mut visitor = ProhibitOpaqueVisitor {
637 opaque_identity_ty: tcx.mk_opaque(
639 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
641 generics: tcx.generics_of(def_id),
645 let prohibit_opaque = tcx
646 .explicit_item_bounds(def_id)
648 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
650 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
651 prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
654 if let Some(ty) = prohibit_opaque.break_value() {
655 visitor.visit_item(&item);
656 let is_async = match item.kind {
657 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
658 matches!(origin, hir::OpaqueTyOrigin::AsyncFn(..))
663 let mut err = struct_span_err!(
667 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
669 if is_async { "async fn" } else { "impl Trait" },
672 for (span, name) in visitor.selftys {
675 "consider spelling out the type instead",
676 name.unwrap_or_else(|| format!("{:?}", ty)),
677 Applicability::MaybeIncorrect,
685 /// Checks that an opaque type does not contain cycles.
686 pub(super) fn check_opaque_for_cycles<'tcx>(
689 substs: SubstsRef<'tcx>,
691 origin: &hir::OpaqueTyOrigin,
692 ) -> Result<(), ErrorGuaranteed> {
693 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() {
694 let reported = match origin {
695 hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span),
696 _ => opaque_type_cycle_error(tcx, def_id, span),
704 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
706 /// This is mostly checked at the places that specify the opaque type, but we
707 /// check those cases in the `param_env` of that function, which may have
708 /// bounds not on this opaque type:
710 /// type X<T> = impl Clone
711 /// fn f<T: Clone>(t: T) -> X<T> {
715 /// Without this check the above code is incorrectly accepted: we would ICE if
716 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
717 #[instrument(level = "debug", skip(tcx))]
718 fn check_opaque_meets_bounds<'tcx>(
721 substs: SubstsRef<'tcx>,
723 origin: &hir::OpaqueTyOrigin,
725 let hidden_type = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs);
727 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
728 let defining_use_anchor = match *origin {
729 hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
730 hir::OpaqueTyOrigin::TyAlias => def_id,
732 let param_env = tcx.param_env(defining_use_anchor);
736 .with_opaque_type_inference(DefiningAnchor::Bind(defining_use_anchor))
738 let ocx = ObligationCtxt::new(&infcx);
739 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
741 let misc_cause = traits::ObligationCause::misc(span, hir_id);
743 match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_type) {
744 Ok(infer_ok) => ocx.register_infer_ok_obligations(infer_ok),
746 tcx.sess.delay_span_bug(
748 &format!("could not unify `{hidden_type}` with revealed type:\n{ty_err}"),
753 // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
754 // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
755 // hidden type is well formed even without those bounds.
757 ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_type.into())).to_predicate(tcx);
758 ocx.register_obligation(Obligation::new(misc_cause, param_env, predicate));
760 // Check that all obligations are satisfied by the implementation's
762 let errors = ocx.select_all_or_error();
763 if !errors.is_empty() {
764 infcx.err_ctxt().report_fulfillment_errors(&errors, None, false);
767 // Checked when type checking the function containing them.
768 hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {}
769 // Can have different predicates to their defining use
770 hir::OpaqueTyOrigin::TyAlias => {
771 let outlives_environment = OutlivesEnvironment::new(param_env);
772 infcx.check_region_obligations_and_report_errors(
774 &outlives_environment,
778 // Clean up after ourselves
779 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
782 fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) {
784 "check_item_type(it.def_id={:?}, it.name={})",
786 tcx.def_path_str(id.def_id.to_def_id())
788 let _indenter = indenter();
789 match tcx.def_kind(id.def_id) {
790 DefKind::Static(..) => {
791 tcx.ensure().typeck(id.def_id.def_id);
792 maybe_check_static_with_link_section(tcx, id.def_id.def_id);
793 check_static_inhabited(tcx, id.def_id.def_id);
796 tcx.ensure().typeck(id.def_id.def_id);
799 let item = tcx.hir().item(id);
800 let hir::ItemKind::Enum(ref enum_definition, _) = item.kind else {
803 check_enum(tcx, &enum_definition.variants, item.def_id.def_id);
805 DefKind::Fn => {} // entirely within check_item_body
807 let it = tcx.hir().item(id);
808 let hir::ItemKind::Impl(ref impl_) = it.kind else {
811 debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
812 if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
813 check_impl_items_against_trait(
820 check_on_unimplemented(tcx, it);
824 let it = tcx.hir().item(id);
825 let hir::ItemKind::Trait(_, _, _, _, ref items) = it.kind else {
828 check_on_unimplemented(tcx, it);
830 for item in items.iter() {
831 let item = tcx.hir().trait_item(item.id);
833 hir::TraitItemKind::Fn(ref sig, _) => {
834 let abi = sig.header.abi;
835 fn_maybe_err(tcx, item.ident.span, abi);
837 hir::TraitItemKind::Type(.., Some(default)) => {
838 let assoc_item = tcx.associated_item(item.def_id);
840 InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
841 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
846 ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
854 check_struct(tcx, id.def_id.def_id);
857 check_union(tcx, id.def_id.def_id);
859 DefKind::OpaqueTy => {
860 let item = tcx.hir().item(id);
861 let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item.kind else {
864 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
865 // `async-std` (and `pub async fn` in general).
866 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
867 // See https://github.com/rust-lang/rust/issues/75100
868 if !tcx.sess.opts.actually_rustdoc {
869 let substs = InternalSubsts::identity_for_item(tcx, item.def_id.to_def_id());
870 check_opaque(tcx, item.def_id.def_id, substs, &origin);
873 DefKind::TyAlias => {
874 let pty_ty = tcx.type_of(id.def_id);
875 let generics = tcx.generics_of(id.def_id);
876 check_type_params_are_used(tcx, &generics, pty_ty);
878 DefKind::ForeignMod => {
879 let it = tcx.hir().item(id);
880 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
883 check_abi(tcx, it.hir_id(), it.span, abi);
885 if abi == Abi::RustIntrinsic {
887 let item = tcx.hir().foreign_item(item.id);
888 intrinsic::check_intrinsic_type(tcx, item);
890 } else if abi == Abi::PlatformIntrinsic {
892 let item = tcx.hir().foreign_item(item.id);
893 intrinsic::check_platform_intrinsic_type(tcx, item);
897 let def_id = item.id.def_id.def_id;
898 let generics = tcx.generics_of(def_id);
899 let own_counts = generics.own_counts();
900 if generics.params.len() - own_counts.lifetimes != 0 {
901 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
902 (_, 0) => ("type", "types", Some("u32")),
903 // We don't specify an example value, because we can't generate
904 // a valid value for any type.
905 (0, _) => ("const", "consts", None),
906 _ => ("type or const", "types or consts", None),
912 "foreign items may not have {kinds} parameters",
914 .span_label(item.span, &format!("can't have {kinds} parameters"))
916 // FIXME: once we start storing spans for type arguments, turn this
917 // into a suggestion.
919 "replace the {} parameters with concrete {}{}",
922 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
928 let item = tcx.hir().foreign_item(item.id);
930 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
931 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
933 hir::ForeignItemKind::Static(..) => {
934 check_static_inhabited(tcx, def_id);
941 DefKind::GlobalAsm => {
942 let it = tcx.hir().item(id);
943 let hir::ItemKind::GlobalAsm(asm) = it.kind else { span_bug!(it.span, "DefKind::GlobalAsm but got {:#?}", it) };
944 InlineAsmCtxt::new_global_asm(tcx).check_asm(asm, id.hir_id());
950 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
951 // an error would be reported if this fails.
952 let _ = traits::OnUnimplementedDirective::of_item(tcx, item.def_id.to_def_id());
955 pub(super) fn check_specialization_validity<'tcx>(
957 trait_def: &ty::TraitDef,
958 trait_item: &ty::AssocItem,
960 impl_item: &hir::ImplItemRef,
962 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
963 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
964 if parent.is_from_trait() {
967 Some((parent, parent.item(tcx, trait_item.def_id)))
971 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
973 // Parent impl exists, and contains the parent item we're trying to specialize, but
974 // doesn't mark it `default`.
975 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
976 Some(Err(parent_impl.def_id()))
979 // Parent impl contains item and makes it specializable.
980 Some(_) => Some(Ok(())),
982 // Parent impl doesn't mention the item. This means it's inherited from the
983 // grandparent. In that case, if parent is a `default impl`, inherited items use the
984 // "defaultness" from the grandparent, else they are final.
986 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
989 Some(Err(parent_impl.def_id()))
995 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
996 // item. This is allowed, the item isn't actually getting specialized here.
997 let result = opt_result.unwrap_or(Ok(()));
999 if let Err(parent_impl) = result {
1000 report_forbidden_specialization(tcx, impl_item, parent_impl);
1004 fn check_impl_items_against_trait<'tcx>(
1006 full_impl_span: Span,
1007 impl_id: LocalDefId,
1008 impl_trait_ref: ty::TraitRef<'tcx>,
1009 impl_item_refs: &[hir::ImplItemRef],
1011 // If the trait reference itself is erroneous (so the compilation is going
1012 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1013 // isn't populated for such impls.
1014 if impl_trait_ref.references_error() {
1018 // Negative impls are not expected to have any items
1019 match tcx.impl_polarity(impl_id) {
1020 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
1021 ty::ImplPolarity::Negative => {
1022 if let [first_item_ref, ..] = impl_item_refs {
1023 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
1028 "negative impls cannot have any items"
1036 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
1038 for impl_item in impl_item_refs {
1039 let ty_impl_item = tcx.associated_item(impl_item.id.def_id);
1040 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
1041 tcx.associated_item(trait_item_id)
1043 // Checked in `associated_item`.
1044 tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
1047 let impl_item_full = tcx.hir().impl_item(impl_item.id);
1048 match impl_item_full.kind {
1049 hir::ImplItemKind::Const(..) => {
1050 let _ = tcx.compare_assoc_const_impl_item_with_trait_item((
1051 impl_item.id.def_id.def_id,
1052 ty_impl_item.trait_item_def_id.unwrap(),
1055 hir::ImplItemKind::Fn(..) => {
1056 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1057 compare_impl_method(
1065 hir::ImplItemKind::Type(impl_ty) => {
1066 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1078 check_specialization_validity(
1082 impl_id.to_def_id(),
1087 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1088 // Check for missing items from trait
1089 let mut missing_items = Vec::new();
1091 let mut must_implement_one_of: Option<&[Ident]> =
1092 trait_def.must_implement_one_of.as_deref();
1094 for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
1095 let is_implemented = ancestors
1096 .leaf_def(tcx, trait_item_id)
1097 .map_or(false, |node_item| node_item.item.defaultness(tcx).has_value());
1099 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1100 missing_items.push(tcx.associated_item(trait_item_id));
1103 // true if this item is specifically implemented in this impl
1104 let is_implemented_here = ancestors
1105 .leaf_def(tcx, trait_item_id)
1106 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
1108 if !is_implemented_here {
1109 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1110 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1119 // Unmarked default bodies are considered stable (at least for now).
1120 EvalResult::Allow | EvalResult::Unmarked => {}
1124 if let Some(required_items) = &must_implement_one_of {
1125 if is_implemented_here {
1126 let trait_item = tcx.associated_item(trait_item_id);
1127 if required_items.contains(&trait_item.ident(tcx)) {
1128 must_implement_one_of = None;
1134 if !missing_items.is_empty() {
1135 missing_items_err(tcx, tcx.def_span(impl_id), &missing_items, full_impl_span);
1138 if let Some(missing_items) = must_implement_one_of {
1140 .get_attr(impl_trait_ref.def_id, sym::rustc_must_implement_one_of)
1141 .map(|attr| attr.span);
1143 missing_items_must_implement_one_of_err(
1145 tcx.def_span(impl_id),
1153 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1154 let t = tcx.type_of(def_id);
1155 if let ty::Adt(def, substs) = t.kind()
1158 let fields = &def.non_enum_variant().fields;
1159 if fields.is_empty() {
1160 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1163 let e = fields[0].ty(tcx, substs);
1164 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1165 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1166 .span_label(sp, "SIMD elements must have the same type")
1171 let len = if let ty::Array(_ty, c) = e.kind() {
1172 c.try_eval_usize(tcx, tcx.param_env(def.did()))
1174 Some(fields.len() as u64)
1176 if let Some(len) = len {
1178 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1180 } else if len > MAX_SIMD_LANES {
1185 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1192 // Check that we use types valid for use in the lanes of a SIMD "vector register"
1193 // These are scalar types which directly match a "machine" type
1194 // Yes: Integers, floats, "thin" pointers
1195 // No: char, "fat" pointers, compound types
1197 ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
1198 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
1199 ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
1203 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
1205 { /* struct([f32; 4]) is ok */ }
1211 "SIMD vector element type should be a \
1212 primitive scalar (integer/float/pointer) type"
1221 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1222 let repr = def.repr();
1224 for attr in tcx.get_attrs(def.did(), sym::repr) {
1225 for r in attr::parse_repr_attr(&tcx.sess, attr) {
1226 if let attr::ReprPacked(pack) = r
1227 && let Some(repr_pack) = repr.pack
1228 && pack as u64 != repr_pack.bytes()
1234 "type has conflicting packed representation hints"
1240 if repr.align.is_some() {
1245 "type has conflicting packed and align representation hints"
1249 if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1250 let mut err = struct_span_err!(
1254 "packed type cannot transitively contain a `#[repr(align)]` type"
1258 tcx.def_span(def_spans[0].0),
1260 "`{}` has a `#[repr(align)]` attribute",
1261 tcx.item_name(def_spans[0].0)
1265 if def_spans.len() > 2 {
1266 let mut first = true;
1267 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1268 let ident = tcx.item_name(*adt_def);
1273 "`{}` contains a field of type `{}`",
1274 tcx.type_of(def.did()),
1278 format!("...which contains a field of type `{ident}`")
1291 pub(super) fn check_packed_inner(
1294 stack: &mut Vec<DefId>,
1295 ) -> Option<Vec<(DefId, Span)>> {
1296 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1297 if def.is_struct() || def.is_union() {
1298 if def.repr().align.is_some() {
1299 return Some(vec![(def.did(), DUMMY_SP)]);
1303 for field in &def.non_enum_variant().fields {
1304 if let ty::Adt(def, _) = field.ty(tcx, substs).kind()
1305 && !stack.contains(&def.did())
1306 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1308 defs.push((def.did(), field.ident(tcx).span));
1319 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: ty::AdtDef<'tcx>) {
1320 if !adt.repr().transparent() {
1324 if adt.is_union() && !tcx.features().transparent_unions {
1326 &tcx.sess.parse_sess,
1327 sym::transparent_unions,
1329 "transparent unions are unstable",
1334 if adt.variants().len() != 1 {
1335 bad_variant_count(tcx, adt, sp, adt.did());
1336 if adt.variants().is_empty() {
1337 // Don't bother checking the fields. No variants (and thus no fields) exist.
1342 // For each field, figure out if it's known to be a ZST and align(1), with "known"
1343 // respecting #[non_exhaustive] attributes.
1344 let field_infos = adt.all_fields().map(|field| {
1345 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1346 let param_env = tcx.param_env(field.did);
1347 let layout = tcx.layout_of(param_env.and(ty));
1348 // We are currently checking the type this field came from, so it must be local
1349 let span = tcx.hir().span_if_local(field.did).unwrap();
1350 let zst = layout.map_or(false, |layout| layout.is_zst());
1351 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1353 return (span, zst, align1, None);
1356 fn check_non_exhaustive<'tcx>(
1359 ) -> ControlFlow<(&'static str, DefId, SubstsRef<'tcx>, bool)> {
1361 ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)),
1362 ty::Array(ty, _) => check_non_exhaustive(tcx, *ty),
1363 ty::Adt(def, subst) => {
1364 if !def.did().is_local() {
1365 let non_exhaustive = def.is_variant_list_non_exhaustive()
1369 .any(ty::VariantDef::is_field_list_non_exhaustive);
1370 let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1371 if non_exhaustive || has_priv {
1372 return ControlFlow::Break((
1381 .map(|field| field.ty(tcx, subst))
1382 .try_for_each(|t| check_non_exhaustive(tcx, t))
1384 _ => ControlFlow::Continue(()),
1388 (span, zst, align1, check_non_exhaustive(tcx, ty).break_value())
1391 let non_zst_fields = field_infos
1393 .filter_map(|(span, zst, _align1, _non_exhaustive)| if !zst { Some(span) } else { None });
1394 let non_zst_count = non_zst_fields.clone().count();
1395 if non_zst_count >= 2 {
1396 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1398 let incompatible_zst_fields =
1399 field_infos.clone().filter(|(_, _, _, opt)| opt.is_some()).count();
1400 let incompat = incompatible_zst_fields + non_zst_count >= 2 && non_zst_count < 2;
1401 for (span, zst, align1, non_exhaustive) in field_infos {
1407 "zero-sized field in transparent {} has alignment larger than 1",
1410 .span_label(span, "has alignment larger than 1")
1413 if incompat && let Some((descr, def_id, substs, non_exhaustive)) = non_exhaustive {
1414 tcx.struct_span_lint_hir(
1415 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS,
1416 tcx.hir().local_def_id_to_hir_id(adt.did().expect_local()),
1418 "zero-sized fields in `repr(transparent)` cannot contain external non-exhaustive types",
1420 let note = if non_exhaustive {
1421 "is marked with `#[non_exhaustive]`"
1423 "contains private fields"
1425 let field_ty = tcx.def_path_str_with_substs(def_id, substs);
1427 .note(format!("this {descr} contains `{field_ty}`, which {note}, \
1428 and makes it not a breaking change to become non-zero-sized in the future."))
1435 #[allow(trivial_numeric_casts)]
1436 fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, vs: &'tcx [hir::Variant<'tcx>], def_id: LocalDefId) {
1437 let def = tcx.adt_def(def_id);
1438 let sp = tcx.def_span(def_id);
1439 def.destructor(tcx); // force the destructor to be evaluated
1442 if let Some(attr) = tcx.get_attrs(def_id.to_def_id(), sym::repr).next() {
1447 "unsupported representation for zero-variant enum"
1449 .span_label(sp, "zero-variant enum")
1454 let repr_type_ty = def.repr().discr_type().to_ty(tcx);
1455 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1456 if !tcx.features().repr128 {
1458 &tcx.sess.parse_sess,
1461 "repr with 128-bit type is unstable",
1468 if let Some(ref e) = v.disr_expr {
1469 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1473 if tcx.adt_def(def_id).repr().int.is_none() && tcx.features().arbitrary_enum_discriminant {
1474 let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1476 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1477 let has_non_units = vs.iter().any(|var| !is_unit(var));
1478 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1479 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1481 if disr_non_unit || (disr_units && has_non_units) {
1483 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1488 detect_discriminant_duplicate(tcx, def.discriminants(tcx).collect(), vs, sp);
1490 let _ = tcx.representability(def_id);
1491 check_transparent(tcx, sp, def);
1494 /// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1495 fn detect_discriminant_duplicate<'tcx>(
1497 mut discrs: Vec<(VariantIdx, Discr<'tcx>)>,
1498 vs: &'tcx [hir::Variant<'tcx>],
1501 // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1502 // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1503 let report = |dis: Discr<'tcx>, idx: usize, err: &mut Diagnostic| {
1504 let var = &vs[idx]; // HIR for the duplicate discriminant
1505 let (span, display_discr) = match var.disr_expr {
1507 // In the case the discriminant is both a duplicate and overflowed, let the user know
1508 if let hir::ExprKind::Lit(lit) = &tcx.hir().body(expr.body).value.kind
1509 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1510 && *lit_value != dis.val
1512 (tcx.hir().span(expr.hir_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1513 // Otherwise, format the value as-is
1515 (tcx.hir().span(expr.hir_id), format!("`{dis}`"))
1519 // At this point we know this discriminant is a duplicate, and was not explicitly
1520 // assigned by the user. Here we iterate backwards to fetch the HIR for the last
1521 // explicitly assigned discriminant, and letting the user know that this was the
1522 // increment startpoint, and how many steps from there leading to the duplicate
1523 if let Some((n, hir::Variant { span, ident, .. })) =
1524 vs[..idx].iter().rev().enumerate().find(|v| v.1.disr_expr.is_some())
1526 let ve_ident = var.ident;
1528 let sp = if n > 1 { "variants" } else { "variant" };
1532 format!("discriminant for `{ve_ident}` incremented from this startpoint (`{ident}` + {n} {sp} later => `{ve_ident}` = {dis})"),
1536 (vs[idx].span, format!("`{dis}`"))
1540 err.span_label(span, format!("{display_discr} assigned here"));
1543 // Here we loop through the discriminants, comparing each discriminant to another.
1544 // When a duplicate is detected, we instantiate an error and point to both
1545 // initial and duplicate value. The duplicate discriminant is then discarded by swapping
1546 // it with the last element and decrementing the `vec.len` (which is why we have to evaluate
1547 // `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
1548 // style as we are mutating `discrs` on the fly).
1550 while i < discrs.len() {
1551 let hir_var_i_idx = discrs[i].0.index();
1552 let mut error: Option<DiagnosticBuilder<'_, _>> = None;
1555 while o < discrs.len() {
1556 let hir_var_o_idx = discrs[o].0.index();
1558 if discrs[i].1.val == discrs[o].1.val {
1559 let err = error.get_or_insert_with(|| {
1560 let mut ret = struct_span_err!(
1564 "discriminant value `{}` assigned more than once",
1568 report(discrs[i].1, hir_var_i_idx, &mut ret);
1573 report(discrs[o].1, hir_var_o_idx, err);
1575 // Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
1576 discrs[o] = *discrs.last().unwrap();
1583 if let Some(mut e) = error {
1591 pub(super) fn check_type_params_are_used<'tcx>(
1593 generics: &ty::Generics,
1596 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1598 assert_eq!(generics.parent, None);
1600 if generics.own_counts().types == 0 {
1604 let mut params_used = BitSet::new_empty(generics.params.len());
1606 if ty.references_error() {
1607 // If there is already another error, do not emit
1608 // an error for not using a type parameter.
1609 assert!(tcx.sess.has_errors().is_some());
1613 for leaf in ty.walk() {
1614 if let GenericArgKind::Type(leaf_ty) = leaf.unpack()
1615 && let ty::Param(param) = leaf_ty.kind()
1617 debug!("found use of ty param {:?}", param);
1618 params_used.insert(param.index);
1622 for param in &generics.params {
1623 if !params_used.contains(param.index)
1624 && let ty::GenericParamDefKind::Type { .. } = param.kind
1626 let span = tcx.def_span(param.def_id);
1631 "type parameter `{}` is unused",
1634 .span_label(span, "unused type parameter")
1640 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1641 let module = tcx.hir_module_items(module_def_id);
1642 for id in module.items() {
1643 check_item_type(tcx, id);
1647 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) -> ErrorGuaranteed {
1648 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1649 .span_label(span, "recursive `async fn`")
1650 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1652 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1657 /// Emit an error for recursive opaque types.
1659 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1660 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1663 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1664 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1665 fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) -> ErrorGuaranteed {
1666 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1668 let mut label = false;
1669 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1670 let typeck_results = tcx.typeck(def_id);
1674 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1675 .all(|ty| matches!(ty.kind(), ty::Never))
1680 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1681 .map(|expr| expr.span)
1682 .collect::<Vec<Span>>();
1683 let span_len = spans.len();
1685 err.span_label(spans[0], "this returned value is of `!` type");
1687 let mut multispan: MultiSpan = spans.clone().into();
1689 multispan.push_span_label(span, "this returned value is of `!` type");
1691 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1693 err.help("this error will resolve once the item's body returns a concrete type");
1695 let mut seen = FxHashSet::default();
1697 err.span_label(span, "recursive opaque type");
1699 for (sp, ty) in visitor
1702 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1703 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1705 struct OpaqueTypeCollector(Vec<DefId>);
1706 impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypeCollector {
1707 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1709 ty::Opaque(def, _) => {
1711 ControlFlow::CONTINUE
1713 _ => t.super_visit_with(self),
1717 let mut visitor = OpaqueTypeCollector(vec![]);
1718 ty.visit_with(&mut visitor);
1719 for def_id in visitor.0 {
1720 let ty_span = tcx.def_span(def_id);
1721 if !seen.contains(&ty_span) {
1722 err.span_label(ty_span, &format!("returning this opaque type `{ty}`"));
1723 seen.insert(ty_span);
1725 err.span_label(sp, &format!("returning here with type `{ty}`"));
1731 err.span_label(span, "cannot resolve opaque type");