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