1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Decoding metadata from a single crate's metadata
13 use cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary, ForeignModule};
16 use rustc_data_structures::sync::{Lrc, ReadGuard};
17 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash, Definitions};
19 use rustc::middle::cstore::LinkagePreference;
20 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
21 use rustc::hir::def::{self, Def, CtorKind};
22 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, DefIndexAddressSpace,
23 CRATE_DEF_INDEX, LOCAL_CRATE, LocalDefId};
24 use rustc::hir::map::definitions::DefPathTable;
25 use rustc_data_structures::fingerprint::Fingerprint;
26 use rustc::middle::lang_items;
27 use rustc::mir::{self, interpret};
28 use rustc::mir::interpret::AllocDecodingSession;
29 use rustc::session::Session;
30 use rustc::ty::{self, Ty, TyCtxt};
31 use rustc::ty::codec::TyDecoder;
33 use rustc::util::captures::Captures;
39 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
41 use syntax::ast::{self, Ident};
42 use syntax::source_map;
43 use syntax::symbol::InternedString;
44 use syntax::ext::base::{MacroKind, SyntaxExtension};
45 use syntax::ext::hygiene::Mark;
46 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
48 pub struct DecodeContext<'a, 'tcx: 'a> {
49 opaque: opaque::Decoder<'a>,
50 cdata: Option<&'a CrateMetadata>,
51 sess: Option<&'a Session>,
52 tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
54 // Cache the last used source_file for translating spans as an optimization.
55 last_source_file_index: usize,
57 lazy_state: LazyState,
59 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
60 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
63 /// Abstract over the various ways one can create metadata decoders.
64 pub trait Metadata<'a, 'tcx>: Copy {
65 fn raw_bytes(self) -> &'a [u8];
66 fn cdata(self) -> Option<&'a CrateMetadata> { None }
67 fn sess(self) -> Option<&'a Session> { None }
68 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { None }
70 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
73 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
75 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
77 last_source_file_index: 0,
78 lazy_state: LazyState::NoNode,
79 alloc_decoding_session: self.cdata().map(|cdata| {
80 cdata.alloc_decoding_state.new_decoding_session()
86 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
87 fn raw_bytes(self) -> &'a [u8] {
93 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'a Session) {
94 fn raw_bytes(self) -> &'a [u8] {
99 fn sess(self) -> Option<&'a Session> {
100 let (_, sess) = self;
106 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
107 fn raw_bytes(self) -> &'a [u8] {
108 self.blob.raw_bytes()
110 fn cdata(self) -> Option<&'a CrateMetadata> {
115 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
116 fn raw_bytes(self) -> &'a [u8] {
119 fn cdata(self) -> Option<&'a CrateMetadata> {
122 fn sess(self) -> Option<&'a Session> {
127 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
128 fn raw_bytes(self) -> &'a [u8] {
131 fn cdata(self) -> Option<&'a CrateMetadata> {
134 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
139 impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
140 pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
141 let mut dcx = meta.decoder(self.position);
142 dcx.lazy_state = LazyState::NodeStart(self.position);
143 T::decode(&mut dcx).unwrap()
147 impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
148 pub fn decode<M: Metadata<'a, 'tcx>>(
151 ) -> impl Iterator<Item = T> + Captures<'tcx> + 'a {
152 let mut dcx = meta.decoder(self.position);
153 dcx.lazy_state = LazyState::NodeStart(self.position);
154 (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
158 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
159 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
160 self.tcx.expect("missing TyCtxt in DecodeContext")
163 pub fn cdata(&self) -> &'a CrateMetadata {
164 self.cdata.expect("missing CrateMetadata in DecodeContext")
167 fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
168 let distance = self.read_usize()?;
169 let position = match self.lazy_state {
170 LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
171 LazyState::NodeStart(start) => {
172 assert!(distance + min_size <= start);
173 start - distance - min_size
175 LazyState::Previous(last_min_end) => last_min_end + distance,
177 self.lazy_state = LazyState::Previous(position + min_size);
182 impl<'a, 'tcx: 'a> TyDecoder<'a, 'tcx> for DecodeContext<'a, 'tcx> {
185 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
186 self.tcx.expect("missing TyCtxt in DecodeContext")
190 fn peek_byte(&self) -> u8 {
191 self.opaque.data[self.opaque.position()]
195 fn position(&self) -> usize {
196 self.opaque.position()
199 fn cached_ty_for_shorthand<F>(&mut self,
202 -> Result<Ty<'tcx>, Self::Error>
203 where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>
205 let tcx = self.tcx();
207 let key = ty::CReaderCacheKey {
208 cnum: self.cdata().cnum,
212 if let Some(&ty) = tcx.rcache.borrow().get(&key) {
216 let ty = or_insert_with(self)?;
217 tcx.rcache.borrow_mut().insert(key, ty);
221 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
222 where F: FnOnce(&mut Self) -> R
224 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
225 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
226 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
228 self.opaque = old_opaque;
229 self.lazy_state = old_state;
233 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
234 if cnum == LOCAL_CRATE {
237 self.cdata().cnum_map[cnum]
242 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
243 fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
244 Ok(Lazy::with_position(self.read_lazy_distance(Lazy::<T>::min_size())?))
248 impl<'a, 'tcx, T> SpecializedDecoder<LazySeq<T>> for DecodeContext<'a, 'tcx> {
249 fn specialized_decode(&mut self) -> Result<LazySeq<T>, Self::Error> {
250 let len = self.read_usize()?;
251 let position = if len == 0 {
254 self.read_lazy_distance(LazySeq::<T>::min_size(len))?
256 Ok(LazySeq::with_position_and_length(position, len))
261 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
263 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
264 let krate = CrateNum::decode(self)?;
265 let index = DefIndex::decode(self)?;
274 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
276 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
277 Ok(DefIndex::from_raw_u32(self.read_u32()?))
281 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for DecodeContext<'a, 'tcx> {
283 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
284 self.specialized_decode().map(|i| LocalDefId::from_def_id(i))
288 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
289 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
290 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
291 alloc_decoding_session.decode_alloc_id(self)
293 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
298 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
299 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
300 let tag = u8::decode(self)?;
302 if tag == TAG_INVALID_SPAN {
306 debug_assert_eq!(tag, TAG_VALID_SPAN);
308 let lo = BytePos::decode(self)?;
309 let len = BytePos::decode(self)?;
312 let sess = if let Some(sess) = self.sess {
315 bug!("Cannot decode Span without Session.")
318 let imported_source_files = self.cdata().imported_source_files(&sess.source_map());
320 // Optimize for the case that most spans within a translated item
321 // originate from the same source_file.
322 let last_source_file = &imported_source_files[self.last_source_file_index];
324 if lo >= last_source_file.original_start_pos &&
325 lo <= last_source_file.original_end_pos {
329 let mut b = imported_source_files.len();
333 if imported_source_files[m].original_start_pos > lo {
340 self.last_source_file_index = a;
341 &imported_source_files[a]
345 // Make sure our binary search above is correct.
346 debug_assert!(lo >= source_file.original_start_pos &&
347 lo <= source_file.original_end_pos);
349 // Make sure we correctly filtered out invalid spans during encoding
350 debug_assert!(hi >= source_file.original_start_pos &&
351 hi <= source_file.original_end_pos);
353 let lo = (lo + source_file.translated_source_file.start_pos)
354 - source_file.original_start_pos;
355 let hi = (hi + source_file.translated_source_file.start_pos)
356 - source_file.original_start_pos;
358 Ok(Span::new(lo, hi, NO_EXPANSION))
362 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
363 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
364 Fingerprint::decode_opaque(&mut self.opaque)
368 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
369 for DecodeContext<'a, 'tcx> {
371 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
372 Ok(mir::ClearCrossCrate::Clear)
376 implement_ty_decoder!( DecodeContext<'a, 'tcx> );
378 impl<'a, 'tcx> MetadataBlob {
379 pub fn is_compatible(&self) -> bool {
380 self.raw_bytes().starts_with(METADATA_HEADER)
383 pub fn get_rustc_version(&self) -> String {
384 Lazy::with_position(METADATA_HEADER.len() + 4).decode(self)
387 pub fn get_root(&self) -> CrateRoot {
388 let slice = self.raw_bytes();
389 let offset = METADATA_HEADER.len();
390 let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
391 ((slice[offset + 2] as u32) << 8) |
392 ((slice[offset + 3] as u32) << 0)) as usize;
393 Lazy::with_position(pos).decode(self)
396 pub fn list_crate_metadata(&self,
397 out: &mut dyn io::Write) -> io::Result<()> {
398 write!(out, "=External Dependencies=\n")?;
399 let root = self.get_root();
400 for (i, dep) in root.crate_deps
403 write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
410 impl<'tcx> EntryKind<'tcx> {
411 fn to_def(&self, did: DefId) -> Option<Def> {
413 EntryKind::Const(..) => Def::Const(did),
414 EntryKind::AssociatedConst(..) => Def::AssociatedConst(did),
415 EntryKind::ImmStatic |
416 EntryKind::ForeignImmStatic => Def::Static(did, false),
417 EntryKind::MutStatic |
418 EntryKind::ForeignMutStatic => Def::Static(did, true),
419 EntryKind::Struct(_, _) => Def::Struct(did),
420 EntryKind::Union(_, _) => Def::Union(did),
422 EntryKind::ForeignFn(_) => Def::Fn(did),
423 EntryKind::Method(_) => Def::Method(did),
424 EntryKind::Type => Def::TyAlias(did),
425 EntryKind::Existential => Def::Existential(did),
426 EntryKind::AssociatedType(_) => Def::AssociatedTy(did),
427 EntryKind::AssociatedExistential(_) => Def::AssociatedExistential(did),
428 EntryKind::Mod(_) => Def::Mod(did),
429 EntryKind::Variant(_) => Def::Variant(did),
430 EntryKind::Trait(_) => Def::Trait(did),
431 EntryKind::Enum(..) => Def::Enum(did),
432 EntryKind::MacroDef(_) => Def::Macro(did, MacroKind::Bang),
433 EntryKind::ForeignType => Def::ForeignTy(did),
435 EntryKind::ForeignMod |
436 EntryKind::GlobalAsm |
439 EntryKind::Generator(_) |
440 EntryKind::Closure(_) => return None,
445 /// Create the "fake" DefPathTable for a given proc macro crate.
447 /// The DefPathTable is as follows:
449 /// CRATE_ROOT (DefIndex 0:0)
450 /// |- GlobalMetaDataKind data (DefIndex 1:0 .. DefIndex 1:N)
451 /// |- proc macro #0 (DefIndex 1:N)
452 /// |- proc macro #1 (DefIndex 1:N+1)
454 crate fn proc_macro_def_path_table(crate_root: &CrateRoot,
455 proc_macros: &[(ast::Name, Lrc<SyntaxExtension>)])
458 let mut definitions = Definitions::new();
460 let name = crate_root.name.as_str();
461 let disambiguator = crate_root.disambiguator;
462 debug!("creating proc macro def path table for {:?}/{:?}", name, disambiguator);
463 let crate_root = definitions.create_root_def(&name, disambiguator);
464 for (index, (name, _)) in proc_macros.iter().enumerate() {
465 let def_index = definitions.create_def_with_parent(
468 DefPathData::MacroDef(name.as_interned_str()),
469 DefIndexAddressSpace::High,
472 debug!("definition for {:?} is {:?}", name, def_index);
473 assert_eq!(def_index, DefIndex::from_proc_macro_index(index));
476 definitions.def_path_table().clone()
479 impl<'a, 'tcx> CrateMetadata {
480 fn is_proc_macro(&self, id: DefIndex) -> bool {
481 self.proc_macros.is_some() && id != CRATE_DEF_INDEX
484 fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
485 assert!(!self.is_proc_macro(item_id));
486 self.root.index.lookup(self.blob.raw_bytes(), item_id)
489 fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
490 match self.maybe_entry(item_id) {
492 bug!("entry: id not found: {:?} in crate {:?} with number {}",
497 Some(d) => d.decode(self),
501 fn local_def_id(&self, index: DefIndex) -> DefId {
508 pub fn item_name(&self, item_index: DefIndex) -> InternedString {
509 self.def_key(item_index)
513 .expect("no name in item_name")
516 pub fn get_def(&self, index: DefIndex) -> Option<Def> {
517 if !self.is_proc_macro(index) {
518 self.entry(index).kind.to_def(self.local_def_id(index))
520 let kind = self.proc_macros.as_ref().unwrap()[index.to_proc_macro_index()].1.kind();
521 Some(Def::Macro(self.local_def_id(index), kind))
525 pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
526 match self.is_proc_macro(index) {
528 false => self.entry(index).span.decode((self, sess)),
532 pub fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
533 let data = match self.entry(item_id).kind {
534 EntryKind::Trait(data) => data.decode((self, sess)),
538 ty::TraitDef::new(self.local_def_id(item_id),
543 self.def_path_table.def_path_hash(item_id))
546 fn get_variant(&self,
547 tcx: TyCtxt<'a, 'tcx, 'tcx>,
550 adt_kind: ty::AdtKind)
553 let data = match item.kind {
554 EntryKind::Variant(data) |
555 EntryKind::Struct(data, _) |
556 EntryKind::Union(data, _) => data.decode(self),
560 let def_id = self.local_def_id(data.struct_ctor.unwrap_or(index));
561 let attribute_def_id = self.local_def_id(index);
566 self.item_name(index).as_symbol(),
568 item.children.decode(self).map(|index| {
569 let f = self.entry(index);
571 did: self.local_def_id(index),
572 ident: Ident::from_interned_str(self.item_name(index)),
573 vis: f.visibility.decode(self)
582 pub fn get_adt_def(&self,
584 tcx: TyCtxt<'a, 'tcx, 'tcx>)
585 -> &'tcx ty::AdtDef {
586 let item = self.entry(item_id);
587 let did = self.local_def_id(item_id);
589 let (kind, repr) = match item.kind {
590 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
591 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
592 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
593 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
596 let variants = if let ty::AdtKind::Enum = kind {
600 self.get_variant(tcx, &self.entry(index), index, kind)
604 std::iter::once(self.get_variant(tcx, &item, item_id, kind)).collect()
607 tcx.alloc_adt_def(did, kind, variants, repr)
610 pub fn get_predicates(&self,
612 tcx: TyCtxt<'a, 'tcx, 'tcx>)
613 -> ty::GenericPredicates<'tcx> {
614 self.entry(item_id).predicates.unwrap().decode((self, tcx))
617 pub fn get_predicates_defined_on(&self,
619 tcx: TyCtxt<'a, 'tcx, 'tcx>)
620 -> ty::GenericPredicates<'tcx> {
621 self.entry(item_id).predicates_defined_on.unwrap().decode((self, tcx))
624 pub fn get_super_predicates(&self,
626 tcx: TyCtxt<'a, 'tcx, 'tcx>)
627 -> ty::GenericPredicates<'tcx> {
628 match self.entry(item_id).kind {
629 EntryKind::Trait(data) => data.decode(self).super_predicates.decode((self, tcx)),
634 pub fn get_generics(&self,
638 self.entry(item_id).generics.unwrap().decode((self, sess))
641 pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
642 self.entry(id).ty.unwrap().decode((self, tcx))
645 pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
646 match self.is_proc_macro(id) {
648 false => self.entry(id).stability.map(|stab| stab.decode(self)),
652 pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
653 match self.is_proc_macro(id) {
655 false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
659 pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
660 match self.is_proc_macro(id) {
661 true => ty::Visibility::Public,
662 false => self.entry(id).visibility.decode(self),
666 fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
667 match self.entry(id).kind {
668 EntryKind::Impl(data) => data.decode(self),
673 pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
674 self.get_impl_data(id).parent_impl
677 pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
678 self.get_impl_data(id).polarity
681 pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
682 self.get_impl_data(id).defaultness
685 pub fn get_coerce_unsized_info(&self,
687 -> Option<ty::adjustment::CoerceUnsizedInfo> {
688 self.get_impl_data(id).coerce_unsized_info
691 pub fn get_impl_trait(&self,
693 tcx: TyCtxt<'a, 'tcx, 'tcx>)
694 -> Option<ty::TraitRef<'tcx>> {
695 self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
698 /// Iterates over all the stability attributes in the given crate.
699 pub fn get_lib_features(&self) -> Vec<(ast::Name, Option<ast::Name>)> {
700 // FIXME: For a proc macro crate, not sure whether we should return the "host"
701 // features or an empty Vec. Both don't cause ICEs.
708 /// Iterates over the language items in the given crate.
709 pub fn get_lang_items(&self) -> Vec<(DefId, usize)> {
710 if self.proc_macros.is_some() {
711 // Proc macro crates do not export any lang-items to the target.
717 .map(|(def_index, index)| (self.local_def_id(def_index), index))
722 /// Iterates over each child of the given item.
723 pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
724 where F: FnMut(def::Export)
726 if let Some(ref proc_macros) = self.proc_macros {
727 /* If we are loading as a proc macro, we want to return the view of this crate
728 * as a proc macro crate, not as a Rust crate. See `proc_macro_def_path_table`
729 * for the DefPathTable we are corresponding to.
731 if id == CRATE_DEF_INDEX {
732 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
733 let def = Def::Macro(
736 index: DefIndex::from_proc_macro_index(id),
740 let ident = Ident::with_empty_ctxt(name);
741 callback(def::Export {
744 vis: ty::Visibility::Public,
753 let item = match self.maybe_entry(id) {
755 Some(item) => item.decode((self, sess)),
758 // Iterate over all children.
759 let macros_only = self.dep_kind.lock().macros_only();
760 for child_index in item.children.decode((self, sess)) {
766 if let Some(child) = self.maybe_entry(child_index) {
767 let child = child.decode((self, sess));
769 EntryKind::MacroDef(..) => {}
770 _ if macros_only => continue,
774 // Hand off the item to the callback.
776 // FIXME(eddyb) Don't encode these in children.
777 EntryKind::ForeignMod => {
778 for child_index in child.children.decode((self, sess)) {
779 if let Some(def) = self.get_def(child_index) {
780 callback(def::Export {
782 ident: Ident::from_interned_str(self.item_name(child_index)),
783 vis: self.get_visibility(child_index),
784 span: self.entry(child_index).span.decode((self, sess)),
790 EntryKind::Impl(_) => continue,
795 let def_key = self.def_key(child_index);
796 let span = child.span.decode((self, sess));
797 if let (Some(def), Some(name)) =
798 (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
799 let ident = Ident::from_interned_str(name);
800 let vis = self.get_visibility(child_index);
801 callback(def::Export { def, ident, vis, span });
802 // For non-re-export structs and variants add their constructors to children.
803 // Re-export lists automatically contain constructors when necessary.
806 if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
807 let ctor_kind = self.get_ctor_kind(child_index);
808 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
809 callback(def::Export {
811 vis: self.get_visibility(ctor_def_id.index),
816 Def::Variant(def_id) => {
817 // Braced variants, unlike structs, generate unusable names in
818 // value namespace, they are reserved for possible future use.
819 let ctor_kind = self.get_ctor_kind(child_index);
820 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
821 let vis = self.get_visibility(child_index);
822 callback(def::Export { def: ctor_def, ident, vis, span });
830 if let EntryKind::Mod(data) = item.kind {
831 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
834 _ if macros_only => continue,
842 pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
843 match self.entry(id).kind {
844 EntryKind::AssociatedConst(_, data, _) |
845 EntryKind::Const(data, _) => data.ast_promotable,
850 pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
851 !self.is_proc_macro(id) &&
852 self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
855 pub fn maybe_get_optimized_mir(&self,
856 tcx: TyCtxt<'a, 'tcx, 'tcx>,
858 -> Option<Mir<'tcx>> {
859 match self.is_proc_macro(id) {
861 false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
865 pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
866 match self.entry(id).kind {
867 EntryKind::Const(qualif, _) |
868 EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif, _) |
869 EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif, _) => {
876 pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
877 let item = self.entry(id);
878 let def_key = self.def_key(id);
879 let parent = self.local_def_id(def_key.parent.unwrap());
880 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
882 let (kind, container, has_self) = match item.kind {
883 EntryKind::AssociatedConst(container, _, _) => {
884 (ty::AssociatedKind::Const, container, false)
886 EntryKind::Method(data) => {
887 let data = data.decode(self);
888 (ty::AssociatedKind::Method, data.container, data.has_self)
890 EntryKind::AssociatedType(container) => {
891 (ty::AssociatedKind::Type, container, false)
893 _ => bug!("cannot get associated-item of `{:?}`", def_key)
897 ident: Ident::from_interned_str(name),
899 vis: item.visibility.decode(self),
900 defaultness: container.defaultness(),
901 def_id: self.local_def_id(id),
902 container: container.with_def_id(parent),
903 method_has_self_argument: has_self
907 pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
908 self.entry(id).variances.decode(self).collect()
911 pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
912 match self.entry(node_id).kind {
913 EntryKind::Struct(data, _) |
914 EntryKind::Union(data, _) |
915 EntryKind::Variant(data) => data.decode(self).ctor_kind,
916 _ => CtorKind::Fictive,
920 pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
921 match self.entry(node_id).kind {
922 EntryKind::Struct(data, _) => {
923 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
929 pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
930 if self.is_proc_macro(node_id) {
934 // The attributes for a tuple struct are attached to the definition, not the ctor;
935 // we assume that someone passing in a tuple struct ctor is actually wanting to
936 // look at the definition
937 let def_key = self.def_key(node_id);
938 let item_id = if def_key.disambiguated_data.data == DefPathData::StructCtor {
939 def_key.parent.unwrap()
944 let item = self.entry(item_id);
945 Lrc::from(self.get_attributes(&item, sess))
948 pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
952 .map(|index| self.item_name(index).as_symbol())
956 fn get_attributes(&self, item: &Entry<'tcx>, sess: &Session) -> Vec<ast::Attribute> {
958 .decode((self, sess))
960 // Need new unique IDs: old thread-local IDs won't map to new threads.
961 attr.id = attr::mk_attr_id();
967 // Translate a DefId from the current compilation environment to a DefId
968 // for an external crate.
969 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
970 for (local, &global) in self.cnum_map.iter_enumerated() {
971 if global == did.krate {
982 pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
986 .map(|index| self.local_def_id(index))
990 pub fn get_implementations_for_trait(&self,
991 filter: Option<DefId>,
992 result: &mut Vec<DefId>) {
993 if self.proc_macros.is_some() {
994 // proc-macro crates export no trait impls.
998 // Do a reverse lookup beforehand to avoid touching the crate_num
999 // hash map in the loop below.
1000 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1001 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1002 Some(None) => return,
1006 if let Some(filter) = filter {
1007 if let Some(impls) = self.trait_impls
1009 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
1012 for impls in self.trait_impls.values() {
1013 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
1018 pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1019 let def_key = self.def_key(id);
1020 match def_key.disambiguated_data.data {
1021 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1022 // Not an associated item
1025 def_key.parent.and_then(|parent_index| {
1026 match self.entry(parent_index).kind {
1027 EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
1034 pub fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1035 if self.proc_macros.is_some() {
1036 // Proc macro crates do not have any *target* native libraries.
1039 self.root.native_libraries.decode((self, sess)).collect()
1043 pub fn get_foreign_modules(&self, sess: &Session) -> Vec<ForeignModule> {
1044 if self.proc_macros.is_some() {
1045 // Proc macro crates do not have any *target* foreign modules.
1048 self.root.foreign_modules.decode((self, sess)).collect()
1052 pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> {
1054 .dylib_dependency_formats
1057 .flat_map(|(i, link)| {
1058 let cnum = CrateNum::new(i + 1);
1059 link.map(|link| (self.cnum_map[cnum], link))
1064 pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> {
1065 if self.proc_macros.is_some() {
1066 // Proc macro crates do not depend on any target weak lang-items.
1076 pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
1077 let arg_names = match self.entry(id).kind {
1078 EntryKind::Fn(data) |
1079 EntryKind::ForeignFn(data) => data.decode(self).arg_names,
1080 EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
1081 _ => LazySeq::empty(),
1083 arg_names.decode(self).collect()
1086 pub fn exported_symbols(&self,
1087 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1088 -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1089 if self.proc_macros.is_some() {
1090 // If this crate is a custom derive crate, then we're not even going to
1091 // link those in so we skip those crates.
1094 let lazy_seq: LazySeq<(ExportedSymbol<'tcx>, SymbolExportLevel)> =
1095 LazySeq::with_position_and_length(self.root.exported_symbols.position,
1096 self.root.exported_symbols.len);
1097 lazy_seq.decode((self, tcx)).collect()
1101 pub fn get_rendered_const(&self, id: DefIndex) -> String {
1102 match self.entry(id).kind {
1103 EntryKind::Const(_, data) |
1104 EntryKind::AssociatedConst(_, _, data) => data.decode(self).0,
1109 pub fn get_macro(&self, id: DefIndex) -> MacroDef {
1110 let entry = self.entry(id);
1112 EntryKind::MacroDef(macro_def) => macro_def.decode(self),
1117 crate fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1118 let constness = match self.entry(id).kind {
1119 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1120 EntryKind::Fn(data) => data.decode(self).constness,
1121 _ => hir::Constness::NotConst,
1123 constness == hir::Constness::Const
1126 pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1127 match self.entry(id).kind {
1128 EntryKind::ForeignImmStatic |
1129 EntryKind::ForeignMutStatic |
1130 EntryKind::ForeignFn(_) => true,
1135 pub fn fn_sig(&self,
1137 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1138 -> ty::PolyFnSig<'tcx> {
1139 let sig = match self.entry(id).kind {
1140 EntryKind::Fn(data) |
1141 EntryKind::ForeignFn(data) => data.decode(self).sig,
1142 EntryKind::Method(data) => data.decode(self).fn_data.sig,
1143 EntryKind::Variant(data) |
1144 EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1145 EntryKind::Closure(data) => data.decode(self).sig,
1148 sig.decode((self, tcx))
1152 pub fn def_key(&self, index: DefIndex) -> DefKey {
1153 self.def_path_table.def_key(index)
1156 // Returns the path leading to the thing with this `id`.
1157 pub fn def_path(&self, id: DefIndex) -> DefPath {
1158 debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1159 DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1163 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1164 self.def_path_table.def_path_hash(index)
1167 /// Imports the source_map from an external crate into the source_map of the crate
1168 /// currently being compiled (the "local crate").
1170 /// The import algorithm works analogous to how AST items are inlined from an
1171 /// external crate's metadata:
1172 /// For every SourceFile in the external source_map an 'inline' copy is created in the
1173 /// local source_map. The correspondence relation between external and local
1174 /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1175 /// function. When an item from an external crate is later inlined into this
1176 /// crate, this correspondence information is used to translate the span
1177 /// information of the inlined item so that it refers the correct positions in
1178 /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1180 /// The import algorithm in the function below will reuse SourceFiles already
1181 /// existing in the local source_map. For example, even if the SourceFile of some
1182 /// source file of libstd gets imported many times, there will only ever be
1183 /// one SourceFile object for the corresponding file in the local source_map.
1185 /// Note that imported SourceFiles do not actually contain the source code of the
1186 /// file they represent, just information about length, line breaks, and
1187 /// multibyte characters. This information is enough to generate valid debuginfo
1188 /// for items inlined from other crates.
1190 /// Proc macro crates don't currently export spans, so this function does not have
1191 /// to work for them.
1192 pub fn imported_source_files(&'a self,
1193 local_source_map: &source_map::SourceMap)
1194 -> ReadGuard<'a, Vec<cstore::ImportedSourceFile>> {
1196 let source_files = self.source_map_import_info.borrow();
1197 if !source_files.is_empty() {
1198 return source_files;
1202 // Lock the source_map_import_info to ensure this only happens once
1203 let mut source_map_import_info = self.source_map_import_info.borrow_mut();
1205 if !source_map_import_info.is_empty() {
1206 drop(source_map_import_info);
1207 return self.source_map_import_info.borrow();
1210 let external_source_map = self.root.source_map.decode(self);
1212 let imported_source_files = external_source_map.map(|source_file_to_import| {
1213 // We can't reuse an existing SourceFile, so allocate a new one
1214 // containing the information we need.
1215 let syntax_pos::SourceFile { name,
1221 mut multibyte_chars,
1222 mut non_narrow_chars,
1224 .. } = source_file_to_import;
1226 let source_length = (end_pos - start_pos).to_usize();
1228 // Translate line-start positions and multibyte character
1229 // position into frame of reference local to file.
1230 // `SourceMap::new_imported_source_file()` will then translate those
1231 // coordinates to their new global frame of reference when the
1232 // offset of the SourceFile is known.
1233 for pos in &mut lines {
1234 *pos = *pos - start_pos;
1236 for mbc in &mut multibyte_chars {
1237 mbc.pos = mbc.pos - start_pos;
1239 for swc in &mut non_narrow_chars {
1240 *swc = *swc - start_pos;
1243 let local_version = local_source_map.new_imported_source_file(name,
1252 debug!("CrateMetaData::imported_source_files alloc \
1253 source_file {:?} original (start_pos {:?} end_pos {:?}) \
1254 translated (start_pos {:?} end_pos {:?})",
1255 local_version.name, start_pos, end_pos,
1256 local_version.start_pos, local_version.end_pos);
1258 cstore::ImportedSourceFile {
1259 original_start_pos: start_pos,
1260 original_end_pos: end_pos,
1261 translated_source_file: local_version,
1265 *source_map_import_info = imported_source_files;
1266 drop(source_map_import_info);
1268 // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1269 self.source_map_import_info.borrow()