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.
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.
11 use dep_graph::{DepGraph, DepNode, DepTrackingMap, DepTrackingMapConfig};
12 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
13 use middle::const_val::ConstVal;
14 use middle::privacy::AccessLevels;
16 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
18 use rustc_data_structures::indexed_vec::IndexVec;
19 use std::cell::{RefCell, RefMut};
21 use syntax_pos::{Span, DUMMY_SP};
24 fn map_crate(&self) -> CrateNum;
25 fn default_span(&self, tcx: TyCtxt) -> Span;
28 impl<'tcx> Key for ty::InstanceDef<'tcx> {
29 fn map_crate(&self) -> CrateNum {
33 fn default_span(&self, tcx: TyCtxt) -> Span {
34 tcx.def_span(self.def_id())
38 impl Key for CrateNum {
39 fn map_crate(&self) -> CrateNum {
42 fn default_span(&self, _: TyCtxt) -> Span {
48 fn map_crate(&self) -> CrateNum {
51 fn default_span(&self, tcx: TyCtxt) -> Span {
56 impl Key for (DefId, DefId) {
57 fn map_crate(&self) -> CrateNum {
60 fn default_span(&self, tcx: TyCtxt) -> Span {
61 self.1.default_span(tcx)
65 impl Key for (CrateNum, DefId) {
66 fn map_crate(&self) -> CrateNum {
69 fn default_span(&self, tcx: TyCtxt) -> Span {
70 self.1.default_span(tcx)
74 trait Value<'tcx>: Sized {
75 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
78 impl<'tcx, T> Value<'tcx> for T {
79 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
80 tcx.sess.abort_if_errors();
81 bug!("Value::from_cycle_error called without errors");
85 impl<'tcx, T: Default> Value<'tcx> for T {
86 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
91 impl<'tcx> Value<'tcx> for Ty<'tcx> {
92 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
97 pub struct CycleError<'a, 'tcx: 'a> {
99 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
102 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
103 pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
104 assert!(!cycle.is_empty());
106 let mut err = struct_span_err!(self.sess, span, E0391,
107 "unsupported cyclic reference between types/traits detected");
108 err.span_label(span, &format!("cyclic reference"));
110 err.span_note(cycle[0].0, &format!("the cycle begins when {}...",
111 cycle[0].1.describe(self)));
113 for &(span, ref query) in &cycle[1..] {
114 err.span_note(span, &format!("...which then requires {}...",
115 query.describe(self)));
118 err.note(&format!("...which then again requires {}, completing the cycle.",
119 cycle[0].1.describe(self)));
124 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
125 -> Result<R, CycleError<'a, 'gcx>>
126 where F: FnOnce() -> R
129 let mut stack = self.maps.query_stack.borrow_mut();
130 if let Some((i, _)) = stack.iter().enumerate().rev()
131 .find(|&(_, &(_, ref q))| *q == query) {
132 return Err(CycleError {
134 cycle: RefMut::map(stack, |stack| &mut stack[i..])
137 stack.push((span, query));
140 let result = compute();
142 self.maps.query_stack.borrow_mut().pop();
148 trait QueryDescription: DepTrackingMapConfig {
149 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
152 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
153 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
154 format!("processing `{}`", tcx.item_path_str(def_id))
158 impl<'tcx> QueryDescription for queries::super_predicates<'tcx> {
159 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
160 format!("computing the supertraits of `{}`",
161 tcx.item_path_str(def_id))
165 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
166 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
167 let id = tcx.hir.as_local_node_id(def_id).unwrap();
168 format!("computing the bounds for type parameter `{}`",
169 tcx.hir.ty_param_name(id))
173 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
174 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
175 format!("coherence checking all impls of trait `{}`",
176 tcx.item_path_str(def_id))
180 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
181 fn describe(_: TyCtxt, k: CrateNum) -> String {
182 format!("all inherent impls defined in crate `{:?}`", k)
186 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
187 fn describe(_: TyCtxt, _: CrateNum) -> String {
188 format!("check for overlap between inherent impls defined in this crate")
192 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
193 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
194 format!("generating MIR shim for `{}`",
195 tcx.item_path_str(def.def_id()))
199 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
200 fn describe(_: TyCtxt, _: CrateNum) -> String {
201 format!("privacy access levels")
205 macro_rules! define_maps {
208 pub $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
209 pub struct Maps<$tcx> {
210 providers: IndexVec<CrateNum, Providers<$tcx>>,
211 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
212 $($(#[$attr])* pub $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
215 impl<$tcx> Maps<$tcx> {
216 pub fn new(dep_graph: DepGraph,
217 providers: IndexVec<CrateNum, Providers<$tcx>>)
221 query_stack: RefCell::new(vec![]),
222 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
228 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
229 pub enum Query<$tcx> {
230 $($(#[$attr])* $name($K)),*
233 impl<$tcx> Query<$tcx> {
234 pub fn describe(&self, tcx: TyCtxt) -> String {
236 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
242 use std::marker::PhantomData;
244 $(#[allow(bad_style)]
245 pub struct $name<$tcx> {
246 data: PhantomData<&$tcx ()>
250 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
255 fn to_dep_node(key: &$K) -> DepNode<DefId> {
256 use dep_graph::DepNode::*;
261 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
262 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
266 -> Result<R, CycleError<'a, $tcx>>
267 where F: FnOnce(&$V) -> R
269 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
270 return Ok(f(result));
273 // FIXME(eddyb) Get more valid Span's on queries.
274 if span == DUMMY_SP {
275 span = key.default_span(tcx);
278 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
280 let result = tcx.cycle_check(span, Query::$name(key), || {
281 let provider = tcx.maps.providers[key.map_crate()].$name;
282 provider(tcx.global_tcx(), key)
285 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
288 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
289 -> Result<$V, CycleError<'a, $tcx>> {
290 Self::try_get_with(tcx, span, key, Clone::clone)
294 pub fn get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) -> $V {
295 Self::try_get(tcx, span, key).unwrap_or_else(|e| {
297 Value::from_cycle_error(tcx.global_tcx())
301 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
302 // FIXME(eddyb) Move away from using `DepTrackingMap`
303 // so we don't have to explicitly ignore a false edge:
304 // we can't observe a value dependency, only side-effects,
305 // through `force`, and once everything has been updated,
306 // perhaps only diagnostics, if those, will remain.
307 let _ignore = tcx.dep_graph.in_ignore();
308 match Self::try_get_with(tcx, span, key, |_| ()) {
310 Err(e) => tcx.report_cycle(e)
315 pub struct Providers<$tcx> {
316 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
319 impl<$tcx> Copy for Providers<$tcx> {}
320 impl<$tcx> Clone for Providers<$tcx> {
321 fn clone(&self) -> Self { *self }
324 impl<$tcx> Default for Providers<$tcx> {
325 fn default() -> Self {
326 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
327 bug!("tcx.maps.{}({:?}) unsupported by its crate",
328 stringify!($name), key);
330 Providers { $($name),* }
336 // Each of these maps also corresponds to a method on a
337 // `Provider` trait for requesting a value of that type,
338 // and a method on `Maps` itself for doing that in a
339 // a way that memoizes and does dep-graph tracking,
340 // wrapping around the actual chain of providers that
341 // the driver creates (using several `rustc_*` crates).
342 define_maps! { <'tcx>
343 /// Records the type of every item.
344 pub ty: ItemSignature(DefId) -> Ty<'tcx>,
346 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
347 /// associated generics and predicates.
348 pub generics: ItemSignature(DefId) -> &'tcx ty::Generics,
349 pub predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
351 /// Maps from the def-id of a trait to the list of
352 /// super-predicates. This is a subset of the full list of
353 /// predicates. We store these in a separate map because we must
354 /// evaluate them even during type conversion, often before the
355 /// full predicates are available (note that supertraits have
356 /// additional acyclicity requirements).
357 pub super_predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
359 /// To avoid cycles within the predicates of a single item we compute
360 /// per-type-parameter predicates for resolving `T::AssocTy`.
361 pub type_param_predicates: TypeParamPredicates((DefId, DefId))
362 -> ty::GenericPredicates<'tcx>,
364 pub trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
365 pub adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
366 pub adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
367 pub adt_sized_constraint: SizedConstraint(DefId) -> Ty<'tcx>,
369 /// Maps from def-id of a type or region parameter to its
370 /// (inferred) variance.
371 pub variances: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
373 /// Maps from an impl/trait def-id to a list of the def-ids of its items
374 pub associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
376 /// Maps from a trait item to the trait item "descriptor"
377 pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
379 pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
381 /// Maps a DefId of a type to a list of its inherent impls.
382 /// Contains implementations of methods that are inherent to a type.
383 /// Methods in these implementations don't need to be exported.
384 pub inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
386 /// Maps from the def-id of a function/method or const/static
387 /// to its MIR. Mutation is done at an item granularity to
388 /// allow MIR optimization passes to function and still
389 /// access cross-crate MIR (e.g. inlining or const eval).
391 /// Note that cross-crate MIR appears to be always borrowed
392 /// (in the `RefCell` sense) to prevent accidental mutation.
393 pub mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
395 /// Maps DefId's that have an associated Mir to the result
396 /// of the MIR qualify_consts pass. The actual meaning of
397 /// the value isn't known except to the pass itself.
398 pub mir_const_qualif: Mir(DefId) -> u8,
400 /// Records the type of each closure. The def ID is the ID of the
401 /// expression defining the closure.
402 pub closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
404 /// Records the type of each closure. The def ID is the ID of the
405 /// expression defining the closure.
406 pub closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
408 /// Caches CoerceUnsized kinds for impls on custom types.
409 pub coerce_unsized_info: ItemSignature(DefId)
410 -> ty::adjustment::CoerceUnsizedInfo,
412 pub typeck_tables: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
414 pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
416 /// Gets a complete map from all types to their inherent impls.
417 /// Not meant to be used directly outside of coherence.
418 /// (Defined only for LOCAL_CRATE)
419 pub crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
421 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
422 /// Not meant to be used directly outside of coherence.
423 /// (Defined only for LOCAL_CRATE)
424 pub crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
426 /// Results of evaluating monomorphic constants embedded in
427 /// other items, such as enum variant explicit discriminants.
428 pub monomorphic_const_eval: MonomorphicConstEval(DefId) -> Result<ConstVal<'tcx>, ()>,
430 /// Performs the privacy check and computes "access levels".
431 pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
433 pub mir_shims: mir_shim(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>
436 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
437 DepNode::CoherenceCheckTrait(def_id)
440 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
444 fn mir_shim(instance: ty::InstanceDef) -> DepNode<DefId> {