]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/maps.rs
Auto merge of #40867 - alexcrichton:rollup, r=alexcrichton
[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 middle::const_val::ConstVal;
14 use middle::privacy::AccessLevels;
15 use mir;
16 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
17
18 use rustc_data_structures::indexed_vec::IndexVec;
19 use std::cell::{RefCell, RefMut};
20 use std::rc::Rc;
21 use syntax_pos::{Span, DUMMY_SP};
22
23 trait Key {
24     fn map_crate(&self) -> CrateNum;
25     fn default_span(&self, tcx: TyCtxt) -> Span;
26 }
27
28 impl<'tcx> Key for ty::InstanceDef<'tcx> {
29     fn map_crate(&self) -> CrateNum {
30         LOCAL_CRATE
31     }
32
33     fn default_span(&self, tcx: TyCtxt) -> Span {
34         tcx.def_span(self.def_id())
35     }
36 }
37
38 impl Key for CrateNum {
39     fn map_crate(&self) -> CrateNum {
40         *self
41     }
42     fn default_span(&self, _: TyCtxt) -> Span {
43         DUMMY_SP
44     }
45 }
46
47 impl Key for DefId {
48     fn map_crate(&self) -> CrateNum {
49         self.krate
50     }
51     fn default_span(&self, tcx: TyCtxt) -> Span {
52         tcx.def_span(*self)
53     }
54 }
55
56 impl Key for (DefId, DefId) {
57     fn map_crate(&self) -> CrateNum {
58         self.0.krate
59     }
60     fn default_span(&self, tcx: TyCtxt) -> Span {
61         self.1.default_span(tcx)
62     }
63 }
64
65 impl Key for (CrateNum, DefId) {
66     fn map_crate(&self) -> CrateNum {
67         self.0
68     }
69     fn default_span(&self, tcx: TyCtxt) -> Span {
70         self.1.default_span(tcx)
71     }
72 }
73
74 trait Value<'tcx>: Sized {
75     fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
76 }
77
78 impl<'tcx, T> Value<'tcx> for T {
79     default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
80         tcx.sess.abort_if_errors();
81         bug!("Value::from_cycle_error called without errors");
82     }
83 }
84
85 impl<'tcx, T: Default> Value<'tcx> for T {
86     default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
87         T::default()
88     }
89 }
90
91 impl<'tcx> Value<'tcx> for Ty<'tcx> {
92     fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
93         tcx.types.err
94     }
95 }
96
97 pub struct CycleError<'a, 'tcx: 'a> {
98     span: Span,
99     cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
100 }
101
102 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
103     pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
104         assert!(!cycle.is_empty());
105
106         let mut err = struct_span_err!(self.sess, span, E0391,
107             "unsupported cyclic reference between types/traits detected");
108         err.span_label(span, &format!("cyclic reference"));
109
110         err.span_note(cycle[0].0, &format!("the cycle begins when {}...",
111                                            cycle[0].1.describe(self)));
112
113         for &(span, ref query) in &cycle[1..] {
114             err.span_note(span, &format!("...which then requires {}...",
115                                          query.describe(self)));
116         }
117
118         err.note(&format!("...which then again requires {}, completing the cycle.",
119                           cycle[0].1.describe(self)));
120
121         err.emit();
122     }
123
124     fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
125                          -> Result<R, CycleError<'a, 'gcx>>
126         where F: FnOnce() -> R
127     {
128         {
129             let mut stack = self.maps.query_stack.borrow_mut();
130             if let Some((i, _)) = stack.iter().enumerate().rev()
131                                        .find(|&(_, &(_, ref q))| *q == query) {
132                 return Err(CycleError {
133                     span: span,
134                     cycle: RefMut::map(stack, |stack| &mut stack[i..])
135                 });
136             }
137             stack.push((span, query));
138         }
139
140         let result = compute();
141
142         self.maps.query_stack.borrow_mut().pop();
143
144         Ok(result)
145     }
146 }
147
148 trait QueryDescription: DepTrackingMapConfig {
149     fn describe(tcx: TyCtxt, key: Self::Key) -> String;
150 }
151
152 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
153     default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
154         format!("processing `{}`", tcx.item_path_str(def_id))
155     }
156 }
157
158 impl<'tcx> QueryDescription for queries::super_predicates<'tcx> {
159     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
160         format!("computing the supertraits of `{}`",
161                 tcx.item_path_str(def_id))
162     }
163 }
164
165 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
166     fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
167         let id = tcx.hir.as_local_node_id(def_id).unwrap();
168         format!("computing the bounds for type parameter `{}`",
169                 tcx.hir.ty_param_name(id))
170     }
171 }
172
173 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
174     fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
175         format!("coherence checking all impls of trait `{}`",
176                 tcx.item_path_str(def_id))
177     }
178 }
179
180 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
181     fn describe(_: TyCtxt, k: CrateNum) -> String {
182         format!("all inherent impls defined in crate `{:?}`", k)
183     }
184 }
185
186 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
187     fn describe(_: TyCtxt, _: CrateNum) -> String {
188         format!("check for overlap between inherent impls defined in this crate")
189     }
190 }
191
192 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
193     fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
194         format!("generating MIR shim for `{}`",
195                 tcx.item_path_str(def.def_id()))
196     }
197 }
198
199 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
200     fn describe(_: TyCtxt, _: CrateNum) -> String {
201         format!("privacy access levels")
202     }
203 }
204
205 macro_rules! define_maps {
206     (<$tcx:tt>
207      $($(#[$attr:meta])*
208        pub $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
209         pub struct Maps<$tcx> {
210             providers: IndexVec<CrateNum, Providers<$tcx>>,
211             query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
212             $($(#[$attr])* pub $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
213         }
214
215         impl<$tcx> Maps<$tcx> {
216             pub fn new(dep_graph: DepGraph,
217                        providers: IndexVec<CrateNum, Providers<$tcx>>)
218                        -> Self {
219                 Maps {
220                     providers,
221                     query_stack: RefCell::new(vec![]),
222                     $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
223                 }
224             }
225         }
226
227         #[allow(bad_style)]
228         #[derive(Copy, Clone, Debug, PartialEq, Eq)]
229         pub enum Query<$tcx> {
230             $($(#[$attr])* $name($K)),*
231         }
232
233         impl<$tcx> Query<$tcx> {
234             pub fn describe(&self, tcx: TyCtxt) -> String {
235                 match *self {
236                     $(Query::$name(key) => queries::$name::describe(tcx, key)),*
237                 }
238             }
239         }
240
241         pub mod queries {
242             use std::marker::PhantomData;
243
244             $(#[allow(bad_style)]
245             pub struct $name<$tcx> {
246                 data: PhantomData<&$tcx ()>
247             })*
248         }
249
250         $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
251             type Key = $K;
252             type Value = $V;
253
254             #[allow(unused)]
255             fn to_dep_node(key: &$K) -> DepNode<DefId> {
256                 use dep_graph::DepNode::*;
257
258                 $node(*key)
259             }
260         }
261         impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
262             fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
263                                   mut span: Span,
264                                   key: $K,
265                                   f: F)
266                                   -> Result<R, CycleError<'a, $tcx>>
267                 where F: FnOnce(&$V) -> R
268             {
269                 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
270                     return Ok(f(result));
271                 }
272
273                 // FIXME(eddyb) Get more valid Span's on queries.
274                 if span == DUMMY_SP {
275                     span = key.default_span(tcx);
276                 }
277
278                 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
279
280                 let result = tcx.cycle_check(span, Query::$name(key), || {
281                     let provider = tcx.maps.providers[key.map_crate()].$name;
282                     provider(tcx.global_tcx(), key)
283                 })?;
284
285                 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
286             }
287
288             pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
289                            -> Result<$V, CycleError<'a, $tcx>> {
290                 Self::try_get_with(tcx, span, key, Clone::clone)
291             }
292
293             $(#[$attr])*
294             pub fn get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) -> $V {
295                 Self::try_get(tcx, span, key).unwrap_or_else(|e| {
296                     tcx.report_cycle(e);
297                     Value::from_cycle_error(tcx.global_tcx())
298                 })
299             }
300
301             pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
302                 // FIXME(eddyb) Move away from using `DepTrackingMap`
303                 // so we don't have to explicitly ignore a false edge:
304                 // we can't observe a value dependency, only side-effects,
305                 // through `force`, and once everything has been updated,
306                 // perhaps only diagnostics, if those, will remain.
307                 let _ignore = tcx.dep_graph.in_ignore();
308                 match Self::try_get_with(tcx, span, key, |_| ()) {
309                     Ok(()) => {}
310                     Err(e) => tcx.report_cycle(e)
311                 }
312             }
313         })*
314
315         pub struct Providers<$tcx> {
316             $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
317         }
318
319         impl<$tcx> Copy for Providers<$tcx> {}
320         impl<$tcx> Clone for Providers<$tcx> {
321             fn clone(&self) -> Self { *self }
322         }
323
324         impl<$tcx> Default for Providers<$tcx> {
325             fn default() -> Self {
326                 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
327                     bug!("tcx.maps.{}({:?}) unsupported by its crate",
328                          stringify!($name), key);
329                 })*
330                 Providers { $($name),* }
331             }
332         }
333     }
334 }
335
336 // Each of these maps also corresponds to a method on a
337 // `Provider` trait for requesting a value of that type,
338 // and a method on `Maps` itself for doing that in a
339 // a way that memoizes and does dep-graph tracking,
340 // wrapping around the actual chain of providers that
341 // the driver creates (using several `rustc_*` crates).
342 define_maps! { <'tcx>
343     /// Records the type of every item.
344     pub ty: ItemSignature(DefId) -> Ty<'tcx>,
345
346     /// Maps from the def-id of an item (trait/struct/enum/fn) to its
347     /// associated generics and predicates.
348     pub generics: ItemSignature(DefId) -> &'tcx ty::Generics,
349     pub predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
350
351     /// Maps from the def-id of a trait to the list of
352     /// super-predicates. This is a subset of the full list of
353     /// predicates. We store these in a separate map because we must
354     /// evaluate them even during type conversion, often before the
355     /// full predicates are available (note that supertraits have
356     /// additional acyclicity requirements).
357     pub super_predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
358
359     /// To avoid cycles within the predicates of a single item we compute
360     /// per-type-parameter predicates for resolving `T::AssocTy`.
361     pub type_param_predicates: TypeParamPredicates((DefId, DefId))
362         -> ty::GenericPredicates<'tcx>,
363
364     pub trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
365     pub adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
366     pub adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
367     pub adt_sized_constraint: SizedConstraint(DefId) -> Ty<'tcx>,
368
369     /// Maps from def-id of a type or region parameter to its
370     /// (inferred) variance.
371     pub variances: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
372
373     /// Maps from an impl/trait def-id to a list of the def-ids of its items
374     pub associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
375
376     /// Maps from a trait item to the trait item "descriptor"
377     pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
378
379     pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
380
381     /// Maps a DefId of a type to a list of its inherent impls.
382     /// Contains implementations of methods that are inherent to a type.
383     /// Methods in these implementations don't need to be exported.
384     pub inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
385
386     /// Maps from the def-id of a function/method or const/static
387     /// to its MIR. Mutation is done at an item granularity to
388     /// allow MIR optimization passes to function and still
389     /// access cross-crate MIR (e.g. inlining or const eval).
390     ///
391     /// Note that cross-crate MIR appears to be always borrowed
392     /// (in the `RefCell` sense) to prevent accidental mutation.
393     pub mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
394
395     /// Maps DefId's that have an associated Mir to the result
396     /// of the MIR qualify_consts pass. The actual meaning of
397     /// the value isn't known except to the pass itself.
398     pub mir_const_qualif: Mir(DefId) -> u8,
399
400     /// Records the type of each closure. The def ID is the ID of the
401     /// expression defining the closure.
402     pub closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
403
404     /// Records the type of each closure. The def ID is the ID of the
405     /// expression defining the closure.
406     pub closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
407
408     /// Caches CoerceUnsized kinds for impls on custom types.
409     pub coerce_unsized_info: ItemSignature(DefId)
410         -> ty::adjustment::CoerceUnsizedInfo,
411
412     pub typeck_tables: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
413
414     pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
415
416     /// Gets a complete map from all types to their inherent impls.
417     /// Not meant to be used directly outside of coherence.
418     /// (Defined only for LOCAL_CRATE)
419     pub crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
420
421     /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
422     /// Not meant to be used directly outside of coherence.
423     /// (Defined only for LOCAL_CRATE)
424     pub crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
425
426     /// Results of evaluating monomorphic constants embedded in
427     /// other items, such as enum variant explicit discriminants.
428     pub monomorphic_const_eval: MonomorphicConstEval(DefId) -> Result<ConstVal<'tcx>, ()>,
429
430     /// Performs the privacy check and computes "access levels".
431     pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
432
433     pub mir_shims: mir_shim(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>
434 }
435
436 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
437     DepNode::CoherenceCheckTrait(def_id)
438 }
439
440 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
441     DepNode::Coherence
442 }
443
444 fn mir_shim(instance: ty::InstanceDef) -> DepNode<DefId> {
445     instance.dep_node()
446 }