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