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