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