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};
16 use rustc_data_structures::sync::Lrc;
17 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash};
19 use rustc::middle::cstore::{LinkagePreference, ExternConstBody,
20 ExternBodyNestedBodies};
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};
25 use rustc::ich::Fingerprint;
26 use rustc::middle::lang_items;
27 use rustc::mir::{self, interpret};
28 use rustc::session::Session;
29 use rustc::ty::{self, Ty, TyCtxt};
30 use rustc::ty::codec::TyDecoder;
32 use rustc::util::nodemap::FxHashMap;
35 use std::collections::BTreeMap;
40 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
42 use syntax::ast::{self, Ident};
44 use syntax::symbol::{InternedString, Symbol};
45 use syntax::ext::base::MacroKind;
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 filemap for translating spans as an optimization.
55 last_filemap_index: usize,
57 lazy_state: LazyState,
59 // interpreter allocation cache
60 interpret_alloc_cache: FxHashMap<usize, interpret::AllocId>,
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_filemap_index: 0,
78 lazy_state: LazyState::NoNode,
79 interpret_alloc_cache: FxHashMap::default(),
84 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
85 fn raw_bytes(self) -> &'a [u8] {
91 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'a Session) {
92 fn raw_bytes(self) -> &'a [u8] {
97 fn sess(self) -> Option<&'a Session> {
104 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
105 fn raw_bytes(self) -> &'a [u8] {
106 self.blob.raw_bytes()
108 fn cdata(self) -> Option<&'a CrateMetadata> {
113 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
114 fn raw_bytes(self) -> &'a [u8] {
117 fn cdata(self) -> Option<&'a CrateMetadata> {
120 fn sess(self) -> Option<&'a Session> {
125 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
126 fn raw_bytes(self) -> &'a [u8] {
129 fn cdata(self) -> Option<&'a CrateMetadata> {
132 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
137 impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
138 pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
139 let mut dcx = meta.decoder(self.position);
140 dcx.lazy_state = LazyState::NodeStart(self.position);
141 T::decode(&mut dcx).unwrap()
145 impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
146 pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> impl Iterator<Item = T> + 'a {
147 let mut dcx = meta.decoder(self.position);
148 dcx.lazy_state = LazyState::NodeStart(self.position);
149 (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
153 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
154 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
155 self.tcx.expect("missing TyCtxt in DecodeContext")
158 pub fn cdata(&self) -> &'a CrateMetadata {
159 self.cdata.expect("missing CrateMetadata in DecodeContext")
162 fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
163 let distance = self.read_usize()?;
164 let position = match self.lazy_state {
165 LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
166 LazyState::NodeStart(start) => {
167 assert!(distance + min_size <= start);
168 start - distance - min_size
170 LazyState::Previous(last_min_end) => last_min_end + distance,
172 self.lazy_state = LazyState::Previous(position + min_size);
177 impl<'a, 'tcx: 'a> TyDecoder<'a, 'tcx> for DecodeContext<'a, 'tcx> {
180 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
181 self.tcx.expect("missing TyCtxt in DecodeContext")
185 fn peek_byte(&self) -> u8 {
186 self.opaque.data[self.opaque.position()]
190 fn position(&self) -> usize {
191 self.opaque.position()
194 fn cached_ty_for_shorthand<F>(&mut self,
197 -> Result<Ty<'tcx>, Self::Error>
198 where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>
200 let tcx = self.tcx();
202 let key = ty::CReaderCacheKey {
203 cnum: self.cdata().cnum,
207 if let Some(&ty) = tcx.rcache.borrow().get(&key) {
211 let ty = or_insert_with(self)?;
212 tcx.rcache.borrow_mut().insert(key, ty);
216 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
217 where F: FnOnce(&mut Self) -> R
219 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
220 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
221 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
223 self.opaque = old_opaque;
224 self.lazy_state = old_state;
228 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
229 if cnum == LOCAL_CRATE {
232 self.cdata().cnum_map.borrow()[cnum]
237 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
238 fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
239 Ok(Lazy::with_position(self.read_lazy_distance(Lazy::<T>::min_size())?))
243 impl<'a, 'tcx, T> SpecializedDecoder<LazySeq<T>> for DecodeContext<'a, 'tcx> {
244 fn specialized_decode(&mut self) -> Result<LazySeq<T>, Self::Error> {
245 let len = self.read_usize()?;
246 let position = if len == 0 {
249 self.read_lazy_distance(LazySeq::<T>::min_size(len))?
251 Ok(LazySeq::with_position_and_length(position, len))
256 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
258 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
259 let krate = CrateNum::decode(self)?;
260 let index = DefIndex::decode(self)?;
269 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
271 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
272 Ok(DefIndex::from_raw_u32(self.read_u32()?))
276 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
277 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
278 const MAX1: usize = usize::max_value() - 1;
280 let interpret_interner = || tcx.unwrap().interpret_interner.borrow_mut();
281 let pos = self.position();
282 match usize::decode(self)? {
283 ::std::usize::MAX => {
284 let alloc_id = interpret_interner().reserve();
285 trace!("creating alloc id {:?} at {}", alloc_id, pos);
286 // insert early to allow recursive allocs
287 self.interpret_alloc_cache.insert(pos, alloc_id);
289 let allocation = interpret::Allocation::decode(self)?;
290 trace!("decoded alloc {:?} {:#?}", alloc_id, allocation);
291 let allocation = self.tcx.unwrap().intern_const_alloc(allocation);
292 interpret_interner().intern_at_reserved(alloc_id, allocation);
294 let num = usize::decode(self)?;
296 let glob = interpret::GlobalId::decode(self)?;
297 interpret_interner().cache(glob, alloc_id);
303 trace!("creating fn alloc id at {}", pos);
304 let instance = ty::Instance::decode(self)?;
305 trace!("decoded fn alloc instance: {:?}", instance);
306 let id = interpret_interner().create_fn_alloc(instance);
307 trace!("created fn alloc id: {:?}", id);
308 self.interpret_alloc_cache.insert(pos, id);
312 trace!("loading shorthand {}", shorthand);
313 if let Some(&alloc_id) = self.interpret_alloc_cache.get(&shorthand) {
316 trace!("shorthand {} not cached, loading entire allocation", shorthand);
317 // need to load allocation
318 self.with_position(shorthand, |this| interpret::AllocId::decode(this))
324 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
325 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
326 let tag = u8::decode(self)?;
328 if tag == TAG_INVALID_SPAN {
332 debug_assert_eq!(tag, TAG_VALID_SPAN);
334 let lo = BytePos::decode(self)?;
335 let len = BytePos::decode(self)?;
338 let sess = if let Some(sess) = self.sess {
341 bug!("Cannot decode Span without Session.")
344 let imported_filemaps = self.cdata().imported_filemaps(&sess.codemap());
346 // Optimize for the case that most spans within a translated item
347 // originate from the same filemap.
348 let last_filemap = &imported_filemaps[self.last_filemap_index];
350 if lo >= last_filemap.original_start_pos &&
351 lo <= last_filemap.original_end_pos {
355 let mut b = imported_filemaps.len();
359 if imported_filemaps[m].original_start_pos > lo {
366 self.last_filemap_index = a;
367 &imported_filemaps[a]
371 // Make sure our binary search above is correct.
372 debug_assert!(lo >= filemap.original_start_pos &&
373 lo <= filemap.original_end_pos);
375 // Make sure we correctly filtered out invalid spans during encoding
376 debug_assert!(hi >= filemap.original_start_pos &&
377 hi <= filemap.original_end_pos);
379 let lo = (lo + filemap.translated_filemap.start_pos) - filemap.original_start_pos;
380 let hi = (hi + filemap.translated_filemap.start_pos) - filemap.original_start_pos;
382 Ok(Span::new(lo, hi, NO_EXPANSION))
386 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
387 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
388 Fingerprint::decode_opaque(&mut self.opaque)
392 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
393 for DecodeContext<'a, 'tcx> {
395 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
396 Ok(mir::ClearCrossCrate::Clear)
400 implement_ty_decoder!( DecodeContext<'a, 'tcx> );
402 impl<'a, 'tcx> MetadataBlob {
403 pub fn is_compatible(&self) -> bool {
404 self.raw_bytes().starts_with(METADATA_HEADER)
407 pub fn get_rustc_version(&self) -> String {
408 Lazy::with_position(METADATA_HEADER.len() + 4).decode(self)
411 pub fn get_root(&self) -> CrateRoot {
412 let slice = self.raw_bytes();
413 let offset = METADATA_HEADER.len();
414 let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
415 ((slice[offset + 2] as u32) << 8) |
416 ((slice[offset + 3] as u32) << 0)) as usize;
417 Lazy::with_position(pos).decode(self)
420 pub fn list_crate_metadata(&self,
421 out: &mut io::Write) -> io::Result<()> {
422 write!(out, "=External Dependencies=\n")?;
423 let root = self.get_root();
424 for (i, dep) in root.crate_deps
427 write!(out, "{} {}-{}\n", i + 1, dep.name, dep.hash)?;
434 impl<'tcx> EntryKind<'tcx> {
435 fn to_def(&self, did: DefId) -> Option<Def> {
437 EntryKind::Const(_) => Def::Const(did),
438 EntryKind::AssociatedConst(..) => Def::AssociatedConst(did),
439 EntryKind::ImmStatic |
440 EntryKind::ForeignImmStatic => Def::Static(did, false),
441 EntryKind::MutStatic |
442 EntryKind::ForeignMutStatic => Def::Static(did, true),
443 EntryKind::Struct(_, _) => Def::Struct(did),
444 EntryKind::Union(_, _) => Def::Union(did),
446 EntryKind::ForeignFn(_) => Def::Fn(did),
447 EntryKind::Method(_) => Def::Method(did),
448 EntryKind::Type => Def::TyAlias(did),
449 EntryKind::AssociatedType(_) => Def::AssociatedTy(did),
450 EntryKind::Mod(_) => Def::Mod(did),
451 EntryKind::Variant(_) => Def::Variant(did),
452 EntryKind::Trait(_) => Def::Trait(did),
453 EntryKind::Enum(..) => Def::Enum(did),
454 EntryKind::MacroDef(_) => Def::Macro(did, MacroKind::Bang),
455 EntryKind::GlobalAsm => Def::GlobalAsm(did),
456 EntryKind::ForeignType => Def::TyForeign(did),
458 EntryKind::ForeignMod |
461 EntryKind::Generator(_) |
462 EntryKind::Closure(_) => return None,
467 impl<'a, 'tcx> CrateMetadata {
468 fn is_proc_macro(&self, id: DefIndex) -> bool {
469 self.proc_macros.is_some() && id != CRATE_DEF_INDEX
472 fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
473 assert!(!self.is_proc_macro(item_id));
474 self.root.index.lookup(self.blob.raw_bytes(), item_id)
477 fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
478 match self.maybe_entry(item_id) {
480 bug!("entry: id not found: {:?} in crate {:?} with number {}",
485 Some(d) => d.decode(self),
489 fn local_def_id(&self, index: DefIndex) -> DefId {
496 pub fn item_name(&self, item_index: DefIndex) -> InternedString {
497 self.def_key(item_index)
501 .expect("no name in item_name")
504 pub fn get_def(&self, index: DefIndex) -> Option<Def> {
505 if !self.is_proc_macro(index) {
506 self.entry(index).kind.to_def(self.local_def_id(index))
508 let kind = self.proc_macros.as_ref().unwrap()[index.to_proc_macro_index()].1.kind();
509 Some(Def::Macro(self.local_def_id(index), kind))
513 pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
514 match self.is_proc_macro(index) {
516 false => self.entry(index).span.decode((self, sess)),
520 pub fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
521 let data = match self.entry(item_id).kind {
522 EntryKind::Trait(data) => data.decode((self, sess)),
526 ty::TraitDef::new(self.local_def_id(item_id),
530 self.def_path_table.def_path_hash(item_id))
533 fn get_variant(&self, item: &Entry, index: DefIndex) -> ty::VariantDef {
534 let data = match item.kind {
535 EntryKind::Variant(data) |
536 EntryKind::Struct(data, _) |
537 EntryKind::Union(data, _) => data.decode(self),
542 did: self.local_def_id(data.struct_ctor.unwrap_or(index)),
543 name: Symbol::intern(&self.item_name(index)),
544 fields: item.children.decode(self).map(|index| {
545 let f = self.entry(index);
547 did: self.local_def_id(index),
548 name: Symbol::intern(&self.item_name(index)),
549 vis: f.visibility.decode(self)
553 ctor_kind: data.ctor_kind,
557 pub fn get_adt_def(&self,
559 tcx: TyCtxt<'a, 'tcx, 'tcx>)
560 -> &'tcx ty::AdtDef {
561 let item = self.entry(item_id);
562 let did = self.local_def_id(item_id);
563 let kind = match item.kind {
564 EntryKind::Enum(_) => ty::AdtKind::Enum,
565 EntryKind::Struct(_, _) => ty::AdtKind::Struct,
566 EntryKind::Union(_, _) => ty::AdtKind::Union,
567 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
569 let variants = if let ty::AdtKind::Enum = kind {
573 self.get_variant(&self.entry(index), index)
577 vec![self.get_variant(&item, item_id)]
579 let (kind, repr) = match item.kind {
580 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
581 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
582 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
583 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
586 tcx.alloc_adt_def(did, kind, variants, repr)
589 pub fn get_predicates(&self,
591 tcx: TyCtxt<'a, 'tcx, 'tcx>)
592 -> ty::GenericPredicates<'tcx> {
593 self.entry(item_id).predicates.unwrap().decode((self, tcx))
596 pub fn get_super_predicates(&self,
598 tcx: TyCtxt<'a, 'tcx, 'tcx>)
599 -> ty::GenericPredicates<'tcx> {
600 match self.entry(item_id).kind {
601 EntryKind::Trait(data) => data.decode(self).super_predicates.decode((self, tcx)),
606 pub fn get_generics(&self,
610 self.entry(item_id).generics.unwrap().decode((self, sess))
613 pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
614 self.entry(id).ty.unwrap().decode((self, tcx))
617 pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
618 match self.is_proc_macro(id) {
620 false => self.entry(id).stability.map(|stab| stab.decode(self)),
624 pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
625 match self.is_proc_macro(id) {
627 false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
631 pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
632 match self.is_proc_macro(id) {
633 true => ty::Visibility::Public,
634 false => self.entry(id).visibility.decode(self),
638 fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
639 match self.entry(id).kind {
640 EntryKind::Impl(data) => data.decode(self),
645 pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
646 self.get_impl_data(id).parent_impl
649 pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
650 self.get_impl_data(id).polarity
653 pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
654 self.get_impl_data(id).defaultness
657 pub fn get_coerce_unsized_info(&self,
659 -> Option<ty::adjustment::CoerceUnsizedInfo> {
660 self.get_impl_data(id).coerce_unsized_info
663 pub fn get_impl_trait(&self,
665 tcx: TyCtxt<'a, 'tcx, 'tcx>)
666 -> Option<ty::TraitRef<'tcx>> {
667 self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
670 /// Iterates over the language items in the given crate.
671 pub fn get_lang_items(&self) -> Vec<(DefId, usize)> {
675 .map(|(def_index, index)| (self.local_def_id(def_index), index))
679 /// Iterates over each child of the given item.
680 pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
681 where F: FnMut(def::Export)
683 if let Some(ref proc_macros) = self.proc_macros {
684 if id == CRATE_DEF_INDEX {
685 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
686 let def = Def::Macro(
689 index: DefIndex::from_proc_macro_index(id),
693 let ident = Ident::with_empty_ctxt(name);
694 callback(def::Export {
697 vis: ty::Visibility::Public,
707 let item = match self.maybe_entry(id) {
709 Some(item) => item.decode((self, sess)),
712 // Iterate over all children.
713 let macros_only = self.dep_kind.get().macros_only();
714 for child_index in item.children.decode((self, sess)) {
720 if let Some(child) = self.maybe_entry(child_index) {
721 let child = child.decode((self, sess));
723 EntryKind::MacroDef(..) => {}
724 _ if macros_only => continue,
728 // Hand off the item to the callback.
730 // FIXME(eddyb) Don't encode these in children.
731 EntryKind::ForeignMod => {
732 for child_index in child.children.decode((self, sess)) {
733 if let Some(def) = self.get_def(child_index) {
734 callback(def::Export {
736 ident: Ident::from_str(&self.item_name(child_index)),
737 vis: self.get_visibility(child_index),
738 span: self.entry(child_index).span.decode((self, sess)),
745 EntryKind::Impl(_) => continue,
750 let def_key = self.def_key(child_index);
751 let span = child.span.decode((self, sess));
752 if let (Some(def), Some(name)) =
753 (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
754 let ident = Ident::from_str(&name);
755 let vis = self.get_visibility(child_index);
756 let is_import = false;
757 callback(def::Export { def, ident, vis, span, is_import });
758 // For non-re-export structs and variants add their constructors to children.
759 // Re-export lists automatically contain constructors when necessary.
762 if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
763 let ctor_kind = self.get_ctor_kind(child_index);
764 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
765 callback(def::Export {
767 vis: self.get_visibility(ctor_def_id.index),
768 ident, span, is_import,
772 Def::Variant(def_id) => {
773 // Braced variants, unlike structs, generate unusable names in
774 // value namespace, they are reserved for possible future use.
775 let ctor_kind = self.get_ctor_kind(child_index);
776 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
777 let vis = self.get_visibility(child_index);
778 callback(def::Export { def: ctor_def, ident, vis, span, is_import });
786 if let EntryKind::Mod(data) = item.kind {
787 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
790 _ if macros_only => continue,
798 pub fn extern_const_body(&self,
799 tcx: TyCtxt<'a, 'tcx, 'tcx>,
801 -> ExternConstBody<'tcx> {
802 assert!(!self.is_proc_macro(id));
803 let ast = self.entry(id).ast.unwrap();
804 let def_id = self.local_def_id(id);
805 let ast = ast.decode((self, tcx));
806 let body = ast.body.decode((self, tcx));
808 body: tcx.hir.intern_inlined_body(def_id, body),
809 fingerprint: ast.stable_bodies_hash,
813 pub fn item_body_tables(&self,
815 tcx: TyCtxt<'a, 'tcx, 'tcx>)
816 -> &'tcx ty::TypeckTables<'tcx> {
817 let ast = self.entry(id).ast.unwrap().decode(self);
818 tcx.alloc_tables(ast.tables.decode((self, tcx)))
821 pub fn item_body_nested_bodies(&self, id: DefIndex) -> ExternBodyNestedBodies {
822 if let Some(ref ast) = self.entry(id).ast {
823 let ast = ast.decode(self);
824 let nested_bodies: BTreeMap<_, _> = ast.nested_bodies
826 .map(|body| (body.id(), body))
828 ExternBodyNestedBodies {
829 nested_bodies: Lrc::new(nested_bodies),
830 fingerprint: ast.stable_bodies_hash,
833 ExternBodyNestedBodies {
834 nested_bodies: Lrc::new(BTreeMap::new()),
835 fingerprint: Fingerprint::ZERO,
840 pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
841 self.entry(id).ast.expect("const item missing `ast`")
842 .decode(self).rvalue_promotable_to_static
845 pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
846 !self.is_proc_macro(id) &&
847 self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
850 pub fn maybe_get_optimized_mir(&self,
851 tcx: TyCtxt<'a, 'tcx, 'tcx>,
853 -> Option<Mir<'tcx>> {
854 match self.is_proc_macro(id) {
856 false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
860 pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
861 match self.entry(id).kind {
862 EntryKind::Const(qualif) |
863 EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif) |
864 EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif) => {
871 pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
872 let item = self.entry(id);
873 let def_key = self.def_key(id);
874 let parent = self.local_def_id(def_key.parent.unwrap());
875 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
877 let (kind, container, has_self) = match item.kind {
878 EntryKind::AssociatedConst(container, _) => {
879 (ty::AssociatedKind::Const, container, false)
881 EntryKind::Method(data) => {
882 let data = data.decode(self);
883 (ty::AssociatedKind::Method, data.container, data.has_self)
885 EntryKind::AssociatedType(container) => {
886 (ty::AssociatedKind::Type, container, false)
888 _ => bug!("cannot get associated-item of `{:?}`", def_key)
892 name: Symbol::intern(&name),
894 vis: item.visibility.decode(self),
895 defaultness: container.defaultness(),
896 def_id: self.local_def_id(id),
897 container: container.with_def_id(parent),
898 method_has_self_argument: has_self
902 pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
903 self.entry(id).variances.decode(self).collect()
906 pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
907 match self.entry(node_id).kind {
908 EntryKind::Struct(data, _) |
909 EntryKind::Union(data, _) |
910 EntryKind::Variant(data) => data.decode(self).ctor_kind,
911 _ => CtorKind::Fictive,
915 pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
916 match self.entry(node_id).kind {
917 EntryKind::Struct(data, _) => {
918 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
924 pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
925 let (node_as, node_index) =
926 (node_id.address_space().index(), node_id.as_array_index());
927 if self.is_proc_macro(node_id) {
931 if let Some(&Some(ref val)) =
932 self.attribute_cache.borrow()[node_as].get(node_index) {
936 // The attributes for a tuple struct are attached to the definition, not the ctor;
937 // we assume that someone passing in a tuple struct ctor is actually wanting to
938 // look at the definition
939 let mut item = self.entry(node_id);
940 let def_key = self.def_key(node_id);
941 if def_key.disambiguated_data.data == DefPathData::StructCtor {
942 item = self.entry(def_key.parent.unwrap());
944 let result: Lrc<[ast::Attribute]> = Lrc::from(self.get_attributes(&item, sess));
945 let vec_ = &mut self.attribute_cache.borrow_mut()[node_as];
946 if vec_.len() < node_index + 1 {
947 vec_.resize(node_index + 1, None);
949 vec_[node_index] = Some(result.clone());
953 pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
957 .map(|index| Symbol::intern(&self.item_name(index)))
961 fn get_attributes(&self, item: &Entry<'tcx>, sess: &Session) -> Vec<ast::Attribute> {
963 .decode((self, sess))
965 // Need new unique IDs: old thread-local IDs won't map to new threads.
966 attr.id = attr::mk_attr_id();
972 // Translate a DefId from the current compilation environment to a DefId
973 // for an external crate.
974 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
975 for (local, &global) in self.cnum_map.borrow().iter_enumerated() {
976 if global == did.krate {
987 pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
991 .map(|index| self.local_def_id(index))
995 pub fn get_implementations_for_trait(&self,
996 filter: Option<DefId>,
997 result: &mut Vec<DefId>) {
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,
1003 None if self.proc_macros.is_some() => return,
1007 if let Some(filter) = filter {
1008 if let Some(impls) = self.trait_impls
1010 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
1013 for impls in self.trait_impls.values() {
1014 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
1019 pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1020 self.def_key(id).parent.and_then(|parent_index| {
1021 match self.entry(parent_index).kind {
1022 EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
1029 pub fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1030 self.root.native_libraries.decode((self, sess)).collect()
1033 pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> {
1035 .dylib_dependency_formats
1038 .flat_map(|(i, link)| {
1039 let cnum = CrateNum::new(i + 1);
1040 link.map(|link| (self.cnum_map.borrow()[cnum], link))
1045 pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> {
1052 pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
1053 let arg_names = match self.entry(id).kind {
1054 EntryKind::Fn(data) |
1055 EntryKind::ForeignFn(data) => data.decode(self).arg_names,
1056 EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
1057 _ => LazySeq::empty(),
1059 arg_names.decode(self).collect()
1062 pub fn exported_symbols(&self) -> Vec<(ExportedSymbol, SymbolExportLevel)> {
1069 pub fn get_macro(&self, id: DefIndex) -> (InternedString, MacroDef) {
1070 let entry = self.entry(id);
1072 EntryKind::MacroDef(macro_def) => (self.item_name(id), macro_def.decode(self)),
1077 pub fn is_const_fn(&self, id: DefIndex) -> bool {
1078 let constness = match self.entry(id).kind {
1079 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1080 EntryKind::Fn(data) => data.decode(self).constness,
1081 _ => hir::Constness::NotConst,
1083 constness == hir::Constness::Const
1086 pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1087 match self.entry(id).kind {
1088 EntryKind::ForeignImmStatic |
1089 EntryKind::ForeignMutStatic |
1090 EntryKind::ForeignFn(_) => true,
1095 pub fn is_dllimport_foreign_item(&self, id: DefIndex) -> bool {
1096 self.dllimport_foreign_items.contains(&id)
1099 pub fn fn_sig(&self,
1101 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1102 -> ty::PolyFnSig<'tcx> {
1103 let sig = match self.entry(id).kind {
1104 EntryKind::Fn(data) |
1105 EntryKind::ForeignFn(data) => data.decode(self).sig,
1106 EntryKind::Method(data) => data.decode(self).fn_data.sig,
1107 EntryKind::Variant(data) |
1108 EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1109 EntryKind::Closure(data) => data.decode(self).sig,
1112 sig.decode((self, tcx))
1116 pub fn def_key(&self, index: DefIndex) -> DefKey {
1117 self.def_path_table.def_key(index)
1120 // Returns the path leading to the thing with this `id`.
1121 pub fn def_path(&self, id: DefIndex) -> DefPath {
1122 debug!("def_path(id={:?})", id);
1123 DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1127 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1128 self.def_path_table.def_path_hash(index)
1131 /// Imports the codemap from an external crate into the codemap of the crate
1132 /// currently being compiled (the "local crate").
1134 /// The import algorithm works analogous to how AST items are inlined from an
1135 /// external crate's metadata:
1136 /// For every FileMap in the external codemap an 'inline' copy is created in the
1137 /// local codemap. The correspondence relation between external and local
1138 /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
1139 /// function. When an item from an external crate is later inlined into this
1140 /// crate, this correspondence information is used to translate the span
1141 /// information of the inlined item so that it refers the correct positions in
1142 /// the local codemap (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1144 /// The import algorithm in the function below will reuse FileMaps already
1145 /// existing in the local codemap. For example, even if the FileMap of some
1146 /// source file of libstd gets imported many times, there will only ever be
1147 /// one FileMap object for the corresponding file in the local codemap.
1149 /// Note that imported FileMaps do not actually contain the source code of the
1150 /// file they represent, just information about length, line breaks, and
1151 /// multibyte characters. This information is enough to generate valid debuginfo
1152 /// for items inlined from other crates.
1153 pub fn imported_filemaps(&'a self,
1154 local_codemap: &codemap::CodeMap)
1155 -> Ref<'a, Vec<cstore::ImportedFileMap>> {
1157 let filemaps = self.codemap_import_info.borrow();
1158 if !filemaps.is_empty() {
1163 let external_codemap = self.root.codemap.decode(self);
1165 let imported_filemaps = external_codemap.map(|filemap_to_import| {
1166 // We can't reuse an existing FileMap, so allocate a new one
1167 // containing the information we need.
1168 let syntax_pos::FileMap { name,
1177 .. } = filemap_to_import;
1179 let source_length = (end_pos - start_pos).to_usize();
1181 // Translate line-start positions and multibyte character
1182 // position into frame of reference local to file.
1183 // `CodeMap::new_imported_filemap()` will then translate those
1184 // coordinates to their new global frame of reference when the
1185 // offset of the FileMap is known.
1186 let mut lines = lines.into_inner();
1187 for pos in &mut lines {
1188 *pos = *pos - start_pos;
1190 let mut multibyte_chars = multibyte_chars.into_inner();
1191 for mbc in &mut multibyte_chars {
1192 mbc.pos = mbc.pos - start_pos;
1194 let mut non_narrow_chars = non_narrow_chars.into_inner();
1195 for swc in &mut non_narrow_chars {
1196 *swc = *swc - start_pos;
1199 let local_version = local_codemap.new_imported_filemap(name,
1208 debug!("CrateMetaData::imported_filemaps alloc \
1209 filemap {:?} original (start_pos {:?} end_pos {:?}) \
1210 translated (start_pos {:?} end_pos {:?})",
1211 local_version.name, start_pos, end_pos,
1212 local_version.start_pos, local_version.end_pos);
1214 cstore::ImportedFileMap {
1215 original_start_pos: start_pos,
1216 original_end_pos: end_pos,
1217 translated_filemap: local_version,
1221 // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1222 *self.codemap_import_info.borrow_mut() = imported_filemaps;
1223 self.codemap_import_info.borrow()