rustc_hir_analysis/variance/
mod.rs

1//! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide]
2//! chapter for more info.
3//!
4//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html
5
6use itertools::Itertools;
7use rustc_arena::DroplessArena;
8use rustc_hir as hir;
9use rustc_hir::def::DefKind;
10use rustc_hir::def_id::{DefId, LocalDefId};
11use rustc_middle::query::Providers;
12use rustc_middle::span_bug;
13use rustc_middle::ty::{
14    self, CrateVariancesMap, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
15};
16use tracing::{debug, instrument};
17
18/// Defines the `TermsContext` basically houses an arena where we can
19/// allocate terms.
20mod terms;
21
22/// Code to gather up constraints.
23mod constraints;
24
25/// Code to solve constraints and write out the results.
26mod solve;
27
28pub(crate) mod dump;
29
30pub(crate) fn provide(providers: &mut Providers) {
31    *providers = Providers { variances_of, crate_variances, ..*providers };
32}
33
34fn crate_variances(tcx: TyCtxt<'_>, (): ()) -> CrateVariancesMap<'_> {
35    let arena = DroplessArena::default();
36    let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &arena);
37    let constraints_cx = constraints::add_constraints_from_crate(terms_cx);
38    solve::solve_constraints(constraints_cx)
39}
40
41fn variances_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Variance] {
42    // Skip items with no generics - there's nothing to infer in them.
43    if tcx.generics_of(item_def_id).is_empty() {
44        return &[];
45    }
46
47    let kind = tcx.def_kind(item_def_id);
48    match kind {
49        DefKind::Fn
50        | DefKind::AssocFn
51        | DefKind::Enum
52        | DefKind::Struct
53        | DefKind::Union
54        | DefKind::Ctor(..) => {
55            // These are inferred.
56            let crate_map = tcx.crate_variances(());
57            return crate_map.variances.get(&item_def_id.to_def_id()).copied().unwrap_or(&[]);
58        }
59        DefKind::TyAlias if tcx.type_alias_is_lazy(item_def_id) => {
60            // These are inferred.
61            let crate_map = tcx.crate_variances(());
62            return crate_map.variances.get(&item_def_id.to_def_id()).copied().unwrap_or(&[]);
63        }
64        DefKind::AssocTy => match tcx.opt_rpitit_info(item_def_id.to_def_id()) {
65            Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
66                return variance_of_opaque(
67                    tcx,
68                    opaque_def_id.expect_local(),
69                    ForceCaptureTraitArgs::Yes,
70                );
71            }
72            None | Some(ty::ImplTraitInTraitData::Impl { .. }) => {}
73        },
74        DefKind::OpaqueTy => {
75            let force_capture_trait_args = if let hir::OpaqueTyOrigin::FnReturn {
76                parent: _,
77                in_trait_or_impl: Some(hir::RpitContext::Trait),
78            } =
79                tcx.hir_node_by_def_id(item_def_id).expect_opaque_ty().origin
80            {
81                ForceCaptureTraitArgs::Yes
82            } else {
83                ForceCaptureTraitArgs::No
84            };
85
86            return variance_of_opaque(tcx, item_def_id, force_capture_trait_args);
87        }
88        _ => {}
89    }
90
91    // Variance not relevant.
92    span_bug!(
93        tcx.def_span(item_def_id),
94        "asked to compute variance for {}",
95        kind.descr(item_def_id.to_def_id())
96    );
97}
98
99#[derive(Debug, Copy, Clone)]
100enum ForceCaptureTraitArgs {
101    Yes,
102    No,
103}
104
105#[instrument(level = "trace", skip(tcx), ret)]
106fn variance_of_opaque(
107    tcx: TyCtxt<'_>,
108    item_def_id: LocalDefId,
109    force_capture_trait_args: ForceCaptureTraitArgs,
110) -> &[ty::Variance] {
111    let generics = tcx.generics_of(item_def_id);
112
113    // Opaque types may only use regions that are bound. So for
114    // ```rust
115    // type Foo<'a, 'b, 'c> = impl Trait<'a> + 'b;
116    // ```
117    // we may not use `'c` in the hidden type.
118    struct OpaqueTypeLifetimeCollector<'tcx> {
119        tcx: TyCtxt<'tcx>,
120        root_def_id: DefId,
121        variances: Vec<ty::Variance>,
122    }
123
124    impl<'tcx> OpaqueTypeLifetimeCollector<'tcx> {
125        #[instrument(level = "trace", skip(self), ret)]
126        fn visit_opaque(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) {
127            if def_id != self.root_def_id && self.tcx.is_descendant_of(def_id, self.root_def_id) {
128                let child_variances = self.tcx.variances_of(def_id);
129                for (a, v) in args.iter().zip_eq(child_variances) {
130                    if *v != ty::Bivariant {
131                        a.visit_with(self);
132                    }
133                }
134            } else {
135                args.visit_with(self)
136            }
137        }
138    }
139
140    impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeLifetimeCollector<'tcx> {
141        #[instrument(level = "trace", skip(self), ret)]
142        fn visit_region(&mut self, r: ty::Region<'tcx>) {
143            if let ty::RegionKind::ReEarlyParam(ebr) = r.kind() {
144                self.variances[ebr.index as usize] = ty::Invariant;
145            }
146        }
147
148        #[instrument(level = "trace", skip(self), ret)]
149        fn visit_ty(&mut self, t: Ty<'tcx>) {
150            match t.kind() {
151                ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
152                    self.visit_opaque(*def_id, args);
153                }
154                _ => t.super_visit_with(self),
155            }
156        }
157    }
158
159    // By default, RPIT are invariant wrt type and const generics, but they are bivariant wrt
160    // lifetime generics.
161    let mut variances = vec![ty::Invariant; generics.count()];
162
163    // Mark all lifetimes from parent generics as unused (Bivariant).
164    // This will be overridden later if required.
165    {
166        let mut generics = generics;
167        while let Some(def_id) = generics.parent {
168            generics = tcx.generics_of(def_id);
169
170            // Don't mark trait params generic if we're in an RPITIT.
171            if matches!(force_capture_trait_args, ForceCaptureTraitArgs::Yes)
172                && generics.parent.is_none()
173            {
174                debug_assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
175                break;
176            }
177
178            for param in &generics.own_params {
179                match param.kind {
180                    ty::GenericParamDefKind::Lifetime => {
181                        variances[param.index as usize] = ty::Bivariant;
182                    }
183                    ty::GenericParamDefKind::Type { .. }
184                    | ty::GenericParamDefKind::Const { .. } => {}
185                }
186            }
187        }
188    }
189
190    let mut collector =
191        OpaqueTypeLifetimeCollector { tcx, root_def_id: item_def_id.to_def_id(), variances };
192    let id_args = ty::GenericArgs::identity_for_item(tcx, item_def_id);
193    for (pred, _) in tcx.explicit_item_bounds(item_def_id).iter_instantiated_copied(tcx, id_args) {
194        debug!(?pred);
195
196        // We only ignore opaque type args if the opaque type is the outermost type.
197        // The opaque type may be nested within itself via recursion in e.g.
198        // type Foo<'a> = impl PartialEq<Foo<'a>>;
199        // which thus mentions `'a` and should thus accept hidden types that borrow 'a
200        // instead of requiring an additional `+ 'a`.
201        match pred.kind().skip_binder() {
202            ty::ClauseKind::Trait(ty::TraitPredicate {
203                trait_ref: ty::TraitRef { def_id: _, args, .. },
204                polarity: _,
205            })
206            | ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
207                trait_ref: ty::TraitRef { def_id: _, args, .. },
208                constness: _,
209            }) => {
210                for arg in &args[1..] {
211                    arg.visit_with(&mut collector);
212                }
213            }
214            ty::ClauseKind::Projection(ty::ProjectionPredicate {
215                projection_term: ty::AliasTerm { args, .. },
216                term,
217            }) => {
218                for arg in &args[1..] {
219                    arg.visit_with(&mut collector);
220                }
221                term.visit_with(&mut collector);
222            }
223            ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(_, region)) => {
224                region.visit_with(&mut collector);
225            }
226            _ => {
227                pred.visit_with(&mut collector);
228            }
229        }
230    }
231    tcx.arena.alloc_from_iter(collector.variances)
232}