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