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