]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/decoder.rs
rustc: Store InternedString in `DefPathData`
[rust.git] / src / librustc_metadata / decoder.rs
1 // Copyright 2012-2014 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 // Decoding metadata from a single crate's metadata
12
13 use cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary};
14 use schema::*;
15
16 use rustc::dep_graph::{DepGraph, DepNode, DepKind};
17 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash};
18 use rustc::hir::map::definitions::GlobalMetaDataKind;
19 use rustc::hir;
20
21 use rustc::middle::cstore::LinkagePreference;
22 use rustc::hir::def::{self, Def, CtorKind};
23 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
24 use rustc::middle::lang_items;
25 use rustc::session::Session;
26 use rustc::ty::{self, Ty, TyCtxt};
27 use rustc::ty::subst::Substs;
28
29 use rustc::mir::Mir;
30
31 use std::borrow::Cow;
32 use std::cell::Ref;
33 use std::collections::BTreeMap;
34 use std::io;
35 use std::mem;
36 use std::rc::Rc;
37 use std::str;
38 use std::u32;
39
40 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
41 use syntax::attr;
42 use syntax::ast::{self, Ident};
43 use syntax::codemap;
44 use syntax::symbol::{InternedString, Symbol};
45 use syntax::ext::base::MacroKind;
46 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
47
48 pub struct DecodeContext<'a, 'tcx: 'a> {
49     opaque: opaque::Decoder<'a>,
50     cdata: Option<&'a CrateMetadata>,
51     sess: Option<&'a Session>,
52     tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
53
54     // Cache the last used filemap for translating spans as an optimization.
55     last_filemap_index: usize,
56
57     lazy_state: LazyState,
58 }
59
60 /// Abstract over the various ways one can create metadata decoders.
61 pub trait Metadata<'a, 'tcx>: Copy {
62     fn raw_bytes(self) -> &'a [u8];
63     fn cdata(self) -> Option<&'a CrateMetadata> { None }
64     fn sess(self) -> Option<&'a Session> { None }
65     fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { None }
66
67     fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
68         let tcx = self.tcx();
69         DecodeContext {
70             opaque: opaque::Decoder::new(self.raw_bytes(), pos),
71             cdata: self.cdata(),
72             sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
73             tcx,
74             last_filemap_index: 0,
75             lazy_state: LazyState::NoNode,
76         }
77     }
78 }
79
80 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
81     fn raw_bytes(self) -> &'a [u8] {
82         &self.0
83     }
84 }
85
86 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
87     fn raw_bytes(self) -> &'a [u8] {
88         self.blob.raw_bytes()
89     }
90     fn cdata(self) -> Option<&'a CrateMetadata> {
91         Some(self)
92     }
93 }
94
95 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
96     fn raw_bytes(self) -> &'a [u8] {
97         self.0.raw_bytes()
98     }
99     fn cdata(self) -> Option<&'a CrateMetadata> {
100         Some(self.0)
101     }
102     fn sess(self) -> Option<&'a Session> {
103         Some(&self.1)
104     }
105 }
106
107 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
108     fn raw_bytes(self) -> &'a [u8] {
109         self.0.raw_bytes()
110     }
111     fn cdata(self) -> Option<&'a CrateMetadata> {
112         Some(self.0)
113     }
114     fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
115         Some(self.1)
116     }
117 }
118
119 impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
120     pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
121         let mut dcx = meta.decoder(self.position);
122         dcx.lazy_state = LazyState::NodeStart(self.position);
123         T::decode(&mut dcx).unwrap()
124     }
125 }
126
127 impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
128     pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> impl Iterator<Item = T> + 'a {
129         let mut dcx = meta.decoder(self.position);
130         dcx.lazy_state = LazyState::NodeStart(self.position);
131         (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
132     }
133 }
134
135 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
136     pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
137         self.tcx.expect("missing TyCtxt in DecodeContext")
138     }
139
140     pub fn cdata(&self) -> &'a CrateMetadata {
141         self.cdata.expect("missing CrateMetadata in DecodeContext")
142     }
143
144     fn with_position<F: FnOnce(&mut Self) -> R, R>(&mut self, pos: usize, f: F) -> R {
145         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
146         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
147         let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
148         let r = f(self);
149         self.opaque = old_opaque;
150         self.lazy_state = old_state;
151         r
152     }
153
154     fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
155         let distance = self.read_usize()?;
156         let position = match self.lazy_state {
157             LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
158             LazyState::NodeStart(start) => {
159                 assert!(distance + min_size <= start);
160                 start - distance - min_size
161             }
162             LazyState::Previous(last_min_end) => last_min_end + distance,
163         };
164         self.lazy_state = LazyState::Previous(position + min_size);
165         Ok(position)
166     }
167 }
168
169 macro_rules! decoder_methods {
170     ($($name:ident -> $ty:ty;)*) => {
171         $(fn $name(&mut self) -> Result<$ty, Self::Error> {
172             self.opaque.$name()
173         })*
174     }
175 }
176
177 impl<'doc, 'tcx> Decoder for DecodeContext<'doc, 'tcx> {
178     type Error = <opaque::Decoder<'doc> as Decoder>::Error;
179
180     decoder_methods! {
181         read_nil -> ();
182
183         read_u128 -> u128;
184         read_u64 -> u64;
185         read_u32 -> u32;
186         read_u16 -> u16;
187         read_u8 -> u8;
188         read_usize -> usize;
189
190         read_i128 -> i128;
191         read_i64 -> i64;
192         read_i32 -> i32;
193         read_i16 -> i16;
194         read_i8 -> i8;
195         read_isize -> isize;
196
197         read_bool -> bool;
198         read_f64 -> f64;
199         read_f32 -> f32;
200         read_char -> char;
201         read_str -> Cow<str>;
202     }
203
204     fn error(&mut self, err: &str) -> Self::Error {
205         self.opaque.error(err)
206     }
207 }
208
209 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
210     fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
211         Ok(Lazy::with_position(self.read_lazy_distance(Lazy::<T>::min_size())?))
212     }
213 }
214
215 impl<'a, 'tcx, T> SpecializedDecoder<LazySeq<T>> for DecodeContext<'a, 'tcx> {
216     fn specialized_decode(&mut self) -> Result<LazySeq<T>, Self::Error> {
217         let len = self.read_usize()?;
218         let position = if len == 0 {
219             0
220         } else {
221             self.read_lazy_distance(LazySeq::<T>::min_size(len))?
222         };
223         Ok(LazySeq::with_position_and_length(position, len))
224     }
225 }
226
227 impl<'a, 'tcx> SpecializedDecoder<CrateNum> for DecodeContext<'a, 'tcx> {
228     fn specialized_decode(&mut self) -> Result<CrateNum, Self::Error> {
229         let cnum = CrateNum::from_u32(u32::decode(self)?);
230         if cnum == LOCAL_CRATE {
231             Ok(self.cdata().cnum)
232         } else {
233             Ok(self.cdata().cnum_map.borrow()[cnum])
234         }
235     }
236 }
237
238 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
239     fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
240         let lo = BytePos::decode(self)?;
241         let hi = BytePos::decode(self)?;
242
243         let sess = if let Some(sess) = self.sess {
244             sess
245         } else {
246             return Ok(Span::new(lo, hi, NO_EXPANSION));
247         };
248
249         let (lo, hi) = if lo > hi {
250             // Currently macro expansion sometimes produces invalid Span values
251             // where lo > hi. In order not to crash the compiler when trying to
252             // translate these values, let's transform them into something we
253             // can handle (and which will produce useful debug locations at
254             // least some of the time).
255             // This workaround is only necessary as long as macro expansion is
256             // not fixed. FIXME(#23480)
257             (lo, lo)
258         } else {
259             (lo, hi)
260         };
261
262         let imported_filemaps = self.cdata().imported_filemaps(&sess.codemap());
263         let filemap = {
264             // Optimize for the case that most spans within a translated item
265             // originate from the same filemap.
266             let last_filemap = &imported_filemaps[self.last_filemap_index];
267
268             if lo >= last_filemap.original_start_pos && lo <= last_filemap.original_end_pos &&
269                hi >= last_filemap.original_start_pos &&
270                hi <= last_filemap.original_end_pos {
271                 last_filemap
272             } else {
273                 let mut a = 0;
274                 let mut b = imported_filemaps.len();
275
276                 while b - a > 1 {
277                     let m = (a + b) / 2;
278                     if imported_filemaps[m].original_start_pos > lo {
279                         b = m;
280                     } else {
281                         a = m;
282                     }
283                 }
284
285                 self.last_filemap_index = a;
286                 &imported_filemaps[a]
287             }
288         };
289
290         let lo = (lo - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
291         let hi = (hi - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
292
293         Ok(Span::new(lo, hi, NO_EXPANSION))
294     }
295 }
296
297 // FIXME(#36588) These impls are horribly unsound as they allow
298 // the caller to pick any lifetime for 'tcx, including 'static,
299 // by using the unspecialized proxies to them.
300
301 impl<'a, 'tcx> SpecializedDecoder<Ty<'tcx>> for DecodeContext<'a, 'tcx> {
302     fn specialized_decode(&mut self) -> Result<Ty<'tcx>, Self::Error> {
303         let tcx = self.tcx();
304
305         // Handle shorthands first, if we have an usize > 0x80.
306         if self.opaque.data[self.opaque.position()] & 0x80 != 0 {
307             let pos = self.read_usize()?;
308             assert!(pos >= SHORTHAND_OFFSET);
309             let key = ty::CReaderCacheKey {
310                 cnum: self.cdata().cnum,
311                 pos: pos - SHORTHAND_OFFSET,
312             };
313             if let Some(ty) = tcx.rcache.borrow().get(&key).cloned() {
314                 return Ok(ty);
315             }
316
317             let ty = self.with_position(key.pos, Ty::decode)?;
318             tcx.rcache.borrow_mut().insert(key, ty);
319             Ok(ty)
320         } else {
321             Ok(tcx.mk_ty(ty::TypeVariants::decode(self)?))
322         }
323     }
324 }
325
326
327 impl<'a, 'tcx> SpecializedDecoder<ty::GenericPredicates<'tcx>> for DecodeContext<'a, 'tcx> {
328     fn specialized_decode(&mut self) -> Result<ty::GenericPredicates<'tcx>, Self::Error> {
329         Ok(ty::GenericPredicates {
330             parent: Decodable::decode(self)?,
331             predicates: (0..self.read_usize()?).map(|_| {
332                     // Handle shorthands first, if we have an usize > 0x80.
333                     if self.opaque.data[self.opaque.position()] & 0x80 != 0 {
334                         let pos = self.read_usize()?;
335                         assert!(pos >= SHORTHAND_OFFSET);
336                         let pos = pos - SHORTHAND_OFFSET;
337
338                         self.with_position(pos, ty::Predicate::decode)
339                     } else {
340                         ty::Predicate::decode(self)
341                     }
342                 })
343                 .collect::<Result<Vec<_>, _>>()?,
344         })
345     }
346 }
347
348 impl<'a, 'tcx> SpecializedDecoder<&'tcx Substs<'tcx>> for DecodeContext<'a, 'tcx> {
349     fn specialized_decode(&mut self) -> Result<&'tcx Substs<'tcx>, Self::Error> {
350         Ok(self.tcx().mk_substs((0..self.read_usize()?).map(|_| Decodable::decode(self)))?)
351     }
352 }
353
354 impl<'a, 'tcx> SpecializedDecoder<ty::Region<'tcx>> for DecodeContext<'a, 'tcx> {
355     fn specialized_decode(&mut self) -> Result<ty::Region<'tcx>, Self::Error> {
356         Ok(self.tcx().mk_region(Decodable::decode(self)?))
357     }
358 }
359
360 impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Slice<Ty<'tcx>>> for DecodeContext<'a, 'tcx> {
361     fn specialized_decode(&mut self) -> Result<&'tcx ty::Slice<Ty<'tcx>>, Self::Error> {
362         Ok(self.tcx().mk_type_list((0..self.read_usize()?).map(|_| Decodable::decode(self)))?)
363     }
364 }
365
366 impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::AdtDef> for DecodeContext<'a, 'tcx> {
367     fn specialized_decode(&mut self) -> Result<&'tcx ty::AdtDef, Self::Error> {
368         let def_id = DefId::decode(self)?;
369         Ok(self.tcx().adt_def(def_id))
370     }
371 }
372
373 impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>
374     for DecodeContext<'a, 'tcx> {
375     fn specialized_decode(&mut self)
376         -> Result<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>, Self::Error> {
377         Ok(self.tcx().mk_existential_predicates((0..self.read_usize()?)
378                                                 .map(|_| Decodable::decode(self)))?)
379     }
380 }
381
382 impl<'a, 'tcx> MetadataBlob {
383     pub fn is_compatible(&self) -> bool {
384         self.raw_bytes().starts_with(METADATA_HEADER)
385     }
386
387     pub fn get_rustc_version(&self) -> String {
388         Lazy::with_position(METADATA_HEADER.len() + 4).decode(self)
389     }
390
391     pub fn get_root(&self) -> CrateRoot {
392         let slice = self.raw_bytes();
393         let offset = METADATA_HEADER.len();
394         let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
395                    ((slice[offset + 2] as u32) << 8) |
396                    ((slice[offset + 3] as u32) << 0)) as usize;
397         Lazy::with_position(pos).decode(self)
398     }
399
400     pub fn list_crate_metadata(&self,
401                                out: &mut io::Write) -> io::Result<()> {
402         write!(out, "=External Dependencies=\n")?;
403         let root = self.get_root();
404         for (i, dep) in root.crate_deps
405                             .get_untracked()
406                             .decode(self)
407                             .enumerate() {
408             write!(out, "{} {}-{}\n", i + 1, dep.name, dep.hash)?;
409         }
410         write!(out, "\n")?;
411         Ok(())
412     }
413 }
414
415 impl<'tcx> EntryKind<'tcx> {
416     fn to_def(&self, did: DefId) -> Option<Def> {
417         Some(match *self {
418             EntryKind::Const(_) => Def::Const(did),
419             EntryKind::AssociatedConst(..) => Def::AssociatedConst(did),
420             EntryKind::ImmStatic |
421             EntryKind::ForeignImmStatic => Def::Static(did, false),
422             EntryKind::MutStatic |
423             EntryKind::ForeignMutStatic => Def::Static(did, true),
424             EntryKind::Struct(_, _) => Def::Struct(did),
425             EntryKind::Union(_, _) => Def::Union(did),
426             EntryKind::Fn(_) |
427             EntryKind::ForeignFn(_) => Def::Fn(did),
428             EntryKind::Method(_) => Def::Method(did),
429             EntryKind::Type => Def::TyAlias(did),
430             EntryKind::AssociatedType(_) => Def::AssociatedTy(did),
431             EntryKind::Mod(_) => Def::Mod(did),
432             EntryKind::Variant(_) => Def::Variant(did),
433             EntryKind::Trait(_) => Def::Trait(did),
434             EntryKind::Enum(..) => Def::Enum(did),
435             EntryKind::MacroDef(_) => Def::Macro(did, MacroKind::Bang),
436             EntryKind::GlobalAsm => Def::GlobalAsm(did),
437
438             EntryKind::ForeignMod |
439             EntryKind::Impl(_) |
440             EntryKind::DefaultImpl(_) |
441             EntryKind::Field |
442             EntryKind::Generator(_) |
443             EntryKind::Closure(_) => return None,
444         })
445     }
446 }
447
448 impl<'a, 'tcx> CrateMetadata {
449     fn is_proc_macro(&self, id: DefIndex) -> bool {
450         self.proc_macros.is_some() && id != CRATE_DEF_INDEX
451     }
452
453     fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
454         assert!(!self.is_proc_macro(item_id));
455         self.root.index.lookup(self.blob.raw_bytes(), item_id)
456     }
457
458     fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
459         match self.maybe_entry(item_id) {
460             None => {
461                 bug!("entry: id not found: {:?} in crate {:?} with number {}",
462                      item_id,
463                      self.name,
464                      self.cnum)
465             }
466             Some(d) => d.decode(self),
467         }
468     }
469
470     fn local_def_id(&self, index: DefIndex) -> DefId {
471         DefId {
472             krate: self.cnum,
473             index,
474         }
475     }
476
477     pub fn item_name(&self, item_index: DefIndex) -> InternedString {
478         self.def_key(item_index)
479             .disambiguated_data
480             .data
481             .get_opt_name()
482             .expect("no name in item_name")
483     }
484
485     pub fn get_def(&self, index: DefIndex) -> Option<Def> {
486         if !self.is_proc_macro(index) {
487             self.entry(index).kind.to_def(self.local_def_id(index))
488         } else {
489             let kind = self.proc_macros.as_ref().unwrap()[index.as_usize() - 1].1.kind();
490             Some(Def::Macro(self.local_def_id(index), kind))
491         }
492     }
493
494     pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
495         match self.is_proc_macro(index) {
496             true => DUMMY_SP,
497             false => self.entry(index).span.decode((self, sess)),
498         }
499     }
500
501     pub fn get_trait_def(&self, item_id: DefIndex) -> ty::TraitDef {
502         let data = match self.entry(item_id).kind {
503             EntryKind::Trait(data) => data.decode(self),
504             _ => bug!(),
505         };
506
507         ty::TraitDef::new(self.local_def_id(item_id),
508                           data.unsafety,
509                           data.paren_sugar,
510                           data.has_default_impl,
511                           self.def_path_table.def_path_hash(item_id))
512     }
513
514     fn get_variant(&self, item: &Entry, index: DefIndex) -> ty::VariantDef {
515         let data = match item.kind {
516             EntryKind::Variant(data) |
517             EntryKind::Struct(data, _) |
518             EntryKind::Union(data, _) => data.decode(self),
519             _ => bug!(),
520         };
521
522         ty::VariantDef {
523             did: self.local_def_id(data.struct_ctor.unwrap_or(index)),
524             name: Symbol::intern(&self.item_name(index)),
525             fields: item.children.decode(self).map(|index| {
526                 let f = self.entry(index);
527                 ty::FieldDef {
528                     did: self.local_def_id(index),
529                     name: Symbol::intern(&self.item_name(index)),
530                     vis: f.visibility.decode(self)
531                 }
532             }).collect(),
533             discr: data.discr,
534             ctor_kind: data.ctor_kind,
535         }
536     }
537
538     pub fn get_adt_def(&self,
539                        item_id: DefIndex,
540                        tcx: TyCtxt<'a, 'tcx, 'tcx>)
541                        -> &'tcx ty::AdtDef {
542         let item = self.entry(item_id);
543         let did = self.local_def_id(item_id);
544         let kind = match item.kind {
545             EntryKind::Enum(_) => ty::AdtKind::Enum,
546             EntryKind::Struct(_, _) => ty::AdtKind::Struct,
547             EntryKind::Union(_, _) => ty::AdtKind::Union,
548             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
549         };
550         let variants = if let ty::AdtKind::Enum = kind {
551             item.children
552                 .decode(self)
553                 .map(|index| {
554                     self.get_variant(&self.entry(index), index)
555                 })
556                 .collect()
557         } else {
558             vec![self.get_variant(&item, item_id)]
559         };
560         let (kind, repr) = match item.kind {
561             EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
562             EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
563             EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
564             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
565         };
566
567         tcx.alloc_adt_def(did, kind, variants, repr)
568     }
569
570     pub fn get_predicates(&self,
571                           item_id: DefIndex,
572                           tcx: TyCtxt<'a, 'tcx, 'tcx>)
573                           -> ty::GenericPredicates<'tcx> {
574         self.entry(item_id).predicates.unwrap().decode((self, tcx))
575     }
576
577     pub fn get_super_predicates(&self,
578                                 item_id: DefIndex,
579                                 tcx: TyCtxt<'a, 'tcx, 'tcx>)
580                                 -> ty::GenericPredicates<'tcx> {
581         match self.entry(item_id).kind {
582             EntryKind::Trait(data) => data.decode(self).super_predicates.decode((self, tcx)),
583             _ => bug!(),
584         }
585     }
586
587     pub fn get_generics(&self, item_id: DefIndex) -> ty::Generics {
588         self.entry(item_id).generics.unwrap().decode(self)
589     }
590
591     pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
592         self.entry(id).ty.unwrap().decode((self, tcx))
593     }
594
595     pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
596         match self.is_proc_macro(id) {
597             true => None,
598             false => self.entry(id).stability.map(|stab| stab.decode(self)),
599         }
600     }
601
602     pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
603         match self.is_proc_macro(id) {
604             true => None,
605             false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
606         }
607     }
608
609     pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
610         match self.is_proc_macro(id) {
611             true => ty::Visibility::Public,
612             false => self.entry(id).visibility.decode(self),
613         }
614     }
615
616     fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
617         match self.entry(id).kind {
618             EntryKind::Impl(data) => data.decode(self),
619             _ => bug!(),
620         }
621     }
622
623     pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
624         self.get_impl_data(id).parent_impl
625     }
626
627     pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
628         self.get_impl_data(id).polarity
629     }
630
631     pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
632         self.get_impl_data(id).defaultness
633     }
634
635     pub fn get_coerce_unsized_info(&self,
636                                    id: DefIndex)
637                                    -> Option<ty::adjustment::CoerceUnsizedInfo> {
638         self.get_impl_data(id).coerce_unsized_info
639     }
640
641     pub fn get_impl_trait(&self,
642                           id: DefIndex,
643                           tcx: TyCtxt<'a, 'tcx, 'tcx>)
644                           -> Option<ty::TraitRef<'tcx>> {
645         self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
646     }
647
648     /// Iterates over the language items in the given crate.
649     pub fn get_lang_items(&self, dep_graph: &DepGraph) -> Vec<(DefIndex, usize)> {
650         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItems);
651         self.root
652             .lang_items
653             .get(dep_graph, dep_node)
654             .decode(self)
655             .collect()
656     }
657
658     /// Iterates over each child of the given item.
659     pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
660         where F: FnMut(def::Export)
661     {
662         if let Some(ref proc_macros) = self.proc_macros {
663             if id == CRATE_DEF_INDEX {
664                 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
665                     let def = Def::Macro(
666                         DefId {
667                             krate: self.cnum,
668                             index: DefIndex::new(id + 1)
669                         },
670                         ext.kind()
671                     );
672                     let ident = Ident::with_empty_ctxt(name);
673                     callback(def::Export { ident: ident, def: def, span: DUMMY_SP });
674                 }
675             }
676             return
677         }
678
679         // Find the item.
680         let item = match self.maybe_entry(id) {
681             None => return,
682             Some(item) => item.decode((self, sess)),
683         };
684
685         // Iterate over all children.
686         let macros_only = self.dep_kind.get().macros_only();
687         for child_index in item.children.decode((self, sess)) {
688             if macros_only {
689                 continue
690             }
691
692             // Get the item.
693             if let Some(child) = self.maybe_entry(child_index) {
694                 let child = child.decode((self, sess));
695                 match child.kind {
696                     EntryKind::MacroDef(..) => {}
697                     _ if macros_only => continue,
698                     _ => {}
699                 }
700
701                 // Hand off the item to the callback.
702                 match child.kind {
703                     // FIXME(eddyb) Don't encode these in children.
704                     EntryKind::ForeignMod => {
705                         for child_index in child.children.decode((self, sess)) {
706                             if let Some(def) = self.get_def(child_index) {
707                                 callback(def::Export {
708                                     def,
709                                     ident: Ident::from_str(&self.item_name(child_index)),
710                                     span: self.entry(child_index).span.decode((self, sess)),
711                                 });
712                             }
713                         }
714                         continue;
715                     }
716                     EntryKind::Impl(_) |
717                     EntryKind::DefaultImpl(_) => continue,
718
719                     _ => {}
720                 }
721
722                 let def_key = self.def_key(child_index);
723                 let span = child.span.decode((self, sess));
724                 if let (Some(def), Some(name)) =
725                     (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
726                     let ident = Ident::from_str(&name);
727                     callback(def::Export { def: def, ident: ident, span: span });
728                     // For non-reexport structs and variants add their constructors to children.
729                     // Reexport lists automatically contain constructors when necessary.
730                     match def {
731                         Def::Struct(..) => {
732                             if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
733                                 let ctor_kind = self.get_ctor_kind(child_index);
734                                 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
735                                 callback(def::Export { def: ctor_def, ident: ident, span: span });
736                             }
737                         }
738                         Def::Variant(def_id) => {
739                             // Braced variants, unlike structs, generate unusable names in
740                             // value namespace, they are reserved for possible future use.
741                             let ctor_kind = self.get_ctor_kind(child_index);
742                             let ctor_def = Def::VariantCtor(def_id, ctor_kind);
743                             callback(def::Export { def: ctor_def, ident: ident, span: span });
744                         }
745                         _ => {}
746                     }
747                 }
748             }
749         }
750
751         if let EntryKind::Mod(data) = item.kind {
752             for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
753                 match exp.def {
754                     Def::Macro(..) => {}
755                     _ if macros_only => continue,
756                     _ => {}
757                 }
758                 callback(exp);
759             }
760         }
761     }
762
763     pub fn extern_const_body(&self,
764                              tcx: TyCtxt<'a, 'tcx, 'tcx>,
765                              id: DefIndex)
766                              -> &'tcx hir::Body {
767         assert!(!self.is_proc_macro(id));
768         let ast = self.entry(id).ast.unwrap();
769         let def_id = self.local_def_id(id);
770         let body = ast.decode((self, tcx)).body.decode((self, tcx));
771         tcx.hir.intern_inlined_body(def_id, body)
772     }
773
774     pub fn item_body_tables(&self,
775                             id: DefIndex,
776                             tcx: TyCtxt<'a, 'tcx, 'tcx>)
777                             -> &'tcx ty::TypeckTables<'tcx> {
778         let ast = self.entry(id).ast.unwrap().decode(self);
779         tcx.alloc_tables(ast.tables.decode((self, tcx)))
780     }
781
782     pub fn item_body_nested_bodies(&self, id: DefIndex) -> BTreeMap<hir::BodyId, hir::Body> {
783         self.entry(id).ast.into_iter().flat_map(|ast| {
784             ast.decode(self).nested_bodies.decode(self).map(|body| (body.id(), body))
785         }).collect()
786     }
787
788     pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
789         self.entry(id).ast.expect("const item missing `ast`")
790             .decode(self).rvalue_promotable_to_static
791     }
792
793     pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
794         !self.is_proc_macro(id) &&
795         self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
796     }
797
798     pub fn maybe_get_optimized_mir(&self,
799                                    tcx: TyCtxt<'a, 'tcx, 'tcx>,
800                                    id: DefIndex)
801                                    -> Option<Mir<'tcx>> {
802         match self.is_proc_macro(id) {
803             true => None,
804             false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
805         }
806     }
807
808     pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
809         match self.entry(id).kind {
810             EntryKind::Const(qualif) |
811             EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif) |
812             EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif) => {
813                 qualif
814             }
815             _ => bug!(),
816         }
817     }
818
819     pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
820         let item = self.entry(id);
821         let def_key = self.def_key(id);
822         let parent = self.local_def_id(def_key.parent.unwrap());
823         let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
824
825         let (kind, container, has_self) = match item.kind {
826             EntryKind::AssociatedConst(container, _) => {
827                 (ty::AssociatedKind::Const, container, false)
828             }
829             EntryKind::Method(data) => {
830                 let data = data.decode(self);
831                 (ty::AssociatedKind::Method, data.container, data.has_self)
832             }
833             EntryKind::AssociatedType(container) => {
834                 (ty::AssociatedKind::Type, container, false)
835             }
836             _ => bug!("cannot get associated-item of `{:?}`", def_key)
837         };
838
839         ty::AssociatedItem {
840             name: Symbol::intern(&name),
841             kind,
842             vis: item.visibility.decode(self),
843             defaultness: container.defaultness(),
844             def_id: self.local_def_id(id),
845             container: container.with_def_id(parent),
846             method_has_self_argument: has_self
847         }
848     }
849
850     pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
851         self.entry(id).variances.decode(self).collect()
852     }
853
854     pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
855         match self.entry(node_id).kind {
856             EntryKind::Struct(data, _) |
857             EntryKind::Union(data, _) |
858             EntryKind::Variant(data) => data.decode(self).ctor_kind,
859             _ => CtorKind::Fictive,
860         }
861     }
862
863     pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
864         match self.entry(node_id).kind {
865             EntryKind::Struct(data, _) => {
866                 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
867             }
868             _ => None,
869         }
870     }
871
872     pub fn get_item_attrs(&self,
873                           node_id: DefIndex,
874                           dep_graph: &DepGraph) -> Rc<[ast::Attribute]> {
875         let (node_as, node_index) =
876             (node_id.address_space().index(), node_id.as_array_index());
877         if self.is_proc_macro(node_id) {
878             return Rc::new([]);
879         }
880
881         let dep_node = self.def_path_hash(node_id).to_dep_node(DepKind::MetaData);
882         dep_graph.read(dep_node);
883
884         if let Some(&Some(ref val)) =
885             self.attribute_cache.borrow()[node_as].get(node_index) {
886             return val.clone();
887         }
888
889         // The attributes for a tuple struct are attached to the definition, not the ctor;
890         // we assume that someone passing in a tuple struct ctor is actually wanting to
891         // look at the definition
892         let mut item = self.entry(node_id);
893         let def_key = self.def_key(node_id);
894         if def_key.disambiguated_data.data == DefPathData::StructCtor {
895             item = self.entry(def_key.parent.unwrap());
896         }
897         let result: Rc<[ast::Attribute]> = Rc::from(self.get_attributes(&item));
898         let vec_ = &mut self.attribute_cache.borrow_mut()[node_as];
899         if vec_.len() < node_index + 1 {
900             vec_.resize(node_index + 1, None);
901         }
902         vec_[node_index] = Some(result.clone());
903         result
904     }
905
906     pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
907         self.entry(id)
908             .children
909             .decode(self)
910             .map(|index| Symbol::intern(&self.item_name(index)))
911             .collect()
912     }
913
914     fn get_attributes(&self, item: &Entry<'tcx>) -> Vec<ast::Attribute> {
915         item.attributes
916             .decode(self)
917             .map(|mut attr| {
918                 // Need new unique IDs: old thread-local IDs won't map to new threads.
919                 attr.id = attr::mk_attr_id();
920                 attr
921             })
922             .collect()
923     }
924
925     // Translate a DefId from the current compilation environment to a DefId
926     // for an external crate.
927     fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
928         for (local, &global) in self.cnum_map.borrow().iter_enumerated() {
929             if global == did.krate {
930                 return Some(DefId {
931                     krate: local,
932                     index: did.index,
933                 });
934             }
935         }
936
937         None
938     }
939
940     pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
941         self.entry(id)
942             .inherent_impls
943             .decode(self)
944             .map(|index| self.local_def_id(index))
945             .collect()
946     }
947
948     pub fn get_implementations_for_trait(&self,
949                                          filter: Option<DefId>,
950                                          dep_graph: &DepGraph,
951                                          result: &mut Vec<DefId>) {
952         // Do a reverse lookup beforehand to avoid touching the crate_num
953         // hash map in the loop below.
954         let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
955             Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
956             Some(None) => return,
957             None if self.proc_macros.is_some() => return,
958             None => None,
959         };
960
961         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::Impls);
962
963         if let Some(filter) = filter {
964             if let Some(impls) = self.trait_impls
965                                      .get(dep_graph, dep_node)
966                                      .get(&filter) {
967                 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
968             }
969         } else {
970             for impls in self.trait_impls.get(dep_graph, dep_node).values() {
971                 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
972             }
973         }
974     }
975
976     pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
977         self.def_key(id).parent.and_then(|parent_index| {
978             match self.entry(parent_index).kind {
979                 EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
980                 _ => None,
981             }
982         })
983     }
984
985
986     pub fn get_native_libraries(&self,
987                                 dep_graph: &DepGraph)
988                                 -> Vec<NativeLibrary> {
989         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries);
990         self.root
991             .native_libraries
992             .get(dep_graph, dep_node)
993             .decode(self)
994             .collect()
995     }
996
997     pub fn get_dylib_dependency_formats(&self,
998                                         dep_graph: &DepGraph)
999                                         -> Vec<(CrateNum, LinkagePreference)> {
1000         let dep_node =
1001             self.metadata_dep_node(GlobalMetaDataKind::DylibDependencyFormats);
1002         self.root
1003             .dylib_dependency_formats
1004             .get(dep_graph, dep_node)
1005             .decode(self)
1006             .enumerate()
1007             .flat_map(|(i, link)| {
1008                 let cnum = CrateNum::new(i + 1);
1009                 link.map(|link| (self.cnum_map.borrow()[cnum], link))
1010             })
1011             .collect()
1012     }
1013
1014     pub fn get_missing_lang_items(&self, dep_graph: &DepGraph) -> Vec<lang_items::LangItem> {
1015         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItemsMissing);
1016         self.root
1017             .lang_items_missing
1018             .get(dep_graph, dep_node)
1019             .decode(self)
1020             .collect()
1021     }
1022
1023     pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
1024         let arg_names = match self.entry(id).kind {
1025             EntryKind::Fn(data) |
1026             EntryKind::ForeignFn(data) => data.decode(self).arg_names,
1027             EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
1028             _ => LazySeq::empty(),
1029         };
1030         arg_names.decode(self).collect()
1031     }
1032
1033     pub fn get_exported_symbols(&self, dep_graph: &DepGraph) -> Vec<DefId> {
1034         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols);
1035         self.exported_symbols
1036             .get(dep_graph, dep_node)
1037             .iter()
1038             .map(|&index| self.local_def_id(index))
1039             .collect()
1040     }
1041
1042     pub fn get_macro(&self, id: DefIndex) -> (InternedString, MacroDef) {
1043         let entry = self.entry(id);
1044         match entry.kind {
1045             EntryKind::MacroDef(macro_def) => (self.item_name(id), macro_def.decode(self)),
1046             _ => bug!(),
1047         }
1048     }
1049
1050     pub fn is_const_fn(&self, id: DefIndex) -> bool {
1051         let constness = match self.entry(id).kind {
1052             EntryKind::Method(data) => data.decode(self).fn_data.constness,
1053             EntryKind::Fn(data) => data.decode(self).constness,
1054             _ => hir::Constness::NotConst,
1055         };
1056         constness == hir::Constness::Const
1057     }
1058
1059     pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1060         match self.entry(id).kind {
1061             EntryKind::ForeignImmStatic |
1062             EntryKind::ForeignMutStatic |
1063             EntryKind::ForeignFn(_) => true,
1064             _ => false,
1065         }
1066     }
1067
1068     pub fn is_dllimport_foreign_item(&self, id: DefIndex, dep_graph: &DepGraph) -> bool {
1069         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries);
1070         self.dllimport_foreign_items
1071             .get(dep_graph, dep_node)
1072             .contains(&id)
1073     }
1074
1075     pub fn is_default_impl(&self, impl_id: DefIndex) -> bool {
1076         match self.entry(impl_id).kind {
1077             EntryKind::DefaultImpl(_) => true,
1078             _ => false,
1079         }
1080     }
1081
1082     pub fn closure_kind(&self, closure_id: DefIndex) -> ty::ClosureKind {
1083         match self.entry(closure_id).kind {
1084             EntryKind::Closure(data) => data.decode(self).kind,
1085             _ => bug!(),
1086         }
1087     }
1088
1089     pub fn fn_sig(&self,
1090                   id: DefIndex,
1091                   tcx: TyCtxt<'a, 'tcx, 'tcx>)
1092                   -> ty::PolyFnSig<'tcx> {
1093         let sig = match self.entry(id).kind {
1094             EntryKind::Fn(data) |
1095             EntryKind::ForeignFn(data) => data.decode(self).sig,
1096             EntryKind::Method(data) => data.decode(self).fn_data.sig,
1097             EntryKind::Variant(data) |
1098             EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1099             EntryKind::Closure(data) => data.decode(self).sig,
1100             _ => bug!(),
1101         };
1102         sig.decode((self, tcx))
1103     }
1104
1105     fn get_generator_data(&self,
1106                       id: DefIndex,
1107                       tcx: TyCtxt<'a, 'tcx, 'tcx>)
1108                       -> Option<GeneratorData<'tcx>> {
1109         match self.entry(id).kind {
1110             EntryKind::Generator(data) => Some(data.decode((self, tcx))),
1111             _ => None,
1112         }
1113     }
1114
1115     pub fn generator_sig(&self,
1116                       id: DefIndex,
1117                       tcx: TyCtxt<'a, 'tcx, 'tcx>)
1118                       -> Option<ty::PolyGenSig<'tcx>> {
1119         self.get_generator_data(id, tcx).map(|d| d.sig)
1120     }
1121
1122     #[inline]
1123     pub fn def_key(&self, index: DefIndex) -> DefKey {
1124         self.def_path_table.def_key(index)
1125     }
1126
1127     // Returns the path leading to the thing with this `id`.
1128     pub fn def_path(&self, id: DefIndex) -> DefPath {
1129         debug!("def_path(id={:?})", id);
1130         DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1131     }
1132
1133     #[inline]
1134     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1135         self.def_path_table.def_path_hash(index)
1136     }
1137
1138     /// Imports the codemap from an external crate into the codemap of the crate
1139     /// currently being compiled (the "local crate").
1140     ///
1141     /// The import algorithm works analogous to how AST items are inlined from an
1142     /// external crate's metadata:
1143     /// For every FileMap in the external codemap an 'inline' copy is created in the
1144     /// local codemap. The correspondence relation between external and local
1145     /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
1146     /// function. When an item from an external crate is later inlined into this
1147     /// crate, this correspondence information is used to translate the span
1148     /// information of the inlined item so that it refers the correct positions in
1149     /// the local codemap (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1150     ///
1151     /// The import algorithm in the function below will reuse FileMaps already
1152     /// existing in the local codemap. For example, even if the FileMap of some
1153     /// source file of libstd gets imported many times, there will only ever be
1154     /// one FileMap object for the corresponding file in the local codemap.
1155     ///
1156     /// Note that imported FileMaps do not actually contain the source code of the
1157     /// file they represent, just information about length, line breaks, and
1158     /// multibyte characters. This information is enough to generate valid debuginfo
1159     /// for items inlined from other crates.
1160     pub fn imported_filemaps(&'a self,
1161                              local_codemap: &codemap::CodeMap)
1162                              -> Ref<'a, Vec<cstore::ImportedFileMap>> {
1163         {
1164             let filemaps = self.codemap_import_info.borrow();
1165             if !filemaps.is_empty() {
1166                 return filemaps;
1167             }
1168         }
1169
1170         let external_codemap = self.root.codemap.decode(self);
1171
1172         let imported_filemaps = external_codemap.map(|filemap_to_import| {
1173             // We can't reuse an existing FileMap, so allocate a new one
1174             // containing the information we need.
1175             let syntax_pos::FileMap { name,
1176                                       name_was_remapped,
1177                                       src_hash,
1178                                       start_pos,
1179                                       end_pos,
1180                                       lines,
1181                                       multibyte_chars,
1182                                       .. } = filemap_to_import;
1183
1184             let source_length = (end_pos - start_pos).to_usize();
1185
1186             // Translate line-start positions and multibyte character
1187             // position into frame of reference local to file.
1188             // `CodeMap::new_imported_filemap()` will then translate those
1189             // coordinates to their new global frame of reference when the
1190             // offset of the FileMap is known.
1191             let mut lines = lines.into_inner();
1192             for pos in &mut lines {
1193                 *pos = *pos - start_pos;
1194             }
1195             let mut multibyte_chars = multibyte_chars.into_inner();
1196             for mbc in &mut multibyte_chars {
1197                 mbc.pos = mbc.pos - start_pos;
1198             }
1199
1200             let local_version = local_codemap.new_imported_filemap(name,
1201                                                                    name_was_remapped,
1202                                                                    self.cnum.as_u32(),
1203                                                                    src_hash,
1204                                                                    source_length,
1205                                                                    lines,
1206                                                                    multibyte_chars);
1207             debug!("CrateMetaData::imported_filemaps alloc \
1208                     filemap {:?} original (start_pos {:?} end_pos {:?}) \
1209                     translated (start_pos {:?} end_pos {:?})",
1210                    local_version.name, start_pos, end_pos,
1211                    local_version.start_pos, local_version.end_pos);
1212
1213             cstore::ImportedFileMap {
1214                 original_start_pos: start_pos,
1215                 original_end_pos: end_pos,
1216                 translated_filemap: local_version,
1217             }
1218         }).collect();
1219
1220         // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1221         *self.codemap_import_info.borrow_mut() = imported_filemaps;
1222         self.codemap_import_info.borrow()
1223     }
1224
1225     pub fn metadata_dep_node(&self, kind: GlobalMetaDataKind) -> DepNode {
1226         let def_index = kind.def_index(&self.def_path_table);
1227         let def_path_hash = self.def_path_table.def_path_hash(def_index);
1228         def_path_hash.to_dep_node(DepKind::MetaData)
1229     }
1230 }