1use std::cell::LazyCell;2use std::ops::ControlFlow;34use rustc_abi::{ExternAbi, FieldIdx, ScalableElt};5use rustc_data_structures::unord::{UnordMap, UnordSet};6use rustc_errors::codes::*;7use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, MultiSpan};8use rustc_hir as hir;9use rustc_hir::attrs::ReprAttr::ReprPacked;10use rustc_hir::def::{CtorKind, DefKind};11use rustc_hir::{LangItem, Node, find_attr, intravisit};12use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};13use rustc_infer::traits::{Obligation, ObligationCauseCode, WellFormedLoc};14use rustc_lint_defs::builtin::UNSUPPORTED_CALLING_CONVENTIONS;15use rustc_macros::Diagnostic;16use rustc_middle::hir::nested_filter;17use rustc_middle::middle::resolve_bound_vars::ResolvedArg;18use rustc_middle::middle::stability::EvalResult;19use rustc_middle::ty::error::TypeErrorToStringExt;20use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};21use rustc_middle::ty::util::Discr;22use rustc_middle::ty::{23 AdtDef, BottomUpFolder, FnSig, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable,24 TypeVisitable, TypeVisitableExt, Unnormalized, fold_regions,25};26use rustc_session::lint::builtin::UNINHABITED_STATIC;27use rustc_span::sym;28use rustc_target::spec::{AbiMap, AbiMapping};29use rustc_trait_selection::error_reporting::InferCtxtErrorExt;30use rustc_trait_selection::traits;31use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;32use tracing::{debug, instrument};33use ty::TypingMode;3435use super::compare_impl_item::check_type_bounds;36use super::*;37use crate::check::wfcheck::{38 check_associated_item, check_trait_item, check_type_defn, check_variances_for_type_defn,39 check_where_clauses, enter_wf_checking_ctxt,40};41use crate::diagnostics;4243fn add_abi_diag_help<T: EmissionGuarantee>(abi: ExternAbi, diag: &mut Diag<'_, T>) {44 if let ExternAbi::Cdecl { unwind } = abi {45 let c_abi = ExternAbi::C { unwind };46 diag.help(format!("use `extern {c_abi}` instead",));47 } else if let ExternAbi::Stdcall { unwind } = abi {48 let c_abi = ExternAbi::C { unwind };49 let system_abi = ExternAbi::System { unwind };50 diag.help(format!(51 "if you need `extern {abi}` on win32 and `extern {c_abi}` everywhere else, \52 use `extern {system_abi}`"53 ));54 }55}5657pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: ExternAbi) {58 struct UnsupportedCallingConventions {59 abi: ExternAbi,60 }6162 impl<'a> Diagnostic<'a, ()> for UnsupportedCallingConventions {63 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {64 let Self { abi } = self;65 let mut lint = Diag::new(66 dcx,67 level,68 format!("{abi} is not a supported ABI for the current target"),69 );70 add_abi_diag_help(abi, &mut lint);71 lint72 }73 }74 // FIXME: This should be checked earlier, e.g. in `rustc_ast_lowering`, as this75 // currently only guards function imports, function definitions, and function pointer types.76 // Functions in trait declarations can still use "deprecated" ABIs without any warning.7778 match AbiMap::from_target(&tcx.sess.target).canonize_abi(abi, false) {79 AbiMapping::Direct(..) => (),80 // already erred in rustc_ast_lowering81 AbiMapping::Invalid => {82 tcx.dcx().span_delayed_bug(span, format!("{abi} should be rejected in ast_lowering"));83 }84 AbiMapping::Deprecated(..) => {85 tcx.emit_node_span_lint(86 UNSUPPORTED_CALLING_CONVENTIONS,87 hir_id,88 span,89 UnsupportedCallingConventions { abi },90 );91 }92 }93}9495pub fn check_custom_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, fn_sig: FnSig<'_>, fn_sig_span: Span) {96 if fn_sig.abi() == ExternAbi::Custom {97 // Function definitions that use `extern "custom"` must be naked functions.98 if !find_attr!(tcx, def_id, Naked(_)) {99 tcx.dcx().emit_err(crate::diagnostics::AbiCustomClothedFunction {100 span: fn_sig_span,101 naked_span: tcx.def_span(def_id).shrink_to_lo(),102 });103 }104 }105}106107fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {108 let def = tcx.adt_def(def_id);109 let span = tcx.def_span(def_id);110 def.destructor(tcx); // force the destructor to be evaluated111112 if let Some(scalable) = def.repr().scalable {113 check_scalable_vector(tcx, span, def_id, scalable);114 } else if def.repr().simd() {115 check_simd(tcx, span, def_id);116 }117118 check_transparent(tcx, def);119 check_packed(tcx, span, def);120 check_type_defn(tcx, def_id, false)121}122123fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {124 let def = tcx.adt_def(def_id);125 let span = tcx.def_span(def_id);126 def.destructor(tcx); // force the destructor to be evaluated127 check_transparent(tcx, def);128 check_union_fields(tcx, span, def_id);129 check_packed(tcx, span, def);130 check_type_defn(tcx, def_id, true)131}132133fn allowed_union_or_unsafe_field<'tcx>(134 tcx: TyCtxt<'tcx>,135 ty: Ty<'tcx>,136 typing_env: ty::TypingEnv<'tcx>,137 span: Span,138) -> bool {139 // HACK (not that bad of a hack don't worry): Some codegen tests don't even define proper140 // impls for `Copy`. Let's short-circuit here for this validity check, since a lot of them141 // use unions. We should eventually fix all the tests to define that lang item or use142 // minicore stubs.143 if ty.is_trivially_pure_clone_copy() {144 return true;145 }146 // If `BikeshedGuaranteedNoDrop` is not defined in a `#[no_core]` test, fall back to `Copy`.147 // This is an underapproximation of `BikeshedGuaranteedNoDrop`,148 let def_id = tcx149 .lang_items()150 .get(LangItem::BikeshedGuaranteedNoDrop)151 .unwrap_or_else(|| tcx.require_lang_item(LangItem::Copy, span));152 let Ok(ty) = tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)) else {153 tcx.dcx().span_delayed_bug(span, "could not normalize field type");154 return true;155 };156 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);157 infcx.predicate_must_hold_modulo_regions(&Obligation::new(158 tcx,159 ObligationCause::dummy_with_span(span),160 param_env,161 ty::TraitRef::new(tcx, def_id, [ty]),162 ))163}164165/// Check that the fields of the `union` do not need dropping.166fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {167 let def = tcx.adt_def(item_def_id);168 assert!(def.is_union());169170 let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);171 let args = ty::GenericArgs::identity_for_item(tcx, item_def_id);172173 for field in &def.non_enum_variant().fields {174 if !allowed_union_or_unsafe_field(175 tcx,176 field.ty(tcx, args).skip_norm_wip(),177 typing_env,178 span,179 ) {180 let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {181 // We are currently checking the type this field came from, so it must be local.182 Some(Node::Field(field)) => (field.span, field.ty.span),183 _ => unreachable!("mir field has to correspond to hir field"),184 };185 tcx.dcx().emit_err(diagnostics::InvalidUnionField {186 field_span,187 sugg: diagnostics::InvalidUnionFieldSuggestion {188 lo: ty_span.shrink_to_lo(),189 hi: ty_span.shrink_to_hi(),190 },191 note: (),192 });193 return false;194 }195 }196197 true198}199200/// Check that a `static` is inhabited.201fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {202 #[derive(Diagnostic)]203 #[diag("static of uninhabited type")]204 #[note("uninhabited statics cannot be initialized, and any access would be an immediate error")]205 struct StaticOfUninhabitedType;206207 // Make sure statics are inhabited.208 // Other parts of the compiler assume that there are no uninhabited places. In principle it209 // would be enough to check this for `extern` statics, as statics with an initializer will210 // have UB during initialization if they are uninhabited, but there also seems to be no good211 // reason to allow any statics to be uninhabited.212 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();213 let span = tcx.def_span(def_id);214 let layout = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {215 Ok(l) => l,216 // Foreign statics that overflow their allowed size should emit an error217 Err(LayoutError::SizeOverflow(_))218 if matches!(tcx.def_kind(def_id), DefKind::Static{ .. }219 if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) =>220 {221 tcx.dcx().emit_err(diagnostics::TooLargeStatic { span });222 return;223 }224 // SIMD types with invalid layout (e.g., zero-length) should emit an error225 Err(e @ LayoutError::InvalidSimd { .. }) => {226 let ty_span = tcx.ty_span(def_id);227 tcx.dcx().span_err(ty_span, e.to_string());228 return;229 }230 // Generic statics are rejected, but we still reach this case.231 Err(e) => {232 tcx.dcx().span_delayed_bug(span, format!("{e:?}"));233 return;234 }235 };236 if layout.is_uninhabited() {237 tcx.emit_node_span_lint(238 UNINHABITED_STATIC,239 tcx.local_def_id_to_hir_id(def_id),240 span,241 StaticOfUninhabitedType,242 );243 }244}245246/// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`247/// projections that would result in "inheriting lifetimes".248fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {249 let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);250251 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting252 // `async-std` (and `pub async fn` in general).253 // Since rustdoc doesn't care about the hidden type behind `impl Trait`, just don't look at it!254 // See https://github.com/rust-lang/rust/issues/75100255 if tcx.sess.opts.actually_rustdoc {256 return;257 }258259 if tcx.type_of(def_id).instantiate_identity().skip_norm_wip().references_error() {260 return;261 }262 if check_opaque_for_cycles(tcx, def_id).is_err() {263 return;264 }265266 let _ = check_opaque_meets_bounds(tcx, def_id, origin);267}268269/// Checks that an opaque type does not contain cycles.270pub(super) fn check_opaque_for_cycles<'tcx>(271 tcx: TyCtxt<'tcx>,272 def_id: LocalDefId,273) -> Result<(), ErrorGuaranteed> {274 let args = GenericArgs::identity_for_item(tcx, def_id);275276 // First, try to look at any opaque expansion cycles, considering coroutine fields277 // (even though these aren't necessarily true errors).278 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() {279 let reported = opaque_type_cycle_error(tcx, def_id);280 return Err(reported);281 }282283 Ok(())284}285286/// Check that the hidden type behind `impl Trait` actually implements `Trait`.287///288/// This is mostly checked at the places that specify the opaque type, but we289/// check those cases in the `param_env` of that function, which may have290/// bounds not on this opaque type:291///292/// ```ignore (illustrative)293/// type X<T> = impl Clone;294/// fn f<T: Clone>(t: T) -> X<T> {295/// t296/// }297/// ```298///299/// Without this check the above code is incorrectly accepted: we would ICE if300/// some tried, for example, to clone an `Option<X<&mut ()>>`.301#[instrument(level = "debug", skip(tcx))]302fn check_opaque_meets_bounds<'tcx>(303 tcx: TyCtxt<'tcx>,304 def_id: LocalDefId,305 origin: hir::OpaqueTyOrigin<LocalDefId>,306) -> Result<(), ErrorGuaranteed> {307 let (span, definition_def_id) =308 if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {309 (span, Some(def_id))310 } else {311 (tcx.def_span(def_id), None)312 };313314 let defining_use_anchor = match origin {315 hir::OpaqueTyOrigin::FnReturn { parent, .. }316 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }317 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,318 };319 let param_env = tcx.param_env(defining_use_anchor);320321 // FIXME(#132279): Once `PostBorrowck` is supported in the old solver, this branch should be removed.322 let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {323 TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)324 } else {325 TypingMode::analysis_in_body(tcx, defining_use_anchor)326 });327 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);328329 let args = match origin {330 hir::OpaqueTyOrigin::FnReturn { parent, .. }331 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }332 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(333 tcx, parent,334 )335 .extend_to(tcx, def_id.to_def_id(), |param, _| {336 tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()337 }),338 };339340 let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);341342 // `ReErased` regions appear in the "parent_args" of closures/coroutines.343 // We're ignoring them here and replacing them with fresh region variables.344 // See tests in ui/type-alias-impl-trait/closure_{parent_args,wf_outlives}.rs.345 //346 // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it347 // here rather than using ReErased.348 let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args).skip_norm_wip();349 let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {350 ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)),351 _ => re,352 });353354 // HACK: We eagerly instantiate some bounds to report better errors for them...355 // This isn't necessary for correctness, since we register these bounds when356 // equating the opaque below, but we should clean this up in the new solver.357 for (predicate, pred_span) in tcx358 .explicit_item_bounds(def_id)359 .iter_instantiated_copied(tcx, args)360 .map(Unnormalized::skip_norm_wip)361 {362 let predicate = predicate.fold_with(&mut BottomUpFolder {363 tcx,364 ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },365 lt_op: |lt| lt,366 ct_op: |ct| ct,367 });368369 ocx.register_obligation(Obligation::new(370 tcx,371 ObligationCause::new(372 span,373 def_id,374 ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),375 ),376 param_env,377 predicate,378 ));379 }380381 let misc_cause = ObligationCause::misc(span, def_id);382 // FIXME: We should just register the item bounds here, rather than equating.383 // FIXME(const_trait_impl): When we do that, please make sure to also register384 // the `[const]` bounds.385 match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {386 Ok(()) => {}387 Err(ty_err) => {388 // Some types may be left "stranded" if they can't be reached389 // from a lowered rustc_middle bound but they're mentioned in the HIR.390 // This will happen, e.g., when a nested opaque is inside of a non-391 // existent associated type, like `impl Trait<Missing = impl Trait>`.392 // See <tests/ui/impl-trait/stranded-opaque.rs>.393 let ty_err = ty_err.to_string(tcx);394 let guar = tcx.dcx().span_delayed_bug(395 span,396 format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),397 );398 return Err(guar);399 }400 }401402 // Additionally require the hidden type to be well-formed with only the generics of the opaque type.403 // Defining use functions may have more bounds than the opaque type, which is ok, as long as the404 // hidden type is well formed even without those bounds.405 let predicate =406 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));407 ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));408409 // Check that all obligations are satisfied by the implementation's410 // version.411 let errors = ocx.evaluate_obligations_error_on_ambiguity();412 if !errors.is_empty() {413 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);414 return Err(guar);415 }416417 let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;418 ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;419420 if infcx.next_trait_solver() {421 Ok(())422 } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =423 origin424 {425 // HACK: this should also fall through to the hidden type check below, but the original426 // implementation had a bug where equivalent lifetimes are not identical. This caused us427 // to reject existing stable code that is otherwise completely fine. The real fix is to428 // compare the hidden types via our type equivalence/relation infra instead of doing an429 // identity check.430 let _ = infcx.take_opaque_types();431 Ok(())432 } else {433 // Check that any hidden types found during wf checking match the hidden types that `type_of` sees.434 for (mut key, mut ty) in infcx.take_opaque_types() {435 ty.ty = infcx.resolve_vars_if_possible(ty.ty);436 key = infcx.resolve_vars_if_possible(key);437 sanity_check_found_hidden_type(tcx, key, ty)?;438 }439 Ok(())440 }441}442443fn best_definition_site_of_opaque<'tcx>(444 tcx: TyCtxt<'tcx>,445 opaque_def_id: LocalDefId,446 origin: hir::OpaqueTyOrigin<LocalDefId>,447) -> Option<(Span, LocalDefId)> {448 struct TaitConstraintLocator<'tcx> {449 opaque_def_id: LocalDefId,450 tcx: TyCtxt<'tcx>,451 }452 impl<'tcx> TaitConstraintLocator<'tcx> {453 fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {454 if !self.tcx.has_typeck_results(item_def_id) {455 return ControlFlow::Continue(());456 }457458 let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);459 // Don't try to check items that cannot possibly constrain the type.460 if !opaque_types_defined_by.contains(&self.opaque_def_id) {461 return ControlFlow::Continue(());462 }463464 if let Some(hidden_ty) = self465 .tcx466 .mir_borrowck(item_def_id)467 .ok()468 .and_then(|opaque_types| opaque_types.get(&self.opaque_def_id))469 {470 ControlFlow::Break((hidden_ty.span, item_def_id))471 } else {472 ControlFlow::Continue(())473 }474 }475 }476 impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {477 type NestedFilter = nested_filter::All;478 type Result = ControlFlow<(Span, LocalDefId)>;479 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {480 self.tcx481 }482 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {483 intravisit::walk_expr(self, ex)484 }485 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {486 self.check(it.owner_id.def_id)?;487 intravisit::walk_item(self, it)488 }489 fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {490 self.check(it.owner_id.def_id)?;491 intravisit::walk_impl_item(self, it)492 }493 fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {494 self.check(it.owner_id.def_id)?;495 intravisit::walk_trait_item(self, it)496 }497 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {498 intravisit::walk_foreign_item(self, it)499 }500 }501502 let mut locator = TaitConstraintLocator { tcx, opaque_def_id };503 match origin {504 hir::OpaqueTyOrigin::FnReturn { parent, .. }505 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),506 hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {507 let impl_def_id = tcx.local_parent(parent);508 for assoc in tcx.associated_items(impl_def_id).in_definition_order() {509 match assoc.kind {510 ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {511 if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())512 {513 return Some(span);514 }515 }516 ty::AssocKind::Type { .. } => {}517 }518 }519520 None521 }522 hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {523 tcx.hir_walk_toplevel_module(&mut locator).break_value()524 }525 }526}527528fn sanity_check_found_hidden_type<'tcx>(529 tcx: TyCtxt<'tcx>,530 key: ty::OpaqueTypeKey<'tcx>,531 mut ty: ty::ProvisionalHiddenType<'tcx>,532) -> Result<(), ErrorGuaranteed> {533 if ty.ty.is_ty_var() {534 // Nothing was actually constrained.535 return Ok(());536 }537 if let &ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = ty.ty.kind() {538 if def_id == key.def_id.to_def_id() && args == key.args {539 // Nothing was actually constrained, this is an opaque usage that was540 // only discovered to be opaque after inference vars resolved.541 return Ok(());542 }543 }544 let erase_re_vars = |ty: Ty<'tcx>| {545 fold_regions(tcx, ty, |r, _| match r.kind() {546 RegionKind::ReVar(_) => tcx.lifetimes.re_erased,547 _ => r,548 })549 };550 // Closures frequently end up containing erased lifetimes in their final representation.551 // These correspond to lifetime variables that never got resolved, so we patch this up here.552 ty.ty = erase_re_vars(ty.ty);553 // Get the hidden type.554 let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args).skip_norm_wip();555 let hidden_ty = erase_re_vars(hidden_ty);556557 // If the hidden types differ, emit a type mismatch diagnostic.558 if hidden_ty == ty.ty {559 Ok(())560 } else {561 let span = tcx.def_span(key.def_id);562 let other = ty::ProvisionalHiddenType { ty: hidden_ty, span };563 Err(ty.build_mismatch_error(&other, tcx)?.emit())564 }565}566567/// Check that the opaque's precise captures list is valid (if present).568/// We check this for regular `impl Trait`s and also RPITITs, even though the latter569/// are technically GATs.570///571/// This function is responsible for:572/// 1. Checking that all type/const params are mention in the captures list.573/// 2. Checking that all lifetimes that are implicitly captured are mentioned.574/// 3. Asserting that all parameters mentioned in the captures list are invariant.575fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {576 let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();577 let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {578 hir::GenericBound::Use(bounds, ..) => Some(bounds),579 _ => None,580 }) else {581 // No precise capturing args; nothing to validate582 return;583 };584585 let mut expected_captures = UnordSet::default();586 let mut shadowed_captures = UnordSet::default();587 let mut seen_params = UnordMap::default();588 let mut prev_non_lifetime_param = None;589 for arg in precise_capturing_args {590 let (hir_id, ident) = match *arg {591 hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {592 hir_id,593 ident,594 ..595 }) => {596 if prev_non_lifetime_param.is_none() {597 prev_non_lifetime_param = Some(ident);598 }599 (hir_id, ident)600 }601 hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {602 if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {603 tcx.dcx().emit_err(diagnostics::LifetimesMustBeFirst {604 lifetime_span: ident.span,605 name: ident.name,606 other_span: prev_non_lifetime_param.span,607 });608 }609 (hir_id, ident)610 }611 };612613 let ident = ident.normalize_to_macros_2_0();614 if let Some(span) = seen_params.insert(ident, ident.span) {615 tcx.dcx().emit_err(diagnostics::DuplicatePreciseCapture {616 name: ident.name,617 first_span: span,618 second_span: ident.span,619 });620 }621622 match tcx.named_bound_var(hir_id) {623 Some(ResolvedArg::EarlyBound(def_id)) => {624 expected_captures.insert(def_id.to_def_id());625626 // Make sure we allow capturing these lifetimes through `Self` and627 // `T::Assoc` projection syntax, too. These will occur when we only628 // see lifetimes are captured after hir-lowering -- this aligns with629 // the cases that were stabilized with the `impl_trait_projection`630 // feature -- see <https://github.com/rust-lang/rust/pull/115659>.631 if let DefKind::LifetimeParam = tcx.def_kind(def_id)632 && let Some(def_id) = tcx633 .map_opaque_lifetime_to_parent_lifetime(def_id)634 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))635 {636 shadowed_captures.insert(def_id);637 }638 }639 _ => {640 tcx.dcx()641 .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");642 }643 }644 }645646 let variances = tcx.variances_of(opaque_def_id);647 let mut def_id = Some(opaque_def_id.to_def_id());648 while let Some(generics) = def_id {649 let generics = tcx.generics_of(generics);650 def_id = generics.parent;651652 for param in &generics.own_params {653 if expected_captures.contains(¶m.def_id) {654 assert_eq!(655 variances[param.index as usize],656 ty::Invariant,657 "precise captured param should be invariant"658 );659 continue;660 }661 // If a param is shadowed by a early-bound (duplicated) lifetime, then662 // it may or may not be captured as invariant, depending on if it shows663 // up through `Self` or `T::Assoc` syntax.664 if shadowed_captures.contains(¶m.def_id) {665 continue;666 }667668 match param.kind {669 ty::GenericParamDefKind::Lifetime => {670 let use_span = tcx.def_span(param.def_id);671 let opaque_span = tcx.def_span(opaque_def_id);672 // Check if the lifetime param was captured but isn't named in the precise captures list.673 if variances[param.index as usize] == ty::Invariant {674 if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))675 && let Some(def_id) = tcx676 .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())677 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))678 {679 tcx.dcx().emit_err(diagnostics::LifetimeNotCaptured {680 opaque_span,681 use_span,682 param_span: tcx.def_span(def_id),683 });684 } else {685 if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {686 tcx.dcx().emit_err(diagnostics::LifetimeImplicitlyCaptured {687 opaque_span,688 param_span: tcx.def_span(param.def_id),689 });690 } else {691 // If the `use_span` is actually just the param itself, then we must692 // have not duplicated the lifetime but captured the original.693 // The "effective" `use_span` will be the span of the opaque itself,694 // and the param span will be the def span of the param.695 tcx.dcx().emit_err(diagnostics::LifetimeNotCaptured {696 opaque_span,697 use_span: opaque_span,698 param_span: use_span,699 });700 }701 }702 continue;703 }704 }705 ty::GenericParamDefKind::Type { .. } => {706 if matches!(tcx.def_kind(param.def_id), DefKind::Trait | DefKind::TraitAlias) {707 // FIXME(precise_capturing): Structured suggestion for this would be useful708 tcx.dcx().emit_err(diagnostics::SelfTyNotCaptured {709 trait_span: tcx.def_span(param.def_id),710 opaque_span: tcx.def_span(opaque_def_id),711 });712 } else {713 // FIXME(precise_capturing): Structured suggestion for this would be useful714 tcx.dcx().emit_err(diagnostics::ParamNotCaptured {715 param_span: tcx.def_span(param.def_id),716 opaque_span: tcx.def_span(opaque_def_id),717 kind: "type",718 });719 }720 }721 ty::GenericParamDefKind::Const { .. } => {722 // FIXME(precise_capturing): Structured suggestion for this would be useful723 tcx.dcx().emit_err(diagnostics::ParamNotCaptured {724 param_span: tcx.def_span(param.def_id),725 opaque_span: tcx.def_span(opaque_def_id),726 kind: "const",727 });728 }729 }730 }731 }732}733734fn is_enum_of_nonnullable_ptr<'tcx>(735 tcx: TyCtxt<'tcx>,736 adt_def: AdtDef<'tcx>,737 args: GenericArgsRef<'tcx>,738) -> bool {739 if adt_def.repr().inhibit_enum_layout_opt() {740 return false;741 }742743 let [var_one, var_two] = &adt_def.variants().raw[..] else {744 return false;745 };746 let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {747 return false;748 };749 matches!(field.ty(tcx, args).skip_norm_wip().kind(), ty::FnPtr(..) | ty::Ref(..))750}751752fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {753 if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {754 if match tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {755 ty::RawPtr(_, _) => false,756 ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),757 _ => true,758 } {759 tcx.dcx().emit_err(diagnostics::LinkageType { span: tcx.def_span(def_id) });760 }761 }762}763764pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {765 let mut res = Ok(());766 let generics = tcx.generics_of(def_id);767768 for param in &generics.own_params {769 match param.kind {770 ty::GenericParamDefKind::Lifetime { .. } => {}771 ty::GenericParamDefKind::Type { has_default, .. } => {772 if has_default {773 tcx.ensure_ok().type_of(param.def_id);774 }775 }776 ty::GenericParamDefKind::Const { has_default, .. } => {777 tcx.ensure_ok().type_of(param.def_id);778 if has_default {779 // need to store default and type of default780 let ct = tcx.const_param_default(param.def_id).skip_binder();781 if let ty::ConstKind::Unevaluated(uv) = ct.kind()782 && let Some(def_id) = uv.kind.opt_def_id()783 {784 tcx.ensure_ok().type_of(def_id);785 }786 }787 }788 }789 }790791 match tcx.def_kind(def_id) {792 DefKind::Static { .. } => {793 tcx.ensure_ok().generics_of(def_id);794 tcx.ensure_ok().type_of(def_id);795 tcx.ensure_ok().predicates_of(def_id);796797 check_static_inhabited(tcx, def_id);798 check_static_linkage(tcx, def_id);799 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();800 res = res.and(wfcheck::check_static_item(801 tcx, def_id, ty, /* should_check_for_sync */ true,802 ));803804 // Only `Node::Item` and `Node::ForeignItem` still have HIR based805 // checks. Returning early here does not miss any checks and806 // avoids this query from having a direct dependency edge on the HIR807 return res;808 }809 DefKind::Enum => {810 tcx.ensure_ok().generics_of(def_id);811 tcx.ensure_ok().type_of(def_id);812 tcx.ensure_ok().predicates_of(def_id);813 crate::collect::check_enum_variant_types(tcx, def_id);814 check_enum(tcx, def_id);815 check_variances_for_type_defn(tcx, def_id);816 res = res.and(check_type_defn(tcx, def_id, true));817 // enums are fully handled by the type based check and have no hir wfcheck logic818 return res;819 }820 DefKind::Fn => {821 tcx.ensure_ok().generics_of(def_id);822 tcx.ensure_ok().type_of(def_id);823 tcx.ensure_ok().predicates_of(def_id);824 tcx.ensure_ok().fn_sig(def_id);825 tcx.ensure_ok().codegen_fn_attrs(def_id);826 if let Some(i) = tcx.intrinsic(def_id) {827 intrinsic::check_intrinsic_type(828 tcx,829 def_id,830 tcx.def_ident_span(def_id).unwrap(),831 i.name,832 )833 }834 }835 DefKind::Impl { of_trait } => {836 tcx.ensure_ok().generics_of(def_id);837 tcx.ensure_ok().type_of(def_id);838 tcx.ensure_ok().predicates_of(def_id);839 tcx.ensure_ok().associated_items(def_id);840 if of_trait {841 let impl_trait_header = tcx.impl_trait_header(def_id);842 res = res.and(tcx.ensure_result().coherent_trait(843 impl_trait_header.trait_ref.instantiate_identity().skip_norm_wip().def_id,844 ));845846 if res.is_ok() {847 // Checking this only makes sense if the all trait impls satisfy basic848 // requirements (see `coherent_trait` query), otherwise849 // we run into infinite recursions a lot.850 check_impl_items_against_trait(tcx, def_id, impl_trait_header);851 }852 }853 }854 DefKind::Trait => {855 tcx.ensure_ok().generics_of(def_id);856 tcx.ensure_ok().trait_def(def_id);857 tcx.ensure_ok().explicit_super_predicates_of(def_id);858 tcx.ensure_ok().predicates_of(def_id);859 tcx.ensure_ok().associated_items(def_id);860 let assoc_items = tcx.associated_items(def_id);861862 for &assoc_item in assoc_items.in_definition_order() {863 match assoc_item.kind {864 ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {865 let trait_args = GenericArgs::identity_for_item(tcx, def_id);866 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(867 tcx,868 assoc_item,869 assoc_item,870 ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),871 );872 }873 _ => {}874 }875 }876 res = res.and(wfcheck::check_trait(tcx, def_id));877 wfcheck::check_gat_where_clauses(tcx, def_id);878 // Trait aliases do not have hir checks anymore879 return res;880 }881 DefKind::TraitAlias => {882 tcx.ensure_ok().generics_of(def_id);883 tcx.ensure_ok().explicit_implied_predicates_of(def_id);884 tcx.ensure_ok().explicit_super_predicates_of(def_id);885 tcx.ensure_ok().predicates_of(def_id);886 res = res.and(wfcheck::check_trait(tcx, def_id));887 // Trait aliases do not have hir checks anymore888 return res;889 }890 def_kind @ (DefKind::Struct | DefKind::Union) => {891 tcx.ensure_ok().generics_of(def_id);892 tcx.ensure_ok().type_of(def_id);893 tcx.ensure_ok().predicates_of(def_id);894895 let adt = tcx.adt_def(def_id).non_enum_variant();896 for f in adt.fields.iter() {897 tcx.ensure_ok().generics_of(f.did);898 tcx.ensure_ok().type_of(f.did);899 tcx.ensure_ok().predicates_of(f.did);900 }901902 if let Some((_, ctor_def_id)) = adt.ctor {903 crate::collect::check_ctor(tcx, ctor_def_id.expect_local());904 }905 check_variances_for_type_defn(tcx, def_id);906 res = res.and(match def_kind {907 DefKind::Struct => check_struct(tcx, def_id),908 DefKind::Union => check_union(tcx, def_id),909 _ => unreachable!(),910 });911 // structs and enums are fully handled by the type based check and have no hir wfcheck logic912 return res;913 }914 DefKind::OpaqueTy => {915 check_opaque_precise_captures(tcx, def_id);916917 let origin = tcx.local_opaque_ty_origin(def_id);918 if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }919 | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin920 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)921 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()922 {923 // Skip opaques from RPIT in traits with no default body.924 } else {925 check_opaque(tcx, def_id);926 }927928 tcx.ensure_ok().predicates_of(def_id);929 tcx.ensure_ok().explicit_item_bounds(def_id);930 tcx.ensure_ok().explicit_item_self_bounds(def_id);931 if tcx.is_conditionally_const(def_id) {932 tcx.ensure_ok().explicit_implied_const_bounds(def_id);933 tcx.ensure_ok().const_conditions(def_id);934 }935936 // Only `Node::Item` and `Node::ForeignItem` still have HIR based937 // checks. Returning early here does not miss any checks and938 // avoids this query from having a direct dependency edge on the HIR939 return res;940 }941 DefKind::Const { .. } => {942 tcx.ensure_ok().generics_of(def_id);943 tcx.ensure_ok().type_of(def_id);944 tcx.ensure_ok().predicates_of(def_id);945946 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {947 let ty = tcx.type_of(def_id).instantiate_identity();948 let ty_span = tcx.ty_span(def_id);949 let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);950 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());951 wfcx.register_bound(952 traits::ObligationCause::new(953 ty_span,954 def_id,955 ObligationCauseCode::SizedConstOrStatic,956 ),957 tcx.param_env(def_id),958 ty,959 tcx.require_lang_item(LangItem::Sized, ty_span),960 );961 check_where_clauses(wfcx, def_id);962963 if tcx.is_type_const(def_id) {964 wfcheck::check_type_const(wfcx, def_id, ty, true)?;965 }966 Ok(())967 }));968969 // Only `Node::Item` and `Node::ForeignItem` still have HIR based970 // checks. Returning early here does not miss any checks and971 // avoids this query from having a direct dependency edge on the HIR972 return res;973 }974 DefKind::TyAlias => {975 tcx.ensure_ok().generics_of(def_id);976 tcx.ensure_ok().type_of(def_id);977 tcx.ensure_ok().predicates_of(def_id);978 let ty = tcx.type_of(def_id).instantiate_identity();979 let span = tcx.def_span(def_id);980 if tcx.type_alias_is_lazy(def_id) {981 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {982 let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);983 wfcx.register_wf_obligation(984 span,985 Some(WellFormedLoc::Ty(def_id)),986 item_ty.into(),987 );988 check_where_clauses(wfcx, def_id);989 Ok(())990 }));991 } else {992 check_type_alias_type_params_are_used(tcx, def_id);993 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {994 // HACK: We sometimes incidentally check that const arguments have the correct995 // type as a side effect of the anon const desugaring. To make this "consistent"996 // for users we explicitly check `ConstArgHasType` clauses so that const args997 // that don't go through an anon const still have their types checked.998 //999 // We use the unnormalized type as this mirrors the behaviour that we previously1000 // would have had when all const arguments were anon consts.1001 //1002 // Changing this to normalized obligations is a breaking change:1003 // `type Bar = [(); panic!()];` would become an error1004 if let Some(unnormalized_obligations) = wfcx.unnormalized_obligations(span, ty.skip_norm_wip())1005 {1006 let filtered_obligations =1007 unnormalized_obligations.into_iter().filter(|o| {1008 matches!(o.predicate.kind().skip_binder(),1009 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _))1010 if matches!(ct.kind(), ty::ConstKind::Param(..)))1011 });1012 wfcx.ocx.register_obligations(filtered_obligations)1013 }1014 Ok(())1015 }));1016 }10171018 // Only `Node::Item` and `Node::ForeignItem` still have HIR based1019 // checks. Returning early here does not miss any checks and1020 // avoids this query from having a direct dependency edge on the HIR1021 return res;1022 }1023 DefKind::ForeignMod => {1024 let it = tcx.hir_expect_item(def_id);1025 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {1026 return Ok(());1027 };10281029 check_abi(tcx, it.hir_id(), it.span, abi);10301031 for &item in items {1032 let def_id = item.owner_id.def_id;10331034 let generics = tcx.generics_of(def_id);1035 let own_counts = generics.own_counts();1036 if generics.own_params.len() - own_counts.lifetimes != 0 {1037 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {1038 (_, 0) => ("type", "types", Some("u32")),1039 // We don't specify an example value, because we can't generate1040 // a valid value for any type.1041 (0, _) => ("const", "consts", None),1042 _ => ("type or const", "types or consts", None),1043 };1044 let name = if find_attr!(tcx, def_id, RustcEiiForeignItem) {1045 "externally implementable items"1046 } else {1047 "foreign items"1048 };10491050 let span = tcx.def_span(def_id);1051 struct_span_code_err!(1052 tcx.dcx(),1053 span,1054 E0044,1055 "{name} may not have {kinds} parameters",1056 )1057 .with_span_label(span, format!("can't have {kinds} parameters"))1058 .with_help(1059 // FIXME: once we start storing spans for type arguments, turn this1060 // into a suggestion.1061 format!(1062 "replace the {} parameters with concrete {}{}",1063 kinds,1064 kinds_pl,1065 egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),1066 ),1067 )1068 .emit();1069 }10701071 tcx.ensure_ok().generics_of(def_id);1072 tcx.ensure_ok().type_of(def_id);1073 tcx.ensure_ok().predicates_of(def_id);1074 if tcx.is_conditionally_const(def_id) {1075 tcx.ensure_ok().explicit_implied_const_bounds(def_id);1076 tcx.ensure_ok().const_conditions(def_id);1077 }1078 match tcx.def_kind(def_id) {1079 DefKind::Fn => {1080 tcx.ensure_ok().codegen_fn_attrs(def_id);1081 tcx.ensure_ok().fn_sig(def_id);1082 let item = tcx.hir_foreign_item(item);1083 let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { bug!() };1084 check_c_variadic_abi(tcx, sig.decl, abi, item.span);1085 }1086 DefKind::Static { .. } => {1087 tcx.ensure_ok().codegen_fn_attrs(def_id);1088 }1089 _ => (),1090 }1091 }1092 // Doesn't have any hir based checks1093 return res;1094 }1095 DefKind::Closure => {1096 // This is guaranteed to be called by metadata encoding,1097 // we still call it in wfcheck eagerly to ensure errors in codegen1098 // attrs prevent lints from spamming the output.1099 tcx.ensure_ok().codegen_fn_attrs(def_id);1100 // We do not call `type_of` for closures here as that1101 // depends on typecheck and would therefore hide1102 // any further errors in case one typeck fails.11031104 // Only `Node::Item` and `Node::ForeignItem` still have HIR based1105 // checks. Returning early here does not miss any checks and1106 // avoids this query from having a direct dependency edge on the HIR1107 return res;1108 }1109 DefKind::AssocFn => {1110 tcx.ensure_ok().codegen_fn_attrs(def_id);1111 tcx.ensure_ok().type_of(def_id);1112 tcx.ensure_ok().fn_sig(def_id);1113 tcx.ensure_ok().predicates_of(def_id);1114 res = res.and(check_associated_item(tcx, def_id));1115 let assoc_item = tcx.associated_item(def_id);1116 match assoc_item.container {1117 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}1118 ty::AssocContainer::Trait => {1119 res = res.and(check_trait_item(tcx, def_id));1120 }1121 }11221123 // Only `Node::Item` and `Node::ForeignItem` still have HIR based1124 // checks. Returning early here does not miss any checks and1125 // avoids this query from having a direct dependency edge on the HIR1126 return res;1127 }1128 DefKind::AssocConst { .. } => {1129 tcx.ensure_ok().type_of(def_id);1130 tcx.ensure_ok().predicates_of(def_id);1131 res = res.and(check_associated_item(tcx, def_id));1132 let assoc_item = tcx.associated_item(def_id);1133 match assoc_item.container {1134 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}1135 ty::AssocContainer::Trait => {1136 res = res.and(check_trait_item(tcx, def_id));1137 }1138 }11391140 // Only `Node::Item` and `Node::ForeignItem` still have HIR based1141 // checks. Returning early here does not miss any checks and1142 // avoids this query from having a direct dependency edge on the HIR1143 return res;1144 }1145 DefKind::AssocTy => {1146 tcx.ensure_ok().predicates_of(def_id);1147 res = res.and(check_associated_item(tcx, def_id));11481149 let assoc_item = tcx.associated_item(def_id);1150 let has_type = match assoc_item.container {1151 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,1152 ty::AssocContainer::Trait => {1153 tcx.ensure_ok().explicit_item_bounds(def_id);1154 tcx.ensure_ok().explicit_item_self_bounds(def_id);1155 if tcx.is_conditionally_const(def_id) {1156 tcx.ensure_ok().explicit_implied_const_bounds(def_id);1157 tcx.ensure_ok().const_conditions(def_id);1158 }1159 res = res.and(check_trait_item(tcx, def_id));1160 assoc_item.defaultness(tcx).has_value()1161 }1162 };1163 if has_type {1164 tcx.ensure_ok().type_of(def_id);1165 }11661167 // Only `Node::Item` and `Node::ForeignItem` still have HIR based1168 // checks. Returning early here does not miss any checks and1169 // avoids this query from having a direct dependency edge on the HIR1170 return res;1171 }11721173 // These have no wf checks1174 DefKind::AnonConst1175 | DefKind::InlineConst1176 | DefKind::ExternCrate1177 | DefKind::Macro(..)1178 | DefKind::Use1179 | DefKind::GlobalAsm1180 | DefKind::Mod => return res,1181 _ => {}1182 }1183 let node = tcx.hir_node_by_def_id(def_id);1184 res.and(match node {1185 hir::Node::Crate(_) => bug!("check_well_formed cannot be applied to the crate root"),1186 hir::Node::Item(item) => wfcheck::check_item(tcx, item),1187 hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),1188 _ => unreachable!("{node:?}"),1189 })1190}11911192pub(super) fn check_specialization_validity<'tcx>(1193 tcx: TyCtxt<'tcx>,1194 trait_def: &ty::TraitDef,1195 trait_item: ty::AssocItem,1196 impl_id: DefId,1197 impl_item: DefId,1198) {1199 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };1200 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {1201 if parent.is_from_trait() {1202 None1203 } else {1204 Some((parent, parent.item(tcx, trait_item.def_id)))1205 }1206 });12071208 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {1209 match parent_item {1210 // Parent impl exists, and contains the parent item we're trying to specialize, but1211 // doesn't mark it `default`.1212 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {1213 Some(Err(parent_impl.def_id()))1214 }12151216 // Parent impl contains item and makes it specializable.1217 Some(_) => Some(Ok(())),12181219 // Parent impl doesn't mention the item. This means it's inherited from the1220 // grandparent. In that case, if parent is a `default impl`, inherited items use the1221 // "defaultness" from the grandparent, else they are final.1222 None => {1223 if tcx.defaultness(parent_impl.def_id()).is_default() {1224 None1225 } else {1226 Some(Err(parent_impl.def_id()))1227 }1228 }1229 }1230 });12311232 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the1233 // item. This is allowed, the item isn't actually getting specialized here.1234 let result = opt_result.unwrap_or(Ok(()));12351236 if let Err(parent_impl) = result {1237 if !tcx.is_impl_trait_in_trait(impl_item) {1238 let span = tcx.def_span(impl_item);1239 let ident = tcx.item_ident(impl_item);12401241 let err = match tcx.span_of_impl(parent_impl) {1242 Ok(sp) => diagnostics::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp },1243 Err(cname) => diagnostics::ImplNotMarkedDefault::Err { span, ident, cname },1244 };12451246 tcx.dcx().emit_err(err);1247 } else {1248 tcx.dcx().delayed_bug(format!("parent item: {parent_impl:?} not marked as default"));1249 }1250 }1251}12521253fn check_overriding_final_trait_item<'tcx>(1254 tcx: TyCtxt<'tcx>,1255 trait_item: ty::AssocItem,1256 impl_item: ty::AssocItem,1257) {1258 if trait_item.defaultness(tcx).is_final() {1259 tcx.dcx().emit_err(diagnostics::OverridingFinalTraitFunction {1260 impl_span: tcx.def_span(impl_item.def_id),1261 trait_span: tcx.def_span(trait_item.def_id),1262 ident: tcx.item_ident(impl_item.def_id),1263 });1264 }1265}12661267fn check_impl_items_against_trait<'tcx>(1268 tcx: TyCtxt<'tcx>,1269 impl_id: LocalDefId,1270 impl_trait_header: ty::ImplTraitHeader<'tcx>,1271) {1272 let trait_ref = impl_trait_header.trait_ref.instantiate_identity().skip_norm_wip();1273 // If the trait reference itself is erroneous (so the compilation is going1274 // to fail), skip checking the items here -- the `impl_item` table in `tcx`1275 // isn't populated for such impls.1276 if trait_ref.references_error() {1277 return;1278 }12791280 let impl_item_refs = tcx.associated_item_def_ids(impl_id);12811282 // Negative impls are not expected to have any items1283 match impl_trait_header.polarity {1284 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}1285 ty::ImplPolarity::Negative => {1286 if let [first_item_ref, ..] = *impl_item_refs {1287 let first_item_span = tcx.def_span(first_item_ref);1288 struct_span_code_err!(1289 tcx.dcx(),1290 first_item_span,1291 E0749,1292 "negative impls cannot have any items"1293 )1294 .emit();1295 }1296 return;1297 }1298 }12991300 let trait_def = tcx.trait_def(trait_ref.def_id);13011302 let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);13031304 for &impl_item in impl_item_refs {1305 let ty_impl_item = tcx.associated_item(impl_item);1306 let ty_trait_item = match ty_impl_item.expect_trait_impl() {1307 Ok(trait_item_id) => tcx.associated_item(trait_item_id),1308 Err(ErrorGuaranteed { .. }) => continue,1309 };13101311 let res = tcx.ensure_result().compare_impl_item(impl_item.expect_local());1312 if res.is_ok() {1313 match ty_impl_item.kind {1314 ty::AssocKind::Fn { .. } => {1315 compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(1316 tcx,1317 ty_impl_item,1318 ty_trait_item,1319 tcx.impl_trait_ref(ty_impl_item.container_id(tcx))1320 .instantiate_identity()1321 .skip_norm_wip(),1322 );1323 }1324 ty::AssocKind::Const { .. } => {}1325 ty::AssocKind::Type { .. } => {}1326 }1327 }13281329 if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {1330 tcx.emit_node_span_lint(1331 rustc_lint_defs::builtin::DEAD_CODE,1332 tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),1333 tcx.def_span(ty_impl_item.def_id),1334 diagnostics::UselessImplItem,1335 )1336 }13371338 check_specialization_validity(1339 tcx,1340 trait_def,1341 ty_trait_item,1342 impl_id.to_def_id(),1343 impl_item,1344 );13451346 check_overriding_final_trait_item(tcx, ty_trait_item, ty_impl_item);1347 }13481349 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {1350 // Check for missing items from trait1351 let mut missing_items = Vec::new();13521353 let mut must_implement_one_of: Option<&[Ident]> =1354 trait_def.must_implement_one_of.as_deref();13551356 for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {1357 let leaf_def = ancestors.leaf_def(tcx, trait_item_id);13581359 let is_implemented = leaf_def1360 .as_ref()1361 .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());13621363 if !is_implemented1364 && tcx.defaultness(impl_id).is_final()1365 // unsized types don't need to implement methods that have `Self: Sized` bounds.1366 && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))1367 {1368 missing_items.push(tcx.associated_item(trait_item_id));1369 }13701371 // true if this item is specifically implemented in this impl1372 let is_implemented_here =1373 leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());13741375 if !is_implemented_here {1376 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));1377 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {1378 // When the feature `pin_ergonomics` is disabled, we report `Drop::drop` is missing,1379 // instead of `Drop::drop` is unstable that might be confusing.1380 EvalResult::Deny { .. }1381 if !tcx.features().pin_ergonomics()1382 && tcx.is_lang_item(trait_ref.def_id, hir::LangItem::Drop)1383 && tcx.item_name(trait_item_id) == sym::drop =>1384 {1385 missing_items.push(tcx.associated_item(trait_item_id));1386 }1387 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(1388 tcx,1389 full_impl_span,1390 trait_item_id,1391 feature,1392 reason,1393 issue,1394 ),13951396 // Unmarked default bodies are considered stable (at least for now).1397 EvalResult::Allow | EvalResult::Unmarked => {}1398 }1399 }14001401 if let Some(required_items) = &must_implement_one_of {1402 if is_implemented_here {1403 let trait_item = tcx.associated_item(trait_item_id);1404 if required_items.contains(&trait_item.ident(tcx)) {1405 must_implement_one_of = None;1406 }1407 }1408 }14091410 if let Some(leaf_def) = &leaf_def1411 && !leaf_def.is_final()1412 && let def_id = leaf_def.item.def_id1413 && tcx.impl_method_has_trait_impl_trait_tys(def_id)1414 {1415 let def_kind = tcx.def_kind(def_id);1416 let descr = tcx.def_kind_descr(def_kind, def_id);1417 let (msg, feature) = if tcx.asyncness(def_id).is_async() {1418 (1419 format!("async {descr} in trait cannot be specialized"),1420 "async functions in traits",1421 )1422 } else {1423 (1424 format!(1425 "{descr} with return-position `impl Trait` in trait cannot be specialized"1426 ),1427 "return position `impl Trait` in traits",1428 )1429 };1430 tcx.dcx()1431 .struct_span_err(tcx.def_span(def_id), msg)1432 .with_note(format!(1433 "specialization behaves in inconsistent and surprising ways with \1434 {feature}, and for now is disallowed"1435 ))1436 .emit();1437 }1438 }14391440 if !missing_items.is_empty() {1441 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));1442 missing_items_err(tcx, impl_id, &missing_items, full_impl_span);1443 }14441445 if let Some(missing_items) = must_implement_one_of {1446 let attr_span = find_attr!(tcx, trait_ref.def_id, RustcMustImplementOneOf {attr_span, ..} => *attr_span);14471448 missing_items_must_implement_one_of_err(1449 tcx,1450 tcx.def_span(impl_id),1451 missing_items,1452 attr_span,1453 );1454 }1455 }1456}14571458fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {1459 let t = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();1460 if let ty::Adt(def, args) = t.kind()1461 && def.is_struct()1462 {1463 let fields = &def.non_enum_variant().fields;1464 if fields.is_empty() {1465 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();1466 return;1467 }14681469 let array_field = &fields[FieldIdx::ZERO];1470 let array_ty = array_field.ty(tcx, args).skip_norm_wip();1471 let ty::Array(element_ty, len_const) = array_ty.kind() else {1472 struct_span_code_err!(1473 tcx.dcx(),1474 sp,1475 E0076,1476 "SIMD vector's only field must be an array"1477 )1478 .with_span_label(tcx.def_span(array_field.did), "not an array")1479 .emit();1480 return;1481 };14821483 if let Some(second_field) = fields.get(FieldIdx::ONE) {1484 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot have multiple fields")1485 .with_span_label(tcx.def_span(second_field.did), "excess field")1486 .emit();1487 return;1488 }14891490 // FIXME(repr_simd): This check is nice, but perhaps unnecessary due to the fact1491 // we do not expect users to implement their own `repr(simd)` types. If they could,1492 // this check is easily side-steppable by hiding the const behind normalization.1493 // The consequence is that the error is, in general, only observable post-mono.1494 if let Some(len) = len_const.try_to_target_usize(tcx) {1495 if len == 0 {1496 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();1497 return;1498 } else if len > MAX_SIMD_LANES {1499 struct_span_code_err!(1500 tcx.dcx(),1501 sp,1502 E0075,1503 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",1504 )1505 .emit();1506 return;1507 }1508 }15091510 // Check that we use types valid for use in the lanes of a SIMD "vector register"1511 // These are scalar types which directly match a "machine" type1512 // Yes: Integers, floats, "thin" pointers1513 // No: char, "wide" pointers, compound types1514 match element_ty.kind() {1515 ty::Param(_) => (), // pass struct<T>([T; 4]) through, let monomorphization catch errors1516 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), // struct([u8; 4]) is ok1517 _ => {1518 struct_span_code_err!(1519 tcx.dcx(),1520 sp,1521 E0077,1522 "SIMD vector element type should be a \1523 primitive scalar (integer/float/pointer) type"1524 )1525 .emit();1526 return;1527 }1528 }1529 }1530}15311532#[tracing::instrument(skip(tcx), level = "debug")]1533fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalable: ScalableElt) {1534 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();1535 let ty::Adt(def, args) = ty.kind() else { return };1536 if !def.is_struct() {1537 tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");1538 return;1539 }15401541 let fields = &def.non_enum_variant().fields;1542 match scalable {1543 ScalableElt::ElementCount(..) if fields.is_empty() => {1544 let mut err =1545 tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");1546 err.help("scalable vector types' only field must be a primitive scalar type");1547 err.emit();1548 return;1549 }1550 ScalableElt::ElementCount(..) if fields.len() >= 2 => {1551 tcx.dcx().struct_span_err(span, "scalable vectors cannot have multiple fields").emit();1552 return;1553 }1554 ScalableElt::Container if fields.is_empty() => {1555 let mut err = tcx1556 .dcx()1557 .struct_span_err(span, "scalable vector tuples must have at least one field");1558 err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");1559 err.emit();1560 return;1561 }1562 ScalableElt::Container if fields.len() > 8 => {1563 let mut err = tcx1564 .dcx()1565 .struct_span_err(span, "scalable vector tuples can have at most eight fields");1566 err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");1567 err.emit();1568 return;1569 }1570 _ => {}1571 }15721573 match scalable {1574 ScalableElt::ElementCount(..) => {1575 let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args).skip_norm_wip();15761577 // Check that `element_ty` only uses types valid in the lanes of a scalable vector1578 // register: scalar types which directly match a "machine" type - integers, floats and1579 // bools1580 match element_ty.kind() {1581 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Bool => (),1582 _ => {1583 let mut err = tcx.dcx().struct_span_err(1584 span,1585 "element type of a scalable vector must be a primitive scalar",1586 );1587 err.help("only `u*`, `i*`, `f*` and `bool` types are accepted");1588 err.emit();1589 }1590 }1591 }1592 ScalableElt::Container => {1593 let mut prev_field_ty = None;1594 for field in fields.iter() {1595 let element_ty = field.ty(tcx, args).skip_norm_wip();1596 if let ty::Adt(def, _) = element_ty.kind()1597 && def.repr().scalable()1598 {1599 match def1600 .repr()1601 .scalable1602 .expect("`repr().scalable.is_some()` != `repr().scalable()`")1603 {1604 ScalableElt::ElementCount(_) => { /* expected field */ }1605 ScalableElt::Container => {1606 tcx.dcx().span_err(1607 tcx.def_span(field.did),1608 "scalable vector structs cannot contain other scalable vector structs",1609 );1610 break;1611 }1612 }1613 } else {1614 tcx.dcx().span_err(1615 tcx.def_span(field.did),1616 "scalable vector structs can only have scalable vector fields",1617 );1618 break;1619 }16201621 if let Some(prev_ty) = prev_field_ty.replace(element_ty)1622 && prev_ty != element_ty1623 {1624 tcx.dcx().span_err(1625 tcx.def_span(field.did),1626 "all fields in a scalable vector struct must be the same type",1627 );1628 break;1629 }1630 }1631 }1632 }1633}16341635pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {1636 let repr = def.repr();1637 if repr.packed() {1638 // `#[pin_v2]` on a packed type is unsound: drop glue for a packed type moves an1639 // over-aligned field to an aligned location before running its destructor, which would1640 // move a structurally pinned field out from under a `Pin<&mut _>` that was handed out.1641 if def.is_pin_project() {1642 tcx.dcx().emit_err(diagnostics::PinV2OnPacked {1643 span: sp,1644 pin_v2_span: find_attr!(tcx, def.did(), PinV2(span) => *span),1645 adt_name: tcx.item_name(def.did()),1646 });1647 }1648 if let Some(reprs) = find_attr!(tcx, def.did(), Repr { reprs, .. } => reprs) {1649 for (r, _) in reprs {1650 if let ReprPacked(pack) = r1651 && let Some(repr_pack) = repr.pack1652 && pack != &repr_pack1653 {1654 struct_span_code_err!(1655 tcx.dcx(),1656 sp,1657 E0634,1658 "type has conflicting packed representation hints"1659 )1660 .emit();1661 }1662 }1663 }1664 if repr.align.is_some() {1665 struct_span_code_err!(1666 tcx.dcx(),1667 sp,1668 E0587,1669 "type has conflicting packed and align representation hints"1670 )1671 .emit();1672 } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {1673 let mut err = struct_span_code_err!(1674 tcx.dcx(),1675 sp,1676 E0588,1677 "packed type cannot transitively contain a `#[repr(align)]` type"1678 );16791680 err.span_note(1681 tcx.def_span(def_spans[0].0),1682 format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),1683 );16841685 if def_spans.len() > 2 {1686 let mut first = true;1687 for (adt_def, span) in def_spans.iter().skip(1).rev() {1688 let ident = tcx.item_name(*adt_def);1689 err.span_note(1690 *span,1691 if first {1692 format!(1693 "`{}` contains a field of type `{}`",1694 tcx.type_of(def.did()).instantiate_identity().skip_norm_wip(),1695 ident1696 )1697 } else {1698 format!("...which contains a field of type `{ident}`")1699 },1700 );1701 first = false;1702 }1703 }17041705 err.emit();1706 }1707 }1708}17091710pub(super) fn check_packed_inner(1711 tcx: TyCtxt<'_>,1712 def_id: DefId,1713 stack: &mut Vec<DefId>,1714) -> Option<Vec<(DefId, Span)>> {1715 if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {1716 if def.is_struct() || def.is_union() {1717 if def.repr().align.is_some() {1718 return Some(vec![(def.did(), DUMMY_SP)]);1719 }17201721 stack.push(def_id);1722 for field in &def.non_enum_variant().fields {1723 if let ty::Adt(def, _) = field.ty(tcx, args).skip_norm_wip().kind()1724 && !stack.contains(&def.did())1725 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)1726 {1727 defs.push((def.did(), field.ident(tcx).span));1728 return Some(defs);1729 }1730 }1731 stack.pop();1732 }1733 }17341735 None1736}17371738pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {1739 if !adt.repr().transparent() {1740 return;1741 }17421743 if adt.is_union() && !tcx.features().transparent_unions() {1744 feature_err(1745 &tcx.sess,1746 sym::transparent_unions,1747 tcx.def_span(adt.did()),1748 "transparent unions are unstable",1749 )1750 .emit();1751 }17521753 if adt.variants().len() != 1 {1754 bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());1755 // Don't bother checking the fields.1756 return;1757 }1758 let variant = adt.variant(VariantIdx::ZERO);17591760 if variant.fields.len() <= 1 {1761 // No need to check when there's at most one field.1762 return;1763 }17641765 let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());17661767 /// We call a field "trivial" for `repr(transparent)` purposes if it can be ignored.1768 /// IOW, `repr(transparent)` is allowed if there is at most one non-trivial field.1769 /// This enum captures all the reasons why a field might not be "trivial".1770 enum NonTrivialReason<'tcx> {1771 UnknownLayout,1772 NonZeroSized,1773 NonTrivialAlignment,1774 PrivateField { inside: Ty<'tcx> },1775 NonExhaustive { ty: Ty<'tcx> },1776 ReprC { ty: Ty<'tcx> },1777 }1778 struct NonTrivialFieldInfo<'tcx> {1779 span: Span,1780 reason: NonTrivialReason<'tcx>,1781 }17821783 /// Check if this type is "trivial" for `repr(transparent)`. If not, return the reason why1784 /// and the problematic type.1785 fn is_trivial<'tcx>(1786 tcx: TyCtxt<'tcx>,1787 typing_env: ty::TypingEnv<'tcx>,1788 ty: Ty<'tcx>,1789 ) -> ControlFlow<NonTrivialReason<'tcx>> {1790 // We can encounter projections during traversal, so ensure the type is normalized.1791 let ty =1792 tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);1793 match ty.kind() {1794 ty::Tuple(list) => list.iter().try_for_each(|t| is_trivial(tcx, typing_env, t)),1795 ty::Array(ty, _) => is_trivial(tcx, typing_env, *ty),1796 ty::Adt(def, args) => {1797 if !def.did().is_local() && !find_attr!(tcx, def.did(), RustcPubTransparent(_)) {1798 let non_exhaustive = def.is_variant_list_non_exhaustive()1799 || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);1800 if non_exhaustive {1801 return ControlFlow::Break(NonTrivialReason::NonExhaustive { ty });1802 }1803 let has_priv = def.all_fields().any(|f| !f.vis.is_public());1804 if has_priv {1805 return ControlFlow::Break(NonTrivialReason::PrivateField { inside: ty });1806 }1807 }1808 if def.repr().c() {1809 return ControlFlow::Break(NonTrivialReason::ReprC { ty });1810 }1811 def.all_fields()1812 .map(|field| field.ty(tcx, args).skip_norm_wip())1813 .try_for_each(|t| is_trivial(tcx, typing_env, t))1814 }1815 _ => ControlFlow::Continue(()),1816 }1817 }18181819 let non_trivial_fields = variant1820 .fields1821 .iter()1822 .filter_map(|field| {1823 let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did)).skip_norm_wip();1824 let layout = tcx.layout_of(typing_env.as_query_input(ty));1825 // We are currently checking the type this field came from, so it must be local1826 let span = tcx.hir_span_if_local(field.did).unwrap();1827 // Rule out non-1ZST1828 if !layout.is_ok_and(|layout| layout.is_1zst()) {1829 let reason = match layout {1830 Err(_) => NonTrivialReason::UnknownLayout,1831 Ok(layout) => {1832 if !(layout.is_sized() && layout.size.bytes() == 0) {1833 NonTrivialReason::NonZeroSized1834 } else {1835 NonTrivialReason::NonTrivialAlignment1836 }1837 }1838 };1839 return Some(NonTrivialFieldInfo { span, reason });1840 }1841 // Recursively check for other things that have to be ruled out.1842 if let Some(reason) = is_trivial(tcx, typing_env, ty).break_value() {1843 return Some(NonTrivialFieldInfo { span, reason });1844 }1845 // Otherwise,1846 None1847 })1848 .collect::<Vec<_>>();18491850 if non_trivial_fields.len() > 1 {1851 let count = non_trivial_fields.len();1852 let desc = if adt.is_enum() {1853 format_args!("the variant of a transparent {}", adt.descr())1854 } else {1855 format_args!("transparent {}", adt.descr())1856 };1857 let ty_span = tcx.def_span(adt.did());1858 let mut diag = tcx.dcx().struct_span_err(1859 ty_span,1860 format!("{desc} needs at most one non-trivial field, but has {count}"),1861 );1862 diag.code(E0690);18631864 // Label for the type.1865 diag.span_label(ty_span, format!("needs at most one non-trivial field, but has {count}"));1866 // Label for each non-trivial field.1867 for field in non_trivial_fields {1868 let msg = match field.reason {1869 NonTrivialReason::UnknownLayout => {1870 format!("this field is generic and hence may have non-zero size")1871 }1872 NonTrivialReason::NonZeroSized => format!("this field has non-zero size"),1873 NonTrivialReason::NonTrivialAlignment => format!("this field requires alignment"),1874 NonTrivialReason::PrivateField { inside } => format!(1875 "this field contains `{inside}`, which has private fields, so it could become non-zero-sized in the future"1876 ),1877 NonTrivialReason::NonExhaustive { ty } => format!(1878 "this field contains `{ty}`, which is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future"1879 ),1880 NonTrivialReason::ReprC { ty } => format!(1881 "this field contains `{ty}`, which is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets"1882 ),1883 };1884 diag.span_label(field.span, msg);1885 }18861887 diag.emit();1888 return;1889 }1890}18911892#[allow(trivial_numeric_casts)]1893fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {1894 let def = tcx.adt_def(def_id);1895 def.destructor(tcx); // force the destructor to be evaluated18961897 if def.variants().is_empty() {1898 find_attr!(tcx, def_id, Repr { reprs, first_span } => {1899 struct_span_code_err!(1900 tcx.dcx(),1901 reprs.first().map(|repr| repr.1).unwrap_or(*first_span),1902 E0084,1903 "unsupported representation for zero-variant enum"1904 )1905 .with_span_label(tcx.def_span(def_id), "zero-variant enum")1906 .emit();1907 });1908 }19091910 for v in def.variants() {1911 if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {1912 tcx.ensure_ok().typeck(discr_def_id.expect_local());1913 }1914 }19151916 if def.repr().int.is_none() {1917 let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind(), Some(CtorKind::Const));1918 let get_disr = |var: &ty::VariantDef| match var.discr {1919 ty::VariantDiscr::Explicit(disr) => Some(disr),1920 ty::VariantDiscr::Relative(_) => None,1921 };19221923 let non_unit = def.variants().iter().find(|var| !is_unit(var));1924 let disr_unit =1925 def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var));1926 let disr_non_unit =1927 def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var));19281929 if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) {1930 let mut err = struct_span_code_err!(1931 tcx.dcx(),1932 tcx.def_span(def_id),1933 E0732,1934 "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"1935 );1936 if let Some(disr_non_unit) = disr_non_unit {1937 err.span_label(1938 tcx.def_span(disr_non_unit),1939 "explicit discriminant on non-unit variant specified here",1940 );1941 } else {1942 err.span_label(1943 tcx.def_span(disr_unit.unwrap()),1944 "explicit discriminant specified here",1945 );1946 err.span_label(1947 tcx.def_span(non_unit.unwrap().def_id),1948 "non-unit discriminant declared here",1949 );1950 }1951 err.emit();1952 }1953 }19541955 detect_discriminant_duplicate(tcx, def);1956 check_transparent(tcx, def);1957}19581959/// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal1960fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {1961 // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.1962 // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`1963 let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {1964 let var = adt.variant(idx); // HIR for the duplicate discriminant1965 let (span, display_discr) = match var.discr {1966 ty::VariantDiscr::Explicit(discr_def_id) => {1967 // In the case the discriminant is both a duplicate and overflowed, let the user know1968 if let hir::Node::AnonConst(expr) =1969 tcx.hir_node_by_def_id(discr_def_id.expect_local())1970 && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind1971 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node1972 && *lit_value != dis.val1973 {1974 (tcx.def_span(discr_def_id), format!("`{dis}` (overflowed from `{lit_value}`)"))1975 } else {1976 // Otherwise, format the value as-is1977 (tcx.def_span(discr_def_id), format!("`{dis}`"))1978 }1979 }1980 // This should not happen.1981 ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), format!("`{dis}`")),1982 ty::VariantDiscr::Relative(distance_to_explicit) => {1983 // At this point we know this discriminant is a duplicate, and was not explicitly1984 // assigned by the user. Here we iterate backwards to fetch the HIR for the last1985 // explicitly assigned discriminant, and letting the user know that this was the1986 // increment startpoint, and how many steps from there leading to the duplicate1987 if let Some(explicit_idx) =1988 idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)1989 {1990 let explicit_variant = adt.variant(explicit_idx);1991 let ve_ident = var.name;1992 let ex_ident = explicit_variant.name;1993 let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };19941995 err.span_label(1996 tcx.def_span(explicit_variant.def_id),1997 format!(1998 "discriminant for `{ve_ident}` incremented from this startpoint \1999 (`{ex_ident}` + {distance_to_explicit} {sp} later \2000 => `{ve_ident}` = {dis})"
Findings
✓ No findings reported for this file.