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;
17 use middle::region::RegionMaps;
19 use session::CompileResult;
20 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
22 use ty::subst::Substs;
23 use util::nodemap::NodeSet;
25 use rustc_data_structures::indexed_vec::IndexVec;
26 use std::cell::{RefCell, RefMut};
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::region_resolve_crate<'tcx> {
296 fn describe(_: TyCtxt, _: CrateNum) -> String {
297 format!("resolve crate")
301 macro_rules! define_maps {
304 [$($pub:tt)*] $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
305 pub struct Maps<$tcx> {
306 providers: IndexVec<CrateNum, Providers<$tcx>>,
307 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
308 $($(#[$attr])* $($pub)* $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
311 impl<$tcx> Maps<$tcx> {
312 pub fn new(dep_graph: DepGraph,
313 providers: IndexVec<CrateNum, Providers<$tcx>>)
317 query_stack: RefCell::new(vec![]),
318 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
324 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
325 pub enum Query<$tcx> {
326 $($(#[$attr])* $name($K)),*
329 impl<$tcx> Query<$tcx> {
330 pub fn describe(&self, tcx: TyCtxt) -> String {
332 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
338 use std::marker::PhantomData;
340 $(#[allow(bad_style)]
341 pub struct $name<$tcx> {
342 data: PhantomData<&$tcx ()>
346 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
351 fn to_dep_node(key: &$K) -> DepNode<DefId> {
352 use dep_graph::DepNode::*;
357 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
358 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
362 -> Result<R, CycleError<'a, $tcx>>
363 where F: FnOnce(&$V) -> R
365 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
370 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
371 return Ok(f(result));
374 // FIXME(eddyb) Get more valid Span's on queries.
375 // def_span guard is necesary to prevent a recursive loop,
376 // default_span calls def_span query internally.
377 if span == DUMMY_SP && stringify!($name) != "def_span" {
378 span = key.default_span(tcx)
381 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
383 let result = tcx.cycle_check(span, Query::$name(key), || {
384 let provider = tcx.maps.providers[key.map_crate()].$name;
385 provider(tcx.global_tcx(), key)
388 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
391 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
392 -> Result<$V, CycleError<'a, $tcx>> {
393 Self::try_get_with(tcx, span, key, Clone::clone)
396 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
397 // FIXME(eddyb) Move away from using `DepTrackingMap`
398 // so we don't have to explicitly ignore a false edge:
399 // we can't observe a value dependency, only side-effects,
400 // through `force`, and once everything has been updated,
401 // perhaps only diagnostics, if those, will remain.
402 let _ignore = tcx.dep_graph.in_ignore();
403 match Self::try_get_with(tcx, span, key, |_| ()) {
405 Err(e) => tcx.report_cycle(e)
410 #[derive(Copy, Clone)]
411 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
412 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
416 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
417 type Target = TyCtxt<'a, 'gcx, 'tcx>;
418 fn deref(&self) -> &Self::Target {
423 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
424 /// Return a transparent wrapper for `TyCtxt` which uses
425 /// `span` as the location of queries performed through it.
426 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
434 pub fn $name(self, key: $K) -> $V {
435 self.at(DUMMY_SP).$name(key)
439 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
441 pub fn $name(self, key: $K) -> $V {
442 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|e| {
443 self.report_cycle(e);
444 Value::from_cycle_error(self.global_tcx())
449 pub struct Providers<$tcx> {
450 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
453 impl<$tcx> Copy for Providers<$tcx> {}
454 impl<$tcx> Clone for Providers<$tcx> {
455 fn clone(&self) -> Self { *self }
458 impl<$tcx> Default for Providers<$tcx> {
459 fn default() -> Self {
460 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
461 bug!("tcx.maps.{}({:?}) unsupported by its crate",
462 stringify!($name), key);
464 Providers { $($name),* }
470 // Each of these maps also corresponds to a method on a
471 // `Provider` trait for requesting a value of that type,
472 // and a method on `Maps` itself for doing that in a
473 // a way that memoizes and does dep-graph tracking,
474 // wrapping around the actual chain of providers that
475 // the driver creates (using several `rustc_*` crates).
476 define_maps! { <'tcx>
477 /// Records the type of every item.
478 [] type_of: ItemSignature(DefId) -> Ty<'tcx>,
480 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
481 /// associated generics and predicates.
482 [] generics_of: ItemSignature(DefId) -> &'tcx ty::Generics,
483 [] predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
485 /// Maps from the def-id of a trait to the list of
486 /// super-predicates. This is a subset of the full list of
487 /// predicates. We store these in a separate map because we must
488 /// evaluate them even during type conversion, often before the
489 /// full predicates are available (note that supertraits have
490 /// additional acyclicity requirements).
491 [] super_predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
493 /// To avoid cycles within the predicates of a single item we compute
494 /// per-type-parameter predicates for resolving `T::AssocTy`.
495 [] type_param_predicates: TypeParamPredicates((DefId, DefId))
496 -> ty::GenericPredicates<'tcx>,
498 [] trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
499 [] adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
500 [] adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
501 [] adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
502 [] adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
504 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
505 [] is_foreign_item: IsForeignItem(DefId) -> bool,
507 /// Maps from def-id of a type or region parameter to its
508 /// (inferred) variance.
509 [pub] variances_of: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
511 /// Maps from an impl/trait def-id to a list of the def-ids of its items
512 [] associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
514 /// Maps from a trait item to the trait item "descriptor"
515 [] associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
517 [] impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
518 [] impl_polarity: ItemSignature(DefId) -> hir::ImplPolarity,
520 /// Maps a DefId of a type to a list of its inherent impls.
521 /// Contains implementations of methods that are inherent to a type.
522 /// Methods in these implementations don't need to be exported.
523 [] inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
525 /// Maps from the def-id of a function/method or const/static
526 /// to its MIR. Mutation is done at an item granularity to
527 /// allow MIR optimization passes to function and still
528 /// access cross-crate MIR (e.g. inlining or const eval).
530 /// Note that cross-crate MIR appears to be always borrowed
531 /// (in the `RefCell` sense) to prevent accidental mutation.
532 [pub] mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
534 /// Maps DefId's that have an associated Mir to the result
535 /// of the MIR qualify_consts pass. The actual meaning of
536 /// the value isn't known except to the pass itself.
537 [] mir_const_qualif: Mir(DefId) -> u8,
539 /// Records the type of each closure. The def ID is the ID of the
540 /// expression defining the closure.
541 [] closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
543 /// Records the type of each closure. The def ID is the ID of the
544 /// expression defining the closure.
545 [] closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
547 /// Caches CoerceUnsized kinds for impls on custom types.
548 [] coerce_unsized_info: ItemSignature(DefId)
549 -> ty::adjustment::CoerceUnsizedInfo,
551 [] typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
553 [] typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
555 [] has_typeck_tables: TypeckTables(DefId) -> bool,
557 [] coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
559 [] borrowck: BorrowCheck(DefId) -> (),
561 /// Gets a complete map from all types to their inherent impls.
562 /// Not meant to be used directly outside of coherence.
563 /// (Defined only for LOCAL_CRATE)
564 [] crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
566 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
567 /// Not meant to be used directly outside of coherence.
568 /// (Defined only for LOCAL_CRATE)
569 [] crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
571 /// Results of evaluating const items or constants embedded in
572 /// other items (such as enum variant explicit discriminants).
573 [] const_eval: const_eval_dep_node((DefId, &'tcx Substs<'tcx>))
574 -> const_val::EvalResult<'tcx>,
576 /// Performs the privacy check and computes "access levels".
577 [] privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
579 [] reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
581 [] region_resolve_crate: region_resolve_crate_dep_node(CrateNum) -> Rc<RegionMaps<'tcx>>,
583 [] mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>,
585 [] def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
586 [] symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
588 [] describe_def: DescribeDef(DefId) -> Option<Def>,
589 [] def_span: DefSpan(DefId) -> Span
592 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
593 DepNode::CoherenceCheckTrait(def_id)
596 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
600 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
601 DepNode::Reachability
604 fn region_resolve_crate_dep_node(_: CrateNum) -> DepNode<DefId> {
605 DepNode::RegionResolveCrate
608 fn mir_shim_dep_node(instance: ty::InstanceDef) -> DepNode<DefId> {
612 fn symbol_name_dep_node(instance: ty::Instance) -> DepNode<DefId> {
613 // symbol_name uses the substs only to traverse them to find the
614 // hash, and that does not create any new dep-nodes.
615 DepNode::SymbolName(instance.def.def_id())
618 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
619 DepNode::TypeckBodiesKrate
622 fn const_eval_dep_node((def_id, _): (DefId, &Substs)) -> DepNode<DefId> {
623 DepNode::ConstEval(def_id)