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 check_sized_if_body(wfcx, item.def_id.expect_local(), ty, Some(span));
1114 Ok(())
1115 }
1116 ty::AssocKind::Fn => {
1117 let sig = tcx.fn_sig(item.def_id).instantiate_identity();
1118 let hir_sig = sig_if_method.expect("bad signature for method");
1119 check_fn_or_method(
1120 wfcx,
1121 item.ident(tcx).span,
1122 sig,
1123 hir_sig.decl,
1124 item.def_id.expect_local(),
1125 );
1126 check_method_receiver(wfcx, hir_sig, item, self_ty)
1127 }
1128 ty::AssocKind::Type => {
1129 if let ty::AssocItemContainer::Trait = item.container {
1130 check_associated_type_bounds(wfcx, item, span)
1131 }
1132 if item.defaultness(tcx).has_value() {
1133 let ty = tcx.type_of(item.def_id).instantiate_identity();
1134 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1135 wfcx.register_wf_obligation(span, loc, ty.into());
1136 }
1137 Ok(())
1138 }
1139 }
1140 })
1141}
1142
1143fn check_type_defn<'tcx>(
1145 tcx: TyCtxt<'tcx>,
1146 item: &hir::Item<'tcx>,
1147 all_sized: bool,
1148) -> Result<(), ErrorGuaranteed> {
1149 let _ = tcx.representability(item.owner_id.def_id);
1150 let adt_def = tcx.adt_def(item.owner_id);
1151
1152 enter_wf_checking_ctxt(tcx, item.span, item.owner_id.def_id, |wfcx| {
1153 let variants = adt_def.variants();
1154 let packed = adt_def.repr().packed();
1155
1156 for variant in variants.iter() {
1157 for field in &variant.fields {
1159 if let Some(def_id) = field.value
1160 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1161 {
1162 if let Some(def_id) = def_id.as_local()
1165 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1166 && let expr = &tcx.hir().body(anon.body).value
1167 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1168 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1169 {
1170 } else {
1173 let _ = tcx.const_eval_poly(def_id);
1176 }
1177 }
1178 let field_id = field.did.expect_local();
1179 let hir::FieldDef { ty: hir_ty, .. } =
1180 tcx.hir_node_by_def_id(field_id).expect_field();
1181 let ty = wfcx.normalize(
1182 hir_ty.span,
1183 None,
1184 tcx.type_of(field.did).instantiate_identity(),
1185 );
1186 wfcx.register_wf_obligation(
1187 hir_ty.span,
1188 Some(WellFormedLoc::Ty(field_id)),
1189 ty.into(),
1190 )
1191 }
1192
1193 let needs_drop_copy = || {
1196 packed && {
1197 let ty = tcx.type_of(variant.tail().did).instantiate_identity();
1198 let ty = tcx.erase_regions(ty);
1199 assert!(!ty.has_infer());
1200 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1201 }
1202 };
1203 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1205 let unsized_len = if all_sized { 0 } else { 1 };
1206 for (idx, field) in
1207 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1208 {
1209 let last = idx == variant.fields.len() - 1;
1210 let field_id = field.did.expect_local();
1211 let hir::FieldDef { ty: hir_ty, .. } =
1212 tcx.hir_node_by_def_id(field_id).expect_field();
1213 let ty = wfcx.normalize(
1214 hir_ty.span,
1215 None,
1216 tcx.type_of(field.did).instantiate_identity(),
1217 );
1218 wfcx.register_bound(
1219 traits::ObligationCause::new(
1220 hir_ty.span,
1221 wfcx.body_def_id,
1222 ObligationCauseCode::FieldSized {
1223 adt_kind: match &item.kind {
1224 ItemKind::Struct(..) => AdtKind::Struct,
1225 ItemKind::Union(..) => AdtKind::Union,
1226 ItemKind::Enum(..) => AdtKind::Enum,
1227 kind => span_bug!(
1228 item.span,
1229 "should be wfchecking an ADT, got {kind:?}"
1230 ),
1231 },
1232 span: hir_ty.span,
1233 last,
1234 },
1235 ),
1236 wfcx.param_env,
1237 ty,
1238 tcx.require_lang_item(LangItem::Sized, Some(hir_ty.span)),
1239 );
1240 }
1241
1242 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1244 match tcx.const_eval_poly(discr_def_id) {
1245 Ok(_) => {}
1246 Err(ErrorHandled::Reported(..)) => {}
1247 Err(ErrorHandled::TooGeneric(sp)) => {
1248 span_bug!(sp, "enum variant discr was too generic to eval")
1249 }
1250 }
1251 }
1252 }
1253
1254 check_where_clauses(wfcx, item.span, item.owner_id.def_id);
1255 Ok(())
1256 })
1257}
1258
1259#[instrument(skip(tcx, item))]
1260fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1261 debug!(?item.owner_id);
1262
1263 let def_id = item.owner_id.def_id;
1264 let trait_def = tcx.trait_def(def_id);
1265 if trait_def.is_marker
1266 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1267 {
1268 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1269 struct_span_code_err!(
1270 tcx.dcx(),
1271 tcx.def_span(*associated_def_id),
1272 E0714,
1273 "marker traits cannot have associated items",
1274 )
1275 .emit();
1276 }
1277 }
1278
1279 let res = enter_wf_checking_ctxt(tcx, item.span, def_id, |wfcx| {
1280 check_where_clauses(wfcx, item.span, def_id);
1281 Ok(())
1282 });
1283
1284 if let hir::ItemKind::Trait(..) = item.kind {
1286 check_gat_where_clauses(tcx, item.owner_id.def_id);
1287 }
1288 res
1289}
1290
1291fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, span: Span) {
1296 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1297
1298 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1299 let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
1300 let normalized_bound = wfcx.normalize(span, None, bound);
1301 traits::wf::clause_obligations(
1302 wfcx.infcx,
1303 wfcx.param_env,
1304 wfcx.body_def_id,
1305 normalized_bound,
1306 bound_span,
1307 )
1308 });
1309
1310 wfcx.register_obligations(wf_obligations);
1311}
1312
1313fn check_item_fn(
1314 tcx: TyCtxt<'_>,
1315 def_id: LocalDefId,
1316 ident: Ident,
1317 span: Span,
1318 decl: &hir::FnDecl<'_>,
1319) -> Result<(), ErrorGuaranteed> {
1320 enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| {
1321 let sig = tcx.fn_sig(def_id).instantiate_identity();
1322 check_fn_or_method(wfcx, ident.span, sig, decl, def_id);
1323 Ok(())
1324 })
1325}
1326
1327enum UnsizedHandling {
1328 Forbid,
1329 AllowIfForeignTail,
1330}
1331
1332fn check_item_type(
1333 tcx: TyCtxt<'_>,
1334 item_id: LocalDefId,
1335 ty_span: Span,
1336 unsized_handling: UnsizedHandling,
1337) -> Result<(), ErrorGuaranteed> {
1338 debug!("check_item_type: {:?}", item_id);
1339
1340 enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| {
1341 let ty = tcx.type_of(item_id).instantiate_identity();
1342 let item_ty = wfcx.normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty);
1343
1344 let forbid_unsized = match unsized_handling {
1345 UnsizedHandling::Forbid => true,
1346 UnsizedHandling::AllowIfForeignTail => {
1347 let tail =
1348 tcx.struct_tail_for_codegen(item_ty, wfcx.infcx.typing_env(wfcx.param_env));
1349 !matches!(tail.kind(), ty::Foreign(_))
1350 }
1351 };
1352
1353 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1354 if forbid_unsized {
1355 wfcx.register_bound(
1356 traits::ObligationCause::new(
1357 ty_span,
1358 wfcx.body_def_id,
1359 ObligationCauseCode::WellFormed(None),
1360 ),
1361 wfcx.param_env,
1362 item_ty,
1363 tcx.require_lang_item(LangItem::Sized, Some(ty_span)),
1364 );
1365 }
1366
1367 let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1369 == Some(hir::Mutability::Not)
1370 && !tcx.is_foreign_item(item_id.to_def_id())
1371 && !tcx.is_thread_local_static(item_id.to_def_id());
1372
1373 if should_check_for_sync {
1374 wfcx.register_bound(
1375 traits::ObligationCause::new(
1376 ty_span,
1377 wfcx.body_def_id,
1378 ObligationCauseCode::SharedStatic,
1379 ),
1380 wfcx.param_env,
1381 item_ty,
1382 tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
1383 );
1384 }
1385 Ok(())
1386 })
1387}
1388
1389#[instrument(level = "debug", skip(tcx, hir_self_ty, hir_trait_ref))]
1390fn check_impl<'tcx>(
1391 tcx: TyCtxt<'tcx>,
1392 item: &'tcx hir::Item<'tcx>,
1393 hir_self_ty: &hir::Ty<'_>,
1394 hir_trait_ref: &Option<hir::TraitRef<'_>>,
1395) -> Result<(), ErrorGuaranteed> {
1396 enter_wf_checking_ctxt(tcx, item.span, item.owner_id.def_id, |wfcx| {
1397 match hir_trait_ref {
1398 Some(hir_trait_ref) => {
1399 let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().instantiate_identity();
1403 tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1406 let trait_span = hir_trait_ref.path.span;
1407 let trait_ref = wfcx.normalize(
1408 trait_span,
1409 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1410 trait_ref,
1411 );
1412 let trait_pred =
1413 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1414 let mut obligations = traits::wf::trait_obligations(
1415 wfcx.infcx,
1416 wfcx.param_env,
1417 wfcx.body_def_id,
1418 trait_pred,
1419 trait_span,
1420 item,
1421 );
1422 for obligation in &mut obligations {
1423 if obligation.cause.span != trait_span {
1424 continue;
1426 }
1427 if let Some(pred) = obligation.predicate.as_trait_clause()
1428 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1429 {
1430 obligation.cause.span = hir_self_ty.span;
1431 }
1432 if let Some(pred) = obligation.predicate.as_projection_clause()
1433 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1434 {
1435 obligation.cause.span = hir_self_ty.span;
1436 }
1437 }
1438
1439 if tcx.is_conditionally_const(item.owner_id.def_id) {
1441 for (bound, _) in
1442 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1443 {
1444 let bound = wfcx.normalize(
1445 item.span,
1446 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1447 bound,
1448 );
1449 wfcx.register_obligation(Obligation::new(
1450 tcx,
1451 ObligationCause::new(
1452 hir_self_ty.span,
1453 wfcx.body_def_id,
1454 ObligationCauseCode::WellFormed(None),
1455 ),
1456 wfcx.param_env,
1457 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1458 ))
1459 }
1460 }
1461
1462 debug!(?obligations);
1463 wfcx.register_obligations(obligations);
1464 }
1465 None => {
1466 let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1467 let self_ty = wfcx.normalize(
1468 item.span,
1469 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1470 self_ty,
1471 );
1472 wfcx.register_wf_obligation(
1473 hir_self_ty.span,
1474 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1475 self_ty.into(),
1476 );
1477 }
1478 }
1479
1480 check_where_clauses(wfcx, item.span, item.owner_id.def_id);
1481 Ok(())
1482 })
1483}
1484
1485#[instrument(level = "debug", skip(wfcx))]
1487fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
1488 let infcx = wfcx.infcx;
1489 let tcx = wfcx.tcx();
1490
1491 let predicates = tcx.predicates_of(def_id.to_def_id());
1492 let generics = tcx.generics_of(def_id);
1493
1494 for param in &generics.own_params {
1501 if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1502 if !default.has_param() {
1509 wfcx.register_wf_obligation(
1510 tcx.def_span(param.def_id),
1511 matches!(param.kind, GenericParamDefKind::Type { .. })
1512 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1513 default,
1514 );
1515 }
1516 }
1517 }
1518
1519 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1528 if param.index >= generics.parent_count as u32
1529 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1531 && !default.has_param()
1533 {
1534 return default;
1536 }
1537 tcx.mk_param_from_def(param)
1538 });
1539
1540 let default_obligations = predicates
1542 .predicates
1543 .iter()
1544 .flat_map(|&(pred, sp)| {
1545 #[derive(Default)]
1546 struct CountParams {
1547 params: FxHashSet<u32>,
1548 }
1549 impl<'tcx> ty::visit::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1550 type Result = ControlFlow<()>;
1551 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1552 if let ty::Param(param) = t.kind() {
1553 self.params.insert(param.index);
1554 }
1555 t.super_visit_with(self)
1556 }
1557
1558 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1559 ControlFlow::Break(())
1560 }
1561
1562 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1563 if let ty::ConstKind::Param(param) = c.kind() {
1564 self.params.insert(param.index);
1565 }
1566 c.super_visit_with(self)
1567 }
1568 }
1569 let mut param_count = CountParams::default();
1570 let has_region = pred.visit_with(&mut param_count).is_break();
1571 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1572 if instantiated_pred.has_non_region_param()
1575 || param_count.params.len() > 1
1576 || has_region
1577 {
1578 None
1579 } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1580 None
1582 } else {
1583 Some((instantiated_pred, sp))
1584 }
1585 })
1586 .map(|(pred, sp)| {
1587 let pred = wfcx.normalize(sp, None, pred);
1597 let cause = traits::ObligationCause::new(
1598 sp,
1599 wfcx.body_def_id,
1600 ObligationCauseCode::WhereClause(def_id.to_def_id(), DUMMY_SP),
1601 );
1602 Obligation::new(tcx, cause, wfcx.param_env, pred)
1603 });
1604
1605 let predicates = predicates.instantiate_identity(tcx);
1606
1607 let predicates = wfcx.normalize(span, None, predicates);
1608
1609 debug!(?predicates.predicates);
1610 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1611 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1612 traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1613 });
1614 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1615 wfcx.register_obligations(obligations);
1616}
1617
1618#[instrument(level = "debug", skip(wfcx, span, hir_decl))]
1619fn check_fn_or_method<'tcx>(
1620 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1621 span: Span,
1622 sig: ty::PolyFnSig<'tcx>,
1623 hir_decl: &hir::FnDecl<'_>,
1624 def_id: LocalDefId,
1625) {
1626 let tcx = wfcx.tcx();
1627 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1628
1629 let arg_span =
1635 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1636
1637 sig.inputs_and_output =
1638 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1639 wfcx.normalize(
1640 arg_span(idx),
1641 Some(WellFormedLoc::Param {
1642 function: def_id,
1643 param_idx: idx,
1646 }),
1647 ty,
1648 )
1649 }));
1650
1651 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1652 wfcx.register_wf_obligation(
1653 arg_span(idx),
1654 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1655 ty.into(),
1656 );
1657 }
1658
1659 check_where_clauses(wfcx, span, def_id);
1660
1661 if sig.abi == ExternAbi::RustCall {
1662 let span = tcx.def_span(def_id);
1663 let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1664 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1665 if let Some(ty) = inputs.next() {
1667 wfcx.register_bound(
1668 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1669 wfcx.param_env,
1670 *ty,
1671 tcx.require_lang_item(hir::LangItem::Tuple, Some(span)),
1672 );
1673 wfcx.register_bound(
1674 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1675 wfcx.param_env,
1676 *ty,
1677 tcx.require_lang_item(hir::LangItem::Sized, Some(span)),
1678 );
1679 } else {
1680 tcx.dcx().span_err(
1681 hir_decl.inputs.last().map_or(span, |input| input.span),
1682 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1683 );
1684 }
1685 if inputs.next().is_some() {
1687 tcx.dcx().span_err(
1688 hir_decl.inputs.last().map_or(span, |input| input.span),
1689 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1690 );
1691 }
1692 }
1693
1694 check_sized_if_body(
1696 wfcx,
1697 def_id,
1698 sig.output(),
1699 match hir_decl.output {
1700 hir::FnRetTy::Return(ty) => Some(ty.span),
1701 hir::FnRetTy::DefaultReturn(_) => None,
1702 },
1703 );
1704}
1705
1706fn check_sized_if_body<'tcx>(
1707 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1708 def_id: LocalDefId,
1709 ty: Ty<'tcx>,
1710 maybe_span: Option<Span>,
1711) {
1712 let tcx = wfcx.tcx();
1713 if let Some(body) = tcx.hir().maybe_body_owned_by(def_id) {
1714 let span = maybe_span.unwrap_or(body.value.span);
1715
1716 wfcx.register_bound(
1717 ObligationCause::new(span, def_id, traits::ObligationCauseCode::SizedReturnType),
1718 wfcx.param_env,
1719 ty,
1720 tcx.require_lang_item(LangItem::Sized, Some(span)),
1721 );
1722 }
1723}
1724
1725#[derive(Clone, Copy, PartialEq)]
1727enum ArbitrarySelfTypesLevel {
1728 Basic, WithPointers, }
1731
1732#[instrument(level = "debug", skip(wfcx))]
1733fn check_method_receiver<'tcx>(
1734 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1735 fn_sig: &hir::FnSig<'_>,
1736 method: ty::AssocItem,
1737 self_ty: Ty<'tcx>,
1738) -> Result<(), ErrorGuaranteed> {
1739 let tcx = wfcx.tcx();
1740
1741 if !method.fn_has_self_parameter {
1742 return Ok(());
1743 }
1744
1745 let span = fn_sig.decl.inputs[0].span;
1746
1747 let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1748 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1749 let sig = wfcx.normalize(span, None, sig);
1750
1751 debug!("check_method_receiver: sig={:?}", sig);
1752
1753 let self_ty = wfcx.normalize(span, None, self_ty);
1754
1755 let receiver_ty = sig.inputs()[0];
1756 let receiver_ty = wfcx.normalize(span, None, receiver_ty);
1757
1758 if receiver_ty.references_error() {
1761 return Ok(());
1762 }
1763
1764 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1765 Some(ArbitrarySelfTypesLevel::WithPointers)
1766 } else if tcx.features().arbitrary_self_types() {
1767 Some(ArbitrarySelfTypesLevel::Basic)
1768 } else {
1769 None
1770 };
1771 let generics = tcx.generics_of(method.def_id);
1772
1773 let receiver_validity =
1774 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1775 if let Err(receiver_validity_err) = receiver_validity {
1776 return Err(match arbitrary_self_types_level {
1777 None if receiver_is_valid(
1781 wfcx,
1782 span,
1783 receiver_ty,
1784 self_ty,
1785 Some(ArbitrarySelfTypesLevel::Basic),
1786 generics,
1787 )
1788 .is_ok() =>
1789 {
1790 feature_err(
1792 &tcx.sess,
1793 sym::arbitrary_self_types,
1794 span,
1795 format!(
1796 "`{receiver_ty}` cannot be used as the type of `self` without \
1797 the `arbitrary_self_types` feature",
1798 ),
1799 )
1800 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1801 .emit()
1802 }
1803 None | Some(ArbitrarySelfTypesLevel::Basic)
1804 if receiver_is_valid(
1805 wfcx,
1806 span,
1807 receiver_ty,
1808 self_ty,
1809 Some(ArbitrarySelfTypesLevel::WithPointers),
1810 generics,
1811 )
1812 .is_ok() =>
1813 {
1814 feature_err(
1816 &tcx.sess,
1817 sym::arbitrary_self_types_pointers,
1818 span,
1819 format!(
1820 "`{receiver_ty}` cannot be used as the type of `self` without \
1821 the `arbitrary_self_types_pointers` feature",
1822 ),
1823 )
1824 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1825 .emit()
1826 }
1827 _ =>
1828 {
1830 match receiver_validity_err {
1831 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1832 let hint = match receiver_ty
1833 .builtin_deref(false)
1834 .unwrap_or(receiver_ty)
1835 .ty_adt_def()
1836 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1837 {
1838 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1839 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1840 _ => None,
1841 };
1842
1843 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1844 }
1845 ReceiverValidityError::DoesNotDeref => {
1846 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1847 span,
1848 receiver_ty,
1849 })
1850 }
1851 ReceiverValidityError::MethodGenericParamUsed => {
1852 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1853 }
1854 }
1855 }
1856 });
1857 }
1858 Ok(())
1859}
1860
1861enum ReceiverValidityError {
1865 DoesNotDeref,
1868 MethodGenericParamUsed,
1870}
1871
1872fn confirm_type_is_not_a_method_generic_param(
1875 ty: Ty<'_>,
1876 method_generics: &ty::Generics,
1877) -> Result<(), ReceiverValidityError> {
1878 if let ty::Param(param) = ty.kind() {
1879 if (param.index as usize) >= method_generics.parent_count {
1880 return Err(ReceiverValidityError::MethodGenericParamUsed);
1881 }
1882 }
1883 Ok(())
1884}
1885
1886fn receiver_is_valid<'tcx>(
1896 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1897 span: Span,
1898 receiver_ty: Ty<'tcx>,
1899 self_ty: Ty<'tcx>,
1900 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1901 method_generics: &ty::Generics,
1902) -> Result<(), ReceiverValidityError> {
1903 let infcx = wfcx.infcx;
1904 let tcx = wfcx.tcx();
1905 let cause =
1906 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1907
1908 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1910 let ocx = ObligationCtxt::new(wfcx.infcx);
1911 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1912 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1913 }) {
1914 return Ok(());
1915 }
1916
1917 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1918
1919 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1920
1921 if arbitrary_self_types_enabled.is_some() {
1925 autoderef = autoderef.use_receiver_trait();
1926 }
1927
1928 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1930 autoderef = autoderef.include_raw_pointers();
1931 }
1932
1933 while let Some((potential_self_ty, _)) = autoderef.next() {
1935 debug!(
1936 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1937 potential_self_ty, self_ty
1938 );
1939
1940 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1941
1942 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1945 let ocx = ObligationCtxt::new(wfcx.infcx);
1946 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1947 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1948 }) {
1949 wfcx.register_obligations(autoderef.into_obligations());
1950 return Ok(());
1951 }
1952
1953 if arbitrary_self_types_enabled.is_none() {
1956 let legacy_receiver_trait_def_id =
1957 tcx.require_lang_item(LangItem::LegacyReceiver, Some(span));
1958 if !legacy_receiver_is_implemented(
1959 wfcx,
1960 legacy_receiver_trait_def_id,
1961 cause.clone(),
1962 potential_self_ty,
1963 ) {
1964 break;
1966 }
1967
1968 wfcx.register_bound(
1970 cause.clone(),
1971 wfcx.param_env,
1972 potential_self_ty,
1973 legacy_receiver_trait_def_id,
1974 );
1975 }
1976 }
1977
1978 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1979 Err(ReceiverValidityError::DoesNotDeref)
1980}
1981
1982fn legacy_receiver_is_implemented<'tcx>(
1983 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1984 legacy_receiver_trait_def_id: DefId,
1985 cause: ObligationCause<'tcx>,
1986 receiver_ty: Ty<'tcx>,
1987) -> bool {
1988 let tcx = wfcx.tcx();
1989 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1990
1991 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1992
1993 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1994 true
1995 } else {
1996 debug!(
1997 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1998 receiver_ty
1999 );
2000 false
2001 }
2002}
2003
2004fn check_variances_for_type_defn<'tcx>(
2005 tcx: TyCtxt<'tcx>,
2006 item: &'tcx hir::Item<'tcx>,
2007 hir_generics: &hir::Generics<'tcx>,
2008) {
2009 match item.kind {
2010 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2011 }
2013 ItemKind::TyAlias(..) => {
2014 assert!(
2015 tcx.type_alias_is_lazy(item.owner_id),
2016 "should not be computing variance of non-weak type alias"
2017 );
2018 }
2019 kind => span_bug!(item.span, "cannot compute the variances of {kind:?}"),
2020 }
2021
2022 let ty_predicates = tcx.predicates_of(item.owner_id);
2023 assert_eq!(ty_predicates.parent, None);
2024 let variances = tcx.variances_of(item.owner_id);
2025
2026 let mut constrained_parameters: FxHashSet<_> = variances
2027 .iter()
2028 .enumerate()
2029 .filter(|&(_, &variance)| variance != ty::Bivariant)
2030 .map(|(index, _)| Parameter(index as u32))
2031 .collect();
2032
2033 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2034
2035 let explicitly_bounded_params = LazyCell::new(|| {
2037 let icx = crate::collect::ItemCtxt::new(tcx, item.owner_id.def_id);
2038 hir_generics
2039 .predicates
2040 .iter()
2041 .filter_map(|predicate| match predicate.kind {
2042 hir::WherePredicateKind::BoundPredicate(predicate) => {
2043 match icx.lower_ty(predicate.bounded_ty).kind() {
2044 ty::Param(data) => Some(Parameter(data.index)),
2045 _ => None,
2046 }
2047 }
2048 _ => None,
2049 })
2050 .collect::<FxHashSet<_>>()
2051 });
2052
2053 let ty_generics = tcx.generics_of(item.owner_id);
2054
2055 for (index, _) in variances.iter().enumerate() {
2056 let parameter = Parameter(index as u32);
2057
2058 if constrained_parameters.contains(¶meter) {
2059 continue;
2060 }
2061
2062 let ty_param = &ty_generics.own_params[index];
2063 let hir_param = &hir_generics.params[index];
2064
2065 if ty_param.def_id != hir_param.def_id.into() {
2066 tcx.dcx().span_delayed_bug(
2074 hir_param.span,
2075 "hir generics and ty generics in different order",
2076 );
2077 continue;
2078 }
2079
2080 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2082 .type_of(item.owner_id)
2083 .instantiate_identity()
2084 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2085 {
2086 continue;
2087 }
2088
2089 match hir_param.name {
2090 hir::ParamName::Error(_) => {
2091 }
2094 _ => {
2095 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2096 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2097 }
2098 }
2099 }
2100}
2101
2102struct HasErrorDeep<'tcx> {
2104 tcx: TyCtxt<'tcx>,
2105 seen: FxHashSet<DefId>,
2106}
2107impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2108 type Result = ControlFlow<ErrorGuaranteed>;
2109
2110 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2111 match *ty.kind() {
2112 ty::Adt(def, _) => {
2113 if self.seen.insert(def.did()) {
2114 for field in def.all_fields() {
2115 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2116 }
2117 }
2118 }
2119 ty::Error(guar) => return ControlFlow::Break(guar),
2120 _ => {}
2121 }
2122 ty.super_visit_with(self)
2123 }
2124
2125 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2126 if let Err(guar) = r.error_reported() {
2127 ControlFlow::Break(guar)
2128 } else {
2129 ControlFlow::Continue(())
2130 }
2131 }
2132
2133 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2134 if let Err(guar) = c.error_reported() {
2135 ControlFlow::Break(guar)
2136 } else {
2137 ControlFlow::Continue(())
2138 }
2139 }
2140}
2141
2142fn report_bivariance<'tcx>(
2143 tcx: TyCtxt<'tcx>,
2144 param: &'tcx hir::GenericParam<'tcx>,
2145 has_explicit_bounds: bool,
2146 item: &'tcx hir::Item<'tcx>,
2147) -> ErrorGuaranteed {
2148 let param_name = param.name.ident();
2149
2150 let help = match item.kind {
2151 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2152 if let Some(def_id) = tcx.lang_items().phantom_data() {
2153 errors::UnusedGenericParameterHelp::Adt {
2154 param_name,
2155 phantom_data: tcx.def_path_str(def_id),
2156 }
2157 } else {
2158 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2159 }
2160 }
2161 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2162 item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2163 };
2164
2165 let mut usage_spans = vec![];
2166 intravisit::walk_item(
2167 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2168 item,
2169 );
2170
2171 if !usage_spans.is_empty() {
2172 let item_def_id = item.owner_id.to_def_id();
2176 let is_probably_cyclical =
2177 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2178 .visit_def(item_def_id)
2179 .is_break();
2180 if is_probably_cyclical {
2189 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2190 spans: usage_spans,
2191 param_span: param.span,
2192 param_name,
2193 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2194 help,
2195 note: (),
2196 });
2197 }
2198 }
2199
2200 let const_param_help =
2201 matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2202
2203 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2204 span: param.span,
2205 param_name,
2206 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2207 usage_spans,
2208 help,
2209 const_param_help,
2210 });
2211 diag.code(E0392);
2212 diag.emit()
2213}
2214
2215struct IsProbablyCyclical<'tcx> {
2221 tcx: TyCtxt<'tcx>,
2222 item_def_id: DefId,
2223 seen: FxHashSet<DefId>,
2224}
2225
2226impl<'tcx> IsProbablyCyclical<'tcx> {
2227 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2228 match self.tcx.def_kind(def_id) {
2229 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2230 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2231 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2232 })
2233 }
2234 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2235 self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2236 }
2237 _ => ControlFlow::Continue(()),
2238 }
2239 }
2240}
2241
2242impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2243 type Result = ControlFlow<(), ()>;
2244
2245 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2246 let def_id = match ty.kind() {
2247 ty::Adt(adt_def, _) => Some(adt_def.did()),
2248 ty::Alias(ty::Weak, alias_ty) => Some(alias_ty.def_id),
2249 _ => None,
2250 };
2251 if let Some(def_id) = def_id {
2252 if def_id == self.item_def_id {
2253 return ControlFlow::Break(());
2254 }
2255 if self.seen.insert(def_id) {
2256 self.visit_def(def_id)?;
2257 }
2258 }
2259 ty.super_visit_with(self)
2260 }
2261}
2262
2263struct CollectUsageSpans<'a> {
2268 spans: &'a mut Vec<Span>,
2269 param_def_id: DefId,
2270}
2271
2272impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2273 type Result = ();
2274
2275 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2276 }
2278
2279 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2280 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2281 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2282 && def_id == self.param_def_id
2283 {
2284 self.spans.push(t.span);
2285 return;
2286 } else if let Res::SelfTyAlias { .. } = qpath.res {
2287 self.spans.push(t.span);
2288 return;
2289 }
2290 }
2291 intravisit::walk_ty(self, t);
2292 }
2293}
2294
2295impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2296 #[instrument(level = "debug", skip(self))]
2299 fn check_false_global_bounds(&mut self) {
2300 let tcx = self.ocx.infcx.tcx;
2301 let mut span = self.span;
2302 let empty_env = ty::ParamEnv::empty();
2303
2304 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2305 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2307
2308 for (pred, obligation_span) in implied_obligations {
2309 if let ty::ClauseKind::WellFormed(..) = pred.kind().skip_binder() {
2313 continue;
2314 }
2315 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2317 let pred = self.normalize(span, None, pred);
2318
2319 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2321 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2322 span = predicates
2323 .iter()
2324 .find(|pred| pred.span.contains(obligation_span))
2326 .map(|pred| pred.span)
2327 .unwrap_or(obligation_span);
2328 }
2329
2330 let obligation = Obligation::new(
2331 tcx,
2332 traits::ObligationCause::new(
2333 span,
2334 self.body_def_id,
2335 ObligationCauseCode::TrivialBound,
2336 ),
2337 empty_env,
2338 pred,
2339 );
2340 self.ocx.register_obligation(obligation);
2341 }
2342 }
2343 }
2344}
2345
2346fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalModDefId) -> Result<(), ErrorGuaranteed> {
2347 let items = tcx.hir_module_items(module);
2348 let res = items
2349 .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2350 .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2351 .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2352 .and(
2353 items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2354 )
2355 .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2356 if module == LocalModDefId::CRATE_DEF_ID {
2357 super::entry::check_for_entry_fn(tcx);
2358 }
2359 res
2360}
2361
2362fn lint_redundant_lifetimes<'tcx>(
2363 tcx: TyCtxt<'tcx>,
2364 owner_id: LocalDefId,
2365 outlives_env: &OutlivesEnvironment<'tcx>,
2366) {
2367 let def_kind = tcx.def_kind(owner_id);
2368 match def_kind {
2369 DefKind::Struct
2370 | DefKind::Union
2371 | DefKind::Enum
2372 | DefKind::Trait
2373 | DefKind::TraitAlias
2374 | DefKind::Fn
2375 | DefKind::Const
2376 | DefKind::Impl { of_trait: _ } => {
2377 }
2379 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2380 let parent_def_id = tcx.local_parent(owner_id);
2381 if matches!(tcx.def_kind(parent_def_id), DefKind::Impl { of_trait: true }) {
2382 return;
2387 }
2388 }
2389 DefKind::Mod
2390 | DefKind::Variant
2391 | DefKind::TyAlias
2392 | DefKind::ForeignTy
2393 | DefKind::TyParam
2394 | DefKind::ConstParam
2395 | DefKind::Static { .. }
2396 | DefKind::Ctor(_, _)
2397 | DefKind::Macro(_)
2398 | DefKind::ExternCrate
2399 | DefKind::Use
2400 | DefKind::ForeignMod
2401 | DefKind::AnonConst
2402 | DefKind::InlineConst
2403 | DefKind::OpaqueTy
2404 | DefKind::Field
2405 | DefKind::LifetimeParam
2406 | DefKind::GlobalAsm
2407 | DefKind::Closure
2408 | DefKind::SyntheticCoroutineBody => return,
2409 }
2410
2411 let mut lifetimes = vec![tcx.lifetimes.re_static];
2420 lifetimes.extend(
2421 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2422 );
2423 if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2425 for (idx, var) in
2426 tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2427 {
2428 let ty::BoundVariableKind::Region(kind) = var else { continue };
2429 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2430 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2431 }
2432 }
2433 lifetimes.retain(|candidate| candidate.has_name());
2434
2435 let mut shadowed = FxHashSet::default();
2439
2440 for (idx, &candidate) in lifetimes.iter().enumerate() {
2441 if shadowed.contains(&candidate) {
2446 continue;
2447 }
2448
2449 for &victim in &lifetimes[(idx + 1)..] {
2450 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2458 continue;
2459 };
2460
2461 if tcx.parent(def_id) != owner_id.to_def_id() {
2466 continue;
2467 }
2468
2469 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2471 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2472 {
2473 shadowed.insert(victim);
2474 tcx.emit_node_span_lint(
2475 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2476 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2477 tcx.def_span(def_id),
2478 RedundantLifetimeArgsLint { candidate, victim },
2479 );
2480 }
2481 }
2482 }
2483}
2484
2485#[derive(LintDiagnostic)]
2486#[diag(hir_analysis_redundant_lifetime_args)]
2487#[note]
2488struct RedundantLifetimeArgsLint<'tcx> {
2489 victim: ty::Region<'tcx>,
2491 candidate: ty::Region<'tcx>,
2493}
2494
2495pub fn provide(providers: &mut Providers) {
2496 *providers = Providers { check_mod_type_wf, check_well_formed, ..*providers };
2497}