]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/variance/mod.rs
Update const_forget.rs
[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 hir::Node;
7 use rustc::ty::query::Providers;
8 use rustc::ty::{self, CrateVariancesMap, TyCtxt};
9 use rustc_hir as hir;
10 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
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<'_>, crate_num: CrateNum) -> &CrateVariancesMap<'_> {
33     assert_eq!(crate_num, LOCAL_CRATE);
34     let mut arena = arena::TypedArena::default();
35     let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &mut arena);
36     let constraints_cx = constraints::add_constraints_from_crate(terms_cx);
37     tcx.arena.alloc(solve::solve_constraints(constraints_cx))
38 }
39
40 fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] {
41     let id = tcx.hir().as_local_hir_id(item_def_id).expect("expected local def-id");
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::Method(..) => {}
58
59             _ => unsupported(),
60         },
61
62         Node::ImplItem(item) => match item.kind {
63             hir::ImplItemKind::Method(..) => {}
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(LOCAL_CRATE);
82     crate_map.variances.get(&item_def_id).copied().unwrap_or(&[])
83 }