1use std::cell::LazyCell;
2use std::ops::ControlFlow;
3
4use rustc_abi::{ExternAbi, FieldIdx};
5use rustc_attr_data_structures::ReprAttr::ReprPacked;
6use rustc_attr_data_structures::{AttributeKind, find_attr};
7use rustc_data_structures::unord::{UnordMap, UnordSet};
8use rustc_errors::codes::*;
9use rustc_errors::{EmissionGuarantee, MultiSpan};
10use rustc_hir::def::{CtorKind, DefKind};
11use rustc_hir::{LangItem, Node, intravisit};
12use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
13use rustc_infer::traits::{Obligation, ObligationCauseCode, WellFormedLoc};
14use rustc_lint_defs::builtin::{
15 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS, UNSUPPORTED_CALLING_CONVENTIONS,
16};
17use rustc_middle::hir::nested_filter;
18use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
19use rustc_middle::middle::stability::EvalResult;
20use rustc_middle::ty::error::TypeErrorToStringExt;
21use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
22use rustc_middle::ty::util::Discr;
23use rustc_middle::ty::{
24 AdtDef, BottomUpFolder, FnSig, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable,
25 TypeVisitable, TypeVisitableExt, fold_regions,
26};
27use rustc_session::lint::builtin::UNINHABITED_STATIC;
28use rustc_target::spec::{AbiMap, AbiMapping};
29use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
30use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective;
31use rustc_trait_selection::traits;
32use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
33use tracing::{debug, instrument};
34use ty::TypingMode;
35use {rustc_attr_data_structures as attrs, rustc_hir as hir};
36
37use super::compare_impl_item::check_type_bounds;
38use super::*;
39use crate::check::wfcheck::{
40 check_associated_item, check_trait_item, check_variances_for_type_defn, check_where_clauses,
41 enter_wf_checking_ctxt,
42};
43
44fn add_abi_diag_help<T: EmissionGuarantee>(abi: ExternAbi, diag: &mut Diag<'_, T>) {
45 if let ExternAbi::Cdecl { unwind } = abi {
46 let c_abi = ExternAbi::C { unwind };
47 diag.help(format!("use `extern {c_abi}` instead",));
48 } else if let ExternAbi::Stdcall { unwind } = abi {
49 let c_abi = ExternAbi::C { unwind };
50 let system_abi = ExternAbi::System { unwind };
51 diag.help(format!(
52 "if you need `extern {abi}` on win32 and `extern {c_abi}` everywhere else, \
53 use `extern {system_abi}`"
54 ));
55 }
56}
57
58pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: ExternAbi) {
59 match AbiMap::from_target(&tcx.sess.target).canonize_abi(abi, false) {
64 AbiMapping::Direct(..) => (),
65 AbiMapping::Invalid => {
67 tcx.dcx().span_delayed_bug(span, format!("{abi} should be rejected in ast_lowering"));
68 }
69 AbiMapping::Deprecated(..) => {
70 tcx.node_span_lint(UNSUPPORTED_CALLING_CONVENTIONS, hir_id, span, |lint| {
71 lint.primary_message(format!(
72 "{abi} is not a supported ABI for the current target"
73 ));
74 add_abi_diag_help(abi, lint);
75 });
76 }
77 }
78}
79
80pub fn check_custom_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, fn_sig: FnSig<'_>, fn_sig_span: Span) {
81 if fn_sig.abi == ExternAbi::Custom {
82 if !find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Naked(_)) {
84 tcx.dcx().emit_err(crate::errors::AbiCustomClothedFunction {
85 span: fn_sig_span,
86 naked_span: tcx.def_span(def_id).shrink_to_lo(),
87 });
88 }
89 }
90}
91
92fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) {
93 let def = tcx.adt_def(def_id);
94 let span = tcx.def_span(def_id);
95 def.destructor(tcx); if def.repr().simd() {
98 check_simd(tcx, span, def_id);
99 }
100
101 check_transparent(tcx, def);
102 check_packed(tcx, span, def);
103}
104
105fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) {
106 let def = tcx.adt_def(def_id);
107 let span = tcx.def_span(def_id);
108 def.destructor(tcx); check_transparent(tcx, def);
110 check_union_fields(tcx, span, def_id);
111 check_packed(tcx, span, def);
112}
113
114fn allowed_union_or_unsafe_field<'tcx>(
115 tcx: TyCtxt<'tcx>,
116 ty: Ty<'tcx>,
117 typing_env: ty::TypingEnv<'tcx>,
118 span: Span,
119) -> bool {
120 if ty.is_trivially_pure_clone_copy() {
125 return true;
126 }
127 let def_id = tcx
130 .lang_items()
131 .get(LangItem::BikeshedGuaranteedNoDrop)
132 .unwrap_or_else(|| tcx.require_lang_item(LangItem::Copy, span));
133 let Ok(ty) = tcx.try_normalize_erasing_regions(typing_env, ty) else {
134 tcx.dcx().span_delayed_bug(span, "could not normalize field type");
135 return true;
136 };
137 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
138 infcx.predicate_must_hold_modulo_regions(&Obligation::new(
139 tcx,
140 ObligationCause::dummy_with_span(span),
141 param_env,
142 ty::TraitRef::new(tcx, def_id, [ty]),
143 ))
144}
145
146fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
148 let def = tcx.adt_def(item_def_id);
149 assert!(def.is_union());
150
151 let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
152 let args = ty::GenericArgs::identity_for_item(tcx, item_def_id);
153
154 for field in &def.non_enum_variant().fields {
155 if !allowed_union_or_unsafe_field(tcx, field.ty(tcx, args), typing_env, span) {
156 let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {
157 Some(Node::Field(field)) => (field.span, field.ty.span),
159 _ => unreachable!("mir field has to correspond to hir field"),
160 };
161 tcx.dcx().emit_err(errors::InvalidUnionField {
162 field_span,
163 sugg: errors::InvalidUnionFieldSuggestion {
164 lo: ty_span.shrink_to_lo(),
165 hi: ty_span.shrink_to_hi(),
166 },
167 note: (),
168 });
169 return false;
170 }
171 }
172
173 true
174}
175
176fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
178 let ty = tcx.type_of(def_id).instantiate_identity();
184 let span = tcx.def_span(def_id);
185 let layout = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
186 Ok(l) => l,
187 Err(LayoutError::SizeOverflow(_))
189 if matches!(tcx.def_kind(def_id), DefKind::Static{ .. }
190 if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) =>
191 {
192 tcx.dcx().emit_err(errors::TooLargeStatic { span });
193 return;
194 }
195 Err(e) => {
197 tcx.dcx().span_delayed_bug(span, format!("{e:?}"));
198 return;
199 }
200 };
201 if layout.is_uninhabited() {
202 tcx.node_span_lint(
203 UNINHABITED_STATIC,
204 tcx.local_def_id_to_hir_id(def_id),
205 span,
206 |lint| {
207 lint.primary_message("static of uninhabited type");
208 lint
209 .note("uninhabited statics cannot be initialized, and any access would be an immediate error");
210 },
211 );
212 }
213}
214
215fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
218 let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);
219
220 if tcx.sess.opts.actually_rustdoc {
225 return;
226 }
227
228 if tcx.type_of(def_id).instantiate_identity().references_error() {
229 return;
230 }
231 if check_opaque_for_cycles(tcx, def_id).is_err() {
232 return;
233 }
234
235 let _ = check_opaque_meets_bounds(tcx, def_id, origin);
236}
237
238pub(super) fn check_opaque_for_cycles<'tcx>(
240 tcx: TyCtxt<'tcx>,
241 def_id: LocalDefId,
242) -> Result<(), ErrorGuaranteed> {
243 let args = GenericArgs::identity_for_item(tcx, def_id);
244
245 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() {
248 let reported = opaque_type_cycle_error(tcx, def_id);
249 return Err(reported);
250 }
251
252 Ok(())
253}
254
255#[instrument(level = "debug", skip(tcx))]
271fn check_opaque_meets_bounds<'tcx>(
272 tcx: TyCtxt<'tcx>,
273 def_id: LocalDefId,
274 origin: hir::OpaqueTyOrigin<LocalDefId>,
275) -> Result<(), ErrorGuaranteed> {
276 let (span, definition_def_id) =
277 if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {
278 (span, Some(def_id))
279 } else {
280 (tcx.def_span(def_id), None)
281 };
282
283 let defining_use_anchor = match origin {
284 hir::OpaqueTyOrigin::FnReturn { parent, .. }
285 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
286 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
287 };
288 let param_env = tcx.param_env(defining_use_anchor);
289
290 let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
292 TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
293 } else {
294 TypingMode::analysis_in_body(tcx, defining_use_anchor)
295 });
296 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
297
298 let args = match origin {
299 hir::OpaqueTyOrigin::FnReturn { parent, .. }
300 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
301 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(
302 tcx, parent,
303 )
304 .extend_to(tcx, def_id.to_def_id(), |param, _| {
305 tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
306 }),
307 };
308
309 let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
310
311 let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args);
318 let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {
319 ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)),
320 _ => re,
321 });
322
323 for (predicate, pred_span) in
327 tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx, args)
328 {
329 let predicate = predicate.fold_with(&mut BottomUpFolder {
330 tcx,
331 ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
332 lt_op: |lt| lt,
333 ct_op: |ct| ct,
334 });
335
336 ocx.register_obligation(Obligation::new(
337 tcx,
338 ObligationCause::new(
339 span,
340 def_id,
341 ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
342 ),
343 param_env,
344 predicate,
345 ));
346 }
347
348 let misc_cause = ObligationCause::misc(span, def_id);
349 match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
353 Ok(()) => {}
354 Err(ty_err) => {
355 let ty_err = ty_err.to_string(tcx);
361 let guar = tcx.dcx().span_delayed_bug(
362 span,
363 format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
364 );
365 return Err(guar);
366 }
367 }
368
369 let predicate =
373 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
374 ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
375
376 let errors = ocx.select_all_or_error();
379 if !errors.is_empty() {
380 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
381 return Err(guar);
382 }
383
384 let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
385 ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
386
387 if infcx.next_trait_solver() {
388 Ok(())
389 } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
390 origin
391 {
392 let _ = infcx.take_opaque_types();
398 Ok(())
399 } else {
400 for (mut key, mut ty) in infcx.take_opaque_types() {
402 ty.ty = infcx.resolve_vars_if_possible(ty.ty);
403 key = infcx.resolve_vars_if_possible(key);
404 sanity_check_found_hidden_type(tcx, key, ty)?;
405 }
406 Ok(())
407 }
408}
409
410fn best_definition_site_of_opaque<'tcx>(
411 tcx: TyCtxt<'tcx>,
412 opaque_def_id: LocalDefId,
413 origin: hir::OpaqueTyOrigin<LocalDefId>,
414) -> Option<(Span, LocalDefId)> {
415 struct TaitConstraintLocator<'tcx> {
416 opaque_def_id: LocalDefId,
417 tcx: TyCtxt<'tcx>,
418 }
419 impl<'tcx> TaitConstraintLocator<'tcx> {
420 fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
421 if !self.tcx.has_typeck_results(item_def_id) {
422 return ControlFlow::Continue(());
423 }
424
425 let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
426 if !opaque_types_defined_by.contains(&self.opaque_def_id) {
428 return ControlFlow::Continue(());
429 }
430
431 if let Some(hidden_ty) = self
432 .tcx
433 .mir_borrowck(item_def_id)
434 .ok()
435 .and_then(|opaque_types| opaque_types.0.get(&self.opaque_def_id))
436 {
437 ControlFlow::Break((hidden_ty.span, item_def_id))
438 } else {
439 ControlFlow::Continue(())
440 }
441 }
442 }
443 impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
444 type NestedFilter = nested_filter::All;
445 type Result = ControlFlow<(Span, LocalDefId)>;
446 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
447 self.tcx
448 }
449 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
450 intravisit::walk_expr(self, ex)
451 }
452 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
453 self.check(it.owner_id.def_id)?;
454 intravisit::walk_item(self, it)
455 }
456 fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
457 self.check(it.owner_id.def_id)?;
458 intravisit::walk_impl_item(self, it)
459 }
460 fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
461 self.check(it.owner_id.def_id)?;
462 intravisit::walk_trait_item(self, it)
463 }
464 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
465 intravisit::walk_foreign_item(self, it)
466 }
467 }
468
469 let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
470 match origin {
471 hir::OpaqueTyOrigin::FnReturn { parent, .. }
472 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
473 hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
474 let impl_def_id = tcx.local_parent(parent);
475 for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
476 match assoc.kind {
477 ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
478 if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
479 {
480 return Some(span);
481 }
482 }
483 ty::AssocKind::Type { .. } => {}
484 }
485 }
486
487 None
488 }
489 hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
490 tcx.hir_walk_toplevel_module(&mut locator).break_value()
491 }
492 }
493}
494
495fn sanity_check_found_hidden_type<'tcx>(
496 tcx: TyCtxt<'tcx>,
497 key: ty::OpaqueTypeKey<'tcx>,
498 mut ty: ty::OpaqueHiddenType<'tcx>,
499) -> Result<(), ErrorGuaranteed> {
500 if ty.ty.is_ty_var() {
501 return Ok(());
503 }
504 if let ty::Alias(ty::Opaque, alias) = ty.ty.kind() {
505 if alias.def_id == key.def_id.to_def_id() && alias.args == key.args {
506 return Ok(());
509 }
510 }
511 let strip_vars = |ty: Ty<'tcx>| {
512 ty.fold_with(&mut BottomUpFolder {
513 tcx,
514 ty_op: |t| t,
515 ct_op: |c| c,
516 lt_op: |l| match l.kind() {
517 RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
518 _ => l,
519 },
520 })
521 };
522 ty.ty = strip_vars(ty.ty);
525 let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args);
527 let hidden_ty = strip_vars(hidden_ty);
528
529 if hidden_ty == ty.ty {
531 Ok(())
532 } else {
533 let span = tcx.def_span(key.def_id);
534 let other = ty::OpaqueHiddenType { ty: hidden_ty, span };
535 Err(ty.build_mismatch_error(&other, tcx)?.emit())
536 }
537}
538
539fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
548 let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
549 let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
550 hir::GenericBound::Use(bounds, ..) => Some(bounds),
551 _ => None,
552 }) else {
553 return;
555 };
556
557 let mut expected_captures = UnordSet::default();
558 let mut shadowed_captures = UnordSet::default();
559 let mut seen_params = UnordMap::default();
560 let mut prev_non_lifetime_param = None;
561 for arg in precise_capturing_args {
562 let (hir_id, ident) = match *arg {
563 hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
564 hir_id,
565 ident,
566 ..
567 }) => {
568 if prev_non_lifetime_param.is_none() {
569 prev_non_lifetime_param = Some(ident);
570 }
571 (hir_id, ident)
572 }
573 hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
574 if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
575 tcx.dcx().emit_err(errors::LifetimesMustBeFirst {
576 lifetime_span: ident.span,
577 name: ident.name,
578 other_span: prev_non_lifetime_param.span,
579 });
580 }
581 (hir_id, ident)
582 }
583 };
584
585 let ident = ident.normalize_to_macros_2_0();
586 if let Some(span) = seen_params.insert(ident, ident.span) {
587 tcx.dcx().emit_err(errors::DuplicatePreciseCapture {
588 name: ident.name,
589 first_span: span,
590 second_span: ident.span,
591 });
592 }
593
594 match tcx.named_bound_var(hir_id) {
595 Some(ResolvedArg::EarlyBound(def_id)) => {
596 expected_captures.insert(def_id.to_def_id());
597
598 if let DefKind::LifetimeParam = tcx.def_kind(def_id)
604 && let Some(def_id) = tcx
605 .map_opaque_lifetime_to_parent_lifetime(def_id)
606 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
607 {
608 shadowed_captures.insert(def_id);
609 }
610 }
611 _ => {
612 tcx.dcx()
613 .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
614 }
615 }
616 }
617
618 let variances = tcx.variances_of(opaque_def_id);
619 let mut def_id = Some(opaque_def_id.to_def_id());
620 while let Some(generics) = def_id {
621 let generics = tcx.generics_of(generics);
622 def_id = generics.parent;
623
624 for param in &generics.own_params {
625 if expected_captures.contains(¶m.def_id) {
626 assert_eq!(
627 variances[param.index as usize],
628 ty::Invariant,
629 "precise captured param should be invariant"
630 );
631 continue;
632 }
633 if shadowed_captures.contains(¶m.def_id) {
637 continue;
638 }
639
640 match param.kind {
641 ty::GenericParamDefKind::Lifetime => {
642 let use_span = tcx.def_span(param.def_id);
643 let opaque_span = tcx.def_span(opaque_def_id);
644 if variances[param.index as usize] == ty::Invariant {
646 if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
647 && let Some(def_id) = tcx
648 .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
649 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
650 {
651 tcx.dcx().emit_err(errors::LifetimeNotCaptured {
652 opaque_span,
653 use_span,
654 param_span: tcx.def_span(def_id),
655 });
656 } else {
657 if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
658 tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured {
659 opaque_span,
660 param_span: tcx.def_span(param.def_id),
661 });
662 } else {
663 tcx.dcx().emit_err(errors::LifetimeNotCaptured {
668 opaque_span,
669 use_span: opaque_span,
670 param_span: use_span,
671 });
672 }
673 }
674 continue;
675 }
676 }
677 ty::GenericParamDefKind::Type { .. } => {
678 if matches!(tcx.def_kind(param.def_id), DefKind::Trait | DefKind::TraitAlias) {
679 tcx.dcx().emit_err(errors::SelfTyNotCaptured {
681 trait_span: tcx.def_span(param.def_id),
682 opaque_span: tcx.def_span(opaque_def_id),
683 });
684 } else {
685 tcx.dcx().emit_err(errors::ParamNotCaptured {
687 param_span: tcx.def_span(param.def_id),
688 opaque_span: tcx.def_span(opaque_def_id),
689 kind: "type",
690 });
691 }
692 }
693 ty::GenericParamDefKind::Const { .. } => {
694 tcx.dcx().emit_err(errors::ParamNotCaptured {
696 param_span: tcx.def_span(param.def_id),
697 opaque_span: tcx.def_span(opaque_def_id),
698 kind: "const",
699 });
700 }
701 }
702 }
703 }
704}
705
706fn is_enum_of_nonnullable_ptr<'tcx>(
707 tcx: TyCtxt<'tcx>,
708 adt_def: AdtDef<'tcx>,
709 args: GenericArgsRef<'tcx>,
710) -> bool {
711 if adt_def.repr().inhibit_enum_layout_opt() {
712 return false;
713 }
714
715 let [var_one, var_two] = &adt_def.variants().raw[..] else {
716 return false;
717 };
718 let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
719 return false;
720 };
721 matches!(field.ty(tcx, args).kind(), ty::FnPtr(..) | ty::Ref(..))
722}
723
724fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
725 if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
726 if match tcx.type_of(def_id).instantiate_identity().kind() {
727 ty::RawPtr(_, _) => false,
728 ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
729 _ => true,
730 } {
731 tcx.dcx().emit_err(errors::LinkageType { span: tcx.def_span(def_id) });
732 }
733 }
734}
735
736pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
737 let mut res = Ok(());
738 let generics = tcx.generics_of(def_id);
739
740 for param in &generics.own_params {
741 match param.kind {
742 ty::GenericParamDefKind::Lifetime { .. } => {}
743 ty::GenericParamDefKind::Type { has_default, .. } => {
744 if has_default {
745 tcx.ensure_ok().type_of(param.def_id);
746 }
747 }
748 ty::GenericParamDefKind::Const { has_default, .. } => {
749 tcx.ensure_ok().type_of(param.def_id);
750 if has_default {
751 let ct = tcx.const_param_default(param.def_id).skip_binder();
753 if let ty::ConstKind::Unevaluated(uv) = ct.kind() {
754 tcx.ensure_ok().type_of(uv.def);
755 }
756 }
757 }
758 }
759 }
760
761 match tcx.def_kind(def_id) {
762 def_kind @ (DefKind::Static { .. } | DefKind::Const) => {
763 tcx.ensure_ok().generics_of(def_id);
764 tcx.ensure_ok().type_of(def_id);
765 tcx.ensure_ok().predicates_of(def_id);
766 match def_kind {
767 DefKind::Static { .. } => {
768 check_static_inhabited(tcx, def_id);
769 check_static_linkage(tcx, def_id);
770 res = res.and(wfcheck::check_static_item(tcx, def_id));
771 }
772 DefKind::Const => res = res.and(wfcheck::check_const_item(tcx, def_id)),
773 _ => unreachable!(),
774 }
775 return res;
779 }
780 DefKind::Enum => {
781 tcx.ensure_ok().generics_of(def_id);
782 tcx.ensure_ok().type_of(def_id);
783 tcx.ensure_ok().predicates_of(def_id);
784 crate::collect::lower_enum_variant_types(tcx, def_id.to_def_id());
785 check_enum(tcx, def_id);
786 check_variances_for_type_defn(tcx, def_id);
787 }
788 DefKind::Fn => {
789 tcx.ensure_ok().generics_of(def_id);
790 tcx.ensure_ok().type_of(def_id);
791 tcx.ensure_ok().predicates_of(def_id);
792 tcx.ensure_ok().fn_sig(def_id);
793 tcx.ensure_ok().codegen_fn_attrs(def_id);
794 if let Some(i) = tcx.intrinsic(def_id) {
795 intrinsic::check_intrinsic_type(
796 tcx,
797 def_id,
798 tcx.def_ident_span(def_id).unwrap(),
799 i.name,
800 )
801 }
802 }
803 DefKind::Impl { of_trait } => {
804 tcx.ensure_ok().generics_of(def_id);
805 tcx.ensure_ok().type_of(def_id);
806 tcx.ensure_ok().impl_trait_header(def_id);
807 tcx.ensure_ok().predicates_of(def_id);
808 tcx.ensure_ok().associated_items(def_id);
809 if of_trait && let Some(impl_trait_header) = tcx.impl_trait_header(def_id) {
810 res = res.and(
811 tcx.ensure_ok()
812 .coherent_trait(impl_trait_header.trait_ref.instantiate_identity().def_id),
813 );
814
815 if res.is_ok() {
816 check_impl_items_against_trait(tcx, def_id, impl_trait_header);
820 }
821 }
822 }
823 DefKind::Trait => {
824 tcx.ensure_ok().generics_of(def_id);
825 tcx.ensure_ok().trait_def(def_id);
826 tcx.ensure_ok().explicit_super_predicates_of(def_id);
827 tcx.ensure_ok().predicates_of(def_id);
828 tcx.ensure_ok().associated_items(def_id);
829 let assoc_items = tcx.associated_items(def_id);
830 check_on_unimplemented(tcx, def_id);
831
832 for &assoc_item in assoc_items.in_definition_order() {
833 match assoc_item.kind {
834 ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {
835 let trait_args = GenericArgs::identity_for_item(tcx, def_id);
836 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
837 tcx,
838 assoc_item,
839 assoc_item,
840 ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),
841 );
842 }
843 _ => {}
844 }
845 }
846 }
847 DefKind::TraitAlias => {
848 tcx.ensure_ok().generics_of(def_id);
849 tcx.ensure_ok().explicit_implied_predicates_of(def_id);
850 tcx.ensure_ok().explicit_super_predicates_of(def_id);
851 tcx.ensure_ok().predicates_of(def_id);
852 }
853 def_kind @ (DefKind::Struct | DefKind::Union) => {
854 tcx.ensure_ok().generics_of(def_id);
855 tcx.ensure_ok().type_of(def_id);
856 tcx.ensure_ok().predicates_of(def_id);
857
858 let adt = tcx.adt_def(def_id).non_enum_variant();
859 for f in adt.fields.iter() {
860 tcx.ensure_ok().generics_of(f.did);
861 tcx.ensure_ok().type_of(f.did);
862 tcx.ensure_ok().predicates_of(f.did);
863 }
864
865 if let Some((_, ctor_def_id)) = adt.ctor {
866 crate::collect::lower_variant_ctor(tcx, ctor_def_id.expect_local());
867 }
868 match def_kind {
869 DefKind::Struct => check_struct(tcx, def_id),
870 DefKind::Union => check_union(tcx, def_id),
871 _ => unreachable!(),
872 }
873 check_variances_for_type_defn(tcx, def_id);
874 }
875 DefKind::OpaqueTy => {
876 check_opaque_precise_captures(tcx, def_id);
877
878 let origin = tcx.local_opaque_ty_origin(def_id);
879 if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
880 | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin
881 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
882 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
883 {
884 } else {
886 check_opaque(tcx, def_id);
887 }
888
889 tcx.ensure_ok().predicates_of(def_id);
890 tcx.ensure_ok().explicit_item_bounds(def_id);
891 tcx.ensure_ok().explicit_item_self_bounds(def_id);
892 if tcx.is_conditionally_const(def_id) {
893 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
894 tcx.ensure_ok().const_conditions(def_id);
895 }
896
897 return res;
901 }
902 DefKind::TyAlias => {
903 tcx.ensure_ok().generics_of(def_id);
904 tcx.ensure_ok().type_of(def_id);
905 tcx.ensure_ok().predicates_of(def_id);
906 check_type_alias_type_params_are_used(tcx, def_id);
907 if tcx.type_alias_is_lazy(def_id) {
908 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
909 let ty = tcx.type_of(def_id).instantiate_identity();
910 let span = tcx.def_span(def_id);
911 let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
912 wfcx.register_wf_obligation(
913 span,
914 Some(WellFormedLoc::Ty(def_id)),
915 item_ty.into(),
916 );
917 check_where_clauses(wfcx, def_id);
918 Ok(())
919 }));
920 check_variances_for_type_defn(tcx, def_id);
921 }
922 }
923 DefKind::ForeignMod => {
924 let it = tcx.hir_expect_item(def_id);
925 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
926 return Ok(());
927 };
928
929 check_abi(tcx, it.hir_id(), it.span, abi);
930
931 for &item in items {
932 let def_id = item.owner_id.def_id;
933
934 let generics = tcx.generics_of(def_id);
935 let own_counts = generics.own_counts();
936 if generics.own_params.len() - own_counts.lifetimes != 0 {
937 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
938 (_, 0) => ("type", "types", Some("u32")),
939 (0, _) => ("const", "consts", None),
942 _ => ("type or const", "types or consts", None),
943 };
944 let span = tcx.def_span(def_id);
945 struct_span_code_err!(
946 tcx.dcx(),
947 span,
948 E0044,
949 "foreign items may not have {kinds} parameters",
950 )
951 .with_span_label(span, format!("can't have {kinds} parameters"))
952 .with_help(
953 format!(
956 "replace the {} parameters with concrete {}{}",
957 kinds,
958 kinds_pl,
959 egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
960 ),
961 )
962 .emit();
963 }
964
965 tcx.ensure_ok().generics_of(def_id);
966 tcx.ensure_ok().type_of(def_id);
967 tcx.ensure_ok().predicates_of(def_id);
968 if tcx.is_conditionally_const(def_id) {
969 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
970 tcx.ensure_ok().const_conditions(def_id);
971 }
972 match tcx.def_kind(def_id) {
973 DefKind::Fn => {
974 tcx.ensure_ok().codegen_fn_attrs(def_id);
975 tcx.ensure_ok().fn_sig(def_id);
976 let item = tcx.hir_foreign_item(item);
977 let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { bug!() };
978 require_c_abi_if_c_variadic(tcx, sig.decl, abi, item.span);
979 }
980 DefKind::Static { .. } => {
981 tcx.ensure_ok().codegen_fn_attrs(def_id);
982 }
983 _ => (),
984 }
985 }
986 }
987 DefKind::Closure => {
988 tcx.ensure_ok().codegen_fn_attrs(def_id);
992 return res;
1000 }
1001 DefKind::AssocFn => {
1002 tcx.ensure_ok().codegen_fn_attrs(def_id);
1003 tcx.ensure_ok().type_of(def_id);
1004 tcx.ensure_ok().fn_sig(def_id);
1005 tcx.ensure_ok().predicates_of(def_id);
1006 res = res.and(check_associated_item(tcx, def_id));
1007 let assoc_item = tcx.associated_item(def_id);
1008 match assoc_item.container {
1009 ty::AssocItemContainer::Impl => {}
1010 ty::AssocItemContainer::Trait => {
1011 res = res.and(check_trait_item(tcx, def_id));
1012 }
1013 }
1014
1015 return res;
1019 }
1020 DefKind::AssocConst => {
1021 tcx.ensure_ok().type_of(def_id);
1022 tcx.ensure_ok().predicates_of(def_id);
1023 res = res.and(check_associated_item(tcx, def_id));
1024 let assoc_item = tcx.associated_item(def_id);
1025 match assoc_item.container {
1026 ty::AssocItemContainer::Impl => {}
1027 ty::AssocItemContainer::Trait => {
1028 res = res.and(check_trait_item(tcx, def_id));
1029 }
1030 }
1031
1032 return res;
1036 }
1037 DefKind::AssocTy => {
1038 tcx.ensure_ok().predicates_of(def_id);
1039 res = res.and(check_associated_item(tcx, def_id));
1040
1041 let assoc_item = tcx.associated_item(def_id);
1042 let has_type = match assoc_item.container {
1043 ty::AssocItemContainer::Impl => true,
1044 ty::AssocItemContainer::Trait => {
1045 tcx.ensure_ok().explicit_item_bounds(def_id);
1046 tcx.ensure_ok().explicit_item_self_bounds(def_id);
1047 if tcx.is_conditionally_const(def_id) {
1048 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1049 tcx.ensure_ok().const_conditions(def_id);
1050 }
1051 res = res.and(check_trait_item(tcx, def_id));
1052 assoc_item.defaultness(tcx).has_value()
1053 }
1054 };
1055 if has_type {
1056 tcx.ensure_ok().type_of(def_id);
1057 }
1058
1059 return res;
1063 }
1064
1065 DefKind::AnonConst | DefKind::InlineConst => return res,
1069 _ => {}
1070 }
1071 let node = tcx.hir_node_by_def_id(def_id);
1072 res.and(match node {
1073 hir::Node::Crate(_) => bug!("check_well_formed cannot be applied to the crate root"),
1074 hir::Node::Item(item) => wfcheck::check_item(tcx, item),
1075 hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),
1076 _ => unreachable!("{node:?}"),
1077 })
1078}
1079
1080pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1081 let _ = OnUnimplementedDirective::of_item(tcx, def_id.to_def_id());
1083}
1084
1085pub(super) fn check_specialization_validity<'tcx>(
1086 tcx: TyCtxt<'tcx>,
1087 trait_def: &ty::TraitDef,
1088 trait_item: ty::AssocItem,
1089 impl_id: DefId,
1090 impl_item: DefId,
1091) {
1092 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
1093 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
1094 if parent.is_from_trait() {
1095 None
1096 } else {
1097 Some((parent, parent.item(tcx, trait_item.def_id)))
1098 }
1099 });
1100
1101 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1102 match parent_item {
1103 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
1106 Some(Err(parent_impl.def_id()))
1107 }
1108
1109 Some(_) => Some(Ok(())),
1111
1112 None => {
1116 if tcx.defaultness(parent_impl.def_id()).is_default() {
1117 None
1118 } else {
1119 Some(Err(parent_impl.def_id()))
1120 }
1121 }
1122 }
1123 });
1124
1125 let result = opt_result.unwrap_or(Ok(()));
1128
1129 if let Err(parent_impl) = result {
1130 if !tcx.is_impl_trait_in_trait(impl_item) {
1131 report_forbidden_specialization(tcx, impl_item, parent_impl);
1132 } else {
1133 tcx.dcx().delayed_bug(format!("parent item: {parent_impl:?} not marked as default"));
1134 }
1135 }
1136}
1137
1138fn check_impl_items_against_trait<'tcx>(
1139 tcx: TyCtxt<'tcx>,
1140 impl_id: LocalDefId,
1141 impl_trait_header: ty::ImplTraitHeader<'tcx>,
1142) {
1143 let trait_ref = impl_trait_header.trait_ref.instantiate_identity();
1144 if trait_ref.references_error() {
1148 return;
1149 }
1150
1151 let impl_item_refs = tcx.associated_item_def_ids(impl_id);
1152
1153 match impl_trait_header.polarity {
1155 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
1156 ty::ImplPolarity::Negative => {
1157 if let [first_item_ref, ..] = impl_item_refs {
1158 let first_item_span = tcx.def_span(first_item_ref);
1159 struct_span_code_err!(
1160 tcx.dcx(),
1161 first_item_span,
1162 E0749,
1163 "negative impls cannot have any items"
1164 )
1165 .emit();
1166 }
1167 return;
1168 }
1169 }
1170
1171 let trait_def = tcx.trait_def(trait_ref.def_id);
1172
1173 let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
1174
1175 for &impl_item in impl_item_refs {
1176 let ty_impl_item = tcx.associated_item(impl_item);
1177 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
1178 tcx.associated_item(trait_item_id)
1179 } else {
1180 tcx.dcx().span_delayed_bug(tcx.def_span(impl_item), "missing associated item in trait");
1182 continue;
1183 };
1184
1185 let res = tcx.ensure_ok().compare_impl_item(impl_item.expect_local());
1186
1187 if res.is_ok() {
1188 match ty_impl_item.kind {
1189 ty::AssocKind::Fn { .. } => {
1190 compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1191 tcx,
1192 ty_impl_item,
1193 ty_trait_item,
1194 tcx.impl_trait_ref(ty_impl_item.container_id(tcx))
1195 .unwrap()
1196 .instantiate_identity(),
1197 );
1198 }
1199 ty::AssocKind::Const { .. } => {}
1200 ty::AssocKind::Type { .. } => {}
1201 }
1202 }
1203
1204 if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1205 tcx.emit_node_span_lint(
1206 rustc_lint_defs::builtin::DEAD_CODE,
1207 tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1208 tcx.def_span(ty_impl_item.def_id),
1209 errors::UselessImplItem,
1210 )
1211 }
1212
1213 check_specialization_validity(
1214 tcx,
1215 trait_def,
1216 ty_trait_item,
1217 impl_id.to_def_id(),
1218 impl_item,
1219 );
1220 }
1221
1222 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1223 let mut missing_items = Vec::new();
1225
1226 let mut must_implement_one_of: Option<&[Ident]> =
1227 trait_def.must_implement_one_of.as_deref();
1228
1229 for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1230 let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1231
1232 let is_implemented = leaf_def
1233 .as_ref()
1234 .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1235
1236 if !is_implemented
1237 && tcx.defaultness(impl_id).is_final()
1238 && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1240 {
1241 missing_items.push(tcx.associated_item(trait_item_id));
1242 }
1243
1244 let is_implemented_here =
1246 leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1247
1248 if !is_implemented_here {
1249 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1250 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1251 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1252 tcx,
1253 full_impl_span,
1254 trait_item_id,
1255 feature,
1256 reason,
1257 issue,
1258 ),
1259
1260 EvalResult::Allow | EvalResult::Unmarked => {}
1262 }
1263 }
1264
1265 if let Some(required_items) = &must_implement_one_of {
1266 if is_implemented_here {
1267 let trait_item = tcx.associated_item(trait_item_id);
1268 if required_items.contains(&trait_item.ident(tcx)) {
1269 must_implement_one_of = None;
1270 }
1271 }
1272 }
1273
1274 if let Some(leaf_def) = &leaf_def
1275 && !leaf_def.is_final()
1276 && let def_id = leaf_def.item.def_id
1277 && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1278 {
1279 let def_kind = tcx.def_kind(def_id);
1280 let descr = tcx.def_kind_descr(def_kind, def_id);
1281 let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1282 (
1283 format!("async {descr} in trait cannot be specialized"),
1284 "async functions in traits",
1285 )
1286 } else {
1287 (
1288 format!(
1289 "{descr} with return-position `impl Trait` in trait cannot be specialized"
1290 ),
1291 "return position `impl Trait` in traits",
1292 )
1293 };
1294 tcx.dcx()
1295 .struct_span_err(tcx.def_span(def_id), msg)
1296 .with_note(format!(
1297 "specialization behaves in inconsistent and surprising ways with \
1298 {feature}, and for now is disallowed"
1299 ))
1300 .emit();
1301 }
1302 }
1303
1304 if !missing_items.is_empty() {
1305 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1306 missing_items_err(tcx, impl_id, &missing_items, full_impl_span);
1307 }
1308
1309 if let Some(missing_items) = must_implement_one_of {
1310 let attr_span = tcx
1311 .get_attr(trait_ref.def_id, sym::rustc_must_implement_one_of)
1312 .map(|attr| attr.span());
1313
1314 missing_items_must_implement_one_of_err(
1315 tcx,
1316 tcx.def_span(impl_id),
1317 missing_items,
1318 attr_span,
1319 );
1320 }
1321 }
1322}
1323
1324fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1325 let t = tcx.type_of(def_id).instantiate_identity();
1326 if let ty::Adt(def, args) = t.kind()
1327 && def.is_struct()
1328 {
1329 let fields = &def.non_enum_variant().fields;
1330 if fields.is_empty() {
1331 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1332 return;
1333 }
1334
1335 let array_field = &fields[FieldIdx::ZERO];
1336 let array_ty = array_field.ty(tcx, args);
1337 let ty::Array(element_ty, len_const) = array_ty.kind() else {
1338 struct_span_code_err!(
1339 tcx.dcx(),
1340 sp,
1341 E0076,
1342 "SIMD vector's only field must be an array"
1343 )
1344 .with_span_label(tcx.def_span(array_field.did), "not an array")
1345 .emit();
1346 return;
1347 };
1348
1349 if let Some(second_field) = fields.get(FieldIdx::ONE) {
1350 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot have multiple fields")
1351 .with_span_label(tcx.def_span(second_field.did), "excess field")
1352 .emit();
1353 return;
1354 }
1355
1356 if let Some(len) = len_const.try_to_target_usize(tcx) {
1361 if len == 0 {
1362 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1363 return;
1364 } else if len > MAX_SIMD_LANES {
1365 struct_span_code_err!(
1366 tcx.dcx(),
1367 sp,
1368 E0075,
1369 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1370 )
1371 .emit();
1372 return;
1373 }
1374 }
1375
1376 match element_ty.kind() {
1381 ty::Param(_) => (), ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), _ => {
1384 struct_span_code_err!(
1385 tcx.dcx(),
1386 sp,
1387 E0077,
1388 "SIMD vector element type should be a \
1389 primitive scalar (integer/float/pointer) type"
1390 )
1391 .emit();
1392 return;
1393 }
1394 }
1395 }
1396}
1397
1398pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1399 let repr = def.repr();
1400 if repr.packed() {
1401 if let Some(reprs) = attrs::find_attr!(tcx.get_all_attrs(def.did()), attrs::AttributeKind::Repr { reprs, .. } => reprs)
1402 {
1403 for (r, _) in reprs {
1404 if let ReprPacked(pack) = r
1405 && let Some(repr_pack) = repr.pack
1406 && pack != &repr_pack
1407 {
1408 struct_span_code_err!(
1409 tcx.dcx(),
1410 sp,
1411 E0634,
1412 "type has conflicting packed representation hints"
1413 )
1414 .emit();
1415 }
1416 }
1417 }
1418 if repr.align.is_some() {
1419 struct_span_code_err!(
1420 tcx.dcx(),
1421 sp,
1422 E0587,
1423 "type has conflicting packed and align representation hints"
1424 )
1425 .emit();
1426 } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1427 let mut err = struct_span_code_err!(
1428 tcx.dcx(),
1429 sp,
1430 E0588,
1431 "packed type cannot transitively contain a `#[repr(align)]` type"
1432 );
1433
1434 err.span_note(
1435 tcx.def_span(def_spans[0].0),
1436 format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),
1437 );
1438
1439 if def_spans.len() > 2 {
1440 let mut first = true;
1441 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1442 let ident = tcx.item_name(*adt_def);
1443 err.span_note(
1444 *span,
1445 if first {
1446 format!(
1447 "`{}` contains a field of type `{}`",
1448 tcx.type_of(def.did()).instantiate_identity(),
1449 ident
1450 )
1451 } else {
1452 format!("...which contains a field of type `{ident}`")
1453 },
1454 );
1455 first = false;
1456 }
1457 }
1458
1459 err.emit();
1460 }
1461 }
1462}
1463
1464pub(super) fn check_packed_inner(
1465 tcx: TyCtxt<'_>,
1466 def_id: DefId,
1467 stack: &mut Vec<DefId>,
1468) -> Option<Vec<(DefId, Span)>> {
1469 if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().kind() {
1470 if def.is_struct() || def.is_union() {
1471 if def.repr().align.is_some() {
1472 return Some(vec![(def.did(), DUMMY_SP)]);
1473 }
1474
1475 stack.push(def_id);
1476 for field in &def.non_enum_variant().fields {
1477 if let ty::Adt(def, _) = field.ty(tcx, args).kind()
1478 && !stack.contains(&def.did())
1479 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1480 {
1481 defs.push((def.did(), field.ident(tcx).span));
1482 return Some(defs);
1483 }
1484 }
1485 stack.pop();
1486 }
1487 }
1488
1489 None
1490}
1491
1492pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1493 if !adt.repr().transparent() {
1494 return;
1495 }
1496
1497 if adt.is_union() && !tcx.features().transparent_unions() {
1498 feature_err(
1499 &tcx.sess,
1500 sym::transparent_unions,
1501 tcx.def_span(adt.did()),
1502 "transparent unions are unstable",
1503 )
1504 .emit();
1505 }
1506
1507 if adt.variants().len() != 1 {
1508 bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1509 return;
1511 }
1512
1513 let field_infos = adt.all_fields().map(|field| {
1516 let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did));
1517 let typing_env = ty::TypingEnv::non_body_analysis(tcx, field.did);
1518 let layout = tcx.layout_of(typing_env.as_query_input(ty));
1519 let span = tcx.hir_span_if_local(field.did).unwrap();
1521 let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1522 if !trivial {
1523 return (span, trivial, None);
1524 }
1525 fn check_non_exhaustive<'tcx>(
1528 tcx: TyCtxt<'tcx>,
1529 t: Ty<'tcx>,
1530 ) -> ControlFlow<(&'static str, DefId, GenericArgsRef<'tcx>, bool)> {
1531 match t.kind() {
1532 ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)),
1533 ty::Array(ty, _) => check_non_exhaustive(tcx, *ty),
1534 ty::Adt(def, args) => {
1535 if !def.did().is_local()
1536 && !attrs::find_attr!(
1537 tcx.get_all_attrs(def.did()),
1538 AttributeKind::PubTransparent(_)
1539 )
1540 {
1541 let non_exhaustive = def.is_variant_list_non_exhaustive()
1542 || def
1543 .variants()
1544 .iter()
1545 .any(ty::VariantDef::is_field_list_non_exhaustive);
1546 let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1547 if non_exhaustive || has_priv {
1548 return ControlFlow::Break((
1549 def.descr(),
1550 def.did(),
1551 args,
1552 non_exhaustive,
1553 ));
1554 }
1555 }
1556 def.all_fields()
1557 .map(|field| field.ty(tcx, args))
1558 .try_for_each(|t| check_non_exhaustive(tcx, t))
1559 }
1560 _ => ControlFlow::Continue(()),
1561 }
1562 }
1563
1564 (span, trivial, check_non_exhaustive(tcx, ty).break_value())
1565 });
1566
1567 let non_trivial_fields = field_infos
1568 .clone()
1569 .filter_map(|(span, trivial, _non_exhaustive)| if !trivial { Some(span) } else { None });
1570 let non_trivial_count = non_trivial_fields.clone().count();
1571 if non_trivial_count >= 2 {
1572 bad_non_zero_sized_fields(
1573 tcx,
1574 adt,
1575 non_trivial_count,
1576 non_trivial_fields,
1577 tcx.def_span(adt.did()),
1578 );
1579 return;
1580 }
1581 let mut prev_non_exhaustive_1zst = false;
1582 for (span, _trivial, non_exhaustive_1zst) in field_infos {
1583 if let Some((descr, def_id, args, non_exhaustive)) = non_exhaustive_1zst {
1584 if non_trivial_count > 0 || prev_non_exhaustive_1zst {
1587 tcx.node_span_lint(
1588 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS,
1589 tcx.local_def_id_to_hir_id(adt.did().expect_local()),
1590 span,
1591 |lint| {
1592 lint.primary_message(
1593 "zero-sized fields in `repr(transparent)` cannot \
1594 contain external non-exhaustive types",
1595 );
1596 let note = if non_exhaustive {
1597 "is marked with `#[non_exhaustive]`"
1598 } else {
1599 "contains private fields"
1600 };
1601 let field_ty = tcx.def_path_str_with_args(def_id, args);
1602 lint.note(format!(
1603 "this {descr} contains `{field_ty}`, which {note}, \
1604 and makes it not a breaking change to become \
1605 non-zero-sized in the future."
1606 ));
1607 },
1608 )
1609 } else {
1610 prev_non_exhaustive_1zst = true;
1611 }
1612 }
1613 }
1614}
1615
1616#[allow(trivial_numeric_casts)]
1617fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1618 let def = tcx.adt_def(def_id);
1619 def.destructor(tcx); if def.variants().is_empty() {
1622 attrs::find_attr!(
1623 tcx.get_all_attrs(def_id),
1624 attrs::AttributeKind::Repr { reprs, first_span } => {
1625 struct_span_code_err!(
1626 tcx.dcx(),
1627 reprs.first().map(|repr| repr.1).unwrap_or(*first_span),
1628 E0084,
1629 "unsupported representation for zero-variant enum"
1630 )
1631 .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1632 .emit();
1633 }
1634 );
1635 }
1636
1637 for v in def.variants() {
1638 if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1639 tcx.ensure_ok().typeck(discr_def_id.expect_local());
1640 }
1641 }
1642
1643 if def.repr().int.is_none() {
1644 let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind(), Some(CtorKind::Const));
1645 let has_disr = |var: &ty::VariantDef| matches!(var.discr, ty::VariantDiscr::Explicit(_));
1646
1647 let has_non_units = def.variants().iter().any(|var| !is_unit(var));
1648 let disr_units = def.variants().iter().any(|var| is_unit(var) && has_disr(var));
1649 let disr_non_unit = def.variants().iter().any(|var| !is_unit(var) && has_disr(var));
1650
1651 if disr_non_unit || (disr_units && has_non_units) {
1652 struct_span_code_err!(
1653 tcx.dcx(),
1654 tcx.def_span(def_id),
1655 E0732,
1656 "`#[repr(inttype)]` must be specified"
1657 )
1658 .emit();
1659 }
1660 }
1661
1662 detect_discriminant_duplicate(tcx, def);
1663 check_transparent(tcx, def);
1664}
1665
1666fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1668 let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1671 let var = adt.variant(idx); let (span, display_discr) = match var.discr {
1673 ty::VariantDiscr::Explicit(discr_def_id) => {
1674 if let hir::Node::AnonConst(expr) =
1676 tcx.hir_node_by_def_id(discr_def_id.expect_local())
1677 && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1678 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1679 && *lit_value != dis.val
1680 {
1681 (tcx.def_span(discr_def_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1682 } else {
1683 (tcx.def_span(discr_def_id), format!("`{dis}`"))
1685 }
1686 }
1687 ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), format!("`{dis}`")),
1689 ty::VariantDiscr::Relative(distance_to_explicit) => {
1690 if let Some(explicit_idx) =
1695 idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1696 {
1697 let explicit_variant = adt.variant(explicit_idx);
1698 let ve_ident = var.name;
1699 let ex_ident = explicit_variant.name;
1700 let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1701
1702 err.span_label(
1703 tcx.def_span(explicit_variant.def_id),
1704 format!(
1705 "discriminant for `{ve_ident}` incremented from this startpoint \
1706 (`{ex_ident}` + {distance_to_explicit} {sp} later \
1707 => `{ve_ident}` = {dis})"
1708 ),
1709 );
1710 }
1711
1712 (tcx.def_span(var.def_id), format!("`{dis}`"))
1713 }
1714 };
1715
1716 err.span_label(span, format!("{display_discr} assigned here"));
1717 };
1718
1719 let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1720
1721 let mut i = 0;
1728 while i < discrs.len() {
1729 let var_i_idx = discrs[i].0;
1730 let mut error: Option<Diag<'_, _>> = None;
1731
1732 let mut o = i + 1;
1733 while o < discrs.len() {
1734 let var_o_idx = discrs[o].0;
1735
1736 if discrs[i].1.val == discrs[o].1.val {
1737 let err = error.get_or_insert_with(|| {
1738 let mut ret = struct_span_code_err!(
1739 tcx.dcx(),
1740 tcx.def_span(adt.did()),
1741 E0081,
1742 "discriminant value `{}` assigned more than once",
1743 discrs[i].1,
1744 );
1745
1746 report(discrs[i].1, var_i_idx, &mut ret);
1747
1748 ret
1749 });
1750
1751 report(discrs[o].1, var_o_idx, err);
1752
1753 discrs[o] = *discrs.last().unwrap();
1755 discrs.pop();
1756 } else {
1757 o += 1;
1758 }
1759 }
1760
1761 if let Some(e) = error {
1762 e.emit();
1763 }
1764
1765 i += 1;
1766 }
1767}
1768
1769fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1770 if tcx.type_alias_is_lazy(def_id) {
1771 return;
1774 }
1775
1776 let generics = tcx.generics_of(def_id);
1777 if generics.own_counts().types == 0 {
1778 return;
1779 }
1780
1781 let ty = tcx.type_of(def_id).instantiate_identity();
1782 if ty.references_error() {
1783 return;
1785 }
1786
1787 let bounded_params = LazyCell::new(|| {
1789 tcx.explicit_predicates_of(def_id)
1790 .predicates
1791 .iter()
1792 .filter_map(|(predicate, span)| {
1793 let bounded_ty = match predicate.kind().skip_binder() {
1794 ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
1795 ty::ClauseKind::TypeOutlives(pred) => pred.0,
1796 _ => return None,
1797 };
1798 if let ty::Param(param) = bounded_ty.kind() {
1799 Some((param.index, span))
1800 } else {
1801 None
1802 }
1803 })
1804 .collect::<FxIndexMap<_, _>>()
1810 });
1811
1812 let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
1813 for leaf in ty.walk() {
1814 if let GenericArgKind::Type(leaf_ty) = leaf.kind()
1815 && let ty::Param(param) = leaf_ty.kind()
1816 {
1817 debug!("found use of ty param {:?}", param);
1818 params_used.insert(param.index);
1819 }
1820 }
1821
1822 for param in &generics.own_params {
1823 if !params_used.contains(param.index)
1824 && let ty::GenericParamDefKind::Type { .. } = param.kind
1825 {
1826 let span = tcx.def_span(param.def_id);
1827 let param_name = Ident::new(param.name, span);
1828
1829 let has_explicit_bounds = bounded_params.is_empty()
1833 || (*bounded_params).get(¶m.index).is_some_and(|&&pred_sp| pred_sp != span);
1834 let const_param_help = !has_explicit_bounds;
1835
1836 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
1837 span,
1838 param_name,
1839 param_def_kind: tcx.def_descr(param.def_id),
1840 help: errors::UnusedGenericParameterHelp::TyAlias { param_name },
1841 usage_spans: vec![],
1842 const_param_help,
1843 });
1844 diag.code(E0091);
1845 diag.emit();
1846 }
1847 }
1848}
1849
1850fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
1859 let span = tcx.def_span(opaque_def_id);
1860 let mut err = struct_span_code_err!(tcx.dcx(), span, E0720, "cannot resolve opaque type");
1861
1862 let mut label = false;
1863 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
1864 let typeck_results = tcx.typeck(def_id);
1865 if visitor
1866 .returns
1867 .iter()
1868 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1869 .all(|ty| matches!(ty.kind(), ty::Never))
1870 {
1871 let spans = visitor
1872 .returns
1873 .iter()
1874 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1875 .map(|expr| expr.span)
1876 .collect::<Vec<Span>>();
1877 let span_len = spans.len();
1878 if span_len == 1 {
1879 err.span_label(spans[0], "this returned value is of `!` type");
1880 } else {
1881 let mut multispan: MultiSpan = spans.clone().into();
1882 for span in spans {
1883 multispan.push_span_label(span, "this returned value is of `!` type");
1884 }
1885 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1886 }
1887 err.help("this error will resolve once the item's body returns a concrete type");
1888 } else {
1889 let mut seen = FxHashSet::default();
1890 seen.insert(span);
1891 err.span_label(span, "recursive opaque type");
1892 label = true;
1893 for (sp, ty) in visitor
1894 .returns
1895 .iter()
1896 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1897 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1898 {
1899 #[derive(Default)]
1900 struct OpaqueTypeCollector {
1901 opaques: Vec<DefId>,
1902 closures: Vec<DefId>,
1903 }
1904 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
1905 fn visit_ty(&mut self, t: Ty<'tcx>) {
1906 match *t.kind() {
1907 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
1908 self.opaques.push(def);
1909 }
1910 ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
1911 self.closures.push(def_id);
1912 t.super_visit_with(self);
1913 }
1914 _ => t.super_visit_with(self),
1915 }
1916 }
1917 }
1918
1919 let mut visitor = OpaqueTypeCollector::default();
1920 ty.visit_with(&mut visitor);
1921 for def_id in visitor.opaques {
1922 let ty_span = tcx.def_span(def_id);
1923 if !seen.contains(&ty_span) {
1924 let descr = if ty.is_impl_trait() { "opaque " } else { "" };
1925 err.span_label(ty_span, format!("returning this {descr}type `{ty}`"));
1926 seen.insert(ty_span);
1927 }
1928 err.span_label(sp, format!("returning here with type `{ty}`"));
1929 }
1930
1931 for closure_def_id in visitor.closures {
1932 let Some(closure_local_did) = closure_def_id.as_local() else {
1933 continue;
1934 };
1935 let typeck_results = tcx.typeck(closure_local_did);
1936
1937 let mut label_match = |ty: Ty<'_>, span| {
1938 for arg in ty.walk() {
1939 if let ty::GenericArgKind::Type(ty) = arg.kind()
1940 && let ty::Alias(
1941 ty::Opaque,
1942 ty::AliasTy { def_id: captured_def_id, .. },
1943 ) = *ty.kind()
1944 && captured_def_id == opaque_def_id.to_def_id()
1945 {
1946 err.span_label(
1947 span,
1948 format!(
1949 "{} captures itself here",
1950 tcx.def_descr(closure_def_id)
1951 ),
1952 );
1953 }
1954 }
1955 };
1956
1957 for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
1959 {
1960 label_match(capture.place.ty(), capture.get_path_span(tcx));
1961 }
1962 if tcx.is_coroutine(closure_def_id)
1964 && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
1965 {
1966 for interior_ty in &coroutine_layout.field_tys {
1967 label_match(interior_ty.ty, interior_ty.source_info.span);
1968 }
1969 }
1970 }
1971 }
1972 }
1973 }
1974 if !label {
1975 err.span_label(span, "cannot resolve opaque type");
1976 }
1977 err.emit()
1978}
1979
1980pub(super) fn check_coroutine_obligations(
1981 tcx: TyCtxt<'_>,
1982 def_id: LocalDefId,
1983) -> Result<(), ErrorGuaranteed> {
1984 debug_assert!(!tcx.is_typeck_child(def_id.to_def_id()));
1985
1986 let typeck_results = tcx.typeck(def_id);
1987 let param_env = tcx.param_env(def_id);
1988
1989 debug!(?typeck_results.coroutine_stalled_predicates);
1990
1991 let mode = if tcx.next_trait_solver_globally() {
1992 TypingMode::borrowck(tcx, def_id)
1996 } else {
1997 TypingMode::analysis_in_body(tcx, def_id)
1998 };
1999
2000 let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
2005
2006 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2007 for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
2008 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
2009 }
2010
2011 let errors = ocx.select_all_or_error();
2012 debug!(?errors);
2013 if !errors.is_empty() {
2014 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2015 }
2016
2017 if !tcx.next_trait_solver_globally() {
2018 for (key, ty) in infcx.take_opaque_types() {
2021 let hidden_type = infcx.resolve_vars_if_possible(ty);
2022 let key = infcx.resolve_vars_if_possible(key);
2023 sanity_check_found_hidden_type(tcx, key, hidden_type)?;
2024 }
2025 } else {
2026 let _ = infcx.take_opaque_types();
2029 }
2030
2031 Ok(())
2032}