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