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_expand::base::{SyntaxExtension, SyntaxExtensionKind};
15 use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, ProcMacroDerive};
17 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
18 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
19 use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash};
20 use rustc_hir::lang_items;
21 use rustc_index::vec::{Idx, IndexVec};
22 use rustc_middle::dep_graph::{self, DepNode, DepNodeExt, DepNodeIndex};
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};
31 use rustc_serialize::{opaque, Decodable, Decoder};
32 use rustc_session::Session;
33 use rustc_span::hygiene::ExpnDataDecodeMode;
34 use rustc_span::source_map::{respan, Spanned};
35 use rustc_span::symbol::{sym, Ident, Symbol};
36 use rustc_span::{self, hygiene::MacroKind, BytePos, ExpnId, Pos, Span, SyntaxContext, DUMMY_SP};
38 use proc_macro::bridge::client::ProcMacro;
42 use std::num::NonZeroUsize;
46 pub use cstore_impl::{provide, provide_extern};
47 use rustc_span::hygiene::HygieneDecodeContext;
51 crate struct MetadataBlob(MetadataRef);
53 // A map from external crate numbers (as decoded from some crate file) to
54 // local crate numbers (as generated during this session). Each external
55 // crate may refer to types in other external crates, and each has their
57 crate type CrateNumMap = IndexVec<CrateNum, CrateNum>;
59 crate struct CrateMetadata {
60 /// The primary crate data - binary metadata blob.
63 // --- Some data pre-decoded from the metadata blob, usually for performance ---
64 /// Properties of the whole crate.
65 /// NOTE(eddyb) we pass `'static` to a `'tcx` parameter because this
66 /// lifetime is only used behind `Lazy`, and therefore acts like an
67 /// universal (`for<'tcx>`), that is paired up with whichever `TyCtxt`
68 /// is being used to decode those values.
69 root: CrateRoot<'static>,
71 /// FIXME: Used only from queries and can use query cache,
72 /// so pre-decoding can probably be avoided.
74 FxHashMap<(u32, DefIndex), Lazy<[(DefIndex, Option<ty::fast_reject::SimplifiedType>)]>>,
75 /// Proc macro descriptions for this crate, if it's a proc macro crate.
76 raw_proc_macros: Option<&'static [ProcMacro]>,
77 /// Source maps for code from the crate.
78 source_map_import_info: OnceCell<Vec<ImportedSourceFile>>,
79 /// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
80 alloc_decoding_state: AllocDecodingState,
81 /// The `DepNodeIndex` of the `DepNode` representing this upstream crate.
82 /// It is initialized on the first access in `get_crate_dep_node_index()`.
83 /// Do not access the value directly, as it might not have been initialized yet.
84 /// The field must always be initialized to `DepNodeIndex::INVALID`.
85 dep_node_index: AtomicCell<DepNodeIndex>,
86 /// Caches decoded `DefKey`s.
87 def_key_cache: Lock<FxHashMap<DefIndex, DefKey>>,
88 /// Caches decoded `DefPathHash`es.
89 def_path_hash_cache: Lock<FxHashMap<DefIndex, DefPathHash>>,
91 // --- Other significant crate properties ---
92 /// ID of this crate, from the current compilation session's point of view.
94 /// Maps crate IDs as they are were seen from this crate's compilation sessions into
95 /// IDs as they are seen from the current compilation session.
96 cnum_map: CrateNumMap,
97 /// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
98 dependencies: Lock<Vec<CrateNum>>,
99 /// How to link (or not link) this crate to the currently compiled crate.
100 dep_kind: Lock<CrateDepKind>,
101 /// Filesystem location of this crate.
103 /// Whether or not this crate should be consider a private dependency
104 /// for purposes of the 'exported_private_dependencies' lint
106 /// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
107 host_hash: Option<Svh>,
109 /// Additional data used for decoding `HygieneData` (e.g. `SyntaxContext`
111 /// Note that we store a `HygieneDecodeContext` for each `CrateMetadat`. This is
112 /// because `SyntaxContext` ids are not globally unique, so we need
113 /// to track which ids we've decoded on a per-crate basis.
114 hygiene_context: HygieneDecodeContext,
116 // --- Data used only for improving diagnostics ---
117 /// Information about the `extern crate` item or path that caused this crate to be loaded.
118 /// If this is `None`, then the crate was injected (e.g., by the allocator).
119 extern_crate: Lock<Option<ExternCrate>>,
122 /// Holds information about a rustc_span::SourceFile imported from another crate.
123 /// See `imported_source_files()` for more information.
124 struct ImportedSourceFile {
125 /// This SourceFile's byte-offset within the source_map of its original crate
126 original_start_pos: rustc_span::BytePos,
127 /// The end of this SourceFile within the source_map of its original crate
128 original_end_pos: rustc_span::BytePos,
129 /// The imported SourceFile's representation within the local source_map
130 translated_source_file: Lrc<rustc_span::SourceFile>,
133 pub(super) struct DecodeContext<'a, 'tcx> {
134 opaque: opaque::Decoder<'a>,
135 cdata: Option<CrateMetadataRef<'a>>,
136 sess: Option<&'tcx Session>,
137 tcx: Option<TyCtxt<'tcx>>,
139 // Cache the last used source_file for translating spans as an optimization.
140 last_source_file_index: usize,
142 lazy_state: LazyState,
144 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
145 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
148 /// Abstract over the various ways one can create metadata decoders.
149 pub(super) trait Metadata<'a, 'tcx>: Copy {
150 fn raw_bytes(self) -> &'a [u8];
151 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
154 fn sess(self) -> Option<&'tcx Session> {
157 fn tcx(self) -> Option<TyCtxt<'tcx>> {
161 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
162 let tcx = self.tcx();
164 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
166 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
168 last_source_file_index: 0,
169 lazy_state: LazyState::NoNode,
170 alloc_decoding_session: self
172 .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()),
177 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
178 fn raw_bytes(self) -> &'a [u8] {
183 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
184 fn raw_bytes(self) -> &'a [u8] {
185 let (blob, _) = self;
189 fn sess(self) -> Option<&'tcx Session> {
190 let (_, sess) = self;
195 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadataRef<'a> {
196 fn raw_bytes(self) -> &'a [u8] {
197 self.blob.raw_bytes()
199 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
204 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, &'tcx Session) {
205 fn raw_bytes(self) -> &'a [u8] {
208 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
211 fn sess(self) -> Option<&'tcx Session> {
216 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, TyCtxt<'tcx>) {
217 fn raw_bytes(self) -> &'a [u8] {
220 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
223 fn tcx(self) -> Option<TyCtxt<'tcx>> {
228 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Lazy<T> {
229 fn decode<M: Metadata<'a, 'tcx>>(self, metadata: M) -> T {
230 let mut dcx = metadata.decoder(self.position.get());
231 dcx.lazy_state = LazyState::NodeStart(self.position);
232 T::decode(&mut dcx).unwrap()
236 impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable<DecodeContext<'a, 'tcx>>> Lazy<[T]> {
237 fn decode<M: Metadata<'a, 'tcx>>(
240 ) -> impl ExactSizeIterator<Item = T> + Captures<'a> + Captures<'tcx> + 'x {
241 let mut dcx = metadata.decoder(self.position.get());
242 dcx.lazy_state = LazyState::NodeStart(self.position);
243 (0..self.meta).map(move |_| T::decode(&mut dcx).unwrap())
247 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
248 fn tcx(&self) -> TyCtxt<'tcx> {
249 self.tcx.expect("missing TyCtxt in DecodeContext")
252 fn cdata(&self) -> CrateMetadataRef<'a> {
253 self.cdata.expect("missing CrateMetadata in DecodeContext")
256 fn read_lazy_with_meta<T: ?Sized + LazyMeta>(
259 ) -> Result<Lazy<T>, <Self as Decoder>::Error> {
260 let min_size = T::min_size(meta);
261 let distance = self.read_usize()?;
262 let position = match self.lazy_state {
263 LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
264 LazyState::NodeStart(start) => {
265 let start = start.get();
266 assert!(distance + min_size <= start);
267 start - distance - min_size
269 LazyState::Previous(last_min_end) => last_min_end.get() + distance,
271 self.lazy_state = LazyState::Previous(NonZeroUsize::new(position + min_size).unwrap());
272 Ok(Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta))
276 impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> {
277 const CLEAR_CROSS_CRATE: bool = true;
280 fn tcx(&self) -> TyCtxt<'tcx> {
281 self.tcx.expect("missing TyCtxt in DecodeContext")
285 fn peek_byte(&self) -> u8 {
286 self.opaque.data[self.opaque.position()]
290 fn position(&self) -> usize {
291 self.opaque.position()
294 fn cached_ty_for_shorthand<F>(
298 ) -> Result<Ty<'tcx>, Self::Error>
300 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
302 let tcx = self.tcx();
304 let key = ty::CReaderCacheKey { cnum: self.cdata().cnum, pos: shorthand };
306 if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) {
310 let ty = or_insert_with(self)?;
311 tcx.ty_rcache.borrow_mut().insert(key, ty);
315 fn cached_predicate_for_shorthand<F>(
319 ) -> Result<ty::Predicate<'tcx>, Self::Error>
321 F: FnOnce(&mut Self) -> Result<ty::Predicate<'tcx>, Self::Error>,
323 let tcx = self.tcx();
325 let key = ty::CReaderCacheKey { cnum: self.cdata().cnum, pos: shorthand };
327 if let Some(&pred) = tcx.pred_rcache.borrow().get(&key) {
331 let pred = or_insert_with(self)?;
332 tcx.pred_rcache.borrow_mut().insert(key, pred);
336 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
338 F: FnOnce(&mut Self) -> R,
340 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
341 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
342 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
344 self.opaque = old_opaque;
345 self.lazy_state = old_state;
349 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
350 if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] }
353 fn decode_alloc_id(&mut self) -> Result<rustc_middle::mir::interpret::AllocId, Self::Error> {
354 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
355 alloc_decoding_session.decode_alloc_id(self)
357 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
362 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for CrateNum {
363 fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<CrateNum, String> {
364 let cnum = CrateNum::from_u32(d.read_u32()?);
365 Ok(d.map_encoded_cnum_to_current(cnum))
369 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefIndex {
370 fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<DefIndex, String> {
371 Ok(DefIndex::from_u32(d.read_u32()?))
375 impl<'a, 'tcx> FingerprintDecoder for DecodeContext<'a, 'tcx> {
376 fn decode_fingerprint(&mut self) -> Result<Fingerprint, String> {
377 Fingerprint::decode_opaque(&mut self.opaque)
381 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for SyntaxContext {
382 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<SyntaxContext, String> {
383 let cdata = decoder.cdata();
384 let sess = decoder.sess.unwrap();
385 let cname = cdata.root.name;
386 rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| {
387 debug!("SpecializedDecoder<SyntaxContext>: decoding {}", id);
392 .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname))
393 .decode((&cdata, sess)))
398 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for ExpnId {
399 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<ExpnId, String> {
400 let local_cdata = decoder.cdata();
401 let sess = decoder.sess.unwrap();
402 let expn_cnum = Cell::new(None);
403 let get_ctxt = |cnum| {
404 expn_cnum.set(Some(cnum));
405 if cnum == LOCAL_CRATE {
406 &local_cdata.hygiene_context
408 &local_cdata.cstore.get_crate_data(cnum).cdata.hygiene_context
412 rustc_span::hygiene::decode_expn_id(
414 ExpnDataDecodeMode::Metadata(get_ctxt),
416 let cnum = expn_cnum.get().unwrap();
417 // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s
418 // are stored in the owning crate, to avoid duplication.
419 let crate_data = if cnum == LOCAL_CRATE {
422 local_cdata.cstore.get_crate_data(cnum)
427 .get(&crate_data, index)
429 .decode((&crate_data, sess)))
435 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for Span {
436 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Span, String> {
437 let tag = u8::decode(decoder)?;
439 if tag == TAG_INVALID_SPAN {
443 debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN);
445 let lo = BytePos::decode(decoder)?;
446 let len = BytePos::decode(decoder)?;
447 let ctxt = SyntaxContext::decode(decoder)?;
450 let sess = if let Some(sess) = decoder.sess {
453 bug!("Cannot decode Span without Session.")
456 // There are two possibilities here:
457 // 1. This is a 'local span', which is located inside a `SourceFile`
458 // that came from this crate. In this case, we use the source map data
459 // encoded in this crate. This branch should be taken nearly all of the time.
460 // 2. This is a 'foreign span', which is located inside a `SourceFile`
461 // that came from a *different* crate (some crate upstream of the one
462 // whose metadata we're looking at). For example, consider this dependency graph:
466 // Suppose that we're currently compiling crate A, and start deserializing
467 // metadata from crate B. When we deserialize a Span from crate B's metadata,
468 // there are two posibilites:
470 // 1. The span references a file from crate B. This makes it a 'local' span,
471 // which means that we can use crate B's serialized source map information.
472 // 2. The span references a file from crate C. This makes it a 'foreign' span,
473 // which means we need to use Crate *C* (not crate B) to determine the source
474 // map information. We only record source map information for a file in the
475 // crate that 'owns' it, so deserializing a Span may require us to look at
476 // a transitive dependency.
478 // When we encode a foreign span, we adjust its 'lo' and 'high' values
479 // to be based on the *foreign* crate (e.g. crate C), not the crate
480 // we are writing metadata for (e.g. crate B). This allows us to
481 // treat the 'local' and 'foreign' cases almost identically during deserialization:
482 // we can call `imported_source_files` for the proper crate, and binary search
483 // through the returned slice using our span.
484 let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL {
485 decoder.cdata().imported_source_files(sess)
487 // When we encode a proc-macro crate, all `Span`s should be encoded
488 // with `TAG_VALID_SPAN_LOCAL`
489 if decoder.cdata().root.is_proc_macro_crate() {
490 // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE
491 // since we don't have `cnum_map` populated.
492 let cnum = u32::decode(decoder)?;
494 "Decoding of crate {:?} tried to access proc-macro dep {:?}",
495 decoder.cdata().root.name,
499 // tag is TAG_VALID_SPAN_FOREIGN, checked by `debug_assert` above
500 let cnum = CrateNum::decode(decoder)?;
502 "SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {:?}",
506 // Decoding 'foreign' spans should be rare enough that it's
507 // not worth it to maintain a per-CrateNum cache for `last_source_file_index`.
508 // We just set it to 0, to ensure that we don't try to access something out
509 // of bounds for our initial 'guess'
510 decoder.last_source_file_index = 0;
512 let foreign_data = decoder.cdata().cstore.get_crate_data(cnum);
513 foreign_data.imported_source_files(sess)
517 // Optimize for the case that most spans within a translated item
518 // originate from the same source_file.
519 let last_source_file = &imported_source_files[decoder.last_source_file_index];
521 if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos
525 let index = imported_source_files
526 .binary_search_by_key(&lo, |source_file| source_file.original_start_pos)
527 .unwrap_or_else(|index| index - 1);
529 // Don't try to cache the index for foreign spans,
530 // as this would require a map from CrateNums to indices
531 if tag == TAG_VALID_SPAN_LOCAL {
532 decoder.last_source_file_index = index;
534 &imported_source_files[index]
538 // Make sure our binary search above is correct.
540 lo >= source_file.original_start_pos && lo <= source_file.original_end_pos,
541 "Bad binary search: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
543 source_file.original_start_pos,
544 source_file.original_end_pos
547 // Make sure we correctly filtered out invalid spans during encoding
549 hi >= source_file.original_start_pos && hi <= source_file.original_end_pos,
550 "Bad binary search: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
552 source_file.original_start_pos,
553 source_file.original_end_pos
557 (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
559 (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
561 Ok(Span::new(lo, hi, ctxt))
565 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
566 fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
567 ty::codec::RefDecodable::decode(d)
571 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
574 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
575 decoder.read_lazy_with_meta(())
579 impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
582 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
583 let len = decoder.read_usize()?;
584 if len == 0 { Ok(Lazy::empty()) } else { decoder.read_lazy_with_meta(len) }
588 impl<'a, 'tcx, I: Idx, T: Decodable<DecodeContext<'a, 'tcx>>> Decodable<DecodeContext<'a, 'tcx>>
589 for Lazy<Table<I, T>>
591 Option<T>: FixedSizeEncoding,
593 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Self, String> {
594 let len = decoder.read_usize()?;
595 decoder.read_lazy_with_meta(len)
599 implement_ty_decoder!(DecodeContext<'a, 'tcx>);
602 crate fn new(metadata_ref: MetadataRef) -> MetadataBlob {
603 MetadataBlob(metadata_ref)
606 crate fn is_compatible(&self) -> bool {
607 self.raw_bytes().starts_with(METADATA_HEADER)
610 crate fn get_rustc_version(&self) -> String {
611 Lazy::<String>::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap())
615 crate fn get_root(&self) -> CrateRoot<'tcx> {
616 let slice = self.raw_bytes();
617 let offset = METADATA_HEADER.len();
618 let pos = (((slice[offset + 0] as u32) << 24)
619 | ((slice[offset + 1] as u32) << 16)
620 | ((slice[offset + 2] as u32) << 8)
621 | ((slice[offset + 3] as u32) << 0)) as usize;
622 Lazy::<CrateRoot<'tcx>>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self)
625 crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> {
626 write!(out, "=External Dependencies=\n")?;
627 let root = self.get_root();
628 for (i, dep) in root.crate_deps.decode(self).enumerate() {
629 write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
637 fn def_kind(&self) -> DefKind {
639 EntryKind::AnonConst(..) => DefKind::AnonConst,
640 EntryKind::Const(..) => DefKind::Const,
641 EntryKind::AssocConst(..) => DefKind::AssocConst,
643 | EntryKind::MutStatic
644 | EntryKind::ForeignImmStatic
645 | EntryKind::ForeignMutStatic => DefKind::Static,
646 EntryKind::Struct(_, _) => DefKind::Struct,
647 EntryKind::Union(_, _) => DefKind::Union,
648 EntryKind::Fn(_) | EntryKind::ForeignFn(_) => DefKind::Fn,
649 EntryKind::AssocFn(_) => DefKind::AssocFn,
650 EntryKind::Type => DefKind::TyAlias,
651 EntryKind::TypeParam => DefKind::TyParam,
652 EntryKind::ConstParam => DefKind::ConstParam,
653 EntryKind::OpaqueTy => DefKind::OpaqueTy,
654 EntryKind::AssocType(_) => DefKind::AssocTy,
655 EntryKind::Mod(_) => DefKind::Mod,
656 EntryKind::Variant(_) => DefKind::Variant,
657 EntryKind::Trait(_) => DefKind::Trait,
658 EntryKind::TraitAlias => DefKind::TraitAlias,
659 EntryKind::Enum(..) => DefKind::Enum,
660 EntryKind::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
661 EntryKind::ForeignType => DefKind::ForeignTy,
662 EntryKind::Impl(_) => DefKind::Impl,
663 EntryKind::Closure => DefKind::Closure,
664 EntryKind::ForeignMod => DefKind::ForeignMod,
665 EntryKind::GlobalAsm => DefKind::GlobalAsm,
666 EntryKind::Field => DefKind::Field,
667 EntryKind::Generator(_) => DefKind::Generator,
673 crate fn is_proc_macro_crate(&self) -> bool {
674 self.proc_macro_data.is_some()
677 crate fn name(&self) -> Symbol {
681 crate fn disambiguator(&self) -> CrateDisambiguator {
685 crate fn hash(&self) -> Svh {
689 crate fn triple(&self) -> &TargetTriple {
693 crate fn decode_crate_deps(
695 metadata: &'a MetadataBlob,
696 ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
697 self.crate_deps.decode(metadata)
701 impl<'a, 'tcx> CrateMetadataRef<'a> {
702 fn is_proc_macro(&self, id: DefIndex) -> bool {
703 self.root.proc_macro_data.and_then(|data| data.decode(self).find(|x| *x == id)).is_some()
706 fn maybe_kind(&self, item_id: DefIndex) -> Option<EntryKind> {
707 self.root.tables.kind.get(self, item_id).map(|k| k.decode(self))
710 fn kind(&self, item_id: DefIndex) -> EntryKind {
711 assert!(!self.is_proc_macro(item_id));
712 self.maybe_kind(item_id).unwrap_or_else(|| {
714 "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}",
722 fn raw_proc_macro(&self, id: DefIndex) -> &ProcMacro {
723 // DefIndex's in root.proc_macro_data have a one-to-one correspondence
724 // with items in 'raw_proc_macros'.
725 let pos = self.root.proc_macro_data.unwrap().decode(self).position(|i| i == id).unwrap();
726 &self.raw_proc_macros.unwrap()[pos]
729 fn item_ident(&self, item_index: DefIndex, sess: &Session) -> Ident {
730 if !self.is_proc_macro(item_index) {
736 .expect("no name in item_ident");
741 .get(self, item_index)
742 .map(|data| data.decode((self, sess)))
743 .unwrap_or_else(|| panic!("Missing ident span for {:?} ({:?})", name, item_index));
744 Ident::new(name, span)
747 Symbol::intern(self.raw_proc_macro(item_index).name()),
748 self.get_span(item_index, sess),
753 fn def_kind(&self, index: DefIndex) -> DefKind {
754 if !self.is_proc_macro(index) {
755 self.kind(index).def_kind()
757 DefKind::Macro(macro_kind(self.raw_proc_macro(index)))
761 fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
762 self.root.tables.span.get(self, index).unwrap().decode((self, sess))
765 fn load_proc_macro(&self, id: DefIndex, sess: &Session) -> SyntaxExtension {
766 let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
767 ProcMacro::CustomDerive { trait_name, attributes, client } => {
769 attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
772 SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
776 ProcMacro::Attr { name, client } => {
777 (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new())
779 ProcMacro::Bang { name, client } => {
780 (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new())
784 SyntaxExtension::new(
787 self.get_span(id, sess),
790 Symbol::intern(name),
791 &self.get_item_attrs(id, sess),
795 fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
796 match self.kind(item_id) {
797 EntryKind::Trait(data) => {
798 let data = data.decode((self, sess));
800 self.local_def_id(item_id),
805 data.specialization_kind,
806 self.def_path_hash(item_id),
809 EntryKind::TraitAlias => ty::TraitDef::new(
810 self.local_def_id(item_id),
811 hir::Unsafety::Normal,
815 ty::trait_def::TraitSpecializationKind::None,
816 self.def_path_hash(item_id),
818 _ => bug!("def-index does not refer to trait or trait alias"),
828 ) -> ty::VariantDef {
829 let data = match kind {
830 EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => {
836 let adt_kind = match kind {
837 EntryKind::Variant(_) => ty::AdtKind::Enum,
838 EntryKind::Struct(..) => ty::AdtKind::Struct,
839 EntryKind::Union(..) => ty::AdtKind::Union,
844 if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
845 let ctor_did = data.ctor.map(|index| self.local_def_id(index));
848 self.item_ident(index, sess),
856 .unwrap_or(Lazy::empty())
858 .map(|index| ty::FieldDef {
859 did: self.local_def_id(index),
860 ident: self.item_ident(index, sess),
861 vis: self.get_visibility(index),
868 data.is_non_exhaustive,
872 fn get_adt_def(&self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef {
873 let kind = self.kind(item_id);
874 let did = self.local_def_id(item_id);
876 let (adt_kind, repr) = match kind {
877 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
878 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
879 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
880 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
883 let variants = if let ty::AdtKind::Enum = adt_kind {
888 .unwrap_or(Lazy::empty())
890 .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess))
893 std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect()
896 tcx.alloc_adt_def(did, adt_kind, variants, repr)
899 fn get_explicit_predicates(
903 ) -> ty::GenericPredicates<'tcx> {
904 self.root.tables.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx))
907 fn get_inferred_outlives(
911 ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
916 .map(|predicates| predicates.decode((self, tcx)))
920 fn get_super_predicates(
924 ) -> ty::GenericPredicates<'tcx> {
925 self.root.tables.super_predicates.get(self, item_id).unwrap().decode((self, tcx))
928 fn get_generics(&self, item_id: DefIndex, sess: &Session) -> ty::Generics {
929 self.root.tables.generics.get(self, item_id).unwrap().decode((self, sess))
932 fn get_type(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
933 self.root.tables.ty.get(self, id).unwrap().decode((self, tcx))
936 fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
937 match self.is_proc_macro(id) {
938 true => self.root.proc_macro_stability,
939 false => self.root.tables.stability.get(self, id).map(|stab| stab.decode(self)),
943 fn get_const_stability(&self, id: DefIndex) -> Option<attr::ConstStability> {
944 self.root.tables.const_stability.get(self, id).map(|stab| stab.decode(self))
947 fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
952 .filter(|_| !self.is_proc_macro(id))
953 .map(|depr| depr.decode(self))
956 fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
957 match self.is_proc_macro(id) {
958 true => ty::Visibility::Public,
959 false => self.root.tables.visibility.get(self, id).unwrap().decode(self),
963 fn get_impl_data(&self, id: DefIndex) -> ImplData {
964 match self.kind(id) {
965 EntryKind::Impl(data) => data.decode(self),
970 fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
971 self.get_impl_data(id).parent_impl
974 fn get_impl_polarity(&self, id: DefIndex) -> ty::ImplPolarity {
975 self.get_impl_data(id).polarity
978 fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
979 self.get_impl_data(id).defaultness
982 fn get_coerce_unsized_info(&self, id: DefIndex) -> Option<ty::adjustment::CoerceUnsizedInfo> {
983 self.get_impl_data(id).coerce_unsized_info
986 fn get_impl_trait(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option<ty::TraitRef<'tcx>> {
987 self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx)))
990 /// Iterates over all the stability attributes in the given crate.
991 fn get_lib_features(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Option<Symbol>)] {
992 // FIXME: For a proc macro crate, not sure whether we should return the "host"
993 // features or an empty Vec. Both don't cause ICEs.
994 tcx.arena.alloc_from_iter(self.root.lib_features.decode(self))
997 /// Iterates over the language items in the given crate.
998 fn get_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] {
999 if self.root.is_proc_macro_crate() {
1000 // Proc macro crates do not export any lang-items to the target.
1003 tcx.arena.alloc_from_iter(
1007 .map(|(def_index, index)| (self.local_def_id(def_index), index)),
1012 /// Iterates over the diagnostic items in the given crate.
1013 fn get_diagnostic_items(&self) -> FxHashMap<Symbol, DefId> {
1014 if self.root.is_proc_macro_crate() {
1015 // Proc macro crates do not export any diagnostic-items to the target.
1021 .map(|(name, def_index)| (name, self.local_def_id(def_index)))
1026 /// Iterates over each child of the given item.
1027 fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
1029 F: FnMut(Export<hir::HirId>),
1031 if let Some(proc_macros_ids) = self.root.proc_macro_data.map(|d| d.decode(self)) {
1032 /* If we are loading as a proc macro, we want to return the view of this crate
1033 * as a proc macro crate.
1035 if id == CRATE_DEF_INDEX {
1036 for def_index in proc_macros_ids {
1037 let raw_macro = self.raw_proc_macro(def_index);
1039 DefKind::Macro(macro_kind(raw_macro)),
1040 self.local_def_id(def_index),
1042 let ident = self.item_ident(def_index, sess);
1046 vis: ty::Visibility::Public,
1047 span: self.get_span(def_index, sess),
1055 let kind = match self.maybe_kind(id) {
1060 // Iterate over all children.
1061 let macros_only = self.dep_kind.lock().macros_only();
1062 let children = self.root.tables.children.get(self, id).unwrap_or(Lazy::empty());
1063 for child_index in children.decode((self, sess)) {
1069 if let Some(child_kind) = self.maybe_kind(child_index) {
1071 EntryKind::MacroDef(..) => {}
1072 _ if macros_only => continue,
1076 // Hand off the item to the callback.
1078 // FIXME(eddyb) Don't encode these in children.
1079 EntryKind::ForeignMod => {
1080 let child_children = self
1084 .get(self, child_index)
1085 .unwrap_or(Lazy::empty());
1086 for child_index in child_children.decode((self, sess)) {
1087 let kind = self.def_kind(child_index);
1089 res: Res::Def(kind, self.local_def_id(child_index)),
1090 ident: self.item_ident(child_index, sess),
1091 vis: self.get_visibility(child_index),
1096 .get(self, child_index)
1098 .decode((self, sess)),
1103 EntryKind::Impl(_) => continue,
1108 let def_key = self.def_key(child_index);
1109 let span = self.get_span(child_index, sess);
1110 if def_key.disambiguated_data.data.get_opt_name().is_some() {
1111 let kind = self.def_kind(child_index);
1112 let ident = self.item_ident(child_index, sess);
1113 let vis = self.get_visibility(child_index);
1114 let def_id = self.local_def_id(child_index);
1115 let res = Res::Def(kind, def_id);
1116 callback(Export { res, ident, vis, span });
1117 // For non-re-export structs and variants add their constructors to children.
1118 // Re-export lists automatically contain constructors when necessary.
1120 DefKind::Struct => {
1121 if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
1122 let ctor_kind = self.get_ctor_kind(child_index);
1124 Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1125 let vis = self.get_visibility(ctor_def_id.index);
1126 callback(Export { res: ctor_res, vis, ident, span });
1129 DefKind::Variant => {
1130 // Braced variants, unlike structs, generate unusable names in
1131 // value namespace, they are reserved for possible future use.
1132 // It's ok to use the variant's id as a ctor id since an
1133 // error will be reported on any use of such resolution anyway.
1134 let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
1135 let ctor_kind = self.get_ctor_kind(child_index);
1137 Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
1138 let mut vis = self.get_visibility(ctor_def_id.index);
1139 if ctor_def_id == def_id && vis == ty::Visibility::Public {
1140 // For non-exhaustive variants lower the constructor visibility to
1141 // within the crate. We only need this for fictive constructors,
1142 // for other constructors correct visibilities
1143 // were already encoded in metadata.
1144 let attrs = self.get_item_attrs(def_id.index, sess);
1145 if sess.contains_name(&attrs, sym::non_exhaustive) {
1146 let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
1147 vis = ty::Visibility::Restricted(crate_def_id);
1150 callback(Export { res: ctor_res, ident, vis, span });
1158 if let EntryKind::Mod(data) = kind {
1159 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
1161 Res::Def(DefKind::Macro(..), _) => {}
1162 _ if macros_only => continue,
1170 fn is_item_mir_available(&self, id: DefIndex) -> bool {
1171 !self.is_proc_macro(id) && self.root.tables.mir.get(self, id).is_some()
1174 fn module_expansion(&self, id: DefIndex, sess: &Session) -> ExpnId {
1175 if let EntryKind::Mod(m) = self.kind(id) {
1176 m.decode((self, sess)).expansion
1178 panic!("Expected module, found {:?}", self.local_def_id(id))
1182 fn get_optimized_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> {
1187 .filter(|_| !self.is_proc_macro(id))
1188 .unwrap_or_else(|| {
1189 bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id))
1191 .decode((self, tcx))
1194 fn get_unused_generic_params(&self, id: DefIndex) -> FiniteBitSet<u32> {
1197 .unused_generic_params
1199 .filter(|_| !self.is_proc_macro(id))
1200 .map(|params| params.decode(self))
1201 .unwrap_or_default()
1204 fn get_promoted_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> IndexVec<Promoted, Body<'tcx>> {
1209 .filter(|_| !self.is_proc_macro(id))
1210 .unwrap_or_else(|| {
1211 bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id))
1213 .decode((self, tcx))
1216 fn mir_const_qualif(&self, id: DefIndex) -> mir::ConstQualifs {
1217 match self.kind(id) {
1218 EntryKind::AnonConst(qualif, _)
1219 | EntryKind::Const(qualif, _)
1220 | EntryKind::AssocConst(
1221 AssocContainer::ImplDefault
1222 | AssocContainer::ImplFinal
1223 | AssocContainer::TraitWithDefault,
1227 _ => bug!("mir_const_qualif: unexpected kind"),
1231 fn get_associated_item(&self, id: DefIndex, sess: &Session) -> ty::AssocItem {
1232 let def_key = self.def_key(id);
1233 let parent = self.local_def_id(def_key.parent.unwrap());
1234 let ident = self.item_ident(id, sess);
1236 let (kind, container, has_self) = match self.kind(id) {
1237 EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false),
1238 EntryKind::AssocFn(data) => {
1239 let data = data.decode(self);
1240 (ty::AssocKind::Fn, data.container, data.has_self)
1242 EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false),
1243 _ => bug!("cannot get associated-item of `{:?}`", def_key),
1249 vis: self.get_visibility(id),
1250 defaultness: container.defaultness(),
1251 def_id: self.local_def_id(id),
1252 container: container.with_def_id(parent),
1253 fn_has_self_parameter: has_self,
1257 fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
1258 self.root.tables.variances.get(self, id).unwrap_or(Lazy::empty()).decode(self).collect()
1261 fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
1262 match self.kind(node_id) {
1263 EntryKind::Struct(data, _) | EntryKind::Union(data, _) | EntryKind::Variant(data) => {
1264 data.decode(self).ctor_kind
1266 _ => CtorKind::Fictive,
1270 fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
1271 match self.kind(node_id) {
1272 EntryKind::Struct(data, _) => {
1273 data.decode(self).ctor.map(|index| self.local_def_id(index))
1275 EntryKind::Variant(data) => {
1276 data.decode(self).ctor.map(|index| self.local_def_id(index))
1282 fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Vec<ast::Attribute> {
1283 // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
1284 // we assume that someone passing in a tuple struct ctor is actually wanting to
1285 // look at the definition
1286 let def_key = self.def_key(node_id);
1287 let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
1288 def_key.parent.unwrap()
1297 .unwrap_or(Lazy::empty())
1298 .decode((self, sess))
1299 .collect::<Vec<_>>()
1302 fn get_struct_field_names(&self, id: DefIndex, sess: &Session) -> Vec<Spanned<Symbol>> {
1307 .unwrap_or(Lazy::empty())
1309 .map(|index| respan(self.get_span(index, sess), self.item_ident(index, sess).name))
1313 fn get_inherent_implementations_for_type(
1317 ) -> &'tcx [DefId] {
1318 tcx.arena.alloc_from_iter(
1323 .unwrap_or(Lazy::empty())
1325 .map(|index| self.local_def_id(index)),
1329 fn get_implementations_for_trait(
1332 filter: Option<DefId>,
1333 ) -> &'tcx [(DefId, Option<ty::fast_reject::SimplifiedType>)] {
1334 if self.root.is_proc_macro_crate() {
1335 // proc-macro crates export no trait impls.
1339 // Do a reverse lookup beforehand to avoid touching the crate_num
1340 // hash map in the loop below.
1341 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1342 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1343 Some(None) => return &[],
1347 if let Some(filter) = filter {
1348 if let Some(impls) = self.trait_impls.get(&filter) {
1349 tcx.arena.alloc_from_iter(
1350 impls.decode(self).map(|(idx, simplified_self_ty)| {
1351 (self.local_def_id(idx), simplified_self_ty)
1358 tcx.arena.alloc_from_iter(self.trait_impls.values().flat_map(|impls| {
1361 .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty))
1366 fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1367 let def_key = self.def_key(id);
1368 match def_key.disambiguated_data.data {
1369 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1370 // Not an associated item
1373 def_key.parent.and_then(|parent_index| match self.kind(parent_index) {
1374 EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)),
1379 fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLib> {
1380 if self.root.is_proc_macro_crate() {
1381 // Proc macro crates do not have any *target* native libraries.
1384 self.root.native_libraries.decode((self, sess)).collect()
1388 fn get_foreign_modules(&self, tcx: TyCtxt<'tcx>) -> &'tcx [ForeignModule] {
1389 if self.root.is_proc_macro_crate() {
1390 // Proc macro crates do not have any *target* foreign modules.
1393 tcx.arena.alloc_from_iter(self.root.foreign_modules.decode((self, tcx.sess)))
1397 fn get_dylib_dependency_formats(
1400 ) -> &'tcx [(CrateNum, LinkagePreference)] {
1401 tcx.arena.alloc_from_iter(
1402 self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| {
1403 let cnum = CrateNum::new(i + 1);
1404 link.map(|link| (self.cnum_map[cnum], link))
1409 fn get_missing_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] {
1410 if self.root.is_proc_macro_crate() {
1411 // Proc macro crates do not depend on any target weak lang-items.
1414 tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self))
1418 fn get_fn_param_names(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [Ident] {
1419 let param_names = match self.kind(id) {
1420 EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names,
1421 EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names,
1424 tcx.arena.alloc_from_iter(param_names.decode((self, tcx)))
1427 fn exported_symbols(
1430 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] {
1431 if self.root.is_proc_macro_crate() {
1432 // If this crate is a custom derive crate, then we're not even going to
1433 // link those in so we skip those crates.
1436 tcx.arena.alloc_from_iter(self.root.exported_symbols.decode((self, tcx)))
1440 fn get_rendered_const(&self, id: DefIndex) -> String {
1441 match self.kind(id) {
1442 EntryKind::AnonConst(_, data)
1443 | EntryKind::Const(_, data)
1444 | EntryKind::AssocConst(_, _, data) => data.decode(self).0,
1449 fn get_macro(&self, id: DefIndex, sess: &Session) -> MacroDef {
1450 match self.kind(id) {
1451 EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)),
1456 // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we
1457 // don't serialize constness for tuple variant and tuple struct constructors.
1458 fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1459 let constness = match self.kind(id) {
1460 EntryKind::AssocFn(data) => data.decode(self).fn_data.constness,
1461 EntryKind::Fn(data) => data.decode(self).constness,
1462 EntryKind::ForeignFn(data) => data.decode(self).constness,
1463 EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const,
1464 _ => hir::Constness::NotConst,
1466 constness == hir::Constness::Const
1469 fn asyncness(&self, id: DefIndex) -> hir::IsAsync {
1470 match self.kind(id) {
1471 EntryKind::Fn(data) => data.decode(self).asyncness,
1472 EntryKind::AssocFn(data) => data.decode(self).fn_data.asyncness,
1473 EntryKind::ForeignFn(data) => data.decode(self).asyncness,
1474 _ => bug!("asyncness: expected function kind"),
1478 fn is_foreign_item(&self, id: DefIndex) -> bool {
1479 match self.kind(id) {
1480 EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => {
1487 fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1488 match self.kind(id) {
1489 EntryKind::ImmStatic | EntryKind::ForeignImmStatic => Some(hir::Mutability::Not),
1490 EntryKind::MutStatic | EntryKind::ForeignMutStatic => Some(hir::Mutability::Mut),
1495 fn generator_kind(&self, id: DefIndex) -> Option<hir::GeneratorKind> {
1496 match self.kind(id) {
1497 EntryKind::Generator(data) => Some(data),
1502 fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
1503 self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx))
1507 fn def_key(&self, index: DefIndex) -> DefKey {
1508 *self.def_key_cache.lock().entry(index).or_insert_with(|| {
1509 let mut key = self.root.tables.def_keys.get(self, index).unwrap().decode(self);
1510 if self.is_proc_macro(index) {
1511 let name = self.raw_proc_macro(index).name();
1512 key.disambiguated_data.data = DefPathData::MacroNs(Symbol::intern(name));
1518 // Returns the path leading to the thing with this `id`.
1519 fn def_path(&self, id: DefIndex) -> DefPath {
1520 debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1521 DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1524 fn def_path_hash_unlocked(
1527 def_path_hashes: &mut FxHashMap<DefIndex, DefPathHash>,
1529 *def_path_hashes.entry(index).or_insert_with(|| {
1530 self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self)
1535 fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1536 let mut def_path_hashes = self.def_path_hash_cache.lock();
1537 self.def_path_hash_unlocked(index, &mut def_path_hashes)
1540 fn all_def_path_hashes_and_def_ids(&self) -> Vec<(DefPathHash, DefId)> {
1541 let mut def_path_hashes = self.def_path_hash_cache.lock();
1542 (0..self.num_def_ids())
1544 let index = DefIndex::from_usize(index);
1545 (self.def_path_hash_unlocked(index, &mut def_path_hashes), self.local_def_id(index))
1550 /// Get the `DepNodeIndex` corresponding this crate. The result of this
1551 /// method is cached in the `dep_node_index` field.
1552 fn get_crate_dep_node_index(&self, tcx: TyCtxt<'tcx>) -> DepNodeIndex {
1553 let mut dep_node_index = self.dep_node_index.load();
1555 if unlikely!(dep_node_index == DepNodeIndex::INVALID) {
1556 // We have not cached the DepNodeIndex for this upstream crate yet,
1557 // so use the dep-graph to find it out and cache it.
1558 // Note that multiple threads can enter this block concurrently.
1559 // That is fine because the DepNodeIndex remains constant
1560 // throughout the whole compilation session, and multiple stores
1561 // would always write the same value.
1563 let def_path_hash = self.def_path_hash(CRATE_DEF_INDEX);
1565 DepNode::from_def_path_hash(def_path_hash, dep_graph::DepKind::CrateMetadata);
1567 dep_node_index = tcx.dep_graph.dep_node_index_of(&dep_node);
1568 assert!(dep_node_index != DepNodeIndex::INVALID);
1569 self.dep_node_index.store(dep_node_index);
1575 /// Imports the source_map from an external crate into the source_map of the crate
1576 /// currently being compiled (the "local crate").
1578 /// The import algorithm works analogous to how AST items are inlined from an
1579 /// external crate's metadata:
1580 /// For every SourceFile in the external source_map an 'inline' copy is created in the
1581 /// local source_map. The correspondence relation between external and local
1582 /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1583 /// function. When an item from an external crate is later inlined into this
1584 /// crate, this correspondence information is used to translate the span
1585 /// information of the inlined item so that it refers the correct positions in
1586 /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1588 /// The import algorithm in the function below will reuse SourceFiles already
1589 /// existing in the local source_map. For example, even if the SourceFile of some
1590 /// source file of libstd gets imported many times, there will only ever be
1591 /// one SourceFile object for the corresponding file in the local source_map.
1593 /// Note that imported SourceFiles do not actually contain the source code of the
1594 /// file they represent, just information about length, line breaks, and
1595 /// multibyte characters. This information is enough to generate valid debuginfo
1596 /// for items inlined from other crates.
1598 /// Proc macro crates don't currently export spans, so this function does not have
1599 /// to work for them.
1600 fn imported_source_files(&self, sess: &Session) -> &'a [ImportedSourceFile] {
1601 // Translate the virtual `/rustc/$hash` prefix back to a real directory
1602 // that should hold actual sources, where possible.
1604 // NOTE: if you update this, you might need to also update bootstrap's code for generating
1605 // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`.
1606 let virtual_rust_source_base_dir = option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR")
1609 // Only spend time on further checks if we have what to translate *to*.
1610 sess.real_rust_source_base_dir.is_some()
1612 .filter(|virtual_dir| {
1613 // Don't translate away `/rustc/$hash` if we're still remapping to it,
1614 // since that means we're still building `std`/`rustc` that need it,
1615 // and we don't want the real path to leak into codegen/debuginfo.
1616 !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir)
1618 let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| {
1620 "try_to_translate_virtual_to_real(name={:?}): \
1621 virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}",
1622 name, virtual_rust_source_base_dir, sess.real_rust_source_base_dir,
1625 if let Some(virtual_dir) = virtual_rust_source_base_dir {
1626 if let Some(real_dir) = &sess.real_rust_source_base_dir {
1627 if let rustc_span::FileName::Real(old_name) = name {
1628 if let rustc_span::RealFileName::Named(one_path) = old_name {
1629 if let Ok(rest) = one_path.strip_prefix(virtual_dir) {
1630 let virtual_name = one_path.clone();
1632 // The std library crates are in
1633 // `$sysroot/lib/rustlib/src/rust/library`, whereas other crates
1634 // may be in `$sysroot/lib/rustlib/src/rust/` directly. So we
1635 // detect crates from the std libs and handle them specially.
1636 const STD_LIBS: &[&str] = &[
1646 "profiler_builtins",
1648 "rustc-std-workspace-core",
1649 "rustc-std-workspace-alloc",
1650 "rustc-std-workspace-std",
1653 let is_std_lib = STD_LIBS.iter().any(|l| rest.starts_with(l));
1655 let new_path = if is_std_lib {
1656 real_dir.join("library").join(rest)
1662 "try_to_translate_virtual_to_real: `{}` -> `{}`",
1663 virtual_name.display(),
1666 let new_name = rustc_span::RealFileName::Devirtualized {
1667 local_path: new_path,
1670 *old_name = new_name;
1678 self.cdata.source_map_import_info.get_or_init(|| {
1679 let external_source_map = self.root.source_map.decode(self);
1682 .map(|source_file_to_import| {
1683 // We can't reuse an existing SourceFile, so allocate a new one
1684 // containing the information we need.
1685 let rustc_span::SourceFile {
1692 mut multibyte_chars,
1693 mut non_narrow_chars,
1697 } = source_file_to_import;
1699 // If this file's path has been remapped to `/rustc/$hash`,
1700 // we might be able to reverse that (also see comments above,
1701 // on `try_to_translate_virtual_to_real`).
1702 // FIXME(eddyb) we could check `name_was_remapped` here,
1703 // but in practice it seems to be always `false`.
1704 try_to_translate_virtual_to_real(&mut name);
1706 let source_length = (end_pos - start_pos).to_usize();
1708 // Translate line-start positions and multibyte character
1709 // position into frame of reference local to file.
1710 // `SourceMap::new_imported_source_file()` will then translate those
1711 // coordinates to their new global frame of reference when the
1712 // offset of the SourceFile is known.
1713 for pos in &mut lines {
1714 *pos = *pos - start_pos;
1716 for mbc in &mut multibyte_chars {
1717 mbc.pos = mbc.pos - start_pos;
1719 for swc in &mut non_narrow_chars {
1720 *swc = *swc - start_pos;
1722 for np in &mut normalized_pos {
1723 np.pos = np.pos - start_pos;
1726 let local_version = sess.source_map().new_imported_source_file(
1741 "CrateMetaData::imported_source_files alloc \
1742 source_file {:?} original (start_pos {:?} end_pos {:?}) \
1743 translated (start_pos {:?} end_pos {:?})",
1747 local_version.start_pos,
1748 local_version.end_pos
1751 ImportedSourceFile {
1752 original_start_pos: start_pos,
1753 original_end_pos: end_pos,
1754 translated_source_file: local_version,
1762 impl CrateMetadata {
1766 root: CrateRoot<'static>,
1767 raw_proc_macros: Option<&'static [ProcMacro]>,
1769 cnum_map: CrateNumMap,
1770 dep_kind: CrateDepKind,
1771 source: CrateSource,
1773 host_hash: Option<Svh>,
1774 ) -> CrateMetadata {
1775 let trait_impls = root
1777 .decode((&blob, sess))
1778 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1780 let alloc_decoding_state =
1781 AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
1782 let dependencies = Lock::new(cnum_map.iter().cloned().collect());
1788 source_map_import_info: OnceCell::new(),
1789 alloc_decoding_state,
1790 dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
1794 dep_kind: Lock::new(dep_kind),
1798 extern_crate: Lock::new(None),
1799 hygiene_context: Default::default(),
1800 def_key_cache: Default::default(),
1801 def_path_hash_cache: Default::default(),
1805 crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
1806 self.dependencies.borrow()
1809 crate fn add_dependency(&self, cnum: CrateNum) {
1810 self.dependencies.borrow_mut().push(cnum);
1813 crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool {
1814 let mut extern_crate = self.extern_crate.borrow_mut();
1815 let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank);
1817 *extern_crate = Some(new_extern_crate);
1822 crate fn source(&self) -> &CrateSource {
1826 crate fn dep_kind(&self) -> CrateDepKind {
1827 *self.dep_kind.lock()
1830 crate fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) {
1831 self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
1834 crate fn panic_strategy(&self) -> PanicStrategy {
1835 self.root.panic_strategy
1838 crate fn needs_panic_runtime(&self) -> bool {
1839 self.root.needs_panic_runtime
1842 crate fn is_panic_runtime(&self) -> bool {
1843 self.root.panic_runtime
1846 crate fn is_profiler_runtime(&self) -> bool {
1847 self.root.profiler_runtime
1850 crate fn needs_allocator(&self) -> bool {
1851 self.root.needs_allocator
1854 crate fn has_global_allocator(&self) -> bool {
1855 self.root.has_global_allocator
1858 crate fn has_default_lib_allocator(&self) -> bool {
1859 self.root.has_default_lib_allocator
1862 crate fn is_proc_macro_crate(&self) -> bool {
1863 self.root.is_proc_macro_crate()
1866 crate fn name(&self) -> Symbol {
1870 crate fn disambiguator(&self) -> CrateDisambiguator {
1871 self.root.disambiguator
1874 crate fn hash(&self) -> Svh {
1878 fn num_def_ids(&self) -> usize {
1879 self.root.tables.def_keys.size()
1882 fn local_def_id(&self, index: DefIndex) -> DefId {
1883 DefId { krate: self.cnum, index }
1886 // Translate a DefId from the current compilation environment to a DefId
1887 // for an external crate.
1888 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1889 for (local, &global) in self.cnum_map.iter_enumerated() {
1890 if global == did.krate {
1891 return Some(DefId { krate: local, index: did.index });
1899 // Cannot be implemented on 'ProcMacro', as libproc_macro
1900 // does not depend on librustc_ast
1901 fn macro_kind(raw: &ProcMacro) -> MacroKind {
1903 ProcMacro::CustomDerive { .. } => MacroKind::Derive,
1904 ProcMacro::Attr { .. } => MacroKind::Attr,
1905 ProcMacro::Bang { .. } => MacroKind::Bang,