3 // Terms are structured as a straightforward tree. Rather than rely on
4 // GC, we allocate terms out of a bounded arena (the lifetime of this
5 // arena is the lifetime 'a that is threaded around).
7 // We assign a unique index to each type/region parameter whose variance
8 // is to be inferred. We refer to such variables as "inferreds". An
9 // `InferredIndex` is a newtype'd int representing the index of such
12 use rustc_arena::TypedArena;
14 use rustc_hir::itemlikevisit::ItemLikeVisitor;
15 use rustc_hir::HirIdMap;
16 use rustc_middle::ty::{self, TyCtxt};
19 use self::VarianceTerm::*;
21 pub type VarianceTermPtr<'a> = &'a VarianceTerm<'a>;
23 #[derive(Copy, Clone, Debug)]
24 pub struct InferredIndex(pub usize);
26 #[derive(Copy, Clone)]
27 pub enum VarianceTerm<'a> {
28 ConstantTerm(ty::Variance),
29 TransformTerm(VarianceTermPtr<'a>, VarianceTermPtr<'a>),
30 InferredTerm(InferredIndex),
33 impl<'a> fmt::Debug for VarianceTerm<'a> {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 ConstantTerm(c1) => write!(f, "{:?}", c1),
37 TransformTerm(v1, v2) => write!(f, "({:?} \u{00D7} {:?})", v1, v2),
38 InferredTerm(id) => write!(f, "[{}]", {
39 let InferredIndex(i) = id;
46 // The first pass over the crate simply builds up the set of inferreds.
48 pub struct TermsContext<'a, 'tcx> {
49 pub tcx: TyCtxt<'tcx>,
50 pub arena: &'a TypedArena<VarianceTerm<'a>>,
52 // For marker types, UnsafeCell, and other lang items where
53 // variance is hardcoded, records the item-id and the hardcoded
55 pub lang_items: Vec<(hir::HirId, Vec<ty::Variance>)>,
57 // Maps from the node id of an item to the first inferred index
58 // used for its type & region parameters.
59 pub inferred_starts: HirIdMap<InferredIndex>,
61 // Maps from an InferredIndex to the term for that variable.
62 pub inferred_terms: Vec<VarianceTermPtr<'a>>,
65 pub fn determine_parameters_to_be_inferred<'a, 'tcx>(
67 arena: &'a mut TypedArena<VarianceTerm<'a>>,
68 ) -> TermsContext<'a, 'tcx> {
69 let mut terms_cx = TermsContext {
72 inferred_starts: Default::default(),
73 inferred_terms: vec![],
75 lang_items: lang_items(tcx),
78 // See the following for a discussion on dep-graph management.
80 // - https://rustc-dev-guide.rust-lang.org/query.html
81 // - https://rustc-dev-guide.rust-lang.org/variance.html
82 tcx.hir().krate().visit_all_item_likes(&mut terms_cx);
87 fn lang_items(tcx: TyCtxt<'_>) -> Vec<(hir::HirId, Vec<ty::Variance>)> {
88 let lang_items = tcx.lang_items();
90 (lang_items.phantom_data(), vec![ty::Covariant]),
91 (lang_items.unsafe_cell_type(), vec![ty::Invariant]),
94 all.into_iter() // iterating over (Option<DefId>, Variance)
95 .filter(|&(ref d, _)| d.is_some())
96 .map(|(d, v)| (d.unwrap(), v)) // (DefId, Variance)
97 .filter_map(|(d, v)| {
98 d.as_local().map(|d| tcx.hir().local_def_id_to_hir_id(d)).map(|n| (n, v))
99 }) // (HirId, Variance)
103 impl<'a, 'tcx> TermsContext<'a, 'tcx> {
104 fn add_inferreds_for_item(&mut self, id: hir::HirId) {
106 let def_id = tcx.hir().local_def_id(id);
107 let count = tcx.generics_of(def_id).count();
113 // Record the start of this item's inferreds.
114 let start = self.inferred_terms.len();
115 let newly_added = self.inferred_starts.insert(id, InferredIndex(start)).is_none();
116 assert!(newly_added);
118 // N.B., in the code below for writing the results back into the
119 // `CrateVariancesMap`, we rely on the fact that all inferreds
120 // for a particular item are assigned continuous indices.
122 let arena = self.arena;
123 self.inferred_terms.extend(
124 (start..(start + count)).map(|i| &*arena.alloc(InferredTerm(InferredIndex(i)))),
129 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for TermsContext<'a, 'tcx> {
130 fn visit_item(&mut self, item: &hir::Item<'_>) {
131 debug!("add_inferreds for item {}", self.tcx.hir().node_to_string(item.hir_id));
134 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
135 self.add_inferreds_for_item(item.hir_id);
137 if let hir::VariantData::Tuple(..) = *struct_def {
138 self.add_inferreds_for_item(struct_def.ctor_hir_id().unwrap());
142 hir::ItemKind::Enum(ref enum_def, _) => {
143 self.add_inferreds_for_item(item.hir_id);
145 for variant in enum_def.variants {
146 if let hir::VariantData::Tuple(..) = variant.data {
147 self.add_inferreds_for_item(variant.data.ctor_hir_id().unwrap());
152 hir::ItemKind::Fn(..) => {
153 self.add_inferreds_for_item(item.hir_id);
156 hir::ItemKind::ForeignMod(ref foreign_mod) => {
157 for foreign_item in foreign_mod.items {
158 if let hir::ForeignItemKind::Fn(..) = foreign_item.kind {
159 self.add_inferreds_for_item(foreign_item.hir_id);
168 fn visit_trait_item(&mut self, trait_item: &hir::TraitItem<'_>) {
169 if let hir::TraitItemKind::Fn(..) = trait_item.kind {
170 self.add_inferreds_for_item(trait_item.hir_id);
174 fn visit_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) {
175 if let hir::ImplItemKind::Fn(..) = impl_item.kind {
176 self.add_inferreds_for_item(impl_item.hir_id);