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