1 // Decoding metadata from a single crate's metadata
3 use crate::creader::CrateMetadataRef;
4 use crate::rmeta::table::{FixedSizeEncoding, Table};
7 use rustc::dep_graph::{self, DepNode, DepNodeIndex};
8 use rustc::hir::exports::Export;
9 use rustc::hir::map::definitions::DefPathTable;
10 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash};
11 use rustc::middle::cstore::{CrateSource, ExternCrate};
12 use rustc::middle::cstore::{ForeignModule, LinkagePreference, NativeLibrary};
13 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
14 use rustc::middle::lang_items;
15 use rustc::mir::interpret::{AllocDecodingSession, AllocDecodingState};
16 use rustc::mir::{self, interpret, BodyAndCache, Promoted};
17 use rustc::session::Session;
18 use rustc::ty::codec::TyDecoder;
19 use rustc::ty::{self, Ty, TyCtxt};
20 use rustc::util::common::record_time;
21 use rustc_data_structures::captures::Captures;
22 use rustc_data_structures::fingerprint::Fingerprint;
23 use rustc_data_structures::fx::FxHashMap;
24 use rustc_data_structures::svh::Svh;
25 use rustc_data_structures::sync::{AtomicCell, Lock, LockGuard, Lrc, Once};
27 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
28 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
29 use rustc_index::vec::{Idx, IndexVec};
33 use std::num::NonZeroUsize;
37 use proc_macro::bridge::client::ProcMacro;
38 use rustc_ast::ast::{self, Ident};
39 use rustc_attr as attr;
40 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
41 use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, ProcMacroDerive};
42 use rustc_serialize::{opaque, Decodable, Decoder, SpecializedDecoder};
43 use rustc_span::source_map::{self, respan, Spanned};
44 use rustc_span::symbol::{sym, Symbol};
45 use rustc_span::{self, hygiene::MacroKind, BytePos, Pos, Span, DUMMY_SP};
47 pub use cstore_impl::{provide, provide_extern};
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>,
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 ---
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 ---
111 /// Information about the `extern crate` item or path that caused this crate to be loaded.
112 /// If this is `None`, then the crate was injected (e.g., by the allocator).
113 extern_crate: Lock<Option<ExternCrate>>,
116 /// Holds information about a rustc_span::SourceFile imported from another crate.
117 /// See `imported_source_files()` for more information.
118 struct ImportedSourceFile {
119 /// This SourceFile's byte-offset within the source_map of its original crate
120 original_start_pos: rustc_span::BytePos,
121 /// The end of this SourceFile within the source_map of its original crate
122 original_end_pos: rustc_span::BytePos,
123 /// The imported SourceFile's representation within the local source_map
124 translated_source_file: Lrc<rustc_span::SourceFile>,
127 pub(super) struct DecodeContext<'a, 'tcx> {
128 opaque: opaque::Decoder<'a>,
129 cdata: Option<CrateMetadataRef<'a>>,
130 sess: Option<&'tcx Session>,
131 tcx: Option<TyCtxt<'tcx>>,
133 // Cache the last used source_file for translating spans as an optimization.
134 last_source_file_index: usize,
136 lazy_state: LazyState,
138 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
139 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
142 /// Abstract over the various ways one can create metadata decoders.
143 pub(super) trait Metadata<'a, 'tcx>: Copy {
144 fn raw_bytes(self) -> &'a [u8];
145 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
148 fn sess(self) -> Option<&'tcx Session> {
151 fn tcx(self) -> Option<TyCtxt<'tcx>> {
155 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
156 let tcx = self.tcx();
158 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
160 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
162 last_source_file_index: 0,
163 lazy_state: LazyState::NoNode,
164 alloc_decoding_session: self
166 .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()),
171 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
172 fn raw_bytes(self) -> &'a [u8] {
177 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
178 fn raw_bytes(self) -> &'a [u8] {
179 let (blob, _) = self;
183 fn sess(self) -> Option<&'tcx Session> {
184 let (_, sess) = self;
189 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadataRef<'a> {
190 fn raw_bytes(self) -> &'a [u8] {
191 self.blob.raw_bytes()
193 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
198 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, &'tcx Session) {
199 fn raw_bytes(self) -> &'a [u8] {
202 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
205 fn sess(self) -> Option<&'tcx Session> {
210 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, TyCtxt<'tcx>) {
211 fn raw_bytes(self) -> &'a [u8] {
214 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
217 fn tcx(self) -> Option<TyCtxt<'tcx>> {
222 impl<'a, 'tcx, T: Decodable> Lazy<T> {
223 fn decode<M: Metadata<'a, 'tcx>>(self, metadata: M) -> T {
224 let mut dcx = metadata.decoder(self.position.get());
225 dcx.lazy_state = LazyState::NodeStart(self.position);
226 T::decode(&mut dcx).unwrap()
230 impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable> Lazy<[T]> {
231 fn decode<M: Metadata<'a, 'tcx>>(
234 ) -> impl ExactSizeIterator<Item = T> + Captures<'a> + Captures<'tcx> + 'x {
235 let mut dcx = metadata.decoder(self.position.get());
236 dcx.lazy_state = LazyState::NodeStart(self.position);
237 (0..self.meta).map(move |_| T::decode(&mut dcx).unwrap())
241 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
242 fn tcx(&self) -> TyCtxt<'tcx> {
243 self.tcx.expect("missing TyCtxt in DecodeContext")
246 fn cdata(&self) -> CrateMetadataRef<'a> {
247 self.cdata.expect("missing CrateMetadata in DecodeContext")
250 fn read_lazy_with_meta<T: ?Sized + LazyMeta>(
253 ) -> Result<Lazy<T>, <Self as Decoder>::Error> {
254 let min_size = T::min_size(meta);
255 let distance = self.read_usize()?;
256 let position = match self.lazy_state {
257 LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
258 LazyState::NodeStart(start) => {
259 let start = start.get();
260 assert!(distance + min_size <= start);
261 start - distance - min_size
263 LazyState::Previous(last_min_end) => last_min_end.get() + distance,
265 self.lazy_state = LazyState::Previous(NonZeroUsize::new(position + min_size).unwrap());
266 Ok(Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta))
270 impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> {
272 fn tcx(&self) -> TyCtxt<'tcx> {
273 self.tcx.expect("missing TyCtxt in DecodeContext")
277 fn peek_byte(&self) -> u8 {
278 self.opaque.data[self.opaque.position()]
282 fn position(&self) -> usize {
283 self.opaque.position()
286 fn cached_ty_for_shorthand<F>(
290 ) -> Result<Ty<'tcx>, Self::Error>
292 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
294 let tcx = self.tcx();
296 let key = ty::CReaderCacheKey { cnum: self.cdata().cnum, pos: shorthand };
298 if let Some(&ty) = tcx.rcache.borrow().get(&key) {
302 let ty = or_insert_with(self)?;
303 tcx.rcache.borrow_mut().insert(key, ty);
307 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
309 F: FnOnce(&mut Self) -> R,
311 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
312 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
313 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
315 self.opaque = old_opaque;
316 self.lazy_state = old_state;
320 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
321 if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] }
325 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
326 fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
327 self.read_lazy_with_meta(())
331 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<[T]>> for DecodeContext<'a, 'tcx> {
332 fn specialized_decode(&mut self) -> Result<Lazy<[T]>, Self::Error> {
333 let len = self.read_usize()?;
334 if len == 0 { Ok(Lazy::empty()) } else { self.read_lazy_with_meta(len) }
338 impl<'a, 'tcx, I: Idx, T> SpecializedDecoder<Lazy<Table<I, T>>> for DecodeContext<'a, 'tcx>
340 Option<T>: FixedSizeEncoding,
342 fn specialized_decode(&mut self) -> Result<Lazy<Table<I, T>>, Self::Error> {
343 let len = self.read_usize()?;
344 self.read_lazy_with_meta(len)
348 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
350 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
351 let krate = CrateNum::decode(self)?;
352 let index = DefIndex::decode(self)?;
354 Ok(DefId { krate, index })
358 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
360 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
361 Ok(DefIndex::from_u32(self.read_u32()?))
365 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for DecodeContext<'a, 'tcx> {
367 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
368 self.specialized_decode().map(|i| LocalDefId::from_def_id(i))
372 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
373 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
374 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
375 alloc_decoding_session.decode_alloc_id(self)
377 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
382 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
383 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
384 let tag = u8::decode(self)?;
386 if tag == TAG_INVALID_SPAN {
390 debug_assert_eq!(tag, TAG_VALID_SPAN);
392 let lo = BytePos::decode(self)?;
393 let len = BytePos::decode(self)?;
396 let sess = if let Some(sess) = self.sess {
399 bug!("Cannot decode Span without Session.")
402 let imported_source_files = self.cdata().imported_source_files(&sess.source_map());
404 // Optimize for the case that most spans within a translated item
405 // originate from the same source_file.
406 let last_source_file = &imported_source_files[self.last_source_file_index];
408 if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos
412 let index = imported_source_files
413 .binary_search_by_key(&lo, |source_file| source_file.original_start_pos)
414 .unwrap_or_else(|index| index - 1);
416 self.last_source_file_index = index;
417 &imported_source_files[index]
421 // Make sure our binary search above is correct.
422 debug_assert!(lo >= source_file.original_start_pos && lo <= source_file.original_end_pos);
424 // Make sure we correctly filtered out invalid spans during encoding
425 debug_assert!(hi >= source_file.original_start_pos && hi <= source_file.original_end_pos);
428 (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
430 (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
432 Ok(Span::with_root_ctxt(lo, hi))
436 impl SpecializedDecoder<Ident> for DecodeContext<'_, '_> {
437 fn specialized_decode(&mut self) -> Result<Ident, Self::Error> {
438 // FIXME(jseyfried): intercrate hygiene
440 Ok(Ident::with_dummy_span(Symbol::decode(self)?))
444 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
445 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
446 Fingerprint::decode_opaque(&mut self.opaque)
450 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
451 for DecodeContext<'a, 'tcx>
454 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
455 Ok(mir::ClearCrossCrate::Clear)
459 implement_ty_decoder!(DecodeContext<'a, 'tcx>);
462 crate fn new(metadata_ref: MetadataRef) -> MetadataBlob {
463 MetadataBlob(metadata_ref)
466 crate fn is_compatible(&self) -> bool {
467 self.raw_bytes().starts_with(METADATA_HEADER)
470 crate fn get_rustc_version(&self) -> String {
471 Lazy::<String>::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap())
475 crate fn get_root(&self) -> CrateRoot<'tcx> {
476 let slice = self.raw_bytes();
477 let offset = METADATA_HEADER.len();
478 let pos = (((slice[offset + 0] as u32) << 24)
479 | ((slice[offset + 1] as u32) << 16)
480 | ((slice[offset + 2] as u32) << 8)
481 | ((slice[offset + 3] as u32) << 0)) as usize;
482 Lazy::<CrateRoot<'tcx>>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self)
485 crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> {
486 write!(out, "=External Dependencies=\n")?;
487 let root = self.get_root();
488 for (i, dep) in root.crate_deps.decode(self).enumerate() {
489 write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
497 fn def_kind(&self) -> Option<DefKind> {
499 EntryKind::Const(..) => DefKind::Const,
500 EntryKind::AssocConst(..) => DefKind::AssocConst,
502 | EntryKind::MutStatic
503 | EntryKind::ForeignImmStatic
504 | EntryKind::ForeignMutStatic => DefKind::Static,
505 EntryKind::Struct(_, _) => DefKind::Struct,
506 EntryKind::Union(_, _) => DefKind::Union,
507 EntryKind::Fn(_) | EntryKind::ForeignFn(_) => DefKind::Fn,
508 EntryKind::Method(_) => DefKind::AssocFn,
509 EntryKind::Type => DefKind::TyAlias,
510 EntryKind::TypeParam => DefKind::TyParam,
511 EntryKind::ConstParam => DefKind::ConstParam,
512 EntryKind::OpaqueTy => DefKind::OpaqueTy,
513 EntryKind::AssocType(_) => DefKind::AssocTy,
514 EntryKind::AssocOpaqueTy(_) => DefKind::AssocOpaqueTy,
515 EntryKind::Mod(_) => DefKind::Mod,
516 EntryKind::Variant(_) => DefKind::Variant,
517 EntryKind::Trait(_) => DefKind::Trait,
518 EntryKind::TraitAlias => DefKind::TraitAlias,
519 EntryKind::Enum(..) => DefKind::Enum,
520 EntryKind::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
521 EntryKind::ForeignType => DefKind::ForeignTy,
523 EntryKind::ForeignMod
524 | EntryKind::GlobalAsm
527 | EntryKind::Generator(_)
528 | EntryKind::Closure => return None,
534 crate fn is_proc_macro_crate(&self) -> bool {
535 self.proc_macro_data.is_some()
538 crate fn name(&self) -> Symbol {
542 crate fn disambiguator(&self) -> CrateDisambiguator {
546 crate fn hash(&self) -> Svh {
550 crate fn triple(&self) -> &TargetTriple {
554 crate fn decode_crate_deps(
556 metadata: &'a MetadataBlob,
557 ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
558 self.crate_deps.decode(metadata)
562 impl<'a, 'tcx> CrateMetadataRef<'a> {
563 fn is_proc_macro(&self, id: DefIndex) -> bool {
564 self.root.proc_macro_data.and_then(|data| data.decode(self).find(|x| *x == id)).is_some()
567 fn maybe_kind(&self, item_id: DefIndex) -> Option<EntryKind> {
568 self.root.per_def.kind.get(self, item_id).map(|k| k.decode(self))
571 fn kind(&self, item_id: DefIndex) -> EntryKind {
572 assert!(!self.is_proc_macro(item_id));
573 self.maybe_kind(item_id).unwrap_or_else(|| {
575 "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}",
583 fn raw_proc_macro(&self, id: DefIndex) -> &ProcMacro {
584 // DefIndex's in root.proc_macro_data have a one-to-one correspondence
585 // with items in 'raw_proc_macros'.
586 let pos = self.root.proc_macro_data.unwrap().decode(self).position(|i| i == id).unwrap();
587 &self.raw_proc_macros.unwrap()[pos]
590 fn item_name(&self, item_index: DefIndex) -> Symbol {
591 if !self.is_proc_macro(item_index) {
592 self.def_key(item_index)
596 .expect("no name in item_name")
598 Symbol::intern(self.raw_proc_macro(item_index).name())
602 fn def_kind(&self, index: DefIndex) -> Option<DefKind> {
603 if !self.is_proc_macro(index) {
604 self.kind(index).def_kind()
606 Some(DefKind::Macro(macro_kind(self.raw_proc_macro(index))))
610 fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
611 self.root.per_def.span.get(self, index).unwrap().decode((self, sess))
614 fn load_proc_macro(&self, id: DefIndex, sess: &Session) -> SyntaxExtension {
615 let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
616 ProcMacro::CustomDerive { trait_name, attributes, client } => {
618 attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
621 SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
625 ProcMacro::Attr { name, client } => {
626 (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new())
628 ProcMacro::Bang { name, client } => {
629 (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new())
633 SyntaxExtension::new(
636 self.get_span(id, sess),
639 Symbol::intern(name),
640 &self.get_item_attrs(id, sess),
644 fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
645 match self.kind(item_id) {
646 EntryKind::Trait(data) => {
647 let data = data.decode((self, sess));
649 self.local_def_id(item_id),
654 self.def_path_table.def_path_hash(item_id),
657 EntryKind::TraitAlias => ty::TraitDef::new(
658 self.local_def_id(item_id),
659 hir::Unsafety::Normal,
663 self.def_path_table.def_path_hash(item_id),
665 _ => bug!("def-index does not refer to trait or trait alias"),
675 ) -> ty::VariantDef {
676 let data = match kind {
677 EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => {
683 let adt_kind = match kind {
684 EntryKind::Variant(_) => ty::AdtKind::Enum,
685 EntryKind::Struct(..) => ty::AdtKind::Struct,
686 EntryKind::Union(..) => ty::AdtKind::Union,
691 if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
692 let ctor_did = data.ctor.map(|index| self.local_def_id(index));
696 Ident::with_dummy_span(self.item_name(index)),
704 .unwrap_or(Lazy::empty())
706 .map(|index| ty::FieldDef {
707 did: self.local_def_id(index),
708 ident: Ident::with_dummy_span(self.item_name(index)),
709 vis: self.get_visibility(index),
719 fn get_adt_def(&self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef {
720 let kind = self.kind(item_id);
721 let did = self.local_def_id(item_id);
723 let (adt_kind, repr) = match kind {
724 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
725 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
726 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
727 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
730 let variants = if let ty::AdtKind::Enum = adt_kind {
735 .unwrap_or(Lazy::empty())
737 .map(|index| self.get_variant(tcx, &self.kind(index), index, did))
740 std::iter::once(self.get_variant(tcx, &kind, item_id, did)).collect()
743 tcx.alloc_adt_def(did, adt_kind, variants, repr)
746 fn get_explicit_predicates(
750 ) -> ty::GenericPredicates<'tcx> {
751 self.root.per_def.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx))
754 fn get_inferred_outlives(
758 ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
763 .map(|predicates| predicates.decode((self, tcx)))
767 fn get_super_predicates(
771 ) -> ty::GenericPredicates<'tcx> {
772 self.root.per_def.super_predicates.get(self, item_id).unwrap().decode((self, tcx))
775 fn get_generics(&self, item_id: DefIndex, sess: &Session) -> ty::Generics {
776 self.root.per_def.generics.get(self, item_id).unwrap().decode((self, sess))
779 fn get_type(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
780 self.root.per_def.ty.get(self, id).unwrap().decode((self, tcx))
783 fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
784 match self.is_proc_macro(id) {
785 true => self.root.proc_macro_stability,
786 false => self.root.per_def.stability.get(self, id).map(|stab| stab.decode(self)),
790 fn get_const_stability(&self, id: DefIndex) -> Option<attr::ConstStability> {
791 self.root.per_def.const_stability.get(self, id).map(|stab| stab.decode(self))
794 fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
799 .filter(|_| !self.is_proc_macro(id))
800 .map(|depr| depr.decode(self))
803 fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
804 match self.is_proc_macro(id) {
805 true => ty::Visibility::Public,
806 false => self.root.per_def.visibility.get(self, id).unwrap().decode(self),
810 fn get_impl_data(&self, id: DefIndex) -> ImplData {
811 match self.kind(id) {
812 EntryKind::Impl(data) => data.decode(self),
817 fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
818 self.get_impl_data(id).parent_impl
821 fn get_impl_polarity(&self, id: DefIndex) -> ty::ImplPolarity {
822 self.get_impl_data(id).polarity
825 fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
826 self.get_impl_data(id).defaultness
829 fn get_coerce_unsized_info(&self, id: DefIndex) -> Option<ty::adjustment::CoerceUnsizedInfo> {
830 self.get_impl_data(id).coerce_unsized_info
833 fn get_impl_trait(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option<ty::TraitRef<'tcx>> {
834 self.root.per_def.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx)))
837 /// Iterates over all the stability attributes in the given crate.
838 fn get_lib_features(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(ast::Name, Option<ast::Name>)] {
839 // FIXME: For a proc macro crate, not sure whether we should return the "host"
840 // features or an empty Vec. Both don't cause ICEs.
841 tcx.arena.alloc_from_iter(self.root.lib_features.decode(self))
844 /// Iterates over the language items in the given crate.
845 fn get_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] {
846 if self.root.is_proc_macro_crate() {
847 // Proc macro crates do not export any lang-items to the target.
850 tcx.arena.alloc_from_iter(
854 .map(|(def_index, index)| (self.local_def_id(def_index), index)),
859 /// Iterates over the diagnostic items in the given crate.
860 fn get_diagnostic_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx FxHashMap<Symbol, DefId> {
861 tcx.arena.alloc(if self.root.is_proc_macro_crate() {
862 // Proc macro crates do not export any diagnostic-items to the target.
868 .map(|(name, def_index)| (name, self.local_def_id(def_index)))
873 /// Iterates over each child of the given item.
874 fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
876 F: FnMut(Export<hir::HirId>),
878 if let Some(proc_macros_ids) = self.root.proc_macro_data.map(|d| d.decode(self)) {
879 /* If we are loading as a proc macro, we want to return the view of this crate
880 * as a proc macro crate.
882 if id == CRATE_DEF_INDEX {
883 for def_index in proc_macros_ids {
884 let raw_macro = self.raw_proc_macro(def_index);
886 DefKind::Macro(macro_kind(raw_macro)),
887 self.local_def_id(def_index),
889 let ident = Ident::from_str(raw_macro.name());
890 callback(Export { ident, res, vis: ty::Visibility::Public, span: DUMMY_SP });
897 let kind = match self.maybe_kind(id) {
902 // Iterate over all children.
903 let macros_only = self.dep_kind.lock().macros_only();
904 let children = self.root.per_def.children.get(self, id).unwrap_or(Lazy::empty());
905 for child_index in children.decode((self, sess)) {
911 if let Some(child_kind) = self.maybe_kind(child_index) {
913 EntryKind::MacroDef(..) => {}
914 _ if macros_only => continue,
918 // Hand off the item to the callback.
920 // FIXME(eddyb) Don't encode these in children.
921 EntryKind::ForeignMod => {
922 let child_children = self
926 .get(self, child_index)
927 .unwrap_or(Lazy::empty());
928 for child_index in child_children.decode((self, sess)) {
929 if let Some(kind) = self.def_kind(child_index) {
931 res: Res::Def(kind, self.local_def_id(child_index)),
932 ident: Ident::with_dummy_span(self.item_name(child_index)),
933 vis: self.get_visibility(child_index),
938 .get(self, child_index)
940 .decode((self, sess)),
946 EntryKind::Impl(_) => continue,
951 let def_key = self.def_key(child_index);
952 let span = self.get_span(child_index, sess);
953 if let (Some(kind), Some(name)) =
954 (self.def_kind(child_index), def_key.disambiguated_data.data.get_opt_name())
956 let ident = Ident::with_dummy_span(name);
957 let vis = self.get_visibility(child_index);
958 let def_id = self.local_def_id(child_index);
959 let res = Res::Def(kind, def_id);
960 callback(Export { res, ident, vis, span });
961 // For non-re-export structs and variants add their constructors to children.
962 // Re-export lists automatically contain constructors when necessary.
965 if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
966 let ctor_kind = self.get_ctor_kind(child_index);
968 Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
969 let vis = self.get_visibility(ctor_def_id.index);
970 callback(Export { res: ctor_res, vis, ident, span });
973 DefKind::Variant => {
974 // Braced variants, unlike structs, generate unusable names in
975 // value namespace, they are reserved for possible future use.
976 // It's ok to use the variant's id as a ctor id since an
977 // error will be reported on any use of such resolution anyway.
978 let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
979 let ctor_kind = self.get_ctor_kind(child_index);
981 Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
982 let mut vis = self.get_visibility(ctor_def_id.index);
983 if ctor_def_id == def_id && vis == ty::Visibility::Public {
984 // For non-exhaustive variants lower the constructor visibility to
985 // within the crate. We only need this for fictive constructors,
986 // for other constructors correct visibilities
987 // were already encoded in metadata.
988 let attrs = self.get_item_attrs(def_id.index, sess);
989 if attr::contains_name(&attrs, sym::non_exhaustive) {
990 let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
991 vis = ty::Visibility::Restricted(crate_def_id);
994 callback(Export { res: ctor_res, ident, vis, span });
1002 if let EntryKind::Mod(data) = kind {
1003 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
1005 Res::Def(DefKind::Macro(..), _) => {}
1006 _ if macros_only => continue,
1014 fn is_item_mir_available(&self, id: DefIndex) -> bool {
1015 !self.is_proc_macro(id) && self.root.per_def.mir.get(self, id).is_some()
1018 fn get_optimized_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> BodyAndCache<'tcx> {
1019 let mut cache = self
1024 .filter(|_| !self.is_proc_macro(id))
1025 .unwrap_or_else(|| {
1026 bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id))
1028 .decode((self, tcx));
1029 cache.ensure_predecessors();
1033 fn get_promoted_mir(
1037 ) -> IndexVec<Promoted, BodyAndCache<'tcx>> {
1038 let mut cache = self
1043 .filter(|_| !self.is_proc_macro(id))
1044 .unwrap_or_else(|| {
1045 bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id))
1047 .decode((self, tcx));
1048 for body in cache.iter_mut() {
1049 body.ensure_predecessors();
1054 fn mir_const_qualif(&self, id: DefIndex) -> mir::ConstQualifs {
1055 match self.kind(id) {
1056 EntryKind::Const(qualif, _)
1057 | EntryKind::AssocConst(AssocContainer::ImplDefault, qualif, _)
1058 | EntryKind::AssocConst(AssocContainer::ImplFinal, qualif, _) => qualif,
1063 fn get_associated_item(&self, id: DefIndex) -> ty::AssocItem {
1064 let def_key = self.def_key(id);
1065 let parent = self.local_def_id(def_key.parent.unwrap());
1066 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
1068 let (kind, container, has_self) = match self.kind(id) {
1069 EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false),
1070 EntryKind::Method(data) => {
1071 let data = data.decode(self);
1072 (ty::AssocKind::Method, data.container, data.has_self)
1074 EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false),
1075 EntryKind::AssocOpaqueTy(container) => (ty::AssocKind::OpaqueTy, container, false),
1076 _ => bug!("cannot get associated-item of `{:?}`", def_key),
1080 ident: Ident::with_dummy_span(name),
1082 vis: self.get_visibility(id),
1083 defaultness: container.defaultness(),
1084 def_id: self.local_def_id(id),
1085 container: container.with_def_id(parent),
1086 method_has_self_argument: has_self,
1090 fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
1091 self.root.per_def.variances.get(self, id).unwrap_or(Lazy::empty()).decode(self).collect()
1094 fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
1095 match self.kind(node_id) {
1096 EntryKind::Struct(data, _) | EntryKind::Union(data, _) | EntryKind::Variant(data) => {
1097 data.decode(self).ctor_kind
1099 _ => CtorKind::Fictive,
1103 fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
1104 match self.kind(node_id) {
1105 EntryKind::Struct(data, _) => {
1106 data.decode(self).ctor.map(|index| self.local_def_id(index))
1108 EntryKind::Variant(data) => {
1109 data.decode(self).ctor.map(|index| self.local_def_id(index))
1115 fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
1116 // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
1117 // we assume that someone passing in a tuple struct ctor is actually wanting to
1118 // look at the definition
1119 let def_key = self.def_key(node_id);
1120 let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
1121 def_key.parent.unwrap()
1131 .unwrap_or(Lazy::empty())
1132 .decode((self, sess))
1133 .collect::<Vec<_>>(),
1137 fn get_struct_field_names(&self, id: DefIndex, sess: &Session) -> Vec<Spanned<ast::Name>> {
1142 .unwrap_or(Lazy::empty())
1144 .map(|index| respan(self.get_span(index, sess), self.item_name(index)))
1148 fn get_inherent_implementations_for_type(
1152 ) -> &'tcx [DefId] {
1153 tcx.arena.alloc_from_iter(
1158 .unwrap_or(Lazy::empty())
1160 .map(|index| self.local_def_id(index)),
1164 fn get_implementations_for_trait(
1167 filter: Option<DefId>,
1168 ) -> &'tcx [DefId] {
1169 if self.root.is_proc_macro_crate() {
1170 // proc-macro crates export no trait impls.
1174 // Do a reverse lookup beforehand to avoid touching the crate_num
1175 // hash map in the loop below.
1176 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1177 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1178 Some(None) => return &[],
1182 if let Some(filter) = filter {
1183 if let Some(impls) = self.trait_impls.get(&filter) {
1184 tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx)))
1189 tcx.arena.alloc_from_iter(
1192 .flat_map(|impls| impls.decode(self).map(|idx| self.local_def_id(idx))),
1197 fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1198 let def_key = self.def_key(id);
1199 match def_key.disambiguated_data.data {
1200 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1201 // Not an associated item
1204 def_key.parent.and_then(|parent_index| match self.kind(parent_index) {
1205 EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)),
1210 fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1211 if self.root.is_proc_macro_crate() {
1212 // Proc macro crates do not have any *target* native libraries.
1215 self.root.native_libraries.decode((self, sess)).collect()
1219 fn get_foreign_modules(&self, tcx: TyCtxt<'tcx>) -> &'tcx [ForeignModule] {
1220 if self.root.is_proc_macro_crate() {
1221 // Proc macro crates do not have any *target* foreign modules.
1224 tcx.arena.alloc_from_iter(self.root.foreign_modules.decode((self, tcx.sess)))
1228 fn get_dylib_dependency_formats(
1231 ) -> &'tcx [(CrateNum, LinkagePreference)] {
1232 tcx.arena.alloc_from_iter(
1233 self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| {
1234 let cnum = CrateNum::new(i + 1);
1235 link.map(|link| (self.cnum_map[cnum], link))
1240 fn get_missing_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] {
1241 if self.root.is_proc_macro_crate() {
1242 // Proc macro crates do not depend on any target weak lang-items.
1245 tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self))
1249 fn get_fn_param_names(&self, id: DefIndex) -> Vec<ast::Name> {
1250 let param_names = match self.kind(id) {
1251 EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names,
1252 EntryKind::Method(data) => data.decode(self).fn_data.param_names,
1255 param_names.decode(self).collect()
1258 fn exported_symbols(
1261 ) -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1262 if self.root.is_proc_macro_crate() {
1263 // If this crate is a custom derive crate, then we're not even going to
1264 // link those in so we skip those crates.
1267 self.root.exported_symbols.decode((self, tcx)).collect()
1271 fn get_rendered_const(&self, id: DefIndex) -> String {
1272 match self.kind(id) {
1273 EntryKind::Const(_, data) | EntryKind::AssocConst(_, _, data) => data.decode(self).0,
1278 fn get_macro(&self, id: DefIndex, sess: &Session) -> MacroDef {
1279 match self.kind(id) {
1280 EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)),
1285 // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we
1286 // don't serialize constness for tuple variant and tuple struct constructors.
1287 fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1288 let constness = match self.kind(id) {
1289 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1290 EntryKind::Fn(data) => data.decode(self).constness,
1291 // Some intrinsics can be const fn. While we could recompute this (at least until we
1292 // stop having hardcoded whitelists and move to stability attributes), it seems cleaner
1293 // to treat all const fns equally.
1294 EntryKind::ForeignFn(data) => data.decode(self).constness,
1295 EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const,
1296 _ => hir::Constness::NotConst,
1298 constness == hir::Constness::Const
1301 fn asyncness(&self, id: DefIndex) -> hir::IsAsync {
1302 match self.kind(id) {
1303 EntryKind::Fn(data) => data.decode(self).asyncness,
1304 EntryKind::Method(data) => data.decode(self).fn_data.asyncness,
1305 EntryKind::ForeignFn(data) => data.decode(self).asyncness,
1306 _ => bug!("asyncness: expected function kind"),
1310 fn is_foreign_item(&self, id: DefIndex) -> bool {
1311 match self.kind(id) {
1312 EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => {
1319 fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1320 match self.kind(id) {
1321 EntryKind::ImmStatic | EntryKind::ForeignImmStatic => Some(hir::Mutability::Not),
1322 EntryKind::MutStatic | EntryKind::ForeignMutStatic => Some(hir::Mutability::Mut),
1327 fn generator_kind(&self, id: DefIndex) -> Option<hir::GeneratorKind> {
1328 match self.kind(id) {
1329 EntryKind::Generator(data) => Some(data),
1334 fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
1335 self.root.per_def.fn_sig.get(self, id).unwrap().decode((self, tcx))
1339 fn def_key(&self, index: DefIndex) -> DefKey {
1340 let mut key = self.def_path_table.def_key(index);
1341 if self.is_proc_macro(index) {
1342 let name = self.raw_proc_macro(index).name();
1343 key.disambiguated_data.data = DefPathData::MacroNs(Symbol::intern(name));
1348 // Returns the path leading to the thing with this `id`.
1349 fn def_path(&self, id: DefIndex) -> DefPath {
1350 debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1351 DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1354 /// Imports the source_map from an external crate into the source_map of the crate
1355 /// currently being compiled (the "local crate").
1357 /// The import algorithm works analogous to how AST items are inlined from an
1358 /// external crate's metadata:
1359 /// For every SourceFile in the external source_map an 'inline' copy is created in the
1360 /// local source_map. The correspondence relation between external and local
1361 /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1362 /// function. When an item from an external crate is later inlined into this
1363 /// crate, this correspondence information is used to translate the span
1364 /// information of the inlined item so that it refers the correct positions in
1365 /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1367 /// The import algorithm in the function below will reuse SourceFiles already
1368 /// existing in the local source_map. For example, even if the SourceFile of some
1369 /// source file of libstd gets imported many times, there will only ever be
1370 /// one SourceFile object for the corresponding file in the local source_map.
1372 /// Note that imported SourceFiles do not actually contain the source code of the
1373 /// file they represent, just information about length, line breaks, and
1374 /// multibyte characters. This information is enough to generate valid debuginfo
1375 /// for items inlined from other crates.
1377 /// Proc macro crates don't currently export spans, so this function does not have
1378 /// to work for them.
1379 fn imported_source_files(
1381 local_source_map: &source_map::SourceMap,
1382 ) -> &'a [ImportedSourceFile] {
1383 self.cdata.source_map_import_info.init_locking(|| {
1384 let external_source_map = self.root.source_map.decode(self);
1387 .map(|source_file_to_import| {
1388 // We can't reuse an existing SourceFile, so allocate a new one
1389 // containing the information we need.
1390 let rustc_span::SourceFile {
1397 mut multibyte_chars,
1398 mut non_narrow_chars,
1402 } = source_file_to_import;
1404 let source_length = (end_pos - start_pos).to_usize();
1406 // Translate line-start positions and multibyte character
1407 // position into frame of reference local to file.
1408 // `SourceMap::new_imported_source_file()` will then translate those
1409 // coordinates to their new global frame of reference when the
1410 // offset of the SourceFile is known.
1411 for pos in &mut lines {
1412 *pos = *pos - start_pos;
1414 for mbc in &mut multibyte_chars {
1415 mbc.pos = mbc.pos - start_pos;
1417 for swc in &mut non_narrow_chars {
1418 *swc = *swc - start_pos;
1420 for np in &mut normalized_pos {
1421 np.pos = np.pos - start_pos;
1424 let local_version = local_source_map.new_imported_source_file(
1437 "CrateMetaData::imported_source_files alloc \
1438 source_file {:?} original (start_pos {:?} end_pos {:?}) \
1439 translated (start_pos {:?} end_pos {:?})",
1443 local_version.start_pos,
1444 local_version.end_pos
1447 ImportedSourceFile {
1448 original_start_pos: start_pos,
1449 original_end_pos: end_pos,
1450 translated_source_file: local_version,
1458 impl CrateMetadata {
1462 root: CrateRoot<'static>,
1463 raw_proc_macros: Option<&'static [ProcMacro]>,
1465 cnum_map: CrateNumMap,
1467 source: CrateSource,
1469 host_hash: Option<Svh>,
1470 ) -> CrateMetadata {
1471 let def_path_table = record_time(&sess.perf_stats.decode_def_path_tables_time, || {
1472 root.def_path_table.decode((&blob, sess))
1474 let trait_impls = root
1476 .decode((&blob, sess))
1477 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1479 let alloc_decoding_state =
1480 AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
1481 let dependencies = Lock::new(cnum_map.iter().cloned().collect());
1488 source_map_import_info: Once::new(),
1489 alloc_decoding_state,
1490 dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
1494 dep_kind: Lock::new(dep_kind),
1498 extern_crate: Lock::new(None),
1502 crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
1503 self.dependencies.borrow()
1506 crate fn add_dependency(&self, cnum: CrateNum) {
1507 self.dependencies.borrow_mut().push(cnum);
1510 crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool {
1511 let mut extern_crate = self.extern_crate.borrow_mut();
1512 let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank);
1514 *extern_crate = Some(new_extern_crate);
1519 crate fn source(&self) -> &CrateSource {
1523 crate fn dep_kind(&self) -> DepKind {
1524 *self.dep_kind.lock()
1527 crate fn update_dep_kind(&self, f: impl FnOnce(DepKind) -> DepKind) {
1528 self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
1531 crate fn panic_strategy(&self) -> PanicStrategy {
1532 self.root.panic_strategy
1535 crate fn needs_panic_runtime(&self) -> bool {
1536 self.root.needs_panic_runtime
1539 crate fn is_panic_runtime(&self) -> bool {
1540 self.root.panic_runtime
1543 crate fn is_profiler_runtime(&self) -> bool {
1544 self.root.profiler_runtime
1547 crate fn needs_allocator(&self) -> bool {
1548 self.root.needs_allocator
1551 crate fn has_global_allocator(&self) -> bool {
1552 self.root.has_global_allocator
1555 crate fn has_default_lib_allocator(&self) -> bool {
1556 self.root.has_default_lib_allocator
1559 crate fn is_proc_macro_crate(&self) -> bool {
1560 self.root.is_proc_macro_crate()
1563 crate fn name(&self) -> Symbol {
1567 crate fn disambiguator(&self) -> CrateDisambiguator {
1568 self.root.disambiguator
1571 crate fn hash(&self) -> Svh {
1575 fn local_def_id(&self, index: DefIndex) -> DefId {
1576 DefId { krate: self.cnum, index }
1579 // Translate a DefId from the current compilation environment to a DefId
1580 // for an external crate.
1581 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1582 for (local, &global) in self.cnum_map.iter_enumerated() {
1583 if global == did.krate {
1584 return Some(DefId { krate: local, index: did.index });
1592 fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1593 self.def_path_table.def_path_hash(index)
1596 /// Get the `DepNodeIndex` corresponding this crate. The result of this
1597 /// method is cached in the `dep_node_index` field.
1598 fn get_crate_dep_node_index(&self, tcx: TyCtxt<'tcx>) -> DepNodeIndex {
1599 let mut dep_node_index = self.dep_node_index.load();
1601 if unlikely!(dep_node_index == DepNodeIndex::INVALID) {
1602 // We have not cached the DepNodeIndex for this upstream crate yet,
1603 // so use the dep-graph to find it out and cache it.
1604 // Note that multiple threads can enter this block concurrently.
1605 // That is fine because the DepNodeIndex remains constant
1606 // throughout the whole compilation session, and multiple stores
1607 // would always write the same value.
1609 let def_path_hash = self.def_path_hash(CRATE_DEF_INDEX);
1611 DepNode::from_def_path_hash(def_path_hash, dep_graph::DepKind::CrateMetadata);
1613 dep_node_index = tcx.dep_graph.dep_node_index_of(&dep_node);
1614 assert!(dep_node_index != DepNodeIndex::INVALID);
1615 self.dep_node_index.store(dep_node_index);
1622 // Cannot be implemented on 'ProcMacro', as libproc_macro
1623 // does not depend on librustc_ast
1624 fn macro_kind(raw: &ProcMacro) -> MacroKind {
1626 ProcMacro::CustomDerive { .. } => MacroKind::Derive,
1627 ProcMacro::Attr { .. } => MacroKind::Attr,
1628 ProcMacro::Bang { .. } => MacroKind::Bang,