1 use crate::check::intrinsicck::InlineAsmCtxt;
3 use super::compare_method::check_type_bounds;
4 use super::compare_method::{compare_impl_method, compare_ty_impl};
6 use rustc_attr as attr;
7 use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan};
9 use rustc_hir::def::{CtorKind, DefKind, Res};
10 use rustc_hir::def_id::{DefId, LocalDefId};
11 use rustc_hir::intravisit::Visitor;
12 use rustc_hir::{ItemKind, Node, PathSegment};
13 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
14 use rustc_infer::infer::{DefiningAnchor, RegionVariableOrigin, TyCtxtInferExt};
15 use rustc_infer::traits::Obligation;
16 use rustc_lint::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS;
17 use rustc_middle::hir::nested_filter;
18 use rustc_middle::middle::stability::EvalResult;
19 use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
20 use rustc_middle::ty::subst::GenericArgKind;
21 use rustc_middle::ty::util::{Discr, IntTypeExt};
22 use rustc_middle::ty::{
23 self, ParamEnv, ToPredicate, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
25 use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
26 use rustc_span::symbol::sym;
27 use rustc_span::{self, Span};
28 use rustc_target::spec::abi::Abi;
29 use rustc_trait_selection::traits::error_reporting::on_unimplemented::OnUnimplementedDirective;
30 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
31 use rustc_trait_selection::traits::{self, ObligationCtxt};
33 use std::ops::ControlFlow;
35 pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
36 match tcx.sess.target.is_abi_supported(abi) {
43 "`{abi}` is not a supported ABI for the current target",
48 tcx.struct_span_lint_hir(
49 UNSUPPORTED_CALLING_CONVENTIONS,
52 "use of calling convention not supported on this target",
58 // This ABI is only allowed on function pointers
59 if abi == Abi::CCmseNonSecureCall {
64 "the `\"C-cmse-nonsecure-call\"` ABI is only allowed on function pointers"
70 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) {
71 let def = tcx.adt_def(def_id);
72 let span = tcx.def_span(def_id);
73 def.destructor(tcx); // force the destructor to be evaluated
75 if def.repr().simd() {
76 check_simd(tcx, span, def_id);
79 check_transparent(tcx, def);
80 check_packed(tcx, span, def);
83 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) {
84 let def = tcx.adt_def(def_id);
85 let span = tcx.def_span(def_id);
86 def.destructor(tcx); // force the destructor to be evaluated
87 check_transparent(tcx, def);
88 check_union_fields(tcx, span, def_id);
89 check_packed(tcx, span, def);
92 /// Check that the fields of the `union` do not need dropping.
93 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
94 let item_type = tcx.type_of(item_def_id);
95 if let ty::Adt(def, substs) = item_type.kind() {
96 assert!(def.is_union());
98 fn allowed_union_field<'tcx>(
101 param_env: ty::ParamEnv<'tcx>,
104 // We don't just accept all !needs_drop fields, due to semver concerns.
106 ty::Ref(..) => true, // references never drop (even mutable refs, which are non-Copy and hence fail the later check)
108 // allow tuples of allowed types
109 tys.iter().all(|ty| allowed_union_field(ty, tcx, param_env, span))
111 ty::Array(elem, _len) => {
112 // Like `Copy`, we do *not* special-case length 0.
113 allowed_union_field(*elem, tcx, param_env, span)
116 // Fallback case: allow `ManuallyDrop` and things that are `Copy`.
117 ty.ty_adt_def().is_some_and(|adt_def| adt_def.is_manually_drop())
118 || ty.is_copy_modulo_regions(tcx, param_env)
123 let param_env = tcx.param_env(item_def_id);
124 for field in &def.non_enum_variant().fields {
125 let field_ty = field.ty(tcx, substs);
127 if !allowed_union_field(field_ty, tcx, param_env, span) {
128 let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
129 // We are currently checking the type this field came from, so it must be local.
130 Some(Node::Field(field)) => (field.span, field.ty.span),
131 _ => unreachable!("mir field has to correspond to hir field"),
137 "unions cannot contain fields that may need dropping"
140 "a type is guaranteed not to need dropping \
141 when it implements `Copy`, or when it is the special `ManuallyDrop<_>` type",
143 .multipart_suggestion_verbose(
144 "when the type does not implement `Copy`, \
145 wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped",
147 (ty_span.shrink_to_lo(), "std::mem::ManuallyDrop<".into()),
148 (ty_span.shrink_to_hi(), ">".into()),
150 Applicability::MaybeIncorrect,
154 } else if field_ty.needs_drop(tcx, param_env) {
155 // This should never happen. But we can get here e.g. in case of name resolution errors.
156 tcx.sess.delay_span_bug(span, "we should never accept maybe-dropping union fields");
160 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
165 /// Check that a `static` is inhabited.
166 fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
167 // Make sure statics are inhabited.
168 // Other parts of the compiler assume that there are no uninhabited places. In principle it
169 // would be enough to check this for `extern` statics, as statics with an initializer will
170 // have UB during initialization if they are uninhabited, but there also seems to be no good
171 // reason to allow any statics to be uninhabited.
172 let ty = tcx.type_of(def_id);
173 let span = tcx.def_span(def_id);
174 let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
176 // Foreign statics that overflow their allowed size should emit an error
177 Err(LayoutError::SizeOverflow(_))
179 let node = tcx.hir().get_by_def_id(def_id);
182 hir::Node::ForeignItem(hir::ForeignItem {
183 kind: hir::ForeignItemKind::Static(..),
190 .struct_span_err(span, "extern static is too large for the current architecture")
194 // Generic statics are rejected, but we still reach this case.
196 tcx.sess.delay_span_bug(span, &e.to_string());
200 if layout.abi.is_uninhabited() {
201 tcx.struct_span_lint_hir(
203 tcx.hir().local_def_id_to_hir_id(def_id),
205 "static of uninhabited type",
208 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
214 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
215 /// projections that would result in "inheriting lifetimes".
216 fn check_opaque<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) {
217 let item = tcx.hir().item(id);
218 let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item.kind else {
219 tcx.sess.delay_span_bug(tcx.hir().span(id.hir_id()), "expected opaque item");
223 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
224 // `async-std` (and `pub async fn` in general).
225 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
226 // See https://github.com/rust-lang/rust/issues/75100
227 if tcx.sess.opts.actually_rustdoc {
231 let substs = InternalSubsts::identity_for_item(tcx, item.owner_id.to_def_id());
232 let span = tcx.def_span(item.owner_id.def_id);
234 check_opaque_for_inheriting_lifetimes(tcx, item.owner_id.def_id, span);
235 if tcx.type_of(item.owner_id.def_id).references_error() {
238 if check_opaque_for_cycles(tcx, item.owner_id.def_id, substs, span, &origin).is_err() {
241 check_opaque_meets_bounds(tcx, item.owner_id.def_id, substs, span, &origin);
243 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
244 /// in "inheriting lifetimes".
245 #[instrument(level = "debug", skip(tcx, span))]
246 pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>(
251 let item = tcx.hir().expect_item(def_id);
252 debug!(?item, ?span);
254 struct FoundParentLifetime;
255 struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
256 impl<'tcx> ty::visit::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
257 type BreakTy = FoundParentLifetime;
259 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
260 debug!("FindParentLifetimeVisitor: r={:?}", r);
261 if let ty::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = *r {
262 if index < self.0.parent_count as u32 {
263 return ControlFlow::Break(FoundParentLifetime);
265 return ControlFlow::CONTINUE;
269 r.super_visit_with(self)
272 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
273 if let ty::ConstKind::Unevaluated(..) = c.kind() {
274 // FIXME(#72219) We currently don't detect lifetimes within substs
275 // which would violate this check. Even though the particular substitution is not used
276 // within the const, this should still be fixed.
277 return ControlFlow::CONTINUE;
279 c.super_visit_with(self)
283 struct ProhibitOpaqueVisitor<'tcx> {
285 opaque_identity_ty: Ty<'tcx>,
286 generics: &'tcx ty::Generics,
287 selftys: Vec<(Span, Option<String>)>,
290 impl<'tcx> ty::visit::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
291 type BreakTy = Ty<'tcx>;
293 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
294 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
295 if t == self.opaque_identity_ty {
296 ControlFlow::CONTINUE
298 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
299 .map_break(|FoundParentLifetime| t)
304 impl<'tcx> Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
305 type NestedFilter = nested_filter::OnlyBodies;
307 fn nested_visit_map(&mut self) -> Self::Map {
311 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
313 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
314 [PathSegment { res: Res::SelfTyParam { .. }, .. }] => {
315 let impl_ty_name = None;
316 self.selftys.push((path.span, impl_ty_name));
318 [PathSegment { res: Res::SelfTyAlias { alias_to: def_id, .. }, .. }] => {
319 let impl_ty_name = Some(self.tcx.def_path_str(*def_id));
320 self.selftys.push((path.span, impl_ty_name));
326 hir::intravisit::walk_ty(self, arg);
330 if let ItemKind::OpaqueTy(hir::OpaqueTy {
331 origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..),
335 let mut visitor = ProhibitOpaqueVisitor {
336 opaque_identity_ty: tcx.mk_opaque(
338 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
340 generics: tcx.generics_of(def_id),
344 let prohibit_opaque = tcx
345 .explicit_item_bounds(def_id)
347 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
349 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
350 prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
353 if let Some(ty) = prohibit_opaque.break_value() {
354 visitor.visit_item(&item);
355 let is_async = match item.kind {
356 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
357 matches!(origin, hir::OpaqueTyOrigin::AsyncFn(..))
362 let mut err = struct_span_err!(
366 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
368 if is_async { "async fn" } else { "impl Trait" },
371 for (span, name) in visitor.selftys {
374 "consider spelling out the type instead",
375 name.unwrap_or_else(|| format!("{:?}", ty)),
376 Applicability::MaybeIncorrect,
384 /// Checks that an opaque type does not contain cycles.
385 pub(super) fn check_opaque_for_cycles<'tcx>(
388 substs: SubstsRef<'tcx>,
390 origin: &hir::OpaqueTyOrigin,
391 ) -> Result<(), ErrorGuaranteed> {
392 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() {
393 let reported = match origin {
394 hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span),
395 _ => opaque_type_cycle_error(tcx, def_id, span),
403 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
405 /// This is mostly checked at the places that specify the opaque type, but we
406 /// check those cases in the `param_env` of that function, which may have
407 /// bounds not on this opaque type:
409 /// ```ignore (illustrative)
410 /// type X<T> = impl Clone;
411 /// fn f<T: Clone>(t: T) -> X<T> {
416 /// Without this check the above code is incorrectly accepted: we would ICE if
417 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
418 #[instrument(level = "debug", skip(tcx))]
419 fn check_opaque_meets_bounds<'tcx>(
422 substs: SubstsRef<'tcx>,
424 origin: &hir::OpaqueTyOrigin,
426 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
427 let defining_use_anchor = match *origin {
428 hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
429 hir::OpaqueTyOrigin::TyAlias => def_id,
431 let param_env = tcx.param_env(defining_use_anchor);
435 .with_opaque_type_inference(DefiningAnchor::Bind(defining_use_anchor))
437 let ocx = ObligationCtxt::new(&infcx);
438 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
440 // `ReErased` regions appear in the "parent_substs" of closures/generators.
441 // We're ignoring them here and replacing them with fresh region variables.
442 // See tests in ui/type-alias-impl-trait/closure_{parent_substs,wf_outlives}.rs.
444 // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it
445 // here rather than using ReErased.
446 let hidden_ty = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs);
447 let hidden_ty = tcx.fold_regions(hidden_ty, |re, _dbi| match re.kind() {
448 ty::ReErased => infcx.next_region_var(RegionVariableOrigin::MiscVariable(span)),
452 let misc_cause = traits::ObligationCause::misc(span, hir_id);
454 match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_ty) {
455 Ok(infer_ok) => ocx.register_infer_ok_obligations(infer_ok),
457 tcx.sess.delay_span_bug(
459 &format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
464 // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
465 // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
466 // hidden type is well formed even without those bounds.
468 ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_ty.into())).to_predicate(tcx);
469 ocx.register_obligation(Obligation::new(misc_cause, param_env, predicate));
471 // Check that all obligations are satisfied by the implementation's
473 let errors = ocx.select_all_or_error();
474 if !errors.is_empty() {
475 infcx.err_ctxt().report_fulfillment_errors(&errors, None);
478 // Checked when type checking the function containing them.
479 hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {}
480 // Can have different predicates to their defining use
481 hir::OpaqueTyOrigin::TyAlias => {
482 let outlives_environment = OutlivesEnvironment::new(param_env);
483 infcx.check_region_obligations_and_report_errors(
485 &outlives_environment,
489 // Clean up after ourselves
490 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
493 fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) {
495 "check_item_type(it.def_id={:?}, it.name={})",
497 tcx.def_path_str(id.owner_id.to_def_id())
499 let _indenter = indenter();
500 match tcx.def_kind(id.owner_id) {
501 DefKind::Static(..) => {
502 tcx.ensure().typeck(id.owner_id.def_id);
503 maybe_check_static_with_link_section(tcx, id.owner_id.def_id);
504 check_static_inhabited(tcx, id.owner_id.def_id);
507 tcx.ensure().typeck(id.owner_id.def_id);
510 check_enum(tcx, id.owner_id.def_id);
512 DefKind::Fn => {} // entirely within check_item_body
514 let it = tcx.hir().item(id);
515 let hir::ItemKind::Impl(ref impl_) = it.kind else {
518 debug!("ItemKind::Impl {} with id {:?}", it.ident, it.owner_id);
519 if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.owner_id) {
520 check_impl_items_against_trait(
527 check_on_unimplemented(tcx, it);
531 let it = tcx.hir().item(id);
532 let hir::ItemKind::Trait(_, _, _, _, ref items) = it.kind else {
535 check_on_unimplemented(tcx, it);
537 for item in items.iter() {
538 let item = tcx.hir().trait_item(item.id);
540 hir::TraitItemKind::Fn(ref sig, _) => {
541 let abi = sig.header.abi;
542 fn_maybe_err(tcx, item.ident.span, abi);
544 hir::TraitItemKind::Type(.., Some(default)) => {
545 let assoc_item = tcx.associated_item(item.owner_id);
547 InternalSubsts::identity_for_item(tcx, it.owner_id.to_def_id());
548 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
553 ty::TraitRef { def_id: it.owner_id.to_def_id(), substs: trait_substs },
561 check_struct(tcx, id.owner_id.def_id);
564 check_union(tcx, id.owner_id.def_id);
566 DefKind::OpaqueTy => {
567 check_opaque(tcx, id);
569 DefKind::ImplTraitPlaceholder => {
570 let parent = tcx.impl_trait_in_trait_parent(id.owner_id.to_def_id());
571 // Only check the validity of this opaque type if the function has a default body
572 if let hir::Node::TraitItem(hir::TraitItem {
573 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
575 }) = tcx.hir().get_by_def_id(parent.expect_local())
577 check_opaque(tcx, id);
580 DefKind::TyAlias => {
581 let pty_ty = tcx.type_of(id.owner_id);
582 let generics = tcx.generics_of(id.owner_id);
583 check_type_params_are_used(tcx, &generics, pty_ty);
585 DefKind::ForeignMod => {
586 let it = tcx.hir().item(id);
587 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
590 check_abi(tcx, it.hir_id(), it.span, abi);
592 if abi == Abi::RustIntrinsic {
594 let item = tcx.hir().foreign_item(item.id);
595 intrinsic::check_intrinsic_type(tcx, item);
597 } else if abi == Abi::PlatformIntrinsic {
599 let item = tcx.hir().foreign_item(item.id);
600 intrinsic::check_platform_intrinsic_type(tcx, item);
604 let def_id = item.id.owner_id.def_id;
605 let generics = tcx.generics_of(def_id);
606 let own_counts = generics.own_counts();
607 if generics.params.len() - own_counts.lifetimes != 0 {
608 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
609 (_, 0) => ("type", "types", Some("u32")),
610 // We don't specify an example value, because we can't generate
611 // a valid value for any type.
612 (0, _) => ("const", "consts", None),
613 _ => ("type or const", "types or consts", None),
619 "foreign items may not have {kinds} parameters",
621 .span_label(item.span, &format!("can't have {kinds} parameters"))
623 // FIXME: once we start storing spans for type arguments, turn this
624 // into a suggestion.
626 "replace the {} parameters with concrete {}{}",
629 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
635 let item = tcx.hir().foreign_item(item.id);
637 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
638 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
640 hir::ForeignItemKind::Static(..) => {
641 check_static_inhabited(tcx, def_id);
648 DefKind::GlobalAsm => {
649 let it = tcx.hir().item(id);
650 let hir::ItemKind::GlobalAsm(asm) = it.kind else { span_bug!(it.span, "DefKind::GlobalAsm but got {:#?}", it) };
651 InlineAsmCtxt::new_global_asm(tcx).check_asm(asm, id.hir_id());
657 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
658 // an error would be reported if this fails.
659 let _ = OnUnimplementedDirective::of_item(tcx, item.owner_id.to_def_id());
662 pub(super) fn check_specialization_validity<'tcx>(
664 trait_def: &ty::TraitDef,
665 trait_item: &ty::AssocItem,
667 impl_item: &hir::ImplItemRef,
669 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
670 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
671 if parent.is_from_trait() {
674 Some((parent, parent.item(tcx, trait_item.def_id)))
678 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
680 // Parent impl exists, and contains the parent item we're trying to specialize, but
681 // doesn't mark it `default`.
682 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
683 Some(Err(parent_impl.def_id()))
686 // Parent impl contains item and makes it specializable.
687 Some(_) => Some(Ok(())),
689 // Parent impl doesn't mention the item. This means it's inherited from the
690 // grandparent. In that case, if parent is a `default impl`, inherited items use the
691 // "defaultness" from the grandparent, else they are final.
693 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
696 Some(Err(parent_impl.def_id()))
702 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
703 // item. This is allowed, the item isn't actually getting specialized here.
704 let result = opt_result.unwrap_or(Ok(()));
706 if let Err(parent_impl) = result {
707 report_forbidden_specialization(tcx, impl_item, parent_impl);
711 fn check_impl_items_against_trait<'tcx>(
713 full_impl_span: Span,
715 impl_trait_ref: ty::TraitRef<'tcx>,
716 impl_item_refs: &[hir::ImplItemRef],
718 // If the trait reference itself is erroneous (so the compilation is going
719 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
720 // isn't populated for such impls.
721 if impl_trait_ref.references_error() {
725 // Negative impls are not expected to have any items
726 match tcx.impl_polarity(impl_id) {
727 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
728 ty::ImplPolarity::Negative => {
729 if let [first_item_ref, ..] = impl_item_refs {
730 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
735 "negative impls cannot have any items"
743 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
745 for impl_item in impl_item_refs {
746 let ty_impl_item = tcx.associated_item(impl_item.id.owner_id);
747 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
748 tcx.associated_item(trait_item_id)
750 // Checked in `associated_item`.
751 tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
754 let impl_item_full = tcx.hir().impl_item(impl_item.id);
755 match impl_item_full.kind {
756 hir::ImplItemKind::Const(..) => {
757 let _ = tcx.compare_assoc_const_impl_item_with_trait_item((
758 impl_item.id.owner_id.def_id,
759 ty_impl_item.trait_item_def_id.unwrap(),
762 hir::ImplItemKind::Fn(..) => {
763 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
772 hir::ImplItemKind::Type(impl_ty) => {
773 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
785 check_specialization_validity(
794 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
795 // Check for missing items from trait
796 let mut missing_items = Vec::new();
798 let mut must_implement_one_of: Option<&[Ident]> =
799 trait_def.must_implement_one_of.as_deref();
801 for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
802 let is_implemented = ancestors
803 .leaf_def(tcx, trait_item_id)
804 .map_or(false, |node_item| node_item.item.defaultness(tcx).has_value());
806 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
807 missing_items.push(tcx.associated_item(trait_item_id));
810 // true if this item is specifically implemented in this impl
811 let is_implemented_here = ancestors
812 .leaf_def(tcx, trait_item_id)
813 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
815 if !is_implemented_here {
816 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
817 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
826 // Unmarked default bodies are considered stable (at least for now).
827 EvalResult::Allow | EvalResult::Unmarked => {}
831 if let Some(required_items) = &must_implement_one_of {
832 if is_implemented_here {
833 let trait_item = tcx.associated_item(trait_item_id);
834 if required_items.contains(&trait_item.ident(tcx)) {
835 must_implement_one_of = None;
841 if !missing_items.is_empty() {
842 missing_items_err(tcx, tcx.def_span(impl_id), &missing_items, full_impl_span);
845 if let Some(missing_items) = must_implement_one_of {
847 .get_attr(impl_trait_ref.def_id, sym::rustc_must_implement_one_of)
848 .map(|attr| attr.span);
850 missing_items_must_implement_one_of_err(
852 tcx.def_span(impl_id),
860 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
861 let t = tcx.type_of(def_id);
862 if let ty::Adt(def, substs) = t.kind()
865 let fields = &def.non_enum_variant().fields;
866 if fields.is_empty() {
867 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
870 let e = fields[0].ty(tcx, substs);
871 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
872 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
873 .span_label(sp, "SIMD elements must have the same type")
878 let len = if let ty::Array(_ty, c) = e.kind() {
879 c.try_eval_usize(tcx, tcx.param_env(def.did()))
881 Some(fields.len() as u64)
883 if let Some(len) = len {
885 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
887 } else if len > MAX_SIMD_LANES {
892 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
899 // Check that we use types valid for use in the lanes of a SIMD "vector register"
900 // These are scalar types which directly match a "machine" type
901 // Yes: Integers, floats, "thin" pointers
902 // No: char, "fat" pointers, compound types
904 ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
905 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
906 ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
910 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
912 { /* struct([f32; 4]) is ok */ }
918 "SIMD vector element type should be a \
919 primitive scalar (integer/float/pointer) type"
928 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
929 let repr = def.repr();
931 for attr in tcx.get_attrs(def.did(), sym::repr) {
932 for r in attr::parse_repr_attr(&tcx.sess, attr) {
933 if let attr::ReprPacked(pack) = r
934 && let Some(repr_pack) = repr.pack
935 && pack as u64 != repr_pack.bytes()
941 "type has conflicting packed representation hints"
947 if repr.align.is_some() {
952 "type has conflicting packed and align representation hints"
956 if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
957 let mut err = struct_span_err!(
961 "packed type cannot transitively contain a `#[repr(align)]` type"
965 tcx.def_span(def_spans[0].0),
967 "`{}` has a `#[repr(align)]` attribute",
968 tcx.item_name(def_spans[0].0)
972 if def_spans.len() > 2 {
973 let mut first = true;
974 for (adt_def, span) in def_spans.iter().skip(1).rev() {
975 let ident = tcx.item_name(*adt_def);
980 "`{}` contains a field of type `{}`",
981 tcx.type_of(def.did()),
985 format!("...which contains a field of type `{ident}`")
998 pub(super) fn check_packed_inner(
1001 stack: &mut Vec<DefId>,
1002 ) -> Option<Vec<(DefId, Span)>> {
1003 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1004 if def.is_struct() || def.is_union() {
1005 if def.repr().align.is_some() {
1006 return Some(vec![(def.did(), DUMMY_SP)]);
1010 for field in &def.non_enum_variant().fields {
1011 if let ty::Adt(def, _) = field.ty(tcx, substs).kind()
1012 && !stack.contains(&def.did())
1013 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1015 defs.push((def.did(), field.ident(tcx).span));
1026 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1027 if !adt.repr().transparent() {
1031 if adt.is_union() && !tcx.features().transparent_unions {
1033 &tcx.sess.parse_sess,
1034 sym::transparent_unions,
1035 tcx.def_span(adt.did()),
1036 "transparent unions are unstable",
1041 if adt.variants().len() != 1 {
1042 bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1043 if adt.variants().is_empty() {
1044 // Don't bother checking the fields. No variants (and thus no fields) exist.
1049 // For each field, figure out if it's known to be a ZST and align(1), with "known"
1050 // respecting #[non_exhaustive] attributes.
1051 let field_infos = adt.all_fields().map(|field| {
1052 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1053 let param_env = tcx.param_env(field.did);
1054 let layout = tcx.layout_of(param_env.and(ty));
1055 // We are currently checking the type this field came from, so it must be local
1056 let span = tcx.hir().span_if_local(field.did).unwrap();
1057 let zst = layout.map_or(false, |layout| layout.is_zst());
1058 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1060 return (span, zst, align1, None);
1063 fn check_non_exhaustive<'tcx>(
1066 ) -> ControlFlow<(&'static str, DefId, SubstsRef<'tcx>, bool)> {
1068 ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)),
1069 ty::Array(ty, _) => check_non_exhaustive(tcx, *ty),
1070 ty::Adt(def, subst) => {
1071 if !def.did().is_local() {
1072 let non_exhaustive = def.is_variant_list_non_exhaustive()
1076 .any(ty::VariantDef::is_field_list_non_exhaustive);
1077 let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1078 if non_exhaustive || has_priv {
1079 return ControlFlow::Break((
1088 .map(|field| field.ty(tcx, subst))
1089 .try_for_each(|t| check_non_exhaustive(tcx, t))
1091 _ => ControlFlow::Continue(()),
1095 (span, zst, align1, check_non_exhaustive(tcx, ty).break_value())
1098 let non_zst_fields = field_infos
1100 .filter_map(|(span, zst, _align1, _non_exhaustive)| if !zst { Some(span) } else { None });
1101 let non_zst_count = non_zst_fields.clone().count();
1102 if non_zst_count >= 2 {
1103 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, tcx.def_span(adt.did()));
1105 let incompatible_zst_fields =
1106 field_infos.clone().filter(|(_, _, _, opt)| opt.is_some()).count();
1107 let incompat = incompatible_zst_fields + non_zst_count >= 2 && non_zst_count < 2;
1108 for (span, zst, align1, non_exhaustive) in field_infos {
1114 "zero-sized field in transparent {} has alignment larger than 1",
1117 .span_label(span, "has alignment larger than 1")
1120 if incompat && let Some((descr, def_id, substs, non_exhaustive)) = non_exhaustive {
1121 tcx.struct_span_lint_hir(
1122 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS,
1123 tcx.hir().local_def_id_to_hir_id(adt.did().expect_local()),
1125 "zero-sized fields in `repr(transparent)` cannot contain external non-exhaustive types",
1127 let note = if non_exhaustive {
1128 "is marked with `#[non_exhaustive]`"
1130 "contains private fields"
1132 let field_ty = tcx.def_path_str_with_substs(def_id, substs);
1134 .note(format!("this {descr} contains `{field_ty}`, which {note}, \
1135 and makes it not a breaking change to become non-zero-sized in the future."))
1142 #[allow(trivial_numeric_casts)]
1143 fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1144 let def = tcx.adt_def(def_id);
1145 def.destructor(tcx); // force the destructor to be evaluated
1147 if def.variants().is_empty() {
1148 if let Some(attr) = tcx.get_attrs(def_id.to_def_id(), sym::repr).next() {
1153 "unsupported representation for zero-variant enum"
1155 .span_label(tcx.def_span(def_id), "zero-variant enum")
1160 let repr_type_ty = def.repr().discr_type().to_ty(tcx);
1161 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1162 if !tcx.features().repr128 {
1164 &tcx.sess.parse_sess,
1166 tcx.def_span(def_id),
1167 "repr with 128-bit type is unstable",
1173 for v in def.variants() {
1174 if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1175 tcx.ensure().typeck(discr_def_id.expect_local());
1179 if def.repr().int.is_none() {
1180 let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind, CtorKind::Const);
1181 let has_disr = |var: &ty::VariantDef| matches!(var.discr, ty::VariantDiscr::Explicit(_));
1183 let has_non_units = def.variants().iter().any(|var| !is_unit(var));
1184 let disr_units = def.variants().iter().any(|var| is_unit(&var) && has_disr(&var));
1185 let disr_non_unit = def.variants().iter().any(|var| !is_unit(&var) && has_disr(&var));
1187 if disr_non_unit || (disr_units && has_non_units) {
1188 let mut err = struct_span_err!(
1190 tcx.def_span(def_id),
1192 "`#[repr(inttype)]` must be specified"
1198 detect_discriminant_duplicate(tcx, def);
1199 check_transparent(tcx, def);
1202 /// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1203 fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1204 // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1205 // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1206 let report = |dis: Discr<'tcx>, idx, err: &mut Diagnostic| {
1207 let var = adt.variant(idx); // HIR for the duplicate discriminant
1208 let (span, display_discr) = match var.discr {
1209 ty::VariantDiscr::Explicit(discr_def_id) => {
1210 // In the case the discriminant is both a duplicate and overflowed, let the user know
1211 if let hir::Node::AnonConst(expr) = tcx.hir().get_by_def_id(discr_def_id.expect_local())
1212 && let hir::ExprKind::Lit(lit) = &tcx.hir().body(expr.body).value.kind
1213 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1214 && *lit_value != dis.val
1216 (tcx.def_span(discr_def_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1218 // Otherwise, format the value as-is
1219 (tcx.def_span(discr_def_id), format!("`{dis}`"))
1222 // This should not happen.
1223 ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), format!("`{dis}`")),
1224 ty::VariantDiscr::Relative(distance_to_explicit) => {
1225 // At this point we know this discriminant is a duplicate, and was not explicitly
1226 // assigned by the user. Here we iterate backwards to fetch the HIR for the last
1227 // explicitly assigned discriminant, and letting the user know that this was the
1228 // increment startpoint, and how many steps from there leading to the duplicate
1229 if let Some(explicit_idx) =
1230 idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1232 let explicit_variant = adt.variant(explicit_idx);
1233 let ve_ident = var.name;
1234 let ex_ident = explicit_variant.name;
1235 let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1238 tcx.def_span(explicit_variant.def_id),
1240 "discriminant for `{ve_ident}` incremented from this startpoint \
1241 (`{ex_ident}` + {distance_to_explicit} {sp} later \
1242 => `{ve_ident}` = {dis})"
1247 (tcx.def_span(var.def_id), format!("`{dis}`"))
1251 err.span_label(span, format!("{display_discr} assigned here"));
1254 let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1256 // Here we loop through the discriminants, comparing each discriminant to another.
1257 // When a duplicate is detected, we instantiate an error and point to both
1258 // initial and duplicate value. The duplicate discriminant is then discarded by swapping
1259 // it with the last element and decrementing the `vec.len` (which is why we have to evaluate
1260 // `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
1261 // style as we are mutating `discrs` on the fly).
1263 while i < discrs.len() {
1264 let var_i_idx = discrs[i].0;
1265 let mut error: Option<DiagnosticBuilder<'_, _>> = None;
1268 while o < discrs.len() {
1269 let var_o_idx = discrs[o].0;
1271 if discrs[i].1.val == discrs[o].1.val {
1272 let err = error.get_or_insert_with(|| {
1273 let mut ret = struct_span_err!(
1275 tcx.def_span(adt.did()),
1277 "discriminant value `{}` assigned more than once",
1281 report(discrs[i].1, var_i_idx, &mut ret);
1286 report(discrs[o].1, var_o_idx, err);
1288 // Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
1289 discrs[o] = *discrs.last().unwrap();
1296 if let Some(mut e) = error {
1304 pub(super) fn check_type_params_are_used<'tcx>(
1306 generics: &ty::Generics,
1309 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1311 assert_eq!(generics.parent, None);
1313 if generics.own_counts().types == 0 {
1317 let mut params_used = BitSet::new_empty(generics.params.len());
1319 if ty.references_error() {
1320 // If there is already another error, do not emit
1321 // an error for not using a type parameter.
1322 assert!(tcx.sess.has_errors().is_some());
1326 for leaf in ty.walk() {
1327 if let GenericArgKind::Type(leaf_ty) = leaf.unpack()
1328 && let ty::Param(param) = leaf_ty.kind()
1330 debug!("found use of ty param {:?}", param);
1331 params_used.insert(param.index);
1335 for param in &generics.params {
1336 if !params_used.contains(param.index)
1337 && let ty::GenericParamDefKind::Type { .. } = param.kind
1339 let span = tcx.def_span(param.def_id);
1344 "type parameter `{}` is unused",
1347 .span_label(span, "unused type parameter")
1353 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1354 let module = tcx.hir_module_items(module_def_id);
1355 for id in module.items() {
1356 check_item_type(tcx, id);
1360 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) -> ErrorGuaranteed {
1361 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1362 .span_label(span, "recursive `async fn`")
1363 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1365 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1370 /// Emit an error for recursive opaque types.
1372 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1373 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1376 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1377 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1378 fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) -> ErrorGuaranteed {
1379 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1381 let mut label = false;
1382 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1383 let typeck_results = tcx.typeck(def_id);
1387 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1388 .all(|ty| matches!(ty.kind(), ty::Never))
1393 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1394 .map(|expr| expr.span)
1395 .collect::<Vec<Span>>();
1396 let span_len = spans.len();
1398 err.span_label(spans[0], "this returned value is of `!` type");
1400 let mut multispan: MultiSpan = spans.clone().into();
1402 multispan.push_span_label(span, "this returned value is of `!` type");
1404 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1406 err.help("this error will resolve once the item's body returns a concrete type");
1408 let mut seen = FxHashSet::default();
1410 err.span_label(span, "recursive opaque type");
1412 for (sp, ty) in visitor
1415 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1416 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1418 struct OpaqueTypeCollector(Vec<DefId>);
1419 impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypeCollector {
1420 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1422 ty::Opaque(def, _) => {
1424 ControlFlow::CONTINUE
1426 _ => t.super_visit_with(self),
1430 let mut visitor = OpaqueTypeCollector(vec![]);
1431 ty.visit_with(&mut visitor);
1432 for def_id in visitor.0 {
1433 let ty_span = tcx.def_span(def_id);
1434 if !seen.contains(&ty_span) {
1435 err.span_label(ty_span, &format!("returning this opaque type `{ty}`"));
1436 seen.insert(ty_span);
1438 err.span_label(sp, &format!("returning here with type `{ty}`"));
1444 err.span_label(span, "cannot resolve opaque type");