]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/variance/mod.rs
Rename `ImplItem.node` to `ImplItem.kind`
[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 rustc::hir;
8 use hir::Node;
9 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
10 use rustc::ty::{self, CrateVariancesMap, TyCtxt};
11 use rustc::ty::query::Providers;
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 {
31         variances_of,
32         crate_variances,
33         ..*providers
34     };
35 }
36
37 fn crate_variances(tcx: TyCtxt<'_>, crate_num: CrateNum) -> &CrateVariancesMap<'_> {
38     assert_eq!(crate_num, LOCAL_CRATE);
39     let mut arena = arena::TypedArena::default();
40     let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &mut arena);
41     let constraints_cx = constraints::add_constraints_from_crate(terms_cx);
42     tcx.arena.alloc(solve::solve_constraints(constraints_cx))
43 }
44
45 fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] {
46     let id = tcx.hir().as_local_hir_id(item_def_id).expect("expected local def-id");
47     let unsupported = || {
48         // Variance not relevant.
49         span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item")
50     };
51     match tcx.hir().get(id) {
52         Node::Item(item) => match item.node {
53             hir::ItemKind::Enum(..) |
54             hir::ItemKind::Struct(..) |
55             hir::ItemKind::Union(..) |
56             hir::ItemKind::Fn(..) => {}
57
58             _ => unsupported()
59         },
60
61         Node::TraitItem(item) => match item.node {
62             hir::TraitItemKind::Method(..) => {}
63
64             _ => unsupported()
65         },
66
67         Node::ImplItem(item) => match item.kind {
68             hir::ImplItemKind::Method(..) => {}
69
70             _ => unsupported()
71         },
72
73         Node::ForeignItem(item) => match item.node {
74             hir::ForeignItemKind::Fn(..) => {}
75
76             _ => unsupported()
77         },
78
79         Node::Variant(_) | Node::Ctor(..) => {}
80
81         _ => unsupported()
82     }
83
84     // Everything else must be inferred.
85
86     let crate_map = tcx.crate_variances(LOCAL_CRATE);
87     crate_map.variances.get(&item_def_id)
88                        .map(|p| *p)
89                        .unwrap_or(&[])
90 }