]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/variance/mod.rs
Rollup merge of #87690 - sharnoff:mut-ptr-allocated-obj-link, r=Mark-Simulacrum
[rust.git] / compiler / rustc_typeck / 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 hir::Node;
7 use rustc_arena::DroplessArena;
8 use rustc_hir as hir;
9 use rustc_hir::def_id::DefId;
10 use rustc_middle::ty::query::Providers;
11 use rustc_middle::ty::{self, CrateVariancesMap, TyCtxt};
12
13 /// Defines the `TermsContext` basically houses an arena where we can
14 /// allocate terms.
15 mod terms;
16
17 /// Code to gather up constraints.
18 mod constraints;
19
20 /// Code to solve constraints and write out the results.
21 mod solve;
22
23 /// Code to write unit tests of variance.
24 pub mod test;
25
26 /// Code for transforming variances.
27 mod xform;
28
29 pub fn provide(providers: &mut Providers) {
30     *providers = Providers { variances_of, crate_variances, ..*providers };
31 }
32
33 fn crate_variances(tcx: TyCtxt<'_>, (): ()) -> CrateVariancesMap<'_> {
34     let arena = DroplessArena::default();
35     let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &arena);
36     let constraints_cx = constraints::add_constraints_from_crate(terms_cx);
37     solve::solve_constraints(constraints_cx)
38 }
39
40 fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] {
41     let id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
42     let unsupported = || {
43         // Variance not relevant.
44         span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item")
45     };
46     match tcx.hir().get(id) {
47         Node::Item(item) => match item.kind {
48             hir::ItemKind::Enum(..)
49             | hir::ItemKind::Struct(..)
50             | hir::ItemKind::Union(..)
51             | hir::ItemKind::Fn(..) => {}
52
53             _ => unsupported(),
54         },
55
56         Node::TraitItem(item) => match item.kind {
57             hir::TraitItemKind::Fn(..) => {}
58
59             _ => unsupported(),
60         },
61
62         Node::ImplItem(item) => match item.kind {
63             hir::ImplItemKind::Fn(..) => {}
64
65             _ => unsupported(),
66         },
67
68         Node::ForeignItem(item) => match item.kind {
69             hir::ForeignItemKind::Fn(..) => {}
70
71             _ => unsupported(),
72         },
73
74         Node::Variant(_) | Node::Ctor(..) => {}
75
76         _ => unsupported(),
77     }
78
79     // Everything else must be inferred.
80
81     let crate_map = tcx.crate_variances(());
82     crate_map.variances.get(&item_def_id).copied().unwrap_or(&[])
83 }