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};
15 use middle::const_val;
16 use middle::privacy::AccessLevels;
18 use session::CompileResult;
19 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
20 use ty::subst::Substs;
21 use util::nodemap::NodeSet;
23 use rustc_data_structures::indexed_vec::IndexVec;
24 use std::cell::{RefCell, RefMut};
27 use syntax_pos::{Span, DUMMY_SP};
28 use syntax::symbol::Symbol;
31 fn map_crate(&self) -> CrateNum;
32 fn default_span(&self, tcx: TyCtxt) -> Span;
35 impl<'tcx> Key for ty::InstanceDef<'tcx> {
36 fn map_crate(&self) -> CrateNum {
40 fn default_span(&self, tcx: TyCtxt) -> Span {
41 tcx.def_span(self.def_id())
45 impl<'tcx> Key for ty::Instance<'tcx> {
46 fn map_crate(&self) -> CrateNum {
50 fn default_span(&self, tcx: TyCtxt) -> Span {
51 tcx.def_span(self.def_id())
55 impl Key for CrateNum {
56 fn map_crate(&self) -> CrateNum {
59 fn default_span(&self, _: TyCtxt) -> Span {
65 fn map_crate(&self) -> CrateNum {
68 fn default_span(&self, tcx: TyCtxt) -> Span {
73 impl Key for (DefId, DefId) {
74 fn map_crate(&self) -> CrateNum {
77 fn default_span(&self, tcx: TyCtxt) -> Span {
78 self.1.default_span(tcx)
82 impl Key for (CrateNum, DefId) {
83 fn map_crate(&self) -> CrateNum {
86 fn default_span(&self, tcx: TyCtxt) -> Span {
87 self.1.default_span(tcx)
91 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
92 fn map_crate(&self) -> CrateNum {
95 fn default_span(&self, tcx: TyCtxt) -> Span {
96 self.0.default_span(tcx)
100 trait Value<'tcx>: Sized {
101 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
104 impl<'tcx, T> Value<'tcx> for T {
105 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
106 tcx.sess.abort_if_errors();
107 bug!("Value::from_cycle_error called without errors");
111 impl<'tcx, T: Default> Value<'tcx> for T {
112 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
117 impl<'tcx> Value<'tcx> for Ty<'tcx> {
118 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
123 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
124 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
129 impl<'tcx> Value<'tcx> for ty::SymbolName {
130 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
131 ty::SymbolName { name: Symbol::intern("<error>").as_str() }
135 pub struct CycleError<'a, 'tcx: 'a> {
137 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
140 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
141 pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
142 assert!(!cycle.is_empty());
144 let mut err = struct_span_err!(self.sess, span, E0391,
145 "unsupported cyclic reference between types/traits detected");
146 err.span_label(span, &format!("cyclic reference"));
148 err.span_note(cycle[0].0, &format!("the cycle begins when {}...",
149 cycle[0].1.describe(self)));
151 for &(span, ref query) in &cycle[1..] {
152 err.span_note(span, &format!("...which then requires {}...",
153 query.describe(self)));
156 err.note(&format!("...which then again requires {}, completing the cycle.",
157 cycle[0].1.describe(self)));
162 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
163 -> Result<R, CycleError<'a, 'gcx>>
164 where F: FnOnce() -> R
167 let mut stack = self.maps.query_stack.borrow_mut();
168 if let Some((i, _)) = stack.iter().enumerate().rev()
169 .find(|&(_, &(_, ref q))| *q == query) {
170 return Err(CycleError {
172 cycle: RefMut::map(stack, |stack| &mut stack[i..])
175 stack.push((span, query));
178 let result = compute();
180 self.maps.query_stack.borrow_mut().pop();
186 trait QueryDescription: DepTrackingMapConfig {
187 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
190 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
191 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
192 format!("processing `{}`", tcx.item_path_str(def_id))
196 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
197 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
198 format!("computing the supertraits of `{}`",
199 tcx.item_path_str(def_id))
203 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
204 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
205 let id = tcx.hir.as_local_node_id(def_id).unwrap();
206 format!("computing the bounds for type parameter `{}`",
207 tcx.hir.ty_param_name(id))
211 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
212 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
213 format!("coherence checking all impls of trait `{}`",
214 tcx.item_path_str(def_id))
218 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
219 fn describe(_: TyCtxt, k: CrateNum) -> String {
220 format!("all inherent impls defined in crate `{:?}`", k)
224 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
225 fn describe(_: TyCtxt, _: CrateNum) -> String {
226 format!("check for overlap between inherent impls defined in this crate")
230 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
231 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
232 format!("generating MIR shim for `{}`",
233 tcx.item_path_str(def.def_id()))
237 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
238 fn describe(_: TyCtxt, _: CrateNum) -> String {
239 format!("privacy access levels")
243 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
244 fn describe(_: TyCtxt, _: CrateNum) -> String {
245 format!("type-checking all item bodies")
249 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
250 fn describe(_: TyCtxt, _: CrateNum) -> String {
251 format!("reachability")
255 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
256 fn describe(tcx: TyCtxt, (def_id, _): (DefId, &'tcx Substs<'tcx>)) -> String {
257 format!("const-evaluating `{}`",
258 tcx.item_path_str(def_id))
262 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
263 fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
264 format!("computing the symbol for `{}`", instance)
268 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
269 fn describe(_: TyCtxt, _: DefId) -> String {
274 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
275 fn describe(_: TyCtxt, _: DefId) -> String {
280 macro_rules! define_maps {
283 pub $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
284 pub struct Maps<$tcx> {
285 providers: IndexVec<CrateNum, Providers<$tcx>>,
286 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
287 $($(#[$attr])* pub $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
290 impl<$tcx> Maps<$tcx> {
291 pub fn new(dep_graph: DepGraph,
292 providers: IndexVec<CrateNum, Providers<$tcx>>)
296 query_stack: RefCell::new(vec![]),
297 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
303 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
304 pub enum Query<$tcx> {
305 $($(#[$attr])* $name($K)),*
308 impl<$tcx> Query<$tcx> {
309 pub fn describe(&self, tcx: TyCtxt) -> String {
311 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
317 use std::marker::PhantomData;
319 $(#[allow(bad_style)]
320 pub struct $name<$tcx> {
321 data: PhantomData<&$tcx ()>
325 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
330 fn to_dep_node(key: &$K) -> DepNode<DefId> {
331 use dep_graph::DepNode::*;
336 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
337 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
341 -> Result<R, CycleError<'a, $tcx>>
342 where F: FnOnce(&$V) -> R
344 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
345 return Ok(f(result));
348 // FIXME(eddyb) Get more valid Span's on queries.
349 if span == DUMMY_SP && stringify!($name) != "def_span" {
350 span = key.default_span(tcx)
353 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
355 let result = tcx.cycle_check(span, Query::$name(key), || {
356 let provider = tcx.maps.providers[key.map_crate()].$name;
357 provider(tcx.global_tcx(), key)
360 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
363 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
364 -> Result<$V, CycleError<'a, $tcx>> {
365 Self::try_get_with(tcx, span, key, Clone::clone)
368 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
369 // FIXME(eddyb) Move away from using `DepTrackingMap`
370 // so we don't have to explicitly ignore a false edge:
371 // we can't observe a value dependency, only side-effects,
372 // through `force`, and once everything has been updated,
373 // perhaps only diagnostics, if those, will remain.
374 let _ignore = tcx.dep_graph.in_ignore();
375 match Self::try_get_with(tcx, span, key, |_| ()) {
377 Err(e) => tcx.report_cycle(e)
382 #[derive(Copy, Clone)]
383 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
384 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
388 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
389 type Target = TyCtxt<'a, 'gcx, 'tcx>;
390 fn deref(&self) -> &Self::Target {
395 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
396 /// Return a transparent wrapper for `TyCtxt` which uses
397 /// `span` as the location of queries performed through it.
398 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
406 pub fn $name(self, key: $K) -> $V {
407 self.at(DUMMY_SP).$name(key)
411 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
413 pub fn $name(self, key: $K) -> $V {
414 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|e| {
415 self.report_cycle(e);
416 Value::from_cycle_error(self.global_tcx())
421 pub struct Providers<$tcx> {
422 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
425 impl<$tcx> Copy for Providers<$tcx> {}
426 impl<$tcx> Clone for Providers<$tcx> {
427 fn clone(&self) -> Self { *self }
430 impl<$tcx> Default for Providers<$tcx> {
431 fn default() -> Self {
432 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
433 bug!("tcx.maps.{}({:?}) unsupported by its crate",
434 stringify!($name), key);
436 Providers { $($name),* }
442 // Each of these maps also corresponds to a method on a
443 // `Provider` trait for requesting a value of that type,
444 // and a method on `Maps` itself for doing that in a
445 // a way that memoizes and does dep-graph tracking,
446 // wrapping around the actual chain of providers that
447 // the driver creates (using several `rustc_*` crates).
448 define_maps! { <'tcx>
449 /// Records the type of every item.
450 pub type_of: ItemSignature(DefId) -> Ty<'tcx>,
452 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
453 /// associated generics and predicates.
454 pub generics_of: ItemSignature(DefId) -> &'tcx ty::Generics,
455 pub predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
457 /// Maps from the def-id of a trait to the list of
458 /// super-predicates. This is a subset of the full list of
459 /// predicates. We store these in a separate map because we must
460 /// evaluate them even during type conversion, often before the
461 /// full predicates are available (note that supertraits have
462 /// additional acyclicity requirements).
463 pub super_predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
465 /// To avoid cycles within the predicates of a single item we compute
466 /// per-type-parameter predicates for resolving `T::AssocTy`.
467 pub type_param_predicates: TypeParamPredicates((DefId, DefId))
468 -> ty::GenericPredicates<'tcx>,
470 pub trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
471 pub adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
472 pub adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
473 pub adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
474 pub adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
476 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
477 pub is_foreign_item: IsForeignItem(DefId) -> bool,
479 /// Maps from def-id of a type or region parameter to its
480 /// (inferred) variance.
481 pub variances_of: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
483 /// Maps from an impl/trait def-id to a list of the def-ids of its items
484 pub associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
486 /// Maps from a trait item to the trait item "descriptor"
487 pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
489 pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
490 pub impl_polarity: ItemSignature(DefId) -> hir::ImplPolarity,
492 /// Maps a DefId of a type to a list of its inherent impls.
493 /// Contains implementations of methods that are inherent to a type.
494 /// Methods in these implementations don't need to be exported.
495 pub inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
497 /// Maps from the def-id of a function/method or const/static
498 /// to its MIR. Mutation is done at an item granularity to
499 /// allow MIR optimization passes to function and still
500 /// access cross-crate MIR (e.g. inlining or const eval).
502 /// Note that cross-crate MIR appears to be always borrowed
503 /// (in the `RefCell` sense) to prevent accidental mutation.
504 pub mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
506 /// Maps DefId's that have an associated Mir to the result
507 /// of the MIR qualify_consts pass. The actual meaning of
508 /// the value isn't known except to the pass itself.
509 pub mir_const_qualif: Mir(DefId) -> u8,
511 /// Records the type of each closure. The def ID is the ID of the
512 /// expression defining the closure.
513 pub closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
515 /// Records the type of each closure. The def ID is the ID of the
516 /// expression defining the closure.
517 pub closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
519 /// Caches CoerceUnsized kinds for impls on custom types.
520 pub coerce_unsized_info: ItemSignature(DefId)
521 -> ty::adjustment::CoerceUnsizedInfo,
523 pub typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
525 pub typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
527 pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
529 pub borrowck: BorrowCheck(DefId) -> (),
531 /// Gets a complete map from all types to their inherent impls.
532 /// Not meant to be used directly outside of coherence.
533 /// (Defined only for LOCAL_CRATE)
534 pub crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
536 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
537 /// Not meant to be used directly outside of coherence.
538 /// (Defined only for LOCAL_CRATE)
539 pub crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
541 /// Results of evaluating const items or constants embedded in
542 /// other items (such as enum variant explicit discriminants).
543 pub const_eval: const_eval_dep_node((DefId, &'tcx Substs<'tcx>))
544 -> const_val::EvalResult<'tcx>,
546 /// Performs the privacy check and computes "access levels".
547 pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
549 pub reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
551 pub mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>,
553 pub def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
554 pub symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
556 pub describe_def: MetaData(DefId) -> Option<Def>,
557 pub def_span: MetaData(DefId) -> Span
560 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
561 DepNode::CoherenceCheckTrait(def_id)
564 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
568 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
569 DepNode::Reachability
572 fn mir_shim_dep_node(instance: ty::InstanceDef) -> DepNode<DefId> {
576 fn symbol_name_dep_node(instance: ty::Instance) -> DepNode<DefId> {
577 // symbol_name uses the substs only to traverse them to find the
578 // hash, and that does not create any new dep-nodes.
579 DepNode::SymbolName(instance.def.def_id())
582 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
583 DepNode::TypeckBodiesKrate
586 fn const_eval_dep_node((def_id, _): (DefId, &Substs)) -> DepNode<DefId> {
587 DepNode::ConstEval(def_id)