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