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