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};
13 use middle::const_val::ConstVal;
15 use ty::{self, Ty, TyCtxt};
17 use rustc_data_structures::indexed_vec::IndexVec;
18 use std::cell::{RefCell, RefMut};
20 use syntax_pos::{Span, DUMMY_SP};
23 fn map_crate(&self) -> CrateNum;
24 fn default_span(&self, tcx: TyCtxt) -> Span;
27 impl Key for CrateNum {
28 fn map_crate(&self) -> CrateNum {
31 fn default_span(&self, _: TyCtxt) -> Span {
37 fn map_crate(&self) -> CrateNum {
40 fn default_span(&self, tcx: TyCtxt) -> Span {
45 impl Key for (DefId, DefId) {
46 fn map_crate(&self) -> CrateNum {
49 fn default_span(&self, tcx: TyCtxt) -> Span {
50 self.1.default_span(tcx)
54 impl Key for (CrateNum, DefId) {
55 fn map_crate(&self) -> CrateNum {
58 fn default_span(&self, tcx: TyCtxt) -> Span {
59 self.1.default_span(tcx)
63 trait Value<'tcx>: Sized {
64 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
67 impl<'tcx, T> Value<'tcx> for T {
68 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
69 tcx.sess.abort_if_errors();
70 bug!("Value::from_cycle_error called without errors");
74 impl<'tcx, T: Default> Value<'tcx> for T {
75 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
80 impl<'tcx> Value<'tcx> for Ty<'tcx> {
81 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
86 pub struct CycleError<'a> {
88 cycle: RefMut<'a, [(Span, Query)]>,
91 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
92 pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
93 assert!(!cycle.is_empty());
95 let mut err = struct_span_err!(self.sess, span, E0391,
96 "unsupported cyclic reference between types/traits detected");
97 err.span_label(span, &format!("cyclic reference"));
99 err.span_note(cycle[0].0, &format!("the cycle begins when {}...",
100 cycle[0].1.describe(self)));
102 for &(span, ref query) in &cycle[1..] {
103 err.span_note(span, &format!("...which then requires {}...",
104 query.describe(self)));
107 err.note(&format!("...which then again requires {}, completing the cycle.",
108 cycle[0].1.describe(self)));
113 fn cycle_check<F, R>(self, span: Span, query: Query, compute: F)
114 -> Result<R, CycleError<'a>>
115 where F: FnOnce() -> R
118 let mut stack = self.maps.query_stack.borrow_mut();
119 if let Some((i, _)) = stack.iter().enumerate().rev()
120 .find(|&(_, &(_, ref q))| *q == query) {
121 return Err(CycleError {
123 cycle: RefMut::map(stack, |stack| &mut stack[i..])
126 stack.push((span, query));
129 let result = compute();
131 self.maps.query_stack.borrow_mut().pop();
137 trait QueryDescription: DepTrackingMapConfig {
138 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
141 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
142 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
143 format!("processing `{}`", tcx.item_path_str(def_id))
147 impl<'tcx> QueryDescription for queries::super_predicates<'tcx> {
148 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
149 format!("computing the supertraits of `{}`",
150 tcx.item_path_str(def_id))
154 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
155 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
156 let id = tcx.hir.as_local_node_id(def_id).unwrap();
157 format!("computing the bounds for type parameter `{}`",
158 tcx.hir.ty_param_name(id))
162 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
163 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
164 format!("coherence checking all impls of trait `{}`",
165 tcx.item_path_str(def_id))
169 impl<'tcx> QueryDescription for queries::coherent_inherent_impls<'tcx> {
170 fn describe(_: TyCtxt, _: CrateNum) -> String {
171 format!("coherence checking all inherent impls")
175 macro_rules! define_maps {
178 pub $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
179 pub struct Maps<$tcx> {
180 providers: IndexVec<CrateNum, Providers<$tcx>>,
181 query_stack: RefCell<Vec<(Span, Query)>>,
182 $($(#[$attr])* pub $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
185 impl<$tcx> Maps<$tcx> {
186 pub fn new(dep_graph: DepGraph,
187 providers: IndexVec<CrateNum, Providers<$tcx>>)
191 query_stack: RefCell::new(vec![]),
192 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
198 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
200 $($(#[$attr])* $name($K)),*
204 pub fn describe(&self, tcx: TyCtxt) -> String {
206 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
212 use std::marker::PhantomData;
214 $(#[allow(bad_style)]
215 pub struct $name<$tcx> {
216 data: PhantomData<&$tcx ()>
220 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
225 fn to_dep_node(key: &$K) -> DepNode<DefId> {
226 use dep_graph::DepNode::*;
231 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
232 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
236 -> Result<R, CycleError<'a>>
237 where F: FnOnce(&$V) -> R
239 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
240 return Ok(f(result));
243 // FIXME(eddyb) Get more valid Span's on queries.
244 if span == DUMMY_SP {
245 span = key.default_span(tcx);
248 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
250 let result = tcx.cycle_check(span, Query::$name(key), || {
251 let provider = tcx.maps.providers[key.map_crate()].$name;
252 provider(tcx.global_tcx(), key)
255 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
258 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
259 -> Result<$V, CycleError<'a>> {
260 Self::try_get_with(tcx, span, key, Clone::clone)
264 pub fn get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) -> $V {
265 Self::try_get(tcx, span, key).unwrap_or_else(|e| {
267 Value::from_cycle_error(tcx.global_tcx())
271 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
272 // FIXME(eddyb) Move away from using `DepTrackingMap`
273 // so we don't have to explicitly ignore a false edge:
274 // we can't observe a value dependency, only side-effects,
275 // through `force`, and once everything has been updated,
276 // perhaps only diagnostics, if those, will remain.
277 let _ignore = tcx.dep_graph.in_ignore();
278 match Self::try_get_with(tcx, span, key, |_| ()) {
280 Err(e) => tcx.report_cycle(e)
285 pub struct Providers<$tcx> {
286 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
289 impl<$tcx> Copy for Providers<$tcx> {}
290 impl<$tcx> Clone for Providers<$tcx> {
291 fn clone(&self) -> Self { *self }
294 impl<$tcx> Default for Providers<$tcx> {
295 fn default() -> Self {
296 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
297 bug!("tcx.maps.{}({:?}) unsupported by its crate",
298 stringify!($name), key);
300 Providers { $($name),* }
306 // Each of these maps also corresponds to a method on a
307 // `Provider` trait for requesting a value of that type,
308 // and a method on `Maps` itself for doing that in a
309 // a way that memoizes and does dep-graph tracking,
310 // wrapping around the actual chain of providers that
311 // the driver creates (using several `rustc_*` crates).
312 define_maps! { <'tcx>
313 /// Records the type of every item.
314 pub ty: ItemSignature(DefId) -> Ty<'tcx>,
316 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
317 /// associated generics and predicates.
318 pub generics: ItemSignature(DefId) -> &'tcx ty::Generics,
319 pub predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
321 /// Maps from the def-id of a trait to the list of
322 /// super-predicates. This is a subset of the full list of
323 /// predicates. We store these in a separate map because we must
324 /// evaluate them even during type conversion, often before the
325 /// full predicates are available (note that supertraits have
326 /// additional acyclicity requirements).
327 pub super_predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
329 /// To avoid cycles within the predicates of a single item we compute
330 /// per-type-parameter predicates for resolving `T::AssocTy`.
331 pub type_param_predicates: TypeParamPredicates((DefId, DefId))
332 -> ty::GenericPredicates<'tcx>,
334 pub trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
335 pub adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
336 pub adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
337 pub adt_sized_constraint: SizedConstraint(DefId) -> Ty<'tcx>,
339 /// Maps from def-id of a type or region parameter to its
340 /// (inferred) variance.
341 pub variances: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
343 /// Maps from an impl/trait def-id to a list of the def-ids of its items
344 pub associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
346 /// Maps from a trait item to the trait item "descriptor"
347 pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
349 pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
351 /// Maps a DefId of a type to a list of its inherent impls.
352 /// Contains implementations of methods that are inherent to a type.
353 /// Methods in these implementations don't need to be exported.
354 pub inherent_impls: InherentImpls(DefId) -> Vec<DefId>,
356 /// Maps from the def-id of a function/method or const/static
357 /// to its MIR. Mutation is done at an item granularity to
358 /// allow MIR optimization passes to function and still
359 /// access cross-crate MIR (e.g. inlining or const eval).
361 /// Note that cross-crate MIR appears to be always borrowed
362 /// (in the `RefCell` sense) to prevent accidental mutation.
363 pub mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
365 /// Maps DefId's that have an associated Mir to the result
366 /// of the MIR qualify_consts pass. The actual meaning of
367 /// the value isn't known except to the pass itself.
368 pub mir_const_qualif: Mir(DefId) -> u8,
370 /// Records the type of each closure. The def ID is the ID of the
371 /// expression defining the closure.
372 pub closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
374 /// Records the type of each closure. The def ID is the ID of the
375 /// expression defining the closure.
376 pub closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
378 /// Caches CoerceUnsized kinds for impls on custom types.
379 pub custom_coerce_unsized_kind: ItemSignature(DefId)
380 -> ty::adjustment::CustomCoerceUnsized,
382 pub typeck_tables: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
384 pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
386 pub coherent_inherent_impls: coherent_inherent_impls_dep_node(CrateNum) -> (),
388 /// Results of evaluating monomorphic constants embedded in
389 /// other items, such as enum variant explicit discriminants.
390 pub monomorphic_const_eval: MonomorphicConstEval(DefId) -> Result<ConstVal<'tcx>, ()>
393 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
394 DepNode::CoherenceCheckTrait(def_id)
397 fn coherent_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {