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::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};
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};
40 use proc_macro::bridge::client::ProcMacro;
44 use std::num::NonZeroUsize;
48 pub use cstore_impl::{provide, provide_extern};
49 use rustc_span::hygiene::HygieneDecodeContext;
53 crate struct MetadataBlob(MetadataRef);
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
59 crate type CrateNumMap = IndexVec<CrateNum, CrateNum>;
61 crate struct CrateMetadata {
62 /// The primary crate data - binary metadata blob.
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>,
73 /// FIXME: Used only from queries and can use query cache,
74 /// so pre-decoding can probably be avoided.
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
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>>,
97 // --- Other significant crate properties ---
98 /// ID of this crate, from the current compilation session's point of view.
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.
109 /// Whether or not this crate should be consider a private dependency
110 /// for purposes of the 'exported_private_dependencies' lint
112 /// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
113 host_hash: Option<Svh>,
115 /// Additional data used for decoding `HygieneData` (e.g. `SyntaxContext`
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,
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>>,
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>,
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>>,
145 // Cache the last used source_file for translating spans as an optimization.
146 last_source_file_index: usize,
148 lazy_state: LazyState,
150 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
151 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
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>> {
160 fn sess(self) -> Option<&'tcx Session> {
163 fn tcx(self) -> Option<TyCtxt<'tcx>> {
167 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
168 let tcx = self.tcx();
170 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
172 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
174 last_source_file_index: 0,
175 lazy_state: LazyState::NoNode,
176 alloc_decoding_session: self
178 .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()),
183 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
184 fn raw_bytes(self) -> &'a [u8] {
189 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
190 fn raw_bytes(self) -> &'a [u8] {
191 let (blob, _) = self;
195 fn sess(self) -> Option<&'tcx Session> {
196 let (_, sess) = self;
201 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadataRef<'a> {
202 fn raw_bytes(self) -> &'a [u8] {
203 self.blob.raw_bytes()
205 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
210 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, &'tcx Session) {
211 fn raw_bytes(self) -> &'a [u8] {
214 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
217 fn sess(self) -> Option<&'tcx Session> {
222 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, TyCtxt<'tcx>) {
223 fn raw_bytes(self) -> &'a [u8] {
226 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
229 fn tcx(self) -> Option<TyCtxt<'tcx>> {
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()
242 impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable<DecodeContext<'a, 'tcx>>> Lazy<[T]> {
243 fn decode<M: Metadata<'a, 'tcx>>(
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())
253 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
254 fn tcx(&self) -> TyCtxt<'tcx> {
255 self.tcx.expect("missing TyCtxt in DecodeContext")
258 fn cdata(&self) -> CrateMetadataRef<'a> {
259 self.cdata.expect("missing CrateMetadata in DecodeContext")
262 fn read_lazy_with_meta<T: ?Sized + LazyMeta>(
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
275 LazyState::Previous(last_min_end) => last_min_end.get() + distance,
277 self.lazy_state = LazyState::Previous(NonZeroUsize::new(position + min_size).unwrap());
278 Ok(Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta))
282 impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> {
283 const CLEAR_CROSS_CRATE: bool = true;
286 fn tcx(&self) -> TyCtxt<'tcx> {
287 self.tcx.expect("missing TyCtxt in DecodeContext")
291 fn peek_byte(&self) -> u8 {
292 self.opaque.data[self.opaque.position()]
296 fn position(&self) -> usize {
297 self.opaque.position()
300 fn cached_ty_for_shorthand<F>(
304 ) -> Result<Ty<'tcx>, Self::Error>
306 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
308 let tcx = self.tcx();
310 let key = ty::CReaderCacheKey { cnum: self.cdata().cnum, pos: shorthand };
312 if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) {
316 let ty = or_insert_with(self)?;
317 tcx.ty_rcache.borrow_mut().insert(key, ty);
321 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
323 F: FnOnce(&mut Self) -> R,
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);
329 self.opaque = old_opaque;
330 self.lazy_state = old_state;
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] }
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)
342 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
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))
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()?))
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)
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);
377 .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname))
378 .decode((&cdata, sess)))
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
393 &local_cdata.cstore.get_crate_data(cnum).cdata.hygiene_context
397 rustc_span::hygiene::decode_expn_id(
399 ExpnDataDecodeMode::Metadata(get_ctxt),
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 {
407 local_cdata.cstore.get_crate_data(cnum)
412 .get(&crate_data, index)
414 .decode((&crate_data, sess)))
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)?;
424 if tag == TAG_INVALID_SPAN {
428 debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN);
430 let lo = BytePos::decode(decoder)?;
431 let len = BytePos::decode(decoder)?;
432 let ctxt = SyntaxContext::decode(decoder)?;
435 let sess = if let Some(sess) = decoder.sess {
438 bug!("Cannot decode Span without Session.")
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:
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:
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.
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)
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)?;
479 "Decoding of crate {:?} tried to access proc-macro dep {:?}",
480 decoder.cdata().root.name,
484 // tag is TAG_VALID_SPAN_FOREIGN, checked by `debug_assert` above
485 let cnum = CrateNum::decode(decoder)?;
487 "SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {:?}",
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;
497 let foreign_data = decoder.cdata().cstore.get_crate_data(cnum);
498 foreign_data.imported_source_files(sess)
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];
506 if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos
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);
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;
519 &imported_source_files[index]
523 // Make sure our binary search above is correct.
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={:?}",
528 source_file.original_start_pos,
529 source_file.original_end_pos
532 // Make sure we correctly filtered out invalid spans during encoding
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={:?}",
537 source_file.original_start_pos,
538 source_file.original_end_pos
542 (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
544 (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
546 Ok(Span::new(lo, hi, ctxt))
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)
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)
562 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
565 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
566 decoder.read_lazy_with_meta(())
570 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
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) }
579 impl<'a, 'tcx, I: Idx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
580 for Lazy<Table<I, T>>
582 Option<T>: FixedSizeEncoding,
584 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
585 let len = decoder.read_usize()?;
586 decoder.read_lazy_with_meta(len)
590 implement_ty_decoder!(DecodeContext<'a, 'tcx>);
593 crate fn new(metadata_ref: MetadataRef) -> MetadataBlob {
594 MetadataBlob(metadata_ref)
597 crate fn is_compatible(&self) -> bool {
598 self.raw_bytes().starts_with(METADATA_HEADER)
601 crate fn get_rustc_version(&self) -> String {
602 Lazy::<String>::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap())
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)
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)?;
628 fn def_kind(&self) -> DefKind {
630 EntryKind::AnonConst(..) => DefKind::AnonConst,
631 EntryKind::Const(..) => DefKind::Const,
632 EntryKind::AssocConst(..) => DefKind::AssocConst,
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,
665 crate fn is_proc_macro_crate(&self) -> bool {
666 self.proc_macro_data.is_some()
669 crate fn name(&self) -> Symbol {
673 crate fn disambiguator(&self) -> CrateDisambiguator {
677 crate fn hash(&self) -> Svh {
681 crate fn triple(&self) -> &TargetTriple {
685 crate fn decode_crate_deps(
687 metadata: &'a MetadataBlob,
688 ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
689 self.crate_deps.decode(metadata)
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))
698 fn kind(&self, item_id: DefIndex) -> EntryKind {
699 self.maybe_kind(item_id).unwrap_or_else(|| {
701 "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}",
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'.
719 .position(|i| i == id)
721 &self.raw_proc_macros.unwrap()[pos]
724 fn item_ident(&self, item_index: DefIndex, sess: &Session) -> Ident {
730 .expect("no name in item_ident");
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)
741 fn def_kind(&self, index: DefIndex) -> DefKind {
742 self.kind(index).def_kind()
745 fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
750 .unwrap_or_else(|| panic!("Missing span for {:?}", index))
751 .decode((self, sess))
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 } => {
758 attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
761 SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
765 ProcMacro::Attr { name, client } => {
766 (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new())
768 ProcMacro::Bang { name, client } => {
769 (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new())
773 let attrs: Vec<_> = self.get_item_attrs(id, sess).collect();
774 SyntaxExtension::new(
777 self.get_span(id, sess),
780 Symbol::intern(name),
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));
790 self.local_def_id(item_id),
795 data.specialization_kind,
796 self.def_path_hash(item_id),
799 EntryKind::TraitAlias => ty::TraitDef::new(
800 self.local_def_id(item_id),
801 hir::Unsafety::Normal,
805 ty::trait_def::TraitSpecializationKind::None,
806 self.def_path_hash(item_id),
808 _ => bug!("def-index does not refer to trait or trait alias"),
818 ) -> ty::VariantDef {
819 let data = match kind {
820 EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => {
826 let adt_kind = match kind {
827 EntryKind::Variant(_) => ty::AdtKind::Enum,
828 EntryKind::Struct(..) => ty::AdtKind::Struct,
829 EntryKind::Union(..) => ty::AdtKind::Union,
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));
838 self.item_ident(index, sess),
846 .unwrap_or_else(Lazy::empty)
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),
858 data.is_non_exhaustive,
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);
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),
873 let variants = if let ty::AdtKind::Enum = adt_kind {
878 .unwrap_or_else(Lazy::empty)
880 .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess))
883 std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect()
886 tcx.alloc_adt_def(did, adt_kind, variants, repr)
889 fn get_explicit_predicates(
893 ) -> ty::GenericPredicates<'tcx> {
894 self.root.tables.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx))
897 fn get_inferred_outlives(
901 ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
906 .map(|predicates| tcx.arena.alloc_from_iter(predicates.decode((self, tcx))))
910 fn get_super_predicates(
914 ) -> ty::GenericPredicates<'tcx> {
915 self.root.tables.super_predicates.get(self, item_id).unwrap().decode((self, tcx))
918 fn get_explicit_item_bounds(
922 ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
925 .explicit_item_bounds
927 .map(|bounds| tcx.arena.alloc_from_iter(bounds.decode((self, tcx))))
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))
935 fn get_type(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
940 .unwrap_or_else(|| panic!("Not a type: {:?}", id))
944 fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
945 self.root.tables.stability.get(self, id).map(|stab| stab.decode(self))
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))
952 fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
953 self.root.tables.deprecation.get(self, id).map(|depr| depr.decode(self))
956 fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
957 self.root.tables.visibility.get(self, id).unwrap().decode(self)
960 fn get_impl_data(&self, id: DefIndex) -> ImplData {
961 match self.kind(id) {
962 EntryKind::Impl(data) => data.decode(self),
967 fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
968 self.get_impl_data(id).parent_impl
971 fn get_impl_polarity(&self, id: DefIndex) -> ty::ImplPolarity {
972 self.get_impl_data(id).polarity
975 fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
976 self.get_impl_data(id).defaultness
979 fn get_coerce_unsized_info(&self, id: DefIndex) -> Option<ty::adjustment::CoerceUnsizedInfo> {
980 self.get_impl_data(id).coerce_unsized_info
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)))
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))
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))
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.
1004 tcx.arena.alloc_from_iter(
1008 .map(|(def_index, index)| (self.local_def_id(def_index), index)),
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.
1022 .map(|(name, def_index)| (name, self.local_def_id(def_index)))
1027 /// Iterates over each child of the given item.
1028 fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
1030 F: FnMut(Export<hir::HirId>),
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.
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);
1041 DefKind::Macro(macro_kind(raw_macro)),
1042 self.local_def_id(def_index),
1044 let ident = self.item_ident(def_index, sess);
1045 callback(Export { ident, res, vis: ty::Visibility::Public, span: ident.span });
1052 let kind = match self.maybe_kind(id) {
1057 // Iterate over all children.
1058 let macros_only = self.dep_kind.lock().macros_only();
1060 let children = self.root.tables.children.get(self, id).unwrap_or_else(Lazy::empty);
1062 for child_index in children.decode((self, sess)) {
1064 let child_kind = match self.maybe_kind(child_index) {
1065 Some(child_kind) => child_kind,
1069 // Hand off the item to the callback.
1071 // FIXME(eddyb) Don't encode these in children.
1072 EntryKind::ForeignMod => {
1073 let child_children = self
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);
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),
1089 .get(self, child_index)
1091 .decode((self, sess)),
1096 EntryKind::Impl(_) => continue,
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.
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);
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 });
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);
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);
1143 callback(Export { res: ctor_res, ident, vis, span });
1151 if let EntryKind::Mod(data) = kind {
1152 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
1154 Res::Def(DefKind::Macro(..), _) => {}
1155 _ if macros_only => continue,
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()
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
1172 panic!("Expected module, found {:?}", self.local_def_id(id))
1176 fn get_optimized_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> {
1181 .unwrap_or_else(|| {
1182 bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id))
1184 .decode((self, tcx))
1187 fn get_mir_for_ctfe(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> {
1192 .unwrap_or_else(|| {
1193 bug!("get_mir_for_ctfe: missing MIR for `{:?}`", self.local_def_id(id))
1195 .decode((self, tcx))
1198 fn get_mir_abstract_const(
1202 ) -> Result<Option<&'tcx [mir::abstract_const::Node<'tcx>]>, ErrorReported> {
1205 .mir_abstract_consts
1207 .map_or(Ok(None), |v| Ok(Some(v.decode((self, tcx)))))
1210 fn get_unused_generic_params(&self, id: DefIndex) -> FiniteBitSet<u32> {
1213 .unused_generic_params
1215 .map(|params| params.decode(self))
1216 .unwrap_or_default()
1219 fn get_promoted_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> IndexVec<Promoted, Body<'tcx>> {
1224 .unwrap_or_else(|| {
1225 bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id))
1227 .decode((self, tcx))
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,
1241 _ => bug!("mir_const_qualif: unexpected kind"),
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);
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)
1256 EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false),
1257 _ => bug!("cannot get associated-item of `{:?}`", def_key),
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,
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)
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
1280 _ => CtorKind::Fictive,
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))
1289 EntryKind::Variant(data) => {
1290 data.decode(self).ctor.map(|index| self.local_def_id(index))
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()
1315 .unwrap_or_else(Lazy::empty)
1316 .decode((self, sess))
1319 fn get_struct_field_names(&self, id: DefIndex, sess: &Session) -> Vec<Spanned<Symbol>> {
1324 .unwrap_or_else(Lazy::empty)
1326 .map(|index| respan(self.get_span(index, sess), self.item_ident(index, sess).name))
1330 fn get_inherent_implementations_for_type(
1334 ) -> &'tcx [DefId] {
1335 tcx.arena.alloc_from_iter(
1340 .unwrap_or_else(Lazy::empty)
1342 .map(|index| self.local_def_id(index)),
1346 fn get_implementations_for_trait(
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.
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 &[],
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)
1375 tcx.arena.alloc_from_iter(self.trait_impls.values().flat_map(|impls| {
1378 .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty))
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
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)),
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.
1401 self.root.native_libraries.decode((self, sess)).collect()
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())
1410 let modules: FxHashMap<DefId, ForeignModule> =
1411 self.root.foreign_modules.decode((self, tcx.sess)).map(|m| (m.def_id, m)).collect();
1416 fn get_dylib_dependency_formats(
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))
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.
1433 tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self))
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,
1443 tcx.arena.alloc_from_iter(param_names.decode((self, tcx)))
1446 fn exported_symbols(
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.
1455 tcx.arena.alloc_from_iter(self.root.exported_symbols.decode((self, tcx)))
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,
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)),
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,
1485 constness == hir::Constness::Const
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"),
1497 fn is_foreign_item(&self, id: DefIndex) -> bool {
1498 match self.kind(id) {
1499 EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => {
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),
1514 fn generator_kind(&self, id: DefIndex) -> Option<hir::GeneratorKind> {
1515 match self.kind(id) {
1516 EntryKind::Generator(data) => Some(data),
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))
1526 fn def_key(&self, index: DefIndex) -> DefKey {
1531 .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self))
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(
1548 ) -> Option<DefId> {
1549 let def_index_guess = DefIndex::from_u32(index_guess);
1554 .get(self, def_index_guess)
1555 .map(|lazy| lazy.decode(self));
1557 // Fast path: the definition and its index is unchanged from the
1558 // previous compilation session. There is no need to decode anything
1560 if old_hash == Some(hash) {
1561 return Some(DefId { krate, index: def_index_guess });
1564 let is_proc_macro = self.is_proc_macro_crate();
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);
1583 map.get(&hash).map(|index| DefId { krate, index: *index })
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))
1592 fn def_path_hash_unlocked(
1595 def_path_hashes: &mut FxHashMap<DefIndex, DefPathHash>,
1597 *def_path_hashes.entry(index).or_insert_with(|| {
1598 self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self)
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)
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();
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.
1621 let def_path_hash = self.def_path_hash(CRATE_DEF_INDEX);
1623 DepNode::from_def_path_hash(def_path_hash, dep_graph::DepKind::CrateMetadata);
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);
1633 /// Imports the source_map from an external crate into the source_map of the crate
1634 /// currently being compiled (the "local crate").
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>>`).
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.
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.
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.
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")
1667 // Only spend time on further checks if we have what to translate *to*.
1668 sess.real_rust_source_base_dir.is_some()
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)
1676 let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| {
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,
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();
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] = &[
1704 "profiler_builtins",
1706 "rustc-std-workspace-core",
1707 "rustc-std-workspace-alloc",
1708 "rustc-std-workspace-std",
1711 let is_std_lib = STD_LIBS.iter().any(|l| rest.starts_with(l));
1713 let new_path = if is_std_lib {
1714 real_dir.join("library").join(rest)
1720 "try_to_translate_virtual_to_real: `{}` -> `{}`",
1721 virtual_name.display(),
1724 let new_name = rustc_span::RealFileName::Devirtualized {
1725 local_path: new_path,
1728 *old_name = new_name;
1736 self.cdata.source_map_import_info.get_or_init(|| {
1737 let external_source_map = self.root.source_map.decode(self);
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 {
1750 mut multibyte_chars,
1751 mut non_narrow_chars,
1755 } = source_file_to_import;
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);
1764 let source_length = (end_pos - start_pos).to_usize();
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;
1774 for mbc in &mut multibyte_chars {
1775 mbc.pos = mbc.pos - start_pos;
1777 for swc in &mut non_narrow_chars {
1778 *swc = *swc - start_pos;
1780 for np in &mut normalized_pos {
1781 np.pos = np.pos - start_pos;
1784 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,
1849 dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
1853 dep_kind: Lock::new(dep_kind),
1857 extern_crate: Lock::new(None),
1858 hygiene_context: Default::default(),
1859 def_key_cache: Default::default(),
1860 def_path_hash_cache: Default::default(),
1864 crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
1865 self.dependencies.borrow()
1868 crate fn add_dependency(&self, cnum: CrateNum) {
1869 self.dependencies.borrow_mut().push(cnum);
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);
1876 *extern_crate = Some(new_extern_crate);
1881 crate fn source(&self) -> &CrateSource {
1885 crate fn dep_kind(&self) -> CrateDepKind {
1886 *self.dep_kind.lock()
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))
1893 crate fn panic_strategy(&self) -> PanicStrategy {
1894 self.root.panic_strategy
1897 crate fn needs_panic_runtime(&self) -> bool {
1898 self.root.needs_panic_runtime
1901 crate fn is_panic_runtime(&self) -> bool {
1902 self.root.panic_runtime
1905 crate fn is_profiler_runtime(&self) -> bool {
1906 self.root.profiler_runtime
1909 crate fn needs_allocator(&self) -> bool {
1910 self.root.needs_allocator
1913 crate fn has_global_allocator(&self) -> bool {
1914 self.root.has_global_allocator
1917 crate fn has_default_lib_allocator(&self) -> bool {
1918 self.root.has_default_lib_allocator
1921 crate fn is_proc_macro_crate(&self) -> bool {
1922 self.root.is_proc_macro_crate()
1925 crate fn name(&self) -> Symbol {
1929 crate fn disambiguator(&self) -> CrateDisambiguator {
1930 self.root.disambiguator
1933 crate fn hash(&self) -> Svh {
1937 fn num_def_ids(&self) -> usize {
1938 self.root.tables.def_keys.size()
1941 fn local_def_id(&self, index: DefIndex) -> DefId {
1942 DefId { krate: self.cnum, index }
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 });
1958 // Cannot be implemented on 'ProcMacro', as libproc_macro
1959 // does not depend on librustc_ast
1960 fn macro_kind(raw: &ProcMacro) -> MacroKind {
1962 ProcMacro::CustomDerive { .. } => MacroKind::Derive,
1963 ProcMacro::Attr { .. } => MacroKind::Attr,
1964 ProcMacro::Bang { .. } => MacroKind::Bang,