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