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::dep_graph::{DepGraph, DepNode, GlobalMetaDataKind};
17 use rustc::hir::map::{DefKey, DefPath, DefPathData};
20 use rustc::middle::cstore::LinkagePreference;
21 use rustc::hir::def::{self, Def, CtorKind};
22 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
23 use rustc::middle::lang_items;
24 use rustc::session::Session;
25 use rustc::ty::{self, Ty, TyCtxt};
26 use rustc::ty::subst::Substs;
32 use std::collections::BTreeMap;
39 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
43 use syntax::ext::base::MacroKind;
44 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
46 pub struct DecodeContext<'a, 'tcx: 'a> {
47 opaque: opaque::Decoder<'a>,
48 cdata: Option<&'a CrateMetadata>,
49 sess: Option<&'a Session>,
50 tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
52 // Cache the last used filemap for translating spans as an optimization.
53 last_filemap_index: usize,
55 lazy_state: LazyState,
58 /// Abstract over the various ways one can create metadata decoders.
59 pub trait Metadata<'a, 'tcx>: Copy {
60 fn raw_bytes(self) -> &'a [u8];
61 fn cdata(self) -> Option<&'a CrateMetadata> { None }
62 fn sess(self) -> Option<&'a Session> { None }
63 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { None }
65 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
68 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
70 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
72 last_filemap_index: 0,
73 lazy_state: LazyState::NoNode,
78 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
79 fn raw_bytes(self) -> &'a [u8] {
84 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
85 fn raw_bytes(self) -> &'a [u8] {
88 fn cdata(self) -> Option<&'a CrateMetadata> {
93 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
94 fn raw_bytes(self) -> &'a [u8] {
97 fn cdata(self) -> Option<&'a CrateMetadata> {
100 fn sess(self) -> Option<&'a Session> {
105 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
106 fn raw_bytes(self) -> &'a [u8] {
109 fn cdata(self) -> Option<&'a CrateMetadata> {
112 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
117 impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
118 pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
119 let mut dcx = meta.decoder(self.position);
120 dcx.lazy_state = LazyState::NodeStart(self.position);
121 T::decode(&mut dcx).unwrap()
125 impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
126 pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> impl Iterator<Item = T> + 'a {
127 let mut dcx = meta.decoder(self.position);
128 dcx.lazy_state = LazyState::NodeStart(self.position);
129 (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
133 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
134 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
135 self.tcx.expect("missing TyCtxt in DecodeContext")
138 pub fn cdata(&self) -> &'a CrateMetadata {
139 self.cdata.expect("missing CrateMetadata in DecodeContext")
142 fn with_position<F: FnOnce(&mut Self) -> R, R>(&mut self, pos: usize, f: F) -> R {
143 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
144 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
145 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
147 self.opaque = old_opaque;
148 self.lazy_state = old_state;
152 fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
153 let distance = self.read_usize()?;
154 let position = match self.lazy_state {
155 LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
156 LazyState::NodeStart(start) => {
157 assert!(distance + min_size <= start);
158 start - distance - min_size
160 LazyState::Previous(last_min_end) => last_min_end + distance,
162 self.lazy_state = LazyState::Previous(position + min_size);
167 macro_rules! decoder_methods {
168 ($($name:ident -> $ty:ty;)*) => {
169 $(fn $name(&mut self) -> Result<$ty, Self::Error> {
175 impl<'doc, 'tcx> Decoder for DecodeContext<'doc, 'tcx> {
176 type Error = <opaque::Decoder<'doc> as Decoder>::Error;
199 read_str -> Cow<str>;
202 fn error(&mut self, err: &str) -> Self::Error {
203 self.opaque.error(err)
207 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
208 fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
209 Ok(Lazy::with_position(self.read_lazy_distance(Lazy::<T>::min_size())?))
213 impl<'a, 'tcx, T> SpecializedDecoder<LazySeq<T>> for DecodeContext<'a, 'tcx> {
214 fn specialized_decode(&mut self) -> Result<LazySeq<T>, Self::Error> {
215 let len = self.read_usize()?;
216 let position = if len == 0 {
219 self.read_lazy_distance(LazySeq::<T>::min_size(len))?
221 Ok(LazySeq::with_position_and_length(position, len))
225 impl<'a, 'tcx> SpecializedDecoder<CrateNum> for DecodeContext<'a, 'tcx> {
226 fn specialized_decode(&mut self) -> Result<CrateNum, Self::Error> {
227 let cnum = CrateNum::from_u32(u32::decode(self)?);
228 if cnum == LOCAL_CRATE {
229 Ok(self.cdata().cnum)
231 Ok(self.cdata().cnum_map.borrow()[cnum])
236 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
237 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
238 let lo = BytePos::decode(self)?;
239 let hi = BytePos::decode(self)?;
241 let sess = if let Some(sess) = self.sess {
244 return Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION });
247 let (lo, hi) = if lo > hi {
248 // Currently macro expansion sometimes produces invalid Span values
249 // where lo > hi. In order not to crash the compiler when trying to
250 // translate these values, let's transform them into something we
251 // can handle (and which will produce useful debug locations at
252 // least some of the time).
253 // This workaround is only necessary as long as macro expansion is
254 // not fixed. FIXME(#23480)
260 let imported_filemaps = self.cdata().imported_filemaps(&sess.codemap());
262 // Optimize for the case that most spans within a translated item
263 // originate from the same filemap.
264 let last_filemap = &imported_filemaps[self.last_filemap_index];
266 if lo >= last_filemap.original_start_pos && lo <= last_filemap.original_end_pos &&
267 hi >= last_filemap.original_start_pos &&
268 hi <= last_filemap.original_end_pos {
272 let mut b = imported_filemaps.len();
276 if imported_filemaps[m].original_start_pos > lo {
283 self.last_filemap_index = a;
284 &imported_filemaps[a]
288 let lo = (lo - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
289 let hi = (hi - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
291 Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION })
295 // FIXME(#36588) These impls are horribly unsound as they allow
296 // the caller to pick any lifetime for 'tcx, including 'static,
297 // by using the unspecialized proxies to them.
299 impl<'a, 'tcx> SpecializedDecoder<Ty<'tcx>> for DecodeContext<'a, 'tcx> {
300 fn specialized_decode(&mut self) -> Result<Ty<'tcx>, Self::Error> {
301 let tcx = self.tcx();
303 // Handle shorthands first, if we have an usize > 0x80.
304 if self.opaque.data[self.opaque.position()] & 0x80 != 0 {
305 let pos = self.read_usize()?;
306 assert!(pos >= SHORTHAND_OFFSET);
307 let key = ty::CReaderCacheKey {
308 cnum: self.cdata().cnum,
309 pos: pos - SHORTHAND_OFFSET,
311 if let Some(ty) = tcx.rcache.borrow().get(&key).cloned() {
315 let ty = self.with_position(key.pos, Ty::decode)?;
316 tcx.rcache.borrow_mut().insert(key, ty);
319 Ok(tcx.mk_ty(ty::TypeVariants::decode(self)?))
325 impl<'a, 'tcx> SpecializedDecoder<ty::GenericPredicates<'tcx>> for DecodeContext<'a, 'tcx> {
326 fn specialized_decode(&mut self) -> Result<ty::GenericPredicates<'tcx>, Self::Error> {
327 Ok(ty::GenericPredicates {
328 parent: Decodable::decode(self)?,
329 predicates: (0..self.read_usize()?).map(|_| {
330 // Handle shorthands first, if we have an usize > 0x80.
331 if self.opaque.data[self.opaque.position()] & 0x80 != 0 {
332 let pos = self.read_usize()?;
333 assert!(pos >= SHORTHAND_OFFSET);
334 let pos = pos - SHORTHAND_OFFSET;
336 self.with_position(pos, ty::Predicate::decode)
338 ty::Predicate::decode(self)
341 .collect::<Result<Vec<_>, _>>()?,
346 impl<'a, 'tcx> SpecializedDecoder<&'tcx Substs<'tcx>> for DecodeContext<'a, 'tcx> {
347 fn specialized_decode(&mut self) -> Result<&'tcx Substs<'tcx>, Self::Error> {
348 Ok(self.tcx().mk_substs((0..self.read_usize()?).map(|_| Decodable::decode(self)))?)
352 impl<'a, 'tcx> SpecializedDecoder<ty::Region<'tcx>> for DecodeContext<'a, 'tcx> {
353 fn specialized_decode(&mut self) -> Result<ty::Region<'tcx>, Self::Error> {
354 Ok(self.tcx().mk_region(Decodable::decode(self)?))
358 impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Slice<Ty<'tcx>>> for DecodeContext<'a, 'tcx> {
359 fn specialized_decode(&mut self) -> Result<&'tcx ty::Slice<Ty<'tcx>>, Self::Error> {
360 Ok(self.tcx().mk_type_list((0..self.read_usize()?).map(|_| Decodable::decode(self)))?)
364 impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::AdtDef> for DecodeContext<'a, 'tcx> {
365 fn specialized_decode(&mut self) -> Result<&'tcx ty::AdtDef, Self::Error> {
366 let def_id = DefId::decode(self)?;
367 Ok(self.tcx().adt_def(def_id))
371 impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>
372 for DecodeContext<'a, 'tcx> {
373 fn specialized_decode(&mut self)
374 -> Result<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>, Self::Error> {
375 Ok(self.tcx().mk_existential_predicates((0..self.read_usize()?)
376 .map(|_| Decodable::decode(self)))?)
380 impl<'a, 'tcx> MetadataBlob {
381 pub fn is_compatible(&self) -> bool {
382 self.raw_bytes().starts_with(METADATA_HEADER)
385 pub fn get_rustc_version(&self) -> String {
386 Lazy::with_position(METADATA_HEADER.len() + 4).decode(self)
389 pub fn get_root(&self) -> CrateRoot {
390 let slice = self.raw_bytes();
391 let offset = METADATA_HEADER.len();
392 let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
393 ((slice[offset + 2] as u32) << 8) |
394 ((slice[offset + 3] as u32) << 0)) as usize;
395 Lazy::with_position(pos).decode(self)
398 pub fn list_crate_metadata(&self,
399 out: &mut io::Write) -> io::Result<()> {
400 write!(out, "=External Dependencies=\n")?;
401 let root = self.get_root();
402 for (i, dep) in root.crate_deps
406 write!(out, "{} {}-{}\n", i + 1, dep.name, dep.hash)?;
413 impl<'tcx> EntryKind<'tcx> {
414 fn to_def(&self, did: DefId) -> Option<Def> {
416 EntryKind::Const(_) => Def::Const(did),
417 EntryKind::AssociatedConst(..) => Def::AssociatedConst(did),
418 EntryKind::ImmStatic |
419 EntryKind::ForeignImmStatic => Def::Static(did, false),
420 EntryKind::MutStatic |
421 EntryKind::ForeignMutStatic => Def::Static(did, true),
422 EntryKind::Struct(_, _) => Def::Struct(did),
423 EntryKind::Union(_, _) => Def::Union(did),
425 EntryKind::ForeignFn(_) => Def::Fn(did),
426 EntryKind::Method(_) => Def::Method(did),
427 EntryKind::Type => Def::TyAlias(did),
428 EntryKind::AssociatedType(_) => Def::AssociatedTy(did),
429 EntryKind::Mod(_) => Def::Mod(did),
430 EntryKind::Variant(_) => Def::Variant(did),
431 EntryKind::Trait(_) => Def::Trait(did),
432 EntryKind::Enum(..) => Def::Enum(did),
433 EntryKind::MacroDef(_) => Def::Macro(did, MacroKind::Bang),
434 EntryKind::GlobalAsm => Def::GlobalAsm(did),
436 EntryKind::ForeignMod |
438 EntryKind::DefaultImpl(_) |
440 EntryKind::Closure(_) => return None,
445 impl<'a, 'tcx> CrateMetadata {
446 fn is_proc_macro(&self, id: DefIndex) -> bool {
447 self.proc_macros.is_some() && id != CRATE_DEF_INDEX
450 fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
451 assert!(!self.is_proc_macro(item_id));
452 self.root.index.lookup(self.blob.raw_bytes(), item_id)
455 fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
456 match self.maybe_entry(item_id) {
458 bug!("entry: id not found: {:?} in crate {:?} with number {}",
463 Some(d) => d.decode(self),
467 fn local_def_id(&self, index: DefIndex) -> DefId {
474 fn item_name(&self, item_index: DefIndex) -> ast::Name {
475 self.def_key(item_index)
479 .expect("no name in item_name")
482 pub fn get_def(&self, index: DefIndex) -> Option<Def> {
483 if !self.is_proc_macro(index) {
484 self.entry(index).kind.to_def(self.local_def_id(index))
486 let kind = self.proc_macros.as_ref().unwrap()[index.as_usize() - 1].1.kind();
487 Some(Def::Macro(self.local_def_id(index), kind))
491 pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
492 match self.is_proc_macro(index) {
494 false => self.entry(index).span.decode((self, sess)),
498 pub fn get_trait_def(&self, item_id: DefIndex) -> ty::TraitDef {
499 let data = match self.entry(item_id).kind {
500 EntryKind::Trait(data) => data.decode(self),
504 ty::TraitDef::new(self.local_def_id(item_id),
507 data.has_default_impl,
508 self.def_path_table.def_path_hash(item_id))
511 fn get_variant(&self, item: &Entry, index: DefIndex) -> ty::VariantDef {
512 let data = match item.kind {
513 EntryKind::Variant(data) |
514 EntryKind::Struct(data, _) |
515 EntryKind::Union(data, _) => data.decode(self),
520 did: self.local_def_id(data.struct_ctor.unwrap_or(index)),
521 name: self.item_name(index),
522 fields: item.children.decode(self).map(|index| {
523 let f = self.entry(index);
525 did: self.local_def_id(index),
526 name: self.item_name(index),
527 vis: f.visibility.decode(self)
531 ctor_kind: data.ctor_kind,
535 pub fn get_adt_def(&self,
537 tcx: TyCtxt<'a, 'tcx, 'tcx>)
538 -> &'tcx ty::AdtDef {
539 let item = self.entry(item_id);
540 let did = self.local_def_id(item_id);
541 let kind = match item.kind {
542 EntryKind::Enum(_) => ty::AdtKind::Enum,
543 EntryKind::Struct(_, _) => ty::AdtKind::Struct,
544 EntryKind::Union(_, _) => ty::AdtKind::Union,
545 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
547 let variants = if let ty::AdtKind::Enum = kind {
551 self.get_variant(&self.entry(index), index)
555 vec![self.get_variant(&item, item_id)]
557 let (kind, repr) = match item.kind {
558 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
559 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
560 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
561 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
564 tcx.alloc_adt_def(did, kind, variants, repr)
567 pub fn get_predicates(&self,
569 tcx: TyCtxt<'a, 'tcx, 'tcx>)
570 -> ty::GenericPredicates<'tcx> {
571 self.entry(item_id).predicates.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, item_id: DefIndex) -> ty::Generics {
585 self.entry(item_id).generics.unwrap().decode(self)
588 pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
589 self.entry(id).ty.unwrap().decode((self, tcx))
592 pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
593 match self.is_proc_macro(id) {
595 false => self.entry(id).stability.map(|stab| stab.decode(self)),
599 pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
600 match self.is_proc_macro(id) {
602 false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
606 pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
607 match self.is_proc_macro(id) {
608 true => ty::Visibility::Public,
609 false => self.entry(id).visibility.decode(self),
613 fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
614 match self.entry(id).kind {
615 EntryKind::Impl(data) => data.decode(self),
620 pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
621 self.get_impl_data(id).parent_impl
624 pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
625 self.get_impl_data(id).polarity
628 pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
629 self.get_impl_data(id).defaultness
632 pub fn get_coerce_unsized_info(&self,
634 -> Option<ty::adjustment::CoerceUnsizedInfo> {
635 self.get_impl_data(id).coerce_unsized_info
638 pub fn get_impl_trait(&self,
640 tcx: TyCtxt<'a, 'tcx, 'tcx>)
641 -> Option<ty::TraitRef<'tcx>> {
642 self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
645 /// Iterates over the language items in the given crate.
646 pub fn get_lang_items(&self, dep_graph: &DepGraph) -> Vec<(DefIndex, usize)> {
647 let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItems);
650 .get(dep_graph, dep_node)
655 /// Iterates over each child of the given item.
656 pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F)
657 where F: FnMut(def::Export)
659 if let Some(ref proc_macros) = self.proc_macros {
660 if id == CRATE_DEF_INDEX {
661 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
662 let def = Def::Macro(
665 index: DefIndex::new(id + 1)
669 callback(def::Export { name: name, def: def, span: DUMMY_SP });
676 let item = match self.maybe_entry(id) {
678 Some(item) => item.decode(self),
681 // Iterate over all children.
682 let macros_only = self.dep_kind.get().macros_only();
683 for child_index in item.children.decode(self) {
689 if let Some(child) = self.maybe_entry(child_index) {
690 let child = child.decode(self);
692 EntryKind::MacroDef(..) => {}
693 _ if macros_only => continue,
697 // Hand off the item to the callback.
699 // FIXME(eddyb) Don't encode these in children.
700 EntryKind::ForeignMod => {
701 for child_index in child.children.decode(self) {
702 if let Some(def) = self.get_def(child_index) {
703 callback(def::Export {
705 name: self.item_name(child_index),
706 span: self.entry(child_index).span.decode(self),
713 EntryKind::DefaultImpl(_) => continue,
718 let def_key = self.def_key(child_index);
719 let span = child.span.decode(self);
720 if let (Some(def), Some(name)) =
721 (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
722 callback(def::Export { def: def, name: name, span: span });
723 // For non-reexport structs and variants add their constructors to children.
724 // Reexport lists automatically contain constructors when necessary.
727 if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
728 let ctor_kind = self.get_ctor_kind(child_index);
729 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
730 callback(def::Export { def: ctor_def, name: name, span: span });
733 Def::Variant(def_id) => {
734 // Braced variants, unlike structs, generate unusable names in
735 // value namespace, they are reserved for possible future use.
736 let ctor_kind = self.get_ctor_kind(child_index);
737 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
738 callback(def::Export { def: ctor_def, name: name, span: span });
746 if let EntryKind::Mod(data) = item.kind {
747 for exp in data.decode(self).reexports.decode(self) {
750 _ if macros_only => continue,
758 pub fn item_body(&self,
759 tcx: TyCtxt<'a, 'tcx, 'tcx>,
762 assert!(!self.is_proc_macro(id));
763 let ast = self.entry(id).ast.unwrap();
764 let def_id = self.local_def_id(id);
765 let body = ast.decode(self).body.decode(self);
766 tcx.hir.intern_inlined_body(def_id, body)
769 pub fn item_body_tables(&self,
771 tcx: TyCtxt<'a, 'tcx, 'tcx>)
772 -> &'tcx ty::TypeckTables<'tcx> {
773 let ast = self.entry(id).ast.unwrap().decode(self);
774 tcx.alloc_tables(ast.tables.decode((self, tcx)))
777 pub fn item_body_nested_bodies(&self, id: DefIndex) -> BTreeMap<hir::BodyId, hir::Body> {
778 self.entry(id).ast.into_iter().flat_map(|ast| {
779 ast.decode(self).nested_bodies.decode(self).map(|body| (body.id(), body))
783 pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
784 self.entry(id).ast.expect("const item missing `ast`")
785 .decode(self).rvalue_promotable_to_static
788 pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
789 !self.is_proc_macro(id) &&
790 self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
793 pub fn maybe_get_optimized_mir(&self,
794 tcx: TyCtxt<'a, 'tcx, 'tcx>,
796 -> Option<Mir<'tcx>> {
797 match self.is_proc_macro(id) {
799 false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
803 pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
804 match self.entry(id).kind {
805 EntryKind::Const(qualif) |
806 EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif) |
807 EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif) => {
814 pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
815 let item = self.entry(id);
816 let def_key = self.def_key(id);
817 let parent = self.local_def_id(def_key.parent.unwrap());
818 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
820 let (kind, container, has_self) = match item.kind {
821 EntryKind::AssociatedConst(container, _) => {
822 (ty::AssociatedKind::Const, container, false)
824 EntryKind::Method(data) => {
825 let data = data.decode(self);
826 (ty::AssociatedKind::Method, data.container, data.has_self)
828 EntryKind::AssociatedType(container) => {
829 (ty::AssociatedKind::Type, container, false)
831 _ => bug!("cannot get associated-item of `{:?}`", def_key)
837 vis: item.visibility.decode(self),
838 defaultness: container.defaultness(),
839 def_id: self.local_def_id(id),
840 container: container.with_def_id(parent),
841 method_has_self_argument: has_self
845 pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
846 self.entry(id).variances.decode(self).collect()
849 pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
850 match self.entry(node_id).kind {
851 EntryKind::Struct(data, _) |
852 EntryKind::Union(data, _) |
853 EntryKind::Variant(data) => data.decode(self).ctor_kind,
854 _ => CtorKind::Fictive,
858 pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
859 match self.entry(node_id).kind {
860 EntryKind::Struct(data, _) => {
861 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
867 pub fn get_item_attrs(&self,
869 dep_graph: &DepGraph) -> Rc<[ast::Attribute]> {
870 let (node_as, node_index) =
871 (node_id.address_space().index(), node_id.as_array_index());
872 if self.is_proc_macro(node_id) {
876 dep_graph.read(DepNode::MetaData(self.local_def_id(node_id)));
878 if let Some(&Some(ref val)) =
879 self.attribute_cache.borrow()[node_as].get(node_index) {
883 // The attributes for a tuple struct are attached to the definition, not the ctor;
884 // we assume that someone passing in a tuple struct ctor is actually wanting to
885 // look at the definition
886 let mut item = self.entry(node_id);
887 let def_key = self.def_key(node_id);
888 if def_key.disambiguated_data.data == DefPathData::StructCtor {
889 item = self.entry(def_key.parent.unwrap());
891 let result = Rc::__from_array(self.get_attributes(&item).into_boxed_slice());
892 let vec_ = &mut self.attribute_cache.borrow_mut()[node_as];
893 if vec_.len() < node_index + 1 {
894 vec_.resize(node_index + 1, None);
896 vec_[node_index] = Some(result.clone());
900 pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
904 .map(|index| self.item_name(index))
908 fn get_attributes(&self, item: &Entry<'tcx>) -> Vec<ast::Attribute> {
912 // Need new unique IDs: old thread-local IDs won't map to new threads.
913 attr.id = attr::mk_attr_id();
919 // Translate a DefId from the current compilation environment to a DefId
920 // for an external crate.
921 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
922 for (local, &global) in self.cnum_map.borrow().iter_enumerated() {
923 if global == did.krate {
934 pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
938 .map(|index| self.local_def_id(index))
942 pub fn get_implementations_for_trait(&self,
943 filter: Option<DefId>,
944 dep_graph: &DepGraph,
945 result: &mut Vec<DefId>) {
946 // Do a reverse lookup beforehand to avoid touching the crate_num
947 // hash map in the loop below.
948 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
949 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
950 Some(None) => return,
951 None if self.proc_macros.is_some() => return,
955 let dep_node = self.metadata_dep_node(GlobalMetaDataKind::Impls);
957 if let Some(filter) = filter {
958 if let Some(impls) = self.trait_impls
959 .get(dep_graph, dep_node)
961 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
964 for impls in self.trait_impls.get(dep_graph, dep_node).values() {
965 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
970 pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
971 self.def_key(id).parent.and_then(|parent_index| {
972 match self.entry(parent_index).kind {
973 EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
980 pub fn get_native_libraries(&self,
981 dep_graph: &DepGraph)
982 -> Vec<NativeLibrary> {
983 let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries);
986 .get(dep_graph, dep_node)
991 pub fn get_dylib_dependency_formats(&self,
992 dep_graph: &DepGraph)
993 -> Vec<(CrateNum, LinkagePreference)> {
996 index: CRATE_DEF_INDEX,
998 let dep_node = DepNode::GlobalMetaData(def_id,
999 GlobalMetaDataKind::DylibDependencyFormats);
1001 .dylib_dependency_formats
1002 .get(dep_graph, dep_node)
1005 .flat_map(|(i, link)| {
1006 let cnum = CrateNum::new(i + 1);
1007 link.map(|link| (self.cnum_map.borrow()[cnum], link))
1012 pub fn get_missing_lang_items(&self, dep_graph: &DepGraph) -> Vec<lang_items::LangItem> {
1013 let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItemsMissing);
1016 .get(dep_graph, dep_node)
1021 pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
1022 let arg_names = match self.entry(id).kind {
1023 EntryKind::Fn(data) |
1024 EntryKind::ForeignFn(data) => data.decode(self).arg_names,
1025 EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
1026 _ => LazySeq::empty(),
1028 arg_names.decode(self).collect()
1031 pub fn get_exported_symbols(&self, dep_graph: &DepGraph) -> Vec<DefId> {
1032 let dep_node = self.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols);
1033 self.exported_symbols
1034 .get(dep_graph, dep_node)
1036 .map(|&index| self.local_def_id(index))
1040 pub fn get_macro(&self, id: DefIndex) -> (ast::Name, MacroDef) {
1041 let entry = self.entry(id);
1043 EntryKind::MacroDef(macro_def) => (self.item_name(id), macro_def.decode(self)),
1048 pub fn is_const_fn(&self, id: DefIndex) -> bool {
1049 let constness = match self.entry(id).kind {
1050 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1051 EntryKind::Fn(data) => data.decode(self).constness,
1052 _ => hir::Constness::NotConst,
1054 constness == hir::Constness::Const
1057 pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1058 match self.entry(id).kind {
1059 EntryKind::ForeignImmStatic |
1060 EntryKind::ForeignMutStatic |
1061 EntryKind::ForeignFn(_) => true,
1066 pub fn is_dllimport_foreign_item(&self, id: DefIndex, dep_graph: &DepGraph) -> bool {
1067 let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries);
1068 self.dllimport_foreign_items
1069 .get(dep_graph, dep_node)
1073 pub fn is_default_impl(&self, impl_id: DefIndex) -> bool {
1074 match self.entry(impl_id).kind {
1075 EntryKind::DefaultImpl(_) => true,
1080 pub fn closure_kind(&self, closure_id: DefIndex) -> ty::ClosureKind {
1081 match self.entry(closure_id).kind {
1082 EntryKind::Closure(data) => data.decode(self).kind,
1087 pub fn closure_ty(&self,
1088 closure_id: DefIndex,
1089 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1090 -> ty::PolyFnSig<'tcx> {
1091 match self.entry(closure_id).kind {
1092 EntryKind::Closure(data) => data.decode(self).ty.decode((self, tcx)),
1098 pub fn def_key(&self, index: DefIndex) -> DefKey {
1099 self.def_path_table.def_key(index)
1102 // Returns the path leading to the thing with this `id`.
1103 pub fn def_path(&self, id: DefIndex) -> DefPath {
1104 debug!("def_path(id={:?})", id);
1105 DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1109 pub fn def_path_hash(&self, index: DefIndex) -> u64 {
1110 self.def_path_table.def_path_hash(index)
1113 /// Imports the codemap from an external crate into the codemap of the crate
1114 /// currently being compiled (the "local crate").
1116 /// The import algorithm works analogous to how AST items are inlined from an
1117 /// external crate's metadata:
1118 /// For every FileMap in the external codemap an 'inline' copy is created in the
1119 /// local codemap. The correspondence relation between external and local
1120 /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
1121 /// function. When an item from an external crate is later inlined into this
1122 /// crate, this correspondence information is used to translate the span
1123 /// information of the inlined item so that it refers the correct positions in
1124 /// the local codemap (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1126 /// The import algorithm in the function below will reuse FileMaps already
1127 /// existing in the local codemap. For example, even if the FileMap of some
1128 /// source file of libstd gets imported many times, there will only ever be
1129 /// one FileMap object for the corresponding file in the local codemap.
1131 /// Note that imported FileMaps do not actually contain the source code of the
1132 /// file they represent, just information about length, line breaks, and
1133 /// multibyte characters. This information is enough to generate valid debuginfo
1134 /// for items inlined from other crates.
1135 pub fn imported_filemaps(&'a self,
1136 local_codemap: &codemap::CodeMap)
1137 -> Ref<'a, Vec<cstore::ImportedFileMap>> {
1139 let filemaps = self.codemap_import_info.borrow();
1140 if !filemaps.is_empty() {
1145 let external_codemap = self.root.codemap.decode(self);
1147 let imported_filemaps = external_codemap.map(|filemap_to_import| {
1148 // We can't reuse an existing FileMap, so allocate a new one
1149 // containing the information we need.
1150 let syntax_pos::FileMap { name,
1156 .. } = filemap_to_import;
1158 let source_length = (end_pos - start_pos).to_usize();
1160 // Translate line-start positions and multibyte character
1161 // position into frame of reference local to file.
1162 // `CodeMap::new_imported_filemap()` will then translate those
1163 // coordinates to their new global frame of reference when the
1164 // offset of the FileMap is known.
1165 let mut lines = lines.into_inner();
1166 for pos in &mut lines {
1167 *pos = *pos - start_pos;
1169 let mut multibyte_chars = multibyte_chars.into_inner();
1170 for mbc in &mut multibyte_chars {
1171 mbc.pos = mbc.pos - start_pos;
1174 let local_version = local_codemap.new_imported_filemap(name,
1180 debug!("CrateMetaData::imported_filemaps alloc \
1181 filemap {:?} original (start_pos {:?} end_pos {:?}) \
1182 translated (start_pos {:?} end_pos {:?})",
1183 local_version.name, start_pos, end_pos,
1184 local_version.start_pos, local_version.end_pos);
1186 cstore::ImportedFileMap {
1187 original_start_pos: start_pos,
1188 original_end_pos: end_pos,
1189 translated_filemap: local_version,
1193 // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1194 *self.codemap_import_info.borrow_mut() = imported_filemaps;
1195 self.codemap_import_info.borrow()
1198 pub fn metadata_dep_node(&self, kind: GlobalMetaDataKind) -> DepNode<DefId> {
1199 let def_id = DefId {
1201 index: CRATE_DEF_INDEX,
1204 DepNode::GlobalMetaData(def_id, kind)