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};
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 matches!(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 { eii_macro, span, .. } in
1200 find_attr!(tcx.get_all_attrs(def_id), AttributeKind::EiiImpls(impls) => impls)
1201 .into_iter()
1202 .flatten()
1203 {
1204 if let Some(eii_extern_target) = find_attr!(tcx.get_all_attrs(*eii_macro), AttributeKind::EiiExternTarget(EiiDecl {eii_extern_target, ..}) => *eii_extern_target)
1207 {
1208 let _ = compare_eii_function_types(
1209 tcx,
1210 def_id,
1211 eii_extern_target,
1212 tcx.item_name(*eii_macro),
1213 *span,
1214 );
1215 } else {
1216 panic!(
1217 "EII impl macro {eii_macro:?} did not have an eii extern target attribute pointing to a foreign function"
1218 )
1219 }
1220 }
1221}
1222
1223#[instrument(level = "debug", skip(tcx))]
1224pub(crate) fn check_static_item<'tcx>(
1225 tcx: TyCtxt<'tcx>,
1226 item_id: LocalDefId,
1227 ty: Ty<'tcx>,
1228 should_check_for_sync: bool,
1229) -> Result<(), ErrorGuaranteed> {
1230 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1231 let span = tcx.ty_span(item_id);
1232 let loc = Some(WellFormedLoc::Ty(item_id));
1233 let item_ty = wfcx.deeply_normalize(span, loc, ty);
1234
1235 let is_foreign_item = tcx.is_foreign_item(item_id);
1236 let is_structurally_foreign_item = || {
1237 let tail = tcx.struct_tail_raw(
1238 item_ty,
1239 &ObligationCause::dummy(),
1240 |ty| wfcx.deeply_normalize(span, loc, ty),
1241 || {},
1242 );
1243
1244 matches!(tail.kind(), ty::Foreign(_))
1245 };
1246 let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1247
1248 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1249 if forbid_unsized {
1250 let span = tcx.def_span(item_id);
1251 wfcx.register_bound(
1252 traits::ObligationCause::new(
1253 span,
1254 wfcx.body_def_id,
1255 ObligationCauseCode::SizedConstOrStatic,
1256 ),
1257 wfcx.param_env,
1258 item_ty,
1259 tcx.require_lang_item(LangItem::Sized, span),
1260 );
1261 }
1262
1263 let should_check_for_sync = should_check_for_sync
1265 && !is_foreign_item
1266 && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1267 && !tcx.is_thread_local_static(item_id.to_def_id());
1268
1269 if should_check_for_sync {
1270 wfcx.register_bound(
1271 traits::ObligationCause::new(
1272 span,
1273 wfcx.body_def_id,
1274 ObligationCauseCode::SharedStatic,
1275 ),
1276 wfcx.param_env,
1277 item_ty,
1278 tcx.require_lang_item(LangItem::Sync, span),
1279 );
1280 }
1281 Ok(())
1282 })
1283}
1284
1285#[instrument(level = "debug", skip(wfcx))]
1286pub(super) fn check_type_const<'tcx>(
1287 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1288 def_id: LocalDefId,
1289 item_ty: Ty<'tcx>,
1290 has_value: bool,
1291) -> Result<(), ErrorGuaranteed> {
1292 let tcx = wfcx.tcx();
1293 let span = tcx.def_span(def_id);
1294
1295 wfcx.register_bound(
1296 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1297 wfcx.param_env,
1298 item_ty,
1299 tcx.require_lang_item(LangItem::ConstParamTy, span),
1300 );
1301
1302 if has_value {
1303 let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1304 let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1305 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1306
1307 wfcx.register_obligation(Obligation::new(
1308 tcx,
1309 ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1310 wfcx.param_env,
1311 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1312 ));
1313 }
1314 Ok(())
1315}
1316
1317#[instrument(level = "debug", skip(tcx, impl_))]
1318fn check_impl<'tcx>(
1319 tcx: TyCtxt<'tcx>,
1320 item: &'tcx hir::Item<'tcx>,
1321 impl_: &hir::Impl<'_>,
1322) -> Result<(), ErrorGuaranteed> {
1323 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1324 match impl_.of_trait {
1325 Some(of_trait) => {
1326 let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1330 tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1333 let trait_span = of_trait.trait_ref.path.span;
1334 let trait_ref = wfcx.deeply_normalize(
1335 trait_span,
1336 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1337 trait_ref,
1338 );
1339 let trait_pred =
1340 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1341 let mut obligations = traits::wf::trait_obligations(
1342 wfcx.infcx,
1343 wfcx.param_env,
1344 wfcx.body_def_id,
1345 trait_pred,
1346 trait_span,
1347 item,
1348 );
1349 for obligation in &mut obligations {
1350 if obligation.cause.span != trait_span {
1351 continue;
1353 }
1354 if let Some(pred) = obligation.predicate.as_trait_clause()
1355 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1356 {
1357 obligation.cause.span = impl_.self_ty.span;
1358 }
1359 if let Some(pred) = obligation.predicate.as_projection_clause()
1360 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1361 {
1362 obligation.cause.span = impl_.self_ty.span;
1363 }
1364 }
1365
1366 if tcx.is_conditionally_const(item.owner_id.def_id) {
1368 for (bound, _) in
1369 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1370 {
1371 let bound = wfcx.normalize(
1372 item.span,
1373 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1374 bound,
1375 );
1376 wfcx.register_obligation(Obligation::new(
1377 tcx,
1378 ObligationCause::new(
1379 impl_.self_ty.span,
1380 wfcx.body_def_id,
1381 ObligationCauseCode::WellFormed(None),
1382 ),
1383 wfcx.param_env,
1384 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1385 ))
1386 }
1387 }
1388
1389 debug!(?obligations);
1390 wfcx.register_obligations(obligations);
1391 }
1392 None => {
1393 let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1394 let self_ty = wfcx.deeply_normalize(
1395 item.span,
1396 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1397 self_ty,
1398 );
1399 wfcx.register_wf_obligation(
1400 impl_.self_ty.span,
1401 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1402 self_ty.into(),
1403 );
1404 }
1405 }
1406
1407 check_where_clauses(wfcx, item.owner_id.def_id);
1408 Ok(())
1409 })
1410}
1411
1412#[instrument(level = "debug", skip(wfcx))]
1414pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1415 let infcx = wfcx.infcx;
1416 let tcx = wfcx.tcx();
1417
1418 let predicates = tcx.predicates_of(def_id.to_def_id());
1419 let generics = tcx.generics_of(def_id);
1420
1421 for param in &generics.own_params {
1428 if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1429 if !default.has_param() {
1436 wfcx.register_wf_obligation(
1437 tcx.def_span(param.def_id),
1438 matches!(param.kind, GenericParamDefKind::Type { .. })
1439 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1440 default.as_term().unwrap(),
1441 );
1442 } else {
1443 let GenericArgKind::Const(ct) = default.kind() else {
1446 continue;
1447 };
1448
1449 let ct_ty = match ct.kind() {
1450 ty::ConstKind::Infer(_)
1451 | ty::ConstKind::Placeholder(_)
1452 | ty::ConstKind::Bound(_, _) => unreachable!(),
1453 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1454 ty::ConstKind::Value(cv) => cv.ty,
1455 ty::ConstKind::Unevaluated(uv) => {
1456 infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1457 }
1458 ty::ConstKind::Param(param_ct) => {
1459 param_ct.find_const_ty_from_env(wfcx.param_env)
1460 }
1461 };
1462
1463 let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1464 if !ct_ty.has_param() && !param_ty.has_param() {
1465 let cause = traits::ObligationCause::new(
1466 tcx.def_span(param.def_id),
1467 wfcx.body_def_id,
1468 ObligationCauseCode::WellFormed(None),
1469 );
1470 wfcx.register_obligation(Obligation::new(
1471 tcx,
1472 cause,
1473 wfcx.param_env,
1474 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1475 ));
1476 }
1477 }
1478 }
1479 }
1480
1481 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1490 if param.index >= generics.parent_count as u32
1491 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1493 && !default.has_param()
1495 {
1496 return default;
1498 }
1499 tcx.mk_param_from_def(param)
1500 });
1501
1502 let default_obligations = predicates
1504 .predicates
1505 .iter()
1506 .flat_map(|&(pred, sp)| {
1507 #[derive(Default)]
1508 struct CountParams {
1509 params: FxHashSet<u32>,
1510 }
1511 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1512 type Result = ControlFlow<()>;
1513 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1514 if let ty::Param(param) = t.kind() {
1515 self.params.insert(param.index);
1516 }
1517 t.super_visit_with(self)
1518 }
1519
1520 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1521 ControlFlow::Break(())
1522 }
1523
1524 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1525 if let ty::ConstKind::Param(param) = c.kind() {
1526 self.params.insert(param.index);
1527 }
1528 c.super_visit_with(self)
1529 }
1530 }
1531 let mut param_count = CountParams::default();
1532 let has_region = pred.visit_with(&mut param_count).is_break();
1533 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1534 if instantiated_pred.has_non_region_param()
1537 || param_count.params.len() > 1
1538 || has_region
1539 {
1540 None
1541 } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1542 None
1544 } else {
1545 Some((instantiated_pred, sp))
1546 }
1547 })
1548 .map(|(pred, sp)| {
1549 let pred = wfcx.normalize(sp, None, pred);
1559 let cause = traits::ObligationCause::new(
1560 sp,
1561 wfcx.body_def_id,
1562 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1563 );
1564 Obligation::new(tcx, cause, wfcx.param_env, pred)
1565 });
1566
1567 let predicates = predicates.instantiate_identity(tcx);
1568
1569 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1570 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1571 traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1572 });
1573 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1574 wfcx.register_obligations(obligations);
1575}
1576
1577#[instrument(level = "debug", skip(wfcx, hir_decl))]
1578fn check_fn_or_method<'tcx>(
1579 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1580 sig: ty::PolyFnSig<'tcx>,
1581 hir_decl: &hir::FnDecl<'_>,
1582 def_id: LocalDefId,
1583) {
1584 let tcx = wfcx.tcx();
1585 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1586
1587 let arg_span =
1593 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1594
1595 sig.inputs_and_output =
1596 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1597 wfcx.deeply_normalize(
1598 arg_span(idx),
1599 Some(WellFormedLoc::Param {
1600 function: def_id,
1601 param_idx: idx,
1604 }),
1605 ty,
1606 )
1607 }));
1608
1609 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1610 wfcx.register_wf_obligation(
1611 arg_span(idx),
1612 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1613 ty.into(),
1614 );
1615 }
1616
1617 check_where_clauses(wfcx, def_id);
1618
1619 if sig.abi == ExternAbi::RustCall {
1620 let span = tcx.def_span(def_id);
1621 let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1622 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1623 if let Some(ty) = inputs.next() {
1625 wfcx.register_bound(
1626 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1627 wfcx.param_env,
1628 *ty,
1629 tcx.require_lang_item(hir::LangItem::Tuple, span),
1630 );
1631 wfcx.register_bound(
1632 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1633 wfcx.param_env,
1634 *ty,
1635 tcx.require_lang_item(hir::LangItem::Sized, span),
1636 );
1637 } else {
1638 tcx.dcx().span_err(
1639 hir_decl.inputs.last().map_or(span, |input| input.span),
1640 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1641 );
1642 }
1643 if inputs.next().is_some() {
1645 tcx.dcx().span_err(
1646 hir_decl.inputs.last().map_or(span, |input| input.span),
1647 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1648 );
1649 }
1650 }
1651
1652 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1654 let span = match hir_decl.output {
1655 hir::FnRetTy::Return(ty) => ty.span,
1656 hir::FnRetTy::DefaultReturn(_) => body.value.span,
1657 };
1658
1659 wfcx.register_bound(
1660 ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1661 wfcx.param_env,
1662 sig.output(),
1663 tcx.require_lang_item(LangItem::Sized, span),
1664 );
1665 }
1666}
1667
1668#[derive(Clone, Copy, PartialEq)]
1670enum ArbitrarySelfTypesLevel {
1671 Basic, WithPointers, }
1674
1675#[instrument(level = "debug", skip(wfcx))]
1676fn check_method_receiver<'tcx>(
1677 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1678 fn_sig: &hir::FnSig<'_>,
1679 method: ty::AssocItem,
1680 self_ty: Ty<'tcx>,
1681) -> Result<(), ErrorGuaranteed> {
1682 let tcx = wfcx.tcx();
1683
1684 if !method.is_method() {
1685 return Ok(());
1686 }
1687
1688 let span = fn_sig.decl.inputs[0].span;
1689 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1690
1691 let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1692 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1693 let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1694
1695 debug!("check_method_receiver: sig={:?}", sig);
1696
1697 let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1698
1699 let receiver_ty = sig.inputs()[0];
1700 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1701
1702 receiver_ty.error_reported()?;
1705
1706 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1707 Some(ArbitrarySelfTypesLevel::WithPointers)
1708 } else if tcx.features().arbitrary_self_types() {
1709 Some(ArbitrarySelfTypesLevel::Basic)
1710 } else {
1711 None
1712 };
1713 let generics = tcx.generics_of(method.def_id);
1714
1715 let receiver_validity =
1716 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1717 if let Err(receiver_validity_err) = receiver_validity {
1718 return Err(match arbitrary_self_types_level {
1719 None if receiver_is_valid(
1723 wfcx,
1724 span,
1725 receiver_ty,
1726 self_ty,
1727 Some(ArbitrarySelfTypesLevel::Basic),
1728 generics,
1729 )
1730 .is_ok() =>
1731 {
1732 feature_err(
1734 &tcx.sess,
1735 sym::arbitrary_self_types,
1736 span,
1737 format!(
1738 "`{receiver_ty}` cannot be used as the type of `self` without \
1739 the `arbitrary_self_types` feature",
1740 ),
1741 )
1742 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1743 .emit()
1744 }
1745 None | Some(ArbitrarySelfTypesLevel::Basic)
1746 if receiver_is_valid(
1747 wfcx,
1748 span,
1749 receiver_ty,
1750 self_ty,
1751 Some(ArbitrarySelfTypesLevel::WithPointers),
1752 generics,
1753 )
1754 .is_ok() =>
1755 {
1756 feature_err(
1758 &tcx.sess,
1759 sym::arbitrary_self_types_pointers,
1760 span,
1761 format!(
1762 "`{receiver_ty}` cannot be used as the type of `self` without \
1763 the `arbitrary_self_types_pointers` feature",
1764 ),
1765 )
1766 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1767 .emit()
1768 }
1769 _ =>
1770 {
1772 match receiver_validity_err {
1773 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1774 let hint = match receiver_ty
1775 .builtin_deref(false)
1776 .unwrap_or(receiver_ty)
1777 .ty_adt_def()
1778 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1779 {
1780 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1781 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1782 _ => None,
1783 };
1784
1785 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1786 }
1787 ReceiverValidityError::DoesNotDeref => {
1788 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1789 span,
1790 receiver_ty,
1791 })
1792 }
1793 ReceiverValidityError::MethodGenericParamUsed => {
1794 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1795 }
1796 }
1797 }
1798 });
1799 }
1800 Ok(())
1801}
1802
1803enum ReceiverValidityError {
1807 DoesNotDeref,
1810 MethodGenericParamUsed,
1812}
1813
1814fn confirm_type_is_not_a_method_generic_param(
1817 ty: Ty<'_>,
1818 method_generics: &ty::Generics,
1819) -> Result<(), ReceiverValidityError> {
1820 if let ty::Param(param) = ty.kind() {
1821 if (param.index as usize) >= method_generics.parent_count {
1822 return Err(ReceiverValidityError::MethodGenericParamUsed);
1823 }
1824 }
1825 Ok(())
1826}
1827
1828fn receiver_is_valid<'tcx>(
1838 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1839 span: Span,
1840 receiver_ty: Ty<'tcx>,
1841 self_ty: Ty<'tcx>,
1842 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1843 method_generics: &ty::Generics,
1844) -> Result<(), ReceiverValidityError> {
1845 let infcx = wfcx.infcx;
1846 let tcx = wfcx.tcx();
1847 let cause =
1848 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1849
1850 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1852 let ocx = ObligationCtxt::new(wfcx.infcx);
1853 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1854 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1855 Ok(())
1856 } else {
1857 Err(NoSolution)
1858 }
1859 }) {
1860 return Ok(());
1861 }
1862
1863 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1864
1865 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1866
1867 if arbitrary_self_types_enabled.is_some() {
1871 autoderef = autoderef.use_receiver_trait();
1872 }
1873
1874 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1876 autoderef = autoderef.include_raw_pointers();
1877 }
1878
1879 while let Some((potential_self_ty, _)) = autoderef.next() {
1881 debug!(
1882 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1883 potential_self_ty, self_ty
1884 );
1885
1886 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1887
1888 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1891 let ocx = ObligationCtxt::new(wfcx.infcx);
1892 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1893 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1894 Ok(())
1895 } else {
1896 Err(NoSolution)
1897 }
1898 }) {
1899 wfcx.register_obligations(autoderef.into_obligations());
1900 return Ok(());
1901 }
1902
1903 if arbitrary_self_types_enabled.is_none() {
1906 let legacy_receiver_trait_def_id =
1907 tcx.require_lang_item(LangItem::LegacyReceiver, span);
1908 if !legacy_receiver_is_implemented(
1909 wfcx,
1910 legacy_receiver_trait_def_id,
1911 cause.clone(),
1912 potential_self_ty,
1913 ) {
1914 break;
1916 }
1917
1918 wfcx.register_bound(
1920 cause.clone(),
1921 wfcx.param_env,
1922 potential_self_ty,
1923 legacy_receiver_trait_def_id,
1924 );
1925 }
1926 }
1927
1928 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1929 Err(ReceiverValidityError::DoesNotDeref)
1930}
1931
1932fn legacy_receiver_is_implemented<'tcx>(
1933 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1934 legacy_receiver_trait_def_id: DefId,
1935 cause: ObligationCause<'tcx>,
1936 receiver_ty: Ty<'tcx>,
1937) -> bool {
1938 let tcx = wfcx.tcx();
1939 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1940
1941 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1942
1943 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1944 true
1945 } else {
1946 debug!(
1947 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1948 receiver_ty
1949 );
1950 false
1951 }
1952}
1953
1954pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1955 match tcx.def_kind(def_id) {
1956 DefKind::Enum | DefKind::Struct | DefKind::Union => {
1957 }
1959 DefKind::TyAlias => {
1960 assert!(
1961 tcx.type_alias_is_lazy(def_id),
1962 "should not be computing variance of non-free type alias"
1963 );
1964 }
1965 kind => span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
1966 }
1967
1968 let ty_predicates = tcx.predicates_of(def_id);
1969 assert_eq!(ty_predicates.parent, None);
1970 let variances = tcx.variances_of(def_id);
1971
1972 let mut constrained_parameters: FxHashSet<_> = variances
1973 .iter()
1974 .enumerate()
1975 .filter(|&(_, &variance)| variance != ty::Bivariant)
1976 .map(|(index, _)| Parameter(index as u32))
1977 .collect();
1978
1979 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1980
1981 let explicitly_bounded_params = LazyCell::new(|| {
1983 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
1984 tcx.hir_node_by_def_id(def_id)
1985 .generics()
1986 .unwrap()
1987 .predicates
1988 .iter()
1989 .filter_map(|predicate| match predicate.kind {
1990 hir::WherePredicateKind::BoundPredicate(predicate) => {
1991 match icx.lower_ty(predicate.bounded_ty).kind() {
1992 ty::Param(data) => Some(Parameter(data.index)),
1993 _ => None,
1994 }
1995 }
1996 _ => None,
1997 })
1998 .collect::<FxHashSet<_>>()
1999 });
2000
2001 for (index, _) in variances.iter().enumerate() {
2002 let parameter = Parameter(index as u32);
2003
2004 if constrained_parameters.contains(¶meter) {
2005 continue;
2006 }
2007
2008 let node = tcx.hir_node_by_def_id(def_id);
2009 let item = node.expect_item();
2010 let hir_generics = node.generics().unwrap();
2011 let hir_param = &hir_generics.params[index];
2012
2013 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2014
2015 if ty_param.def_id != hir_param.def_id.into() {
2016 tcx.dcx().span_delayed_bug(
2024 hir_param.span,
2025 "hir generics and ty generics in different order",
2026 );
2027 continue;
2028 }
2029
2030 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2032 .type_of(def_id)
2033 .instantiate_identity()
2034 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2035 {
2036 continue;
2037 }
2038
2039 match hir_param.name {
2040 hir::ParamName::Error(_) => {
2041 }
2044 _ => {
2045 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2046 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2047 }
2048 }
2049 }
2050}
2051
2052struct HasErrorDeep<'tcx> {
2054 tcx: TyCtxt<'tcx>,
2055 seen: FxHashSet<DefId>,
2056}
2057impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2058 type Result = ControlFlow<ErrorGuaranteed>;
2059
2060 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2061 match *ty.kind() {
2062 ty::Adt(def, _) => {
2063 if self.seen.insert(def.did()) {
2064 for field in def.all_fields() {
2065 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2066 }
2067 }
2068 }
2069 ty::Error(guar) => return ControlFlow::Break(guar),
2070 _ => {}
2071 }
2072 ty.super_visit_with(self)
2073 }
2074
2075 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2076 if let Err(guar) = r.error_reported() {
2077 ControlFlow::Break(guar)
2078 } else {
2079 ControlFlow::Continue(())
2080 }
2081 }
2082
2083 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2084 if let Err(guar) = c.error_reported() {
2085 ControlFlow::Break(guar)
2086 } else {
2087 ControlFlow::Continue(())
2088 }
2089 }
2090}
2091
2092fn report_bivariance<'tcx>(
2093 tcx: TyCtxt<'tcx>,
2094 param: &'tcx hir::GenericParam<'tcx>,
2095 has_explicit_bounds: bool,
2096 item: &'tcx hir::Item<'tcx>,
2097) -> ErrorGuaranteed {
2098 let param_name = param.name.ident();
2099
2100 let help = match item.kind {
2101 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2102 if let Some(def_id) = tcx.lang_items().phantom_data() {
2103 errors::UnusedGenericParameterHelp::Adt {
2104 param_name,
2105 phantom_data: tcx.def_path_str(def_id),
2106 }
2107 } else {
2108 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2109 }
2110 }
2111 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2112 item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2113 };
2114
2115 let mut usage_spans = vec![];
2116 intravisit::walk_item(
2117 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2118 item,
2119 );
2120
2121 if !usage_spans.is_empty() {
2122 let item_def_id = item.owner_id.to_def_id();
2126 let is_probably_cyclical =
2127 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2128 .visit_def(item_def_id)
2129 .is_break();
2130 if is_probably_cyclical {
2139 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2140 spans: usage_spans,
2141 param_span: param.span,
2142 param_name,
2143 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2144 help,
2145 note: (),
2146 });
2147 }
2148 }
2149
2150 let const_param_help =
2151 matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2152
2153 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2154 span: param.span,
2155 param_name,
2156 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2157 usage_spans,
2158 help,
2159 const_param_help,
2160 });
2161 diag.code(E0392);
2162 diag.emit()
2163}
2164
2165struct IsProbablyCyclical<'tcx> {
2171 tcx: TyCtxt<'tcx>,
2172 item_def_id: DefId,
2173 seen: FxHashSet<DefId>,
2174}
2175
2176impl<'tcx> IsProbablyCyclical<'tcx> {
2177 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2178 match self.tcx.def_kind(def_id) {
2179 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2180 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2181 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2182 })
2183 }
2184 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2185 self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2186 }
2187 _ => ControlFlow::Continue(()),
2188 }
2189 }
2190}
2191
2192impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2193 type Result = ControlFlow<(), ()>;
2194
2195 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2196 let def_id = match ty.kind() {
2197 ty::Adt(adt_def, _) => Some(adt_def.did()),
2198 ty::Alias(ty::Free, alias_ty) => Some(alias_ty.def_id),
2199 _ => None,
2200 };
2201 if let Some(def_id) = def_id {
2202 if def_id == self.item_def_id {
2203 return ControlFlow::Break(());
2204 }
2205 if self.seen.insert(def_id) {
2206 self.visit_def(def_id)?;
2207 }
2208 }
2209 ty.super_visit_with(self)
2210 }
2211}
2212
2213struct CollectUsageSpans<'a> {
2218 spans: &'a mut Vec<Span>,
2219 param_def_id: DefId,
2220}
2221
2222impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2223 type Result = ();
2224
2225 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2226 }
2228
2229 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2230 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2231 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2232 && def_id == self.param_def_id
2233 {
2234 self.spans.push(t.span);
2235 return;
2236 } else if let Res::SelfTyAlias { .. } = qpath.res {
2237 self.spans.push(t.span);
2238 return;
2239 }
2240 }
2241 intravisit::walk_ty(self, t);
2242 }
2243}
2244
2245impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2246 #[instrument(level = "debug", skip(self))]
2249 fn check_false_global_bounds(&mut self) {
2250 let tcx = self.ocx.infcx.tcx;
2251 let mut span = tcx.def_span(self.body_def_id);
2252 let empty_env = ty::ParamEnv::empty();
2253
2254 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2255 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2257
2258 for (pred, obligation_span) in implied_obligations {
2259 match pred.kind().skip_binder() {
2260 ty::ClauseKind::WellFormed(..)
2264 | ty::ClauseKind::UnstableFeature(..) => continue,
2266 _ => {}
2267 }
2268
2269 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2271 let pred = self.normalize(span, None, pred);
2272
2273 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2275 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2276 span = predicates
2277 .iter()
2278 .find(|pred| pred.span.contains(obligation_span))
2280 .map(|pred| pred.span)
2281 .unwrap_or(obligation_span);
2282 }
2283
2284 let obligation = Obligation::new(
2285 tcx,
2286 traits::ObligationCause::new(
2287 span,
2288 self.body_def_id,
2289 ObligationCauseCode::TrivialBound,
2290 ),
2291 empty_env,
2292 pred,
2293 );
2294 self.ocx.register_obligation(obligation);
2295 }
2296 }
2297 }
2298}
2299
2300pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2301 let items = tcx.hir_crate_items(());
2302 let res = items
2303 .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2304 .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2305 .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2306 .and(
2307 items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2308 )
2309 .and(items.par_nested_bodies(|item| tcx.ensure_ok().check_well_formed(item)))
2310 .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2311 super::entry::check_for_entry_fn(tcx);
2312
2313 res
2314}
2315
2316fn lint_redundant_lifetimes<'tcx>(
2317 tcx: TyCtxt<'tcx>,
2318 owner_id: LocalDefId,
2319 outlives_env: &OutlivesEnvironment<'tcx>,
2320) {
2321 let def_kind = tcx.def_kind(owner_id);
2322 match def_kind {
2323 DefKind::Struct
2324 | DefKind::Union
2325 | DefKind::Enum
2326 | DefKind::Trait
2327 | DefKind::TraitAlias
2328 | DefKind::Fn
2329 | DefKind::Const
2330 | DefKind::Impl { of_trait: _ } => {
2331 }
2333 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2334 if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2335 return;
2340 }
2341 }
2342 DefKind::Mod
2343 | DefKind::Variant
2344 | DefKind::TyAlias
2345 | DefKind::ForeignTy
2346 | DefKind::TyParam
2347 | DefKind::ConstParam
2348 | DefKind::Static { .. }
2349 | DefKind::Ctor(_, _)
2350 | DefKind::Macro(_)
2351 | DefKind::ExternCrate
2352 | DefKind::Use
2353 | DefKind::ForeignMod
2354 | DefKind::AnonConst
2355 | DefKind::InlineConst
2356 | DefKind::OpaqueTy
2357 | DefKind::Field
2358 | DefKind::LifetimeParam
2359 | DefKind::GlobalAsm
2360 | DefKind::Closure
2361 | DefKind::SyntheticCoroutineBody => return,
2362 }
2363
2364 let mut lifetimes = vec![tcx.lifetimes.re_static];
2373 lifetimes.extend(
2374 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2375 );
2376 if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2378 for (idx, var) in
2379 tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2380 {
2381 let ty::BoundVariableKind::Region(kind) = var else { continue };
2382 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2383 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2384 }
2385 }
2386 lifetimes.retain(|candidate| candidate.is_named(tcx));
2387
2388 let mut shadowed = FxHashSet::default();
2392
2393 for (idx, &candidate) in lifetimes.iter().enumerate() {
2394 if shadowed.contains(&candidate) {
2399 continue;
2400 }
2401
2402 for &victim in &lifetimes[(idx + 1)..] {
2403 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2411 continue;
2412 };
2413
2414 if tcx.parent(def_id) != owner_id.to_def_id() {
2419 continue;
2420 }
2421
2422 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2424 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2425 {
2426 shadowed.insert(victim);
2427 tcx.emit_node_span_lint(
2428 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2429 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2430 tcx.def_span(def_id),
2431 RedundantLifetimeArgsLint { candidate, victim },
2432 );
2433 }
2434 }
2435 }
2436}
2437
2438#[derive(LintDiagnostic)]
2439#[diag(hir_analysis_redundant_lifetime_args)]
2440#[note]
2441struct RedundantLifetimeArgsLint<'tcx> {
2442 victim: ty::Region<'tcx>,
2444 candidate: ty::Region<'tcx>,
2446}