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