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::Const(_, _, ty, _) => check_const_item(tcx, def_id, ty.span),
294 hir::ItemKind::Struct(..) => check_type_defn(tcx, item, false),
295 hir::ItemKind::Union(..) => check_type_defn(tcx, item, true),
296 hir::ItemKind::Enum(..) => check_type_defn(tcx, item, true),
297 hir::ItemKind::Trait(..) => check_trait(tcx, item),
298 hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
299 _ => Ok(()),
300 }
301}
302
303pub(super) fn check_foreign_item<'tcx>(
304 tcx: TyCtxt<'tcx>,
305 item: &'tcx hir::ForeignItem<'tcx>,
306) -> Result<(), ErrorGuaranteed> {
307 let def_id = item.owner_id.def_id;
308
309 debug!(
310 ?item.owner_id,
311 item.name = ? tcx.def_path_str(def_id)
312 );
313
314 match item.kind {
315 hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
316 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
317 }
318}
319
320pub(crate) fn check_trait_item<'tcx>(
321 tcx: TyCtxt<'tcx>,
322 def_id: LocalDefId,
323) -> Result<(), ErrorGuaranteed> {
324 lint_item_shadowing_supertrait_item(tcx, def_id);
326
327 let mut res = Ok(());
328
329 if matches!(tcx.def_kind(def_id), DefKind::AssocFn) {
330 for &assoc_ty_def_id in tcx.associated_types_for_impl_traits_in_associated_fn(def_id) {
331 res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
332 }
333 }
334 res
335}
336
337fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
350 let mut required_bounds_by_item = FxIndexMap::default();
352 let associated_items = tcx.associated_items(trait_def_id);
353
354 loop {
360 let mut should_continue = false;
361 for gat_item in associated_items.in_definition_order() {
362 let gat_def_id = gat_item.def_id.expect_local();
363 let gat_item = tcx.associated_item(gat_def_id);
364 if !gat_item.is_type() {
366 continue;
367 }
368 let gat_generics = tcx.generics_of(gat_def_id);
369 if gat_generics.is_own_empty() {
371 continue;
372 }
373
374 let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
378 for item in associated_items.in_definition_order() {
379 let item_def_id = item.def_id.expect_local();
380 if item_def_id == gat_def_id {
382 continue;
383 }
384
385 let param_env = tcx.param_env(item_def_id);
386
387 let item_required_bounds = match tcx.associated_item(item_def_id).kind {
388 ty::AssocKind::Fn { .. } => {
390 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
394 item_def_id.to_def_id(),
395 tcx.fn_sig(item_def_id).instantiate_identity(),
396 );
397 gather_gat_bounds(
398 tcx,
399 param_env,
400 item_def_id,
401 sig.inputs_and_output,
402 &sig.inputs().iter().copied().collect(),
405 gat_def_id,
406 gat_generics,
407 )
408 }
409 ty::AssocKind::Type { .. } => {
411 let param_env = augment_param_env(
415 tcx,
416 param_env,
417 required_bounds_by_item.get(&item_def_id),
418 );
419 gather_gat_bounds(
420 tcx,
421 param_env,
422 item_def_id,
423 tcx.explicit_item_bounds(item_def_id)
424 .iter_identity_copied()
425 .collect::<Vec<_>>(),
426 &FxIndexSet::default(),
427 gat_def_id,
428 gat_generics,
429 )
430 }
431 ty::AssocKind::Const { .. } => None,
432 };
433
434 if let Some(item_required_bounds) = item_required_bounds {
435 if let Some(new_required_bounds) = &mut new_required_bounds {
441 new_required_bounds.retain(|b| item_required_bounds.contains(b));
442 } else {
443 new_required_bounds = Some(item_required_bounds);
444 }
445 }
446 }
447
448 if let Some(new_required_bounds) = new_required_bounds {
449 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
450 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
451 should_continue = true;
454 }
455 }
456 }
457 if !should_continue {
462 break;
463 }
464 }
465
466 for (gat_def_id, required_bounds) in required_bounds_by_item {
467 if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
469 continue;
470 }
471
472 let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
473 debug!(?required_bounds);
474 let param_env = tcx.param_env(gat_def_id);
475
476 let unsatisfied_bounds: Vec<_> = required_bounds
477 .into_iter()
478 .filter(|clause| match clause.kind().skip_binder() {
479 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
480 !region_known_to_outlive(
481 tcx,
482 gat_def_id,
483 param_env,
484 &FxIndexSet::default(),
485 a,
486 b,
487 )
488 }
489 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
490 !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
491 }
492 _ => bug!("Unexpected ClauseKind"),
493 })
494 .map(|clause| clause.to_string())
495 .collect();
496
497 if !unsatisfied_bounds.is_empty() {
498 let plural = pluralize!(unsatisfied_bounds.len());
499 let suggestion = format!(
500 "{} {}",
501 gat_item_hir.generics.add_where_or_trailing_comma(),
502 unsatisfied_bounds.join(", "),
503 );
504 let bound =
505 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
506 tcx.dcx()
507 .struct_span_err(
508 gat_item_hir.span,
509 format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
510 )
511 .with_span_suggestion(
512 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
513 format!("add the required where clause{plural}"),
514 suggestion,
515 Applicability::MachineApplicable,
516 )
517 .with_note(format!(
518 "{bound} currently required to ensure that impls have maximum flexibility"
519 ))
520 .with_note(
521 "we are soliciting feedback, see issue #87479 \
522 <https://github.com/rust-lang/rust/issues/87479> for more information",
523 )
524 .emit();
525 }
526 }
527}
528
529fn augment_param_env<'tcx>(
531 tcx: TyCtxt<'tcx>,
532 param_env: ty::ParamEnv<'tcx>,
533 new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
534) -> ty::ParamEnv<'tcx> {
535 let Some(new_predicates) = new_predicates else {
536 return param_env;
537 };
538
539 if new_predicates.is_empty() {
540 return param_env;
541 }
542
543 let bounds = tcx.mk_clauses_from_iter(
544 param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
545 );
546 ty::ParamEnv::new(bounds)
549}
550
551fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
562 tcx: TyCtxt<'tcx>,
563 param_env: ty::ParamEnv<'tcx>,
564 item_def_id: LocalDefId,
565 to_check: T,
566 wf_tys: &FxIndexSet<Ty<'tcx>>,
567 gat_def_id: LocalDefId,
568 gat_generics: &'tcx ty::Generics,
569) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
570 let mut bounds = FxIndexSet::default();
572
573 let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
574
575 if types.is_empty() && regions.is_empty() {
581 return None;
582 }
583
584 for (region_a, region_a_idx) in ®ions {
585 if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
589 continue;
590 }
591 for (ty, ty_idx) in &types {
596 if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
598 debug!(?ty_idx, ?region_a_idx);
599 debug!("required clause: {ty} must outlive {region_a}");
600 let ty_param = gat_generics.param_at(*ty_idx, tcx);
604 let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
605 let region_param = gat_generics.param_at(*region_a_idx, tcx);
608 let region_param = ty::Region::new_early_param(
609 tcx,
610 ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
611 );
612 bounds.insert(
615 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
616 .upcast(tcx),
617 );
618 }
619 }
620
621 for (region_b, region_b_idx) in ®ions {
626 if matches!(region_b.kind(), ty::ReStatic | ty::ReError(_)) || region_a == region_b {
630 continue;
631 }
632 if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
633 debug!(?region_a_idx, ?region_b_idx);
634 debug!("required clause: {region_a} must outlive {region_b}");
635 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
637 let region_a_param = ty::Region::new_early_param(
638 tcx,
639 ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
640 );
641 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
643 let region_b_param = ty::Region::new_early_param(
644 tcx,
645 ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
646 );
647 bounds.insert(
649 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
650 region_a_param,
651 region_b_param,
652 ))
653 .upcast(tcx),
654 );
655 }
656 }
657 }
658
659 Some(bounds)
660}
661
662fn ty_known_to_outlive<'tcx>(
665 tcx: TyCtxt<'tcx>,
666 id: LocalDefId,
667 param_env: ty::ParamEnv<'tcx>,
668 wf_tys: &FxIndexSet<Ty<'tcx>>,
669 ty: Ty<'tcx>,
670 region: ty::Region<'tcx>,
671) -> bool {
672 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
673 infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
674 sub_region: region,
675 sup_type: ty,
676 origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
677 });
678 })
679}
680
681fn region_known_to_outlive<'tcx>(
684 tcx: TyCtxt<'tcx>,
685 id: LocalDefId,
686 param_env: ty::ParamEnv<'tcx>,
687 wf_tys: &FxIndexSet<Ty<'tcx>>,
688 region_a: ty::Region<'tcx>,
689 region_b: ty::Region<'tcx>,
690) -> bool {
691 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
692 infcx.sub_regions(
693 SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
694 region_b,
695 region_a,
696 );
697 })
698}
699
700fn test_region_obligations<'tcx>(
704 tcx: TyCtxt<'tcx>,
705 id: LocalDefId,
706 param_env: ty::ParamEnv<'tcx>,
707 wf_tys: &FxIndexSet<Ty<'tcx>>,
708 add_constraints: impl FnOnce(&InferCtxt<'tcx>),
709) -> bool {
710 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
714
715 add_constraints(&infcx);
716
717 let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
718 debug!(?errors, "errors");
719
720 errors.is_empty()
723}
724
725struct GATArgsCollector<'tcx> {
730 gat: DefId,
731 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
733 types: FxIndexSet<(Ty<'tcx>, usize)>,
735}
736
737impl<'tcx> GATArgsCollector<'tcx> {
738 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
739 gat: DefId,
740 t: T,
741 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
742 let mut visitor =
743 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
744 t.visit_with(&mut visitor);
745 (visitor.regions, visitor.types)
746 }
747}
748
749impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
750 fn visit_ty(&mut self, t: Ty<'tcx>) {
751 match t.kind() {
752 ty::Alias(ty::Projection, p) if p.def_id == self.gat => {
753 for (idx, arg) in p.args.iter().enumerate() {
754 match arg.kind() {
755 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
756 self.regions.insert((lt, idx));
757 }
758 GenericArgKind::Type(t) => {
759 self.types.insert((t, idx));
760 }
761 _ => {}
762 }
763 }
764 }
765 _ => {}
766 }
767 t.super_visit_with(self)
768 }
769}
770
771fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
772 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
773 let trait_def_id = tcx.local_parent(trait_item_def_id);
774
775 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
776 .skip(1)
777 .flat_map(|supertrait_def_id| {
778 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
779 })
780 .collect();
781 if !shadowed.is_empty() {
782 let shadowee = if let [shadowed] = shadowed[..] {
783 errors::SupertraitItemShadowee::Labeled {
784 span: tcx.def_span(shadowed.def_id),
785 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
786 }
787 } else {
788 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
789 .iter()
790 .map(|item| {
791 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
792 })
793 .unzip();
794 errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
795 };
796
797 tcx.emit_node_span_lint(
798 SUPERTRAIT_ITEM_SHADOWING_DEFINITION,
799 tcx.local_def_id_to_hir_id(trait_item_def_id),
800 tcx.def_span(trait_item_def_id),
801 errors::SupertraitItemShadowing {
802 item: item_name,
803 subtrait: tcx.item_name(trait_def_id.to_def_id()),
804 shadowee,
805 },
806 );
807 }
808}
809
810fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
811 match param.kind {
812 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
814
815 ty::GenericParamDefKind::Const { .. } => {
817 let ty = tcx.type_of(param.def_id).instantiate_identity();
818 let span = tcx.def_span(param.def_id);
819 let def_id = param.def_id.expect_local();
820
821 if tcx.features().unsized_const_params() {
822 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
823 wfcx.register_bound(
824 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
825 wfcx.param_env,
826 ty,
827 tcx.require_lang_item(LangItem::UnsizedConstParamTy, span),
828 );
829 Ok(())
830 })
831 } else if tcx.features().adt_const_params() {
832 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
833 wfcx.register_bound(
834 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
835 wfcx.param_env,
836 ty,
837 tcx.require_lang_item(LangItem::ConstParamTy, span),
838 );
839 Ok(())
840 })
841 } else {
842 let span = || {
843 let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
844 tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
845 else {
846 bug!()
847 };
848 span
849 };
850 let mut diag = match ty.kind() {
851 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
852 ty::FnPtr(..) => tcx.dcx().struct_span_err(
853 span(),
854 "using function pointers as const generic parameters is forbidden",
855 ),
856 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
857 span(),
858 "using raw pointers as const generic parameters is forbidden",
859 ),
860 _ => {
861 ty.error_reported()?;
863
864 tcx.dcx().struct_span_err(
865 span(),
866 format!(
867 "`{ty}` is forbidden as the type of a const generic parameter",
868 ),
869 )
870 }
871 };
872
873 diag.note("the only supported types are integers, `bool`, and `char`");
874
875 let cause = ObligationCause::misc(span(), def_id);
876 let adt_const_params_feature_string =
877 " more complex and user defined types".to_string();
878 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
879 tcx,
880 tcx.param_env(param.def_id),
881 ty,
882 LangItem::ConstParamTy,
883 cause,
884 ) {
885 Err(
887 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
888 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
889 ) => None,
890 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
891 Some(vec![
892 (adt_const_params_feature_string, sym::adt_const_params),
893 (
894 " references to implement the `ConstParamTy` trait".into(),
895 sym::unsized_const_params,
896 ),
897 ])
898 }
899 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
902 fn ty_is_local(ty: Ty<'_>) -> bool {
903 match ty.kind() {
904 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
905 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
907 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
910 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
913 _ => false,
914 }
915 }
916
917 ty_is_local(ty).then_some(vec![(
918 adt_const_params_feature_string,
919 sym::adt_const_params,
920 )])
921 }
922 Ok(..) => Some(vec![(adt_const_params_feature_string, sym::adt_const_params)]),
924 };
925 if let Some(features) = may_suggest_feature {
926 tcx.disabled_nightly_features(&mut diag, features);
927 }
928
929 Err(diag.emit())
930 }
931 }
932 }
933}
934
935#[instrument(level = "debug", skip(tcx))]
936pub(crate) fn check_associated_item(
937 tcx: TyCtxt<'_>,
938 item_id: LocalDefId,
939) -> Result<(), ErrorGuaranteed> {
940 let loc = Some(WellFormedLoc::Ty(item_id));
941 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
942 let item = tcx.associated_item(item_id);
943
944 tcx.ensure_ok()
947 .coherent_trait(tcx.parent(item.trait_item_def_id.unwrap_or(item_id.into())))?;
948
949 let self_ty = match item.container {
950 ty::AssocItemContainer::Trait => tcx.types.self_param,
951 ty::AssocItemContainer::Impl => {
952 tcx.type_of(item.container_id(tcx)).instantiate_identity()
953 }
954 };
955
956 let span = tcx.def_span(item_id);
957
958 match item.kind {
959 ty::AssocKind::Const { .. } => {
960 let ty = tcx.type_of(item.def_id).instantiate_identity();
961 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
962 wfcx.register_wf_obligation(span, loc, ty.into());
963 check_sized_if_body(
964 wfcx,
965 item.def_id.expect_local(),
966 ty,
967 Some(span),
968 ObligationCauseCode::SizedConstOrStatic,
969 );
970 Ok(())
971 }
972 ty::AssocKind::Fn { .. } => {
973 let sig = tcx.fn_sig(item.def_id).instantiate_identity();
974 let hir_sig =
975 tcx.hir_node_by_def_id(item_id).fn_sig().expect("bad signature for method");
976 check_fn_or_method(wfcx, sig, hir_sig.decl, item_id);
977 check_method_receiver(wfcx, hir_sig, item, self_ty)
978 }
979 ty::AssocKind::Type { .. } => {
980 if let ty::AssocItemContainer::Trait = item.container {
981 check_associated_type_bounds(wfcx, item, span)
982 }
983 if item.defaultness(tcx).has_value() {
984 let ty = tcx.type_of(item.def_id).instantiate_identity();
985 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
986 wfcx.register_wf_obligation(span, loc, ty.into());
987 }
988 Ok(())
989 }
990 }
991 })
992}
993
994fn check_type_defn<'tcx>(
996 tcx: TyCtxt<'tcx>,
997 item: &hir::Item<'tcx>,
998 all_sized: bool,
999) -> Result<(), ErrorGuaranteed> {
1000 let _ = tcx.representability(item.owner_id.def_id);
1001 let adt_def = tcx.adt_def(item.owner_id);
1002
1003 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1004 let variants = adt_def.variants();
1005 let packed = adt_def.repr().packed();
1006
1007 for variant in variants.iter() {
1008 for field in &variant.fields {
1010 if let Some(def_id) = field.value
1011 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1012 {
1013 if let Some(def_id) = def_id.as_local()
1016 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1017 && let expr = &tcx.hir_body(anon.body).value
1018 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1019 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1020 {
1021 } else {
1024 let _ = tcx.const_eval_poly(def_id);
1027 }
1028 }
1029 let field_id = field.did.expect_local();
1030 let hir::FieldDef { ty: hir_ty, .. } =
1031 tcx.hir_node_by_def_id(field_id).expect_field();
1032 let ty = wfcx.deeply_normalize(
1033 hir_ty.span,
1034 None,
1035 tcx.type_of(field.did).instantiate_identity(),
1036 );
1037 wfcx.register_wf_obligation(
1038 hir_ty.span,
1039 Some(WellFormedLoc::Ty(field_id)),
1040 ty.into(),
1041 )
1042 }
1043
1044 let needs_drop_copy = || {
1047 packed && {
1048 let ty = tcx.type_of(variant.tail().did).instantiate_identity();
1049 let ty = tcx.erase_regions(ty);
1050 assert!(!ty.has_infer());
1051 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1052 }
1053 };
1054 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1056 let unsized_len = if all_sized { 0 } else { 1 };
1057 for (idx, field) in
1058 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1059 {
1060 let last = idx == variant.fields.len() - 1;
1061 let field_id = field.did.expect_local();
1062 let hir::FieldDef { ty: hir_ty, .. } =
1063 tcx.hir_node_by_def_id(field_id).expect_field();
1064 let ty = wfcx.normalize(
1065 hir_ty.span,
1066 None,
1067 tcx.type_of(field.did).instantiate_identity(),
1068 );
1069 wfcx.register_bound(
1070 traits::ObligationCause::new(
1071 hir_ty.span,
1072 wfcx.body_def_id,
1073 ObligationCauseCode::FieldSized {
1074 adt_kind: match &item.kind {
1075 ItemKind::Struct(..) => AdtKind::Struct,
1076 ItemKind::Union(..) => AdtKind::Union,
1077 ItemKind::Enum(..) => AdtKind::Enum,
1078 kind => span_bug!(
1079 item.span,
1080 "should be wfchecking an ADT, got {kind:?}"
1081 ),
1082 },
1083 span: hir_ty.span,
1084 last,
1085 },
1086 ),
1087 wfcx.param_env,
1088 ty,
1089 tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1090 );
1091 }
1092
1093 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1095 match tcx.const_eval_poly(discr_def_id) {
1096 Ok(_) => {}
1097 Err(ErrorHandled::Reported(..)) => {}
1098 Err(ErrorHandled::TooGeneric(sp)) => {
1099 span_bug!(sp, "enum variant discr was too generic to eval")
1100 }
1101 }
1102 }
1103 }
1104
1105 check_where_clauses(wfcx, item.owner_id.def_id);
1106 Ok(())
1107 })
1108}
1109
1110#[instrument(skip(tcx, item))]
1111fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1112 debug!(?item.owner_id);
1113
1114 let def_id = item.owner_id.def_id;
1115 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1116 return Ok(());
1118 }
1119
1120 let trait_def = tcx.trait_def(def_id);
1121 if trait_def.is_marker
1122 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1123 {
1124 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1125 struct_span_code_err!(
1126 tcx.dcx(),
1127 tcx.def_span(*associated_def_id),
1128 E0714,
1129 "marker traits cannot have associated items",
1130 )
1131 .emit();
1132 }
1133 }
1134
1135 let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1136 check_where_clauses(wfcx, def_id);
1137 Ok(())
1138 });
1139
1140 if let hir::ItemKind::Trait(..) = item.kind {
1142 check_gat_where_clauses(tcx, item.owner_id.def_id);
1143 }
1144 res
1145}
1146
1147fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, span: Span) {
1152 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1153
1154 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1155 let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
1156 let normalized_bound = wfcx.normalize(span, None, bound);
1157 traits::wf::clause_obligations(
1158 wfcx.infcx,
1159 wfcx.param_env,
1160 wfcx.body_def_id,
1161 normalized_bound,
1162 bound_span,
1163 )
1164 });
1165
1166 wfcx.register_obligations(wf_obligations);
1167}
1168
1169fn check_item_fn(
1170 tcx: TyCtxt<'_>,
1171 def_id: LocalDefId,
1172 decl: &hir::FnDecl<'_>,
1173) -> Result<(), ErrorGuaranteed> {
1174 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1175 let sig = tcx.fn_sig(def_id).instantiate_identity();
1176 check_fn_or_method(wfcx, sig, decl, def_id);
1177 Ok(())
1178 })
1179}
1180
1181#[instrument(level = "debug", skip(tcx))]
1182pub(super) fn check_static_item(
1183 tcx: TyCtxt<'_>,
1184 item_id: LocalDefId,
1185) -> Result<(), ErrorGuaranteed> {
1186 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1187 let ty = tcx.type_of(item_id).instantiate_identity();
1188 let item_ty = wfcx.deeply_normalize(DUMMY_SP, Some(WellFormedLoc::Ty(item_id)), ty);
1189
1190 let is_foreign_item = tcx.is_foreign_item(item_id);
1191
1192 let forbid_unsized = !is_foreign_item || {
1193 let tail = tcx.struct_tail_for_codegen(item_ty, wfcx.infcx.typing_env(wfcx.param_env));
1194 !matches!(tail.kind(), ty::Foreign(_))
1195 };
1196
1197 wfcx.register_wf_obligation(DUMMY_SP, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1198 if forbid_unsized {
1199 let span = tcx.def_span(item_id);
1200 wfcx.register_bound(
1201 traits::ObligationCause::new(
1202 span,
1203 wfcx.body_def_id,
1204 ObligationCauseCode::SizedConstOrStatic,
1205 ),
1206 wfcx.param_env,
1207 item_ty,
1208 tcx.require_lang_item(LangItem::Sized, span),
1209 );
1210 }
1211
1212 let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1214 == Some(hir::Mutability::Not)
1215 && !is_foreign_item
1216 && !tcx.is_thread_local_static(item_id.to_def_id());
1217
1218 if should_check_for_sync {
1219 let span = tcx.def_span(item_id);
1220 wfcx.register_bound(
1221 traits::ObligationCause::new(
1222 span,
1223 wfcx.body_def_id,
1224 ObligationCauseCode::SharedStatic,
1225 ),
1226 wfcx.param_env,
1227 item_ty,
1228 tcx.require_lang_item(LangItem::Sync, span),
1229 );
1230 }
1231 Ok(())
1232 })
1233}
1234
1235fn check_const_item(
1236 tcx: TyCtxt<'_>,
1237 def_id: LocalDefId,
1238 ty_span: Span,
1239) -> Result<(), ErrorGuaranteed> {
1240 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1241 let ty = tcx.type_of(def_id).instantiate_identity();
1242 let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
1243
1244 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
1245 wfcx.register_bound(
1246 traits::ObligationCause::new(
1247 ty_span,
1248 wfcx.body_def_id,
1249 ObligationCauseCode::SizedConstOrStatic,
1250 ),
1251 wfcx.param_env,
1252 ty,
1253 tcx.require_lang_item(LangItem::Sized, ty_span),
1254 );
1255
1256 check_where_clauses(wfcx, def_id);
1257
1258 Ok(())
1259 })
1260}
1261
1262#[instrument(level = "debug", skip(tcx, hir_self_ty, hir_trait_ref))]
1263fn check_impl<'tcx>(
1264 tcx: TyCtxt<'tcx>,
1265 item: &'tcx hir::Item<'tcx>,
1266 hir_self_ty: &hir::Ty<'_>,
1267 hir_trait_ref: &Option<hir::TraitRef<'_>>,
1268) -> Result<(), ErrorGuaranteed> {
1269 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1270 match hir_trait_ref {
1271 Some(hir_trait_ref) => {
1272 let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().instantiate_identity();
1276 tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1279 let trait_span = hir_trait_ref.path.span;
1280 let trait_ref = wfcx.deeply_normalize(
1281 trait_span,
1282 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1283 trait_ref,
1284 );
1285 let trait_pred =
1286 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1287 let mut obligations = traits::wf::trait_obligations(
1288 wfcx.infcx,
1289 wfcx.param_env,
1290 wfcx.body_def_id,
1291 trait_pred,
1292 trait_span,
1293 item,
1294 );
1295 for obligation in &mut obligations {
1296 if obligation.cause.span != trait_span {
1297 continue;
1299 }
1300 if let Some(pred) = obligation.predicate.as_trait_clause()
1301 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1302 {
1303 obligation.cause.span = hir_self_ty.span;
1304 }
1305 if let Some(pred) = obligation.predicate.as_projection_clause()
1306 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1307 {
1308 obligation.cause.span = hir_self_ty.span;
1309 }
1310 }
1311
1312 if tcx.is_conditionally_const(item.owner_id.def_id) {
1314 for (bound, _) in
1315 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1316 {
1317 let bound = wfcx.normalize(
1318 item.span,
1319 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1320 bound,
1321 );
1322 wfcx.register_obligation(Obligation::new(
1323 tcx,
1324 ObligationCause::new(
1325 hir_self_ty.span,
1326 wfcx.body_def_id,
1327 ObligationCauseCode::WellFormed(None),
1328 ),
1329 wfcx.param_env,
1330 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1331 ))
1332 }
1333 }
1334
1335 debug!(?obligations);
1336 wfcx.register_obligations(obligations);
1337 }
1338 None => {
1339 let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1340 let self_ty = wfcx.deeply_normalize(
1341 item.span,
1342 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1343 self_ty,
1344 );
1345 wfcx.register_wf_obligation(
1346 hir_self_ty.span,
1347 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1348 self_ty.into(),
1349 );
1350 }
1351 }
1352
1353 check_where_clauses(wfcx, item.owner_id.def_id);
1354 Ok(())
1355 })
1356}
1357
1358#[instrument(level = "debug", skip(wfcx))]
1360pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1361 let infcx = wfcx.infcx;
1362 let tcx = wfcx.tcx();
1363
1364 let predicates = tcx.predicates_of(def_id.to_def_id());
1365 let generics = tcx.generics_of(def_id);
1366
1367 for param in &generics.own_params {
1374 if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1375 if !default.has_param() {
1382 wfcx.register_wf_obligation(
1383 tcx.def_span(param.def_id),
1384 matches!(param.kind, GenericParamDefKind::Type { .. })
1385 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1386 default.as_term().unwrap(),
1387 );
1388 } else {
1389 let GenericArgKind::Const(ct) = default.kind() else {
1392 continue;
1393 };
1394
1395 let ct_ty = match ct.kind() {
1396 ty::ConstKind::Infer(_)
1397 | ty::ConstKind::Placeholder(_)
1398 | ty::ConstKind::Bound(_, _) => unreachable!(),
1399 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1400 ty::ConstKind::Value(cv) => cv.ty,
1401 ty::ConstKind::Unevaluated(uv) => {
1402 infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1403 }
1404 ty::ConstKind::Param(param_ct) => {
1405 param_ct.find_const_ty_from_env(wfcx.param_env)
1406 }
1407 };
1408
1409 let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1410 if !ct_ty.has_param() && !param_ty.has_param() {
1411 let cause = traits::ObligationCause::new(
1412 tcx.def_span(param.def_id),
1413 wfcx.body_def_id,
1414 ObligationCauseCode::WellFormed(None),
1415 );
1416 wfcx.register_obligation(Obligation::new(
1417 tcx,
1418 cause,
1419 wfcx.param_env,
1420 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1421 ));
1422 }
1423 }
1424 }
1425 }
1426
1427 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1436 if param.index >= generics.parent_count as u32
1437 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1439 && !default.has_param()
1441 {
1442 return default;
1444 }
1445 tcx.mk_param_from_def(param)
1446 });
1447
1448 let default_obligations = predicates
1450 .predicates
1451 .iter()
1452 .flat_map(|&(pred, sp)| {
1453 #[derive(Default)]
1454 struct CountParams {
1455 params: FxHashSet<u32>,
1456 }
1457 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1458 type Result = ControlFlow<()>;
1459 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1460 if let ty::Param(param) = t.kind() {
1461 self.params.insert(param.index);
1462 }
1463 t.super_visit_with(self)
1464 }
1465
1466 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1467 ControlFlow::Break(())
1468 }
1469
1470 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1471 if let ty::ConstKind::Param(param) = c.kind() {
1472 self.params.insert(param.index);
1473 }
1474 c.super_visit_with(self)
1475 }
1476 }
1477 let mut param_count = CountParams::default();
1478 let has_region = pred.visit_with(&mut param_count).is_break();
1479 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1480 if instantiated_pred.has_non_region_param()
1483 || param_count.params.len() > 1
1484 || has_region
1485 {
1486 None
1487 } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1488 None
1490 } else {
1491 Some((instantiated_pred, sp))
1492 }
1493 })
1494 .map(|(pred, sp)| {
1495 let pred = wfcx.normalize(sp, None, pred);
1505 let cause = traits::ObligationCause::new(
1506 sp,
1507 wfcx.body_def_id,
1508 ObligationCauseCode::WhereClause(def_id.to_def_id(), DUMMY_SP),
1509 );
1510 Obligation::new(tcx, cause, wfcx.param_env, pred)
1511 });
1512
1513 let predicates = predicates.instantiate_identity(tcx);
1514
1515 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1516 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1517 let p = wfcx.normalize(sp, None, p);
1518 traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1519 });
1520 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1521 wfcx.register_obligations(obligations);
1522}
1523
1524#[instrument(level = "debug", skip(wfcx, hir_decl))]
1525fn check_fn_or_method<'tcx>(
1526 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1527 sig: ty::PolyFnSig<'tcx>,
1528 hir_decl: &hir::FnDecl<'_>,
1529 def_id: LocalDefId,
1530) {
1531 let tcx = wfcx.tcx();
1532 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1533
1534 let arg_span =
1540 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1541
1542 sig.inputs_and_output =
1543 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1544 wfcx.deeply_normalize(
1545 arg_span(idx),
1546 Some(WellFormedLoc::Param {
1547 function: def_id,
1548 param_idx: idx,
1551 }),
1552 ty,
1553 )
1554 }));
1555
1556 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1557 wfcx.register_wf_obligation(
1558 arg_span(idx),
1559 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1560 ty.into(),
1561 );
1562 }
1563
1564 check_where_clauses(wfcx, def_id);
1565
1566 if sig.abi == ExternAbi::RustCall {
1567 let span = tcx.def_span(def_id);
1568 let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1569 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1570 if let Some(ty) = inputs.next() {
1572 wfcx.register_bound(
1573 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1574 wfcx.param_env,
1575 *ty,
1576 tcx.require_lang_item(hir::LangItem::Tuple, span),
1577 );
1578 wfcx.register_bound(
1579 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1580 wfcx.param_env,
1581 *ty,
1582 tcx.require_lang_item(hir::LangItem::Sized, span),
1583 );
1584 } else {
1585 tcx.dcx().span_err(
1586 hir_decl.inputs.last().map_or(span, |input| input.span),
1587 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1588 );
1589 }
1590 if inputs.next().is_some() {
1592 tcx.dcx().span_err(
1593 hir_decl.inputs.last().map_or(span, |input| input.span),
1594 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1595 );
1596 }
1597 }
1598
1599 check_sized_if_body(
1601 wfcx,
1602 def_id,
1603 sig.output(),
1604 match hir_decl.output {
1605 hir::FnRetTy::Return(ty) => Some(ty.span),
1606 hir::FnRetTy::DefaultReturn(_) => None,
1607 },
1608 ObligationCauseCode::SizedReturnType,
1609 );
1610}
1611
1612fn check_sized_if_body<'tcx>(
1613 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1614 def_id: LocalDefId,
1615 ty: Ty<'tcx>,
1616 maybe_span: Option<Span>,
1617 code: ObligationCauseCode<'tcx>,
1618) {
1619 let tcx = wfcx.tcx();
1620 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1621 let span = maybe_span.unwrap_or(body.value.span);
1622
1623 wfcx.register_bound(
1624 ObligationCause::new(span, def_id, code),
1625 wfcx.param_env,
1626 ty,
1627 tcx.require_lang_item(LangItem::Sized, span),
1628 );
1629 }
1630}
1631
1632#[derive(Clone, Copy, PartialEq)]
1634enum ArbitrarySelfTypesLevel {
1635 Basic, WithPointers, }
1638
1639#[instrument(level = "debug", skip(wfcx))]
1640fn check_method_receiver<'tcx>(
1641 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1642 fn_sig: &hir::FnSig<'_>,
1643 method: ty::AssocItem,
1644 self_ty: Ty<'tcx>,
1645) -> Result<(), ErrorGuaranteed> {
1646 let tcx = wfcx.tcx();
1647
1648 if !method.is_method() {
1649 return Ok(());
1650 }
1651
1652 let span = fn_sig.decl.inputs[0].span;
1653 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1654
1655 let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1656 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1657 let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1658
1659 debug!("check_method_receiver: sig={:?}", sig);
1660
1661 let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1662
1663 let receiver_ty = sig.inputs()[0];
1664 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1665
1666 if receiver_ty.references_error() {
1669 return Ok(());
1670 }
1671
1672 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1673 Some(ArbitrarySelfTypesLevel::WithPointers)
1674 } else if tcx.features().arbitrary_self_types() {
1675 Some(ArbitrarySelfTypesLevel::Basic)
1676 } else {
1677 None
1678 };
1679 let generics = tcx.generics_of(method.def_id);
1680
1681 let receiver_validity =
1682 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1683 if let Err(receiver_validity_err) = receiver_validity {
1684 return Err(match arbitrary_self_types_level {
1685 None if receiver_is_valid(
1689 wfcx,
1690 span,
1691 receiver_ty,
1692 self_ty,
1693 Some(ArbitrarySelfTypesLevel::Basic),
1694 generics,
1695 )
1696 .is_ok() =>
1697 {
1698 feature_err(
1700 &tcx.sess,
1701 sym::arbitrary_self_types,
1702 span,
1703 format!(
1704 "`{receiver_ty}` cannot be used as the type of `self` without \
1705 the `arbitrary_self_types` feature",
1706 ),
1707 )
1708 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1709 .emit()
1710 }
1711 None | Some(ArbitrarySelfTypesLevel::Basic)
1712 if receiver_is_valid(
1713 wfcx,
1714 span,
1715 receiver_ty,
1716 self_ty,
1717 Some(ArbitrarySelfTypesLevel::WithPointers),
1718 generics,
1719 )
1720 .is_ok() =>
1721 {
1722 feature_err(
1724 &tcx.sess,
1725 sym::arbitrary_self_types_pointers,
1726 span,
1727 format!(
1728 "`{receiver_ty}` cannot be used as the type of `self` without \
1729 the `arbitrary_self_types_pointers` feature",
1730 ),
1731 )
1732 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1733 .emit()
1734 }
1735 _ =>
1736 {
1738 match receiver_validity_err {
1739 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1740 let hint = match receiver_ty
1741 .builtin_deref(false)
1742 .unwrap_or(receiver_ty)
1743 .ty_adt_def()
1744 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1745 {
1746 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1747 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1748 _ => None,
1749 };
1750
1751 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1752 }
1753 ReceiverValidityError::DoesNotDeref => {
1754 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1755 span,
1756 receiver_ty,
1757 })
1758 }
1759 ReceiverValidityError::MethodGenericParamUsed => {
1760 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1761 }
1762 }
1763 }
1764 });
1765 }
1766 Ok(())
1767}
1768
1769enum ReceiverValidityError {
1773 DoesNotDeref,
1776 MethodGenericParamUsed,
1778}
1779
1780fn confirm_type_is_not_a_method_generic_param(
1783 ty: Ty<'_>,
1784 method_generics: &ty::Generics,
1785) -> Result<(), ReceiverValidityError> {
1786 if let ty::Param(param) = ty.kind() {
1787 if (param.index as usize) >= method_generics.parent_count {
1788 return Err(ReceiverValidityError::MethodGenericParamUsed);
1789 }
1790 }
1791 Ok(())
1792}
1793
1794fn receiver_is_valid<'tcx>(
1804 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1805 span: Span,
1806 receiver_ty: Ty<'tcx>,
1807 self_ty: Ty<'tcx>,
1808 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1809 method_generics: &ty::Generics,
1810) -> Result<(), ReceiverValidityError> {
1811 let infcx = wfcx.infcx;
1812 let tcx = wfcx.tcx();
1813 let cause =
1814 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1815
1816 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1818 let ocx = ObligationCtxt::new(wfcx.infcx);
1819 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1820 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1821 }) {
1822 return Ok(());
1823 }
1824
1825 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1826
1827 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1828
1829 if arbitrary_self_types_enabled.is_some() {
1833 autoderef = autoderef.use_receiver_trait();
1834 }
1835
1836 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1838 autoderef = autoderef.include_raw_pointers();
1839 }
1840
1841 while let Some((potential_self_ty, _)) = autoderef.next() {
1843 debug!(
1844 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1845 potential_self_ty, self_ty
1846 );
1847
1848 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1849
1850 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1853 let ocx = ObligationCtxt::new(wfcx.infcx);
1854 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1855 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1856 }) {
1857 wfcx.register_obligations(autoderef.into_obligations());
1858 return Ok(());
1859 }
1860
1861 if arbitrary_self_types_enabled.is_none() {
1864 let legacy_receiver_trait_def_id =
1865 tcx.require_lang_item(LangItem::LegacyReceiver, span);
1866 if !legacy_receiver_is_implemented(
1867 wfcx,
1868 legacy_receiver_trait_def_id,
1869 cause.clone(),
1870 potential_self_ty,
1871 ) {
1872 break;
1874 }
1875
1876 wfcx.register_bound(
1878 cause.clone(),
1879 wfcx.param_env,
1880 potential_self_ty,
1881 legacy_receiver_trait_def_id,
1882 );
1883 }
1884 }
1885
1886 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1887 Err(ReceiverValidityError::DoesNotDeref)
1888}
1889
1890fn legacy_receiver_is_implemented<'tcx>(
1891 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1892 legacy_receiver_trait_def_id: DefId,
1893 cause: ObligationCause<'tcx>,
1894 receiver_ty: Ty<'tcx>,
1895) -> bool {
1896 let tcx = wfcx.tcx();
1897 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1898
1899 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1900
1901 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1902 true
1903 } else {
1904 debug!(
1905 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1906 receiver_ty
1907 );
1908 false
1909 }
1910}
1911
1912pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1913 match tcx.def_kind(def_id) {
1914 DefKind::Enum | DefKind::Struct | DefKind::Union => {
1915 }
1917 DefKind::TyAlias => {
1918 assert!(
1919 tcx.type_alias_is_lazy(def_id),
1920 "should not be computing variance of non-free type alias"
1921 );
1922 }
1923 kind => span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
1924 }
1925
1926 let ty_predicates = tcx.predicates_of(def_id);
1927 assert_eq!(ty_predicates.parent, None);
1928 let variances = tcx.variances_of(def_id);
1929
1930 let mut constrained_parameters: FxHashSet<_> = variances
1931 .iter()
1932 .enumerate()
1933 .filter(|&(_, &variance)| variance != ty::Bivariant)
1934 .map(|(index, _)| Parameter(index as u32))
1935 .collect();
1936
1937 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1938
1939 let explicitly_bounded_params = LazyCell::new(|| {
1941 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
1942 tcx.hir_node_by_def_id(def_id)
1943 .generics()
1944 .unwrap()
1945 .predicates
1946 .iter()
1947 .filter_map(|predicate| match predicate.kind {
1948 hir::WherePredicateKind::BoundPredicate(predicate) => {
1949 match icx.lower_ty(predicate.bounded_ty).kind() {
1950 ty::Param(data) => Some(Parameter(data.index)),
1951 _ => None,
1952 }
1953 }
1954 _ => None,
1955 })
1956 .collect::<FxHashSet<_>>()
1957 });
1958
1959 for (index, _) in variances.iter().enumerate() {
1960 let parameter = Parameter(index as u32);
1961
1962 if constrained_parameters.contains(¶meter) {
1963 continue;
1964 }
1965
1966 let node = tcx.hir_node_by_def_id(def_id);
1967 let item = node.expect_item();
1968 let hir_generics = node.generics().unwrap();
1969 let hir_param = &hir_generics.params[index];
1970
1971 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
1972
1973 if ty_param.def_id != hir_param.def_id.into() {
1974 tcx.dcx().span_delayed_bug(
1982 hir_param.span,
1983 "hir generics and ty generics in different order",
1984 );
1985 continue;
1986 }
1987
1988 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
1990 .type_of(def_id)
1991 .instantiate_identity()
1992 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
1993 {
1994 continue;
1995 }
1996
1997 match hir_param.name {
1998 hir::ParamName::Error(_) => {
1999 }
2002 _ => {
2003 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2004 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2005 }
2006 }
2007 }
2008}
2009
2010struct HasErrorDeep<'tcx> {
2012 tcx: TyCtxt<'tcx>,
2013 seen: FxHashSet<DefId>,
2014}
2015impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2016 type Result = ControlFlow<ErrorGuaranteed>;
2017
2018 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2019 match *ty.kind() {
2020 ty::Adt(def, _) => {
2021 if self.seen.insert(def.did()) {
2022 for field in def.all_fields() {
2023 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2024 }
2025 }
2026 }
2027 ty::Error(guar) => return ControlFlow::Break(guar),
2028 _ => {}
2029 }
2030 ty.super_visit_with(self)
2031 }
2032
2033 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2034 if let Err(guar) = r.error_reported() {
2035 ControlFlow::Break(guar)
2036 } else {
2037 ControlFlow::Continue(())
2038 }
2039 }
2040
2041 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2042 if let Err(guar) = c.error_reported() {
2043 ControlFlow::Break(guar)
2044 } else {
2045 ControlFlow::Continue(())
2046 }
2047 }
2048}
2049
2050fn report_bivariance<'tcx>(
2051 tcx: TyCtxt<'tcx>,
2052 param: &'tcx hir::GenericParam<'tcx>,
2053 has_explicit_bounds: bool,
2054 item: &'tcx hir::Item<'tcx>,
2055) -> ErrorGuaranteed {
2056 let param_name = param.name.ident();
2057
2058 let help = match item.kind {
2059 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2060 if let Some(def_id) = tcx.lang_items().phantom_data() {
2061 errors::UnusedGenericParameterHelp::Adt {
2062 param_name,
2063 phantom_data: tcx.def_path_str(def_id),
2064 }
2065 } else {
2066 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2067 }
2068 }
2069 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2070 item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2071 };
2072
2073 let mut usage_spans = vec![];
2074 intravisit::walk_item(
2075 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2076 item,
2077 );
2078
2079 if !usage_spans.is_empty() {
2080 let item_def_id = item.owner_id.to_def_id();
2084 let is_probably_cyclical =
2085 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2086 .visit_def(item_def_id)
2087 .is_break();
2088 if is_probably_cyclical {
2097 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2098 spans: usage_spans,
2099 param_span: param.span,
2100 param_name,
2101 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2102 help,
2103 note: (),
2104 });
2105 }
2106 }
2107
2108 let const_param_help =
2109 matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2110
2111 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2112 span: param.span,
2113 param_name,
2114 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2115 usage_spans,
2116 help,
2117 const_param_help,
2118 });
2119 diag.code(E0392);
2120 diag.emit()
2121}
2122
2123struct IsProbablyCyclical<'tcx> {
2129 tcx: TyCtxt<'tcx>,
2130 item_def_id: DefId,
2131 seen: FxHashSet<DefId>,
2132}
2133
2134impl<'tcx> IsProbablyCyclical<'tcx> {
2135 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2136 match self.tcx.def_kind(def_id) {
2137 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2138 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2139 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2140 })
2141 }
2142 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2143 self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2144 }
2145 _ => ControlFlow::Continue(()),
2146 }
2147 }
2148}
2149
2150impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2151 type Result = ControlFlow<(), ()>;
2152
2153 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2154 let def_id = match ty.kind() {
2155 ty::Adt(adt_def, _) => Some(adt_def.did()),
2156 ty::Alias(ty::Free, alias_ty) => Some(alias_ty.def_id),
2157 _ => None,
2158 };
2159 if let Some(def_id) = def_id {
2160 if def_id == self.item_def_id {
2161 return ControlFlow::Break(());
2162 }
2163 if self.seen.insert(def_id) {
2164 self.visit_def(def_id)?;
2165 }
2166 }
2167 ty.super_visit_with(self)
2168 }
2169}
2170
2171struct CollectUsageSpans<'a> {
2176 spans: &'a mut Vec<Span>,
2177 param_def_id: DefId,
2178}
2179
2180impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2181 type Result = ();
2182
2183 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2184 }
2186
2187 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2188 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2189 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2190 && def_id == self.param_def_id
2191 {
2192 self.spans.push(t.span);
2193 return;
2194 } else if let Res::SelfTyAlias { .. } = qpath.res {
2195 self.spans.push(t.span);
2196 return;
2197 }
2198 }
2199 intravisit::walk_ty(self, t);
2200 }
2201}
2202
2203impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2204 #[instrument(level = "debug", skip(self))]
2207 fn check_false_global_bounds(&mut self) {
2208 let tcx = self.ocx.infcx.tcx;
2209 let mut span = tcx.def_span(self.body_def_id);
2210 let empty_env = ty::ParamEnv::empty();
2211
2212 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2213 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2215
2216 for (pred, obligation_span) in implied_obligations {
2217 if let ty::ClauseKind::WellFormed(..) = pred.kind().skip_binder() {
2221 continue;
2222 }
2223 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2225 let pred = self.normalize(span, None, pred);
2226
2227 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2229 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2230 span = predicates
2231 .iter()
2232 .find(|pred| pred.span.contains(obligation_span))
2234 .map(|pred| pred.span)
2235 .unwrap_or(obligation_span);
2236 }
2237
2238 let obligation = Obligation::new(
2239 tcx,
2240 traits::ObligationCause::new(
2241 span,
2242 self.body_def_id,
2243 ObligationCauseCode::TrivialBound,
2244 ),
2245 empty_env,
2246 pred,
2247 );
2248 self.ocx.register_obligation(obligation);
2249 }
2250 }
2251 }
2252}
2253
2254pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2255 let items = tcx.hir_crate_items(());
2256 let res = items
2257 .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2258 .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2259 .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2260 .and(
2261 items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2262 )
2263 .and(items.par_nested_bodies(|item| tcx.ensure_ok().check_well_formed(item)))
2264 .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2265 super::entry::check_for_entry_fn(tcx);
2266
2267 res
2268}
2269
2270fn lint_redundant_lifetimes<'tcx>(
2271 tcx: TyCtxt<'tcx>,
2272 owner_id: LocalDefId,
2273 outlives_env: &OutlivesEnvironment<'tcx>,
2274) {
2275 let def_kind = tcx.def_kind(owner_id);
2276 match def_kind {
2277 DefKind::Struct
2278 | DefKind::Union
2279 | DefKind::Enum
2280 | DefKind::Trait
2281 | DefKind::TraitAlias
2282 | DefKind::Fn
2283 | DefKind::Const
2284 | DefKind::Impl { of_trait: _ } => {
2285 }
2287 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2288 let parent_def_id = tcx.local_parent(owner_id);
2289 if matches!(tcx.def_kind(parent_def_id), DefKind::Impl { of_trait: true }) {
2290 return;
2295 }
2296 }
2297 DefKind::Mod
2298 | DefKind::Variant
2299 | DefKind::TyAlias
2300 | DefKind::ForeignTy
2301 | DefKind::TyParam
2302 | DefKind::ConstParam
2303 | DefKind::Static { .. }
2304 | DefKind::Ctor(_, _)
2305 | DefKind::Macro(_)
2306 | DefKind::ExternCrate
2307 | DefKind::Use
2308 | DefKind::ForeignMod
2309 | DefKind::AnonConst
2310 | DefKind::InlineConst
2311 | DefKind::OpaqueTy
2312 | DefKind::Field
2313 | DefKind::LifetimeParam
2314 | DefKind::GlobalAsm
2315 | DefKind::Closure
2316 | DefKind::SyntheticCoroutineBody => return,
2317 }
2318
2319 let mut lifetimes = vec![tcx.lifetimes.re_static];
2328 lifetimes.extend(
2329 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2330 );
2331 if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2333 for (idx, var) in
2334 tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2335 {
2336 let ty::BoundVariableKind::Region(kind) = var else { continue };
2337 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2338 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2339 }
2340 }
2341 lifetimes.retain(|candidate| candidate.is_named(tcx));
2342
2343 let mut shadowed = FxHashSet::default();
2347
2348 for (idx, &candidate) in lifetimes.iter().enumerate() {
2349 if shadowed.contains(&candidate) {
2354 continue;
2355 }
2356
2357 for &victim in &lifetimes[(idx + 1)..] {
2358 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2366 continue;
2367 };
2368
2369 if tcx.parent(def_id) != owner_id.to_def_id() {
2374 continue;
2375 }
2376
2377 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2379 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2380 {
2381 shadowed.insert(victim);
2382 tcx.emit_node_span_lint(
2383 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2384 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2385 tcx.def_span(def_id),
2386 RedundantLifetimeArgsLint { candidate, victim },
2387 );
2388 }
2389 }
2390 }
2391}
2392
2393#[derive(LintDiagnostic)]
2394#[diag(hir_analysis_redundant_lifetime_args)]
2395#[note]
2396struct RedundantLifetimeArgsLint<'tcx> {
2397 victim: ty::Region<'tcx>,
2399 candidate: ty::Region<'tcx>,
2401}