]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/variance/mod.rs
New upstream version 1.47.0+dfsg1
[rustc.git] / src / librustc_typeck / 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::TypedArena;
8 use rustc_hir as hir;
9 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
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<'_>, crate_num: CrateNum) -> CrateVariancesMap<'_> {
34 assert_eq!(crate_num, LOCAL_CRATE);
35 let mut 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 solve::solve_constraints(constraints_cx)
39 }
40
41 fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] {
42 let id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
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::Fn(..) => {}
59
60 _ => unsupported(),
61 },
62
63 Node::ImplItem(item) => match item.kind {
64 hir::ImplItemKind::Fn(..) => {}
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).copied().unwrap_or(&[])
84 }