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