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, BodyCache, interpret, Promoted};
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::util::common::record_time;
27 use rustc::util::captures::Captures;
31 use std::num::NonZeroUsize;
34 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
36 use syntax::ast::{self, Ident};
37 use syntax::source_map::{self, respan, Spanned};
38 use syntax_expand::base::{SyntaxExtensionKind, SyntaxExtension};
39 use syntax_expand::proc_macro::{AttrProcMacro, ProcMacroDerive, BangProcMacro};
40 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, hygiene::MacroKind};
41 use syntax_pos::symbol::{Symbol, sym};
43 use proc_macro::bridge::client::ProcMacro;
45 pub use cstore_impl::{provide, provide_extern};
49 crate struct MetadataBlob(MetadataRef);
51 // A map from external crate numbers (as decoded from some crate file) to
52 // local crate numbers (as generated during this session). Each external
53 // crate may refer to types in other external crates, and each has their
55 crate type CrateNumMap = IndexVec<CrateNum, CrateNum>;
57 crate struct CrateMetadata {
58 /// The primary crate data - binary metadata blob.
61 // --- Some data pre-decoded from the metadata blob, usually for performance ---
63 /// Properties of the whole crate.
64 /// NOTE(eddyb) we pass `'static` to a `'tcx` parameter because this
65 /// lifetime is only used behind `Lazy`, and therefore acts like an
66 /// universal (`for<'tcx>`), that is paired up with whichever `TyCtxt`
67 /// is being used to decode those values.
68 root: CrateRoot<'static>,
69 /// For each definition in this crate, we encode a key. When the
70 /// crate is loaded, we read all the keys and put them in this
71 /// hashmap, which gives the reverse mapping. This allows us to
72 /// quickly retrace a `DefPath`, which is needed for incremental
73 /// compilation support.
74 def_path_table: DefPathTable,
76 /// FIXME: Used only from queries and can use query cache,
77 /// so pre-decoding can probably be avoided.
78 trait_impls: FxHashMap<(u32, DefIndex), Lazy<[DefIndex]>>,
79 /// Proc macro descriptions for this crate, if it's a proc macro crate.
80 raw_proc_macros: Option<&'static [ProcMacro]>,
81 /// Source maps for code from the crate.
82 source_map_import_info: Once<Vec<ImportedSourceFile>>,
83 /// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
84 alloc_decoding_state: AllocDecodingState,
85 /// The `DepNodeIndex` of the `DepNode` representing this upstream crate.
86 /// It is initialized on the first access in `get_crate_dep_node_index()`.
87 /// Do not access the value directly, as it might not have been initialized yet.
88 /// The field must always be initialized to `DepNodeIndex::INVALID`.
89 dep_node_index: AtomicCell<DepNodeIndex>,
91 // --- Other significant crate properties ---
93 /// ID of this crate, from the current compilation session's point of view.
95 /// Maps crate IDs as they are were seen from this crate's compilation sessions into
96 /// IDs as they are seen from the current compilation session.
97 cnum_map: CrateNumMap,
98 /// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
99 dependencies: Lock<Vec<CrateNum>>,
100 /// How to link (or not link) this crate to the currently compiled crate.
101 dep_kind: Lock<DepKind>,
102 /// Filesystem location of this crate.
104 /// Whether or not this crate should be consider a private dependency
105 /// for purposes of the 'exported_private_dependencies' lint
107 /// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
108 host_hash: Option<Svh>,
110 // --- Data used only for improving diagnostics ---
112 /// Information about the `extern crate` item or path that caused this crate to be loaded.
113 /// If this is `None`, then the crate was injected (e.g., by the allocator).
114 extern_crate: Lock<Option<ExternCrate>>,
117 /// Holds information about a syntax_pos::SourceFile imported from another crate.
118 /// See `imported_source_files()` for more information.
119 struct ImportedSourceFile {
120 /// This SourceFile's byte-offset within the source_map of its original crate
121 original_start_pos: syntax_pos::BytePos,
122 /// The end of this SourceFile within the source_map of its original crate
123 original_end_pos: syntax_pos::BytePos,
124 /// The imported SourceFile's representation within the local source_map
125 translated_source_file: Lrc<syntax_pos::SourceFile>,
128 pub(super) struct DecodeContext<'a, 'tcx> {
129 opaque: opaque::Decoder<'a>,
130 cdata: Option<&'a CrateMetadata>,
131 sess: Option<&'tcx Session>,
132 tcx: Option<TyCtxt<'tcx>>,
134 // Cache the last used source_file for translating spans as an optimization.
135 last_source_file_index: usize,
137 lazy_state: LazyState,
139 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
140 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
143 /// Abstract over the various ways one can create metadata decoders.
144 pub(super) trait Metadata<'a, 'tcx>: Copy {
145 fn raw_bytes(self) -> &'a [u8];
146 fn cdata(self) -> Option<&'a CrateMetadata> { None }
147 fn sess(self) -> Option<&'tcx Session> { None }
148 fn tcx(self) -> Option<TyCtxt<'tcx>> { None }
150 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
151 let tcx = self.tcx();
153 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
155 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
157 last_source_file_index: 0,
158 lazy_state: LazyState::NoNode,
159 alloc_decoding_session: self.cdata().map(|cdata| {
160 cdata.alloc_decoding_state.new_decoding_session()
166 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
167 fn raw_bytes(self) -> &'a [u8] {
173 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
174 fn raw_bytes(self) -> &'a [u8] {
175 let (blob, _) = self;
179 fn sess(self) -> Option<&'tcx Session> {
180 let (_, sess) = self;
186 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
187 fn raw_bytes(self) -> &'a [u8] {
188 self.blob.raw_bytes()
190 fn cdata(self) -> Option<&'a CrateMetadata> {
195 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'tcx Session) {
196 fn raw_bytes(self) -> &'a [u8] {
199 fn cdata(self) -> Option<&'a CrateMetadata> {
202 fn sess(self) -> Option<&'tcx Session> {
207 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'tcx>) {
208 fn raw_bytes(self) -> &'a [u8] {
211 fn cdata(self) -> Option<&'a CrateMetadata> {
214 fn tcx(self) -> Option<TyCtxt<'tcx>> {
219 impl<'a, 'tcx, T: Decodable> Lazy<T> {
220 fn decode<M: Metadata<'a, 'tcx>>(self, metadata: M) -> T {
221 let mut dcx = metadata.decoder(self.position.get());
222 dcx.lazy_state = LazyState::NodeStart(self.position);
223 T::decode(&mut dcx).unwrap()
227 impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable> Lazy<[T]> {
228 fn decode<M: Metadata<'a, 'tcx>>(
231 ) -> impl ExactSizeIterator<Item = T> + Captures<'a> + Captures<'tcx> + 'x {
232 let mut dcx = metadata.decoder(self.position.get());
233 dcx.lazy_state = LazyState::NodeStart(self.position);
234 (0..self.meta).map(move |_| T::decode(&mut dcx).unwrap())
238 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
239 fn tcx(&self) -> TyCtxt<'tcx> {
240 self.tcx.expect("missing TyCtxt in DecodeContext")
243 fn cdata(&self) -> &'a CrateMetadata {
244 self.cdata.expect("missing CrateMetadata in DecodeContext")
247 fn read_lazy_with_meta<T: ?Sized + LazyMeta>(
250 ) -> Result<Lazy<T>, <Self as Decoder>::Error> {
251 let min_size = T::min_size(meta);
252 let distance = self.read_usize()?;
253 let position = match self.lazy_state {
254 LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
255 LazyState::NodeStart(start) => {
256 let start = start.get();
257 assert!(distance + min_size <= start);
258 start - distance - min_size
260 LazyState::Previous(last_min_end) => last_min_end.get() + distance,
262 self.lazy_state = LazyState::Previous(NonZeroUsize::new(position + min_size).unwrap());
263 Ok(Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta))
267 impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> {
269 fn tcx(&self) -> TyCtxt<'tcx> {
270 self.tcx.expect("missing TyCtxt in DecodeContext")
274 fn peek_byte(&self) -> u8 {
275 self.opaque.data[self.opaque.position()]
279 fn position(&self) -> usize {
280 self.opaque.position()
283 fn cached_ty_for_shorthand<F>(&mut self,
286 -> Result<Ty<'tcx>, Self::Error>
287 where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>
289 let tcx = self.tcx();
291 let key = ty::CReaderCacheKey {
292 cnum: self.cdata().cnum,
296 if let Some(&ty) = tcx.rcache.borrow().get(&key) {
300 let ty = or_insert_with(self)?;
301 tcx.rcache.borrow_mut().insert(key, ty);
305 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
306 where F: FnOnce(&mut Self) -> R
308 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
309 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
310 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
312 self.opaque = old_opaque;
313 self.lazy_state = old_state;
317 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
318 if cnum == LOCAL_CRATE {
321 self.cdata().cnum_map[cnum]
326 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
327 fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
328 self.read_lazy_with_meta(())
332 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<[T]>> for DecodeContext<'a, 'tcx> {
333 fn specialized_decode(&mut self) -> Result<Lazy<[T]>, Self::Error> {
334 let len = self.read_usize()?;
338 self.read_lazy_with_meta(len)
343 impl<'a, 'tcx, I: Idx, T> SpecializedDecoder<Lazy<Table<I, T>>> for DecodeContext<'a, 'tcx>
344 where Option<T>: FixedSizeEncoding,
346 fn specialized_decode(&mut self) -> Result<Lazy<Table<I, T>>, Self::Error> {
347 let len = self.read_usize()?;
348 self.read_lazy_with_meta(len)
352 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
354 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
355 let krate = CrateNum::decode(self)?;
356 let index = DefIndex::decode(self)?;
365 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
367 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
368 Ok(DefIndex::from_u32(self.read_u32()?))
372 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for DecodeContext<'a, 'tcx> {
374 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
375 self.specialized_decode().map(|i| LocalDefId::from_def_id(i))
379 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
380 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
381 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
382 alloc_decoding_session.decode_alloc_id(self)
384 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
389 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
390 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
391 let tag = u8::decode(self)?;
393 if tag == TAG_INVALID_SPAN {
397 debug_assert_eq!(tag, TAG_VALID_SPAN);
399 let lo = BytePos::decode(self)?;
400 let len = BytePos::decode(self)?;
403 let sess = if let Some(sess) = self.sess {
406 bug!("Cannot decode Span without Session.")
409 let imported_source_files = self.cdata().imported_source_files(&sess.source_map());
411 // Optimize for the case that most spans within a translated item
412 // originate from the same source_file.
413 let last_source_file = &imported_source_files[self.last_source_file_index];
415 if lo >= last_source_file.original_start_pos &&
416 lo <= last_source_file.original_end_pos {
420 let mut b = imported_source_files.len();
424 if imported_source_files[m].original_start_pos > lo {
431 self.last_source_file_index = a;
432 &imported_source_files[a]
436 // Make sure our binary search above is correct.
437 debug_assert!(lo >= source_file.original_start_pos &&
438 lo <= source_file.original_end_pos);
440 // Make sure we correctly filtered out invalid spans during encoding
441 debug_assert!(hi >= source_file.original_start_pos &&
442 hi <= source_file.original_end_pos);
444 let lo = (lo + source_file.translated_source_file.start_pos)
445 - source_file.original_start_pos;
446 let hi = (hi + source_file.translated_source_file.start_pos)
447 - source_file.original_start_pos;
449 Ok(Span::with_root_ctxt(lo, hi))
453 impl SpecializedDecoder<Ident> for DecodeContext<'_, '_> {
454 fn specialized_decode(&mut self) -> Result<Ident, Self::Error> {
455 // FIXME(jseyfried): intercrate hygiene
457 Ok(Ident::with_dummy_span(Symbol::decode(self)?))
461 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
462 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
463 Fingerprint::decode_opaque(&mut self.opaque)
467 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
468 for DecodeContext<'a, 'tcx> {
470 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
471 Ok(mir::ClearCrossCrate::Clear)
475 implement_ty_decoder!( DecodeContext<'a, 'tcx> );
478 crate fn new(metadata_ref: MetadataRef) -> MetadataBlob {
479 MetadataBlob(metadata_ref)
482 crate fn is_compatible(&self) -> bool {
483 self.raw_bytes().starts_with(METADATA_HEADER)
486 crate fn get_rustc_version(&self) -> String {
487 Lazy::<String>::from_position(
488 NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap(),
492 crate fn get_root(&self) -> CrateRoot<'tcx> {
493 let slice = self.raw_bytes();
494 let offset = METADATA_HEADER.len();
495 let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
496 ((slice[offset + 2] as u32) << 8) |
497 ((slice[offset + 3] as u32) << 0)) as usize;
498 Lazy::<CrateRoot<'tcx>>::from_position(
499 NonZeroUsize::new(pos).unwrap(),
503 crate fn list_crate_metadata(&self,
504 out: &mut dyn io::Write) -> io::Result<()> {
505 write!(out, "=External Dependencies=\n")?;
506 let root = self.get_root();
507 for (i, dep) in root.crate_deps
510 write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
517 impl<'tcx> EntryKind<'tcx> {
518 fn def_kind(&self) -> Option<DefKind> {
520 EntryKind::Const(..) => DefKind::Const,
521 EntryKind::AssocConst(..) => DefKind::AssocConst,
522 EntryKind::ImmStatic |
523 EntryKind::MutStatic |
524 EntryKind::ForeignImmStatic |
525 EntryKind::ForeignMutStatic => DefKind::Static,
526 EntryKind::Struct(_, _) => DefKind::Struct,
527 EntryKind::Union(_, _) => DefKind::Union,
529 EntryKind::ForeignFn(_) => DefKind::Fn,
530 EntryKind::Method(_) => DefKind::Method,
531 EntryKind::Type => DefKind::TyAlias,
532 EntryKind::TypeParam => DefKind::TyParam,
533 EntryKind::ConstParam => DefKind::ConstParam,
534 EntryKind::OpaqueTy => DefKind::OpaqueTy,
535 EntryKind::AssocType(_) => DefKind::AssocTy,
536 EntryKind::AssocOpaqueTy(_) => DefKind::AssocOpaqueTy,
537 EntryKind::Mod(_) => DefKind::Mod,
538 EntryKind::Variant(_) => DefKind::Variant,
539 EntryKind::Trait(_) => DefKind::Trait,
540 EntryKind::TraitAlias => DefKind::TraitAlias,
541 EntryKind::Enum(..) => DefKind::Enum,
542 EntryKind::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
543 EntryKind::ForeignType => DefKind::ForeignTy,
545 EntryKind::ForeignMod |
546 EntryKind::GlobalAsm |
549 EntryKind::Generator(_) |
550 EntryKind::Closure => return None,
556 crate fn is_proc_macro_crate(&self) -> bool {
557 self.proc_macro_data.is_some()
560 crate fn name(&self) -> Symbol {
564 crate fn disambiguator(&self) -> CrateDisambiguator {
568 crate fn hash(&self) -> Svh {
572 crate fn triple(&self) -> &TargetTriple {
576 crate fn decode_crate_deps(
578 metadata: &'a MetadataBlob,
579 ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
580 self.crate_deps.decode(metadata)
584 impl<'a, 'tcx> CrateMetadata {
588 root: CrateRoot<'static>,
589 raw_proc_macros: Option<&'static [ProcMacro]>,
591 cnum_map: CrateNumMap,
595 host_hash: Option<Svh>,
597 let def_path_table = record_time(&sess.perf_stats.decode_def_path_tables_time, || {
598 root.def_path_table.decode((&blob, sess))
600 let trait_impls = root.impls.decode((&blob, sess))
601 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls)).collect();
602 let alloc_decoding_state =
603 AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
604 let dependencies = Lock::new(cnum_map.iter().cloned().collect());
611 source_map_import_info: Once::new(),
612 alloc_decoding_state,
613 dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
617 dep_kind: Lock::new(dep_kind),
621 extern_crate: Lock::new(None),
625 fn is_proc_macro(&self, id: DefIndex) -> bool {
626 self.root.proc_macro_data.and_then(|data| data.decode(self).find(|x| *x == id)).is_some()
629 fn maybe_kind(&self, item_id: DefIndex) -> Option<EntryKind<'tcx>> {
630 self.root.per_def.kind.get(self, item_id).map(|k| k.decode(self))
633 fn kind(&self, item_id: DefIndex) -> EntryKind<'tcx> {
634 assert!(!self.is_proc_macro(item_id));
635 self.maybe_kind(item_id).unwrap_or_else(|| {
637 "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}",
645 fn local_def_id(&self, index: DefIndex) -> DefId {
652 fn raw_proc_macro(&self, id: DefIndex) -> &ProcMacro {
653 // DefIndex's in root.proc_macro_data have a one-to-one correspondence
654 // with items in 'raw_proc_macros'.
655 // NOTE: If you update the order of macros in 'proc_macro_data' for any reason,
656 // you must also update src/libsyntax_ext/proc_macro_harness.rs
657 // Failing to do so will result in incorrect data being associated
658 // with proc macros when deserialized.
659 let pos = self.root.proc_macro_data.unwrap().decode(self).position(|i| i == id).unwrap();
660 &self.raw_proc_macros.unwrap()[pos]
663 fn item_name(&self, item_index: DefIndex) -> Symbol {
664 if !self.is_proc_macro(item_index) {
665 self.def_key(item_index)
669 .expect("no name in item_name")
671 Symbol::intern(self.raw_proc_macro(item_index).name())
675 fn def_kind(&self, index: DefIndex) -> Option<DefKind> {
676 if !self.is_proc_macro(index) {
677 self.kind(index).def_kind()
680 macro_kind(self.raw_proc_macro(index))
685 fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
686 self.root.per_def.span.get(self, index).unwrap().decode((self, sess))
689 fn load_proc_macro(&self, id: DefIndex, sess: &Session) -> SyntaxExtension {
690 let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
691 ProcMacro::CustomDerive { trait_name, attributes, client } => {
693 attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
696 SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
700 ProcMacro::Attr { name, client } => (
701 name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new()
703 ProcMacro::Bang { name, client } => (
704 name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new()
708 SyntaxExtension::new(
711 self.get_span(id, sess),
714 Symbol::intern(name),
715 &self.get_item_attrs(id, sess),
719 fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
720 match self.kind(item_id) {
721 EntryKind::Trait(data) => {
722 let data = data.decode((self, sess));
723 ty::TraitDef::new(self.local_def_id(item_id),
728 self.def_path_table.def_path_hash(item_id))
730 EntryKind::TraitAlias => {
731 ty::TraitDef::new(self.local_def_id(item_id),
732 hir::Unsafety::Normal,
736 self.def_path_table.def_path_hash(item_id))
738 _ => bug!("def-index does not refer to trait or trait alias"),
745 kind: &EntryKind<'_>,
748 ) -> ty::VariantDef {
749 let data = match kind {
750 EntryKind::Variant(data) |
751 EntryKind::Struct(data, _) |
752 EntryKind::Union(data, _) => data.decode(self),
756 let adt_kind = match kind {
757 EntryKind::Variant(_) => ty::AdtKind::Enum,
758 EntryKind::Struct(..) => ty::AdtKind::Struct,
759 EntryKind::Union(..) => ty::AdtKind::Union,
763 let variant_did = if adt_kind == ty::AdtKind::Enum {
764 Some(self.local_def_id(index))
768 let ctor_did = data.ctor.map(|index| self.local_def_id(index));
772 Ident::with_dummy_span(self.item_name(index)),
776 self.root.per_def.children.get(self, index).unwrap_or(Lazy::empty())
777 .decode(self).map(|index| ty::FieldDef {
778 did: self.local_def_id(index),
779 ident: Ident::with_dummy_span(self.item_name(index)),
780 vis: self.get_visibility(index),
789 fn get_adt_def(&self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef {
790 let kind = self.kind(item_id);
791 let did = self.local_def_id(item_id);
793 let (adt_kind, repr) = match kind {
794 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
795 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
796 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
797 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
800 let variants = if let ty::AdtKind::Enum = adt_kind {
801 self.root.per_def.children.get(self, item_id).unwrap_or(Lazy::empty())
804 self.get_variant(tcx, &self.kind(index), index, did)
808 std::iter::once(self.get_variant(tcx, &kind, item_id, did)).collect()
811 tcx.alloc_adt_def(did, adt_kind, variants, repr)
814 fn get_explicit_predicates(
818 ) -> ty::GenericPredicates<'tcx> {
819 self.root.per_def.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx))
822 fn get_inferred_outlives(
826 ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
827 self.root.per_def.inferred_outlives.get(self, item_id).map(|predicates| {
828 predicates.decode((self, tcx))
829 }).unwrap_or_default()
832 fn get_super_predicates(
836 ) -> ty::GenericPredicates<'tcx> {
837 self.root.per_def.super_predicates.get(self, item_id).unwrap().decode((self, tcx))
840 fn get_generics(&self, item_id: DefIndex, sess: &Session) -> ty::Generics {
841 self.root.per_def.generics.get(self, item_id).unwrap().decode((self, sess))
844 fn get_type(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
845 self.root.per_def.ty.get(self, id).unwrap().decode((self, tcx))
848 fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
849 match self.is_proc_macro(id) {
850 true => self.root.proc_macro_stability.clone(),
851 false => self.root.per_def.stability.get(self, id).map(|stab| stab.decode(self)),
855 fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
856 self.root.per_def.deprecation.get(self, id)
857 .filter(|_| !self.is_proc_macro(id))
858 .map(|depr| depr.decode(self))
861 fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
862 match self.is_proc_macro(id) {
863 true => ty::Visibility::Public,
864 false => self.root.per_def.visibility.get(self, id).unwrap().decode(self),
868 fn get_impl_data(&self, id: DefIndex) -> ImplData {
869 match self.kind(id) {
870 EntryKind::Impl(data) => data.decode(self),
875 fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
876 self.get_impl_data(id).parent_impl
879 fn get_impl_polarity(&self, id: DefIndex) -> ty::ImplPolarity {
880 self.get_impl_data(id).polarity
883 fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
884 self.get_impl_data(id).defaultness
887 fn get_coerce_unsized_info(
890 ) -> Option<ty::adjustment::CoerceUnsizedInfo> {
891 self.get_impl_data(id).coerce_unsized_info
894 fn get_impl_trait(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option<ty::TraitRef<'tcx>> {
895 self.root.per_def.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx)))
898 /// Iterates over all the stability attributes in the given crate.
899 fn get_lib_features(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(ast::Name, Option<ast::Name>)] {
900 // FIXME: For a proc macro crate, not sure whether we should return the "host"
901 // features or an empty Vec. Both don't cause ICEs.
902 tcx.arena.alloc_from_iter(self.root
907 /// Iterates over the language items in the given crate.
908 fn get_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] {
909 if self.root.is_proc_macro_crate() {
910 // Proc macro crates do not export any lang-items to the target.
913 tcx.arena.alloc_from_iter(self.root
916 .map(|(def_index, index)| (self.local_def_id(def_index), index)))
920 /// Iterates over the diagnostic items in the given crate.
921 fn get_diagnostic_items(
924 ) -> &'tcx FxHashMap<Symbol, DefId> {
925 tcx.arena.alloc(if self.root.is_proc_macro_crate() {
926 // Proc macro crates do not export any diagnostic-items to the target.
932 .map(|(name, def_index)| (name, self.local_def_id(def_index)))
937 /// Iterates over each child of the given item.
938 fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
939 where F: FnMut(def::Export<hir::HirId>)
941 if let Some(proc_macros_ids) = self.root.proc_macro_data.map(|d| d.decode(self)) {
942 /* If we are loading as a proc macro, we want to return the view of this crate
943 * as a proc macro crate.
945 if id == CRATE_DEF_INDEX {
946 for def_index in proc_macros_ids {
947 let raw_macro = self.raw_proc_macro(def_index);
949 DefKind::Macro(macro_kind(raw_macro)),
950 self.local_def_id(def_index),
952 let ident = Ident::from_str(raw_macro.name());
953 callback(def::Export {
956 vis: ty::Visibility::Public,
965 let kind = match self.maybe_kind(id) {
970 // Iterate over all children.
971 let macros_only = self.dep_kind.lock().macros_only();
972 let children = self.root.per_def.children.get(self, id).unwrap_or(Lazy::empty());
973 for child_index in children.decode((self, sess)) {
979 if let Some(child_kind) = self.maybe_kind(child_index) {
981 EntryKind::MacroDef(..) => {}
982 _ if macros_only => continue,
986 // Hand off the item to the callback.
988 // FIXME(eddyb) Don't encode these in children.
989 EntryKind::ForeignMod => {
991 self.root.per_def.children.get(self, child_index)
992 .unwrap_or(Lazy::empty());
993 for child_index in child_children.decode((self, sess)) {
994 if let Some(kind) = self.def_kind(child_index) {
995 callback(def::Export {
996 res: Res::Def(kind, self.local_def_id(child_index)),
997 ident: Ident::with_dummy_span(self.item_name(child_index)),
998 vis: self.get_visibility(child_index),
999 span: self.root.per_def.span.get(self, child_index).unwrap()
1000 .decode((self, sess)),
1006 EntryKind::Impl(_) => continue,
1011 let def_key = self.def_key(child_index);
1012 let span = self.get_span(child_index, sess);
1013 if let (Some(kind), Some(name)) =
1014 (self.def_kind(child_index), def_key.disambiguated_data.data.get_opt_name()) {
1015 let ident = Ident::with_dummy_span(name);
1016 let vis = self.get_visibility(child_index);
1017 let def_id = self.local_def_id(child_index);
1018 let res = Res::Def(kind, def_id);
1019 callback(def::Export { res, ident, vis, span });
1020 // For non-re-export structs and variants add their constructors to children.
1021 // Re-export lists automatically contain constructors when necessary.
1023 DefKind::Struct => {
1024 if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
1025 let ctor_kind = self.get_ctor_kind(child_index);
1026 let ctor_res = Res::Def(
1027 DefKind::Ctor(CtorOf::Struct, ctor_kind),
1030 let vis = self.get_visibility(ctor_def_id.index);
1031 callback(def::Export { res: ctor_res, vis, ident, span });
1034 DefKind::Variant => {
1035 // Braced variants, unlike structs, generate unusable names in
1036 // value namespace, they are reserved for possible future use.
1037 // It's ok to use the variant's id as a ctor id since an
1038 // error will be reported on any use of such resolution anyway.
1039 let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
1040 let ctor_kind = self.get_ctor_kind(child_index);
1041 let ctor_res = Res::Def(
1042 DefKind::Ctor(CtorOf::Variant, ctor_kind),
1045 let mut vis = self.get_visibility(ctor_def_id.index);
1046 if ctor_def_id == def_id && vis == ty::Visibility::Public {
1047 // For non-exhaustive variants lower the constructor visibility to
1048 // within the crate. We only need this for fictive constructors,
1049 // for other constructors correct visibilities
1050 // were already encoded in metadata.
1051 let attrs = self.get_item_attrs(def_id.index, sess);
1052 if attr::contains_name(&attrs, sym::non_exhaustive) {
1053 let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
1054 vis = ty::Visibility::Restricted(crate_def_id);
1057 callback(def::Export { res: ctor_res, ident, vis, span });
1065 if let EntryKind::Mod(data) = kind {
1066 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
1068 Res::Def(DefKind::Macro(..), _) => {}
1069 _ if macros_only => continue,
1077 fn is_item_mir_available(&self, id: DefIndex) -> bool {
1078 !self.is_proc_macro(id) &&
1079 self.root.per_def.mir.get(self, id).is_some()
1082 fn get_optimized_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> BodyCache<'tcx> {
1083 self.root.per_def.mir.get(self, id)
1084 .filter(|_| !self.is_proc_macro(id))
1085 .unwrap_or_else(|| {
1086 bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id))
1088 .decode((self, tcx))
1091 fn get_promoted_mir(
1095 ) -> IndexVec<Promoted, BodyCache<'tcx>> {
1096 self.root.per_def.promoted_mir.get(self, id)
1097 .filter(|_| !self.is_proc_macro(id))
1098 .unwrap_or_else(|| {
1099 bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id))
1101 .decode((self, tcx))
1104 fn mir_const_qualif(&self, id: DefIndex) -> mir::ConstQualifs {
1105 match self.kind(id) {
1106 EntryKind::Const(qualif, _) |
1107 EntryKind::AssocConst(AssocContainer::ImplDefault, qualif, _) |
1108 EntryKind::AssocConst(AssocContainer::ImplFinal, qualif, _) => {
1115 fn get_associated_item(&self, id: DefIndex) -> ty::AssocItem {
1116 let def_key = self.def_key(id);
1117 let parent = self.local_def_id(def_key.parent.unwrap());
1118 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
1120 let (kind, container, has_self) = match self.kind(id) {
1121 EntryKind::AssocConst(container, _, _) => {
1122 (ty::AssocKind::Const, container, false)
1124 EntryKind::Method(data) => {
1125 let data = data.decode(self);
1126 (ty::AssocKind::Method, data.container, data.has_self)
1128 EntryKind::AssocType(container) => {
1129 (ty::AssocKind::Type, container, false)
1131 EntryKind::AssocOpaqueTy(container) => {
1132 (ty::AssocKind::OpaqueTy, container, false)
1134 _ => bug!("cannot get associated-item of `{:?}`", def_key)
1138 ident: Ident::with_dummy_span(name),
1140 vis: self.get_visibility(id),
1141 defaultness: container.defaultness(),
1142 def_id: self.local_def_id(id),
1143 container: container.with_def_id(parent),
1144 method_has_self_argument: has_self
1148 fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
1149 self.root.per_def.variances.get(self, id).unwrap_or(Lazy::empty())
1150 .decode(self).collect()
1153 fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
1154 match self.kind(node_id) {
1155 EntryKind::Struct(data, _) |
1156 EntryKind::Union(data, _) |
1157 EntryKind::Variant(data) => data.decode(self).ctor_kind,
1158 _ => CtorKind::Fictive,
1162 fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
1163 match self.kind(node_id) {
1164 EntryKind::Struct(data, _) => {
1165 data.decode(self).ctor.map(|index| self.local_def_id(index))
1167 EntryKind::Variant(data) => {
1168 data.decode(self).ctor.map(|index| self.local_def_id(index))
1174 fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
1175 // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
1176 // we assume that someone passing in a tuple struct ctor is actually wanting to
1177 // look at the definition
1178 let def_key = self.def_key(node_id);
1179 let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
1180 def_key.parent.unwrap()
1185 Lrc::from(self.root.per_def.attributes.get(self, item_id).unwrap_or(Lazy::empty())
1186 .decode((self, sess))
1187 .collect::<Vec<_>>())
1190 fn get_struct_field_names(
1194 ) -> Vec<Spanned<ast::Name>> {
1195 self.root.per_def.children.get(self, id).unwrap_or(Lazy::empty())
1197 .map(|index| respan(self.get_span(index, sess), self.item_name(index)))
1201 // Translate a DefId from the current compilation environment to a DefId
1202 // for an external crate.
1203 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1204 for (local, &global) in self.cnum_map.iter_enumerated() {
1205 if global == did.krate {
1216 fn get_inherent_implementations_for_type(
1220 ) -> &'tcx [DefId] {
1221 tcx.arena.alloc_from_iter(
1222 self.root.per_def.inherent_impls.get(self, id).unwrap_or(Lazy::empty())
1224 .map(|index| self.local_def_id(index))
1228 fn get_implementations_for_trait(
1231 filter: Option<DefId>,
1232 ) -> &'tcx [DefId] {
1233 if self.root.is_proc_macro_crate() {
1234 // proc-macro crates export no trait impls.
1238 // Do a reverse lookup beforehand to avoid touching the crate_num
1239 // hash map in the loop below.
1240 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1241 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1242 Some(None) => return &[],
1246 if let Some(filter) = filter {
1247 if let Some(impls) = self.trait_impls.get(&filter) {
1248 tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx)))
1253 tcx.arena.alloc_from_iter(self.trait_impls.values().flat_map(|impls| {
1254 impls.decode(self).map(|idx| self.local_def_id(idx))
1259 fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1260 let def_key = self.def_key(id);
1261 match def_key.disambiguated_data.data {
1262 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1263 // Not an associated item
1266 def_key.parent.and_then(|parent_index| {
1267 match self.kind(parent_index) {
1268 EntryKind::Trait(_) |
1269 EntryKind::TraitAlias => Some(self.local_def_id(parent_index)),
1276 fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1277 if self.root.is_proc_macro_crate() {
1278 // Proc macro crates do not have any *target* native libraries.
1281 self.root.native_libraries.decode((self, sess)).collect()
1285 fn get_foreign_modules(&self, tcx: TyCtxt<'tcx>) -> &'tcx [ForeignModule] {
1286 if self.root.is_proc_macro_crate() {
1287 // Proc macro crates do not have any *target* foreign modules.
1290 tcx.arena.alloc_from_iter(self.root.foreign_modules.decode((self, tcx.sess)))
1294 fn get_dylib_dependency_formats(
1297 ) -> &'tcx [(CrateNum, LinkagePreference)] {
1298 tcx.arena.alloc_from_iter(self.root
1299 .dylib_dependency_formats
1302 .flat_map(|(i, link)| {
1303 let cnum = CrateNum::new(i + 1);
1304 link.map(|link| (self.cnum_map[cnum], link))
1308 fn get_missing_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] {
1309 if self.root.is_proc_macro_crate() {
1310 // Proc macro crates do not depend on any target weak lang-items.
1313 tcx.arena.alloc_from_iter(self.root
1319 fn get_fn_param_names(&self, id: DefIndex) -> Vec<ast::Name> {
1320 let param_names = match self.kind(id) {
1321 EntryKind::Fn(data) |
1322 EntryKind::ForeignFn(data) => data.decode(self).param_names,
1323 EntryKind::Method(data) => data.decode(self).fn_data.param_names,
1326 param_names.decode(self).collect()
1329 fn exported_symbols(
1332 ) -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1333 if self.root.is_proc_macro_crate() {
1334 // If this crate is a custom derive crate, then we're not even going to
1335 // link those in so we skip those crates.
1338 self.root.exported_symbols.decode((self, tcx)).collect()
1342 fn get_rendered_const(&self, id: DefIndex) -> String {
1343 match self.kind(id) {
1344 EntryKind::Const(_, data) |
1345 EntryKind::AssocConst(_, _, data) => data.decode(self).0,
1350 fn get_macro(&self, id: DefIndex) -> MacroDef {
1351 match self.kind(id) {
1352 EntryKind::MacroDef(macro_def) => macro_def.decode(self),
1357 fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1358 let constness = match self.kind(id) {
1359 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1360 EntryKind::Fn(data) => data.decode(self).constness,
1361 EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const,
1362 _ => hir::Constness::NotConst,
1364 constness == hir::Constness::Const
1367 fn asyncness(&self, id: DefIndex) -> hir::IsAsync {
1368 match self.kind(id) {
1369 EntryKind::Fn(data) => data.decode(self).asyncness,
1370 EntryKind::Method(data) => data.decode(self).fn_data.asyncness,
1371 EntryKind::ForeignFn(data) => data.decode(self).asyncness,
1372 _ => bug!("asyncness: expected function kind"),
1376 fn is_foreign_item(&self, id: DefIndex) -> bool {
1377 match self.kind(id) {
1378 EntryKind::ForeignImmStatic |
1379 EntryKind::ForeignMutStatic |
1380 EntryKind::ForeignFn(_) => true,
1385 fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1386 match self.kind(id) {
1387 EntryKind::ImmStatic |
1388 EntryKind::ForeignImmStatic => Some(hir::Mutability::Immutable),
1389 EntryKind::MutStatic |
1390 EntryKind::ForeignMutStatic => Some(hir::Mutability::Mutable),
1395 fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
1396 self.root.per_def.fn_sig.get(self, id).unwrap().decode((self, tcx))
1400 fn def_key(&self, index: DefIndex) -> DefKey {
1401 let mut key = self.def_path_table.def_key(index);
1402 if self.is_proc_macro(index) {
1403 let name = self.raw_proc_macro(index).name();
1404 key.disambiguated_data.data = DefPathData::MacroNs(Symbol::intern(name));
1409 // Returns the path leading to the thing with this `id`.
1410 fn def_path(&self, id: DefIndex) -> DefPath {
1411 debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1412 DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1416 fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1417 self.def_path_table.def_path_hash(index)
1420 /// Imports the source_map from an external crate into the source_map of the crate
1421 /// currently being compiled (the "local crate").
1423 /// The import algorithm works analogous to how AST items are inlined from an
1424 /// external crate's metadata:
1425 /// For every SourceFile in the external source_map an 'inline' copy is created in the
1426 /// local source_map. The correspondence relation between external and local
1427 /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1428 /// function. When an item from an external crate is later inlined into this
1429 /// crate, this correspondence information is used to translate the span
1430 /// information of the inlined item so that it refers the correct positions in
1431 /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1433 /// The import algorithm in the function below will reuse SourceFiles already
1434 /// existing in the local source_map. For example, even if the SourceFile of some
1435 /// source file of libstd gets imported many times, there will only ever be
1436 /// one SourceFile object for the corresponding file in the local source_map.
1438 /// Note that imported SourceFiles do not actually contain the source code of the
1439 /// file they represent, just information about length, line breaks, and
1440 /// multibyte characters. This information is enough to generate valid debuginfo
1441 /// for items inlined from other crates.
1443 /// Proc macro crates don't currently export spans, so this function does not have
1444 /// to work for them.
1445 fn imported_source_files(
1447 local_source_map: &source_map::SourceMap,
1448 ) -> &[ImportedSourceFile] {
1449 self.source_map_import_info.init_locking(|| {
1450 let external_source_map = self.root.source_map.decode(self);
1452 external_source_map.map(|source_file_to_import| {
1453 // We can't reuse an existing SourceFile, so allocate a new one
1454 // containing the information we need.
1455 let syntax_pos::SourceFile { name,
1461 mut multibyte_chars,
1462 mut non_narrow_chars,
1465 .. } = source_file_to_import;
1467 let source_length = (end_pos - start_pos).to_usize();
1469 // Translate line-start positions and multibyte character
1470 // position into frame of reference local to file.
1471 // `SourceMap::new_imported_source_file()` will then translate those
1472 // coordinates to their new global frame of reference when the
1473 // offset of the SourceFile is known.
1474 for pos in &mut lines {
1475 *pos = *pos - start_pos;
1477 for mbc in &mut multibyte_chars {
1478 mbc.pos = mbc.pos - start_pos;
1480 for swc in &mut non_narrow_chars {
1481 *swc = *swc - start_pos;
1483 for np in &mut normalized_pos {
1484 np.pos = np.pos - start_pos;
1487 let local_version = local_source_map.new_imported_source_file(name,
1497 debug!("CrateMetaData::imported_source_files alloc \
1498 source_file {:?} original (start_pos {:?} end_pos {:?}) \
1499 translated (start_pos {:?} end_pos {:?})",
1500 local_version.name, start_pos, end_pos,
1501 local_version.start_pos, local_version.end_pos);
1503 ImportedSourceFile {
1504 original_start_pos: start_pos,
1505 original_end_pos: end_pos,
1506 translated_source_file: local_version,
1512 /// Get the `DepNodeIndex` corresponding this crate. The result of this
1513 /// method is cached in the `dep_node_index` field.
1514 fn get_crate_dep_node_index(&self, tcx: TyCtxt<'tcx>) -> DepNodeIndex {
1515 let mut dep_node_index = self.dep_node_index.load();
1517 if unlikely!(dep_node_index == DepNodeIndex::INVALID) {
1518 // We have not cached the DepNodeIndex for this upstream crate yet,
1519 // so use the dep-graph to find it out and cache it.
1520 // Note that multiple threads can enter this block concurrently.
1521 // That is fine because the DepNodeIndex remains constant
1522 // throughout the whole compilation session, and multiple stores
1523 // would always write the same value.
1525 let def_path_hash = self.def_path_hash(CRATE_DEF_INDEX);
1526 let dep_node = def_path_hash.to_dep_node(dep_graph::DepKind::CrateMetadata);
1528 dep_node_index = tcx.dep_graph.dep_node_index_of(&dep_node);
1529 assert!(dep_node_index != DepNodeIndex::INVALID);
1530 self.dep_node_index.store(dep_node_index);
1536 crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
1537 self.dependencies.borrow()
1540 crate fn add_dependency(&self, cnum: CrateNum) {
1541 self.dependencies.borrow_mut().push(cnum);
1544 crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool {
1545 let mut extern_crate = self.extern_crate.borrow_mut();
1546 let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank);
1548 *extern_crate = Some(new_extern_crate);
1553 crate fn source(&self) -> &CrateSource {
1557 crate fn dep_kind(&self) -> DepKind {
1558 *self.dep_kind.lock()
1561 crate fn update_dep_kind(&self, f: impl FnOnce(DepKind) -> DepKind) {
1562 self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
1565 crate fn panic_strategy(&self) -> PanicStrategy {
1566 self.root.panic_strategy
1569 crate fn needs_panic_runtime(&self) -> bool {
1570 self.root.needs_panic_runtime
1573 crate fn is_panic_runtime(&self) -> bool {
1574 self.root.panic_runtime
1577 crate fn is_sanitizer_runtime(&self) -> bool {
1578 self.root.sanitizer_runtime
1581 crate fn is_profiler_runtime(&self) -> bool {
1582 self.root.profiler_runtime
1585 crate fn needs_allocator(&self) -> bool {
1586 self.root.needs_allocator
1589 crate fn has_global_allocator(&self) -> bool {
1590 self.root.has_global_allocator
1593 crate fn has_default_lib_allocator(&self) -> bool {
1594 self.root.has_default_lib_allocator
1597 crate fn is_proc_macro_crate(&self) -> bool {
1598 self.root.is_proc_macro_crate()
1601 crate fn name(&self) -> Symbol {
1605 crate fn disambiguator(&self) -> CrateDisambiguator {
1606 self.root.disambiguator
1609 crate fn hash(&self) -> Svh {
1614 // Cannot be implemented on 'ProcMacro', as libproc_macro
1615 // does not depend on libsyntax
1616 fn macro_kind(raw: &ProcMacro) -> MacroKind {
1618 ProcMacro::CustomDerive { .. } => MacroKind::Derive,
1619 ProcMacro::Attr { .. } => MacroKind::Attr,
1620 ProcMacro::Bang { .. } => MacroKind::Bang