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