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