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