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