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};
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::traits::solve::NoSolution;
20use rustc_middle::ty::trait_def::TraitSpecializationKind;
21use rustc_middle::ty::{
22 self, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags,
23 TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
24 Upcast,
25};
26use rustc_middle::{bug, span_bug};
27use rustc_session::parse::feature_err;
28use rustc_span::{DUMMY_SP, Ident, Span, sym};
29use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
30use rustc_trait_selection::regions::{InferCtxtRegionExt, OutlivesEnvironmentBuildExt};
31use rustc_trait_selection::traits::misc::{
32 ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
33};
34use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
35use rustc_trait_selection::traits::{
36 self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
37 WellFormedLoc,
38};
39use tracing::{debug, instrument};
40use {rustc_ast as ast, rustc_hir as hir};
41
42use crate::autoderef::Autoderef;
43use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
44use crate::errors::InvalidReceiverTyHint;
45use crate::{errors, fluent_generated as fluent};
46
47pub(super) struct WfCheckingCtxt<'a, 'tcx> {
48 pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
49 span: Span,
50 body_def_id: LocalDefId,
51 param_env: ty::ParamEnv<'tcx>,
52}
53impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
54 type Target = ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>;
55 fn deref(&self) -> &Self::Target {
56 &self.ocx
57 }
58}
59
60impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
61 fn tcx(&self) -> TyCtxt<'tcx> {
62 self.ocx.infcx.tcx
63 }
64
65 fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
68 where
69 T: TypeFoldable<TyCtxt<'tcx>>,
70 {
71 self.ocx.normalize(
72 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
73 self.param_env,
74 value,
75 )
76 }
77
78 fn deeply_normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
88 where
89 T: TypeFoldable<TyCtxt<'tcx>>,
90 {
91 if self.infcx.next_trait_solver() {
92 match self.ocx.deeply_normalize(
93 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
94 self.param_env,
95 value.clone(),
96 ) {
97 Ok(value) => value,
98 Err(errors) => {
99 self.infcx.err_ctxt().report_fulfillment_errors(errors);
100 value
101 }
102 }
103 } else {
104 self.normalize(span, loc, value)
105 }
106 }
107
108 fn register_wf_obligation(&self, span: Span, loc: Option<WellFormedLoc>, term: ty::Term<'tcx>) {
109 let cause = traits::ObligationCause::new(
110 span,
111 self.body_def_id,
112 ObligationCauseCode::WellFormed(loc),
113 );
114 self.ocx.register_obligation(Obligation::new(
115 self.tcx(),
116 cause,
117 self.param_env,
118 ty::ClauseKind::WellFormed(term),
119 ));
120 }
121}
122
123pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
124 tcx: TyCtxt<'tcx>,
125 span: Span,
126 body_def_id: LocalDefId,
127 f: F,
128) -> Result<(), ErrorGuaranteed>
129where
130 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> Result<(), ErrorGuaranteed>,
131{
132 let param_env = tcx.param_env(body_def_id);
133 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
134 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
135
136 let mut wfcx = WfCheckingCtxt { ocx, span, body_def_id, param_env };
137
138 if !tcx.features().trivial_bounds() {
139 wfcx.check_false_global_bounds()
140 }
141 f(&mut wfcx)?;
142
143 let errors = wfcx.select_all_or_error();
144 if !errors.is_empty() {
145 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
146 }
147
148 let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
149 debug!(?assumed_wf_types);
150
151 let infcx_compat = infcx.fork();
152
153 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
156 &infcx,
157 body_def_id,
158 param_env,
159 assumed_wf_types.iter().copied(),
160 true,
161 );
162
163 lint_redundant_lifetimes(tcx, body_def_id, &outlives_env);
164
165 let errors = infcx.resolve_regions_with_outlives_env(&outlives_env);
166 if errors.is_empty() {
167 return Ok(());
168 }
169
170 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
171 &infcx_compat,
172 body_def_id,
173 param_env,
174 assumed_wf_types,
175 false,
178 );
179 let errors_compat = infcx_compat.resolve_regions_with_outlives_env(&outlives_env);
180 if errors_compat.is_empty() {
181 Ok(())
184 } else {
185 Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
186 }
187}
188
189fn check_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
190 let node = tcx.hir_node_by_def_id(def_id);
191 let mut res = match node {
192 hir::Node::Crate(_) => bug!("check_well_formed cannot be applied to the crate root"),
193 hir::Node::Item(item) => check_item(tcx, item),
194 hir::Node::TraitItem(item) => check_trait_item(tcx, item),
195 hir::Node::ImplItem(item) => check_impl_item(tcx, item),
196 hir::Node::ForeignItem(item) => check_foreign_item(tcx, item),
197 hir::Node::ConstBlock(_) | hir::Node::Expr(_) | hir::Node::OpaqueTy(_) => {
198 Ok(crate::check::check::check_item_type(tcx, def_id))
199 }
200 _ => unreachable!("{node:?}"),
201 };
202
203 if let Some(generics) = node.generics() {
204 for param in generics.params {
205 res = res.and(check_param_wf(tcx, param));
206 }
207 }
208
209 res
210}
211
212#[instrument(skip(tcx), level = "debug")]
226fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) -> Result<(), ErrorGuaranteed> {
227 let def_id = item.owner_id.def_id;
228
229 debug!(
230 ?item.owner_id,
231 item.name = ? tcx.def_path_str(def_id)
232 );
233 crate::collect::lower_item(tcx, item.item_id());
234 crate::collect::reject_placeholder_type_signatures_in_item(tcx, item);
235
236 let res = match item.kind {
237 hir::ItemKind::Impl(impl_) => {
255 let header = tcx.impl_trait_header(def_id);
256 let is_auto = header
257 .is_some_and(|header| tcx.trait_is_auto(header.trait_ref.skip_binder().def_id));
258
259 crate::impl_wf_check::check_impl_wf(tcx, def_id)?;
260 let mut res = Ok(());
261 if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
262 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
263 res = Err(tcx
264 .dcx()
265 .struct_span_err(sp, "impls of auto traits cannot be default")
266 .with_span_labels(impl_.defaultness_span, "default because of this")
267 .with_span_label(sp, "auto trait")
268 .emit());
269 }
270 match header.map(|h| h.polarity) {
272 Some(ty::ImplPolarity::Positive) | None => {
274 res = res.and(check_impl(tcx, item, impl_.self_ty, &impl_.of_trait));
275 }
276 Some(ty::ImplPolarity::Negative) => {
277 let ast::ImplPolarity::Negative(span) = impl_.polarity else {
278 bug!("impl_polarity query disagrees with impl's polarity in HIR");
279 };
280 if let hir::Defaultness::Default { .. } = impl_.defaultness {
282 let mut spans = vec![span];
283 spans.extend(impl_.defaultness_span);
284 res = Err(struct_span_code_err!(
285 tcx.dcx(),
286 spans,
287 E0750,
288 "negative impls cannot be default impls"
289 )
290 .emit());
291 }
292 }
293 Some(ty::ImplPolarity::Reservation) => {
294 }
296 }
297 res
298 }
299 hir::ItemKind::Fn { ident, sig, .. } => {
300 check_item_fn(tcx, def_id, ident, item.span, sig.decl)
301 }
302 hir::ItemKind::Static(_, _, ty, _) => {
303 check_static_item(tcx, def_id, ty.span, UnsizedHandling::Forbid)
304 }
305 hir::ItemKind::Const(_, _, ty, _) => check_const_item(tcx, def_id, ty.span, item.span),
306 hir::ItemKind::Struct(_, generics, _) => {
307 let res = check_type_defn(tcx, item, false);
308 check_variances_for_type_defn(tcx, item, generics);
309 res
310 }
311 hir::ItemKind::Union(_, generics, _) => {
312 let res = check_type_defn(tcx, item, true);
313 check_variances_for_type_defn(tcx, item, generics);
314 res
315 }
316 hir::ItemKind::Enum(_, generics, _) => {
317 let res = check_type_defn(tcx, item, true);
318 check_variances_for_type_defn(tcx, item, generics);
319 res
320 }
321 hir::ItemKind::Trait(..) => check_trait(tcx, item),
322 hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
323 hir::ItemKind::ForeignMod { .. } => Ok(()),
325 hir::ItemKind::TyAlias(_, generics, hir_ty) if tcx.type_alias_is_lazy(item.owner_id) => {
326 let res = enter_wf_checking_ctxt(tcx, item.span, def_id, |wfcx| {
327 let ty = tcx.type_of(def_id).instantiate_identity();
328 let item_ty =
329 wfcx.deeply_normalize(hir_ty.span, Some(WellFormedLoc::Ty(def_id)), ty);
330 wfcx.register_wf_obligation(
331 hir_ty.span,
332 Some(WellFormedLoc::Ty(def_id)),
333 item_ty.into(),
334 );
335 check_where_clauses(wfcx, item.span, def_id);
336 Ok(())
337 });
338 check_variances_for_type_defn(tcx, item, generics);
339 res
340 }
341 _ => Ok(()),
342 };
343
344 crate::check::check::check_item_type(tcx, def_id);
345
346 res
347}
348
349fn check_foreign_item<'tcx>(
350 tcx: TyCtxt<'tcx>,
351 item: &'tcx hir::ForeignItem<'tcx>,
352) -> Result<(), ErrorGuaranteed> {
353 let def_id = item.owner_id.def_id;
354
355 debug!(
356 ?item.owner_id,
357 item.name = ? tcx.def_path_str(def_id)
358 );
359
360 match item.kind {
361 hir::ForeignItemKind::Fn(sig, ..) => {
362 check_item_fn(tcx, def_id, item.ident, item.span, sig.decl)
363 }
364 hir::ForeignItemKind::Static(ty, ..) => {
365 check_static_item(tcx, def_id, ty.span, UnsizedHandling::AllowIfForeignTail)
366 }
367 hir::ForeignItemKind::Type => Ok(()),
368 }
369}
370
371fn check_trait_item<'tcx>(
372 tcx: TyCtxt<'tcx>,
373 trait_item: &'tcx hir::TraitItem<'tcx>,
374) -> Result<(), ErrorGuaranteed> {
375 let def_id = trait_item.owner_id.def_id;
376
377 crate::collect::lower_trait_item(tcx, trait_item.trait_item_id());
378
379 let (method_sig, span) = match trait_item.kind {
380 hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
381 hir::TraitItemKind::Type(_bounds, Some(ty)) => (None, ty.span),
382 _ => (None, trait_item.span),
383 };
384
385 lint_item_shadowing_supertrait_item(tcx, def_id);
387
388 let mut res = check_associated_item(tcx, def_id, span, method_sig);
389
390 if matches!(trait_item.kind, hir::TraitItemKind::Fn(..)) {
391 for &assoc_ty_def_id in tcx.associated_types_for_impl_traits_in_associated_fn(def_id) {
392 res = res.and(check_associated_item(
393 tcx,
394 assoc_ty_def_id.expect_local(),
395 tcx.def_span(assoc_ty_def_id),
396 None,
397 ));
398 }
399 }
400 res
401}
402
403fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
416 let mut required_bounds_by_item = FxIndexMap::default();
418 let associated_items = tcx.associated_items(trait_def_id);
419
420 loop {
426 let mut should_continue = false;
427 for gat_item in associated_items.in_definition_order() {
428 let gat_def_id = gat_item.def_id.expect_local();
429 let gat_item = tcx.associated_item(gat_def_id);
430 if !gat_item.is_type() {
432 continue;
433 }
434 let gat_generics = tcx.generics_of(gat_def_id);
435 if gat_generics.is_own_empty() {
437 continue;
438 }
439
440 let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
444 for item in associated_items.in_definition_order() {
445 let item_def_id = item.def_id.expect_local();
446 if item_def_id == gat_def_id {
448 continue;
449 }
450
451 let param_env = tcx.param_env(item_def_id);
452
453 let item_required_bounds = match tcx.associated_item(item_def_id).kind {
454 ty::AssocKind::Fn { .. } => {
456 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
460 item_def_id.to_def_id(),
461 tcx.fn_sig(item_def_id).instantiate_identity(),
462 );
463 gather_gat_bounds(
464 tcx,
465 param_env,
466 item_def_id,
467 sig.inputs_and_output,
468 &sig.inputs().iter().copied().collect(),
471 gat_def_id,
472 gat_generics,
473 )
474 }
475 ty::AssocKind::Type { .. } => {
477 let param_env = augment_param_env(
481 tcx,
482 param_env,
483 required_bounds_by_item.get(&item_def_id),
484 );
485 gather_gat_bounds(
486 tcx,
487 param_env,
488 item_def_id,
489 tcx.explicit_item_bounds(item_def_id)
490 .iter_identity_copied()
491 .collect::<Vec<_>>(),
492 &FxIndexSet::default(),
493 gat_def_id,
494 gat_generics,
495 )
496 }
497 ty::AssocKind::Const { .. } => None,
498 };
499
500 if let Some(item_required_bounds) = item_required_bounds {
501 if let Some(new_required_bounds) = &mut new_required_bounds {
507 new_required_bounds.retain(|b| item_required_bounds.contains(b));
508 } else {
509 new_required_bounds = Some(item_required_bounds);
510 }
511 }
512 }
513
514 if let Some(new_required_bounds) = new_required_bounds {
515 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
516 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
517 should_continue = true;
520 }
521 }
522 }
523 if !should_continue {
528 break;
529 }
530 }
531
532 for (gat_def_id, required_bounds) in required_bounds_by_item {
533 if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
535 continue;
536 }
537
538 let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
539 debug!(?required_bounds);
540 let param_env = tcx.param_env(gat_def_id);
541
542 let unsatisfied_bounds: Vec<_> = required_bounds
543 .into_iter()
544 .filter(|clause| match clause.kind().skip_binder() {
545 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
546 !region_known_to_outlive(
547 tcx,
548 gat_def_id,
549 param_env,
550 &FxIndexSet::default(),
551 a,
552 b,
553 )
554 }
555 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
556 !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
557 }
558 _ => bug!("Unexpected ClauseKind"),
559 })
560 .map(|clause| clause.to_string())
561 .collect();
562
563 if !unsatisfied_bounds.is_empty() {
564 let plural = pluralize!(unsatisfied_bounds.len());
565 let suggestion = format!(
566 "{} {}",
567 gat_item_hir.generics.add_where_or_trailing_comma(),
568 unsatisfied_bounds.join(", "),
569 );
570 let bound =
571 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
572 tcx.dcx()
573 .struct_span_err(
574 gat_item_hir.span,
575 format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
576 )
577 .with_span_suggestion(
578 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
579 format!("add the required where clause{plural}"),
580 suggestion,
581 Applicability::MachineApplicable,
582 )
583 .with_note(format!(
584 "{bound} currently required to ensure that impls have maximum flexibility"
585 ))
586 .with_note(
587 "we are soliciting feedback, see issue #87479 \
588 <https://github.com/rust-lang/rust/issues/87479> for more information",
589 )
590 .emit();
591 }
592 }
593}
594
595fn augment_param_env<'tcx>(
597 tcx: TyCtxt<'tcx>,
598 param_env: ty::ParamEnv<'tcx>,
599 new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
600) -> ty::ParamEnv<'tcx> {
601 let Some(new_predicates) = new_predicates else {
602 return param_env;
603 };
604
605 if new_predicates.is_empty() {
606 return param_env;
607 }
608
609 let bounds = tcx.mk_clauses_from_iter(
610 param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
611 );
612 ty::ParamEnv::new(bounds)
615}
616
617fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
628 tcx: TyCtxt<'tcx>,
629 param_env: ty::ParamEnv<'tcx>,
630 item_def_id: LocalDefId,
631 to_check: T,
632 wf_tys: &FxIndexSet<Ty<'tcx>>,
633 gat_def_id: LocalDefId,
634 gat_generics: &'tcx ty::Generics,
635) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
636 let mut bounds = FxIndexSet::default();
638
639 let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
640
641 if types.is_empty() && regions.is_empty() {
647 return None;
648 }
649
650 for (region_a, region_a_idx) in ®ions {
651 if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
655 continue;
656 }
657 for (ty, ty_idx) in &types {
662 if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
664 debug!(?ty_idx, ?region_a_idx);
665 debug!("required clause: {ty} must outlive {region_a}");
666 let ty_param = gat_generics.param_at(*ty_idx, tcx);
670 let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
671 let region_param = gat_generics.param_at(*region_a_idx, tcx);
674 let region_param = ty::Region::new_early_param(
675 tcx,
676 ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
677 );
678 bounds.insert(
681 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
682 .upcast(tcx),
683 );
684 }
685 }
686
687 for (region_b, region_b_idx) in ®ions {
692 if matches!(region_b.kind(), ty::ReStatic | ty::ReError(_)) || region_a == region_b {
696 continue;
697 }
698 if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
699 debug!(?region_a_idx, ?region_b_idx);
700 debug!("required clause: {region_a} must outlive {region_b}");
701 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
703 let region_a_param = ty::Region::new_early_param(
704 tcx,
705 ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
706 );
707 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
709 let region_b_param = ty::Region::new_early_param(
710 tcx,
711 ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
712 );
713 bounds.insert(
715 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
716 region_a_param,
717 region_b_param,
718 ))
719 .upcast(tcx),
720 );
721 }
722 }
723 }
724
725 Some(bounds)
726}
727
728fn ty_known_to_outlive<'tcx>(
731 tcx: TyCtxt<'tcx>,
732 id: LocalDefId,
733 param_env: ty::ParamEnv<'tcx>,
734 wf_tys: &FxIndexSet<Ty<'tcx>>,
735 ty: Ty<'tcx>,
736 region: ty::Region<'tcx>,
737) -> bool {
738 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
739 infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
740 sub_region: region,
741 sup_type: ty,
742 origin: infer::RelateParamBound(DUMMY_SP, ty, None),
743 });
744 })
745}
746
747fn region_known_to_outlive<'tcx>(
750 tcx: TyCtxt<'tcx>,
751 id: LocalDefId,
752 param_env: ty::ParamEnv<'tcx>,
753 wf_tys: &FxIndexSet<Ty<'tcx>>,
754 region_a: ty::Region<'tcx>,
755 region_b: ty::Region<'tcx>,
756) -> bool {
757 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
758 infcx.sub_regions(infer::RelateRegionParamBound(DUMMY_SP, None), region_b, region_a);
759 })
760}
761
762fn test_region_obligations<'tcx>(
766 tcx: TyCtxt<'tcx>,
767 id: LocalDefId,
768 param_env: ty::ParamEnv<'tcx>,
769 wf_tys: &FxIndexSet<Ty<'tcx>>,
770 add_constraints: impl FnOnce(&InferCtxt<'tcx>),
771) -> bool {
772 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
776
777 add_constraints(&infcx);
778
779 let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
780 debug!(?errors, "errors");
781
782 errors.is_empty()
785}
786
787struct GATArgsCollector<'tcx> {
792 gat: DefId,
793 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
795 types: FxIndexSet<(Ty<'tcx>, usize)>,
797}
798
799impl<'tcx> GATArgsCollector<'tcx> {
800 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
801 gat: DefId,
802 t: T,
803 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
804 let mut visitor =
805 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
806 t.visit_with(&mut visitor);
807 (visitor.regions, visitor.types)
808 }
809}
810
811impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
812 fn visit_ty(&mut self, t: Ty<'tcx>) {
813 match t.kind() {
814 ty::Alias(ty::Projection, p) if p.def_id == self.gat => {
815 for (idx, arg) in p.args.iter().enumerate() {
816 match arg.kind() {
817 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
818 self.regions.insert((lt, idx));
819 }
820 GenericArgKind::Type(t) => {
821 self.types.insert((t, idx));
822 }
823 _ => {}
824 }
825 }
826 }
827 _ => {}
828 }
829 t.super_visit_with(self)
830 }
831}
832
833fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
834 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
835 let trait_def_id = tcx.local_parent(trait_item_def_id);
836
837 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
838 .skip(1)
839 .flat_map(|supertrait_def_id| {
840 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
841 })
842 .collect();
843 if !shadowed.is_empty() {
844 let shadowee = if let [shadowed] = shadowed[..] {
845 errors::SupertraitItemShadowee::Labeled {
846 span: tcx.def_span(shadowed.def_id),
847 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
848 }
849 } else {
850 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
851 .iter()
852 .map(|item| {
853 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
854 })
855 .unzip();
856 errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
857 };
858
859 tcx.emit_node_span_lint(
860 SUPERTRAIT_ITEM_SHADOWING_DEFINITION,
861 tcx.local_def_id_to_hir_id(trait_item_def_id),
862 tcx.def_span(trait_item_def_id),
863 errors::SupertraitItemShadowing {
864 item: item_name,
865 subtrait: tcx.item_name(trait_def_id.to_def_id()),
866 shadowee,
867 },
868 );
869 }
870}
871
872fn check_impl_item<'tcx>(
873 tcx: TyCtxt<'tcx>,
874 impl_item: &'tcx hir::ImplItem<'tcx>,
875) -> Result<(), ErrorGuaranteed> {
876 crate::collect::lower_impl_item(tcx, impl_item.impl_item_id());
877
878 let (method_sig, span) = match impl_item.kind {
879 hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
880 hir::ImplItemKind::Type(ty) if ty.span != DUMMY_SP => (None, ty.span),
882 _ => (None, impl_item.span),
883 };
884 check_associated_item(tcx, impl_item.owner_id.def_id, span, method_sig)
885}
886
887fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) -> Result<(), ErrorGuaranteed> {
888 match param.kind {
889 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => Ok(()),
891
892 hir::GenericParamKind::Const { ty: hir_ty, default: _, synthetic: _ } => {
894 let ty = tcx.type_of(param.def_id).instantiate_identity();
895
896 if tcx.features().unsized_const_params() {
897 enter_wf_checking_ctxt(tcx, hir_ty.span, tcx.local_parent(param.def_id), |wfcx| {
898 wfcx.register_bound(
899 ObligationCause::new(
900 hir_ty.span,
901 param.def_id,
902 ObligationCauseCode::ConstParam(ty),
903 ),
904 wfcx.param_env,
905 ty,
906 tcx.require_lang_item(LangItem::UnsizedConstParamTy, hir_ty.span),
907 );
908 Ok(())
909 })
910 } else if tcx.features().adt_const_params() {
911 enter_wf_checking_ctxt(tcx, hir_ty.span, tcx.local_parent(param.def_id), |wfcx| {
912 wfcx.register_bound(
913 ObligationCause::new(
914 hir_ty.span,
915 param.def_id,
916 ObligationCauseCode::ConstParam(ty),
917 ),
918 wfcx.param_env,
919 ty,
920 tcx.require_lang_item(LangItem::ConstParamTy, hir_ty.span),
921 );
922 Ok(())
923 })
924 } else {
925 let mut diag = match ty.kind() {
926 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
927 ty::FnPtr(..) => tcx.dcx().struct_span_err(
928 hir_ty.span,
929 "using function pointers as const generic parameters is forbidden",
930 ),
931 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
932 hir_ty.span,
933 "using raw pointers as const generic parameters is forbidden",
934 ),
935 _ => {
936 ty.error_reported()?;
938
939 tcx.dcx().struct_span_err(
940 hir_ty.span,
941 format!(
942 "`{ty}` is forbidden as the type of a const generic parameter",
943 ),
944 )
945 }
946 };
947
948 diag.note("the only supported types are integers, `bool`, and `char`");
949
950 let cause = ObligationCause::misc(hir_ty.span, param.def_id);
951 let adt_const_params_feature_string =
952 " more complex and user defined types".to_string();
953 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
954 tcx,
955 tcx.param_env(param.def_id),
956 ty,
957 LangItem::ConstParamTy,
958 cause,
959 ) {
960 Err(
962 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
963 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
964 ) => None,
965 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
966 Some(vec![
967 (adt_const_params_feature_string, sym::adt_const_params),
968 (
969 " references to implement the `ConstParamTy` trait".into(),
970 sym::unsized_const_params,
971 ),
972 ])
973 }
974 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
977 fn ty_is_local(ty: Ty<'_>) -> bool {
978 match ty.kind() {
979 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
980 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
982 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
985 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
988 _ => false,
989 }
990 }
991
992 ty_is_local(ty).then_some(vec![(
993 adt_const_params_feature_string,
994 sym::adt_const_params,
995 )])
996 }
997 Ok(..) => Some(vec![(adt_const_params_feature_string, sym::adt_const_params)]),
999 };
1000 if let Some(features) = may_suggest_feature {
1001 tcx.disabled_nightly_features(&mut diag, features);
1002 }
1003
1004 Err(diag.emit())
1005 }
1006 }
1007 }
1008}
1009
1010#[instrument(level = "debug", skip(tcx, span, sig_if_method))]
1011fn check_associated_item(
1012 tcx: TyCtxt<'_>,
1013 item_id: LocalDefId,
1014 span: Span,
1015 sig_if_method: Option<&hir::FnSig<'_>>,
1016) -> Result<(), ErrorGuaranteed> {
1017 let loc = Some(WellFormedLoc::Ty(item_id));
1018 enter_wf_checking_ctxt(tcx, span, item_id, |wfcx| {
1019 let item = tcx.associated_item(item_id);
1020
1021 tcx.ensure_ok()
1024 .coherent_trait(tcx.parent(item.trait_item_def_id.unwrap_or(item_id.into())))?;
1025
1026 let self_ty = match item.container {
1027 ty::AssocItemContainer::Trait => tcx.types.self_param,
1028 ty::AssocItemContainer::Impl => {
1029 tcx.type_of(item.container_id(tcx)).instantiate_identity()
1030 }
1031 };
1032
1033 match item.kind {
1034 ty::AssocKind::Const { .. } => {
1035 let ty = tcx.type_of(item.def_id).instantiate_identity();
1036 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1037 wfcx.register_wf_obligation(span, loc, ty.into());
1038 check_sized_if_body(
1039 wfcx,
1040 item.def_id.expect_local(),
1041 ty,
1042 Some(span),
1043 ObligationCauseCode::SizedConstOrStatic,
1044 );
1045 Ok(())
1046 }
1047 ty::AssocKind::Fn { .. } => {
1048 let sig = tcx.fn_sig(item.def_id).instantiate_identity();
1049 let hir_sig = sig_if_method.expect("bad signature for method");
1050 check_fn_or_method(
1051 wfcx,
1052 item.ident(tcx).span,
1053 sig,
1054 hir_sig.decl,
1055 item.def_id.expect_local(),
1056 );
1057 check_method_receiver(wfcx, hir_sig, item, self_ty)
1058 }
1059 ty::AssocKind::Type { .. } => {
1060 if let ty::AssocItemContainer::Trait = item.container {
1061 check_associated_type_bounds(wfcx, item, span)
1062 }
1063 if item.defaultness(tcx).has_value() {
1064 let ty = tcx.type_of(item.def_id).instantiate_identity();
1065 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1066 wfcx.register_wf_obligation(span, loc, ty.into());
1067 }
1068 Ok(())
1069 }
1070 }
1071 })
1072}
1073
1074fn check_type_defn<'tcx>(
1076 tcx: TyCtxt<'tcx>,
1077 item: &hir::Item<'tcx>,
1078 all_sized: bool,
1079) -> Result<(), ErrorGuaranteed> {
1080 let _ = tcx.representability(item.owner_id.def_id);
1081 let adt_def = tcx.adt_def(item.owner_id);
1082
1083 enter_wf_checking_ctxt(tcx, item.span, item.owner_id.def_id, |wfcx| {
1084 let variants = adt_def.variants();
1085 let packed = adt_def.repr().packed();
1086
1087 for variant in variants.iter() {
1088 for field in &variant.fields {
1090 if let Some(def_id) = field.value
1091 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1092 {
1093 if let Some(def_id) = def_id.as_local()
1096 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1097 && let expr = &tcx.hir_body(anon.body).value
1098 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1099 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1100 {
1101 } else {
1104 let _ = tcx.const_eval_poly(def_id);
1107 }
1108 }
1109 let field_id = field.did.expect_local();
1110 let hir::FieldDef { ty: hir_ty, .. } =
1111 tcx.hir_node_by_def_id(field_id).expect_field();
1112 let ty = wfcx.deeply_normalize(
1113 hir_ty.span,
1114 None,
1115 tcx.type_of(field.did).instantiate_identity(),
1116 );
1117 wfcx.register_wf_obligation(
1118 hir_ty.span,
1119 Some(WellFormedLoc::Ty(field_id)),
1120 ty.into(),
1121 )
1122 }
1123
1124 let needs_drop_copy = || {
1127 packed && {
1128 let ty = tcx.type_of(variant.tail().did).instantiate_identity();
1129 let ty = tcx.erase_regions(ty);
1130 assert!(!ty.has_infer());
1131 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1132 }
1133 };
1134 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1136 let unsized_len = if all_sized { 0 } else { 1 };
1137 for (idx, field) in
1138 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1139 {
1140 let last = idx == variant.fields.len() - 1;
1141 let field_id = field.did.expect_local();
1142 let hir::FieldDef { ty: hir_ty, .. } =
1143 tcx.hir_node_by_def_id(field_id).expect_field();
1144 let ty = wfcx.normalize(
1145 hir_ty.span,
1146 None,
1147 tcx.type_of(field.did).instantiate_identity(),
1148 );
1149 wfcx.register_bound(
1150 traits::ObligationCause::new(
1151 hir_ty.span,
1152 wfcx.body_def_id,
1153 ObligationCauseCode::FieldSized {
1154 adt_kind: match &item.kind {
1155 ItemKind::Struct(..) => AdtKind::Struct,
1156 ItemKind::Union(..) => AdtKind::Union,
1157 ItemKind::Enum(..) => AdtKind::Enum,
1158 kind => span_bug!(
1159 item.span,
1160 "should be wfchecking an ADT, got {kind:?}"
1161 ),
1162 },
1163 span: hir_ty.span,
1164 last,
1165 },
1166 ),
1167 wfcx.param_env,
1168 ty,
1169 tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1170 );
1171 }
1172
1173 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1175 match tcx.const_eval_poly(discr_def_id) {
1176 Ok(_) => {}
1177 Err(ErrorHandled::Reported(..)) => {}
1178 Err(ErrorHandled::TooGeneric(sp)) => {
1179 span_bug!(sp, "enum variant discr was too generic to eval")
1180 }
1181 }
1182 }
1183 }
1184
1185 check_where_clauses(wfcx, item.span, item.owner_id.def_id);
1186 Ok(())
1187 })
1188}
1189
1190#[instrument(skip(tcx, item))]
1191fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1192 debug!(?item.owner_id);
1193
1194 let def_id = item.owner_id.def_id;
1195 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1196 return Ok(());
1198 }
1199
1200 let trait_def = tcx.trait_def(def_id);
1201 if trait_def.is_marker
1202 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1203 {
1204 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1205 struct_span_code_err!(
1206 tcx.dcx(),
1207 tcx.def_span(*associated_def_id),
1208 E0714,
1209 "marker traits cannot have associated items",
1210 )
1211 .emit();
1212 }
1213 }
1214
1215 let res = enter_wf_checking_ctxt(tcx, item.span, def_id, |wfcx| {
1216 check_where_clauses(wfcx, item.span, def_id);
1217 Ok(())
1218 });
1219
1220 if let hir::ItemKind::Trait(..) = item.kind {
1222 check_gat_where_clauses(tcx, item.owner_id.def_id);
1223 }
1224 res
1225}
1226
1227fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, span: Span) {
1232 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1233
1234 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1235 let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
1236 let normalized_bound = wfcx.normalize(span, None, bound);
1237 traits::wf::clause_obligations(
1238 wfcx.infcx,
1239 wfcx.param_env,
1240 wfcx.body_def_id,
1241 normalized_bound,
1242 bound_span,
1243 )
1244 });
1245
1246 wfcx.register_obligations(wf_obligations);
1247}
1248
1249fn check_item_fn(
1250 tcx: TyCtxt<'_>,
1251 def_id: LocalDefId,
1252 ident: Ident,
1253 span: Span,
1254 decl: &hir::FnDecl<'_>,
1255) -> Result<(), ErrorGuaranteed> {
1256 enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| {
1257 let sig = tcx.fn_sig(def_id).instantiate_identity();
1258 check_fn_or_method(wfcx, ident.span, sig, decl, def_id);
1259 Ok(())
1260 })
1261}
1262
1263enum UnsizedHandling {
1264 Forbid,
1265 AllowIfForeignTail,
1266}
1267
1268#[instrument(level = "debug", skip(tcx, ty_span, unsized_handling))]
1269fn check_static_item(
1270 tcx: TyCtxt<'_>,
1271 item_id: LocalDefId,
1272 ty_span: Span,
1273 unsized_handling: UnsizedHandling,
1274) -> Result<(), ErrorGuaranteed> {
1275 enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| {
1276 let ty = tcx.type_of(item_id).instantiate_identity();
1277 let item_ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty);
1278
1279 let forbid_unsized = match unsized_handling {
1280 UnsizedHandling::Forbid => true,
1281 UnsizedHandling::AllowIfForeignTail => {
1282 let tail =
1283 tcx.struct_tail_for_codegen(item_ty, wfcx.infcx.typing_env(wfcx.param_env));
1284 !matches!(tail.kind(), ty::Foreign(_))
1285 }
1286 };
1287
1288 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1289 if forbid_unsized {
1290 wfcx.register_bound(
1291 traits::ObligationCause::new(
1292 ty_span,
1293 wfcx.body_def_id,
1294 ObligationCauseCode::SizedConstOrStatic,
1295 ),
1296 wfcx.param_env,
1297 item_ty,
1298 tcx.require_lang_item(LangItem::Sized, ty_span),
1299 );
1300 }
1301
1302 let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1304 == Some(hir::Mutability::Not)
1305 && !tcx.is_foreign_item(item_id.to_def_id())
1306 && !tcx.is_thread_local_static(item_id.to_def_id());
1307
1308 if should_check_for_sync {
1309 wfcx.register_bound(
1310 traits::ObligationCause::new(
1311 ty_span,
1312 wfcx.body_def_id,
1313 ObligationCauseCode::SharedStatic,
1314 ),
1315 wfcx.param_env,
1316 item_ty,
1317 tcx.require_lang_item(LangItem::Sync, ty_span),
1318 );
1319 }
1320 Ok(())
1321 })
1322}
1323
1324fn check_const_item(
1325 tcx: TyCtxt<'_>,
1326 def_id: LocalDefId,
1327 ty_span: Span,
1328 item_span: Span,
1329) -> Result<(), ErrorGuaranteed> {
1330 enter_wf_checking_ctxt(tcx, ty_span, def_id, |wfcx| {
1331 let ty = tcx.type_of(def_id).instantiate_identity();
1332 let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
1333
1334 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
1335 wfcx.register_bound(
1336 traits::ObligationCause::new(
1337 ty_span,
1338 wfcx.body_def_id,
1339 ObligationCauseCode::SizedConstOrStatic,
1340 ),
1341 wfcx.param_env,
1342 ty,
1343 tcx.require_lang_item(LangItem::Sized, ty_span),
1344 );
1345
1346 check_where_clauses(wfcx, item_span, def_id);
1347
1348 Ok(())
1349 })
1350}
1351
1352#[instrument(level = "debug", skip(tcx, hir_self_ty, hir_trait_ref))]
1353fn check_impl<'tcx>(
1354 tcx: TyCtxt<'tcx>,
1355 item: &'tcx hir::Item<'tcx>,
1356 hir_self_ty: &hir::Ty<'_>,
1357 hir_trait_ref: &Option<hir::TraitRef<'_>>,
1358) -> Result<(), ErrorGuaranteed> {
1359 enter_wf_checking_ctxt(tcx, item.span, item.owner_id.def_id, |wfcx| {
1360 match hir_trait_ref {
1361 Some(hir_trait_ref) => {
1362 let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().instantiate_identity();
1366 tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1369 let trait_span = hir_trait_ref.path.span;
1370 let trait_ref = wfcx.deeply_normalize(
1371 trait_span,
1372 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1373 trait_ref,
1374 );
1375 let trait_pred =
1376 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1377 let mut obligations = traits::wf::trait_obligations(
1378 wfcx.infcx,
1379 wfcx.param_env,
1380 wfcx.body_def_id,
1381 trait_pred,
1382 trait_span,
1383 item,
1384 );
1385 for obligation in &mut obligations {
1386 if obligation.cause.span != trait_span {
1387 continue;
1389 }
1390 if let Some(pred) = obligation.predicate.as_trait_clause()
1391 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1392 {
1393 obligation.cause.span = hir_self_ty.span;
1394 }
1395 if let Some(pred) = obligation.predicate.as_projection_clause()
1396 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1397 {
1398 obligation.cause.span = hir_self_ty.span;
1399 }
1400 }
1401
1402 if tcx.is_conditionally_const(item.owner_id.def_id) {
1404 for (bound, _) in
1405 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1406 {
1407 let bound = wfcx.normalize(
1408 item.span,
1409 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1410 bound,
1411 );
1412 wfcx.register_obligation(Obligation::new(
1413 tcx,
1414 ObligationCause::new(
1415 hir_self_ty.span,
1416 wfcx.body_def_id,
1417 ObligationCauseCode::WellFormed(None),
1418 ),
1419 wfcx.param_env,
1420 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1421 ))
1422 }
1423 }
1424
1425 debug!(?obligations);
1426 wfcx.register_obligations(obligations);
1427 }
1428 None => {
1429 let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1430 let self_ty = wfcx.deeply_normalize(
1431 item.span,
1432 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1433 self_ty,
1434 );
1435 wfcx.register_wf_obligation(
1436 hir_self_ty.span,
1437 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1438 self_ty.into(),
1439 );
1440 }
1441 }
1442
1443 check_where_clauses(wfcx, item.span, item.owner_id.def_id);
1444 Ok(())
1445 })
1446}
1447
1448#[instrument(level = "debug", skip(wfcx))]
1450fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
1451 let infcx = wfcx.infcx;
1452 let tcx = wfcx.tcx();
1453
1454 let predicates = tcx.predicates_of(def_id.to_def_id());
1455 let generics = tcx.generics_of(def_id);
1456
1457 for param in &generics.own_params {
1464 if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1465 if !default.has_param() {
1472 wfcx.register_wf_obligation(
1473 tcx.def_span(param.def_id),
1474 matches!(param.kind, GenericParamDefKind::Type { .. })
1475 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1476 default.as_term().unwrap(),
1477 );
1478 } else {
1479 let GenericArgKind::Const(ct) = default.kind() else {
1482 continue;
1483 };
1484
1485 let ct_ty = match ct.kind() {
1486 ty::ConstKind::Infer(_)
1487 | ty::ConstKind::Placeholder(_)
1488 | ty::ConstKind::Bound(_, _) => unreachable!(),
1489 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1490 ty::ConstKind::Value(cv) => cv.ty,
1491 ty::ConstKind::Unevaluated(uv) => {
1492 infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1493 }
1494 ty::ConstKind::Param(param_ct) => param_ct.find_ty_from_env(wfcx.param_env),
1495 };
1496
1497 let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1498 if !ct_ty.has_param() && !param_ty.has_param() {
1499 let cause = traits::ObligationCause::new(
1500 tcx.def_span(param.def_id),
1501 wfcx.body_def_id,
1502 ObligationCauseCode::WellFormed(None),
1503 );
1504 wfcx.register_obligation(Obligation::new(
1505 tcx,
1506 cause,
1507 wfcx.param_env,
1508 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1509 ));
1510 }
1511 }
1512 }
1513 }
1514
1515 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1524 if param.index >= generics.parent_count as u32
1525 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1527 && !default.has_param()
1529 {
1530 return default;
1532 }
1533 tcx.mk_param_from_def(param)
1534 });
1535
1536 let default_obligations = predicates
1538 .predicates
1539 .iter()
1540 .flat_map(|&(pred, sp)| {
1541 #[derive(Default)]
1542 struct CountParams {
1543 params: FxHashSet<u32>,
1544 }
1545 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1546 type Result = ControlFlow<()>;
1547 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1548 if let ty::Param(param) = t.kind() {
1549 self.params.insert(param.index);
1550 }
1551 t.super_visit_with(self)
1552 }
1553
1554 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1555 ControlFlow::Break(())
1556 }
1557
1558 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1559 if let ty::ConstKind::Param(param) = c.kind() {
1560 self.params.insert(param.index);
1561 }
1562 c.super_visit_with(self)
1563 }
1564 }
1565 let mut param_count = CountParams::default();
1566 let has_region = pred.visit_with(&mut param_count).is_break();
1567 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1568 if instantiated_pred.has_non_region_param()
1571 || param_count.params.len() > 1
1572 || has_region
1573 {
1574 None
1575 } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1576 None
1578 } else {
1579 Some((instantiated_pred, sp))
1580 }
1581 })
1582 .map(|(pred, sp)| {
1583 let pred = wfcx.normalize(sp, None, pred);
1593 let cause = traits::ObligationCause::new(
1594 sp,
1595 wfcx.body_def_id,
1596 ObligationCauseCode::WhereClause(def_id.to_def_id(), DUMMY_SP),
1597 );
1598 Obligation::new(tcx, cause, wfcx.param_env, pred)
1599 });
1600
1601 let predicates = predicates.instantiate_identity(tcx);
1602
1603 let predicates = wfcx.normalize(span, None, predicates);
1604
1605 debug!(?predicates.predicates);
1606 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1607 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1608 traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1609 });
1610 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1611 wfcx.register_obligations(obligations);
1612}
1613
1614#[instrument(level = "debug", skip(wfcx, span, hir_decl))]
1615fn check_fn_or_method<'tcx>(
1616 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1617 span: Span,
1618 sig: ty::PolyFnSig<'tcx>,
1619 hir_decl: &hir::FnDecl<'_>,
1620 def_id: LocalDefId,
1621) {
1622 let tcx = wfcx.tcx();
1623 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1624
1625 let arg_span =
1631 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1632
1633 sig.inputs_and_output =
1634 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1635 wfcx.deeply_normalize(
1636 arg_span(idx),
1637 Some(WellFormedLoc::Param {
1638 function: def_id,
1639 param_idx: idx,
1642 }),
1643 ty,
1644 )
1645 }));
1646
1647 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1648 wfcx.register_wf_obligation(
1649 arg_span(idx),
1650 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1651 ty.into(),
1652 );
1653 }
1654
1655 check_where_clauses(wfcx, span, def_id);
1656
1657 if sig.abi == ExternAbi::RustCall {
1658 let span = tcx.def_span(def_id);
1659 let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1660 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1661 if let Some(ty) = inputs.next() {
1663 wfcx.register_bound(
1664 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1665 wfcx.param_env,
1666 *ty,
1667 tcx.require_lang_item(hir::LangItem::Tuple, span),
1668 );
1669 wfcx.register_bound(
1670 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1671 wfcx.param_env,
1672 *ty,
1673 tcx.require_lang_item(hir::LangItem::Sized, span),
1674 );
1675 } else {
1676 tcx.dcx().span_err(
1677 hir_decl.inputs.last().map_or(span, |input| input.span),
1678 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1679 );
1680 }
1681 if inputs.next().is_some() {
1683 tcx.dcx().span_err(
1684 hir_decl.inputs.last().map_or(span, |input| input.span),
1685 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1686 );
1687 }
1688 }
1689
1690 check_sized_if_body(
1692 wfcx,
1693 def_id,
1694 sig.output(),
1695 match hir_decl.output {
1696 hir::FnRetTy::Return(ty) => Some(ty.span),
1697 hir::FnRetTy::DefaultReturn(_) => None,
1698 },
1699 ObligationCauseCode::SizedReturnType,
1700 );
1701}
1702
1703fn check_sized_if_body<'tcx>(
1704 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1705 def_id: LocalDefId,
1706 ty: Ty<'tcx>,
1707 maybe_span: Option<Span>,
1708 code: ObligationCauseCode<'tcx>,
1709) {
1710 let tcx = wfcx.tcx();
1711 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1712 let span = maybe_span.unwrap_or(body.value.span);
1713
1714 wfcx.register_bound(
1715 ObligationCause::new(span, def_id, code),
1716 wfcx.param_env,
1717 ty,
1718 tcx.require_lang_item(LangItem::Sized, span),
1719 );
1720 }
1721}
1722
1723#[derive(Clone, Copy, PartialEq)]
1725enum ArbitrarySelfTypesLevel {
1726 Basic, WithPointers, }
1729
1730#[instrument(level = "debug", skip(wfcx))]
1731fn check_method_receiver<'tcx>(
1732 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1733 fn_sig: &hir::FnSig<'_>,
1734 method: ty::AssocItem,
1735 self_ty: Ty<'tcx>,
1736) -> Result<(), ErrorGuaranteed> {
1737 let tcx = wfcx.tcx();
1738
1739 if !method.is_method() {
1740 return Ok(());
1741 }
1742
1743 let span = fn_sig.decl.inputs[0].span;
1744
1745 let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1746 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1747 let sig = wfcx.normalize(span, None, sig);
1748
1749 debug!("check_method_receiver: sig={:?}", sig);
1750
1751 let self_ty = wfcx.normalize(span, None, self_ty);
1752
1753 let receiver_ty = sig.inputs()[0];
1754 let receiver_ty = wfcx.normalize(span, None, receiver_ty);
1755
1756 if receiver_ty.references_error() {
1759 return Ok(());
1760 }
1761
1762 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1763 Some(ArbitrarySelfTypesLevel::WithPointers)
1764 } else if tcx.features().arbitrary_self_types() {
1765 Some(ArbitrarySelfTypesLevel::Basic)
1766 } else {
1767 None
1768 };
1769 let generics = tcx.generics_of(method.def_id);
1770
1771 let receiver_validity =
1772 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1773 if let Err(receiver_validity_err) = receiver_validity {
1774 return Err(match arbitrary_self_types_level {
1775 None if receiver_is_valid(
1779 wfcx,
1780 span,
1781 receiver_ty,
1782 self_ty,
1783 Some(ArbitrarySelfTypesLevel::Basic),
1784 generics,
1785 )
1786 .is_ok() =>
1787 {
1788 feature_err(
1790 &tcx.sess,
1791 sym::arbitrary_self_types,
1792 span,
1793 format!(
1794 "`{receiver_ty}` cannot be used as the type of `self` without \
1795 the `arbitrary_self_types` feature",
1796 ),
1797 )
1798 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1799 .emit()
1800 }
1801 None | Some(ArbitrarySelfTypesLevel::Basic)
1802 if receiver_is_valid(
1803 wfcx,
1804 span,
1805 receiver_ty,
1806 self_ty,
1807 Some(ArbitrarySelfTypesLevel::WithPointers),
1808 generics,
1809 )
1810 .is_ok() =>
1811 {
1812 feature_err(
1814 &tcx.sess,
1815 sym::arbitrary_self_types_pointers,
1816 span,
1817 format!(
1818 "`{receiver_ty}` cannot be used as the type of `self` without \
1819 the `arbitrary_self_types_pointers` feature",
1820 ),
1821 )
1822 .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1823 .emit()
1824 }
1825 _ =>
1826 {
1828 match receiver_validity_err {
1829 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1830 let hint = match receiver_ty
1831 .builtin_deref(false)
1832 .unwrap_or(receiver_ty)
1833 .ty_adt_def()
1834 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1835 {
1836 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1837 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1838 _ => None,
1839 };
1840
1841 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1842 }
1843 ReceiverValidityError::DoesNotDeref => {
1844 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1845 span,
1846 receiver_ty,
1847 })
1848 }
1849 ReceiverValidityError::MethodGenericParamUsed => {
1850 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1851 }
1852 }
1853 }
1854 });
1855 }
1856 Ok(())
1857}
1858
1859enum ReceiverValidityError {
1863 DoesNotDeref,
1866 MethodGenericParamUsed,
1868}
1869
1870fn confirm_type_is_not_a_method_generic_param(
1873 ty: Ty<'_>,
1874 method_generics: &ty::Generics,
1875) -> Result<(), ReceiverValidityError> {
1876 if let ty::Param(param) = ty.kind() {
1877 if (param.index as usize) >= method_generics.parent_count {
1878 return Err(ReceiverValidityError::MethodGenericParamUsed);
1879 }
1880 }
1881 Ok(())
1882}
1883
1884fn receiver_is_valid<'tcx>(
1894 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1895 span: Span,
1896 receiver_ty: Ty<'tcx>,
1897 self_ty: Ty<'tcx>,
1898 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1899 method_generics: &ty::Generics,
1900) -> Result<(), ReceiverValidityError> {
1901 let infcx = wfcx.infcx;
1902 let tcx = wfcx.tcx();
1903 let cause =
1904 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1905
1906 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1908 let ocx = ObligationCtxt::new(wfcx.infcx);
1909 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1910 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1911 }) {
1912 return Ok(());
1913 }
1914
1915 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1916
1917 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1918
1919 if arbitrary_self_types_enabled.is_some() {
1923 autoderef = autoderef.use_receiver_trait();
1924 }
1925
1926 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1928 autoderef = autoderef.include_raw_pointers();
1929 }
1930
1931 while let Some((potential_self_ty, _)) = autoderef.next() {
1933 debug!(
1934 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1935 potential_self_ty, self_ty
1936 );
1937
1938 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1939
1940 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1943 let ocx = ObligationCtxt::new(wfcx.infcx);
1944 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1945 if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1946 }) {
1947 wfcx.register_obligations(autoderef.into_obligations());
1948 return Ok(());
1949 }
1950
1951 if arbitrary_self_types_enabled.is_none() {
1954 let legacy_receiver_trait_def_id =
1955 tcx.require_lang_item(LangItem::LegacyReceiver, span);
1956 if !legacy_receiver_is_implemented(
1957 wfcx,
1958 legacy_receiver_trait_def_id,
1959 cause.clone(),
1960 potential_self_ty,
1961 ) {
1962 break;
1964 }
1965
1966 wfcx.register_bound(
1968 cause.clone(),
1969 wfcx.param_env,
1970 potential_self_ty,
1971 legacy_receiver_trait_def_id,
1972 );
1973 }
1974 }
1975
1976 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1977 Err(ReceiverValidityError::DoesNotDeref)
1978}
1979
1980fn legacy_receiver_is_implemented<'tcx>(
1981 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1982 legacy_receiver_trait_def_id: DefId,
1983 cause: ObligationCause<'tcx>,
1984 receiver_ty: Ty<'tcx>,
1985) -> bool {
1986 let tcx = wfcx.tcx();
1987 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1988
1989 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1990
1991 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1992 true
1993 } else {
1994 debug!(
1995 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1996 receiver_ty
1997 );
1998 false
1999 }
2000}
2001
2002fn check_variances_for_type_defn<'tcx>(
2003 tcx: TyCtxt<'tcx>,
2004 item: &'tcx hir::Item<'tcx>,
2005 hir_generics: &hir::Generics<'tcx>,
2006) {
2007 match item.kind {
2008 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2009 }
2011 ItemKind::TyAlias(..) => {
2012 assert!(
2013 tcx.type_alias_is_lazy(item.owner_id),
2014 "should not be computing variance of non-free type alias"
2015 );
2016 }
2017 kind => span_bug!(item.span, "cannot compute the variances of {kind:?}"),
2018 }
2019
2020 let ty_predicates = tcx.predicates_of(item.owner_id);
2021 assert_eq!(ty_predicates.parent, None);
2022 let variances = tcx.variances_of(item.owner_id);
2023
2024 let mut constrained_parameters: FxHashSet<_> = variances
2025 .iter()
2026 .enumerate()
2027 .filter(|&(_, &variance)| variance != ty::Bivariant)
2028 .map(|(index, _)| Parameter(index as u32))
2029 .collect();
2030
2031 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2032
2033 let explicitly_bounded_params = LazyCell::new(|| {
2035 let icx = crate::collect::ItemCtxt::new(tcx, item.owner_id.def_id);
2036 hir_generics
2037 .predicates
2038 .iter()
2039 .filter_map(|predicate| match predicate.kind {
2040 hir::WherePredicateKind::BoundPredicate(predicate) => {
2041 match icx.lower_ty(predicate.bounded_ty).kind() {
2042 ty::Param(data) => Some(Parameter(data.index)),
2043 _ => None,
2044 }
2045 }
2046 _ => None,
2047 })
2048 .collect::<FxHashSet<_>>()
2049 });
2050
2051 let ty_generics = tcx.generics_of(item.owner_id);
2052
2053 for (index, _) in variances.iter().enumerate() {
2054 let parameter = Parameter(index as u32);
2055
2056 if constrained_parameters.contains(¶meter) {
2057 continue;
2058 }
2059
2060 let ty_param = &ty_generics.own_params[index];
2061 let hir_param = &hir_generics.params[index];
2062
2063 if ty_param.def_id != hir_param.def_id.into() {
2064 tcx.dcx().span_delayed_bug(
2072 hir_param.span,
2073 "hir generics and ty generics in different order",
2074 );
2075 continue;
2076 }
2077
2078 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2080 .type_of(item.owner_id)
2081 .instantiate_identity()
2082 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2083 {
2084 continue;
2085 }
2086
2087 match hir_param.name {
2088 hir::ParamName::Error(_) => {
2089 }
2092 _ => {
2093 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2094 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2095 }
2096 }
2097 }
2098}
2099
2100struct HasErrorDeep<'tcx> {
2102 tcx: TyCtxt<'tcx>,
2103 seen: FxHashSet<DefId>,
2104}
2105impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2106 type Result = ControlFlow<ErrorGuaranteed>;
2107
2108 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2109 match *ty.kind() {
2110 ty::Adt(def, _) => {
2111 if self.seen.insert(def.did()) {
2112 for field in def.all_fields() {
2113 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2114 }
2115 }
2116 }
2117 ty::Error(guar) => return ControlFlow::Break(guar),
2118 _ => {}
2119 }
2120 ty.super_visit_with(self)
2121 }
2122
2123 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2124 if let Err(guar) = r.error_reported() {
2125 ControlFlow::Break(guar)
2126 } else {
2127 ControlFlow::Continue(())
2128 }
2129 }
2130
2131 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2132 if let Err(guar) = c.error_reported() {
2133 ControlFlow::Break(guar)
2134 } else {
2135 ControlFlow::Continue(())
2136 }
2137 }
2138}
2139
2140fn report_bivariance<'tcx>(
2141 tcx: TyCtxt<'tcx>,
2142 param: &'tcx hir::GenericParam<'tcx>,
2143 has_explicit_bounds: bool,
2144 item: &'tcx hir::Item<'tcx>,
2145) -> ErrorGuaranteed {
2146 let param_name = param.name.ident();
2147
2148 let help = match item.kind {
2149 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2150 if let Some(def_id) = tcx.lang_items().phantom_data() {
2151 errors::UnusedGenericParameterHelp::Adt {
2152 param_name,
2153 phantom_data: tcx.def_path_str(def_id),
2154 }
2155 } else {
2156 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2157 }
2158 }
2159 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2160 item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2161 };
2162
2163 let mut usage_spans = vec![];
2164 intravisit::walk_item(
2165 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2166 item,
2167 );
2168
2169 if !usage_spans.is_empty() {
2170 let item_def_id = item.owner_id.to_def_id();
2174 let is_probably_cyclical =
2175 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2176 .visit_def(item_def_id)
2177 .is_break();
2178 if is_probably_cyclical {
2187 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2188 spans: usage_spans,
2189 param_span: param.span,
2190 param_name,
2191 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2192 help,
2193 note: (),
2194 });
2195 }
2196 }
2197
2198 let const_param_help =
2199 matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2200
2201 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2202 span: param.span,
2203 param_name,
2204 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2205 usage_spans,
2206 help,
2207 const_param_help,
2208 });
2209 diag.code(E0392);
2210 diag.emit()
2211}
2212
2213struct IsProbablyCyclical<'tcx> {
2219 tcx: TyCtxt<'tcx>,
2220 item_def_id: DefId,
2221 seen: FxHashSet<DefId>,
2222}
2223
2224impl<'tcx> IsProbablyCyclical<'tcx> {
2225 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2226 match self.tcx.def_kind(def_id) {
2227 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2228 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2229 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2230 })
2231 }
2232 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2233 self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2234 }
2235 _ => ControlFlow::Continue(()),
2236 }
2237 }
2238}
2239
2240impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2241 type Result = ControlFlow<(), ()>;
2242
2243 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2244 let def_id = match ty.kind() {
2245 ty::Adt(adt_def, _) => Some(adt_def.did()),
2246 ty::Alias(ty::Free, alias_ty) => Some(alias_ty.def_id),
2247 _ => None,
2248 };
2249 if let Some(def_id) = def_id {
2250 if def_id == self.item_def_id {
2251 return ControlFlow::Break(());
2252 }
2253 if self.seen.insert(def_id) {
2254 self.visit_def(def_id)?;
2255 }
2256 }
2257 ty.super_visit_with(self)
2258 }
2259}
2260
2261struct CollectUsageSpans<'a> {
2266 spans: &'a mut Vec<Span>,
2267 param_def_id: DefId,
2268}
2269
2270impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2271 type Result = ();
2272
2273 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2274 }
2276
2277 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2278 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2279 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2280 && def_id == self.param_def_id
2281 {
2282 self.spans.push(t.span);
2283 return;
2284 } else if let Res::SelfTyAlias { .. } = qpath.res {
2285 self.spans.push(t.span);
2286 return;
2287 }
2288 }
2289 intravisit::walk_ty(self, t);
2290 }
2291}
2292
2293impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2294 #[instrument(level = "debug", skip(self))]
2297 fn check_false_global_bounds(&mut self) {
2298 let tcx = self.ocx.infcx.tcx;
2299 let mut span = self.span;
2300 let empty_env = ty::ParamEnv::empty();
2301
2302 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2303 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2305
2306 for (pred, obligation_span) in implied_obligations {
2307 if let ty::ClauseKind::WellFormed(..) = pred.kind().skip_binder() {
2311 continue;
2312 }
2313 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2315 let pred = self.normalize(span, None, pred);
2316
2317 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2319 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2320 span = predicates
2321 .iter()
2322 .find(|pred| pred.span.contains(obligation_span))
2324 .map(|pred| pred.span)
2325 .unwrap_or(obligation_span);
2326 }
2327
2328 let obligation = Obligation::new(
2329 tcx,
2330 traits::ObligationCause::new(
2331 span,
2332 self.body_def_id,
2333 ObligationCauseCode::TrivialBound,
2334 ),
2335 empty_env,
2336 pred,
2337 );
2338 self.ocx.register_obligation(obligation);
2339 }
2340 }
2341 }
2342}
2343
2344fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2345 let items = tcx.hir_crate_items(());
2346 let res = items
2347 .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2348 .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2349 .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2350 .and(
2351 items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2352 )
2353 .and(items.par_nested_bodies(|item| tcx.ensure_ok().check_well_formed(item)))
2354 .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2355 super::entry::check_for_entry_fn(tcx);
2356
2357 res
2358}
2359
2360fn lint_redundant_lifetimes<'tcx>(
2361 tcx: TyCtxt<'tcx>,
2362 owner_id: LocalDefId,
2363 outlives_env: &OutlivesEnvironment<'tcx>,
2364) {
2365 let def_kind = tcx.def_kind(owner_id);
2366 match def_kind {
2367 DefKind::Struct
2368 | DefKind::Union
2369 | DefKind::Enum
2370 | DefKind::Trait
2371 | DefKind::TraitAlias
2372 | DefKind::Fn
2373 | DefKind::Const
2374 | DefKind::Impl { of_trait: _ } => {
2375 }
2377 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2378 let parent_def_id = tcx.local_parent(owner_id);
2379 if matches!(tcx.def_kind(parent_def_id), DefKind::Impl { of_trait: true }) {
2380 return;
2385 }
2386 }
2387 DefKind::Mod
2388 | DefKind::Variant
2389 | DefKind::TyAlias
2390 | DefKind::ForeignTy
2391 | DefKind::TyParam
2392 | DefKind::ConstParam
2393 | DefKind::Static { .. }
2394 | DefKind::Ctor(_, _)
2395 | DefKind::Macro(_)
2396 | DefKind::ExternCrate
2397 | DefKind::Use
2398 | DefKind::ForeignMod
2399 | DefKind::AnonConst
2400 | DefKind::InlineConst
2401 | DefKind::OpaqueTy
2402 | DefKind::Field
2403 | DefKind::LifetimeParam
2404 | DefKind::GlobalAsm
2405 | DefKind::Closure
2406 | DefKind::SyntheticCoroutineBody => return,
2407 }
2408
2409 let mut lifetimes = vec![tcx.lifetimes.re_static];
2418 lifetimes.extend(
2419 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2420 );
2421 if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2423 for (idx, var) in
2424 tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2425 {
2426 let ty::BoundVariableKind::Region(kind) = var else { continue };
2427 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2428 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2429 }
2430 }
2431 lifetimes.retain(|candidate| candidate.has_name());
2432
2433 let mut shadowed = FxHashSet::default();
2437
2438 for (idx, &candidate) in lifetimes.iter().enumerate() {
2439 if shadowed.contains(&candidate) {
2444 continue;
2445 }
2446
2447 for &victim in &lifetimes[(idx + 1)..] {
2448 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2456 continue;
2457 };
2458
2459 if tcx.parent(def_id) != owner_id.to_def_id() {
2464 continue;
2465 }
2466
2467 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2469 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2470 {
2471 shadowed.insert(victim);
2472 tcx.emit_node_span_lint(
2473 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2474 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2475 tcx.def_span(def_id),
2476 RedundantLifetimeArgsLint { candidate, victim },
2477 );
2478 }
2479 }
2480 }
2481}
2482
2483#[derive(LintDiagnostic)]
2484#[diag(hir_analysis_redundant_lifetime_args)]
2485#[note]
2486struct RedundantLifetimeArgsLint<'tcx> {
2487 victim: ty::Region<'tcx>,
2489 candidate: ty::Region<'tcx>,
2491}
2492
2493pub fn provide(providers: &mut Providers) {
2494 *providers = Providers { check_type_wf, check_well_formed, ..*providers };
2495}