1use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
2use rustc_hir as hir;
3use rustc_infer::traits::util;
4use rustc_middle::ty::{
5 self, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt,
6 Upcast, shift_vars,
7};
8use rustc_middle::{bug, span_bug};
9use rustc_span::Span;
10use rustc_span::def_id::{DefId, LocalDefId};
11use tracing::{debug, instrument};
12
13use super::ItemCtxt;
14use super::predicates_of::assert_only_contains_predicates_from;
15use crate::hir_ty_lowering::{
16 HirTyLowerer, ImpliedBoundsContext, OverlappingAsssocItemConstraints, PredicateFilter,
17};
18
19fn associated_type_bounds<'tcx>(
27 tcx: TyCtxt<'tcx>,
28 assoc_item_def_id: LocalDefId,
29 hir_bounds: &'tcx [hir::GenericBound<'tcx>],
30 span: Span,
31 filter: PredicateFilter,
32) -> &'tcx [(ty::Clause<'tcx>, Span)] {
33 {
let _guard = ReducedQueriesGuard::new();
{
let item_ty =
Ty::new_projection_from_args(tcx, assoc_item_def_id.to_def_id(),
GenericArgs::identity_for_item(tcx, assoc_item_def_id));
let icx = ItemCtxt::new(tcx, assoc_item_def_id);
let mut bounds = Vec::new();
icx.lowerer().lower_bounds(item_ty, hir_bounds, &mut bounds,
ty::List::empty(), filter,
OverlappingAsssocItemConstraints::Allowed);
match filter {
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfTraitThatDefines(_) |
PredicateFilter::SelfAndAssociatedTypeBounds => {
icx.lowerer().add_implicit_sizedness_bounds(&mut bounds,
item_ty, hir_bounds,
ImpliedBoundsContext::AssociatedTypeOrImplTrait, span);
icx.lowerer().add_default_traits(&mut bounds, item_ty,
hir_bounds, ImpliedBoundsContext::AssociatedTypeOrImplTrait,
span);
let trait_def_id = tcx.local_parent(assoc_item_def_id);
let trait_predicates =
tcx.trait_explicit_predicates_and_bounds(trait_def_id);
let item_trait_ref =
ty::TraitRef::identity(tcx,
tcx.parent(assoc_item_def_id.to_def_id()));
bounds.extend(trait_predicates.predicates.iter().copied().filter_map(|(clause,
span)|
{
remap_gat_vars_and_recurse_into_nested_projections(tcx,
filter, item_trait_ref, assoc_item_def_id, span, clause)
}));
}
PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst
=> {}
}
let bounds = tcx.arena.alloc_from_iter(bounds);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/item_bounds.rs:104",
"rustc_hir_analysis::collect::item_bounds",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/item_bounds.rs"),
::tracing_core::__macro_support::Option::Some(104u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::item_bounds"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("associated_type_bounds({0}) = {1:?}",
tcx.def_path_str(assoc_item_def_id.to_def_id()), bounds) as
&dyn Value))])
});
} else { ; }
};
assert_only_contains_predicates_from(filter, bounds, item_ty);
bounds
}
}ty::print::with_reduced_queries!({
34 let item_ty = Ty::new_projection_from_args(
35 tcx,
36 assoc_item_def_id.to_def_id(),
37 GenericArgs::identity_for_item(tcx, assoc_item_def_id),
38 );
39
40 let icx = ItemCtxt::new(tcx, assoc_item_def_id);
41 let mut bounds = Vec::new();
42 icx.lowerer().lower_bounds(
43 item_ty,
44 hir_bounds,
45 &mut bounds,
46 ty::List::empty(),
47 filter,
48 OverlappingAsssocItemConstraints::Allowed,
49 );
50
51 match filter {
52 PredicateFilter::All
53 | PredicateFilter::SelfOnly
54 | PredicateFilter::SelfTraitThatDefines(_)
55 | PredicateFilter::SelfAndAssociatedTypeBounds => {
56 icx.lowerer().add_implicit_sizedness_bounds(
58 &mut bounds,
59 item_ty,
60 hir_bounds,
61 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
62 span,
63 );
64 icx.lowerer().add_default_traits(
65 &mut bounds,
66 item_ty,
67 hir_bounds,
68 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
69 span,
70 );
71
72 let trait_def_id = tcx.local_parent(assoc_item_def_id);
74 let trait_predicates = tcx.trait_explicit_predicates_and_bounds(trait_def_id);
75
76 let item_trait_ref =
77 ty::TraitRef::identity(tcx, tcx.parent(assoc_item_def_id.to_def_id()));
78 bounds.extend(trait_predicates.predicates.iter().copied().filter_map(
79 |(clause, span)| {
80 remap_gat_vars_and_recurse_into_nested_projections(
81 tcx,
82 filter,
83 item_trait_ref,
84 assoc_item_def_id,
85 span,
86 clause,
87 )
88 },
89 ));
90 }
91 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
93 }
101 }
102
103 let bounds = tcx.arena.alloc_from_iter(bounds);
104 debug!(
105 "associated_type_bounds({}) = {:?}",
106 tcx.def_path_str(assoc_item_def_id.to_def_id()),
107 bounds
108 );
109
110 assert_only_contains_predicates_from(filter, bounds, item_ty);
111
112 bounds
113 })
114}
115
116fn remap_gat_vars_and_recurse_into_nested_projections<'tcx>(
130 tcx: TyCtxt<'tcx>,
131 filter: PredicateFilter,
132 item_trait_ref: ty::TraitRef<'tcx>,
133 assoc_item_def_id: LocalDefId,
134 span: Span,
135 clause: ty::Clause<'tcx>,
136) -> Option<(ty::Clause<'tcx>, Span)> {
137 let mut clause_ty = match clause.kind().skip_binder() {
138 ty::ClauseKind::Trait(tr) => tr.self_ty(),
139 ty::ClauseKind::Projection(proj) => proj.projection_term.self_ty(),
140 ty::ClauseKind::TypeOutlives(outlives) => outlives.0,
141 ty::ClauseKind::HostEffect(host) => host.self_ty(),
142 _ => return None,
143 };
144
145 let gat_vars = loop {
146 if let ty::Alias(
147 alias_ty @ ty::AliasTy { kind: ty::Projection { def_id: alias_ty_def_id }, .. },
148 ) = *clause_ty.kind()
149 {
150 if alias_ty.trait_ref(tcx) == item_trait_ref
151 && alias_ty_def_id == assoc_item_def_id.to_def_id()
152 {
153 break &alias_ty.args[item_trait_ref.args.len()..];
156 } else {
157 match filter {
159 PredicateFilter::All => {}
160 PredicateFilter::SelfOnly => {
161 return None;
162 }
163 PredicateFilter::SelfTraitThatDefines(_)
164 | PredicateFilter::SelfConstIfConst
165 | PredicateFilter::SelfAndAssociatedTypeBounds
166 | PredicateFilter::ConstIfConst => {
167 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("invalid predicate filter for `remap_gat_vars_and_recurse_into_nested_projections`")));
}unreachable!(
168 "invalid predicate filter for \
169 `remap_gat_vars_and_recurse_into_nested_projections`"
170 )
171 }
172 }
173
174 clause_ty = alias_ty.self_ty();
175 continue;
176 }
177 }
178
179 return None;
180 };
181
182 if gat_vars.is_empty() {
184 return Some((clause, span));
185 }
186
187 let mut mapping = FxIndexMap::default();
190 let generics = tcx.generics_of(assoc_item_def_id);
191 for (param, var) in std::iter::zip(&generics.own_params, gat_vars) {
192 let existing = match var.kind() {
193 ty::GenericArgKind::Lifetime(re) => {
194 let ty::RegionKind::ReBound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) =
195 re.kind()
196 else {
197 return None;
198 };
199 mapping.insert(bv.var, tcx.mk_param_from_def(param))
200 }
201 ty::GenericArgKind::Type(ty) => {
202 let ty::Bound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) = *ty.kind() else {
203 return None;
204 };
205 mapping.insert(bv.var, tcx.mk_param_from_def(param))
206 }
207 ty::GenericArgKind::Const(ct) => {
208 let ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) =
209 ct.kind()
210 else {
211 return None;
212 };
213 mapping.insert(bv.var, tcx.mk_param_from_def(param))
214 }
215 };
216
217 if existing.is_some() {
218 return None;
219 }
220 }
221
222 let mut folder =
225 MapAndCompressBoundVars { tcx, binder: ty::INNERMOST, still_bound_vars: ::alloc::vec::Vec::new()vec![], mapping };
226 let pred = clause.kind().skip_binder().fold_with(&mut folder);
227
228 Some((
229 ty::Binder::bind_with_vars(pred, tcx.mk_bound_variable_kinds(&folder.still_bound_vars))
230 .upcast(tcx),
231 span,
232 ))
233}
234
235struct MapAndCompressBoundVars<'tcx> {
242 tcx: TyCtxt<'tcx>,
243 binder: ty::DebruijnIndex,
245 still_bound_vars: Vec<ty::BoundVariableKind<'tcx>>,
248 mapping: FxIndexMap<ty::BoundVar, ty::GenericArg<'tcx>>,
252}
253
254impl<'tcx> TypeFolder<TyCtxt<'tcx>> for MapAndCompressBoundVars<'tcx> {
255 fn cx(&self) -> TyCtxt<'tcx> {
256 self.tcx
257 }
258
259 fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
260 where
261 ty::Binder<'tcx, T>: TypeSuperFoldable<TyCtxt<'tcx>>,
262 {
263 self.binder.shift_in(1);
264 let out = t.super_fold_with(self);
265 self.binder.shift_out(1);
266 out
267 }
268
269 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
270 if !ty.has_bound_vars() {
271 return ty;
272 }
273
274 if let ty::Bound(ty::BoundVarIndexKind::Bound(binder), old_bound) = *ty.kind()
275 && self.binder == binder
276 {
277 let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
278 mapped.expect_ty()
279 } else {
280 let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
283 self.still_bound_vars.push(ty::BoundVariableKind::Ty(old_bound.kind));
284 let mapped = Ty::new_bound(
285 self.tcx,
286 ty::INNERMOST,
287 ty::BoundTy { var, kind: old_bound.kind },
288 );
289 self.mapping.insert(old_bound.var, mapped.into());
290 mapped
291 };
292
293 shift_vars(self.tcx, mapped, self.binder.as_u32())
294 } else {
295 ty.super_fold_with(self)
296 }
297 }
298
299 fn fold_region(&mut self, re: ty::Region<'tcx>) -> ty::Region<'tcx> {
300 if let ty::ReBound(ty::BoundVarIndexKind::Bound(binder), old_bound) = re.kind()
301 && self.binder == binder
302 {
303 let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
304 mapped.expect_region()
305 } else {
306 let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
307 self.still_bound_vars.push(ty::BoundVariableKind::Region(old_bound.kind));
308 let mapped = ty::Region::new_bound(
309 self.tcx,
310 ty::INNERMOST,
311 ty::BoundRegion { var, kind: old_bound.kind },
312 );
313 self.mapping.insert(old_bound.var, mapped.into());
314 mapped
315 };
316
317 shift_vars(self.tcx, mapped, self.binder.as_u32())
318 } else {
319 re
320 }
321 }
322
323 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
324 if !ct.has_bound_vars() {
325 return ct;
326 }
327
328 if let ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(binder), old_bound) = ct.kind()
329 && self.binder == binder
330 {
331 let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
332 mapped.expect_const()
333 } else {
334 let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
335 self.still_bound_vars.push(ty::BoundVariableKind::Const);
336 let mapped =
337 ty::Const::new_bound(self.tcx, ty::INNERMOST, ty::BoundConst::new(var));
338 self.mapping.insert(old_bound.var, mapped.into());
339 mapped
340 };
341
342 shift_vars(self.tcx, mapped, self.binder.as_u32())
343 } else {
344 ct.super_fold_with(self)
345 }
346 }
347
348 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
349 if !p.has_bound_vars() { p } else { p.super_fold_with(self) }
350 }
351}
352
353#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("opaque_type_bounds",
"rustc_hir_analysis::collect::item_bounds",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/item_bounds.rs"),
::tracing_core::__macro_support::Option::Some(357u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::item_bounds"),
::tracing_core::field::FieldSet::new(&["opaque_def_id",
"hir_bounds", "span", "filter"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opaque_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_bounds)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&filter)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: &'tcx [(ty::Clause<'tcx>, Span)] =
loop {};
return __tracing_attr_fake_return;
}
{
{
let _guard = ReducedQueriesGuard::new();
{
let icx = ItemCtxt::new(tcx, opaque_def_id);
let mut bounds = Vec::new();
icx.lowerer().lower_bounds(item_ty, hir_bounds, &mut bounds,
ty::List::empty(), filter,
OverlappingAsssocItemConstraints::Allowed);
match filter {
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfTraitThatDefines(_) |
PredicateFilter::SelfAndAssociatedTypeBounds => {
icx.lowerer().add_implicit_sizedness_bounds(&mut bounds,
item_ty, hir_bounds,
ImpliedBoundsContext::AssociatedTypeOrImplTrait, span);
icx.lowerer().add_default_traits(&mut bounds, item_ty,
hir_bounds, ImpliedBoundsContext::AssociatedTypeOrImplTrait,
span);
}
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => {}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/item_bounds.rs:401",
"rustc_hir_analysis::collect::item_bounds",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/item_bounds.rs"),
::tracing_core::__macro_support::Option::Some(401u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::item_bounds"),
::tracing_core::field::FieldSet::new(&["bounds"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&bounds) as
&dyn Value))])
});
} else { ; }
};
tcx.arena.alloc_slice(&bounds)
}
}
}
}
}#[instrument(level = "trace", skip(tcx, item_ty))]
358fn opaque_type_bounds<'tcx>(
359 tcx: TyCtxt<'tcx>,
360 opaque_def_id: LocalDefId,
361 hir_bounds: &'tcx [hir::GenericBound<'tcx>],
362 item_ty: Ty<'tcx>,
363 span: Span,
364 filter: PredicateFilter,
365) -> &'tcx [(ty::Clause<'tcx>, Span)] {
366 ty::print::with_reduced_queries!({
367 let icx = ItemCtxt::new(tcx, opaque_def_id);
368 let mut bounds = Vec::new();
369 icx.lowerer().lower_bounds(
370 item_ty,
371 hir_bounds,
372 &mut bounds,
373 ty::List::empty(),
374 filter,
375 OverlappingAsssocItemConstraints::Allowed,
376 );
377 match filter {
379 PredicateFilter::All
380 | PredicateFilter::SelfOnly
381 | PredicateFilter::SelfTraitThatDefines(_)
382 | PredicateFilter::SelfAndAssociatedTypeBounds => {
383 icx.lowerer().add_implicit_sizedness_bounds(
384 &mut bounds,
385 item_ty,
386 hir_bounds,
387 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
388 span,
389 );
390 icx.lowerer().add_default_traits(
391 &mut bounds,
392 item_ty,
393 hir_bounds,
394 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
395 span,
396 );
397 }
398 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
400 }
401 debug!(?bounds);
402
403 tcx.arena.alloc_slice(&bounds)
404 })
405}
406
407pub(super) fn explicit_item_bounds(
408 tcx: TyCtxt<'_>,
409 def_id: LocalDefId,
410) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
411 explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::All)
412}
413
414pub(super) fn explicit_item_self_bounds(
415 tcx: TyCtxt<'_>,
416 def_id: LocalDefId,
417) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
418 explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::SelfOnly)
419}
420
421pub(super) fn explicit_item_bounds_with_filter(
422 tcx: TyCtxt<'_>,
423 def_id: LocalDefId,
424 filter: PredicateFilter,
425) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
426 match tcx.opt_rpitit_info(def_id.to_def_id()) {
427 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
430 let opaque_ty = tcx.hir_node_by_def_id(opaque_def_id.expect_local()).expect_opaque_ty();
431 let bounds =
432 associated_type_bounds(tcx, def_id, opaque_ty.bounds, opaque_ty.span, filter);
433 return ty::EarlyBinder::bind(bounds);
434 }
435 Some(ty::ImplTraitInTraitData::Impl { .. }) => {
436 ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
format_args!("RPITIT in impl should not have item bounds"))span_bug!(tcx.def_span(def_id), "RPITIT in impl should not have item bounds")
437 }
438 None => {}
439 }
440
441 let bounds = match tcx.hir_node_by_def_id(def_id) {
442 hir::Node::TraitItem(hir::TraitItem {
443 kind: hir::TraitItemKind::Type(bounds, _),
444 span,
445 ..
446 }) => associated_type_bounds(tcx, def_id, bounds, *span, filter),
447 hir::Node::OpaqueTy(hir::OpaqueTy { bounds, origin, span, .. }) => match origin {
448 rustc_hir::OpaqueTyOrigin::FnReturn {
452 parent,
453 in_trait_or_impl: Some(hir::RpitContext::Trait),
454 }
455 | rustc_hir::OpaqueTyOrigin::AsyncFn {
456 parent,
457 in_trait_or_impl: Some(hir::RpitContext::Trait),
458 } => {
459 let args = GenericArgs::identity_for_item(tcx, def_id);
460 let item_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
461 let bounds = &*tcx.arena.alloc_slice(
462 &opaque_type_bounds(tcx, def_id, bounds, item_ty, *span, filter)
463 .to_vec()
464 .fold_with(&mut AssocTyToOpaque { tcx, fn_def_id: parent.to_def_id() }),
465 );
466 assert_only_contains_predicates_from(filter, bounds, item_ty);
467 bounds
468 }
469 rustc_hir::OpaqueTyOrigin::FnReturn {
470 parent: _,
471 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
472 }
473 | rustc_hir::OpaqueTyOrigin::AsyncFn {
474 parent: _,
475 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
476 }
477 | rustc_hir::OpaqueTyOrigin::TyAlias { parent: _, .. } => {
478 let args = GenericArgs::identity_for_item(tcx, def_id);
479 let item_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
480 let bounds = opaque_type_bounds(tcx, def_id, bounds, item_ty, *span, filter);
481 assert_only_contains_predicates_from(filter, bounds, item_ty);
482 bounds
483 }
484 },
485 hir::Node::Item(hir::Item { kind: hir::ItemKind::TyAlias(..), .. }) => &[],
486 node => ::rustc_middle::util::bug::bug_fmt(format_args!("item_bounds called on {0:?} => {1:?}",
def_id, node))bug!("item_bounds called on {def_id:?} => {node:?}"),
487 };
488
489 ty::EarlyBinder::bind(bounds)
490}
491
492pub(super) fn item_bounds(tcx: TyCtxt<'_>, def_id: DefId) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
493 tcx.explicit_item_bounds(def_id).map_bound(|bounds| {
494 tcx.mk_clauses_from_iter(util::elaborate(tcx, bounds.iter().map(|&(bound, _span)| bound)))
495 })
496}
497
498pub(super) fn item_self_bounds(
499 tcx: TyCtxt<'_>,
500 def_id: DefId,
501) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
502 tcx.explicit_item_self_bounds(def_id).map_bound(|bounds| {
503 tcx.mk_clauses_from_iter(
504 util::elaborate(tcx, bounds.iter().map(|&(bound, _span)| bound)).filter_only_self(),
505 )
506 })
507}
508
509pub(super) fn item_non_self_bounds(
512 tcx: TyCtxt<'_>,
513 def_id: DefId,
514) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
515 let all_bounds: FxIndexSet<_> = tcx.item_bounds(def_id).skip_binder().iter().collect();
516 let own_bounds: FxIndexSet<_> = tcx.item_self_bounds(def_id).skip_binder().iter().collect();
517 if all_bounds.len() == own_bounds.len() {
518 ty::EarlyBinder::bind(ty::ListWithCachedTypeInfo::empty())
519 } else {
520 ty::EarlyBinder::bind(tcx.mk_clauses_from_iter(all_bounds.difference(&own_bounds).copied()))
521 }
522}
523
524pub(super) fn impl_super_outlives(
527 tcx: TyCtxt<'_>,
528 def_id: DefId,
529) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
530 tcx.impl_trait_header(def_id).trait_ref.map_bound(|trait_ref| {
531 let clause: ty::Clause<'_> = trait_ref.upcast(tcx);
532 tcx.mk_clauses_from_iter(util::elaborate(tcx, [clause]).filter(|clause| {
533 #[allow(non_exhaustive_omitted_patterns)] match clause.kind().skip_binder() {
ty::ClauseKind::TypeOutlives(_) | ty::ClauseKind::RegionOutlives(_) =>
true,
_ => false,
}matches!(
534 clause.kind().skip_binder(),
535 ty::ClauseKind::TypeOutlives(_) | ty::ClauseKind::RegionOutlives(_)
536 )
537 }))
538 })
539}
540
541struct AssocTyToOpaque<'tcx> {
542 tcx: TyCtxt<'tcx>,
543 fn_def_id: DefId,
544}
545
546impl<'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTyToOpaque<'tcx> {
547 fn cx(&self) -> TyCtxt<'tcx> {
548 self.tcx
549 }
550
551 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
552 if let &ty::Alias(
553 projection_ty @ ty::AliasTy {
554 kind: ty::Projection { def_id: projection_ty_def_id },
555 ..
556 },
557 ) = ty.kind()
558 && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) =
559 self.tcx.opt_rpitit_info(projection_ty_def_id)
560 && fn_def_id == self.fn_def_id
561 {
562 self.tcx.type_of(projection_ty_def_id).instantiate(self.tcx, projection_ty.args)
563 } else {
564 ty.super_fold_with(self)
565 }
566 }
567}