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