]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/decoder.rs
Improve intercrate hygiene.
[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::{self, Ident};
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                     let ident = Ident::with_empty_ctxt(name);
671                     callback(def::Export { ident: ident, def: def, span: DUMMY_SP });
672                 }
673             }
674             return
675         }
676
677         // Find the item.
678         let item = match self.maybe_entry(id) {
679             None => return,
680             Some(item) => item.decode(self),
681         };
682
683         // Iterate over all children.
684         let macros_only = self.dep_kind.get().macros_only();
685         for child_index in item.children.decode(self) {
686             if macros_only {
687                 continue
688             }
689
690             // Get the item.
691             if let Some(child) = self.maybe_entry(child_index) {
692                 let child = child.decode(self);
693                 match child.kind {
694                     EntryKind::MacroDef(..) => {}
695                     _ if macros_only => continue,
696                     _ => {}
697                 }
698
699                 // Hand off the item to the callback.
700                 match child.kind {
701                     // FIXME(eddyb) Don't encode these in children.
702                     EntryKind::ForeignMod => {
703                         for child_index in child.children.decode(self) {
704                             if let Some(def) = self.get_def(child_index) {
705                                 callback(def::Export {
706                                     def: def,
707                                     ident: Ident::with_empty_ctxt(self.item_name(child_index)),
708                                     span: self.entry(child_index).span.decode(self),
709                                 });
710                             }
711                         }
712                         continue;
713                     }
714                     EntryKind::Impl(_) |
715                     EntryKind::DefaultImpl(_) => continue,
716
717                     _ => {}
718                 }
719
720                 let def_key = self.def_key(child_index);
721                 let span = child.span.decode(self);
722                 if let (Some(def), Some(name)) =
723                     (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
724                     let ident = Ident::with_empty_ctxt(name);
725                     callback(def::Export { def: def, ident: ident, span: span });
726                     // For non-reexport structs and variants add their constructors to children.
727                     // Reexport lists automatically contain constructors when necessary.
728                     match def {
729                         Def::Struct(..) => {
730                             if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
731                                 let ctor_kind = self.get_ctor_kind(child_index);
732                                 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
733                                 callback(def::Export { def: ctor_def, ident: ident, span: span });
734                             }
735                         }
736                         Def::Variant(def_id) => {
737                             // Braced variants, unlike structs, generate unusable names in
738                             // value namespace, they are reserved for possible future use.
739                             let ctor_kind = self.get_ctor_kind(child_index);
740                             let ctor_def = Def::VariantCtor(def_id, ctor_kind);
741                             callback(def::Export { def: ctor_def, ident: ident, span: span });
742                         }
743                         _ => {}
744                     }
745                 }
746             }
747         }
748
749         if let EntryKind::Mod(data) = item.kind {
750             for exp in data.decode(self).reexports.decode(self) {
751                 match exp.def {
752                     Def::Macro(..) => {}
753                     _ if macros_only => continue,
754                     _ => {}
755                 }
756                 callback(exp);
757             }
758         }
759     }
760
761     pub fn item_body(&self,
762                      tcx: TyCtxt<'a, 'tcx, 'tcx>,
763                      id: DefIndex)
764                      -> &'tcx hir::Body {
765         assert!(!self.is_proc_macro(id));
766         let ast = self.entry(id).ast.unwrap();
767         let def_id = self.local_def_id(id);
768         let body = ast.decode(self).body.decode(self);
769         tcx.hir.intern_inlined_body(def_id, body)
770     }
771
772     pub fn item_body_tables(&self,
773                             id: DefIndex,
774                             tcx: TyCtxt<'a, 'tcx, 'tcx>)
775                             -> &'tcx ty::TypeckTables<'tcx> {
776         let ast = self.entry(id).ast.unwrap().decode(self);
777         tcx.alloc_tables(ast.tables.decode((self, tcx)))
778     }
779
780     pub fn item_body_nested_bodies(&self, id: DefIndex) -> BTreeMap<hir::BodyId, hir::Body> {
781         self.entry(id).ast.into_iter().flat_map(|ast| {
782             ast.decode(self).nested_bodies.decode(self).map(|body| (body.id(), body))
783         }).collect()
784     }
785
786     pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
787         self.entry(id).ast.expect("const item missing `ast`")
788             .decode(self).rvalue_promotable_to_static
789     }
790
791     pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
792         !self.is_proc_macro(id) &&
793         self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
794     }
795
796     pub fn maybe_get_optimized_mir(&self,
797                                    tcx: TyCtxt<'a, 'tcx, 'tcx>,
798                                    id: DefIndex)
799                                    -> Option<Mir<'tcx>> {
800         match self.is_proc_macro(id) {
801             true => None,
802             false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
803         }
804     }
805
806     pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
807         match self.entry(id).kind {
808             EntryKind::Const(qualif) |
809             EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif) |
810             EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif) => {
811                 qualif
812             }
813             _ => bug!(),
814         }
815     }
816
817     pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
818         let item = self.entry(id);
819         let def_key = self.def_key(id);
820         let parent = self.local_def_id(def_key.parent.unwrap());
821         let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
822
823         let (kind, container, has_self) = match item.kind {
824             EntryKind::AssociatedConst(container, _) => {
825                 (ty::AssociatedKind::Const, container, false)
826             }
827             EntryKind::Method(data) => {
828                 let data = data.decode(self);
829                 (ty::AssociatedKind::Method, data.container, data.has_self)
830             }
831             EntryKind::AssociatedType(container) => {
832                 (ty::AssociatedKind::Type, container, false)
833             }
834             _ => bug!("cannot get associated-item of `{:?}`", def_key)
835         };
836
837         ty::AssociatedItem {
838             name: name,
839             kind: kind,
840             vis: item.visibility.decode(self),
841             defaultness: container.defaultness(),
842             def_id: self.local_def_id(id),
843             container: container.with_def_id(parent),
844             method_has_self_argument: has_self
845         }
846     }
847
848     pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
849         self.entry(id).variances.decode(self).collect()
850     }
851
852     pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
853         match self.entry(node_id).kind {
854             EntryKind::Struct(data, _) |
855             EntryKind::Union(data, _) |
856             EntryKind::Variant(data) => data.decode(self).ctor_kind,
857             _ => CtorKind::Fictive,
858         }
859     }
860
861     pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
862         match self.entry(node_id).kind {
863             EntryKind::Struct(data, _) => {
864                 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
865             }
866             _ => None,
867         }
868     }
869
870     pub fn get_item_attrs(&self,
871                           node_id: DefIndex,
872                           dep_graph: &DepGraph) -> Rc<[ast::Attribute]> {
873         let (node_as, node_index) =
874             (node_id.address_space().index(), node_id.as_array_index());
875         if self.is_proc_macro(node_id) {
876             return Rc::new([]);
877         }
878
879         dep_graph.read(DepNode::MetaData(self.local_def_id(node_id)));
880
881         if let Some(&Some(ref val)) =
882             self.attribute_cache.borrow()[node_as].get(node_index) {
883             return val.clone();
884         }
885
886         // The attributes for a tuple struct are attached to the definition, not the ctor;
887         // we assume that someone passing in a tuple struct ctor is actually wanting to
888         // look at the definition
889         let mut item = self.entry(node_id);
890         let def_key = self.def_key(node_id);
891         if def_key.disambiguated_data.data == DefPathData::StructCtor {
892             item = self.entry(def_key.parent.unwrap());
893         }
894         let result = Rc::__from_array(self.get_attributes(&item).into_boxed_slice());
895         let vec_ = &mut self.attribute_cache.borrow_mut()[node_as];
896         if vec_.len() < node_index + 1 {
897             vec_.resize(node_index + 1, None);
898         }
899         vec_[node_index] = Some(result.clone());
900         result
901     }
902
903     pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
904         self.entry(id)
905             .children
906             .decode(self)
907             .map(|index| self.item_name(index))
908             .collect()
909     }
910
911     fn get_attributes(&self, item: &Entry<'tcx>) -> Vec<ast::Attribute> {
912         item.attributes
913             .decode(self)
914             .map(|mut attr| {
915                 // Need new unique IDs: old thread-local IDs won't map to new threads.
916                 attr.id = attr::mk_attr_id();
917                 attr
918             })
919             .collect()
920     }
921
922     // Translate a DefId from the current compilation environment to a DefId
923     // for an external crate.
924     fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
925         for (local, &global) in self.cnum_map.borrow().iter_enumerated() {
926             if global == did.krate {
927                 return Some(DefId {
928                     krate: local,
929                     index: did.index,
930                 });
931             }
932         }
933
934         None
935     }
936
937     pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
938         self.entry(id)
939             .inherent_impls
940             .decode(self)
941             .map(|index| self.local_def_id(index))
942             .collect()
943     }
944
945     pub fn get_implementations_for_trait(&self,
946                                          filter: Option<DefId>,
947                                          dep_graph: &DepGraph,
948                                          result: &mut Vec<DefId>) {
949         // Do a reverse lookup beforehand to avoid touching the crate_num
950         // hash map in the loop below.
951         let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
952             Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
953             Some(None) => return,
954             None if self.proc_macros.is_some() => return,
955             None => None,
956         };
957
958         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::Impls);
959
960         if let Some(filter) = filter {
961             if let Some(impls) = self.trait_impls
962                                      .get(dep_graph, dep_node)
963                                      .get(&filter) {
964                 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
965             }
966         } else {
967             for impls in self.trait_impls.get(dep_graph, dep_node).values() {
968                 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
969             }
970         }
971     }
972
973     pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
974         self.def_key(id).parent.and_then(|parent_index| {
975             match self.entry(parent_index).kind {
976                 EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
977                 _ => None,
978             }
979         })
980     }
981
982
983     pub fn get_native_libraries(&self,
984                                 dep_graph: &DepGraph)
985                                 -> Vec<NativeLibrary> {
986         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries);
987         self.root
988             .native_libraries
989             .get(dep_graph, dep_node)
990             .decode(self)
991             .collect()
992     }
993
994     pub fn get_dylib_dependency_formats(&self,
995                                         dep_graph: &DepGraph)
996                                         -> Vec<(CrateNum, LinkagePreference)> {
997         let def_id = DefId {
998             krate: self.cnum,
999             index: CRATE_DEF_INDEX,
1000         };
1001         let dep_node = DepNode::GlobalMetaData(def_id,
1002                                                GlobalMetaDataKind::DylibDependencyFormats);
1003         self.root
1004             .dylib_dependency_formats
1005             .get(dep_graph, dep_node)
1006             .decode(self)
1007             .enumerate()
1008             .flat_map(|(i, link)| {
1009                 let cnum = CrateNum::new(i + 1);
1010                 link.map(|link| (self.cnum_map.borrow()[cnum], link))
1011             })
1012             .collect()
1013     }
1014
1015     pub fn get_missing_lang_items(&self, dep_graph: &DepGraph) -> Vec<lang_items::LangItem> {
1016         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItemsMissing);
1017         self.root
1018             .lang_items_missing
1019             .get(dep_graph, dep_node)
1020             .decode(self)
1021             .collect()
1022     }
1023
1024     pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
1025         let arg_names = match self.entry(id).kind {
1026             EntryKind::Fn(data) |
1027             EntryKind::ForeignFn(data) => data.decode(self).arg_names,
1028             EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
1029             _ => LazySeq::empty(),
1030         };
1031         arg_names.decode(self).collect()
1032     }
1033
1034     pub fn get_exported_symbols(&self, dep_graph: &DepGraph) -> Vec<DefId> {
1035         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols);
1036         self.exported_symbols
1037             .get(dep_graph, dep_node)
1038             .iter()
1039             .map(|&index| self.local_def_id(index))
1040             .collect()
1041     }
1042
1043     pub fn get_macro(&self, id: DefIndex) -> (ast::Name, MacroDef) {
1044         let entry = self.entry(id);
1045         match entry.kind {
1046             EntryKind::MacroDef(macro_def) => (self.item_name(id), macro_def.decode(self)),
1047             _ => bug!(),
1048         }
1049     }
1050
1051     pub fn is_const_fn(&self, id: DefIndex) -> bool {
1052         let constness = match self.entry(id).kind {
1053             EntryKind::Method(data) => data.decode(self).fn_data.constness,
1054             EntryKind::Fn(data) => data.decode(self).constness,
1055             _ => hir::Constness::NotConst,
1056         };
1057         constness == hir::Constness::Const
1058     }
1059
1060     pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1061         match self.entry(id).kind {
1062             EntryKind::ForeignImmStatic |
1063             EntryKind::ForeignMutStatic |
1064             EntryKind::ForeignFn(_) => true,
1065             _ => false,
1066         }
1067     }
1068
1069     pub fn is_dllimport_foreign_item(&self, id: DefIndex, dep_graph: &DepGraph) -> bool {
1070         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries);
1071         self.dllimport_foreign_items
1072             .get(dep_graph, dep_node)
1073             .contains(&id)
1074     }
1075
1076     pub fn is_default_impl(&self, impl_id: DefIndex) -> bool {
1077         match self.entry(impl_id).kind {
1078             EntryKind::DefaultImpl(_) => true,
1079             _ => false,
1080         }
1081     }
1082
1083     pub fn closure_kind(&self, closure_id: DefIndex) -> ty::ClosureKind {
1084         match self.entry(closure_id).kind {
1085             EntryKind::Closure(data) => data.decode(self).kind,
1086             _ => bug!(),
1087         }
1088     }
1089
1090     pub fn closure_ty(&self,
1091                       closure_id: DefIndex,
1092                       tcx: TyCtxt<'a, 'tcx, 'tcx>)
1093                       -> ty::PolyFnSig<'tcx> {
1094         match self.entry(closure_id).kind {
1095             EntryKind::Closure(data) => data.decode(self).ty.decode((self, tcx)),
1096             _ => bug!(),
1097         }
1098     }
1099
1100     #[inline]
1101     pub fn def_key(&self, index: DefIndex) -> DefKey {
1102         self.def_path_table.def_key(index)
1103     }
1104
1105     // Returns the path leading to the thing with this `id`.
1106     pub fn def_path(&self, id: DefIndex) -> DefPath {
1107         debug!("def_path(id={:?})", id);
1108         DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1109     }
1110
1111     #[inline]
1112     pub fn def_path_hash(&self, index: DefIndex) -> ich::Fingerprint {
1113         self.def_path_table.def_path_hash(index)
1114     }
1115
1116     /// Imports the codemap from an external crate into the codemap of the crate
1117     /// currently being compiled (the "local crate").
1118     ///
1119     /// The import algorithm works analogous to how AST items are inlined from an
1120     /// external crate's metadata:
1121     /// For every FileMap in the external codemap an 'inline' copy is created in the
1122     /// local codemap. The correspondence relation between external and local
1123     /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
1124     /// function. When an item from an external crate is later inlined into this
1125     /// crate, this correspondence information is used to translate the span
1126     /// information of the inlined item so that it refers the correct positions in
1127     /// the local codemap (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1128     ///
1129     /// The import algorithm in the function below will reuse FileMaps already
1130     /// existing in the local codemap. For example, even if the FileMap of some
1131     /// source file of libstd gets imported many times, there will only ever be
1132     /// one FileMap object for the corresponding file in the local codemap.
1133     ///
1134     /// Note that imported FileMaps do not actually contain the source code of the
1135     /// file they represent, just information about length, line breaks, and
1136     /// multibyte characters. This information is enough to generate valid debuginfo
1137     /// for items inlined from other crates.
1138     pub fn imported_filemaps(&'a self,
1139                              local_codemap: &codemap::CodeMap)
1140                              -> Ref<'a, Vec<cstore::ImportedFileMap>> {
1141         {
1142             let filemaps = self.codemap_import_info.borrow();
1143             if !filemaps.is_empty() {
1144                 return filemaps;
1145             }
1146         }
1147
1148         let external_codemap = self.root.codemap.decode(self);
1149
1150         let imported_filemaps = external_codemap.map(|filemap_to_import| {
1151             // We can't reuse an existing FileMap, so allocate a new one
1152             // containing the information we need.
1153             let syntax_pos::FileMap { name,
1154                                       name_was_remapped,
1155                                       start_pos,
1156                                       end_pos,
1157                                       lines,
1158                                       multibyte_chars,
1159                                       .. } = filemap_to_import;
1160
1161             let source_length = (end_pos - start_pos).to_usize();
1162
1163             // Translate line-start positions and multibyte character
1164             // position into frame of reference local to file.
1165             // `CodeMap::new_imported_filemap()` will then translate those
1166             // coordinates to their new global frame of reference when the
1167             // offset of the FileMap is known.
1168             let mut lines = lines.into_inner();
1169             for pos in &mut lines {
1170                 *pos = *pos - start_pos;
1171             }
1172             let mut multibyte_chars = multibyte_chars.into_inner();
1173             for mbc in &mut multibyte_chars {
1174                 mbc.pos = mbc.pos - start_pos;
1175             }
1176
1177             let local_version = local_codemap.new_imported_filemap(name,
1178                                                                    name_was_remapped,
1179                                                                    self.cnum.as_u32(),
1180                                                                    source_length,
1181                                                                    lines,
1182                                                                    multibyte_chars);
1183             debug!("CrateMetaData::imported_filemaps alloc \
1184                     filemap {:?} original (start_pos {:?} end_pos {:?}) \
1185                     translated (start_pos {:?} end_pos {:?})",
1186                    local_version.name, start_pos, end_pos,
1187                    local_version.start_pos, local_version.end_pos);
1188
1189             cstore::ImportedFileMap {
1190                 original_start_pos: start_pos,
1191                 original_end_pos: end_pos,
1192                 translated_filemap: local_version,
1193             }
1194         }).collect();
1195
1196         // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1197         *self.codemap_import_info.borrow_mut() = imported_filemaps;
1198         self.codemap_import_info.borrow()
1199     }
1200
1201     pub fn metadata_dep_node(&self, kind: GlobalMetaDataKind) -> DepNode<DefId> {
1202         let def_id = DefId {
1203             krate: self.cnum,
1204             index: CRATE_DEF_INDEX,
1205         };
1206
1207         DepNode::GlobalMetaData(def_id, kind)
1208     }
1209 }