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