1use std::cell::LazyCell;
2use std::ops::{ControlFlow, Deref};
3
4use hir::intravisit::{self, Visitor};
5use rustc_abi::ExternAbi;
6use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
7use rustc_errors::codes::*;
8use rustc_errors::{Applicability, ErrorGuaranteed, pluralize, struct_span_code_err};
9use rustc_hir::def::{DefKind, Res};
10use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
11use rustc_hir::lang_items::LangItem;
12use rustc_hir::{AmbigArg, ItemKind};
13use rustc_infer::infer::outlives::env::OutlivesEnvironment;
14use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
15use rustc_lint_defs::builtin::SUPERTRAIT_ITEM_SHADOWING_DEFINITION;
16use rustc_macros::LintDiagnostic;
17use rustc_middle::mir::interpret::ErrorHandled;
18use rustc_middle::query::Providers;
19use rustc_middle::ty::print::with_no_trimmed_paths;
20use rustc_middle::ty::trait_def::TraitSpecializationKind;
21use rustc_middle::ty::{
22 self, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFoldable,
23 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Upcast,
24};
25use rustc_middle::{bug, span_bug};
26use rustc_session::parse::feature_err;
27use rustc_span::{DUMMY_SP, Ident, Span, sym};
28use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
29use rustc_trait_selection::regions::{InferCtxtRegionExt, OutlivesEnvironmentBuildExt};
30use rustc_trait_selection::traits::misc::{
31 ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
32};
33use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
34use rustc_trait_selection::traits::{
35 self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
36 WellFormedLoc,
37};
38use rustc_type_ir::TypeFlags;
39use rustc_type_ir::solve::NoSolution;
40use tracing::{debug, instrument};
41use {rustc_ast as ast, rustc_hir as hir};
42
43use crate::autoderef::Autoderef;
44use crate::collect::CollectItemTypesVisitor;
45use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
46use crate::errors::InvalidReceiverTyHint;
47use crate::{errors, fluent_generated as fluent};
48
49pub(super) struct WfCheckingCtxt<'a, 'tcx> {
50 pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
51 span: Span,
52 body_def_id: LocalDefId,
53 param_env: ty::ParamEnv<'tcx>,
54}
55impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
56 type Target = ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>;
57 fn deref(&self) -> &Self::Target {
58 &self.ocx
59 }
60}
61
62impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
63 fn tcx(&self) -> TyCtxt<'tcx> {
64 self.ocx.infcx.tcx
65 }
66
67 fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
70 where
71 T: TypeFoldable<TyCtxt<'tcx>>,
72 {
73 self.ocx.normalize(
74 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
75 self.param_env,
76 value,
77 )
78 }
79
80 fn register_wf_obligation(
81 &self,
82 span: Span,
83 loc: Option<WellFormedLoc>,
84 arg: ty::GenericArg<'tcx>,
85 ) {
86 let cause = traits::ObligationCause::new(
87 span,
88 self.body_def_id,
89 ObligationCauseCode::WellFormed(loc),
90 );
91 self.ocx.register_obligation(Obligation::new(
92 self.tcx(),
93 cause,
94 self.param_env,
95 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg))),
96 ));
97 }
98}
99
100pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
101 tcx: TyCtxt<'tcx>,
102 span: Span,
103 body_def_id: LocalDefId,
104 f: F,
105) -> Result<(), ErrorGuaranteed>
106where
107 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> Result<(), ErrorGuaranteed>,
108{
109 let param_env = tcx.param_env(body_def_id);
110 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
111 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
112
113 let mut wfcx = WfCheckingCtxt { ocx, span, body_def_id, param_env };
114
115 if !tcx.features().trivial_bounds() {
116 wfcx.check_false_global_bounds()
117 }
118 f(&mut wfcx)?;
119
120 let errors = wfcx.select_all_or_error();
121 if !errors.is_empty() {
122 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
123 }
124
125 let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
126 debug!(?assumed_wf_types);
127
128 let infcx_compat = infcx.fork();
129
130 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
132 &infcx,
133 body_def_id,
134 param_env,
135 assumed_wf_types.iter().copied(),
136 false,
137 );
138
139 lint_redundant_lifetimes(tcx, body_def_id, &outlives_env);
140
141 let errors = infcx.resolve_regions_with_outlives_env(&outlives_env);
142 if errors.is_empty() {
143 return Ok(());
144 }
145
146 let is_bevy = 'is_bevy: {
147 let is_bevy_paramset = |def: ty::AdtDef<'_>| {
150 let adt_did = with_no_trimmed_paths!(infcx.tcx.def_path_str(def.0.did));
151 adt_did.contains("ParamSet")
152 };
153 for ty in assumed_wf_types.iter() {
154 match ty.kind() {
155 ty::Adt(def, _) => {
156 if is_bevy_paramset(*def) {
157 break 'is_bevy true;
158 }
159 }
160 ty::Ref(_, ty, _) => match ty.kind() {
161 ty::Adt(def, _) => {
162 if is_bevy_paramset(*def) {
163 break 'is_bevy true;
164 }
165 }
166 _ => {}
167 },
168 _ => {}
169 }
170 }
171 false
172 };
173
174 if is_bevy && !infcx.tcx.sess.opts.unstable_opts.no_implied_bounds_compat {
179 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
180 &infcx,
181 body_def_id,
182 param_env,
183 assumed_wf_types,
184 true,
185 );
186 let errors_compat = infcx_compat.resolve_regions_with_outlives_env(&outlives_env);
187 if errors_compat.is_empty() {
188 Ok(())
189 } else {
190 Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
191 }
192 } else {
193 Err(infcx.err_ctxt().report_region_errors(body_def_id, &errors))
194 }
195}
196
197fn check_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
198 let node = tcx.hir_node_by_def_id(def_id);
199 let mut res = match node {
200 hir::Node::Crate(_) => bug!("check_well_formed cannot be applied to the crate root"),
201 hir::Node::Item(item) => check_item(tcx, item),
202 hir::Node::TraitItem(item) => check_trait_item(tcx, item),
203 hir::Node::ImplItem(item) => check_impl_item(tcx, item),
204 hir::Node::ForeignItem(item) => check_foreign_item(tcx, item),
205 hir::Node::OpaqueTy(_) => Ok(crate::check::check::check_item_type(tcx, def_id)),
206 _ => unreachable!(),
207 };
208
209 if let Some(generics) = node.generics() {
210 for param in generics.params {
211 res = res.and(check_param_wf(tcx, param));
212 }
213 }
214
215 res
216}
217
218#[instrument(skip(tcx), level = "debug")]
232fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) -> Result<(), ErrorGuaranteed> {
233 let def_id = item.owner_id.def_id;
234
235 debug!(
236 ?item.owner_id,
237 item.name = ? tcx.def_path_str(def_id)
238 );
239 CollectItemTypesVisitor { tcx }.visit_item(item);
240
241 let res = match item.kind {
242 hir::ItemKind::Impl(impl_) => {
260 let header = tcx.impl_trait_header(def_id);
261 let is_auto = header
262 .is_some_and(|header| tcx.trait_is_auto(header.trait_ref.skip_binder().def_id));
263
264 crate::impl_wf_check::check_impl_wf(tcx, def_id)?;
265 let mut res = Ok(());
266 if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
267 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
268 res = Err(tcx
269 .dcx()
270 .struct_span_err(sp, "impls of auto traits cannot be default")
271 .with_span_labels(impl_.defaultness_span, "default because of this")
272 .with_span_label(sp, "auto trait")
273 .emit());
274 }
275 match header.map(|h| h.polarity) {
277 Some(ty::ImplPolarity::Positive) | None => {
279 res = res.and(check_impl(tcx, item, impl_.self_ty, &impl_.of_trait));
280 }
281 Some(ty::ImplPolarity::Negative) => {
282 let ast::ImplPolarity::Negative(span) = impl_.polarity else {
283 bug!("impl_polarity query disagrees with impl's polarity in HIR");
284 };
285 if let hir::Defaultness::Default { .. } = impl_.defaultness {
287 let mut spans = vec![span];
288 spans.extend(impl_.defaultness_span);
289 res = Err(struct_span_code_err!(
290 tcx.dcx(),
291 spans,
292 E0750,
293 "negative impls cannot be default impls"
294 )
295 .emit());
296 }
297 }
298 Some(ty::ImplPolarity::Reservation) => {
299 }
301 }
302 res
303 }
304 hir::ItemKind::Fn { sig, .. } => {
305 check_item_fn(tcx, def_id, item.ident, item.span, sig.decl)
306 }
307 hir::ItemKind::Static(ty, ..) => {
308 check_item_type(tcx, def_id, ty.span, UnsizedHandling::Forbid)
309 }
310 hir::ItemKind::Const(ty, ..) => {
311 check_item_type(tcx, def_id, ty.span, UnsizedHandling::Forbid)
312 }
313 hir::ItemKind::Struct(_, hir_generics) => {
314 let res = check_type_defn(tcx, item, false);
315 check_variances_for_type_defn(tcx, item, hir_generics);
316 res
317 }
318 hir::ItemKind::Union(_, hir_generics) => {
319 let res = check_type_defn(tcx, item, true);
320 check_variances_for_type_defn(tcx, item, hir_generics);
321 res
322 }
323 hir::ItemKind::Enum(_, hir_generics) => {
324 let res = check_type_defn(tcx, item, true);
325 check_variances_for_type_defn(tcx, item, hir_generics);
326 res
327 }
328 hir::ItemKind::Trait(..) => check_trait(tcx, item),
329 hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
330 hir::ItemKind::ForeignMod { .. } => Ok(()),
332 hir::ItemKind::TyAlias(hir_ty, hir_generics) if tcx.type_alias_is_lazy(item.owner_id) => {
333 let res = enter_wf_checking_ctxt(tcx, item.span, def_id, |wfcx| {
334 let ty = tcx.type_of(def_id).instantiate_identity();
335 let item_ty = wfcx.normalize(hir_ty.span, Some(WellFormedLoc::Ty(def_id)), ty);
336 wfcx.register_wf_obligation(
337 hir_ty.span,
338 Some(WellFormedLoc::Ty(def_id)),
339 item_ty.into(),
340 );
341 check_where_clauses(wfcx, item.span, def_id);
342 Ok(())
343 });
344 check_variances_for_type_defn(tcx, item, hir_generics);
345 res
346 }
347 _ => Ok(()),
348 };
349
350 crate::check::check::check_item_type(tcx, def_id);
351
352 res
353}
354
355fn check_foreign_item<'tcx>(
356 tcx: TyCtxt<'tcx>,
357 item: &'tcx hir::ForeignItem<'tcx>,
358) -> Result<(), ErrorGuaranteed> {
359 let def_id = item.owner_id.def_id;
360
361 CollectItemTypesVisitor { tcx }.visit_foreign_item(item);
362
363 debug!(
364 ?item.owner_id,
365 item.name = ? tcx.def_path_str(def_id)
366 );
367
368 match item.kind {
369 hir::ForeignItemKind::Fn(sig, ..) => {
370 check_item_fn(tcx, def_id, item.ident, item.span, sig.decl)
371 }
372 hir::ForeignItemKind::Static(ty, ..) => {
373 check_item_type(tcx, def_id, ty.span, UnsizedHandling::AllowIfForeignTail)
374 }
375 hir::ForeignItemKind::Type => Ok(()),
376 }
377}
378
379fn check_trait_item<'tcx>(
380 tcx: TyCtxt<'tcx>,
381 trait_item: &'tcx hir::TraitItem<'tcx>,
382) -> Result<(), ErrorGuaranteed> {
383 let def_id = trait_item.owner_id.def_id;
384
385 CollectItemTypesVisitor { tcx }.visit_trait_item(trait_item);
386
387 let (method_sig, span) = match trait_item.kind {
388 hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
389 hir::TraitItemKind::Type(_bounds, Some(ty)) => (None, ty.span),
390 _ => (None, trait_item.span),
391 };
392
393 check_dyn_incompatible_self_trait_by_name(tcx, trait_item);
394
395 lint_item_shadowing_supertrait_item(tcx, def_id);
397
398 let mut res = check_associated_item(tcx, def_id, span, method_sig);
399
400 if matches!(trait_item.kind, hir::TraitItemKind::Fn(..)) {
401 for &assoc_ty_def_id in tcx.associated_types_for_impl_traits_in_associated_fn(def_id) {
402 res = res.and(check_associated_item(
403 tcx,
404 assoc_ty_def_id.expect_local(),
405 tcx.def_span(assoc_ty_def_id),
406 None,
407 ));
408 }
409 }
410 res
411}
412
413fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
426 let mut required_bounds_by_item = FxIndexMap::default();
428 let associated_items = tcx.associated_items(trait_def_id);
429
430 loop {
436 let mut should_continue = false;
437 for gat_item in associated_items.in_definition_order() {
438 let gat_def_id = gat_item.def_id.expect_local();
439 let gat_item = tcx.associated_item(gat_def_id);
440 if gat_item.kind != ty::AssocKind::Type {
442 continue;
443 }
444 let gat_generics = tcx.generics_of(gat_def_id);
445 if gat_generics.is_own_empty() {
447 continue;
448 }
449
450 let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
454 for item in associated_items.in_definition_order() {
455 let item_def_id = item.def_id.expect_local();
456 if item_def_id == gat_def_id {
458 continue;
459 }
460
461 let param_env = tcx.param_env(item_def_id);
462
463 let item_required_bounds = match tcx.associated_item(item_def_id).kind {
464 ty::AssocKind::Fn => {
466 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
470 item_def_id.to_def_id(),
471 tcx.fn_sig(item_def_id).instantiate_identity(),
472 );
473 gather_gat_bounds(
474 tcx,
475 param_env,
476 item_def_id,
477 sig.inputs_and_output,
478 &sig.inputs().iter().copied().collect(),
481 gat_def_id,
482 gat_generics,
483 )
484 }
485 ty::AssocKind::Type => {
487 let param_env = augment_param_env(
491 tcx,
492 param_env,
493 required_bounds_by_item.get(&item_def_id),
494 );
495 gather_gat_bounds(
496 tcx,
497 param_env,
498 item_def_id,
499 tcx.explicit_item_bounds(item_def_id)
500 .iter_identity_copied()
501 .collect::<Vec<_>>(),
502 &FxIndexSet::default(),
503 gat_def_id,
504 gat_generics,
505 )
506 }
507 ty::AssocKind::Const => None,
508 };
509
510 if let Some(item_required_bounds) = item_required_bounds {
511 if let Some(new_required_bounds) = &mut new_required_bounds {
517 new_required_bounds.retain(|b| item_required_bounds.contains(b));
518 } else {
519 new_required_bounds = Some(item_required_bounds);
520 }
521 }
522 }
523
524 if let Some(new_required_bounds) = new_required_bounds {
525 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
526 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
527 should_continue = true;
530 }
531 }
532 }
533 if !should_continue {
538 break;
539 }
540 }
541
542 for (gat_def_id, required_bounds) in required_bounds_by_item {
543 if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
545 continue;
546 }
547
548 let gat_item_hir = tcx.hir().expect_trait_item(gat_def_id);
549 debug!(?required_bounds);
550 let param_env = tcx.param_env(gat_def_id);
551
552 let unsatisfied_bounds: Vec<_> = required_bounds
553 .into_iter()
554 .filter(|clause| match clause.kind().skip_binder() {
555 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
556 !region_known_to_outlive(
557 tcx,
558 gat_def_id,
559 param_env,
560 &FxIndexSet::default(),
561 a,
562 b,
563 )
564 }
565 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
566 !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
567 }
568 _ => bug!("Unexpected ClauseKind"),
569 })
570 .map(|clause| clause.to_string())
571 .collect();
572
573 if !unsatisfied_bounds.is_empty() {
574 let plural = pluralize!(unsatisfied_bounds.len());
575 let suggestion = format!(
576 "{} {}",
577 gat_item_hir.generics.add_where_or_trailing_comma(),
578 unsatisfied_bounds.join(", "),
579 );
580 let bound =
581 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
582 tcx.dcx()
583 .struct_span_err(
584 gat_item_hir.span,
585 format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
586 )
587 .with_span_suggestion(
588 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
589 format!("add the required where clause{plural}"),
590 suggestion,
591 Applicability::MachineApplicable,
592 )
593 .with_note(format!(
594 "{bound} currently required to ensure that impls have maximum flexibility"
595 ))
596 .with_note(
597 "we are soliciting feedback, see issue #87479 \
598 <https://github.com/rust-lang/rust/issues/87479> for more information",
599 )
600 .emit();
601 }
602 }
603}
604
605fn augment_param_env<'tcx>(
607 tcx: TyCtxt<'tcx>,
608 param_env: ty::ParamEnv<'tcx>,
609 new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
610) -> ty::ParamEnv<'tcx> {
611 let Some(new_predicates) = new_predicates else {
612 return param_env;
613 };
614
615 if new_predicates.is_empty() {
616 return param_env;
617 }
618
619 let bounds = tcx.mk_clauses_from_iter(
620 param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
621 );
622 ty::ParamEnv::new(bounds)
625}
626
627fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
638 tcx: TyCtxt<'tcx>,
639 param_env: ty::ParamEnv<'tcx>,
640 item_def_id: LocalDefId,
641 to_check: T,
642 wf_tys: &FxIndexSet<Ty<'tcx>>,
643 gat_def_id: LocalDefId,
644 gat_generics: &'tcx ty::Generics,
645) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
646 let mut bounds = FxIndexSet::default();
648
649 let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
650
651 if types.is_empty() && regions.is_empty() {
657 return None;
658 }
659
660 for (region_a, region_a_idx) in ®ions {
661 if let ty::ReStatic | ty::ReError(_) = **region_a {
665 continue;
666 }
667 for (ty, ty_idx) in &types {
672 if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
674 debug!(?ty_idx, ?region_a_idx);
675 debug!("required clause: {ty} must outlive {region_a}");
676 let ty_param = gat_generics.param_at(*ty_idx, tcx);
680 let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
681 let region_param = gat_generics.param_at(*region_a_idx, tcx);
684 let region_param = ty::Region::new_early_param(
685 tcx,
686 ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
687 );
688 bounds.insert(
691 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
692 .upcast(tcx),
693 );
694 }
695 }
696
697 for (region_b, region_b_idx) in ®ions {
702 if matches!(**region_b, ty::ReStatic | ty::ReError(_)) || region_a == region_b {
706 continue;
707 }
708 if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
709 debug!(?region_a_idx, ?region_b_idx);
710 debug!("required clause: {region_a} must outlive {region_b}");
711 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
713 let region_a_param = ty::Region::new_early_param(
714 tcx,
715 ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
716 );
717 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
719 let region_b_param = ty::Region::new_early_param(
720 tcx,
721 ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
722 );
723 bounds.insert(
725 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
726 region_a_param,
727 region_b_param,
728 ))
729 .upcast(tcx),
730 );
731 }
732 }
733 }
734
735 Some(bounds)
736}
737
738fn ty_known_to_outlive<'tcx>(
741 tcx: TyCtxt<'tcx>,
742 id: LocalDefId,
743 param_env: ty::ParamEnv<'tcx>,
744 wf_tys: &FxIndexSet<Ty<'tcx>>,
745 ty: Ty<'tcx>,
746 region: ty::Region<'tcx>,
747) -> bool {
748 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
749 infcx.register_region_obligation(infer::RegionObligation {
750 sub_region: region,
751 sup_type: ty,
752 origin: infer::RelateParamBound(DUMMY_SP, ty, None),
753 });
754 })
755}
756
757fn region_known_to_outlive<'tcx>(
760 tcx: TyCtxt<'tcx>,
761 id: LocalDefId,
762 param_env: ty::ParamEnv<'tcx>,
763 wf_tys: &FxIndexSet<Ty<'tcx>>,
764 region_a: ty::Region<'tcx>,
765 region_b: ty::Region<'tcx>,
766) -> bool {
767 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
768 infcx.sub_regions(infer::RelateRegionParamBound(DUMMY_SP, None), region_b, region_a);
769 })
770}
771
772fn test_region_obligations<'tcx>(
776 tcx: TyCtxt<'tcx>,
777 id: LocalDefId,
778 param_env: ty::ParamEnv<'tcx>,
779 wf_tys: &FxIndexSet<Ty<'tcx>>,
780 add_constraints: impl FnOnce(&InferCtxt<'tcx>),
781) -> bool {
782 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
786
787 add_constraints(&infcx);
788
789 let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
790 debug!(?errors, "errors");
791
792 errors.is_empty()
795}
796
797struct GATArgsCollector<'tcx> {
802 gat: DefId,
803 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
805 types: FxIndexSet<(Ty<'tcx>, usize)>,
807}
808
809impl<'tcx> GATArgsCollector<'tcx> {
810 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
811 gat: DefId,
812 t: T,
813 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
814 let mut visitor =
815 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
816 t.visit_with(&mut visitor);
817 (visitor.regions, visitor.types)
818 }
819}
820
821impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
822 fn visit_ty(&mut self, t: Ty<'tcx>) {
823 match t.kind() {
824 ty::Alias(ty::Projection, p) if p.def_id == self.gat => {
825 for (idx, arg) in p.args.iter().enumerate() {
826 match arg.unpack() {
827 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
828 self.regions.insert((lt, idx));
829 }
830 GenericArgKind::Type(t) => {
831 self.types.insert((t, idx));
832 }
833 _ => {}
834 }
835 }
836 }
837 _ => {}
838 }
839 t.super_visit_with(self)
840 }
841}
842
843fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
844 match ty.kind {
845 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
846 [s] => s.res.opt_def_id() == Some(trait_def_id.to_def_id()),
847 _ => false,
848 },
849 _ => false,
850 }
851}
852
853fn check_dyn_incompatible_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
857 let (trait_name, trait_def_id) =
858 match tcx.hir_node_by_def_id(tcx.hir().get_parent_item(item.hir_id()).def_id) {
859 hir::Node::Item(item) => match item.kind {
860 hir::ItemKind::Trait(..) => (item.ident, item.owner_id),
861 _ => return,
862 },
863 _ => return,
864 };
865 let mut trait_should_be_self = vec![];
866 match &item.kind {
867 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
868 if could_be_self(trait_def_id.def_id, ty) =>
869 {
870 trait_should_be_self.push(ty.span)
871 }
872 hir::TraitItemKind::Fn(sig, _) => {
873 for ty in sig.decl.inputs {
874 if could_be_self(trait_def_id.def_id, ty) {
875 trait_should_be_self.push(ty.span);
876 }
877 }
878 match sig.decl.output {
879 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id.def_id, ty) => {
880 trait_should_be_self.push(ty.span);
881 }
882 _ => {}
883 }
884 }
885 _ => {}
886 }
887 if !trait_should_be_self.is_empty() {
888 if tcx.is_dyn_compatible(trait_def_id) {
889 return;
890 }
891 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
892 tcx.dcx()
893 .struct_span_err(
894 trait_should_be_self,
895 "associated item referring to unboxed trait object for its own trait",
896 )
897 .with_span_label(trait_name.span, "in this trait")
898 .with_multipart_suggestion(
899 "you might have meant to use `Self` to refer to the implementing type",
900 sugg,
901 Applicability::MachineApplicable,
902 )
903 .emit();
904 }
905}
906
907fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
908 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
909 let trait_def_id = tcx.local_parent(trait_item_def_id);
910
911 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
912 .skip(1)
913 .flat_map(|supertrait_def_id| {
914 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
915 })
916 .collect();
917 if !shadowed.is_empty() {
918 let shadowee = if let [shadowed] = shadowed[..] {
919 errors::SupertraitItemShadowee::Labeled {
920 span: tcx.def_span(shadowed.def_id),
921 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
922 }
923 } else {
924 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
925 .iter()
926 .map(|item| {
927 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
928 })
929 .unzip();
930 errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
931 };
932
933 tcx.emit_node_span_lint(
934 SUPERTRAIT_ITEM_SHADOWING_DEFINITION,
935 tcx.local_def_id_to_hir_id(trait_item_def_id),
936 tcx.def_span(trait_item_def_id),
937 errors::SupertraitItemShadowing {
938 item: item_name,
939 subtrait: tcx.item_name(trait_def_id.to_def_id()),
940 shadowee,
941 },
942 );
943 }
944}
945
946fn check_impl_item<'tcx>(
947 tcx: TyCtxt<'tcx>,
948 impl_item: &'tcx hir::ImplItem<'tcx>,
949) -> Result<(), ErrorGuaranteed> {
950 CollectItemTypesVisitor { tcx }.visit_impl_item(impl_item);
951
952 let (method_sig, span) = match impl_item.kind {
953 hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
954 hir::ImplItemKind::Type(ty) if ty.span != DUMMY_SP => (None, ty.span),
956 _ => (None, impl_item.span),
957 };
958 check_associated_item(tcx, impl_item.owner_id.def_id, span, method_sig)
959}
960
961fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) -> Result<(), ErrorGuaranteed> {
962 match param.kind {
963 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => Ok(()),
965
966 hir::GenericParamKind::Const { ty: hir_ty, default: _, synthetic: _ } => {
968 let ty = tcx.type_of(param.def_id).instantiate_identity();
969
970 if tcx.features().unsized_const_params() {
971 enter_wf_checking_ctxt(tcx, hir_ty.span, param.def_id, |wfcx| {
972 wfcx.register_bound(
973 ObligationCause::new(
974 hir_ty.span,
975 param.def_id,
976 ObligationCauseCode::ConstParam(ty),
977 ),
978 wfcx.param_env,
979 ty,
980 tcx.require_lang_item(LangItem::UnsizedConstParamTy, Some(hir_ty.span)),
981 );
982 Ok(())
983 })
984 } else if tcx.features().adt_const_params() {
985 enter_wf_checking_ctxt(tcx, hir_ty.span, param.def_id, |wfcx| {
986 wfcx.register_bound(
987 ObligationCause::new(
988 hir_ty.span,
989 param.def_id,
990 ObligationCauseCode::ConstParam(ty),
991 ),
992 wfcx.param_env,
993 ty,
994 tcx.require_lang_item(LangItem::ConstParamTy, Some(hir_ty.span)),
995 );
996 Ok(())
997 })
998 } else {
999 let mut diag = match ty.kind() {
1000 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
1001 ty::FnPtr(..) => tcx.dcx().struct_span_err(
1002 hir_ty.span,
1003 "using function pointers as const generic parameters is forbidden",
1004 ),
1005 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
1006 hir_ty.span,
1007 "using raw pointers as const generic parameters is forbidden",
1008 ),
1009 _ => {
1010 ty.error_reported()?;
1012
1013 tcx.dcx().struct_span_err(
1014 hir_ty.span,
1015 format!(
1016 "`{ty}` is forbidden as the type of a const generic parameter",
1017 ),
1018 )
1019 }
1020 };
1021
1022 diag.note("the only supported types are integers, `bool`, and `char`");
1023
1024 let cause = ObligationCause::misc(hir_ty.span, param.def_id);
1025 let adt_const_params_feature_string =
1026 " more complex and user defined types".to_string();
1027 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
1028 tcx,
1029 tcx.param_env(param.def_id),
1030 ty,
1031 LangItem::ConstParamTy,
1032 cause,
1033 ) {
1034 Err(
1036 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
1037 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
1038 ) => None,
1039 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
1040 Some(vec![
1041 (adt_const_params_feature_string, sym::adt_const_params),
1042 (
1043 " references to implement the `ConstParamTy` trait".into(),
1044 sym::unsized_const_params,
1045 ),
1046 ])
1047 }
1048 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
1051 fn ty_is_local(ty: Ty<'_>) -> bool {
1052 match ty.kind() {
1053 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
1054 ty::Array(ty, ..) => ty_is_local(*ty),
1056 ty::Slice(ty) => ty_is_local(*ty),
1057 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
1060 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
1063 _ => false,
1064 }
1065 }
1066
1067 ty_is_local(ty).then_some(vec![(
1068 adt_const_params_feature_string,
1069 sym::adt_const_params,
1070 )])
1071 }
1072 Ok(..) => Some(vec![(adt_const_params_feature_string, sym::adt_const_params)]),
1074 };
1075 if let Some(features) = may_suggest_feature {
1076 tcx.disabled_nightly_features(&mut diag, Some(param.hir_id), features);
1077 }
1078
1079 Err(diag.emit())
1080 }
1081 }
1082 }
1083}
1084
1085#[instrument(level = "debug", skip(tcx, span, sig_if_method))]
1086fn check_associated_item(
1087 tcx: TyCtxt<'_>,
1088 item_id: LocalDefId,
1089 span: Span,
1090 sig_if_method: Option<&hir::FnSig<'_>>,
1091) -> Result<(), ErrorGuaranteed> {
1092 let loc = Some(WellFormedLoc::Ty(item_id));
1093 enter_wf_checking_ctxt(tcx, span, item_id, |wfcx| {
1094 let item = tcx.associated_item(item_id);
1095
1096 tcx.ensure_ok()
1099 .coherent_trait(tcx.parent(item.trait_item_def_id.unwrap_or(item_id.into())))?;
1100
1101 let self_ty = match item.container {
1102 ty::AssocItemContainer::Trait => tcx.types.self_param,
1103 ty::AssocItemContainer::Impl => {
1104 tcx.type_of(item.container_id(tcx)).instantiate_identity()
1105 }
1106 };
1107
1108 match item.kind {
1109 ty::AssocKind::Const => {
1110 let ty = tcx.type_of(item.def_id).instantiate_identity();
1111 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1112 wfcx.register_wf_obligation(span, loc, ty.into());
1113 Ok(())
1114 }
1115 ty::AssocKind::Fn => {
1116 let sig = tcx.fn_sig(item.def_id).instantiate_identity();
1117 let hir_sig = sig_if_method.expect("bad signature for method");
1118 check_fn_or_method(
1119 wfcx,
1120 item.ident(tcx).span,
1121 sig,
1122 hir_sig.decl,
1123 item.def_id.expect_local(),
1124 );
1125 check_method_receiver(wfcx, hir_sig, item, self_ty)
1126 }
1127 ty::AssocKind::Type => {
1128 if let ty::AssocItemContainer::Trait = item.container {
1129 check_associated_type_bounds(wfcx, item, span)
1130 }
1131 if item.defaultness(tcx).has_value() {
1132 let ty = tcx.type_of(item.def_id).instantiate_identity();
1133 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1134 wfcx.register_wf_obligation(span, loc, ty.into());
1135 }
1136 Ok(())
1137 }
1138 }
1139 })
1140}
1141
1142fn check_type_defn<'tcx>(
1144 tcx: TyCtxt<'tcx>,
1145 item: &hir::Item<'tcx>,
1146 all_sized: bool,
1147) -> Result<(), ErrorGuaranteed> {
1148 let _ = tcx.representability(item.owner_id.def_id);
1149 let adt_def = tcx.adt_def(item.owner_id);
1150
1151 enter_wf_checking_ctxt(tcx, item.span, item.owner_id.def_id, |wfcx| {
1152 let variants = adt_def.variants();
1153 let packed = adt_def.repr().packed();
1154
1155 for variant in variants.iter() {
1156 for field in &variant.fields {
1158 if let Some(def_id) = field.value
1159 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1160 {
1161 if let Some(def_id) = def_id.as_local()
1164 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1165 && let expr = &tcx.hir().body(anon.body).value
1166 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1167 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1168 {
1169 } else {
1172 let _ = tcx.const_eval_poly(def_id);
1175 }
1176 }
1177 let field_id = field.did.expect_local();
1178 let hir::FieldDef { ty: hir_ty, .. } =
1179 tcx.hir_node_by_def_id(field_id).expect_field();
1180 let ty = wfcx.normalize(
1181 hir_ty.span,
1182 None,
1183 tcx.type_of(field.did).instantiate_identity(),
1184 );
1185 wfcx.register_wf_obligation(
1186 hir_ty.span,
1187 Some(WellFormedLoc::Ty(field_id)),
1188 ty.into(),
1189 )
1190 }
1191
1192 let needs_drop_copy = || {
1195 packed && {
1196 let ty = tcx.type_of(variant.tail().did).instantiate_identity();
1197 let ty = tcx.erase_regions(ty);
1198 assert!(!ty.has_infer());
1199 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1200 }
1201 };
1202 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1204 let unsized_len = if all_sized { 0 } else { 1 };
1205 for (idx, field) in
1206 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1207 {
1208 let last = idx == variant.fields.len() - 1;
1209 let field_id = field.did.expect_local();
1210 let hir::FieldDef { ty: hir_ty, .. } =
1211 tcx.hir_node_by_def_id(field_id).expect_field();
1212 let ty = wfcx.normalize(
1213 hir_ty.span,
1214 None,
1215 tcx.type_of(field.did).instantiate_identity(),
1216 );
1217 wfcx.register_bound(
1218 traits::ObligationCause::new(
1219 hir_ty.span,
1220 wfcx.body_def_id,
1221 ObligationCauseCode::FieldSized {
1222 adt_kind: match &item.kind {
1223 ItemKind::Struct(..) => AdtKind::Struct,
1224 ItemKind::Union(..) => AdtKind::Union,
1225 ItemKind::Enum(..) => AdtKind::Enum,
1226 kind => span_bug!(
1227 item.span,
1228 "should be wfchecking an ADT, got {kind:?}"
1229 ),
1230 },
1231 span: hir_ty.span,
1232 last,
1233 },
1234 ),
1235 wfcx.param_env,
1236 ty,
1237 tcx.require_lang_item(LangItem::Sized, None),
1238 );
1239 }
1240
1241 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1243 match tcx.const_eval_poly(discr_def_id) {
1244 Ok(_) => {}
1245 Err(ErrorHandled::Reported(..)) => {}
1246 Err(ErrorHandled::TooGeneric(sp)) => {
1247 span_bug!(sp, "enum variant discr was too generic to eval")
1248 }
1249 }
1250 }
1251 }
1252
1253 check_where_clauses(wfcx, item.span, item.owner_id.def_id);
1254 Ok(())
1255 })
1256}
1257
1258#[instrument(skip(tcx, item))]
1259fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1260 debug!(?item.owner_id);
1261
1262 let def_id = item.owner_id.def_id;
1263 let trait_def = tcx.trait_def(def_id);
1264 if trait_def.is_marker
1265 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1266 {
1267 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1268 struct_span_code_err!(
1269 tcx.dcx(),
1270 tcx.def_span(*associated_def_id),
1271 E0714,
1272 "marker traits cannot have associated items",
1273 )
1274 .emit();
1275 }
1276 }
1277
1278 let res = enter_wf_checking_ctxt(tcx, item.span, def_id, |wfcx| {
1279 check_where_clauses(wfcx, item.span, def_id);
1280 Ok(())
1281 });
1282
1283 if let hir::ItemKind::Trait(..) = item.kind {
1285 check_gat_where_clauses(tcx, item.owner_id.def_id);
1286 }
1287 res
1288}
1289
1290fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, span: Span) {
1295 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1296
1297 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1298 let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
1299 let normalized_bound = wfcx.normalize(span, None, bound);
1300 traits::wf::clause_obligations(
1301 wfcx.infcx,
1302 wfcx.param_env,
1303 wfcx.body_def_id,
1304 normalized_bound,
1305 bound_span,
1306 )
1307 });
1308
1309 wfcx.register_obligations(wf_obligations);
1310}
1311
1312fn check_item_fn(
1313 tcx: TyCtxt<'_>,
1314 def_id: LocalDefId,
1315 ident: Ident,
1316 span: Span,
1317 decl: &hir::FnDecl<'_>,
1318) -> Result<(), ErrorGuaranteed> {
1319 enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| {
1320 let sig = tcx.fn_sig(def_id).instantiate_identity();
1321 check_fn_or_method(wfcx, ident.span, sig, decl, def_id);
1322 Ok(())
1323 })
1324}
1325
1326enum UnsizedHandling {
1327 Forbid,
1328 AllowIfForeignTail,
1329}
1330
1331fn check_item_type(
1332 tcx: TyCtxt<'_>,
1333 item_id: LocalDefId,
1334 ty_span: Span,
1335 unsized_handling: UnsizedHandling,
1336) -> Result<(), ErrorGuaranteed> {
1337 debug!("check_item_type: {:?}", item_id);
1338
1339 enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| {
1340 let ty = tcx.type_of(item_id).instantiate_identity();
1341 let item_ty = wfcx.normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty);
1342
1343 let forbid_unsized = match unsized_handling {
1344 UnsizedHandling::Forbid => true,
1345 UnsizedHandling::AllowIfForeignTail => {
1346 let tail =
1347 tcx.struct_tail_for_codegen(item_ty, wfcx.infcx.typing_env(wfcx.param_env));
1348 !matches!(tail.kind(), ty::Foreign(_))
1349 }
1350 };
1351
1352 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1353 if forbid_unsized {
1354 wfcx.register_bound(
1355 traits::ObligationCause::new(
1356 ty_span,
1357 wfcx.body_def_id,
1358 ObligationCauseCode::WellFormed(None),
1359 ),
1360 wfcx.param_env,
1361 item_ty,
1362 tcx.require_lang_item(LangItem::Sized, None),
1363 );
1364 }
1365
1366 let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1368 == Some(hir::Mutability::Not)
1369 && !tcx.is_foreign_item(item_id.to_def_id())
1370 && !tcx.is_thread_local_static(item_id.to_def_id());
1371
1372 if should_check_for_sync {
1373 wfcx.register_bound(
1374 traits::ObligationCause::new(
1375 ty_span,
1376 wfcx.body_def_id,
1377 ObligationCauseCode::SharedStatic,
1378 ),
1379 wfcx.param_env,
1380 item_ty,
1381 tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
1382 );
1383 }
1384 Ok(())
1385 })
1386}
1387
1388#[instrument(level = "debug", skip(tcx, hir_self_ty, hir_trait_ref))]
1389fn check_impl<'tcx>(
1390 tcx: TyCtxt<'tcx>,
1391 item: &'tcx hir::Item<'tcx>,
1392 hir_self_ty: &hir::Ty<'_>,
1393 hir_trait_ref: &Option<hir::TraitRef<'_>>,
1394) -> Result<(), ErrorGuaranteed> {
1395 enter_wf_checking_ctxt(tcx, item.span, item.owner_id.def_id, |wfcx| {
1396 match hir_trait_ref {
1397 Some(hir_trait_ref) => {
1398 let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().instantiate_identity();
1402 tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1405 let trait_span = hir_trait_ref.path.span;
1406 let trait_ref = wfcx.normalize(
1407 trait_span,
1408 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1409 trait_ref,
1410 );
1411 let trait_pred =
1412 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1413 let mut obligations = traits::wf::trait_obligations(
1414 wfcx.infcx,
1415 wfcx.param_env,
1416 wfcx.body_def_id,
1417 trait_pred,
1418 trait_span,
1419 item,
1420 );
1421 for obligation in &mut obligations {
1422 if obligation.cause.span != trait_span {
1423 continue;
1425 }
1426 if let Some(pred) = obligation.predicate.as_trait_clause()
1427 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1428 {
1429 obligation.cause.span = hir_self_ty.span;
1430 }
1431 if let Some(pred) = obligation.predicate.as_projection_clause()
1432 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1433 {
1434 obligation.cause.span = hir_self_ty.span;
1435 }
1436 }
1437
1438 if tcx.is_conditionally_const(item.owner_id.def_id) {
1440 for (bound, _) in
1441 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1442 {
1443 let bound = wfcx.normalize(
1444 item.span,
1445 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1446 bound,
1447 );
1448 wfcx.register_obligation(Obligation::new(
1449 tcx,
1450 ObligationCause::new(
1451 hir_self_ty.span,
1452 wfcx.body_def_id,
1453 ObligationCauseCode::WellFormed(None),
1454 ),
1455 wfcx.param_env,
1456 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1457 ))
1458 }
1459 }
1460
1461 debug!(?obligations);
1462 wfcx.register_obligations(obligations);
1463 }
1464 None => {
1465 let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1466 let self_ty = wfcx.normalize(
1467 item.span,
1468 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1469 self_ty,
1470 );
1471 wfcx.register_wf_obligation(
1472 hir_self_ty.span,
1473 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1474 self_ty.into(),
1475 );
1476 }
1477 }
1478
1479 check_where_clauses(wfcx, item.span, item.owner_id.def_id);
1480 Ok(())
1481 })
1482}
1483
1484#[instrument(level = "debug", skip(wfcx))]
1486fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
1487 let infcx = wfcx.infcx;
1488 let tcx = wfcx.tcx();
1489
1490 let predicates = tcx.predicates_of(def_id.to_def_id());
1491 let generics = tcx.generics_of(def_id);
1492
1493 for param in &generics.own_params {
1500 if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1501 if !default.has_param() {
1508 wfcx.register_wf_obligation(
1509 tcx.def_span(param.def_id),
1510 matches!(param.kind, GenericParamDefKind::Type { .. })
1511 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1512 default,
1513 );
1514 }
1515 }
1516 }
1517
1518 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1527 if param.index >= generics.parent_count as u32
1528 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1530 && !default.has_param()
1532 {
1533 return default;
1535 }
1536 tcx.mk_param_from_def(param)
1537 });
1538
1539 let default_obligations = predicates
1541 .predicates
1542 .iter()
1543 .flat_map(|&(pred, sp)| {
1544 #[derive(Default)]
1545 struct CountParams {
1546 params: FxHashSet<u32>,
1547 }
1548 impl<'tcx> ty::visit::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1549 type Result = ControlFlow<()>;
1550 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1551 if let ty::Param(param) = t.kind() {
1552 self.params.insert(param.index);
1553 }
1554 t.super_visit_with(self)
1555 }
1556
1557 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1558 ControlFlow::Break(())
1559 }
1560
1561 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1562 if let ty::ConstKind::Param(param) = c.kind() {
1563 self.params.insert(param.index);
1564 }
1565 c.super_visit_with(self)
1566 }
1567 }
1568 let mut param_count = CountParams::default();
1569 let has_region = pred.visit_with(&mut param_count).is_break();
1570 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1571 if instantiated_pred.has_non_region_param()
1574 || param_count.params.len() > 1
1575 || has_region
1576 {
1577 None
1578 } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1579 None
1581 } else {
1582 Some((instantiated_pred, sp))
1583 }
1584 })
1585 .map(|(pred, sp)| {
1586 let pred = wfcx.normalize(sp, None, pred);
1596 let cause = traits::ObligationCause::new(
1597 sp,
1598 wfcx.body_def_id,
1599 ObligationCauseCode::WhereClause(def_id.to_def_id(), DUMMY_SP),
1600 );
1601 Obligation::new(tcx, cause, wfcx.param_env, pred)
1602 });
1603
1604 let predicates = predicates.instantiate_identity(tcx);
1605
1606 let predicates = wfcx.normalize(span, None, predicates);
1607
1608 debug!(?predicates.predicates);
1609 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1610 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1611 traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1612 });
1613 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1614 wfcx.register_obligations(obligations);
1615}
1616
1617#[instrument(level = "debug", skip(wfcx, span, hir_decl))]
1618fn check_fn_or_method<'tcx>(
1619 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1620 span: Span,
1621 sig: ty::PolyFnSig<'tcx>,
1622 hir_decl: &hir::FnDecl<'_>,
1623 def_id: LocalDefId,
1624) {
1625 let tcx = wfcx.tcx();
1626 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1627
1628 let arg_span =
1634 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1635
1636 sig.inputs_and_output =
1637 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1638 wfcx.normalize(
1639 arg_span(idx),
1640 Some(WellFormedLoc::Param {
1641 function: def_id,
1642 param_idx: idx,
1645 }),
1646 ty,
1647 )
1648 }));
1649
1650 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1651 wfcx.register_wf_obligation(
1652 arg_span(idx),
1653 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1654 ty.into(),
1655 );
1656 }
1657
1658 check_where_clauses(wfcx, span, def_id);
1659
1660 if sig.abi == ExternAbi::RustCall {
1661 let span = tcx.def_span(def_id);
1662 let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1663 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1664 if let Some(ty) = inputs.next() {
1666 wfcx.register_bound(
1667 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1668 wfcx.param_env,
1669 *ty,
1670 tcx.require_lang_item(hir::LangItem::Tuple, Some(span)),
1671 );
1672 wfcx.register_bound(
1673 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1674 wfcx.param_env,
1675 *ty,
1676 tcx.require_lang_item(hir::LangItem::Sized, Some(span)),
1677 );
1678 } else {
1679 tcx.dcx().span_err(
1680 hir_decl.inputs.last().map_or(span, |input| input.span),
1681 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1682 );
1683 }
1684 if inputs.next().is_some() {
1686 tcx.dcx().span_err(
1687 hir_decl.inputs.last().map_or(span, |input| input.span),
1688 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1689 );
1690 }
1691 }
1692}
1693
1694#[derive(Clone, Copy, PartialEq)]
1696enum ArbitrarySelfTypesLevel {
1697 Basic, WithPointers, }
1700
1701#[instrument(level = "debug", skip(wfcx))]
1702fn check_method_receiver<'tcx>(
1703 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1704 fn_sig: &hir::FnSig<'_>,
1705 method: ty::AssocItem,
1706 self_ty: Ty<'tcx>,
1707) -> Result<(), ErrorGuaranteed> {
1708 let tcx = wfcx.tcx();
1709
1710 if !method.fn_has_self_parameter {
1711 return Ok(());
1712 }
1713
1714 let span = fn_sig.decl.inputs[0].span;
1715
1716 let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1717 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1718 let sig = wfcx.normalize(span, None, sig);
1719
1720 debug!("check_method_receiver: sig={:?}", sig);
1721
1722 let self_ty = wfcx.normalize(span, None, self_ty);
1723
1724 let receiver_ty = sig.inputs()[0];
1725 let receiver_ty = wfcx.normalize(span, None, receiver_ty);
1726
1727 if receiver_ty.references_error() {
1730 return Ok(());
1731 }
1732
1733 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1734 Some(ArbitrarySelfTypesLevel::WithPointers)
1735 } else if tcx.features().arbitrary_self_types() {
1736 Some(ArbitrarySelfTypesLevel::Basic)
1737 } else {
1738 None
1739 };
1740 let generics = tcx.generics_of(method.def_id);
1741
1742 let receiver_validity =
1743 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1744 if let Err(receiver_validity_err) = receiver_validity {
1745 return Err(match arbitrary_self_types_level {
1746 None if receiver_is_valid(
1750 wfcx,
1751 span,
1752 receiver_ty,
1753 self_ty,
1754 Some(ArbitrarySelfTypesLevel::Basic),
1755 generics,
1756 )
1757 .is_ok() =>
1758 {
1759 feature_err(
1761 &tcx.sess,
1762 sym::arbitrary_self_types,
1763 span,
1764 format!(
1765 "`{receiver_ty}` cannot be used as the type of `self` without \
1766 the `arbitrary_self_types` feature",
1767 ),
1768 )
1769 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1770 .emit()
1771 }
1772 None | Some(ArbitrarySelfTypesLevel::Basic)
1773 if receiver_is_valid(
1774 wfcx,
1775 span,
1776 receiver_ty,
1777 self_ty,
1778 Some(ArbitrarySelfTypesLevel::WithPointers),
1779 generics,
1780 )
1781 .is_ok() =>
1782 {
1783 feature_err(
1785 &tcx.sess,
1786 sym::arbitrary_self_types_pointers,
1787 span,
1788 format!(
1789 "`{receiver_ty}` cannot be used as the type of `self` without \
1790 the `arbitrary_self_types_pointers` feature",
1791 ),
1792 )
1793 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1794 .emit()
1795 }
1796 _ =>
1797 {
1799 match receiver_validity_err {
1800 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1801 let hint = match receiver_ty
1802 .builtin_deref(false)
1803 .unwrap_or(receiver_ty)
1804 .ty_adt_def()
1805 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1806 {
1807 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1808 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1809 _ => None,
1810 };
1811
1812 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1813 }
1814 ReceiverValidityError::DoesNotDeref => {
1815 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1816 span,
1817 receiver_ty,
1818 })
1819 }
1820 ReceiverValidityError::MethodGenericParamUsed => {
1821 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1822 }
1823 }
1824 }
1825 });
1826 }
1827 Ok(())
1828}
1829
1830enum ReceiverValidityError {
1834 DoesNotDeref,
1837 MethodGenericParamUsed,
1839}
1840
1841fn confirm_type_is_not_a_method_generic_param(
1844 ty: Ty<'_>,
1845 method_generics: &ty::Generics,
1846) -> Result<(), ReceiverValidityError> {
1847 if let ty::Param(param) = ty.kind() {
1848 if (param.index as usize) >= method_generics.parent_count {
1849 return Err(ReceiverValidityError::MethodGenericParamUsed);
1850 }
1851 }
1852 Ok(())
1853}
1854
1855fn receiver_is_valid<'tcx>(
1865 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1866 span: Span,
1867 receiver_ty: Ty<'tcx>,
1868 self_ty: Ty<'tcx>,
1869 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1870 method_generics: &ty::Generics,
1871) -> Result<(), ReceiverValidityError> {
1872 let infcx = wfcx.infcx;
1873 let tcx = wfcx.tcx();
1874 let cause =
1875 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1876
1877 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1879 let ocx = ObligationCtxt::new(wfcx.infcx);
1880 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1881 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1882 }) {
1883 return Ok(());
1884 }
1885
1886 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1887
1888 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1889
1890 if arbitrary_self_types_enabled.is_some() {
1894 autoderef = autoderef.use_receiver_trait();
1895 }
1896
1897 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1899 autoderef = autoderef.include_raw_pointers();
1900 }
1901
1902 while let Some((potential_self_ty, _)) = autoderef.next() {
1904 debug!(
1905 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1906 potential_self_ty, self_ty
1907 );
1908
1909 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1910
1911 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1914 let ocx = ObligationCtxt::new(wfcx.infcx);
1915 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1916 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1917 }) {
1918 wfcx.register_obligations(autoderef.into_obligations());
1919 return Ok(());
1920 }
1921
1922 if arbitrary_self_types_enabled.is_none() {
1925 let legacy_receiver_trait_def_id =
1926 tcx.require_lang_item(LangItem::LegacyReceiver, Some(span));
1927 if !legacy_receiver_is_implemented(
1928 wfcx,
1929 legacy_receiver_trait_def_id,
1930 cause.clone(),
1931 potential_self_ty,
1932 ) {
1933 break;
1935 }
1936
1937 wfcx.register_bound(
1939 cause.clone(),
1940 wfcx.param_env,
1941 potential_self_ty,
1942 legacy_receiver_trait_def_id,
1943 );
1944 }
1945 }
1946
1947 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1948 Err(ReceiverValidityError::DoesNotDeref)
1949}
1950
1951fn legacy_receiver_is_implemented<'tcx>(
1952 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1953 legacy_receiver_trait_def_id: DefId,
1954 cause: ObligationCause<'tcx>,
1955 receiver_ty: Ty<'tcx>,
1956) -> bool {
1957 let tcx = wfcx.tcx();
1958 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1959
1960 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1961
1962 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1963 true
1964 } else {
1965 debug!(
1966 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1967 receiver_ty
1968 );
1969 false
1970 }
1971}
1972
1973fn check_variances_for_type_defn<'tcx>(
1974 tcx: TyCtxt<'tcx>,
1975 item: &'tcx hir::Item<'tcx>,
1976 hir_generics: &hir::Generics<'tcx>,
1977) {
1978 match item.kind {
1979 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1980 }
1982 ItemKind::TyAlias(..) => {
1983 assert!(
1984 tcx.type_alias_is_lazy(item.owner_id),
1985 "should not be computing variance of non-weak type alias"
1986 );
1987 }
1988 kind => span_bug!(item.span, "cannot compute the variances of {kind:?}"),
1989 }
1990
1991 let ty_predicates = tcx.predicates_of(item.owner_id);
1992 assert_eq!(ty_predicates.parent, None);
1993 let variances = tcx.variances_of(item.owner_id);
1994
1995 let mut constrained_parameters: FxHashSet<_> = variances
1996 .iter()
1997 .enumerate()
1998 .filter(|&(_, &variance)| variance != ty::Bivariant)
1999 .map(|(index, _)| Parameter(index as u32))
2000 .collect();
2001
2002 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2003
2004 let explicitly_bounded_params = LazyCell::new(|| {
2006 let icx = crate::collect::ItemCtxt::new(tcx, item.owner_id.def_id);
2007 hir_generics
2008 .predicates
2009 .iter()
2010 .filter_map(|predicate| match predicate.kind {
2011 hir::WherePredicateKind::BoundPredicate(predicate) => {
2012 match icx.lower_ty(predicate.bounded_ty).kind() {
2013 ty::Param(data) => Some(Parameter(data.index)),
2014 _ => None,
2015 }
2016 }
2017 _ => None,
2018 })
2019 .collect::<FxHashSet<_>>()
2020 });
2021
2022 let ty_generics = tcx.generics_of(item.owner_id);
2023
2024 for (index, _) in variances.iter().enumerate() {
2025 let parameter = Parameter(index as u32);
2026
2027 if constrained_parameters.contains(¶meter) {
2028 continue;
2029 }
2030
2031 let ty_param = &ty_generics.own_params[index];
2032 let hir_param = &hir_generics.params[index];
2033
2034 if ty_param.def_id != hir_param.def_id.into() {
2035 tcx.dcx().span_delayed_bug(
2043 hir_param.span,
2044 "hir generics and ty generics in different order",
2045 );
2046 continue;
2047 }
2048
2049 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2051 .type_of(item.owner_id)
2052 .instantiate_identity()
2053 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2054 {
2055 continue;
2056 }
2057
2058 match hir_param.name {
2059 hir::ParamName::Error(_) => {
2060 }
2063 _ => {
2064 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2065 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2066 }
2067 }
2068 }
2069}
2070
2071struct HasErrorDeep<'tcx> {
2073 tcx: TyCtxt<'tcx>,
2074 seen: FxHashSet<DefId>,
2075}
2076impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2077 type Result = ControlFlow<ErrorGuaranteed>;
2078
2079 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2080 match *ty.kind() {
2081 ty::Adt(def, _) => {
2082 if self.seen.insert(def.did()) {
2083 for field in def.all_fields() {
2084 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2085 }
2086 }
2087 }
2088 ty::Error(guar) => return ControlFlow::Break(guar),
2089 _ => {}
2090 }
2091 ty.super_visit_with(self)
2092 }
2093
2094 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2095 if let Err(guar) = r.error_reported() {
2096 ControlFlow::Break(guar)
2097 } else {
2098 ControlFlow::Continue(())
2099 }
2100 }
2101
2102 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2103 if let Err(guar) = c.error_reported() {
2104 ControlFlow::Break(guar)
2105 } else {
2106 ControlFlow::Continue(())
2107 }
2108 }
2109}
2110
2111fn report_bivariance<'tcx>(
2112 tcx: TyCtxt<'tcx>,
2113 param: &'tcx hir::GenericParam<'tcx>,
2114 has_explicit_bounds: bool,
2115 item: &'tcx hir::Item<'tcx>,
2116) -> ErrorGuaranteed {
2117 let param_name = param.name.ident();
2118
2119 let help = match item.kind {
2120 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2121 if let Some(def_id) = tcx.lang_items().phantom_data() {
2122 errors::UnusedGenericParameterHelp::Adt {
2123 param_name,
2124 phantom_data: tcx.def_path_str(def_id),
2125 }
2126 } else {
2127 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2128 }
2129 }
2130 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2131 item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2132 };
2133
2134 let mut usage_spans = vec![];
2135 intravisit::walk_item(
2136 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2137 item,
2138 );
2139
2140 if !usage_spans.is_empty() {
2141 let item_def_id = item.owner_id.to_def_id();
2145 let is_probably_cyclical =
2146 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2147 .visit_def(item_def_id)
2148 .is_break();
2149 if is_probably_cyclical {
2158 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2159 spans: usage_spans,
2160 param_span: param.span,
2161 param_name,
2162 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2163 help,
2164 note: (),
2165 });
2166 }
2167 }
2168
2169 let const_param_help =
2170 matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2171
2172 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2173 span: param.span,
2174 param_name,
2175 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2176 usage_spans,
2177 help,
2178 const_param_help,
2179 });
2180 diag.code(E0392);
2181 diag.emit()
2182}
2183
2184struct IsProbablyCyclical<'tcx> {
2190 tcx: TyCtxt<'tcx>,
2191 item_def_id: DefId,
2192 seen: FxHashSet<DefId>,
2193}
2194
2195impl<'tcx> IsProbablyCyclical<'tcx> {
2196 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2197 match self.tcx.def_kind(def_id) {
2198 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2199 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2200 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2201 })
2202 }
2203 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2204 self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2205 }
2206 _ => ControlFlow::Continue(()),
2207 }
2208 }
2209}
2210
2211impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2212 type Result = ControlFlow<(), ()>;
2213
2214 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2215 let def_id = match ty.kind() {
2216 ty::Adt(adt_def, _) => Some(adt_def.did()),
2217 ty::Alias(ty::Weak, alias_ty) => Some(alias_ty.def_id),
2218 _ => None,
2219 };
2220 if let Some(def_id) = def_id {
2221 if def_id == self.item_def_id {
2222 return ControlFlow::Break(());
2223 }
2224 if self.seen.insert(def_id) {
2225 self.visit_def(def_id)?;
2226 }
2227 }
2228 ty.super_visit_with(self)
2229 }
2230}
2231
2232struct CollectUsageSpans<'a> {
2237 spans: &'a mut Vec<Span>,
2238 param_def_id: DefId,
2239}
2240
2241impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2242 type Result = ();
2243
2244 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2245 }
2247
2248 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2249 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2250 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2251 && def_id == self.param_def_id
2252 {
2253 self.spans.push(t.span);
2254 return;
2255 } else if let Res::SelfTyAlias { .. } = qpath.res {
2256 self.spans.push(t.span);
2257 return;
2258 }
2259 }
2260 intravisit::walk_ty(self, t);
2261 }
2262}
2263
2264impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2265 #[instrument(level = "debug", skip(self))]
2268 fn check_false_global_bounds(&mut self) {
2269 let tcx = self.ocx.infcx.tcx;
2270 let mut span = self.span;
2271 let empty_env = ty::ParamEnv::empty();
2272
2273 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2274 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2276
2277 for (pred, obligation_span) in implied_obligations {
2278 if let ty::ClauseKind::WellFormed(..) = pred.kind().skip_binder() {
2282 continue;
2283 }
2284 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2286 let pred = self.normalize(span, None, pred);
2287
2288 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2290 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2291 span = predicates
2292 .iter()
2293 .find(|pred| pred.span.contains(obligation_span))
2295 .map(|pred| pred.span)
2296 .unwrap_or(obligation_span);
2297 }
2298
2299 let obligation = Obligation::new(
2300 tcx,
2301 traits::ObligationCause::new(
2302 span,
2303 self.body_def_id,
2304 ObligationCauseCode::TrivialBound,
2305 ),
2306 empty_env,
2307 pred,
2308 );
2309 self.ocx.register_obligation(obligation);
2310 }
2311 }
2312 }
2313}
2314
2315fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalModDefId) -> Result<(), ErrorGuaranteed> {
2316 let items = tcx.hir_module_items(module);
2317 let res = items
2318 .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2319 .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2320 .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2321 .and(
2322 items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2323 )
2324 .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2325 if module == LocalModDefId::CRATE_DEF_ID {
2326 super::entry::check_for_entry_fn(tcx);
2327 }
2328 res
2329}
2330
2331fn lint_redundant_lifetimes<'tcx>(
2332 tcx: TyCtxt<'tcx>,
2333 owner_id: LocalDefId,
2334 outlives_env: &OutlivesEnvironment<'tcx>,
2335) {
2336 let def_kind = tcx.def_kind(owner_id);
2337 match def_kind {
2338 DefKind::Struct
2339 | DefKind::Union
2340 | DefKind::Enum
2341 | DefKind::Trait
2342 | DefKind::TraitAlias
2343 | DefKind::Fn
2344 | DefKind::Const
2345 | DefKind::Impl { of_trait: _ } => {
2346 }
2348 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2349 let parent_def_id = tcx.local_parent(owner_id);
2350 if matches!(tcx.def_kind(parent_def_id), DefKind::Impl { of_trait: true }) {
2351 return;
2356 }
2357 }
2358 DefKind::Mod
2359 | DefKind::Variant
2360 | DefKind::TyAlias
2361 | DefKind::ForeignTy
2362 | DefKind::TyParam
2363 | DefKind::ConstParam
2364 | DefKind::Static { .. }
2365 | DefKind::Ctor(_, _)
2366 | DefKind::Macro(_)
2367 | DefKind::ExternCrate
2368 | DefKind::Use
2369 | DefKind::ForeignMod
2370 | DefKind::AnonConst
2371 | DefKind::InlineConst
2372 | DefKind::OpaqueTy
2373 | DefKind::Field
2374 | DefKind::LifetimeParam
2375 | DefKind::GlobalAsm
2376 | DefKind::Closure
2377 | DefKind::SyntheticCoroutineBody => return,
2378 }
2379
2380 let mut lifetimes = vec![tcx.lifetimes.re_static];
2389 lifetimes.extend(
2390 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2391 );
2392 if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2394 for (idx, var) in
2395 tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2396 {
2397 let ty::BoundVariableKind::Region(kind) = var else { continue };
2398 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2399 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2400 }
2401 }
2402 lifetimes.retain(|candidate| candidate.has_name());
2403
2404 let mut shadowed = FxHashSet::default();
2408
2409 for (idx, &candidate) in lifetimes.iter().enumerate() {
2410 if shadowed.contains(&candidate) {
2415 continue;
2416 }
2417
2418 for &victim in &lifetimes[(idx + 1)..] {
2419 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2427 continue;
2428 };
2429
2430 if tcx.parent(def_id) != owner_id.to_def_id() {
2435 continue;
2436 }
2437
2438 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2440 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2441 {
2442 shadowed.insert(victim);
2443 tcx.emit_node_span_lint(
2444 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2445 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2446 tcx.def_span(def_id),
2447 RedundantLifetimeArgsLint { candidate, victim },
2448 );
2449 }
2450 }
2451 }
2452}
2453
2454#[derive(LintDiagnostic)]
2455#[diag(hir_analysis_redundant_lifetime_args)]
2456#[note]
2457struct RedundantLifetimeArgsLint<'tcx> {
2458 victim: ty::Region<'tcx>,
2460 candidate: ty::Region<'tcx>,
2462}
2463
2464pub fn provide(providers: &mut Providers) {
2465 *providers = Providers { check_mod_type_wf, check_well_formed, ..*providers };
2466}