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