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};
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::*;
39
40fn add_abi_diag_help<T: EmissionGuarantee>(abi: ExternAbi, diag: &mut Diag<'_, T>) {
41 if let ExternAbi::Cdecl { unwind } = abi {
42 let c_abi = ExternAbi::C { unwind };
43 diag.help(format!("use `extern {c_abi}` instead",));
44 } else if let ExternAbi::Stdcall { unwind } = abi {
45 let c_abi = ExternAbi::C { unwind };
46 let system_abi = ExternAbi::System { unwind };
47 diag.help(format!(
48 "if you need `extern {abi}` on win32 and `extern {c_abi}` everywhere else, \
49 use `extern {system_abi}`"
50 ));
51 }
52}
53
54pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: ExternAbi) {
55 match AbiMap::from_target(&tcx.sess.target).canonize_abi(abi, false) {
60 AbiMapping::Direct(..) => (),
61 AbiMapping::Invalid => {
63 tcx.dcx().span_delayed_bug(span, format!("{abi} should be rejected in ast_lowering"));
64 }
65 AbiMapping::Deprecated(..) => {
66 tcx.node_span_lint(UNSUPPORTED_CALLING_CONVENTIONS, hir_id, span, |lint| {
67 lint.primary_message(format!(
68 "{abi} is not a supported ABI for the current target"
69 ));
70 add_abi_diag_help(abi, lint);
71 });
72 }
73 }
74}
75
76pub fn check_custom_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, fn_sig: FnSig<'_>, fn_sig_span: Span) {
77 if fn_sig.abi == ExternAbi::Custom {
78 if !find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Naked(_)) {
80 tcx.dcx().emit_err(crate::errors::AbiCustomClothedFunction {
81 span: fn_sig_span,
82 naked_span: tcx.def_span(def_id).shrink_to_lo(),
83 });
84 }
85 }
86}
87
88fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) {
89 let def = tcx.adt_def(def_id);
90 let span = tcx.def_span(def_id);
91 def.destructor(tcx); if def.repr().simd() {
94 check_simd(tcx, span, def_id);
95 }
96
97 check_transparent(tcx, def);
98 check_packed(tcx, span, def);
99}
100
101fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) {
102 let def = tcx.adt_def(def_id);
103 let span = tcx.def_span(def_id);
104 def.destructor(tcx); check_transparent(tcx, def);
106 check_union_fields(tcx, span, def_id);
107 check_packed(tcx, span, def);
108}
109
110fn allowed_union_or_unsafe_field<'tcx>(
111 tcx: TyCtxt<'tcx>,
112 ty: Ty<'tcx>,
113 typing_env: ty::TypingEnv<'tcx>,
114 span: Span,
115) -> bool {
116 if ty.is_trivially_pure_clone_copy() {
121 return true;
122 }
123 let def_id = tcx
126 .lang_items()
127 .get(LangItem::BikeshedGuaranteedNoDrop)
128 .unwrap_or_else(|| tcx.require_lang_item(LangItem::Copy, span));
129 let Ok(ty) = tcx.try_normalize_erasing_regions(typing_env, ty) else {
130 tcx.dcx().span_delayed_bug(span, "could not normalize field type");
131 return true;
132 };
133 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
134 infcx.predicate_must_hold_modulo_regions(&Obligation::new(
135 tcx,
136 ObligationCause::dummy_with_span(span),
137 param_env,
138 ty::TraitRef::new(tcx, def_id, [ty]),
139 ))
140}
141
142fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
144 let def = tcx.adt_def(item_def_id);
145 assert!(def.is_union());
146
147 let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
148 let args = ty::GenericArgs::identity_for_item(tcx, item_def_id);
149
150 for field in &def.non_enum_variant().fields {
151 if !allowed_union_or_unsafe_field(tcx, field.ty(tcx, args), typing_env, span) {
152 let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {
153 Some(Node::Field(field)) => (field.span, field.ty.span),
155 _ => unreachable!("mir field has to correspond to hir field"),
156 };
157 tcx.dcx().emit_err(errors::InvalidUnionField {
158 field_span,
159 sugg: errors::InvalidUnionFieldSuggestion {
160 lo: ty_span.shrink_to_lo(),
161 hi: ty_span.shrink_to_hi(),
162 },
163 note: (),
164 });
165 return false;
166 }
167 }
168
169 true
170}
171
172fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
174 let ty = tcx.type_of(def_id).instantiate_identity();
180 let span = tcx.def_span(def_id);
181 let layout = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
182 Ok(l) => l,
183 Err(LayoutError::SizeOverflow(_))
185 if matches!(tcx.def_kind(def_id), DefKind::Static{ .. }
186 if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) =>
187 {
188 tcx.dcx().emit_err(errors::TooLargeStatic { span });
189 return;
190 }
191 Err(e) => {
193 tcx.dcx().span_delayed_bug(span, format!("{e:?}"));
194 return;
195 }
196 };
197 if layout.is_uninhabited() {
198 tcx.node_span_lint(
199 UNINHABITED_STATIC,
200 tcx.local_def_id_to_hir_id(def_id),
201 span,
202 |lint| {
203 lint.primary_message("static of uninhabited type");
204 lint
205 .note("uninhabited statics cannot be initialized, and any access would be an immediate error");
206 },
207 );
208 }
209}
210
211fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
214 let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);
215
216 if tcx.sess.opts.actually_rustdoc {
221 return;
222 }
223
224 if tcx.type_of(def_id).instantiate_identity().references_error() {
225 return;
226 }
227 if check_opaque_for_cycles(tcx, def_id).is_err() {
228 return;
229 }
230
231 let _ = check_opaque_meets_bounds(tcx, def_id, origin);
232}
233
234pub(super) fn check_opaque_for_cycles<'tcx>(
236 tcx: TyCtxt<'tcx>,
237 def_id: LocalDefId,
238) -> Result<(), ErrorGuaranteed> {
239 let args = GenericArgs::identity_for_item(tcx, def_id);
240
241 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() {
244 let reported = opaque_type_cycle_error(tcx, def_id);
245 return Err(reported);
246 }
247
248 Ok(())
249}
250
251#[instrument(level = "debug", skip(tcx))]
267fn check_opaque_meets_bounds<'tcx>(
268 tcx: TyCtxt<'tcx>,
269 def_id: LocalDefId,
270 origin: hir::OpaqueTyOrigin<LocalDefId>,
271) -> Result<(), ErrorGuaranteed> {
272 let (span, definition_def_id) =
273 if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {
274 (span, Some(def_id))
275 } else {
276 (tcx.def_span(def_id), None)
277 };
278
279 let defining_use_anchor = match origin {
280 hir::OpaqueTyOrigin::FnReturn { parent, .. }
281 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
282 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
283 };
284 let param_env = tcx.param_env(defining_use_anchor);
285
286 let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
288 TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
289 } else {
290 TypingMode::analysis_in_body(tcx, defining_use_anchor)
291 });
292 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
293
294 let args = match origin {
295 hir::OpaqueTyOrigin::FnReturn { parent, .. }
296 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
297 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(
298 tcx, parent,
299 )
300 .extend_to(tcx, def_id.to_def_id(), |param, _| {
301 tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
302 }),
303 };
304
305 let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
306
307 let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args);
314 let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {
315 ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)),
316 _ => re,
317 });
318
319 for (predicate, pred_span) in
323 tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx, args)
324 {
325 let predicate = predicate.fold_with(&mut BottomUpFolder {
326 tcx,
327 ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
328 lt_op: |lt| lt,
329 ct_op: |ct| ct,
330 });
331
332 ocx.register_obligation(Obligation::new(
333 tcx,
334 ObligationCause::new(
335 span,
336 def_id,
337 ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
338 ),
339 param_env,
340 predicate,
341 ));
342 }
343
344 let misc_cause = ObligationCause::misc(span, def_id);
345 match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
349 Ok(()) => {}
350 Err(ty_err) => {
351 let ty_err = ty_err.to_string(tcx);
357 let guar = tcx.dcx().span_delayed_bug(
358 span,
359 format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
360 );
361 return Err(guar);
362 }
363 }
364
365 let predicate =
369 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
370 ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
371
372 let errors = ocx.select_all_or_error();
375 if !errors.is_empty() {
376 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
377 return Err(guar);
378 }
379
380 let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
381 ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
382
383 if infcx.next_trait_solver() {
384 Ok(())
385 } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
386 origin
387 {
388 let _ = infcx.take_opaque_types();
394 Ok(())
395 } else {
396 for (mut key, mut ty) in infcx.take_opaque_types() {
398 ty.ty = infcx.resolve_vars_if_possible(ty.ty);
399 key = infcx.resolve_vars_if_possible(key);
400 sanity_check_found_hidden_type(tcx, key, ty)?;
401 }
402 Ok(())
403 }
404}
405
406fn best_definition_site_of_opaque<'tcx>(
407 tcx: TyCtxt<'tcx>,
408 opaque_def_id: LocalDefId,
409 origin: hir::OpaqueTyOrigin<LocalDefId>,
410) -> Option<(Span, LocalDefId)> {
411 struct TaitConstraintLocator<'tcx> {
412 opaque_def_id: LocalDefId,
413 tcx: TyCtxt<'tcx>,
414 }
415 impl<'tcx> TaitConstraintLocator<'tcx> {
416 fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
417 if !self.tcx.has_typeck_results(item_def_id) {
418 return ControlFlow::Continue(());
419 }
420
421 let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
422 if !opaque_types_defined_by.contains(&self.opaque_def_id) {
424 return ControlFlow::Continue(());
425 }
426
427 if let Some(hidden_ty) = self
428 .tcx
429 .mir_borrowck(item_def_id)
430 .ok()
431 .and_then(|opaque_types| opaque_types.0.get(&self.opaque_def_id))
432 {
433 ControlFlow::Break((hidden_ty.span, item_def_id))
434 } else {
435 ControlFlow::Continue(())
436 }
437 }
438 }
439 impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
440 type NestedFilter = nested_filter::All;
441 type Result = ControlFlow<(Span, LocalDefId)>;
442 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
443 self.tcx
444 }
445 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
446 intravisit::walk_expr(self, ex)
447 }
448 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
449 self.check(it.owner_id.def_id)?;
450 intravisit::walk_item(self, it)
451 }
452 fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
453 self.check(it.owner_id.def_id)?;
454 intravisit::walk_impl_item(self, it)
455 }
456 fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
457 self.check(it.owner_id.def_id)?;
458 intravisit::walk_trait_item(self, it)
459 }
460 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
461 intravisit::walk_foreign_item(self, it)
462 }
463 }
464
465 let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
466 match origin {
467 hir::OpaqueTyOrigin::FnReturn { parent, .. }
468 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
469 hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
470 let impl_def_id = tcx.local_parent(parent);
471 for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
472 match assoc.kind {
473 ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
474 if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
475 {
476 return Some(span);
477 }
478 }
479 ty::AssocKind::Type { .. } => {}
480 }
481 }
482
483 None
484 }
485 hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
486 tcx.hir_walk_toplevel_module(&mut locator).break_value()
487 }
488 }
489}
490
491fn sanity_check_found_hidden_type<'tcx>(
492 tcx: TyCtxt<'tcx>,
493 key: ty::OpaqueTypeKey<'tcx>,
494 mut ty: ty::OpaqueHiddenType<'tcx>,
495) -> Result<(), ErrorGuaranteed> {
496 if ty.ty.is_ty_var() {
497 return Ok(());
499 }
500 if let ty::Alias(ty::Opaque, alias) = ty.ty.kind() {
501 if alias.def_id == key.def_id.to_def_id() && alias.args == key.args {
502 return Ok(());
505 }
506 }
507 let strip_vars = |ty: Ty<'tcx>| {
508 ty.fold_with(&mut BottomUpFolder {
509 tcx,
510 ty_op: |t| t,
511 ct_op: |c| c,
512 lt_op: |l| match l.kind() {
513 RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
514 _ => l,
515 },
516 })
517 };
518 ty.ty = strip_vars(ty.ty);
521 let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args);
523 let hidden_ty = strip_vars(hidden_ty);
524
525 if hidden_ty == ty.ty {
527 Ok(())
528 } else {
529 let span = tcx.def_span(key.def_id);
530 let other = ty::OpaqueHiddenType { ty: hidden_ty, span };
531 Err(ty.build_mismatch_error(&other, tcx)?.emit())
532 }
533}
534
535fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
544 let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
545 let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
546 hir::GenericBound::Use(bounds, ..) => Some(bounds),
547 _ => None,
548 }) else {
549 return;
551 };
552
553 let mut expected_captures = UnordSet::default();
554 let mut shadowed_captures = UnordSet::default();
555 let mut seen_params = UnordMap::default();
556 let mut prev_non_lifetime_param = None;
557 for arg in precise_capturing_args {
558 let (hir_id, ident) = match *arg {
559 hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
560 hir_id,
561 ident,
562 ..
563 }) => {
564 if prev_non_lifetime_param.is_none() {
565 prev_non_lifetime_param = Some(ident);
566 }
567 (hir_id, ident)
568 }
569 hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
570 if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
571 tcx.dcx().emit_err(errors::LifetimesMustBeFirst {
572 lifetime_span: ident.span,
573 name: ident.name,
574 other_span: prev_non_lifetime_param.span,
575 });
576 }
577 (hir_id, ident)
578 }
579 };
580
581 let ident = ident.normalize_to_macros_2_0();
582 if let Some(span) = seen_params.insert(ident, ident.span) {
583 tcx.dcx().emit_err(errors::DuplicatePreciseCapture {
584 name: ident.name,
585 first_span: span,
586 second_span: ident.span,
587 });
588 }
589
590 match tcx.named_bound_var(hir_id) {
591 Some(ResolvedArg::EarlyBound(def_id)) => {
592 expected_captures.insert(def_id.to_def_id());
593
594 if let DefKind::LifetimeParam = tcx.def_kind(def_id)
600 && let Some(def_id) = tcx
601 .map_opaque_lifetime_to_parent_lifetime(def_id)
602 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
603 {
604 shadowed_captures.insert(def_id);
605 }
606 }
607 _ => {
608 tcx.dcx()
609 .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
610 }
611 }
612 }
613
614 let variances = tcx.variances_of(opaque_def_id);
615 let mut def_id = Some(opaque_def_id.to_def_id());
616 while let Some(generics) = def_id {
617 let generics = tcx.generics_of(generics);
618 def_id = generics.parent;
619
620 for param in &generics.own_params {
621 if expected_captures.contains(¶m.def_id) {
622 assert_eq!(
623 variances[param.index as usize],
624 ty::Invariant,
625 "precise captured param should be invariant"
626 );
627 continue;
628 }
629 if shadowed_captures.contains(¶m.def_id) {
633 continue;
634 }
635
636 match param.kind {
637 ty::GenericParamDefKind::Lifetime => {
638 let use_span = tcx.def_span(param.def_id);
639 let opaque_span = tcx.def_span(opaque_def_id);
640 if variances[param.index as usize] == ty::Invariant {
642 if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
643 && let Some(def_id) = tcx
644 .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
645 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
646 {
647 tcx.dcx().emit_err(errors::LifetimeNotCaptured {
648 opaque_span,
649 use_span,
650 param_span: tcx.def_span(def_id),
651 });
652 } else {
653 if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
654 tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured {
655 opaque_span,
656 param_span: tcx.def_span(param.def_id),
657 });
658 } else {
659 tcx.dcx().emit_err(errors::LifetimeNotCaptured {
664 opaque_span,
665 use_span: opaque_span,
666 param_span: use_span,
667 });
668 }
669 }
670 continue;
671 }
672 }
673 ty::GenericParamDefKind::Type { .. } => {
674 if matches!(tcx.def_kind(param.def_id), DefKind::Trait | DefKind::TraitAlias) {
675 tcx.dcx().emit_err(errors::SelfTyNotCaptured {
677 trait_span: tcx.def_span(param.def_id),
678 opaque_span: tcx.def_span(opaque_def_id),
679 });
680 } else {
681 tcx.dcx().emit_err(errors::ParamNotCaptured {
683 param_span: tcx.def_span(param.def_id),
684 opaque_span: tcx.def_span(opaque_def_id),
685 kind: "type",
686 });
687 }
688 }
689 ty::GenericParamDefKind::Const { .. } => {
690 tcx.dcx().emit_err(errors::ParamNotCaptured {
692 param_span: tcx.def_span(param.def_id),
693 opaque_span: tcx.def_span(opaque_def_id),
694 kind: "const",
695 });
696 }
697 }
698 }
699 }
700}
701
702fn is_enum_of_nonnullable_ptr<'tcx>(
703 tcx: TyCtxt<'tcx>,
704 adt_def: AdtDef<'tcx>,
705 args: GenericArgsRef<'tcx>,
706) -> bool {
707 if adt_def.repr().inhibit_enum_layout_opt() {
708 return false;
709 }
710
711 let [var_one, var_two] = &adt_def.variants().raw[..] else {
712 return false;
713 };
714 let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
715 return false;
716 };
717 matches!(field.ty(tcx, args).kind(), ty::FnPtr(..) | ty::Ref(..))
718}
719
720fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
721 if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
722 if match tcx.type_of(def_id).instantiate_identity().kind() {
723 ty::RawPtr(_, _) => false,
724 ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
725 _ => true,
726 } {
727 tcx.dcx().emit_err(errors::LinkageType { span: tcx.def_span(def_id) });
728 }
729 }
730}
731
732pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) {
733 let generics = tcx.generics_of(def_id);
734
735 for param in &generics.own_params {
736 match param.kind {
737 ty::GenericParamDefKind::Lifetime { .. } => {}
738 ty::GenericParamDefKind::Type { has_default, .. } => {
739 if has_default {
740 tcx.ensure_ok().type_of(param.def_id);
741 }
742 }
743 ty::GenericParamDefKind::Const { has_default, .. } => {
744 tcx.ensure_ok().type_of(param.def_id);
745 if has_default {
746 let ct = tcx.const_param_default(param.def_id).skip_binder();
748 if let ty::ConstKind::Unevaluated(uv) = ct.kind() {
749 tcx.ensure_ok().type_of(uv.def);
750 }
751 }
752 }
753 }
754 }
755
756 match tcx.def_kind(def_id) {
757 DefKind::Static { .. } => {
758 check_static_inhabited(tcx, def_id);
759 check_static_linkage(tcx, def_id);
760 }
761 DefKind::Const => {}
762 DefKind::Enum => {
763 check_enum(tcx, def_id);
764 }
765 DefKind::Fn => {
766 if let Some(i) = tcx.intrinsic(def_id) {
767 intrinsic::check_intrinsic_type(
768 tcx,
769 def_id,
770 tcx.def_ident_span(def_id).unwrap(),
771 i.name,
772 )
773 }
774 }
775 DefKind::Impl { of_trait } => {
776 if of_trait && let Some(impl_trait_header) = tcx.impl_trait_header(def_id) {
777 if tcx
778 .ensure_ok()
779 .coherent_trait(impl_trait_header.trait_ref.instantiate_identity().def_id)
780 .is_ok()
781 {
782 check_impl_items_against_trait(tcx, def_id, impl_trait_header);
783 }
784 }
785 }
786 DefKind::Trait => {
787 let assoc_items = tcx.associated_items(def_id);
788 check_on_unimplemented(tcx, def_id);
789
790 for &assoc_item in assoc_items.in_definition_order() {
791 match assoc_item.kind {
792 ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {
793 let trait_args = GenericArgs::identity_for_item(tcx, def_id);
794 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
795 tcx,
796 assoc_item,
797 assoc_item,
798 ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),
799 );
800 }
801 _ => {}
802 }
803 }
804 }
805 DefKind::Struct => {
806 check_struct(tcx, def_id);
807 }
808 DefKind::Union => {
809 check_union(tcx, def_id);
810 }
811 DefKind::OpaqueTy => {
812 check_opaque_precise_captures(tcx, def_id);
813
814 let origin = tcx.local_opaque_ty_origin(def_id);
815 if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
816 | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin
817 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
818 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
819 {
820 } else {
822 check_opaque(tcx, def_id);
823 }
824
825 tcx.ensure_ok().predicates_of(def_id);
826 tcx.ensure_ok().explicit_item_bounds(def_id);
827 tcx.ensure_ok().explicit_item_self_bounds(def_id);
828 tcx.ensure_ok().item_bounds(def_id);
829 tcx.ensure_ok().item_self_bounds(def_id);
830 if tcx.is_conditionally_const(def_id) {
831 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
832 tcx.ensure_ok().const_conditions(def_id);
833 }
834 }
835 DefKind::TyAlias => {
836 check_type_alias_type_params_are_used(tcx, def_id);
837 }
838 DefKind::ForeignMod => {
839 let it = tcx.hir_expect_item(def_id);
840 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
841 return;
842 };
843
844 check_abi(tcx, it.hir_id(), it.span, abi);
845
846 for item in items {
847 let def_id = item.id.owner_id.def_id;
848
849 let generics = tcx.generics_of(def_id);
850 let own_counts = generics.own_counts();
851 if generics.own_params.len() - own_counts.lifetimes != 0 {
852 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
853 (_, 0) => ("type", "types", Some("u32")),
854 (0, _) => ("const", "consts", None),
857 _ => ("type or const", "types or consts", None),
858 };
859 struct_span_code_err!(
860 tcx.dcx(),
861 item.span,
862 E0044,
863 "foreign items may not have {kinds} parameters",
864 )
865 .with_span_label(item.span, format!("can't have {kinds} parameters"))
866 .with_help(
867 format!(
870 "replace the {} parameters with concrete {}{}",
871 kinds,
872 kinds_pl,
873 egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
874 ),
875 )
876 .emit();
877 }
878
879 let item = tcx.hir_foreign_item(item.id);
880 match &item.kind {
881 hir::ForeignItemKind::Fn(sig, _, _) => {
882 require_c_abi_if_c_variadic(tcx, sig.decl, abi, item.span);
883 }
884 hir::ForeignItemKind::Static(..) => {
885 check_static_inhabited(tcx, def_id);
886 check_static_linkage(tcx, def_id);
887 }
888 _ => {}
889 }
890 }
891 }
892 DefKind::Closure => {
893 tcx.ensure_ok().codegen_fn_attrs(def_id);
897 }
901 _ => {}
902 }
903}
904
905pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, def_id: LocalDefId) {
906 let _ = OnUnimplementedDirective::of_item(tcx, def_id.to_def_id());
908}
909
910pub(super) fn check_specialization_validity<'tcx>(
911 tcx: TyCtxt<'tcx>,
912 trait_def: &ty::TraitDef,
913 trait_item: ty::AssocItem,
914 impl_id: DefId,
915 impl_item: DefId,
916) {
917 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
918 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
919 if parent.is_from_trait() {
920 None
921 } else {
922 Some((parent, parent.item(tcx, trait_item.def_id)))
923 }
924 });
925
926 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
927 match parent_item {
928 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
931 Some(Err(parent_impl.def_id()))
932 }
933
934 Some(_) => Some(Ok(())),
936
937 None => {
941 if tcx.defaultness(parent_impl.def_id()).is_default() {
942 None
943 } else {
944 Some(Err(parent_impl.def_id()))
945 }
946 }
947 }
948 });
949
950 let result = opt_result.unwrap_or(Ok(()));
953
954 if let Err(parent_impl) = result {
955 if !tcx.is_impl_trait_in_trait(impl_item) {
956 report_forbidden_specialization(tcx, impl_item, parent_impl);
957 } else {
958 tcx.dcx().delayed_bug(format!("parent item: {parent_impl:?} not marked as default"));
959 }
960 }
961}
962
963fn check_impl_items_against_trait<'tcx>(
964 tcx: TyCtxt<'tcx>,
965 impl_id: LocalDefId,
966 impl_trait_header: ty::ImplTraitHeader<'tcx>,
967) {
968 let trait_ref = impl_trait_header.trait_ref.instantiate_identity();
969 if trait_ref.references_error() {
973 return;
974 }
975
976 let impl_item_refs = tcx.associated_item_def_ids(impl_id);
977
978 match impl_trait_header.polarity {
980 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
981 ty::ImplPolarity::Negative => {
982 if let [first_item_ref, ..] = impl_item_refs {
983 let first_item_span = tcx.def_span(first_item_ref);
984 struct_span_code_err!(
985 tcx.dcx(),
986 first_item_span,
987 E0749,
988 "negative impls cannot have any items"
989 )
990 .emit();
991 }
992 return;
993 }
994 }
995
996 let trait_def = tcx.trait_def(trait_ref.def_id);
997
998 let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
999
1000 for &impl_item in impl_item_refs {
1001 let ty_impl_item = tcx.associated_item(impl_item);
1002 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
1003 tcx.associated_item(trait_item_id)
1004 } else {
1005 tcx.dcx().span_delayed_bug(tcx.def_span(impl_item), "missing associated item in trait");
1007 continue;
1008 };
1009
1010 let res = tcx.ensure_ok().compare_impl_item(impl_item.expect_local());
1011
1012 if res.is_ok() {
1013 match ty_impl_item.kind {
1014 ty::AssocKind::Fn { .. } => {
1015 compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1016 tcx,
1017 ty_impl_item,
1018 ty_trait_item,
1019 tcx.impl_trait_ref(ty_impl_item.container_id(tcx))
1020 .unwrap()
1021 .instantiate_identity(),
1022 );
1023 }
1024 ty::AssocKind::Const { .. } => {}
1025 ty::AssocKind::Type { .. } => {}
1026 }
1027 }
1028
1029 if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1030 tcx.emit_node_span_lint(
1031 rustc_lint_defs::builtin::DEAD_CODE,
1032 tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1033 tcx.def_span(ty_impl_item.def_id),
1034 errors::UselessImplItem,
1035 )
1036 }
1037
1038 check_specialization_validity(
1039 tcx,
1040 trait_def,
1041 ty_trait_item,
1042 impl_id.to_def_id(),
1043 impl_item,
1044 );
1045 }
1046
1047 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1048 let mut missing_items = Vec::new();
1050
1051 let mut must_implement_one_of: Option<&[Ident]> =
1052 trait_def.must_implement_one_of.as_deref();
1053
1054 for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1055 let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1056
1057 let is_implemented = leaf_def
1058 .as_ref()
1059 .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1060
1061 if !is_implemented
1062 && tcx.defaultness(impl_id).is_final()
1063 && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1065 {
1066 missing_items.push(tcx.associated_item(trait_item_id));
1067 }
1068
1069 let is_implemented_here =
1071 leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1072
1073 if !is_implemented_here {
1074 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1075 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1076 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1077 tcx,
1078 full_impl_span,
1079 trait_item_id,
1080 feature,
1081 reason,
1082 issue,
1083 ),
1084
1085 EvalResult::Allow | EvalResult::Unmarked => {}
1087 }
1088 }
1089
1090 if let Some(required_items) = &must_implement_one_of {
1091 if is_implemented_here {
1092 let trait_item = tcx.associated_item(trait_item_id);
1093 if required_items.contains(&trait_item.ident(tcx)) {
1094 must_implement_one_of = None;
1095 }
1096 }
1097 }
1098
1099 if let Some(leaf_def) = &leaf_def
1100 && !leaf_def.is_final()
1101 && let def_id = leaf_def.item.def_id
1102 && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1103 {
1104 let def_kind = tcx.def_kind(def_id);
1105 let descr = tcx.def_kind_descr(def_kind, def_id);
1106 let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1107 (
1108 format!("async {descr} in trait cannot be specialized"),
1109 "async functions in traits",
1110 )
1111 } else {
1112 (
1113 format!(
1114 "{descr} with return-position `impl Trait` in trait cannot be specialized"
1115 ),
1116 "return position `impl Trait` in traits",
1117 )
1118 };
1119 tcx.dcx()
1120 .struct_span_err(tcx.def_span(def_id), msg)
1121 .with_note(format!(
1122 "specialization behaves in inconsistent and surprising ways with \
1123 {feature}, and for now is disallowed"
1124 ))
1125 .emit();
1126 }
1127 }
1128
1129 if !missing_items.is_empty() {
1130 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1131 missing_items_err(tcx, impl_id, &missing_items, full_impl_span);
1132 }
1133
1134 if let Some(missing_items) = must_implement_one_of {
1135 let attr_span = tcx
1136 .get_attr(trait_ref.def_id, sym::rustc_must_implement_one_of)
1137 .map(|attr| attr.span());
1138
1139 missing_items_must_implement_one_of_err(
1140 tcx,
1141 tcx.def_span(impl_id),
1142 missing_items,
1143 attr_span,
1144 );
1145 }
1146 }
1147}
1148
1149fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1150 let t = tcx.type_of(def_id).instantiate_identity();
1151 if let ty::Adt(def, args) = t.kind()
1152 && def.is_struct()
1153 {
1154 let fields = &def.non_enum_variant().fields;
1155 if fields.is_empty() {
1156 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1157 return;
1158 }
1159
1160 let array_field = &fields[FieldIdx::ZERO];
1161 let array_ty = array_field.ty(tcx, args);
1162 let ty::Array(element_ty, len_const) = array_ty.kind() else {
1163 struct_span_code_err!(
1164 tcx.dcx(),
1165 sp,
1166 E0076,
1167 "SIMD vector's only field must be an array"
1168 )
1169 .with_span_label(tcx.def_span(array_field.did), "not an array")
1170 .emit();
1171 return;
1172 };
1173
1174 if let Some(second_field) = fields.get(FieldIdx::ONE) {
1175 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot have multiple fields")
1176 .with_span_label(tcx.def_span(second_field.did), "excess field")
1177 .emit();
1178 return;
1179 }
1180
1181 if let Some(len) = len_const.try_to_target_usize(tcx) {
1186 if len == 0 {
1187 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1188 return;
1189 } else if len > MAX_SIMD_LANES {
1190 struct_span_code_err!(
1191 tcx.dcx(),
1192 sp,
1193 E0075,
1194 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1195 )
1196 .emit();
1197 return;
1198 }
1199 }
1200
1201 match element_ty.kind() {
1206 ty::Param(_) => (), ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), _ => {
1209 struct_span_code_err!(
1210 tcx.dcx(),
1211 sp,
1212 E0077,
1213 "SIMD vector element type should be a \
1214 primitive scalar (integer/float/pointer) type"
1215 )
1216 .emit();
1217 return;
1218 }
1219 }
1220 }
1221}
1222
1223pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1224 let repr = def.repr();
1225 if repr.packed() {
1226 if let Some(reprs) =
1227 attrs::find_attr!(tcx.get_all_attrs(def.did()), attrs::AttributeKind::Repr(r) => r)
1228 {
1229 for (r, _) in reprs {
1230 if let ReprPacked(pack) = r
1231 && let Some(repr_pack) = repr.pack
1232 && pack != &repr_pack
1233 {
1234 struct_span_code_err!(
1235 tcx.dcx(),
1236 sp,
1237 E0634,
1238 "type has conflicting packed representation hints"
1239 )
1240 .emit();
1241 }
1242 }
1243 }
1244 if repr.align.is_some() {
1245 struct_span_code_err!(
1246 tcx.dcx(),
1247 sp,
1248 E0587,
1249 "type has conflicting packed and align representation hints"
1250 )
1251 .emit();
1252 } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1253 let mut err = struct_span_code_err!(
1254 tcx.dcx(),
1255 sp,
1256 E0588,
1257 "packed type cannot transitively contain a `#[repr(align)]` type"
1258 );
1259
1260 err.span_note(
1261 tcx.def_span(def_spans[0].0),
1262 format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),
1263 );
1264
1265 if def_spans.len() > 2 {
1266 let mut first = true;
1267 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1268 let ident = tcx.item_name(*adt_def);
1269 err.span_note(
1270 *span,
1271 if first {
1272 format!(
1273 "`{}` contains a field of type `{}`",
1274 tcx.type_of(def.did()).instantiate_identity(),
1275 ident
1276 )
1277 } else {
1278 format!("...which contains a field of type `{ident}`")
1279 },
1280 );
1281 first = false;
1282 }
1283 }
1284
1285 err.emit();
1286 }
1287 }
1288}
1289
1290pub(super) fn check_packed_inner(
1291 tcx: TyCtxt<'_>,
1292 def_id: DefId,
1293 stack: &mut Vec<DefId>,
1294) -> Option<Vec<(DefId, Span)>> {
1295 if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().kind() {
1296 if def.is_struct() || def.is_union() {
1297 if def.repr().align.is_some() {
1298 return Some(vec![(def.did(), DUMMY_SP)]);
1299 }
1300
1301 stack.push(def_id);
1302 for field in &def.non_enum_variant().fields {
1303 if let ty::Adt(def, _) = field.ty(tcx, args).kind()
1304 && !stack.contains(&def.did())
1305 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1306 {
1307 defs.push((def.did(), field.ident(tcx).span));
1308 return Some(defs);
1309 }
1310 }
1311 stack.pop();
1312 }
1313 }
1314
1315 None
1316}
1317
1318pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1319 if !adt.repr().transparent() {
1320 return;
1321 }
1322
1323 if adt.is_union() && !tcx.features().transparent_unions() {
1324 feature_err(
1325 &tcx.sess,
1326 sym::transparent_unions,
1327 tcx.def_span(adt.did()),
1328 "transparent unions are unstable",
1329 )
1330 .emit();
1331 }
1332
1333 if adt.variants().len() != 1 {
1334 bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1335 return;
1337 }
1338
1339 let field_infos = adt.all_fields().map(|field| {
1342 let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did));
1343 let typing_env = ty::TypingEnv::non_body_analysis(tcx, field.did);
1344 let layout = tcx.layout_of(typing_env.as_query_input(ty));
1345 let span = tcx.hir_span_if_local(field.did).unwrap();
1347 let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1348 if !trivial {
1349 return (span, trivial, None);
1350 }
1351 fn check_non_exhaustive<'tcx>(
1354 tcx: TyCtxt<'tcx>,
1355 t: Ty<'tcx>,
1356 ) -> ControlFlow<(&'static str, DefId, GenericArgsRef<'tcx>, bool)> {
1357 match t.kind() {
1358 ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)),
1359 ty::Array(ty, _) => check_non_exhaustive(tcx, *ty),
1360 ty::Adt(def, args) => {
1361 if !def.did().is_local()
1362 && !attrs::find_attr!(
1363 tcx.get_all_attrs(def.did()),
1364 AttributeKind::PubTransparent(_)
1365 )
1366 {
1367 let non_exhaustive = def.is_variant_list_non_exhaustive()
1368 || def
1369 .variants()
1370 .iter()
1371 .any(ty::VariantDef::is_field_list_non_exhaustive);
1372 let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1373 if non_exhaustive || has_priv {
1374 return ControlFlow::Break((
1375 def.descr(),
1376 def.did(),
1377 args,
1378 non_exhaustive,
1379 ));
1380 }
1381 }
1382 def.all_fields()
1383 .map(|field| field.ty(tcx, args))
1384 .try_for_each(|t| check_non_exhaustive(tcx, t))
1385 }
1386 _ => ControlFlow::Continue(()),
1387 }
1388 }
1389
1390 (span, trivial, check_non_exhaustive(tcx, ty).break_value())
1391 });
1392
1393 let non_trivial_fields = field_infos
1394 .clone()
1395 .filter_map(|(span, trivial, _non_exhaustive)| if !trivial { Some(span) } else { None });
1396 let non_trivial_count = non_trivial_fields.clone().count();
1397 if non_trivial_count >= 2 {
1398 bad_non_zero_sized_fields(
1399 tcx,
1400 adt,
1401 non_trivial_count,
1402 non_trivial_fields,
1403 tcx.def_span(adt.did()),
1404 );
1405 return;
1406 }
1407 let mut prev_non_exhaustive_1zst = false;
1408 for (span, _trivial, non_exhaustive_1zst) in field_infos {
1409 if let Some((descr, def_id, args, non_exhaustive)) = non_exhaustive_1zst {
1410 if non_trivial_count > 0 || prev_non_exhaustive_1zst {
1413 tcx.node_span_lint(
1414 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS,
1415 tcx.local_def_id_to_hir_id(adt.did().expect_local()),
1416 span,
1417 |lint| {
1418 lint.primary_message(
1419 "zero-sized fields in `repr(transparent)` cannot \
1420 contain external non-exhaustive types",
1421 );
1422 let note = if non_exhaustive {
1423 "is marked with `#[non_exhaustive]`"
1424 } else {
1425 "contains private fields"
1426 };
1427 let field_ty = tcx.def_path_str_with_args(def_id, args);
1428 lint.note(format!(
1429 "this {descr} contains `{field_ty}`, which {note}, \
1430 and makes it not a breaking change to become \
1431 non-zero-sized in the future."
1432 ));
1433 },
1434 )
1435 } else {
1436 prev_non_exhaustive_1zst = true;
1437 }
1438 }
1439 }
1440}
1441
1442#[allow(trivial_numeric_casts)]
1443fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1444 let def = tcx.adt_def(def_id);
1445 def.destructor(tcx); if def.variants().is_empty() {
1448 attrs::find_attr!(
1449 tcx.get_all_attrs(def_id),
1450 attrs::AttributeKind::Repr(rs) => {
1451 struct_span_code_err!(
1452 tcx.dcx(),
1453 rs.first().unwrap().1,
1454 E0084,
1455 "unsupported representation for zero-variant enum"
1456 )
1457 .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1458 .emit();
1459 }
1460 );
1461 }
1462
1463 for v in def.variants() {
1464 if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1465 tcx.ensure_ok().typeck(discr_def_id.expect_local());
1466 }
1467 }
1468
1469 if def.repr().int.is_none() {
1470 let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind(), Some(CtorKind::Const));
1471 let has_disr = |var: &ty::VariantDef| matches!(var.discr, ty::VariantDiscr::Explicit(_));
1472
1473 let has_non_units = def.variants().iter().any(|var| !is_unit(var));
1474 let disr_units = def.variants().iter().any(|var| is_unit(var) && has_disr(var));
1475 let disr_non_unit = def.variants().iter().any(|var| !is_unit(var) && has_disr(var));
1476
1477 if disr_non_unit || (disr_units && has_non_units) {
1478 struct_span_code_err!(
1479 tcx.dcx(),
1480 tcx.def_span(def_id),
1481 E0732,
1482 "`#[repr(inttype)]` must be specified"
1483 )
1484 .emit();
1485 }
1486 }
1487
1488 detect_discriminant_duplicate(tcx, def);
1489 check_transparent(tcx, def);
1490}
1491
1492fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1494 let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1497 let var = adt.variant(idx); let (span, display_discr) = match var.discr {
1499 ty::VariantDiscr::Explicit(discr_def_id) => {
1500 if let hir::Node::AnonConst(expr) =
1502 tcx.hir_node_by_def_id(discr_def_id.expect_local())
1503 && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1504 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1505 && *lit_value != dis.val
1506 {
1507 (tcx.def_span(discr_def_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1508 } else {
1509 (tcx.def_span(discr_def_id), format!("`{dis}`"))
1511 }
1512 }
1513 ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), format!("`{dis}`")),
1515 ty::VariantDiscr::Relative(distance_to_explicit) => {
1516 if let Some(explicit_idx) =
1521 idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1522 {
1523 let explicit_variant = adt.variant(explicit_idx);
1524 let ve_ident = var.name;
1525 let ex_ident = explicit_variant.name;
1526 let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1527
1528 err.span_label(
1529 tcx.def_span(explicit_variant.def_id),
1530 format!(
1531 "discriminant for `{ve_ident}` incremented from this startpoint \
1532 (`{ex_ident}` + {distance_to_explicit} {sp} later \
1533 => `{ve_ident}` = {dis})"
1534 ),
1535 );
1536 }
1537
1538 (tcx.def_span(var.def_id), format!("`{dis}`"))
1539 }
1540 };
1541
1542 err.span_label(span, format!("{display_discr} assigned here"));
1543 };
1544
1545 let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1546
1547 let mut i = 0;
1554 while i < discrs.len() {
1555 let var_i_idx = discrs[i].0;
1556 let mut error: Option<Diag<'_, _>> = None;
1557
1558 let mut o = i + 1;
1559 while o < discrs.len() {
1560 let var_o_idx = discrs[o].0;
1561
1562 if discrs[i].1.val == discrs[o].1.val {
1563 let err = error.get_or_insert_with(|| {
1564 let mut ret = struct_span_code_err!(
1565 tcx.dcx(),
1566 tcx.def_span(adt.did()),
1567 E0081,
1568 "discriminant value `{}` assigned more than once",
1569 discrs[i].1,
1570 );
1571
1572 report(discrs[i].1, var_i_idx, &mut ret);
1573
1574 ret
1575 });
1576
1577 report(discrs[o].1, var_o_idx, err);
1578
1579 discrs[o] = *discrs.last().unwrap();
1581 discrs.pop();
1582 } else {
1583 o += 1;
1584 }
1585 }
1586
1587 if let Some(e) = error {
1588 e.emit();
1589 }
1590
1591 i += 1;
1592 }
1593}
1594
1595fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1596 if tcx.type_alias_is_lazy(def_id) {
1597 return;
1600 }
1601
1602 let generics = tcx.generics_of(def_id);
1603 if generics.own_counts().types == 0 {
1604 return;
1605 }
1606
1607 let ty = tcx.type_of(def_id).instantiate_identity();
1608 if ty.references_error() {
1609 return;
1611 }
1612
1613 let bounded_params = LazyCell::new(|| {
1615 tcx.explicit_predicates_of(def_id)
1616 .predicates
1617 .iter()
1618 .filter_map(|(predicate, span)| {
1619 let bounded_ty = match predicate.kind().skip_binder() {
1620 ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
1621 ty::ClauseKind::TypeOutlives(pred) => pred.0,
1622 _ => return None,
1623 };
1624 if let ty::Param(param) = bounded_ty.kind() {
1625 Some((param.index, span))
1626 } else {
1627 None
1628 }
1629 })
1630 .collect::<FxIndexMap<_, _>>()
1636 });
1637
1638 let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
1639 for leaf in ty.walk() {
1640 if let GenericArgKind::Type(leaf_ty) = leaf.kind()
1641 && let ty::Param(param) = leaf_ty.kind()
1642 {
1643 debug!("found use of ty param {:?}", param);
1644 params_used.insert(param.index);
1645 }
1646 }
1647
1648 for param in &generics.own_params {
1649 if !params_used.contains(param.index)
1650 && let ty::GenericParamDefKind::Type { .. } = param.kind
1651 {
1652 let span = tcx.def_span(param.def_id);
1653 let param_name = Ident::new(param.name, span);
1654
1655 let has_explicit_bounds = bounded_params.is_empty()
1659 || (*bounded_params).get(¶m.index).is_some_and(|&&pred_sp| pred_sp != span);
1660 let const_param_help = !has_explicit_bounds;
1661
1662 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
1663 span,
1664 param_name,
1665 param_def_kind: tcx.def_descr(param.def_id),
1666 help: errors::UnusedGenericParameterHelp::TyAlias { param_name },
1667 usage_spans: vec![],
1668 const_param_help,
1669 });
1670 diag.code(E0091);
1671 diag.emit();
1672 }
1673 }
1674}
1675
1676fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
1685 let span = tcx.def_span(opaque_def_id);
1686 let mut err = struct_span_code_err!(tcx.dcx(), span, E0720, "cannot resolve opaque type");
1687
1688 let mut label = false;
1689 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
1690 let typeck_results = tcx.typeck(def_id);
1691 if visitor
1692 .returns
1693 .iter()
1694 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1695 .all(|ty| matches!(ty.kind(), ty::Never))
1696 {
1697 let spans = visitor
1698 .returns
1699 .iter()
1700 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1701 .map(|expr| expr.span)
1702 .collect::<Vec<Span>>();
1703 let span_len = spans.len();
1704 if span_len == 1 {
1705 err.span_label(spans[0], "this returned value is of `!` type");
1706 } else {
1707 let mut multispan: MultiSpan = spans.clone().into();
1708 for span in spans {
1709 multispan.push_span_label(span, "this returned value is of `!` type");
1710 }
1711 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1712 }
1713 err.help("this error will resolve once the item's body returns a concrete type");
1714 } else {
1715 let mut seen = FxHashSet::default();
1716 seen.insert(span);
1717 err.span_label(span, "recursive opaque type");
1718 label = true;
1719 for (sp, ty) in visitor
1720 .returns
1721 .iter()
1722 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1723 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1724 {
1725 #[derive(Default)]
1726 struct OpaqueTypeCollector {
1727 opaques: Vec<DefId>,
1728 closures: Vec<DefId>,
1729 }
1730 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
1731 fn visit_ty(&mut self, t: Ty<'tcx>) {
1732 match *t.kind() {
1733 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
1734 self.opaques.push(def);
1735 }
1736 ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
1737 self.closures.push(def_id);
1738 t.super_visit_with(self);
1739 }
1740 _ => t.super_visit_with(self),
1741 }
1742 }
1743 }
1744
1745 let mut visitor = OpaqueTypeCollector::default();
1746 ty.visit_with(&mut visitor);
1747 for def_id in visitor.opaques {
1748 let ty_span = tcx.def_span(def_id);
1749 if !seen.contains(&ty_span) {
1750 let descr = if ty.is_impl_trait() { "opaque " } else { "" };
1751 err.span_label(ty_span, format!("returning this {descr}type `{ty}`"));
1752 seen.insert(ty_span);
1753 }
1754 err.span_label(sp, format!("returning here with type `{ty}`"));
1755 }
1756
1757 for closure_def_id in visitor.closures {
1758 let Some(closure_local_did) = closure_def_id.as_local() else {
1759 continue;
1760 };
1761 let typeck_results = tcx.typeck(closure_local_did);
1762
1763 let mut label_match = |ty: Ty<'_>, span| {
1764 for arg in ty.walk() {
1765 if let ty::GenericArgKind::Type(ty) = arg.kind()
1766 && let ty::Alias(
1767 ty::Opaque,
1768 ty::AliasTy { def_id: captured_def_id, .. },
1769 ) = *ty.kind()
1770 && captured_def_id == opaque_def_id.to_def_id()
1771 {
1772 err.span_label(
1773 span,
1774 format!(
1775 "{} captures itself here",
1776 tcx.def_descr(closure_def_id)
1777 ),
1778 );
1779 }
1780 }
1781 };
1782
1783 for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
1785 {
1786 label_match(capture.place.ty(), capture.get_path_span(tcx));
1787 }
1788 if tcx.is_coroutine(closure_def_id)
1790 && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
1791 {
1792 for interior_ty in &coroutine_layout.field_tys {
1793 label_match(interior_ty.ty, interior_ty.source_info.span);
1794 }
1795 }
1796 }
1797 }
1798 }
1799 }
1800 if !label {
1801 err.span_label(span, "cannot resolve opaque type");
1802 }
1803 err.emit()
1804}
1805
1806pub(super) fn check_coroutine_obligations(
1807 tcx: TyCtxt<'_>,
1808 def_id: LocalDefId,
1809) -> Result<(), ErrorGuaranteed> {
1810 debug_assert!(!tcx.is_typeck_child(def_id.to_def_id()));
1811
1812 let typeck_results = tcx.typeck(def_id);
1813 let param_env = tcx.param_env(def_id);
1814
1815 debug!(?typeck_results.coroutine_stalled_predicates);
1816
1817 let mode = if tcx.next_trait_solver_globally() {
1818 TypingMode::borrowck(tcx, def_id)
1822 } else {
1823 TypingMode::analysis_in_body(tcx, def_id)
1824 };
1825
1826 let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
1831
1832 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1833 for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
1834 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
1835 }
1836
1837 let errors = ocx.select_all_or_error();
1838 debug!(?errors);
1839 if !errors.is_empty() {
1840 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
1841 }
1842
1843 if !tcx.next_trait_solver_globally() {
1844 for (key, ty) in infcx.take_opaque_types() {
1847 let hidden_type = infcx.resolve_vars_if_possible(ty);
1848 let key = infcx.resolve_vars_if_possible(key);
1849 sanity_check_found_hidden_type(tcx, key, hidden_type)?;
1850 }
1851 } else {
1852 let _ = infcx.take_opaque_types();
1855 }
1856
1857 Ok(())
1858}