1 // Decoding metadata from a single crate's metadata
3 use crate::cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary, ForeignModule};
6 use rustc_data_structures::sync::{Lrc, ReadGuard};
7 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash, Definitions};
9 use rustc::middle::cstore::LinkagePreference;
10 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
11 use rustc::hir::def::{self, Res, DefKind, CtorOf, CtorKind};
12 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use rustc::hir::map::definitions::DefPathTable;
14 use rustc_data_structures::fingerprint::Fingerprint;
15 use rustc::middle::lang_items;
16 use rustc::mir::{self, interpret};
17 use rustc::mir::interpret::AllocDecodingSession;
18 use rustc::session::Session;
19 use rustc::ty::{self, Ty, TyCtxt};
20 use rustc::ty::codec::TyDecoder;
22 use rustc::util::captures::Captures;
28 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
30 use syntax::ast::{self, Ident};
31 use syntax::source_map;
32 use syntax::symbol::{Symbol, sym};
33 use syntax::ext::base::{MacroKind, SyntaxExtension};
34 use syntax::ext::hygiene::Mark;
35 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
38 pub struct DecodeContext<'a, 'tcx: 'a> {
39 opaque: opaque::Decoder<'a>,
40 cdata: Option<&'a CrateMetadata>,
41 sess: Option<&'a Session>,
42 tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
44 // Cache the last used source_file for translating spans as an optimization.
45 last_source_file_index: usize,
47 lazy_state: LazyState,
49 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
50 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
53 /// Abstract over the various ways one can create metadata decoders.
54 pub trait Metadata<'a, 'tcx>: Copy {
55 fn raw_bytes(self) -> &'a [u8];
56 fn cdata(self) -> Option<&'a CrateMetadata> { None }
57 fn sess(self) -> Option<&'a Session> { None }
58 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { None }
60 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
63 opaque: opaque::Decoder::new(self.raw_bytes(), pos),
65 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
67 last_source_file_index: 0,
68 lazy_state: LazyState::NoNode,
69 alloc_decoding_session: self.cdata().map(|cdata| {
70 cdata.alloc_decoding_state.new_decoding_session()
76 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
77 fn raw_bytes(self) -> &'a [u8] {
83 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'a Session) {
84 fn raw_bytes(self) -> &'a [u8] {
89 fn sess(self) -> Option<&'a Session> {
96 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
97 fn raw_bytes(self) -> &'a [u8] {
100 fn cdata(self) -> Option<&'a CrateMetadata> {
105 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
106 fn raw_bytes(self) -> &'a [u8] {
109 fn cdata(self) -> Option<&'a CrateMetadata> {
112 fn sess(self) -> Option<&'a Session> {
117 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
118 fn raw_bytes(self) -> &'a [u8] {
121 fn cdata(self) -> Option<&'a CrateMetadata> {
124 fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
129 impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
130 pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
131 let mut dcx = meta.decoder(self.position);
132 dcx.lazy_state = LazyState::NodeStart(self.position);
133 T::decode(&mut dcx).unwrap()
137 impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
138 pub fn decode<M: Metadata<'a, 'tcx>>(
141 ) -> impl Iterator<Item = T> + Captures<'tcx> + 'a {
142 let mut dcx = meta.decoder(self.position);
143 dcx.lazy_state = LazyState::NodeStart(self.position);
144 (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
148 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
149 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
150 self.tcx.expect("missing TyCtxt in DecodeContext")
153 pub fn cdata(&self) -> &'a CrateMetadata {
154 self.cdata.expect("missing CrateMetadata in DecodeContext")
157 fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
158 let distance = self.read_usize()?;
159 let position = match self.lazy_state {
160 LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
161 LazyState::NodeStart(start) => {
162 assert!(distance + min_size <= start);
163 start - distance - min_size
165 LazyState::Previous(last_min_end) => last_min_end + distance,
167 self.lazy_state = LazyState::Previous(position + min_size);
172 impl<'a, 'tcx: 'a> TyDecoder<'a, 'tcx> for DecodeContext<'a, 'tcx> {
175 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
176 self.tcx.expect("missing TyCtxt in DecodeContext")
180 fn peek_byte(&self) -> u8 {
181 self.opaque.data[self.opaque.position()]
185 fn position(&self) -> usize {
186 self.opaque.position()
189 fn cached_ty_for_shorthand<F>(&mut self,
192 -> Result<Ty<'tcx>, Self::Error>
193 where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>
195 let tcx = self.tcx();
197 let key = ty::CReaderCacheKey {
198 cnum: self.cdata().cnum,
202 if let Some(&ty) = tcx.rcache.borrow().get(&key) {
206 let ty = or_insert_with(self)?;
207 tcx.rcache.borrow_mut().insert(key, ty);
211 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
212 where F: FnOnce(&mut Self) -> R
214 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
215 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
216 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
218 self.opaque = old_opaque;
219 self.lazy_state = old_state;
223 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
224 if cnum == LOCAL_CRATE {
227 self.cdata().cnum_map[cnum]
232 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
233 fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
234 Ok(Lazy::with_position(self.read_lazy_distance(Lazy::<T>::min_size())?))
238 impl<'a, 'tcx, T> SpecializedDecoder<LazySeq<T>> for DecodeContext<'a, 'tcx> {
239 fn specialized_decode(&mut self) -> Result<LazySeq<T>, Self::Error> {
240 let len = self.read_usize()?;
241 let position = if len == 0 {
244 self.read_lazy_distance(LazySeq::<T>::min_size(len))?
246 Ok(LazySeq::with_position_and_length(position, len))
251 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
253 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
254 let krate = CrateNum::decode(self)?;
255 let index = DefIndex::decode(self)?;
264 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
266 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
267 Ok(DefIndex::from_u32(self.read_u32()?))
271 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for DecodeContext<'a, 'tcx> {
273 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
274 self.specialized_decode().map(|i| LocalDefId::from_def_id(i))
278 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
279 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
280 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
281 alloc_decoding_session.decode_alloc_id(self)
283 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
288 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
289 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
290 let tag = u8::decode(self)?;
292 if tag == TAG_INVALID_SPAN {
296 debug_assert_eq!(tag, TAG_VALID_SPAN);
298 let lo = BytePos::decode(self)?;
299 let len = BytePos::decode(self)?;
302 let sess = if let Some(sess) = self.sess {
305 bug!("Cannot decode Span without Session.")
308 let imported_source_files = self.cdata().imported_source_files(&sess.source_map());
310 // Optimize for the case that most spans within a translated item
311 // originate from the same source_file.
312 let last_source_file = &imported_source_files[self.last_source_file_index];
314 if lo >= last_source_file.original_start_pos &&
315 lo <= last_source_file.original_end_pos {
319 let mut b = imported_source_files.len();
323 if imported_source_files[m].original_start_pos > lo {
330 self.last_source_file_index = a;
331 &imported_source_files[a]
335 // Make sure our binary search above is correct.
336 debug_assert!(lo >= source_file.original_start_pos &&
337 lo <= source_file.original_end_pos);
339 // Make sure we correctly filtered out invalid spans during encoding
340 debug_assert!(hi >= source_file.original_start_pos &&
341 hi <= source_file.original_end_pos);
343 let lo = (lo + source_file.translated_source_file.start_pos)
344 - source_file.original_start_pos;
345 let hi = (hi + source_file.translated_source_file.start_pos)
346 - source_file.original_start_pos;
348 Ok(Span::new(lo, hi, NO_EXPANSION))
352 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
353 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
354 Fingerprint::decode_opaque(&mut self.opaque)
358 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
359 for DecodeContext<'a, 'tcx> {
361 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
362 Ok(mir::ClearCrossCrate::Clear)
366 implement_ty_decoder!( DecodeContext<'a, 'tcx> );
368 impl<'tcx> MetadataBlob {
369 pub fn is_compatible(&self) -> bool {
370 self.raw_bytes().starts_with(METADATA_HEADER)
373 pub fn get_rustc_version(&self) -> String {
374 Lazy::with_position(METADATA_HEADER.len() + 4).decode(self)
377 pub fn get_root(&self) -> CrateRoot<'tcx> {
378 let slice = self.raw_bytes();
379 let offset = METADATA_HEADER.len();
380 let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
381 ((slice[offset + 2] as u32) << 8) |
382 ((slice[offset + 3] as u32) << 0)) as usize;
383 Lazy::with_position(pos).decode(self)
386 pub fn list_crate_metadata(&self,
387 out: &mut dyn io::Write) -> io::Result<()> {
388 write!(out, "=External Dependencies=\n")?;
389 let root = self.get_root();
390 for (i, dep) in root.crate_deps
393 write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
400 impl<'tcx> EntryKind<'tcx> {
401 fn def_kind(&self) -> Option<DefKind> {
403 EntryKind::Const(..) => DefKind::Const,
404 EntryKind::AssociatedConst(..) => DefKind::AssociatedConst,
405 EntryKind::ImmStatic |
406 EntryKind::MutStatic |
407 EntryKind::ForeignImmStatic |
408 EntryKind::ForeignMutStatic => DefKind::Static,
409 EntryKind::Struct(_, _) => DefKind::Struct,
410 EntryKind::Union(_, _) => DefKind::Union,
412 EntryKind::ForeignFn(_) => DefKind::Fn,
413 EntryKind::Method(_) => DefKind::Method,
414 EntryKind::Type => DefKind::TyAlias,
415 EntryKind::TypeParam => DefKind::TyParam,
416 EntryKind::ConstParam => DefKind::ConstParam,
417 EntryKind::Existential => DefKind::Existential,
418 EntryKind::AssociatedType(_) => DefKind::AssociatedTy,
419 EntryKind::AssociatedExistential(_) => DefKind::AssociatedExistential,
420 EntryKind::Mod(_) => DefKind::Mod,
421 EntryKind::Variant(_) => DefKind::Variant,
422 EntryKind::Trait(_) => DefKind::Trait,
423 EntryKind::TraitAlias(_) => DefKind::TraitAlias,
424 EntryKind::Enum(..) => DefKind::Enum,
425 EntryKind::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
426 EntryKind::ForeignType => DefKind::ForeignTy,
428 EntryKind::ForeignMod |
429 EntryKind::GlobalAsm |
432 EntryKind::Generator(_) |
433 EntryKind::Closure(_) => return None,
438 /// Creates the "fake" DefPathTable for a given proc macro crate.
440 /// The DefPathTable is as follows:
442 /// CRATE_ROOT (DefIndex 0:0)
443 /// |- GlobalMetaDataKind data (DefIndex 1:0 .. DefIndex 1:N)
444 /// |- proc macro #0 (DefIndex 1:N)
445 /// |- proc macro #1 (DefIndex 1:N+1)
447 crate fn proc_macro_def_path_table(crate_root: &CrateRoot<'_>,
448 proc_macros: &[(ast::Name, Lrc<SyntaxExtension>)])
451 let mut definitions = Definitions::default();
453 let name = crate_root.name.as_str();
454 let disambiguator = crate_root.disambiguator;
455 debug!("creating proc macro def path table for {:?}/{:?}", name, disambiguator);
456 let crate_root = definitions.create_root_def(&name, disambiguator);
457 for (index, (name, _)) in proc_macros.iter().enumerate() {
458 let def_index = definitions.create_def_with_parent(
461 DefPathData::MacroNs(name.as_interned_str()),
464 debug!("definition for {:?} is {:?}", name, def_index);
465 assert_eq!(def_index, DefIndex::from_proc_macro_index(index));
468 definitions.def_path_table().clone()
471 impl<'a, 'tcx> CrateMetadata {
472 fn is_proc_macro(&self, id: DefIndex) -> bool {
473 self.proc_macros.is_some() && id != CRATE_DEF_INDEX
476 fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
477 assert!(!self.is_proc_macro(item_id));
478 self.root.entries_index.lookup(self.blob.raw_bytes(), item_id)
481 fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
482 match self.maybe_entry(item_id) {
484 bug!("entry: id not found: {:?} in crate {:?} with number {}",
489 Some(d) => d.decode(self),
493 fn local_def_id(&self, index: DefIndex) -> DefId {
500 pub fn item_name(&self, item_index: DefIndex) -> Symbol {
501 self.def_key(item_index)
505 .expect("no name in item_name")
509 pub fn def_kind(&self, index: DefIndex) -> Option<DefKind> {
510 if !self.is_proc_macro(index) {
511 self.entry(index).kind.def_kind()
513 let kind = self.proc_macros.as_ref().unwrap()[index.to_proc_macro_index()].1.kind();
514 Some(DefKind::Macro(kind))
518 pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
519 match self.is_proc_macro(index) {
521 false => self.entry(index).span.decode((self, sess)),
525 pub fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
526 match self.entry(item_id).kind {
527 EntryKind::Trait(data) => {
528 let data = data.decode((self, sess));
529 ty::TraitDef::new(self.local_def_id(item_id),
534 self.def_path_table.def_path_hash(item_id))
536 EntryKind::TraitAlias(_) => {
537 ty::TraitDef::new(self.local_def_id(item_id),
538 hir::Unsafety::Normal,
542 self.def_path_table.def_path_hash(item_id))
544 _ => bug!("def-index does not refer to trait or trait alias"),
550 tcx: TyCtxt<'a, 'tcx, 'tcx>,
554 adt_kind: ty::AdtKind
555 ) -> ty::VariantDef {
556 let data = match item.kind {
557 EntryKind::Variant(data) |
558 EntryKind::Struct(data, _) |
559 EntryKind::Union(data, _) => data.decode(self),
563 let variant_did = if adt_kind == ty::AdtKind::Enum {
564 Some(self.local_def_id(index))
568 let ctor_did = data.ctor.map(|index| self.local_def_id(index));
572 Ident::with_empty_ctxt(self.item_name(index)),
576 item.children.decode(self).map(|index| {
577 let f = self.entry(index);
579 did: self.local_def_id(index),
580 ident: Ident::with_empty_ctxt(self.item_name(index)),
581 vis: f.visibility.decode(self)
591 pub fn get_adt_def(&self,
593 tcx: TyCtxt<'a, 'tcx, 'tcx>)
594 -> &'tcx ty::AdtDef {
595 let item = self.entry(item_id);
596 let did = self.local_def_id(item_id);
598 let (kind, repr) = match item.kind {
599 EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
600 EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
601 EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
602 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
605 let variants = if let ty::AdtKind::Enum = kind {
609 self.get_variant(tcx, &self.entry(index), index, did, kind)
613 std::iter::once(self.get_variant(tcx, &item, item_id, did, kind)).collect()
616 tcx.alloc_adt_def(did, kind, variants, repr)
619 pub fn get_predicates(&self,
621 tcx: TyCtxt<'a, 'tcx, 'tcx>)
622 -> ty::GenericPredicates<'tcx> {
623 self.entry(item_id).predicates.unwrap().decode((self, tcx))
626 pub fn get_predicates_defined_on(&self,
628 tcx: TyCtxt<'a, 'tcx, 'tcx>)
629 -> ty::GenericPredicates<'tcx> {
630 self.entry(item_id).predicates_defined_on.unwrap().decode((self, tcx))
633 pub fn get_super_predicates(&self,
635 tcx: TyCtxt<'a, 'tcx, 'tcx>)
636 -> ty::GenericPredicates<'tcx> {
637 let super_predicates = match self.entry(item_id).kind {
638 EntryKind::Trait(data) => data.decode(self).super_predicates,
639 EntryKind::TraitAlias(data) => data.decode(self).super_predicates,
640 _ => bug!("def-index does not refer to trait or trait alias"),
643 super_predicates.decode((self, tcx))
646 pub fn get_generics(&self,
650 self.entry(item_id).generics.unwrap().decode((self, sess))
653 pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
654 self.entry(id).ty.unwrap().decode((self, tcx))
657 pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
658 match self.is_proc_macro(id) {
659 true => self.root.proc_macro_stability.clone(),
660 false => self.entry(id).stability.map(|stab| stab.decode(self)),
664 pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
665 match self.is_proc_macro(id) {
667 false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
671 pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
672 match self.is_proc_macro(id) {
673 true => ty::Visibility::Public,
674 false => self.entry(id).visibility.decode(self),
678 fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
679 match self.entry(id).kind {
680 EntryKind::Impl(data) => data.decode(self),
685 pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
686 self.get_impl_data(id).parent_impl
689 pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
690 self.get_impl_data(id).polarity
693 pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
694 self.get_impl_data(id).defaultness
697 pub fn get_coerce_unsized_info(&self,
699 -> Option<ty::adjustment::CoerceUnsizedInfo> {
700 self.get_impl_data(id).coerce_unsized_info
703 pub fn get_impl_trait(&self,
705 tcx: TyCtxt<'a, 'tcx, 'tcx>)
706 -> Option<ty::TraitRef<'tcx>> {
707 self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
710 /// Iterates over all the stability attributes in the given crate.
711 pub fn get_lib_features(&self) -> Vec<(ast::Name, Option<ast::Name>)> {
712 // FIXME: For a proc macro crate, not sure whether we should return the "host"
713 // features or an empty Vec. Both don't cause ICEs.
720 /// Iterates over the language items in the given crate.
721 pub fn get_lang_items(&self) -> Vec<(DefId, usize)> {
722 if self.proc_macros.is_some() {
723 // Proc macro crates do not export any lang-items to the target.
729 .map(|(def_index, index)| (self.local_def_id(def_index), index))
734 /// Iterates over each child of the given item.
735 pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
736 where F: FnMut(def::Export<hir::HirId>)
738 if let Some(ref proc_macros) = self.proc_macros {
739 /* If we are loading as a proc macro, we want to return the view of this crate
740 * as a proc macro crate, not as a Rust crate. See `proc_macro_def_path_table`
741 * for the DefPathTable we are corresponding to.
743 if id == CRATE_DEF_INDEX {
744 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
746 DefKind::Macro(ext.kind()),
747 self.local_def_id(DefIndex::from_proc_macro_index(id)),
749 let ident = Ident::with_empty_ctxt(name);
750 callback(def::Export {
753 vis: ty::Visibility::Public,
762 let item = match self.maybe_entry(id) {
764 Some(item) => item.decode((self, sess)),
767 // Iterate over all children.
768 let macros_only = self.dep_kind.lock().macros_only();
769 for child_index in item.children.decode((self, sess)) {
775 if let Some(child) = self.maybe_entry(child_index) {
776 let child = child.decode((self, sess));
778 EntryKind::MacroDef(..) => {}
779 _ if macros_only => continue,
783 // Hand off the item to the callback.
785 // FIXME(eddyb) Don't encode these in children.
786 EntryKind::ForeignMod => {
787 for child_index in child.children.decode((self, sess)) {
788 if let Some(kind) = self.def_kind(child_index) {
789 callback(def::Export {
790 res: Res::Def(kind, self.local_def_id(child_index)),
791 ident: Ident::with_empty_ctxt(self.item_name(child_index)),
792 vis: self.get_visibility(child_index),
793 span: self.entry(child_index).span.decode((self, sess)),
799 EntryKind::Impl(_) => continue,
804 let def_key = self.def_key(child_index);
805 let span = child.span.decode((self, sess));
806 if let (Some(kind), Some(name)) =
807 (self.def_kind(child_index), def_key.disambiguated_data.data.get_opt_name()) {
808 let ident = Ident::from_interned_str(name);
809 let vis = self.get_visibility(child_index);
810 let def_id = self.local_def_id(child_index);
811 let res = Res::Def(kind, def_id);
812 callback(def::Export { res, ident, vis, span });
813 // For non-re-export structs and variants add their constructors to children.
814 // Re-export lists automatically contain constructors when necessary.
817 if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
818 let ctor_kind = self.get_ctor_kind(child_index);
819 let ctor_res = Res::Def(
820 DefKind::Ctor(CtorOf::Struct, ctor_kind),
823 let vis = self.get_visibility(ctor_def_id.index);
824 callback(def::Export { res: ctor_res, vis, ident, span });
827 DefKind::Variant => {
828 // Braced variants, unlike structs, generate unusable names in
829 // value namespace, they are reserved for possible future use.
830 // It's ok to use the variant's id as a ctor id since an
831 // error will be reported on any use of such resolution anyway.
832 let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
833 let ctor_kind = self.get_ctor_kind(child_index);
834 let ctor_res = Res::Def(
835 DefKind::Ctor(CtorOf::Variant, ctor_kind),
838 let mut vis = self.get_visibility(ctor_def_id.index);
839 if ctor_def_id == def_id && vis == ty::Visibility::Public {
840 // For non-exhaustive variants lower the constructor visibility to
841 // within the crate. We only need this for fictive constructors,
842 // for other constructors correct visibilities
843 // were already encoded in metadata.
844 let attrs = self.get_item_attrs(def_id.index, sess);
845 if attr::contains_name(&attrs, sym::non_exhaustive) {
846 let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
847 vis = ty::Visibility::Restricted(crate_def_id);
850 callback(def::Export { res: ctor_res, ident, vis, span });
858 if let EntryKind::Mod(data) = item.kind {
859 for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
861 Res::Def(DefKind::Macro(..), _) => {}
862 _ if macros_only => continue,
870 pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
871 match self.entry(id).kind {
872 EntryKind::AssociatedConst(_, data, _) |
873 EntryKind::Const(data, _) => data.ast_promotable,
878 pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
879 !self.is_proc_macro(id) &&
880 self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
883 pub fn maybe_get_optimized_mir(&self,
884 tcx: TyCtxt<'a, 'tcx, 'tcx>,
886 -> Option<Mir<'tcx>> {
887 match self.is_proc_macro(id) {
889 false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
893 pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
894 match self.entry(id).kind {
895 EntryKind::Const(qualif, _) |
896 EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif, _) |
897 EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif, _) => {
904 pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
905 let item = self.entry(id);
906 let def_key = self.def_key(id);
907 let parent = self.local_def_id(def_key.parent.unwrap());
908 let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
910 let (kind, container, has_self) = match item.kind {
911 EntryKind::AssociatedConst(container, _, _) => {
912 (ty::AssociatedKind::Const, container, false)
914 EntryKind::Method(data) => {
915 let data = data.decode(self);
916 (ty::AssociatedKind::Method, data.container, data.has_self)
918 EntryKind::AssociatedType(container) => {
919 (ty::AssociatedKind::Type, container, false)
921 EntryKind::AssociatedExistential(container) => {
922 (ty::AssociatedKind::Existential, container, false)
924 _ => bug!("cannot get associated-item of `{:?}`", def_key)
928 ident: Ident::from_interned_str(name),
930 vis: item.visibility.decode(self),
931 defaultness: container.defaultness(),
932 def_id: self.local_def_id(id),
933 container: container.with_def_id(parent),
934 method_has_self_argument: has_self
938 pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
939 self.entry(id).variances.decode(self).collect()
942 pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
943 match self.entry(node_id).kind {
944 EntryKind::Struct(data, _) |
945 EntryKind::Union(data, _) |
946 EntryKind::Variant(data) => data.decode(self).ctor_kind,
947 _ => CtorKind::Fictive,
951 pub fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
952 match self.entry(node_id).kind {
953 EntryKind::Struct(data, _) => {
954 data.decode(self).ctor.map(|index| self.local_def_id(index))
956 EntryKind::Variant(data) => {
957 data.decode(self).ctor.map(|index| self.local_def_id(index))
963 pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
964 if self.is_proc_macro(node_id) {
968 // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
969 // we assume that someone passing in a tuple struct ctor is actually wanting to
970 // look at the definition
971 let def_key = self.def_key(node_id);
972 let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
973 def_key.parent.unwrap()
978 let item = self.entry(item_id);
979 Lrc::from(self.get_attributes(&item, sess))
982 pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
986 .map(|index| self.item_name(index))
990 fn get_attributes(&self, item: &Entry<'tcx>, sess: &Session) -> Vec<ast::Attribute> {
992 .decode((self, sess))
994 // Need new unique IDs: old thread-local IDs won't map to new threads.
995 attr.id = attr::mk_attr_id();
1001 // Translate a DefId from the current compilation environment to a DefId
1002 // for an external crate.
1003 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1004 for (local, &global) in self.cnum_map.iter_enumerated() {
1005 if global == did.krate {
1016 pub fn get_inherent_implementations_for_type(
1018 tcx: TyCtxt<'_, 'tcx, '_>,
1020 ) -> &'tcx [DefId] {
1021 tcx.arena.alloc_from_iter(self.entry(id)
1024 .map(|index| self.local_def_id(index)))
1027 pub fn get_implementations_for_trait(
1029 tcx: TyCtxt<'_, 'tcx, '_>,
1030 filter: Option<DefId>,
1031 ) -> &'tcx [DefId] {
1032 if self.proc_macros.is_some() {
1033 // proc-macro crates export no trait impls.
1037 // Do a reverse lookup beforehand to avoid touching the crate_num
1038 // hash map in the loop below.
1039 let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1040 Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1041 Some(None) => return &[],
1045 if let Some(filter) = filter {
1046 if let Some(impls) = self.trait_impls.get(&filter) {
1047 tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx)))
1052 tcx.arena.alloc_from_iter(self.trait_impls.values().flat_map(|impls| {
1053 impls.decode(self).map(|idx| self.local_def_id(idx))
1058 pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1059 let def_key = self.def_key(id);
1060 match def_key.disambiguated_data.data {
1061 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1062 // Not an associated item
1065 def_key.parent.and_then(|parent_index| {
1066 match self.entry(parent_index).kind {
1067 EntryKind::Trait(_) |
1068 EntryKind::TraitAlias(_) => Some(self.local_def_id(parent_index)),
1075 pub fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1076 if self.proc_macros.is_some() {
1077 // Proc macro crates do not have any *target* native libraries.
1080 self.root.native_libraries.decode((self, sess)).collect()
1084 pub fn get_foreign_modules(&self, sess: &Session) -> Vec<ForeignModule> {
1085 if self.proc_macros.is_some() {
1086 // Proc macro crates do not have any *target* foreign modules.
1089 self.root.foreign_modules.decode((self, sess)).collect()
1093 pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> {
1095 .dylib_dependency_formats
1098 .flat_map(|(i, link)| {
1099 let cnum = CrateNum::new(i + 1);
1100 link.map(|link| (self.cnum_map[cnum], link))
1105 pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> {
1106 if self.proc_macros.is_some() {
1107 // Proc macro crates do not depend on any target weak lang-items.
1117 pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
1118 let arg_names = match self.entry(id).kind {
1119 EntryKind::Fn(data) |
1120 EntryKind::ForeignFn(data) => data.decode(self).arg_names,
1121 EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
1122 _ => LazySeq::empty(),
1124 arg_names.decode(self).collect()
1127 pub fn exported_symbols(&self,
1128 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1129 -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1130 if self.proc_macros.is_some() {
1131 // If this crate is a custom derive crate, then we're not even going to
1132 // link those in so we skip those crates.
1135 self.root.exported_symbols.decode((self, tcx)).collect()
1139 pub fn get_rendered_const(&self, id: DefIndex) -> String {
1140 match self.entry(id).kind {
1141 EntryKind::Const(_, data) |
1142 EntryKind::AssociatedConst(_, _, data) => data.decode(self).0,
1147 pub fn get_macro(&self, id: DefIndex) -> MacroDef {
1148 let entry = self.entry(id);
1150 EntryKind::MacroDef(macro_def) => macro_def.decode(self),
1155 crate fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1156 let constness = match self.entry(id).kind {
1157 EntryKind::Method(data) => data.decode(self).fn_data.constness,
1158 EntryKind::Fn(data) => data.decode(self).constness,
1159 _ => hir::Constness::NotConst,
1161 constness == hir::Constness::Const
1164 pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1165 match self.entry(id).kind {
1166 EntryKind::ForeignImmStatic |
1167 EntryKind::ForeignMutStatic |
1168 EntryKind::ForeignFn(_) => true,
1173 crate fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1174 match self.entry(id).kind {
1175 EntryKind::ImmStatic |
1176 EntryKind::ForeignImmStatic => Some(hir::MutImmutable),
1177 EntryKind::MutStatic |
1178 EntryKind::ForeignMutStatic => Some(hir::MutMutable),
1183 pub fn fn_sig(&self,
1185 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1186 -> ty::PolyFnSig<'tcx> {
1187 let sig = match self.entry(id).kind {
1188 EntryKind::Fn(data) |
1189 EntryKind::ForeignFn(data) => data.decode(self).sig,
1190 EntryKind::Method(data) => data.decode(self).fn_data.sig,
1191 EntryKind::Variant(data) |
1192 EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1193 EntryKind::Closure(data) => data.decode(self).sig,
1196 sig.decode((self, tcx))
1200 pub fn def_key(&self, index: DefIndex) -> DefKey {
1201 self.def_path_table.def_key(index)
1204 // Returns the path leading to the thing with this `id`.
1205 pub fn def_path(&self, id: DefIndex) -> DefPath {
1206 debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1207 DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1211 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1212 self.def_path_table.def_path_hash(index)
1215 /// Imports the source_map from an external crate into the source_map of the crate
1216 /// currently being compiled (the "local crate").
1218 /// The import algorithm works analogous to how AST items are inlined from an
1219 /// external crate's metadata:
1220 /// For every SourceFile in the external source_map an 'inline' copy is created in the
1221 /// local source_map. The correspondence relation between external and local
1222 /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1223 /// function. When an item from an external crate is later inlined into this
1224 /// crate, this correspondence information is used to translate the span
1225 /// information of the inlined item so that it refers the correct positions in
1226 /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1228 /// The import algorithm in the function below will reuse SourceFiles already
1229 /// existing in the local source_map. For example, even if the SourceFile of some
1230 /// source file of libstd gets imported many times, there will only ever be
1231 /// one SourceFile object for the corresponding file in the local source_map.
1233 /// Note that imported SourceFiles do not actually contain the source code of the
1234 /// file they represent, just information about length, line breaks, and
1235 /// multibyte characters. This information is enough to generate valid debuginfo
1236 /// for items inlined from other crates.
1238 /// Proc macro crates don't currently export spans, so this function does not have
1239 /// to work for them.
1240 pub fn imported_source_files(&'a self,
1241 local_source_map: &source_map::SourceMap)
1242 -> ReadGuard<'a, Vec<cstore::ImportedSourceFile>> {
1244 let source_files = self.source_map_import_info.borrow();
1245 if !source_files.is_empty() {
1246 return source_files;
1250 // Lock the source_map_import_info to ensure this only happens once
1251 let mut source_map_import_info = self.source_map_import_info.borrow_mut();
1253 if !source_map_import_info.is_empty() {
1254 drop(source_map_import_info);
1255 return self.source_map_import_info.borrow();
1258 let external_source_map = self.root.source_map.decode(self);
1260 let imported_source_files = external_source_map.map(|source_file_to_import| {
1261 // We can't reuse an existing SourceFile, so allocate a new one
1262 // containing the information we need.
1263 let syntax_pos::SourceFile { name,
1269 mut multibyte_chars,
1270 mut non_narrow_chars,
1272 .. } = source_file_to_import;
1274 let source_length = (end_pos - start_pos).to_usize();
1276 // Translate line-start positions and multibyte character
1277 // position into frame of reference local to file.
1278 // `SourceMap::new_imported_source_file()` will then translate those
1279 // coordinates to their new global frame of reference when the
1280 // offset of the SourceFile is known.
1281 for pos in &mut lines {
1282 *pos = *pos - start_pos;
1284 for mbc in &mut multibyte_chars {
1285 mbc.pos = mbc.pos - start_pos;
1287 for swc in &mut non_narrow_chars {
1288 *swc = *swc - start_pos;
1291 let local_version = local_source_map.new_imported_source_file(name,
1300 debug!("CrateMetaData::imported_source_files alloc \
1301 source_file {:?} original (start_pos {:?} end_pos {:?}) \
1302 translated (start_pos {:?} end_pos {:?})",
1303 local_version.name, start_pos, end_pos,
1304 local_version.start_pos, local_version.end_pos);
1306 cstore::ImportedSourceFile {
1307 original_start_pos: start_pos,
1308 original_end_pos: end_pos,
1309 translated_source_file: local_version,
1313 *source_map_import_info = imported_source_files;
1314 drop(source_map_import_info);
1316 // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1317 self.source_map_import_info.borrow()