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