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