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