1use std::cell::LazyCell;
2use std::ops::{ControlFlow, Deref};
3
4use hir::intravisit::{self, Visitor};
5use rustc_abi::ExternAbi;
6use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
7use rustc_errors::codes::*;
8use rustc_errors::{Applicability, ErrorGuaranteed, pluralize, struct_span_code_err};
9use rustc_hir::def::{DefKind, Res};
10use rustc_hir::def_id::{DefId, LocalDefId};
11use rustc_hir::lang_items::LangItem;
12use rustc_hir::{AmbigArg, ItemKind};
13use rustc_infer::infer::outlives::env::OutlivesEnvironment;
14use rustc_infer::infer::{self, InferCtxt, SubregionOrigin, TyCtxtInferExt};
15use rustc_lint_defs::builtin::SUPERTRAIT_ITEM_SHADOWING_DEFINITION;
16use rustc_macros::LintDiagnostic;
17use rustc_middle::mir::interpret::ErrorHandled;
18use rustc_middle::traits::solve::NoSolution;
19use rustc_middle::ty::trait_def::TraitSpecializationKind;
20use rustc_middle::ty::{
21 self, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags,
22 TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
23 Upcast,
24};
25use rustc_middle::{bug, span_bug};
26use rustc_session::parse::feature_err;
27use rustc_span::{DUMMY_SP, Span, sym};
28use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
29use rustc_trait_selection::regions::{InferCtxtRegionExt, OutlivesEnvironmentBuildExt};
30use rustc_trait_selection::traits::misc::{
31 ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
32};
33use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
34use rustc_trait_selection::traits::{
35 self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
36 WellFormedLoc,
37};
38use tracing::{debug, instrument};
39use {rustc_ast as ast, rustc_hir as hir};
40
41use crate::autoderef::Autoderef;
42use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
43use crate::errors::InvalidReceiverTyHint;
44use crate::{errors, fluent_generated as fluent};
45
46pub(super) struct WfCheckingCtxt<'a, 'tcx> {
47 pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
48 body_def_id: LocalDefId,
49 param_env: ty::ParamEnv<'tcx>,
50}
51impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
52 type Target = ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>;
53 fn deref(&self) -> &Self::Target {
54 &self.ocx
55 }
56}
57
58impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
59 fn tcx(&self) -> TyCtxt<'tcx> {
60 self.ocx.infcx.tcx
61 }
62
63 fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
66 where
67 T: TypeFoldable<TyCtxt<'tcx>>,
68 {
69 self.ocx.normalize(
70 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
71 self.param_env,
72 value,
73 )
74 }
75
76 pub(super) fn deeply_normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
86 where
87 T: TypeFoldable<TyCtxt<'tcx>>,
88 {
89 if self.infcx.next_trait_solver() {
90 match self.ocx.deeply_normalize(
91 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
92 self.param_env,
93 value.clone(),
94 ) {
95 Ok(value) => value,
96 Err(errors) => {
97 self.infcx.err_ctxt().report_fulfillment_errors(errors);
98 value
99 }
100 }
101 } else {
102 self.normalize(span, loc, value)
103 }
104 }
105
106 pub(super) fn register_wf_obligation(
107 &self,
108 span: Span,
109 loc: Option<WellFormedLoc>,
110 term: ty::Term<'tcx>,
111 ) {
112 let cause = traits::ObligationCause::new(
113 span,
114 self.body_def_id,
115 ObligationCauseCode::WellFormed(loc),
116 );
117 self.ocx.register_obligation(Obligation::new(
118 self.tcx(),
119 cause,
120 self.param_env,
121 ty::ClauseKind::WellFormed(term),
122 ));
123 }
124}
125
126pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
127 tcx: TyCtxt<'tcx>,
128 body_def_id: LocalDefId,
129 f: F,
130) -> Result<(), ErrorGuaranteed>
131where
132 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> Result<(), ErrorGuaranteed>,
133{
134 let param_env = tcx.param_env(body_def_id);
135 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
136 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
137
138 let mut wfcx = WfCheckingCtxt { ocx, body_def_id, param_env };
139
140 if !tcx.features().trivial_bounds() {
141 wfcx.check_false_global_bounds()
142 }
143 f(&mut wfcx)?;
144
145 let errors = wfcx.select_all_or_error();
146 if !errors.is_empty() {
147 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
148 }
149
150 let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
151 debug!(?assumed_wf_types);
152
153 let infcx_compat = infcx.fork();
154
155 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
158 &infcx,
159 body_def_id,
160 param_env,
161 assumed_wf_types.iter().copied(),
162 true,
163 );
164
165 lint_redundant_lifetimes(tcx, body_def_id, &outlives_env);
166
167 let errors = infcx.resolve_regions_with_outlives_env(&outlives_env);
168 if errors.is_empty() {
169 return Ok(());
170 }
171
172 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
173 &infcx_compat,
174 body_def_id,
175 param_env,
176 assumed_wf_types,
177 false,
180 );
181 let errors_compat = infcx_compat.resolve_regions_with_outlives_env(&outlives_env);
182 if errors_compat.is_empty() {
183 Ok(())
186 } else {
187 Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
188 }
189}
190
191pub(super) fn check_well_formed(
192 tcx: TyCtxt<'_>,
193 def_id: LocalDefId,
194) -> Result<(), ErrorGuaranteed> {
195 let mut res = crate::check::check::check_item_type(tcx, def_id);
196
197 for param in &tcx.generics_of(def_id).own_params {
198 res = res.and(check_param_wf(tcx, param));
199 }
200
201 res
202}
203
204#[instrument(skip(tcx), level = "debug")]
218pub(super) fn check_item<'tcx>(
219 tcx: TyCtxt<'tcx>,
220 item: &'tcx hir::Item<'tcx>,
221) -> Result<(), ErrorGuaranteed> {
222 let def_id = item.owner_id.def_id;
223
224 debug!(
225 ?item.owner_id,
226 item.name = ? tcx.def_path_str(def_id)
227 );
228
229 match item.kind {
230 hir::ItemKind::Impl(impl_) => {
248 let header = tcx.impl_trait_header(def_id);
249 let is_auto = header
250 .is_some_and(|header| tcx.trait_is_auto(header.trait_ref.skip_binder().def_id));
251
252 crate::impl_wf_check::check_impl_wf(tcx, def_id)?;
253 let mut res = Ok(());
254 if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
255 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
256 res = Err(tcx
257 .dcx()
258 .struct_span_err(sp, "impls of auto traits cannot be default")
259 .with_span_labels(impl_.defaultness_span, "default because of this")
260 .with_span_label(sp, "auto trait")
261 .emit());
262 }
263 match header.map(|h| h.polarity) {
265 Some(ty::ImplPolarity::Positive) | None => {
267 res = res.and(check_impl(tcx, item, impl_.self_ty, &impl_.of_trait));
268 }
269 Some(ty::ImplPolarity::Negative) => {
270 let ast::ImplPolarity::Negative(span) = impl_.polarity else {
271 bug!("impl_polarity query disagrees with impl's polarity in HIR");
272 };
273 if let hir::Defaultness::Default { .. } = impl_.defaultness {
275 let mut spans = vec![span];
276 spans.extend(impl_.defaultness_span);
277 res = Err(struct_span_code_err!(
278 tcx.dcx(),
279 spans,
280 E0750,
281 "negative impls cannot be default impls"
282 )
283 .emit());
284 }
285 }
286 Some(ty::ImplPolarity::Reservation) => {
287 }
289 }
290 res
291 }
292 hir::ItemKind::Fn { sig, .. } => check_item_fn(tcx, def_id, sig.decl),
293 hir::ItemKind::Struct(..) => check_type_defn(tcx, item, false),
294 hir::ItemKind::Union(..) => check_type_defn(tcx, item, true),
295 hir::ItemKind::Enum(..) => check_type_defn(tcx, item, true),
296 hir::ItemKind::Trait(..) => check_trait(tcx, item),
297 hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
298 _ => Ok(()),
299 }
300}
301
302pub(super) fn check_foreign_item<'tcx>(
303 tcx: TyCtxt<'tcx>,
304 item: &'tcx hir::ForeignItem<'tcx>,
305) -> Result<(), ErrorGuaranteed> {
306 let def_id = item.owner_id.def_id;
307
308 debug!(
309 ?item.owner_id,
310 item.name = ? tcx.def_path_str(def_id)
311 );
312
313 match item.kind {
314 hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
315 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
316 }
317}
318
319pub(crate) fn check_trait_item<'tcx>(
320 tcx: TyCtxt<'tcx>,
321 def_id: LocalDefId,
322) -> Result<(), ErrorGuaranteed> {
323 lint_item_shadowing_supertrait_item(tcx, def_id);
325
326 let mut res = Ok(());
327
328 if matches!(tcx.def_kind(def_id), DefKind::AssocFn) {
329 for &assoc_ty_def_id in
330 tcx.associated_types_for_impl_traits_in_associated_fn(def_id.to_def_id())
331 {
332 res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
333 }
334 }
335 res
336}
337
338fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
351 let mut required_bounds_by_item = FxIndexMap::default();
353 let associated_items = tcx.associated_items(trait_def_id);
354
355 loop {
361 let mut should_continue = false;
362 for gat_item in associated_items.in_definition_order() {
363 let gat_def_id = gat_item.def_id.expect_local();
364 let gat_item = tcx.associated_item(gat_def_id);
365 if !gat_item.is_type() {
367 continue;
368 }
369 let gat_generics = tcx.generics_of(gat_def_id);
370 if gat_generics.is_own_empty() {
372 continue;
373 }
374
375 let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
379 for item in associated_items.in_definition_order() {
380 let item_def_id = item.def_id.expect_local();
381 if item_def_id == gat_def_id {
383 continue;
384 }
385
386 let param_env = tcx.param_env(item_def_id);
387
388 let item_required_bounds = match tcx.associated_item(item_def_id).kind {
389 ty::AssocKind::Fn { .. } => {
391 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
395 item_def_id.to_def_id(),
396 tcx.fn_sig(item_def_id).instantiate_identity(),
397 );
398 gather_gat_bounds(
399 tcx,
400 param_env,
401 item_def_id,
402 sig.inputs_and_output,
403 &sig.inputs().iter().copied().collect(),
406 gat_def_id,
407 gat_generics,
408 )
409 }
410 ty::AssocKind::Type { .. } => {
412 let param_env = augment_param_env(
416 tcx,
417 param_env,
418 required_bounds_by_item.get(&item_def_id),
419 );
420 gather_gat_bounds(
421 tcx,
422 param_env,
423 item_def_id,
424 tcx.explicit_item_bounds(item_def_id)
425 .iter_identity_copied()
426 .collect::<Vec<_>>(),
427 &FxIndexSet::default(),
428 gat_def_id,
429 gat_generics,
430 )
431 }
432 ty::AssocKind::Const { .. } => None,
433 };
434
435 if let Some(item_required_bounds) = item_required_bounds {
436 if let Some(new_required_bounds) = &mut new_required_bounds {
442 new_required_bounds.retain(|b| item_required_bounds.contains(b));
443 } else {
444 new_required_bounds = Some(item_required_bounds);
445 }
446 }
447 }
448
449 if let Some(new_required_bounds) = new_required_bounds {
450 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
451 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
452 should_continue = true;
455 }
456 }
457 }
458 if !should_continue {
463 break;
464 }
465 }
466
467 for (gat_def_id, required_bounds) in required_bounds_by_item {
468 if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
470 continue;
471 }
472
473 let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
474 debug!(?required_bounds);
475 let param_env = tcx.param_env(gat_def_id);
476
477 let unsatisfied_bounds: Vec<_> = required_bounds
478 .into_iter()
479 .filter(|clause| match clause.kind().skip_binder() {
480 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
481 !region_known_to_outlive(
482 tcx,
483 gat_def_id,
484 param_env,
485 &FxIndexSet::default(),
486 a,
487 b,
488 )
489 }
490 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
491 !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
492 }
493 _ => bug!("Unexpected ClauseKind"),
494 })
495 .map(|clause| clause.to_string())
496 .collect();
497
498 if !unsatisfied_bounds.is_empty() {
499 let plural = pluralize!(unsatisfied_bounds.len());
500 let suggestion = format!(
501 "{} {}",
502 gat_item_hir.generics.add_where_or_trailing_comma(),
503 unsatisfied_bounds.join(", "),
504 );
505 let bound =
506 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
507 tcx.dcx()
508 .struct_span_err(
509 gat_item_hir.span,
510 format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
511 )
512 .with_span_suggestion(
513 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
514 format!("add the required where clause{plural}"),
515 suggestion,
516 Applicability::MachineApplicable,
517 )
518 .with_note(format!(
519 "{bound} currently required to ensure that impls have maximum flexibility"
520 ))
521 .with_note(
522 "we are soliciting feedback, see issue #87479 \
523 <https://github.com/rust-lang/rust/issues/87479> for more information",
524 )
525 .emit();
526 }
527 }
528}
529
530fn augment_param_env<'tcx>(
532 tcx: TyCtxt<'tcx>,
533 param_env: ty::ParamEnv<'tcx>,
534 new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
535) -> ty::ParamEnv<'tcx> {
536 let Some(new_predicates) = new_predicates else {
537 return param_env;
538 };
539
540 if new_predicates.is_empty() {
541 return param_env;
542 }
543
544 let bounds = tcx.mk_clauses_from_iter(
545 param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
546 );
547 ty::ParamEnv::new(bounds)
550}
551
552fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
563 tcx: TyCtxt<'tcx>,
564 param_env: ty::ParamEnv<'tcx>,
565 item_def_id: LocalDefId,
566 to_check: T,
567 wf_tys: &FxIndexSet<Ty<'tcx>>,
568 gat_def_id: LocalDefId,
569 gat_generics: &'tcx ty::Generics,
570) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
571 let mut bounds = FxIndexSet::default();
573
574 let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
575
576 if types.is_empty() && regions.is_empty() {
582 return None;
583 }
584
585 for (region_a, region_a_idx) in ®ions {
586 if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
590 continue;
591 }
592 for (ty, ty_idx) in &types {
597 if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
599 debug!(?ty_idx, ?region_a_idx);
600 debug!("required clause: {ty} must outlive {region_a}");
601 let ty_param = gat_generics.param_at(*ty_idx, tcx);
605 let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
606 let region_param = gat_generics.param_at(*region_a_idx, tcx);
609 let region_param = ty::Region::new_early_param(
610 tcx,
611 ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
612 );
613 bounds.insert(
616 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
617 .upcast(tcx),
618 );
619 }
620 }
621
622 for (region_b, region_b_idx) in ®ions {
627 if matches!(region_b.kind(), ty::ReStatic | ty::ReError(_)) || region_a == region_b {
631 continue;
632 }
633 if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
634 debug!(?region_a_idx, ?region_b_idx);
635 debug!("required clause: {region_a} must outlive {region_b}");
636 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
638 let region_a_param = ty::Region::new_early_param(
639 tcx,
640 ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
641 );
642 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
644 let region_b_param = ty::Region::new_early_param(
645 tcx,
646 ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
647 );
648 bounds.insert(
650 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
651 region_a_param,
652 region_b_param,
653 ))
654 .upcast(tcx),
655 );
656 }
657 }
658 }
659
660 Some(bounds)
661}
662
663fn ty_known_to_outlive<'tcx>(
666 tcx: TyCtxt<'tcx>,
667 id: LocalDefId,
668 param_env: ty::ParamEnv<'tcx>,
669 wf_tys: &FxIndexSet<Ty<'tcx>>,
670 ty: Ty<'tcx>,
671 region: ty::Region<'tcx>,
672) -> bool {
673 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
674 infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
675 sub_region: region,
676 sup_type: ty,
677 origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
678 });
679 })
680}
681
682fn region_known_to_outlive<'tcx>(
685 tcx: TyCtxt<'tcx>,
686 id: LocalDefId,
687 param_env: ty::ParamEnv<'tcx>,
688 wf_tys: &FxIndexSet<Ty<'tcx>>,
689 region_a: ty::Region<'tcx>,
690 region_b: ty::Region<'tcx>,
691) -> bool {
692 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
693 infcx.sub_regions(
694 SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
695 region_b,
696 region_a,
697 );
698 })
699}
700
701fn test_region_obligations<'tcx>(
705 tcx: TyCtxt<'tcx>,
706 id: LocalDefId,
707 param_env: ty::ParamEnv<'tcx>,
708 wf_tys: &FxIndexSet<Ty<'tcx>>,
709 add_constraints: impl FnOnce(&InferCtxt<'tcx>),
710) -> bool {
711 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
715
716 add_constraints(&infcx);
717
718 let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
719 debug!(?errors, "errors");
720
721 errors.is_empty()
724}
725
726struct GATArgsCollector<'tcx> {
731 gat: DefId,
732 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
734 types: FxIndexSet<(Ty<'tcx>, usize)>,
736}
737
738impl<'tcx> GATArgsCollector<'tcx> {
739 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
740 gat: DefId,
741 t: T,
742 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
743 let mut visitor =
744 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
745 t.visit_with(&mut visitor);
746 (visitor.regions, visitor.types)
747 }
748}
749
750impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
751 fn visit_ty(&mut self, t: Ty<'tcx>) {
752 match t.kind() {
753 ty::Alias(ty::Projection, p) if p.def_id == self.gat => {
754 for (idx, arg) in p.args.iter().enumerate() {
755 match arg.kind() {
756 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
757 self.regions.insert((lt, idx));
758 }
759 GenericArgKind::Type(t) => {
760 self.types.insert((t, idx));
761 }
762 _ => {}
763 }
764 }
765 }
766 _ => {}
767 }
768 t.super_visit_with(self)
769 }
770}
771
772fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
773 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
774 let trait_def_id = tcx.local_parent(trait_item_def_id);
775
776 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
777 .skip(1)
778 .flat_map(|supertrait_def_id| {
779 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
780 })
781 .collect();
782 if !shadowed.is_empty() {
783 let shadowee = if let [shadowed] = shadowed[..] {
784 errors::SupertraitItemShadowee::Labeled {
785 span: tcx.def_span(shadowed.def_id),
786 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
787 }
788 } else {
789 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
790 .iter()
791 .map(|item| {
792 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
793 })
794 .unzip();
795 errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
796 };
797
798 tcx.emit_node_span_lint(
799 SUPERTRAIT_ITEM_SHADOWING_DEFINITION,
800 tcx.local_def_id_to_hir_id(trait_item_def_id),
801 tcx.def_span(trait_item_def_id),
802 errors::SupertraitItemShadowing {
803 item: item_name,
804 subtrait: tcx.item_name(trait_def_id.to_def_id()),
805 shadowee,
806 },
807 );
808 }
809}
810
811fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
812 match param.kind {
813 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
815
816 ty::GenericParamDefKind::Const { .. } => {
818 let ty = tcx.type_of(param.def_id).instantiate_identity();
819 let span = tcx.def_span(param.def_id);
820 let def_id = param.def_id.expect_local();
821
822 if tcx.features().unsized_const_params() {
823 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
824 wfcx.register_bound(
825 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
826 wfcx.param_env,
827 ty,
828 tcx.require_lang_item(LangItem::UnsizedConstParamTy, span),
829 );
830 Ok(())
831 })
832 } else if tcx.features().adt_const_params() {
833 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
834 wfcx.register_bound(
835 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
836 wfcx.param_env,
837 ty,
838 tcx.require_lang_item(LangItem::ConstParamTy, span),
839 );
840 Ok(())
841 })
842 } else {
843 let span = || {
844 let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
845 tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
846 else {
847 bug!()
848 };
849 span
850 };
851 let mut diag = match ty.kind() {
852 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
853 ty::FnPtr(..) => tcx.dcx().struct_span_err(
854 span(),
855 "using function pointers as const generic parameters is forbidden",
856 ),
857 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
858 span(),
859 "using raw pointers as const generic parameters is forbidden",
860 ),
861 _ => {
862 ty.error_reported()?;
864
865 tcx.dcx().struct_span_err(
866 span(),
867 format!(
868 "`{ty}` is forbidden as the type of a const generic parameter",
869 ),
870 )
871 }
872 };
873
874 diag.note("the only supported types are integers, `bool`, and `char`");
875
876 let cause = ObligationCause::misc(span(), def_id);
877 let adt_const_params_feature_string =
878 " more complex and user defined types".to_string();
879 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
880 tcx,
881 tcx.param_env(param.def_id),
882 ty,
883 LangItem::ConstParamTy,
884 cause,
885 ) {
886 Err(
888 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
889 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
890 ) => None,
891 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
892 Some(vec![
893 (adt_const_params_feature_string, sym::adt_const_params),
894 (
895 " references to implement the `ConstParamTy` trait".into(),
896 sym::unsized_const_params,
897 ),
898 ])
899 }
900 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
903 fn ty_is_local(ty: Ty<'_>) -> bool {
904 match ty.kind() {
905 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
906 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
908 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
911 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
914 _ => false,
915 }
916 }
917
918 ty_is_local(ty).then_some(vec![(
919 adt_const_params_feature_string,
920 sym::adt_const_params,
921 )])
922 }
923 Ok(..) => Some(vec![(adt_const_params_feature_string, sym::adt_const_params)]),
925 };
926 if let Some(features) = may_suggest_feature {
927 tcx.disabled_nightly_features(&mut diag, features);
928 }
929
930 Err(diag.emit())
931 }
932 }
933 }
934}
935
936#[instrument(level = "debug", skip(tcx))]
937pub(crate) fn check_associated_item(
938 tcx: TyCtxt<'_>,
939 item_id: LocalDefId,
940) -> Result<(), ErrorGuaranteed> {
941 let loc = Some(WellFormedLoc::Ty(item_id));
942 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
943 let item = tcx.associated_item(item_id);
944
945 tcx.ensure_ok()
948 .coherent_trait(tcx.parent(item.trait_item_def_id.unwrap_or(item_id.into())))?;
949
950 let self_ty = match item.container {
951 ty::AssocItemContainer::Trait => tcx.types.self_param,
952 ty::AssocItemContainer::Impl => {
953 tcx.type_of(item.container_id(tcx)).instantiate_identity()
954 }
955 };
956
957 let span = tcx.def_span(item_id);
958
959 match item.kind {
960 ty::AssocKind::Const { .. } => {
961 let ty = tcx.type_of(item.def_id).instantiate_identity();
962 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
963 wfcx.register_wf_obligation(span, loc, ty.into());
964 check_sized_if_body(
965 wfcx,
966 item.def_id.expect_local(),
967 ty,
968 Some(span),
969 ObligationCauseCode::SizedConstOrStatic,
970 );
971 Ok(())
972 }
973 ty::AssocKind::Fn { .. } => {
974 let sig = tcx.fn_sig(item.def_id).instantiate_identity();
975 let hir_sig =
976 tcx.hir_node_by_def_id(item_id).fn_sig().expect("bad signature for method");
977 check_fn_or_method(wfcx, sig, hir_sig.decl, item_id);
978 check_method_receiver(wfcx, hir_sig, item, self_ty)
979 }
980 ty::AssocKind::Type { .. } => {
981 if let ty::AssocItemContainer::Trait = item.container {
982 check_associated_type_bounds(wfcx, item, span)
983 }
984 if item.defaultness(tcx).has_value() {
985 let ty = tcx.type_of(item.def_id).instantiate_identity();
986 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
987 wfcx.register_wf_obligation(span, loc, ty.into());
988 }
989 Ok(())
990 }
991 }
992 })
993}
994
995fn check_type_defn<'tcx>(
997 tcx: TyCtxt<'tcx>,
998 item: &hir::Item<'tcx>,
999 all_sized: bool,
1000) -> Result<(), ErrorGuaranteed> {
1001 let _ = tcx.representability(item.owner_id.def_id);
1002 let adt_def = tcx.adt_def(item.owner_id);
1003
1004 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1005 let variants = adt_def.variants();
1006 let packed = adt_def.repr().packed();
1007
1008 for variant in variants.iter() {
1009 for field in &variant.fields {
1011 if let Some(def_id) = field.value
1012 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1013 {
1014 if let Some(def_id) = def_id.as_local()
1017 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1018 && let expr = &tcx.hir_body(anon.body).value
1019 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1020 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1021 {
1022 } else {
1025 let _ = tcx.const_eval_poly(def_id);
1028 }
1029 }
1030 let field_id = field.did.expect_local();
1031 let hir::FieldDef { ty: hir_ty, .. } =
1032 tcx.hir_node_by_def_id(field_id).expect_field();
1033 let ty = wfcx.deeply_normalize(
1034 hir_ty.span,
1035 None,
1036 tcx.type_of(field.did).instantiate_identity(),
1037 );
1038 wfcx.register_wf_obligation(
1039 hir_ty.span,
1040 Some(WellFormedLoc::Ty(field_id)),
1041 ty.into(),
1042 )
1043 }
1044
1045 let needs_drop_copy = || {
1048 packed && {
1049 let ty = tcx.type_of(variant.tail().did).instantiate_identity();
1050 let ty = tcx.erase_regions(ty);
1051 assert!(!ty.has_infer());
1052 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1053 }
1054 };
1055 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1057 let unsized_len = if all_sized { 0 } else { 1 };
1058 for (idx, field) in
1059 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1060 {
1061 let last = idx == variant.fields.len() - 1;
1062 let field_id = field.did.expect_local();
1063 let hir::FieldDef { ty: hir_ty, .. } =
1064 tcx.hir_node_by_def_id(field_id).expect_field();
1065 let ty = wfcx.normalize(
1066 hir_ty.span,
1067 None,
1068 tcx.type_of(field.did).instantiate_identity(),
1069 );
1070 wfcx.register_bound(
1071 traits::ObligationCause::new(
1072 hir_ty.span,
1073 wfcx.body_def_id,
1074 ObligationCauseCode::FieldSized {
1075 adt_kind: match &item.kind {
1076 ItemKind::Struct(..) => AdtKind::Struct,
1077 ItemKind::Union(..) => AdtKind::Union,
1078 ItemKind::Enum(..) => AdtKind::Enum,
1079 kind => span_bug!(
1080 item.span,
1081 "should be wfchecking an ADT, got {kind:?}"
1082 ),
1083 },
1084 span: hir_ty.span,
1085 last,
1086 },
1087 ),
1088 wfcx.param_env,
1089 ty,
1090 tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1091 );
1092 }
1093
1094 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1096 match tcx.const_eval_poly(discr_def_id) {
1097 Ok(_) => {}
1098 Err(ErrorHandled::Reported(..)) => {}
1099 Err(ErrorHandled::TooGeneric(sp)) => {
1100 span_bug!(sp, "enum variant discr was too generic to eval")
1101 }
1102 }
1103 }
1104 }
1105
1106 check_where_clauses(wfcx, item.owner_id.def_id);
1107 Ok(())
1108 })
1109}
1110
1111#[instrument(skip(tcx, item))]
1112fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1113 debug!(?item.owner_id);
1114
1115 let def_id = item.owner_id.def_id;
1116 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1117 return Ok(());
1119 }
1120
1121 let trait_def = tcx.trait_def(def_id);
1122 if trait_def.is_marker
1123 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1124 {
1125 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1126 struct_span_code_err!(
1127 tcx.dcx(),
1128 tcx.def_span(*associated_def_id),
1129 E0714,
1130 "marker traits cannot have associated items",
1131 )
1132 .emit();
1133 }
1134 }
1135
1136 let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1137 check_where_clauses(wfcx, def_id);
1138 Ok(())
1139 });
1140
1141 if let hir::ItemKind::Trait(..) = item.kind {
1143 check_gat_where_clauses(tcx, item.owner_id.def_id);
1144 }
1145 res
1146}
1147
1148fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, span: Span) {
1153 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1154
1155 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1156 let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
1157 let normalized_bound = wfcx.normalize(span, None, bound);
1158 traits::wf::clause_obligations(
1159 wfcx.infcx,
1160 wfcx.param_env,
1161 wfcx.body_def_id,
1162 normalized_bound,
1163 bound_span,
1164 )
1165 });
1166
1167 wfcx.register_obligations(wf_obligations);
1168}
1169
1170fn check_item_fn(
1171 tcx: TyCtxt<'_>,
1172 def_id: LocalDefId,
1173 decl: &hir::FnDecl<'_>,
1174) -> Result<(), ErrorGuaranteed> {
1175 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1176 let sig = tcx.fn_sig(def_id).instantiate_identity();
1177 check_fn_or_method(wfcx, sig, decl, def_id);
1178 Ok(())
1179 })
1180}
1181
1182#[instrument(level = "debug", skip(tcx))]
1183pub(super) fn check_static_item(
1184 tcx: TyCtxt<'_>,
1185 item_id: LocalDefId,
1186) -> Result<(), ErrorGuaranteed> {
1187 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1188 let ty = tcx.type_of(item_id).instantiate_identity();
1189 let span = tcx.ty_span(item_id);
1190 let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1191
1192 let is_foreign_item = tcx.is_foreign_item(item_id);
1193
1194 let forbid_unsized = !is_foreign_item || {
1195 let tail = tcx.struct_tail_for_codegen(item_ty, wfcx.infcx.typing_env(wfcx.param_env));
1196 !matches!(tail.kind(), ty::Foreign(_))
1197 };
1198
1199 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1200 if forbid_unsized {
1201 let span = tcx.def_span(item_id);
1202 wfcx.register_bound(
1203 traits::ObligationCause::new(
1204 span,
1205 wfcx.body_def_id,
1206 ObligationCauseCode::SizedConstOrStatic,
1207 ),
1208 wfcx.param_env,
1209 item_ty,
1210 tcx.require_lang_item(LangItem::Sized, span),
1211 );
1212 }
1213
1214 let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1216 == Some(hir::Mutability::Not)
1217 && !is_foreign_item
1218 && !tcx.is_thread_local_static(item_id.to_def_id());
1219
1220 if should_check_for_sync {
1221 wfcx.register_bound(
1222 traits::ObligationCause::new(
1223 span,
1224 wfcx.body_def_id,
1225 ObligationCauseCode::SharedStatic,
1226 ),
1227 wfcx.param_env,
1228 item_ty,
1229 tcx.require_lang_item(LangItem::Sync, span),
1230 );
1231 }
1232 Ok(())
1233 })
1234}
1235
1236pub(crate) fn check_const_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1237 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1238 let ty = tcx.type_of(def_id).instantiate_identity();
1239 let ty_span = tcx.ty_span(def_id);
1240 let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
1241
1242 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
1243 wfcx.register_bound(
1244 traits::ObligationCause::new(
1245 ty_span,
1246 wfcx.body_def_id,
1247 ObligationCauseCode::SizedConstOrStatic,
1248 ),
1249 wfcx.param_env,
1250 ty,
1251 tcx.require_lang_item(LangItem::Sized, ty_span),
1252 );
1253
1254 check_where_clauses(wfcx, def_id);
1255
1256 Ok(())
1257 })
1258}
1259
1260#[instrument(level = "debug", skip(tcx, hir_self_ty, hir_trait_ref))]
1261fn check_impl<'tcx>(
1262 tcx: TyCtxt<'tcx>,
1263 item: &'tcx hir::Item<'tcx>,
1264 hir_self_ty: &hir::Ty<'_>,
1265 hir_trait_ref: &Option<hir::TraitRef<'_>>,
1266) -> Result<(), ErrorGuaranteed> {
1267 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1268 match hir_trait_ref {
1269 Some(hir_trait_ref) => {
1270 let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().instantiate_identity();
1274 tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1277 let trait_span = hir_trait_ref.path.span;
1278 let trait_ref = wfcx.deeply_normalize(
1279 trait_span,
1280 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1281 trait_ref,
1282 );
1283 let trait_pred =
1284 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1285 let mut obligations = traits::wf::trait_obligations(
1286 wfcx.infcx,
1287 wfcx.param_env,
1288 wfcx.body_def_id,
1289 trait_pred,
1290 trait_span,
1291 item,
1292 );
1293 for obligation in &mut obligations {
1294 if obligation.cause.span != trait_span {
1295 continue;
1297 }
1298 if let Some(pred) = obligation.predicate.as_trait_clause()
1299 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1300 {
1301 obligation.cause.span = hir_self_ty.span;
1302 }
1303 if let Some(pred) = obligation.predicate.as_projection_clause()
1304 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1305 {
1306 obligation.cause.span = hir_self_ty.span;
1307 }
1308 }
1309
1310 if tcx.is_conditionally_const(item.owner_id.def_id) {
1312 for (bound, _) in
1313 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1314 {
1315 let bound = wfcx.normalize(
1316 item.span,
1317 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1318 bound,
1319 );
1320 wfcx.register_obligation(Obligation::new(
1321 tcx,
1322 ObligationCause::new(
1323 hir_self_ty.span,
1324 wfcx.body_def_id,
1325 ObligationCauseCode::WellFormed(None),
1326 ),
1327 wfcx.param_env,
1328 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1329 ))
1330 }
1331 }
1332
1333 debug!(?obligations);
1334 wfcx.register_obligations(obligations);
1335 }
1336 None => {
1337 let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1338 let self_ty = wfcx.deeply_normalize(
1339 item.span,
1340 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1341 self_ty,
1342 );
1343 wfcx.register_wf_obligation(
1344 hir_self_ty.span,
1345 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1346 self_ty.into(),
1347 );
1348 }
1349 }
1350
1351 check_where_clauses(wfcx, item.owner_id.def_id);
1352 Ok(())
1353 })
1354}
1355
1356#[instrument(level = "debug", skip(wfcx))]
1358pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1359 let infcx = wfcx.infcx;
1360 let tcx = wfcx.tcx();
1361
1362 let predicates = tcx.predicates_of(def_id.to_def_id());
1363 let generics = tcx.generics_of(def_id);
1364
1365 for param in &generics.own_params {
1372 if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1373 if !default.has_param() {
1380 wfcx.register_wf_obligation(
1381 tcx.def_span(param.def_id),
1382 matches!(param.kind, GenericParamDefKind::Type { .. })
1383 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1384 default.as_term().unwrap(),
1385 );
1386 } else {
1387 let GenericArgKind::Const(ct) = default.kind() else {
1390 continue;
1391 };
1392
1393 let ct_ty = match ct.kind() {
1394 ty::ConstKind::Infer(_)
1395 | ty::ConstKind::Placeholder(_)
1396 | ty::ConstKind::Bound(_, _) => unreachable!(),
1397 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1398 ty::ConstKind::Value(cv) => cv.ty,
1399 ty::ConstKind::Unevaluated(uv) => {
1400 infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1401 }
1402 ty::ConstKind::Param(param_ct) => {
1403 param_ct.find_const_ty_from_env(wfcx.param_env)
1404 }
1405 };
1406
1407 let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1408 if !ct_ty.has_param() && !param_ty.has_param() {
1409 let cause = traits::ObligationCause::new(
1410 tcx.def_span(param.def_id),
1411 wfcx.body_def_id,
1412 ObligationCauseCode::WellFormed(None),
1413 );
1414 wfcx.register_obligation(Obligation::new(
1415 tcx,
1416 cause,
1417 wfcx.param_env,
1418 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1419 ));
1420 }
1421 }
1422 }
1423 }
1424
1425 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1434 if param.index >= generics.parent_count as u32
1435 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1437 && !default.has_param()
1439 {
1440 return default;
1442 }
1443 tcx.mk_param_from_def(param)
1444 });
1445
1446 let default_obligations = predicates
1448 .predicates
1449 .iter()
1450 .flat_map(|&(pred, sp)| {
1451 #[derive(Default)]
1452 struct CountParams {
1453 params: FxHashSet<u32>,
1454 }
1455 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1456 type Result = ControlFlow<()>;
1457 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1458 if let ty::Param(param) = t.kind() {
1459 self.params.insert(param.index);
1460 }
1461 t.super_visit_with(self)
1462 }
1463
1464 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1465 ControlFlow::Break(())
1466 }
1467
1468 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1469 if let ty::ConstKind::Param(param) = c.kind() {
1470 self.params.insert(param.index);
1471 }
1472 c.super_visit_with(self)
1473 }
1474 }
1475 let mut param_count = CountParams::default();
1476 let has_region = pred.visit_with(&mut param_count).is_break();
1477 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1478 if instantiated_pred.has_non_region_param()
1481 || param_count.params.len() > 1
1482 || has_region
1483 {
1484 None
1485 } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1486 None
1488 } else {
1489 Some((instantiated_pred, sp))
1490 }
1491 })
1492 .map(|(pred, sp)| {
1493 let pred = wfcx.normalize(sp, None, pred);
1503 let cause = traits::ObligationCause::new(
1504 sp,
1505 wfcx.body_def_id,
1506 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1507 );
1508 Obligation::new(tcx, cause, wfcx.param_env, pred)
1509 });
1510
1511 let predicates = predicates.instantiate_identity(tcx);
1512
1513 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1514 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1515 let p = wfcx.normalize(sp, None, p);
1516 traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1517 });
1518 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1519 wfcx.register_obligations(obligations);
1520}
1521
1522#[instrument(level = "debug", skip(wfcx, hir_decl))]
1523fn check_fn_or_method<'tcx>(
1524 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1525 sig: ty::PolyFnSig<'tcx>,
1526 hir_decl: &hir::FnDecl<'_>,
1527 def_id: LocalDefId,
1528) {
1529 let tcx = wfcx.tcx();
1530 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1531
1532 let arg_span =
1538 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1539
1540 sig.inputs_and_output =
1541 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1542 wfcx.deeply_normalize(
1543 arg_span(idx),
1544 Some(WellFormedLoc::Param {
1545 function: def_id,
1546 param_idx: idx,
1549 }),
1550 ty,
1551 )
1552 }));
1553
1554 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1555 wfcx.register_wf_obligation(
1556 arg_span(idx),
1557 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1558 ty.into(),
1559 );
1560 }
1561
1562 check_where_clauses(wfcx, def_id);
1563
1564 if sig.abi == ExternAbi::RustCall {
1565 let span = tcx.def_span(def_id);
1566 let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1567 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1568 if let Some(ty) = inputs.next() {
1570 wfcx.register_bound(
1571 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1572 wfcx.param_env,
1573 *ty,
1574 tcx.require_lang_item(hir::LangItem::Tuple, span),
1575 );
1576 wfcx.register_bound(
1577 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1578 wfcx.param_env,
1579 *ty,
1580 tcx.require_lang_item(hir::LangItem::Sized, span),
1581 );
1582 } else {
1583 tcx.dcx().span_err(
1584 hir_decl.inputs.last().map_or(span, |input| input.span),
1585 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1586 );
1587 }
1588 if inputs.next().is_some() {
1590 tcx.dcx().span_err(
1591 hir_decl.inputs.last().map_or(span, |input| input.span),
1592 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1593 );
1594 }
1595 }
1596
1597 check_sized_if_body(
1599 wfcx,
1600 def_id,
1601 sig.output(),
1602 match hir_decl.output {
1603 hir::FnRetTy::Return(ty) => Some(ty.span),
1604 hir::FnRetTy::DefaultReturn(_) => None,
1605 },
1606 ObligationCauseCode::SizedReturnType,
1607 );
1608}
1609
1610fn check_sized_if_body<'tcx>(
1611 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1612 def_id: LocalDefId,
1613 ty: Ty<'tcx>,
1614 maybe_span: Option<Span>,
1615 code: ObligationCauseCode<'tcx>,
1616) {
1617 let tcx = wfcx.tcx();
1618 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1619 let span = maybe_span.unwrap_or(body.value.span);
1620
1621 wfcx.register_bound(
1622 ObligationCause::new(span, def_id, code),
1623 wfcx.param_env,
1624 ty,
1625 tcx.require_lang_item(LangItem::Sized, span),
1626 );
1627 }
1628}
1629
1630#[derive(Clone, Copy, PartialEq)]
1632enum ArbitrarySelfTypesLevel {
1633 Basic, WithPointers, }
1636
1637#[instrument(level = "debug", skip(wfcx))]
1638fn check_method_receiver<'tcx>(
1639 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1640 fn_sig: &hir::FnSig<'_>,
1641 method: ty::AssocItem,
1642 self_ty: Ty<'tcx>,
1643) -> Result<(), ErrorGuaranteed> {
1644 let tcx = wfcx.tcx();
1645
1646 if !method.is_method() {
1647 return Ok(());
1648 }
1649
1650 let span = fn_sig.decl.inputs[0].span;
1651 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1652
1653 let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1654 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1655 let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1656
1657 debug!("check_method_receiver: sig={:?}", sig);
1658
1659 let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1660
1661 let receiver_ty = sig.inputs()[0];
1662 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1663
1664 if receiver_ty.references_error() {
1667 return Ok(());
1668 }
1669
1670 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1671 Some(ArbitrarySelfTypesLevel::WithPointers)
1672 } else if tcx.features().arbitrary_self_types() {
1673 Some(ArbitrarySelfTypesLevel::Basic)
1674 } else {
1675 None
1676 };
1677 let generics = tcx.generics_of(method.def_id);
1678
1679 let receiver_validity =
1680 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1681 if let Err(receiver_validity_err) = receiver_validity {
1682 return Err(match arbitrary_self_types_level {
1683 None if receiver_is_valid(
1687 wfcx,
1688 span,
1689 receiver_ty,
1690 self_ty,
1691 Some(ArbitrarySelfTypesLevel::Basic),
1692 generics,
1693 )
1694 .is_ok() =>
1695 {
1696 feature_err(
1698 &tcx.sess,
1699 sym::arbitrary_self_types,
1700 span,
1701 format!(
1702 "`{receiver_ty}` cannot be used as the type of `self` without \
1703 the `arbitrary_self_types` feature",
1704 ),
1705 )
1706 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1707 .emit()
1708 }
1709 None | Some(ArbitrarySelfTypesLevel::Basic)
1710 if receiver_is_valid(
1711 wfcx,
1712 span,
1713 receiver_ty,
1714 self_ty,
1715 Some(ArbitrarySelfTypesLevel::WithPointers),
1716 generics,
1717 )
1718 .is_ok() =>
1719 {
1720 feature_err(
1722 &tcx.sess,
1723 sym::arbitrary_self_types_pointers,
1724 span,
1725 format!(
1726 "`{receiver_ty}` cannot be used as the type of `self` without \
1727 the `arbitrary_self_types_pointers` feature",
1728 ),
1729 )
1730 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1731 .emit()
1732 }
1733 _ =>
1734 {
1736 match receiver_validity_err {
1737 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1738 let hint = match receiver_ty
1739 .builtin_deref(false)
1740 .unwrap_or(receiver_ty)
1741 .ty_adt_def()
1742 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1743 {
1744 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1745 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1746 _ => None,
1747 };
1748
1749 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1750 }
1751 ReceiverValidityError::DoesNotDeref => {
1752 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1753 span,
1754 receiver_ty,
1755 })
1756 }
1757 ReceiverValidityError::MethodGenericParamUsed => {
1758 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1759 }
1760 }
1761 }
1762 });
1763 }
1764 Ok(())
1765}
1766
1767enum ReceiverValidityError {
1771 DoesNotDeref,
1774 MethodGenericParamUsed,
1776}
1777
1778fn confirm_type_is_not_a_method_generic_param(
1781 ty: Ty<'_>,
1782 method_generics: &ty::Generics,
1783) -> Result<(), ReceiverValidityError> {
1784 if let ty::Param(param) = ty.kind() {
1785 if (param.index as usize) >= method_generics.parent_count {
1786 return Err(ReceiverValidityError::MethodGenericParamUsed);
1787 }
1788 }
1789 Ok(())
1790}
1791
1792fn receiver_is_valid<'tcx>(
1802 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1803 span: Span,
1804 receiver_ty: Ty<'tcx>,
1805 self_ty: Ty<'tcx>,
1806 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1807 method_generics: &ty::Generics,
1808) -> Result<(), ReceiverValidityError> {
1809 let infcx = wfcx.infcx;
1810 let tcx = wfcx.tcx();
1811 let cause =
1812 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1813
1814 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1816 let ocx = ObligationCtxt::new(wfcx.infcx);
1817 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1818 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1819 }) {
1820 return Ok(());
1821 }
1822
1823 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1824
1825 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1826
1827 if arbitrary_self_types_enabled.is_some() {
1831 autoderef = autoderef.use_receiver_trait();
1832 }
1833
1834 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1836 autoderef = autoderef.include_raw_pointers();
1837 }
1838
1839 while let Some((potential_self_ty, _)) = autoderef.next() {
1841 debug!(
1842 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1843 potential_self_ty, self_ty
1844 );
1845
1846 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1847
1848 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1851 let ocx = ObligationCtxt::new(wfcx.infcx);
1852 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1853 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1854 }) {
1855 wfcx.register_obligations(autoderef.into_obligations());
1856 return Ok(());
1857 }
1858
1859 if arbitrary_self_types_enabled.is_none() {
1862 let legacy_receiver_trait_def_id =
1863 tcx.require_lang_item(LangItem::LegacyReceiver, span);
1864 if !legacy_receiver_is_implemented(
1865 wfcx,
1866 legacy_receiver_trait_def_id,
1867 cause.clone(),
1868 potential_self_ty,
1869 ) {
1870 break;
1872 }
1873
1874 wfcx.register_bound(
1876 cause.clone(),
1877 wfcx.param_env,
1878 potential_self_ty,
1879 legacy_receiver_trait_def_id,
1880 );
1881 }
1882 }
1883
1884 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1885 Err(ReceiverValidityError::DoesNotDeref)
1886}
1887
1888fn legacy_receiver_is_implemented<'tcx>(
1889 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1890 legacy_receiver_trait_def_id: DefId,
1891 cause: ObligationCause<'tcx>,
1892 receiver_ty: Ty<'tcx>,
1893) -> bool {
1894 let tcx = wfcx.tcx();
1895 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1896
1897 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1898
1899 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1900 true
1901 } else {
1902 debug!(
1903 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1904 receiver_ty
1905 );
1906 false
1907 }
1908}
1909
1910pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1911 match tcx.def_kind(def_id) {
1912 DefKind::Enum | DefKind::Struct | DefKind::Union => {
1913 }
1915 DefKind::TyAlias => {
1916 assert!(
1917 tcx.type_alias_is_lazy(def_id),
1918 "should not be computing variance of non-free type alias"
1919 );
1920 }
1921 kind => span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
1922 }
1923
1924 let ty_predicates = tcx.predicates_of(def_id);
1925 assert_eq!(ty_predicates.parent, None);
1926 let variances = tcx.variances_of(def_id);
1927
1928 let mut constrained_parameters: FxHashSet<_> = variances
1929 .iter()
1930 .enumerate()
1931 .filter(|&(_, &variance)| variance != ty::Bivariant)
1932 .map(|(index, _)| Parameter(index as u32))
1933 .collect();
1934
1935 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1936
1937 let explicitly_bounded_params = LazyCell::new(|| {
1939 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
1940 tcx.hir_node_by_def_id(def_id)
1941 .generics()
1942 .unwrap()
1943 .predicates
1944 .iter()
1945 .filter_map(|predicate| match predicate.kind {
1946 hir::WherePredicateKind::BoundPredicate(predicate) => {
1947 match icx.lower_ty(predicate.bounded_ty).kind() {
1948 ty::Param(data) => Some(Parameter(data.index)),
1949 _ => None,
1950 }
1951 }
1952 _ => None,
1953 })
1954 .collect::<FxHashSet<_>>()
1955 });
1956
1957 for (index, _) in variances.iter().enumerate() {
1958 let parameter = Parameter(index as u32);
1959
1960 if constrained_parameters.contains(¶meter) {
1961 continue;
1962 }
1963
1964 let node = tcx.hir_node_by_def_id(def_id);
1965 let item = node.expect_item();
1966 let hir_generics = node.generics().unwrap();
1967 let hir_param = &hir_generics.params[index];
1968
1969 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
1970
1971 if ty_param.def_id != hir_param.def_id.into() {
1972 tcx.dcx().span_delayed_bug(
1980 hir_param.span,
1981 "hir generics and ty generics in different order",
1982 );
1983 continue;
1984 }
1985
1986 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
1988 .type_of(def_id)
1989 .instantiate_identity()
1990 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
1991 {
1992 continue;
1993 }
1994
1995 match hir_param.name {
1996 hir::ParamName::Error(_) => {
1997 }
2000 _ => {
2001 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2002 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2003 }
2004 }
2005 }
2006}
2007
2008struct HasErrorDeep<'tcx> {
2010 tcx: TyCtxt<'tcx>,
2011 seen: FxHashSet<DefId>,
2012}
2013impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2014 type Result = ControlFlow<ErrorGuaranteed>;
2015
2016 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2017 match *ty.kind() {
2018 ty::Adt(def, _) => {
2019 if self.seen.insert(def.did()) {
2020 for field in def.all_fields() {
2021 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2022 }
2023 }
2024 }
2025 ty::Error(guar) => return ControlFlow::Break(guar),
2026 _ => {}
2027 }
2028 ty.super_visit_with(self)
2029 }
2030
2031 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2032 if let Err(guar) = r.error_reported() {
2033 ControlFlow::Break(guar)
2034 } else {
2035 ControlFlow::Continue(())
2036 }
2037 }
2038
2039 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2040 if let Err(guar) = c.error_reported() {
2041 ControlFlow::Break(guar)
2042 } else {
2043 ControlFlow::Continue(())
2044 }
2045 }
2046}
2047
2048fn report_bivariance<'tcx>(
2049 tcx: TyCtxt<'tcx>,
2050 param: &'tcx hir::GenericParam<'tcx>,
2051 has_explicit_bounds: bool,
2052 item: &'tcx hir::Item<'tcx>,
2053) -> ErrorGuaranteed {
2054 let param_name = param.name.ident();
2055
2056 let help = match item.kind {
2057 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2058 if let Some(def_id) = tcx.lang_items().phantom_data() {
2059 errors::UnusedGenericParameterHelp::Adt {
2060 param_name,
2061 phantom_data: tcx.def_path_str(def_id),
2062 }
2063 } else {
2064 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2065 }
2066 }
2067 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2068 item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2069 };
2070
2071 let mut usage_spans = vec![];
2072 intravisit::walk_item(
2073 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2074 item,
2075 );
2076
2077 if !usage_spans.is_empty() {
2078 let item_def_id = item.owner_id.to_def_id();
2082 let is_probably_cyclical =
2083 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2084 .visit_def(item_def_id)
2085 .is_break();
2086 if is_probably_cyclical {
2095 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2096 spans: usage_spans,
2097 param_span: param.span,
2098 param_name,
2099 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2100 help,
2101 note: (),
2102 });
2103 }
2104 }
2105
2106 let const_param_help =
2107 matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2108
2109 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2110 span: param.span,
2111 param_name,
2112 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2113 usage_spans,
2114 help,
2115 const_param_help,
2116 });
2117 diag.code(E0392);
2118 diag.emit()
2119}
2120
2121struct IsProbablyCyclical<'tcx> {
2127 tcx: TyCtxt<'tcx>,
2128 item_def_id: DefId,
2129 seen: FxHashSet<DefId>,
2130}
2131
2132impl<'tcx> IsProbablyCyclical<'tcx> {
2133 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2134 match self.tcx.def_kind(def_id) {
2135 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2136 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2137 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2138 })
2139 }
2140 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2141 self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2142 }
2143 _ => ControlFlow::Continue(()),
2144 }
2145 }
2146}
2147
2148impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2149 type Result = ControlFlow<(), ()>;
2150
2151 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2152 let def_id = match ty.kind() {
2153 ty::Adt(adt_def, _) => Some(adt_def.did()),
2154 ty::Alias(ty::Free, alias_ty) => Some(alias_ty.def_id),
2155 _ => None,
2156 };
2157 if let Some(def_id) = def_id {
2158 if def_id == self.item_def_id {
2159 return ControlFlow::Break(());
2160 }
2161 if self.seen.insert(def_id) {
2162 self.visit_def(def_id)?;
2163 }
2164 }
2165 ty.super_visit_with(self)
2166 }
2167}
2168
2169struct CollectUsageSpans<'a> {
2174 spans: &'a mut Vec<Span>,
2175 param_def_id: DefId,
2176}
2177
2178impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2179 type Result = ();
2180
2181 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2182 }
2184
2185 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2186 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2187 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2188 && def_id == self.param_def_id
2189 {
2190 self.spans.push(t.span);
2191 return;
2192 } else if let Res::SelfTyAlias { .. } = qpath.res {
2193 self.spans.push(t.span);
2194 return;
2195 }
2196 }
2197 intravisit::walk_ty(self, t);
2198 }
2199}
2200
2201impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2202 #[instrument(level = "debug", skip(self))]
2205 fn check_false_global_bounds(&mut self) {
2206 let tcx = self.ocx.infcx.tcx;
2207 let mut span = tcx.def_span(self.body_def_id);
2208 let empty_env = ty::ParamEnv::empty();
2209
2210 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2211 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2213
2214 for (pred, obligation_span) in implied_obligations {
2215 if let ty::ClauseKind::WellFormed(..) = pred.kind().skip_binder() {
2219 continue;
2220 }
2221 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2223 let pred = self.normalize(span, None, pred);
2224
2225 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2227 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2228 span = predicates
2229 .iter()
2230 .find(|pred| pred.span.contains(obligation_span))
2232 .map(|pred| pred.span)
2233 .unwrap_or(obligation_span);
2234 }
2235
2236 let obligation = Obligation::new(
2237 tcx,
2238 traits::ObligationCause::new(
2239 span,
2240 self.body_def_id,
2241 ObligationCauseCode::TrivialBound,
2242 ),
2243 empty_env,
2244 pred,
2245 );
2246 self.ocx.register_obligation(obligation);
2247 }
2248 }
2249 }
2250}
2251
2252pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2253 let items = tcx.hir_crate_items(());
2254 let res = items
2255 .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2256 .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2257 .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2258 .and(
2259 items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2260 )
2261 .and(items.par_nested_bodies(|item| tcx.ensure_ok().check_well_formed(item)))
2262 .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2263 super::entry::check_for_entry_fn(tcx);
2264
2265 res
2266}
2267
2268fn lint_redundant_lifetimes<'tcx>(
2269 tcx: TyCtxt<'tcx>,
2270 owner_id: LocalDefId,
2271 outlives_env: &OutlivesEnvironment<'tcx>,
2272) {
2273 let def_kind = tcx.def_kind(owner_id);
2274 match def_kind {
2275 DefKind::Struct
2276 | DefKind::Union
2277 | DefKind::Enum
2278 | DefKind::Trait
2279 | DefKind::TraitAlias
2280 | DefKind::Fn
2281 | DefKind::Const
2282 | DefKind::Impl { of_trait: _ } => {
2283 }
2285 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2286 let parent_def_id = tcx.local_parent(owner_id);
2287 if matches!(tcx.def_kind(parent_def_id), DefKind::Impl { of_trait: true }) {
2288 return;
2293 }
2294 }
2295 DefKind::Mod
2296 | DefKind::Variant
2297 | DefKind::TyAlias
2298 | DefKind::ForeignTy
2299 | DefKind::TyParam
2300 | DefKind::ConstParam
2301 | DefKind::Static { .. }
2302 | DefKind::Ctor(_, _)
2303 | DefKind::Macro(_)
2304 | DefKind::ExternCrate
2305 | DefKind::Use
2306 | DefKind::ForeignMod
2307 | DefKind::AnonConst
2308 | DefKind::InlineConst
2309 | DefKind::OpaqueTy
2310 | DefKind::Field
2311 | DefKind::LifetimeParam
2312 | DefKind::GlobalAsm
2313 | DefKind::Closure
2314 | DefKind::SyntheticCoroutineBody => return,
2315 }
2316
2317 let mut lifetimes = vec![tcx.lifetimes.re_static];
2326 lifetimes.extend(
2327 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2328 );
2329 if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2331 for (idx, var) in
2332 tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2333 {
2334 let ty::BoundVariableKind::Region(kind) = var else { continue };
2335 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2336 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2337 }
2338 }
2339 lifetimes.retain(|candidate| candidate.is_named(tcx));
2340
2341 let mut shadowed = FxHashSet::default();
2345
2346 for (idx, &candidate) in lifetimes.iter().enumerate() {
2347 if shadowed.contains(&candidate) {
2352 continue;
2353 }
2354
2355 for &victim in &lifetimes[(idx + 1)..] {
2356 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2364 continue;
2365 };
2366
2367 if tcx.parent(def_id) != owner_id.to_def_id() {
2372 continue;
2373 }
2374
2375 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2377 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2378 {
2379 shadowed.insert(victim);
2380 tcx.emit_node_span_lint(
2381 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2382 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2383 tcx.def_span(def_id),
2384 RedundantLifetimeArgsLint { candidate, victim },
2385 );
2386 }
2387 }
2388 }
2389}
2390
2391#[derive(LintDiagnostic)]
2392#[diag(hir_analysis_redundant_lifetime_args)]
2393#[note]
2394struct RedundantLifetimeArgsLint<'tcx> {
2395 victim: ty::Region<'tcx>,
2397 candidate: ty::Region<'tcx>,
2399}