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