1use std::marker::PhantomData;
2
3use smallvec::smallvec;
4
5use crate::data_structures::HashSet;
6use crate::inherent::*;
7use crate::lang_items::SolverTraitLangItem;
8use crate::outlives::{Component, push_outlives_components};
9use crate::{self as ty, Interner, Region, Unnormalized, Upcast as _};
10
11pub struct Elaborator<I: Interner, O> {
18 cx: I,
19 stack: Vec<O>,
20 visited: HashSet<ty::Binder<I, ty::PredicateKind<I>>>,
21 mode: Filter,
22 elaborate_sized: ElaborateSized,
23}
24
25enum Filter {
26 All,
27 OnlySelf,
28}
29
30#[derive(#[automatically_derived]
impl ::core::cmp::Eq for ElaborateSized {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ElaborateSized {
#[inline]
fn eq(&self, other: &ElaborateSized) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
31enum ElaborateSized {
32 Yes,
33 No,
34}
35
36pub trait Elaboratable<I: Interner> {
38 fn predicate(&self) -> I::Predicate;
39
40 fn child(&self, clause: I::Clause) -> Self;
42
43 fn child_with_derived_cause(
46 &self,
47 clause: I::Clause,
48 span: I::Span,
49 parent_trait_pred: ty::Binder<I, ty::TraitPredicate<I>>,
50 index: usize,
51 ) -> Self;
52}
53
54pub struct ClauseWithSupertraitSpan<I: Interner> {
55 pub clause: I::Clause,
56 pub supertrait_span: I::Span,
58}
59
60impl<I: Interner> ClauseWithSupertraitSpan<I> {
61 pub fn new(clause: I::Clause, span: I::Span) -> Self {
62 ClauseWithSupertraitSpan { clause, supertrait_span: span }
63 }
64}
65
66impl<I: Interner> Elaboratable<I> for ClauseWithSupertraitSpan<I> {
67 fn predicate(&self) -> <I as Interner>::Predicate {
68 self.clause.as_predicate()
69 }
70
71 fn child(&self, clause: <I as Interner>::Clause) -> Self {
72 ClauseWithSupertraitSpan { clause, supertrait_span: self.supertrait_span }
73 }
74
75 fn child_with_derived_cause(
76 &self,
77 clause: <I as Interner>::Clause,
78 supertrait_span: <I as Interner>::Span,
79 _parent_trait_pred: crate::Binder<I, crate::TraitPredicate<I>>,
80 _index: usize,
81 ) -> Self {
82 ClauseWithSupertraitSpan { clause, supertrait_span }
83 }
84}
85
86pub fn elaborate<I: Interner, O: Elaboratable<I>>(
87 cx: I,
88 obligations: impl IntoIterator<Item = O>,
89) -> Elaborator<I, O> {
90 let mut elaborator = Elaborator {
91 cx,
92 stack: Vec::new(),
93 visited: HashSet::default(),
94 mode: Filter::All,
95 elaborate_sized: ElaborateSized::No,
96 };
97 elaborator.extend_deduped(obligations);
98 elaborator
99}
100
101impl<I: Interner, O: Elaboratable<I>> Elaborator<I, O> {
102 fn extend_deduped(&mut self, obligations: impl IntoIterator<Item = O>) {
104 self.stack.extend(
109 obligations.into_iter().filter(|o| {
110 self.visited.insert(self.cx.anonymize_bound_vars(o.predicate().kind()))
111 }),
112 );
113 }
114
115 pub fn filter_only_self(mut self) -> Self {
118 self.mode = Filter::OnlySelf;
119 self
120 }
121
122 pub fn elaborate_sized(mut self) -> Self {
125 self.elaborate_sized = ElaborateSized::Yes;
126 self
127 }
128
129 fn elaborate(&mut self, elaboratable: &O) {
130 let cx = self.cx;
131
132 let Some(clause) = elaboratable.predicate().as_clause() else {
134 return;
135 };
136
137 if self.elaborate_sized == ElaborateSized::No
144 && let Some(did) = clause.as_trait_clause().map(|c| c.def_id())
145 && self.cx.is_trait_lang_item(did, SolverTraitLangItem::Sized)
146 {
147 return;
148 }
149
150 let bound_clause = clause.kind();
151 match bound_clause.skip_binder() {
152 ty::ClauseKind::Trait(data) => {
153 if data.polarity != ty::PredicatePolarity::Positive {
155 return;
156 }
157
158 let map_to_child_clause =
159 |(index, (clause, span)): (usize, (I::Clause, I::Span))| {
160 elaboratable.child_with_derived_cause(
161 clause.instantiate_supertrait(cx, bound_clause.rebind(data.trait_ref)),
162 span,
163 bound_clause.rebind(data),
164 index,
165 )
166 };
167
168 match self.mode {
171 Filter::All => self.extend_deduped(
172 cx.explicit_implied_clauses_of(data.def_id().into())
173 .iter_identity()
174 .map(Unnormalized::skip_norm_wip)
175 .enumerate()
176 .map(map_to_child_clause),
177 ),
178 Filter::OnlySelf => self.extend_deduped(
179 cx.explicit_super_clauses_of(data.def_id())
180 .iter_identity()
181 .map(Unnormalized::skip_norm_wip)
182 .enumerate()
183 .map(map_to_child_clause),
184 ),
185 };
186 }
187 ty::ClauseKind::HostEffect(data) => self.extend_deduped(
189 cx.explicit_implied_const_bounds(data.def_id().into()).iter_identity().map(
190 |trait_ref| {
191 elaboratable.child(
192 trait_ref
193 .to_host_effect_clause(cx, data.constness)
194 .skip_norm_wip()
195 .instantiate_supertrait(cx, bound_clause.rebind(data.trait_ref)),
196 )
197 },
198 ),
199 ),
200 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty_max, r_min)) => {
201 if r_min.is_bound() {
216 return;
217 }
218
219 let mut components = ::smallvec::SmallVec::new()smallvec![];
220 push_outlives_components(cx, ty_max, &mut components);
221 self.extend_deduped(
222 components
223 .into_iter()
224 .filter_map(|component| elaborate_component_to_clause(cx, component, r_min))
225 .map(|clause| elaboratable.child(bound_clause.rebind(clause).upcast(cx))),
226 );
227 }
228 ty::ClauseKind::RegionOutlives(..) => {
229 }
231 ty::ClauseKind::WellFormed(..) => {
232 }
235 ty::ClauseKind::Projection(..) => {
236 }
238 ty::ClauseKind::ConstEvaluatable(..) => {
239 }
242 ty::ClauseKind::ConstArgHasType(..) => {
243 }
245 ty::ClauseKind::UnstableFeature(_) => {
246 }
248 }
249 }
250}
251
252fn elaborate_component_to_clause<I: Interner>(
253 cx: I,
254 component: Component<I>,
255 outlives_region: Region<I>,
256) -> Option<ty::ClauseKind<I>> {
257 match component {
258 Component::Region(r) => {
259 if r.is_bound() {
260 None
261 } else {
262 Some(ty::ClauseKind::RegionOutlives(ty::OutlivesClause(r, outlives_region)))
263 }
264 }
265
266 Component::Param(p) => {
267 let ty = Ty::new_param(cx, p);
268 Some(ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, outlives_region)))
269 }
270
271 Component::Placeholder(p) => {
272 let ty = Ty::new_placeholder(cx, p);
273 Some(ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, outlives_region)))
274 }
275
276 Component::UnresolvedInferenceVariable(_) => None,
277
278 Component::Alias(is_rigid, alias_ty) => {
279 Some(ty::ClauseKind::TypeOutlives(ty::OutlivesClause(
282 alias_ty.to_ty(cx, is_rigid),
283 outlives_region,
284 )))
285 }
286
287 Component::EscapingAlias(_) => {
288 None
291 }
292 }
293}
294
295impl<I: Interner, O: Elaboratable<I>> Iterator for Elaborator<I, O> {
296 type Item = O;
297
298 fn size_hint(&self) -> (usize, Option<usize>) {
299 (self.stack.len(), None)
300 }
301
302 fn next(&mut self) -> Option<Self::Item> {
303 if let Some(obligation) = self.stack.pop() {
305 self.elaborate(&obligation);
306 Some(obligation)
307 } else {
308 None
309 }
310 }
311}
312
313pub fn supertrait_def_ids<I: Interner>(
322 cx: I,
323 trait_def_id: I::TraitId,
324) -> impl Iterator<Item = I::TraitId> {
325 let mut set = HashSet::default();
326 let mut stack = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[trait_def_id]))vec![trait_def_id];
327
328 set.insert(trait_def_id);
329
330 std::iter::from_fn(move || {
331 let trait_def_id = stack.pop()?;
332
333 for (clause, _) in cx
334 .explicit_super_clauses_of(trait_def_id)
335 .iter_identity()
336 .map(Unnormalized::skip_norm_wip)
337 {
338 if let ty::ClauseKind::Trait(data) = clause.kind().skip_binder()
339 && set.insert(data.def_id())
340 {
341 stack.push(data.def_id());
342 }
343 }
344
345 Some(trait_def_id)
346 })
347}
348
349pub fn supertraits<I: Interner>(
350 cx: I,
351 trait_ref: ty::Binder<I, ty::TraitRef<I>>,
352) -> FilterToTraits<I, Elaborator<I, I::Clause>> {
353 elaborate(cx, [trait_ref.upcast(cx)]).filter_only_self().filter_to_traits()
354}
355
356impl<I: Interner> Elaborator<I, I::Clause> {
357 fn filter_to_traits(self) -> FilterToTraits<I, Self> {
358 FilterToTraits { _cx: PhantomData, base_iterator: self }
359 }
360}
361
362pub struct FilterToTraits<I: Interner, It: Iterator<Item = I::Clause>> {
365 _cx: PhantomData<I>,
366 base_iterator: It,
367}
368
369impl<I: Interner, It: Iterator<Item = I::Clause>> Iterator for FilterToTraits<I, It> {
370 type Item = ty::Binder<I, ty::TraitRef<I>>;
371
372 fn next(&mut self) -> Option<ty::Binder<I, ty::TraitRef<I>>> {
373 while let Some(pred) = self.base_iterator.next() {
374 if let Some(data) = pred.as_trait_clause() {
375 return Some(data.map_bound(|t| t.trait_ref));
376 }
377 }
378 None
379 }
380
381 fn size_hint(&self) -> (usize, Option<usize>) {
382 let (_, upper) = self.base_iterator.size_hint();
383 (0, upper)
384 }
385}
386
387pub fn elaborate_outlives_assumptions<I: Interner>(
388 cx: I,
389 assumptions: impl IntoIterator<Item = ty::OutlivesClause<I, I::GenericArg>>,
390) -> HashSet<ty::OutlivesClause<I, I::GenericArg>> {
391 let mut collected = HashSet::default();
392
393 for ty::OutlivesClause(arg1, r2) in assumptions {
394 collected.insert(ty::OutlivesClause(arg1, r2));
395 match arg1.kind() {
396 ty::GenericArgKind::Type(ty1) => {
399 let mut components = ::smallvec::SmallVec::new()smallvec![];
400 push_outlives_components(cx, ty1, &mut components);
401 for c in components {
402 match c {
403 Component::Region(r1) => {
404 if !r1.is_bound() {
405 collected.insert(ty::OutlivesClause(r1.into(), r2));
406 }
407 }
408
409 Component::Param(p) => {
410 let ty = Ty::new_param(cx, p);
411 collected.insert(ty::OutlivesClause(ty.into(), r2));
412 }
413
414 Component::Placeholder(p) => {
415 let ty = Ty::new_placeholder(cx, p);
416 collected.insert(ty::OutlivesClause(ty.into(), r2));
417 }
418
419 Component::Alias(is_rigid, alias_ty) => {
420 collected.insert(ty::OutlivesClause(
421 alias_ty.to_ty(cx, is_rigid).into(),
422 r2,
423 ));
424 }
425
426 Component::UnresolvedInferenceVariable(_) | Component::EscapingAlias(_) => {
427 }
428 }
429 }
430 }
431 ty::GenericArgKind::Lifetime(_) => {}
433 ty::GenericArgKind::Const(_) => {}
435 }
436 }
437
438 collected
439}