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