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