1 //! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide]
2 //! chapter for more info.
4 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html
6 use rustc_arena::DroplessArena;
7 use rustc_hir::def::DefKind;
8 use rustc_hir::def_id::DefId;
9 use rustc_middle::ty::query::Providers;
10 use rustc_middle::ty::{self, CrateVariancesMap, TyCtxt};
12 /// Defines the `TermsContext` basically houses an arena where we can
16 /// Code to gather up constraints.
19 /// Code to solve constraints and write out the results.
22 /// Code to write unit tests of variance.
25 /// Code for transforming variances.
28 pub fn provide(providers: &mut Providers) {
29 *providers = Providers { variances_of, crate_variances, ..*providers };
32 fn crate_variances(tcx: TyCtxt<'_>, (): ()) -> CrateVariancesMap<'_> {
33 let arena = DroplessArena::default();
34 let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &arena);
35 let constraints_cx = constraints::add_constraints_from_crate(terms_cx);
36 solve::solve_constraints(constraints_cx)
39 fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] {
40 // Skip items with no generics - there's nothing to infer in them.
41 if tcx.generics_of(item_def_id).count() == 0 {
45 match tcx.def_kind(item_def_id) {
52 | DefKind::Ctor(..) => {}
54 // Variance not relevant.
55 span_bug!(tcx.def_span(item_def_id), "asked to compute variance for wrong kind of item")
59 // Everything else must be inferred.
61 let crate_map = tcx.crate_variances(());
62 crate_map.variances.get(&item_def_id).copied().unwrap_or(&[])