]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/decoder.rs
Remove unused code from remaining compiler crates
[rust.git] / compiler / rustc_metadata / src / 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 as ast;
8 use rustc_attr as attr;
9 use rustc_data_structures::captures::Captures;
10 use rustc_data_structures::fingerprint::{Fingerprint, FingerprintDecoder};
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::svh::Svh;
13 use rustc_data_structures::sync::{AtomicCell, Lock, LockGuard, Lrc, OnceCell};
14 use rustc_errors::ErrorReported;
15 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
16 use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, ProcMacroDerive};
17 use rustc_hir as hir;
18 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
19 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
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, NativeLib};
27 use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
28 use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
29 use rustc_middle::mir::{self, Body, Promoted};
30 use rustc_middle::ty::codec::TyDecoder;
31 use rustc_middle::ty::{self, Ty, TyCtxt};
32 use rustc_serialize::{opaque, Decodable, Decoder};
33 use rustc_session::Session;
34 use rustc_span::hygiene::ExpnDataDecodeMode;
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{sym, Ident, Symbol};
37 use rustc_span::{self, hygiene::MacroKind, BytePos, ExpnId, Pos, Span, SyntaxContext, DUMMY_SP};
38
39 use proc_macro::bridge::client::ProcMacro;
40 use std::cell::Cell;
41 use std::io;
42 use std::mem;
43 use std::num::NonZeroUsize;
44 use std::path::Path;
45 use tracing::debug;
46
47 pub use cstore_impl::{provide, provide_extern};
48 use rustc_span::hygiene::HygieneDecodeContext;
49
50 mod cstore_impl;
51
52 crate struct MetadataBlob(MetadataRef);
53
54 // A map from external crate numbers (as decoded from some crate file) to
55 // local crate numbers (as generated during this session). Each external
56 // crate may refer to types in other external crates, and each has their
57 // own crate numbers.
58 crate type CrateNumMap = IndexVec<CrateNum, CrateNum>;
59
60 crate struct CrateMetadata {
61     /// The primary crate data - binary metadata blob.
62     blob: MetadataBlob,
63
64     // --- Some data pre-decoded from the metadata blob, usually for performance ---
65     /// Properties of the whole crate.
66     /// NOTE(eddyb) we pass `'static` to a `'tcx` parameter because this
67     /// lifetime is only used behind `Lazy`, and therefore acts like an
68     /// universal (`for<'tcx>`), that is paired up with whichever `TyCtxt`
69     /// is being used to decode those values.
70     root: CrateRoot<'static>,
71     /// Trait impl data.
72     /// FIXME: Used only from queries and can use query cache,
73     /// so pre-decoding can probably be avoided.
74     trait_impls:
75         FxHashMap<(u32, DefIndex), Lazy<[(DefIndex, Option<ty::fast_reject::SimplifiedType>)]>>,
76     /// Proc macro descriptions for this crate, if it's a proc macro crate.
77     raw_proc_macros: Option<&'static [ProcMacro]>,
78     /// Source maps for code from the crate.
79     source_map_import_info: OnceCell<Vec<ImportedSourceFile>>,
80     /// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
81     alloc_decoding_state: AllocDecodingState,
82     /// The `DepNodeIndex` of the `DepNode` representing this upstream crate.
83     /// It is initialized on the first access in `get_crate_dep_node_index()`.
84     /// Do not access the value directly, as it might not have been initialized yet.
85     /// The field must always be initialized to `DepNodeIndex::INVALID`.
86     dep_node_index: AtomicCell<DepNodeIndex>,
87     /// Caches decoded `DefKey`s.
88     def_key_cache: Lock<FxHashMap<DefIndex, DefKey>>,
89     /// Caches decoded `DefPathHash`es.
90     def_path_hash_cache: Lock<FxHashMap<DefIndex, DefPathHash>>,
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<CrateDepKind>,
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     /// Additional data used for decoding `HygieneData` (e.g. `SyntaxContext`
111     /// and `ExpnId`).
112     /// Note that we store a `HygieneDecodeContext` for each `CrateMetadat`. This is
113     /// because `SyntaxContext` ids are not globally unique, so we need
114     /// to track which ids we've decoded on a per-crate basis.
115     hygiene_context: HygieneDecodeContext,
116
117     // --- Data used only for improving diagnostics ---
118     /// Information about the `extern crate` item or path that caused this crate to be loaded.
119     /// If this is `None`, then the crate was injected (e.g., by the allocator).
120     extern_crate: Lock<Option<ExternCrate>>,
121 }
122
123 /// Holds information about a rustc_span::SourceFile imported from another crate.
124 /// See `imported_source_files()` for more information.
125 struct ImportedSourceFile {
126     /// This SourceFile's byte-offset within the source_map of its original crate
127     original_start_pos: rustc_span::BytePos,
128     /// The end of this SourceFile within the source_map of its original crate
129     original_end_pos: rustc_span::BytePos,
130     /// The imported SourceFile's representation within the local source_map
131     translated_source_file: Lrc<rustc_span::SourceFile>,
132 }
133
134 pub(super) struct DecodeContext<'a, 'tcx> {
135     opaque: opaque::Decoder<'a>,
136     cdata: Option<CrateMetadataRef<'a>>,
137     sess: Option<&'tcx Session>,
138     tcx: Option<TyCtxt<'tcx>>,
139
140     // Cache the last used source_file for translating spans as an optimization.
141     last_source_file_index: usize,
142
143     lazy_state: LazyState,
144
145     // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
146     alloc_decoding_session: Option<AllocDecodingSession<'a>>,
147 }
148
149 /// Abstract over the various ways one can create metadata decoders.
150 pub(super) trait Metadata<'a, 'tcx>: Copy {
151     fn raw_bytes(self) -> &'a [u8];
152     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
153         None
154     }
155     fn sess(self) -> Option<&'tcx Session> {
156         None
157     }
158     fn tcx(self) -> Option<TyCtxt<'tcx>> {
159         None
160     }
161
162     fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
163         let tcx = self.tcx();
164         DecodeContext {
165             opaque: opaque::Decoder::new(self.raw_bytes(), pos),
166             cdata: self.cdata(),
167             sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
168             tcx,
169             last_source_file_index: 0,
170             lazy_state: LazyState::NoNode,
171             alloc_decoding_session: self
172                 .cdata()
173                 .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()),
174         }
175     }
176 }
177
178 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
179     fn raw_bytes(self) -> &'a [u8] {
180         &self.0
181     }
182 }
183
184 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
185     fn raw_bytes(self) -> &'a [u8] {
186         let (blob, _) = self;
187         &blob.0
188     }
189
190     fn sess(self) -> Option<&'tcx Session> {
191         let (_, sess) = self;
192         Some(sess)
193     }
194 }
195
196 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadataRef<'a> {
197     fn raw_bytes(self) -> &'a [u8] {
198         self.blob.raw_bytes()
199     }
200     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
201         Some(*self)
202     }
203 }
204
205 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, &'tcx Session) {
206     fn raw_bytes(self) -> &'a [u8] {
207         self.0.raw_bytes()
208     }
209     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
210         Some(*self.0)
211     }
212     fn sess(self) -> Option<&'tcx Session> {
213         Some(&self.1)
214     }
215 }
216
217 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, TyCtxt<'tcx>) {
218     fn raw_bytes(self) -> &'a [u8] {
219         self.0.raw_bytes()
220     }
221     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
222         Some(*self.0)
223     }
224     fn tcx(self) -> Option<TyCtxt<'tcx>> {
225         Some(self.1)
226     }
227 }
228
229 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Lazy<T> {
230     fn decode<M: Metadata<'a, 'tcx>>(self, metadata: M) -> T {
231         let mut dcx = metadata.decoder(self.position.get());
232         dcx.lazy_state = LazyState::NodeStart(self.position);
233         T::decode(&mut dcx).unwrap()
234     }
235 }
236
237 impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable<DecodeContext<'a, 'tcx>>> Lazy<[T]> {
238     fn decode<M: Metadata<'a, 'tcx>>(
239         self,
240         metadata: M,
241     ) -> impl ExactSizeIterator<Item = T> + Captures<'a> + Captures<'tcx> + 'x {
242         let mut dcx = metadata.decoder(self.position.get());
243         dcx.lazy_state = LazyState::NodeStart(self.position);
244         (0..self.meta).map(move |_| T::decode(&mut dcx).unwrap())
245     }
246 }
247
248 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
249     fn tcx(&self) -> TyCtxt<'tcx> {
250         self.tcx.expect("missing TyCtxt in DecodeContext")
251     }
252
253     fn cdata(&self) -> CrateMetadataRef<'a> {
254         self.cdata.expect("missing CrateMetadata in DecodeContext")
255     }
256
257     fn read_lazy_with_meta<T: ?Sized + LazyMeta>(
258         &mut self,
259         meta: T::Meta,
260     ) -> Result<Lazy<T>, <Self as Decoder>::Error> {
261         let min_size = T::min_size(meta);
262         let distance = self.read_usize()?;
263         let position = match self.lazy_state {
264             LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
265             LazyState::NodeStart(start) => {
266                 let start = start.get();
267                 assert!(distance + min_size <= start);
268                 start - distance - min_size
269             }
270             LazyState::Previous(last_min_end) => last_min_end.get() + distance,
271         };
272         self.lazy_state = LazyState::Previous(NonZeroUsize::new(position + min_size).unwrap());
273         Ok(Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta))
274     }
275 }
276
277 impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> {
278     const CLEAR_CROSS_CRATE: bool = true;
279
280     #[inline]
281     fn tcx(&self) -> TyCtxt<'tcx> {
282         self.tcx.expect("missing TyCtxt in DecodeContext")
283     }
284
285     #[inline]
286     fn peek_byte(&self) -> u8 {
287         self.opaque.data[self.opaque.position()]
288     }
289
290     #[inline]
291     fn position(&self) -> usize {
292         self.opaque.position()
293     }
294
295     fn cached_ty_for_shorthand<F>(
296         &mut self,
297         shorthand: usize,
298         or_insert_with: F,
299     ) -> Result<Ty<'tcx>, Self::Error>
300     where
301         F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
302     {
303         let tcx = self.tcx();
304
305         let key = ty::CReaderCacheKey { cnum: self.cdata().cnum, pos: shorthand };
306
307         if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) {
308             return Ok(ty);
309         }
310
311         let ty = or_insert_with(self)?;
312         tcx.ty_rcache.borrow_mut().insert(key, ty);
313         Ok(ty)
314     }
315
316     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
317     where
318         F: FnOnce(&mut Self) -> R,
319     {
320         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
321         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
322         let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
323         let r = f(self);
324         self.opaque = old_opaque;
325         self.lazy_state = old_state;
326         r
327     }
328
329     fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
330         if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] }
331     }
332
333     fn decode_alloc_id(&mut self) -> Result<rustc_middle::mir::interpret::AllocId, Self::Error> {
334         if let Some(alloc_decoding_session) = self.alloc_decoding_session {
335             alloc_decoding_session.decode_alloc_id(self)
336         } else {
337             bug!("Attempting to decode interpret::AllocId without CrateMetadata")
338         }
339     }
340 }
341
342 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for CrateNum {
343     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<CrateNum, String> {
344         let cnum = CrateNum::from_u32(d.read_u32()?);
345         Ok(d.map_encoded_cnum_to_current(cnum))
346     }
347 }
348
349 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefIndex {
350     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<DefIndex, String> {
351         Ok(DefIndex::from_u32(d.read_u32()?))
352     }
353 }
354
355 impl<'a, 'tcx> FingerprintDecoder for DecodeContext<'a, 'tcx> {
356     fn decode_fingerprint(&mut self) -> Result<Fingerprint, String> {
357         Fingerprint::decode_opaque(&mut self.opaque)
358     }
359 }
360
361 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for SyntaxContext {
362     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<SyntaxContext, String> {
363         let cdata = decoder.cdata();
364         let sess = decoder.sess.unwrap();
365         let cname = cdata.root.name;
366         rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| {
367             debug!("SpecializedDecoder<SyntaxContext>: decoding {}", id);
368             Ok(cdata
369                 .root
370                 .syntax_contexts
371                 .get(&cdata, id)
372                 .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname))
373                 .decode((&cdata, sess)))
374         })
375     }
376 }
377
378 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for ExpnId {
379     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<ExpnId, String> {
380         let local_cdata = decoder.cdata();
381         let sess = decoder.sess.unwrap();
382         let expn_cnum = Cell::new(None);
383         let get_ctxt = |cnum| {
384             expn_cnum.set(Some(cnum));
385             if cnum == LOCAL_CRATE {
386                 &local_cdata.hygiene_context
387             } else {
388                 &local_cdata.cstore.get_crate_data(cnum).cdata.hygiene_context
389             }
390         };
391
392         rustc_span::hygiene::decode_expn_id(
393             decoder,
394             ExpnDataDecodeMode::Metadata(get_ctxt),
395             |_this, index| {
396                 let cnum = expn_cnum.get().unwrap();
397                 // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s
398                 // are stored in the owning crate, to avoid duplication.
399                 let crate_data = if cnum == LOCAL_CRATE {
400                     local_cdata
401                 } else {
402                     local_cdata.cstore.get_crate_data(cnum)
403                 };
404                 Ok(crate_data
405                     .root
406                     .expn_data
407                     .get(&crate_data, index)
408                     .unwrap()
409                     .decode((&crate_data, sess)))
410             },
411         )
412     }
413 }
414
415 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for Span {
416     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Span, String> {
417         let tag = u8::decode(decoder)?;
418
419         if tag == TAG_INVALID_SPAN {
420             return Ok(DUMMY_SP);
421         }
422
423         debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN);
424
425         let lo = BytePos::decode(decoder)?;
426         let len = BytePos::decode(decoder)?;
427         let ctxt = SyntaxContext::decode(decoder)?;
428         let hi = lo + len;
429
430         let sess = if let Some(sess) = decoder.sess {
431             sess
432         } else {
433             bug!("Cannot decode Span without Session.")
434         };
435
436         // There are two possibilities here:
437         // 1. This is a 'local span', which is located inside a `SourceFile`
438         // that came from this crate. In this case, we use the source map data
439         // encoded in this crate. This branch should be taken nearly all of the time.
440         // 2. This is a 'foreign span', which is located inside a `SourceFile`
441         // that came from a *different* crate (some crate upstream of the one
442         // whose metadata we're looking at). For example, consider this dependency graph:
443         //
444         // A -> B -> C
445         //
446         // Suppose that we're currently compiling crate A, and start deserializing
447         // metadata from crate B. When we deserialize a Span from crate B's metadata,
448         // there are two posibilites:
449         //
450         // 1. The span references a file from crate B. This makes it a 'local' span,
451         // which means that we can use crate B's serialized source map information.
452         // 2. The span references a file from crate C. This makes it a 'foreign' span,
453         // which means we need to use Crate *C* (not crate B) to determine the source
454         // map information. We only record source map information for a file in the
455         // crate that 'owns' it, so deserializing a Span may require us to look at
456         // a transitive dependency.
457         //
458         // When we encode a foreign span, we adjust its 'lo' and 'high' values
459         // to be based on the *foreign* crate (e.g. crate C), not the crate
460         // we are writing metadata for (e.g. crate B). This allows us to
461         // treat the 'local' and 'foreign' cases almost identically during deserialization:
462         // we can call `imported_source_files` for the proper crate, and binary search
463         // through the returned slice using our span.
464         let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL {
465             decoder.cdata().imported_source_files(sess)
466         } else {
467             // When we encode a proc-macro crate, all `Span`s should be encoded
468             // with `TAG_VALID_SPAN_LOCAL`
469             if decoder.cdata().root.is_proc_macro_crate() {
470                 // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE
471                 // since we don't have `cnum_map` populated.
472                 let cnum = u32::decode(decoder)?;
473                 panic!(
474                     "Decoding of crate {:?} tried to access proc-macro dep {:?}",
475                     decoder.cdata().root.name,
476                     cnum
477                 );
478             }
479             // tag is TAG_VALID_SPAN_FOREIGN, checked by `debug_assert` above
480             let cnum = CrateNum::decode(decoder)?;
481             debug!(
482                 "SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {:?}",
483                 cnum
484             );
485
486             // Decoding 'foreign' spans should be rare enough that it's
487             // not worth it to maintain a per-CrateNum cache for `last_source_file_index`.
488             // We just set it to 0, to ensure that we don't try to access something out
489             // of bounds for our initial 'guess'
490             decoder.last_source_file_index = 0;
491
492             let foreign_data = decoder.cdata().cstore.get_crate_data(cnum);
493             foreign_data.imported_source_files(sess)
494         };
495
496         let source_file = {
497             // Optimize for the case that most spans within a translated item
498             // originate from the same source_file.
499             let last_source_file = &imported_source_files[decoder.last_source_file_index];
500
501             if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos
502             {
503                 last_source_file
504             } else {
505                 let index = imported_source_files
506                     .binary_search_by_key(&lo, |source_file| source_file.original_start_pos)
507                     .unwrap_or_else(|index| index - 1);
508
509                 // Don't try to cache the index for foreign spans,
510                 // as this would require a map from CrateNums to indices
511                 if tag == TAG_VALID_SPAN_LOCAL {
512                     decoder.last_source_file_index = index;
513                 }
514                 &imported_source_files[index]
515             }
516         };
517
518         // Make sure our binary search above is correct.
519         debug_assert!(
520             lo >= source_file.original_start_pos && lo <= source_file.original_end_pos,
521             "Bad binary search: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
522             lo,
523             source_file.original_start_pos,
524             source_file.original_end_pos
525         );
526
527         // Make sure we correctly filtered out invalid spans during encoding
528         debug_assert!(
529             hi >= source_file.original_start_pos && hi <= source_file.original_end_pos,
530             "Bad binary search: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
531             hi,
532             source_file.original_start_pos,
533             source_file.original_end_pos
534         );
535
536         let lo =
537             (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
538         let hi =
539             (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
540
541         Ok(Span::new(lo, hi, ctxt))
542     }
543 }
544
545 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for &'tcx [mir::abstract_const::Node<'tcx>] {
546     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
547         ty::codec::RefDecodable::decode(d)
548     }
549 }
550
551 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
552     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
553         ty::codec::RefDecodable::decode(d)
554     }
555 }
556
557 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
558     for Lazy<T>
559 {
560     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
561         decoder.read_lazy_with_meta(())
562     }
563 }
564
565 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
566     for Lazy<[T]>
567 {
568     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
569         let len = decoder.read_usize()?;
570         if len == 0 { Ok(Lazy::empty()) } else { decoder.read_lazy_with_meta(len) }
571     }
572 }
573
574 impl<'a, 'tcx, I: Idx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
575     for Lazy<Table<I, T>>
576 where
577     Option<T>: FixedSizeEncoding,
578 {
579     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
580         let len = decoder.read_usize()?;
581         decoder.read_lazy_with_meta(len)
582     }
583 }
584
585 implement_ty_decoder!(DecodeContext<'a, 'tcx>);
586
587 impl MetadataBlob {
588     crate fn new(metadata_ref: MetadataRef) -> MetadataBlob {
589         MetadataBlob(metadata_ref)
590     }
591
592     crate fn is_compatible(&self) -> bool {
593         self.raw_bytes().starts_with(METADATA_HEADER)
594     }
595
596     crate fn get_rustc_version(&self) -> String {
597         Lazy::<String>::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap())
598             .decode(self)
599     }
600
601     crate fn get_root(&self) -> CrateRoot<'tcx> {
602         let slice = self.raw_bytes();
603         let offset = METADATA_HEADER.len();
604         let pos = (((slice[offset + 0] as u32) << 24)
605             | ((slice[offset + 1] as u32) << 16)
606             | ((slice[offset + 2] as u32) << 8)
607             | ((slice[offset + 3] as u32) << 0)) as usize;
608         Lazy::<CrateRoot<'tcx>>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self)
609     }
610
611     crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> {
612         write!(out, "=External Dependencies=\n")?;
613         let root = self.get_root();
614         for (i, dep) in root.crate_deps.decode(self).enumerate() {
615             write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
616         }
617         write!(out, "\n")?;
618         Ok(())
619     }
620 }
621
622 impl EntryKind {
623     fn def_kind(&self) -> DefKind {
624         match *self {
625             EntryKind::AnonConst(..) => DefKind::AnonConst,
626             EntryKind::Const(..) => DefKind::Const,
627             EntryKind::AssocConst(..) => DefKind::AssocConst,
628             EntryKind::ImmStatic
629             | EntryKind::MutStatic
630             | EntryKind::ForeignImmStatic
631             | EntryKind::ForeignMutStatic => DefKind::Static,
632             EntryKind::Struct(_, _) => DefKind::Struct,
633             EntryKind::Union(_, _) => DefKind::Union,
634             EntryKind::Fn(_) | EntryKind::ForeignFn(_) => DefKind::Fn,
635             EntryKind::AssocFn(_) => DefKind::AssocFn,
636             EntryKind::Type => DefKind::TyAlias,
637             EntryKind::TypeParam => DefKind::TyParam,
638             EntryKind::ConstParam => DefKind::ConstParam,
639             EntryKind::OpaqueTy => DefKind::OpaqueTy,
640             EntryKind::AssocType(_) => DefKind::AssocTy,
641             EntryKind::Mod(_) => DefKind::Mod,
642             EntryKind::Variant(_) => DefKind::Variant,
643             EntryKind::Trait(_) => DefKind::Trait,
644             EntryKind::TraitAlias => DefKind::TraitAlias,
645             EntryKind::Enum(..) => DefKind::Enum,
646             EntryKind::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
647             EntryKind::ForeignType => DefKind::ForeignTy,
648             EntryKind::Impl(_) => DefKind::Impl,
649             EntryKind::Closure => DefKind::Closure,
650             EntryKind::ForeignMod => DefKind::ForeignMod,
651             EntryKind::GlobalAsm => DefKind::GlobalAsm,
652             EntryKind::Field => DefKind::Field,
653             EntryKind::Generator(_) => DefKind::Generator,
654         }
655     }
656 }
657
658 impl CrateRoot<'_> {
659     crate fn is_proc_macro_crate(&self) -> bool {
660         self.proc_macro_data.is_some()
661     }
662
663     crate fn name(&self) -> Symbol {
664         self.name
665     }
666
667     crate fn disambiguator(&self) -> CrateDisambiguator {
668         self.disambiguator
669     }
670
671     crate fn hash(&self) -> Svh {
672         self.hash
673     }
674
675     crate fn triple(&self) -> &TargetTriple {
676         &self.triple
677     }
678
679     crate fn decode_crate_deps(
680         &self,
681         metadata: &'a MetadataBlob,
682     ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
683         self.crate_deps.decode(metadata)
684     }
685 }
686
687 impl<'a, 'tcx> CrateMetadataRef<'a> {
688     fn is_proc_macro(&self, id: DefIndex) -> bool {
689         self.root
690             .proc_macro_data
691             .as_ref()
692             .and_then(|data| data.macros.decode(self).find(|x| *x == id))
693             .is_some()
694     }
695
696     fn maybe_kind(&self, item_id: DefIndex) -> Option<EntryKind> {
697         self.root.tables.kind.get(self, item_id).map(|k| k.decode(self))
698     }
699
700     fn kind(&self, item_id: DefIndex) -> EntryKind {
701         assert!(!self.is_proc_macro(item_id));
702         self.maybe_kind(item_id).unwrap_or_else(|| {
703             bug!(
704                 "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}",
705                 item_id,
706                 self.root.name,
707                 self.cnum,
708             )
709         })
710     }
711
712     fn raw_proc_macro(&self, id: DefIndex) -> &ProcMacro {
713         // DefIndex's in root.proc_macro_data have a one-to-one correspondence
714         // with items in 'raw_proc_macros'.
715         let pos = self
716             .root
717             .proc_macro_data
718             .as_ref()
719             .unwrap()
720             .macros
721             .decode(self)
722             .position(|i| i == id)
723             .unwrap();
724         &self.raw_proc_macros.unwrap()[pos]
725     }
726
727     fn item_ident(&self, item_index: DefIndex, sess: &Session) -> Ident {
728         if !self.is_proc_macro(item_index) {
729             let name = self
730                 .def_key(item_index)
731                 .disambiguated_data
732                 .data
733                 .get_opt_name()
734                 .expect("no name in item_ident");
735             let span = self
736                 .root
737                 .tables
738                 .ident_span
739                 .get(self, item_index)
740                 .map(|data| data.decode((self, sess)))
741                 .unwrap_or_else(|| panic!("Missing ident span for {:?} ({:?})", name, item_index));
742             Ident::new(name, span)
743         } else {
744             Ident::new(
745                 Symbol::intern(self.raw_proc_macro(item_index).name()),
746                 self.get_span(item_index, sess),
747             )
748         }
749     }
750
751     fn def_kind(&self, index: DefIndex) -> DefKind {
752         if !self.is_proc_macro(index) {
753             self.kind(index).def_kind()
754         } else {
755             DefKind::Macro(macro_kind(self.raw_proc_macro(index)))
756         }
757     }
758
759     fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
760         self.root
761             .tables
762             .span
763             .get(self, index)
764             .unwrap_or_else(|| panic!("Missing span for {:?}", index))
765             .decode((self, sess))
766     }
767
768     fn load_proc_macro(&self, id: DefIndex, sess: &Session) -> SyntaxExtension {
769         let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
770             ProcMacro::CustomDerive { trait_name, attributes, client } => {
771                 let helper_attrs =
772                     attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
773                 (
774                     trait_name,
775                     SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
776                     helper_attrs,
777                 )
778             }
779             ProcMacro::Attr { name, client } => {
780                 (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new())
781             }
782             ProcMacro::Bang { name, client } => {
783                 (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new())
784             }
785         };
786
787         SyntaxExtension::new(
788             sess,
789             kind,
790             self.get_span(id, sess),
791             helper_attrs,
792             self.root.edition,
793             Symbol::intern(name),
794             &self.get_item_attrs(id, sess),
795         )
796     }
797
798     fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
799         match self.kind(item_id) {
800             EntryKind::Trait(data) => {
801                 let data = data.decode((self, sess));
802                 ty::TraitDef::new(
803                     self.local_def_id(item_id),
804                     data.unsafety,
805                     data.paren_sugar,
806                     data.has_auto_impl,
807                     data.is_marker,
808                     data.specialization_kind,
809                     self.def_path_hash(item_id),
810                 )
811             }
812             EntryKind::TraitAlias => ty::TraitDef::new(
813                 self.local_def_id(item_id),
814                 hir::Unsafety::Normal,
815                 false,
816                 false,
817                 false,
818                 ty::trait_def::TraitSpecializationKind::None,
819                 self.def_path_hash(item_id),
820             ),
821             _ => bug!("def-index does not refer to trait or trait alias"),
822         }
823     }
824
825     fn get_variant(
826         &self,
827         kind: &EntryKind,
828         index: DefIndex,
829         parent_did: DefId,
830         sess: &Session,
831     ) -> ty::VariantDef {
832         let data = match kind {
833             EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => {
834                 data.decode(self)
835             }
836             _ => bug!(),
837         };
838
839         let adt_kind = match kind {
840             EntryKind::Variant(_) => ty::AdtKind::Enum,
841             EntryKind::Struct(..) => ty::AdtKind::Struct,
842             EntryKind::Union(..) => ty::AdtKind::Union,
843             _ => bug!(),
844         };
845
846         let variant_did =
847             if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
848         let ctor_did = data.ctor.map(|index| self.local_def_id(index));
849
850         ty::VariantDef::new(
851             self.item_ident(index, sess),
852             variant_did,
853             ctor_did,
854             data.discr,
855             self.root
856                 .tables
857                 .children
858                 .get(self, index)
859                 .unwrap_or(Lazy::empty())
860                 .decode(self)
861                 .map(|index| ty::FieldDef {
862                     did: self.local_def_id(index),
863                     ident: self.item_ident(index, sess),
864                     vis: self.get_visibility(index),
865                 })
866                 .collect(),
867             data.ctor_kind,
868             adt_kind,
869             parent_did,
870             false,
871             data.is_non_exhaustive,
872         )
873     }
874
875     fn get_adt_def(&self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef {
876         let kind = self.kind(item_id);
877         let did = self.local_def_id(item_id);
878
879         let (adt_kind, repr) = match kind {
880             EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
881             EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
882             EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
883             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
884         };
885
886         let variants = if let ty::AdtKind::Enum = adt_kind {
887             self.root
888                 .tables
889                 .children
890                 .get(self, item_id)
891                 .unwrap_or(Lazy::empty())
892                 .decode(self)
893                 .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess))
894                 .collect()
895         } else {
896             std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect()
897         };
898
899         tcx.alloc_adt_def(did, adt_kind, variants, repr)
900     }
901
902     fn get_explicit_predicates(
903         &self,
904         item_id: DefIndex,
905         tcx: TyCtxt<'tcx>,
906     ) -> ty::GenericPredicates<'tcx> {
907         self.root.tables.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx))
908     }
909
910     fn get_inferred_outlives(
911         &self,
912         item_id: DefIndex,
913         tcx: TyCtxt<'tcx>,
914     ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
915         self.root
916             .tables
917             .inferred_outlives
918             .get(self, item_id)
919             .map(|predicates| tcx.arena.alloc_from_iter(predicates.decode((self, tcx))))
920             .unwrap_or_default()
921     }
922
923     fn get_super_predicates(
924         &self,
925         item_id: DefIndex,
926         tcx: TyCtxt<'tcx>,
927     ) -> ty::GenericPredicates<'tcx> {
928         self.root.tables.super_predicates.get(self, item_id).unwrap().decode((self, tcx))
929     }
930
931     fn get_explicit_item_bounds(
932         &self,
933         item_id: DefIndex,
934         tcx: TyCtxt<'tcx>,
935     ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
936         self.root
937             .tables
938             .explicit_item_bounds
939             .get(self, item_id)
940             .map(|bounds| tcx.arena.alloc_from_iter(bounds.decode((self, tcx))))
941             .unwrap_or_default()
942     }
943
944     fn get_generics(&self, item_id: DefIndex, sess: &Session) -> ty::Generics {
945         self.root.tables.generics.get(self, item_id).unwrap().decode((self, sess))
946     }
947
948     fn get_type(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
949         self.root.tables.ty.get(self, id).unwrap().decode((self, tcx))
950     }
951
952     fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
953         match self.is_proc_macro(id) {
954             true => self.root.proc_macro_data.as_ref().unwrap().stability,
955             false => self.root.tables.stability.get(self, id).map(|stab| stab.decode(self)),
956         }
957     }
958
959     fn get_const_stability(&self, id: DefIndex) -> Option<attr::ConstStability> {
960         self.root.tables.const_stability.get(self, id).map(|stab| stab.decode(self))
961     }
962
963     fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
964         self.root
965             .tables
966             .deprecation
967             .get(self, id)
968             .filter(|_| !self.is_proc_macro(id))
969             .map(|depr| depr.decode(self))
970     }
971
972     fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
973         match self.is_proc_macro(id) {
974             true => ty::Visibility::Public,
975             false => self.root.tables.visibility.get(self, id).unwrap().decode(self),
976         }
977     }
978
979     fn get_impl_data(&self, id: DefIndex) -> ImplData {
980         match self.kind(id) {
981             EntryKind::Impl(data) => data.decode(self),
982             _ => bug!(),
983         }
984     }
985
986     fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
987         self.get_impl_data(id).parent_impl
988     }
989
990     fn get_impl_polarity(&self, id: DefIndex) -> ty::ImplPolarity {
991         self.get_impl_data(id).polarity
992     }
993
994     fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
995         self.get_impl_data(id).defaultness
996     }
997
998     fn get_coerce_unsized_info(&self, id: DefIndex) -> Option<ty::adjustment::CoerceUnsizedInfo> {
999         self.get_impl_data(id).coerce_unsized_info
1000     }
1001
1002     fn get_impl_trait(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option<ty::TraitRef<'tcx>> {
1003         self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx)))
1004     }
1005
1006     fn get_expn_that_defined(&self, id: DefIndex, sess: &Session) -> ExpnId {
1007         self.root.tables.expn_that_defined.get(self, id).unwrap().decode((self, sess))
1008     }
1009
1010     /// Iterates over all the stability attributes in the given crate.
1011     fn get_lib_features(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Option<Symbol>)] {
1012         // FIXME: For a proc macro crate, not sure whether we should return the "host"
1013         // features or an empty Vec. Both don't cause ICEs.
1014         tcx.arena.alloc_from_iter(self.root.lib_features.decode(self))
1015     }
1016
1017     /// Iterates over the language items in the given crate.
1018     fn get_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] {
1019         if self.root.is_proc_macro_crate() {
1020             // Proc macro crates do not export any lang-items to the target.
1021             &[]
1022         } else {
1023             tcx.arena.alloc_from_iter(
1024                 self.root
1025                     .lang_items
1026                     .decode(self)
1027                     .map(|(def_index, index)| (self.local_def_id(def_index), index)),
1028             )
1029         }
1030     }
1031
1032     /// Iterates over the diagnostic items in the given crate.
1033     fn get_diagnostic_items(&self) -> FxHashMap<Symbol, DefId> {
1034         if self.root.is_proc_macro_crate() {
1035             // Proc macro crates do not export any diagnostic-items to the target.
1036             Default::default()
1037         } else {
1038             self.root
1039                 .diagnostic_items
1040                 .decode(self)
1041                 .map(|(name, def_index)| (name, self.local_def_id(def_index)))
1042                 .collect()
1043         }
1044     }
1045
1046     /// Iterates over each child of the given item.
1047     fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
1048     where
1049         F: FnMut(Export<hir::HirId>),
1050     {
1051         if let Some(data) = &self.root.proc_macro_data {
1052             /* If we are loading as a proc macro, we want to return the view of this crate
1053              * as a proc macro crate.
1054              */
1055             if id == CRATE_DEF_INDEX {
1056                 let macros = data.macros.decode(self);
1057                 for def_index in macros {
1058                     let raw_macro = self.raw_proc_macro(def_index);
1059                     let res = Res::Def(
1060                         DefKind::Macro(macro_kind(raw_macro)),
1061                         self.local_def_id(def_index),
1062                     );
1063                     let ident = self.item_ident(def_index, sess);
1064                     callback(Export { ident, res, vis: ty::Visibility::Public, span: ident.span });
1065                 }
1066             }
1067             return;
1068         }
1069
1070         // Find the item.
1071         let kind = match self.maybe_kind(id) {
1072             None => return,
1073             Some(kind) => kind,
1074         };
1075
1076         // Iterate over all children.
1077         let macros_only = self.dep_kind.lock().macros_only();
1078         let children = self.root.tables.children.get(self, id).unwrap_or(Lazy::empty());
1079         for child_index in children.decode((self, sess)) {
1080             if macros_only {
1081                 continue;
1082             }
1083
1084             // Get the item.
1085             if let Some(child_kind) = self.maybe_kind(child_index) {
1086                 match child_kind {
1087                     EntryKind::MacroDef(..) => {}
1088                     _ if macros_only => continue,
1089                     _ => {}
1090                 }
1091
1092                 // Hand off the item to the callback.
1093                 match child_kind {
1094                     // FIXME(eddyb) Don't encode these in children.
1095                     EntryKind::ForeignMod => {
1096                         let child_children = self
1097                             .root
1098                             .tables
1099                             .children
1100                             .get(self, child_index)
1101                             .unwrap_or(Lazy::empty());
1102                         for child_index in child_children.decode((self, sess)) {
1103                             let kind = self.def_kind(child_index);
1104                             callback(Export {
1105                                 res: Res::Def(kind, self.local_def_id(child_index)),
1106                                 ident: self.item_ident(child_index, sess),
1107                                 vis: self.get_visibility(child_index),
1108                                 span: self
1109                                     .root
1110                                     .tables
1111                                     .span
1112                                     .get(self, child_index)
1113                                     .unwrap()
1114                                     .decode((self, sess)),
1115                             });
1116                         }
1117                         continue;
1118                     }
1119                     EntryKind::Impl(_) => continue,
1120
1121                     _ => {}
1122                 }
1123
1124                 let def_key = self.def_key(child_index);
1125                 let span = self.get_span(child_index, sess);
1126                 if def_key.disambiguated_data.data.get_opt_name().is_some() {
1127                     let kind = self.def_kind(child_index);
1128                     let ident = self.item_ident(child_index, sess);
1129                     let vis = self.get_visibility(child_index);
1130                     let def_id = self.local_def_id(child_index);
1131                     let res = Res::Def(kind, def_id);
1132                     callback(Export { res, ident, vis, span });
1133                     // For non-re-export structs and variants add their constructors to children.
1134                     // Re-export lists automatically contain constructors when necessary.
1135                     match kind {
1136                         DefKind::Struct => {
1137                             if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
1138                                 let ctor_kind = self.get_ctor_kind(child_index);
1139                                 let ctor_res =
1140                                     Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1141                                 let vis = self.get_visibility(ctor_def_id.index);
1142                                 callback(Export { res: ctor_res, vis, ident, span });
1143                             }
1144                         }
1145                         DefKind::Variant => {
1146                             // Braced variants, unlike structs, generate unusable names in
1147                             // value namespace, they are reserved for possible future use.
1148                             // It's ok to use the variant's id as a ctor id since an
1149                             // error will be reported on any use of such resolution anyway.
1150                             let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
1151                             let ctor_kind = self.get_ctor_kind(child_index);
1152                             let ctor_res =
1153                                 Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
1154                             let mut vis = self.get_visibility(ctor_def_id.index);
1155                             if ctor_def_id == def_id && vis == ty::Visibility::Public {
1156                                 // For non-exhaustive variants lower the constructor visibility to
1157                                 // within the crate. We only need this for fictive constructors,
1158                                 // for other constructors correct visibilities
1159                                 // were already encoded in metadata.
1160                                 let attrs = self.get_item_attrs(def_id.index, sess);
1161                                 if sess.contains_name(&attrs, sym::non_exhaustive) {
1162                                     let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
1163                                     vis = ty::Visibility::Restricted(crate_def_id);
1164                                 }
1165                             }
1166                             callback(Export { res: ctor_res, ident, vis, span });
1167                         }
1168                         _ => {}
1169                     }
1170                 }
1171             }
1172         }
1173
1174         if let EntryKind::Mod(data) = kind {
1175             for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
1176                 match exp.res {
1177                     Res::Def(DefKind::Macro(..), _) => {}
1178                     _ if macros_only => continue,
1179                     _ => {}
1180                 }
1181                 callback(exp);
1182             }
1183         }
1184     }
1185
1186     fn is_item_mir_available(&self, id: DefIndex) -> bool {
1187         !self.is_proc_macro(id) && self.root.tables.mir.get(self, id).is_some()
1188     }
1189
1190     fn module_expansion(&self, id: DefIndex, sess: &Session) -> ExpnId {
1191         if let EntryKind::Mod(m) = self.kind(id) {
1192             m.decode((self, sess)).expansion
1193         } else {
1194             panic!("Expected module, found {:?}", self.local_def_id(id))
1195         }
1196     }
1197
1198     fn get_optimized_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> {
1199         self.root
1200             .tables
1201             .mir
1202             .get(self, id)
1203             .filter(|_| !self.is_proc_macro(id))
1204             .unwrap_or_else(|| {
1205                 bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id))
1206             })
1207             .decode((self, tcx))
1208     }
1209
1210     fn get_mir_abstract_const(
1211         &self,
1212         tcx: TyCtxt<'tcx>,
1213         id: DefIndex,
1214     ) -> Result<Option<&'tcx [mir::abstract_const::Node<'tcx>]>, ErrorReported> {
1215         self.root
1216             .tables
1217             .mir_abstract_consts
1218             .get(self, id)
1219             .filter(|_| !self.is_proc_macro(id))
1220             .map_or(Ok(None), |v| Ok(Some(v.decode((self, tcx)))))
1221     }
1222
1223     fn get_unused_generic_params(&self, id: DefIndex) -> FiniteBitSet<u32> {
1224         self.root
1225             .tables
1226             .unused_generic_params
1227             .get(self, id)
1228             .filter(|_| !self.is_proc_macro(id))
1229             .map(|params| params.decode(self))
1230             .unwrap_or_default()
1231     }
1232
1233     fn get_promoted_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> IndexVec<Promoted, Body<'tcx>> {
1234         self.root
1235             .tables
1236             .promoted_mir
1237             .get(self, id)
1238             .filter(|_| !self.is_proc_macro(id))
1239             .unwrap_or_else(|| {
1240                 bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id))
1241             })
1242             .decode((self, tcx))
1243     }
1244
1245     fn mir_const_qualif(&self, id: DefIndex) -> mir::ConstQualifs {
1246         match self.kind(id) {
1247             EntryKind::AnonConst(qualif, _)
1248             | EntryKind::Const(qualif, _)
1249             | EntryKind::AssocConst(
1250                 AssocContainer::ImplDefault
1251                 | AssocContainer::ImplFinal
1252                 | AssocContainer::TraitWithDefault,
1253                 qualif,
1254                 _,
1255             ) => qualif,
1256             _ => bug!("mir_const_qualif: unexpected kind"),
1257         }
1258     }
1259
1260     fn get_associated_item(&self, id: DefIndex, sess: &Session) -> ty::AssocItem {
1261         let def_key = self.def_key(id);
1262         let parent = self.local_def_id(def_key.parent.unwrap());
1263         let ident = self.item_ident(id, sess);
1264
1265         let (kind, container, has_self) = match self.kind(id) {
1266             EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false),
1267             EntryKind::AssocFn(data) => {
1268                 let data = data.decode(self);
1269                 (ty::AssocKind::Fn, data.container, data.has_self)
1270             }
1271             EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false),
1272             _ => bug!("cannot get associated-item of `{:?}`", def_key),
1273         };
1274
1275         ty::AssocItem {
1276             ident,
1277             kind,
1278             vis: self.get_visibility(id),
1279             defaultness: container.defaultness(),
1280             def_id: self.local_def_id(id),
1281             container: container.with_def_id(parent),
1282             fn_has_self_parameter: has_self,
1283         }
1284     }
1285
1286     fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
1287         self.root.tables.variances.get(self, id).unwrap_or(Lazy::empty()).decode(self).collect()
1288     }
1289
1290     fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
1291         match self.kind(node_id) {
1292             EntryKind::Struct(data, _) | EntryKind::Union(data, _) | EntryKind::Variant(data) => {
1293                 data.decode(self).ctor_kind
1294             }
1295             _ => CtorKind::Fictive,
1296         }
1297     }
1298
1299     fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
1300         match self.kind(node_id) {
1301             EntryKind::Struct(data, _) => {
1302                 data.decode(self).ctor.map(|index| self.local_def_id(index))
1303             }
1304             EntryKind::Variant(data) => {
1305                 data.decode(self).ctor.map(|index| self.local_def_id(index))
1306             }
1307             _ => None,
1308         }
1309     }
1310
1311     fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Vec<ast::Attribute> {
1312         // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
1313         // we assume that someone passing in a tuple struct ctor is actually wanting to
1314         // look at the definition
1315         let def_key = self.def_key(node_id);
1316         let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
1317             def_key.parent.unwrap()
1318         } else {
1319             node_id
1320         };
1321
1322         self.root
1323             .tables
1324             .attributes
1325             .get(self, item_id)
1326             .unwrap_or(Lazy::empty())
1327             .decode((self, sess))
1328             .collect::<Vec<_>>()
1329     }
1330
1331     fn get_struct_field_names(&self, id: DefIndex, sess: &Session) -> Vec<Spanned<Symbol>> {
1332         self.root
1333             .tables
1334             .children
1335             .get(self, id)
1336             .unwrap_or(Lazy::empty())
1337             .decode(self)
1338             .map(|index| respan(self.get_span(index, sess), self.item_ident(index, sess).name))
1339             .collect()
1340     }
1341
1342     fn get_inherent_implementations_for_type(
1343         &self,
1344         tcx: TyCtxt<'tcx>,
1345         id: DefIndex,
1346     ) -> &'tcx [DefId] {
1347         tcx.arena.alloc_from_iter(
1348             self.root
1349                 .tables
1350                 .inherent_impls
1351                 .get(self, id)
1352                 .unwrap_or(Lazy::empty())
1353                 .decode(self)
1354                 .map(|index| self.local_def_id(index)),
1355         )
1356     }
1357
1358     fn get_implementations_for_trait(
1359         &self,
1360         tcx: TyCtxt<'tcx>,
1361         filter: Option<DefId>,
1362     ) -> &'tcx [(DefId, Option<ty::fast_reject::SimplifiedType>)] {
1363         if self.root.is_proc_macro_crate() {
1364             // proc-macro crates export no trait impls.
1365             return &[];
1366         }
1367
1368         // Do a reverse lookup beforehand to avoid touching the crate_num
1369         // hash map in the loop below.
1370         let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1371             Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1372             Some(None) => return &[],
1373             None => None,
1374         };
1375
1376         if let Some(filter) = filter {
1377             if let Some(impls) = self.trait_impls.get(&filter) {
1378                 tcx.arena.alloc_from_iter(
1379                     impls.decode(self).map(|(idx, simplified_self_ty)| {
1380                         (self.local_def_id(idx), simplified_self_ty)
1381                     }),
1382                 )
1383             } else {
1384                 &[]
1385             }
1386         } else {
1387             tcx.arena.alloc_from_iter(self.trait_impls.values().flat_map(|impls| {
1388                 impls
1389                     .decode(self)
1390                     .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty))
1391             }))
1392         }
1393     }
1394
1395     fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1396         let def_key = self.def_key(id);
1397         match def_key.disambiguated_data.data {
1398             DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1399             // Not an associated item
1400             _ => return None,
1401         }
1402         def_key.parent.and_then(|parent_index| match self.kind(parent_index) {
1403             EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)),
1404             _ => None,
1405         })
1406     }
1407
1408     fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLib> {
1409         if self.root.is_proc_macro_crate() {
1410             // Proc macro crates do not have any *target* native libraries.
1411             vec![]
1412         } else {
1413             self.root.native_libraries.decode((self, sess)).collect()
1414         }
1415     }
1416
1417     fn get_foreign_modules(&self, tcx: TyCtxt<'tcx>) -> &'tcx [ForeignModule] {
1418         if self.root.is_proc_macro_crate() {
1419             // Proc macro crates do not have any *target* foreign modules.
1420             &[]
1421         } else {
1422             tcx.arena.alloc_from_iter(self.root.foreign_modules.decode((self, tcx.sess)))
1423         }
1424     }
1425
1426     fn get_dylib_dependency_formats(
1427         &self,
1428         tcx: TyCtxt<'tcx>,
1429     ) -> &'tcx [(CrateNum, LinkagePreference)] {
1430         tcx.arena.alloc_from_iter(
1431             self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| {
1432                 let cnum = CrateNum::new(i + 1);
1433                 link.map(|link| (self.cnum_map[cnum], link))
1434             }),
1435         )
1436     }
1437
1438     fn get_missing_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] {
1439         if self.root.is_proc_macro_crate() {
1440             // Proc macro crates do not depend on any target weak lang-items.
1441             &[]
1442         } else {
1443             tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self))
1444         }
1445     }
1446
1447     fn get_fn_param_names(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [Ident] {
1448         let param_names = match self.kind(id) {
1449             EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names,
1450             EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names,
1451             _ => Lazy::empty(),
1452         };
1453         tcx.arena.alloc_from_iter(param_names.decode((self, tcx)))
1454     }
1455
1456     fn exported_symbols(
1457         &self,
1458         tcx: TyCtxt<'tcx>,
1459     ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] {
1460         if self.root.is_proc_macro_crate() {
1461             // If this crate is a custom derive crate, then we're not even going to
1462             // link those in so we skip those crates.
1463             &[]
1464         } else {
1465             tcx.arena.alloc_from_iter(self.root.exported_symbols.decode((self, tcx)))
1466         }
1467     }
1468
1469     fn get_rendered_const(&self, id: DefIndex) -> String {
1470         match self.kind(id) {
1471             EntryKind::AnonConst(_, data)
1472             | EntryKind::Const(_, data)
1473             | EntryKind::AssocConst(_, _, data) => data.decode(self).0,
1474             _ => bug!(),
1475         }
1476     }
1477
1478     fn get_macro(&self, id: DefIndex, sess: &Session) -> MacroDef {
1479         match self.kind(id) {
1480             EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)),
1481             _ => bug!(),
1482         }
1483     }
1484
1485     // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we
1486     // don't serialize constness for tuple variant and tuple struct constructors.
1487     fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1488         let constness = match self.kind(id) {
1489             EntryKind::AssocFn(data) => data.decode(self).fn_data.constness,
1490             EntryKind::Fn(data) => data.decode(self).constness,
1491             EntryKind::ForeignFn(data) => data.decode(self).constness,
1492             EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const,
1493             _ => hir::Constness::NotConst,
1494         };
1495         constness == hir::Constness::Const
1496     }
1497
1498     fn asyncness(&self, id: DefIndex) -> hir::IsAsync {
1499         match self.kind(id) {
1500             EntryKind::Fn(data) => data.decode(self).asyncness,
1501             EntryKind::AssocFn(data) => data.decode(self).fn_data.asyncness,
1502             EntryKind::ForeignFn(data) => data.decode(self).asyncness,
1503             _ => bug!("asyncness: expected function kind"),
1504         }
1505     }
1506
1507     fn is_foreign_item(&self, id: DefIndex) -> bool {
1508         match self.kind(id) {
1509             EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => {
1510                 true
1511             }
1512             _ => false,
1513         }
1514     }
1515
1516     fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1517         match self.kind(id) {
1518             EntryKind::ImmStatic | EntryKind::ForeignImmStatic => Some(hir::Mutability::Not),
1519             EntryKind::MutStatic | EntryKind::ForeignMutStatic => Some(hir::Mutability::Mut),
1520             _ => None,
1521         }
1522     }
1523
1524     fn generator_kind(&self, id: DefIndex) -> Option<hir::GeneratorKind> {
1525         match self.kind(id) {
1526             EntryKind::Generator(data) => Some(data),
1527             _ => None,
1528         }
1529     }
1530
1531     fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
1532         self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx))
1533     }
1534
1535     #[inline]
1536     fn def_key(&self, index: DefIndex) -> DefKey {
1537         *self.def_key_cache.lock().entry(index).or_insert_with(|| {
1538             let mut key = self.root.tables.def_keys.get(self, index).unwrap().decode(self);
1539             if self.is_proc_macro(index) {
1540                 let name = self.raw_proc_macro(index).name();
1541                 key.disambiguated_data.data = DefPathData::MacroNs(Symbol::intern(name));
1542             }
1543             key
1544         })
1545     }
1546
1547     // Returns the path leading to the thing with this `id`.
1548     fn def_path(&self, id: DefIndex) -> DefPath {
1549         debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1550         DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1551     }
1552
1553     fn def_path_hash_unlocked(
1554         &self,
1555         index: DefIndex,
1556         def_path_hashes: &mut FxHashMap<DefIndex, DefPathHash>,
1557     ) -> DefPathHash {
1558         *def_path_hashes.entry(index).or_insert_with(|| {
1559             self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self)
1560         })
1561     }
1562
1563     #[inline]
1564     fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1565         let mut def_path_hashes = self.def_path_hash_cache.lock();
1566         self.def_path_hash_unlocked(index, &mut def_path_hashes)
1567     }
1568
1569     fn all_def_path_hashes_and_def_ids(&self) -> Vec<(DefPathHash, DefId)> {
1570         let mut def_path_hashes = self.def_path_hash_cache.lock();
1571         let mut def_index_to_data = |index| {
1572             (self.def_path_hash_unlocked(index, &mut def_path_hashes), self.local_def_id(index))
1573         };
1574         if let Some(data) = &self.root.proc_macro_data {
1575             std::iter::once(CRATE_DEF_INDEX)
1576                 .chain(data.macros.decode(self))
1577                 .map(def_index_to_data)
1578                 .collect()
1579         } else {
1580             (0..self.num_def_ids())
1581                 .map(|index| def_index_to_data(DefIndex::from_usize(index)))
1582                 .collect()
1583         }
1584     }
1585
1586     /// Get the `DepNodeIndex` corresponding this crate. The result of this
1587     /// method is cached in the `dep_node_index` field.
1588     fn get_crate_dep_node_index(&self, tcx: TyCtxt<'tcx>) -> DepNodeIndex {
1589         let mut dep_node_index = self.dep_node_index.load();
1590
1591         if unlikely!(dep_node_index == DepNodeIndex::INVALID) {
1592             // We have not cached the DepNodeIndex for this upstream crate yet,
1593             // so use the dep-graph to find it out and cache it.
1594             // Note that multiple threads can enter this block concurrently.
1595             // That is fine because the DepNodeIndex remains constant
1596             // throughout the whole compilation session, and multiple stores
1597             // would always write the same value.
1598
1599             let def_path_hash = self.def_path_hash(CRATE_DEF_INDEX);
1600             let dep_node =
1601                 DepNode::from_def_path_hash(def_path_hash, dep_graph::DepKind::CrateMetadata);
1602
1603             dep_node_index = tcx.dep_graph.dep_node_index_of(&dep_node);
1604             assert!(dep_node_index != DepNodeIndex::INVALID);
1605             self.dep_node_index.store(dep_node_index);
1606         }
1607
1608         dep_node_index
1609     }
1610
1611     /// Imports the source_map from an external crate into the source_map of the crate
1612     /// currently being compiled (the "local crate").
1613     ///
1614     /// The import algorithm works analogous to how AST items are inlined from an
1615     /// external crate's metadata:
1616     /// For every SourceFile in the external source_map an 'inline' copy is created in the
1617     /// local source_map. The correspondence relation between external and local
1618     /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1619     /// function. When an item from an external crate is later inlined into this
1620     /// crate, this correspondence information is used to translate the span
1621     /// information of the inlined item so that it refers the correct positions in
1622     /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1623     ///
1624     /// The import algorithm in the function below will reuse SourceFiles already
1625     /// existing in the local source_map. For example, even if the SourceFile of some
1626     /// source file of libstd gets imported many times, there will only ever be
1627     /// one SourceFile object for the corresponding file in the local source_map.
1628     ///
1629     /// Note that imported SourceFiles do not actually contain the source code of the
1630     /// file they represent, just information about length, line breaks, and
1631     /// multibyte characters. This information is enough to generate valid debuginfo
1632     /// for items inlined from other crates.
1633     ///
1634     /// Proc macro crates don't currently export spans, so this function does not have
1635     /// to work for them.
1636     fn imported_source_files(&self, sess: &Session) -> &'a [ImportedSourceFile] {
1637         // Translate the virtual `/rustc/$hash` prefix back to a real directory
1638         // that should hold actual sources, where possible.
1639         //
1640         // NOTE: if you update this, you might need to also update bootstrap's code for generating
1641         // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`.
1642         let virtual_rust_source_base_dir = option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR")
1643             .map(Path::new)
1644             .filter(|_| {
1645                 // Only spend time on further checks if we have what to translate *to*.
1646                 sess.real_rust_source_base_dir.is_some()
1647             })
1648             .filter(|virtual_dir| {
1649                 // Don't translate away `/rustc/$hash` if we're still remapping to it,
1650                 // since that means we're still building `std`/`rustc` that need it,
1651                 // and we don't want the real path to leak into codegen/debuginfo.
1652                 !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir)
1653             });
1654         let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| {
1655             debug!(
1656                 "try_to_translate_virtual_to_real(name={:?}): \
1657                  virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}",
1658                 name, virtual_rust_source_base_dir, sess.real_rust_source_base_dir,
1659             );
1660
1661             if let Some(virtual_dir) = virtual_rust_source_base_dir {
1662                 if let Some(real_dir) = &sess.real_rust_source_base_dir {
1663                     if let rustc_span::FileName::Real(old_name) = name {
1664                         if let rustc_span::RealFileName::Named(one_path) = old_name {
1665                             if let Ok(rest) = one_path.strip_prefix(virtual_dir) {
1666                                 let virtual_name = one_path.clone();
1667
1668                                 // The std library crates are in
1669                                 // `$sysroot/lib/rustlib/src/rust/library`, whereas other crates
1670                                 // may be in `$sysroot/lib/rustlib/src/rust/` directly. So we
1671                                 // detect crates from the std libs and handle them specially.
1672                                 const STD_LIBS: &[&str] = &[
1673                                     "core",
1674                                     "alloc",
1675                                     "std",
1676                                     "test",
1677                                     "term",
1678                                     "unwind",
1679                                     "proc_macro",
1680                                     "panic_abort",
1681                                     "panic_unwind",
1682                                     "profiler_builtins",
1683                                     "rtstartup",
1684                                     "rustc-std-workspace-core",
1685                                     "rustc-std-workspace-alloc",
1686                                     "rustc-std-workspace-std",
1687                                     "backtrace",
1688                                 ];
1689                                 let is_std_lib = STD_LIBS.iter().any(|l| rest.starts_with(l));
1690
1691                                 let new_path = if is_std_lib {
1692                                     real_dir.join("library").join(rest)
1693                                 } else {
1694                                     real_dir.join(rest)
1695                                 };
1696
1697                                 debug!(
1698                                     "try_to_translate_virtual_to_real: `{}` -> `{}`",
1699                                     virtual_name.display(),
1700                                     new_path.display(),
1701                                 );
1702                                 let new_name = rustc_span::RealFileName::Devirtualized {
1703                                     local_path: new_path,
1704                                     virtual_name,
1705                                 };
1706                                 *old_name = new_name;
1707                             }
1708                         }
1709                     }
1710                 }
1711             }
1712         };
1713
1714         self.cdata.source_map_import_info.get_or_init(|| {
1715             let external_source_map = self.root.source_map.decode(self);
1716
1717             external_source_map
1718                 .map(|source_file_to_import| {
1719                     // We can't reuse an existing SourceFile, so allocate a new one
1720                     // containing the information we need.
1721                     let rustc_span::SourceFile {
1722                         mut name,
1723                         name_was_remapped,
1724                         src_hash,
1725                         start_pos,
1726                         end_pos,
1727                         mut lines,
1728                         mut multibyte_chars,
1729                         mut non_narrow_chars,
1730                         mut normalized_pos,
1731                         name_hash,
1732                         ..
1733                     } = source_file_to_import;
1734
1735                     // If this file's path has been remapped to `/rustc/$hash`,
1736                     // we might be able to reverse that (also see comments above,
1737                     // on `try_to_translate_virtual_to_real`).
1738                     // FIXME(eddyb) we could check `name_was_remapped` here,
1739                     // but in practice it seems to be always `false`.
1740                     try_to_translate_virtual_to_real(&mut name);
1741
1742                     let source_length = (end_pos - start_pos).to_usize();
1743
1744                     // Translate line-start positions and multibyte character
1745                     // position into frame of reference local to file.
1746                     // `SourceMap::new_imported_source_file()` will then translate those
1747                     // coordinates to their new global frame of reference when the
1748                     // offset of the SourceFile is known.
1749                     for pos in &mut lines {
1750                         *pos = *pos - start_pos;
1751                     }
1752                     for mbc in &mut multibyte_chars {
1753                         mbc.pos = mbc.pos - start_pos;
1754                     }
1755                     for swc in &mut non_narrow_chars {
1756                         *swc = *swc - start_pos;
1757                     }
1758                     for np in &mut normalized_pos {
1759                         np.pos = np.pos - start_pos;
1760                     }
1761
1762                     let local_version = sess.source_map().new_imported_source_file(
1763                         name,
1764                         name_was_remapped,
1765                         src_hash,
1766                         name_hash,
1767                         source_length,
1768                         self.cnum,
1769                         lines,
1770                         multibyte_chars,
1771                         non_narrow_chars,
1772                         normalized_pos,
1773                         start_pos,
1774                         end_pos,
1775                     );
1776                     debug!(
1777                         "CrateMetaData::imported_source_files alloc \
1778                          source_file {:?} original (start_pos {:?} end_pos {:?}) \
1779                          translated (start_pos {:?} end_pos {:?})",
1780                         local_version.name,
1781                         start_pos,
1782                         end_pos,
1783                         local_version.start_pos,
1784                         local_version.end_pos
1785                     );
1786
1787                     ImportedSourceFile {
1788                         original_start_pos: start_pos,
1789                         original_end_pos: end_pos,
1790                         translated_source_file: local_version,
1791                     }
1792                 })
1793                 .collect()
1794         })
1795     }
1796 }
1797
1798 impl CrateMetadata {
1799     crate fn new(
1800         sess: &Session,
1801         blob: MetadataBlob,
1802         root: CrateRoot<'static>,
1803         raw_proc_macros: Option<&'static [ProcMacro]>,
1804         cnum: CrateNum,
1805         cnum_map: CrateNumMap,
1806         dep_kind: CrateDepKind,
1807         source: CrateSource,
1808         private_dep: bool,
1809         host_hash: Option<Svh>,
1810     ) -> CrateMetadata {
1811         let trait_impls = root
1812             .impls
1813             .decode((&blob, sess))
1814             .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1815             .collect();
1816         let alloc_decoding_state =
1817             AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
1818         let dependencies = Lock::new(cnum_map.iter().cloned().collect());
1819         CrateMetadata {
1820             blob,
1821             root,
1822             trait_impls,
1823             raw_proc_macros,
1824             source_map_import_info: OnceCell::new(),
1825             alloc_decoding_state,
1826             dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
1827             cnum,
1828             cnum_map,
1829             dependencies,
1830             dep_kind: Lock::new(dep_kind),
1831             source,
1832             private_dep,
1833             host_hash,
1834             extern_crate: Lock::new(None),
1835             hygiene_context: Default::default(),
1836             def_key_cache: Default::default(),
1837             def_path_hash_cache: Default::default(),
1838         }
1839     }
1840
1841     crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
1842         self.dependencies.borrow()
1843     }
1844
1845     crate fn add_dependency(&self, cnum: CrateNum) {
1846         self.dependencies.borrow_mut().push(cnum);
1847     }
1848
1849     crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool {
1850         let mut extern_crate = self.extern_crate.borrow_mut();
1851         let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank);
1852         if update {
1853             *extern_crate = Some(new_extern_crate);
1854         }
1855         update
1856     }
1857
1858     crate fn source(&self) -> &CrateSource {
1859         &self.source
1860     }
1861
1862     crate fn dep_kind(&self) -> CrateDepKind {
1863         *self.dep_kind.lock()
1864     }
1865
1866     crate fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) {
1867         self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
1868     }
1869
1870     crate fn panic_strategy(&self) -> PanicStrategy {
1871         self.root.panic_strategy
1872     }
1873
1874     crate fn needs_panic_runtime(&self) -> bool {
1875         self.root.needs_panic_runtime
1876     }
1877
1878     crate fn is_panic_runtime(&self) -> bool {
1879         self.root.panic_runtime
1880     }
1881
1882     crate fn is_profiler_runtime(&self) -> bool {
1883         self.root.profiler_runtime
1884     }
1885
1886     crate fn needs_allocator(&self) -> bool {
1887         self.root.needs_allocator
1888     }
1889
1890     crate fn has_global_allocator(&self) -> bool {
1891         self.root.has_global_allocator
1892     }
1893
1894     crate fn has_default_lib_allocator(&self) -> bool {
1895         self.root.has_default_lib_allocator
1896     }
1897
1898     crate fn is_proc_macro_crate(&self) -> bool {
1899         self.root.is_proc_macro_crate()
1900     }
1901
1902     crate fn name(&self) -> Symbol {
1903         self.root.name
1904     }
1905
1906     crate fn disambiguator(&self) -> CrateDisambiguator {
1907         self.root.disambiguator
1908     }
1909
1910     crate fn hash(&self) -> Svh {
1911         self.root.hash
1912     }
1913
1914     fn num_def_ids(&self) -> usize {
1915         self.root.tables.def_keys.size()
1916     }
1917
1918     fn local_def_id(&self, index: DefIndex) -> DefId {
1919         DefId { krate: self.cnum, index }
1920     }
1921
1922     // Translate a DefId from the current compilation environment to a DefId
1923     // for an external crate.
1924     fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1925         for (local, &global) in self.cnum_map.iter_enumerated() {
1926             if global == did.krate {
1927                 return Some(DefId { krate: local, index: did.index });
1928             }
1929         }
1930
1931         None
1932     }
1933 }
1934
1935 // Cannot be implemented on 'ProcMacro', as libproc_macro
1936 // does not depend on librustc_ast
1937 fn macro_kind(raw: &ProcMacro) -> MacroKind {
1938     match raw {
1939         ProcMacro::CustomDerive { .. } => MacroKind::Derive,
1940         ProcMacro::Attr { .. } => MacroKind::Attr,
1941         ProcMacro::Bang { .. } => MacroKind::Bang,
1942     }
1943 }