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