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, 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::coherent_inherent_impls<'tcx> {
181 fn describe(_: TyCtxt, _: CrateNum) -> String {
182 format!("coherence checking all inherent impls")
186 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
187 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
188 format!("generating MIR shim for `{}`",
189 tcx.item_path_str(def.def_id()))
193 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
194 fn describe(_: TyCtxt, _: CrateNum) -> String {
195 format!("privacy access levels")
199 macro_rules! define_maps {
202 pub $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
203 pub struct Maps<$tcx> {
204 providers: IndexVec<CrateNum, Providers<$tcx>>,
205 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
206 $($(#[$attr])* pub $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
209 impl<$tcx> Maps<$tcx> {
210 pub fn new(dep_graph: DepGraph,
211 providers: IndexVec<CrateNum, Providers<$tcx>>)
215 query_stack: RefCell::new(vec![]),
216 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
222 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
223 pub enum Query<$tcx> {
224 $($(#[$attr])* $name($K)),*
227 impl<$tcx> Query<$tcx> {
228 pub fn describe(&self, tcx: TyCtxt) -> String {
230 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
236 use std::marker::PhantomData;
238 $(#[allow(bad_style)]
239 pub struct $name<$tcx> {
240 data: PhantomData<&$tcx ()>
244 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
249 fn to_dep_node(key: &$K) -> DepNode<DefId> {
250 use dep_graph::DepNode::*;
255 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
256 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
260 -> Result<R, CycleError<'a, $tcx>>
261 where F: FnOnce(&$V) -> R
263 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
264 return Ok(f(result));
267 // FIXME(eddyb) Get more valid Span's on queries.
268 if span == DUMMY_SP {
269 span = key.default_span(tcx);
272 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
274 let result = tcx.cycle_check(span, Query::$name(key), || {
275 let provider = tcx.maps.providers[key.map_crate()].$name;
276 provider(tcx.global_tcx(), key)
279 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
282 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
283 -> Result<$V, CycleError<'a, $tcx>> {
284 Self::try_get_with(tcx, span, key, Clone::clone)
288 pub fn get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) -> $V {
289 Self::try_get(tcx, span, key).unwrap_or_else(|e| {
291 Value::from_cycle_error(tcx.global_tcx())
295 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
296 // FIXME(eddyb) Move away from using `DepTrackingMap`
297 // so we don't have to explicitly ignore a false edge:
298 // we can't observe a value dependency, only side-effects,
299 // through `force`, and once everything has been updated,
300 // perhaps only diagnostics, if those, will remain.
301 let _ignore = tcx.dep_graph.in_ignore();
302 match Self::try_get_with(tcx, span, key, |_| ()) {
304 Err(e) => tcx.report_cycle(e)
309 pub struct Providers<$tcx> {
310 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
313 impl<$tcx> Copy for Providers<$tcx> {}
314 impl<$tcx> Clone for Providers<$tcx> {
315 fn clone(&self) -> Self { *self }
318 impl<$tcx> Default for Providers<$tcx> {
319 fn default() -> Self {
320 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
321 bug!("tcx.maps.{}({:?}) unsupported by its crate",
322 stringify!($name), key);
324 Providers { $($name),* }
330 // Each of these maps also corresponds to a method on a
331 // `Provider` trait for requesting a value of that type,
332 // and a method on `Maps` itself for doing that in a
333 // a way that memoizes and does dep-graph tracking,
334 // wrapping around the actual chain of providers that
335 // the driver creates (using several `rustc_*` crates).
336 define_maps! { <'tcx>
337 /// Records the type of every item.
338 pub ty: ItemSignature(DefId) -> Ty<'tcx>,
340 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
341 /// associated generics and predicates.
342 pub generics: ItemSignature(DefId) -> &'tcx ty::Generics,
343 pub predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
345 /// Maps from the def-id of a trait to the list of
346 /// super-predicates. This is a subset of the full list of
347 /// predicates. We store these in a separate map because we must
348 /// evaluate them even during type conversion, often before the
349 /// full predicates are available (note that supertraits have
350 /// additional acyclicity requirements).
351 pub super_predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
353 /// To avoid cycles within the predicates of a single item we compute
354 /// per-type-parameter predicates for resolving `T::AssocTy`.
355 pub type_param_predicates: TypeParamPredicates((DefId, DefId))
356 -> ty::GenericPredicates<'tcx>,
358 pub trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
359 pub adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
360 pub adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
361 pub adt_sized_constraint: SizedConstraint(DefId) -> Ty<'tcx>,
363 /// Maps from def-id of a type or region parameter to its
364 /// (inferred) variance.
365 pub variances: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
367 /// Maps from an impl/trait def-id to a list of the def-ids of its items
368 pub associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
370 /// Maps from a trait item to the trait item "descriptor"
371 pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
373 pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
375 /// Maps a DefId of a type to a list of its inherent impls.
376 /// Contains implementations of methods that are inherent to a type.
377 /// Methods in these implementations don't need to be exported.
378 pub inherent_impls: InherentImpls(DefId) -> Vec<DefId>,
380 /// Maps from the def-id of a function/method or const/static
381 /// to its MIR. Mutation is done at an item granularity to
382 /// allow MIR optimization passes to function and still
383 /// access cross-crate MIR (e.g. inlining or const eval).
385 /// Note that cross-crate MIR appears to be always borrowed
386 /// (in the `RefCell` sense) to prevent accidental mutation.
387 pub mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
389 /// Maps DefId's that have an associated Mir to the result
390 /// of the MIR qualify_consts pass. The actual meaning of
391 /// the value isn't known except to the pass itself.
392 pub mir_const_qualif: Mir(DefId) -> u8,
394 /// Records the type of each closure. The def ID is the ID of the
395 /// expression defining the closure.
396 pub closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
398 /// Records the type of each closure. The def ID is the ID of the
399 /// expression defining the closure.
400 pub closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
402 /// Caches CoerceUnsized kinds for impls on custom types.
403 pub custom_coerce_unsized_kind: ItemSignature(DefId)
404 -> ty::adjustment::CustomCoerceUnsized,
406 pub typeck_tables: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
408 pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
410 pub coherent_inherent_impls: coherent_inherent_impls_dep_node(CrateNum) -> (),
412 /// Results of evaluating monomorphic constants embedded in
413 /// other items, such as enum variant explicit discriminants.
414 pub monomorphic_const_eval: MonomorphicConstEval(DefId) -> Result<ConstVal<'tcx>, ()>,
416 /// Performs the privacy check and computes "access levels".
417 pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
419 pub mir_shims: mir_shim(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>
422 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
423 DepNode::CoherenceCheckTrait(def_id)
426 fn coherent_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
430 fn mir_shim(instance: ty::InstanceDef) -> DepNode<DefId> {