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