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(ty::Projection, alias_ty) = *clause_ty.kind() {
147 if alias_ty.trait_ref(tcx) == item_trait_ref
148 && alias_ty.def_id == assoc_item_def_id.to_def_id()
149 {
150 break &alias_ty.args[item_trait_ref.args.len()..];
153 } else {
154 match filter {
156 PredicateFilter::All => {}
157 PredicateFilter::SelfOnly => {
158 return None;
159 }
160 PredicateFilter::SelfTraitThatDefines(_)
161 | PredicateFilter::SelfConstIfConst
162 | PredicateFilter::SelfAndAssociatedTypeBounds
163 | PredicateFilter::ConstIfConst => {
164 {
::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!(
165 "invalid predicate filter for \
166 `remap_gat_vars_and_recurse_into_nested_projections`"
167 )
168 }
169 }
170
171 clause_ty = alias_ty.self_ty();
172 continue;
173 }
174 }
175
176 return None;
177 };
178
179 if gat_vars.is_empty() {
181 return Some((clause, span));
182 }
183
184 let mut mapping = FxIndexMap::default();
187 let generics = tcx.generics_of(assoc_item_def_id);
188 for (param, var) in std::iter::zip(&generics.own_params, gat_vars) {
189 let existing = match var.kind() {
190 ty::GenericArgKind::Lifetime(re) => {
191 let ty::RegionKind::ReBound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) =
192 re.kind()
193 else {
194 return None;
195 };
196 mapping.insert(bv.var, tcx.mk_param_from_def(param))
197 }
198 ty::GenericArgKind::Type(ty) => {
199 let ty::Bound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) = *ty.kind() else {
200 return None;
201 };
202 mapping.insert(bv.var, tcx.mk_param_from_def(param))
203 }
204 ty::GenericArgKind::Const(ct) => {
205 let ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) =
206 ct.kind()
207 else {
208 return None;
209 };
210 mapping.insert(bv.var, tcx.mk_param_from_def(param))
211 }
212 };
213
214 if existing.is_some() {
215 return None;
216 }
217 }
218
219 let mut folder =
222 MapAndCompressBoundVars { tcx, binder: ty::INNERMOST, still_bound_vars: ::alloc::vec::Vec::new()vec![], mapping };
223 let pred = clause.kind().skip_binder().fold_with(&mut folder);
224
225 Some((
226 ty::Binder::bind_with_vars(pred, tcx.mk_bound_variable_kinds(&folder.still_bound_vars))
227 .upcast(tcx),
228 span,
229 ))
230}
231
232struct MapAndCompressBoundVars<'tcx> {
239 tcx: TyCtxt<'tcx>,
240 binder: ty::DebruijnIndex,
242 still_bound_vars: Vec<ty::BoundVariableKind<'tcx>>,
245 mapping: FxIndexMap<ty::BoundVar, ty::GenericArg<'tcx>>,
249}
250
251impl<'tcx> TypeFolder<TyCtxt<'tcx>> for MapAndCompressBoundVars<'tcx> {
252 fn cx(&self) -> TyCtxt<'tcx> {
253 self.tcx
254 }
255
256 fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
257 where
258 ty::Binder<'tcx, T>: TypeSuperFoldable<TyCtxt<'tcx>>,
259 {
260 self.binder.shift_in(1);
261 let out = t.super_fold_with(self);
262 self.binder.shift_out(1);
263 out
264 }
265
266 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
267 if !ty.has_bound_vars() {
268 return ty;
269 }
270
271 if let ty::Bound(ty::BoundVarIndexKind::Bound(binder), old_bound) = *ty.kind()
272 && self.binder == binder
273 {
274 let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
275 mapped.expect_ty()
276 } else {
277 let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
280 self.still_bound_vars.push(ty::BoundVariableKind::Ty(old_bound.kind));
281 let mapped = Ty::new_bound(
282 self.tcx,
283 ty::INNERMOST,
284 ty::BoundTy { var, kind: old_bound.kind },
285 );
286 self.mapping.insert(old_bound.var, mapped.into());
287 mapped
288 };
289
290 shift_vars(self.tcx, mapped, self.binder.as_u32())
291 } else {
292 ty.super_fold_with(self)
293 }
294 }
295
296 fn fold_region(&mut self, re: ty::Region<'tcx>) -> ty::Region<'tcx> {
297 if let ty::ReBound(ty::BoundVarIndexKind::Bound(binder), old_bound) = re.kind()
298 && self.binder == binder
299 {
300 let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
301 mapped.expect_region()
302 } else {
303 let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
304 self.still_bound_vars.push(ty::BoundVariableKind::Region(old_bound.kind));
305 let mapped = ty::Region::new_bound(
306 self.tcx,
307 ty::INNERMOST,
308 ty::BoundRegion { var, kind: old_bound.kind },
309 );
310 self.mapping.insert(old_bound.var, mapped.into());
311 mapped
312 };
313
314 shift_vars(self.tcx, mapped, self.binder.as_u32())
315 } else {
316 re
317 }
318 }
319
320 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
321 if !ct.has_bound_vars() {
322 return ct;
323 }
324
325 if let ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(binder), old_bound) = ct.kind()
326 && self.binder == binder
327 {
328 let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
329 mapped.expect_const()
330 } else {
331 let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
332 self.still_bound_vars.push(ty::BoundVariableKind::Const);
333 let mapped =
334 ty::Const::new_bound(self.tcx, ty::INNERMOST, ty::BoundConst::new(var));
335 self.mapping.insert(old_bound.var, mapped.into());
336 mapped
337 };
338
339 shift_vars(self.tcx, mapped, self.binder.as_u32())
340 } else {
341 ct.super_fold_with(self)
342 }
343 }
344
345 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
346 if !p.has_bound_vars() { p } else { p.super_fold_with(self) }
347 }
348}
349
350#[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(354u32),
::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:398",
"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(398u32),
::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))]
355fn opaque_type_bounds<'tcx>(
356 tcx: TyCtxt<'tcx>,
357 opaque_def_id: LocalDefId,
358 hir_bounds: &'tcx [hir::GenericBound<'tcx>],
359 item_ty: Ty<'tcx>,
360 span: Span,
361 filter: PredicateFilter,
362) -> &'tcx [(ty::Clause<'tcx>, Span)] {
363 ty::print::with_reduced_queries!({
364 let icx = ItemCtxt::new(tcx, opaque_def_id);
365 let mut bounds = Vec::new();
366 icx.lowerer().lower_bounds(
367 item_ty,
368 hir_bounds,
369 &mut bounds,
370 ty::List::empty(),
371 filter,
372 OverlappingAsssocItemConstraints::Allowed,
373 );
374 match filter {
376 PredicateFilter::All
377 | PredicateFilter::SelfOnly
378 | PredicateFilter::SelfTraitThatDefines(_)
379 | PredicateFilter::SelfAndAssociatedTypeBounds => {
380 icx.lowerer().add_implicit_sizedness_bounds(
381 &mut bounds,
382 item_ty,
383 hir_bounds,
384 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
385 span,
386 );
387 icx.lowerer().add_default_traits(
388 &mut bounds,
389 item_ty,
390 hir_bounds,
391 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
392 span,
393 );
394 }
395 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
397 }
398 debug!(?bounds);
399
400 tcx.arena.alloc_slice(&bounds)
401 })
402}
403
404pub(super) fn explicit_item_bounds(
405 tcx: TyCtxt<'_>,
406 def_id: LocalDefId,
407) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
408 explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::All)
409}
410
411pub(super) fn explicit_item_self_bounds(
412 tcx: TyCtxt<'_>,
413 def_id: LocalDefId,
414) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
415 explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::SelfOnly)
416}
417
418pub(super) fn explicit_item_bounds_with_filter(
419 tcx: TyCtxt<'_>,
420 def_id: LocalDefId,
421 filter: PredicateFilter,
422) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
423 match tcx.opt_rpitit_info(def_id.to_def_id()) {
424 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
427 let opaque_ty = tcx.hir_node_by_def_id(opaque_def_id.expect_local()).expect_opaque_ty();
428 let bounds =
429 associated_type_bounds(tcx, def_id, opaque_ty.bounds, opaque_ty.span, filter);
430 return ty::EarlyBinder::bind(bounds);
431 }
432 Some(ty::ImplTraitInTraitData::Impl { .. }) => {
433 ::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")
434 }
435 None => {}
436 }
437
438 let bounds = match tcx.hir_node_by_def_id(def_id) {
439 hir::Node::TraitItem(hir::TraitItem {
440 kind: hir::TraitItemKind::Type(bounds, _),
441 span,
442 ..
443 }) => associated_type_bounds(tcx, def_id, bounds, *span, filter),
444 hir::Node::OpaqueTy(hir::OpaqueTy { bounds, origin, span, .. }) => match origin {
445 rustc_hir::OpaqueTyOrigin::FnReturn {
449 parent,
450 in_trait_or_impl: Some(hir::RpitContext::Trait),
451 }
452 | rustc_hir::OpaqueTyOrigin::AsyncFn {
453 parent,
454 in_trait_or_impl: Some(hir::RpitContext::Trait),
455 } => {
456 let args = GenericArgs::identity_for_item(tcx, def_id);
457 let item_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
458 let bounds = &*tcx.arena.alloc_slice(
459 &opaque_type_bounds(tcx, def_id, bounds, item_ty, *span, filter)
460 .to_vec()
461 .fold_with(&mut AssocTyToOpaque { tcx, fn_def_id: parent.to_def_id() }),
462 );
463 assert_only_contains_predicates_from(filter, bounds, item_ty);
464 bounds
465 }
466 rustc_hir::OpaqueTyOrigin::FnReturn {
467 parent: _,
468 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
469 }
470 | rustc_hir::OpaqueTyOrigin::AsyncFn {
471 parent: _,
472 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
473 }
474 | rustc_hir::OpaqueTyOrigin::TyAlias { parent: _, .. } => {
475 let args = GenericArgs::identity_for_item(tcx, def_id);
476 let item_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
477 let bounds = opaque_type_bounds(tcx, def_id, bounds, item_ty, *span, filter);
478 assert_only_contains_predicates_from(filter, bounds, item_ty);
479 bounds
480 }
481 },
482 hir::Node::Item(hir::Item { kind: hir::ItemKind::TyAlias(..), .. }) => &[],
483 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:?}"),
484 };
485
486 ty::EarlyBinder::bind(bounds)
487}
488
489pub(super) fn item_bounds(tcx: TyCtxt<'_>, def_id: DefId) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
490 tcx.explicit_item_bounds(def_id).map_bound(|bounds| {
491 tcx.mk_clauses_from_iter(util::elaborate(tcx, bounds.iter().map(|&(bound, _span)| bound)))
492 })
493}
494
495pub(super) fn item_self_bounds(
496 tcx: TyCtxt<'_>,
497 def_id: DefId,
498) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
499 tcx.explicit_item_self_bounds(def_id).map_bound(|bounds| {
500 tcx.mk_clauses_from_iter(
501 util::elaborate(tcx, bounds.iter().map(|&(bound, _span)| bound)).filter_only_self(),
502 )
503 })
504}
505
506pub(super) fn item_non_self_bounds(
509 tcx: TyCtxt<'_>,
510 def_id: DefId,
511) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
512 let all_bounds: FxIndexSet<_> = tcx.item_bounds(def_id).skip_binder().iter().collect();
513 let own_bounds: FxIndexSet<_> = tcx.item_self_bounds(def_id).skip_binder().iter().collect();
514 if all_bounds.len() == own_bounds.len() {
515 ty::EarlyBinder::bind(ty::ListWithCachedTypeInfo::empty())
516 } else {
517 ty::EarlyBinder::bind(tcx.mk_clauses_from_iter(all_bounds.difference(&own_bounds).copied()))
518 }
519}
520
521pub(super) fn impl_super_outlives(
524 tcx: TyCtxt<'_>,
525 def_id: DefId,
526) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
527 tcx.impl_trait_header(def_id).trait_ref.map_bound(|trait_ref| {
528 let clause: ty::Clause<'_> = trait_ref.upcast(tcx);
529 tcx.mk_clauses_from_iter(util::elaborate(tcx, [clause]).filter(|clause| {
530 #[allow(non_exhaustive_omitted_patterns)] match clause.kind().skip_binder() {
ty::ClauseKind::TypeOutlives(_) | ty::ClauseKind::RegionOutlives(_) =>
true,
_ => false,
}matches!(
531 clause.kind().skip_binder(),
532 ty::ClauseKind::TypeOutlives(_) | ty::ClauseKind::RegionOutlives(_)
533 )
534 }))
535 })
536}
537
538struct AssocTyToOpaque<'tcx> {
539 tcx: TyCtxt<'tcx>,
540 fn_def_id: DefId,
541}
542
543impl<'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTyToOpaque<'tcx> {
544 fn cx(&self) -> TyCtxt<'tcx> {
545 self.tcx
546 }
547
548 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
549 if let ty::Alias(ty::Projection, projection_ty) = ty.kind()
550 && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) =
551 self.tcx.opt_rpitit_info(projection_ty.def_id)
552 && fn_def_id == self.fn_def_id
553 {
554 self.tcx.type_of(projection_ty.def_id).instantiate(self.tcx, projection_ty.args)
555 } else {
556 ty.super_fold_with(self)
557 }
558 }
559}