1 //! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide]
2 //! chapter for more info.
4 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html
7 use rustc_arena
::TypedArena
;
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}
;
13 /// Defines the `TermsContext` basically houses an arena where we can
17 /// Code to gather up constraints.
20 /// Code to solve constraints and write out the results.
23 /// Code to write unit tests of variance.
26 /// Code for transforming variances.
29 pub fn provide(providers
: &mut Providers
) {
30 *providers
= Providers { variances_of, crate_variances, ..*providers }
;
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
)
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")
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(..) => {}
57 Node
::TraitItem(item
) => match item
.kind
{
58 hir
::TraitItemKind
::Fn(..) => {}
63 Node
::ImplItem(item
) => match item
.kind
{
64 hir
::ImplItemKind
::Fn(..) => {}
69 Node
::ForeignItem(item
) => match item
.kind
{
70 hir
::ForeignItemKind
::Fn(..) => {}
75 Node
::Variant(_
) | Node
::Ctor(..) => {}
80 // Everything else must be inferred.
82 let crate_map
= tcx
.crate_variances(LOCAL_CRATE
);
83 crate_map
.variances
.get(&item_def_id
).copied().unwrap_or(&[])