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, ty::IsRigid::No,
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:105",
"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(105u32),
::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 ty::IsRigid::No,
37 assoc_item_def_id.to_def_id(),
38 GenericArgs::identity_for_item(tcx, assoc_item_def_id),
39 );
40
41 let icx = ItemCtxt::new(tcx, assoc_item_def_id);
42 let mut bounds = Vec::new();
43 icx.lowerer().lower_bounds(
44 item_ty,
45 hir_bounds,
46 &mut bounds,
47 ty::List::empty(),
48 filter,
49 OverlappingAsssocItemConstraints::Allowed,
50 );
51
52 match filter {
53 PredicateFilter::All
54 | PredicateFilter::SelfOnly
55 | PredicateFilter::SelfTraitThatDefines(_)
56 | PredicateFilter::SelfAndAssociatedTypeBounds => {
57 icx.lowerer().add_implicit_sizedness_bounds(
59 &mut bounds,
60 item_ty,
61 hir_bounds,
62 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
63 span,
64 );
65 icx.lowerer().add_default_traits(
66 &mut bounds,
67 item_ty,
68 hir_bounds,
69 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
70 span,
71 );
72
73 let trait_def_id = tcx.local_parent(assoc_item_def_id);
75 let trait_predicates = tcx.trait_explicit_predicates_and_bounds(trait_def_id);
76
77 let item_trait_ref =
78 ty::TraitRef::identity(tcx, tcx.parent(assoc_item_def_id.to_def_id()));
79 bounds.extend(trait_predicates.predicates.iter().copied().filter_map(
80 |(clause, span)| {
81 remap_gat_vars_and_recurse_into_nested_projections(
82 tcx,
83 filter,
84 item_trait_ref,
85 assoc_item_def_id,
86 span,
87 clause,
88 )
89 },
90 ));
91 }
92 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
94 }
102 }
103
104 let bounds = tcx.arena.alloc_from_iter(bounds);
105 debug!(
106 "associated_type_bounds({}) = {:?}",
107 tcx.def_path_str(assoc_item_def_id.to_def_id()),
108 bounds
109 );
110
111 assert_only_contains_predicates_from(filter, bounds, item_ty);
112
113 bounds
114 })
115}
116
117fn remap_gat_vars_and_recurse_into_nested_projections<'tcx>(
131 tcx: TyCtxt<'tcx>,
132 filter: PredicateFilter,
133 item_trait_ref: ty::TraitRef<'tcx>,
134 assoc_item_def_id: LocalDefId,
135 span: Span,
136 clause: ty::Clause<'tcx>,
137) -> Option<(ty::Clause<'tcx>, Span)> {
138 let mut clause_ty = match clause.kind().skip_binder() {
139 ty::ClauseKind::Trait(tr) => tr.self_ty(),
140 ty::ClauseKind::Projection(proj) => proj.projection_term.self_ty(),
141 ty::ClauseKind::TypeOutlives(outlives) => outlives.0,
142 ty::ClauseKind::HostEffect(host) => host.self_ty(),
143 _ => return None,
144 };
145
146 let gat_vars = loop {
147 if let ty::Alias(
148 _,
149 alias_ty @ ty::AliasTy { kind: ty::Projection { def_id: alias_ty_def_id }, .. },
150 ) = *clause_ty.kind()
151 {
152 if alias_ty.trait_ref(tcx) == item_trait_ref
153 && alias_ty_def_id == assoc_item_def_id.to_def_id()
154 {
155 break &alias_ty.args[item_trait_ref.args.len()..];
158 } else {
159 match filter {
161 PredicateFilter::All => {}
162 PredicateFilter::SelfOnly => {
163 return None;
164 }
165 PredicateFilter::SelfTraitThatDefines(_)
166 | PredicateFilter::SelfConstIfConst
167 | PredicateFilter::SelfAndAssociatedTypeBounds
168 | PredicateFilter::ConstIfConst => {
169 {
::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!(
170 "invalid predicate filter for \
171 `remap_gat_vars_and_recurse_into_nested_projections`"
172 )
173 }
174 }
175
176 clause_ty = alias_ty.self_ty();
177 continue;
178 }
179 }
180
181 return None;
182 };
183
184 if gat_vars.is_empty() {
186 return Some((clause, span));
187 }
188
189 let mut mapping = FxIndexMap::default();
192 let generics = tcx.generics_of(assoc_item_def_id);
193 for (param, var) in std::iter::zip(&generics.own_params, gat_vars) {
194 let existing = match var.kind() {
195 ty::GenericArgKind::Lifetime(re) => {
196 let ty::RegionKind::ReBound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) =
197 re.kind()
198 else {
199 return None;
200 };
201 mapping.insert(bv.var, tcx.mk_param_from_def(param))
202 }
203 ty::GenericArgKind::Type(ty) => {
204 let ty::Bound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) = *ty.kind() else {
205 return None;
206 };
207 mapping.insert(bv.var, tcx.mk_param_from_def(param))
208 }
209 ty::GenericArgKind::Const(ct) => {
210 let ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) =
211 ct.kind()
212 else {
213 return None;
214 };
215 mapping.insert(bv.var, tcx.mk_param_from_def(param))
216 }
217 };
218
219 if existing.is_some() {
220 return None;
221 }
222 }
223
224 let mut folder =
227 MapAndCompressBoundVars { tcx, binder: ty::INNERMOST, still_bound_vars: ::alloc::vec::Vec::new()vec![], mapping };
228 let pred = clause.kind().skip_binder().fold_with(&mut folder);
229
230 Some((
231 ty::Binder::bind_with_vars(pred, tcx.mk_bound_variable_kinds(&folder.still_bound_vars))
232 .upcast(tcx),
233 span,
234 ))
235}
236
237struct MapAndCompressBoundVars<'tcx> {
244 tcx: TyCtxt<'tcx>,
245 binder: ty::DebruijnIndex,
247 still_bound_vars: Vec<ty::BoundVariableKind<'tcx>>,
250 mapping: FxIndexMap<ty::BoundVar, ty::GenericArg<'tcx>>,
254}
255
256impl<'tcx> TypeFolder<TyCtxt<'tcx>> for MapAndCompressBoundVars<'tcx> {
257 fn cx(&self) -> TyCtxt<'tcx> {
258 self.tcx
259 }
260
261 fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
262 where
263 ty::Binder<'tcx, T>: TypeSuperFoldable<TyCtxt<'tcx>>,
264 {
265 self.binder.shift_in(1);
266 let out = t.super_fold_with(self);
267 self.binder.shift_out(1);
268 out
269 }
270
271 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
272 if !ty.has_bound_vars() {
273 return ty;
274 }
275
276 if let ty::Bound(ty::BoundVarIndexKind::Bound(binder), old_bound) = *ty.kind()
277 && self.binder == binder
278 {
279 let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
280 mapped.expect_ty()
281 } else {
282 let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
285 self.still_bound_vars.push(ty::BoundVariableKind::Ty(old_bound.kind));
286 let mapped = Ty::new_bound(
287 self.tcx,
288 ty::INNERMOST,
289 ty::BoundTy { var, kind: old_bound.kind },
290 );
291 self.mapping.insert(old_bound.var, mapped.into());
292 mapped
293 };
294
295 shift_vars(self.tcx, mapped, self.binder.as_u32())
296 } else {
297 ty.super_fold_with(self)
298 }
299 }
300
301 fn fold_region(&mut self, re: ty::Region<'tcx>) -> ty::Region<'tcx> {
302 if let ty::ReBound(ty::BoundVarIndexKind::Bound(binder), old_bound) = re.kind()
303 && self.binder == binder
304 {
305 let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
306 mapped.expect_region()
307 } else {
308 let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
309 self.still_bound_vars.push(ty::BoundVariableKind::Region(old_bound.kind));
310 let mapped = ty::Region::new_bound(
311 self.tcx,
312 ty::INNERMOST,
313 ty::BoundRegion { var, kind: old_bound.kind },
314 );
315 self.mapping.insert(old_bound.var, mapped.into());
316 mapped
317 };
318
319 shift_vars(self.tcx, mapped, self.binder.as_u32())
320 } else {
321 re
322 }
323 }
324
325 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
326 if !ct.has_bound_vars() {
327 return ct;
328 }
329
330 if let ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(binder), old_bound) = ct.kind()
331 && self.binder == binder
332 {
333 let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
334 mapped.expect_const()
335 } else {
336 let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
337 self.still_bound_vars.push(ty::BoundVariableKind::Const);
338 let mapped =
339 ty::Const::new_bound(self.tcx, ty::INNERMOST, ty::BoundConst::new(var));
340 self.mapping.insert(old_bound.var, mapped.into());
341 mapped
342 };
343
344 shift_vars(self.tcx, mapped, self.binder.as_u32())
345 } else {
346 ct.super_fold_with(self)
347 }
348 }
349
350 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
351 if !p.has_bound_vars() { p } else { p.super_fold_with(self) }
352 }
353}
354
355#[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(359u32),
::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:403",
"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(403u32),
::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))]
360fn opaque_type_bounds<'tcx>(
361 tcx: TyCtxt<'tcx>,
362 opaque_def_id: LocalDefId,
363 hir_bounds: &'tcx [hir::GenericBound<'tcx>],
364 item_ty: Ty<'tcx>,
365 span: Span,
366 filter: PredicateFilter,
367) -> &'tcx [(ty::Clause<'tcx>, Span)] {
368 ty::print::with_reduced_queries!({
369 let icx = ItemCtxt::new(tcx, opaque_def_id);
370 let mut bounds = Vec::new();
371 icx.lowerer().lower_bounds(
372 item_ty,
373 hir_bounds,
374 &mut bounds,
375 ty::List::empty(),
376 filter,
377 OverlappingAsssocItemConstraints::Allowed,
378 );
379 match filter {
381 PredicateFilter::All
382 | PredicateFilter::SelfOnly
383 | PredicateFilter::SelfTraitThatDefines(_)
384 | PredicateFilter::SelfAndAssociatedTypeBounds => {
385 icx.lowerer().add_implicit_sizedness_bounds(
386 &mut bounds,
387 item_ty,
388 hir_bounds,
389 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
390 span,
391 );
392 icx.lowerer().add_default_traits(
393 &mut bounds,
394 item_ty,
395 hir_bounds,
396 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
397 span,
398 );
399 }
400 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
402 }
403 debug!(?bounds);
404
405 tcx.arena.alloc_slice(&bounds)
406 })
407}
408
409pub(super) fn explicit_item_bounds(
410 tcx: TyCtxt<'_>,
411 def_id: LocalDefId,
412) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
413 explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::All)
414}
415
416pub(super) fn explicit_item_self_bounds(
417 tcx: TyCtxt<'_>,
418 def_id: LocalDefId,
419) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
420 explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::SelfOnly)
421}
422
423pub(super) fn explicit_item_bounds_with_filter(
424 tcx: TyCtxt<'_>,
425 def_id: LocalDefId,
426 filter: PredicateFilter,
427) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
428 match tcx.opt_rpitit_info(def_id.to_def_id()) {
429 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
432 let opaque_ty = tcx.hir_node_by_def_id(opaque_def_id.expect_local()).expect_opaque_ty();
433 let bounds =
434 associated_type_bounds(tcx, def_id, opaque_ty.bounds, opaque_ty.span, filter);
435 return ty::EarlyBinder::bind_iter(bounds);
436 }
437 Some(ty::ImplTraitInTraitData::Impl { .. }) => {
438 ::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")
439 }
440 None => {}
441 }
442
443 let bounds = match tcx.hir_node_by_def_id(def_id) {
444 hir::Node::TraitItem(hir::TraitItem {
445 kind: hir::TraitItemKind::Type(bounds, _),
446 span,
447 ..
448 }) => associated_type_bounds(tcx, def_id, bounds, *span, filter),
449 hir::Node::OpaqueTy(hir::OpaqueTy { bounds, origin, span, .. }) => match origin {
450 rustc_hir::OpaqueTyOrigin::FnReturn {
454 parent,
455 in_trait_or_impl: Some(hir::RpitContext::Trait),
456 }
457 | rustc_hir::OpaqueTyOrigin::AsyncFn {
458 parent,
459 in_trait_or_impl: Some(hir::RpitContext::Trait),
460 } => {
461 let args = GenericArgs::identity_for_item(tcx, def_id);
462 let item_ty = Ty::new_opaque(tcx, ty::IsRigid::No, def_id.to_def_id(), args);
463 let bounds = &*tcx.arena.alloc_slice(
464 &opaque_type_bounds(tcx, def_id, bounds, item_ty, *span, filter)
465 .to_vec()
466 .fold_with(&mut AssocTyToOpaque { tcx, fn_def_id: parent.to_def_id() }),
467 );
468 assert_only_contains_predicates_from(filter, bounds, item_ty);
469 bounds
470 }
471 rustc_hir::OpaqueTyOrigin::FnReturn {
472 parent: _,
473 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
474 }
475 | rustc_hir::OpaqueTyOrigin::AsyncFn {
476 parent: _,
477 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
478 }
479 | rustc_hir::OpaqueTyOrigin::TyAlias { parent: _, .. } => {
480 let args = GenericArgs::identity_for_item(tcx, def_id);
481 let item_ty = Ty::new_opaque(tcx, ty::IsRigid::No, def_id.to_def_id(), args);
482 let bounds = opaque_type_bounds(tcx, def_id, bounds, item_ty, *span, filter);
483 assert_only_contains_predicates_from(filter, bounds, item_ty);
484 bounds
485 }
486 },
487 hir::Node::Item(hir::Item { kind: hir::ItemKind::TyAlias(..), .. }) => &[],
488 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:?}"),
489 };
490
491 ty::EarlyBinder::bind_iter(bounds)
492}
493
494pub(super) fn item_bounds(tcx: TyCtxt<'_>, def_id: DefId) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
495 tcx.explicit_item_bounds(def_id).map_bound(|bounds| {
496 tcx.mk_clauses_from_iter(util::elaborate(tcx, bounds.iter().map(|&(bound, _span)| bound)))
497 })
498}
499
500pub(super) fn item_self_bounds(
501 tcx: TyCtxt<'_>,
502 def_id: DefId,
503) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
504 tcx.explicit_item_self_bounds(def_id).map_bound(|bounds| {
505 tcx.mk_clauses_from_iter(
506 util::elaborate(tcx, bounds.iter().map(|&(bound, _span)| bound)).filter_only_self(),
507 )
508 })
509}
510
511pub(super) fn item_non_self_bounds(
514 tcx: TyCtxt<'_>,
515 def_id: DefId,
516) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
517 let all_bounds: FxIndexSet<_> = tcx.item_bounds(def_id).skip_binder().iter().collect();
518 let own_bounds: FxIndexSet<_> = tcx.item_self_bounds(def_id).skip_binder().iter().collect();
519 if all_bounds.len() == own_bounds.len() {
520 ty::EarlyBinder::bind(tcx, ty::ListWithCachedTypeInfo::empty())
521 } else {
522 ty::EarlyBinder::bind(
523 tcx,
524 tcx.mk_clauses_from_iter(all_bounds.difference(&own_bounds).copied()),
525 )
526 }
527}
528
529pub(super) fn impl_super_outlives(
532 tcx: TyCtxt<'_>,
533 def_id: DefId,
534) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
535 tcx.impl_trait_header(def_id).trait_ref.map_bound(|trait_ref| {
536 let clause: ty::Clause<'_> = trait_ref.upcast(tcx);
537 tcx.mk_clauses_from_iter(util::elaborate(tcx, [clause]).filter(|clause| {
538 #[allow(non_exhaustive_omitted_patterns)] match clause.kind().skip_binder() {
ty::ClauseKind::TypeOutlives(_) | ty::ClauseKind::RegionOutlives(_) =>
true,
_ => false,
}matches!(
539 clause.kind().skip_binder(),
540 ty::ClauseKind::TypeOutlives(_) | ty::ClauseKind::RegionOutlives(_)
541 )
542 }))
543 })
544}
545
546struct AssocTyToOpaque<'tcx> {
547 tcx: TyCtxt<'tcx>,
548 fn_def_id: DefId,
549}
550
551impl<'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTyToOpaque<'tcx> {
552 fn cx(&self) -> TyCtxt<'tcx> {
553 self.tcx
554 }
555
556 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
557 if let &ty::Alias(
558 _,
559 ty::AliasTy { kind: ty::Projection { def_id: projection_ty_def_id }, args, .. },
560 ) = ty.kind()
561 && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) =
562 self.tcx.opt_rpitit_info(projection_ty_def_id)
563 && fn_def_id == self.fn_def_id
564 {
565 self.tcx.type_of(projection_ty_def_id).instantiate(self.tcx, args).skip_norm_wip()
566 } else {
567 ty.super_fold_with(self)
568 }
569 }
570}