1 // Decoding metadata from a single crate's metadata
4 use crate::rmeta::table::{FixedSizeEncoding, Table};
6 use rustc_index::vec::{Idx, IndexVec};
7 use rustc_data_structures::sync::{Lrc, Lock, LockGuard, Once, AtomicCell};
8 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash};
9 use rustc::hir::map::definitions::DefPathTable;
11 use rustc::middle::cstore::{CrateSource, ExternCrate};
12 use rustc::middle::cstore::{LinkagePreference, NativeLibrary, ForeignModule};
13 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
14 use rustc::hir::def::{self, Res, DefKind, CtorOf, CtorKind};
15 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
16 use rustc_data_structures::fingerprint::Fingerprint;
17 use rustc_data_structures::fx::FxHashMap;
18 use rustc_data_structures::svh::Svh;
19 use rustc::dep_graph::{self, DepNodeIndex};
20 use rustc::middle::lang_items;
21 use rustc::mir::{self, interpret};
22 use rustc::mir::interpret::{AllocDecodingSession, AllocDecodingState};
23 use rustc::session::Session;
24 use rustc::ty::{self, Ty, TyCtxt};
25 use rustc::ty::codec::TyDecoder;
26 use rustc::mir::{Body, Promoted};
27 use rustc::util::common::record_time;
28 use rustc::util::captures::Captures;
32 use std::num::NonZeroUsize;
35 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
37 use syntax::ast::{self, Ident};
38 use syntax::source_map::{self, respan, Spanned};
39 use syntax_expand::base::{SyntaxExtensionKind, SyntaxExtension};
40 use syntax_expand::proc_macro::{AttrProcMacro, ProcMacroDerive, BangProcMacro};
41 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, hygiene::MacroKind};
42 use syntax_pos::symbol::{Symbol, sym};
44 use proc_macro::bridge::client::ProcMacro;
46 pub use cstore_impl::{provide, provide_extern};
50 crate struct MetadataBlob(MetadataRef);
52 // A map from external crate numbers (as decoded from some crate file) to
53 // local crate numbers (as generated during this session). Each external
54 // crate may refer to types in other external crates, and each has their
56 crate type CrateNumMap = IndexVec<CrateNum, CrateNum>;
58 crate struct CrateMetadata {
59 /// The primary crate data - binary metadata blob.
62 // --- Some data pre-decoded from the metadata blob, usually for performance ---
64 /// Properties of the whole crate.
65 /// NOTE(eddyb) we pass `'static` to a `'tcx` parameter because this
66 /// lifetime is only used behind `Lazy`, and therefore acts like an
67 /// universal (`for<'tcx>`), that is paired up with whichever `TyCtxt`
68 /// is being used to decode those values.
69 root: CrateRoot<'static>,
70 /// For each definition in this crate, we encode a key. When the
71 /// crate is loaded, we read all the keys and put them in this
72 /// hashmap, which gives the reverse mapping. This allows us to
73 /// quickly retrace a `DefPath`, which is needed for incremental
74 /// compilation support.
75 def_path_table: DefPathTable,
77 /// FIXME: Used only from queries and can use query cache,
78 /// so pre-decoding can probably be avoided.
79 trait_impls: FxHashMap<(u32, DefIndex), Lazy<[DefIndex]>>,
80 /// Proc macro descriptions for this crate, if it's a proc macro crate.
81 raw_proc_macros: Option<&'static [ProcMacro]>,
82 /// Source maps for code from the crate.
83 source_map_import_info: Once<Vec<ImportedSourceFile>>,
84 /// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
85 alloc_decoding_state: AllocDecodingState,
86 /// The `DepNodeIndex` of the `DepNode` representing this upstream crate.
87 /// It is initialized on the first access in `get_crate_dep_node_index()`.
88 /// Do not access the value directly, as it might not have been initialized yet.
89 /// The field must always be initialized to `DepNodeIndex::INVALID`.
90 dep_node_index: AtomicCell<DepNodeIndex>,
92 // --- Other significant crate properties ---
94 /// ID of this crate, from the current compilation session's point of view.
96 /// Maps crate IDs as they are were seen from this crate's compilation sessions into
97 /// IDs as they are seen from the current compilation session.
98 cnum_map: CrateNumMap,
99 /// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
100 dependencies: Lock<Vec<CrateNum>>,
101 /// How to link (or not link) this crate to the currently compiled crate.
102 dep_kind: Lock<DepKind>,
103 /// Filesystem location of this crate.
105 /// Whether or not this crate should be consider a private dependency
106 /// for purposes of the 'exported_private_dependencies' lint
108 /// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
109 host_hash: Option<Svh>,
111 // --- Data used only for improving diagnostics ---
113 /// Information about the `extern crate` item or path that caused this crate to be loaded.
114 /// If this is `None`, then the crate was injected (e.g., by the allocator).
115 extern_crate: Lock<Option<ExternCrate>>,
118 /// Holds information about a syntax_pos::SourceFile imported from another crate.
119 /// See `imported_source_files()` for more information.
120 struct ImportedSourceFile {
121 /// This SourceFile's byte-offset within the source_map of its original crate
122 original_start_pos: syntax_pos::BytePos,
123 /// The end of this SourceFile within the source_map of its original crate
124 original_end_pos: syntax_pos::BytePos,
125 /// The imported SourceFile's representation within the local source_map
126 translated_source_file: Lrc<syntax_pos::SourceFile>,
129 pub(super) struct DecodeContext<'a, 'tcx> {
130 opaque: opaque::Decoder<'a>,
131 cdata: Option<&'a CrateMetadata>,
132 sess: Option<&'tcx Session>,
133 tcx: Option<TyCtxt<'tcx>>,
135 // Cache the last used source_file for translating spans as an optimization.
136 last_source_file_index: usize,
138 lazy_state: LazyState,
140 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
141 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
144 /// Abstract over the various ways one can create metadata decoders.
145 pub(super) trait Metadata<'a, 'tcx>: Copy {
146 fn raw_bytes(self) -> &'a [u8];
147 fn cdata(self) -> Option<&'a CrateMetadata> { None }
148 fn sess(self) -> Option<&'tcx Session> { None }
149 fn tcx(self) -> Option<TyCtxt<'tcx>> { None }
151 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
152 let tcx = self.tcx();
154 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
156 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
158 last_source_file_index: 0,
159 lazy_state: LazyState::NoNode,
160 alloc_decoding_session: self.cdata().map(|cdata| {
161 cdata.alloc_decoding_state.new_decoding_session()
167 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
168 fn raw_bytes(self) -> &'a [u8] {
174 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
175 fn raw_bytes(self) -> &'a [u8] {
176 let (blob, _) = self;
180 fn sess(self) -> Option<&'tcx Session> {
181 let (_, sess) = self;
187 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
188 fn raw_bytes(self) -> &'a [u8] {
189 self.blob.raw_bytes()
191 fn cdata(self) -> Option<&'a CrateMetadata> {
196 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'tcx Session) {
197 fn raw_bytes(self) -> &'a [u8] {
200 fn cdata(self) -> Option<&'a CrateMetadata> {
203 fn sess(self) -> Option<&'tcx Session> {
208 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'tcx>) {
209 fn raw_bytes(self) -> &'a [u8] {
212 fn cdata(self) -> Option<&'a CrateMetadata> {
215 fn tcx(self) -> Option<TyCtxt<'tcx>> {
220 impl<'a, 'tcx, T: Decodable> Lazy<T> {
221 fn decode<M: Metadata<'a, 'tcx>>(self, metadata: M) -> T {
222 let mut dcx = metadata.decoder(self.position.get());
223 dcx.lazy_state = LazyState::NodeStart(self.position);
224 T::decode(&mut dcx).unwrap()
228 impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable> Lazy<[T]> {
229 fn decode<M: Metadata<'a, 'tcx>>(
232 ) -> impl ExactSizeIterator<Item = T> + Captures<'a> + Captures<'tcx> + 'x {
233 let mut dcx = metadata.decoder(self.position.get());
234 dcx.lazy_state = LazyState::NodeStart(self.position);
235 (0..self.meta).map(move |_| T::decode(&mut dcx).unwrap())
239 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
240 fn tcx(&self) -> TyCtxt<'tcx> {
241 self.tcx.expect("missing TyCtxt in DecodeContext")
244 fn cdata(&self) -> &'a CrateMetadata {
245 self.cdata.expect("missing CrateMetadata in DecodeContext")
248 fn read_lazy_with_meta<T: ?Sized + LazyMeta>(
251 ) -> Result<Lazy<T>, <Self as Decoder>::Error> {
252 let min_size = T::min_size(meta);
253 let distance = self.read_usize()?;
254 let position = match self.lazy_state {
255 LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
256 LazyState::NodeStart(start) => {
257 let start = start.get();
258 assert!(distance + min_size <= start);
259 start - distance - min_size
261 LazyState::Previous(last_min_end) => last_min_end.get() + distance,
263 self.lazy_state = LazyState::Previous(NonZeroUsize::new(position + min_size).unwrap());
264 Ok(Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta))
268 impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> {
270 fn tcx(&self) -> TyCtxt<'tcx> {
271 self.tcx.expect("missing TyCtxt in DecodeContext")
275 fn peek_byte(&self) -> u8 {
276 self.opaque.data[self.opaque.position()]
280 fn position(&self) -> usize {
281 self.opaque.position()
284 fn cached_ty_for_shorthand<F>(&mut self,
287 -> Result<Ty<'tcx>, Self::Error>
288 where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>
290 let tcx = self.tcx();
292 let key = ty::CReaderCacheKey {
293 cnum: self.cdata().cnum,
297 if let Some(&ty) = tcx.rcache.borrow().get(&key) {
301 let ty = or_insert_with(self)?;
302 tcx.rcache.borrow_mut().insert(key, ty);
306 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
307 where F: FnOnce(&mut Self) -> R
309 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
310 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
311 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
313 self.opaque = old_opaque;
314 self.lazy_state = old_state;
318 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
319 if cnum == LOCAL_CRATE {
322 self.cdata().cnum_map[cnum]
327 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
328 fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
329 self.read_lazy_with_meta(())
333 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<[T]>> for DecodeContext<'a, 'tcx> {
334 fn specialized_decode(&mut self) -> Result<Lazy<[T]>, Self::Error> {
335 let len = self.read_usize()?;
339 self.read_lazy_with_meta(len)
344 impl<'a, 'tcx, I: Idx, T> SpecializedDecoder<Lazy<Table<I, T>>> for DecodeContext<'a, 'tcx>
345 where Option<T>: FixedSizeEncoding,
347 fn specialized_decode(&mut self) -> Result<Lazy<Table<I, T>>, Self::Error> {
348 let len = self.read_usize()?;
349 self.read_lazy_with_meta(len)
353 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
355 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
356 let krate = CrateNum::decode(self)?;
357 let index = DefIndex::decode(self)?;
366 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
368 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
369 Ok(DefIndex::from_u32(self.read_u32()?))
373 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for DecodeContext<'a, 'tcx> {
375 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
376 self.specialized_decode().map(|i| LocalDefId::from_def_id(i))
380 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
381 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
382 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
383 alloc_decoding_session.decode_alloc_id(self)
385 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
390 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
391 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
392 let tag = u8::decode(self)?;
394 if tag == TAG_INVALID_SPAN {
398 debug_assert_eq!(tag, TAG_VALID_SPAN);
400 let lo = BytePos::decode(self)?;
401 let len = BytePos::decode(self)?;
404 let sess = if let Some(sess) = self.sess {
407 bug!("Cannot decode Span without Session.")
410 let imported_source_files = self.cdata().imported_source_files(&sess.source_map());
412 // Optimize for the case that most spans within a translated item
413 // originate from the same source_file.
414 let last_source_file = &imported_source_files[self.last_source_file_index];
416 if lo >= last_source_file.original_start_pos &&
417 lo <= last_source_file.original_end_pos {
421 let mut b = imported_source_files.len();
425 if imported_source_files[m].original_start_pos > lo {
432 self.last_source_file_index = a;
433 &imported_source_files[a]
437 // Make sure our binary search above is correct.
438 debug_assert!(lo >= source_file.original_start_pos &&
439 lo <= source_file.original_end_pos);
441 // Make sure we correctly filtered out invalid spans during encoding
442 debug_assert!(hi >= source_file.original_start_pos &&
443 hi <= source_file.original_end_pos);
445 let lo = (lo + source_file.translated_source_file.start_pos)
446 - source_file.original_start_pos;
447 let hi = (hi + source_file.translated_source_file.start_pos)
448 - source_file.original_start_pos;
450 Ok(Span::with_root_ctxt(lo, hi))
454 impl SpecializedDecoder<Ident> for DecodeContext<'_, '_> {
455 fn specialized_decode(&mut self) -> Result<Ident, Self::Error> {
456 // FIXME(jseyfried): intercrate hygiene
458 Ok(Ident::with_dummy_span(Symbol::decode(self)?))
462 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
463 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
464 Fingerprint::decode_opaque(&mut self.opaque)
468 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
469 for DecodeContext<'a, 'tcx> {
471 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
472 Ok(mir::ClearCrossCrate::Clear)
476 implement_ty_decoder!( DecodeContext<'a, 'tcx> );
479 crate fn new(metadata_ref: MetadataRef) -> MetadataBlob {
480 MetadataBlob(metadata_ref)
483 crate fn is_compatible(&self) -> bool {
484 self.raw_bytes().starts_with(METADATA_HEADER)
487 crate fn get_rustc_version(&self) -> String {
488 Lazy::<String>::from_position(
489 NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap(),
493 crate fn get_root(&self) -> CrateRoot<'tcx> {
494 let slice = self.raw_bytes();
495 let offset = METADATA_HEADER.len();
496 let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
497 ((slice[offset + 2] as u32) << 8) |
498 ((slice[offset + 3] as u32) << 0)) as usize;
499 Lazy::<CrateRoot<'tcx>>::from_position(
500 NonZeroUsize::new(pos).unwrap(),
504 crate fn list_crate_metadata(&self,
505 out: &mut dyn io::Write) -> io::Result<()> {
506 write!(out, "=External Dependencies=\n")?;
507 let root = self.get_root();
508 for (i, dep) in root.crate_deps
511 write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
518 impl<'tcx> EntryKind<'tcx> {
519 fn def_kind(&self) -> Option<DefKind> {
521 EntryKind::Const(..) => DefKind::Const,
522 EntryKind::AssocConst(..) => DefKind::AssocConst,
523 EntryKind::ImmStatic |
524 EntryKind::MutStatic |
525 EntryKind::ForeignImmStatic |
526 EntryKind::ForeignMutStatic => DefKind::Static,
527 EntryKind::Struct(_, _) => DefKind::Struct,
528 EntryKind::Union(_, _) => DefKind::Union,
530 EntryKind::ForeignFn(_) => DefKind::Fn,
531 EntryKind::Method(_) => DefKind::Method,
532 EntryKind::Type => DefKind::TyAlias,
533 EntryKind::TypeParam => DefKind::TyParam,
534 EntryKind::ConstParam => DefKind::ConstParam,
535 EntryKind::OpaqueTy => DefKind::OpaqueTy,
536 EntryKind::AssocType(_) => DefKind::AssocTy,
537 EntryKind::AssocOpaqueTy(_) => DefKind::AssocOpaqueTy,
538 EntryKind::Mod(_) => DefKind::Mod,
539 EntryKind::Variant(_) => DefKind::Variant,
540 EntryKind::Trait(_) => DefKind::Trait,
541 EntryKind::TraitAlias => DefKind::TraitAlias,
542 EntryKind::Enum(..) => DefKind::Enum,
543 EntryKind::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
544 EntryKind::ForeignType => DefKind::ForeignTy,
546 EntryKind::ForeignMod |
547 EntryKind::GlobalAsm |
550 EntryKind::Generator(_) |
551 EntryKind::Closure => return None,
557 crate fn is_proc_macro_crate(&self) -> bool {
558 self.proc_macro_data.is_some()
561 crate fn name(&self) -> Symbol {
565 crate fn disambiguator(&self) -> CrateDisambiguator {
569 crate fn hash(&self) -> Svh {
573 crate fn triple(&self) -> &TargetTriple {
577 crate fn decode_crate_deps(
579 metadata: &'a MetadataBlob,
580 ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
581 self.crate_deps.decode(metadata)
585 impl<'a, 'tcx> CrateMetadata {
589 root: CrateRoot<'static>,
590 raw_proc_macros: Option<&'static [ProcMacro]>,
592 cnum_map: CrateNumMap,
596 host_hash: Option<Svh>,
598 let def_path_table = record_time(&sess.perf_stats.decode_def_path_tables_time, || {
599 root.def_path_table.decode((&blob, sess))
601 let trait_impls = root.impls.decode((&blob, sess))
602 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls)).collect();
603 let alloc_decoding_state =
604 AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
605 let dependencies = Lock::new(cnum_map.iter().cloned().collect());
612 source_map_import_info: Once::new(),
613 alloc_decoding_state,
614 dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
618 dep_kind: Lock::new(dep_kind),
622 extern_crate: Lock::new(None),
626 fn is_proc_macro(&self, id: DefIndex) -> bool {
627 self.root.proc_macro_data.and_then(|data| data.decode(self).find(|x| *x == id)).is_some()
630 fn maybe_kind(&self, item_id: DefIndex) -> Option<EntryKind<'tcx>> {
631 self.root.per_def.kind.get(self, item_id).map(|k| k.decode(self))
634 fn kind(&self, item_id: DefIndex) -> EntryKind<'tcx> {
635 assert!(!self.is_proc_macro(item_id));
636 self.maybe_kind(item_id).unwrap_or_else(|| {
638 "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}",
646 fn local_def_id(&self, index: DefIndex) -> DefId {
653 fn raw_proc_macro(&self, id: DefIndex) -> &ProcMacro {
654 // DefIndex's in root.proc_macro_data have a one-to-one correspondence
655 // with items in 'raw_proc_macros'.
656 // NOTE: If you update the order of macros in 'proc_macro_data' for any reason,
657 // you must also update src/libsyntax_ext/proc_macro_harness.rs
658 // Failing to do so will result in incorrect data being associated
659 // with proc macros when deserialized.
660 let pos = self.root.proc_macro_data.unwrap().decode(self).position(|i| i == id).unwrap();
661 &self.raw_proc_macros.unwrap()[pos]
664 fn item_name(&self, item_index: DefIndex) -> Symbol {
665 if !self.is_proc_macro(item_index) {
666 self.def_key(item_index)
670 .expect("no name in item_name")
672 Symbol::intern(self.raw_proc_macro(item_index).name())
676 fn def_kind(&self, index: DefIndex) -> Option<DefKind> {
677 if !self.is_proc_macro(index) {
678 self.kind(index).def_kind()
681 macro_kind(self.raw_proc_macro(index))
686 fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
687 self.root.per_def.span.get(self, index).unwrap().decode((self, sess))
690 fn load_proc_macro(&self, id: DefIndex, sess: &Session) -> SyntaxExtension {
691 let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
692 ProcMacro::CustomDerive { trait_name, attributes, client } => {
694 attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
697 SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
701 ProcMacro::Attr { name, client } => (
702 name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new()
704 ProcMacro::Bang { name, client } => (
705 name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new()
709 SyntaxExtension::new(
712 self.get_span(id, sess),
715 Symbol::intern(name),
716 &self.get_item_attrs(id, sess),
720 fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
721 match self.kind(item_id) {
722 EntryKind::Trait(data) => {
723 let data = data.decode((self, sess));
724 ty::TraitDef::new(self.local_def_id(item_id),
729 self.def_path_table.def_path_hash(item_id))
731 EntryKind::TraitAlias => {
732 ty::TraitDef::new(self.local_def_id(item_id),
733 hir::Unsafety::Normal,
737 self.def_path_table.def_path_hash(item_id))
739 _ => bug!("def-index does not refer to trait or trait alias"),
746 kind: &EntryKind<'_>,
749 ) -> ty::VariantDef {
750 let data = match kind {
751 EntryKind::Variant(data) |
752 EntryKind::Struct(data, _) |
753 EntryKind::Union(data, _) => data.decode(self),
757 let adt_kind = match kind {
758 EntryKind::Variant(_) => ty::AdtKind::Enum,
759 EntryKind::Struct(..) => ty::AdtKind::Struct,
760 EntryKind::Union(..) => ty::AdtKind::Union,
764 let variant_did = if adt_kind == ty::AdtKind::Enum {
765 Some(self.local_def_id(index))
769 let ctor_did = data.ctor.map(|index| self.local_def_id(index));
773 Ident::with_dummy_span(self.item_name(index)),
777 self.root.per_def.children.get(self, index).unwrap_or(Lazy::empty())
778 .decode(self).map(|index| ty::FieldDef {
779 did: self.local_def_id(index),
780 ident: Ident::with_dummy_span(self.item_name(index)),
781 vis: self.get_visibility(index),
790 fn get_adt_def(&self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef {
791 let kind = self.kind(item_id);
792 let did = self.local_def_id(item_id);
794 let (adt_kind, repr) = match kind {
795 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
796 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
797 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
798 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
801 let variants = if let ty::AdtKind::Enum = adt_kind {
802 self.root.per_def.children.get(self, item_id).unwrap_or(Lazy::empty())
805 self.get_variant(tcx, &self.kind(index), index, did)
809 std::iter::once(self.get_variant(tcx, &kind, item_id, did)).collect()
812 tcx.alloc_adt_def(did, adt_kind, variants, repr)
815 fn get_explicit_predicates(
819 ) -> ty::GenericPredicates<'tcx> {
820 self.root.per_def.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx))
823 fn get_inferred_outlives(
827 ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
828 self.root.per_def.inferred_outlives.get(self, item_id).map(|predicates| {
829 predicates.decode((self, tcx))
830 }).unwrap_or_default()
833 fn get_super_predicates(
837 ) -> ty::GenericPredicates<'tcx> {
838 self.root.per_def.super_predicates.get(self, item_id).unwrap().decode((self, tcx))
841 fn get_generics(&self, item_id: DefIndex, sess: &Session) -> ty::Generics {
842 self.root.per_def.generics.get(self, item_id).unwrap().decode((self, sess))
845 fn get_type(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
846 self.root.per_def.ty.get(self, id).unwrap().decode((self, tcx))
849 fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
850 match self.is_proc_macro(id) {
851 true => self.root.proc_macro_stability.clone(),
852 false => self.root.per_def.stability.get(self, id).map(|stab| stab.decode(self)),
856 fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
857 self.root.per_def.deprecation.get(self, id)
858 .filter(|_| !self.is_proc_macro(id))
859 .map(|depr| depr.decode(self))
862 fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
863 match self.is_proc_macro(id) {
864 true => ty::Visibility::Public,
865 false => self.root.per_def.visibility.get(self, id).unwrap().decode(self),
869 fn get_impl_data(&self, id: DefIndex) -> ImplData {
870 match self.kind(id) {
871 EntryKind::Impl(data) => data.decode(self),
876 fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
877 self.get_impl_data(id).parent_impl
880 fn get_impl_polarity(&self, id: DefIndex) -> ty::ImplPolarity {
881 self.get_impl_data(id).polarity
884 fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
885 self.get_impl_data(id).defaultness
888 fn get_coerce_unsized_info(
891 ) -> Option<ty::adjustment::CoerceUnsizedInfo> {
892 self.get_impl_data(id).coerce_unsized_info
895 fn get_impl_trait(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option<ty::TraitRef<'tcx>> {
896 self.root.per_def.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx)))
899 /// Iterates over all the stability attributes in the given crate.
900 fn get_lib_features(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(ast::Name, Option<ast::Name>)] {
901 // FIXME: For a proc macro crate, not sure whether we should return the "host"
902 // features or an empty Vec. Both don't cause ICEs.
903 tcx.arena.alloc_from_iter(self.root
908 /// Iterates over the language items in the given crate.
909 fn get_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] {
910 if self.root.is_proc_macro_crate() {
911 // Proc macro crates do not export any lang-items to the target.
914 tcx.arena.alloc_from_iter(self.root
917 .map(|(def_index, index)| (self.local_def_id(def_index), index)))
921 /// Iterates over the diagnostic items in the given crate.
922 fn get_diagnostic_items(
925 ) -> &'tcx FxHashMap<Symbol, DefId> {
926 tcx.arena.alloc(if self.root.is_proc_macro_crate() {
927 // Proc macro crates do not export any diagnostic-items to the target.
933 .map(|(name, def_index)| (name, self.local_def_id(def_index)))
938 /// Iterates over each child of the given item.
939 fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
940 where F: FnMut(def::Export<hir::HirId>)
942 if let Some(proc_macros_ids) = self.root.proc_macro_data.map(|d| d.decode(self)) {
943 /* If we are loading as a proc macro, we want to return the view of this crate
944 * as a proc macro crate.
946 if id == CRATE_DEF_INDEX {
947 for def_index in proc_macros_ids {
948 let raw_macro = self.raw_proc_macro(def_index);
950 DefKind::Macro(macro_kind(raw_macro)),
951 self.local_def_id(def_index),
953 let ident = Ident::from_str(raw_macro.name());
954 callback(def::Export {
957 vis: ty::Visibility::Public,
966 let kind = match self.maybe_kind(id) {
971 // Iterate over all children.
972 let macros_only = self.dep_kind.lock().macros_only();
973 let children = self.root.per_def.children.get(self, id).unwrap_or(Lazy::empty());
974 for child_index in children.decode((self, sess)) {
980 if let Some(child_kind) = self.maybe_kind(child_index) {
982 EntryKind::MacroDef(..) => {}
983 _ if macros_only => continue,
987 // Hand off the item to the callback.
989 // FIXME(eddyb) Don't encode these in children.
990 EntryKind::ForeignMod => {
992 self.root.per_def.children.get(self, child_index)
993 .unwrap_or(Lazy::empty());
994 for child_index in child_children.decode((self, sess)) {
995 if let Some(kind) = self.def_kind(child_index) {
996 callback(def::Export {
997 res: Res::Def(kind, self.local_def_id(child_index)),
998 ident: Ident::with_dummy_span(self.item_name(child_index)),
999 vis: self.get_visibility(child_index),
1000 span: self.root.per_def.span.get(self, child_index).unwrap()
1001 .decode((self, sess)),
1007 EntryKind::Impl(_) => continue,
1012 let def_key = self.def_key(child_index);
1013 let span = self.get_span(child_index, sess);
1014 if let (Some(kind), Some(name)) =
1015 (self.def_kind(child_index), def_key.disambiguated_data.data.get_opt_name()) {
1016 let ident = Ident::with_dummy_span(name);
1017 let vis = self.get_visibility(child_index);
1018 let def_id = self.local_def_id(child_index);
1019 let res = Res::Def(kind, def_id);
1020 callback(def::Export { res, ident, vis, span });
1021 // For non-re-export structs and variants add their constructors to children.
1022 // Re-export lists automatically contain constructors when necessary.
1024 DefKind::Struct => {
1025 if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
1026 let ctor_kind = self.get_ctor_kind(child_index);
1027 let ctor_res = Res::Def(
1028 DefKind::Ctor(CtorOf::Struct, ctor_kind),
1031 let vis = self.get_visibility(ctor_def_id.index);
1032 callback(def::Export { res: ctor_res, vis, ident, span });
1035 DefKind::Variant => {
1036 // Braced variants, unlike structs, generate unusable names in
1037 // value namespace, they are reserved for possible future use.
1038 // It's ok to use the variant's id as a ctor id since an
1039 // error will be reported on any use of such resolution anyway.
1040 let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
1041 let ctor_kind = self.get_ctor_kind(child_index);
1042 let ctor_res = Res::Def(
1043 DefKind::Ctor(CtorOf::Variant, ctor_kind),
1046 let mut vis = self.get_visibility(ctor_def_id.index);
1047 if ctor_def_id == def_id && vis == ty::Visibility::Public {
1048 // For non-exhaustive variants lower the constructor visibility to
1049 // within the crate. We only need this for fictive constructors,
1050 // for other constructors correct visibilities
1051 // were already encoded in metadata.
1052 let attrs = self.get_item_attrs(def_id.index, sess);
1053 if attr::contains_name(&attrs, sym::non_exhaustive) {
1054 let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
1055 vis = ty::Visibility::Restricted(crate_def_id);
1058 callback(def::Export { res: ctor_res, ident, vis, span });
1066 if let EntryKind::Mod(data) = kind {
1067 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
1069 Res::Def(DefKind::Macro(..), _) => {}
1070 _ if macros_only => continue,
1078 fn is_item_mir_available(&self, id: DefIndex) -> bool {
1079 !self.is_proc_macro(id) &&
1080 self.root.per_def.mir.get(self, id).is_some()
1083 fn get_optimized_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> {
1084 self.root.per_def.mir.get(self, id)
1085 .filter(|_| !self.is_proc_macro(id))
1086 .unwrap_or_else(|| {
1087 bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id))
1089 .decode((self, tcx))
1092 fn get_promoted_mir(
1096 ) -> IndexVec<Promoted, Body<'tcx>> {
1097 self.root.per_def.promoted_mir.get(self, id)
1098 .filter(|_| !self.is_proc_macro(id))
1099 .unwrap_or_else(|| {
1100 bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id))
1102 .decode((self, tcx))
1105 fn mir_const_qualif(&self, id: DefIndex) -> mir::ConstQualifs {
1106 match self.kind(id) {
1107 EntryKind::Const(qualif, _) |
1108 EntryKind::AssocConst(AssocContainer::ImplDefault, qualif, _) |
1109 EntryKind::AssocConst(AssocContainer::ImplFinal, qualif, _) => {
1116 fn get_associated_item(&self, id: DefIndex) -> ty::AssocItem {
1117 let def_key = self.def_key(id);
1118 let parent = self.local_def_id(def_key.parent.unwrap());
1119 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
1121 let (kind, container, has_self) = match self.kind(id) {
1122 EntryKind::AssocConst(container, _, _) => {
1123 (ty::AssocKind::Const, container, false)
1125 EntryKind::Method(data) => {
1126 let data = data.decode(self);
1127 (ty::AssocKind::Method, data.container, data.has_self)
1129 EntryKind::AssocType(container) => {
1130 (ty::AssocKind::Type, container, false)
1132 EntryKind::AssocOpaqueTy(container) => {
1133 (ty::AssocKind::OpaqueTy, container, false)
1135 _ => bug!("cannot get associated-item of `{:?}`", def_key)
1139 ident: Ident::with_dummy_span(name),
1141 vis: self.get_visibility(id),
1142 defaultness: container.defaultness(),
1143 def_id: self.local_def_id(id),
1144 container: container.with_def_id(parent),
1145 method_has_self_argument: has_self
1149 fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
1150 self.root.per_def.variances.get(self, id).unwrap_or(Lazy::empty())
1151 .decode(self).collect()
1154 fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
1155 match self.kind(node_id) {
1156 EntryKind::Struct(data, _) |
1157 EntryKind::Union(data, _) |
1158 EntryKind::Variant(data) => data.decode(self).ctor_kind,
1159 _ => CtorKind::Fictive,
1163 fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
1164 match self.kind(node_id) {
1165 EntryKind::Struct(data, _) => {
1166 data.decode(self).ctor.map(|index| self.local_def_id(index))
1168 EntryKind::Variant(data) => {
1169 data.decode(self).ctor.map(|index| self.local_def_id(index))
1175 fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
1176 // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
1177 // we assume that someone passing in a tuple struct ctor is actually wanting to
1178 // look at the definition
1179 let def_key = self.def_key(node_id);
1180 let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
1181 def_key.parent.unwrap()
1186 Lrc::from(self.root.per_def.attributes.get(self, item_id).unwrap_or(Lazy::empty())
1187 .decode((self, sess))
1188 .collect::<Vec<_>>())
1191 fn get_struct_field_names(
1195 ) -> Vec<Spanned<ast::Name>> {
1196 self.root.per_def.children.get(self, id).unwrap_or(Lazy::empty())
1198 .map(|index| respan(self.get_span(index, sess), self.item_name(index)))
1202 // Translate a DefId from the current compilation environment to a DefId
1203 // for an external crate.
1204 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1205 for (local, &global) in self.cnum_map.iter_enumerated() {
1206 if global == did.krate {
1217 fn get_inherent_implementations_for_type(
1221 ) -> &'tcx [DefId] {
1222 tcx.arena.alloc_from_iter(
1223 self.root.per_def.inherent_impls.get(self, id).unwrap_or(Lazy::empty())
1225 .map(|index| self.local_def_id(index))
1229 fn get_implementations_for_trait(
1232 filter: Option<DefId>,
1233 ) -> &'tcx [DefId] {
1234 if self.root.is_proc_macro_crate() {
1235 // proc-macro crates export no trait impls.
1239 // Do a reverse lookup beforehand to avoid touching the crate_num
1240 // hash map in the loop below.
1241 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1242 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1243 Some(None) => return &[],
1247 if let Some(filter) = filter {
1248 if let Some(impls) = self.trait_impls.get(&filter) {
1249 tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx)))
1254 tcx.arena.alloc_from_iter(self.trait_impls.values().flat_map(|impls| {
1255 impls.decode(self).map(|idx| self.local_def_id(idx))
1260 fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1261 let def_key = self.def_key(id);
1262 match def_key.disambiguated_data.data {
1263 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1264 // Not an associated item
1267 def_key.parent.and_then(|parent_index| {
1268 match self.kind(parent_index) {
1269 EntryKind::Trait(_) |
1270 EntryKind::TraitAlias => Some(self.local_def_id(parent_index)),
1277 fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1278 if self.root.is_proc_macro_crate() {
1279 // Proc macro crates do not have any *target* native libraries.
1282 self.root.native_libraries.decode((self, sess)).collect()
1286 fn get_foreign_modules(&self, tcx: TyCtxt<'tcx>) -> &'tcx [ForeignModule] {
1287 if self.root.is_proc_macro_crate() {
1288 // Proc macro crates do not have any *target* foreign modules.
1291 tcx.arena.alloc_from_iter(self.root.foreign_modules.decode((self, tcx.sess)))
1295 fn get_dylib_dependency_formats(
1298 ) -> &'tcx [(CrateNum, LinkagePreference)] {
1299 tcx.arena.alloc_from_iter(self.root
1300 .dylib_dependency_formats
1303 .flat_map(|(i, link)| {
1304 let cnum = CrateNum::new(i + 1);
1305 link.map(|link| (self.cnum_map[cnum], link))
1309 fn get_missing_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] {
1310 if self.root.is_proc_macro_crate() {
1311 // Proc macro crates do not depend on any target weak lang-items.
1314 tcx.arena.alloc_from_iter(self.root
1320 fn get_fn_param_names(&self, id: DefIndex) -> Vec<ast::Name> {
1321 let param_names = match self.kind(id) {
1322 EntryKind::Fn(data) |
1323 EntryKind::ForeignFn(data) => data.decode(self).param_names,
1324 EntryKind::Method(data) => data.decode(self).fn_data.param_names,
1327 param_names.decode(self).collect()
1330 fn exported_symbols(
1333 ) -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1334 if self.root.is_proc_macro_crate() {
1335 // If this crate is a custom derive crate, then we're not even going to
1336 // link those in so we skip those crates.
1339 self.root.exported_symbols.decode((self, tcx)).collect()
1343 fn get_rendered_const(&self, id: DefIndex) -> String {
1344 match self.kind(id) {
1345 EntryKind::Const(_, data) |
1346 EntryKind::AssocConst(_, _, data) => data.decode(self).0,
1351 fn get_macro(&self, id: DefIndex) -> MacroDef {
1352 match self.kind(id) {
1353 EntryKind::MacroDef(macro_def) => macro_def.decode(self),
1358 fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1359 let constness = match self.kind(id) {
1360 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1361 EntryKind::Fn(data) => data.decode(self).constness,
1362 EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const,
1363 _ => hir::Constness::NotConst,
1365 constness == hir::Constness::Const
1368 fn asyncness(&self, id: DefIndex) -> hir::IsAsync {
1369 match self.kind(id) {
1370 EntryKind::Fn(data) => data.decode(self).asyncness,
1371 EntryKind::Method(data) => data.decode(self).fn_data.asyncness,
1372 EntryKind::ForeignFn(data) => data.decode(self).asyncness,
1373 _ => bug!("asyncness: expected function kind"),
1377 fn is_foreign_item(&self, id: DefIndex) -> bool {
1378 match self.kind(id) {
1379 EntryKind::ForeignImmStatic |
1380 EntryKind::ForeignMutStatic |
1381 EntryKind::ForeignFn(_) => true,
1386 fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1387 match self.kind(id) {
1388 EntryKind::ImmStatic |
1389 EntryKind::ForeignImmStatic => Some(hir::Mutability::Immutable),
1390 EntryKind::MutStatic |
1391 EntryKind::ForeignMutStatic => Some(hir::Mutability::Mutable),
1396 fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
1397 self.root.per_def.fn_sig.get(self, id).unwrap().decode((self, tcx))
1401 fn def_key(&self, index: DefIndex) -> DefKey {
1402 let mut key = self.def_path_table.def_key(index);
1403 if self.is_proc_macro(index) {
1404 let name = self.raw_proc_macro(index).name();
1405 key.disambiguated_data.data = DefPathData::MacroNs(Symbol::intern(name));
1410 // Returns the path leading to the thing with this `id`.
1411 fn def_path(&self, id: DefIndex) -> DefPath {
1412 debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1413 DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1417 fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1418 self.def_path_table.def_path_hash(index)
1421 /// Imports the source_map from an external crate into the source_map of the crate
1422 /// currently being compiled (the "local crate").
1424 /// The import algorithm works analogous to how AST items are inlined from an
1425 /// external crate's metadata:
1426 /// For every SourceFile in the external source_map an 'inline' copy is created in the
1427 /// local source_map. The correspondence relation between external and local
1428 /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1429 /// function. When an item from an external crate is later inlined into this
1430 /// crate, this correspondence information is used to translate the span
1431 /// information of the inlined item so that it refers the correct positions in
1432 /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1434 /// The import algorithm in the function below will reuse SourceFiles already
1435 /// existing in the local source_map. For example, even if the SourceFile of some
1436 /// source file of libstd gets imported many times, there will only ever be
1437 /// one SourceFile object for the corresponding file in the local source_map.
1439 /// Note that imported SourceFiles do not actually contain the source code of the
1440 /// file they represent, just information about length, line breaks, and
1441 /// multibyte characters. This information is enough to generate valid debuginfo
1442 /// for items inlined from other crates.
1444 /// Proc macro crates don't currently export spans, so this function does not have
1445 /// to work for them.
1446 fn imported_source_files(
1448 local_source_map: &source_map::SourceMap,
1449 ) -> &[ImportedSourceFile] {
1450 self.source_map_import_info.init_locking(|| {
1451 let external_source_map = self.root.source_map.decode(self);
1453 external_source_map.map(|source_file_to_import| {
1454 // We can't reuse an existing SourceFile, so allocate a new one
1455 // containing the information we need.
1456 let syntax_pos::SourceFile { name,
1462 mut multibyte_chars,
1463 mut non_narrow_chars,
1466 .. } = source_file_to_import;
1468 let source_length = (end_pos - start_pos).to_usize();
1470 // Translate line-start positions and multibyte character
1471 // position into frame of reference local to file.
1472 // `SourceMap::new_imported_source_file()` will then translate those
1473 // coordinates to their new global frame of reference when the
1474 // offset of the SourceFile is known.
1475 for pos in &mut lines {
1476 *pos = *pos - start_pos;
1478 for mbc in &mut multibyte_chars {
1479 mbc.pos = mbc.pos - start_pos;
1481 for swc in &mut non_narrow_chars {
1482 *swc = *swc - start_pos;
1484 for np in &mut normalized_pos {
1485 np.pos = np.pos - start_pos;
1488 let local_version = local_source_map.new_imported_source_file(name,
1498 debug!("CrateMetaData::imported_source_files alloc \
1499 source_file {:?} original (start_pos {:?} end_pos {:?}) \
1500 translated (start_pos {:?} end_pos {:?})",
1501 local_version.name, start_pos, end_pos,
1502 local_version.start_pos, local_version.end_pos);
1504 ImportedSourceFile {
1505 original_start_pos: start_pos,
1506 original_end_pos: end_pos,
1507 translated_source_file: local_version,
1513 /// Get the `DepNodeIndex` corresponding this crate. The result of this
1514 /// method is cached in the `dep_node_index` field.
1515 fn get_crate_dep_node_index(&self, tcx: TyCtxt<'tcx>) -> DepNodeIndex {
1516 let mut dep_node_index = self.dep_node_index.load();
1518 if unlikely!(dep_node_index == DepNodeIndex::INVALID) {
1519 // We have not cached the DepNodeIndex for this upstream crate yet,
1520 // so use the dep-graph to find it out and cache it.
1521 // Note that multiple threads can enter this block concurrently.
1522 // That is fine because the DepNodeIndex remains constant
1523 // throughout the whole compilation session, and multiple stores
1524 // would always write the same value.
1526 let def_path_hash = self.def_path_hash(CRATE_DEF_INDEX);
1527 let dep_node = def_path_hash.to_dep_node(dep_graph::DepKind::CrateMetadata);
1529 dep_node_index = tcx.dep_graph.dep_node_index_of(&dep_node);
1530 assert!(dep_node_index != DepNodeIndex::INVALID);
1531 self.dep_node_index.store(dep_node_index);
1537 crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
1538 self.dependencies.borrow()
1541 crate fn add_dependency(&self, cnum: CrateNum) {
1542 self.dependencies.borrow_mut().push(cnum);
1545 crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool {
1546 let mut extern_crate = self.extern_crate.borrow_mut();
1547 let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank);
1549 *extern_crate = Some(new_extern_crate);
1554 crate fn source(&self) -> &CrateSource {
1558 crate fn dep_kind(&self) -> DepKind {
1559 *self.dep_kind.lock()
1562 crate fn update_dep_kind(&self, f: impl FnOnce(DepKind) -> DepKind) {
1563 self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
1566 crate fn panic_strategy(&self) -> PanicStrategy {
1567 self.root.panic_strategy
1570 crate fn needs_panic_runtime(&self) -> bool {
1571 self.root.needs_panic_runtime
1574 crate fn is_panic_runtime(&self) -> bool {
1575 self.root.panic_runtime
1578 crate fn is_sanitizer_runtime(&self) -> bool {
1579 self.root.sanitizer_runtime
1582 crate fn is_profiler_runtime(&self) -> bool {
1583 self.root.profiler_runtime
1586 crate fn needs_allocator(&self) -> bool {
1587 self.root.needs_allocator
1590 crate fn has_global_allocator(&self) -> bool {
1591 self.root.has_global_allocator
1594 crate fn has_default_lib_allocator(&self) -> bool {
1595 self.root.has_default_lib_allocator
1598 crate fn is_proc_macro_crate(&self) -> bool {
1599 self.root.is_proc_macro_crate()
1602 crate fn name(&self) -> Symbol {
1606 crate fn disambiguator(&self) -> CrateDisambiguator {
1607 self.root.disambiguator
1610 crate fn hash(&self) -> Svh {
1615 // Cannot be implemented on 'ProcMacro', as libproc_macro
1616 // does not depend on libsyntax
1617 fn macro_kind(raw: &ProcMacro) -> MacroKind {
1619 ProcMacro::CustomDerive { .. } => MacroKind::Derive,
1620 ProcMacro::Attr { .. } => MacroKind::Attr,
1621 ProcMacro::Bang { .. } => MacroKind::Bang