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