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