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};
14 use middle::const_val;
15 use middle::privacy::AccessLevels;
17 use session::CompileResult;
18 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
19 use util::nodemap::NodeSet;
21 use rustc_data_structures::indexed_vec::IndexVec;
22 use std::cell::{RefCell, RefMut};
24 use syntax_pos::{Span, DUMMY_SP};
27 fn map_crate(&self) -> CrateNum;
28 fn default_span(&self, tcx: TyCtxt) -> Span;
31 impl<'tcx> Key for ty::InstanceDef<'tcx> {
32 fn map_crate(&self) -> CrateNum {
36 fn default_span(&self, tcx: TyCtxt) -> Span {
37 tcx.def_span(self.def_id())
41 impl Key for CrateNum {
42 fn map_crate(&self) -> CrateNum {
45 fn default_span(&self, _: TyCtxt) -> Span {
51 fn map_crate(&self) -> CrateNum {
54 fn default_span(&self, tcx: TyCtxt) -> Span {
59 impl Key for (DefId, DefId) {
60 fn map_crate(&self) -> CrateNum {
63 fn default_span(&self, tcx: TyCtxt) -> Span {
64 self.1.default_span(tcx)
68 impl Key for (CrateNum, DefId) {
69 fn map_crate(&self) -> CrateNum {
72 fn default_span(&self, tcx: TyCtxt) -> Span {
73 self.1.default_span(tcx)
77 trait Value<'tcx>: Sized {
78 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
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");
88 impl<'tcx, T: Default> Value<'tcx> for T {
89 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
94 impl<'tcx> Value<'tcx> for Ty<'tcx> {
95 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
100 pub struct CycleError<'a, 'tcx: 'a> {
102 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
105 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
106 pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
107 assert!(!cycle.is_empty());
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"));
113 err.span_note(cycle[0].0, &format!("the cycle begins when {}...",
114 cycle[0].1.describe(self)));
116 for &(span, ref query) in &cycle[1..] {
117 err.span_note(span, &format!("...which then requires {}...",
118 query.describe(self)));
121 err.note(&format!("...which then again requires {}, completing the cycle.",
122 cycle[0].1.describe(self)));
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
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 {
137 cycle: RefMut::map(stack, |stack| &mut stack[i..])
140 stack.push((span, query));
143 let result = compute();
145 self.maps.query_stack.borrow_mut().pop();
151 trait QueryDescription: DepTrackingMapConfig {
152 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
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))
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))
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))
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))
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)
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")
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()))
202 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
203 fn describe(_: TyCtxt, _: CrateNum) -> String {
204 format!("privacy access levels")
208 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
209 fn describe(_: TyCtxt, _: CrateNum) -> String {
210 format!("type-checking all item bodies")
214 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
215 fn describe(_: TyCtxt, _: CrateNum) -> String {
216 format!("reachability")
220 macro_rules! define_maps {
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>>>),*
230 impl<$tcx> Maps<$tcx> {
231 pub fn new(dep_graph: DepGraph,
232 providers: IndexVec<CrateNum, Providers<$tcx>>)
236 query_stack: RefCell::new(vec![]),
237 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
243 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
244 pub enum Query<$tcx> {
245 $($(#[$attr])* $name($K)),*
248 impl<$tcx> Query<$tcx> {
249 pub fn describe(&self, tcx: TyCtxt) -> String {
251 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
257 use std::marker::PhantomData;
259 $(#[allow(bad_style)]
260 pub struct $name<$tcx> {
261 data: PhantomData<&$tcx ()>
265 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
270 fn to_dep_node(key: &$K) -> DepNode<DefId> {
271 use dep_graph::DepNode::*;
276 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
277 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
281 -> Result<R, CycleError<'a, $tcx>>
282 where F: FnOnce(&$V) -> R
284 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
285 return Ok(f(result));
288 // FIXME(eddyb) Get more valid Span's on queries.
289 if span == DUMMY_SP {
290 span = key.default_span(tcx);
293 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
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)
300 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
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)
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| {
312 Value::from_cycle_error(tcx.global_tcx())
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, |_| ()) {
325 Err(e) => tcx.report_cycle(e)
330 pub struct Providers<$tcx> {
331 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
334 impl<$tcx> Copy for Providers<$tcx> {}
335 impl<$tcx> Clone for Providers<$tcx> {
336 fn clone(&self) -> Self { *self }
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);
345 Providers { $($name),* }
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>,
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>,
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>,
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>,
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>,
384 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
385 pub is_foreign_item: IsForeignItem(DefId) -> bool,
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>>,
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>>,
394 /// Maps from a trait item to the trait item "descriptor"
395 pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
397 pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
398 pub impl_polarity: ItemSignature(DefId) -> hir::ImplPolarity,
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>>,
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).
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>>,
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,
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,
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>,
427 /// Caches CoerceUnsized kinds for impls on custom types.
428 pub coerce_unsized_info: ItemSignature(DefId)
429 -> ty::adjustment::CoerceUnsizedInfo,
431 pub typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
433 pub typeck_tables: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
435 pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
437 pub borrowck: BorrowCheck(DefId) -> (),
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,
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) -> (),
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>,
453 /// Performs the privacy check and computes "access levels".
454 pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
456 pub reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
458 pub mir_shims: mir_shim(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>
461 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
462 DepNode::CoherenceCheckTrait(def_id)
465 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
469 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
470 DepNode::Reachability
473 fn mir_shim(instance: ty::InstanceDef) -> DepNode<DefId> {
477 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
478 DepNode::TypeckBodiesKrate