rustc_hir_analysis/collect/
item_bounds.rs

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::{HirTyLowerer, PredicateFilter};
16
17/// For associated types we include both bounds written on the type
18/// (`type X: Trait`) and predicates from the trait: `where Self::X: Trait`.
19///
20/// Note that this filtering is done with the items identity args to
21/// simplify checking that these bounds are met in impls. This means that
22/// a bound such as `for<'b> <Self as X<'b>>::U: Clone` can't be used, as in
23/// `hr-associated-type-bound-1.rs`.
24fn associated_type_bounds<'tcx>(
25    tcx: TyCtxt<'tcx>,
26    assoc_item_def_id: LocalDefId,
27    hir_bounds: &'tcx [hir::GenericBound<'tcx>],
28    span: Span,
29    filter: PredicateFilter,
30) -> &'tcx [(ty::Clause<'tcx>, Span)] {
31    ty::print::with_reduced_queries!({
32        let item_ty = Ty::new_projection_from_args(
33            tcx,
34            assoc_item_def_id.to_def_id(),
35            GenericArgs::identity_for_item(tcx, assoc_item_def_id),
36        );
37
38        let icx = ItemCtxt::new(tcx, assoc_item_def_id);
39        let mut bounds = Vec::new();
40        icx.lowerer().lower_bounds(item_ty, hir_bounds, &mut bounds, ty::List::empty(), filter);
41        // Implicit bounds are added to associated types unless a `?Trait` bound is found
42        match filter {
43            PredicateFilter::All
44            | PredicateFilter::SelfOnly
45            | PredicateFilter::SelfTraitThatDefines(_)
46            | PredicateFilter::SelfAndAssociatedTypeBounds => {
47                icx.lowerer().add_default_traits(&mut bounds, item_ty, hir_bounds, None, span);
48            }
49            // `ConstIfConst` is only interested in `~const` bounds.
50            PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
51        }
52
53        let trait_def_id = tcx.local_parent(assoc_item_def_id);
54        let trait_predicates = tcx.trait_explicit_predicates_and_bounds(trait_def_id);
55
56        let item_trait_ref = ty::TraitRef::identity(tcx, tcx.parent(assoc_item_def_id.to_def_id()));
57        let bounds_from_parent =
58            trait_predicates.predicates.iter().copied().filter_map(|(clause, span)| {
59                remap_gat_vars_and_recurse_into_nested_projections(
60                    tcx,
61                    filter,
62                    item_trait_ref,
63                    assoc_item_def_id,
64                    span,
65                    clause,
66                )
67            });
68
69        let all_bounds = tcx.arena.alloc_from_iter(bounds.into_iter().chain(bounds_from_parent));
70        debug!(
71            "associated_type_bounds({}) = {:?}",
72            tcx.def_path_str(assoc_item_def_id.to_def_id()),
73            all_bounds
74        );
75
76        assert_only_contains_predicates_from(filter, all_bounds, item_ty);
77
78        all_bounds
79    })
80}
81
82/// The code below is quite involved, so let me explain.
83///
84/// We loop here, because we also want to collect vars for nested associated items as
85/// well. For example, given a clause like `Self::A::B`, we want to add that to the
86/// item bounds for `A`, so that we may use that bound in the case that `Self::A::B` is
87/// rigid.
88///
89/// Secondly, regarding bound vars, when we see a where clause that mentions a GAT
90/// like `for<'a, ...> Self::Assoc<'a, ...>: Bound<'b, ...>`, we want to turn that into
91/// an item bound on the GAT, where all of the GAT args are substituted with the GAT's
92/// param regions, and then keep all of the other late-bound vars in the bound around.
93/// We need to "compress" the binder so that it doesn't mention any of those vars that
94/// were mapped to params.
95fn remap_gat_vars_and_recurse_into_nested_projections<'tcx>(
96    tcx: TyCtxt<'tcx>,
97    filter: PredicateFilter,
98    item_trait_ref: ty::TraitRef<'tcx>,
99    assoc_item_def_id: LocalDefId,
100    span: Span,
101    clause: ty::Clause<'tcx>,
102) -> Option<(ty::Clause<'tcx>, Span)> {
103    let mut clause_ty = match clause.kind().skip_binder() {
104        ty::ClauseKind::Trait(tr) => tr.self_ty(),
105        ty::ClauseKind::Projection(proj) => proj.projection_term.self_ty(),
106        ty::ClauseKind::TypeOutlives(outlives) => outlives.0,
107        _ => return None,
108    };
109
110    let gat_vars = loop {
111        if let ty::Alias(ty::Projection, alias_ty) = *clause_ty.kind() {
112            if alias_ty.trait_ref(tcx) == item_trait_ref
113                && alias_ty.def_id == assoc_item_def_id.to_def_id()
114            {
115                // We have found the GAT in question...
116                // Return the vars, since we may need to remap them.
117                break &alias_ty.args[item_trait_ref.args.len()..];
118            } else {
119                // Only collect *self* type bounds if the filter is for self.
120                match filter {
121                    PredicateFilter::All => {}
122                    PredicateFilter::SelfOnly => {
123                        return None;
124                    }
125                    PredicateFilter::SelfTraitThatDefines(_)
126                    | PredicateFilter::SelfConstIfConst
127                    | PredicateFilter::SelfAndAssociatedTypeBounds
128                    | PredicateFilter::ConstIfConst => {
129                        unreachable!(
130                            "invalid predicate filter for \
131                            `remap_gat_vars_and_recurse_into_nested_projections`"
132                        )
133                    }
134                }
135
136                clause_ty = alias_ty.self_ty();
137                continue;
138            }
139        }
140
141        return None;
142    };
143
144    // Special-case: No GAT vars, no mapping needed.
145    if gat_vars.is_empty() {
146        return Some((clause, span));
147    }
148
149    // First, check that all of the GAT args are substituted with a unique late-bound arg.
150    // If we find a duplicate, then it can't be mapped to the definition's params.
151    let mut mapping = FxIndexMap::default();
152    let generics = tcx.generics_of(assoc_item_def_id);
153    for (param, var) in std::iter::zip(&generics.own_params, gat_vars) {
154        let existing = match var.kind() {
155            ty::GenericArgKind::Lifetime(re) => {
156                if let ty::RegionKind::ReBound(ty::INNERMOST, bv) = re.kind() {
157                    mapping.insert(bv.var, tcx.mk_param_from_def(param))
158                } else {
159                    return None;
160                }
161            }
162            ty::GenericArgKind::Type(ty) => {
163                if let ty::Bound(ty::INNERMOST, bv) = *ty.kind() {
164                    mapping.insert(bv.var, tcx.mk_param_from_def(param))
165                } else {
166                    return None;
167                }
168            }
169            ty::GenericArgKind::Const(ct) => {
170                if let ty::ConstKind::Bound(ty::INNERMOST, bv) = ct.kind() {
171                    mapping.insert(bv, tcx.mk_param_from_def(param))
172                } else {
173                    return None;
174                }
175            }
176        };
177
178        if existing.is_some() {
179            return None;
180        }
181    }
182
183    // Finally, map all of the args in the GAT to the params we expect, and compress
184    // the remaining late-bound vars so that they count up from var 0.
185    let mut folder =
186        MapAndCompressBoundVars { tcx, binder: ty::INNERMOST, still_bound_vars: vec![], mapping };
187    let pred = clause.kind().skip_binder().fold_with(&mut folder);
188
189    Some((
190        ty::Binder::bind_with_vars(pred, tcx.mk_bound_variable_kinds(&folder.still_bound_vars))
191            .upcast(tcx),
192        span,
193    ))
194}
195
196/// Given some where clause like `for<'b, 'c> <Self as Trait<'a_identity>>::Gat<'b>: Bound<'c>`,
197/// the mapping will map `'b` back to the GAT's `'b_identity`. Then we need to compress the
198/// remaining bound var `'c` to index 0.
199///
200/// This folder gives us: `for<'c> <Self as Trait<'a_identity>>::Gat<'b_identity>: Bound<'c>`,
201/// which is sufficient for an item bound for `Gat`, since all of the GAT's args are identity.
202struct MapAndCompressBoundVars<'tcx> {
203    tcx: TyCtxt<'tcx>,
204    /// How deep are we? Makes sure we don't touch the vars of nested binders.
205    binder: ty::DebruijnIndex,
206    /// List of bound vars that remain unsubstituted because they were not
207    /// mentioned in the GAT's args.
208    still_bound_vars: Vec<ty::BoundVariableKind>,
209    /// Subtle invariant: If the `GenericArg` is bound, then it should be
210    /// stored with the debruijn index of `INNERMOST` so it can be shifted
211    /// correctly during substitution.
212    mapping: FxIndexMap<ty::BoundVar, ty::GenericArg<'tcx>>,
213}
214
215impl<'tcx> TypeFolder<TyCtxt<'tcx>> for MapAndCompressBoundVars<'tcx> {
216    fn cx(&self) -> TyCtxt<'tcx> {
217        self.tcx
218    }
219
220    fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
221    where
222        ty::Binder<'tcx, T>: TypeSuperFoldable<TyCtxt<'tcx>>,
223    {
224        self.binder.shift_in(1);
225        let out = t.super_fold_with(self);
226        self.binder.shift_out(1);
227        out
228    }
229
230    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
231        if !ty.has_bound_vars() {
232            return ty;
233        }
234
235        if let ty::Bound(binder, old_bound) = *ty.kind()
236            && self.binder == binder
237        {
238            let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
239                mapped.expect_ty()
240            } else {
241                // If we didn't find a mapped generic, then make a new one.
242                // Allocate a new var idx, and insert a new bound ty.
243                let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
244                self.still_bound_vars.push(ty::BoundVariableKind::Ty(old_bound.kind));
245                let mapped = Ty::new_bound(
246                    self.tcx,
247                    ty::INNERMOST,
248                    ty::BoundTy { var, kind: old_bound.kind },
249                );
250                self.mapping.insert(old_bound.var, mapped.into());
251                mapped
252            };
253
254            shift_vars(self.tcx, mapped, self.binder.as_u32())
255        } else {
256            ty.super_fold_with(self)
257        }
258    }
259
260    fn fold_region(&mut self, re: ty::Region<'tcx>) -> ty::Region<'tcx> {
261        if let ty::ReBound(binder, old_bound) = re.kind()
262            && self.binder == binder
263        {
264            let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
265                mapped.expect_region()
266            } else {
267                let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
268                self.still_bound_vars.push(ty::BoundVariableKind::Region(old_bound.kind));
269                let mapped = ty::Region::new_bound(
270                    self.tcx,
271                    ty::INNERMOST,
272                    ty::BoundRegion { var, kind: old_bound.kind },
273                );
274                self.mapping.insert(old_bound.var, mapped.into());
275                mapped
276            };
277
278            shift_vars(self.tcx, mapped, self.binder.as_u32())
279        } else {
280            re
281        }
282    }
283
284    fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
285        if !ct.has_bound_vars() {
286            return ct;
287        }
288
289        if let ty::ConstKind::Bound(binder, old_var) = ct.kind()
290            && self.binder == binder
291        {
292            let mapped = if let Some(mapped) = self.mapping.get(&old_var) {
293                mapped.expect_const()
294            } else {
295                let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
296                self.still_bound_vars.push(ty::BoundVariableKind::Const);
297                let mapped = ty::Const::new_bound(self.tcx, ty::INNERMOST, var);
298                self.mapping.insert(old_var, mapped.into());
299                mapped
300            };
301
302            shift_vars(self.tcx, mapped, self.binder.as_u32())
303        } else {
304            ct.super_fold_with(self)
305        }
306    }
307
308    fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
309        if !p.has_bound_vars() { p } else { p.super_fold_with(self) }
310    }
311}
312
313/// Opaque types don't inherit bounds from their parent: for return position
314/// impl trait it isn't possible to write a suitable predicate on the
315/// containing function and for type-alias impl trait we don't have a backwards
316/// compatibility issue.
317#[instrument(level = "trace", skip(tcx, item_ty))]
318fn opaque_type_bounds<'tcx>(
319    tcx: TyCtxt<'tcx>,
320    opaque_def_id: LocalDefId,
321    hir_bounds: &'tcx [hir::GenericBound<'tcx>],
322    item_ty: Ty<'tcx>,
323    span: Span,
324    filter: PredicateFilter,
325) -> &'tcx [(ty::Clause<'tcx>, Span)] {
326    ty::print::with_reduced_queries!({
327        let icx = ItemCtxt::new(tcx, opaque_def_id);
328        let mut bounds = Vec::new();
329        icx.lowerer().lower_bounds(item_ty, hir_bounds, &mut bounds, ty::List::empty(), filter);
330        // Implicit bounds are added to opaque types unless a `?Trait` bound is found
331        match filter {
332            PredicateFilter::All
333            | PredicateFilter::SelfOnly
334            | PredicateFilter::SelfTraitThatDefines(_)
335            | PredicateFilter::SelfAndAssociatedTypeBounds => {
336                icx.lowerer().add_default_traits(&mut bounds, item_ty, hir_bounds, None, span);
337            }
338            //`ConstIfConst` is only interested in `~const` bounds.
339            PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
340        }
341        debug!(?bounds);
342
343        tcx.arena.alloc_slice(&bounds)
344    })
345}
346
347pub(super) fn explicit_item_bounds(
348    tcx: TyCtxt<'_>,
349    def_id: LocalDefId,
350) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
351    explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::All)
352}
353
354pub(super) fn explicit_item_self_bounds(
355    tcx: TyCtxt<'_>,
356    def_id: LocalDefId,
357) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
358    explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::SelfOnly)
359}
360
361pub(super) fn explicit_item_bounds_with_filter(
362    tcx: TyCtxt<'_>,
363    def_id: LocalDefId,
364    filter: PredicateFilter,
365) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
366    match tcx.opt_rpitit_info(def_id.to_def_id()) {
367        // RPITIT's bounds are the same as opaque type bounds, but with
368        // a projection self type.
369        Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
370            let opaque_ty = tcx.hir_node_by_def_id(opaque_def_id.expect_local()).expect_opaque_ty();
371            let bounds =
372                associated_type_bounds(tcx, def_id, opaque_ty.bounds, opaque_ty.span, filter);
373            return ty::EarlyBinder::bind(bounds);
374        }
375        Some(ty::ImplTraitInTraitData::Impl { .. }) => {
376            span_bug!(tcx.def_span(def_id), "RPITIT in impl should not have item bounds")
377        }
378        None => {}
379    }
380
381    let bounds = match tcx.hir_node_by_def_id(def_id) {
382        hir::Node::TraitItem(hir::TraitItem {
383            kind: hir::TraitItemKind::Type(bounds, _),
384            span,
385            ..
386        }) => associated_type_bounds(tcx, def_id, bounds, *span, filter),
387        hir::Node::OpaqueTy(hir::OpaqueTy { bounds, origin, span, .. }) => match origin {
388            // Since RPITITs are lowered as projections in `<dyn HirTyLowerer>::lower_ty`,
389            // when we're asking for the item bounds of the *opaques* in a trait's default
390            // method signature, we need to map these projections back to opaques.
391            rustc_hir::OpaqueTyOrigin::FnReturn {
392                parent,
393                in_trait_or_impl: Some(hir::RpitContext::Trait),
394            }
395            | rustc_hir::OpaqueTyOrigin::AsyncFn {
396                parent,
397                in_trait_or_impl: Some(hir::RpitContext::Trait),
398            } => {
399                let args = GenericArgs::identity_for_item(tcx, def_id);
400                let item_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
401                let bounds = &*tcx.arena.alloc_slice(
402                    &opaque_type_bounds(tcx, def_id, bounds, item_ty, *span, filter)
403                        .to_vec()
404                        .fold_with(&mut AssocTyToOpaque { tcx, fn_def_id: parent.to_def_id() }),
405                );
406                assert_only_contains_predicates_from(filter, bounds, item_ty);
407                bounds
408            }
409            rustc_hir::OpaqueTyOrigin::FnReturn {
410                parent: _,
411                in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
412            }
413            | rustc_hir::OpaqueTyOrigin::AsyncFn {
414                parent: _,
415                in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
416            }
417            | rustc_hir::OpaqueTyOrigin::TyAlias { parent: _, .. } => {
418                let args = GenericArgs::identity_for_item(tcx, def_id);
419                let item_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
420                let bounds = opaque_type_bounds(tcx, def_id, bounds, item_ty, *span, filter);
421                assert_only_contains_predicates_from(filter, bounds, item_ty);
422                bounds
423            }
424        },
425        hir::Node::Item(hir::Item { kind: hir::ItemKind::TyAlias(..), .. }) => &[],
426        node => bug!("item_bounds called on {def_id:?} => {node:?}"),
427    };
428
429    ty::EarlyBinder::bind(bounds)
430}
431
432pub(super) fn item_bounds(tcx: TyCtxt<'_>, def_id: DefId) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
433    tcx.explicit_item_bounds(def_id).map_bound(|bounds| {
434        tcx.mk_clauses_from_iter(util::elaborate(tcx, bounds.iter().map(|&(bound, _span)| bound)))
435    })
436}
437
438pub(super) fn item_self_bounds(
439    tcx: TyCtxt<'_>,
440    def_id: DefId,
441) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
442    tcx.explicit_item_self_bounds(def_id).map_bound(|bounds| {
443        tcx.mk_clauses_from_iter(
444            util::elaborate(tcx, bounds.iter().map(|&(bound, _span)| bound)).filter_only_self(),
445        )
446    })
447}
448
449/// This exists as an optimization to compute only the item bounds of the item
450/// that are not `Self` bounds.
451pub(super) fn item_non_self_bounds(
452    tcx: TyCtxt<'_>,
453    def_id: DefId,
454) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
455    let all_bounds: FxIndexSet<_> = tcx.item_bounds(def_id).skip_binder().iter().collect();
456    let own_bounds: FxIndexSet<_> = tcx.item_self_bounds(def_id).skip_binder().iter().collect();
457    if all_bounds.len() == own_bounds.len() {
458        ty::EarlyBinder::bind(ty::ListWithCachedTypeInfo::empty())
459    } else {
460        ty::EarlyBinder::bind(tcx.mk_clauses_from_iter(all_bounds.difference(&own_bounds).copied()))
461    }
462}
463
464/// This exists as an optimization to compute only the supertraits of this impl's
465/// trait that are outlives bounds.
466pub(super) fn impl_super_outlives(
467    tcx: TyCtxt<'_>,
468    def_id: DefId,
469) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
470    tcx.impl_trait_header(def_id).expect("expected an impl of trait").trait_ref.map_bound(
471        |trait_ref| {
472            let clause: ty::Clause<'_> = trait_ref.upcast(tcx);
473            tcx.mk_clauses_from_iter(util::elaborate(tcx, [clause]).filter(|clause| {
474                matches!(
475                    clause.kind().skip_binder(),
476                    ty::ClauseKind::TypeOutlives(_) | ty::ClauseKind::RegionOutlives(_)
477                )
478            }))
479        },
480    )
481}
482
483struct AssocTyToOpaque<'tcx> {
484    tcx: TyCtxt<'tcx>,
485    fn_def_id: DefId,
486}
487
488impl<'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTyToOpaque<'tcx> {
489    fn cx(&self) -> TyCtxt<'tcx> {
490        self.tcx
491    }
492
493    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
494        if let ty::Alias(ty::Projection, projection_ty) = ty.kind()
495            && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) =
496                self.tcx.opt_rpitit_info(projection_ty.def_id)
497            && fn_def_id == self.fn_def_id
498        {
499            self.tcx.type_of(projection_ty.def_id).instantiate(self.tcx, projection_ty.args)
500        } else {
501            ty.super_fold_with(self)
502        }
503    }
504}