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 session::CompileResult;
17 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
18 use util::nodemap::NodeSet;
20 use rustc_data_structures::indexed_vec::IndexVec;
21 use std::cell::{RefCell, RefMut};
23 use syntax_pos::{Span, DUMMY_SP};
26 fn map_crate(&self) -> CrateNum;
27 fn default_span(&self, tcx: TyCtxt) -> Span;
30 impl<'tcx> Key for ty::InstanceDef<'tcx> {
31 fn map_crate(&self) -> CrateNum {
35 fn default_span(&self, tcx: TyCtxt) -> Span {
36 tcx.def_span(self.def_id())
40 impl Key for CrateNum {
41 fn map_crate(&self) -> CrateNum {
44 fn default_span(&self, _: TyCtxt) -> Span {
50 fn map_crate(&self) -> CrateNum {
53 fn default_span(&self, tcx: TyCtxt) -> Span {
58 impl Key for (DefId, DefId) {
59 fn map_crate(&self) -> CrateNum {
62 fn default_span(&self, tcx: TyCtxt) -> Span {
63 self.1.default_span(tcx)
67 impl Key for (CrateNum, DefId) {
68 fn map_crate(&self) -> CrateNum {
71 fn default_span(&self, tcx: TyCtxt) -> Span {
72 self.1.default_span(tcx)
76 trait Value<'tcx>: Sized {
77 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
80 impl<'tcx, T> Value<'tcx> for T {
81 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
82 tcx.sess.abort_if_errors();
83 bug!("Value::from_cycle_error called without errors");
87 impl<'tcx, T: Default> Value<'tcx> for T {
88 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
93 impl<'tcx> Value<'tcx> for Ty<'tcx> {
94 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
99 pub struct CycleError<'a, 'tcx: 'a> {
101 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
104 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
105 pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
106 assert!(!cycle.is_empty());
108 let mut err = struct_span_err!(self.sess, span, E0391,
109 "unsupported cyclic reference between types/traits detected");
110 err.span_label(span, &format!("cyclic reference"));
112 err.span_note(cycle[0].0, &format!("the cycle begins when {}...",
113 cycle[0].1.describe(self)));
115 for &(span, ref query) in &cycle[1..] {
116 err.span_note(span, &format!("...which then requires {}...",
117 query.describe(self)));
120 err.note(&format!("...which then again requires {}, completing the cycle.",
121 cycle[0].1.describe(self)));
126 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
127 -> Result<R, CycleError<'a, 'gcx>>
128 where F: FnOnce() -> R
131 let mut stack = self.maps.query_stack.borrow_mut();
132 if let Some((i, _)) = stack.iter().enumerate().rev()
133 .find(|&(_, &(_, ref q))| *q == query) {
134 return Err(CycleError {
136 cycle: RefMut::map(stack, |stack| &mut stack[i..])
139 stack.push((span, query));
142 let result = compute();
144 self.maps.query_stack.borrow_mut().pop();
150 trait QueryDescription: DepTrackingMapConfig {
151 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
154 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
155 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
156 format!("processing `{}`", tcx.item_path_str(def_id))
160 impl<'tcx> QueryDescription for queries::super_predicates<'tcx> {
161 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
162 format!("computing the supertraits of `{}`",
163 tcx.item_path_str(def_id))
167 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
168 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
169 let id = tcx.hir.as_local_node_id(def_id).unwrap();
170 format!("computing the bounds for type parameter `{}`",
171 tcx.hir.ty_param_name(id))
175 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
176 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
177 format!("coherence checking all impls of trait `{}`",
178 tcx.item_path_str(def_id))
182 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
183 fn describe(_: TyCtxt, k: CrateNum) -> String {
184 format!("all inherent impls defined in crate `{:?}`", k)
188 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
189 fn describe(_: TyCtxt, _: CrateNum) -> String {
190 format!("check for overlap between inherent impls defined in this crate")
194 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
195 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
196 format!("generating MIR shim for `{}`",
197 tcx.item_path_str(def.def_id()))
201 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
202 fn describe(_: TyCtxt, _: CrateNum) -> String {
203 format!("privacy access levels")
207 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
208 fn describe(_: TyCtxt, _: CrateNum) -> String {
209 format!("type-checking all item bodies")
213 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
214 fn describe(_: TyCtxt, _: CrateNum) -> String {
215 format!("reachability")
219 macro_rules! define_maps {
222 pub $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
223 pub struct Maps<$tcx> {
224 providers: IndexVec<CrateNum, Providers<$tcx>>,
225 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
226 $($(#[$attr])* pub $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
229 impl<$tcx> Maps<$tcx> {
230 pub fn new(dep_graph: DepGraph,
231 providers: IndexVec<CrateNum, Providers<$tcx>>)
235 query_stack: RefCell::new(vec![]),
236 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
242 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
243 pub enum Query<$tcx> {
244 $($(#[$attr])* $name($K)),*
247 impl<$tcx> Query<$tcx> {
248 pub fn describe(&self, tcx: TyCtxt) -> String {
250 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
256 use std::marker::PhantomData;
258 $(#[allow(bad_style)]
259 pub struct $name<$tcx> {
260 data: PhantomData<&$tcx ()>
264 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
269 fn to_dep_node(key: &$K) -> DepNode<DefId> {
270 use dep_graph::DepNode::*;
275 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
276 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
280 -> Result<R, CycleError<'a, $tcx>>
281 where F: FnOnce(&$V) -> R
283 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
284 return Ok(f(result));
287 // FIXME(eddyb) Get more valid Span's on queries.
288 if span == DUMMY_SP {
289 span = key.default_span(tcx);
292 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
294 let result = tcx.cycle_check(span, Query::$name(key), || {
295 let provider = tcx.maps.providers[key.map_crate()].$name;
296 provider(tcx.global_tcx(), key)
299 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
302 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
303 -> Result<$V, CycleError<'a, $tcx>> {
304 Self::try_get_with(tcx, span, key, Clone::clone)
308 pub fn get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) -> $V {
309 Self::try_get(tcx, span, key).unwrap_or_else(|e| {
311 Value::from_cycle_error(tcx.global_tcx())
315 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
316 // FIXME(eddyb) Move away from using `DepTrackingMap`
317 // so we don't have to explicitly ignore a false edge:
318 // we can't observe a value dependency, only side-effects,
319 // through `force`, and once everything has been updated,
320 // perhaps only diagnostics, if those, will remain.
321 let _ignore = tcx.dep_graph.in_ignore();
322 match Self::try_get_with(tcx, span, key, |_| ()) {
324 Err(e) => tcx.report_cycle(e)
329 pub struct Providers<$tcx> {
330 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
333 impl<$tcx> Copy for Providers<$tcx> {}
334 impl<$tcx> Clone for Providers<$tcx> {
335 fn clone(&self) -> Self { *self }
338 impl<$tcx> Default for Providers<$tcx> {
339 fn default() -> Self {
340 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
341 bug!("tcx.maps.{}({:?}) unsupported by its crate",
342 stringify!($name), key);
344 Providers { $($name),* }
350 // Each of these maps also corresponds to a method on a
351 // `Provider` trait for requesting a value of that type,
352 // and a method on `Maps` itself for doing that in a
353 // a way that memoizes and does dep-graph tracking,
354 // wrapping around the actual chain of providers that
355 // the driver creates (using several `rustc_*` crates).
356 define_maps! { <'tcx>
357 /// Records the type of every item.
358 pub ty: ItemSignature(DefId) -> Ty<'tcx>,
360 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
361 /// associated generics and predicates.
362 pub generics: ItemSignature(DefId) -> &'tcx ty::Generics,
363 pub predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
365 /// Maps from the def-id of a trait to the list of
366 /// super-predicates. This is a subset of the full list of
367 /// predicates. We store these in a separate map because we must
368 /// evaluate them even during type conversion, often before the
369 /// full predicates are available (note that supertraits have
370 /// additional acyclicity requirements).
371 pub super_predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
373 /// To avoid cycles within the predicates of a single item we compute
374 /// per-type-parameter predicates for resolving `T::AssocTy`.
375 pub type_param_predicates: TypeParamPredicates((DefId, DefId))
376 -> ty::GenericPredicates<'tcx>,
378 pub trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
379 pub adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
380 pub adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
381 pub adt_sized_constraint: SizedConstraint(DefId) -> Ty<'tcx>,
383 /// Maps from def-id of a type or region parameter to its
384 /// (inferred) variance.
385 pub variances: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
387 /// Maps from an impl/trait def-id to a list of the def-ids of its items
388 pub associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
390 /// Maps from a trait item to the trait item "descriptor"
391 pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
393 pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
395 /// Maps a DefId of a type to a list of its inherent impls.
396 /// Contains implementations of methods that are inherent to a type.
397 /// Methods in these implementations don't need to be exported.
398 pub inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
400 /// Maps from the def-id of a function/method or const/static
401 /// to its MIR. Mutation is done at an item granularity to
402 /// allow MIR optimization passes to function and still
403 /// access cross-crate MIR (e.g. inlining or const eval).
405 /// Note that cross-crate MIR appears to be always borrowed
406 /// (in the `RefCell` sense) to prevent accidental mutation.
407 pub mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
409 /// Maps DefId's that have an associated Mir to the result
410 /// of the MIR qualify_consts pass. The actual meaning of
411 /// the value isn't known except to the pass itself.
412 pub mir_const_qualif: Mir(DefId) -> u8,
414 /// Records the type of each closure. The def ID is the ID of the
415 /// expression defining the closure.
416 pub closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
418 /// Records the type of each closure. The def ID is the ID of the
419 /// expression defining the closure.
420 pub closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
422 /// Caches CoerceUnsized kinds for impls on custom types.
423 pub coerce_unsized_info: ItemSignature(DefId)
424 -> ty::adjustment::CoerceUnsizedInfo,
426 pub typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
428 pub typeck_tables: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
430 pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
432 /// Gets a complete map from all types to their inherent impls.
433 /// Not meant to be used directly outside of coherence.
434 /// (Defined only for LOCAL_CRATE)
435 pub crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
437 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
438 /// Not meant to be used directly outside of coherence.
439 /// (Defined only for LOCAL_CRATE)
440 pub crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
442 /// Results of evaluating monomorphic constants embedded in
443 /// other items, such as enum variant explicit discriminants.
444 pub monomorphic_const_eval: MonomorphicConstEval(DefId) -> Result<ConstVal<'tcx>, ()>,
446 /// Performs the privacy check and computes "access levels".
447 pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
449 pub reachable_set: reachability_dep_node(CrateNum) -> NodeSet,
451 pub mir_shims: mir_shim(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>
454 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
455 DepNode::CoherenceCheckTrait(def_id)
458 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
462 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
463 DepNode::Reachability
466 fn mir_shim(instance: ty::InstanceDef) -> DepNode<DefId> {
470 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
471 DepNode::TypeckBodiesKrate