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