1 // Decoding metadata from a single crate's metadata
3 use crate::creader::CrateMetadataRef;
4 use crate::rmeta::table::{FixedSizeEncoding, Table};
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};
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::source_map::{respan, Spanned};
34 use rustc_span::symbol::{sym, Ident, Symbol};
35 use rustc_span::{self, hygiene::MacroKind, BytePos, ExpnId, Pos, Span, SyntaxContext, DUMMY_SP};
37 use proc_macro::bridge::client::ProcMacro;
40 use std::num::NonZeroUsize;
44 pub use cstore_impl::{provide, provide_extern};
45 use rustc_span::hygiene::HygieneDecodeContext;
49 crate struct MetadataBlob(MetadataRef);
51 // A map from external crate numbers (as decoded from some crate file) to
52 // local crate numbers (as generated during this session). Each external
53 // crate may refer to types in other external crates, and each has their
55 crate type CrateNumMap = IndexVec<CrateNum, CrateNum>;
57 crate struct CrateMetadata {
58 /// The primary crate data - binary metadata blob.
61 // --- Some data pre-decoded from the metadata blob, usually for performance ---
62 /// Properties of the whole crate.
63 /// NOTE(eddyb) we pass `'static` to a `'tcx` parameter because this
64 /// lifetime is only used behind `Lazy`, and therefore acts like an
65 /// universal (`for<'tcx>`), that is paired up with whichever `TyCtxt`
66 /// is being used to decode those values.
67 root: CrateRoot<'static>,
69 /// FIXME: Used only from queries and can use query cache,
70 /// so pre-decoding can probably be avoided.
72 FxHashMap<(u32, DefIndex), Lazy<[(DefIndex, Option<ty::fast_reject::SimplifiedType>)]>>,
73 /// Proc macro descriptions for this crate, if it's a proc macro crate.
74 raw_proc_macros: Option<&'static [ProcMacro]>,
75 /// Source maps for code from the crate.
76 source_map_import_info: OnceCell<Vec<ImportedSourceFile>>,
77 /// For every definition in this crate, maps its `DefPathHash` to its
78 /// `DefIndex`. See `raw_def_id_to_def_id` for more details about how
80 def_path_hash_map: OnceCell<UnhashMap<DefPathHash, DefIndex>>,
81 /// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
82 alloc_decoding_state: AllocDecodingState,
83 /// Caches decoded `DefKey`s.
84 def_key_cache: Lock<FxHashMap<DefIndex, DefKey>>,
85 /// Caches decoded `DefPathHash`es.
86 def_path_hash_cache: Lock<FxHashMap<DefIndex, DefPathHash>>,
88 // --- Other significant crate properties ---
89 /// ID of this crate, from the current compilation session's point of view.
91 /// Maps crate IDs as they are were seen from this crate's compilation sessions into
92 /// IDs as they are seen from the current compilation session.
93 cnum_map: CrateNumMap,
94 /// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
95 dependencies: Lock<Vec<CrateNum>>,
96 /// How to link (or not link) this crate to the currently compiled crate.
97 dep_kind: Lock<CrateDepKind>,
98 /// Filesystem location of this crate.
100 /// Whether or not this crate should be consider a private dependency
101 /// for purposes of the 'exported_private_dependencies' lint
103 /// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
104 host_hash: Option<Svh>,
106 /// Additional data used for decoding `HygieneData` (e.g. `SyntaxContext`
108 /// Note that we store a `HygieneDecodeContext` for each `CrateMetadat`. This is
109 /// because `SyntaxContext` ids are not globally unique, so we need
110 /// to track which ids we've decoded on a per-crate basis.
111 hygiene_context: HygieneDecodeContext,
113 // --- Data used only for improving diagnostics ---
114 /// Information about the `extern crate` item or path that caused this crate to be loaded.
115 /// If this is `None`, then the crate was injected (e.g., by the allocator).
116 extern_crate: Lock<Option<ExternCrate>>,
119 /// Holds information about a rustc_span::SourceFile imported from another crate.
120 /// See `imported_source_files()` for more information.
121 struct ImportedSourceFile {
122 /// This SourceFile's byte-offset within the source_map of its original crate
123 original_start_pos: rustc_span::BytePos,
124 /// The end of this SourceFile within the source_map of its original crate
125 original_end_pos: rustc_span::BytePos,
126 /// The imported SourceFile's representation within the local source_map
127 translated_source_file: Lrc<rustc_span::SourceFile>,
130 pub(super) struct DecodeContext<'a, 'tcx> {
131 opaque: opaque::Decoder<'a>,
132 cdata: Option<CrateMetadataRef<'a>>,
133 sess: Option<&'tcx Session>,
134 tcx: Option<TyCtxt<'tcx>>,
136 // Cache the last used source_file for translating spans as an optimization.
137 last_source_file_index: usize,
139 lazy_state: LazyState,
141 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
142 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
145 /// Abstract over the various ways one can create metadata decoders.
146 pub(super) trait Metadata<'a, 'tcx>: Copy {
147 fn raw_bytes(self) -> &'a [u8];
148 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
151 fn sess(self) -> Option<&'tcx Session> {
154 fn tcx(self) -> Option<TyCtxt<'tcx>> {
158 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
159 let tcx = self.tcx();
161 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
163 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
165 last_source_file_index: 0,
166 lazy_state: LazyState::NoNode,
167 alloc_decoding_session: self
169 .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()),
174 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
175 fn raw_bytes(self) -> &'a [u8] {
180 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
181 fn raw_bytes(self) -> &'a [u8] {
182 let (blob, _) = self;
186 fn sess(self) -> Option<&'tcx Session> {
187 let (_, sess) = self;
192 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadataRef<'a> {
193 fn raw_bytes(self) -> &'a [u8] {
194 self.blob.raw_bytes()
196 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
201 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, &'tcx Session) {
202 fn raw_bytes(self) -> &'a [u8] {
205 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
208 fn sess(self) -> Option<&'tcx Session> {
213 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, TyCtxt<'tcx>) {
214 fn raw_bytes(self) -> &'a [u8] {
217 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
220 fn tcx(self) -> Option<TyCtxt<'tcx>> {
225 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Lazy<T> {
226 fn decode<M: Metadata<'a, 'tcx>>(self, metadata: M) -> T {
227 let mut dcx = metadata.decoder(self.position.get());
228 dcx.lazy_state = LazyState::NodeStart(self.position);
229 T::decode(&mut dcx).unwrap()
233 impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable<DecodeContext<'a, 'tcx>>> Lazy<[T]> {
234 fn decode<M: Metadata<'a, 'tcx>>(
237 ) -> impl ExactSizeIterator<Item = T> + Captures<'a> + Captures<'tcx> + 'x {
238 let mut dcx = metadata.decoder(self.position.get());
239 dcx.lazy_state = LazyState::NodeStart(self.position);
240 (0..self.meta).map(move |_| T::decode(&mut dcx).unwrap())
244 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
245 fn tcx(&self) -> TyCtxt<'tcx> {
246 self.tcx.expect("missing TyCtxt in DecodeContext")
249 fn cdata(&self) -> CrateMetadataRef<'a> {
250 self.cdata.expect("missing CrateMetadata in DecodeContext")
253 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
254 if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] }
257 fn read_lazy_with_meta<T: ?Sized + LazyMeta>(
260 ) -> Result<Lazy<T>, <Self as Decoder>::Error> {
261 let min_size = T::min_size(meta);
262 let distance = self.read_usize()?;
263 let position = match self.lazy_state {
264 LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
265 LazyState::NodeStart(start) => {
266 let start = start.get();
267 assert!(distance + min_size <= start);
268 start - distance - min_size
270 LazyState::Previous(last_min_end) => last_min_end.get() + distance,
272 self.lazy_state = LazyState::Previous(NonZeroUsize::new(position + min_size).unwrap());
273 Ok(Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta))
277 impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> {
278 const CLEAR_CROSS_CRATE: bool = true;
281 fn tcx(&self) -> TyCtxt<'tcx> {
282 self.tcx.expect("missing TyCtxt in DecodeContext")
286 fn peek_byte(&self) -> u8 {
287 self.opaque.data[self.opaque.position()]
291 fn position(&self) -> usize {
292 self.opaque.position()
295 fn cached_ty_for_shorthand<F>(
299 ) -> Result<Ty<'tcx>, Self::Error>
301 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
303 let tcx = self.tcx();
305 let key = ty::CReaderCacheKey { cnum: Some(self.cdata().cnum), pos: shorthand };
307 if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) {
311 let ty = or_insert_with(self)?;
312 tcx.ty_rcache.borrow_mut().insert(key, ty);
316 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
318 F: FnOnce(&mut Self) -> R,
320 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
321 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
322 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
324 self.opaque = old_opaque;
325 self.lazy_state = old_state;
329 fn decode_alloc_id(&mut self) -> Result<rustc_middle::mir::interpret::AllocId, Self::Error> {
330 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
331 alloc_decoding_session.decode_alloc_id(self)
333 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
338 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for CrateNum {
339 fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<CrateNum, String> {
340 let cnum = CrateNum::from_u32(d.read_u32()?);
341 Ok(d.map_encoded_cnum_to_current(cnum))
345 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefIndex {
346 fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<DefIndex, String> {
347 Ok(DefIndex::from_u32(d.read_u32()?))
351 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for SyntaxContext {
352 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<SyntaxContext, String> {
353 let cdata = decoder.cdata();
354 let sess = decoder.sess.unwrap();
355 let cname = cdata.root.name;
356 rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| {
357 debug!("SpecializedDecoder<SyntaxContext>: decoding {}", id);
362 .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname))
363 .decode((&cdata, sess)))
368 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for ExpnId {
369 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<ExpnId, String> {
370 let local_cdata = decoder.cdata();
371 let sess = decoder.sess.unwrap();
373 rustc_span::hygiene::decode_expn_id(decoder, |cnum, index| {
374 // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s
375 // are stored in the owning crate, to avoid duplication.
376 debug_assert_ne!(cnum, LOCAL_CRATE);
377 let crate_data = if cnum == local_cdata.cnum {
380 local_cdata.cstore.get_crate_data(cnum)
382 let expn_data = crate_data
385 .get(&crate_data, index)
387 .decode((&crate_data, sess));
388 let expn_hash = crate_data
391 .get(&crate_data, index)
393 .decode((&crate_data, sess));
394 (expn_data, expn_hash)
399 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for Span {
400 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Span, String> {
401 let ctxt = SyntaxContext::decode(decoder)?;
402 let tag = u8::decode(decoder)?;
404 if tag == TAG_PARTIAL_SPAN {
405 return Ok(DUMMY_SP.with_ctxt(ctxt));
408 debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN);
410 let lo = BytePos::decode(decoder)?;
411 let len = BytePos::decode(decoder)?;
414 let sess = if let Some(sess) = decoder.sess {
417 bug!("Cannot decode Span without Session.")
420 // There are two possibilities here:
421 // 1. This is a 'local span', which is located inside a `SourceFile`
422 // that came from this crate. In this case, we use the source map data
423 // encoded in this crate. This branch should be taken nearly all of the time.
424 // 2. This is a 'foreign span', which is located inside a `SourceFile`
425 // that came from a *different* crate (some crate upstream of the one
426 // whose metadata we're looking at). For example, consider this dependency graph:
430 // Suppose that we're currently compiling crate A, and start deserializing
431 // metadata from crate B. When we deserialize a Span from crate B's metadata,
432 // there are two posibilites:
434 // 1. The span references a file from crate B. This makes it a 'local' span,
435 // which means that we can use crate B's serialized source map information.
436 // 2. The span references a file from crate C. This makes it a 'foreign' span,
437 // which means we need to use Crate *C* (not crate B) to determine the source
438 // map information. We only record source map information for a file in the
439 // crate that 'owns' it, so deserializing a Span may require us to look at
440 // a transitive dependency.
442 // When we encode a foreign span, we adjust its 'lo' and 'high' values
443 // to be based on the *foreign* crate (e.g. crate C), not the crate
444 // we are writing metadata for (e.g. crate B). This allows us to
445 // treat the 'local' and 'foreign' cases almost identically during deserialization:
446 // we can call `imported_source_files` for the proper crate, and binary search
447 // through the returned slice using our span.
448 let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL {
449 decoder.cdata().imported_source_files(sess)
451 // When we encode a proc-macro crate, all `Span`s should be encoded
452 // with `TAG_VALID_SPAN_LOCAL`
453 if decoder.cdata().root.is_proc_macro_crate() {
454 // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE
455 // since we don't have `cnum_map` populated.
456 let cnum = u32::decode(decoder)?;
458 "Decoding of crate {:?} tried to access proc-macro dep {:?}",
459 decoder.cdata().root.name,
463 // tag is TAG_VALID_SPAN_FOREIGN, checked by `debug_assert` above
464 let cnum = CrateNum::decode(decoder)?;
466 "SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {:?}",
470 // Decoding 'foreign' spans should be rare enough that it's
471 // not worth it to maintain a per-CrateNum cache for `last_source_file_index`.
472 // We just set it to 0, to ensure that we don't try to access something out
473 // of bounds for our initial 'guess'
474 decoder.last_source_file_index = 0;
476 let foreign_data = decoder.cdata().cstore.get_crate_data(cnum);
477 foreign_data.imported_source_files(sess)
481 // Optimize for the case that most spans within a translated item
482 // originate from the same source_file.
483 let last_source_file = &imported_source_files[decoder.last_source_file_index];
485 if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos
489 let index = imported_source_files
490 .binary_search_by_key(&lo, |source_file| source_file.original_start_pos)
491 .unwrap_or_else(|index| index - 1);
493 // Don't try to cache the index for foreign spans,
494 // as this would require a map from CrateNums to indices
495 if tag == TAG_VALID_SPAN_LOCAL {
496 decoder.last_source_file_index = index;
498 &imported_source_files[index]
502 // Make sure our binary search above is correct.
504 lo >= source_file.original_start_pos && lo <= source_file.original_end_pos,
505 "Bad binary search: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
507 source_file.original_start_pos,
508 source_file.original_end_pos
511 // Make sure we correctly filtered out invalid spans during encoding
513 hi >= source_file.original_start_pos && hi <= source_file.original_end_pos,
514 "Bad binary search: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
516 source_file.original_start_pos,
517 source_file.original_end_pos
521 (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
523 (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
525 Ok(Span::new(lo, hi, ctxt))
529 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for &'tcx [mir::abstract_const::Node<'tcx>] {
530 fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
531 ty::codec::RefDecodable::decode(d)
535 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
536 fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
537 ty::codec::RefDecodable::decode(d)
541 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
544 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
545 decoder.read_lazy_with_meta(())
549 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
552 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
553 let len = decoder.read_usize()?;
554 if len == 0 { Ok(Lazy::empty()) } else { decoder.read_lazy_with_meta(len) }
558 impl<'a, 'tcx, I: Idx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
559 for Lazy<Table<I, T>>
561 Option<T>: FixedSizeEncoding,
563 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
564 let len = decoder.read_usize()?;
565 decoder.read_lazy_with_meta(len)
569 implement_ty_decoder!(DecodeContext<'a, 'tcx>);
572 crate fn new(metadata_ref: MetadataRef) -> MetadataBlob {
573 MetadataBlob(metadata_ref)
576 crate fn is_compatible(&self) -> bool {
577 self.raw_bytes().starts_with(METADATA_HEADER)
580 crate fn get_rustc_version(&self) -> String {
581 Lazy::<String>::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap())
585 crate fn get_root(&self) -> CrateRoot<'tcx> {
586 let slice = self.raw_bytes();
587 let offset = METADATA_HEADER.len();
588 let pos = (((slice[offset + 0] as u32) << 24)
589 | ((slice[offset + 1] as u32) << 16)
590 | ((slice[offset + 2] as u32) << 8)
591 | ((slice[offset + 3] as u32) << 0)) as usize;
592 Lazy::<CrateRoot<'tcx>>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self)
595 crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> {
596 let root = self.get_root();
597 writeln!(out, "Crate info:")?;
598 writeln!(out, "name {}{}", root.name, root.extra_filename)?;
599 writeln!(out, "hash {} stable_crate_id {:?}", root.hash, root.stable_crate_id)?;
600 writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?;
601 writeln!(out, "=External Dependencies=")?;
602 for (i, dep) in root.crate_deps.decode(self).enumerate() {
605 "{} {}{} hash {} host_hash {:?} kind {:?}",
620 crate fn is_proc_macro_crate(&self) -> bool {
621 self.proc_macro_data.is_some()
624 crate fn name(&self) -> Symbol {
628 crate fn hash(&self) -> Svh {
632 crate fn stable_crate_id(&self) -> StableCrateId {
636 crate fn triple(&self) -> &TargetTriple {
640 crate fn decode_crate_deps(
642 metadata: &'a MetadataBlob,
643 ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
644 self.crate_deps.decode(metadata)
648 impl<'a, 'tcx> CrateMetadataRef<'a> {
649 fn raw_proc_macro(&self, id: DefIndex) -> &ProcMacro {
650 // DefIndex's in root.proc_macro_data have a one-to-one correspondence
651 // with items in 'raw_proc_macros'.
659 .position(|i| i == id)
661 &self.raw_proc_macros.unwrap()[pos]
664 fn try_item_ident(&self, item_index: DefIndex, sess: &Session) -> Result<Ident, String> {
670 .ok_or_else(|| format!("Missing opt name for {:?}", item_index))?;
675 .get(self, item_index)
676 .ok_or_else(|| format!("Missing ident span for {:?} ({:?})", name, item_index))?
677 .decode((self, sess));
678 Ok(Ident::new(name, span))
681 fn item_ident(&self, item_index: DefIndex, sess: &Session) -> Ident {
682 self.try_item_ident(item_index, sess).unwrap()
685 fn maybe_kind(&self, item_id: DefIndex) -> Option<EntryKind> {
686 self.root.tables.kind.get(self, item_id).map(|k| k.decode(self))
689 fn kind(&self, item_id: DefIndex) -> EntryKind {
690 self.maybe_kind(item_id).unwrap_or_else(|| {
692 "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}",
700 fn def_kind(&self, item_id: DefIndex) -> DefKind {
701 self.root.tables.def_kind.get(self, item_id).map(|k| k.decode(self)).unwrap_or_else(|| {
703 "CrateMetadata::def_kind({:?}): id not found, in crate {:?} with number {}",
711 fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
716 .unwrap_or_else(|| panic!("Missing span for {:?}", index))
717 .decode((self, sess))
720 fn load_proc_macro(&self, id: DefIndex, sess: &Session) -> SyntaxExtension {
721 let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
722 ProcMacro::CustomDerive { trait_name, attributes, client } => {
724 attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
727 SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
731 ProcMacro::Attr { name, client } => {
732 (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new())
734 ProcMacro::Bang { name, client } => {
735 (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new())
739 let attrs: Vec<_> = self.get_item_attrs(id, sess).collect();
740 SyntaxExtension::new(
743 self.get_span(id, sess),
746 Symbol::intern(name),
751 fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
752 match self.kind(item_id) {
753 EntryKind::Trait(data) => {
754 let data = data.decode((self, sess));
756 self.local_def_id(item_id),
761 data.skip_array_during_method_dispatch,
762 data.specialization_kind,
763 self.def_path_hash(item_id),
766 EntryKind::TraitAlias => ty::TraitDef::new(
767 self.local_def_id(item_id),
768 hir::Unsafety::Normal,
773 ty::trait_def::TraitSpecializationKind::None,
774 self.def_path_hash(item_id),
776 _ => bug!("def-index does not refer to trait or trait alias"),
786 ) -> ty::VariantDef {
787 let data = match kind {
788 EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => {
794 let adt_kind = match kind {
795 EntryKind::Variant(_) => ty::AdtKind::Enum,
796 EntryKind::Struct(..) => ty::AdtKind::Struct,
797 EntryKind::Union(..) => ty::AdtKind::Union,
802 if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
803 let ctor_did = data.ctor.map(|index| self.local_def_id(index));
806 self.item_ident(index, sess),
814 .unwrap_or_else(Lazy::empty)
816 .map(|index| ty::FieldDef {
817 did: self.local_def_id(index),
818 ident: self.item_ident(index, sess),
819 vis: self.get_visibility(index),
826 data.is_non_exhaustive,
830 fn get_adt_def(&self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef {
831 let kind = self.kind(item_id);
832 let did = self.local_def_id(item_id);
834 let (adt_kind, repr) = match kind {
835 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
836 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
837 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
838 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
841 let variants = if let ty::AdtKind::Enum = adt_kind {
846 .unwrap_or_else(Lazy::empty)
848 .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess))
851 std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect()
854 tcx.alloc_adt_def(did, adt_kind, variants, repr)
857 fn get_explicit_predicates(
861 ) -> ty::GenericPredicates<'tcx> {
862 self.root.tables.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx))
865 fn get_inferred_outlives(
869 ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
874 .map(|predicates| tcx.arena.alloc_from_iter(predicates.decode((self, tcx))))
878 fn get_super_predicates(
882 ) -> ty::GenericPredicates<'tcx> {
883 self.root.tables.super_predicates.get(self, item_id).unwrap().decode((self, tcx))
886 fn get_explicit_item_bounds(
890 ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
893 .explicit_item_bounds
895 .map(|bounds| tcx.arena.alloc_from_iter(bounds.decode((self, tcx))))
899 fn get_generics(&self, item_id: DefIndex, sess: &Session) -> ty::Generics {
900 self.root.tables.generics.get(self, item_id).unwrap().decode((self, sess))
903 fn get_type(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
908 .unwrap_or_else(|| panic!("Not a type: {:?}", id))
912 fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
913 self.root.tables.stability.get(self, id).map(|stab| stab.decode(self))
916 fn get_const_stability(&self, id: DefIndex) -> Option<attr::ConstStability> {
917 self.root.tables.const_stability.get(self, id).map(|stab| stab.decode(self))
920 fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
921 self.root.tables.deprecation.get(self, id).map(|depr| depr.decode(self))
924 fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
925 self.root.tables.visibility.get(self, id).unwrap().decode(self)
928 fn get_impl_data(&self, id: DefIndex) -> ImplData {
929 match self.kind(id) {
930 EntryKind::Impl(data) => data.decode(self),
935 fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
936 self.get_impl_data(id).parent_impl
939 fn get_impl_polarity(&self, id: DefIndex) -> ty::ImplPolarity {
940 self.get_impl_data(id).polarity
943 fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
944 self.get_impl_data(id).defaultness
947 fn get_impl_constness(&self, id: DefIndex) -> hir::Constness {
948 self.get_impl_data(id).constness
951 fn get_coerce_unsized_info(&self, id: DefIndex) -> Option<ty::adjustment::CoerceUnsizedInfo> {
952 self.get_impl_data(id).coerce_unsized_info
955 fn get_impl_trait(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option<ty::TraitRef<'tcx>> {
956 self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx)))
959 fn get_expn_that_defined(&self, id: DefIndex, sess: &Session) -> ExpnId {
960 self.root.tables.expn_that_defined.get(self, id).unwrap().decode((self, sess))
963 fn get_const_param_default(
967 ) -> rustc_middle::ty::Const<'tcx> {
968 self.root.tables.const_defaults.get(self, id).unwrap().decode((self, tcx))
971 /// Iterates over all the stability attributes in the given crate.
972 fn get_lib_features(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Option<Symbol>)] {
973 // FIXME: For a proc macro crate, not sure whether we should return the "host"
974 // features or an empty Vec. Both don't cause ICEs.
975 tcx.arena.alloc_from_iter(self.root.lib_features.decode(self))
978 /// Iterates over the language items in the given crate.
979 fn get_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] {
980 if self.root.is_proc_macro_crate() {
981 // Proc macro crates do not export any lang-items to the target.
984 tcx.arena.alloc_from_iter(
988 .map(|(def_index, index)| (self.local_def_id(def_index), index)),
993 /// Iterates over the diagnostic items in the given crate.
994 fn get_diagnostic_items(&self) -> FxHashMap<Symbol, DefId> {
995 if self.root.is_proc_macro_crate() {
996 // Proc macro crates do not export any diagnostic-items to the target.
1002 .map(|(name, def_index)| (name, self.local_def_id(def_index)))
1007 /// Iterates over each child of the given item.
1008 fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
1010 F: FnMut(Export<hir::HirId>),
1012 if let Some(data) = &self.root.proc_macro_data {
1013 /* If we are loading as a proc macro, we want to return the view of this crate
1014 * as a proc macro crate.
1016 if id == CRATE_DEF_INDEX {
1017 let macros = data.macros.decode(self);
1018 for def_index in macros {
1019 let raw_macro = self.raw_proc_macro(def_index);
1021 DefKind::Macro(macro_kind(raw_macro)),
1022 self.local_def_id(def_index),
1024 let ident = self.item_ident(def_index, sess);
1025 callback(Export { ident, res, vis: ty::Visibility::Public, span: ident.span });
1032 let kind = match self.maybe_kind(id) {
1037 // Iterate over all children.
1038 let macros_only = self.dep_kind.lock().macros_only();
1040 let children = self.root.tables.children.get(self, id).unwrap_or_else(Lazy::empty);
1042 for child_index in children.decode((self, sess)) {
1044 let child_kind = match self.maybe_kind(child_index) {
1045 Some(child_kind) => child_kind,
1049 // Hand off the item to the callback.
1051 // FIXME(eddyb) Don't encode these in children.
1052 EntryKind::ForeignMod => {
1053 let child_children = self
1057 .get(self, child_index)
1058 .unwrap_or_else(Lazy::empty);
1059 for child_index in child_children.decode((self, sess)) {
1060 let kind = self.def_kind(child_index);
1062 res: Res::Def(kind, self.local_def_id(child_index)),
1063 ident: self.item_ident(child_index, sess),
1064 vis: self.get_visibility(child_index),
1069 .get(self, child_index)
1071 .decode((self, sess)),
1076 EntryKind::Impl(_) => continue,
1081 let def_key = self.def_key(child_index);
1082 if def_key.disambiguated_data.data.get_opt_name().is_some() {
1083 let span = self.get_span(child_index, sess);
1084 let kind = self.def_kind(child_index);
1085 let ident = self.item_ident(child_index, sess);
1086 let vis = self.get_visibility(child_index);
1087 let def_id = self.local_def_id(child_index);
1088 let res = Res::Def(kind, def_id);
1089 callback(Export { res, ident, vis, span });
1090 // For non-re-export structs and variants add their constructors to children.
1091 // Re-export lists automatically contain constructors when necessary.
1093 DefKind::Struct => {
1094 if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
1095 let ctor_kind = self.get_ctor_kind(child_index);
1097 Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1098 let vis = self.get_visibility(ctor_def_id.index);
1099 callback(Export { res: ctor_res, vis, ident, span });
1102 DefKind::Variant => {
1103 // Braced variants, unlike structs, generate unusable names in
1104 // value namespace, they are reserved for possible future use.
1105 // It's ok to use the variant's id as a ctor id since an
1106 // error will be reported on any use of such resolution anyway.
1107 let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
1108 let ctor_kind = self.get_ctor_kind(child_index);
1110 Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
1111 let mut vis = self.get_visibility(ctor_def_id.index);
1112 if ctor_def_id == def_id && vis == ty::Visibility::Public {
1113 // For non-exhaustive variants lower the constructor visibility to
1114 // within the crate. We only need this for fictive constructors,
1115 // for other constructors correct visibilities
1116 // were already encoded in metadata.
1117 let mut attrs = self.get_item_attrs(def_id.index, sess);
1118 if attrs.any(|item| item.has_name(sym::non_exhaustive)) {
1119 let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
1120 vis = ty::Visibility::Restricted(crate_def_id);
1123 callback(Export { res: ctor_res, ident, vis, span });
1131 if let EntryKind::Mod(data) = kind {
1132 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
1134 Res::Def(DefKind::Macro(..), _) => {}
1135 _ if macros_only => continue,
1143 fn is_ctfe_mir_available(&self, id: DefIndex) -> bool {
1144 self.root.tables.mir_for_ctfe.get(self, id).is_some()
1147 fn is_item_mir_available(&self, id: DefIndex) -> bool {
1148 self.root.tables.mir.get(self, id).is_some()
1151 fn module_expansion(&self, id: DefIndex, sess: &Session) -> ExpnId {
1152 if let EntryKind::Mod(m) = self.kind(id) {
1153 m.decode((self, sess)).expansion
1155 panic!("Expected module, found {:?}", self.local_def_id(id))
1159 fn get_optimized_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> {
1164 .unwrap_or_else(|| {
1165 bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id))
1167 .decode((self, tcx))
1170 fn get_mir_for_ctfe(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> {
1175 .unwrap_or_else(|| {
1176 bug!("get_mir_for_ctfe: missing MIR for `{:?}`", self.local_def_id(id))
1178 .decode((self, tcx))
1181 fn get_mir_abstract_const(
1185 ) -> Result<Option<&'tcx [mir::abstract_const::Node<'tcx>]>, ErrorReported> {
1188 .mir_abstract_consts
1190 .map_or(Ok(None), |v| Ok(Some(v.decode((self, tcx)))))
1193 fn get_unused_generic_params(&self, id: DefIndex) -> FiniteBitSet<u32> {
1196 .unused_generic_params
1198 .map(|params| params.decode(self))
1199 .unwrap_or_default()
1202 fn get_promoted_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> IndexVec<Promoted, Body<'tcx>> {
1207 .unwrap_or_else(|| {
1208 bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id))
1210 .decode((self, tcx))
1213 fn mir_const_qualif(&self, id: DefIndex) -> mir::ConstQualifs {
1214 match self.kind(id) {
1215 EntryKind::AnonConst(qualif, _)
1216 | EntryKind::Const(qualif, _)
1217 | EntryKind::AssocConst(
1218 AssocContainer::ImplDefault
1219 | AssocContainer::ImplFinal
1220 | AssocContainer::TraitWithDefault,
1224 _ => bug!("mir_const_qualif: unexpected kind"),
1228 fn get_associated_item(&self, id: DefIndex, sess: &Session) -> ty::AssocItem {
1229 let def_key = self.def_key(id);
1230 let parent = self.local_def_id(def_key.parent.unwrap());
1231 let ident = self.item_ident(id, sess);
1233 let (kind, container, has_self) = match self.kind(id) {
1234 EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false),
1235 EntryKind::AssocFn(data) => {
1236 let data = data.decode(self);
1237 (ty::AssocKind::Fn, data.container, data.has_self)
1239 EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false),
1240 _ => bug!("cannot get associated-item of `{:?}`", def_key),
1246 vis: self.get_visibility(id),
1247 defaultness: container.defaultness(),
1248 def_id: self.local_def_id(id),
1249 container: container.with_def_id(parent),
1250 fn_has_self_parameter: has_self,
1254 fn get_item_variances(&'a self, id: DefIndex) -> impl Iterator<Item = ty::Variance> + 'a {
1255 self.root.tables.variances.get(self, id).unwrap_or_else(Lazy::empty).decode(self)
1258 fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
1259 match self.kind(node_id) {
1260 EntryKind::Struct(data, _) | EntryKind::Union(data, _) | EntryKind::Variant(data) => {
1261 data.decode(self).ctor_kind
1263 _ => CtorKind::Fictive,
1267 fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
1268 match self.kind(node_id) {
1269 EntryKind::Struct(data, _) => {
1270 data.decode(self).ctor.map(|index| self.local_def_id(index))
1272 EntryKind::Variant(data) => {
1273 data.decode(self).ctor.map(|index| self.local_def_id(index))
1283 ) -> impl Iterator<Item = ast::Attribute> + 'a {
1284 // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
1285 // we assume that someone passing in a tuple struct ctor is actually wanting to
1286 // look at the definition
1287 let def_key = self.def_key(node_id);
1288 let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
1289 def_key.parent.unwrap()
1298 .unwrap_or_else(Lazy::empty)
1299 .decode((self, sess))
1302 fn get_struct_field_names(&self, id: DefIndex, sess: &Session) -> Vec<Spanned<Symbol>> {
1307 .unwrap_or_else(Lazy::empty)
1309 .map(|index| respan(self.get_span(index, sess), self.item_ident(index, sess).name))
1313 fn get_struct_field_visibilities(&self, id: DefIndex) -> Vec<Visibility> {
1318 .unwrap_or_else(Lazy::empty)
1320 .map(|field_index| self.get_visibility(field_index))
1324 fn get_inherent_implementations_for_type(
1328 ) -> &'tcx [DefId] {
1329 tcx.arena.alloc_from_iter(
1334 .unwrap_or_else(Lazy::empty)
1336 .map(|index| self.local_def_id(index)),
1340 fn get_implementations_for_trait(
1343 filter: Option<DefId>,
1344 ) -> &'tcx [(DefId, Option<ty::fast_reject::SimplifiedType>)] {
1345 if self.root.is_proc_macro_crate() {
1346 // proc-macro crates export no trait impls.
1350 if let Some(def_id) = filter {
1351 // Do a reverse lookup beforehand to avoid touching the crate_num
1352 // hash map in the loop below.
1353 let filter = match self.reverse_translate_def_id(def_id) {
1354 Some(def_id) => (def_id.krate.as_u32(), def_id.index),
1358 if let Some(impls) = self.trait_impls.get(&filter) {
1359 tcx.arena.alloc_from_iter(
1360 impls.decode(self).map(|(idx, simplified_self_ty)| {
1361 (self.local_def_id(idx), simplified_self_ty)
1368 tcx.arena.alloc_from_iter(self.trait_impls.values().flat_map(|impls| {
1371 .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty))
1376 fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1377 let def_key = self.def_key(id);
1378 match def_key.disambiguated_data.data {
1379 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1380 // Not an associated item
1383 def_key.parent.and_then(|parent_index| match self.kind(parent_index) {
1384 EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)),
1389 fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLib> {
1390 if self.root.is_proc_macro_crate() {
1391 // Proc macro crates do not have any *target* native libraries.
1394 self.root.native_libraries.decode((self, sess)).collect()
1398 fn get_proc_macro_quoted_span(&self, index: usize, sess: &Session) -> Span {
1401 .proc_macro_quoted_spans
1403 .unwrap_or_else(|| panic!("Missing proc macro quoted span: {:?}", index))
1404 .decode((self, sess))
1407 fn get_foreign_modules(&self, tcx: TyCtxt<'tcx>) -> Lrc<FxHashMap<DefId, ForeignModule>> {
1408 if self.root.is_proc_macro_crate() {
1409 // Proc macro crates do not have any *target* foreign modules.
1410 Lrc::new(FxHashMap::default())
1412 let modules: FxHashMap<DefId, ForeignModule> =
1413 self.root.foreign_modules.decode((self, tcx.sess)).map(|m| (m.def_id, m)).collect();
1418 fn get_dylib_dependency_formats(
1421 ) -> &'tcx [(CrateNum, LinkagePreference)] {
1422 tcx.arena.alloc_from_iter(
1423 self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| {
1424 let cnum = CrateNum::new(i + 1);
1425 link.map(|link| (self.cnum_map[cnum], link))
1430 fn get_missing_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] {
1431 if self.root.is_proc_macro_crate() {
1432 // Proc macro crates do not depend on any target weak lang-items.
1435 tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self))
1439 fn get_fn_param_names(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [Ident] {
1440 let param_names = match self.kind(id) {
1441 EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names,
1442 EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names,
1445 tcx.arena.alloc_from_iter(param_names.decode((self, tcx)))
1448 fn exported_symbols(
1451 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] {
1452 if self.root.is_proc_macro_crate() {
1453 // If this crate is a custom derive crate, then we're not even going to
1454 // link those in so we skip those crates.
1457 tcx.arena.alloc_from_iter(self.root.exported_symbols.decode((self, tcx)))
1461 fn get_rendered_const(&self, id: DefIndex) -> String {
1462 match self.kind(id) {
1463 EntryKind::AnonConst(_, data)
1464 | EntryKind::Const(_, data)
1465 | EntryKind::AssocConst(_, _, data) => data.decode(self).0,
1470 fn get_macro(&self, id: DefIndex, sess: &Session) -> MacroDef {
1471 match self.kind(id) {
1472 EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)),
1477 // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we
1478 // don't serialize constness for tuple variant and tuple struct constructors.
1479 fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1480 let constness = match self.kind(id) {
1481 EntryKind::AssocFn(data) => data.decode(self).fn_data.constness,
1482 EntryKind::Fn(data) => data.decode(self).constness,
1483 EntryKind::ForeignFn(data) => data.decode(self).constness,
1484 EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const,
1485 _ => hir::Constness::NotConst,
1487 constness == hir::Constness::Const
1490 fn asyncness(&self, id: DefIndex) -> hir::IsAsync {
1491 match self.kind(id) {
1492 EntryKind::Fn(data) => data.decode(self).asyncness,
1493 EntryKind::AssocFn(data) => data.decode(self).fn_data.asyncness,
1494 EntryKind::ForeignFn(data) => data.decode(self).asyncness,
1495 _ => bug!("asyncness: expected function kind"),
1499 fn is_foreign_item(&self, id: DefIndex) -> bool {
1500 match self.kind(id) {
1501 EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => {
1508 fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1509 match self.kind(id) {
1510 EntryKind::ImmStatic | EntryKind::ForeignImmStatic => Some(hir::Mutability::Not),
1511 EntryKind::MutStatic | EntryKind::ForeignMutStatic => Some(hir::Mutability::Mut),
1516 fn generator_kind(&self, id: DefIndex) -> Option<hir::GeneratorKind> {
1517 match self.kind(id) {
1518 EntryKind::Generator(data) => Some(data),
1523 fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
1524 self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx))
1528 fn def_key(&self, index: DefIndex) -> DefKey {
1533 .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self))
1536 /// Finds the corresponding `DefId` for the provided `DefPathHash`, if it exists.
1537 /// This is used by incremental compilation to map a serialized `DefPathHash` to
1538 /// its `DefId` in the current session.
1539 /// Normally, only one 'main' crate will change between incremental compilation sessions:
1540 /// all dependencies will be completely unchanged. In this case, we can avoid
1541 /// decoding every `DefPathHash` in the crate, since the `DefIndex` from the previous
1542 /// session will still be valid. If our 'guess' is wrong (the `DefIndex` no longer exists,
1543 /// or has a different `DefPathHash`, then we need to decode all `DefPathHashes` to determine
1544 /// the correct mapping).
1545 fn def_path_hash_to_def_id(
1550 ) -> Option<DefId> {
1551 let def_index_guess = DefIndex::from_u32(index_guess);
1556 .get(self, def_index_guess)
1557 .map(|lazy| lazy.decode(self));
1559 // Fast path: the definition and its index is unchanged from the
1560 // previous compilation session. There is no need to decode anything
1562 if old_hash == Some(hash) {
1563 return Some(DefId { krate, index: def_index_guess });
1566 let is_proc_macro = self.is_proc_macro_crate();
1568 // Slow path: We need to find out the new `DefIndex` of the provided
1569 // `DefPathHash`, if its still exists. This requires decoding every `DefPathHash`
1570 // stored in this crate.
1571 let map = self.cdata.def_path_hash_map.get_or_init(|| {
1572 let end_id = self.root.tables.def_path_hashes.size() as u32;
1573 let mut map = UnhashMap::with_capacity_and_hasher(end_id as usize, Default::default());
1574 for i in 0..end_id {
1575 let def_index = DefIndex::from_u32(i);
1576 // There may be gaps in the encoded table if we're decoding a proc-macro crate
1577 if let Some(hash) = self.root.tables.def_path_hashes.get(self, def_index) {
1578 map.insert(hash.decode(self), def_index);
1579 } else if !is_proc_macro {
1580 panic!("Missing def_path_hashes entry for {:?}", def_index);
1585 map.get(&hash).map(|index| DefId { krate, index: *index })
1588 // Returns the path leading to the thing with this `id`.
1589 fn def_path(&self, id: DefIndex) -> DefPath {
1590 debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1591 DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1594 fn def_path_hash_unlocked(
1597 def_path_hashes: &mut FxHashMap<DefIndex, DefPathHash>,
1599 *def_path_hashes.entry(index).or_insert_with(|| {
1600 self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self)
1605 fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1606 let mut def_path_hashes = self.def_path_hash_cache.lock();
1607 self.def_path_hash_unlocked(index, &mut def_path_hashes)
1610 /// Imports the source_map from an external crate into the source_map of the crate
1611 /// currently being compiled (the "local crate").
1613 /// The import algorithm works analogous to how AST items are inlined from an
1614 /// external crate's metadata:
1615 /// For every SourceFile in the external source_map an 'inline' copy is created in the
1616 /// local source_map. The correspondence relation between external and local
1617 /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1618 /// function. When an item from an external crate is later inlined into this
1619 /// crate, this correspondence information is used to translate the span
1620 /// information of the inlined item so that it refers the correct positions in
1621 /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1623 /// The import algorithm in the function below will reuse SourceFiles already
1624 /// existing in the local source_map. For example, even if the SourceFile of some
1625 /// source file of libstd gets imported many times, there will only ever be
1626 /// one SourceFile object for the corresponding file in the local source_map.
1628 /// Note that imported SourceFiles do not actually contain the source code of the
1629 /// file they represent, just information about length, line breaks, and
1630 /// multibyte characters. This information is enough to generate valid debuginfo
1631 /// for items inlined from other crates.
1633 /// Proc macro crates don't currently export spans, so this function does not have
1634 /// to work for them.
1635 fn imported_source_files(&self, sess: &Session) -> &'a [ImportedSourceFile] {
1636 // Translate the virtual `/rustc/$hash` prefix back to a real directory
1637 // that should hold actual sources, where possible.
1639 // NOTE: if you update this, you might need to also update bootstrap's code for generating
1640 // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`.
1641 let virtual_rust_source_base_dir = option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR")
1644 // Only spend time on further checks if we have what to translate *to*.
1645 sess.opts.real_rust_source_base_dir.is_some()
1647 .filter(|virtual_dir| {
1648 // Don't translate away `/rustc/$hash` if we're still remapping to it,
1649 // since that means we're still building `std`/`rustc` that need it,
1650 // and we don't want the real path to leak into codegen/debuginfo.
1651 !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir)
1653 let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| {
1655 "try_to_translate_virtual_to_real(name={:?}): \
1656 virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}",
1657 name, virtual_rust_source_base_dir, sess.opts.real_rust_source_base_dir,
1660 if let Some(virtual_dir) = virtual_rust_source_base_dir {
1661 if let Some(real_dir) = &sess.opts.real_rust_source_base_dir {
1662 if let rustc_span::FileName::Real(old_name) = name {
1663 if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } =
1666 if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) {
1667 let virtual_name = virtual_name.clone();
1669 // The std library crates are in
1670 // `$sysroot/lib/rustlib/src/rust/library`, whereas other crates
1671 // may be in `$sysroot/lib/rustlib/src/rust/` directly. So we
1672 // detect crates from the std libs and handle them specially.
1673 const STD_LIBS: &[&str] = &[
1683 "profiler_builtins",
1685 "rustc-std-workspace-core",
1686 "rustc-std-workspace-alloc",
1687 "rustc-std-workspace-std",
1690 let is_std_lib = STD_LIBS.iter().any(|l| rest.starts_with(l));
1692 let new_path = if is_std_lib {
1693 real_dir.join("library").join(rest)
1699 "try_to_translate_virtual_to_real: `{}` -> `{}`",
1700 virtual_name.display(),
1703 let new_name = rustc_span::RealFileName::Remapped {
1704 local_path: Some(new_path),
1707 *old_name = new_name;
1715 self.cdata.source_map_import_info.get_or_init(|| {
1716 let external_source_map = self.root.source_map.decode(self);
1719 .map(|source_file_to_import| {
1720 // We can't reuse an existing SourceFile, so allocate a new one
1721 // containing the information we need.
1722 let rustc_span::SourceFile {
1728 mut multibyte_chars,
1729 mut non_narrow_chars,
1733 } = source_file_to_import;
1735 // If this file is under $sysroot/lib/rustlib/src/ but has not been remapped
1736 // during rust bootstrapping by `remap-debuginfo = true`, and the user
1737 // wish to simulate that behaviour by -Z simulate-remapped-rust-src-base,
1738 // then we change `name` to a similar state as if the rust was bootstrapped
1739 // with `remap-debuginfo = true`.
1740 // This is useful for testing so that tests about the effects of
1741 // `try_to_translate_virtual_to_real` don't have to worry about how the
1742 // compiler is bootstrapped.
1743 if let Some(virtual_dir) =
1744 &sess.opts.debugging_opts.simulate_remapped_rust_src_base
1746 if let Some(real_dir) = &sess.opts.real_rust_source_base_dir {
1747 if let rustc_span::FileName::Real(ref mut old_name) = name {
1748 if let rustc_span::RealFileName::LocalPath(local) = old_name {
1749 if let Ok(rest) = local.strip_prefix(real_dir) {
1750 *old_name = rustc_span::RealFileName::Remapped {
1752 virtual_name: virtual_dir.join(rest),
1760 // If this file's path has been remapped to `/rustc/$hash`,
1761 // we might be able to reverse that (also see comments above,
1762 // on `try_to_translate_virtual_to_real`).
1763 try_to_translate_virtual_to_real(&mut name);
1765 let source_length = (end_pos - start_pos).to_usize();
1767 // Translate line-start positions and multibyte character
1768 // position into frame of reference local to file.
1769 // `SourceMap::new_imported_source_file()` will then translate those
1770 // coordinates to their new global frame of reference when the
1771 // offset of the SourceFile is known.
1772 for pos in &mut lines {
1773 *pos = *pos - start_pos;
1775 for mbc in &mut multibyte_chars {
1776 mbc.pos = mbc.pos - start_pos;
1778 for swc in &mut non_narrow_chars {
1779 *swc = *swc - start_pos;
1781 for np in &mut normalized_pos {
1782 np.pos = np.pos - start_pos;
1785 let local_version = sess.source_map().new_imported_source_file(
1799 "CrateMetaData::imported_source_files alloc \
1800 source_file {:?} original (start_pos {:?} end_pos {:?}) \
1801 translated (start_pos {:?} end_pos {:?})",
1805 local_version.start_pos,
1806 local_version.end_pos
1809 ImportedSourceFile {
1810 original_start_pos: start_pos,
1811 original_end_pos: end_pos,
1812 translated_source_file: local_version,
1820 impl CrateMetadata {
1824 root: CrateRoot<'static>,
1825 raw_proc_macros: Option<&'static [ProcMacro]>,
1827 cnum_map: CrateNumMap,
1828 dep_kind: CrateDepKind,
1829 source: CrateSource,
1831 host_hash: Option<Svh>,
1832 ) -> CrateMetadata {
1833 let trait_impls = root
1835 .decode((&blob, sess))
1836 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
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());
1846 source_map_import_info: OnceCell::new(),
1847 def_path_hash_map: Default::default(),
1848 alloc_decoding_state,
1852 dep_kind: Lock::new(dep_kind),
1856 extern_crate: Lock::new(None),
1857 hygiene_context: Default::default(),
1858 def_key_cache: Default::default(),
1859 def_path_hash_cache: Default::default(),
1863 crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
1864 self.dependencies.borrow()
1867 crate fn add_dependency(&self, cnum: CrateNum) {
1868 self.dependencies.borrow_mut().push(cnum);
1871 crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool {
1872 let mut extern_crate = self.extern_crate.borrow_mut();
1873 let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank);
1875 *extern_crate = Some(new_extern_crate);
1880 crate fn source(&self) -> &CrateSource {
1884 crate fn dep_kind(&self) -> CrateDepKind {
1885 *self.dep_kind.lock()
1888 crate fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) {
1889 self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
1892 crate fn panic_strategy(&self) -> PanicStrategy {
1893 self.root.panic_strategy
1896 crate fn needs_panic_runtime(&self) -> bool {
1897 self.root.needs_panic_runtime
1900 crate fn is_panic_runtime(&self) -> bool {
1901 self.root.panic_runtime
1904 crate fn is_profiler_runtime(&self) -> bool {
1905 self.root.profiler_runtime
1908 crate fn needs_allocator(&self) -> bool {
1909 self.root.needs_allocator
1912 crate fn has_global_allocator(&self) -> bool {
1913 self.root.has_global_allocator
1916 crate fn has_default_lib_allocator(&self) -> bool {
1917 self.root.has_default_lib_allocator
1920 crate fn is_proc_macro_crate(&self) -> bool {
1921 self.root.is_proc_macro_crate()
1924 crate fn name(&self) -> Symbol {
1928 crate fn stable_crate_id(&self) -> StableCrateId {
1929 self.root.stable_crate_id
1932 crate fn hash(&self) -> Svh {
1936 fn num_def_ids(&self) -> usize {
1937 self.root.tables.def_keys.size()
1940 fn local_def_id(&self, index: DefIndex) -> DefId {
1941 DefId { krate: self.cnum, index }
1944 // Translate a DefId from the current compilation environment to a DefId
1945 // for an external crate.
1946 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1947 for (local, &global) in self.cnum_map.iter_enumerated() {
1948 if global == did.krate {
1949 return Some(DefId { krate: local, index: did.index });
1957 // Cannot be implemented on 'ProcMacro', as libproc_macro
1958 // does not depend on librustc_ast
1959 fn macro_kind(raw: &ProcMacro) -> MacroKind {
1961 ProcMacro::CustomDerive { .. } => MacroKind::Derive,
1962 ProcMacro::Attr { .. } => MacroKind::Attr,
1963 ProcMacro::Bang { .. } => MacroKind::Bang,