1 // Decoding metadata from a single crate's metadata
3 use crate::cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary, ForeignModule};
6 use rustc_data_structures::indexed_vec::IndexVec;
7 use rustc_data_structures::sync::{Lrc, ReadGuard};
8 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash};
10 use rustc::middle::cstore::LinkagePreference;
11 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
12 use rustc::hir::def::{self, Res, DefKind, CtorOf, CtorKind};
13 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
14 use rustc_data_structures::fingerprint::Fingerprint;
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc::middle::lang_items;
17 use rustc::mir::{self, interpret};
18 use rustc::mir::interpret::AllocDecodingSession;
19 use rustc::session::Session;
20 use rustc::ty::{self, Ty, TyCtxt};
21 use rustc::ty::codec::TyDecoder;
22 use rustc::mir::{Body, Promoted};
23 use rustc::util::captures::Captures;
29 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
31 use syntax::ast::{self, Ident};
32 use syntax::source_map;
33 use syntax::symbol::{Symbol, sym};
34 use syntax::ext::base::{MacroKind, SyntaxExtensionKind, SyntaxExtension};
35 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, symbol::{InternedString}};
37 use proc_macro::bridge::client::ProcMacro;
38 use syntax::ext::proc_macro::{AttrProcMacro, ProcMacroDerive, BangProcMacro};
40 pub struct DecodeContext<'a, 'tcx> {
41 opaque: opaque::Decoder<'a>,
42 cdata: Option<&'a CrateMetadata>,
43 sess: Option<&'tcx Session>,
44 tcx: Option<TyCtxt<'tcx>>,
46 // Cache the last used source_file for translating spans as an optimization.
47 last_source_file_index: usize,
49 lazy_state: LazyState,
51 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
52 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
55 /// Abstract over the various ways one can create metadata decoders.
56 pub trait Metadata<'a, 'tcx>: Copy {
57 fn raw_bytes(self) -> &'a [u8];
58 fn cdata(self) -> Option<&'a CrateMetadata> { None }
59 fn sess(self) -> Option<&'tcx Session> { None }
60 fn tcx(self) -> Option<TyCtxt<'tcx>> { None }
62 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
65 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
67 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
69 last_source_file_index: 0,
70 lazy_state: LazyState::NoNode,
71 alloc_decoding_session: self.cdata().map(|cdata| {
72 cdata.alloc_decoding_state.new_decoding_session()
78 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
79 fn raw_bytes(self) -> &'a [u8] {
85 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
86 fn raw_bytes(self) -> &'a [u8] {
91 fn sess(self) -> Option<&'tcx Session> {
98 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
99 fn raw_bytes(self) -> &'a [u8] {
100 self.blob.raw_bytes()
102 fn cdata(self) -> Option<&'a CrateMetadata> {
107 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'tcx Session) {
108 fn raw_bytes(self) -> &'a [u8] {
111 fn cdata(self) -> Option<&'a CrateMetadata> {
114 fn sess(self) -> Option<&'tcx Session> {
119 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'tcx>) {
120 fn raw_bytes(self) -> &'a [u8] {
123 fn cdata(self) -> Option<&'a CrateMetadata> {
126 fn tcx(self) -> Option<TyCtxt<'tcx>> {
131 impl<'a, 'tcx, T: Decodable> Lazy<T> {
132 pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
133 let mut dcx = meta.decoder(self.position);
134 dcx.lazy_state = LazyState::NodeStart(self.position);
135 T::decode(&mut dcx).unwrap()
139 impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable> Lazy<[T]> {
140 pub fn decode<M: Metadata<'a, 'tcx>>(
143 ) -> impl ExactSizeIterator<Item = T> + Captures<'a> + Captures<'tcx> + 'x {
144 let mut dcx = meta.decoder(self.position);
145 dcx.lazy_state = LazyState::NodeStart(self.position);
146 (0..self.meta).map(move |_| T::decode(&mut dcx).unwrap())
150 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
151 pub fn tcx(&self) -> TyCtxt<'tcx> {
152 self.tcx.expect("missing TyCtxt in DecodeContext")
155 pub fn cdata(&self) -> &'a CrateMetadata {
156 self.cdata.expect("missing CrateMetadata in DecodeContext")
159 fn read_lazy_with_meta<T: ?Sized + LazyMeta>(
162 ) -> Result<Lazy<T>, <Self as Decoder>::Error> {
163 let min_size = T::min_size(meta);
164 let distance = self.read_usize()?;
165 let position = match self.lazy_state {
166 LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
167 LazyState::NodeStart(start) => {
168 assert!(distance + min_size <= start);
169 start - distance - min_size
171 LazyState::Previous(last_min_end) => last_min_end + distance,
173 self.lazy_state = LazyState::Previous(position + min_size);
174 Ok(Lazy::from_position_and_meta(position, meta))
178 impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> {
180 fn tcx(&self) -> TyCtxt<'tcx> {
181 self.tcx.expect("missing TyCtxt in DecodeContext")
185 fn peek_byte(&self) -> u8 {
186 self.opaque.data[self.opaque.position()]
190 fn position(&self) -> usize {
191 self.opaque.position()
194 fn cached_ty_for_shorthand<F>(&mut self,
197 -> Result<Ty<'tcx>, Self::Error>
198 where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>
200 let tcx = self.tcx();
202 let key = ty::CReaderCacheKey {
203 cnum: self.cdata().cnum,
207 if let Some(&ty) = tcx.rcache.borrow().get(&key) {
211 let ty = or_insert_with(self)?;
212 tcx.rcache.borrow_mut().insert(key, ty);
216 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
217 where F: FnOnce(&mut Self) -> R
219 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
220 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
221 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
223 self.opaque = old_opaque;
224 self.lazy_state = old_state;
228 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
229 if cnum == LOCAL_CRATE {
232 self.cdata().cnum_map[cnum]
237 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
238 fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
239 self.read_lazy_with_meta(())
243 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<[T]>> for DecodeContext<'a, 'tcx> {
244 fn specialized_decode(&mut self) -> Result<Lazy<[T]>, Self::Error> {
245 let len = self.read_usize()?;
249 self.read_lazy_with_meta(len)
255 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
257 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
258 let krate = CrateNum::decode(self)?;
259 let index = DefIndex::decode(self)?;
268 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
270 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
271 Ok(DefIndex::from_u32(self.read_u32()?))
275 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for DecodeContext<'a, 'tcx> {
277 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
278 self.specialized_decode().map(|i| LocalDefId::from_def_id(i))
282 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
283 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
284 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
285 alloc_decoding_session.decode_alloc_id(self)
287 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
292 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
293 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
294 let tag = u8::decode(self)?;
296 if tag == TAG_INVALID_SPAN {
300 debug_assert_eq!(tag, TAG_VALID_SPAN);
302 let lo = BytePos::decode(self)?;
303 let len = BytePos::decode(self)?;
306 let sess = if let Some(sess) = self.sess {
309 bug!("Cannot decode Span without Session.")
312 let imported_source_files = self.cdata().imported_source_files(&sess.source_map());
314 // Optimize for the case that most spans within a translated item
315 // originate from the same source_file.
316 let last_source_file = &imported_source_files[self.last_source_file_index];
318 if lo >= last_source_file.original_start_pos &&
319 lo <= last_source_file.original_end_pos {
323 let mut b = imported_source_files.len();
327 if imported_source_files[m].original_start_pos > lo {
334 self.last_source_file_index = a;
335 &imported_source_files[a]
339 // Make sure our binary search above is correct.
340 debug_assert!(lo >= source_file.original_start_pos &&
341 lo <= source_file.original_end_pos);
343 // Make sure we correctly filtered out invalid spans during encoding
344 debug_assert!(hi >= source_file.original_start_pos &&
345 hi <= source_file.original_end_pos);
347 let lo = (lo + source_file.translated_source_file.start_pos)
348 - source_file.original_start_pos;
349 let hi = (hi + source_file.translated_source_file.start_pos)
350 - source_file.original_start_pos;
352 Ok(Span::with_root_ctxt(lo, hi))
356 impl SpecializedDecoder<Ident> for DecodeContext<'_, '_> {
357 fn specialized_decode(&mut self) -> Result<Ident, Self::Error> {
358 // FIXME(jseyfried): intercrate hygiene
360 Ok(Ident::with_dummy_span(Symbol::decode(self)?))
364 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
365 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
366 Fingerprint::decode_opaque(&mut self.opaque)
370 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
371 for DecodeContext<'a, 'tcx> {
373 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
374 Ok(mir::ClearCrossCrate::Clear)
378 implement_ty_decoder!( DecodeContext<'a, 'tcx> );
380 impl<'tcx> MetadataBlob {
381 pub fn is_compatible(&self) -> bool {
382 self.raw_bytes().starts_with(METADATA_HEADER)
385 pub fn get_rustc_version(&self) -> String {
386 Lazy::<String>::from_position(METADATA_HEADER.len() + 4).decode(self)
389 pub fn get_root(&self) -> CrateRoot<'tcx> {
390 let slice = self.raw_bytes();
391 let offset = METADATA_HEADER.len();
392 let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
393 ((slice[offset + 2] as u32) << 8) |
394 ((slice[offset + 3] as u32) << 0)) as usize;
395 Lazy::<CrateRoot<'tcx>>::from_position(pos).decode(self)
398 pub fn list_crate_metadata(&self,
399 out: &mut dyn io::Write) -> io::Result<()> {
400 write!(out, "=External Dependencies=\n")?;
401 let root = self.get_root();
402 for (i, dep) in root.crate_deps
405 write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
412 impl<'tcx> EntryKind<'tcx> {
413 fn def_kind(&self) -> Option<DefKind> {
415 EntryKind::Const(..) => DefKind::Const,
416 EntryKind::AssocConst(..) => DefKind::AssocConst,
417 EntryKind::ImmStatic |
418 EntryKind::MutStatic |
419 EntryKind::ForeignImmStatic |
420 EntryKind::ForeignMutStatic => DefKind::Static,
421 EntryKind::Struct(_, _) => DefKind::Struct,
422 EntryKind::Union(_, _) => DefKind::Union,
424 EntryKind::ForeignFn(_) => DefKind::Fn,
425 EntryKind::Method(_) => DefKind::Method,
426 EntryKind::Type => DefKind::TyAlias,
427 EntryKind::TypeParam => DefKind::TyParam,
428 EntryKind::ConstParam => DefKind::ConstParam,
429 EntryKind::OpaqueTy => DefKind::OpaqueTy,
430 EntryKind::AssocType(_) => DefKind::AssocTy,
431 EntryKind::AssocOpaqueTy(_) => DefKind::AssocOpaqueTy,
432 EntryKind::Mod(_) => DefKind::Mod,
433 EntryKind::Variant(_) => DefKind::Variant,
434 EntryKind::Trait(_) => DefKind::Trait,
435 EntryKind::TraitAlias(_) => DefKind::TraitAlias,
436 EntryKind::Enum(..) => DefKind::Enum,
437 EntryKind::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
438 EntryKind::ForeignType => DefKind::ForeignTy,
440 EntryKind::ForeignMod |
441 EntryKind::GlobalAsm |
444 EntryKind::Generator(_) |
445 EntryKind::Closure(_) => return None,
450 impl<'a, 'tcx> CrateMetadata {
451 pub fn is_proc_macro_crate(&self) -> bool {
452 self.root.proc_macro_decls_static.is_some()
455 fn is_proc_macro(&self, id: DefIndex) -> bool {
456 self.is_proc_macro_crate() &&
457 self.root.proc_macro_data.unwrap().decode(self).find(|x| *x == id).is_some()
460 fn entry_unless_proc_macro(&self, id: DefIndex) -> Option<Entry<'tcx>> {
461 match self.is_proc_macro(id) {
463 false => Some(self.entry(id)),
467 fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
468 self.root.entries_index.lookup(self.blob.raw_bytes(), item_id)
471 fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
472 match self.maybe_entry(item_id) {
474 bug!("entry: id not found: {:?} in crate {:?} with number {}",
479 Some(d) => d.decode(self),
483 fn local_def_id(&self, index: DefIndex) -> DefId {
490 fn raw_proc_macro(&self, id: DefIndex) -> &ProcMacro {
491 // DefIndex's in root.proc_macro_data have a one-to-one correspondence
492 // with items in 'raw_proc_macros'.
493 // NOTE: If you update the order of macros in 'proc_macro_data' for any reason,
494 // you must also update src/libsyntax_ext/proc_macro_harness.rs
495 // Failing to do so will result in incorrect data being associated
496 // with proc macros when deserialized.
497 let pos = self.root.proc_macro_data.unwrap().decode(self).position(|i| i == id).unwrap();
498 &self.raw_proc_macros.unwrap()[pos]
501 pub fn item_name(&self, item_index: DefIndex) -> Symbol {
502 if !self.is_proc_macro(item_index) {
503 self.def_key(item_index)
507 .expect("no name in item_name")
510 Symbol::intern(self.raw_proc_macro(item_index).name())
514 pub fn def_kind(&self, index: DefIndex) -> Option<DefKind> {
515 if !self.is_proc_macro(index) {
516 self.entry(index).kind.def_kind()
519 macro_kind(self.raw_proc_macro(index))
524 pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
525 self.entry(index).span.decode((self, sess))
528 crate fn load_proc_macro(&self, id: DefIndex, sess: &Session) -> SyntaxExtension {
529 let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
530 ProcMacro::CustomDerive { trait_name, attributes, client } => {
532 attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
535 SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
539 ProcMacro::Attr { name, client } => (
540 name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new()
542 ProcMacro::Bang { name, client } => (
543 name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new()
546 let edition = if sess.opts.debugging_opts.dual_proc_macros {
547 self.host_lib.as_ref().unwrap().metadata.get_root().edition
552 SyntaxExtension::new(
555 self.get_span(id, sess),
558 Symbol::intern(name),
559 &self.get_attributes(&self.entry(id), sess),
563 pub fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
564 match self.entry(item_id).kind {
565 EntryKind::Trait(data) => {
566 let data = data.decode((self, sess));
567 ty::TraitDef::new(self.local_def_id(item_id),
572 self.def_path_table.def_path_hash(item_id))
574 EntryKind::TraitAlias(_) => {
575 ty::TraitDef::new(self.local_def_id(item_id),
576 hir::Unsafety::Normal,
580 self.def_path_table.def_path_hash(item_id))
582 _ => bug!("def-index does not refer to trait or trait alias"),
592 adt_kind: ty::AdtKind,
593 ) -> ty::VariantDef {
594 let data = match item.kind {
595 EntryKind::Variant(data) |
596 EntryKind::Struct(data, _) |
597 EntryKind::Union(data, _) => data.decode(self),
601 let variant_did = if adt_kind == ty::AdtKind::Enum {
602 Some(self.local_def_id(index))
606 let ctor_did = data.ctor.map(|index| self.local_def_id(index));
610 Ident::with_dummy_span(self.item_name(index)),
614 item.children.decode(self).map(|index| {
615 let f = self.entry(index);
617 did: self.local_def_id(index),
618 ident: Ident::with_dummy_span(self.item_name(index)),
619 vis: f.visibility.decode(self)
629 pub fn get_adt_def(&self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef {
630 let item = self.entry(item_id);
631 let did = self.local_def_id(item_id);
633 let (kind, repr) = match item.kind {
634 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
635 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
636 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
637 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
640 let variants = if let ty::AdtKind::Enum = kind {
644 self.get_variant(tcx, &self.entry(index), index, did, kind)
648 std::iter::once(self.get_variant(tcx, &item, item_id, did, kind)).collect()
651 tcx.alloc_adt_def(did, kind, variants, repr)
654 pub fn get_predicates(
658 ) -> ty::GenericPredicates<'tcx> {
659 self.entry(item_id).predicates.unwrap().decode((self, tcx))
662 pub fn get_predicates_defined_on(
666 ) -> ty::GenericPredicates<'tcx> {
667 self.entry(item_id).predicates_defined_on.unwrap().decode((self, tcx))
670 pub fn get_super_predicates(
674 ) -> ty::GenericPredicates<'tcx> {
675 let super_predicates = match self.entry(item_id).kind {
676 EntryKind::Trait(data) => data.decode(self).super_predicates,
677 EntryKind::TraitAlias(data) => data.decode(self).super_predicates,
678 _ => bug!("def-index does not refer to trait or trait alias"),
681 super_predicates.decode((self, tcx))
684 pub fn get_generics(&self,
688 self.entry(item_id).generics.unwrap().decode((self, sess))
691 pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
692 self.entry(id).ty.unwrap().decode((self, tcx))
695 pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
696 match self.is_proc_macro(id) {
697 true => self.root.proc_macro_stability.clone(),
698 false => self.entry(id).stability.map(|stab| stab.decode(self)),
702 pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
703 self.entry_unless_proc_macro(id)
704 .and_then(|entry| entry.deprecation.map(|depr| depr.decode(self)))
707 pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
708 match self.is_proc_macro(id) {
709 true => ty::Visibility::Public,
710 false => self.entry(id).visibility.decode(self),
714 fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
715 match self.entry(id).kind {
716 EntryKind::Impl(data) => data.decode(self),
721 pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
722 self.get_impl_data(id).parent_impl
725 pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
726 self.get_impl_data(id).polarity
729 pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
730 self.get_impl_data(id).defaultness
733 pub fn get_coerce_unsized_info(&self,
735 -> Option<ty::adjustment::CoerceUnsizedInfo> {
736 self.get_impl_data(id).coerce_unsized_info
739 pub fn get_impl_trait(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option<ty::TraitRef<'tcx>> {
740 self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
743 /// Iterates over all the stability attributes in the given crate.
744 pub fn get_lib_features(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(ast::Name, Option<ast::Name>)] {
745 // FIXME: For a proc macro crate, not sure whether we should return the "host"
746 // features or an empty Vec. Both don't cause ICEs.
747 tcx.arena.alloc_from_iter(self.root
752 /// Iterates over the language items in the given crate.
753 pub fn get_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] {
754 if self.is_proc_macro_crate() {
755 // Proc macro crates do not export any lang-items to the target.
758 tcx.arena.alloc_from_iter(self.root
761 .map(|(def_index, index)| (self.local_def_id(def_index), index)))
765 /// Iterates over the diagnostic items in the given crate.
766 pub fn get_diagnostic_items(
769 ) -> &'tcx FxHashMap<Symbol, DefId> {
770 tcx.arena.alloc(if self.is_proc_macro_crate() {
771 // Proc macro crates do not export any diagnostic-items to the target.
777 .map(|(name, def_index)| (name, self.local_def_id(def_index)))
782 /// Iterates over each child of the given item.
783 pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
784 where F: FnMut(def::Export<hir::HirId>)
786 if let Some(proc_macros_ids) = self.root.proc_macro_data.map(|d| d.decode(self)) {
787 /* If we are loading as a proc macro, we want to return the view of this crate
788 * as a proc macro crate.
790 if id == CRATE_DEF_INDEX {
791 for def_index in proc_macros_ids {
792 let raw_macro = self.raw_proc_macro(def_index);
794 DefKind::Macro(macro_kind(raw_macro)),
795 self.local_def_id(def_index),
797 let ident = Ident::from_str(raw_macro.name());
798 callback(def::Export {
801 vis: ty::Visibility::Public,
810 let item = match self.maybe_entry(id) {
812 Some(item) => item.decode((self, sess)),
815 // Iterate over all children.
816 let macros_only = self.dep_kind.lock().macros_only();
817 for child_index in item.children.decode((self, sess)) {
823 if let Some(child) = self.maybe_entry(child_index) {
824 let child = child.decode((self, sess));
826 EntryKind::MacroDef(..) => {}
827 _ if macros_only => continue,
831 // Hand off the item to the callback.
833 // FIXME(eddyb) Don't encode these in children.
834 EntryKind::ForeignMod => {
835 for child_index in child.children.decode((self, sess)) {
836 if let Some(kind) = self.def_kind(child_index) {
837 callback(def::Export {
838 res: Res::Def(kind, self.local_def_id(child_index)),
839 ident: Ident::with_dummy_span(self.item_name(child_index)),
840 vis: self.get_visibility(child_index),
841 span: self.entry(child_index).span.decode((self, sess)),
847 EntryKind::Impl(_) => continue,
852 let def_key = self.def_key(child_index);
853 let span = child.span.decode((self, sess));
854 if let (Some(kind), Some(name)) =
855 (self.def_kind(child_index), def_key.disambiguated_data.data.get_opt_name()) {
856 let ident = Ident::from_interned_str(name);
857 let vis = self.get_visibility(child_index);
858 let def_id = self.local_def_id(child_index);
859 let res = Res::Def(kind, def_id);
860 callback(def::Export { res, ident, vis, span });
861 // For non-re-export structs and variants add their constructors to children.
862 // Re-export lists automatically contain constructors when necessary.
865 if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
866 let ctor_kind = self.get_ctor_kind(child_index);
867 let ctor_res = Res::Def(
868 DefKind::Ctor(CtorOf::Struct, ctor_kind),
871 let vis = self.get_visibility(ctor_def_id.index);
872 callback(def::Export { res: ctor_res, vis, ident, span });
875 DefKind::Variant => {
876 // Braced variants, unlike structs, generate unusable names in
877 // value namespace, they are reserved for possible future use.
878 // It's ok to use the variant's id as a ctor id since an
879 // error will be reported on any use of such resolution anyway.
880 let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
881 let ctor_kind = self.get_ctor_kind(child_index);
882 let ctor_res = Res::Def(
883 DefKind::Ctor(CtorOf::Variant, ctor_kind),
886 let mut vis = self.get_visibility(ctor_def_id.index);
887 if ctor_def_id == def_id && vis == ty::Visibility::Public {
888 // For non-exhaustive variants lower the constructor visibility to
889 // within the crate. We only need this for fictive constructors,
890 // for other constructors correct visibilities
891 // were already encoded in metadata.
892 let attrs = self.get_item_attrs(def_id.index, sess);
893 if attr::contains_name(&attrs, sym::non_exhaustive) {
894 let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
895 vis = ty::Visibility::Restricted(crate_def_id);
898 callback(def::Export { res: ctor_res, ident, vis, span });
906 if let EntryKind::Mod(data) = item.kind {
907 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
909 Res::Def(DefKind::Macro(..), _) => {}
910 _ if macros_only => continue,
918 pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
919 match self.entry(id).kind {
920 EntryKind::AssocConst(_, data, _) |
921 EntryKind::Const(data, _) => data.ast_promotable,
926 pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
927 !self.is_proc_macro(id) &&
928 self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
931 pub fn get_optimized_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> {
932 self.entry_unless_proc_macro(id)
933 .and_then(|entry| entry.mir.map(|mir| mir.decode((self, tcx))))
935 bug!("get_optimized_mir: missing MIR for `{:?}", self.local_def_id(id))
939 pub fn get_promoted_mir(
943 ) -> IndexVec<Promoted, Body<'tcx>> {
944 self.entry_unless_proc_macro(id)
945 .and_then(|entry| entry.promoted_mir.map(|promoted| promoted.decode((self, tcx))))
947 bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id))
951 pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
952 match self.entry(id).kind {
953 EntryKind::Const(qualif, _) |
954 EntryKind::AssocConst(AssocContainer::ImplDefault, qualif, _) |
955 EntryKind::AssocConst(AssocContainer::ImplFinal, qualif, _) => {
962 pub fn get_associated_item(&self, id: DefIndex) -> ty::AssocItem {
963 let item = self.entry(id);
964 let def_key = self.def_key(id);
965 let parent = self.local_def_id(def_key.parent.unwrap());
966 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
968 let (kind, container, has_self) = match item.kind {
969 EntryKind::AssocConst(container, _, _) => {
970 (ty::AssocKind::Const, container, false)
972 EntryKind::Method(data) => {
973 let data = data.decode(self);
974 (ty::AssocKind::Method, data.container, data.has_self)
976 EntryKind::AssocType(container) => {
977 (ty::AssocKind::Type, container, false)
979 EntryKind::AssocOpaqueTy(container) => {
980 (ty::AssocKind::OpaqueTy, container, false)
982 _ => bug!("cannot get associated-item of `{:?}`", def_key)
986 ident: Ident::from_interned_str(name),
988 vis: item.visibility.decode(self),
989 defaultness: container.defaultness(),
990 def_id: self.local_def_id(id),
991 container: container.with_def_id(parent),
992 method_has_self_argument: has_self
996 pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
997 self.entry(id).variances.decode(self).collect()
1000 pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
1001 match self.entry(node_id).kind {
1002 EntryKind::Struct(data, _) |
1003 EntryKind::Union(data, _) |
1004 EntryKind::Variant(data) => data.decode(self).ctor_kind,
1005 _ => CtorKind::Fictive,
1009 pub fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
1010 match self.entry(node_id).kind {
1011 EntryKind::Struct(data, _) => {
1012 data.decode(self).ctor.map(|index| self.local_def_id(index))
1014 EntryKind::Variant(data) => {
1015 data.decode(self).ctor.map(|index| self.local_def_id(index))
1022 pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
1023 // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
1024 // we assume that someone passing in a tuple struct ctor is actually wanting to
1025 // look at the definition
1026 let def_key = self.def_key(node_id);
1027 let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
1028 def_key.parent.unwrap()
1033 let item = self.entry(item_id);
1034 Lrc::from(self.get_attributes(&item, sess))
1037 pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
1041 .map(|index| self.item_name(index))
1045 fn get_attributes(&self, item: &Entry<'tcx>, sess: &Session) -> Vec<ast::Attribute> {
1046 item.attributes.decode((self, sess)).collect()
1049 // Translate a DefId from the current compilation environment to a DefId
1050 // for an external crate.
1051 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1052 for (local, &global) in self.cnum_map.iter_enumerated() {
1053 if global == did.krate {
1064 pub fn get_inherent_implementations_for_type(
1068 ) -> &'tcx [DefId] {
1069 tcx.arena.alloc_from_iter(self.entry(id)
1072 .map(|index| self.local_def_id(index)))
1075 pub fn get_implementations_for_trait(
1078 filter: Option<DefId>,
1079 ) -> &'tcx [DefId] {
1080 if self.is_proc_macro_crate() {
1081 // proc-macro crates export no trait impls.
1085 // Do a reverse lookup beforehand to avoid touching the crate_num
1086 // hash map in the loop below.
1087 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1088 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1089 Some(None) => return &[],
1093 if let Some(filter) = filter {
1094 if let Some(impls) = self.trait_impls.get(&filter) {
1095 tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx)))
1100 tcx.arena.alloc_from_iter(self.trait_impls.values().flat_map(|impls| {
1101 impls.decode(self).map(|idx| self.local_def_id(idx))
1106 pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1107 let def_key = self.def_key(id);
1108 match def_key.disambiguated_data.data {
1109 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1110 // Not an associated item
1113 def_key.parent.and_then(|parent_index| {
1114 match self.entry(parent_index).kind {
1115 EntryKind::Trait(_) |
1116 EntryKind::TraitAlias(_) => Some(self.local_def_id(parent_index)),
1123 pub fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1124 if self.is_proc_macro_crate() {
1125 // Proc macro crates do not have any *target* native libraries.
1128 self.root.native_libraries.decode((self, sess)).collect()
1132 pub fn get_foreign_modules(&self, tcx: TyCtxt<'tcx>) -> &'tcx [ForeignModule] {
1133 if self.is_proc_macro_crate() {
1134 // Proc macro crates do not have any *target* foreign modules.
1137 tcx.arena.alloc_from_iter(self.root.foreign_modules.decode((self, tcx.sess)))
1141 pub fn get_dylib_dependency_formats(
1144 ) -> &'tcx [(CrateNum, LinkagePreference)] {
1145 tcx.arena.alloc_from_iter(self.root
1146 .dylib_dependency_formats
1149 .flat_map(|(i, link)| {
1150 let cnum = CrateNum::new(i + 1);
1151 link.map(|link| (self.cnum_map[cnum], link))
1155 pub fn get_missing_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] {
1156 if self.is_proc_macro_crate() {
1157 // Proc macro crates do not depend on any target weak lang-items.
1160 tcx.arena.alloc_from_iter(self.root
1166 pub fn get_fn_param_names(&self, id: DefIndex) -> Vec<ast::Name> {
1167 let param_names = match self.entry(id).kind {
1168 EntryKind::Fn(data) |
1169 EntryKind::ForeignFn(data) => data.decode(self).param_names,
1170 EntryKind::Method(data) => data.decode(self).fn_data.param_names,
1173 param_names.decode(self).collect()
1176 pub fn exported_symbols(
1179 ) -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1180 if self.is_proc_macro_crate() {
1181 // If this crate is a custom derive crate, then we're not even going to
1182 // link those in so we skip those crates.
1185 self.root.exported_symbols.decode((self, tcx)).collect()
1189 pub fn get_rendered_const(&self, id: DefIndex) -> String {
1190 match self.entry(id).kind {
1191 EntryKind::Const(_, data) |
1192 EntryKind::AssocConst(_, _, data) => data.decode(self).0,
1197 pub fn get_macro(&self, id: DefIndex) -> MacroDef {
1198 let entry = self.entry(id);
1200 EntryKind::MacroDef(macro_def) => macro_def.decode(self),
1205 crate fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1206 let constness = match self.entry(id).kind {
1207 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1208 EntryKind::Fn(data) => data.decode(self).constness,
1209 EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const,
1210 _ => hir::Constness::NotConst,
1212 constness == hir::Constness::Const
1215 pub fn asyncness(&self, id: DefIndex) -> hir::IsAsync {
1216 match self.entry(id).kind {
1217 EntryKind::Fn(data) => data.decode(self).asyncness,
1218 EntryKind::Method(data) => data.decode(self).fn_data.asyncness,
1219 EntryKind::ForeignFn(data) => data.decode(self).asyncness,
1220 _ => bug!("asyncness: expect functions entry."),
1224 pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1225 match self.entry(id).kind {
1226 EntryKind::ForeignImmStatic |
1227 EntryKind::ForeignMutStatic |
1228 EntryKind::ForeignFn(_) => true,
1233 crate fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1234 match self.entry(id).kind {
1235 EntryKind::ImmStatic |
1236 EntryKind::ForeignImmStatic => Some(hir::MutImmutable),
1237 EntryKind::MutStatic |
1238 EntryKind::ForeignMutStatic => Some(hir::MutMutable),
1243 pub fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
1244 let sig = match self.entry(id).kind {
1245 EntryKind::Fn(data) |
1246 EntryKind::ForeignFn(data) => data.decode(self).sig,
1247 EntryKind::Method(data) => data.decode(self).fn_data.sig,
1248 EntryKind::Variant(data) |
1249 EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1250 EntryKind::Closure(data) => data.decode(self).sig,
1253 sig.decode((self, tcx))
1257 pub fn def_key(&self, index: DefIndex) -> DefKey {
1258 let mut key = self.def_path_table.def_key(index);
1259 if self.is_proc_macro(index) {
1260 let name = self.raw_proc_macro(index).name();
1261 key.disambiguated_data.data = DefPathData::MacroNs(InternedString::intern(name));
1266 // Returns the path leading to the thing with this `id`.
1267 pub fn def_path(&self, id: DefIndex) -> DefPath {
1268 debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1269 DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1273 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1274 self.def_path_table.def_path_hash(index)
1277 /// Imports the source_map from an external crate into the source_map of the crate
1278 /// currently being compiled (the "local crate").
1280 /// The import algorithm works analogous to how AST items are inlined from an
1281 /// external crate's metadata:
1282 /// For every SourceFile in the external source_map an 'inline' copy is created in the
1283 /// local source_map. The correspondence relation between external and local
1284 /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1285 /// function. When an item from an external crate is later inlined into this
1286 /// crate, this correspondence information is used to translate the span
1287 /// information of the inlined item so that it refers the correct positions in
1288 /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1290 /// The import algorithm in the function below will reuse SourceFiles already
1291 /// existing in the local source_map. For example, even if the SourceFile of some
1292 /// source file of libstd gets imported many times, there will only ever be
1293 /// one SourceFile object for the corresponding file in the local source_map.
1295 /// Note that imported SourceFiles do not actually contain the source code of the
1296 /// file they represent, just information about length, line breaks, and
1297 /// multibyte characters. This information is enough to generate valid debuginfo
1298 /// for items inlined from other crates.
1300 /// Proc macro crates don't currently export spans, so this function does not have
1301 /// to work for them.
1302 pub fn imported_source_files(&'a self,
1303 local_source_map: &source_map::SourceMap)
1304 -> ReadGuard<'a, Vec<cstore::ImportedSourceFile>> {
1306 let source_files = self.source_map_import_info.borrow();
1307 if !source_files.is_empty() {
1308 return source_files;
1312 // Lock the source_map_import_info to ensure this only happens once
1313 let mut source_map_import_info = self.source_map_import_info.borrow_mut();
1315 if !source_map_import_info.is_empty() {
1316 drop(source_map_import_info);
1317 return self.source_map_import_info.borrow();
1320 let external_source_map = self.root.source_map.decode(self);
1322 let imported_source_files = external_source_map.map(|source_file_to_import| {
1323 // We can't reuse an existing SourceFile, so allocate a new one
1324 // containing the information we need.
1325 let syntax_pos::SourceFile { name,
1331 mut multibyte_chars,
1332 mut non_narrow_chars,
1334 .. } = source_file_to_import;
1336 let source_length = (end_pos - start_pos).to_usize();
1338 // Translate line-start positions and multibyte character
1339 // position into frame of reference local to file.
1340 // `SourceMap::new_imported_source_file()` will then translate those
1341 // coordinates to their new global frame of reference when the
1342 // offset of the SourceFile is known.
1343 for pos in &mut lines {
1344 *pos = *pos - start_pos;
1346 for mbc in &mut multibyte_chars {
1347 mbc.pos = mbc.pos - start_pos;
1349 for swc in &mut non_narrow_chars {
1350 *swc = *swc - start_pos;
1353 let local_version = local_source_map.new_imported_source_file(name,
1362 debug!("CrateMetaData::imported_source_files alloc \
1363 source_file {:?} original (start_pos {:?} end_pos {:?}) \
1364 translated (start_pos {:?} end_pos {:?})",
1365 local_version.name, start_pos, end_pos,
1366 local_version.start_pos, local_version.end_pos);
1368 cstore::ImportedSourceFile {
1369 original_start_pos: start_pos,
1370 original_end_pos: end_pos,
1371 translated_source_file: local_version,
1375 *source_map_import_info = imported_source_files;
1376 drop(source_map_import_info);
1378 // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1379 self.source_map_import_info.borrow()
1383 // Cannot be implemented on 'ProcMacro', as libproc_macro
1384 // does not depend on libsyntax
1385 fn macro_kind(raw: &ProcMacro) -> MacroKind {
1387 ProcMacro::CustomDerive { .. } => MacroKind::Derive,
1388 ProcMacro::Attr { .. } => MacroKind::Attr,
1389 ProcMacro::Bang { .. } => MacroKind::Bang