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