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