1use std::assert_matches::assert_matches;
2
3use hir::Node;
4use rustc_data_structures::fx::FxIndexSet;
5use rustc_hir as hir;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LocalDefId};
8use rustc_middle::ty::{
9 self, GenericPredicates, ImplTraitInTraitData, Ty, TyCtxt, TypeVisitable, TypeVisitor, Upcast,
10};
11use rustc_middle::{bug, span_bug};
12use rustc_span::{DUMMY_SP, Ident, Span};
13use tracing::{debug, instrument, trace};
14
15use super::item_bounds::explicit_item_bounds_with_filter;
16use crate::collect::ItemCtxt;
17use crate::constrained_generic_params as cgp;
18use crate::delegation::inherit_predicates_for_delegation_item;
19use crate::hir_ty_lowering::{HirTyLowerer, PredicateFilter, RegionInferReason};
20
21#[instrument(level = "debug", skip(tcx))]
25pub(super) fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
26 let mut result = tcx.explicit_predicates_of(def_id);
27 debug!("predicates_of: explicit_predicates_of({:?}) = {:?}", def_id, result);
28
29 let inferred_outlives = tcx.inferred_outlives_of(def_id);
30 if !inferred_outlives.is_empty() {
31 debug!("predicates_of: inferred_outlives_of({:?}) = {:?}", def_id, inferred_outlives,);
32 let inferred_outlives_iter =
33 inferred_outlives.iter().map(|(clause, span)| ((*clause).upcast(tcx), *span));
34 if result.predicates.is_empty() {
35 result.predicates = tcx.arena.alloc_from_iter(inferred_outlives_iter);
36 } else {
37 result.predicates = tcx.arena.alloc_from_iter(
38 result.predicates.into_iter().copied().chain(inferred_outlives_iter),
39 );
40 }
41 }
42
43 if tcx.is_trait(def_id) {
44 let span = DUMMY_SP;
62
63 result.predicates = tcx.arena.alloc_from_iter(
64 result
65 .predicates
66 .iter()
67 .copied()
68 .chain(std::iter::once((ty::TraitRef::identity(tcx, def_id).upcast(tcx), span))),
69 );
70 }
71
72 debug!("predicates_of({:?}) = {:?}", def_id, result);
73 result
74}
75
76#[instrument(level = "trace", skip(tcx), ret)]
79fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::GenericPredicates<'_> {
80 use rustc_hir::*;
81
82 match tcx.opt_rpitit_info(def_id.to_def_id()) {
83 Some(ImplTraitInTraitData::Trait { fn_def_id, .. }) => {
84 let mut predicates = Vec::new();
85
86 let identity_args = ty::GenericArgs::identity_for_item(tcx, def_id);
91 predicates
92 .extend(tcx.explicit_predicates_of(fn_def_id).instantiate_own(tcx, identity_args));
93
94 compute_bidirectional_outlives_predicates(
99 tcx,
100 &tcx.generics_of(def_id.to_def_id()).own_params
101 [tcx.generics_of(fn_def_id).own_params.len()..],
102 &mut predicates,
103 );
104
105 return ty::GenericPredicates {
106 parent: Some(tcx.parent(def_id.to_def_id())),
107 predicates: tcx.arena.alloc_from_iter(predicates),
108 };
109 }
110
111 Some(ImplTraitInTraitData::Impl { fn_def_id }) => {
112 let assoc_item = tcx.associated_item(def_id);
113 let trait_assoc_predicates =
114 tcx.explicit_predicates_of(assoc_item.trait_item_def_id.unwrap());
115
116 let impl_assoc_identity_args = ty::GenericArgs::identity_for_item(tcx, def_id);
117 let impl_def_id = tcx.parent(fn_def_id);
118 let impl_trait_ref_args =
119 tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity().args;
120
121 let impl_assoc_args =
122 impl_assoc_identity_args.rebase_onto(tcx, impl_def_id, impl_trait_ref_args);
123
124 let impl_predicates = trait_assoc_predicates.instantiate_own(tcx, impl_assoc_args);
125
126 return ty::GenericPredicates {
127 parent: Some(impl_def_id),
128 predicates: tcx.arena.alloc_from_iter(impl_predicates),
129 };
130 }
131
132 None => {}
133 }
134
135 let hir_id = tcx.local_def_id_to_hir_id(def_id);
136 let node = tcx.hir_node(hir_id);
137
138 if let Some(sig) = node.fn_sig()
139 && let Some(sig_id) = sig.decl.opt_delegation_sig_id()
140 {
141 return inherit_predicates_for_delegation_item(tcx, def_id, sig_id);
142 }
143
144 let mut is_trait = None;
145 let mut is_default_impl_trait = None;
146
147 let icx = ItemCtxt::new(tcx, def_id);
148
149 const NO_GENERICS: &hir::Generics<'_> = hir::Generics::empty();
150
151 let mut predicates: FxIndexSet<(ty::Clause<'_>, Span)> = FxIndexSet::default();
154
155 let hir_generics = node.generics().unwrap_or(NO_GENERICS);
156 if let Node::Item(item) = node {
157 match item.kind {
158 ItemKind::Impl(impl_) => {
159 if impl_.defaultness.is_default() {
160 is_default_impl_trait = tcx
161 .impl_trait_ref(def_id)
162 .map(|t| ty::Binder::dummy(t.instantiate_identity()));
163 }
164 }
165 ItemKind::Trait(_, _, _, _, self_bounds, ..)
166 | ItemKind::TraitAlias(_, _, self_bounds) => {
167 is_trait = Some((self_bounds, item.span));
168 }
169 _ => {}
170 }
171 };
172
173 if let Node::TraitItem(item) = node {
174 let mut bounds = Vec::new();
175 icx.lowerer().add_default_trait_item_bounds(item, &mut bounds);
176 predicates.extend(bounds);
177 }
178
179 let generics = tcx.generics_of(def_id);
180
181 if let Some((self_bounds, span)) = is_trait {
186 let mut bounds = Vec::new();
187 icx.lowerer().lower_bounds(
188 tcx.types.self_param,
189 self_bounds,
190 &mut bounds,
191 ty::List::empty(),
192 PredicateFilter::All,
193 );
194 icx.lowerer().add_sizedness_bounds(
195 &mut bounds,
196 tcx.types.self_param,
197 self_bounds,
198 None,
199 Some(def_id),
200 span,
201 );
202 icx.lowerer().add_default_super_traits(
203 def_id,
204 &mut bounds,
205 self_bounds,
206 hir_generics,
207 span,
208 );
209 predicates.extend(bounds);
210 }
211
212 if let Some(trait_ref) = is_default_impl_trait {
221 predicates.insert((trait_ref.upcast(tcx), tcx.def_span(def_id)));
222 }
223
224 for param in hir_generics.params {
228 match param.kind {
229 GenericParamKind::Lifetime { .. } => (),
230 GenericParamKind::Type { .. } => {
231 let param_ty = icx.lowerer().lower_ty_param(param.hir_id);
232 let mut bounds = Vec::new();
233 icx.lowerer().add_sizedness_bounds(
235 &mut bounds,
236 param_ty,
237 &[],
238 Some((param.def_id, hir_generics.predicates)),
239 None,
240 param.span,
241 );
242 icx.lowerer().add_default_traits(
243 &mut bounds,
244 param_ty,
245 &[],
246 Some((param.def_id, hir_generics.predicates)),
247 param.span,
248 );
249 trace!(?bounds);
250 predicates.extend(bounds);
251 trace!(?predicates);
252 }
253 hir::GenericParamKind::Const { .. } => {
254 let param_def_id = param.def_id.to_def_id();
255 let ct_ty = tcx.type_of(param_def_id).instantiate_identity();
256 let ct = icx.lowerer().lower_const_param(param_def_id, param.hir_id);
257 predicates
258 .insert((ty::ClauseKind::ConstArgHasType(ct, ct_ty).upcast(tcx), param.span));
259 }
260 }
261 }
262
263 trace!(?predicates);
264 for predicate in hir_generics.predicates {
266 match predicate.kind {
267 hir::WherePredicateKind::BoundPredicate(bound_pred) => {
268 let ty = icx.lowerer().lower_ty_maybe_return_type_notation(bound_pred.bounded_ty);
269
270 let bound_vars = tcx.late_bound_vars(predicate.hir_id);
271 if bound_pred.bounds.is_empty() {
275 if let ty::Param(_) = ty.kind() {
276 } else {
283 let span = bound_pred.bounded_ty.span;
284 let predicate = ty::Binder::bind_with_vars(
285 ty::ClauseKind::WellFormed(ty.into()),
286 bound_vars,
287 );
288 predicates.insert((predicate.upcast(tcx), span));
289 }
290 }
291
292 let mut bounds = Vec::new();
293 icx.lowerer().lower_bounds(
294 ty,
295 bound_pred.bounds,
296 &mut bounds,
297 bound_vars,
298 PredicateFilter::All,
299 );
300 predicates.extend(bounds);
301 }
302
303 hir::WherePredicateKind::RegionPredicate(region_pred) => {
304 let r1 = icx
305 .lowerer()
306 .lower_lifetime(region_pred.lifetime, RegionInferReason::RegionPredicate);
307 predicates.extend(region_pred.bounds.iter().map(|bound| {
308 let (r2, span) = match bound {
309 hir::GenericBound::Outlives(lt) => (
310 icx.lowerer().lower_lifetime(lt, RegionInferReason::RegionPredicate),
311 lt.ident.span,
312 ),
313 bound => {
314 span_bug!(
315 bound.span(),
316 "lifetime param bounds must be outlives, but found {bound:?}"
317 )
318 }
319 };
320 let pred =
321 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(r1, r2)).upcast(tcx);
322 (pred, span)
323 }))
324 }
325
326 hir::WherePredicateKind::EqPredicate(..) => {
327 }
329 }
330 }
331
332 if tcx.features().generic_const_exprs() {
333 predicates.extend(const_evaluatable_predicates_of(tcx, def_id, &predicates));
334 }
335
336 let mut predicates: Vec<_> = predicates.into_iter().collect();
337
338 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
344 let self_ty = tcx.type_of(def_id).instantiate_identity();
345 let trait_ref = tcx.impl_trait_ref(def_id).map(ty::EarlyBinder::instantiate_identity);
346 cgp::setup_constraining_predicates(
347 tcx,
348 &mut predicates,
349 trait_ref,
350 &mut cgp::parameters_for_impl(tcx, self_ty, trait_ref),
351 );
352 }
353
354 if let Node::OpaqueTy(..) = node {
358 compute_bidirectional_outlives_predicates(tcx, &generics.own_params, &mut predicates);
359 debug!(?predicates);
360 }
361
362 ty::GenericPredicates {
363 parent: generics.parent,
364 predicates: tcx.arena.alloc_from_iter(predicates),
365 }
366}
367
368fn compute_bidirectional_outlives_predicates<'tcx>(
371 tcx: TyCtxt<'tcx>,
372 opaque_own_params: &[ty::GenericParamDef],
373 predicates: &mut Vec<(ty::Clause<'tcx>, Span)>,
374) {
375 for param in opaque_own_params {
376 let orig_lifetime = tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local());
377 if let ty::ReEarlyParam(..) = orig_lifetime.kind() {
378 let dup_lifetime = ty::Region::new_early_param(
379 tcx,
380 ty::EarlyParamRegion { index: param.index, name: param.name },
381 );
382 let span = tcx.def_span(param.def_id);
383 predicates.push((
384 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(orig_lifetime, dup_lifetime))
385 .upcast(tcx),
386 span,
387 ));
388 predicates.push((
389 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(dup_lifetime, orig_lifetime))
390 .upcast(tcx),
391 span,
392 ));
393 }
394 }
395}
396
397#[instrument(level = "debug", skip(tcx, predicates), ret)]
398fn const_evaluatable_predicates_of<'tcx>(
399 tcx: TyCtxt<'tcx>,
400 def_id: LocalDefId,
401 predicates: &FxIndexSet<(ty::Clause<'tcx>, Span)>,
402) -> FxIndexSet<(ty::Clause<'tcx>, Span)> {
403 struct ConstCollector<'tcx> {
404 tcx: TyCtxt<'tcx>,
405 preds: FxIndexSet<(ty::Clause<'tcx>, Span)>,
406 }
407
408 fn is_const_param_default(tcx: TyCtxt<'_>, def: LocalDefId) -> bool {
409 let hir_id = tcx.local_def_id_to_hir_id(def);
410 let (_, parent_node) = tcx
411 .hir_parent_iter(hir_id)
412 .skip_while(|(_, n)| matches!(n, Node::ConstArg(..)))
413 .next()
414 .unwrap();
415 matches!(
416 parent_node,
417 Node::GenericParam(hir::GenericParam { kind: hir::GenericParamKind::Const { .. }, .. })
418 )
419 }
420
421 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ConstCollector<'tcx> {
422 fn visit_const(&mut self, c: ty::Const<'tcx>) {
423 if let ty::ConstKind::Unevaluated(uv) = c.kind() {
424 if is_const_param_default(self.tcx, uv.def.expect_local()) {
425 return;
433 }
434
435 let span = self.tcx.def_span(uv.def);
436 self.preds.insert((ty::ClauseKind::ConstEvaluatable(c).upcast(self.tcx), span));
437 }
438 }
439 }
440
441 let hir_id = tcx.local_def_id_to_hir_id(def_id);
442 let node = tcx.hir_node(hir_id);
443
444 let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() };
445
446 for (clause, _sp) in predicates {
447 clause.visit_with(&mut collector);
448 }
449
450 if let hir::Node::Item(item) = node
451 && let hir::ItemKind::Impl(_) = item.kind
452 {
453 if let Some(of_trait) = tcx.impl_trait_ref(def_id) {
454 debug!("visit impl trait_ref");
455 of_trait.instantiate_identity().visit_with(&mut collector);
456 }
457
458 debug!("visit self_ty");
459 let self_ty = tcx.type_of(def_id);
460 self_ty.instantiate_identity().visit_with(&mut collector);
461 }
462
463 if let Some(_) = tcx.hir_fn_sig_by_hir_id(hir_id) {
464 debug!("visit fn sig");
465 let fn_sig = tcx.fn_sig(def_id);
466 let fn_sig = fn_sig.instantiate_identity();
467 debug!(?fn_sig);
468 fn_sig.visit_with(&mut collector);
469 }
470
471 collector.preds
472}
473
474pub(super) fn trait_explicit_predicates_and_bounds(
475 tcx: TyCtxt<'_>,
476 def_id: LocalDefId,
477) -> ty::GenericPredicates<'_> {
478 assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
479 gather_explicit_predicates_of(tcx, def_id)
480}
481
482pub(super) fn explicit_predicates_of<'tcx>(
483 tcx: TyCtxt<'tcx>,
484 def_id: LocalDefId,
485) -> ty::GenericPredicates<'tcx> {
486 let def_kind = tcx.def_kind(def_id);
487 if let DefKind::Trait = def_kind {
488 let predicates_and_bounds = tcx.trait_explicit_predicates_and_bounds(def_id);
491 let trait_identity_args = ty::GenericArgs::identity_for_item(tcx, def_id);
492
493 let is_assoc_item_ty = |ty: Ty<'tcx>| {
494 if let ty::Alias(ty::Projection, projection) = ty.kind() {
504 projection.args == trait_identity_args
505 && !tcx.is_impl_trait_in_trait(projection.def_id)
507 && tcx.associated_item(projection.def_id).container_id(tcx)
508 == def_id.to_def_id()
509 } else {
510 false
511 }
512 };
513
514 let predicates: Vec<_> = predicates_and_bounds
515 .predicates
516 .iter()
517 .copied()
518 .filter(|(pred, _)| match pred.kind().skip_binder() {
519 ty::ClauseKind::Trait(tr) => !is_assoc_item_ty(tr.self_ty()),
520 ty::ClauseKind::Projection(proj) => {
521 !is_assoc_item_ty(proj.projection_term.self_ty())
522 }
523 ty::ClauseKind::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0),
524 _ => true,
525 })
526 .collect();
527 if predicates.len() == predicates_and_bounds.predicates.len() {
528 predicates_and_bounds
529 } else {
530 ty::GenericPredicates {
531 parent: predicates_and_bounds.parent,
532 predicates: tcx.arena.alloc_slice(&predicates),
533 }
534 }
535 } else {
536 if matches!(def_kind, DefKind::AnonConst)
537 && tcx.features().generic_const_exprs()
538 && let Some(defaulted_param_def_id) =
539 tcx.hir_opt_const_param_default_param_def_id(tcx.local_def_id_to_hir_id(def_id))
540 {
541 let parent_def_id = tcx.local_parent(def_id);
554 let parent_preds = tcx.explicit_predicates_of(parent_def_id);
555
556 let filtered_predicates = parent_preds
560 .predicates
561 .into_iter()
562 .filter(|(pred, _)| {
563 if let ty::ClauseKind::ConstArgHasType(ct, _) = pred.kind().skip_binder() {
564 match ct.kind() {
565 ty::ConstKind::Param(param_const) => {
566 let defaulted_param_idx = tcx
567 .generics_of(parent_def_id)
568 .param_def_id_to_index[&defaulted_param_def_id.to_def_id()];
569 param_const.index < defaulted_param_idx
570 }
571 _ => bug!(
572 "`ConstArgHasType` in `predicates_of`\
573 that isn't a `Param` const"
574 ),
575 }
576 } else {
577 true
578 }
579 })
580 .cloned();
581 return GenericPredicates {
582 parent: parent_preds.parent,
583 predicates: { tcx.arena.alloc_from_iter(filtered_predicates) },
584 };
585 }
586 gather_explicit_predicates_of(tcx, def_id)
587 }
588}
589
590pub(super) fn explicit_super_predicates_of<'tcx>(
594 tcx: TyCtxt<'tcx>,
595 trait_def_id: LocalDefId,
596) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
597 implied_predicates_with_filter(tcx, trait_def_id.to_def_id(), PredicateFilter::SelfOnly)
598}
599
600pub(super) fn explicit_supertraits_containing_assoc_item<'tcx>(
601 tcx: TyCtxt<'tcx>,
602 (trait_def_id, assoc_ident): (DefId, Ident),
603) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
604 implied_predicates_with_filter(
605 tcx,
606 trait_def_id,
607 PredicateFilter::SelfTraitThatDefines(assoc_ident),
608 )
609}
610
611pub(super) fn explicit_implied_predicates_of<'tcx>(
612 tcx: TyCtxt<'tcx>,
613 trait_def_id: LocalDefId,
614) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
615 implied_predicates_with_filter(
616 tcx,
617 trait_def_id.to_def_id(),
618 if tcx.is_trait_alias(trait_def_id.to_def_id()) {
619 PredicateFilter::All
620 } else {
621 PredicateFilter::SelfAndAssociatedTypeBounds
622 },
623 )
624}
625
626pub(super) fn implied_predicates_with_filter<'tcx>(
630 tcx: TyCtxt<'tcx>,
631 trait_def_id: DefId,
632 filter: PredicateFilter,
633) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
634 let Some(trait_def_id) = trait_def_id.as_local() else {
635 assert_matches!(filter, PredicateFilter::SelfTraitThatDefines(_));
638 return tcx.explicit_super_predicates_of(trait_def_id);
639 };
640
641 let Node::Item(item) = tcx.hir_node_by_def_id(trait_def_id) else {
642 bug!("trait_def_id {trait_def_id:?} is not an item");
643 };
644
645 let (generics, superbounds) = match item.kind {
646 hir::ItemKind::Trait(.., generics, supertraits, _) => (generics, supertraits),
647 hir::ItemKind::TraitAlias(_, generics, supertraits) => (generics, supertraits),
648 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
649 };
650
651 let icx = ItemCtxt::new(tcx, trait_def_id);
652
653 let self_param_ty = tcx.types.self_param;
654 let mut bounds = Vec::new();
655 icx.lowerer().lower_bounds(self_param_ty, superbounds, &mut bounds, ty::List::empty(), filter);
656 match filter {
657 PredicateFilter::All
658 | PredicateFilter::SelfOnly
659 | PredicateFilter::SelfTraitThatDefines(_)
660 | PredicateFilter::SelfAndAssociatedTypeBounds => {
661 icx.lowerer().add_default_super_traits(
662 trait_def_id,
663 &mut bounds,
664 superbounds,
665 generics,
666 item.span,
667 );
668 }
669 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
671 }
672
673 let where_bounds_that_match =
674 icx.probe_ty_param_bounds_in_generics(generics, item.owner_id.def_id, filter);
675
676 let implied_bounds =
678 &*tcx.arena.alloc_from_iter(bounds.into_iter().chain(where_bounds_that_match));
679 debug!(?implied_bounds);
680
681 match filter {
686 PredicateFilter::SelfOnly => {
687 for &(pred, span) in implied_bounds {
688 debug!("superbound: {:?}", pred);
689 if let ty::ClauseKind::Trait(bound) = pred.kind().skip_binder()
690 && bound.polarity == ty::PredicatePolarity::Positive
691 {
692 tcx.at(span).explicit_super_predicates_of(bound.def_id());
693 }
694 }
695 }
696 PredicateFilter::All | PredicateFilter::SelfAndAssociatedTypeBounds => {
697 for &(pred, span) in implied_bounds {
698 debug!("superbound: {:?}", pred);
699 if let ty::ClauseKind::Trait(bound) = pred.kind().skip_binder()
700 && bound.polarity == ty::PredicatePolarity::Positive
701 {
702 tcx.at(span).explicit_implied_predicates_of(bound.def_id());
703 }
704 }
705 }
706 _ => {}
707 }
708
709 assert_only_contains_predicates_from(filter, implied_bounds, tcx.types.self_param);
710
711 ty::EarlyBinder::bind(implied_bounds)
712}
713
714pub(super) fn assert_only_contains_predicates_from<'tcx>(
718 filter: PredicateFilter,
719 bounds: &'tcx [(ty::Clause<'tcx>, Span)],
720 ty: Ty<'tcx>,
721) {
722 if !cfg!(debug_assertions) {
723 return;
724 }
725
726 match filter {
727 PredicateFilter::SelfOnly => {
728 for (clause, _) in bounds {
729 match clause.kind().skip_binder() {
730 ty::ClauseKind::Trait(trait_predicate) => {
731 assert_eq!(
732 trait_predicate.self_ty(),
733 ty,
734 "expected `Self` predicate when computing \
735 `{filter:?}` implied bounds: {clause:?}"
736 );
737 }
738 ty::ClauseKind::Projection(projection_predicate) => {
739 assert_eq!(
740 projection_predicate.self_ty(),
741 ty,
742 "expected `Self` predicate when computing \
743 `{filter:?}` implied bounds: {clause:?}"
744 );
745 }
746 ty::ClauseKind::TypeOutlives(outlives_predicate) => {
747 assert_eq!(
748 outlives_predicate.0, ty,
749 "expected `Self` predicate when computing \
750 `{filter:?}` implied bounds: {clause:?}"
751 );
752 }
753 ty::ClauseKind::HostEffect(host_effect_predicate) => {
754 assert_eq!(
755 host_effect_predicate.self_ty(),
756 ty,
757 "expected `Self` predicate when computing \
758 `{filter:?}` implied bounds: {clause:?}"
759 );
760 }
761
762 ty::ClauseKind::RegionOutlives(_)
763 | ty::ClauseKind::ConstArgHasType(_, _)
764 | ty::ClauseKind::WellFormed(_)
765 | ty::ClauseKind::ConstEvaluatable(_) => {
766 bug!(
767 "unexpected non-`Self` predicate when computing \
768 `{filter:?}` implied bounds: {clause:?}"
769 );
770 }
771 }
772 }
773 }
774 PredicateFilter::SelfTraitThatDefines(_) => {
775 for (clause, _) in bounds {
776 match clause.kind().skip_binder() {
777 ty::ClauseKind::Trait(trait_predicate) => {
778 assert_eq!(
779 trait_predicate.self_ty(),
780 ty,
781 "expected `Self` predicate when computing \
782 `{filter:?}` implied bounds: {clause:?}"
783 );
784 }
785
786 ty::ClauseKind::Projection(_)
787 | ty::ClauseKind::TypeOutlives(_)
788 | ty::ClauseKind::RegionOutlives(_)
789 | ty::ClauseKind::ConstArgHasType(_, _)
790 | ty::ClauseKind::WellFormed(_)
791 | ty::ClauseKind::ConstEvaluatable(_)
792 | ty::ClauseKind::HostEffect(..) => {
793 bug!(
794 "unexpected non-`Self` predicate when computing \
795 `{filter:?}` implied bounds: {clause:?}"
796 );
797 }
798 }
799 }
800 }
801 PredicateFilter::ConstIfConst => {
802 for (clause, _) in bounds {
803 match clause.kind().skip_binder() {
804 ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
805 trait_ref: _,
806 constness: ty::BoundConstness::Maybe,
807 }) => {}
808 _ => {
809 bug!(
810 "unexpected non-`HostEffect` predicate when computing \
811 `{filter:?}` implied bounds: {clause:?}"
812 );
813 }
814 }
815 }
816 }
817 PredicateFilter::SelfConstIfConst => {
818 for (clause, _) in bounds {
819 match clause.kind().skip_binder() {
820 ty::ClauseKind::HostEffect(pred) => {
821 assert_eq!(
822 pred.constness,
823 ty::BoundConstness::Maybe,
824 "expected `~const` predicate when computing `{filter:?}` \
825 implied bounds: {clause:?}",
826 );
827 assert_eq!(
828 pred.trait_ref.self_ty(),
829 ty,
830 "expected `Self` predicate when computing `{filter:?}` \
831 implied bounds: {clause:?}"
832 );
833 }
834 _ => {
835 bug!(
836 "unexpected non-`HostEffect` predicate when computing \
837 `{filter:?}` implied bounds: {clause:?}"
838 );
839 }
840 }
841 }
842 }
843 PredicateFilter::All | PredicateFilter::SelfAndAssociatedTypeBounds => {}
844 }
845}
846
847#[instrument(level = "trace", skip(tcx))]
850pub(super) fn type_param_predicates<'tcx>(
851 tcx: TyCtxt<'tcx>,
852 (item_def_id, def_id, assoc_ident): (LocalDefId, LocalDefId, Ident),
853) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
854 match tcx.opt_rpitit_info(item_def_id.to_def_id()) {
855 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
856 return tcx.type_param_predicates((opaque_def_id.expect_local(), def_id, assoc_ident));
857 }
858 Some(ty::ImplTraitInTraitData::Impl { .. }) => {
859 unreachable!("should not be lowering bounds on RPITIT in impl")
860 }
861 None => {}
862 }
863
864 let param_id = tcx.local_def_id_to_hir_id(def_id);
869 let param_owner = tcx.hir_ty_param_owner(def_id);
870
871 let parent = if item_def_id == param_owner {
873 None
875 } else {
876 tcx.generics_of(item_def_id).parent.map(|def_id| def_id.expect_local())
877 };
878
879 let result = if let Some(parent) = parent {
880 let icx = ItemCtxt::new(tcx, parent);
881 icx.probe_ty_param_bounds(DUMMY_SP, def_id, assoc_ident)
882 } else {
883 ty::EarlyBinder::bind(&[] as &[_])
884 };
885 let mut extend = None;
886
887 let item_hir_id = tcx.local_def_id_to_hir_id(item_def_id);
888
889 let hir_node = tcx.hir_node(item_hir_id);
890 let Some(hir_generics) = hir_node.generics() else {
891 return result;
892 };
893
894 if let Node::Item(item) = hir_node
895 && let hir::ItemKind::Trait(..) = item.kind
896 && param_id == item_hir_id
898 {
899 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id.to_def_id());
900 extend = Some((identity_trait_ref.upcast(tcx), item.span));
901 }
902
903 let icx = ItemCtxt::new(tcx, item_def_id);
904 let extra_predicates = extend.into_iter().chain(icx.probe_ty_param_bounds_in_generics(
905 hir_generics,
906 def_id,
907 PredicateFilter::SelfTraitThatDefines(assoc_ident),
908 ));
909
910 let bounds =
911 &*tcx.arena.alloc_from_iter(result.skip_binder().iter().copied().chain(extra_predicates));
912
913 let self_ty = match tcx.def_kind(def_id) {
915 DefKind::TyParam => Ty::new_param(
916 tcx,
917 tcx.generics_of(item_def_id)
918 .param_def_id_to_index(tcx, def_id.to_def_id())
919 .expect("expected generic param to be owned by item"),
920 tcx.item_name(def_id.to_def_id()),
921 ),
922 DefKind::Trait | DefKind::TraitAlias => tcx.types.self_param,
923 _ => unreachable!(),
924 };
925 assert_only_contains_predicates_from(
926 PredicateFilter::SelfTraitThatDefines(assoc_ident),
927 bounds,
928 self_ty,
929 );
930
931 ty::EarlyBinder::bind(bounds)
932}
933
934impl<'tcx> ItemCtxt<'tcx> {
935 #[instrument(level = "trace", skip(self, hir_generics))]
941 fn probe_ty_param_bounds_in_generics(
942 &self,
943 hir_generics: &'tcx hir::Generics<'tcx>,
944 param_def_id: LocalDefId,
945 filter: PredicateFilter,
946 ) -> Vec<(ty::Clause<'tcx>, Span)> {
947 let mut bounds = Vec::new();
948
949 for predicate in hir_generics.predicates {
950 let hir_id = predicate.hir_id;
951 let hir::WherePredicateKind::BoundPredicate(predicate) = predicate.kind else {
952 continue;
953 };
954
955 match filter {
956 _ if predicate.is_param_bound(param_def_id.to_def_id()) => {
957 }
959 PredicateFilter::All => {
960 }
962 PredicateFilter::SelfOnly
963 | PredicateFilter::SelfTraitThatDefines(_)
964 | PredicateFilter::SelfConstIfConst
965 | PredicateFilter::SelfAndAssociatedTypeBounds => continue,
966 PredicateFilter::ConstIfConst => unreachable!(),
967 }
968
969 let bound_ty = self.lowerer().lower_ty_maybe_return_type_notation(predicate.bounded_ty);
970
971 let bound_vars = self.tcx.late_bound_vars(hir_id);
972 self.lowerer().lower_bounds(
973 bound_ty,
974 predicate.bounds,
975 &mut bounds,
976 bound_vars,
977 filter,
978 );
979 }
980
981 bounds
982 }
983}
984
985pub(super) fn const_conditions<'tcx>(
986 tcx: TyCtxt<'tcx>,
987 def_id: LocalDefId,
988) -> ty::ConstConditions<'tcx> {
989 if !tcx.is_conditionally_const(def_id) {
990 bug!("const_conditions invoked for item that is not conditionally const: {def_id:?}");
991 }
992
993 match tcx.opt_rpitit_info(def_id.to_def_id()) {
994 Some(
996 ty::ImplTraitInTraitData::Impl { fn_def_id }
997 | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
998 ) => return tcx.const_conditions(fn_def_id),
999 None => {}
1000 }
1001
1002 let (generics, trait_def_id_and_supertraits, has_parent) = match tcx.hir_node_by_def_id(def_id)
1003 {
1004 Node::Item(item) => match item.kind {
1005 hir::ItemKind::Impl(impl_) => (impl_.generics, None, false),
1006 hir::ItemKind::Fn { generics, .. } => (generics, None, false),
1007 hir::ItemKind::Trait(_, _, _, generics, supertraits, _) => {
1008 (generics, Some((item.owner_id.def_id, supertraits)), false)
1009 }
1010 _ => bug!("const_conditions called on wrong item: {def_id:?}"),
1011 },
1012 Node::TraitItem(item) => match item.kind {
1017 hir::TraitItemKind::Fn(_, _) | hir::TraitItemKind::Type(_, _) => {
1018 (item.generics, None, true)
1019 }
1020 _ => bug!("const_conditions called on wrong item: {def_id:?}"),
1021 },
1022 Node::ImplItem(item) => match item.kind {
1023 hir::ImplItemKind::Fn(_, _) | hir::ImplItemKind::Type(_) => {
1024 (item.generics, None, tcx.is_conditionally_const(tcx.local_parent(def_id)))
1025 }
1026 _ => bug!("const_conditions called on wrong item: {def_id:?}"),
1027 },
1028 Node::ForeignItem(item) => match item.kind {
1029 hir::ForeignItemKind::Fn(_, _, generics) => (generics, None, false),
1030 _ => bug!("const_conditions called on wrong item: {def_id:?}"),
1031 },
1032 Node::OpaqueTy(opaque) => match opaque.origin {
1033 hir::OpaqueTyOrigin::FnReturn { parent, .. } => return tcx.const_conditions(parent),
1034 hir::OpaqueTyOrigin::AsyncFn { .. } | hir::OpaqueTyOrigin::TyAlias { .. } => {
1035 unreachable!()
1036 }
1037 },
1038 Node::Ctor(hir::VariantData::Tuple { .. }) => return Default::default(),
1040 _ => bug!("const_conditions called on wrong item: {def_id:?}"),
1041 };
1042
1043 let icx = ItemCtxt::new(tcx, def_id);
1044 let mut bounds = Vec::new();
1045
1046 for pred in generics.predicates {
1047 match pred.kind {
1048 hir::WherePredicateKind::BoundPredicate(bound_pred) => {
1049 let ty = icx.lowerer().lower_ty_maybe_return_type_notation(bound_pred.bounded_ty);
1050 let bound_vars = tcx.late_bound_vars(pred.hir_id);
1051 icx.lowerer().lower_bounds(
1052 ty,
1053 bound_pred.bounds.iter(),
1054 &mut bounds,
1055 bound_vars,
1056 PredicateFilter::ConstIfConst,
1057 );
1058 }
1059 _ => {}
1060 }
1061 }
1062
1063 if let Some((def_id, supertraits)) = trait_def_id_and_supertraits {
1064 bounds.push((
1066 ty::Binder::dummy(ty::TraitRef::identity(tcx, def_id.to_def_id()))
1067 .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1068 DUMMY_SP,
1069 ));
1070
1071 icx.lowerer().lower_bounds(
1072 tcx.types.self_param,
1073 supertraits,
1074 &mut bounds,
1075 ty::List::empty(),
1076 PredicateFilter::ConstIfConst,
1077 );
1078 }
1079
1080 ty::ConstConditions {
1081 parent: has_parent.then(|| tcx.local_parent(def_id).to_def_id()),
1082 predicates: tcx.arena.alloc_from_iter(bounds.into_iter().map(|(clause, span)| {
1083 (
1084 clause.kind().map_bound(|clause| match clause {
1085 ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
1086 trait_ref,
1087 constness: ty::BoundConstness::Maybe,
1088 }) => trait_ref,
1089 _ => bug!("converted {clause:?}"),
1090 }),
1091 span,
1092 )
1093 })),
1094 }
1095}
1096
1097pub(super) fn explicit_implied_const_bounds<'tcx>(
1098 tcx: TyCtxt<'tcx>,
1099 def_id: LocalDefId,
1100) -> ty::EarlyBinder<'tcx, &'tcx [(ty::PolyTraitRef<'tcx>, Span)]> {
1101 if !tcx.is_conditionally_const(def_id) {
1102 bug!(
1103 "explicit_implied_const_bounds invoked for item that is not conditionally const: {def_id:?}"
1104 );
1105 }
1106
1107 let bounds = match tcx.opt_rpitit_info(def_id.to_def_id()) {
1108 Some(ty::ImplTraitInTraitData::Trait { .. }) => {
1111 explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::ConstIfConst)
1112 }
1113 Some(ty::ImplTraitInTraitData::Impl { .. }) => {
1114 span_bug!(tcx.def_span(def_id), "RPITIT in impl should not have item bounds")
1115 }
1116 None => match tcx.hir_node_by_def_id(def_id) {
1117 Node::Item(hir::Item { kind: hir::ItemKind::Trait(..), .. }) => {
1118 implied_predicates_with_filter(
1119 tcx,
1120 def_id.to_def_id(),
1121 PredicateFilter::SelfConstIfConst,
1122 )
1123 }
1124 Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Type(..), .. })
1125 | Node::OpaqueTy(_) => {
1126 explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::ConstIfConst)
1127 }
1128 _ => bug!("explicit_implied_const_bounds called on wrong item: {def_id:?}"),
1129 },
1130 };
1131
1132 bounds.map_bound(|bounds| {
1133 &*tcx.arena.alloc_from_iter(bounds.iter().copied().map(|(clause, span)| {
1134 (
1135 clause.kind().map_bound(|clause| match clause {
1136 ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
1137 trait_ref,
1138 constness: ty::BoundConstness::Maybe,
1139 }) => trait_ref,
1140 _ => bug!("converted {clause:?}"),
1141 }),
1142 span,
1143 )
1144 }))
1145 })
1146}