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