]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/variance/mod.rs
Rollup merge of #102493 - nnethercote:improve-size-assertions-some-more, r=lqd
[rust.git] / compiler / rustc_hir_analysis / src / 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
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};
11
12 /// Defines the `TermsContext` basically houses an arena where we can
13 /// allocate terms.
14 mod terms;
15
16 /// Code to gather up constraints.
17 mod constraints;
18
19 /// Code to solve constraints and write out the results.
20 mod solve;
21
22 /// Code to write unit tests of variance.
23 pub mod test;
24
25 /// Code for transforming variances.
26 mod xform;
27
28 pub fn provide(providers: &mut Providers) {
29     *providers = Providers { variances_of, crate_variances, ..*providers };
30 }
31
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)
37 }
38
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 {
42         return &[];
43     }
44
45     match tcx.def_kind(item_def_id) {
46         DefKind::Fn
47         | DefKind::AssocFn
48         | DefKind::Enum
49         | DefKind::Struct
50         | DefKind::Union
51         | DefKind::Variant
52         | DefKind::Ctor(..) => {}
53         _ => {
54             // Variance not relevant.
55             span_bug!(tcx.def_span(item_def_id), "asked to compute variance for wrong kind of item")
56         }
57     }
58
59     // Everything else must be inferred.
60
61     let crate_map = tcx.crate_variances(());
62     crate_map.variances.get(&item_def_id).copied().unwrap_or(&[])
63 }