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};
29 use syntax_pos::{Span, DUMMY_SP};
30 use syntax::symbol::Symbol;
33 fn map_crate(&self) -> CrateNum;
34 fn default_span(&self, tcx: TyCtxt) -> Span;
37 impl<'tcx> Key for ty::InstanceDef<'tcx> {
38 fn map_crate(&self) -> CrateNum {
42 fn default_span(&self, tcx: TyCtxt) -> Span {
43 tcx.def_span(self.def_id())
47 impl<'tcx> Key for ty::Instance<'tcx> {
48 fn map_crate(&self) -> CrateNum {
52 fn default_span(&self, tcx: TyCtxt) -> Span {
53 tcx.def_span(self.def_id())
57 impl Key for CrateNum {
58 fn map_crate(&self) -> CrateNum {
61 fn default_span(&self, _: TyCtxt) -> Span {
67 fn map_crate(&self) -> CrateNum {
70 fn default_span(&self, tcx: TyCtxt) -> Span {
75 impl Key for (DefId, DefId) {
76 fn map_crate(&self) -> CrateNum {
79 fn default_span(&self, tcx: TyCtxt) -> Span {
80 self.1.default_span(tcx)
84 impl Key for (CrateNum, DefId) {
85 fn map_crate(&self) -> CrateNum {
88 fn default_span(&self, tcx: TyCtxt) -> Span {
89 self.1.default_span(tcx)
93 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
94 fn map_crate(&self) -> CrateNum {
97 fn default_span(&self, tcx: TyCtxt) -> Span {
98 self.0.default_span(tcx)
102 trait Value<'tcx>: Sized {
103 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
106 impl<'tcx, T> Value<'tcx> for T {
107 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
108 tcx.sess.abort_if_errors();
109 bug!("Value::from_cycle_error called without errors");
113 impl<'tcx, T: Default> Value<'tcx> for T {
114 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
119 impl<'tcx> Value<'tcx> for Ty<'tcx> {
120 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
125 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
126 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
131 impl<'tcx> Value<'tcx> for ty::SymbolName {
132 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
133 ty::SymbolName { name: Symbol::intern("<error>").as_str() }
137 pub struct CycleError<'a, 'tcx: 'a> {
139 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
142 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
143 pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
144 // Subtle: release the refcell lock before invoking `describe()`
145 // below by dropping `cycle`.
146 let stack = cycle.to_vec();
149 assert!(!stack.is_empty());
151 // Disable naming impls with types in this path, since that
152 // sometimes cycles itself, leading to extra cycle errors.
153 // (And cycle errors around impls tend to occur during the
154 // collect/coherence phases anyhow.)
155 item_path::with_forced_impl_filename_line(|| {
157 struct_span_err!(self.sess, span, E0391,
158 "unsupported cyclic reference between types/traits detected");
159 err.span_label(span, &format!("cyclic reference"));
161 err.span_note(stack[0].0, &format!("the cycle begins when {}...",
162 stack[0].1.describe(self)));
164 for &(span, ref query) in &stack[1..] {
165 err.span_note(span, &format!("...which then requires {}...",
166 query.describe(self)));
169 err.note(&format!("...which then again requires {}, completing the cycle.",
170 stack[0].1.describe(self)));
176 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
177 -> Result<R, CycleError<'a, 'gcx>>
178 where F: FnOnce() -> R
181 let mut stack = self.maps.query_stack.borrow_mut();
182 if let Some((i, _)) = stack.iter().enumerate().rev()
183 .find(|&(_, &(_, ref q))| *q == query) {
184 return Err(CycleError {
186 cycle: RefMut::map(stack, |stack| &mut stack[i..])
189 stack.push((span, query));
192 let result = compute();
194 self.maps.query_stack.borrow_mut().pop();
200 trait QueryDescription: DepTrackingMapConfig {
201 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
204 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
205 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
206 format!("processing `{}`", tcx.item_path_str(def_id))
210 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
211 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
212 format!("computing the supertraits of `{}`",
213 tcx.item_path_str(def_id))
217 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
218 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
219 let id = tcx.hir.as_local_node_id(def_id).unwrap();
220 format!("computing the bounds for type parameter `{}`",
221 tcx.hir.ty_param_name(id))
225 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
226 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
227 format!("coherence checking all impls of trait `{}`",
228 tcx.item_path_str(def_id))
232 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
233 fn describe(_: TyCtxt, k: CrateNum) -> String {
234 format!("all inherent impls defined in crate `{:?}`", k)
238 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
239 fn describe(_: TyCtxt, _: CrateNum) -> String {
240 format!("check for overlap between inherent impls defined in this crate")
244 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
245 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
246 format!("generating MIR shim for `{}`",
247 tcx.item_path_str(def.def_id()))
251 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
252 fn describe(_: TyCtxt, _: CrateNum) -> String {
253 format!("privacy access levels")
257 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
258 fn describe(_: TyCtxt, _: CrateNum) -> String {
259 format!("type-checking all item bodies")
263 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
264 fn describe(_: TyCtxt, _: CrateNum) -> String {
265 format!("reachability")
269 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
270 fn describe(tcx: TyCtxt, (def_id, _): (DefId, &'tcx Substs<'tcx>)) -> String {
271 format!("const-evaluating `{}`",
272 tcx.item_path_str(def_id))
276 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
277 fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
278 format!("computing the symbol for `{}`", instance)
282 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
283 fn describe(_: TyCtxt, _: DefId) -> String {
288 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
289 fn describe(_: TyCtxt, _: DefId) -> String {
294 macro_rules! define_maps {
297 [$($pub:tt)*] $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
298 pub struct Maps<$tcx> {
299 providers: IndexVec<CrateNum, Providers<$tcx>>,
300 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
301 $($(#[$attr])* $($pub)* $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
304 impl<$tcx> Maps<$tcx> {
305 pub fn new(dep_graph: DepGraph,
306 providers: IndexVec<CrateNum, Providers<$tcx>>)
310 query_stack: RefCell::new(vec![]),
311 $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
317 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
318 pub enum Query<$tcx> {
319 $($(#[$attr])* $name($K)),*
322 impl<$tcx> Query<$tcx> {
323 pub fn describe(&self, tcx: TyCtxt) -> String {
325 $(Query::$name(key) => queries::$name::describe(tcx, key)),*
331 use std::marker::PhantomData;
333 $(#[allow(bad_style)]
334 pub struct $name<$tcx> {
335 data: PhantomData<&$tcx ()>
339 $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
344 fn to_dep_node(key: &$K) -> DepNode<DefId> {
345 use dep_graph::DepNode::*;
350 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
351 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
355 -> Result<R, CycleError<'a, $tcx>>
356 where F: FnOnce(&$V) -> R
358 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
363 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
364 return Ok(f(result));
367 // FIXME(eddyb) Get more valid Span's on queries.
368 // def_span guard is necesary to prevent a recursive loop,
369 // default_span calls def_span query internally.
370 if span == DUMMY_SP && stringify!($name) != "def_span" {
371 span = key.default_span(tcx)
374 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
376 let result = tcx.cycle_check(span, Query::$name(key), || {
377 let provider = tcx.maps.providers[key.map_crate()].$name;
378 provider(tcx.global_tcx(), key)
381 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
384 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
385 -> Result<$V, CycleError<'a, $tcx>> {
386 Self::try_get_with(tcx, span, key, Clone::clone)
389 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
390 // FIXME(eddyb) Move away from using `DepTrackingMap`
391 // so we don't have to explicitly ignore a false edge:
392 // we can't observe a value dependency, only side-effects,
393 // through `force`, and once everything has been updated,
394 // perhaps only diagnostics, if those, will remain.
395 let _ignore = tcx.dep_graph.in_ignore();
396 match Self::try_get_with(tcx, span, key, |_| ()) {
398 Err(e) => tcx.report_cycle(e)
403 #[derive(Copy, Clone)]
404 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
405 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
409 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
410 type Target = TyCtxt<'a, 'gcx, 'tcx>;
411 fn deref(&self) -> &Self::Target {
416 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
417 /// Return a transparent wrapper for `TyCtxt` which uses
418 /// `span` as the location of queries performed through it.
419 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
427 pub fn $name(self, key: $K) -> $V {
428 self.at(DUMMY_SP).$name(key)
432 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
434 pub fn $name(self, key: $K) -> $V {
435 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|e| {
436 self.report_cycle(e);
437 Value::from_cycle_error(self.global_tcx())
442 pub struct Providers<$tcx> {
443 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
446 impl<$tcx> Copy for Providers<$tcx> {}
447 impl<$tcx> Clone for Providers<$tcx> {
448 fn clone(&self) -> Self { *self }
451 impl<$tcx> Default for Providers<$tcx> {
452 fn default() -> Self {
453 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
454 bug!("tcx.maps.{}({:?}) unsupported by its crate",
455 stringify!($name), key);
457 Providers { $($name),* }
463 // Each of these maps also corresponds to a method on a
464 // `Provider` trait for requesting a value of that type,
465 // and a method on `Maps` itself for doing that in a
466 // a way that memoizes and does dep-graph tracking,
467 // wrapping around the actual chain of providers that
468 // the driver creates (using several `rustc_*` crates).
469 define_maps! { <'tcx>
470 /// Records the type of every item.
471 [] type_of: ItemSignature(DefId) -> Ty<'tcx>,
473 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
474 /// associated generics and predicates.
475 [] generics_of: ItemSignature(DefId) -> &'tcx ty::Generics,
476 [] predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
478 /// Maps from the def-id of a trait to the list of
479 /// super-predicates. This is a subset of the full list of
480 /// predicates. We store these in a separate map because we must
481 /// evaluate them even during type conversion, often before the
482 /// full predicates are available (note that supertraits have
483 /// additional acyclicity requirements).
484 [] super_predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
486 /// To avoid cycles within the predicates of a single item we compute
487 /// per-type-parameter predicates for resolving `T::AssocTy`.
488 [] type_param_predicates: TypeParamPredicates((DefId, DefId))
489 -> ty::GenericPredicates<'tcx>,
491 [] trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
492 [] adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
493 [] adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
494 [] adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
495 [] adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
497 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
498 [] is_foreign_item: IsForeignItem(DefId) -> bool,
500 /// Maps from def-id of a type or region parameter to its
501 /// (inferred) variance.
502 [pub] variances_of: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
504 /// Maps from an impl/trait def-id to a list of the def-ids of its items
505 [] associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
507 /// Maps from a trait item to the trait item "descriptor"
508 [] associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
510 [] impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
511 [] impl_polarity: ItemSignature(DefId) -> hir::ImplPolarity,
513 /// Maps a DefId of a type to a list of its inherent impls.
514 /// Contains implementations of methods that are inherent to a type.
515 /// Methods in these implementations don't need to be exported.
516 [] inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
518 /// Maps from the def-id of a function/method or const/static
519 /// to its MIR. Mutation is done at an item granularity to
520 /// allow MIR optimization passes to function and still
521 /// access cross-crate MIR (e.g. inlining or const eval).
523 /// Note that cross-crate MIR appears to be always borrowed
524 /// (in the `RefCell` sense) to prevent accidental mutation.
525 [pub] mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
527 /// Maps DefId's that have an associated Mir to the result
528 /// of the MIR qualify_consts pass. The actual meaning of
529 /// the value isn't known except to the pass itself.
530 [] mir_const_qualif: Mir(DefId) -> u8,
532 /// Records the type of each closure. The def ID is the ID of the
533 /// expression defining the closure.
534 [] closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
536 /// Records the type of each closure. The def ID is the ID of the
537 /// expression defining the closure.
538 [] closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
540 /// Caches CoerceUnsized kinds for impls on custom types.
541 [] coerce_unsized_info: ItemSignature(DefId)
542 -> ty::adjustment::CoerceUnsizedInfo,
544 [] typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
546 [] typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
548 [] has_typeck_tables: TypeckTables(DefId) -> bool,
550 [] coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
552 [] borrowck: BorrowCheck(DefId) -> (),
554 /// Gets a complete map from all types to their inherent impls.
555 /// Not meant to be used directly outside of coherence.
556 /// (Defined only for LOCAL_CRATE)
557 [] crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
559 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
560 /// Not meant to be used directly outside of coherence.
561 /// (Defined only for LOCAL_CRATE)
562 [] crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
564 /// Results of evaluating const items or constants embedded in
565 /// other items (such as enum variant explicit discriminants).
566 [] const_eval: const_eval_dep_node((DefId, &'tcx Substs<'tcx>))
567 -> const_val::EvalResult<'tcx>,
569 /// Performs the privacy check and computes "access levels".
570 [] privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
572 [] reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
574 [] mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>,
576 [] def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
577 [] symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
579 [] describe_def: DescribeDef(DefId) -> Option<Def>,
580 [] def_span: DefSpan(DefId) -> Span
583 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
584 DepNode::CoherenceCheckTrait(def_id)
587 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
591 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
592 DepNode::Reachability
595 fn mir_shim_dep_node(instance: ty::InstanceDef) -> DepNode<DefId> {
599 fn symbol_name_dep_node(instance: ty::Instance) -> DepNode<DefId> {
600 // symbol_name uses the substs only to traverse them to find the
601 // hash, and that does not create any new dep-nodes.
602 DepNode::SymbolName(instance.def.def_id())
605 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
606 DepNode::TypeckBodiesKrate
609 fn const_eval_dep_node((def_id, _): (DefId, &Substs)) -> DepNode<DefId> {
610 DepNode::ConstEval(def_id)