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