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 ty::subst::Substs;
20 use util::nodemap::NodeSet;
22 use rustc_data_structures::indexed_vec::IndexVec;
23 use std::cell::{RefCell, RefMut};
26 use syntax_pos::{Span, DUMMY_SP};
29 fn map_crate(&self) -> CrateNum;
30 fn default_span(&self, tcx: TyCtxt) -> Span;
33 impl<'tcx> Key for ty::InstanceDef<'tcx> {
34 fn map_crate(&self) -> CrateNum {
38 fn default_span(&self, tcx: TyCtxt) -> Span {
39 tcx.def_span(self.def_id())
43 impl Key for CrateNum {
44 fn map_crate(&self) -> CrateNum {
47 fn default_span(&self, _: TyCtxt) -> Span {
53 fn map_crate(&self) -> CrateNum {
56 fn default_span(&self, tcx: TyCtxt) -> Span {
61 impl Key for (DefId, DefId) {
62 fn map_crate(&self) -> CrateNum {
65 fn default_span(&self, tcx: TyCtxt) -> Span {
66 self.1.default_span(tcx)
70 impl Key for (CrateNum, DefId) {
71 fn map_crate(&self) -> CrateNum {
74 fn default_span(&self, tcx: TyCtxt) -> Span {
75 self.1.default_span(tcx)
79 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
80 fn map_crate(&self) -> CrateNum {
83 fn default_span(&self, tcx: TyCtxt) -> Span {
84 self.0.default_span(tcx)
88 trait Value<'tcx>: Sized {
89 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
92 impl<'tcx, T> Value<'tcx> for T {
93 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
94 tcx.sess.abort_if_errors();
95 bug!("Value::from_cycle_error called without errors");
99 impl<'tcx, T: Default> Value<'tcx> for T {
100 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
105 impl<'tcx> Value<'tcx> for Ty<'tcx> {
106 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
112 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
113 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
118 pub struct CycleError<'a, 'tcx: 'a> {
120 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
123 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
124 pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
125 assert!(!cycle.is_empty());
127 let mut err = struct_span_err!(self.sess, span, E0391,
128 "unsupported cyclic reference between types/traits detected");
129 err.span_label(span, &format!("cyclic reference"));
131 err.span_note(cycle[0].0, &format!("the cycle begins when {}...",
132 cycle[0].1.describe(self)));
134 for &(span, ref query) in &cycle[1..] {
135 err.span_note(span, &format!("...which then requires {}...",
136 query.describe(self)));
139 err.note(&format!("...which then again requires {}, completing the cycle.",
140 cycle[0].1.describe(self)));
145 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
146 -> Result<R, CycleError<'a, 'gcx>>
147 where F: FnOnce() -> R
150 let mut stack = self.maps.query_stack.borrow_mut();
151 if let Some((i, _)) = stack.iter().enumerate().rev()
152 .find(|&(_, &(_, ref q))| *q == query) {
153 return Err(CycleError {
155 cycle: RefMut::map(stack, |stack| &mut stack[i..])
158 stack.push((span, query));
161 let result = compute();
163 self.maps.query_stack.borrow_mut().pop();
169 trait QueryDescription: DepTrackingMapConfig {
170 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
173 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
174 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
175 format!("processing `{}`", tcx.item_path_str(def_id))
179 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
180 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
181 format!("computing the supertraits of `{}`",
182 tcx.item_path_str(def_id))
186 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
187 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
188 let id = tcx.hir.as_local_node_id(def_id).unwrap();
189 format!("computing the bounds for type parameter `{}`",
190 tcx.hir.ty_param_name(id))
194 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
195 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
196 format!("coherence checking all impls of trait `{}`",
197 tcx.item_path_str(def_id))
201 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
202 fn describe(_: TyCtxt, k: CrateNum) -> String {
203 format!("all inherent impls defined in crate `{:?}`", k)
207 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
208 fn describe(_: TyCtxt, _: CrateNum) -> String {
209 format!("check for overlap between inherent impls defined in this crate")
213 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
214 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
215 format!("generating MIR shim for `{}`",
216 tcx.item_path_str(def.def_id()))
220 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
221 fn describe(_: TyCtxt, _: CrateNum) -> String {
222 format!("privacy access levels")
226 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
227 fn describe(_: TyCtxt, _: CrateNum) -> String {
228 format!("type-checking all item bodies")
232 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
233 fn describe(_: TyCtxt, _: CrateNum) -> String {
234 format!("reachability")
238 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
239 fn describe(tcx: TyCtxt, (def_id, _): (DefId, &'tcx Substs<'tcx>)) -> String {
240 format!("const-evaluating `{}`",
241 tcx.item_path_str(def_id))
245 macro_rules! define_maps {
248 pub $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
249 pub struct Maps<$tcx> {
250 providers: IndexVec<CrateNum, Providers<$tcx>>,
251 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
252 $($(#[$attr])* pub $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
255 impl<$tcx> Maps<$tcx> {
256 pub fn new(dep_graph: DepGraph,
257 providers: IndexVec<CrateNum, Providers<$tcx>>)
261 query_stack: RefCell::new(vec![]),
262 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
268 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
269 pub enum Query<$tcx> {
270 $($(#[$attr])* $name($K)),*
273 impl<$tcx> Query<$tcx> {
274 pub fn describe(&self, tcx: TyCtxt) -> String {
276 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
282 use std::marker::PhantomData;
284 $(#[allow(bad_style)]
285 pub struct $name<$tcx> {
286 data: PhantomData<&$tcx ()>
290 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
295 fn to_dep_node(key: &$K) -> DepNode<DefId> {
296 use dep_graph::DepNode::*;
301 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
302 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
306 -> Result<R, CycleError<'a, $tcx>>
307 where F: FnOnce(&$V) -> R
309 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
310 return Ok(f(result));
313 // FIXME(eddyb) Get more valid Span's on queries.
314 if span == DUMMY_SP {
315 span = key.default_span(tcx);
318 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
320 let result = tcx.cycle_check(span, Query::$name(key), || {
321 let provider = tcx.maps.providers[key.map_crate()].$name;
322 provider(tcx.global_tcx(), key)
325 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
328 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
329 -> Result<$V, CycleError<'a, $tcx>> {
330 Self::try_get_with(tcx, span, key, Clone::clone)
333 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
334 // FIXME(eddyb) Move away from using `DepTrackingMap`
335 // so we don't have to explicitly ignore a false edge:
336 // we can't observe a value dependency, only side-effects,
337 // through `force`, and once everything has been updated,
338 // perhaps only diagnostics, if those, will remain.
339 let _ignore = tcx.dep_graph.in_ignore();
340 match Self::try_get_with(tcx, span, key, |_| ()) {
342 Err(e) => tcx.report_cycle(e)
347 #[derive(Copy, Clone)]
348 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
349 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
353 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
354 type Target = TyCtxt<'a, 'gcx, 'tcx>;
355 fn deref(&self) -> &Self::Target {
360 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
361 /// Return a transparent wrapper for `TyCtxt` which uses
362 /// `span` as the location of queries performed through it.
363 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
371 pub fn $name(self, key: $K) -> $V {
372 self.at(DUMMY_SP).$name(key)
376 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
378 pub fn $name(self, key: $K) -> $V {
379 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|e| {
380 self.report_cycle(e);
381 Value::from_cycle_error(self.global_tcx())
386 pub struct Providers<$tcx> {
387 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
390 impl<$tcx> Copy for Providers<$tcx> {}
391 impl<$tcx> Clone for Providers<$tcx> {
392 fn clone(&self) -> Self { *self }
395 impl<$tcx> Default for Providers<$tcx> {
396 fn default() -> Self {
397 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
398 bug!("tcx.maps.{}({:?}) unsupported by its crate",
399 stringify!($name), key);
401 Providers { $($name),* }
407 // Each of these maps also corresponds to a method on a
408 // `Provider` trait for requesting a value of that type,
409 // and a method on `Maps` itself for doing that in a
410 // a way that memoizes and does dep-graph tracking,
411 // wrapping around the actual chain of providers that
412 // the driver creates (using several `rustc_*` crates).
413 define_maps! { <'tcx>
414 /// Records the type of every item.
415 pub type_of: ItemSignature(DefId) -> Ty<'tcx>,
417 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
418 /// associated generics and predicates.
419 pub generics_of: ItemSignature(DefId) -> &'tcx ty::Generics,
420 pub predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
422 /// Maps from the def-id of a trait to the list of
423 /// super-predicates. This is a subset of the full list of
424 /// predicates. We store these in a separate map because we must
425 /// evaluate them even during type conversion, often before the
426 /// full predicates are available (note that supertraits have
427 /// additional acyclicity requirements).
428 pub super_predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
430 /// To avoid cycles within the predicates of a single item we compute
431 /// per-type-parameter predicates for resolving `T::AssocTy`.
432 pub type_param_predicates: TypeParamPredicates((DefId, DefId))
433 -> ty::GenericPredicates<'tcx>,
435 pub trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
436 pub adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
437 pub adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
438 pub adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
439 pub adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
441 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
442 pub is_foreign_item: IsForeignItem(DefId) -> bool,
444 /// Maps from def-id of a type or region parameter to its
445 /// (inferred) variance.
446 pub variances_of: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
448 /// Maps from an impl/trait def-id to a list of the def-ids of its items
449 pub associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
451 /// Maps from a trait item to the trait item "descriptor"
452 pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
454 pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
455 pub impl_polarity: ItemSignature(DefId) -> hir::ImplPolarity,
457 /// Maps a DefId of a type to a list of its inherent impls.
458 /// Contains implementations of methods that are inherent to a type.
459 /// Methods in these implementations don't need to be exported.
460 pub inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
462 /// Maps from the def-id of a function/method or const/static
463 /// to its MIR. Mutation is done at an item granularity to
464 /// allow MIR optimization passes to function and still
465 /// access cross-crate MIR (e.g. inlining or const eval).
467 /// Note that cross-crate MIR appears to be always borrowed
468 /// (in the `RefCell` sense) to prevent accidental mutation.
469 pub mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
471 /// Maps DefId's that have an associated Mir to the result
472 /// of the MIR qualify_consts pass. The actual meaning of
473 /// the value isn't known except to the pass itself.
474 pub mir_const_qualif: Mir(DefId) -> u8,
476 /// Records the type of each closure. The def ID is the ID of the
477 /// expression defining the closure.
478 pub closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
480 /// Records the type of each closure. The def ID is the ID of the
481 /// expression defining the closure.
482 pub closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
484 /// Caches CoerceUnsized kinds for impls on custom types.
485 pub coerce_unsized_info: ItemSignature(DefId)
486 -> ty::adjustment::CoerceUnsizedInfo,
488 pub typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
490 pub typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
492 pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
494 pub borrowck: BorrowCheck(DefId) -> (),
496 /// Gets a complete map from all types to their inherent impls.
497 /// Not meant to be used directly outside of coherence.
498 /// (Defined only for LOCAL_CRATE)
499 pub crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
501 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
502 /// Not meant to be used directly outside of coherence.
503 /// (Defined only for LOCAL_CRATE)
504 pub crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
506 /// Results of evaluating const items or constants embedded in
507 /// other items (such as enum variant explicit discriminants).
508 pub const_eval: const_eval_dep_node((DefId, &'tcx Substs<'tcx>))
509 -> const_val::EvalResult<'tcx>,
511 /// Performs the privacy check and computes "access levels".
512 pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
514 pub reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
516 pub mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>
519 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
520 DepNode::CoherenceCheckTrait(def_id)
523 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
527 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
528 DepNode::Reachability
531 fn mir_shim_dep_node(instance: ty::InstanceDef) -> DepNode<DefId> {
535 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
536 DepNode::TypeckBodiesKrate
539 fn const_eval_dep_node((def_id, _): (DefId, &Substs)) -> DepNode<DefId> {
540 DepNode::ConstEval(def_id)