]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/decoder.rs
Rollup merge of #106779 - RReverser:patch-2, r=Mark-Simulacrum
[rust.git] / compiler / rustc_metadata / src / rmeta / decoder.rs
1 // Decoding metadata from a single crate's metadata
2
3 use crate::creader::{CStore, CrateMetadataRef};
4 use crate::rmeta::*;
5
6 use rustc_ast as ast;
7 use rustc_data_structures::captures::Captures;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_data_structures::svh::Svh;
10 use rustc_data_structures::sync::{Lock, LockGuard, Lrc, OnceCell};
11 use rustc_data_structures::unhash::UnhashMap;
12 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
13 use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, DeriveProcMacro};
14 use rustc_hir::def::{CtorKind, DefKind, Res};
15 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
16 use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash};
17 use rustc_hir::diagnostic_items::DiagnosticItems;
18 use rustc_index::vec::{Idx, IndexVec};
19 use rustc_middle::metadata::ModChild;
20 use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
21 use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
22 use rustc_middle::ty::codec::TyDecoder;
23 use rustc_middle::ty::fast_reject::SimplifiedType;
24 use rustc_middle::ty::GeneratorDiagnosticData;
25 use rustc_middle::ty::{self, ParameterizedOverTcx, Ty, TyCtxt, Visibility};
26 use rustc_serialize::opaque::MemDecoder;
27 use rustc_serialize::{Decodable, Decoder};
28 use rustc_session::cstore::{
29     CrateSource, ExternCrate, ForeignModule, LinkagePreference, NativeLib,
30 };
31 use rustc_session::Session;
32 use rustc_span::hygiene::ExpnIndex;
33 use rustc_span::source_map::{respan, Spanned};
34 use rustc_span::symbol::{kw, Ident, Symbol};
35 use rustc_span::{self, BytePos, ExpnId, Pos, Span, SyntaxContext, DUMMY_SP};
36
37 use proc_macro::bridge::client::ProcMacro;
38 use std::iter::TrustedLen;
39 use std::num::NonZeroUsize;
40 use std::path::Path;
41 use std::{io, iter, mem};
42
43 pub(super) use cstore_impl::provide;
44 pub use cstore_impl::provide_extern;
45 use rustc_span::hygiene::HygieneDecodeContext;
46
47 mod cstore_impl;
48
49 /// A reference to the raw binary version of crate metadata.
50 /// A `MetadataBlob` internally is just a reference counted pointer to
51 /// the actual data, so cloning it is cheap.
52 #[derive(Clone)]
53 pub(crate) struct MetadataBlob(Lrc<MetadataRef>);
54
55 // This is needed so we can create an OwningRef into the blob.
56 // The data behind a `MetadataBlob` has a stable address because it is
57 // contained within an Rc/Arc.
58 unsafe impl rustc_data_structures::owning_ref::StableAddress for MetadataBlob {}
59
60 // This is needed so we can create an OwningRef into the blob.
61 impl std::ops::Deref for MetadataBlob {
62     type Target = [u8];
63
64     #[inline]
65     fn deref(&self) -> &[u8] {
66         &self.0[..]
67     }
68 }
69
70 /// A map from external crate numbers (as decoded from some crate file) to
71 /// local crate numbers (as generated during this session). Each external
72 /// crate may refer to types in other external crates, and each has their
73 /// own crate numbers.
74 pub(crate) type CrateNumMap = IndexVec<CrateNum, CrateNum>;
75
76 pub(crate) struct CrateMetadata {
77     /// The primary crate data - binary metadata blob.
78     blob: MetadataBlob,
79
80     // --- Some data pre-decoded from the metadata blob, usually for performance ---
81     root: CrateRoot,
82     /// Trait impl data.
83     /// FIXME: Used only from queries and can use query cache,
84     /// so pre-decoding can probably be avoided.
85     trait_impls: FxHashMap<(u32, DefIndex), LazyArray<(DefIndex, Option<SimplifiedType>)>>,
86     /// Inherent impls which do not follow the normal coherence rules.
87     ///
88     /// These can be introduced using either `#![rustc_coherence_is_core]`
89     /// or `#[rustc_allow_incoherent_impl]`.
90     incoherent_impls: FxHashMap<SimplifiedType, LazyArray<DefIndex>>,
91     /// Proc macro descriptions for this crate, if it's a proc macro crate.
92     raw_proc_macros: Option<&'static [ProcMacro]>,
93     /// Source maps for code from the crate.
94     source_map_import_info: Lock<Vec<Option<ImportedSourceFile>>>,
95     /// For every definition in this crate, maps its `DefPathHash` to its `DefIndex`.
96     def_path_hash_map: DefPathHashMapRef<'static>,
97     /// Likewise for ExpnHash.
98     expn_hash_map: OnceCell<UnhashMap<ExpnHash, ExpnIndex>>,
99     /// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
100     alloc_decoding_state: AllocDecodingState,
101     /// Caches decoded `DefKey`s.
102     def_key_cache: Lock<FxHashMap<DefIndex, DefKey>>,
103     /// Caches decoded `DefPathHash`es.
104     def_path_hash_cache: Lock<FxHashMap<DefIndex, DefPathHash>>,
105
106     // --- Other significant crate properties ---
107     /// ID of this crate, from the current compilation session's point of view.
108     cnum: CrateNum,
109     /// Maps crate IDs as they are were seen from this crate's compilation sessions into
110     /// IDs as they are seen from the current compilation session.
111     cnum_map: CrateNumMap,
112     /// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
113     dependencies: Lock<Vec<CrateNum>>,
114     /// How to link (or not link) this crate to the currently compiled crate.
115     dep_kind: Lock<CrateDepKind>,
116     /// Filesystem location of this crate.
117     source: Lrc<CrateSource>,
118     /// Whether or not this crate should be consider a private dependency
119     /// for purposes of the 'exported_private_dependencies' lint
120     private_dep: bool,
121     /// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
122     host_hash: Option<Svh>,
123
124     /// Additional data used for decoding `HygieneData` (e.g. `SyntaxContext`
125     /// and `ExpnId`).
126     /// Note that we store a `HygieneDecodeContext` for each `CrateMetadat`. This is
127     /// because `SyntaxContext` ids are not globally unique, so we need
128     /// to track which ids we've decoded on a per-crate basis.
129     hygiene_context: HygieneDecodeContext,
130
131     // --- Data used only for improving diagnostics ---
132     /// Information about the `extern crate` item or path that caused this crate to be loaded.
133     /// If this is `None`, then the crate was injected (e.g., by the allocator).
134     extern_crate: Lock<Option<ExternCrate>>,
135 }
136
137 /// Holds information about a rustc_span::SourceFile imported from another crate.
138 /// See `imported_source_file()` for more information.
139 #[derive(Clone)]
140 struct ImportedSourceFile {
141     /// This SourceFile's byte-offset within the source_map of its original crate
142     original_start_pos: rustc_span::BytePos,
143     /// The end of this SourceFile within the source_map of its original crate
144     original_end_pos: rustc_span::BytePos,
145     /// The imported SourceFile's representation within the local source_map
146     translated_source_file: Lrc<rustc_span::SourceFile>,
147 }
148
149 pub(super) struct DecodeContext<'a, 'tcx> {
150     opaque: MemDecoder<'a>,
151     cdata: Option<CrateMetadataRef<'a>>,
152     blob: &'a MetadataBlob,
153     sess: Option<&'tcx Session>,
154     tcx: Option<TyCtxt<'tcx>>,
155
156     lazy_state: LazyState,
157
158     // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
159     alloc_decoding_session: Option<AllocDecodingSession<'a>>,
160 }
161
162 /// Abstract over the various ways one can create metadata decoders.
163 pub(super) trait Metadata<'a, 'tcx>: Copy {
164     fn blob(self) -> &'a MetadataBlob;
165
166     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
167         None
168     }
169     fn sess(self) -> Option<&'tcx Session> {
170         None
171     }
172     fn tcx(self) -> Option<TyCtxt<'tcx>> {
173         None
174     }
175
176     fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
177         let tcx = self.tcx();
178         DecodeContext {
179             opaque: MemDecoder::new(self.blob(), pos),
180             cdata: self.cdata(),
181             blob: self.blob(),
182             sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
183             tcx,
184             lazy_state: LazyState::NoNode,
185             alloc_decoding_session: self
186                 .cdata()
187                 .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()),
188         }
189     }
190 }
191
192 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
193     #[inline]
194     fn blob(self) -> &'a MetadataBlob {
195         self
196     }
197 }
198
199 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
200     #[inline]
201     fn blob(self) -> &'a MetadataBlob {
202         self.0
203     }
204
205     #[inline]
206     fn sess(self) -> Option<&'tcx Session> {
207         let (_, sess) = self;
208         Some(sess)
209     }
210 }
211
212 impl<'a, 'tcx> Metadata<'a, 'tcx> for CrateMetadataRef<'a> {
213     #[inline]
214     fn blob(self) -> &'a MetadataBlob {
215         &self.cdata.blob
216     }
217     #[inline]
218     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
219         Some(self)
220     }
221 }
222
223 impl<'a, 'tcx> Metadata<'a, 'tcx> for (CrateMetadataRef<'a>, &'tcx Session) {
224     #[inline]
225     fn blob(self) -> &'a MetadataBlob {
226         &self.0.cdata.blob
227     }
228     #[inline]
229     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
230         Some(self.0)
231     }
232     #[inline]
233     fn sess(self) -> Option<&'tcx Session> {
234         Some(self.1)
235     }
236 }
237
238 impl<'a, 'tcx> Metadata<'a, 'tcx> for (CrateMetadataRef<'a>, TyCtxt<'tcx>) {
239     #[inline]
240     fn blob(self) -> &'a MetadataBlob {
241         &self.0.cdata.blob
242     }
243     #[inline]
244     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
245         Some(self.0)
246     }
247     #[inline]
248     fn tcx(self) -> Option<TyCtxt<'tcx>> {
249         Some(self.1)
250     }
251 }
252
253 impl<T: ParameterizedOverTcx> LazyValue<T> {
254     fn decode<'a, 'tcx, M: Metadata<'a, 'tcx>>(self, metadata: M) -> T::Value<'tcx>
255     where
256         T::Value<'tcx>: Decodable<DecodeContext<'a, 'tcx>>,
257     {
258         let mut dcx = metadata.decoder(self.position.get());
259         dcx.lazy_state = LazyState::NodeStart(self.position);
260         T::Value::decode(&mut dcx)
261     }
262 }
263
264 struct DecodeIterator<'a, 'tcx, T> {
265     elem_counter: std::ops::Range<usize>,
266     dcx: DecodeContext<'a, 'tcx>,
267     _phantom: PhantomData<fn() -> T>,
268 }
269
270 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Iterator for DecodeIterator<'a, 'tcx, T> {
271     type Item = T;
272
273     #[inline(always)]
274     fn next(&mut self) -> Option<Self::Item> {
275         self.elem_counter.next().map(|_| T::decode(&mut self.dcx))
276     }
277
278     #[inline(always)]
279     fn size_hint(&self) -> (usize, Option<usize>) {
280         self.elem_counter.size_hint()
281     }
282 }
283
284 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> ExactSizeIterator
285     for DecodeIterator<'a, 'tcx, T>
286 {
287     fn len(&self) -> usize {
288         self.elem_counter.len()
289     }
290 }
291
292 unsafe impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> TrustedLen
293     for DecodeIterator<'a, 'tcx, T>
294 {
295 }
296
297 impl<T: ParameterizedOverTcx> LazyArray<T> {
298     fn decode<'a, 'tcx, M: Metadata<'a, 'tcx>>(
299         self,
300         metadata: M,
301     ) -> DecodeIterator<'a, 'tcx, T::Value<'tcx>>
302     where
303         T::Value<'tcx>: Decodable<DecodeContext<'a, 'tcx>>,
304     {
305         let mut dcx = metadata.decoder(self.position.get());
306         dcx.lazy_state = LazyState::NodeStart(self.position);
307         DecodeIterator { elem_counter: (0..self.num_elems), dcx, _phantom: PhantomData }
308     }
309 }
310
311 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
312     #[inline]
313     fn tcx(&self) -> TyCtxt<'tcx> {
314         debug_assert!(self.tcx.is_some(), "missing TyCtxt in DecodeContext");
315         self.tcx.unwrap()
316     }
317
318     #[inline]
319     pub fn blob(&self) -> &'a MetadataBlob {
320         self.blob
321     }
322
323     #[inline]
324     pub fn cdata(&self) -> CrateMetadataRef<'a> {
325         debug_assert!(self.cdata.is_some(), "missing CrateMetadata in DecodeContext");
326         self.cdata.unwrap()
327     }
328
329     #[inline]
330     fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
331         self.cdata().map_encoded_cnum_to_current(cnum)
332     }
333
334     #[inline]
335     fn read_lazy_offset_then<T>(&mut self, f: impl Fn(NonZeroUsize) -> T) -> T {
336         let distance = self.read_usize();
337         let position = match self.lazy_state {
338             LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
339             LazyState::NodeStart(start) => {
340                 let start = start.get();
341                 assert!(distance <= start);
342                 start - distance
343             }
344             LazyState::Previous(last_pos) => last_pos.get() + distance,
345         };
346         let position = NonZeroUsize::new(position).unwrap();
347         self.lazy_state = LazyState::Previous(position);
348         f(position)
349     }
350
351     fn read_lazy<T>(&mut self) -> LazyValue<T> {
352         self.read_lazy_offset_then(|pos| LazyValue::from_position(pos))
353     }
354
355     fn read_lazy_array<T>(&mut self, len: usize) -> LazyArray<T> {
356         self.read_lazy_offset_then(|pos| LazyArray::from_position_and_num_elems(pos, len))
357     }
358
359     fn read_lazy_table<I, T>(&mut self, len: usize) -> LazyTable<I, T> {
360         self.read_lazy_offset_then(|pos| LazyTable::from_position_and_encoded_size(pos, len))
361     }
362
363     #[inline]
364     pub fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
365         self.opaque.read_raw_bytes(len)
366     }
367 }
368
369 impl<'a, 'tcx> TyDecoder for DecodeContext<'a, 'tcx> {
370     const CLEAR_CROSS_CRATE: bool = true;
371
372     type I = TyCtxt<'tcx>;
373
374     #[inline]
375     fn interner(&self) -> Self::I {
376         self.tcx()
377     }
378
379     #[inline]
380     fn peek_byte(&self) -> u8 {
381         self.opaque.data[self.opaque.position()]
382     }
383
384     #[inline]
385     fn position(&self) -> usize {
386         self.opaque.position()
387     }
388
389     fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
390     where
391         F: FnOnce(&mut Self) -> Ty<'tcx>,
392     {
393         let tcx = self.tcx();
394
395         let key = ty::CReaderCacheKey { cnum: Some(self.cdata().cnum), pos: shorthand };
396
397         if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) {
398             return ty;
399         }
400
401         let ty = or_insert_with(self);
402         tcx.ty_rcache.borrow_mut().insert(key, ty);
403         ty
404     }
405
406     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
407     where
408         F: FnOnce(&mut Self) -> R,
409     {
410         let new_opaque = MemDecoder::new(self.opaque.data, pos);
411         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
412         let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
413         let r = f(self);
414         self.opaque = old_opaque;
415         self.lazy_state = old_state;
416         r
417     }
418
419     fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId {
420         if let Some(alloc_decoding_session) = self.alloc_decoding_session {
421             alloc_decoding_session.decode_alloc_id(self)
422         } else {
423             bug!("Attempting to decode interpret::AllocId without CrateMetadata")
424         }
425     }
426 }
427
428 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for CrateNum {
429     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> CrateNum {
430         let cnum = CrateNum::from_u32(d.read_u32());
431         d.map_encoded_cnum_to_current(cnum)
432     }
433 }
434
435 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefIndex {
436     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefIndex {
437         DefIndex::from_u32(d.read_u32())
438     }
439 }
440
441 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for ExpnIndex {
442     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> ExpnIndex {
443         ExpnIndex::from_u32(d.read_u32())
444     }
445 }
446
447 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for ast::AttrId {
448     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> ast::AttrId {
449         let sess = d.sess.expect("can't decode AttrId without Session");
450         sess.parse_sess.attr_id_generator.mk_attr_id()
451     }
452 }
453
454 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for SyntaxContext {
455     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SyntaxContext {
456         let cdata = decoder.cdata();
457         let sess = decoder.sess.unwrap();
458         let cname = cdata.root.name;
459         rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| {
460             debug!("SpecializedDecoder<SyntaxContext>: decoding {}", id);
461             cdata
462                 .root
463                 .syntax_contexts
464                 .get(cdata, id)
465                 .unwrap_or_else(|| panic!("Missing SyntaxContext {id:?} for crate {cname:?}"))
466                 .decode((cdata, sess))
467         })
468     }
469 }
470
471 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for ExpnId {
472     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> ExpnId {
473         let local_cdata = decoder.cdata();
474         let sess = decoder.sess.unwrap();
475
476         let cnum = CrateNum::decode(decoder);
477         let index = u32::decode(decoder);
478
479         let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| {
480             let ExpnId { krate: cnum, local_id: index } = expn_id;
481             // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s
482             // are stored in the owning crate, to avoid duplication.
483             debug_assert_ne!(cnum, LOCAL_CRATE);
484             let crate_data = if cnum == local_cdata.cnum {
485                 local_cdata
486             } else {
487                 local_cdata.cstore.get_crate_data(cnum)
488             };
489             let expn_data = crate_data
490                 .root
491                 .expn_data
492                 .get(crate_data, index)
493                 .unwrap()
494                 .decode((crate_data, sess));
495             let expn_hash = crate_data
496                 .root
497                 .expn_hashes
498                 .get(crate_data, index)
499                 .unwrap()
500                 .decode((crate_data, sess));
501             (expn_data, expn_hash)
502         });
503         expn_id
504     }
505 }
506
507 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for Span {
508     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span {
509         let ctxt = SyntaxContext::decode(decoder);
510         let tag = u8::decode(decoder);
511
512         if tag == TAG_PARTIAL_SPAN {
513             return DUMMY_SP.with_ctxt(ctxt);
514         }
515
516         debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN);
517
518         let lo = BytePos::decode(decoder);
519         let len = BytePos::decode(decoder);
520         let hi = lo + len;
521
522         let Some(sess) = decoder.sess else {
523             bug!("Cannot decode Span without Session.")
524         };
525
526         // Index of the file in the corresponding crate's list of encoded files.
527         let metadata_index = u32::decode(decoder);
528
529         // There are two possibilities here:
530         // 1. This is a 'local span', which is located inside a `SourceFile`
531         // that came from this crate. In this case, we use the source map data
532         // encoded in this crate. This branch should be taken nearly all of the time.
533         // 2. This is a 'foreign span', which is located inside a `SourceFile`
534         // that came from a *different* crate (some crate upstream of the one
535         // whose metadata we're looking at). For example, consider this dependency graph:
536         //
537         // A -> B -> C
538         //
539         // Suppose that we're currently compiling crate A, and start deserializing
540         // metadata from crate B. When we deserialize a Span from crate B's metadata,
541         // there are two possibilities:
542         //
543         // 1. The span references a file from crate B. This makes it a 'local' span,
544         // which means that we can use crate B's serialized source map information.
545         // 2. The span references a file from crate C. This makes it a 'foreign' span,
546         // which means we need to use Crate *C* (not crate B) to determine the source
547         // map information. We only record source map information for a file in the
548         // crate that 'owns' it, so deserializing a Span may require us to look at
549         // a transitive dependency.
550         //
551         // When we encode a foreign span, we adjust its 'lo' and 'high' values
552         // to be based on the *foreign* crate (e.g. crate C), not the crate
553         // we are writing metadata for (e.g. crate B). This allows us to
554         // treat the 'local' and 'foreign' cases almost identically during deserialization:
555         // we can call `imported_source_file` for the proper crate, and binary search
556         // through the returned slice using our span.
557         let source_file = if tag == TAG_VALID_SPAN_LOCAL {
558             decoder.cdata().imported_source_file(metadata_index, sess)
559         } else {
560             // When we encode a proc-macro crate, all `Span`s should be encoded
561             // with `TAG_VALID_SPAN_LOCAL`
562             if decoder.cdata().root.is_proc_macro_crate() {
563                 // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE
564                 // since we don't have `cnum_map` populated.
565                 let cnum = u32::decode(decoder);
566                 panic!(
567                     "Decoding of crate {:?} tried to access proc-macro dep {:?}",
568                     decoder.cdata().root.name,
569                     cnum
570                 );
571             }
572             // tag is TAG_VALID_SPAN_FOREIGN, checked by `debug_assert` above
573             let cnum = CrateNum::decode(decoder);
574             debug!(
575                 "SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {:?}",
576                 cnum
577             );
578
579             let foreign_data = decoder.cdata().cstore.get_crate_data(cnum);
580             foreign_data.imported_source_file(metadata_index, sess)
581         };
582
583         // Make sure our span is well-formed.
584         debug_assert!(
585             lo + source_file.original_start_pos <= source_file.original_end_pos,
586             "Malformed encoded span: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
587             lo,
588             source_file.original_start_pos,
589             source_file.original_end_pos
590         );
591
592         // Make sure we correctly filtered out invalid spans during encoding.
593         debug_assert!(
594             hi + source_file.original_start_pos <= source_file.original_end_pos,
595             "Malformed encoded span: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
596             hi,
597             source_file.original_start_pos,
598             source_file.original_end_pos
599         );
600
601         let lo = lo + source_file.translated_source_file.start_pos;
602         let hi = hi + source_file.translated_source_file.start_pos;
603
604         // Do not try to decode parent for foreign spans.
605         Span::new(lo, hi, ctxt, None)
606     }
607 }
608
609 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for Symbol {
610     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Self {
611         let tag = d.read_u8();
612
613         match tag {
614             SYMBOL_STR => {
615                 let s = d.read_str();
616                 Symbol::intern(s)
617             }
618             SYMBOL_OFFSET => {
619                 // read str offset
620                 let pos = d.read_usize();
621                 let old_pos = d.opaque.position();
622
623                 // move to str ofset and read
624                 d.opaque.set_position(pos);
625                 let s = d.read_str();
626                 let sym = Symbol::intern(s);
627
628                 // restore position
629                 d.opaque.set_position(old_pos);
630
631                 sym
632             }
633             SYMBOL_PREINTERNED => {
634                 let symbol_index = d.read_u32();
635                 Symbol::new_from_decoded(symbol_index)
636             }
637             _ => unreachable!(),
638         }
639     }
640 }
641
642 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
643     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Self {
644         ty::codec::RefDecodable::decode(d)
645     }
646 }
647
648 impl<'a, 'tcx, T> Decodable<DecodeContext<'a, 'tcx>> for LazyValue<T> {
649     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self {
650         decoder.read_lazy()
651     }
652 }
653
654 impl<'a, 'tcx, T> Decodable<DecodeContext<'a, 'tcx>> for LazyArray<T> {
655     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self {
656         let len = decoder.read_usize();
657         if len == 0 { LazyArray::empty() } else { decoder.read_lazy_array(len) }
658     }
659 }
660
661 impl<'a, 'tcx, I: Idx, T> Decodable<DecodeContext<'a, 'tcx>> for LazyTable<I, T> {
662     fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self {
663         let len = decoder.read_usize();
664         decoder.read_lazy_table(len)
665     }
666 }
667
668 implement_ty_decoder!(DecodeContext<'a, 'tcx>);
669
670 impl MetadataBlob {
671     pub(crate) fn new(metadata_ref: MetadataRef) -> MetadataBlob {
672         MetadataBlob(Lrc::new(metadata_ref))
673     }
674
675     pub(crate) fn is_compatible(&self) -> bool {
676         self.blob().starts_with(METADATA_HEADER)
677     }
678
679     pub(crate) fn get_rustc_version(&self) -> String {
680         LazyValue::<String>::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap())
681             .decode(self)
682     }
683
684     pub(crate) fn get_root(&self) -> CrateRoot {
685         let slice = &self.blob()[..];
686         let offset = METADATA_HEADER.len();
687
688         let pos_bytes = slice[offset..][..4].try_into().unwrap();
689         let pos = u32::from_be_bytes(pos_bytes) as usize;
690
691         LazyValue::<CrateRoot>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self)
692     }
693
694     pub(crate) fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> {
695         let root = self.get_root();
696         writeln!(out, "Crate info:")?;
697         writeln!(out, "name {}{}", root.name, root.extra_filename)?;
698         writeln!(out, "hash {} stable_crate_id {:?}", root.hash, root.stable_crate_id)?;
699         writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?;
700         writeln!(out, "=External Dependencies=")?;
701
702         for (i, dep) in root.crate_deps.decode(self).enumerate() {
703             let CrateDep { name, extra_filename, hash, host_hash, kind } = dep;
704             let number = i + 1;
705
706             writeln!(
707                 out,
708                 "{number} {name}{extra_filename} hash {hash} host_hash {host_hash:?} kind {kind:?}"
709             )?;
710         }
711         write!(out, "\n")?;
712         Ok(())
713     }
714 }
715
716 impl CrateRoot {
717     pub(crate) fn is_proc_macro_crate(&self) -> bool {
718         self.proc_macro_data.is_some()
719     }
720
721     pub(crate) fn name(&self) -> Symbol {
722         self.name
723     }
724
725     pub(crate) fn hash(&self) -> Svh {
726         self.hash
727     }
728
729     pub(crate) fn stable_crate_id(&self) -> StableCrateId {
730         self.stable_crate_id
731     }
732
733     pub(crate) fn triple(&self) -> &TargetTriple {
734         &self.triple
735     }
736
737     pub(crate) fn decode_crate_deps<'a>(
738         &self,
739         metadata: &'a MetadataBlob,
740     ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
741         self.crate_deps.decode(metadata)
742     }
743 }
744
745 impl<'a, 'tcx> CrateMetadataRef<'a> {
746     fn raw_proc_macro(self, id: DefIndex) -> &'a ProcMacro {
747         // DefIndex's in root.proc_macro_data have a one-to-one correspondence
748         // with items in 'raw_proc_macros'.
749         let pos = self
750             .root
751             .proc_macro_data
752             .as_ref()
753             .unwrap()
754             .macros
755             .decode(self)
756             .position(|i| i == id)
757             .unwrap();
758         &self.raw_proc_macros.unwrap()[pos]
759     }
760
761     fn opt_item_name(self, item_index: DefIndex) -> Option<Symbol> {
762         let def_key = self.def_key(item_index);
763         def_key.disambiguated_data.data.get_opt_name().or_else(|| {
764             if def_key.disambiguated_data.data == DefPathData::Ctor {
765                 let parent_index = def_key.parent.expect("no parent for a constructor");
766                 self.def_key(parent_index).disambiguated_data.data.get_opt_name()
767             } else {
768                 None
769             }
770         })
771     }
772
773     fn item_name(self, item_index: DefIndex) -> Symbol {
774         self.opt_item_name(item_index).expect("no encoded ident for item")
775     }
776
777     fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option<Ident> {
778         let name = self.opt_item_name(item_index)?;
779         let span =
780             self.root.tables.def_ident_span.get(self, item_index).unwrap().decode((self, sess));
781         Some(Ident::new(name, span))
782     }
783
784     fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident {
785         self.opt_item_ident(item_index, sess).expect("no encoded ident for item")
786     }
787
788     #[inline]
789     pub(super) fn map_encoded_cnum_to_current(self, cnum: CrateNum) -> CrateNum {
790         if cnum == LOCAL_CRATE { self.cnum } else { self.cnum_map[cnum] }
791     }
792
793     fn def_kind(self, item_id: DefIndex) -> DefKind {
794         self.root.tables.opt_def_kind.get(self, item_id).unwrap_or_else(|| {
795             bug!(
796                 "CrateMetadata::def_kind({:?}): id not found, in crate {:?} with number {}",
797                 item_id,
798                 self.root.name,
799                 self.cnum,
800             )
801         })
802     }
803
804     fn get_span(self, index: DefIndex, sess: &Session) -> Span {
805         self.root
806             .tables
807             .def_span
808             .get(self, index)
809             .unwrap_or_else(|| panic!("Missing span for {index:?}"))
810             .decode((self, sess))
811     }
812
813     fn load_proc_macro(self, id: DefIndex, sess: &Session) -> SyntaxExtension {
814         let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
815             ProcMacro::CustomDerive { trait_name, attributes, client } => {
816                 let helper_attrs =
817                     attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
818                 (
819                     trait_name,
820                     SyntaxExtensionKind::Derive(Box::new(DeriveProcMacro { client })),
821                     helper_attrs,
822                 )
823             }
824             ProcMacro::Attr { name, client } => {
825                 (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new())
826             }
827             ProcMacro::Bang { name, client } => {
828                 (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new())
829             }
830         };
831
832         let attrs: Vec<_> = self.get_item_attrs(id, sess).collect();
833         SyntaxExtension::new(
834             sess,
835             kind,
836             self.get_span(id, sess),
837             helper_attrs,
838             self.root.edition,
839             Symbol::intern(name),
840             &attrs,
841         )
842     }
843
844     fn get_variant(self, kind: &DefKind, index: DefIndex, parent_did: DefId) -> ty::VariantDef {
845         let adt_kind = match kind {
846             DefKind::Variant => ty::AdtKind::Enum,
847             DefKind::Struct => ty::AdtKind::Struct,
848             DefKind::Union => ty::AdtKind::Union,
849             _ => bug!(),
850         };
851
852         let data = self.root.tables.variant_data.get(self, index).unwrap().decode(self);
853
854         let variant_did =
855             if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
856         let ctor = data.ctor.map(|(kind, index)| (kind, self.local_def_id(index)));
857
858         ty::VariantDef::new(
859             self.item_name(index),
860             variant_did,
861             ctor,
862             data.discr,
863             self.root
864                 .tables
865                 .children
866                 .get(self, index)
867                 .unwrap_or_else(LazyArray::empty)
868                 .decode(self)
869                 .map(|index| ty::FieldDef {
870                     did: self.local_def_id(index),
871                     name: self.item_name(index),
872                     vis: self.get_visibility(index),
873                 })
874                 .collect(),
875             adt_kind,
876             parent_did,
877             false,
878             data.is_non_exhaustive,
879         )
880     }
881
882     fn get_adt_def(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::AdtDef<'tcx> {
883         let kind = self.def_kind(item_id);
884         let did = self.local_def_id(item_id);
885
886         let adt_kind = match kind {
887             DefKind::Enum => ty::AdtKind::Enum,
888             DefKind::Struct => ty::AdtKind::Struct,
889             DefKind::Union => ty::AdtKind::Union,
890             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
891         };
892         let repr = self.root.tables.repr_options.get(self, item_id).unwrap().decode(self);
893
894         let variants = if let ty::AdtKind::Enum = adt_kind {
895             self.root
896                 .tables
897                 .children
898                 .get(self, item_id)
899                 .unwrap_or_else(LazyArray::empty)
900                 .decode(self)
901                 .filter_map(|index| {
902                     let kind = self.def_kind(index);
903                     match kind {
904                         DefKind::Ctor(..) => None,
905                         _ => Some(self.get_variant(&kind, index, did)),
906                     }
907                 })
908                 .collect()
909         } else {
910             std::iter::once(self.get_variant(&kind, item_id, did)).collect()
911         };
912
913         tcx.alloc_adt_def(did, adt_kind, variants, repr)
914     }
915
916     fn get_generics(self, item_id: DefIndex, sess: &Session) -> ty::Generics {
917         self.root.tables.generics_of.get(self, item_id).unwrap().decode((self, sess))
918     }
919
920     fn get_visibility(self, id: DefIndex) -> ty::Visibility<DefId> {
921         self.root
922             .tables
923             .visibility
924             .get(self, id)
925             .unwrap()
926             .decode(self)
927             .map_id(|index| self.local_def_id(index))
928     }
929
930     fn get_trait_item_def_id(self, id: DefIndex) -> Option<DefId> {
931         self.root.tables.trait_item_def_id.get(self, id).map(|d| d.decode_from_cdata(self))
932     }
933
934     fn get_expn_that_defined(self, id: DefIndex, sess: &Session) -> ExpnId {
935         self.root.tables.expn_that_defined.get(self, id).unwrap().decode((self, sess))
936     }
937
938     fn get_debugger_visualizers(self) -> Vec<rustc_span::DebuggerVisualizerFile> {
939         self.root.debugger_visualizers.decode(self).collect::<Vec<_>>()
940     }
941
942     /// Iterates over all the stability attributes in the given crate.
943     fn get_lib_features(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Option<Symbol>)] {
944         tcx.arena.alloc_from_iter(self.root.lib_features.decode(self))
945     }
946
947     /// Iterates over the stability implications in the given crate (when a `#[unstable]` attribute
948     /// has an `implied_by` meta item, then the mapping from the implied feature to the actual
949     /// feature is a stability implication).
950     fn get_stability_implications(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Symbol)] {
951         tcx.arena.alloc_from_iter(self.root.stability_implications.decode(self))
952     }
953
954     /// Iterates over the language items in the given crate.
955     fn get_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, LangItem)] {
956         tcx.arena.alloc_from_iter(
957             self.root
958                 .lang_items
959                 .decode(self)
960                 .map(move |(def_index, index)| (self.local_def_id(def_index), index)),
961         )
962     }
963
964     /// Iterates over the diagnostic items in the given crate.
965     fn get_diagnostic_items(self) -> DiagnosticItems {
966         let mut id_to_name = FxHashMap::default();
967         let name_to_id = self
968             .root
969             .diagnostic_items
970             .decode(self)
971             .map(|(name, def_index)| {
972                 let id = self.local_def_id(def_index);
973                 id_to_name.insert(id, name);
974                 (name, id)
975             })
976             .collect();
977         DiagnosticItems { id_to_name, name_to_id }
978     }
979
980     fn get_mod_child(self, id: DefIndex, sess: &Session) -> ModChild {
981         let ident = self.item_ident(id, sess);
982         let kind = self.def_kind(id);
983         let def_id = self.local_def_id(id);
984         let res = Res::Def(kind, def_id);
985         let vis = self.get_visibility(id);
986         let span = self.get_span(id, sess);
987         let macro_rules = match kind {
988             DefKind::Macro(..) => self.root.tables.is_macro_rules.get(self, id),
989             _ => false,
990         };
991
992         ModChild { ident, res, vis, span, macro_rules }
993     }
994
995     /// Iterates over all named children of the given module,
996     /// including both proper items and reexports.
997     /// Module here is understood in name resolution sense - it can be a `mod` item,
998     /// or a crate root, or an enum, or a trait.
999     fn get_module_children(
1000         self,
1001         id: DefIndex,
1002         sess: &'a Session,
1003     ) -> impl Iterator<Item = ModChild> + 'a {
1004         iter::from_generator(move || {
1005             if let Some(data) = &self.root.proc_macro_data {
1006                 // If we are loading as a proc macro, we want to return
1007                 // the view of this crate as a proc macro crate.
1008                 if id == CRATE_DEF_INDEX {
1009                     for child_index in data.macros.decode(self) {
1010                         yield self.get_mod_child(child_index, sess);
1011                     }
1012                 }
1013             } else {
1014                 // Iterate over all children.
1015                 for child_index in self.root.tables.children.get(self, id).unwrap().decode(self) {
1016                     yield self.get_mod_child(child_index, sess);
1017                 }
1018
1019                 if let Some(reexports) = self.root.tables.module_reexports.get(self, id) {
1020                     for reexport in reexports.decode((self, sess)) {
1021                         yield reexport;
1022                     }
1023                 }
1024             }
1025         })
1026     }
1027
1028     fn is_ctfe_mir_available(self, id: DefIndex) -> bool {
1029         self.root.tables.mir_for_ctfe.get(self, id).is_some()
1030     }
1031
1032     fn is_item_mir_available(self, id: DefIndex) -> bool {
1033         self.root.tables.optimized_mir.get(self, id).is_some()
1034     }
1035
1036     fn module_expansion(self, id: DefIndex, sess: &Session) -> ExpnId {
1037         match self.def_kind(id) {
1038             DefKind::Mod | DefKind::Enum | DefKind::Trait => self.get_expn_that_defined(id, sess),
1039             _ => panic!("Expected module, found {:?}", self.local_def_id(id)),
1040         }
1041     }
1042
1043     fn get_fn_has_self_parameter(self, id: DefIndex, sess: &'a Session) -> bool {
1044         self.root
1045             .tables
1046             .fn_arg_names
1047             .get(self, id)
1048             .unwrap_or_else(LazyArray::empty)
1049             .decode((self, sess))
1050             .nth(0)
1051             .map_or(false, |ident| ident.name == kw::SelfLower)
1052     }
1053
1054     fn get_associated_item_def_ids(
1055         self,
1056         id: DefIndex,
1057         sess: &'a Session,
1058     ) -> impl Iterator<Item = DefId> + 'a {
1059         self.root
1060             .tables
1061             .children
1062             .get(self, id)
1063             .unwrap_or_else(LazyArray::empty)
1064             .decode((self, sess))
1065             .map(move |child_index| self.local_def_id(child_index))
1066     }
1067
1068     fn get_associated_item(self, id: DefIndex, sess: &'a Session) -> ty::AssocItem {
1069         let name = self.item_name(id);
1070
1071         let kind = match self.def_kind(id) {
1072             DefKind::AssocConst => ty::AssocKind::Const,
1073             DefKind::AssocFn => ty::AssocKind::Fn,
1074             DefKind::AssocTy => ty::AssocKind::Type,
1075             _ => bug!("cannot get associated-item of `{:?}`", self.def_key(id)),
1076         };
1077         let has_self = self.get_fn_has_self_parameter(id, sess);
1078         let container = self.root.tables.assoc_container.get(self, id).unwrap();
1079
1080         ty::AssocItem {
1081             name,
1082             kind,
1083             def_id: self.local_def_id(id),
1084             trait_item_def_id: self.get_trait_item_def_id(id),
1085             container,
1086             fn_has_self_parameter: has_self,
1087         }
1088     }
1089
1090     fn get_ctor(self, node_id: DefIndex) -> Option<(CtorKind, DefId)> {
1091         match self.def_kind(node_id) {
1092             DefKind::Struct | DefKind::Variant => {
1093                 let vdata = self.root.tables.variant_data.get(self, node_id).unwrap().decode(self);
1094                 vdata.ctor.map(|(kind, index)| (kind, self.local_def_id(index)))
1095             }
1096             _ => None,
1097         }
1098     }
1099
1100     fn get_item_attrs(
1101         self,
1102         id: DefIndex,
1103         sess: &'a Session,
1104     ) -> impl Iterator<Item = ast::Attribute> + 'a {
1105         self.root
1106             .tables
1107             .attributes
1108             .get(self, id)
1109             .unwrap_or_else(|| {
1110                 // Structure and variant constructors don't have any attributes encoded for them,
1111                 // but we assume that someone passing a constructor ID actually wants to look at
1112                 // the attributes on the corresponding struct or variant.
1113                 let def_key = self.def_key(id);
1114                 assert_eq!(def_key.disambiguated_data.data, DefPathData::Ctor);
1115                 let parent_id = def_key.parent.expect("no parent for a constructor");
1116                 self.root
1117                     .tables
1118                     .attributes
1119                     .get(self, parent_id)
1120                     .expect("no encoded attributes for a structure or variant")
1121             })
1122             .decode((self, sess))
1123     }
1124
1125     fn get_struct_field_names(
1126         self,
1127         id: DefIndex,
1128         sess: &'a Session,
1129     ) -> impl Iterator<Item = Spanned<Symbol>> + 'a {
1130         self.root
1131             .tables
1132             .children
1133             .get(self, id)
1134             .unwrap_or_else(LazyArray::empty)
1135             .decode(self)
1136             .map(move |index| respan(self.get_span(index, sess), self.item_name(index)))
1137     }
1138
1139     fn get_struct_field_visibilities(
1140         self,
1141         id: DefIndex,
1142     ) -> impl Iterator<Item = Visibility<DefId>> + 'a {
1143         self.root
1144             .tables
1145             .children
1146             .get(self, id)
1147             .unwrap_or_else(LazyArray::empty)
1148             .decode(self)
1149             .map(move |field_index| self.get_visibility(field_index))
1150     }
1151
1152     fn get_inherent_implementations_for_type(
1153         self,
1154         tcx: TyCtxt<'tcx>,
1155         id: DefIndex,
1156     ) -> &'tcx [DefId] {
1157         tcx.arena.alloc_from_iter(
1158             self.root
1159                 .tables
1160                 .inherent_impls
1161                 .get(self, id)
1162                 .unwrap_or_else(LazyArray::empty)
1163                 .decode(self)
1164                 .map(|index| self.local_def_id(index)),
1165         )
1166     }
1167
1168     /// Decodes all inherent impls in the crate (for rustdoc).
1169     fn get_inherent_impls(self) -> impl Iterator<Item = (DefId, DefId)> + 'a {
1170         (0..self.root.tables.inherent_impls.size()).flat_map(move |i| {
1171             let ty_index = DefIndex::from_usize(i);
1172             let ty_def_id = self.local_def_id(ty_index);
1173             self.root
1174                 .tables
1175                 .inherent_impls
1176                 .get(self, ty_index)
1177                 .unwrap_or_else(LazyArray::empty)
1178                 .decode(self)
1179                 .map(move |impl_index| (ty_def_id, self.local_def_id(impl_index)))
1180         })
1181     }
1182
1183     /// Decodes all traits in the crate (for rustdoc and rustc diagnostics).
1184     fn get_traits(self) -> impl Iterator<Item = DefId> + 'a {
1185         self.root.traits.decode(self).map(move |index| self.local_def_id(index))
1186     }
1187
1188     /// Decodes all trait impls in the crate (for rustdoc).
1189     fn get_trait_impls(self) -> impl Iterator<Item = (DefId, DefId, Option<SimplifiedType>)> + 'a {
1190         self.cdata.trait_impls.iter().flat_map(move |(&(trait_cnum_raw, trait_index), impls)| {
1191             let trait_def_id = DefId {
1192                 krate: self.cnum_map[CrateNum::from_u32(trait_cnum_raw)],
1193                 index: trait_index,
1194             };
1195             impls.decode(self).map(move |(impl_index, simplified_self_ty)| {
1196                 (trait_def_id, self.local_def_id(impl_index), simplified_self_ty)
1197             })
1198         })
1199     }
1200
1201     fn get_all_incoherent_impls(self) -> impl Iterator<Item = DefId> + 'a {
1202         self.cdata
1203             .incoherent_impls
1204             .values()
1205             .flat_map(move |impls| impls.decode(self).map(move |idx| self.local_def_id(idx)))
1206     }
1207
1208     fn get_incoherent_impls(self, tcx: TyCtxt<'tcx>, simp: SimplifiedType) -> &'tcx [DefId] {
1209         if let Some(impls) = self.cdata.incoherent_impls.get(&simp) {
1210             tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx)))
1211         } else {
1212             &[]
1213         }
1214     }
1215
1216     fn get_implementations_of_trait(
1217         self,
1218         tcx: TyCtxt<'tcx>,
1219         trait_def_id: DefId,
1220     ) -> &'tcx [(DefId, Option<SimplifiedType>)] {
1221         if self.trait_impls.is_empty() {
1222             return &[];
1223         }
1224
1225         // Do a reverse lookup beforehand to avoid touching the crate_num
1226         // hash map in the loop below.
1227         let key = match self.reverse_translate_def_id(trait_def_id) {
1228             Some(def_id) => (def_id.krate.as_u32(), def_id.index),
1229             None => return &[],
1230         };
1231
1232         if let Some(impls) = self.trait_impls.get(&key) {
1233             tcx.arena.alloc_from_iter(
1234                 impls
1235                     .decode(self)
1236                     .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)),
1237             )
1238         } else {
1239             &[]
1240         }
1241     }
1242
1243     fn get_native_libraries(self, sess: &'a Session) -> impl Iterator<Item = NativeLib> + 'a {
1244         self.root.native_libraries.decode((self, sess))
1245     }
1246
1247     fn get_proc_macro_quoted_span(self, index: usize, sess: &Session) -> Span {
1248         self.root
1249             .tables
1250             .proc_macro_quoted_spans
1251             .get(self, index)
1252             .unwrap_or_else(|| panic!("Missing proc macro quoted span: {index:?}"))
1253             .decode((self, sess))
1254     }
1255
1256     fn get_foreign_modules(self, sess: &'a Session) -> impl Iterator<Item = ForeignModule> + '_ {
1257         self.root.foreign_modules.decode((self, sess))
1258     }
1259
1260     fn get_dylib_dependency_formats(
1261         self,
1262         tcx: TyCtxt<'tcx>,
1263     ) -> &'tcx [(CrateNum, LinkagePreference)] {
1264         tcx.arena.alloc_from_iter(
1265             self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| {
1266                 let cnum = CrateNum::new(i + 1);
1267                 link.map(|link| (self.cnum_map[cnum], link))
1268             }),
1269         )
1270     }
1271
1272     fn get_missing_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [LangItem] {
1273         tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self))
1274     }
1275
1276     fn exported_symbols(
1277         self,
1278         tcx: TyCtxt<'tcx>,
1279     ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
1280         tcx.arena.alloc_from_iter(self.root.exported_symbols.decode((self, tcx)))
1281     }
1282
1283     fn get_macro(self, id: DefIndex, sess: &Session) -> ast::MacroDef {
1284         match self.def_kind(id) {
1285             DefKind::Macro(_) => {
1286                 let macro_rules = self.root.tables.is_macro_rules.get(self, id);
1287                 let body =
1288                     self.root.tables.macro_definition.get(self, id).unwrap().decode((self, sess));
1289                 ast::MacroDef { macro_rules, body: ast::ptr::P(body) }
1290             }
1291             _ => bug!(),
1292         }
1293     }
1294
1295     fn is_foreign_item(self, id: DefIndex) -> bool {
1296         if let Some(parent) = self.def_key(id).parent {
1297             matches!(self.def_kind(parent), DefKind::ForeignMod)
1298         } else {
1299             false
1300         }
1301     }
1302
1303     #[inline]
1304     fn def_key(self, index: DefIndex) -> DefKey {
1305         *self
1306             .def_key_cache
1307             .lock()
1308             .entry(index)
1309             .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self))
1310     }
1311
1312     // Returns the path leading to the thing with this `id`.
1313     fn def_path(self, id: DefIndex) -> DefPath {
1314         debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1315         DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1316     }
1317
1318     fn def_path_hash_unlocked(
1319         self,
1320         index: DefIndex,
1321         def_path_hashes: &mut FxHashMap<DefIndex, DefPathHash>,
1322     ) -> DefPathHash {
1323         *def_path_hashes
1324             .entry(index)
1325             .or_insert_with(|| self.root.tables.def_path_hashes.get(self, index).unwrap())
1326     }
1327
1328     #[inline]
1329     fn def_path_hash(self, index: DefIndex) -> DefPathHash {
1330         let mut def_path_hashes = self.def_path_hash_cache.lock();
1331         self.def_path_hash_unlocked(index, &mut def_path_hashes)
1332     }
1333
1334     #[inline]
1335     fn def_path_hash_to_def_index(self, hash: DefPathHash) -> DefIndex {
1336         self.def_path_hash_map.def_path_hash_to_def_index(&hash)
1337     }
1338
1339     fn expn_hash_to_expn_id(self, sess: &Session, index_guess: u32, hash: ExpnHash) -> ExpnId {
1340         debug_assert_eq!(ExpnId::from_hash(hash), None);
1341         let index_guess = ExpnIndex::from_u32(index_guess);
1342         let old_hash = self.root.expn_hashes.get(self, index_guess).map(|lazy| lazy.decode(self));
1343
1344         let index = if old_hash == Some(hash) {
1345             // Fast path: the expn and its index is unchanged from the
1346             // previous compilation session. There is no need to decode anything
1347             // else.
1348             index_guess
1349         } else {
1350             // Slow path: We need to find out the new `DefIndex` of the provided
1351             // `DefPathHash`, if its still exists. This requires decoding every `DefPathHash`
1352             // stored in this crate.
1353             let map = self.cdata.expn_hash_map.get_or_init(|| {
1354                 let end_id = self.root.expn_hashes.size() as u32;
1355                 let mut map =
1356                     UnhashMap::with_capacity_and_hasher(end_id as usize, Default::default());
1357                 for i in 0..end_id {
1358                     let i = ExpnIndex::from_u32(i);
1359                     if let Some(hash) = self.root.expn_hashes.get(self, i) {
1360                         map.insert(hash.decode(self), i);
1361                     }
1362                 }
1363                 map
1364             });
1365             map[&hash]
1366         };
1367
1368         let data = self.root.expn_data.get(self, index).unwrap().decode((self, sess));
1369         rustc_span::hygiene::register_expn_id(self.cnum, index, data, hash)
1370     }
1371
1372     /// Imports the source_map from an external crate into the source_map of the crate
1373     /// currently being compiled (the "local crate").
1374     ///
1375     /// The import algorithm works analogous to how AST items are inlined from an
1376     /// external crate's metadata:
1377     /// For every SourceFile in the external source_map an 'inline' copy is created in the
1378     /// local source_map. The correspondence relation between external and local
1379     /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1380     /// function. When an item from an external crate is later inlined into this
1381     /// crate, this correspondence information is used to translate the span
1382     /// information of the inlined item so that it refers the correct positions in
1383     /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1384     ///
1385     /// The import algorithm in the function below will reuse SourceFiles already
1386     /// existing in the local source_map. For example, even if the SourceFile of some
1387     /// source file of libstd gets imported many times, there will only ever be
1388     /// one SourceFile object for the corresponding file in the local source_map.
1389     ///
1390     /// Note that imported SourceFiles do not actually contain the source code of the
1391     /// file they represent, just information about length, line breaks, and
1392     /// multibyte characters. This information is enough to generate valid debuginfo
1393     /// for items inlined from other crates.
1394     ///
1395     /// Proc macro crates don't currently export spans, so this function does not have
1396     /// to work for them.
1397     fn imported_source_file(self, source_file_index: u32, sess: &Session) -> ImportedSourceFile {
1398         fn filter<'a>(sess: &Session, path: Option<&'a Path>) -> Option<&'a Path> {
1399             path.filter(|_| {
1400                 // Only spend time on further checks if we have what to translate *to*.
1401                 sess.opts.real_rust_source_base_dir.is_some()
1402                 // Some tests need the translation to be always skipped.
1403                 && sess.opts.unstable_opts.translate_remapped_path_to_local_path
1404             })
1405             .filter(|virtual_dir| {
1406                 // Don't translate away `/rustc/$hash` if we're still remapping to it,
1407                 // since that means we're still building `std`/`rustc` that need it,
1408                 // and we don't want the real path to leak into codegen/debuginfo.
1409                 !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir)
1410             })
1411         }
1412
1413         // Translate the virtual `/rustc/$hash` prefix back to a real directory
1414         // that should hold actual sources, where possible.
1415         //
1416         // NOTE: if you update this, you might need to also update bootstrap's code for generating
1417         // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`.
1418         let virtual_rust_source_base_dir = [
1419             filter(sess, option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR").map(Path::new)),
1420             filter(sess, sess.opts.unstable_opts.simulate_remapped_rust_src_base.as_deref()),
1421         ];
1422
1423         let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| {
1424             debug!(
1425                 "try_to_translate_virtual_to_real(name={:?}): \
1426                  virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}",
1427                 name, virtual_rust_source_base_dir, sess.opts.real_rust_source_base_dir,
1428             );
1429
1430             for virtual_dir in virtual_rust_source_base_dir.iter().flatten() {
1431                 if let Some(real_dir) = &sess.opts.real_rust_source_base_dir {
1432                     if let rustc_span::FileName::Real(old_name) = name {
1433                         if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } =
1434                             old_name
1435                         {
1436                             if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) {
1437                                 let virtual_name = virtual_name.clone();
1438
1439                                 // The std library crates are in
1440                                 // `$sysroot/lib/rustlib/src/rust/library`, whereas other crates
1441                                 // may be in `$sysroot/lib/rustlib/src/rust/` directly. So we
1442                                 // detect crates from the std libs and handle them specially.
1443                                 const STD_LIBS: &[&str] = &[
1444                                     "core",
1445                                     "alloc",
1446                                     "std",
1447                                     "test",
1448                                     "term",
1449                                     "unwind",
1450                                     "proc_macro",
1451                                     "panic_abort",
1452                                     "panic_unwind",
1453                                     "profiler_builtins",
1454                                     "rtstartup",
1455                                     "rustc-std-workspace-core",
1456                                     "rustc-std-workspace-alloc",
1457                                     "rustc-std-workspace-std",
1458                                     "backtrace",
1459                                 ];
1460                                 let is_std_lib = STD_LIBS.iter().any(|l| rest.starts_with(l));
1461
1462                                 let new_path = if is_std_lib {
1463                                     real_dir.join("library").join(rest)
1464                                 } else {
1465                                     real_dir.join(rest)
1466                                 };
1467
1468                                 debug!(
1469                                     "try_to_translate_virtual_to_real: `{}` -> `{}`",
1470                                     virtual_name.display(),
1471                                     new_path.display(),
1472                                 );
1473                                 let new_name = rustc_span::RealFileName::Remapped {
1474                                     local_path: Some(new_path),
1475                                     virtual_name,
1476                                 };
1477                                 *old_name = new_name;
1478                             }
1479                         }
1480                     }
1481                 }
1482             }
1483         };
1484
1485         let mut import_info = self.cdata.source_map_import_info.lock();
1486         for _ in import_info.len()..=(source_file_index as usize) {
1487             import_info.push(None);
1488         }
1489         import_info[source_file_index as usize]
1490             .get_or_insert_with(|| {
1491                 let source_file_to_import = self
1492                     .root
1493                     .source_map
1494                     .get(self, source_file_index)
1495                     .expect("missing source file")
1496                     .decode(self);
1497
1498                 // We can't reuse an existing SourceFile, so allocate a new one
1499                 // containing the information we need.
1500                 let rustc_span::SourceFile {
1501                     mut name,
1502                     src_hash,
1503                     start_pos,
1504                     end_pos,
1505                     lines,
1506                     multibyte_chars,
1507                     non_narrow_chars,
1508                     normalized_pos,
1509                     name_hash,
1510                     ..
1511                 } = source_file_to_import;
1512
1513                 // If this file is under $sysroot/lib/rustlib/src/ but has not been remapped
1514                 // during rust bootstrapping by `remap-debuginfo = true`, and the user
1515                 // wish to simulate that behaviour by -Z simulate-remapped-rust-src-base,
1516                 // then we change `name` to a similar state as if the rust was bootstrapped
1517                 // with `remap-debuginfo = true`.
1518                 // This is useful for testing so that tests about the effects of
1519                 // `try_to_translate_virtual_to_real` don't have to worry about how the
1520                 // compiler is bootstrapped.
1521                 if let Some(virtual_dir) = &sess.opts.unstable_opts.simulate_remapped_rust_src_base
1522                 {
1523                     if let Some(real_dir) = &sess.opts.real_rust_source_base_dir {
1524                         for subdir in ["library", "compiler"] {
1525                             if let rustc_span::FileName::Real(ref mut old_name) = name {
1526                                 if let rustc_span::RealFileName::LocalPath(local) = old_name {
1527                                     if let Ok(rest) = local.strip_prefix(real_dir.join(subdir)) {
1528                                         *old_name = rustc_span::RealFileName::Remapped {
1529                                             local_path: None,
1530                                             virtual_name: virtual_dir.join(subdir).join(rest),
1531                                         };
1532                                     }
1533                                 }
1534                             }
1535                         }
1536                     }
1537                 }
1538
1539                 // If this file's path has been remapped to `/rustc/$hash`,
1540                 // we might be able to reverse that (also see comments above,
1541                 // on `try_to_translate_virtual_to_real`).
1542                 try_to_translate_virtual_to_real(&mut name);
1543
1544                 let source_length = (end_pos - start_pos).to_usize();
1545
1546                 let local_version = sess.source_map().new_imported_source_file(
1547                     name,
1548                     src_hash,
1549                     name_hash,
1550                     source_length,
1551                     self.cnum,
1552                     lines,
1553                     multibyte_chars,
1554                     non_narrow_chars,
1555                     normalized_pos,
1556                     start_pos,
1557                     source_file_index,
1558                 );
1559                 debug!(
1560                     "CrateMetaData::imported_source_files alloc \
1561                          source_file {:?} original (start_pos {:?} end_pos {:?}) \
1562                          translated (start_pos {:?} end_pos {:?})",
1563                     local_version.name,
1564                     start_pos,
1565                     end_pos,
1566                     local_version.start_pos,
1567                     local_version.end_pos
1568                 );
1569
1570                 ImportedSourceFile {
1571                     original_start_pos: start_pos,
1572                     original_end_pos: end_pos,
1573                     translated_source_file: local_version,
1574                 }
1575             })
1576             .clone()
1577     }
1578
1579     fn get_generator_diagnostic_data(
1580         self,
1581         tcx: TyCtxt<'tcx>,
1582         id: DefIndex,
1583     ) -> Option<GeneratorDiagnosticData<'tcx>> {
1584         self.root
1585             .tables
1586             .generator_diagnostic_data
1587             .get(self, id)
1588             .map(|param| param.decode((self, tcx)))
1589             .map(|generator_data| GeneratorDiagnosticData {
1590                 generator_interior_types: generator_data.generator_interior_types,
1591                 hir_owner: generator_data.hir_owner,
1592                 nodes_types: generator_data.nodes_types,
1593                 adjustments: generator_data.adjustments,
1594             })
1595     }
1596
1597     fn get_attr_flags(self, index: DefIndex) -> AttrFlags {
1598         self.root.tables.attr_flags.get(self, index)
1599     }
1600
1601     fn get_is_intrinsic(self, index: DefIndex) -> bool {
1602         self.root.tables.is_intrinsic.get(self, index)
1603     }
1604 }
1605
1606 impl CrateMetadata {
1607     pub(crate) fn new(
1608         sess: &Session,
1609         cstore: &CStore,
1610         blob: MetadataBlob,
1611         root: CrateRoot,
1612         raw_proc_macros: Option<&'static [ProcMacro]>,
1613         cnum: CrateNum,
1614         cnum_map: CrateNumMap,
1615         dep_kind: CrateDepKind,
1616         source: CrateSource,
1617         private_dep: bool,
1618         host_hash: Option<Svh>,
1619     ) -> CrateMetadata {
1620         let trait_impls = root
1621             .impls
1622             .decode((&blob, sess))
1623             .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1624             .collect();
1625         let alloc_decoding_state =
1626             AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
1627         let dependencies = Lock::new(cnum_map.iter().cloned().collect());
1628
1629         // Pre-decode the DefPathHash->DefIndex table. This is a cheap operation
1630         // that does not copy any data. It just does some data verification.
1631         let def_path_hash_map = root.def_path_hash_map.decode(&blob);
1632
1633         let mut cdata = CrateMetadata {
1634             blob,
1635             root,
1636             trait_impls,
1637             incoherent_impls: Default::default(),
1638             raw_proc_macros,
1639             source_map_import_info: Lock::new(Vec::new()),
1640             def_path_hash_map,
1641             expn_hash_map: Default::default(),
1642             alloc_decoding_state,
1643             cnum,
1644             cnum_map,
1645             dependencies,
1646             dep_kind: Lock::new(dep_kind),
1647             source: Lrc::new(source),
1648             private_dep,
1649             host_hash,
1650             extern_crate: Lock::new(None),
1651             hygiene_context: Default::default(),
1652             def_key_cache: Default::default(),
1653             def_path_hash_cache: Default::default(),
1654         };
1655
1656         // Need `CrateMetadataRef` to decode `DefId`s in simplified types.
1657         cdata.incoherent_impls = cdata
1658             .root
1659             .incoherent_impls
1660             .decode(CrateMetadataRef { cdata: &cdata, cstore })
1661             .map(|incoherent_impls| (incoherent_impls.self_ty, incoherent_impls.impls))
1662             .collect();
1663
1664         cdata
1665     }
1666
1667     pub(crate) fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
1668         self.dependencies.borrow()
1669     }
1670
1671     pub(crate) fn add_dependency(&self, cnum: CrateNum) {
1672         self.dependencies.borrow_mut().push(cnum);
1673     }
1674
1675     pub(crate) fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool {
1676         let mut extern_crate = self.extern_crate.borrow_mut();
1677         let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank);
1678         if update {
1679             *extern_crate = Some(new_extern_crate);
1680         }
1681         update
1682     }
1683
1684     pub(crate) fn source(&self) -> &CrateSource {
1685         &*self.source
1686     }
1687
1688     pub(crate) fn dep_kind(&self) -> CrateDepKind {
1689         *self.dep_kind.lock()
1690     }
1691
1692     pub(crate) fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) {
1693         self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
1694     }
1695
1696     pub(crate) fn required_panic_strategy(&self) -> Option<PanicStrategy> {
1697         self.root.required_panic_strategy
1698     }
1699
1700     pub(crate) fn needs_panic_runtime(&self) -> bool {
1701         self.root.needs_panic_runtime
1702     }
1703
1704     pub(crate) fn is_panic_runtime(&self) -> bool {
1705         self.root.panic_runtime
1706     }
1707
1708     pub(crate) fn is_profiler_runtime(&self) -> bool {
1709         self.root.profiler_runtime
1710     }
1711
1712     pub(crate) fn needs_allocator(&self) -> bool {
1713         self.root.needs_allocator
1714     }
1715
1716     pub(crate) fn has_global_allocator(&self) -> bool {
1717         self.root.has_global_allocator
1718     }
1719
1720     pub(crate) fn has_alloc_error_handler(&self) -> bool {
1721         self.root.has_alloc_error_handler
1722     }
1723
1724     pub(crate) fn has_default_lib_allocator(&self) -> bool {
1725         self.root.has_default_lib_allocator
1726     }
1727
1728     pub(crate) fn is_proc_macro_crate(&self) -> bool {
1729         self.root.is_proc_macro_crate()
1730     }
1731
1732     pub(crate) fn name(&self) -> Symbol {
1733         self.root.name
1734     }
1735
1736     pub(crate) fn stable_crate_id(&self) -> StableCrateId {
1737         self.root.stable_crate_id
1738     }
1739
1740     pub(crate) fn hash(&self) -> Svh {
1741         self.root.hash
1742     }
1743
1744     fn num_def_ids(&self) -> usize {
1745         self.root.tables.def_keys.size()
1746     }
1747
1748     fn local_def_id(&self, index: DefIndex) -> DefId {
1749         DefId { krate: self.cnum, index }
1750     }
1751
1752     // Translate a DefId from the current compilation environment to a DefId
1753     // for an external crate.
1754     fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1755         for (local, &global) in self.cnum_map.iter_enumerated() {
1756             if global == did.krate {
1757                 return Some(DefId { krate: local, index: did.index });
1758             }
1759         }
1760
1761         None
1762     }
1763 }