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 all the stability attributes in the given crate.
649 pub fn get_lib_features(&self) -> Vec<(ast::Name, Option<ast::Name>)> {
656 /// Iterates over the language items in the given crate.
657 pub fn get_lang_items(&self) -> Vec<(DefId, usize)> {
661 .map(|(def_index, index)| (self.local_def_id(def_index), index))
665 /// Iterates over each child of the given item.
666 pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
667 where F: FnMut(def::Export)
669 if let Some(ref proc_macros) = self.proc_macros {
670 if id == CRATE_DEF_INDEX {
671 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
672 let def = Def::Macro(
675 index: DefIndex::from_proc_macro_index(id),
679 let ident = Ident::with_empty_ctxt(name);
680 callback(def::Export {
683 vis: ty::Visibility::Public,
692 let item = match self.maybe_entry(id) {
694 Some(item) => item.decode((self, sess)),
697 // Iterate over all children.
698 let macros_only = self.dep_kind.lock().macros_only();
699 for child_index in item.children.decode((self, sess)) {
705 if let Some(child) = self.maybe_entry(child_index) {
706 let child = child.decode((self, sess));
708 EntryKind::MacroDef(..) => {}
709 _ if macros_only => continue,
713 // Hand off the item to the callback.
715 // FIXME(eddyb) Don't encode these in children.
716 EntryKind::ForeignMod => {
717 for child_index in child.children.decode((self, sess)) {
718 if let Some(def) = self.get_def(child_index) {
719 callback(def::Export {
721 ident: Ident::from_interned_str(self.item_name(child_index)),
722 vis: self.get_visibility(child_index),
723 span: self.entry(child_index).span.decode((self, sess)),
729 EntryKind::Impl(_) => continue,
734 let def_key = self.def_key(child_index);
735 let span = child.span.decode((self, sess));
736 if let (Some(def), Some(name)) =
737 (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
738 let ident = Ident::from_interned_str(name);
739 let vis = self.get_visibility(child_index);
740 callback(def::Export { def, ident, vis, span });
741 // For non-re-export structs and variants add their constructors to children.
742 // Re-export lists automatically contain constructors when necessary.
745 if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
746 let ctor_kind = self.get_ctor_kind(child_index);
747 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
748 callback(def::Export {
750 vis: self.get_visibility(ctor_def_id.index),
755 Def::Variant(def_id) => {
756 // Braced variants, unlike structs, generate unusable names in
757 // value namespace, they are reserved for possible future use.
758 let ctor_kind = self.get_ctor_kind(child_index);
759 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
760 let vis = self.get_visibility(child_index);
761 callback(def::Export { def: ctor_def, ident, vis, span });
769 if let EntryKind::Mod(data) = item.kind {
770 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
773 _ if macros_only => continue,
781 pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
782 match self.entry(id).kind {
783 EntryKind::AssociatedConst(_, data, _) |
784 EntryKind::Const(data, _) => data.ast_promotable,
789 pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
790 !self.is_proc_macro(id) &&
791 self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
794 pub fn maybe_get_optimized_mir(&self,
795 tcx: TyCtxt<'a, 'tcx, 'tcx>,
797 -> Option<Mir<'tcx>> {
798 match self.is_proc_macro(id) {
800 false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
804 pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
805 match self.entry(id).kind {
806 EntryKind::Const(qualif, _) |
807 EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif, _) |
808 EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif, _) => {
815 pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
816 let item = self.entry(id);
817 let def_key = self.def_key(id);
818 let parent = self.local_def_id(def_key.parent.unwrap());
819 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
821 let (kind, container, has_self) = match item.kind {
822 EntryKind::AssociatedConst(container, _, _) => {
823 (ty::AssociatedKind::Const, container, false)
825 EntryKind::Method(data) => {
826 let data = data.decode(self);
827 (ty::AssociatedKind::Method, data.container, data.has_self)
829 EntryKind::AssociatedType(container) => {
830 (ty::AssociatedKind::Type, container, false)
832 _ => bug!("cannot get associated-item of `{:?}`", def_key)
836 ident: Ident::from_interned_str(name),
838 vis: item.visibility.decode(self),
839 defaultness: container.defaultness(),
840 def_id: self.local_def_id(id),
841 container: container.with_def_id(parent),
842 method_has_self_argument: has_self
846 pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
847 self.entry(id).variances.decode(self).collect()
850 pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
851 match self.entry(node_id).kind {
852 EntryKind::Struct(data, _) |
853 EntryKind::Union(data, _) |
854 EntryKind::Variant(data) => data.decode(self).ctor_kind,
855 _ => CtorKind::Fictive,
859 pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
860 match self.entry(node_id).kind {
861 EntryKind::Struct(data, _) => {
862 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
868 pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
869 if self.is_proc_macro(node_id) {
873 // The attributes for a tuple struct are attached to the definition, not the ctor;
874 // we assume that someone passing in a tuple struct ctor is actually wanting to
875 // look at the definition
876 let def_key = self.def_key(node_id);
877 let item_id = if def_key.disambiguated_data.data == DefPathData::StructCtor {
878 def_key.parent.unwrap()
883 let item = self.entry(item_id);
884 Lrc::from(self.get_attributes(&item, sess))
887 pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
891 .map(|index| self.item_name(index).as_symbol())
895 fn get_attributes(&self, item: &Entry<'tcx>, sess: &Session) -> Vec<ast::Attribute> {
897 .decode((self, sess))
899 // Need new unique IDs: old thread-local IDs won't map to new threads.
900 attr.id = attr::mk_attr_id();
906 // Translate a DefId from the current compilation environment to a DefId
907 // for an external crate.
908 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
909 for (local, &global) in self.cnum_map.iter_enumerated() {
910 if global == did.krate {
921 pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
925 .map(|index| self.local_def_id(index))
929 pub fn get_implementations_for_trait(&self,
930 filter: Option<DefId>,
931 result: &mut Vec<DefId>) {
932 // Do a reverse lookup beforehand to avoid touching the crate_num
933 // hash map in the loop below.
934 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
935 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
936 Some(None) => return,
937 None if self.proc_macros.is_some() => return,
941 if let Some(filter) = filter {
942 if let Some(impls) = self.trait_impls
944 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
947 for impls in self.trait_impls.values() {
948 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
953 pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
954 let def_key = self.def_key(id);
955 match def_key.disambiguated_data.data {
956 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
957 // Not an associated item
960 def_key.parent.and_then(|parent_index| {
961 match self.entry(parent_index).kind {
962 EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
969 pub fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
970 self.root.native_libraries.decode((self, sess)).collect()
973 pub fn get_foreign_modules(&self, sess: &Session) -> Vec<ForeignModule> {
974 self.root.foreign_modules.decode((self, sess)).collect()
977 pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> {
979 .dylib_dependency_formats
982 .flat_map(|(i, link)| {
983 let cnum = CrateNum::new(i + 1);
984 link.map(|link| (self.cnum_map[cnum], link))
989 pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> {
996 pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
997 let arg_names = match self.entry(id).kind {
998 EntryKind::Fn(data) |
999 EntryKind::ForeignFn(data) => data.decode(self).arg_names,
1000 EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
1001 _ => LazySeq::empty(),
1003 arg_names.decode(self).collect()
1006 pub fn exported_symbols(&self,
1007 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1008 -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1009 let lazy_seq: LazySeq<(ExportedSymbol<'tcx>, SymbolExportLevel)> =
1010 LazySeq::with_position_and_length(self.root.exported_symbols.position,
1011 self.root.exported_symbols.len);
1012 lazy_seq.decode((self, tcx)).collect()
1015 pub fn get_rendered_const(&self, id: DefIndex) -> String {
1016 match self.entry(id).kind {
1017 EntryKind::Const(_, data) |
1018 EntryKind::AssociatedConst(_, _, data) => data.decode(self).0,
1023 pub fn get_macro(&self, id: DefIndex) -> (InternedString, MacroDef) {
1024 let entry = self.entry(id);
1026 EntryKind::MacroDef(macro_def) => (self.item_name(id), macro_def.decode(self)),
1031 pub fn is_const_fn(&self, id: DefIndex) -> bool {
1032 let constness = match self.entry(id).kind {
1033 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1034 EntryKind::Fn(data) => data.decode(self).constness,
1035 _ => hir::Constness::NotConst,
1037 constness == hir::Constness::Const
1040 pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1041 match self.entry(id).kind {
1042 EntryKind::ForeignImmStatic |
1043 EntryKind::ForeignMutStatic |
1044 EntryKind::ForeignFn(_) => true,
1049 pub fn fn_sig(&self,
1051 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1052 -> ty::PolyFnSig<'tcx> {
1053 let sig = match self.entry(id).kind {
1054 EntryKind::Fn(data) |
1055 EntryKind::ForeignFn(data) => data.decode(self).sig,
1056 EntryKind::Method(data) => data.decode(self).fn_data.sig,
1057 EntryKind::Variant(data) |
1058 EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1059 EntryKind::Closure(data) => data.decode(self).sig,
1062 sig.decode((self, tcx))
1066 pub fn def_key(&self, index: DefIndex) -> DefKey {
1067 if !self.is_proc_macro(index) {
1068 self.def_path_table.def_key(index)
1070 // FIXME(#49271) - It would be better if the DefIds were consistent
1071 // with the DefPathTable, but for proc-macro crates
1073 let name = self.proc_macros
1075 .unwrap()[index.to_proc_macro_index()].0;
1077 parent: Some(CRATE_DEF_INDEX),
1078 disambiguated_data: DisambiguatedDefPathData {
1079 data: DefPathData::MacroDef(name.as_interned_str()),
1086 // Returns the path leading to the thing with this `id`.
1087 pub fn def_path(&self, id: DefIndex) -> DefPath {
1088 debug!("def_path(id={:?})", id);
1089 DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1093 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1094 self.def_path_table.def_path_hash(index)
1097 /// Imports the codemap from an external crate into the codemap of the crate
1098 /// currently being compiled (the "local crate").
1100 /// The import algorithm works analogous to how AST items are inlined from an
1101 /// external crate's metadata:
1102 /// For every FileMap in the external codemap an 'inline' copy is created in the
1103 /// local codemap. The correspondence relation between external and local
1104 /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
1105 /// function. When an item from an external crate is later inlined into this
1106 /// crate, this correspondence information is used to translate the span
1107 /// information of the inlined item so that it refers the correct positions in
1108 /// the local codemap (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1110 /// The import algorithm in the function below will reuse FileMaps already
1111 /// existing in the local codemap. For example, even if the FileMap of some
1112 /// source file of libstd gets imported many times, there will only ever be
1113 /// one FileMap object for the corresponding file in the local codemap.
1115 /// Note that imported FileMaps do not actually contain the source code of the
1116 /// file they represent, just information about length, line breaks, and
1117 /// multibyte characters. This information is enough to generate valid debuginfo
1118 /// for items inlined from other crates.
1119 pub fn imported_filemaps(&'a self,
1120 local_codemap: &codemap::CodeMap)
1121 -> ReadGuard<'a, Vec<cstore::ImportedFileMap>> {
1123 let filemaps = self.codemap_import_info.borrow();
1124 if !filemaps.is_empty() {
1129 // Lock the codemap_import_info to ensure this only happens once
1130 let mut codemap_import_info = self.codemap_import_info.borrow_mut();
1132 if !codemap_import_info.is_empty() {
1133 drop(codemap_import_info);
1134 return self.codemap_import_info.borrow();
1137 let external_codemap = self.root.codemap.decode(self);
1139 let imported_filemaps = external_codemap.map(|filemap_to_import| {
1140 // We can't reuse an existing FileMap, so allocate a new one
1141 // containing the information we need.
1142 let syntax_pos::FileMap { name,
1148 mut multibyte_chars,
1149 mut non_narrow_chars,
1151 .. } = filemap_to_import;
1153 let source_length = (end_pos - start_pos).to_usize();
1155 // Translate line-start positions and multibyte character
1156 // position into frame of reference local to file.
1157 // `CodeMap::new_imported_filemap()` will then translate those
1158 // coordinates to their new global frame of reference when the
1159 // offset of the FileMap is known.
1160 for pos in &mut lines {
1161 *pos = *pos - start_pos;
1163 for mbc in &mut multibyte_chars {
1164 mbc.pos = mbc.pos - start_pos;
1166 for swc in &mut non_narrow_chars {
1167 *swc = *swc - start_pos;
1170 let local_version = local_codemap.new_imported_filemap(name,
1179 debug!("CrateMetaData::imported_filemaps alloc \
1180 filemap {:?} original (start_pos {:?} end_pos {:?}) \
1181 translated (start_pos {:?} end_pos {:?})",
1182 local_version.name, start_pos, end_pos,
1183 local_version.start_pos, local_version.end_pos);
1185 cstore::ImportedFileMap {
1186 original_start_pos: start_pos,
1187 original_end_pos: end_pos,
1188 translated_filemap: local_version,
1192 *codemap_import_info = imported_filemaps;
1193 drop(codemap_import_info);
1195 // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1196 self.codemap_import_info.borrow()