]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/variance/mod.rs
Rollup merge of #67313 - oli-obk:document_all_the_t̶h̶i̶n̶g̶s̶dataflow, r=ecstatic...
[rust.git] / src / librustc_typeck / variance / mod.rs
1 //! Module for inferring the variance of type and lifetime parameters. See the [rustc guide]
2 //! chapter for more info.
3 //!
4 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/variance.html
5
6 use arena;
7 use hir::Node;
8 use rustc::ty::query::Providers;
9 use rustc::ty::{self, CrateVariancesMap, TyCtxt};
10 use rustc_hir as hir;
11 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
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<'_>, crate_num: CrateNum) -> &CrateVariancesMap<'_> {
34     assert_eq!(crate_num, LOCAL_CRATE);
35     let mut arena = arena::TypedArena::default();
36     let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &mut arena);
37     let constraints_cx = constraints::add_constraints_from_crate(terms_cx);
38     tcx.arena.alloc(solve::solve_constraints(constraints_cx))
39 }
40
41 fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] {
42     let id = tcx.hir().as_local_hir_id(item_def_id).expect("expected local def-id");
43     let unsupported = || {
44         // Variance not relevant.
45         span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item")
46     };
47     match tcx.hir().get(id) {
48         Node::Item(item) => match item.kind {
49             hir::ItemKind::Enum(..)
50             | hir::ItemKind::Struct(..)
51             | hir::ItemKind::Union(..)
52             | hir::ItemKind::Fn(..) => {}
53
54             _ => unsupported(),
55         },
56
57         Node::TraitItem(item) => match item.kind {
58             hir::TraitItemKind::Method(..) => {}
59
60             _ => unsupported(),
61         },
62
63         Node::ImplItem(item) => match item.kind {
64             hir::ImplItemKind::Method(..) => {}
65
66             _ => unsupported(),
67         },
68
69         Node::ForeignItem(item) => match item.kind {
70             hir::ForeignItemKind::Fn(..) => {}
71
72             _ => unsupported(),
73         },
74
75         Node::Variant(_) | Node::Ctor(..) => {}
76
77         _ => unsupported(),
78     }
79
80     // Everything else must be inferred.
81
82     let crate_map = tcx.crate_variances(LOCAL_CRATE);
83     crate_map.variances.get(&item_def_id).map(|p| *p).unwrap_or(&[])
84 }