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