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