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