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