]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/maps.rs
convert privacy access levels into a query
[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, 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::coherent_inherent_impls<'tcx> {
181     fn describe(_: TyCtxt, _: CrateNum) -> String {
182         format!("coherence checking all inherent impls")
183     }
184 }
185
186 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
187     fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
188         format!("generating MIR shim for `{}`",
189                 tcx.item_path_str(def.def_id()))
190     }
191 }
192
193 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
194     fn describe(_: TyCtxt, _: CrateNum) -> String {
195         format!("privacy access levels")
196     }
197 }
198
199 macro_rules! define_maps {
200     (<$tcx:tt>
201      $($(#[$attr:meta])*
202        pub $name:ident: $node:ident($K:ty) -> $V:ty),*) => {
203         pub struct Maps<$tcx> {
204             providers: IndexVec<CrateNum, Providers<$tcx>>,
205             query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
206             $($(#[$attr])* pub $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>),*
207         }
208
209         impl<$tcx> Maps<$tcx> {
210             pub fn new(dep_graph: DepGraph,
211                        providers: IndexVec<CrateNum, Providers<$tcx>>)
212                        -> Self {
213                 Maps {
214                     providers,
215                     query_stack: RefCell::new(vec![]),
216                     $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
217                 }
218             }
219         }
220
221         #[allow(bad_style)]
222         #[derive(Copy, Clone, Debug, PartialEq, Eq)]
223         pub enum Query<$tcx> {
224             $($(#[$attr])* $name($K)),*
225         }
226
227         impl<$tcx> Query<$tcx> {
228             pub fn describe(&self, tcx: TyCtxt) -> String {
229                 match *self {
230                     $(Query::$name(key) => queries::$name::describe(tcx, key)),*
231                 }
232             }
233         }
234
235         pub mod queries {
236             use std::marker::PhantomData;
237
238             $(#[allow(bad_style)]
239             pub struct $name<$tcx> {
240                 data: PhantomData<&$tcx ()>
241             })*
242         }
243
244         $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
245             type Key = $K;
246             type Value = $V;
247
248             #[allow(unused)]
249             fn to_dep_node(key: &$K) -> DepNode<DefId> {
250                 use dep_graph::DepNode::*;
251
252                 $node(*key)
253             }
254         }
255         impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
256             fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
257                                   mut span: Span,
258                                   key: $K,
259                                   f: F)
260                                   -> Result<R, CycleError<'a, $tcx>>
261                 where F: FnOnce(&$V) -> R
262             {
263                 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
264                     return Ok(f(result));
265                 }
266
267                 // FIXME(eddyb) Get more valid Span's on queries.
268                 if span == DUMMY_SP {
269                     span = key.default_span(tcx);
270                 }
271
272                 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
273
274                 let result = tcx.cycle_check(span, Query::$name(key), || {
275                     let provider = tcx.maps.providers[key.map_crate()].$name;
276                     provider(tcx.global_tcx(), key)
277                 })?;
278
279                 Ok(f(&tcx.maps.$name.borrow_mut().entry(key).or_insert(result)))
280             }
281
282             pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
283                            -> Result<$V, CycleError<'a, $tcx>> {
284                 Self::try_get_with(tcx, span, key, Clone::clone)
285             }
286
287             $(#[$attr])*
288             pub fn get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) -> $V {
289                 Self::try_get(tcx, span, key).unwrap_or_else(|e| {
290                     tcx.report_cycle(e);
291                     Value::from_cycle_error(tcx.global_tcx())
292                 })
293             }
294
295             pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
296                 // FIXME(eddyb) Move away from using `DepTrackingMap`
297                 // so we don't have to explicitly ignore a false edge:
298                 // we can't observe a value dependency, only side-effects,
299                 // through `force`, and once everything has been updated,
300                 // perhaps only diagnostics, if those, will remain.
301                 let _ignore = tcx.dep_graph.in_ignore();
302                 match Self::try_get_with(tcx, span, key, |_| ()) {
303                     Ok(()) => {}
304                     Err(e) => tcx.report_cycle(e)
305                 }
306             }
307         })*
308
309         pub struct Providers<$tcx> {
310             $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $V),*
311         }
312
313         impl<$tcx> Copy for Providers<$tcx> {}
314         impl<$tcx> Clone for Providers<$tcx> {
315             fn clone(&self) -> Self { *self }
316         }
317
318         impl<$tcx> Default for Providers<$tcx> {
319             fn default() -> Self {
320                 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $V {
321                     bug!("tcx.maps.{}({:?}) unsupported by its crate",
322                          stringify!($name), key);
323                 })*
324                 Providers { $($name),* }
325             }
326         }
327     }
328 }
329
330 // Each of these maps also corresponds to a method on a
331 // `Provider` trait for requesting a value of that type,
332 // and a method on `Maps` itself for doing that in a
333 // a way that memoizes and does dep-graph tracking,
334 // wrapping around the actual chain of providers that
335 // the driver creates (using several `rustc_*` crates).
336 define_maps! { <'tcx>
337     /// Records the type of every item.
338     pub ty: ItemSignature(DefId) -> Ty<'tcx>,
339
340     /// Maps from the def-id of an item (trait/struct/enum/fn) to its
341     /// associated generics and predicates.
342     pub generics: ItemSignature(DefId) -> &'tcx ty::Generics,
343     pub predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
344
345     /// Maps from the def-id of a trait to the list of
346     /// super-predicates. This is a subset of the full list of
347     /// predicates. We store these in a separate map because we must
348     /// evaluate them even during type conversion, often before the
349     /// full predicates are available (note that supertraits have
350     /// additional acyclicity requirements).
351     pub super_predicates: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
352
353     /// To avoid cycles within the predicates of a single item we compute
354     /// per-type-parameter predicates for resolving `T::AssocTy`.
355     pub type_param_predicates: TypeParamPredicates((DefId, DefId))
356         -> ty::GenericPredicates<'tcx>,
357
358     pub trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
359     pub adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
360     pub adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
361     pub adt_sized_constraint: SizedConstraint(DefId) -> Ty<'tcx>,
362
363     /// Maps from def-id of a type or region parameter to its
364     /// (inferred) variance.
365     pub variances: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
366
367     /// Maps from an impl/trait def-id to a list of the def-ids of its items
368     pub associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
369
370     /// Maps from a trait item to the trait item "descriptor"
371     pub associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
372
373     pub impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
374
375     /// Maps a DefId of a type to a list of its inherent impls.
376     /// Contains implementations of methods that are inherent to a type.
377     /// Methods in these implementations don't need to be exported.
378     pub inherent_impls: InherentImpls(DefId) -> Vec<DefId>,
379
380     /// Maps from the def-id of a function/method or const/static
381     /// to its MIR. Mutation is done at an item granularity to
382     /// allow MIR optimization passes to function and still
383     /// access cross-crate MIR (e.g. inlining or const eval).
384     ///
385     /// Note that cross-crate MIR appears to be always borrowed
386     /// (in the `RefCell` sense) to prevent accidental mutation.
387     pub mir: Mir(DefId) -> &'tcx RefCell<mir::Mir<'tcx>>,
388
389     /// Maps DefId's that have an associated Mir to the result
390     /// of the MIR qualify_consts pass. The actual meaning of
391     /// the value isn't known except to the pass itself.
392     pub mir_const_qualif: Mir(DefId) -> u8,
393
394     /// Records the type of each closure. The def ID is the ID of the
395     /// expression defining the closure.
396     pub closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
397
398     /// Records the type of each closure. The def ID is the ID of the
399     /// expression defining the closure.
400     pub closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
401
402     /// Caches CoerceUnsized kinds for impls on custom types.
403     pub custom_coerce_unsized_kind: ItemSignature(DefId)
404         -> ty::adjustment::CustomCoerceUnsized,
405
406     pub typeck_tables: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
407
408     pub coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
409
410     pub coherent_inherent_impls: coherent_inherent_impls_dep_node(CrateNum) -> (),
411
412     /// Results of evaluating monomorphic constants embedded in
413     /// other items, such as enum variant explicit discriminants.
414     pub monomorphic_const_eval: MonomorphicConstEval(DefId) -> Result<ConstVal<'tcx>, ()>,
415
416     /// Performs the privacy check and computes "access levels".
417     pub privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
418
419     pub mir_shims: mir_shim(ty::InstanceDef<'tcx>) -> &'tcx RefCell<mir::Mir<'tcx>>
420 }
421
422 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
423     DepNode::CoherenceCheckTrait(def_id)
424 }
425
426 fn coherent_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
427     DepNode::Coherence
428 }
429
430 fn mir_shim(instance: ty::InstanceDef) -> DepNode<DefId> {
431     instance.dep_node()
432 }