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,
18 DisambiguatedDefPathData};
20 use rustc::middle::cstore::LinkagePreference;
21 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
22 use rustc::hir::def::{self, Def, CtorKind};
23 use rustc::hir::def_id::{CrateNum, DefId, DefIndex,
24 CRATE_DEF_INDEX, LOCAL_CRATE, LocalDefId};
25 use rustc::ich::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};
43 use syntax::symbol::InternedString;
44 use syntax::ext::base::MacroKind;
45 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
47 pub struct DecodeContext<'a, 'tcx: 'a> {
48 opaque: opaque::Decoder<'a>,
49 cdata: Option<&'a CrateMetadata>,
50 sess: Option<&'a Session>,
51 tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
53 // Cache the last used filemap for translating spans as an optimization.
54 last_filemap_index: usize,
56 lazy_state: LazyState,
58 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
59 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
62 /// Abstract over the various ways one can create metadata decoders.
63 pub trait Metadata<'a, 'tcx>: Copy {
64 fn raw_bytes(self) -> &'a [u8];
65 fn cdata(self) -> Option<&'a CrateMetadata> { None }
66 fn sess(self) -> Option<&'a Session> { None }
67 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { None }
69 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
72 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
74 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
76 last_filemap_index: 0,
77 lazy_state: LazyState::NoNode,
78 alloc_decoding_session: self.cdata().map(|cdata| {
79 cdata.alloc_decoding_state.new_decoding_session()
85 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
86 fn raw_bytes(self) -> &'a [u8] {
92 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'a Session) {
93 fn raw_bytes(self) -> &'a [u8] {
98 fn sess(self) -> Option<&'a Session> {
105 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
106 fn raw_bytes(self) -> &'a [u8] {
107 self.blob.raw_bytes()
109 fn cdata(self) -> Option<&'a CrateMetadata> {
114 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
115 fn raw_bytes(self) -> &'a [u8] {
118 fn cdata(self) -> Option<&'a CrateMetadata> {
121 fn sess(self) -> Option<&'a Session> {
126 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
127 fn raw_bytes(self) -> &'a [u8] {
130 fn cdata(self) -> Option<&'a CrateMetadata> {
133 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
138 impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
139 pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
140 let mut dcx = meta.decoder(self.position);
141 dcx.lazy_state = LazyState::NodeStart(self.position);
142 T::decode(&mut dcx).unwrap()
146 impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
147 pub fn decode<M: Metadata<'a, 'tcx>>(
150 ) -> impl Iterator<Item = T> + Captures<'tcx> + 'a {
151 let mut dcx = meta.decoder(self.position);
152 dcx.lazy_state = LazyState::NodeStart(self.position);
153 (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
157 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
158 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
159 self.tcx.expect("missing TyCtxt in DecodeContext")
162 pub fn cdata(&self) -> &'a CrateMetadata {
163 self.cdata.expect("missing CrateMetadata in DecodeContext")
166 fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
167 let distance = self.read_usize()?;
168 let position = match self.lazy_state {
169 LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
170 LazyState::NodeStart(start) => {
171 assert!(distance + min_size <= start);
172 start - distance - min_size
174 LazyState::Previous(last_min_end) => last_min_end + distance,
176 self.lazy_state = LazyState::Previous(position + min_size);
181 impl<'a, 'tcx: 'a> TyDecoder<'a, 'tcx> for DecodeContext<'a, 'tcx> {
184 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
185 self.tcx.expect("missing TyCtxt in DecodeContext")
189 fn peek_byte(&self) -> u8 {
190 self.opaque.data[self.opaque.position()]
194 fn position(&self) -> usize {
195 self.opaque.position()
198 fn cached_ty_for_shorthand<F>(&mut self,
201 -> Result<Ty<'tcx>, Self::Error>
202 where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>
204 let tcx = self.tcx();
206 let key = ty::CReaderCacheKey {
207 cnum: self.cdata().cnum,
211 if let Some(&ty) = tcx.rcache.borrow().get(&key) {
215 let ty = or_insert_with(self)?;
216 tcx.rcache.borrow_mut().insert(key, ty);
220 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
221 where F: FnOnce(&mut Self) -> R
223 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
224 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
225 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
227 self.opaque = old_opaque;
228 self.lazy_state = old_state;
232 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
233 if cnum == LOCAL_CRATE {
236 self.cdata().cnum_map[cnum]
241 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
242 fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
243 Ok(Lazy::with_position(self.read_lazy_distance(Lazy::<T>::min_size())?))
247 impl<'a, 'tcx, T> SpecializedDecoder<LazySeq<T>> for DecodeContext<'a, 'tcx> {
248 fn specialized_decode(&mut self) -> Result<LazySeq<T>, Self::Error> {
249 let len = self.read_usize()?;
250 let position = if len == 0 {
253 self.read_lazy_distance(LazySeq::<T>::min_size(len))?
255 Ok(LazySeq::with_position_and_length(position, len))
260 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
262 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
263 let krate = CrateNum::decode(self)?;
264 let index = DefIndex::decode(self)?;
273 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
275 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
276 Ok(DefIndex::from_raw_u32(self.read_u32()?))
280 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for DecodeContext<'a, 'tcx> {
282 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
283 self.specialized_decode().map(|i| LocalDefId::from_def_id(i))
287 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
288 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
289 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
290 alloc_decoding_session.decode_alloc_id(self)
292 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
297 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
298 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
299 let tag = u8::decode(self)?;
301 if tag == TAG_INVALID_SPAN {
305 debug_assert_eq!(tag, TAG_VALID_SPAN);
307 let lo = BytePos::decode(self)?;
308 let len = BytePos::decode(self)?;
311 let sess = if let Some(sess) = self.sess {
314 bug!("Cannot decode Span without Session.")
317 let imported_filemaps = self.cdata().imported_filemaps(&sess.codemap());
319 // Optimize for the case that most spans within a translated item
320 // originate from the same filemap.
321 let last_filemap = &imported_filemaps[self.last_filemap_index];
323 if lo >= last_filemap.original_start_pos &&
324 lo <= last_filemap.original_end_pos {
328 let mut b = imported_filemaps.len();
332 if imported_filemaps[m].original_start_pos > lo {
339 self.last_filemap_index = a;
340 &imported_filemaps[a]
344 // Make sure our binary search above is correct.
345 debug_assert!(lo >= filemap.original_start_pos &&
346 lo <= filemap.original_end_pos);
348 // Make sure we correctly filtered out invalid spans during encoding
349 debug_assert!(hi >= filemap.original_start_pos &&
350 hi <= filemap.original_end_pos);
352 let lo = (lo + filemap.translated_filemap.start_pos) - filemap.original_start_pos;
353 let hi = (hi + filemap.translated_filemap.start_pos) - filemap.original_start_pos;
355 Ok(Span::new(lo, hi, NO_EXPANSION))
359 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
360 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
361 Fingerprint::decode_opaque(&mut self.opaque)
365 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
366 for DecodeContext<'a, 'tcx> {
368 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
369 Ok(mir::ClearCrossCrate::Clear)
373 implement_ty_decoder!( DecodeContext<'a, 'tcx> );
375 impl<'a, 'tcx> MetadataBlob {
376 pub fn is_compatible(&self) -> bool {
377 self.raw_bytes().starts_with(METADATA_HEADER)
380 pub fn get_rustc_version(&self) -> String {
381 Lazy::with_position(METADATA_HEADER.len() + 4).decode(self)
384 pub fn get_root(&self) -> CrateRoot {
385 let slice = self.raw_bytes();
386 let offset = METADATA_HEADER.len();
387 let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
388 ((slice[offset + 2] as u32) << 8) |
389 ((slice[offset + 3] as u32) << 0)) as usize;
390 Lazy::with_position(pos).decode(self)
393 pub fn list_crate_metadata(&self,
394 out: &mut dyn io::Write) -> io::Result<()> {
395 write!(out, "=External Dependencies=\n")?;
396 let root = self.get_root();
397 for (i, dep) in root.crate_deps
400 write!(out, "{} {}-{}\n", i + 1, dep.name, dep.hash)?;
407 impl<'tcx> EntryKind<'tcx> {
408 fn to_def(&self, did: DefId) -> Option<Def> {
410 EntryKind::Const(..) => Def::Const(did),
411 EntryKind::AssociatedConst(..) => Def::AssociatedConst(did),
412 EntryKind::ImmStatic |
413 EntryKind::ForeignImmStatic => Def::Static(did, false),
414 EntryKind::MutStatic |
415 EntryKind::ForeignMutStatic => Def::Static(did, true),
416 EntryKind::Struct(_, _) => Def::Struct(did),
417 EntryKind::Union(_, _) => Def::Union(did),
419 EntryKind::ForeignFn(_) => Def::Fn(did),
420 EntryKind::Method(_) => Def::Method(did),
421 EntryKind::Type => Def::TyAlias(did),
422 EntryKind::Existential => Def::Existential(did),
423 EntryKind::AssociatedType(_) => Def::AssociatedTy(did),
424 EntryKind::AssociatedExistential(_) => Def::AssociatedExistential(did),
425 EntryKind::Mod(_) => Def::Mod(did),
426 EntryKind::Variant(_) => Def::Variant(did),
427 EntryKind::Trait(_) => Def::Trait(did),
428 EntryKind::Enum(..) => Def::Enum(did),
429 EntryKind::MacroDef(_) => Def::Macro(did, MacroKind::Bang),
430 EntryKind::GlobalAsm => Def::GlobalAsm(did),
431 EntryKind::ForeignType => Def::TyForeign(did),
433 EntryKind::ForeignMod |
436 EntryKind::Generator(_) |
437 EntryKind::Closure(_) => return None,
442 impl<'a, 'tcx> CrateMetadata {
443 fn is_proc_macro(&self, id: DefIndex) -> bool {
444 self.proc_macros.is_some() && id != CRATE_DEF_INDEX
447 fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
448 assert!(!self.is_proc_macro(item_id));
449 self.root.index.lookup(self.blob.raw_bytes(), item_id)
452 fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
453 match self.maybe_entry(item_id) {
455 bug!("entry: id not found: {:?} in crate {:?} with number {}",
460 Some(d) => d.decode(self),
464 fn local_def_id(&self, index: DefIndex) -> DefId {
471 pub fn item_name(&self, item_index: DefIndex) -> InternedString {
472 self.def_key(item_index)
476 .expect("no name in item_name")
479 pub fn get_def(&self, index: DefIndex) -> Option<Def> {
480 if !self.is_proc_macro(index) {
481 self.entry(index).kind.to_def(self.local_def_id(index))
483 let kind = self.proc_macros.as_ref().unwrap()[index.to_proc_macro_index()].1.kind();
484 Some(Def::Macro(self.local_def_id(index), kind))
488 pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
489 match self.is_proc_macro(index) {
491 false => self.entry(index).span.decode((self, sess)),
495 pub fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
496 let data = match self.entry(item_id).kind {
497 EntryKind::Trait(data) => data.decode((self, sess)),
501 ty::TraitDef::new(self.local_def_id(item_id),
505 self.def_path_table.def_path_hash(item_id))
508 fn get_variant(&self, item: &Entry, index: DefIndex) -> ty::VariantDef {
509 let data = match item.kind {
510 EntryKind::Variant(data) |
511 EntryKind::Struct(data, _) |
512 EntryKind::Union(data, _) => data.decode(self),
517 did: self.local_def_id(data.struct_ctor.unwrap_or(index)),
518 name: self.item_name(index).as_symbol(),
519 fields: item.children.decode(self).map(|index| {
520 let f = self.entry(index);
522 did: self.local_def_id(index),
523 ident: Ident::from_interned_str(self.item_name(index)),
524 vis: f.visibility.decode(self)
528 ctor_kind: data.ctor_kind,
532 pub fn get_adt_def(&self,
534 tcx: TyCtxt<'a, 'tcx, 'tcx>)
535 -> &'tcx ty::AdtDef {
536 let item = self.entry(item_id);
537 let did = self.local_def_id(item_id);
539 let (kind, repr) = match item.kind {
540 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
541 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
542 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
543 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
546 let variants = if let ty::AdtKind::Enum = kind {
550 self.get_variant(&self.entry(index), index)
554 vec![self.get_variant(&item, item_id)]
557 tcx.alloc_adt_def(did, kind, variants, repr)
560 pub fn get_predicates(&self,
562 tcx: TyCtxt<'a, 'tcx, 'tcx>)
563 -> ty::GenericPredicates<'tcx> {
564 self.entry(item_id).predicates.unwrap().decode((self, tcx))
567 pub fn get_predicates_defined_on(&self,
569 tcx: TyCtxt<'a, 'tcx, 'tcx>)
570 -> ty::GenericPredicates<'tcx> {
571 self.entry(item_id).predicates_defined_on.unwrap().decode((self, tcx))
574 pub fn get_super_predicates(&self,
576 tcx: TyCtxt<'a, 'tcx, 'tcx>)
577 -> ty::GenericPredicates<'tcx> {
578 match self.entry(item_id).kind {
579 EntryKind::Trait(data) => data.decode(self).super_predicates.decode((self, tcx)),
584 pub fn get_generics(&self,
588 self.entry(item_id).generics.unwrap().decode((self, sess))
591 pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
592 self.entry(id).ty.unwrap().decode((self, tcx))
595 pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
596 match self.is_proc_macro(id) {
598 false => self.entry(id).stability.map(|stab| stab.decode(self)),
602 pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
603 match self.is_proc_macro(id) {
605 false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
609 pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
610 match self.is_proc_macro(id) {
611 true => ty::Visibility::Public,
612 false => self.entry(id).visibility.decode(self),
616 fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
617 match self.entry(id).kind {
618 EntryKind::Impl(data) => data.decode(self),
623 pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
624 self.get_impl_data(id).parent_impl
627 pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
628 self.get_impl_data(id).polarity
631 pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
632 self.get_impl_data(id).defaultness
635 pub fn get_coerce_unsized_info(&self,
637 -> Option<ty::adjustment::CoerceUnsizedInfo> {
638 self.get_impl_data(id).coerce_unsized_info
641 pub fn get_impl_trait(&self,
643 tcx: TyCtxt<'a, 'tcx, 'tcx>)
644 -> Option<ty::TraitRef<'tcx>> {
645 self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
648 /// Iterates over the language items in the given crate.
649 pub fn get_lang_items(&self) -> Vec<(DefId, usize)> {
653 .map(|(def_index, index)| (self.local_def_id(def_index), index))
657 /// Iterates over each child of the given item.
658 pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
659 where F: FnMut(def::Export)
661 if let Some(ref proc_macros) = self.proc_macros {
662 if id == CRATE_DEF_INDEX {
663 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
664 let def = Def::Macro(
667 index: DefIndex::from_proc_macro_index(id),
671 let ident = Ident::with_empty_ctxt(name);
672 callback(def::Export {
675 vis: ty::Visibility::Public,
684 let item = match self.maybe_entry(id) {
686 Some(item) => item.decode((self, sess)),
689 // Iterate over all children.
690 let macros_only = self.dep_kind.lock().macros_only();
691 for child_index in item.children.decode((self, sess)) {
697 if let Some(child) = self.maybe_entry(child_index) {
698 let child = child.decode((self, sess));
700 EntryKind::MacroDef(..) => {}
701 _ if macros_only => continue,
705 // Hand off the item to the callback.
707 // FIXME(eddyb) Don't encode these in children.
708 EntryKind::ForeignMod => {
709 for child_index in child.children.decode((self, sess)) {
710 if let Some(def) = self.get_def(child_index) {
711 callback(def::Export {
713 ident: Ident::from_interned_str(self.item_name(child_index)),
714 vis: self.get_visibility(child_index),
715 span: self.entry(child_index).span.decode((self, sess)),
721 EntryKind::Impl(_) => continue,
726 let def_key = self.def_key(child_index);
727 let span = child.span.decode((self, sess));
728 if let (Some(def), Some(name)) =
729 (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
730 let ident = Ident::from_interned_str(name);
731 let vis = self.get_visibility(child_index);
732 callback(def::Export { def, ident, vis, span });
733 // For non-re-export structs and variants add their constructors to children.
734 // Re-export lists automatically contain constructors when necessary.
737 if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
738 let ctor_kind = self.get_ctor_kind(child_index);
739 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
740 callback(def::Export {
742 vis: self.get_visibility(ctor_def_id.index),
747 Def::Variant(def_id) => {
748 // Braced variants, unlike structs, generate unusable names in
749 // value namespace, they are reserved for possible future use.
750 let ctor_kind = self.get_ctor_kind(child_index);
751 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
752 let vis = self.get_visibility(child_index);
753 callback(def::Export { def: ctor_def, ident, vis, span });
761 if let EntryKind::Mod(data) = item.kind {
762 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
765 _ if macros_only => continue,
773 pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
774 match self.entry(id).kind {
775 EntryKind::AssociatedConst(_, data, _) |
776 EntryKind::Const(data, _) => data.ast_promotable,
781 pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
782 !self.is_proc_macro(id) &&
783 self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
786 pub fn maybe_get_optimized_mir(&self,
787 tcx: TyCtxt<'a, 'tcx, 'tcx>,
789 -> Option<Mir<'tcx>> {
790 match self.is_proc_macro(id) {
792 false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
796 pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
797 match self.entry(id).kind {
798 EntryKind::Const(qualif, _) |
799 EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif, _) |
800 EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif, _) => {
807 pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
808 let item = self.entry(id);
809 let def_key = self.def_key(id);
810 let parent = self.local_def_id(def_key.parent.unwrap());
811 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
813 let (kind, container, has_self) = match item.kind {
814 EntryKind::AssociatedConst(container, _, _) => {
815 (ty::AssociatedKind::Const, container, false)
817 EntryKind::Method(data) => {
818 let data = data.decode(self);
819 (ty::AssociatedKind::Method, data.container, data.has_self)
821 EntryKind::AssociatedType(container) => {
822 (ty::AssociatedKind::Type, container, false)
824 _ => bug!("cannot get associated-item of `{:?}`", def_key)
828 ident: Ident::from_interned_str(name),
830 vis: item.visibility.decode(self),
831 defaultness: container.defaultness(),
832 def_id: self.local_def_id(id),
833 container: container.with_def_id(parent),
834 method_has_self_argument: has_self
838 pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
839 self.entry(id).variances.decode(self).collect()
842 pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
843 match self.entry(node_id).kind {
844 EntryKind::Struct(data, _) |
845 EntryKind::Union(data, _) |
846 EntryKind::Variant(data) => data.decode(self).ctor_kind,
847 _ => CtorKind::Fictive,
851 pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
852 match self.entry(node_id).kind {
853 EntryKind::Struct(data, _) => {
854 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
860 pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
861 if self.is_proc_macro(node_id) {
865 // The attributes for a tuple struct are attached to the definition, not the ctor;
866 // we assume that someone passing in a tuple struct ctor is actually wanting to
867 // look at the definition
868 let def_key = self.def_key(node_id);
869 let item_id = if def_key.disambiguated_data.data == DefPathData::StructCtor {
870 def_key.parent.unwrap()
875 let item = self.entry(item_id);
876 Lrc::from(self.get_attributes(&item, sess))
879 pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
883 .map(|index| self.item_name(index).as_symbol())
887 fn get_attributes(&self, item: &Entry<'tcx>, sess: &Session) -> Vec<ast::Attribute> {
889 .decode((self, sess))
891 // Need new unique IDs: old thread-local IDs won't map to new threads.
892 attr.id = attr::mk_attr_id();
898 // Translate a DefId from the current compilation environment to a DefId
899 // for an external crate.
900 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
901 for (local, &global) in self.cnum_map.iter_enumerated() {
902 if global == did.krate {
913 pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
917 .map(|index| self.local_def_id(index))
921 pub fn get_implementations_for_trait(&self,
922 filter: Option<DefId>,
923 result: &mut Vec<DefId>) {
924 // Do a reverse lookup beforehand to avoid touching the crate_num
925 // hash map in the loop below.
926 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
927 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
928 Some(None) => return,
929 None if self.proc_macros.is_some() => return,
933 if let Some(filter) = filter {
934 if let Some(impls) = self.trait_impls
936 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
939 for impls in self.trait_impls.values() {
940 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
945 pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
946 let def_key = self.def_key(id);
947 match def_key.disambiguated_data.data {
948 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
949 // Not an associated item
952 def_key.parent.and_then(|parent_index| {
953 match self.entry(parent_index).kind {
954 EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
961 pub fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
962 self.root.native_libraries.decode((self, sess)).collect()
965 pub fn get_foreign_modules(&self, sess: &Session) -> Vec<ForeignModule> {
966 self.root.foreign_modules.decode((self, sess)).collect()
969 pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> {
971 .dylib_dependency_formats
974 .flat_map(|(i, link)| {
975 let cnum = CrateNum::new(i + 1);
976 link.map(|link| (self.cnum_map[cnum], link))
981 pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> {
988 pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
989 let arg_names = match self.entry(id).kind {
990 EntryKind::Fn(data) |
991 EntryKind::ForeignFn(data) => data.decode(self).arg_names,
992 EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
993 _ => LazySeq::empty(),
995 arg_names.decode(self).collect()
998 pub fn exported_symbols(&self,
999 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1000 -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1001 let lazy_seq: LazySeq<(ExportedSymbol<'tcx>, SymbolExportLevel)> =
1002 LazySeq::with_position_and_length(self.root.exported_symbols.position,
1003 self.root.exported_symbols.len);
1004 lazy_seq.decode((self, tcx)).collect()
1007 pub fn get_rendered_const(&self, id: DefIndex) -> String {
1008 match self.entry(id).kind {
1009 EntryKind::Const(_, data) |
1010 EntryKind::AssociatedConst(_, _, data) => data.decode(self).0,
1015 pub fn get_macro(&self, id: DefIndex) -> (InternedString, MacroDef) {
1016 let entry = self.entry(id);
1018 EntryKind::MacroDef(macro_def) => (self.item_name(id), macro_def.decode(self)),
1023 pub fn is_const_fn(&self, id: DefIndex) -> bool {
1024 let constness = match self.entry(id).kind {
1025 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1026 EntryKind::Fn(data) => data.decode(self).constness,
1027 _ => hir::Constness::NotConst,
1029 constness == hir::Constness::Const
1032 pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1033 match self.entry(id).kind {
1034 EntryKind::ForeignImmStatic |
1035 EntryKind::ForeignMutStatic |
1036 EntryKind::ForeignFn(_) => true,
1041 pub fn fn_sig(&self,
1043 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1044 -> ty::PolyFnSig<'tcx> {
1045 let sig = match self.entry(id).kind {
1046 EntryKind::Fn(data) |
1047 EntryKind::ForeignFn(data) => data.decode(self).sig,
1048 EntryKind::Method(data) => data.decode(self).fn_data.sig,
1049 EntryKind::Variant(data) |
1050 EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1051 EntryKind::Closure(data) => data.decode(self).sig,
1054 sig.decode((self, tcx))
1058 pub fn def_key(&self, index: DefIndex) -> DefKey {
1059 if !self.is_proc_macro(index) {
1060 self.def_path_table.def_key(index)
1062 // FIXME(#49271) - It would be better if the DefIds were consistent
1063 // with the DefPathTable, but for proc-macro crates
1065 let name = self.proc_macros
1067 .unwrap()[index.to_proc_macro_index()].0;
1069 parent: Some(CRATE_DEF_INDEX),
1070 disambiguated_data: DisambiguatedDefPathData {
1071 data: DefPathData::MacroDef(name.as_interned_str()),
1078 // Returns the path leading to the thing with this `id`.
1079 pub fn def_path(&self, id: DefIndex) -> DefPath {
1080 debug!("def_path(id={:?})", id);
1081 DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1085 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1086 self.def_path_table.def_path_hash(index)
1089 /// Imports the codemap from an external crate into the codemap of the crate
1090 /// currently being compiled (the "local crate").
1092 /// The import algorithm works analogous to how AST items are inlined from an
1093 /// external crate's metadata:
1094 /// For every FileMap in the external codemap an 'inline' copy is created in the
1095 /// local codemap. The correspondence relation between external and local
1096 /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
1097 /// function. When an item from an external crate is later inlined into this
1098 /// crate, this correspondence information is used to translate the span
1099 /// information of the inlined item so that it refers the correct positions in
1100 /// the local codemap (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1102 /// The import algorithm in the function below will reuse FileMaps already
1103 /// existing in the local codemap. For example, even if the FileMap of some
1104 /// source file of libstd gets imported many times, there will only ever be
1105 /// one FileMap object for the corresponding file in the local codemap.
1107 /// Note that imported FileMaps do not actually contain the source code of the
1108 /// file they represent, just information about length, line breaks, and
1109 /// multibyte characters. This information is enough to generate valid debuginfo
1110 /// for items inlined from other crates.
1111 pub fn imported_filemaps(&'a self,
1112 local_codemap: &codemap::CodeMap)
1113 -> ReadGuard<'a, Vec<cstore::ImportedFileMap>> {
1115 let filemaps = self.codemap_import_info.borrow();
1116 if !filemaps.is_empty() {
1121 // Lock the codemap_import_info to ensure this only happens once
1122 let mut codemap_import_info = self.codemap_import_info.borrow_mut();
1124 if !codemap_import_info.is_empty() {
1125 drop(codemap_import_info);
1126 return self.codemap_import_info.borrow();
1129 let external_codemap = self.root.codemap.decode(self);
1131 let imported_filemaps = external_codemap.map(|filemap_to_import| {
1132 // We can't reuse an existing FileMap, so allocate a new one
1133 // containing the information we need.
1134 let syntax_pos::FileMap { name,
1140 mut multibyte_chars,
1141 mut non_narrow_chars,
1143 .. } = filemap_to_import;
1145 let source_length = (end_pos - start_pos).to_usize();
1147 // Translate line-start positions and multibyte character
1148 // position into frame of reference local to file.
1149 // `CodeMap::new_imported_filemap()` will then translate those
1150 // coordinates to their new global frame of reference when the
1151 // offset of the FileMap is known.
1152 for pos in &mut lines {
1153 *pos = *pos - start_pos;
1155 for mbc in &mut multibyte_chars {
1156 mbc.pos = mbc.pos - start_pos;
1158 for swc in &mut non_narrow_chars {
1159 *swc = *swc - start_pos;
1162 let local_version = local_codemap.new_imported_filemap(name,
1171 debug!("CrateMetaData::imported_filemaps alloc \
1172 filemap {:?} original (start_pos {:?} end_pos {:?}) \
1173 translated (start_pos {:?} end_pos {:?})",
1174 local_version.name, start_pos, end_pos,
1175 local_version.start_pos, local_version.end_pos);
1177 cstore::ImportedFileMap {
1178 original_start_pos: start_pos,
1179 original_end_pos: end_pos,
1180 translated_filemap: local_version,
1184 *codemap_import_info = imported_filemaps;
1185 drop(codemap_import_info);
1187 // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1188 self.codemap_import_info.borrow()