1 // Decoding metadata from a single crate's metadata
3 use crate::cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary, ForeignModule};
6 use rustc_data_structures::sync::{Lrc, ReadGuard};
7 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash, Definitions};
9 use rustc::middle::cstore::LinkagePreference;
10 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
11 use rustc::hir::def::{self, Def, CtorKind};
12 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, DefIndexAddressSpace,
13 CRATE_DEF_INDEX, LOCAL_CRATE, LocalDefId};
14 use rustc::hir::map::definitions::DefPathTable;
15 use rustc_data_structures::fingerprint::Fingerprint;
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;
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::InternedString;
34 use syntax::ext::base::{MacroKind, SyntaxExtension};
35 use syntax::ext::hygiene::Mark;
36 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
39 pub struct DecodeContext<'a, 'tcx: 'a> {
40 opaque: opaque::Decoder<'a>,
41 cdata: Option<&'a CrateMetadata>,
42 sess: Option<&'a Session>,
43 tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
45 // Cache the last used source_file for translating spans as an optimization.
46 last_source_file_index: usize,
48 lazy_state: LazyState,
50 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
51 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
54 /// Abstract over the various ways one can create metadata decoders.
55 pub trait Metadata<'a, 'tcx>: Copy {
56 fn raw_bytes(self) -> &'a [u8];
57 fn cdata(self) -> Option<&'a CrateMetadata> { None }
58 fn sess(self) -> Option<&'a Session> { None }
59 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { None }
61 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
64 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
66 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
68 last_source_file_index: 0,
69 lazy_state: LazyState::NoNode,
70 alloc_decoding_session: self.cdata().map(|cdata| {
71 cdata.alloc_decoding_state.new_decoding_session()
77 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
78 fn raw_bytes(self) -> &'a [u8] {
84 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'a Session) {
85 fn raw_bytes(self) -> &'a [u8] {
90 fn sess(self) -> Option<&'a Session> {
97 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
98 fn raw_bytes(self) -> &'a [u8] {
101 fn cdata(self) -> Option<&'a CrateMetadata> {
106 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
107 fn raw_bytes(self) -> &'a [u8] {
110 fn cdata(self) -> Option<&'a CrateMetadata> {
113 fn sess(self) -> Option<&'a Session> {
118 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
119 fn raw_bytes(self) -> &'a [u8] {
122 fn cdata(self) -> Option<&'a CrateMetadata> {
125 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
130 impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
131 pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
132 let mut dcx = meta.decoder(self.position);
133 dcx.lazy_state = LazyState::NodeStart(self.position);
134 T::decode(&mut dcx).unwrap()
138 impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
139 pub fn decode<M: Metadata<'a, 'tcx>>(
142 ) -> impl Iterator<Item = T> + Captures<'tcx> + 'a {
143 let mut dcx = meta.decoder(self.position);
144 dcx.lazy_state = LazyState::NodeStart(self.position);
145 (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
149 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
150 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
151 self.tcx.expect("missing TyCtxt in DecodeContext")
154 pub fn cdata(&self) -> &'a CrateMetadata {
155 self.cdata.expect("missing CrateMetadata in DecodeContext")
158 fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
159 let distance = self.read_usize()?;
160 let position = match self.lazy_state {
161 LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
162 LazyState::NodeStart(start) => {
163 assert!(distance + min_size <= start);
164 start - distance - min_size
166 LazyState::Previous(last_min_end) => last_min_end + distance,
168 self.lazy_state = LazyState::Previous(position + min_size);
173 impl<'a, 'tcx: 'a> TyDecoder<'a, 'tcx> for DecodeContext<'a, 'tcx> {
176 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
177 self.tcx.expect("missing TyCtxt in DecodeContext")
181 fn peek_byte(&self) -> u8 {
182 self.opaque.data[self.opaque.position()]
186 fn position(&self) -> usize {
187 self.opaque.position()
190 fn cached_ty_for_shorthand<F>(&mut self,
193 -> Result<Ty<'tcx>, Self::Error>
194 where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>
196 let tcx = self.tcx();
198 let key = ty::CReaderCacheKey {
199 cnum: self.cdata().cnum,
203 if let Some(&ty) = tcx.rcache.borrow().get(&key) {
207 let ty = or_insert_with(self)?;
208 tcx.rcache.borrow_mut().insert(key, ty);
212 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
213 where F: FnOnce(&mut Self) -> R
215 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
216 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
217 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
219 self.opaque = old_opaque;
220 self.lazy_state = old_state;
224 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
225 if cnum == LOCAL_CRATE {
228 self.cdata().cnum_map[cnum]
233 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
234 fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
235 Ok(Lazy::with_position(self.read_lazy_distance(Lazy::<T>::min_size())?))
239 impl<'a, 'tcx, T> SpecializedDecoder<LazySeq<T>> for DecodeContext<'a, 'tcx> {
240 fn specialized_decode(&mut self) -> Result<LazySeq<T>, Self::Error> {
241 let len = self.read_usize()?;
242 let position = if len == 0 {
245 self.read_lazy_distance(LazySeq::<T>::min_size(len))?
247 Ok(LazySeq::with_position_and_length(position, len))
252 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
254 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
255 let krate = CrateNum::decode(self)?;
256 let index = DefIndex::decode(self)?;
265 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
267 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
268 Ok(DefIndex::from_raw_u32(self.read_u32()?))
272 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for DecodeContext<'a, 'tcx> {
274 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
275 self.specialized_decode().map(|i| LocalDefId::from_def_id(i))
279 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
280 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
281 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
282 alloc_decoding_session.decode_alloc_id(self)
284 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
289 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
290 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
291 let tag = u8::decode(self)?;
293 if tag == TAG_INVALID_SPAN {
297 debug_assert_eq!(tag, TAG_VALID_SPAN);
299 let lo = BytePos::decode(self)?;
300 let len = BytePos::decode(self)?;
303 let sess = if let Some(sess) = self.sess {
306 bug!("Cannot decode Span without Session.")
309 let imported_source_files = self.cdata().imported_source_files(&sess.source_map());
311 // Optimize for the case that most spans within a translated item
312 // originate from the same source_file.
313 let last_source_file = &imported_source_files[self.last_source_file_index];
315 if lo >= last_source_file.original_start_pos &&
316 lo <= last_source_file.original_end_pos {
320 let mut b = imported_source_files.len();
324 if imported_source_files[m].original_start_pos > lo {
331 self.last_source_file_index = a;
332 &imported_source_files[a]
336 // Make sure our binary search above is correct.
337 debug_assert!(lo >= source_file.original_start_pos &&
338 lo <= source_file.original_end_pos);
340 // Make sure we correctly filtered out invalid spans during encoding
341 debug_assert!(hi >= source_file.original_start_pos &&
342 hi <= source_file.original_end_pos);
344 let lo = (lo + source_file.translated_source_file.start_pos)
345 - source_file.original_start_pos;
346 let hi = (hi + source_file.translated_source_file.start_pos)
347 - source_file.original_start_pos;
349 Ok(Span::new(lo, hi, NO_EXPANSION))
353 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
354 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
355 Fingerprint::decode_opaque(&mut self.opaque)
359 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
360 for DecodeContext<'a, 'tcx> {
362 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
363 Ok(mir::ClearCrossCrate::Clear)
367 implement_ty_decoder!( DecodeContext<'a, 'tcx> );
369 impl<'a, 'tcx> MetadataBlob {
370 pub fn is_compatible(&self) -> bool {
371 self.raw_bytes().starts_with(METADATA_HEADER)
374 pub fn get_rustc_version(&self) -> String {
375 Lazy::with_position(METADATA_HEADER.len() + 4).decode(self)
378 pub fn get_root(&self) -> CrateRoot {
379 let slice = self.raw_bytes();
380 let offset = METADATA_HEADER.len();
381 let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
382 ((slice[offset + 2] as u32) << 8) |
383 ((slice[offset + 3] as u32) << 0)) as usize;
384 Lazy::with_position(pos).decode(self)
387 pub fn list_crate_metadata(&self,
388 out: &mut dyn io::Write) -> io::Result<()> {
389 write!(out, "=External Dependencies=\n")?;
390 let root = self.get_root();
391 for (i, dep) in root.crate_deps
394 write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
401 impl<'tcx> EntryKind<'tcx> {
402 fn to_def(&self, did: DefId) -> Option<Def> {
404 EntryKind::Const(..) => Def::Const(did),
405 EntryKind::AssociatedConst(..) => Def::AssociatedConst(did),
406 EntryKind::ImmStatic |
407 EntryKind::ForeignImmStatic => Def::Static(did, false),
408 EntryKind::MutStatic |
409 EntryKind::ForeignMutStatic => Def::Static(did, true),
410 EntryKind::Struct(_, _) => Def::Struct(did),
411 EntryKind::Union(_, _) => Def::Union(did),
413 EntryKind::ForeignFn(_) => Def::Fn(did),
414 EntryKind::Method(_) => Def::Method(did),
415 EntryKind::Type => Def::TyAlias(did),
416 EntryKind::Existential => Def::Existential(did),
417 EntryKind::AssociatedType(_) => Def::AssociatedTy(did),
418 EntryKind::AssociatedExistential(_) => Def::AssociatedExistential(did),
419 EntryKind::Mod(_) => Def::Mod(did),
420 EntryKind::Variant(_) => Def::Variant(did),
421 EntryKind::Trait(_) => Def::Trait(did),
422 EntryKind::TraitAlias(_) => Def::TraitAlias(did),
423 EntryKind::Enum(..) => Def::Enum(did),
424 EntryKind::MacroDef(_) => Def::Macro(did, MacroKind::Bang),
425 EntryKind::ForeignType => Def::ForeignTy(did),
427 EntryKind::ForeignMod |
428 EntryKind::GlobalAsm |
431 EntryKind::Generator(_) |
432 EntryKind::Closure(_) => return None,
437 /// Creates the "fake" DefPathTable for a given proc macro crate.
439 /// The DefPathTable is as follows:
441 /// CRATE_ROOT (DefIndex 0:0)
442 /// |- GlobalMetaDataKind data (DefIndex 1:0 .. DefIndex 1:N)
443 /// |- proc macro #0 (DefIndex 1:N)
444 /// |- proc macro #1 (DefIndex 1:N+1)
446 crate fn proc_macro_def_path_table(crate_root: &CrateRoot,
447 proc_macros: &[(ast::Name, Lrc<SyntaxExtension>)])
450 let mut definitions = Definitions::new();
452 let name = crate_root.name.as_str();
453 let disambiguator = crate_root.disambiguator;
454 debug!("creating proc macro def path table for {:?}/{:?}", name, disambiguator);
455 let crate_root = definitions.create_root_def(&name, disambiguator);
456 for (index, (name, _)) in proc_macros.iter().enumerate() {
457 let def_index = definitions.create_def_with_parent(
460 DefPathData::MacroDef(name.as_interned_str()),
461 DefIndexAddressSpace::High,
464 debug!("definition for {:?} is {:?}", name, def_index);
465 assert_eq!(def_index, DefIndex::from_proc_macro_index(index));
468 definitions.def_path_table().clone()
471 impl<'a, 'tcx> CrateMetadata {
472 fn is_proc_macro(&self, id: DefIndex) -> bool {
473 self.proc_macros.is_some() && id != CRATE_DEF_INDEX
476 fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
477 assert!(!self.is_proc_macro(item_id));
478 self.root.index.lookup(self.blob.raw_bytes(), item_id)
481 fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
482 match self.maybe_entry(item_id) {
484 bug!("entry: id not found: {:?} in crate {:?} with number {}",
489 Some(d) => d.decode(self),
493 fn local_def_id(&self, index: DefIndex) -> DefId {
500 pub fn item_name(&self, item_index: DefIndex) -> InternedString {
501 self.def_key(item_index)
505 .expect("no name in item_name")
508 pub fn get_def(&self, index: DefIndex) -> Option<Def> {
509 if !self.is_proc_macro(index) {
510 self.entry(index).kind.to_def(self.local_def_id(index))
512 let kind = self.proc_macros.as_ref().unwrap()[index.to_proc_macro_index()].1.kind();
513 Some(Def::Macro(self.local_def_id(index), kind))
517 pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
518 match self.is_proc_macro(index) {
520 false => self.entry(index).span.decode((self, sess)),
524 pub fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
525 match self.entry(item_id).kind {
526 EntryKind::Trait(data) => {
527 let data = data.decode((self, sess));
528 ty::TraitDef::new(self.local_def_id(item_id),
533 self.def_path_table.def_path_hash(item_id))
535 EntryKind::TraitAlias(_) => {
536 ty::TraitDef::new(self.local_def_id(item_id),
537 hir::Unsafety::Normal,
541 self.def_path_table.def_path_hash(item_id))
543 _ => bug!("def-index does not refer to trait or trait alias"),
547 fn get_variant(&self,
548 tcx: TyCtxt<'a, 'tcx, 'tcx>,
551 adt_kind: ty::AdtKind)
554 let data = match item.kind {
555 EntryKind::Variant(data) |
556 EntryKind::Struct(data, _) |
557 EntryKind::Union(data, _) => data.decode(self),
561 let def_id = self.local_def_id(data.struct_ctor.unwrap_or(index));
562 let attribute_def_id = self.local_def_id(index);
567 Ident::from_interned_str(self.item_name(index)),
569 item.children.decode(self).map(|index| {
570 let f = self.entry(index);
572 did: self.local_def_id(index),
573 ident: Ident::from_interned_str(self.item_name(index)),
574 vis: f.visibility.decode(self)
583 pub fn get_adt_def(&self,
585 tcx: TyCtxt<'a, 'tcx, 'tcx>)
586 -> &'tcx ty::AdtDef {
587 let item = self.entry(item_id);
588 let did = self.local_def_id(item_id);
590 let (kind, repr) = match item.kind {
591 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
592 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
593 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
594 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
597 let variants = if let ty::AdtKind::Enum = kind {
601 self.get_variant(tcx, &self.entry(index), index, kind)
605 std::iter::once(self.get_variant(tcx, &item, item_id, kind)).collect()
608 tcx.alloc_adt_def(did, kind, variants, repr)
611 pub fn get_predicates(&self,
613 tcx: TyCtxt<'a, 'tcx, 'tcx>)
614 -> ty::GenericPredicates<'tcx> {
615 self.entry(item_id).predicates.unwrap().decode((self, tcx))
618 pub fn get_predicates_defined_on(&self,
620 tcx: TyCtxt<'a, 'tcx, 'tcx>)
621 -> ty::GenericPredicates<'tcx> {
622 self.entry(item_id).predicates_defined_on.unwrap().decode((self, tcx))
625 pub fn get_super_predicates(&self,
627 tcx: TyCtxt<'a, 'tcx, 'tcx>)
628 -> ty::GenericPredicates<'tcx> {
629 let super_predicates = match self.entry(item_id).kind {
630 EntryKind::Trait(data) => data.decode(self).super_predicates,
631 EntryKind::TraitAlias(data) => data.decode(self).super_predicates,
632 _ => bug!("def-index does not refer to trait or trait alias"),
635 super_predicates.decode((self, tcx))
638 pub fn get_generics(&self,
642 self.entry(item_id).generics.unwrap().decode((self, sess))
645 pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
646 self.entry(id).ty.unwrap().decode((self, tcx))
649 pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
650 match self.is_proc_macro(id) {
652 false => self.entry(id).stability.map(|stab| stab.decode(self)),
656 pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
657 match self.is_proc_macro(id) {
659 false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
663 pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
664 match self.is_proc_macro(id) {
665 true => ty::Visibility::Public,
666 false => self.entry(id).visibility.decode(self),
670 fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
671 match self.entry(id).kind {
672 EntryKind::Impl(data) => data.decode(self),
677 pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
678 self.get_impl_data(id).parent_impl
681 pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
682 self.get_impl_data(id).polarity
685 pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
686 self.get_impl_data(id).defaultness
689 pub fn get_coerce_unsized_info(&self,
691 -> Option<ty::adjustment::CoerceUnsizedInfo> {
692 self.get_impl_data(id).coerce_unsized_info
695 pub fn get_impl_trait(&self,
697 tcx: TyCtxt<'a, 'tcx, 'tcx>)
698 -> Option<ty::TraitRef<'tcx>> {
699 self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
702 /// Iterates over all the stability attributes in the given crate.
703 pub fn get_lib_features(&self) -> Vec<(ast::Name, Option<ast::Name>)> {
704 // FIXME: For a proc macro crate, not sure whether we should return the "host"
705 // features or an empty Vec. Both don't cause ICEs.
712 /// Iterates over the language items in the given crate.
713 pub fn get_lang_items(&self) -> Vec<(DefId, usize)> {
714 if self.proc_macros.is_some() {
715 // Proc macro crates do not export any lang-items to the target.
721 .map(|(def_index, index)| (self.local_def_id(def_index), index))
726 /// Iterates over each child of the given item.
727 pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
728 where F: FnMut(def::Export)
730 if let Some(ref proc_macros) = self.proc_macros {
731 /* If we are loading as a proc macro, we want to return the view of this crate
732 * as a proc macro crate, not as a Rust crate. See `proc_macro_def_path_table`
733 * for the DefPathTable we are corresponding to.
735 if id == CRATE_DEF_INDEX {
736 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
737 let def = Def::Macro(
740 index: DefIndex::from_proc_macro_index(id),
744 let ident = Ident::with_empty_ctxt(name);
745 callback(def::Export {
748 vis: ty::Visibility::Public,
757 let item = match self.maybe_entry(id) {
759 Some(item) => item.decode((self, sess)),
762 // Iterate over all children.
763 let macros_only = self.dep_kind.lock().macros_only();
764 for child_index in item.children.decode((self, sess)) {
770 if let Some(child) = self.maybe_entry(child_index) {
771 let child = child.decode((self, sess));
773 EntryKind::MacroDef(..) => {}
774 _ if macros_only => continue,
778 // Hand off the item to the callback.
780 // FIXME(eddyb) Don't encode these in children.
781 EntryKind::ForeignMod => {
782 for child_index in child.children.decode((self, sess)) {
783 if let Some(def) = self.get_def(child_index) {
784 callback(def::Export {
786 ident: Ident::from_interned_str(self.item_name(child_index)),
787 vis: self.get_visibility(child_index),
788 span: self.entry(child_index).span.decode((self, sess)),
794 EntryKind::Impl(_) => continue,
799 let def_key = self.def_key(child_index);
800 let span = child.span.decode((self, sess));
801 if let (Some(def), Some(name)) =
802 (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
803 let ident = Ident::from_interned_str(name);
804 let vis = self.get_visibility(child_index);
805 callback(def::Export { def, ident, vis, span });
806 // For non-re-export structs and variants add their constructors to children.
807 // Re-export lists automatically contain constructors when necessary.
810 if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
811 let ctor_kind = self.get_ctor_kind(child_index);
812 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
813 callback(def::Export {
815 vis: self.get_visibility(ctor_def_id.index),
820 Def::Variant(def_id) => {
821 // Braced variants, unlike structs, generate unusable names in
822 // value namespace, they are reserved for possible future use.
823 let ctor_kind = self.get_ctor_kind(child_index);
824 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
825 let vis = self.get_visibility(child_index);
826 callback(def::Export { def: ctor_def, ident, vis, span });
834 if let EntryKind::Mod(data) = item.kind {
835 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
838 _ if macros_only => continue,
846 pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
847 match self.entry(id).kind {
848 EntryKind::AssociatedConst(_, data, _) |
849 EntryKind::Const(data, _) => data.ast_promotable,
854 pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
855 !self.is_proc_macro(id) &&
856 self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
859 pub fn maybe_get_optimized_mir(&self,
860 tcx: TyCtxt<'a, 'tcx, 'tcx>,
862 -> Option<Mir<'tcx>> {
863 match self.is_proc_macro(id) {
865 false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
869 pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
870 match self.entry(id).kind {
871 EntryKind::Const(qualif, _) |
872 EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif, _) |
873 EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif, _) => {
880 pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
881 let item = self.entry(id);
882 let def_key = self.def_key(id);
883 let parent = self.local_def_id(def_key.parent.unwrap());
884 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
886 let (kind, container, has_self) = match item.kind {
887 EntryKind::AssociatedConst(container, _, _) => {
888 (ty::AssociatedKind::Const, container, false)
890 EntryKind::Method(data) => {
891 let data = data.decode(self);
892 (ty::AssociatedKind::Method, data.container, data.has_self)
894 EntryKind::AssociatedType(container) => {
895 (ty::AssociatedKind::Type, container, false)
897 EntryKind::AssociatedExistential(container) => {
898 (ty::AssociatedKind::Existential, container, false)
900 _ => bug!("cannot get associated-item of `{:?}`", def_key)
904 ident: Ident::from_interned_str(name),
906 vis: item.visibility.decode(self),
907 defaultness: container.defaultness(),
908 def_id: self.local_def_id(id),
909 container: container.with_def_id(parent),
910 method_has_self_argument: has_self
914 pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
915 self.entry(id).variances.decode(self).collect()
918 pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
919 match self.entry(node_id).kind {
920 EntryKind::Struct(data, _) |
921 EntryKind::Union(data, _) |
922 EntryKind::Variant(data) => data.decode(self).ctor_kind,
923 _ => CtorKind::Fictive,
927 pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
928 match self.entry(node_id).kind {
929 EntryKind::Struct(data, _) => {
930 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
936 pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
937 if self.is_proc_macro(node_id) {
941 // The attributes for a tuple struct are attached to the definition, not the ctor;
942 // we assume that someone passing in a tuple struct ctor is actually wanting to
943 // look at the definition
944 let def_key = self.def_key(node_id);
945 let item_id = if def_key.disambiguated_data.data == DefPathData::StructCtor {
946 def_key.parent.unwrap()
951 let item = self.entry(item_id);
952 Lrc::from(self.get_attributes(&item, sess))
955 pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
959 .map(|index| self.item_name(index).as_symbol())
963 fn get_attributes(&self, item: &Entry<'tcx>, sess: &Session) -> Vec<ast::Attribute> {
965 .decode((self, sess))
967 // Need new unique IDs: old thread-local IDs won't map to new threads.
968 attr.id = attr::mk_attr_id();
974 // Translate a DefId from the current compilation environment to a DefId
975 // for an external crate.
976 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
977 for (local, &global) in self.cnum_map.iter_enumerated() {
978 if global == did.krate {
989 pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
993 .map(|index| self.local_def_id(index))
997 pub fn get_implementations_for_trait(&self,
998 filter: Option<DefId>,
999 result: &mut Vec<DefId>) {
1000 if self.proc_macros.is_some() {
1001 // proc-macro crates export no trait impls.
1005 // Do a reverse lookup beforehand to avoid touching the crate_num
1006 // hash map in the loop below.
1007 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1008 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1009 Some(None) => return,
1013 if let Some(filter) = filter {
1014 if let Some(impls) = self.trait_impls
1016 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
1019 for impls in self.trait_impls.values() {
1020 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
1025 pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1026 let def_key = self.def_key(id);
1027 match def_key.disambiguated_data.data {
1028 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1029 // Not an associated item
1032 def_key.parent.and_then(|parent_index| {
1033 match self.entry(parent_index).kind {
1034 EntryKind::Trait(_) |
1035 EntryKind::TraitAlias(_) => Some(self.local_def_id(parent_index)),
1042 pub fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1043 if self.proc_macros.is_some() {
1044 // Proc macro crates do not have any *target* native libraries.
1047 self.root.native_libraries.decode((self, sess)).collect()
1051 pub fn get_foreign_modules(&self, sess: &Session) -> Vec<ForeignModule> {
1052 if self.proc_macros.is_some() {
1053 // Proc macro crates do not have any *target* foreign modules.
1056 self.root.foreign_modules.decode((self, sess)).collect()
1060 pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> {
1062 .dylib_dependency_formats
1065 .flat_map(|(i, link)| {
1066 let cnum = CrateNum::new(i + 1);
1067 link.map(|link| (self.cnum_map[cnum], link))
1072 pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> {
1073 if self.proc_macros.is_some() {
1074 // Proc macro crates do not depend on any target weak lang-items.
1084 pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
1085 let arg_names = match self.entry(id).kind {
1086 EntryKind::Fn(data) |
1087 EntryKind::ForeignFn(data) => data.decode(self).arg_names,
1088 EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
1089 _ => LazySeq::empty(),
1091 arg_names.decode(self).collect()
1094 pub fn exported_symbols(&self,
1095 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1096 -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1097 if self.proc_macros.is_some() {
1098 // If this crate is a custom derive crate, then we're not even going to
1099 // link those in so we skip those crates.
1102 let lazy_seq: LazySeq<(ExportedSymbol<'tcx>, SymbolExportLevel)> =
1103 LazySeq::with_position_and_length(self.root.exported_symbols.position,
1104 self.root.exported_symbols.len);
1105 lazy_seq.decode((self, tcx)).collect()
1109 pub fn get_rendered_const(&self, id: DefIndex) -> String {
1110 match self.entry(id).kind {
1111 EntryKind::Const(_, data) |
1112 EntryKind::AssociatedConst(_, _, data) => data.decode(self).0,
1117 pub fn get_macro(&self, id: DefIndex) -> MacroDef {
1118 let entry = self.entry(id);
1120 EntryKind::MacroDef(macro_def) => macro_def.decode(self),
1125 crate fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1126 let constness = match self.entry(id).kind {
1127 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1128 EntryKind::Fn(data) => data.decode(self).constness,
1129 _ => hir::Constness::NotConst,
1131 constness == hir::Constness::Const
1134 pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1135 match self.entry(id).kind {
1136 EntryKind::ForeignImmStatic |
1137 EntryKind::ForeignMutStatic |
1138 EntryKind::ForeignFn(_) => true,
1143 pub fn fn_sig(&self,
1145 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1146 -> ty::PolyFnSig<'tcx> {
1147 let sig = match self.entry(id).kind {
1148 EntryKind::Fn(data) |
1149 EntryKind::ForeignFn(data) => data.decode(self).sig,
1150 EntryKind::Method(data) => data.decode(self).fn_data.sig,
1151 EntryKind::Variant(data) |
1152 EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1153 EntryKind::Closure(data) => data.decode(self).sig,
1156 sig.decode((self, tcx))
1160 pub fn def_key(&self, index: DefIndex) -> DefKey {
1161 self.def_path_table.def_key(index)
1164 // Returns the path leading to the thing with this `id`.
1165 pub fn def_path(&self, id: DefIndex) -> DefPath {
1166 debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1167 DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1171 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1172 self.def_path_table.def_path_hash(index)
1175 /// Imports the source_map from an external crate into the source_map of the crate
1176 /// currently being compiled (the "local crate").
1178 /// The import algorithm works analogous to how AST items are inlined from an
1179 /// external crate's metadata:
1180 /// For every SourceFile in the external source_map an 'inline' copy is created in the
1181 /// local source_map. The correspondence relation between external and local
1182 /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1183 /// function. When an item from an external crate is later inlined into this
1184 /// crate, this correspondence information is used to translate the span
1185 /// information of the inlined item so that it refers the correct positions in
1186 /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1188 /// The import algorithm in the function below will reuse SourceFiles already
1189 /// existing in the local source_map. For example, even if the SourceFile of some
1190 /// source file of libstd gets imported many times, there will only ever be
1191 /// one SourceFile object for the corresponding file in the local source_map.
1193 /// Note that imported SourceFiles do not actually contain the source code of the
1194 /// file they represent, just information about length, line breaks, and
1195 /// multibyte characters. This information is enough to generate valid debuginfo
1196 /// for items inlined from other crates.
1198 /// Proc macro crates don't currently export spans, so this function does not have
1199 /// to work for them.
1200 pub fn imported_source_files(&'a self,
1201 local_source_map: &source_map::SourceMap)
1202 -> ReadGuard<'a, Vec<cstore::ImportedSourceFile>> {
1204 let source_files = self.source_map_import_info.borrow();
1205 if !source_files.is_empty() {
1206 return source_files;
1210 // Lock the source_map_import_info to ensure this only happens once
1211 let mut source_map_import_info = self.source_map_import_info.borrow_mut();
1213 if !source_map_import_info.is_empty() {
1214 drop(source_map_import_info);
1215 return self.source_map_import_info.borrow();
1218 let external_source_map = self.root.source_map.decode(self);
1220 let imported_source_files = external_source_map.map(|source_file_to_import| {
1221 // We can't reuse an existing SourceFile, so allocate a new one
1222 // containing the information we need.
1223 let syntax_pos::SourceFile { name,
1229 mut multibyte_chars,
1230 mut non_narrow_chars,
1232 .. } = source_file_to_import;
1234 let source_length = (end_pos - start_pos).to_usize();
1236 // Translate line-start positions and multibyte character
1237 // position into frame of reference local to file.
1238 // `SourceMap::new_imported_source_file()` will then translate those
1239 // coordinates to their new global frame of reference when the
1240 // offset of the SourceFile is known.
1241 for pos in &mut lines {
1242 *pos = *pos - start_pos;
1244 for mbc in &mut multibyte_chars {
1245 mbc.pos = mbc.pos - start_pos;
1247 for swc in &mut non_narrow_chars {
1248 *swc = *swc - start_pos;
1251 let local_version = local_source_map.new_imported_source_file(name,
1260 debug!("CrateMetaData::imported_source_files alloc \
1261 source_file {:?} original (start_pos {:?} end_pos {:?}) \
1262 translated (start_pos {:?} end_pos {:?})",
1263 local_version.name, start_pos, end_pos,
1264 local_version.start_pos, local_version.end_pos);
1266 cstore::ImportedSourceFile {
1267 original_start_pos: start_pos,
1268 original_end_pos: end_pos,
1269 translated_source_file: local_version,
1273 *source_map_import_info = imported_source_files;
1274 drop(source_map_import_info);
1276 // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1277 self.source_map_import_info.borrow()