]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/maps.rs
found the stack overflow culprit
[rust.git] / src / librustc / ty / maps.rs
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.
4 //
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.
10
11 use dep_graph::{DepGraph, DepNode, DepTrackingMap, DepTrackingMapConfig};
12 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
13 use hir::def::Def;
14 use hir;
15 use middle::const_val;
16 use middle::privacy::AccessLevels;
17 use mir;
18 use session::CompileResult;
19 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
20 use ty::subst::Substs;
21 use util::nodemap::NodeSet;
22
23 use rustc_data_structures::indexed_vec::IndexVec;
24 use std::cell::{RefCell, RefMut};
25 use std::ops::Deref;
26 use std::rc::Rc;
27 use syntax_pos::{Span, DUMMY_SP};
28 use syntax::symbol::Symbol;
29
30 trait Key {
31     fn map_crate(&self) -> CrateNum;
32     fn default_span(&self, tcx: TyCtxt) -> Span;
33 }
34
35 impl<'tcx> Key for ty::InstanceDef<'tcx> {
36     fn map_crate(&self) -> CrateNum {
37         LOCAL_CRATE
38     }
39
40     fn default_span(&self, tcx: TyCtxt) -> Span {
41         tcx.def_span(self.def_id())
42     }
43 }
44
45 impl<'tcx> Key for ty::Instance<'tcx> {
46     fn map_crate(&self) -> CrateNum {
47         LOCAL_CRATE
48     }
49
50     fn default_span(&self, tcx: TyCtxt) -> Span {
51         tcx.def_span(self.def_id())
52     }
53 }
54
55 impl Key for CrateNum {
56     fn map_crate(&self) -> CrateNum {
57         *self
58     }
59     fn default_span(&self, _: TyCtxt) -> Span {
60         DUMMY_SP
61     }
62 }
63
64 impl Key for DefId {
65     fn map_crate(&self) -> CrateNum {
66         self.krate
67     }
68     fn default_span(&self, tcx: TyCtxt) -> Span {
69         tcx.def_span(*self)
70     }
71 }
72
73 impl Key for (DefId, DefId) {
74     fn map_crate(&self) -> CrateNum {
75         self.0.krate
76     }
77     fn default_span(&self, tcx: TyCtxt) -> Span {
78         self.1.default_span(tcx)
79     }
80 }
81
82 impl Key for (CrateNum, DefId) {
83     fn map_crate(&self) -> CrateNum {
84         self.0
85     }
86     fn default_span(&self, tcx: TyCtxt) -> Span {
87         self.1.default_span(tcx)
88     }
89 }
90
91 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
92     fn map_crate(&self) -> CrateNum {
93         self.0.krate
94     }
95     fn default_span(&self, tcx: TyCtxt) -> Span {
96         self.0.default_span(tcx)
97     }
98 }
99
100 trait Value<'tcx>: Sized {
101     fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
102 }
103
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");
108     }
109 }
110
111 impl<'tcx, T: Default> Value<'tcx> for T {
112     default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
113         T::default()
114     }
115 }
116
117 impl<'tcx> Value<'tcx> for Ty<'tcx> {
118     fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
119         tcx.types.err
120     }
121 }
122
123 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
124     fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
125         Self::empty()
126     }
127 }
128
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() }
132     }
133 }
134
135 pub struct CycleError<'a, 'tcx: 'a> {
136     span: Span,
137     cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
138 }
139
140 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
141     pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
142         assert!(!cycle.is_empty());
143
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"));
147
148         err.span_note(cycle[0].0, &format!("the cycle begins when {}...",
149                                            cycle[0].1.describe(self)));
150
151         for &(span, ref query) in &cycle[1..] {
152             err.span_note(span, &format!("...which then requires {}...",
153                                          query.describe(self)));
154         }
155
156         err.note(&format!("...which then again requires {}, completing the cycle.",
157                           cycle[0].1.describe(self)));
158
159         err.emit();
160     }
161
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
165     {
166         {
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 {
171                     span: span,
172                     cycle: RefMut::map(stack, |stack| &mut stack[i..])
173                 });
174             }
175             stack.push((span, query));
176         }
177
178         let result = compute();
179
180         self.maps.query_stack.borrow_mut().pop();
181
182         Ok(result)
183     }
184 }
185
186 trait QueryDescription: DepTrackingMapConfig {
187     fn describe(tcx: TyCtxt, key: Self::Key) -> String;
188 }
189
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))
193     }
194 }
195
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))
200     }
201 }
202
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))
208     }
209 }
210
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))
215     }
216 }
217
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)
221     }
222 }
223
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")
227     }
228 }
229
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()))
234     }
235 }
236
237 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
238     fn describe(_: TyCtxt, _: CrateNum) -> String {
239         format!("privacy access levels")
240     }
241 }
242
243 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
244     fn describe(_: TyCtxt, _: CrateNum) -> String {
245         format!("type-checking all item bodies")
246     }
247 }
248
249 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
250     fn describe(_: TyCtxt, _: CrateNum) -> String {
251         format!("reachability")
252     }
253 }
254
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))
259     }
260 }
261
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)
265     }
266 }
267
268 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
269     fn describe(_: TyCtxt, _: DefId) -> String {
270         bug!("describe_def")
271     }
272 }
273
274 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
275     fn describe(_: TyCtxt, _: DefId) -> String {
276         bug!("def_span")
277     }
278 }
279
280 macro_rules! define_maps {
281     (<$tcx:tt>
282      $($(#[$attr:meta])*
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>>>),*
288         }
289
290         impl<$tcx> Maps<$tcx> {
291             pub fn new(dep_graph: DepGraph,
292                        providers: IndexVec<CrateNum, Providers<$tcx>>)
293                        -> Self {
294                 Maps {
295                     providers,
296                     query_stack: RefCell::new(vec![]),
297                     $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
298                 }
299             }
300         }
301
302         #[allow(bad_style)]
303         #[derive(Copy, Clone, Debug, PartialEq, Eq)]
304         pub enum Query<$tcx> {
305             $($(#[$attr])* $name($K)),*
306         }
307
308         impl<$tcx> Query<$tcx> {
309             pub fn describe(&self, tcx: TyCtxt) -> String {
310                 match *self {
311                     $(Query::$name(key) => queries::$name::describe(tcx, key)),*
312                 }
313             }
314         }
315
316         pub mod queries {
317             use std::marker::PhantomData;
318
319             $(#[allow(bad_style)]
320             pub struct $name<$tcx> {
321                 data: PhantomData<&$tcx ()>
322             })*
323         }
324
325         $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
326             type Key = $K;
327             type Value = $V;
328
329             #[allow(unused)]
330             fn to_dep_node(key: &$K) -> DepNode<DefId> {
331                 use dep_graph::DepNode::*;
332
333                 $node(*key)
334             }
335         }
336         impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
337             fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
338                                   mut span: Span,
339                                   key: $K,
340                                   f: F)
341                                   -> Result<R, CycleError<'a, $tcx>>
342                 where F: FnOnce(&$V) -> R
343             {
344                 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
345                     return Ok(f(result));
346                 }
347
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)
351                 }
352
353                 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
354
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)
358                 })?;
359
360                 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
361             }
362
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)
366             }
367
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, |_| ()) {
376                     Ok(()) => {}
377                     Err(e) => tcx.report_cycle(e)
378                 }
379             }
380         })*
381
382         #[derive(Copy, Clone)]
383         pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
384             pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
385             pub span: Span,
386         }
387
388         impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
389             type Target = TyCtxt<'a, 'gcx, 'tcx>;
390             fn deref(&self) -> &Self::Target {
391                 &self.tcx
392             }
393         }
394
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> {
399                 TyCtxtAt {
400                     tcx: self,
401                     span
402                 }
403             }
404
405             $($(#[$attr])*
406             pub fn $name(self, key: $K) -> $V {
407                 self.at(DUMMY_SP).$name(key)
408             })*
409         }
410
411         impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
412             $($(#[$attr])*
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())
417                 })
418             })*
419         }
420
421         pub struct Providers<$tcx> {
422             $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
423         }
424
425         impl<$tcx> Copy for Providers<$tcx> {}
426         impl<$tcx> Clone for Providers<$tcx> {
427             fn clone(&self) -> Self { *self }
428         }
429
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);
435                 })*
436                 Providers { $($name),* }
437             }
438         }
439     }
440 }
441
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>,
451
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>,
456
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>,
464
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>,
469
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>,
475
476     /// True if this is a foreign item (i.e., linked via `extern { ... }`).
477     pub is_foreign_item: IsForeignItem(DefId) -> bool,
478
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>>,
482
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>>,
485
486     /// Maps from a trait item to the trait item "descriptor"
487     pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
488
489     pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
490     pub impl_polarity: ItemSignature(DefId) -> hir::ImplPolarity,
491
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>>,
496
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).
501     ///
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>>,
505
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,
510
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,
514
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>,
518
519     /// Caches CoerceUnsized kinds for impls on custom types.
520     pub coerce_unsized_info: ItemSignature(DefId)
521         -> ty::adjustment::CoerceUnsizedInfo,
522
523     pub typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
524
525     pub typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
526
527     pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
528
529     pub borrowck: BorrowCheck(DefId) -> (),
530
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,
535
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) -> (),
540
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>,
545
546     /// Performs the privacy check and computes "access levels".
547     pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
548
549     pub reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
550
551     pub mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>,
552
553     pub def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
554     pub symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
555
556     pub describe_def: MetaData(DefId) -> Option<Def>,
557     pub def_span: MetaData(DefId) -> Span
558 }
559
560 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
561     DepNode::CoherenceCheckTrait(def_id)
562 }
563
564 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
565     DepNode::Coherence
566 }
567
568 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
569     DepNode::Reachability
570 }
571
572 fn mir_shim_dep_node(instance: ty::InstanceDef) -> DepNode<DefId> {
573     instance.dep_node()
574 }
575
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())
580 }
581
582 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
583     DepNode::TypeckBodiesKrate
584 }
585
586 fn const_eval_dep_node((def_id, _): (DefId, &Substs)) -> DepNode<DefId> {
587     DepNode::ConstEval(def_id)
588 }