]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/decoder.rs
rustc: Rename item_body query to extern_const_body
[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, DepKind};
17 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash};
18 use rustc::hir::map::definitions::GlobalMetaDataKind;
19 use rustc::hir;
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,
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::new(lo, hi, 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::new(lo, hi, 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::Generator(_) |
442             EntryKind::Closure(_) => return None,
443         })
444     }
445 }
446
447 impl<'a, 'tcx> CrateMetadata {
448     fn is_proc_macro(&self, id: DefIndex) -> bool {
449         self.proc_macros.is_some() && id != CRATE_DEF_INDEX
450     }
451
452     fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
453         assert!(!self.is_proc_macro(item_id));
454         self.root.index.lookup(self.blob.raw_bytes(), item_id)
455     }
456
457     fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
458         match self.maybe_entry(item_id) {
459             None => {
460                 bug!("entry: id not found: {:?} in crate {:?} with number {}",
461                      item_id,
462                      self.name,
463                      self.cnum)
464             }
465             Some(d) => d.decode(self),
466         }
467     }
468
469     fn local_def_id(&self, index: DefIndex) -> DefId {
470         DefId {
471             krate: self.cnum,
472             index,
473         }
474     }
475
476     pub fn item_name(&self, item_index: DefIndex) -> ast::Name {
477         self.def_key(item_index)
478             .disambiguated_data
479             .data
480             .get_opt_name()
481             .expect("no name in item_name")
482     }
483
484     pub fn get_def(&self, index: DefIndex) -> Option<Def> {
485         if !self.is_proc_macro(index) {
486             self.entry(index).kind.to_def(self.local_def_id(index))
487         } else {
488             let kind = self.proc_macros.as_ref().unwrap()[index.as_usize() - 1].1.kind();
489             Some(Def::Macro(self.local_def_id(index), kind))
490         }
491     }
492
493     pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
494         match self.is_proc_macro(index) {
495             true => DUMMY_SP,
496             false => self.entry(index).span.decode((self, sess)),
497         }
498     }
499
500     pub fn get_trait_def(&self, item_id: DefIndex) -> ty::TraitDef {
501         let data = match self.entry(item_id).kind {
502             EntryKind::Trait(data) => data.decode(self),
503             _ => bug!(),
504         };
505
506         ty::TraitDef::new(self.local_def_id(item_id),
507                           data.unsafety,
508                           data.paren_sugar,
509                           data.has_default_impl,
510                           self.def_path_table.def_path_hash(item_id))
511     }
512
513     fn get_variant(&self, item: &Entry, index: DefIndex) -> ty::VariantDef {
514         let data = match item.kind {
515             EntryKind::Variant(data) |
516             EntryKind::Struct(data, _) |
517             EntryKind::Union(data, _) => data.decode(self),
518             _ => bug!(),
519         };
520
521         ty::VariantDef {
522             did: self.local_def_id(data.struct_ctor.unwrap_or(index)),
523             name: self.item_name(index),
524             fields: item.children.decode(self).map(|index| {
525                 let f = self.entry(index);
526                 ty::FieldDef {
527                     did: self.local_def_id(index),
528                     name: self.item_name(index),
529                     vis: f.visibility.decode(self)
530                 }
531             }).collect(),
532             discr: data.discr,
533             ctor_kind: data.ctor_kind,
534         }
535     }
536
537     pub fn get_adt_def(&self,
538                        item_id: DefIndex,
539                        tcx: TyCtxt<'a, 'tcx, 'tcx>)
540                        -> &'tcx ty::AdtDef {
541         let item = self.entry(item_id);
542         let did = self.local_def_id(item_id);
543         let kind = match item.kind {
544             EntryKind::Enum(_) => ty::AdtKind::Enum,
545             EntryKind::Struct(_, _) => ty::AdtKind::Struct,
546             EntryKind::Union(_, _) => ty::AdtKind::Union,
547             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
548         };
549         let variants = if let ty::AdtKind::Enum = kind {
550             item.children
551                 .decode(self)
552                 .map(|index| {
553                     self.get_variant(&self.entry(index), index)
554                 })
555                 .collect()
556         } else {
557             vec![self.get_variant(&item, item_id)]
558         };
559         let (kind, repr) = match item.kind {
560             EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
561             EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
562             EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
563             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
564         };
565
566         tcx.alloc_adt_def(did, kind, variants, repr)
567     }
568
569     pub fn get_predicates(&self,
570                           item_id: DefIndex,
571                           tcx: TyCtxt<'a, 'tcx, 'tcx>)
572                           -> ty::GenericPredicates<'tcx> {
573         self.entry(item_id).predicates.unwrap().decode((self, tcx))
574     }
575
576     pub fn get_super_predicates(&self,
577                                 item_id: DefIndex,
578                                 tcx: TyCtxt<'a, 'tcx, 'tcx>)
579                                 -> ty::GenericPredicates<'tcx> {
580         match self.entry(item_id).kind {
581             EntryKind::Trait(data) => data.decode(self).super_predicates.decode((self, tcx)),
582             _ => bug!(),
583         }
584     }
585
586     pub fn get_generics(&self, item_id: DefIndex) -> ty::Generics {
587         self.entry(item_id).generics.unwrap().decode(self)
588     }
589
590     pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
591         self.entry(id).ty.unwrap().decode((self, tcx))
592     }
593
594     pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
595         match self.is_proc_macro(id) {
596             true => None,
597             false => self.entry(id).stability.map(|stab| stab.decode(self)),
598         }
599     }
600
601     pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
602         match self.is_proc_macro(id) {
603             true => None,
604             false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
605         }
606     }
607
608     pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
609         match self.is_proc_macro(id) {
610             true => ty::Visibility::Public,
611             false => self.entry(id).visibility.decode(self),
612         }
613     }
614
615     fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
616         match self.entry(id).kind {
617             EntryKind::Impl(data) => data.decode(self),
618             _ => bug!(),
619         }
620     }
621
622     pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
623         self.get_impl_data(id).parent_impl
624     }
625
626     pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
627         self.get_impl_data(id).polarity
628     }
629
630     pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
631         self.get_impl_data(id).defaultness
632     }
633
634     pub fn get_coerce_unsized_info(&self,
635                                    id: DefIndex)
636                                    -> Option<ty::adjustment::CoerceUnsizedInfo> {
637         self.get_impl_data(id).coerce_unsized_info
638     }
639
640     pub fn get_impl_trait(&self,
641                           id: DefIndex,
642                           tcx: TyCtxt<'a, 'tcx, 'tcx>)
643                           -> Option<ty::TraitRef<'tcx>> {
644         self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
645     }
646
647     /// Iterates over the language items in the given crate.
648     pub fn get_lang_items(&self, dep_graph: &DepGraph) -> Vec<(DefIndex, usize)> {
649         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItems);
650         self.root
651             .lang_items
652             .get(dep_graph, dep_node)
653             .decode(self)
654             .collect()
655     }
656
657     /// Iterates over each child of the given item.
658     pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
659         where F: FnMut(def::Export)
660     {
661         if let Some(ref proc_macros) = self.proc_macros {
662             if id == CRATE_DEF_INDEX {
663                 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
664                     let def = Def::Macro(
665                         DefId {
666                             krate: self.cnum,
667                             index: DefIndex::new(id + 1)
668                         },
669                         ext.kind()
670                     );
671                     let ident = Ident::with_empty_ctxt(name);
672                     callback(def::Export { ident: ident, def: def, span: DUMMY_SP });
673                 }
674             }
675             return
676         }
677
678         // Find the item.
679         let item = match self.maybe_entry(id) {
680             None => return,
681             Some(item) => item.decode((self, sess)),
682         };
683
684         // Iterate over all children.
685         let macros_only = self.dep_kind.get().macros_only();
686         for child_index in item.children.decode((self, sess)) {
687             if macros_only {
688                 continue
689             }
690
691             // Get the item.
692             if let Some(child) = self.maybe_entry(child_index) {
693                 let child = child.decode((self, sess));
694                 match child.kind {
695                     EntryKind::MacroDef(..) => {}
696                     _ if macros_only => continue,
697                     _ => {}
698                 }
699
700                 // Hand off the item to the callback.
701                 match child.kind {
702                     // FIXME(eddyb) Don't encode these in children.
703                     EntryKind::ForeignMod => {
704                         for child_index in child.children.decode((self, sess)) {
705                             if let Some(def) = self.get_def(child_index) {
706                                 callback(def::Export {
707                                     def,
708                                     ident: Ident::with_empty_ctxt(self.item_name(child_index)),
709                                     span: self.entry(child_index).span.decode((self, sess)),
710                                 });
711                             }
712                         }
713                         continue;
714                     }
715                     EntryKind::Impl(_) |
716                     EntryKind::DefaultImpl(_) => continue,
717
718                     _ => {}
719                 }
720
721                 let def_key = self.def_key(child_index);
722                 let span = child.span.decode((self, sess));
723                 if let (Some(def), Some(name)) =
724                     (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
725                     let ident = Ident::with_empty_ctxt(name);
726                     callback(def::Export { def: def, ident: ident, span: span });
727                     // For non-reexport structs and variants add their constructors to children.
728                     // Reexport lists automatically contain constructors when necessary.
729                     match def {
730                         Def::Struct(..) => {
731                             if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
732                                 let ctor_kind = self.get_ctor_kind(child_index);
733                                 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
734                                 callback(def::Export { def: ctor_def, ident: ident, span: span });
735                             }
736                         }
737                         Def::Variant(def_id) => {
738                             // Braced variants, unlike structs, generate unusable names in
739                             // value namespace, they are reserved for possible future use.
740                             let ctor_kind = self.get_ctor_kind(child_index);
741                             let ctor_def = Def::VariantCtor(def_id, ctor_kind);
742                             callback(def::Export { def: ctor_def, ident: ident, span: span });
743                         }
744                         _ => {}
745                     }
746                 }
747             }
748         }
749
750         if let EntryKind::Mod(data) = item.kind {
751             for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
752                 match exp.def {
753                     Def::Macro(..) => {}
754                     _ if macros_only => continue,
755                     _ => {}
756                 }
757                 callback(exp);
758             }
759         }
760     }
761
762     pub fn extern_const_body(&self,
763                              tcx: TyCtxt<'a, 'tcx, 'tcx>,
764                              id: DefIndex)
765                              -> &'tcx hir::Body {
766         assert!(!self.is_proc_macro(id));
767         let ast = self.entry(id).ast.unwrap();
768         let def_id = self.local_def_id(id);
769         let body = ast.decode((self, tcx)).body.decode((self, tcx));
770         tcx.hir.intern_inlined_body(def_id, body)
771     }
772
773     pub fn item_body_tables(&self,
774                             id: DefIndex,
775                             tcx: TyCtxt<'a, 'tcx, 'tcx>)
776                             -> &'tcx ty::TypeckTables<'tcx> {
777         let ast = self.entry(id).ast.unwrap().decode(self);
778         tcx.alloc_tables(ast.tables.decode((self, tcx)))
779     }
780
781     pub fn item_body_nested_bodies(&self, id: DefIndex) -> BTreeMap<hir::BodyId, hir::Body> {
782         self.entry(id).ast.into_iter().flat_map(|ast| {
783             ast.decode(self).nested_bodies.decode(self).map(|body| (body.id(), body))
784         }).collect()
785     }
786
787     pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
788         self.entry(id).ast.expect("const item missing `ast`")
789             .decode(self).rvalue_promotable_to_static
790     }
791
792     pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
793         !self.is_proc_macro(id) &&
794         self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
795     }
796
797     pub fn maybe_get_optimized_mir(&self,
798                                    tcx: TyCtxt<'a, 'tcx, 'tcx>,
799                                    id: DefIndex)
800                                    -> Option<Mir<'tcx>> {
801         match self.is_proc_macro(id) {
802             true => None,
803             false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
804         }
805     }
806
807     pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
808         match self.entry(id).kind {
809             EntryKind::Const(qualif) |
810             EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif) |
811             EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif) => {
812                 qualif
813             }
814             _ => bug!(),
815         }
816     }
817
818     pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
819         let item = self.entry(id);
820         let def_key = self.def_key(id);
821         let parent = self.local_def_id(def_key.parent.unwrap());
822         let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
823
824         let (kind, container, has_self) = match item.kind {
825             EntryKind::AssociatedConst(container, _) => {
826                 (ty::AssociatedKind::Const, container, false)
827             }
828             EntryKind::Method(data) => {
829                 let data = data.decode(self);
830                 (ty::AssociatedKind::Method, data.container, data.has_self)
831             }
832             EntryKind::AssociatedType(container) => {
833                 (ty::AssociatedKind::Type, container, false)
834             }
835             _ => bug!("cannot get associated-item of `{:?}`", def_key)
836         };
837
838         ty::AssociatedItem {
839             name,
840             kind,
841             vis: item.visibility.decode(self),
842             defaultness: container.defaultness(),
843             def_id: self.local_def_id(id),
844             container: container.with_def_id(parent),
845             method_has_self_argument: has_self
846         }
847     }
848
849     pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
850         self.entry(id).variances.decode(self).collect()
851     }
852
853     pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
854         match self.entry(node_id).kind {
855             EntryKind::Struct(data, _) |
856             EntryKind::Union(data, _) |
857             EntryKind::Variant(data) => data.decode(self).ctor_kind,
858             _ => CtorKind::Fictive,
859         }
860     }
861
862     pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
863         match self.entry(node_id).kind {
864             EntryKind::Struct(data, _) => {
865                 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
866             }
867             _ => None,
868         }
869     }
870
871     pub fn get_item_attrs(&self,
872                           node_id: DefIndex,
873                           dep_graph: &DepGraph) -> Rc<[ast::Attribute]> {
874         let (node_as, node_index) =
875             (node_id.address_space().index(), node_id.as_array_index());
876         if self.is_proc_macro(node_id) {
877             return Rc::new([]);
878         }
879
880         let dep_node = self.def_path_hash(node_id).to_dep_node(DepKind::MetaData);
881         dep_graph.read(dep_node);
882
883         if let Some(&Some(ref val)) =
884             self.attribute_cache.borrow()[node_as].get(node_index) {
885             return val.clone();
886         }
887
888         // The attributes for a tuple struct are attached to the definition, not the ctor;
889         // we assume that someone passing in a tuple struct ctor is actually wanting to
890         // look at the definition
891         let mut item = self.entry(node_id);
892         let def_key = self.def_key(node_id);
893         if def_key.disambiguated_data.data == DefPathData::StructCtor {
894             item = self.entry(def_key.parent.unwrap());
895         }
896         let result: Rc<[ast::Attribute]> = Rc::from(self.get_attributes(&item));
897         let vec_ = &mut self.attribute_cache.borrow_mut()[node_as];
898         if vec_.len() < node_index + 1 {
899             vec_.resize(node_index + 1, None);
900         }
901         vec_[node_index] = Some(result.clone());
902         result
903     }
904
905     pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
906         self.entry(id)
907             .children
908             .decode(self)
909             .map(|index| self.item_name(index))
910             .collect()
911     }
912
913     fn get_attributes(&self, item: &Entry<'tcx>) -> Vec<ast::Attribute> {
914         item.attributes
915             .decode(self)
916             .map(|mut attr| {
917                 // Need new unique IDs: old thread-local IDs won't map to new threads.
918                 attr.id = attr::mk_attr_id();
919                 attr
920             })
921             .collect()
922     }
923
924     // Translate a DefId from the current compilation environment to a DefId
925     // for an external crate.
926     fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
927         for (local, &global) in self.cnum_map.borrow().iter_enumerated() {
928             if global == did.krate {
929                 return Some(DefId {
930                     krate: local,
931                     index: did.index,
932                 });
933             }
934         }
935
936         None
937     }
938
939     pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
940         self.entry(id)
941             .inherent_impls
942             .decode(self)
943             .map(|index| self.local_def_id(index))
944             .collect()
945     }
946
947     pub fn get_implementations_for_trait(&self,
948                                          filter: Option<DefId>,
949                                          dep_graph: &DepGraph,
950                                          result: &mut Vec<DefId>) {
951         // Do a reverse lookup beforehand to avoid touching the crate_num
952         // hash map in the loop below.
953         let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
954             Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
955             Some(None) => return,
956             None if self.proc_macros.is_some() => return,
957             None => None,
958         };
959
960         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::Impls);
961
962         if let Some(filter) = filter {
963             if let Some(impls) = self.trait_impls
964                                      .get(dep_graph, dep_node)
965                                      .get(&filter) {
966                 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
967             }
968         } else {
969             for impls in self.trait_impls.get(dep_graph, dep_node).values() {
970                 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
971             }
972         }
973     }
974
975     pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
976         self.def_key(id).parent.and_then(|parent_index| {
977             match self.entry(parent_index).kind {
978                 EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
979                 _ => None,
980             }
981         })
982     }
983
984
985     pub fn get_native_libraries(&self,
986                                 dep_graph: &DepGraph)
987                                 -> Vec<NativeLibrary> {
988         let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries);
989         self.root
990             .native_libraries
991             .get(dep_graph, dep_node)
992             .decode(self)
993             .collect()
994     }
995
996     pub fn get_dylib_dependency_formats(&self,
997                                         dep_graph: &DepGraph)
998                                         -> Vec<(CrateNum, LinkagePreference)> {
999         let dep_node =
1000             self.metadata_dep_node(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 fn_sig(&self,
1089                   id: DefIndex,
1090                   tcx: TyCtxt<'a, 'tcx, 'tcx>)
1091                   -> ty::PolyFnSig<'tcx> {
1092         let sig = match self.entry(id).kind {
1093             EntryKind::Fn(data) |
1094             EntryKind::ForeignFn(data) => data.decode(self).sig,
1095             EntryKind::Method(data) => data.decode(self).fn_data.sig,
1096             EntryKind::Variant(data) |
1097             EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1098             EntryKind::Closure(data) => data.decode(self).sig,
1099             _ => bug!(),
1100         };
1101         sig.decode((self, tcx))
1102     }
1103
1104     fn get_generator_data(&self,
1105                       id: DefIndex,
1106                       tcx: TyCtxt<'a, 'tcx, 'tcx>)
1107                       -> Option<GeneratorData<'tcx>> {
1108         match self.entry(id).kind {
1109             EntryKind::Generator(data) => Some(data.decode((self, tcx))),
1110             _ => None,
1111         }
1112     }
1113
1114     pub fn generator_sig(&self,
1115                       id: DefIndex,
1116                       tcx: TyCtxt<'a, 'tcx, 'tcx>)
1117                       -> Option<ty::PolyGenSig<'tcx>> {
1118         self.get_generator_data(id, tcx).map(|d| d.sig)
1119     }
1120
1121     #[inline]
1122     pub fn def_key(&self, index: DefIndex) -> DefKey {
1123         self.def_path_table.def_key(index)
1124     }
1125
1126     // Returns the path leading to the thing with this `id`.
1127     pub fn def_path(&self, id: DefIndex) -> DefPath {
1128         debug!("def_path(id={:?})", id);
1129         DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1130     }
1131
1132     #[inline]
1133     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1134         self.def_path_table.def_path_hash(index)
1135     }
1136
1137     /// Imports the codemap from an external crate into the codemap of the crate
1138     /// currently being compiled (the "local crate").
1139     ///
1140     /// The import algorithm works analogous to how AST items are inlined from an
1141     /// external crate's metadata:
1142     /// For every FileMap in the external codemap an 'inline' copy is created in the
1143     /// local codemap. The correspondence relation between external and local
1144     /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
1145     /// function. When an item from an external crate is later inlined into this
1146     /// crate, this correspondence information is used to translate the span
1147     /// information of the inlined item so that it refers the correct positions in
1148     /// the local codemap (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1149     ///
1150     /// The import algorithm in the function below will reuse FileMaps already
1151     /// existing in the local codemap. For example, even if the FileMap of some
1152     /// source file of libstd gets imported many times, there will only ever be
1153     /// one FileMap object for the corresponding file in the local codemap.
1154     ///
1155     /// Note that imported FileMaps do not actually contain the source code of the
1156     /// file they represent, just information about length, line breaks, and
1157     /// multibyte characters. This information is enough to generate valid debuginfo
1158     /// for items inlined from other crates.
1159     pub fn imported_filemaps(&'a self,
1160                              local_codemap: &codemap::CodeMap)
1161                              -> Ref<'a, Vec<cstore::ImportedFileMap>> {
1162         {
1163             let filemaps = self.codemap_import_info.borrow();
1164             if !filemaps.is_empty() {
1165                 return filemaps;
1166             }
1167         }
1168
1169         let external_codemap = self.root.codemap.decode(self);
1170
1171         let imported_filemaps = external_codemap.map(|filemap_to_import| {
1172             // We can't reuse an existing FileMap, so allocate a new one
1173             // containing the information we need.
1174             let syntax_pos::FileMap { name,
1175                                       name_was_remapped,
1176                                       src_hash,
1177                                       start_pos,
1178                                       end_pos,
1179                                       lines,
1180                                       multibyte_chars,
1181                                       .. } = filemap_to_import;
1182
1183             let source_length = (end_pos - start_pos).to_usize();
1184
1185             // Translate line-start positions and multibyte character
1186             // position into frame of reference local to file.
1187             // `CodeMap::new_imported_filemap()` will then translate those
1188             // coordinates to their new global frame of reference when the
1189             // offset of the FileMap is known.
1190             let mut lines = lines.into_inner();
1191             for pos in &mut lines {
1192                 *pos = *pos - start_pos;
1193             }
1194             let mut multibyte_chars = multibyte_chars.into_inner();
1195             for mbc in &mut multibyte_chars {
1196                 mbc.pos = mbc.pos - start_pos;
1197             }
1198
1199             let local_version = local_codemap.new_imported_filemap(name,
1200                                                                    name_was_remapped,
1201                                                                    self.cnum.as_u32(),
1202                                                                    src_hash,
1203                                                                    source_length,
1204                                                                    lines,
1205                                                                    multibyte_chars);
1206             debug!("CrateMetaData::imported_filemaps alloc \
1207                     filemap {:?} original (start_pos {:?} end_pos {:?}) \
1208                     translated (start_pos {:?} end_pos {:?})",
1209                    local_version.name, start_pos, end_pos,
1210                    local_version.start_pos, local_version.end_pos);
1211
1212             cstore::ImportedFileMap {
1213                 original_start_pos: start_pos,
1214                 original_end_pos: end_pos,
1215                 translated_filemap: local_version,
1216             }
1217         }).collect();
1218
1219         // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1220         *self.codemap_import_info.borrow_mut() = imported_filemaps;
1221         self.codemap_import_info.borrow()
1222     }
1223
1224     pub fn metadata_dep_node(&self, kind: GlobalMetaDataKind) -> DepNode {
1225         let def_index = kind.def_index(&self.def_path_table);
1226         let def_path_hash = self.def_path_table.def_path_hash(def_index);
1227         def_path_hash.to_dep_node(DepKind::MetaData)
1228     }
1229 }