1 use crate::check::intrinsicck::InlineAsmCtxt;
2 use crate::errors::LinkageType;
4 use super::compare_impl_item::check_type_bounds;
5 use super::compare_impl_item::{compare_impl_method, compare_impl_ty};
7 use rustc_attr as attr;
8 use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan};
10 use rustc_hir::def::{CtorKind, DefKind, Res};
11 use rustc_hir::def_id::{DefId, LocalDefId};
12 use rustc_hir::intravisit::Visitor;
13 use rustc_hir::{ItemKind, Node, PathSegment};
14 use rustc_infer::infer::opaque_types::ConstrainOpaqueTypeRegionVisitor;
15 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
16 use rustc_infer::infer::{DefiningAnchor, RegionVariableOrigin, TyCtxtInferExt};
17 use rustc_infer::traits::Obligation;
18 use rustc_lint::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS;
19 use rustc_middle::hir::nested_filter;
20 use rustc_middle::middle::stability::EvalResult;
21 use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
22 use rustc_middle::ty::subst::GenericArgKind;
23 use rustc_middle::ty::util::{Discr, IntTypeExt};
24 use rustc_middle::ty::{self, AdtDef, ParamEnv, 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>,
103 // We don't just accept all !needs_drop fields, due to semver concerns.
105 ty::Ref(..) => true, // references never drop (even mutable refs, which are non-Copy and hence fail the later check)
107 // allow tuples of allowed types
108 tys.iter().all(|ty| allowed_union_field(ty, tcx, param_env))
110 ty::Array(elem, _len) => {
111 // Like `Copy`, we do *not* special-case length 0.
112 allowed_union_field(*elem, tcx, param_env)
115 // Fallback case: allow `ManuallyDrop` and things that are `Copy`.
116 ty.ty_adt_def().is_some_and(|adt_def| adt_def.is_manually_drop())
117 || ty.is_copy_modulo_regions(tcx, param_env)
122 let param_env = tcx.param_env(item_def_id);
123 for field in &def.non_enum_variant().fields {
124 let field_ty = field.ty(tcx, substs);
126 if !allowed_union_field(field_ty, tcx, param_env) {
127 let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
128 // We are currently checking the type this field came from, so it must be local.
129 Some(Node::Field(field)) => (field.span, field.ty.span),
130 _ => unreachable!("mir field has to correspond to hir field"),
136 "unions cannot contain fields that may need dropping"
139 "a type is guaranteed not to need dropping \
140 when it implements `Copy`, or when it is the special `ManuallyDrop<_>` type",
142 .multipart_suggestion_verbose(
143 "when the type does not implement `Copy`, \
144 wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped",
146 (ty_span.shrink_to_lo(), "std::mem::ManuallyDrop<".into()),
147 (ty_span.shrink_to_hi(), ">".into()),
149 Applicability::MaybeIncorrect,
153 } else if field_ty.needs_drop(tcx, param_env) {
154 // This should never happen. But we can get here e.g. in case of name resolution errors.
155 tcx.sess.delay_span_bug(span, "we should never accept maybe-dropping union fields");
159 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
164 /// Check that a `static` is inhabited.
165 fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
166 // Make sure statics are inhabited.
167 // Other parts of the compiler assume that there are no uninhabited places. In principle it
168 // would be enough to check this for `extern` statics, as statics with an initializer will
169 // have UB during initialization if they are uninhabited, but there also seems to be no good
170 // reason to allow any statics to be uninhabited.
171 let ty = tcx.type_of(def_id);
172 let span = tcx.def_span(def_id);
173 let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
175 // Foreign statics that overflow their allowed size should emit an error
176 Err(LayoutError::SizeOverflow(_))
178 let node = tcx.hir().get_by_def_id(def_id);
181 hir::Node::ForeignItem(hir::ForeignItem {
182 kind: hir::ForeignItemKind::Static(..),
189 .struct_span_err(span, "extern static is too large for the current architecture")
193 // Generic statics are rejected, but we still reach this case.
195 tcx.sess.delay_span_bug(span, &e.to_string());
199 if layout.abi.is_uninhabited() {
200 tcx.struct_span_lint_hir(
202 tcx.hir().local_def_id_to_hir_id(def_id),
204 "static of uninhabited type",
207 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
213 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
214 /// projections that would result in "inheriting lifetimes".
215 fn check_opaque(tcx: TyCtxt<'_>, id: hir::ItemId) {
216 let item = tcx.hir().item(id);
217 let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item.kind else {
218 tcx.sess.delay_span_bug(tcx.hir().span(id.hir_id()), "expected opaque item");
222 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
223 // `async-std` (and `pub async fn` in general).
224 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
225 // See https://github.com/rust-lang/rust/issues/75100
226 if tcx.sess.opts.actually_rustdoc {
230 let substs = InternalSubsts::identity_for_item(tcx, item.owner_id.to_def_id());
231 let span = tcx.def_span(item.owner_id.def_id);
233 if !tcx.features().impl_trait_projections {
234 check_opaque_for_inheriting_lifetimes(tcx, item.owner_id.def_id, span);
236 if tcx.type_of(item.owner_id.def_id).references_error() {
239 if check_opaque_for_cycles(tcx, item.owner_id.def_id, substs, span, &origin).is_err() {
242 check_opaque_meets_bounds(tcx, item.owner_id.def_id, substs, span, &origin);
245 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
246 /// in "inheriting lifetimes".
247 #[instrument(level = "debug", skip(tcx, span))]
248 pub(super) fn check_opaque_for_inheriting_lifetimes(
253 let item = tcx.hir().expect_item(def_id);
254 debug!(?item, ?span);
256 struct ProhibitOpaqueVisitor<'tcx> {
258 opaque_identity_ty: Ty<'tcx>,
260 references_parent_regions: bool,
261 selftys: Vec<(Span, Option<String>)>,
264 impl<'tcx> ty::visit::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
265 type BreakTy = Ty<'tcx>;
267 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
268 debug!(?t, "root_visit_ty");
269 if t == self.opaque_identity_ty {
270 ControlFlow::Continue(())
272 t.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
275 if let ty::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = *region
276 && index < self.parent_count
278 self.references_parent_regions= true;
282 if self.references_parent_regions {
283 ControlFlow::Break(t)
285 ControlFlow::Continue(())
291 impl<'tcx> Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
292 type NestedFilter = nested_filter::OnlyBodies;
294 fn nested_visit_map(&mut self) -> Self::Map {
298 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
300 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
301 [PathSegment { res: Res::SelfTyParam { .. }, .. }] => {
302 let impl_ty_name = None;
303 self.selftys.push((path.span, impl_ty_name));
305 [PathSegment { res: Res::SelfTyAlias { alias_to: def_id, .. }, .. }] => {
306 let impl_ty_name = Some(self.tcx.def_path_str(*def_id));
307 self.selftys.push((path.span, impl_ty_name));
313 hir::intravisit::walk_ty(self, arg);
317 if let ItemKind::OpaqueTy(hir::OpaqueTy {
318 origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..),
323 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
324 let opaque_identity_ty = if in_trait {
325 tcx.mk_projection(def_id.to_def_id(), substs)
327 tcx.mk_opaque(def_id.to_def_id(), substs)
329 let mut visitor = ProhibitOpaqueVisitor {
331 parent_count: tcx.generics_of(def_id).parent_count as u32,
332 references_parent_regions: false,
336 let prohibit_opaque = tcx
337 .explicit_item_bounds(def_id)
339 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
341 if let Some(ty) = prohibit_opaque.break_value() {
342 visitor.visit_item(&item);
343 let is_async = match item.kind {
344 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
345 matches!(origin, hir::OpaqueTyOrigin::AsyncFn(..))
350 let mut err = feature_err(
351 &tcx.sess.parse_sess,
352 sym::impl_trait_projections,
355 "`{}` return type cannot contain a projection or `Self` that references \
356 lifetimes from a parent scope",
357 if is_async { "async fn" } else { "impl Trait" },
360 for (span, name) in visitor.selftys {
363 "consider spelling out the type instead",
364 name.unwrap_or_else(|| format!("{:?}", ty)),
365 Applicability::MaybeIncorrect,
373 /// Checks that an opaque type does not contain cycles.
374 pub(super) fn check_opaque_for_cycles<'tcx>(
377 substs: SubstsRef<'tcx>,
379 origin: &hir::OpaqueTyOrigin,
380 ) -> Result<(), ErrorGuaranteed> {
381 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() {
382 let reported = match origin {
383 hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span),
384 _ => opaque_type_cycle_error(tcx, def_id, span),
392 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
394 /// This is mostly checked at the places that specify the opaque type, but we
395 /// check those cases in the `param_env` of that function, which may have
396 /// bounds not on this opaque type:
398 /// ```ignore (illustrative)
399 /// type X<T> = impl Clone;
400 /// fn f<T: Clone>(t: T) -> X<T> {
405 /// Without this check the above code is incorrectly accepted: we would ICE if
406 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
407 #[instrument(level = "debug", skip(tcx))]
408 fn check_opaque_meets_bounds<'tcx>(
411 substs: SubstsRef<'tcx>,
413 origin: &hir::OpaqueTyOrigin,
415 let defining_use_anchor = match *origin {
416 hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
417 hir::OpaqueTyOrigin::TyAlias => def_id,
419 let param_env = tcx.param_env(defining_use_anchor);
423 .with_opaque_type_inference(DefiningAnchor::Bind(defining_use_anchor))
425 let ocx = ObligationCtxt::new(&infcx);
426 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
428 // `ReErased` regions appear in the "parent_substs" of closures/generators.
429 // We're ignoring them here and replacing them with fresh region variables.
430 // See tests in ui/type-alias-impl-trait/closure_{parent_substs,wf_outlives}.rs.
432 // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it
433 // here rather than using ReErased.
434 let hidden_ty = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs);
435 let hidden_ty = tcx.fold_regions(hidden_ty, |re, _dbi| match re.kind() {
436 ty::ReErased => infcx.next_region_var(RegionVariableOrigin::MiscVariable(span)),
440 let misc_cause = traits::ObligationCause::misc(span, def_id);
442 match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
445 tcx.sess.delay_span_bug(
447 &format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
452 // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
453 // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
454 // hidden type is well formed even without those bounds.
455 let predicate = ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_ty.into()));
456 ocx.register_obligation(Obligation::new(tcx, misc_cause, param_env, predicate));
458 // Check that all obligations are satisfied by the implementation's
460 let errors = ocx.select_all_or_error();
461 if !errors.is_empty() {
462 infcx.err_ctxt().report_fulfillment_errors(&errors, None);
465 // Checked when type checking the function containing them.
466 hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {}
467 // Can have different predicates to their defining use
468 hir::OpaqueTyOrigin::TyAlias => {
469 let outlives_environment = OutlivesEnvironment::new(param_env);
470 let _ = infcx.err_ctxt().check_region_obligations_and_report_errors(
472 &outlives_environment,
476 // Clean up after ourselves
477 let _ = infcx.take_opaque_types();
480 fn is_enum_of_nonnullable_ptr<'tcx>(
482 adt_def: AdtDef<'tcx>,
483 substs: SubstsRef<'tcx>,
485 if adt_def.repr().inhibit_enum_layout_opt() {
489 let [var_one, var_two] = &adt_def.variants().raw[..] else {
492 let (([], [field]) | ([field], [])) = (&var_one.fields[..], &var_two.fields[..]) else {
495 matches!(field.ty(tcx, substs).kind(), ty::FnPtr(..) | ty::Ref(..))
498 fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
499 if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
500 if match tcx.type_of(def_id).kind() {
501 ty::RawPtr(_) => false,
502 ty::Adt(adt_def, substs) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *substs),
505 tcx.sess.emit_err(LinkageType { span: tcx.def_span(def_id) });
510 fn check_item_type(tcx: TyCtxt<'_>, id: hir::ItemId) {
512 "check_item_type(it.def_id={:?}, it.name={})",
514 tcx.def_path_str(id.owner_id.to_def_id())
516 let _indenter = indenter();
517 match tcx.def_kind(id.owner_id) {
518 DefKind::Static(..) => {
519 tcx.ensure().typeck(id.owner_id.def_id);
520 maybe_check_static_with_link_section(tcx, id.owner_id.def_id);
521 check_static_inhabited(tcx, id.owner_id.def_id);
522 check_static_linkage(tcx, id.owner_id.def_id);
525 tcx.ensure().typeck(id.owner_id.def_id);
528 check_enum(tcx, id.owner_id.def_id);
530 DefKind::Fn => {} // entirely within check_item_body
532 let it = tcx.hir().item(id);
533 let hir::ItemKind::Impl(impl_) = it.kind else { return };
534 debug!("ItemKind::Impl {} with id {:?}", it.ident, it.owner_id);
535 if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.owner_id) {
536 check_impl_items_against_trait(
540 impl_trait_ref.subst_identity(),
543 check_on_unimplemented(tcx, it);
547 let it = tcx.hir().item(id);
548 let hir::ItemKind::Trait(_, _, _, _, items) = it.kind else {
551 check_on_unimplemented(tcx, it);
553 for item in items.iter() {
554 let item = tcx.hir().trait_item(item.id);
556 hir::TraitItemKind::Fn(sig, _) => {
557 let abi = sig.header.abi;
558 fn_maybe_err(tcx, item.ident.span, abi);
560 hir::TraitItemKind::Type(.., Some(default)) => {
561 let assoc_item = tcx.associated_item(item.owner_id);
563 InternalSubsts::identity_for_item(tcx, it.owner_id.to_def_id());
564 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
569 tcx.mk_trait_ref(it.owner_id.to_def_id(), trait_substs),
577 check_struct(tcx, id.owner_id.def_id);
580 check_union(tcx, id.owner_id.def_id);
582 DefKind::OpaqueTy => {
583 check_opaque(tcx, id);
585 DefKind::ImplTraitPlaceholder => {
586 let parent = tcx.impl_trait_in_trait_parent(id.owner_id.to_def_id());
587 // Only check the validity of this opaque type if the function has a default body
588 if let hir::Node::TraitItem(hir::TraitItem {
589 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
591 }) = tcx.hir().get_by_def_id(parent.expect_local())
593 check_opaque(tcx, id);
596 DefKind::TyAlias => {
597 let pty_ty = tcx.type_of(id.owner_id);
598 let generics = tcx.generics_of(id.owner_id);
599 check_type_params_are_used(tcx, &generics, pty_ty);
601 DefKind::ForeignMod => {
602 let it = tcx.hir().item(id);
603 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
606 check_abi(tcx, it.hir_id(), it.span, abi);
608 if abi == Abi::RustIntrinsic {
610 let item = tcx.hir().foreign_item(item.id);
611 intrinsic::check_intrinsic_type(tcx, item);
613 } else if abi == Abi::PlatformIntrinsic {
615 let item = tcx.hir().foreign_item(item.id);
616 intrinsic::check_platform_intrinsic_type(tcx, item);
620 let def_id = item.id.owner_id.def_id;
621 let generics = tcx.generics_of(def_id);
622 let own_counts = generics.own_counts();
623 if generics.params.len() - own_counts.lifetimes != 0 {
624 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
625 (_, 0) => ("type", "types", Some("u32")),
626 // We don't specify an example value, because we can't generate
627 // a valid value for any type.
628 (0, _) => ("const", "consts", None),
629 _ => ("type or const", "types or consts", None),
635 "foreign items may not have {kinds} parameters",
637 .span_label(item.span, &format!("can't have {kinds} parameters"))
639 // FIXME: once we start storing spans for type arguments, turn this
640 // into a suggestion.
642 "replace the {} parameters with concrete {}{}",
645 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
651 let item = tcx.hir().foreign_item(item.id);
653 hir::ForeignItemKind::Fn(fn_decl, _, _) => {
654 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
656 hir::ForeignItemKind::Static(..) => {
657 check_static_inhabited(tcx, def_id);
658 check_static_linkage(tcx, def_id);
665 DefKind::GlobalAsm => {
666 let it = tcx.hir().item(id);
667 let hir::ItemKind::GlobalAsm(asm) = it.kind else { span_bug!(it.span, "DefKind::GlobalAsm but got {:#?}", it) };
668 InlineAsmCtxt::new_global_asm(tcx).check_asm(asm, id.hir_id());
674 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
675 // an error would be reported if this fails.
676 let _ = OnUnimplementedDirective::of_item(tcx, item.owner_id.to_def_id());
679 pub(super) fn check_specialization_validity<'tcx>(
681 trait_def: &ty::TraitDef,
682 trait_item: &ty::AssocItem,
684 impl_item: &hir::ImplItemRef,
686 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
687 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
688 if parent.is_from_trait() {
691 Some((parent, parent.item(tcx, trait_item.def_id)))
695 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
697 // Parent impl exists, and contains the parent item we're trying to specialize, but
698 // doesn't mark it `default`.
699 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
700 Some(Err(parent_impl.def_id()))
703 // Parent impl contains item and makes it specializable.
704 Some(_) => Some(Ok(())),
706 // Parent impl doesn't mention the item. This means it's inherited from the
707 // grandparent. In that case, if parent is a `default impl`, inherited items use the
708 // "defaultness" from the grandparent, else they are final.
710 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
713 Some(Err(parent_impl.def_id()))
719 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
720 // item. This is allowed, the item isn't actually getting specialized here.
721 let result = opt_result.unwrap_or(Ok(()));
723 if let Err(parent_impl) = result {
724 report_forbidden_specialization(tcx, impl_item, parent_impl);
728 fn check_impl_items_against_trait<'tcx>(
730 full_impl_span: Span,
732 impl_trait_ref: ty::TraitRef<'tcx>,
733 impl_item_refs: &[hir::ImplItemRef],
735 // If the trait reference itself is erroneous (so the compilation is going
736 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
737 // isn't populated for such impls.
738 if impl_trait_ref.references_error() {
742 // Negative impls are not expected to have any items
743 match tcx.impl_polarity(impl_id) {
744 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
745 ty::ImplPolarity::Negative => {
746 if let [first_item_ref, ..] = impl_item_refs {
747 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
752 "negative impls cannot have any items"
760 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
762 for impl_item in impl_item_refs {
763 let ty_impl_item = tcx.associated_item(impl_item.id.owner_id);
764 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
765 tcx.associated_item(trait_item_id)
767 // Checked in `associated_item`.
768 tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
771 let impl_item_full = tcx.hir().impl_item(impl_item.id);
772 match impl_item_full.kind {
773 hir::ImplItemKind::Const(..) => {
774 let _ = tcx.compare_impl_const((
775 impl_item.id.owner_id.def_id,
776 ty_impl_item.trait_item_def_id.unwrap(),
779 hir::ImplItemKind::Fn(..) => {
780 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
789 hir::ImplItemKind::Type(impl_ty) => {
790 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
802 check_specialization_validity(
811 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
812 // Check for missing items from trait
813 let mut missing_items = Vec::new();
815 let mut must_implement_one_of: Option<&[Ident]> =
816 trait_def.must_implement_one_of.as_deref();
818 for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
819 let is_implemented = ancestors
820 .leaf_def(tcx, trait_item_id)
821 .map_or(false, |node_item| node_item.item.defaultness(tcx).has_value());
823 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
824 missing_items.push(tcx.associated_item(trait_item_id));
827 // true if this item is specifically implemented in this impl
828 let is_implemented_here = ancestors
829 .leaf_def(tcx, trait_item_id)
830 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
832 if !is_implemented_here {
833 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
834 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
843 // Unmarked default bodies are considered stable (at least for now).
844 EvalResult::Allow | EvalResult::Unmarked => {}
848 if let Some(required_items) = &must_implement_one_of {
849 if is_implemented_here {
850 let trait_item = tcx.associated_item(trait_item_id);
851 if required_items.contains(&trait_item.ident(tcx)) {
852 must_implement_one_of = None;
858 if !missing_items.is_empty() {
859 missing_items_err(tcx, tcx.def_span(impl_id), &missing_items, full_impl_span);
862 if let Some(missing_items) = must_implement_one_of {
864 .get_attr(impl_trait_ref.def_id, sym::rustc_must_implement_one_of)
865 .map(|attr| attr.span);
867 missing_items_must_implement_one_of_err(
869 tcx.def_span(impl_id),
877 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
878 let t = tcx.type_of(def_id);
879 if let ty::Adt(def, substs) = t.kind()
882 let fields = &def.non_enum_variant().fields;
883 if fields.is_empty() {
884 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
887 let e = fields[0].ty(tcx, substs);
888 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
889 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
890 .span_label(sp, "SIMD elements must have the same type")
895 let len = if let ty::Array(_ty, c) = e.kind() {
896 c.try_eval_usize(tcx, tcx.param_env(def.did()))
898 Some(fields.len() as u64)
900 if let Some(len) = len {
902 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
904 } else if len > MAX_SIMD_LANES {
909 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
916 // Check that we use types valid for use in the lanes of a SIMD "vector register"
917 // These are scalar types which directly match a "machine" type
918 // Yes: Integers, floats, "thin" pointers
919 // No: char, "fat" pointers, compound types
921 ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
922 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
923 ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
927 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
929 { /* struct([f32; 4]) is ok */ }
935 "SIMD vector element type should be a \
936 primitive scalar (integer/float/pointer) type"
945 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
946 let repr = def.repr();
948 for attr in tcx.get_attrs(def.did(), sym::repr) {
949 for r in attr::parse_repr_attr(&tcx.sess, attr) {
950 if let attr::ReprPacked(pack) = r
951 && let Some(repr_pack) = repr.pack
952 && pack as u64 != repr_pack.bytes()
958 "type has conflicting packed representation hints"
964 if repr.align.is_some() {
969 "type has conflicting packed and align representation hints"
973 if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
974 let mut err = struct_span_err!(
978 "packed type cannot transitively contain a `#[repr(align)]` type"
982 tcx.def_span(def_spans[0].0),
984 "`{}` has a `#[repr(align)]` attribute",
985 tcx.item_name(def_spans[0].0)
989 if def_spans.len() > 2 {
990 let mut first = true;
991 for (adt_def, span) in def_spans.iter().skip(1).rev() {
992 let ident = tcx.item_name(*adt_def);
997 "`{}` contains a field of type `{}`",
998 tcx.type_of(def.did()),
1002 format!("...which contains a field of type `{ident}`")
1015 pub(super) fn check_packed_inner(
1018 stack: &mut Vec<DefId>,
1019 ) -> Option<Vec<(DefId, Span)>> {
1020 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1021 if def.is_struct() || def.is_union() {
1022 if def.repr().align.is_some() {
1023 return Some(vec![(def.did(), DUMMY_SP)]);
1027 for field in &def.non_enum_variant().fields {
1028 if let ty::Adt(def, _) = field.ty(tcx, substs).kind()
1029 && !stack.contains(&def.did())
1030 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1032 defs.push((def.did(), field.ident(tcx).span));
1043 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1044 if !adt.repr().transparent() {
1048 if adt.is_union() && !tcx.features().transparent_unions {
1050 &tcx.sess.parse_sess,
1051 sym::transparent_unions,
1052 tcx.def_span(adt.did()),
1053 "transparent unions are unstable",
1058 if adt.variants().len() != 1 {
1059 bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1060 // Don't bother checking the fields.
1064 // For each field, figure out if it's known to be a ZST and align(1), with "known"
1065 // respecting #[non_exhaustive] attributes.
1066 let field_infos = adt.all_fields().map(|field| {
1067 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1068 let param_env = tcx.param_env(field.did);
1069 let layout = tcx.layout_of(param_env.and(ty));
1070 // We are currently checking the type this field came from, so it must be local
1071 let span = tcx.hir().span_if_local(field.did).unwrap();
1072 let zst = layout.map_or(false, |layout| layout.is_zst());
1073 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1075 return (span, zst, align1, None);
1078 fn check_non_exhaustive<'tcx>(
1081 ) -> ControlFlow<(&'static str, DefId, SubstsRef<'tcx>, bool)> {
1083 ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)),
1084 ty::Array(ty, _) => check_non_exhaustive(tcx, *ty),
1085 ty::Adt(def, subst) => {
1086 if !def.did().is_local() {
1087 let non_exhaustive = def.is_variant_list_non_exhaustive()
1091 .any(ty::VariantDef::is_field_list_non_exhaustive);
1092 let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1093 if non_exhaustive || has_priv {
1094 return ControlFlow::Break((
1103 .map(|field| field.ty(tcx, subst))
1104 .try_for_each(|t| check_non_exhaustive(tcx, t))
1106 _ => ControlFlow::Continue(()),
1110 (span, zst, align1, check_non_exhaustive(tcx, ty).break_value())
1113 let non_zst_fields = field_infos
1115 .filter_map(|(span, zst, _align1, _non_exhaustive)| if !zst { Some(span) } else { None });
1116 let non_zst_count = non_zst_fields.clone().count();
1117 if non_zst_count >= 2 {
1118 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, tcx.def_span(adt.did()));
1120 let incompatible_zst_fields =
1121 field_infos.clone().filter(|(_, _, _, opt)| opt.is_some()).count();
1122 let incompat = incompatible_zst_fields + non_zst_count >= 2 && non_zst_count < 2;
1123 for (span, zst, align1, non_exhaustive) in field_infos {
1129 "zero-sized field in transparent {} has alignment larger than 1",
1132 .span_label(span, "has alignment larger than 1")
1135 if incompat && let Some((descr, def_id, substs, non_exhaustive)) = non_exhaustive {
1136 tcx.struct_span_lint_hir(
1137 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS,
1138 tcx.hir().local_def_id_to_hir_id(adt.did().expect_local()),
1140 "zero-sized fields in `repr(transparent)` cannot contain external non-exhaustive types",
1142 let note = if non_exhaustive {
1143 "is marked with `#[non_exhaustive]`"
1145 "contains private fields"
1147 let field_ty = tcx.def_path_str_with_substs(def_id, substs);
1149 .note(format!("this {descr} contains `{field_ty}`, which {note}, \
1150 and makes it not a breaking change to become non-zero-sized in the future."))
1157 #[allow(trivial_numeric_casts)]
1158 fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1159 let def = tcx.adt_def(def_id);
1160 def.destructor(tcx); // force the destructor to be evaluated
1162 if def.variants().is_empty() {
1163 if let Some(attr) = tcx.get_attrs(def_id.to_def_id(), sym::repr).next() {
1168 "unsupported representation for zero-variant enum"
1170 .span_label(tcx.def_span(def_id), "zero-variant enum")
1175 let repr_type_ty = def.repr().discr_type().to_ty(tcx);
1176 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1177 if !tcx.features().repr128 {
1179 &tcx.sess.parse_sess,
1181 tcx.def_span(def_id),
1182 "repr with 128-bit type is unstable",
1188 for v in def.variants() {
1189 if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1190 tcx.ensure().typeck(discr_def_id.expect_local());
1194 if def.repr().int.is_none() {
1195 let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind(), Some(CtorKind::Const));
1196 let has_disr = |var: &ty::VariantDef| matches!(var.discr, ty::VariantDiscr::Explicit(_));
1198 let has_non_units = def.variants().iter().any(|var| !is_unit(var));
1199 let disr_units = def.variants().iter().any(|var| is_unit(&var) && has_disr(&var));
1200 let disr_non_unit = def.variants().iter().any(|var| !is_unit(&var) && has_disr(&var));
1202 if disr_non_unit || (disr_units && has_non_units) {
1203 let mut err = struct_span_err!(
1205 tcx.def_span(def_id),
1207 "`#[repr(inttype)]` must be specified"
1213 detect_discriminant_duplicate(tcx, def);
1214 check_transparent(tcx, def);
1217 /// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1218 fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1219 // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1220 // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1221 let report = |dis: Discr<'tcx>, idx, err: &mut Diagnostic| {
1222 let var = adt.variant(idx); // HIR for the duplicate discriminant
1223 let (span, display_discr) = match var.discr {
1224 ty::VariantDiscr::Explicit(discr_def_id) => {
1225 // In the case the discriminant is both a duplicate and overflowed, let the user know
1226 if let hir::Node::AnonConst(expr) = tcx.hir().get_by_def_id(discr_def_id.expect_local())
1227 && let hir::ExprKind::Lit(lit) = &tcx.hir().body(expr.body).value.kind
1228 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1229 && *lit_value != dis.val
1231 (tcx.def_span(discr_def_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1233 // Otherwise, format the value as-is
1234 (tcx.def_span(discr_def_id), format!("`{dis}`"))
1237 // This should not happen.
1238 ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), format!("`{dis}`")),
1239 ty::VariantDiscr::Relative(distance_to_explicit) => {
1240 // At this point we know this discriminant is a duplicate, and was not explicitly
1241 // assigned by the user. Here we iterate backwards to fetch the HIR for the last
1242 // explicitly assigned discriminant, and letting the user know that this was the
1243 // increment startpoint, and how many steps from there leading to the duplicate
1244 if let Some(explicit_idx) =
1245 idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1247 let explicit_variant = adt.variant(explicit_idx);
1248 let ve_ident = var.name;
1249 let ex_ident = explicit_variant.name;
1250 let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1253 tcx.def_span(explicit_variant.def_id),
1255 "discriminant for `{ve_ident}` incremented from this startpoint \
1256 (`{ex_ident}` + {distance_to_explicit} {sp} later \
1257 => `{ve_ident}` = {dis})"
1262 (tcx.def_span(var.def_id), format!("`{dis}`"))
1266 err.span_label(span, format!("{display_discr} assigned here"));
1269 let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1271 // Here we loop through the discriminants, comparing each discriminant to another.
1272 // When a duplicate is detected, we instantiate an error and point to both
1273 // initial and duplicate value. The duplicate discriminant is then discarded by swapping
1274 // it with the last element and decrementing the `vec.len` (which is why we have to evaluate
1275 // `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
1276 // style as we are mutating `discrs` on the fly).
1278 while i < discrs.len() {
1279 let var_i_idx = discrs[i].0;
1280 let mut error: Option<DiagnosticBuilder<'_, _>> = None;
1283 while o < discrs.len() {
1284 let var_o_idx = discrs[o].0;
1286 if discrs[i].1.val == discrs[o].1.val {
1287 let err = error.get_or_insert_with(|| {
1288 let mut ret = struct_span_err!(
1290 tcx.def_span(adt.did()),
1292 "discriminant value `{}` assigned more than once",
1296 report(discrs[i].1, var_i_idx, &mut ret);
1301 report(discrs[o].1, var_o_idx, err);
1303 // Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
1304 discrs[o] = *discrs.last().unwrap();
1311 if let Some(mut e) = error {
1319 pub(super) fn check_type_params_are_used<'tcx>(
1321 generics: &ty::Generics,
1324 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1326 assert_eq!(generics.parent, None);
1328 if generics.own_counts().types == 0 {
1332 let mut params_used = BitSet::new_empty(generics.params.len());
1334 if ty.references_error() {
1335 // If there is already another error, do not emit
1336 // an error for not using a type parameter.
1337 assert!(tcx.sess.has_errors().is_some());
1341 for leaf in ty.walk() {
1342 if let GenericArgKind::Type(leaf_ty) = leaf.unpack()
1343 && let ty::Param(param) = leaf_ty.kind()
1345 debug!("found use of ty param {:?}", param);
1346 params_used.insert(param.index);
1350 for param in &generics.params {
1351 if !params_used.contains(param.index)
1352 && let ty::GenericParamDefKind::Type { .. } = param.kind
1354 let span = tcx.def_span(param.def_id);
1359 "type parameter `{}` is unused",
1362 .span_label(span, "unused type parameter")
1368 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1369 let module = tcx.hir_module_items(module_def_id);
1370 for id in module.items() {
1371 check_item_type(tcx, id);
1375 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) -> ErrorGuaranteed {
1376 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1377 .span_label(span, "recursive `async fn`")
1378 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1380 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1385 /// Emit an error for recursive opaque types.
1387 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1388 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1391 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1392 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1393 fn opaque_type_cycle_error(
1395 opaque_def_id: LocalDefId,
1397 ) -> ErrorGuaranteed {
1398 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1400 let mut label = false;
1401 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
1402 let typeck_results = tcx.typeck(def_id);
1406 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1407 .all(|ty| matches!(ty.kind(), ty::Never))
1412 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1413 .map(|expr| expr.span)
1414 .collect::<Vec<Span>>();
1415 let span_len = spans.len();
1417 err.span_label(spans[0], "this returned value is of `!` type");
1419 let mut multispan: MultiSpan = spans.clone().into();
1421 multispan.push_span_label(span, "this returned value is of `!` type");
1423 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1425 err.help("this error will resolve once the item's body returns a concrete type");
1427 let mut seen = FxHashSet::default();
1429 err.span_label(span, "recursive opaque type");
1431 for (sp, ty) in visitor
1434 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1435 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1438 struct OpaqueTypeCollector {
1439 opaques: Vec<DefId>,
1440 closures: Vec<DefId>,
1442 impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypeCollector {
1443 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1445 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
1446 self.opaques.push(def);
1447 ControlFlow::Continue(())
1449 ty::Closure(def_id, ..) | ty::Generator(def_id, ..) => {
1450 self.closures.push(def_id);
1451 t.super_visit_with(self)
1453 _ => t.super_visit_with(self),
1458 let mut visitor = OpaqueTypeCollector::default();
1459 ty.visit_with(&mut visitor);
1460 for def_id in visitor.opaques {
1461 let ty_span = tcx.def_span(def_id);
1462 if !seen.contains(&ty_span) {
1463 err.span_label(ty_span, &format!("returning this opaque type `{ty}`"));
1464 seen.insert(ty_span);
1466 err.span_label(sp, &format!("returning here with type `{ty}`"));
1469 for closure_def_id in visitor.closures {
1470 let Some(closure_local_did) = closure_def_id.as_local() else { continue; };
1471 let typeck_results = tcx.typeck(closure_local_did);
1473 let mut label_match = |ty: Ty<'_>, span| {
1474 for arg in ty.walk() {
1475 if let ty::GenericArgKind::Type(ty) = arg.unpack()
1476 && let ty::Alias(ty::Opaque, ty::AliasTy { def_id: captured_def_id, .. }) = *ty.kind()
1477 && captured_def_id == opaque_def_id.to_def_id()
1482 "{} captures itself here",
1483 tcx.def_kind(closure_def_id).descr(closure_def_id)
1490 // Label any closure upvars that capture the opaque
1491 for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
1493 label_match(capture.place.ty(), capture.get_path_span(tcx));
1495 // Label any generator locals that capture the opaque
1497 typeck_results.generator_interior_types.as_ref().skip_binder()
1499 label_match(interior_ty.ty, interior_ty.span);
1506 err.span_label(span, "cannot resolve opaque type");