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