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