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};
31 use syntax::symbol::Symbol;
34 fn map_crate(&self) -> CrateNum;
35 fn default_span(&self, tcx: TyCtxt) -> Span;
38 impl<'tcx> Key for ty::InstanceDef<'tcx> {
39 fn map_crate(&self) -> CrateNum {
43 fn default_span(&self, tcx: TyCtxt) -> Span {
44 tcx.def_span(self.def_id())
48 impl<'tcx> Key for ty::Instance<'tcx> {
49 fn map_crate(&self) -> CrateNum {
53 fn default_span(&self, tcx: TyCtxt) -> Span {
54 tcx.def_span(self.def_id())
58 impl Key for CrateNum {
59 fn map_crate(&self) -> CrateNum {
62 fn default_span(&self, _: TyCtxt) -> Span {
68 fn map_crate(&self) -> CrateNum {
71 fn default_span(&self, tcx: TyCtxt) -> Span {
76 impl Key for (DefId, DefId) {
77 fn map_crate(&self) -> CrateNum {
80 fn default_span(&self, tcx: TyCtxt) -> Span {
81 self.1.default_span(tcx)
85 impl Key for (CrateNum, DefId) {
86 fn map_crate(&self) -> CrateNum {
89 fn default_span(&self, tcx: TyCtxt) -> Span {
90 self.1.default_span(tcx)
94 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
95 fn map_crate(&self) -> CrateNum {
98 fn default_span(&self, tcx: TyCtxt) -> Span {
99 self.0.default_span(tcx)
103 trait Value<'tcx>: Sized {
104 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
107 impl<'tcx, T> Value<'tcx> for T {
108 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
109 tcx.sess.abort_if_errors();
110 bug!("Value::from_cycle_error called without errors");
114 impl<'tcx, T: Default> Value<'tcx> for T {
115 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
120 impl<'tcx> Value<'tcx> for Ty<'tcx> {
121 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
126 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
127 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
132 impl<'tcx> Value<'tcx> for ty::SymbolName {
133 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
134 ty::SymbolName { name: Symbol::intern("<error>").as_str() }
138 pub struct CycleError<'a, 'tcx: 'a> {
140 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
143 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
144 pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
145 // Subtle: release the refcell lock before invoking `describe()`
146 // below by dropping `cycle`.
147 let stack = cycle.to_vec();
150 assert!(!stack.is_empty());
152 // Disable naming impls with types in this path, since that
153 // sometimes cycles itself, leading to extra cycle errors.
154 // (And cycle errors around impls tend to occur during the
155 // collect/coherence phases anyhow.)
156 item_path::with_forced_impl_filename_line(|| {
158 struct_span_err!(self.sess, span, E0391,
159 "unsupported cyclic reference between types/traits detected");
160 err.span_label(span, &format!("cyclic reference"));
162 err.span_note(stack[0].0, &format!("the cycle begins when {}...",
163 stack[0].1.describe(self)));
165 for &(span, ref query) in &stack[1..] {
166 err.span_note(span, &format!("...which then requires {}...",
167 query.describe(self)));
170 err.note(&format!("...which then again requires {}, completing the cycle.",
171 stack[0].1.describe(self)));
177 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
178 -> Result<R, CycleError<'a, 'gcx>>
179 where F: FnOnce() -> R
182 let mut stack = self.maps.query_stack.borrow_mut();
183 if let Some((i, _)) = stack.iter().enumerate().rev()
184 .find(|&(_, &(_, ref q))| *q == query) {
185 return Err(CycleError {
187 cycle: RefMut::map(stack, |stack| &mut stack[i..])
190 stack.push((span, query));
193 let result = compute();
195 self.maps.query_stack.borrow_mut().pop();
201 trait QueryDescription: DepTrackingMapConfig {
202 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
205 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
206 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
207 format!("processing `{}`", tcx.item_path_str(def_id))
211 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
212 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
213 format!("computing the supertraits of `{}`",
214 tcx.item_path_str(def_id))
218 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
219 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
220 let id = tcx.hir.as_local_node_id(def_id).unwrap();
221 format!("computing the bounds for type parameter `{}`",
222 tcx.hir.ty_param_name(id))
226 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
227 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
228 format!("coherence checking all impls of trait `{}`",
229 tcx.item_path_str(def_id))
233 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
234 fn describe(_: TyCtxt, k: CrateNum) -> String {
235 format!("all inherent impls defined in crate `{:?}`", k)
239 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
240 fn describe(_: TyCtxt, _: CrateNum) -> String {
241 format!("check for overlap between inherent impls defined in this crate")
245 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
246 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
247 format!("generating MIR shim for `{}`",
248 tcx.item_path_str(def.def_id()))
252 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
253 fn describe(_: TyCtxt, _: CrateNum) -> String {
254 format!("privacy access levels")
258 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
259 fn describe(_: TyCtxt, _: CrateNum) -> String {
260 format!("type-checking all item bodies")
264 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
265 fn describe(_: TyCtxt, _: CrateNum) -> String {
266 format!("reachability")
270 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
271 fn describe(tcx: TyCtxt, (def_id, _): (DefId, &'tcx Substs<'tcx>)) -> String {
272 format!("const-evaluating `{}`",
273 tcx.item_path_str(def_id))
277 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
278 fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
279 format!("computing the symbol for `{}`", instance)
283 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
284 fn describe(_: TyCtxt, _: DefId) -> String {
289 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
290 fn describe(_: TyCtxt, _: DefId) -> String {
295 impl<'tcx> QueryDescription for queries::item_body_nested_bodies<'tcx> {
296 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
297 format!("nested item bodies of `{}`", tcx.item_path_str(def_id))
301 impl<'tcx> QueryDescription for queries::const_is_rvalue_promotable_to_static<'tcx> {
302 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
303 format!("const checking if rvalue is promotable to static `{}`",
304 tcx.item_path_str(def_id))
308 impl<'tcx> QueryDescription for queries::is_item_mir_available<'tcx> {
309 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
310 format!("checking if item is mir available: `{}`",
311 tcx.item_path_str(def_id))
315 macro_rules! define_maps {
318 [$($pub:tt)*] $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
319 pub struct Maps<$tcx> {
320 providers: IndexVec<CrateNum, Providers<$tcx>>,
321 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
322 $($(#[$attr])* $($pub)* $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
325 impl<$tcx> Maps<$tcx> {
326 pub fn new(dep_graph: DepGraph,
327 providers: IndexVec<CrateNum, Providers<$tcx>>)
331 query_stack: RefCell::new(vec![]),
332 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
338 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
339 pub enum Query<$tcx> {
340 $($(#[$attr])* $name($K)),*
343 impl<$tcx> Query<$tcx> {
344 pub fn describe(&self, tcx: TyCtxt) -> String {
346 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
352 use std::marker::PhantomData;
354 $(#[allow(bad_style)]
355 pub struct $name<$tcx> {
356 data: PhantomData<&$tcx ()>
360 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
365 fn to_dep_node(key: &$K) -> DepNode<DefId> {
366 use dep_graph::DepNode::*;
371 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
372 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
376 -> Result<R, CycleError<'a, $tcx>>
377 where F: FnOnce(&$V) -> R
379 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
384 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
385 return Ok(f(result));
388 // FIXME(eddyb) Get more valid Span's on queries.
389 // def_span guard is necesary to prevent a recursive loop,
390 // default_span calls def_span query internally.
391 if span == DUMMY_SP && stringify!($name) != "def_span" {
392 span = key.default_span(tcx)
395 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
397 let result = tcx.cycle_check(span, Query::$name(key), || {
398 let provider = tcx.maps.providers[key.map_crate()].$name;
399 provider(tcx.global_tcx(), key)
402 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
405 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
406 -> Result<$V, CycleError<'a, $tcx>> {
407 Self::try_get_with(tcx, span, key, Clone::clone)
410 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
411 // FIXME(eddyb) Move away from using `DepTrackingMap`
412 // so we don't have to explicitly ignore a false edge:
413 // we can't observe a value dependency, only side-effects,
414 // through `force`, and once everything has been updated,
415 // perhaps only diagnostics, if those, will remain.
416 let _ignore = tcx.dep_graph.in_ignore();
417 match Self::try_get_with(tcx, span, key, |_| ()) {
419 Err(e) => tcx.report_cycle(e)
424 #[derive(Copy, Clone)]
425 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
426 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
430 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
431 type Target = TyCtxt<'a, 'gcx, 'tcx>;
432 fn deref(&self) -> &Self::Target {
437 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
438 /// Return a transparent wrapper for `TyCtxt` which uses
439 /// `span` as the location of queries performed through it.
440 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
448 pub fn $name(self, key: $K) -> $V {
449 self.at(DUMMY_SP).$name(key)
453 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
455 pub fn $name(self, key: $K) -> $V {
456 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|e| {
457 self.report_cycle(e);
458 Value::from_cycle_error(self.global_tcx())
463 pub struct Providers<$tcx> {
464 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
467 impl<$tcx> Copy for Providers<$tcx> {}
468 impl<$tcx> Clone for Providers<$tcx> {
469 fn clone(&self) -> Self { *self }
472 impl<$tcx> Default for Providers<$tcx> {
473 fn default() -> Self {
474 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
475 bug!("tcx.maps.{}({:?}) unsupported by its crate",
476 stringify!($name), key);
478 Providers { $($name),* }
484 // Each of these maps also corresponds to a method on a
485 // `Provider` trait for requesting a value of that type,
486 // and a method on `Maps` itself for doing that in a
487 // a way that memoizes and does dep-graph tracking,
488 // wrapping around the actual chain of providers that
489 // the driver creates (using several `rustc_*` crates).
490 define_maps! { <'tcx>
491 /// Records the type of every item.
492 [] type_of: ItemSignature(DefId) -> Ty<'tcx>,
494 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
495 /// associated generics and predicates.
496 [] generics_of: ItemSignature(DefId) -> &'tcx ty::Generics,
497 [] predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
499 /// Maps from the def-id of a trait to the list of
500 /// super-predicates. This is a subset of the full list of
501 /// predicates. We store these in a separate map because we must
502 /// evaluate them even during type conversion, often before the
503 /// full predicates are available (note that supertraits have
504 /// additional acyclicity requirements).
505 [] super_predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
507 /// To avoid cycles within the predicates of a single item we compute
508 /// per-type-parameter predicates for resolving `T::AssocTy`.
509 [] type_param_predicates: TypeParamPredicates((DefId, DefId))
510 -> ty::GenericPredicates<'tcx>,
512 [] trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
513 [] adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
514 [] adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
515 [] adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
516 [] adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
518 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
519 [] is_foreign_item: IsForeignItem(DefId) -> bool,
521 /// Maps from def-id of a type or region parameter to its
522 /// (inferred) variance.
523 [pub] variances_of: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
525 /// Maps from an impl/trait def-id to a list of the def-ids of its items
526 [] associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
528 /// Maps from a trait item to the trait item "descriptor"
529 [] associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
531 [] impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
532 [] impl_polarity: ItemSignature(DefId) -> hir::ImplPolarity,
534 /// Maps a DefId of a type to a list of its inherent impls.
535 /// Contains implementations of methods that are inherent to a type.
536 /// Methods in these implementations don't need to be exported.
537 [] inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
539 /// Maps from the def-id of a function/method or const/static
540 /// to its MIR. Mutation is done at an item granularity to
541 /// allow MIR optimization passes to function and still
542 /// access cross-crate MIR (e.g. inlining or const eval).
544 /// Note that cross-crate MIR appears to be always borrowed
545 /// (in the `RefCell` sense) to prevent accidental mutation.
546 [pub] mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
548 /// Maps DefId's that have an associated Mir to the result
549 /// of the MIR qualify_consts pass. The actual meaning of
550 /// the value isn't known except to the pass itself.
551 [] mir_const_qualif: Mir(DefId) -> u8,
553 /// Records the type of each closure. The def ID is the ID of the
554 /// expression defining the closure.
555 [] closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
557 /// Records the type of each closure. The def ID is the ID of the
558 /// expression defining the closure.
559 [] closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
561 /// Caches CoerceUnsized kinds for impls on custom types.
562 [] coerce_unsized_info: ItemSignature(DefId)
563 -> ty::adjustment::CoerceUnsizedInfo,
565 [] typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
567 [] typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
569 [] has_typeck_tables: TypeckTables(DefId) -> bool,
571 [] coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
573 [] borrowck: BorrowCheck(DefId) -> (),
575 /// Gets a complete map from all types to their inherent impls.
576 /// Not meant to be used directly outside of coherence.
577 /// (Defined only for LOCAL_CRATE)
578 [] crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
580 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
581 /// Not meant to be used directly outside of coherence.
582 /// (Defined only for LOCAL_CRATE)
583 [] crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
585 /// Results of evaluating const items or constants embedded in
586 /// other items (such as enum variant explicit discriminants).
587 [] const_eval: const_eval_dep_node((DefId, &'tcx Substs<'tcx>))
588 -> const_val::EvalResult<'tcx>,
590 /// Performs the privacy check and computes "access levels".
591 [] privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
593 [] reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
595 [] mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>,
597 [] def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
598 [] symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
600 [] describe_def: DescribeDef(DefId) -> Option<Def>,
601 [] def_span: DefSpan(DefId) -> Span,
603 [] item_body_nested_bodies: metadata_dep_node(DefId) -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
604 [] const_is_rvalue_promotable_to_static: metadata_dep_node(DefId) -> bool,
605 [] is_item_mir_available: metadata_dep_node(DefId) -> bool,
608 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
609 DepNode::CoherenceCheckTrait(def_id)
612 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
616 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
617 DepNode::Reachability
620 fn metadata_dep_node(def_id: DefId) -> DepNode<DefId> {
621 DepNode::MetaData(def_id)
624 fn mir_shim_dep_node(instance: ty::InstanceDef) -> DepNode<DefId> {
628 fn symbol_name_dep_node(instance: ty::Instance) -> DepNode<DefId> {
629 // symbol_name uses the substs only to traverse them to find the
630 // hash, and that does not create any new dep-nodes.
631 DepNode::SymbolName(instance.def.def_id())
634 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
635 DepNode::TypeckBodiesKrate
638 fn const_eval_dep_node((def_id, _): (DefId, &Substs)) -> DepNode<DefId> {
639 DepNode::ConstEval(def_id)