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