rustc_hir_analysis/outlives/
implicit_infer.rs

1use rustc_data_structures::fx::FxIndexMap;
2use rustc_hir::def::DefKind;
3use rustc_hir::def_id::DefId;
4use rustc_middle::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt};
5use rustc_span::Span;
6use tracing::debug;
7
8use super::explicit::ExplicitPredicatesMap;
9use super::utils::*;
10
11/// Infer predicates for the items in the crate.
12///
13/// `global_inferred_outlives`: this is initially the empty map that
14///     was generated by walking the items in the crate. This will
15///     now be filled with inferred predicates.
16pub(super) fn infer_predicates(
17    tcx: TyCtxt<'_>,
18) -> FxIndexMap<DefId, ty::EarlyBinder<'_, RequiredPredicates<'_>>> {
19    debug!("infer_predicates");
20
21    let mut explicit_map = ExplicitPredicatesMap::new();
22
23    let mut global_inferred_outlives = FxIndexMap::default();
24
25    // If new predicates were added then we need to re-calculate
26    // all crates since there could be new implied predicates.
27    loop {
28        let mut predicates_added = false;
29
30        // Visit all the crates and infer predicates
31        for id in tcx.hir().items() {
32            let item_did = id.owner_id;
33
34            debug!("InferVisitor::visit_item(item={:?})", item_did);
35
36            let mut item_required_predicates = RequiredPredicates::default();
37            match tcx.def_kind(item_did) {
38                DefKind::Union | DefKind::Enum | DefKind::Struct => {
39                    let adt_def = tcx.adt_def(item_did.to_def_id());
40
41                    // Iterate over all fields in item_did
42                    for field_def in adt_def.all_fields() {
43                        // Calculating the predicate requirements necessary
44                        // for item_did.
45                        //
46                        // For field of type &'a T (reference) or Adt
47                        // (struct/enum/union) there will be outlive
48                        // requirements for adt_def.
49                        let field_ty = tcx.type_of(field_def.did).instantiate_identity();
50                        let field_span = tcx.def_span(field_def.did);
51                        insert_required_predicates_to_be_wf(
52                            tcx,
53                            field_ty,
54                            field_span,
55                            &global_inferred_outlives,
56                            &mut item_required_predicates,
57                            &mut explicit_map,
58                        );
59                    }
60                }
61
62                DefKind::TyAlias if tcx.type_alias_is_lazy(item_did) => {
63                    insert_required_predicates_to_be_wf(
64                        tcx,
65                        tcx.type_of(item_did).instantiate_identity(),
66                        tcx.def_span(item_did),
67                        &global_inferred_outlives,
68                        &mut item_required_predicates,
69                        &mut explicit_map,
70                    );
71                }
72
73                _ => {}
74            };
75
76            // If new predicates were added (`local_predicate_map` has more
77            // predicates than the `global_inferred_outlives`), the new predicates
78            // might result in implied predicates for their parent types.
79            // Therefore mark `predicates_added` as true and which will ensure
80            // we walk the crates again and re-calculate predicates for all
81            // items.
82            let item_predicates_len: usize = global_inferred_outlives
83                .get(&item_did.to_def_id())
84                .map_or(0, |p| p.as_ref().skip_binder().len());
85            if item_required_predicates.len() > item_predicates_len {
86                predicates_added = true;
87                global_inferred_outlives
88                    .insert(item_did.to_def_id(), ty::EarlyBinder::bind(item_required_predicates));
89            }
90        }
91
92        if !predicates_added {
93            break;
94        }
95    }
96
97    global_inferred_outlives
98}
99
100fn insert_required_predicates_to_be_wf<'tcx>(
101    tcx: TyCtxt<'tcx>,
102    ty: Ty<'tcx>,
103    span: Span,
104    global_inferred_outlives: &FxIndexMap<DefId, ty::EarlyBinder<'tcx, RequiredPredicates<'tcx>>>,
105    required_predicates: &mut RequiredPredicates<'tcx>,
106    explicit_map: &mut ExplicitPredicatesMap<'tcx>,
107) {
108    for arg in ty.walk() {
109        let leaf_ty = match arg.unpack() {
110            GenericArgKind::Type(ty) => ty,
111
112            // No predicates from lifetimes or constants, except potentially
113            // constants' types, but `walk` will get to them as well.
114            GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
115        };
116
117        match *leaf_ty.kind() {
118            ty::Ref(region, rty, _) => {
119                // The type is `&'a T` which means that we will have
120                // a predicate requirement of `T: 'a` (`T` outlives `'a`).
121                //
122                // We also want to calculate potential predicates for the `T`.
123                debug!("Ref");
124                insert_outlives_predicate(tcx, rty.into(), region, span, required_predicates);
125            }
126
127            ty::Adt(def, args) => {
128                // For ADTs (structs/enums/unions), we check inferred and explicit predicates.
129                debug!("Adt");
130                check_inferred_predicates(
131                    tcx,
132                    def.did(),
133                    args,
134                    global_inferred_outlives,
135                    required_predicates,
136                );
137                check_explicit_predicates(
138                    tcx,
139                    def.did(),
140                    args,
141                    required_predicates,
142                    explicit_map,
143                    None,
144                );
145            }
146
147            ty::Alias(ty::Weak, alias) => {
148                // This corresponds to a type like `Type<'a, T>`.
149                // We check inferred and explicit predicates.
150                debug!("Weak");
151                check_inferred_predicates(
152                    tcx,
153                    alias.def_id,
154                    alias.args,
155                    global_inferred_outlives,
156                    required_predicates,
157                );
158                check_explicit_predicates(
159                    tcx,
160                    alias.def_id,
161                    alias.args,
162                    required_predicates,
163                    explicit_map,
164                    None,
165                );
166            }
167
168            ty::Dynamic(obj, ..) => {
169                // This corresponds to `dyn Trait<..>`. In this case, we should
170                // use the explicit predicates as well.
171                debug!("Dynamic");
172                if let Some(ex_trait_ref) = obj.principal() {
173                    // Here, we are passing the type `usize` as a
174                    // placeholder value with the function
175                    // `with_self_ty`, since there is no concrete type
176                    // `Self` for a `dyn Trait` at this
177                    // stage. Therefore when checking explicit
178                    // predicates in `check_explicit_predicates` we
179                    // need to ignore checking the explicit_map for
180                    // Self type.
181                    let args = ex_trait_ref.with_self_ty(tcx, tcx.types.usize).skip_binder().args;
182                    check_explicit_predicates(
183                        tcx,
184                        ex_trait_ref.skip_binder().def_id,
185                        args,
186                        required_predicates,
187                        explicit_map,
188                        Some(tcx.types.self_param),
189                    );
190                }
191            }
192
193            ty::Alias(ty::Projection, alias) => {
194                // This corresponds to a type like `<() as Trait<'a, T>>::Type`.
195                // We only use the explicit predicates of the trait but
196                // not the ones of the associated type itself.
197                debug!("Projection");
198                check_explicit_predicates(
199                    tcx,
200                    tcx.parent(alias.def_id),
201                    alias.args,
202                    required_predicates,
203                    explicit_map,
204                    None,
205                );
206            }
207
208            // FIXME(inherent_associated_types): Use the explicit predicates from the parent impl.
209            ty::Alias(ty::Inherent, _) => {}
210
211            _ => {}
212        }
213    }
214}
215
216/// Check the explicit predicates declared on the type.
217///
218/// ### Example
219///
220/// ```ignore (illustrative)
221/// struct Outer<'a, T> {
222///     field: Inner<T>,
223/// }
224///
225/// struct Inner<U> where U: 'static, U: Outer {
226///     // ...
227/// }
228/// ```
229/// Here, we should fetch the explicit predicates, which
230/// will give us `U: 'static` and `U: Outer`. The latter we
231/// can ignore, but we will want to process `U: 'static`,
232/// applying the instantiation as above.
233fn check_explicit_predicates<'tcx>(
234    tcx: TyCtxt<'tcx>,
235    def_id: DefId,
236    args: &[GenericArg<'tcx>],
237    required_predicates: &mut RequiredPredicates<'tcx>,
238    explicit_map: &mut ExplicitPredicatesMap<'tcx>,
239    ignored_self_ty: Option<Ty<'tcx>>,
240) {
241    debug!(
242        "check_explicit_predicates(def_id={:?}, \
243         args={:?}, \
244         explicit_map={:?}, \
245         required_predicates={:?}, \
246         ignored_self_ty={:?})",
247        def_id, args, explicit_map, required_predicates, ignored_self_ty,
248    );
249    let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id);
250
251    for (outlives_predicate, &span) in explicit_predicates.as_ref().skip_binder() {
252        debug!("outlives_predicate = {outlives_predicate:?}");
253
254        // Careful: If we are inferring the effects of a `dyn Trait<..>`
255        // type, then when we look up the predicates for `Trait`,
256        // we may find some that reference `Self`. e.g., perhaps the
257        // definition of `Trait` was:
258        //
259        // ```
260        // trait Trait<'a, T> where Self: 'a  { .. }
261        // ```
262        //
263        // we want to ignore such predicates here, because
264        // there is no type parameter for them to affect. Consider
265        // a struct containing `dyn Trait`:
266        //
267        // ```
268        // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> }
269        // ```
270        //
271        // The `where Self: 'a` predicate refers to the *existential, hidden type*
272        // that is represented by the `dyn Trait`, not to the `X` type parameter
273        // (or any other generic parameter) declared on `MyStruct`.
274        //
275        // Note that we do this check for self **before** applying `args`. In the
276        // case that `args` come from a `dyn Trait` type, our caller will have
277        // included `Self = usize` as the value for `Self`. If we were
278        // to apply the args, and not filter this predicate, we might then falsely
279        // conclude that e.g., `X: 'x` was a reasonable inferred requirement.
280        //
281        // Another similar case is where we have an inferred
282        // requirement like `<Self as Trait>::Foo: 'b`. We presently
283        // ignore such requirements as well (cc #54467)-- though
284        // conceivably it might be better if we could extract the `Foo
285        // = X` binding from the object type (there must be such a
286        // binding) and thus infer an outlives requirement that `X:
287        // 'b`.
288        if let Some(self_ty) = ignored_self_ty
289            && let GenericArgKind::Type(ty) = outlives_predicate.0.unpack()
290            && ty.walk().any(|arg| arg == self_ty.into())
291        {
292            debug!("skipping self ty = {ty:?}");
293            continue;
294        }
295
296        let predicate = explicit_predicates.rebind(*outlives_predicate).instantiate(tcx, args);
297        debug!("predicate = {predicate:?}");
298        insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates);
299    }
300}
301
302/// Check the inferred predicates declared on the type.
303///
304/// ### Example
305///
306/// ```ignore (illustrative)
307/// struct Outer<'a, T> {
308///     outer: Inner<'a, T>,
309/// }
310///
311/// struct Inner<'b, U> {
312///     inner: &'b U,
313/// }
314/// ```
315///
316/// Here, when processing the type of field `outer`, we would request the
317/// set of implicit predicates computed for `Inner` thus far. This will
318/// initially come back empty, but in next round we will get `U: 'b`.
319/// We then apply the instantiation `['b => 'a, U => T]` and thus get the
320/// requirement that `T: 'a` holds for `Outer`.
321fn check_inferred_predicates<'tcx>(
322    tcx: TyCtxt<'tcx>,
323    def_id: DefId,
324    args: ty::GenericArgsRef<'tcx>,
325    global_inferred_outlives: &FxIndexMap<DefId, ty::EarlyBinder<'tcx, RequiredPredicates<'tcx>>>,
326    required_predicates: &mut RequiredPredicates<'tcx>,
327) {
328    // Load the current set of inferred and explicit predicates from `global_inferred_outlives`
329    // and filter the ones that are `TypeOutlives`.
330
331    let Some(predicates) = global_inferred_outlives.get(&def_id) else {
332        return;
333    };
334
335    for (&predicate, &span) in predicates.as_ref().skip_binder() {
336        // `predicate` is `U: 'b` in the example above.
337        // So apply the instantiation to get `T: 'a`.
338        let ty::OutlivesPredicate(arg, region) =
339            predicates.rebind(predicate).instantiate(tcx, args);
340        insert_outlives_predicate(tcx, arg, region, span, required_predicates);
341    }
342}