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