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(crate) fn check_static_item<'tcx>(
1184 tcx: TyCtxt<'tcx>,
1185 item_id: LocalDefId,
1186 ty: Ty<'tcx>,
1187 should_check_for_sync: bool,
1188) -> Result<(), ErrorGuaranteed> {
1189 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1190 let span = tcx.ty_span(item_id);
1191 let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1192
1193 let is_foreign_item = tcx.is_foreign_item(item_id);
1194
1195 let forbid_unsized = !is_foreign_item || {
1196 let tail = tcx.struct_tail_for_codegen(item_ty, wfcx.infcx.typing_env(wfcx.param_env));
1197 !matches!(tail.kind(), ty::Foreign(_))
1198 };
1199
1200 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1201 if forbid_unsized {
1202 let span = tcx.def_span(item_id);
1203 wfcx.register_bound(
1204 traits::ObligationCause::new(
1205 span,
1206 wfcx.body_def_id,
1207 ObligationCauseCode::SizedConstOrStatic,
1208 ),
1209 wfcx.param_env,
1210 item_ty,
1211 tcx.require_lang_item(LangItem::Sized, span),
1212 );
1213 }
1214
1215 let should_check_for_sync = should_check_for_sync
1217 && !is_foreign_item
1218 && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1219 && !tcx.is_thread_local_static(item_id.to_def_id());
1220
1221 if should_check_for_sync {
1222 wfcx.register_bound(
1223 traits::ObligationCause::new(
1224 span,
1225 wfcx.body_def_id,
1226 ObligationCauseCode::SharedStatic,
1227 ),
1228 wfcx.param_env,
1229 item_ty,
1230 tcx.require_lang_item(LangItem::Sync, span),
1231 );
1232 }
1233 Ok(())
1234 })
1235}
1236
1237pub(crate) fn check_const_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1238 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1239 let ty = tcx.type_of(def_id).instantiate_identity();
1240 let ty_span = tcx.ty_span(def_id);
1241 let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
1242
1243 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
1244 wfcx.register_bound(
1245 traits::ObligationCause::new(
1246 ty_span,
1247 wfcx.body_def_id,
1248 ObligationCauseCode::SizedConstOrStatic,
1249 ),
1250 wfcx.param_env,
1251 ty,
1252 tcx.require_lang_item(LangItem::Sized, ty_span),
1253 );
1254
1255 check_where_clauses(wfcx, def_id);
1256
1257 Ok(())
1258 })
1259}
1260
1261#[instrument(level = "debug", skip(tcx, hir_self_ty, hir_trait_ref))]
1262fn check_impl<'tcx>(
1263 tcx: TyCtxt<'tcx>,
1264 item: &'tcx hir::Item<'tcx>,
1265 hir_self_ty: &hir::Ty<'_>,
1266 hir_trait_ref: &Option<hir::TraitRef<'_>>,
1267) -> Result<(), ErrorGuaranteed> {
1268 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1269 match hir_trait_ref {
1270 Some(hir_trait_ref) => {
1271 let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().instantiate_identity();
1275 tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1278 let trait_span = hir_trait_ref.path.span;
1279 let trait_ref = wfcx.deeply_normalize(
1280 trait_span,
1281 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1282 trait_ref,
1283 );
1284 let trait_pred =
1285 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1286 let mut obligations = traits::wf::trait_obligations(
1287 wfcx.infcx,
1288 wfcx.param_env,
1289 wfcx.body_def_id,
1290 trait_pred,
1291 trait_span,
1292 item,
1293 );
1294 for obligation in &mut obligations {
1295 if obligation.cause.span != trait_span {
1296 continue;
1298 }
1299 if let Some(pred) = obligation.predicate.as_trait_clause()
1300 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1301 {
1302 obligation.cause.span = hir_self_ty.span;
1303 }
1304 if let Some(pred) = obligation.predicate.as_projection_clause()
1305 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1306 {
1307 obligation.cause.span = hir_self_ty.span;
1308 }
1309 }
1310
1311 if tcx.is_conditionally_const(item.owner_id.def_id) {
1313 for (bound, _) in
1314 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1315 {
1316 let bound = wfcx.normalize(
1317 item.span,
1318 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1319 bound,
1320 );
1321 wfcx.register_obligation(Obligation::new(
1322 tcx,
1323 ObligationCause::new(
1324 hir_self_ty.span,
1325 wfcx.body_def_id,
1326 ObligationCauseCode::WellFormed(None),
1327 ),
1328 wfcx.param_env,
1329 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1330 ))
1331 }
1332 }
1333
1334 debug!(?obligations);
1335 wfcx.register_obligations(obligations);
1336 }
1337 None => {
1338 let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1339 let self_ty = wfcx.deeply_normalize(
1340 item.span,
1341 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1342 self_ty,
1343 );
1344 wfcx.register_wf_obligation(
1345 hir_self_ty.span,
1346 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1347 self_ty.into(),
1348 );
1349 }
1350 }
1351
1352 check_where_clauses(wfcx, item.owner_id.def_id);
1353 Ok(())
1354 })
1355}
1356
1357#[instrument(level = "debug", skip(wfcx))]
1359pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1360 let infcx = wfcx.infcx;
1361 let tcx = wfcx.tcx();
1362
1363 let predicates = tcx.predicates_of(def_id.to_def_id());
1364 let generics = tcx.generics_of(def_id);
1365
1366 for param in &generics.own_params {
1373 if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1374 if !default.has_param() {
1381 wfcx.register_wf_obligation(
1382 tcx.def_span(param.def_id),
1383 matches!(param.kind, GenericParamDefKind::Type { .. })
1384 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1385 default.as_term().unwrap(),
1386 );
1387 } else {
1388 let GenericArgKind::Const(ct) = default.kind() else {
1391 continue;
1392 };
1393
1394 let ct_ty = match ct.kind() {
1395 ty::ConstKind::Infer(_)
1396 | ty::ConstKind::Placeholder(_)
1397 | ty::ConstKind::Bound(_, _) => unreachable!(),
1398 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1399 ty::ConstKind::Value(cv) => cv.ty,
1400 ty::ConstKind::Unevaluated(uv) => {
1401 infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1402 }
1403 ty::ConstKind::Param(param_ct) => {
1404 param_ct.find_const_ty_from_env(wfcx.param_env)
1405 }
1406 };
1407
1408 let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1409 if !ct_ty.has_param() && !param_ty.has_param() {
1410 let cause = traits::ObligationCause::new(
1411 tcx.def_span(param.def_id),
1412 wfcx.body_def_id,
1413 ObligationCauseCode::WellFormed(None),
1414 );
1415 wfcx.register_obligation(Obligation::new(
1416 tcx,
1417 cause,
1418 wfcx.param_env,
1419 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1420 ));
1421 }
1422 }
1423 }
1424 }
1425
1426 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1435 if param.index >= generics.parent_count as u32
1436 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1438 && !default.has_param()
1440 {
1441 return default;
1443 }
1444 tcx.mk_param_from_def(param)
1445 });
1446
1447 let default_obligations = predicates
1449 .predicates
1450 .iter()
1451 .flat_map(|&(pred, sp)| {
1452 #[derive(Default)]
1453 struct CountParams {
1454 params: FxHashSet<u32>,
1455 }
1456 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1457 type Result = ControlFlow<()>;
1458 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1459 if let ty::Param(param) = t.kind() {
1460 self.params.insert(param.index);
1461 }
1462 t.super_visit_with(self)
1463 }
1464
1465 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1466 ControlFlow::Break(())
1467 }
1468
1469 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1470 if let ty::ConstKind::Param(param) = c.kind() {
1471 self.params.insert(param.index);
1472 }
1473 c.super_visit_with(self)
1474 }
1475 }
1476 let mut param_count = CountParams::default();
1477 let has_region = pred.visit_with(&mut param_count).is_break();
1478 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1479 if instantiated_pred.has_non_region_param()
1482 || param_count.params.len() > 1
1483 || has_region
1484 {
1485 None
1486 } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1487 None
1489 } else {
1490 Some((instantiated_pred, sp))
1491 }
1492 })
1493 .map(|(pred, sp)| {
1494 let pred = wfcx.normalize(sp, None, pred);
1504 let cause = traits::ObligationCause::new(
1505 sp,
1506 wfcx.body_def_id,
1507 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1508 );
1509 Obligation::new(tcx, cause, wfcx.param_env, pred)
1510 });
1511
1512 let predicates = predicates.instantiate_identity(tcx);
1513
1514 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1515 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1516 let p = wfcx.normalize(sp, None, p);
1517 traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1518 });
1519 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1520 wfcx.register_obligations(obligations);
1521}
1522
1523#[instrument(level = "debug", skip(wfcx, hir_decl))]
1524fn check_fn_or_method<'tcx>(
1525 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1526 sig: ty::PolyFnSig<'tcx>,
1527 hir_decl: &hir::FnDecl<'_>,
1528 def_id: LocalDefId,
1529) {
1530 let tcx = wfcx.tcx();
1531 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1532
1533 let arg_span =
1539 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1540
1541 sig.inputs_and_output =
1542 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1543 wfcx.deeply_normalize(
1544 arg_span(idx),
1545 Some(WellFormedLoc::Param {
1546 function: def_id,
1547 param_idx: idx,
1550 }),
1551 ty,
1552 )
1553 }));
1554
1555 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1556 wfcx.register_wf_obligation(
1557 arg_span(idx),
1558 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1559 ty.into(),
1560 );
1561 }
1562
1563 check_where_clauses(wfcx, def_id);
1564
1565 if sig.abi == ExternAbi::RustCall {
1566 let span = tcx.def_span(def_id);
1567 let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1568 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1569 if let Some(ty) = inputs.next() {
1571 wfcx.register_bound(
1572 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1573 wfcx.param_env,
1574 *ty,
1575 tcx.require_lang_item(hir::LangItem::Tuple, span),
1576 );
1577 wfcx.register_bound(
1578 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1579 wfcx.param_env,
1580 *ty,
1581 tcx.require_lang_item(hir::LangItem::Sized, span),
1582 );
1583 } else {
1584 tcx.dcx().span_err(
1585 hir_decl.inputs.last().map_or(span, |input| input.span),
1586 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1587 );
1588 }
1589 if inputs.next().is_some() {
1591 tcx.dcx().span_err(
1592 hir_decl.inputs.last().map_or(span, |input| input.span),
1593 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1594 );
1595 }
1596 }
1597
1598 check_sized_if_body(
1600 wfcx,
1601 def_id,
1602 sig.output(),
1603 match hir_decl.output {
1604 hir::FnRetTy::Return(ty) => Some(ty.span),
1605 hir::FnRetTy::DefaultReturn(_) => None,
1606 },
1607 ObligationCauseCode::SizedReturnType,
1608 );
1609}
1610
1611fn check_sized_if_body<'tcx>(
1612 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1613 def_id: LocalDefId,
1614 ty: Ty<'tcx>,
1615 maybe_span: Option<Span>,
1616 code: ObligationCauseCode<'tcx>,
1617) {
1618 let tcx = wfcx.tcx();
1619 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1620 let span = maybe_span.unwrap_or(body.value.span);
1621
1622 wfcx.register_bound(
1623 ObligationCause::new(span, def_id, code),
1624 wfcx.param_env,
1625 ty,
1626 tcx.require_lang_item(LangItem::Sized, span),
1627 );
1628 }
1629}
1630
1631#[derive(Clone, Copy, PartialEq)]
1633enum ArbitrarySelfTypesLevel {
1634 Basic, WithPointers, }
1637
1638#[instrument(level = "debug", skip(wfcx))]
1639fn check_method_receiver<'tcx>(
1640 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1641 fn_sig: &hir::FnSig<'_>,
1642 method: ty::AssocItem,
1643 self_ty: Ty<'tcx>,
1644) -> Result<(), ErrorGuaranteed> {
1645 let tcx = wfcx.tcx();
1646
1647 if !method.is_method() {
1648 return Ok(());
1649 }
1650
1651 let span = fn_sig.decl.inputs[0].span;
1652 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1653
1654 let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1655 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1656 let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1657
1658 debug!("check_method_receiver: sig={:?}", sig);
1659
1660 let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1661
1662 let receiver_ty = sig.inputs()[0];
1663 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1664
1665 if receiver_ty.references_error() {
1668 return Ok(());
1669 }
1670
1671 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1672 Some(ArbitrarySelfTypesLevel::WithPointers)
1673 } else if tcx.features().arbitrary_self_types() {
1674 Some(ArbitrarySelfTypesLevel::Basic)
1675 } else {
1676 None
1677 };
1678 let generics = tcx.generics_of(method.def_id);
1679
1680 let receiver_validity =
1681 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1682 if let Err(receiver_validity_err) = receiver_validity {
1683 return Err(match arbitrary_self_types_level {
1684 None if receiver_is_valid(
1688 wfcx,
1689 span,
1690 receiver_ty,
1691 self_ty,
1692 Some(ArbitrarySelfTypesLevel::Basic),
1693 generics,
1694 )
1695 .is_ok() =>
1696 {
1697 feature_err(
1699 &tcx.sess,
1700 sym::arbitrary_self_types,
1701 span,
1702 format!(
1703 "`{receiver_ty}` cannot be used as the type of `self` without \
1704 the `arbitrary_self_types` feature",
1705 ),
1706 )
1707 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1708 .emit()
1709 }
1710 None | Some(ArbitrarySelfTypesLevel::Basic)
1711 if receiver_is_valid(
1712 wfcx,
1713 span,
1714 receiver_ty,
1715 self_ty,
1716 Some(ArbitrarySelfTypesLevel::WithPointers),
1717 generics,
1718 )
1719 .is_ok() =>
1720 {
1721 feature_err(
1723 &tcx.sess,
1724 sym::arbitrary_self_types_pointers,
1725 span,
1726 format!(
1727 "`{receiver_ty}` cannot be used as the type of `self` without \
1728 the `arbitrary_self_types_pointers` feature",
1729 ),
1730 )
1731 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1732 .emit()
1733 }
1734 _ =>
1735 {
1737 match receiver_validity_err {
1738 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1739 let hint = match receiver_ty
1740 .builtin_deref(false)
1741 .unwrap_or(receiver_ty)
1742 .ty_adt_def()
1743 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1744 {
1745 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1746 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1747 _ => None,
1748 };
1749
1750 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1751 }
1752 ReceiverValidityError::DoesNotDeref => {
1753 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1754 span,
1755 receiver_ty,
1756 })
1757 }
1758 ReceiverValidityError::MethodGenericParamUsed => {
1759 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1760 }
1761 }
1762 }
1763 });
1764 }
1765 Ok(())
1766}
1767
1768enum ReceiverValidityError {
1772 DoesNotDeref,
1775 MethodGenericParamUsed,
1777}
1778
1779fn confirm_type_is_not_a_method_generic_param(
1782 ty: Ty<'_>,
1783 method_generics: &ty::Generics,
1784) -> Result<(), ReceiverValidityError> {
1785 if let ty::Param(param) = ty.kind() {
1786 if (param.index as usize) >= method_generics.parent_count {
1787 return Err(ReceiverValidityError::MethodGenericParamUsed);
1788 }
1789 }
1790 Ok(())
1791}
1792
1793fn receiver_is_valid<'tcx>(
1803 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1804 span: Span,
1805 receiver_ty: Ty<'tcx>,
1806 self_ty: Ty<'tcx>,
1807 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1808 method_generics: &ty::Generics,
1809) -> Result<(), ReceiverValidityError> {
1810 let infcx = wfcx.infcx;
1811 let tcx = wfcx.tcx();
1812 let cause =
1813 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1814
1815 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1817 let ocx = ObligationCtxt::new(wfcx.infcx);
1818 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1819 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1820 }) {
1821 return Ok(());
1822 }
1823
1824 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1825
1826 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1827
1828 if arbitrary_self_types_enabled.is_some() {
1832 autoderef = autoderef.use_receiver_trait();
1833 }
1834
1835 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1837 autoderef = autoderef.include_raw_pointers();
1838 }
1839
1840 while let Some((potential_self_ty, _)) = autoderef.next() {
1842 debug!(
1843 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1844 potential_self_ty, self_ty
1845 );
1846
1847 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1848
1849 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1852 let ocx = ObligationCtxt::new(wfcx.infcx);
1853 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1854 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1855 }) {
1856 wfcx.register_obligations(autoderef.into_obligations());
1857 return Ok(());
1858 }
1859
1860 if arbitrary_self_types_enabled.is_none() {
1863 let legacy_receiver_trait_def_id =
1864 tcx.require_lang_item(LangItem::LegacyReceiver, span);
1865 if !legacy_receiver_is_implemented(
1866 wfcx,
1867 legacy_receiver_trait_def_id,
1868 cause.clone(),
1869 potential_self_ty,
1870 ) {
1871 break;
1873 }
1874
1875 wfcx.register_bound(
1877 cause.clone(),
1878 wfcx.param_env,
1879 potential_self_ty,
1880 legacy_receiver_trait_def_id,
1881 );
1882 }
1883 }
1884
1885 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1886 Err(ReceiverValidityError::DoesNotDeref)
1887}
1888
1889fn legacy_receiver_is_implemented<'tcx>(
1890 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1891 legacy_receiver_trait_def_id: DefId,
1892 cause: ObligationCause<'tcx>,
1893 receiver_ty: Ty<'tcx>,
1894) -> bool {
1895 let tcx = wfcx.tcx();
1896 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1897
1898 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1899
1900 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1901 true
1902 } else {
1903 debug!(
1904 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1905 receiver_ty
1906 );
1907 false
1908 }
1909}
1910
1911pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1912 match tcx.def_kind(def_id) {
1913 DefKind::Enum | DefKind::Struct | DefKind::Union => {
1914 }
1916 DefKind::TyAlias => {
1917 assert!(
1918 tcx.type_alias_is_lazy(def_id),
1919 "should not be computing variance of non-free type alias"
1920 );
1921 }
1922 kind => span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
1923 }
1924
1925 let ty_predicates = tcx.predicates_of(def_id);
1926 assert_eq!(ty_predicates.parent, None);
1927 let variances = tcx.variances_of(def_id);
1928
1929 let mut constrained_parameters: FxHashSet<_> = variances
1930 .iter()
1931 .enumerate()
1932 .filter(|&(_, &variance)| variance != ty::Bivariant)
1933 .map(|(index, _)| Parameter(index as u32))
1934 .collect();
1935
1936 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1937
1938 let explicitly_bounded_params = LazyCell::new(|| {
1940 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
1941 tcx.hir_node_by_def_id(def_id)
1942 .generics()
1943 .unwrap()
1944 .predicates
1945 .iter()
1946 .filter_map(|predicate| match predicate.kind {
1947 hir::WherePredicateKind::BoundPredicate(predicate) => {
1948 match icx.lower_ty(predicate.bounded_ty).kind() {
1949 ty::Param(data) => Some(Parameter(data.index)),
1950 _ => None,
1951 }
1952 }
1953 _ => None,
1954 })
1955 .collect::<FxHashSet<_>>()
1956 });
1957
1958 for (index, _) in variances.iter().enumerate() {
1959 let parameter = Parameter(index as u32);
1960
1961 if constrained_parameters.contains(¶meter) {
1962 continue;
1963 }
1964
1965 let node = tcx.hir_node_by_def_id(def_id);
1966 let item = node.expect_item();
1967 let hir_generics = node.generics().unwrap();
1968 let hir_param = &hir_generics.params[index];
1969
1970 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
1971
1972 if ty_param.def_id != hir_param.def_id.into() {
1973 tcx.dcx().span_delayed_bug(
1981 hir_param.span,
1982 "hir generics and ty generics in different order",
1983 );
1984 continue;
1985 }
1986
1987 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
1989 .type_of(def_id)
1990 .instantiate_identity()
1991 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
1992 {
1993 continue;
1994 }
1995
1996 match hir_param.name {
1997 hir::ParamName::Error(_) => {
1998 }
2001 _ => {
2002 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2003 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2004 }
2005 }
2006 }
2007}
2008
2009struct HasErrorDeep<'tcx> {
2011 tcx: TyCtxt<'tcx>,
2012 seen: FxHashSet<DefId>,
2013}
2014impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2015 type Result = ControlFlow<ErrorGuaranteed>;
2016
2017 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2018 match *ty.kind() {
2019 ty::Adt(def, _) => {
2020 if self.seen.insert(def.did()) {
2021 for field in def.all_fields() {
2022 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2023 }
2024 }
2025 }
2026 ty::Error(guar) => return ControlFlow::Break(guar),
2027 _ => {}
2028 }
2029 ty.super_visit_with(self)
2030 }
2031
2032 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2033 if let Err(guar) = r.error_reported() {
2034 ControlFlow::Break(guar)
2035 } else {
2036 ControlFlow::Continue(())
2037 }
2038 }
2039
2040 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2041 if let Err(guar) = c.error_reported() {
2042 ControlFlow::Break(guar)
2043 } else {
2044 ControlFlow::Continue(())
2045 }
2046 }
2047}
2048
2049fn report_bivariance<'tcx>(
2050 tcx: TyCtxt<'tcx>,
2051 param: &'tcx hir::GenericParam<'tcx>,
2052 has_explicit_bounds: bool,
2053 item: &'tcx hir::Item<'tcx>,
2054) -> ErrorGuaranteed {
2055 let param_name = param.name.ident();
2056
2057 let help = match item.kind {
2058 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2059 if let Some(def_id) = tcx.lang_items().phantom_data() {
2060 errors::UnusedGenericParameterHelp::Adt {
2061 param_name,
2062 phantom_data: tcx.def_path_str(def_id),
2063 }
2064 } else {
2065 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2066 }
2067 }
2068 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2069 item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2070 };
2071
2072 let mut usage_spans = vec![];
2073 intravisit::walk_item(
2074 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2075 item,
2076 );
2077
2078 if !usage_spans.is_empty() {
2079 let item_def_id = item.owner_id.to_def_id();
2083 let is_probably_cyclical =
2084 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2085 .visit_def(item_def_id)
2086 .is_break();
2087 if is_probably_cyclical {
2096 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2097 spans: usage_spans,
2098 param_span: param.span,
2099 param_name,
2100 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2101 help,
2102 note: (),
2103 });
2104 }
2105 }
2106
2107 let const_param_help =
2108 matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2109
2110 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2111 span: param.span,
2112 param_name,
2113 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2114 usage_spans,
2115 help,
2116 const_param_help,
2117 });
2118 diag.code(E0392);
2119 diag.emit()
2120}
2121
2122struct IsProbablyCyclical<'tcx> {
2128 tcx: TyCtxt<'tcx>,
2129 item_def_id: DefId,
2130 seen: FxHashSet<DefId>,
2131}
2132
2133impl<'tcx> IsProbablyCyclical<'tcx> {
2134 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2135 match self.tcx.def_kind(def_id) {
2136 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2137 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2138 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2139 })
2140 }
2141 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2142 self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2143 }
2144 _ => ControlFlow::Continue(()),
2145 }
2146 }
2147}
2148
2149impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2150 type Result = ControlFlow<(), ()>;
2151
2152 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2153 let def_id = match ty.kind() {
2154 ty::Adt(adt_def, _) => Some(adt_def.did()),
2155 ty::Alias(ty::Free, alias_ty) => Some(alias_ty.def_id),
2156 _ => None,
2157 };
2158 if let Some(def_id) = def_id {
2159 if def_id == self.item_def_id {
2160 return ControlFlow::Break(());
2161 }
2162 if self.seen.insert(def_id) {
2163 self.visit_def(def_id)?;
2164 }
2165 }
2166 ty.super_visit_with(self)
2167 }
2168}
2169
2170struct CollectUsageSpans<'a> {
2175 spans: &'a mut Vec<Span>,
2176 param_def_id: DefId,
2177}
2178
2179impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2180 type Result = ();
2181
2182 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2183 }
2185
2186 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2187 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2188 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2189 && def_id == self.param_def_id
2190 {
2191 self.spans.push(t.span);
2192 return;
2193 } else if let Res::SelfTyAlias { .. } = qpath.res {
2194 self.spans.push(t.span);
2195 return;
2196 }
2197 }
2198 intravisit::walk_ty(self, t);
2199 }
2200}
2201
2202impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2203 #[instrument(level = "debug", skip(self))]
2206 fn check_false_global_bounds(&mut self) {
2207 let tcx = self.ocx.infcx.tcx;
2208 let mut span = tcx.def_span(self.body_def_id);
2209 let empty_env = ty::ParamEnv::empty();
2210
2211 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2212 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2214
2215 for (pred, obligation_span) in implied_obligations {
2216 match pred.kind().skip_binder() {
2217 ty::ClauseKind::WellFormed(..)
2221 | ty::ClauseKind::UnstableFeature(..) => continue,
2223 _ => {}
2224 }
2225
2226 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2228 let pred = self.normalize(span, None, pred);
2229
2230 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2232 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2233 span = predicates
2234 .iter()
2235 .find(|pred| pred.span.contains(obligation_span))
2237 .map(|pred| pred.span)
2238 .unwrap_or(obligation_span);
2239 }
2240
2241 let obligation = Obligation::new(
2242 tcx,
2243 traits::ObligationCause::new(
2244 span,
2245 self.body_def_id,
2246 ObligationCauseCode::TrivialBound,
2247 ),
2248 empty_env,
2249 pred,
2250 );
2251 self.ocx.register_obligation(obligation);
2252 }
2253 }
2254 }
2255}
2256
2257pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2258 let items = tcx.hir_crate_items(());
2259 let res = items
2260 .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2261 .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2262 .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2263 .and(
2264 items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2265 )
2266 .and(items.par_nested_bodies(|item| tcx.ensure_ok().check_well_formed(item)))
2267 .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2268 super::entry::check_for_entry_fn(tcx);
2269
2270 res
2271}
2272
2273fn lint_redundant_lifetimes<'tcx>(
2274 tcx: TyCtxt<'tcx>,
2275 owner_id: LocalDefId,
2276 outlives_env: &OutlivesEnvironment<'tcx>,
2277) {
2278 let def_kind = tcx.def_kind(owner_id);
2279 match def_kind {
2280 DefKind::Struct
2281 | DefKind::Union
2282 | DefKind::Enum
2283 | DefKind::Trait
2284 | DefKind::TraitAlias
2285 | DefKind::Fn
2286 | DefKind::Const
2287 | DefKind::Impl { of_trait: _ } => {
2288 }
2290 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2291 let parent_def_id = tcx.local_parent(owner_id);
2292 if matches!(tcx.def_kind(parent_def_id), DefKind::Impl { of_trait: true }) {
2293 return;
2298 }
2299 }
2300 DefKind::Mod
2301 | DefKind::Variant
2302 | DefKind::TyAlias
2303 | DefKind::ForeignTy
2304 | DefKind::TyParam
2305 | DefKind::ConstParam
2306 | DefKind::Static { .. }
2307 | DefKind::Ctor(_, _)
2308 | DefKind::Macro(_)
2309 | DefKind::ExternCrate
2310 | DefKind::Use
2311 | DefKind::ForeignMod
2312 | DefKind::AnonConst
2313 | DefKind::InlineConst
2314 | DefKind::OpaqueTy
2315 | DefKind::Field
2316 | DefKind::LifetimeParam
2317 | DefKind::GlobalAsm
2318 | DefKind::Closure
2319 | DefKind::SyntheticCoroutineBody => return,
2320 }
2321
2322 let mut lifetimes = vec![tcx.lifetimes.re_static];
2331 lifetimes.extend(
2332 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2333 );
2334 if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2336 for (idx, var) in
2337 tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2338 {
2339 let ty::BoundVariableKind::Region(kind) = var else { continue };
2340 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2341 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2342 }
2343 }
2344 lifetimes.retain(|candidate| candidate.is_named(tcx));
2345
2346 let mut shadowed = FxHashSet::default();
2350
2351 for (idx, &candidate) in lifetimes.iter().enumerate() {
2352 if shadowed.contains(&candidate) {
2357 continue;
2358 }
2359
2360 for &victim in &lifetimes[(idx + 1)..] {
2361 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2369 continue;
2370 };
2371
2372 if tcx.parent(def_id) != owner_id.to_def_id() {
2377 continue;
2378 }
2379
2380 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2382 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2383 {
2384 shadowed.insert(victim);
2385 tcx.emit_node_span_lint(
2386 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2387 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2388 tcx.def_span(def_id),
2389 RedundantLifetimeArgsLint { candidate, victim },
2390 );
2391 }
2392 }
2393 }
2394}
2395
2396#[derive(LintDiagnostic)]
2397#[diag(hir_analysis_redundant_lifetime_args)]
2398#[note]
2399struct RedundantLifetimeArgsLint<'tcx> {
2400 victim: ty::Region<'tcx>,
2402 candidate: ty::Region<'tcx>,
2404}