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};
19 use rustc_data_structures::indexed_vec::IndexVec;
20 use std::cell::{RefCell, RefMut};
22 use syntax_pos::{Span, DUMMY_SP};
25 fn map_crate(&self) -> CrateNum;
26 fn default_span(&self, tcx: TyCtxt) -> Span;
29 impl<'tcx> Key for ty::InstanceDef<'tcx> {
30 fn map_crate(&self) -> CrateNum {
34 fn default_span(&self, tcx: TyCtxt) -> Span {
35 tcx.def_span(self.def_id())
39 impl Key for CrateNum {
40 fn map_crate(&self) -> CrateNum {
43 fn default_span(&self, _: TyCtxt) -> Span {
49 fn map_crate(&self) -> CrateNum {
52 fn default_span(&self, tcx: TyCtxt) -> Span {
57 impl Key for (DefId, DefId) {
58 fn map_crate(&self) -> CrateNum {
61 fn default_span(&self, tcx: TyCtxt) -> Span {
62 self.1.default_span(tcx)
66 impl Key for (CrateNum, DefId) {
67 fn map_crate(&self) -> CrateNum {
70 fn default_span(&self, tcx: TyCtxt) -> Span {
71 self.1.default_span(tcx)
75 trait Value<'tcx>: Sized {
76 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
79 impl<'tcx, T> Value<'tcx> for T {
80 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
81 tcx.sess.abort_if_errors();
82 bug!("Value::from_cycle_error called without errors");
86 impl<'tcx, T: Default> Value<'tcx> for T {
87 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
92 impl<'tcx> Value<'tcx> for Ty<'tcx> {
93 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
98 pub struct CycleError<'a, 'tcx: 'a> {
100 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
103 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
104 pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
105 assert!(!cycle.is_empty());
107 let mut err = struct_span_err!(self.sess, span, E0391,
108 "unsupported cyclic reference between types/traits detected");
109 err.span_label(span, &format!("cyclic reference"));
111 err.span_note(cycle[0].0, &format!("the cycle begins when {}...",
112 cycle[0].1.describe(self)));
114 for &(span, ref query) in &cycle[1..] {
115 err.span_note(span, &format!("...which then requires {}...",
116 query.describe(self)));
119 err.note(&format!("...which then again requires {}, completing the cycle.",
120 cycle[0].1.describe(self)));
125 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
126 -> Result<R, CycleError<'a, 'gcx>>
127 where F: FnOnce() -> R
130 let mut stack = self.maps.query_stack.borrow_mut();
131 if let Some((i, _)) = stack.iter().enumerate().rev()
132 .find(|&(_, &(_, ref q))| *q == query) {
133 return Err(CycleError {
135 cycle: RefMut::map(stack, |stack| &mut stack[i..])
138 stack.push((span, query));
141 let result = compute();
143 self.maps.query_stack.borrow_mut().pop();
149 trait QueryDescription: DepTrackingMapConfig {
150 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
153 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
154 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
155 format!("processing `{}`", tcx.item_path_str(def_id))
159 impl<'tcx> QueryDescription for queries::super_predicates<'tcx> {
160 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
161 format!("computing the supertraits of `{}`",
162 tcx.item_path_str(def_id))
166 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
167 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
168 let id = tcx.hir.as_local_node_id(def_id).unwrap();
169 format!("computing the bounds for type parameter `{}`",
170 tcx.hir.ty_param_name(id))
174 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
175 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
176 format!("coherence checking all impls of trait `{}`",
177 tcx.item_path_str(def_id))
181 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
182 fn describe(_: TyCtxt, k: CrateNum) -> String {
183 format!("all inherent impls defined in crate `{:?}`", k)
187 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
188 fn describe(_: TyCtxt, _: CrateNum) -> String {
189 format!("check for overlap between inherent impls defined in this crate")
193 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
194 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
195 format!("generating MIR shim for `{}`",
196 tcx.item_path_str(def.def_id()))
200 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
201 fn describe(_: TyCtxt, _: CrateNum) -> String {
202 format!("privacy access levels")
206 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
207 fn describe(_: TyCtxt, _: CrateNum) -> String {
208 format!("type-checking all item bodies")
213 macro_rules! define_maps {
216 pub $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
217 pub struct Maps<$tcx> {
218 providers: IndexVec<CrateNum, Providers<$tcx>>,
219 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
220 $($(#[$attr])* pub $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
223 impl<$tcx> Maps<$tcx> {
224 pub fn new(dep_graph: DepGraph,
225 providers: IndexVec<CrateNum, Providers<$tcx>>)
229 query_stack: RefCell::new(vec![]),
230 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
236 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
237 pub enum Query<$tcx> {
238 $($(#[$attr])* $name($K)),*
241 impl<$tcx> Query<$tcx> {
242 pub fn describe(&self, tcx: TyCtxt) -> String {
244 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
250 use std::marker::PhantomData;
252 $(#[allow(bad_style)]
253 pub struct $name<$tcx> {
254 data: PhantomData<&$tcx ()>
258 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
263 fn to_dep_node(key: &$K) -> DepNode<DefId> {
264 use dep_graph::DepNode::*;
269 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
270 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
274 -> Result<R, CycleError<'a, $tcx>>
275 where F: FnOnce(&$V) -> R
277 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
278 return Ok(f(result));
281 // FIXME(eddyb) Get more valid Span's on queries.
282 if span == DUMMY_SP {
283 span = key.default_span(tcx);
286 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
288 let result = tcx.cycle_check(span, Query::$name(key), || {
289 let provider = tcx.maps.providers[key.map_crate()].$name;
290 provider(tcx.global_tcx(), key)
293 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
296 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
297 -> Result<$V, CycleError<'a, $tcx>> {
298 Self::try_get_with(tcx, span, key, Clone::clone)
302 pub fn get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) -> $V {
303 Self::try_get(tcx, span, key).unwrap_or_else(|e| {
305 Value::from_cycle_error(tcx.global_tcx())
309 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
310 // FIXME(eddyb) Move away from using `DepTrackingMap`
311 // so we don't have to explicitly ignore a false edge:
312 // we can't observe a value dependency, only side-effects,
313 // through `force`, and once everything has been updated,
314 // perhaps only diagnostics, if those, will remain.
315 let _ignore = tcx.dep_graph.in_ignore();
316 match Self::try_get_with(tcx, span, key, |_| ()) {
318 Err(e) => tcx.report_cycle(e)
323 pub struct Providers<$tcx> {
324 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
327 impl<$tcx> Copy for Providers<$tcx> {}
328 impl<$tcx> Clone for Providers<$tcx> {
329 fn clone(&self) -> Self { *self }
332 impl<$tcx> Default for Providers<$tcx> {
333 fn default() -> Self {
334 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
335 bug!("tcx.maps.{}({:?}) unsupported by its crate",
336 stringify!($name), key);
338 Providers { $($name),* }
344 // Each of these maps also corresponds to a method on a
345 // `Provider` trait for requesting a value of that type,
346 // and a method on `Maps` itself for doing that in a
347 // a way that memoizes and does dep-graph tracking,
348 // wrapping around the actual chain of providers that
349 // the driver creates (using several `rustc_*` crates).
350 define_maps! { <'tcx>
351 /// Records the type of every item.
352 pub ty: ItemSignature(DefId) -> Ty<'tcx>,
354 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
355 /// associated generics and predicates.
356 pub generics: ItemSignature(DefId) -> &'tcx ty::Generics,
357 pub predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
359 /// Maps from the def-id of a trait to the list of
360 /// super-predicates. This is a subset of the full list of
361 /// predicates. We store these in a separate map because we must
362 /// evaluate them even during type conversion, often before the
363 /// full predicates are available (note that supertraits have
364 /// additional acyclicity requirements).
365 pub super_predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
367 /// To avoid cycles within the predicates of a single item we compute
368 /// per-type-parameter predicates for resolving `T::AssocTy`.
369 pub type_param_predicates: TypeParamPredicates((DefId, DefId))
370 -> ty::GenericPredicates<'tcx>,
372 pub trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
373 pub adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
374 pub adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
375 pub adt_sized_constraint: SizedConstraint(DefId) -> Ty<'tcx>,
377 /// Maps from def-id of a type or region parameter to its
378 /// (inferred) variance.
379 pub variances: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
381 /// Maps from an impl/trait def-id to a list of the def-ids of its items
382 pub associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
384 /// Maps from a trait item to the trait item "descriptor"
385 pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
387 pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
389 /// Maps a DefId of a type to a list of its inherent impls.
390 /// Contains implementations of methods that are inherent to a type.
391 /// Methods in these implementations don't need to be exported.
392 pub inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
394 /// Maps from the def-id of a function/method or const/static
395 /// to its MIR. Mutation is done at an item granularity to
396 /// allow MIR optimization passes to function and still
397 /// access cross-crate MIR (e.g. inlining or const eval).
399 /// Note that cross-crate MIR appears to be always borrowed
400 /// (in the `RefCell` sense) to prevent accidental mutation.
401 pub mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
403 /// Maps DefId's that have an associated Mir to the result
404 /// of the MIR qualify_consts pass. The actual meaning of
405 /// the value isn't known except to the pass itself.
406 pub mir_const_qualif: Mir(DefId) -> u8,
408 /// Records the type of each closure. The def ID is the ID of the
409 /// expression defining the closure.
410 pub closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
412 /// Records the type of each closure. The def ID is the ID of the
413 /// expression defining the closure.
414 pub closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
416 /// Caches CoerceUnsized kinds for impls on custom types.
417 pub coerce_unsized_info: ItemSignature(DefId)
418 -> ty::adjustment::CoerceUnsizedInfo,
420 pub typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
422 pub typeck_tables: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
424 pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
426 /// Gets a complete map from all types to their inherent impls.
427 /// Not meant to be used directly outside of coherence.
428 /// (Defined only for LOCAL_CRATE)
429 pub crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
431 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
432 /// Not meant to be used directly outside of coherence.
433 /// (Defined only for LOCAL_CRATE)
434 pub crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
436 /// Results of evaluating monomorphic constants embedded in
437 /// other items, such as enum variant explicit discriminants.
438 pub monomorphic_const_eval: MonomorphicConstEval(DefId) -> Result<ConstVal<'tcx>, ()>,
440 /// Performs the privacy check and computes "access levels".
441 pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
443 pub mir_shims: mir_shim(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>
446 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
447 DepNode::CoherenceCheckTrait(def_id)
450 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
454 fn mir_shim(instance: ty::InstanceDef) -> DepNode<DefId> {
458 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
459 DepNode::TypeckBodiesKrate