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