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