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