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    match tcx.def_kind(item_def_id) {
48        DefKind::Fn
49        | DefKind::AssocFn
50        | DefKind::Enum
51        | DefKind::Struct
52        | DefKind::Union
53        | DefKind::Variant
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!(tcx.def_span(item_def_id), "asked to compute variance for wrong kind of item");
93}
94
95#[derive(Debug, Copy, Clone)]
96enum ForceCaptureTraitArgs {
97    Yes,
98    No,
99}
100
101#[instrument(level = "trace", skip(tcx), ret)]
102fn variance_of_opaque(
103    tcx: TyCtxt<'_>,
104    item_def_id: LocalDefId,
105    force_capture_trait_args: ForceCaptureTraitArgs,
106) -> &[ty::Variance] {
107    let generics = tcx.generics_of(item_def_id);
108
109    // Opaque types may only use regions that are bound. So for
110    // ```rust
111    // type Foo<'a, 'b, 'c> = impl Trait<'a> + 'b;
112    // ```
113    // we may not use `'c` in the hidden type.
114    struct OpaqueTypeLifetimeCollector<'tcx> {
115        tcx: TyCtxt<'tcx>,
116        root_def_id: DefId,
117        variances: Vec<ty::Variance>,
118    }
119
120    impl<'tcx> OpaqueTypeLifetimeCollector<'tcx> {
121        #[instrument(level = "trace", skip(self), ret)]
122        fn visit_opaque(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) {
123            if def_id != self.root_def_id && self.tcx.is_descendant_of(def_id, self.root_def_id) {
124                let child_variances = self.tcx.variances_of(def_id);
125                for (a, v) in args.iter().zip_eq(child_variances) {
126                    if *v != ty::Bivariant {
127                        a.visit_with(self);
128                    }
129                }
130            } else {
131                args.visit_with(self)
132            }
133        }
134    }
135
136    impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeLifetimeCollector<'tcx> {
137        #[instrument(level = "trace", skip(self), ret)]
138        fn visit_region(&mut self, r: ty::Region<'tcx>) {
139            if let ty::RegionKind::ReEarlyParam(ebr) = r.kind() {
140                self.variances[ebr.index as usize] = ty::Invariant;
141            }
142        }
143
144        #[instrument(level = "trace", skip(self), ret)]
145        fn visit_ty(&mut self, t: Ty<'tcx>) {
146            match t.kind() {
147                ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
148                    self.visit_opaque(*def_id, args);
149                }
150                _ => t.super_visit_with(self),
151            }
152        }
153    }
154
155    // By default, RPIT are invariant wrt type and const generics, but they are bivariant wrt
156    // lifetime generics.
157    let mut variances = vec![ty::Invariant; generics.count()];
158
159    // Mark all lifetimes from parent generics as unused (Bivariant).
160    // This will be overridden later if required.
161    {
162        let mut generics = generics;
163        while let Some(def_id) = generics.parent {
164            generics = tcx.generics_of(def_id);
165
166            // Don't mark trait params generic if we're in an RPITIT.
167            if matches!(force_capture_trait_args, ForceCaptureTraitArgs::Yes)
168                && generics.parent.is_none()
169            {
170                debug_assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
171                break;
172            }
173
174            for param in &generics.own_params {
175                match param.kind {
176                    ty::GenericParamDefKind::Lifetime => {
177                        variances[param.index as usize] = ty::Bivariant;
178                    }
179                    ty::GenericParamDefKind::Type { .. }
180                    | ty::GenericParamDefKind::Const { .. } => {}
181                }
182            }
183        }
184    }
185
186    let mut collector =
187        OpaqueTypeLifetimeCollector { tcx, root_def_id: item_def_id.to_def_id(), variances };
188    let id_args = ty::GenericArgs::identity_for_item(tcx, item_def_id);
189    for (pred, _) in tcx.explicit_item_bounds(item_def_id).iter_instantiated_copied(tcx, id_args) {
190        debug!(?pred);
191
192        // We only ignore opaque type args if the opaque type is the outermost type.
193        // The opaque type may be nested within itself via recursion in e.g.
194        // type Foo<'a> = impl PartialEq<Foo<'a>>;
195        // which thus mentions `'a` and should thus accept hidden types that borrow 'a
196        // instead of requiring an additional `+ 'a`.
197        match pred.kind().skip_binder() {
198            ty::ClauseKind::Trait(ty::TraitPredicate {
199                trait_ref: ty::TraitRef { def_id: _, args, .. },
200                polarity: _,
201            }) => {
202                for arg in &args[1..] {
203                    arg.visit_with(&mut collector);
204                }
205            }
206            ty::ClauseKind::Projection(ty::ProjectionPredicate {
207                projection_term: ty::AliasTerm { args, .. },
208                term,
209            }) => {
210                for arg in &args[1..] {
211                    arg.visit_with(&mut collector);
212                }
213                term.visit_with(&mut collector);
214            }
215            ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(_, region)) => {
216                region.visit_with(&mut collector);
217            }
218            _ => {
219                pred.visit_with(&mut collector);
220            }
221        }
222    }
223    tcx.arena.alloc_from_iter(collector.variances)
224}