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};
21 use ty::subst::Substs;
22 use util::nodemap::NodeSet;
24 use rustc_data_structures::indexed_vec::IndexVec;
25 use std::cell::{RefCell, RefMut};
27 use std::collections::BTreeMap;
30 use syntax_pos::{Span, DUMMY_SP};
32 use syntax::symbol::Symbol;
35 fn map_crate(&self) -> CrateNum;
36 fn default_span(&self, tcx: TyCtxt) -> Span;
39 impl<'tcx> Key for ty::InstanceDef<'tcx> {
40 fn map_crate(&self) -> CrateNum {
44 fn default_span(&self, tcx: TyCtxt) -> Span {
45 tcx.def_span(self.def_id())
49 impl<'tcx> Key for ty::Instance<'tcx> {
50 fn map_crate(&self) -> CrateNum {
54 fn default_span(&self, tcx: TyCtxt) -> Span {
55 tcx.def_span(self.def_id())
59 impl Key for CrateNum {
60 fn map_crate(&self) -> CrateNum {
63 fn default_span(&self, _: TyCtxt) -> Span {
69 fn map_crate(&self) -> CrateNum {
72 fn default_span(&self, tcx: TyCtxt) -> Span {
77 impl Key for (DefId, DefId) {
78 fn map_crate(&self) -> CrateNum {
81 fn default_span(&self, tcx: TyCtxt) -> Span {
82 self.1.default_span(tcx)
86 impl Key for (CrateNum, DefId) {
87 fn map_crate(&self) -> CrateNum {
90 fn default_span(&self, tcx: TyCtxt) -> Span {
91 self.1.default_span(tcx)
95 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
96 fn map_crate(&self) -> CrateNum {
99 fn default_span(&self, tcx: TyCtxt) -> Span {
100 self.0.default_span(tcx)
104 trait Value<'tcx>: Sized {
105 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
108 impl<'tcx, T> Value<'tcx> for T {
109 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
110 tcx.sess.abort_if_errors();
111 bug!("Value::from_cycle_error called without errors");
115 impl<'tcx, T: Default> Value<'tcx> for T {
116 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
121 impl<'tcx> Value<'tcx> for Ty<'tcx> {
122 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
127 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
128 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
133 impl<'tcx> Value<'tcx> for ty::SymbolName {
134 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
135 ty::SymbolName { name: Symbol::intern("<error>").as_str() }
139 pub struct CycleError<'a, 'tcx: 'a> {
141 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
144 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
145 pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
146 // Subtle: release the refcell lock before invoking `describe()`
147 // below by dropping `cycle`.
148 let stack = cycle.to_vec();
151 assert!(!stack.is_empty());
153 // Disable naming impls with types in this path, since that
154 // sometimes cycles itself, leading to extra cycle errors.
155 // (And cycle errors around impls tend to occur during the
156 // collect/coherence phases anyhow.)
157 item_path::with_forced_impl_filename_line(|| {
159 struct_span_err!(self.sess, span, E0391,
160 "unsupported cyclic reference between types/traits detected");
161 err.span_label(span, &format!("cyclic reference"));
163 err.span_note(stack[0].0, &format!("the cycle begins when {}...",
164 stack[0].1.describe(self)));
166 for &(span, ref query) in &stack[1..] {
167 err.span_note(span, &format!("...which then requires {}...",
168 query.describe(self)));
171 err.note(&format!("...which then again requires {}, completing the cycle.",
172 stack[0].1.describe(self)));
178 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
179 -> Result<R, CycleError<'a, 'gcx>>
180 where F: FnOnce() -> R
183 let mut stack = self.maps.query_stack.borrow_mut();
184 if let Some((i, _)) = stack.iter().enumerate().rev()
185 .find(|&(_, &(_, ref q))| *q == query) {
186 return Err(CycleError {
188 cycle: RefMut::map(stack, |stack| &mut stack[i..])
191 stack.push((span, query));
194 let result = compute();
196 self.maps.query_stack.borrow_mut().pop();
202 trait QueryDescription: DepTrackingMapConfig {
203 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
206 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
207 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
208 format!("processing `{}`", tcx.item_path_str(def_id))
212 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
213 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
214 format!("computing the supertraits of `{}`",
215 tcx.item_path_str(def_id))
219 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
220 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
221 let id = tcx.hir.as_local_node_id(def_id).unwrap();
222 format!("computing the bounds for type parameter `{}`",
223 tcx.hir.ty_param_name(id))
227 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
228 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
229 format!("coherence checking all impls of trait `{}`",
230 tcx.item_path_str(def_id))
234 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
235 fn describe(_: TyCtxt, k: CrateNum) -> String {
236 format!("all inherent impls defined in crate `{:?}`", k)
240 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
241 fn describe(_: TyCtxt, _: CrateNum) -> String {
242 format!("check for overlap between inherent impls defined in this crate")
246 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
247 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
248 format!("generating MIR shim for `{}`",
249 tcx.item_path_str(def.def_id()))
253 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
254 fn describe(_: TyCtxt, _: CrateNum) -> String {
255 format!("privacy access levels")
259 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
260 fn describe(_: TyCtxt, _: CrateNum) -> String {
261 format!("type-checking all item bodies")
265 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
266 fn describe(_: TyCtxt, _: CrateNum) -> String {
267 format!("reachability")
271 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
272 fn describe(tcx: TyCtxt, (def_id, _): (DefId, &'tcx Substs<'tcx>)) -> String {
273 format!("const-evaluating `{}`",
274 tcx.item_path_str(def_id))
278 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
279 fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
280 format!("computing the symbol for `{}`", instance)
284 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
285 fn describe(_: TyCtxt, _: DefId) -> String {
290 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
291 fn describe(_: TyCtxt, _: DefId) -> String {
297 impl<'tcx> QueryDescription for queries::stability<'tcx> {
298 fn describe(_: TyCtxt, _: DefId) -> String {
303 impl<'tcx> QueryDescription for queries::deprecation<'tcx> {
304 fn describe(_: TyCtxt, _: DefId) -> String {
309 impl<'tcx> QueryDescription for queries::item_body_nested_bodies<'tcx> {
310 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
311 format!("nested item bodies of `{}`", tcx.item_path_str(def_id))
315 impl<'tcx> QueryDescription for queries::const_is_rvalue_promotable_to_static<'tcx> {
316 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
317 format!("const checking if rvalue is promotable to static `{}`",
318 tcx.item_path_str(def_id))
322 impl<'tcx> QueryDescription for queries::is_item_mir_available<'tcx> {
323 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
324 format!("checking if item is mir available: `{}`",
325 tcx.item_path_str(def_id))
329 macro_rules! define_maps {
332 [$($pub:tt)*] $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
333 pub struct Maps<$tcx> {
334 providers: IndexVec<CrateNum, Providers<$tcx>>,
335 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
336 $($(#[$attr])* $($pub)* $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
339 impl<$tcx> Maps<$tcx> {
340 pub fn new(dep_graph: DepGraph,
341 providers: IndexVec<CrateNum, Providers<$tcx>>)
345 query_stack: RefCell::new(vec![]),
346 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
352 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
353 pub enum Query<$tcx> {
354 $($(#[$attr])* $name($K)),*
357 impl<$tcx> Query<$tcx> {
358 pub fn describe(&self, tcx: TyCtxt) -> String {
360 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
366 use std::marker::PhantomData;
368 $(#[allow(bad_style)]
369 pub struct $name<$tcx> {
370 data: PhantomData<&$tcx ()>
374 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
379 fn to_dep_node(key: &$K) -> DepNode<DefId> {
380 use dep_graph::DepNode::*;
385 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
386 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
390 -> Result<R, CycleError<'a, $tcx>>
391 where F: FnOnce(&$V) -> R
393 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
398 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
399 return Ok(f(result));
402 // FIXME(eddyb) Get more valid Span's on queries.
403 // def_span guard is necesary to prevent a recursive loop,
404 // default_span calls def_span query internally.
405 if span == DUMMY_SP && stringify!($name) != "def_span" {
406 span = key.default_span(tcx)
409 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
411 let result = tcx.cycle_check(span, Query::$name(key), || {
412 let provider = tcx.maps.providers[key.map_crate()].$name;
413 provider(tcx.global_tcx(), key)
416 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
419 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
420 -> Result<$V, CycleError<'a, $tcx>> {
421 Self::try_get_with(tcx, span, key, Clone::clone)
424 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
425 // FIXME(eddyb) Move away from using `DepTrackingMap`
426 // so we don't have to explicitly ignore a false edge:
427 // we can't observe a value dependency, only side-effects,
428 // through `force`, and once everything has been updated,
429 // perhaps only diagnostics, if those, will remain.
430 let _ignore = tcx.dep_graph.in_ignore();
431 match Self::try_get_with(tcx, span, key, |_| ()) {
433 Err(e) => tcx.report_cycle(e)
438 #[derive(Copy, Clone)]
439 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
440 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
444 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
445 type Target = TyCtxt<'a, 'gcx, 'tcx>;
446 fn deref(&self) -> &Self::Target {
451 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
452 /// Return a transparent wrapper for `TyCtxt` which uses
453 /// `span` as the location of queries performed through it.
454 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
462 pub fn $name(self, key: $K) -> $V {
463 self.at(DUMMY_SP).$name(key)
467 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
469 pub fn $name(self, key: $K) -> $V {
470 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|e| {
471 self.report_cycle(e);
472 Value::from_cycle_error(self.global_tcx())
477 pub struct Providers<$tcx> {
478 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
481 impl<$tcx> Copy for Providers<$tcx> {}
482 impl<$tcx> Clone for Providers<$tcx> {
483 fn clone(&self) -> Self { *self }
486 impl<$tcx> Default for Providers<$tcx> {
487 fn default() -> Self {
488 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
489 bug!("tcx.maps.{}({:?}) unsupported by its crate",
490 stringify!($name), key);
492 Providers { $($name),* }
498 // Each of these maps also corresponds to a method on a
499 // `Provider` trait for requesting a value of that type,
500 // and a method on `Maps` itself for doing that in a
501 // a way that memoizes and does dep-graph tracking,
502 // wrapping around the actual chain of providers that
503 // the driver creates (using several `rustc_*` crates).
504 define_maps! { <'tcx>
505 /// Records the type of every item.
506 [] type_of: ItemSignature(DefId) -> Ty<'tcx>,
508 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
509 /// associated generics and predicates.
510 [] generics_of: ItemSignature(DefId) -> &'tcx ty::Generics,
511 [] predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
513 /// Maps from the def-id of a trait to the list of
514 /// super-predicates. This is a subset of the full list of
515 /// predicates. We store these in a separate map because we must
516 /// evaluate them even during type conversion, often before the
517 /// full predicates are available (note that supertraits have
518 /// additional acyclicity requirements).
519 [] super_predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
521 /// To avoid cycles within the predicates of a single item we compute
522 /// per-type-parameter predicates for resolving `T::AssocTy`.
523 [] type_param_predicates: TypeParamPredicates((DefId, DefId))
524 -> ty::GenericPredicates<'tcx>,
526 [] trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
527 [] adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
528 [] adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
529 [] adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
530 [] adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
532 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
533 [] is_foreign_item: IsForeignItem(DefId) -> bool,
535 /// Maps from def-id of a type or region parameter to its
536 /// (inferred) variance.
537 [pub] variances_of: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
539 /// Maps from an impl/trait def-id to a list of the def-ids of its items
540 [] associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
542 /// Maps from a trait item to the trait item "descriptor"
543 [] associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
545 [] impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
546 [] impl_polarity: ItemSignature(DefId) -> hir::ImplPolarity,
548 /// Maps a DefId of a type to a list of its inherent impls.
549 /// Contains implementations of methods that are inherent to a type.
550 /// Methods in these implementations don't need to be exported.
551 [] inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
553 /// Maps from the def-id of a function/method or const/static
554 /// to its MIR. Mutation is done at an item granularity to
555 /// allow MIR optimization passes to function and still
556 /// access cross-crate MIR (e.g. inlining or const eval).
558 /// Note that cross-crate MIR appears to be always borrowed
559 /// (in the `RefCell` sense) to prevent accidental mutation.
560 [pub] mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
562 /// Maps DefId's that have an associated Mir to the result
563 /// of the MIR qualify_consts pass. The actual meaning of
564 /// the value isn't known except to the pass itself.
565 [] mir_const_qualif: Mir(DefId) -> u8,
567 /// Records the type of each closure. The def ID is the ID of the
568 /// expression defining the closure.
569 [] closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
571 /// Records the type of each closure. The def ID is the ID of the
572 /// expression defining the closure.
573 [] closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
575 /// Caches CoerceUnsized kinds for impls on custom types.
576 [] coerce_unsized_info: ItemSignature(DefId)
577 -> ty::adjustment::CoerceUnsizedInfo,
579 [] typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
581 [] typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
583 [] has_typeck_tables: TypeckTables(DefId) -> bool,
585 [] coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
587 [] borrowck: BorrowCheck(DefId) -> (),
589 /// Gets a complete map from all types to their inherent impls.
590 /// Not meant to be used directly outside of coherence.
591 /// (Defined only for LOCAL_CRATE)
592 [] crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
594 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
595 /// Not meant to be used directly outside of coherence.
596 /// (Defined only for LOCAL_CRATE)
597 [] crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
599 /// Results of evaluating const items or constants embedded in
600 /// other items (such as enum variant explicit discriminants).
601 [] const_eval: const_eval_dep_node((DefId, &'tcx Substs<'tcx>))
602 -> const_val::EvalResult<'tcx>,
604 /// Performs the privacy check and computes "access levels".
605 [] privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
607 [] reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
609 [] mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>,
611 [] def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
612 [] symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
614 [] describe_def: DescribeDef(DefId) -> Option<Def>,
615 [] def_span: DefSpan(DefId) -> Span,
616 [] stability: Stability(DefId) -> Option<attr::Stability>,
617 [] deprecation: Deprecation(DefId) -> Option<attr::Deprecation>,
618 [] item_body_nested_bodies: metadata_dep_node(DefId) -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
619 [] const_is_rvalue_promotable_to_static: metadata_dep_node(DefId) -> bool,
620 [] is_item_mir_available: metadata_dep_node(DefId) -> bool,
623 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
624 DepNode::CoherenceCheckTrait(def_id)
627 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
631 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
632 DepNode::Reachability
635 fn metadata_dep_node(def_id: DefId) -> DepNode<DefId> {
636 DepNode::MetaData(def_id)
639 fn mir_shim_dep_node(instance: ty::InstanceDef) -> DepNode<DefId> {
643 fn symbol_name_dep_node(instance: ty::Instance) -> DepNode<DefId> {
644 // symbol_name uses the substs only to traverse them to find the
645 // hash, and that does not create any new dep-nodes.
646 DepNode::SymbolName(instance.def.def_id())
649 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
650 DepNode::TypeckBodiesKrate
653 fn const_eval_dep_node((def_id, _): (DefId, &Substs)) -> DepNode<DefId> {
654 DepNode::ConstEval(def_id)