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