]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/maps.rs
Auto merge of #41437 - cuviper:remove-unstable-deprecated, r=alexcrichton
[rust.git] / src / librustc / ty / maps.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use dep_graph::{DepGraph, DepNode, DepTrackingMap, DepTrackingMapConfig};
12 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
13 use hir;
14 use middle::const_val;
15 use middle::privacy::AccessLevels;
16 use mir;
17 use session::CompileResult;
18 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
19 use util::nodemap::NodeSet;
20
21 use rustc_data_structures::indexed_vec::IndexVec;
22 use std::cell::{RefCell, RefMut};
23 use std::rc::Rc;
24 use syntax_pos::{Span, DUMMY_SP};
25
26 trait Key {
27     fn map_crate(&self) -> CrateNum;
28     fn default_span(&self, tcx: TyCtxt) -> Span;
29 }
30
31 impl<'tcx> Key for ty::InstanceDef<'tcx> {
32     fn map_crate(&self) -> CrateNum {
33         LOCAL_CRATE
34     }
35
36     fn default_span(&self, tcx: TyCtxt) -> Span {
37         tcx.def_span(self.def_id())
38     }
39 }
40
41 impl Key for CrateNum {
42     fn map_crate(&self) -> CrateNum {
43         *self
44     }
45     fn default_span(&self, _: TyCtxt) -> Span {
46         DUMMY_SP
47     }
48 }
49
50 impl Key for DefId {
51     fn map_crate(&self) -> CrateNum {
52         self.krate
53     }
54     fn default_span(&self, tcx: TyCtxt) -> Span {
55         tcx.def_span(*self)
56     }
57 }
58
59 impl Key for (DefId, DefId) {
60     fn map_crate(&self) -> CrateNum {
61         self.0.krate
62     }
63     fn default_span(&self, tcx: TyCtxt) -> Span {
64         self.1.default_span(tcx)
65     }
66 }
67
68 impl Key for (CrateNum, DefId) {
69     fn map_crate(&self) -> CrateNum {
70         self.0
71     }
72     fn default_span(&self, tcx: TyCtxt) -> Span {
73         self.1.default_span(tcx)
74     }
75 }
76
77 trait Value<'tcx>: Sized {
78     fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
79 }
80
81 impl<'tcx, T> Value<'tcx> for T {
82     default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
83         tcx.sess.abort_if_errors();
84         bug!("Value::from_cycle_error called without errors");
85     }
86 }
87
88 impl<'tcx, T: Default> Value<'tcx> for T {
89     default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
90         T::default()
91     }
92 }
93
94 impl<'tcx> Value<'tcx> for Ty<'tcx> {
95     fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
96         tcx.types.err
97     }
98 }
99
100 pub struct CycleError<'a, 'tcx: 'a> {
101     span: Span,
102     cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
103 }
104
105 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
106     pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
107         assert!(!cycle.is_empty());
108
109         let mut err = struct_span_err!(self.sess, span, E0391,
110             "unsupported cyclic reference between types/traits detected");
111         err.span_label(span, &format!("cyclic reference"));
112
113         err.span_note(cycle[0].0, &format!("the cycle begins when {}...",
114                                            cycle[0].1.describe(self)));
115
116         for &(span, ref query) in &cycle[1..] {
117             err.span_note(span, &format!("...which then requires {}...",
118                                          query.describe(self)));
119         }
120
121         err.note(&format!("...which then again requires {}, completing the cycle.",
122                           cycle[0].1.describe(self)));
123
124         err.emit();
125     }
126
127     fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
128                          -> Result<R, CycleError<'a, 'gcx>>
129         where F: FnOnce() -> R
130     {
131         {
132             let mut stack = self.maps.query_stack.borrow_mut();
133             if let Some((i, _)) = stack.iter().enumerate().rev()
134                                        .find(|&(_, &(_, ref q))| *q == query) {
135                 return Err(CycleError {
136                     span: span,
137                     cycle: RefMut::map(stack, |stack| &mut stack[i..])
138                 });
139             }
140             stack.push((span, query));
141         }
142
143         let result = compute();
144
145         self.maps.query_stack.borrow_mut().pop();
146
147         Ok(result)
148     }
149 }
150
151 trait QueryDescription: DepTrackingMapConfig {
152     fn describe(tcx: TyCtxt, key: Self::Key) -> String;
153 }
154
155 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
156     default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
157         format!("processing `{}`", tcx.item_path_str(def_id))
158     }
159 }
160
161 impl<'tcx> QueryDescription for queries::super_predicates<'tcx> {
162     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
163         format!("computing the supertraits of `{}`",
164                 tcx.item_path_str(def_id))
165     }
166 }
167
168 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
169     fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
170         let id = tcx.hir.as_local_node_id(def_id).unwrap();
171         format!("computing the bounds for type parameter `{}`",
172                 tcx.hir.ty_param_name(id))
173     }
174 }
175
176 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
177     fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
178         format!("coherence checking all impls of trait `{}`",
179                 tcx.item_path_str(def_id))
180     }
181 }
182
183 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
184     fn describe(_: TyCtxt, k: CrateNum) -> String {
185         format!("all inherent impls defined in crate `{:?}`", k)
186     }
187 }
188
189 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
190     fn describe(_: TyCtxt, _: CrateNum) -> String {
191         format!("check for overlap between inherent impls defined in this crate")
192     }
193 }
194
195 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
196     fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
197         format!("generating MIR shim for `{}`",
198                 tcx.item_path_str(def.def_id()))
199     }
200 }
201
202 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
203     fn describe(_: TyCtxt, _: CrateNum) -> String {
204         format!("privacy access levels")
205     }
206 }
207
208 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
209     fn describe(_: TyCtxt, _: CrateNum) -> String {
210         format!("type-checking all item bodies")
211     }
212 }
213
214 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
215     fn describe(_: TyCtxt, _: CrateNum) -> String {
216         format!("reachability")
217     }
218 }
219
220 macro_rules! define_maps {
221     (<$tcx:tt>
222      $($(#[$attr:meta])*
223        pub $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
224         pub struct Maps<$tcx> {
225             providers: IndexVec<CrateNum, Providers<$tcx>>,
226             query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
227             $($(#[$attr])* pub $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
228         }
229
230         impl<$tcx> Maps<$tcx> {
231             pub fn new(dep_graph: DepGraph,
232                        providers: IndexVec<CrateNum, Providers<$tcx>>)
233                        -> Self {
234                 Maps {
235                     providers,
236                     query_stack: RefCell::new(vec![]),
237                     $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
238                 }
239             }
240         }
241
242         #[allow(bad_style)]
243         #[derive(Copy, Clone, Debug, PartialEq, Eq)]
244         pub enum Query<$tcx> {
245             $($(#[$attr])* $name($K)),*
246         }
247
248         impl<$tcx> Query<$tcx> {
249             pub fn describe(&self, tcx: TyCtxt) -> String {
250                 match *self {
251                     $(Query::$name(key) => queries::$name::describe(tcx, key)),*
252                 }
253             }
254         }
255
256         pub mod queries {
257             use std::marker::PhantomData;
258
259             $(#[allow(bad_style)]
260             pub struct $name<$tcx> {
261                 data: PhantomData<&$tcx ()>
262             })*
263         }
264
265         $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
266             type Key = $K;
267             type Value = $V;
268
269             #[allow(unused)]
270             fn to_dep_node(key: &$K) -> DepNode<DefId> {
271                 use dep_graph::DepNode::*;
272
273                 $node(*key)
274             }
275         }
276         impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
277             fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
278                                   mut span: Span,
279                                   key: $K,
280                                   f: F)
281                                   -> Result<R, CycleError<'a, $tcx>>
282                 where F: FnOnce(&$V) -> R
283             {
284                 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
285                     return Ok(f(result));
286                 }
287
288                 // FIXME(eddyb) Get more valid Span's on queries.
289                 if span == DUMMY_SP {
290                     span = key.default_span(tcx);
291                 }
292
293                 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
294
295                 let result = tcx.cycle_check(span, Query::$name(key), || {
296                     let provider = tcx.maps.providers[key.map_crate()].$name;
297                     provider(tcx.global_tcx(), key)
298                 })?;
299
300                 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
301             }
302
303             pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
304                            -> Result<$V, CycleError<'a, $tcx>> {
305                 Self::try_get_with(tcx, span, key, Clone::clone)
306             }
307
308             $(#[$attr])*
309             pub fn get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) -> $V {
310                 Self::try_get(tcx, span, key).unwrap_or_else(|e| {
311                     tcx.report_cycle(e);
312                     Value::from_cycle_error(tcx.global_tcx())
313                 })
314             }
315
316             pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
317                 // FIXME(eddyb) Move away from using `DepTrackingMap`
318                 // so we don't have to explicitly ignore a false edge:
319                 // we can't observe a value dependency, only side-effects,
320                 // through `force`, and once everything has been updated,
321                 // perhaps only diagnostics, if those, will remain.
322                 let _ignore = tcx.dep_graph.in_ignore();
323                 match Self::try_get_with(tcx, span, key, |_| ()) {
324                     Ok(()) => {}
325                     Err(e) => tcx.report_cycle(e)
326                 }
327             }
328         })*
329
330         pub struct Providers<$tcx> {
331             $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
332         }
333
334         impl<$tcx> Copy for Providers<$tcx> {}
335         impl<$tcx> Clone for Providers<$tcx> {
336             fn clone(&self) -> Self { *self }
337         }
338
339         impl<$tcx> Default for Providers<$tcx> {
340             fn default() -> Self {
341                 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
342                     bug!("tcx.maps.{}({:?}) unsupported by its crate",
343                          stringify!($name), key);
344                 })*
345                 Providers { $($name),* }
346             }
347         }
348     }
349 }
350
351 // Each of these maps also corresponds to a method on a
352 // `Provider` trait for requesting a value of that type,
353 // and a method on `Maps` itself for doing that in a
354 // a way that memoizes and does dep-graph tracking,
355 // wrapping around the actual chain of providers that
356 // the driver creates (using several `rustc_*` crates).
357 define_maps! { <'tcx>
358     /// Records the type of every item.
359     pub ty: ItemSignature(DefId) -> Ty<'tcx>,
360
361     /// Maps from the def-id of an item (trait/struct/enum/fn) to its
362     /// associated generics and predicates.
363     pub generics: ItemSignature(DefId) -> &'tcx ty::Generics,
364     pub predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
365
366     /// Maps from the def-id of a trait to the list of
367     /// super-predicates. This is a subset of the full list of
368     /// predicates. We store these in a separate map because we must
369     /// evaluate them even during type conversion, often before the
370     /// full predicates are available (note that supertraits have
371     /// additional acyclicity requirements).
372     pub super_predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
373
374     /// To avoid cycles within the predicates of a single item we compute
375     /// per-type-parameter predicates for resolving `T::AssocTy`.
376     pub type_param_predicates: TypeParamPredicates((DefId, DefId))
377         -> ty::GenericPredicates<'tcx>,
378
379     pub trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
380     pub adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
381     pub adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
382     pub adt_sized_constraint: SizedConstraint(DefId) -> Ty<'tcx>,
383
384     /// True if this is a foreign item (i.e., linked via `extern { ... }`).
385     pub is_foreign_item: IsForeignItem(DefId) -> bool,
386
387     /// Maps from def-id of a type or region parameter to its
388     /// (inferred) variance.
389     pub variances: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
390
391     /// Maps from an impl/trait def-id to a list of the def-ids of its items
392     pub associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
393
394     /// Maps from a trait item to the trait item "descriptor"
395     pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
396
397     pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
398     pub impl_polarity: ItemSignature(DefId) -> hir::ImplPolarity,
399
400     /// Maps a DefId of a type to a list of its inherent impls.
401     /// Contains implementations of methods that are inherent to a type.
402     /// Methods in these implementations don't need to be exported.
403     pub inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
404
405     /// Maps from the def-id of a function/method or const/static
406     /// to its MIR. Mutation is done at an item granularity to
407     /// allow MIR optimization passes to function and still
408     /// access cross-crate MIR (e.g. inlining or const eval).
409     ///
410     /// Note that cross-crate MIR appears to be always borrowed
411     /// (in the `RefCell` sense) to prevent accidental mutation.
412     pub mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
413
414     /// Maps DefId's that have an associated Mir to the result
415     /// of the MIR qualify_consts pass. The actual meaning of
416     /// the value isn't known except to the pass itself.
417     pub mir_const_qualif: Mir(DefId) -> u8,
418
419     /// Records the type of each closure. The def ID is the ID of the
420     /// expression defining the closure.
421     pub closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
422
423     /// Records the type of each closure. The def ID is the ID of the
424     /// expression defining the closure.
425     pub closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
426
427     /// Caches CoerceUnsized kinds for impls on custom types.
428     pub coerce_unsized_info: ItemSignature(DefId)
429         -> ty::adjustment::CoerceUnsizedInfo,
430
431     pub typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
432
433     pub typeck_tables: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
434
435     pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
436
437     pub borrowck: BorrowCheck(DefId) -> (),
438
439     /// Gets a complete map from all types to their inherent impls.
440     /// Not meant to be used directly outside of coherence.
441     /// (Defined only for LOCAL_CRATE)
442     pub crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
443
444     /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
445     /// Not meant to be used directly outside of coherence.
446     /// (Defined only for LOCAL_CRATE)
447     pub crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
448
449     /// Results of evaluating monomorphic constants embedded in
450     /// other items, such as enum variant explicit discriminants.
451     pub monomorphic_const_eval: MonomorphicConstEval(DefId) -> const_val::EvalResult<'tcx>,
452
453     /// Performs the privacy check and computes "access levels".
454     pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
455
456     pub reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
457
458     pub mir_shims: mir_shim(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>
459 }
460
461 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
462     DepNode::CoherenceCheckTrait(def_id)
463 }
464
465 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
466     DepNode::Coherence
467 }
468
469 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
470     DepNode::Reachability
471 }
472
473 fn mir_shim(instance: ty::InstanceDef) -> DepNode<DefId> {
474     instance.dep_node()
475 }
476
477 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
478     DepNode::TypeckBodiesKrate
479 }