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