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