1 // Copyright 2012-2015 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.
12 use index_builder::{FromId, IndexBuilder, Untracked};
13 use isolated_encoder::IsolatedEncoder;
16 use rustc::middle::cstore::{LinkMeta, LinkagePreference, NativeLibrary,
18 use rustc::hir::def::CtorKind;
19 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LOCAL_CRATE};
20 use rustc::hir::map::definitions::DefPathTable;
21 use rustc::ich::Fingerprint;
22 use rustc::middle::dependency_format::Linkage;
23 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel,
24 metadata_symbol_name};
25 use rustc::middle::lang_items;
26 use rustc::mir::{self, interpret};
27 use rustc::traits::specialization_graph;
28 use rustc::ty::{self, Ty, TyCtxt, ReprOptions, SymbolName};
29 use rustc::ty::codec::{self as ty_codec, TyEncoder};
31 use rustc::session::config::{self, CrateTypeProcMacro};
32 use rustc::util::nodemap::FxHashMap;
34 use rustc_data_structures::stable_hasher::StableHasher;
35 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
38 use std::io::prelude::*;
41 use rustc_data_structures::sync::Lrc;
43 use syntax::ast::{self, CRATE_NODE_ID};
44 use syntax::codemap::Spanned;
46 use syntax::symbol::Symbol;
47 use syntax_pos::{self, FileName, FileMap, Span, DUMMY_SP};
49 use rustc::hir::{self, PatKind};
50 use rustc::hir::itemlikevisit::ItemLikeVisitor;
51 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
52 use rustc::hir::intravisit;
54 pub struct EncodeContext<'a, 'tcx: 'a> {
55 opaque: opaque::Encoder<'a>,
56 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
57 link_meta: &'a LinkMeta,
59 lazy_state: LazyState,
60 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
61 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
62 interpret_alloc_shorthands: FxHashMap<interpret::AllocId, usize>,
64 // This is used to speed up Span encoding.
65 filemap_cache: Lrc<FileMap>,
68 macro_rules! encoder_methods {
69 ($($name:ident($ty:ty);)*) => {
70 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
71 self.opaque.$name(value)
76 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
77 type Error = <opaque::Encoder<'a> as Encoder>::Error;
79 fn emit_nil(&mut self) -> Result<(), Self::Error> {
106 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
107 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
108 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
112 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
113 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
114 self.emit_usize(seq.len)?;
118 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
122 impl<'a, 'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'a, 'tcx> {
124 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
125 self.emit_u32(cnum.as_u32())
129 impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
131 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
142 impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
144 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
145 self.emit_u32(def_index.as_raw_u32())
149 impl<'a, 'tcx> SpecializedEncoder<Span> for EncodeContext<'a, 'tcx> {
150 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
151 if *span == DUMMY_SP {
152 return TAG_INVALID_SPAN.encode(self)
155 let span = span.data();
157 // The Span infrastructure should make sure that this invariant holds:
158 debug_assert!(span.lo <= span.hi);
160 if !self.filemap_cache.contains(span.lo) {
161 let codemap = self.tcx.sess.codemap();
162 let filemap_index = codemap.lookup_filemap_idx(span.lo);
163 self.filemap_cache = codemap.files()[filemap_index].clone();
166 if !self.filemap_cache.contains(span.hi) {
167 // Unfortunately, macro expansion still sometimes generates Spans
168 // that malformed in this way.
169 return TAG_INVALID_SPAN.encode(self)
172 TAG_VALID_SPAN.encode(self)?;
173 span.lo.encode(self)?;
175 // Encode length which is usually less than span.hi and profits more
176 // from the variable-length integer encoding that we use.
177 let len = span.hi - span.lo;
180 // Don't encode the expansion context.
184 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
185 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
186 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
190 impl<'a, 'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'a, 'tcx> {
191 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
192 trace!("encoding {:?} at {}", alloc_id, self.position());
193 if let Some(shorthand) = self.interpret_alloc_shorthands.get(alloc_id).cloned() {
194 trace!("encoding {:?} as shorthand to {}", alloc_id, shorthand);
195 return shorthand.encode(self);
197 let start = self.position();
198 // cache the allocation shorthand now, because the allocation itself might recursively
200 self.interpret_alloc_shorthands.insert(*alloc_id, start);
201 let interpret_interner = self.tcx.interpret_interner.borrow();
202 if let Some(alloc) = interpret_interner.get_alloc(*alloc_id) {
203 trace!("encoding {:?} with {:#?}", alloc_id, alloc);
204 usize::max_value().encode(self)?;
206 let globals = interpret_interner.get_globals(*alloc_id);
207 globals.len().encode(self)?;
208 for glob in globals {
211 } else if let Some(fn_instance) = interpret_interner.get_fn(*alloc_id) {
212 trace!("encoding {:?} with {:#?}", alloc_id, fn_instance);
213 (usize::max_value() - 1).encode(self)?;
214 fn_instance.encode(self)?;
216 bug!("alloc id without corresponding allocation: {}", alloc_id);
222 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
223 fn specialized_encode(&mut self,
224 predicates: &ty::GenericPredicates<'tcx>)
225 -> Result<(), Self::Error> {
226 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
230 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
231 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
232 f.encode_opaque(&mut self.opaque)
236 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
237 for EncodeContext<'a, 'tcx> {
238 fn specialized_encode(&mut self,
239 _: &mir::ClearCrossCrate<T>)
240 -> Result<(), Self::Error> {
245 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
246 fn position(&self) -> usize {
247 self.opaque.position()
251 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
253 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
254 assert_eq!(self.lazy_state, LazyState::NoNode);
255 let pos = self.position();
256 self.lazy_state = LazyState::NodeStart(pos);
257 let r = f(self, pos);
258 self.lazy_state = LazyState::NoNode;
262 fn emit_lazy_distance(&mut self,
265 -> Result<(), <Self as Encoder>::Error> {
266 let min_end = position + min_size;
267 let distance = match self.lazy_state {
268 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
269 LazyState::NodeStart(start) => {
270 assert!(min_end <= start);
273 LazyState::Previous(last_min_end) => {
274 assert!(last_min_end <= position);
275 position - last_min_end
278 self.lazy_state = LazyState::Previous(min_end);
279 self.emit_usize(distance)
282 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
283 self.emit_node(|ecx, pos| {
284 value.encode(ecx).unwrap();
286 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
287 Lazy::with_position(pos)
291 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
292 where I: IntoIterator<Item = T>,
295 self.emit_node(|ecx, pos| {
296 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
298 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
299 LazySeq::with_position_and_length(pos, len)
303 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
304 where I: IntoIterator<Item = &'b T>,
307 self.emit_node(|ecx, pos| {
308 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
310 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
311 LazySeq::with_position_and_length(pos, len)
315 // Encodes something that corresponds to a single DepNode::GlobalMetaData
316 // and registers the Fingerprint in the `metadata_hashes` map.
317 pub fn tracked<'x, DATA, R>(&'x mut self,
318 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
321 op(&mut IsolatedEncoder::new(self), data)
324 fn encode_info_for_items(&mut self) -> Index {
325 let krate = self.tcx.hir.krate();
326 let mut index = IndexBuilder::new(self);
327 index.record(DefId::local(CRATE_DEF_INDEX),
328 IsolatedEncoder::encode_info_for_mod,
329 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
330 let mut visitor = EncodeVisitor { index: index };
331 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
332 for macro_def in &krate.exported_macros {
333 visitor.visit_macro_def(macro_def);
335 visitor.index.into_items()
338 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
339 let definitions = self.tcx.hir.definitions();
340 self.lazy(definitions.def_path_table())
343 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
344 let codemap = self.tcx.sess.codemap();
345 let all_filemaps = codemap.files();
347 let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
349 let adapted = all_filemaps.iter()
351 // No need to re-export imported filemaps, as any downstream
352 // crate will import them from their original source.
353 !filemap.is_imported()
356 // When exporting FileMaps, we expand all paths to absolute
357 // paths because any relative paths are potentially relative to
358 // a wrong directory.
359 // However, if a path has been modified via
360 // `--remap-path-prefix` we assume the user has already set
361 // things up the way they want and don't touch the path values
364 FileName::Real(ref name) => {
365 if filemap.name_was_remapped ||
366 (name.is_relative() && working_dir_was_remapped) {
367 // This path of this FileMap has been modified by
368 // path-remapping, so we use it verbatim (and avoid cloning
369 // the whole map in the process).
372 let mut adapted = (**filemap).clone();
373 adapted.name = Path::new(&working_dir).join(name).into();
374 adapted.name_hash = {
375 let mut hasher: StableHasher<u128> = StableHasher::new();
376 adapted.name.hash(&mut hasher);
382 // expanded code, not from a file
383 _ => filemap.clone(),
386 .collect::<Vec<_>>();
388 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
391 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
392 let mut i = self.position();
394 let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
395 let dylib_dependency_formats = self.tracked(
396 IsolatedEncoder::encode_dylib_dependency_formats,
398 let dep_bytes = self.position() - i;
400 // Encode the language items.
402 let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
403 let lang_items_missing = self.tracked(
404 IsolatedEncoder::encode_lang_items_missing,
406 let lang_item_bytes = self.position() - i;
408 // Encode the native libraries used
410 let native_libraries = self.tracked(
411 IsolatedEncoder::encode_native_libraries,
413 let native_lib_bytes = self.position() - i;
417 let codemap = self.encode_codemap();
418 let codemap_bytes = self.position() - i;
420 // Encode DefPathTable
422 let def_path_table = self.encode_def_path_table();
423 let def_path_table_bytes = self.position() - i;
425 // Encode the def IDs of impls, for coherence checking.
427 let impls = self.tracked(IsolatedEncoder::encode_impls, ());
428 let impl_bytes = self.position() - i;
430 // Encode exported symbols info.
432 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
433 let exported_symbols = self.tracked(
434 IsolatedEncoder::encode_exported_symbols,
436 let exported_symbols_bytes = self.position() - i;
438 // Encode and index the items.
440 let items = self.encode_info_for_items();
441 let item_bytes = self.position() - i;
444 let index = items.write_index(&mut self.opaque.cursor);
445 let index_bytes = self.position() - i;
448 let link_meta = self.link_meta;
449 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
450 let has_default_lib_allocator =
451 attr::contains_name(tcx.hir.krate_attrs(), "default_lib_allocator");
452 let has_global_allocator = tcx.sess.has_global_allocator.get();
453 let root = self.lazy(&CrateRoot {
454 name: tcx.crate_name(LOCAL_CRATE),
455 triple: tcx.sess.opts.target_triple.clone(),
456 hash: link_meta.crate_hash,
457 disambiguator: tcx.sess.local_crate_disambiguator(),
458 panic_strategy: tcx.sess.panic_strategy(),
459 has_global_allocator: has_global_allocator,
460 has_default_lib_allocator: has_default_lib_allocator,
461 plugin_registrar_fn: tcx.sess
464 .map(|id| tcx.hir.local_def_id(id).index),
465 macro_derive_registrar: if is_proc_macro {
466 let id = tcx.sess.derive_registrar_fn.get().unwrap();
467 Some(tcx.hir.local_def_id(id).index)
473 dylib_dependency_formats,
484 let total_bytes = self.position();
486 if self.tcx.sess.meta_stats() {
487 let mut zero_bytes = 0;
488 for e in self.opaque.cursor.get_ref() {
494 println!("metadata stats:");
495 println!(" dep bytes: {}", dep_bytes);
496 println!(" lang item bytes: {}", lang_item_bytes);
497 println!(" native bytes: {}", native_lib_bytes);
498 println!(" codemap bytes: {}", codemap_bytes);
499 println!(" impl bytes: {}", impl_bytes);
500 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
501 println!(" def-path table bytes: {}", def_path_table_bytes);
502 println!(" item bytes: {}", item_bytes);
503 println!(" index bytes: {}", index_bytes);
504 println!(" zero bytes: {}", zero_bytes);
505 println!(" total bytes: {}", total_bytes);
512 // These are methods for encoding various things. They are meant to be used with
513 // IndexBuilder::record() and EncodeContext::tracked(). They actually
514 // would not have to be methods of IsolatedEncoder (free standing functions
515 // taking IsolatedEncoder as first argument would be just fine) but by making
516 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
517 // clause again and again.
518 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
519 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
520 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
522 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
525 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
527 let ty = tcx.type_of(def_id);
528 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
532 /// Encode data for the given variant of the given ADT. The
533 /// index of the variant is untracked: this is ok because we
534 /// will have to lookup the adt-def by its id, and that gives us
535 /// the right to access any information in the adt-def (including,
536 /// e.g., the length of the various vectors).
537 fn encode_enum_variant_info(&mut self,
538 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
541 let def = tcx.adt_def(enum_did);
542 let variant = &def.variants[index];
543 let def_id = variant.did;
544 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
546 let data = VariantData {
547 ctor_kind: variant.ctor_kind,
548 discr: variant.discr,
550 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
551 Some(self.lazy(&tcx.fn_sig(def_id)))
557 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
558 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
561 kind: EntryKind::Variant(self.lazy(&data)),
562 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
563 span: self.lazy(&tcx.def_span(def_id)),
564 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
565 children: self.lazy_seq(variant.fields.iter().map(|f| {
566 assert!(f.did.is_local());
569 stability: self.encode_stability(def_id),
570 deprecation: self.encode_deprecation(def_id),
572 ty: Some(self.encode_item_type(def_id)),
573 inherent_impls: LazySeq::empty(),
574 variances: if variant.ctor_kind == CtorKind::Fn {
575 self.encode_variances_of(def_id)
579 generics: Some(self.encode_generics(def_id)),
580 predicates: Some(self.encode_predicates(def_id)),
583 mir: self.encode_optimized_mir(def_id),
587 fn encode_info_for_mod(&mut self,
588 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
593 let def_id = tcx.hir.local_def_id(id);
594 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
597 reexports: match tcx.module_exports(def_id) {
598 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
599 _ => LazySeq::empty(),
604 kind: EntryKind::Mod(self.lazy(&data)),
605 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
606 span: self.lazy(&tcx.def_span(def_id)),
607 attributes: self.encode_attributes(attrs),
608 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
609 tcx.hir.local_def_id(item_id.id).index
611 stability: self.encode_stability(def_id),
612 deprecation: self.encode_deprecation(def_id),
615 inherent_impls: LazySeq::empty(),
616 variances: LazySeq::empty(),
625 /// Encode data for the given field of the given variant of the
626 /// given ADT. The indices of the variant/field are untracked:
627 /// this is ok because we will have to lookup the adt-def by its
628 /// id, and that gives us the right to access any information in
629 /// the adt-def (including, e.g., the length of the various
631 fn encode_field(&mut self,
632 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
637 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
638 let field = &variant.fields[field_index];
640 let def_id = field.did;
641 debug!("IsolatedEncoder::encode_field({:?})", def_id);
643 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
644 let variant_data = tcx.hir.expect_variant_data(variant_id);
647 kind: EntryKind::Field,
648 visibility: self.lazy(&field.vis),
649 span: self.lazy(&tcx.def_span(def_id)),
650 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
651 children: LazySeq::empty(),
652 stability: self.encode_stability(def_id),
653 deprecation: self.encode_deprecation(def_id),
655 ty: Some(self.encode_item_type(def_id)),
656 inherent_impls: LazySeq::empty(),
657 variances: LazySeq::empty(),
658 generics: Some(self.encode_generics(def_id)),
659 predicates: Some(self.encode_predicates(def_id)),
666 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
667 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
669 let adt_def = tcx.adt_def(adt_def_id);
670 let variant = adt_def.non_enum_variant();
672 let data = VariantData {
673 ctor_kind: variant.ctor_kind,
674 discr: variant.discr,
675 struct_ctor: Some(def_id.index),
676 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
677 Some(self.lazy(&tcx.fn_sig(def_id)))
683 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
684 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
685 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
686 for field in &variant.fields {
687 if ctor_vis.is_at_least(field.vis, tcx) {
688 ctor_vis = field.vis;
692 // If the structure is marked as non_exhaustive then lower the visibility
693 // to within the crate.
694 if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
695 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
698 let repr_options = get_repr_options(&tcx, adt_def_id);
701 kind: EntryKind::Struct(self.lazy(&data), repr_options),
702 visibility: self.lazy(&ctor_vis),
703 span: self.lazy(&tcx.def_span(def_id)),
704 attributes: LazySeq::empty(),
705 children: LazySeq::empty(),
706 stability: self.encode_stability(def_id),
707 deprecation: self.encode_deprecation(def_id),
709 ty: Some(self.encode_item_type(def_id)),
710 inherent_impls: LazySeq::empty(),
711 variances: if variant.ctor_kind == CtorKind::Fn {
712 self.encode_variances_of(def_id)
716 generics: Some(self.encode_generics(def_id)),
717 predicates: Some(self.encode_predicates(def_id)),
720 mir: self.encode_optimized_mir(def_id),
724 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
725 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
727 self.lazy(tcx.generics_of(def_id))
730 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
731 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
733 self.lazy(&tcx.predicates_of(def_id))
736 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
737 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
740 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
741 let ast_item = tcx.hir.expect_trait_item(node_id);
742 let trait_item = tcx.associated_item(def_id);
744 let container = match trait_item.defaultness {
745 hir::Defaultness::Default { has_value: true } =>
746 AssociatedContainer::TraitWithDefault,
747 hir::Defaultness::Default { has_value: false } =>
748 AssociatedContainer::TraitRequired,
749 hir::Defaultness::Final =>
750 span_bug!(ast_item.span, "traits cannot have final items"),
753 let kind = match trait_item.kind {
754 ty::AssociatedKind::Const => {
755 EntryKind::AssociatedConst(container, 0)
757 ty::AssociatedKind::Method => {
758 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
759 let arg_names = match *m {
760 hir::TraitMethod::Required(ref names) => {
761 self.encode_fn_arg_names(names)
763 hir::TraitMethod::Provided(body) => {
764 self.encode_fn_arg_names_for_body(body)
768 constness: hir::Constness::NotConst,
770 sig: self.lazy(&tcx.fn_sig(def_id)),
775 EntryKind::Method(self.lazy(&MethodData {
778 has_self: trait_item.method_has_self_argument,
781 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
786 visibility: self.lazy(&trait_item.vis),
787 span: self.lazy(&ast_item.span),
788 attributes: self.encode_attributes(&ast_item.attrs),
789 children: LazySeq::empty(),
790 stability: self.encode_stability(def_id),
791 deprecation: self.encode_deprecation(def_id),
793 ty: match trait_item.kind {
794 ty::AssociatedKind::Const |
795 ty::AssociatedKind::Method => {
796 Some(self.encode_item_type(def_id))
798 ty::AssociatedKind::Type => {
799 if trait_item.defaultness.has_value() {
800 Some(self.encode_item_type(def_id))
806 inherent_impls: LazySeq::empty(),
807 variances: if trait_item.kind == ty::AssociatedKind::Method {
808 self.encode_variances_of(def_id)
812 generics: Some(self.encode_generics(def_id)),
813 predicates: Some(self.encode_predicates(def_id)),
815 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
816 Some(self.encode_body(body))
820 mir: self.encode_optimized_mir(def_id),
824 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
825 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
828 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
829 let ast_item = self.tcx.hir.expect_impl_item(node_id);
830 let impl_item = self.tcx.associated_item(def_id);
832 let container = match impl_item.defaultness {
833 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
834 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
835 hir::Defaultness::Default { has_value: false } =>
836 span_bug!(ast_item.span, "impl items always have values (currently)"),
839 let kind = match impl_item.kind {
840 ty::AssociatedKind::Const => {
841 EntryKind::AssociatedConst(container,
842 self.tcx.at(ast_item.span).mir_const_qualif(def_id).0)
844 ty::AssociatedKind::Method => {
845 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
847 constness: sig.constness,
848 arg_names: self.encode_fn_arg_names_for_body(body),
849 sig: self.lazy(&tcx.fn_sig(def_id)),
854 EntryKind::Method(self.lazy(&MethodData {
857 has_self: impl_item.method_has_self_argument,
860 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
863 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
865 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
866 let generics = self.tcx.generics_of(def_id);
867 let types = generics.parent_types as usize + generics.types.len();
868 let needs_inline = types > 0 || tcx.trans_fn_attrs(def_id).requests_inline();
869 let is_const_fn = sig.constness == hir::Constness::Const;
870 let ast = if is_const_fn { Some(body) } else { None };
871 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
872 (ast, needs_inline || is_const_fn || always_encode_mir)
879 visibility: self.lazy(&impl_item.vis),
880 span: self.lazy(&ast_item.span),
881 attributes: self.encode_attributes(&ast_item.attrs),
882 children: LazySeq::empty(),
883 stability: self.encode_stability(def_id),
884 deprecation: self.encode_deprecation(def_id),
886 ty: Some(self.encode_item_type(def_id)),
887 inherent_impls: LazySeq::empty(),
888 variances: if impl_item.kind == ty::AssociatedKind::Method {
889 self.encode_variances_of(def_id)
893 generics: Some(self.encode_generics(def_id)),
894 predicates: Some(self.encode_predicates(def_id)),
896 ast: ast.map(|body| self.encode_body(body)),
897 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
901 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
902 -> LazySeq<ast::Name> {
903 self.tcx.dep_graph.with_ignore(|| {
904 let body = self.tcx.hir.body(body_id);
905 self.lazy_seq(body.arguments.iter().map(|arg| {
907 PatKind::Binding(_, _, name, _) => name.node,
908 _ => Symbol::intern("")
914 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
915 -> LazySeq<ast::Name> {
916 self.lazy_seq(names.iter().map(|name| name.node))
919 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
920 debug!("EntryBuilder::encode_mir({:?})", def_id);
921 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
922 let mir = self.tcx.optimized_mir(def_id);
923 Some(self.lazy(&mir))
929 // Encodes the inherent implementations of a structure, enumeration, or trait.
930 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
931 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
932 let implementations = self.tcx.inherent_impls(def_id);
933 if implementations.is_empty() {
936 self.lazy_seq(implementations.iter().map(|&def_id| {
937 assert!(def_id.is_local());
943 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
944 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
945 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
948 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
949 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
950 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
953 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
956 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
958 let kind = match item.node {
959 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
960 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
961 hir::ItemConst(..) => {
962 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id).0)
964 hir::ItemFn(_, _, constness, .., body) => {
967 arg_names: self.encode_fn_arg_names_for_body(body),
968 sig: self.lazy(&tcx.fn_sig(def_id)),
971 EntryKind::Fn(self.lazy(&data))
973 hir::ItemMod(ref m) => {
974 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
976 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
977 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
978 hir::ItemTy(..) => EntryKind::Type,
979 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
980 hir::ItemStruct(ref struct_def, _) => {
981 let variant = tcx.adt_def(def_id).non_enum_variant();
983 // Encode def_ids for each field and method
984 // for methods, write all the stuff get_trait_method
986 let struct_ctor = if !struct_def.is_struct() {
987 Some(tcx.hir.local_def_id(struct_def.id()).index)
992 let repr_options = get_repr_options(&tcx, def_id);
994 EntryKind::Struct(self.lazy(&VariantData {
995 ctor_kind: variant.ctor_kind,
996 discr: variant.discr,
1001 hir::ItemUnion(..) => {
1002 let variant = tcx.adt_def(def_id).non_enum_variant();
1003 let repr_options = get_repr_options(&tcx, def_id);
1005 EntryKind::Union(self.lazy(&VariantData {
1006 ctor_kind: variant.ctor_kind,
1007 discr: variant.discr,
1012 hir::ItemImpl(_, polarity, defaultness, ..) => {
1013 let trait_ref = tcx.impl_trait_ref(def_id);
1014 let parent = if let Some(trait_ref) = trait_ref {
1015 let trait_def = tcx.trait_def(trait_ref.def_id);
1016 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
1018 specialization_graph::Node::Impl(parent) => Some(parent),
1026 // if this is an impl of `CoerceUnsized`, create its
1027 // "unsized info", else just store None
1028 let coerce_unsized_info =
1029 trait_ref.and_then(|t| {
1030 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1031 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1037 let data = ImplData {
1040 parent_impl: parent,
1041 coerce_unsized_info,
1042 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1045 EntryKind::Impl(self.lazy(&data))
1047 hir::ItemTrait(..) => {
1048 let trait_def = tcx.trait_def(def_id);
1049 let data = TraitData {
1050 unsafety: trait_def.unsafety,
1051 paren_sugar: trait_def.paren_sugar,
1052 has_auto_impl: tcx.trait_is_auto(def_id),
1053 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1056 EntryKind::Trait(self.lazy(&data))
1058 hir::ItemExternCrate(_) |
1059 hir::ItemTraitAlias(..) |
1060 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1065 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1066 span: self.lazy(&item.span),
1067 attributes: self.encode_attributes(&item.attrs),
1068 children: match item.node {
1069 hir::ItemForeignMod(ref fm) => {
1070 self.lazy_seq(fm.items
1072 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1074 hir::ItemEnum(..) => {
1075 let def = self.tcx.adt_def(def_id);
1076 self.lazy_seq(def.variants.iter().map(|v| {
1077 assert!(v.did.is_local());
1081 hir::ItemStruct(..) |
1082 hir::ItemUnion(..) => {
1083 let def = self.tcx.adt_def(def_id);
1084 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1085 assert!(f.did.is_local());
1090 hir::ItemTrait(..) => {
1091 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1092 assert!(def_id.is_local());
1096 _ => LazySeq::empty(),
1098 stability: self.encode_stability(def_id),
1099 deprecation: self.encode_deprecation(def_id),
1101 ty: match item.node {
1102 hir::ItemStatic(..) |
1103 hir::ItemConst(..) |
1107 hir::ItemStruct(..) |
1108 hir::ItemUnion(..) |
1109 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1112 inherent_impls: self.encode_inherent_implementations(def_id),
1113 variances: match item.node {
1115 hir::ItemStruct(..) |
1116 hir::ItemUnion(..) |
1117 hir::ItemFn(..) => self.encode_variances_of(def_id),
1118 _ => LazySeq::empty(),
1120 generics: match item.node {
1121 hir::ItemStatic(..) |
1122 hir::ItemConst(..) |
1126 hir::ItemStruct(..) |
1127 hir::ItemUnion(..) |
1129 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1132 predicates: match item.node {
1133 hir::ItemStatic(..) |
1134 hir::ItemConst(..) |
1138 hir::ItemStruct(..) |
1139 hir::ItemUnion(..) |
1141 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1145 ast: match item.node {
1146 hir::ItemConst(_, body) |
1147 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
1148 Some(self.encode_body(body))
1152 mir: match item.node {
1153 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
1154 self.encode_optimized_mir(def_id)
1156 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1157 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1158 let has_tps = generics.ty_params().next().is_some();
1159 let needs_inline = has_tps || tcx.trans_fn_attrs(def_id).requests_inline();
1160 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1161 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
1162 self.encode_optimized_mir(def_id)
1172 /// Serialize the text of exported macros
1173 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1174 use syntax::print::pprust;
1175 let def_id = self.tcx.hir.local_def_id(macro_def.id);
1177 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1178 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1179 legacy: macro_def.legacy,
1181 visibility: self.lazy(&ty::Visibility::Public),
1182 span: self.lazy(¯o_def.span),
1183 attributes: self.encode_attributes(¯o_def.attrs),
1184 stability: self.encode_stability(def_id),
1185 deprecation: self.encode_deprecation(def_id),
1187 children: LazySeq::empty(),
1189 inherent_impls: LazySeq::empty(),
1190 variances: LazySeq::empty(),
1198 fn encode_info_for_ty_param(&mut self,
1199 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1201 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1204 kind: EntryKind::Type,
1205 visibility: self.lazy(&ty::Visibility::Public),
1206 span: self.lazy(&tcx.def_span(def_id)),
1207 attributes: LazySeq::empty(),
1208 children: LazySeq::empty(),
1212 ty: if has_default {
1213 Some(self.encode_item_type(def_id))
1217 inherent_impls: LazySeq::empty(),
1218 variances: LazySeq::empty(),
1227 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1228 debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
1231 kind: EntryKind::Type,
1232 visibility: self.lazy(&ty::Visibility::Public),
1233 span: self.lazy(&tcx.def_span(def_id)),
1234 attributes: LazySeq::empty(),
1235 children: LazySeq::empty(),
1239 ty: Some(self.encode_item_type(def_id)),
1240 inherent_impls: LazySeq::empty(),
1241 variances: LazySeq::empty(),
1242 generics: Some(self.encode_generics(def_id)),
1243 predicates: Some(self.encode_predicates(def_id)),
1250 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1251 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1254 let tables = self.tcx.typeck_tables_of(def_id);
1255 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1256 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1257 let kind = match tables.node_id_to_type(hir_id).sty {
1258 ty::TyGenerator(def_id, ..) => {
1259 let layout = self.tcx.generator_layout(def_id);
1260 let data = GeneratorData {
1261 layout: layout.clone(),
1263 EntryKind::Generator(self.lazy(&data))
1266 ty::TyClosure(def_id, substs) => {
1267 let sig = substs.closure_sig(def_id, self.tcx);
1268 let data = ClosureData { sig: self.lazy(&sig) };
1269 EntryKind::Closure(self.lazy(&data))
1272 _ => bug!("closure that is neither generator nor closure")
1277 visibility: self.lazy(&ty::Visibility::Public),
1278 span: self.lazy(&tcx.def_span(def_id)),
1279 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1280 children: LazySeq::empty(),
1284 ty: Some(self.encode_item_type(def_id)),
1285 inherent_impls: LazySeq::empty(),
1286 variances: LazySeq::empty(),
1287 generics: Some(self.encode_generics(def_id)),
1291 mir: self.encode_optimized_mir(def_id),
1295 fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1296 debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
1298 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1299 let body = tcx.hir.body_owned_by(id);
1302 kind: EntryKind::Const(tcx.mir_const_qualif(def_id).0),
1303 visibility: self.lazy(&ty::Visibility::Public),
1304 span: self.lazy(&tcx.def_span(def_id)),
1305 attributes: LazySeq::empty(),
1306 children: LazySeq::empty(),
1310 ty: Some(self.encode_item_type(def_id)),
1311 inherent_impls: LazySeq::empty(),
1312 variances: LazySeq::empty(),
1313 generics: Some(self.encode_generics(def_id)),
1314 predicates: Some(self.encode_predicates(def_id)),
1316 ast: Some(self.encode_body(body)),
1317 mir: self.encode_optimized_mir(def_id),
1321 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1322 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1323 // we rely on the HashStable specialization for [Attribute]
1324 // to properly filter things out.
1325 self.lazy_seq_from_slice(attrs)
1328 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1329 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1330 self.lazy_seq(used_libraries.iter().cloned())
1333 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1334 let crates = self.tcx.crates();
1336 let mut deps = crates
1339 let dep = CrateDep {
1340 name: self.tcx.original_crate_name(cnum),
1341 hash: self.tcx.crate_hash(cnum),
1342 kind: self.tcx.dep_kind(cnum),
1346 .collect::<Vec<_>>();
1348 deps.sort_by_key(|&(cnum, _)| cnum);
1351 // Sanity-check the crate numbers
1352 let mut expected_cnum = 1;
1353 for &(n, _) in &deps {
1354 assert_eq!(n, CrateNum::new(expected_cnum));
1359 // We're just going to write a list of crate 'name-hash-version's, with
1360 // the assumption that they are numbered 1 to n.
1361 // FIXME (#2166): This is not nearly enough to support correct versioning
1362 // but is enough to get transitive crate dependencies working.
1363 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1366 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1368 let lang_items = tcx.lang_items();
1369 let lang_items = lang_items.items().iter();
1370 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1371 if let Some(def_id) = opt_def_id {
1372 if def_id.is_local() {
1373 return Some((def_id.index, i));
1380 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1382 self.lazy_seq_ref(&tcx.lang_items().missing)
1385 /// Encodes an index, mapping each trait to its (local) implementations.
1386 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1387 debug!("IsolatedEncoder::encode_impls()");
1389 let mut visitor = ImplVisitor {
1393 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1395 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1397 // Bring everything into deterministic order for hashing
1398 all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1399 tcx.def_path_hash(trait_def_id)
1402 let all_impls: Vec<_> = all_impls
1404 .map(|(trait_def_id, mut impls)| {
1405 // Bring everything into deterministic order for hashing
1406 impls.sort_unstable_by_key(|&def_index| {
1407 tcx.hir.definitions().def_path_hash(def_index)
1411 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1412 impls: self.lazy_seq_from_slice(&impls[..]),
1417 self.lazy_seq_from_slice(&all_impls[..])
1420 // Encodes all symbols exported from this crate into the metadata.
1422 // This pass is seeded off the reachability list calculated in the
1423 // middle::reachable module but filters out items that either don't have a
1424 // symbol associated with them (they weren't translated) or if they're an FFI
1425 // definition (as that's not defined in this crate).
1426 fn encode_exported_symbols(&mut self,
1427 exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1428 -> LazySeq<(ExportedSymbol, SymbolExportLevel)> {
1430 // The metadata symbol name is special. It should not show up in
1431 // downstream crates.
1432 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1434 self.lazy_seq(exported_symbols
1436 .filter(|&&(ref exported_symbol, _)| {
1437 match *exported_symbol {
1438 ExportedSymbol::NoDefId(symbol_name) => {
1439 symbol_name != metadata_symbol_name
1447 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1448 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1450 self.lazy_seq(arr.iter().map(|slot| {
1452 Linkage::NotLinked |
1453 Linkage::IncludedFromDylib => None,
1455 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1456 Linkage::Static => Some(LinkagePreference::RequireStatic),
1460 None => LazySeq::empty(),
1464 fn encode_info_for_foreign_item(&mut self,
1465 (def_id, nitem): (DefId, &hir::ForeignItem))
1469 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1471 let kind = match nitem.node {
1472 hir::ForeignItemFn(_, ref names, _) => {
1474 constness: hir::Constness::NotConst,
1475 arg_names: self.encode_fn_arg_names(names),
1476 sig: self.lazy(&tcx.fn_sig(def_id)),
1478 EntryKind::ForeignFn(self.lazy(&data))
1480 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1481 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1482 hir::ForeignItemType => EntryKind::ForeignType,
1487 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1488 span: self.lazy(&nitem.span),
1489 attributes: self.encode_attributes(&nitem.attrs),
1490 children: LazySeq::empty(),
1491 stability: self.encode_stability(def_id),
1492 deprecation: self.encode_deprecation(def_id),
1494 ty: Some(self.encode_item_type(def_id)),
1495 inherent_impls: LazySeq::empty(),
1496 variances: match nitem.node {
1497 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1498 _ => LazySeq::empty(),
1500 generics: Some(self.encode_generics(def_id)),
1501 predicates: Some(self.encode_predicates(def_id)),
1509 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1510 index: IndexBuilder<'a, 'b, 'tcx>,
1513 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1514 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1515 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1517 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1518 intravisit::walk_expr(self, ex);
1519 self.index.encode_info_for_expr(ex);
1521 fn visit_item(&mut self, item: &'tcx hir::Item) {
1522 intravisit::walk_item(self, item);
1523 let def_id = self.index.tcx.hir.local_def_id(item.id);
1525 hir::ItemExternCrate(_) |
1526 hir::ItemUse(..) => (), // ignore these
1527 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1529 self.index.encode_addl_info_for_item(item);
1531 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1532 intravisit::walk_foreign_item(self, ni);
1533 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1534 self.index.record(def_id,
1535 IsolatedEncoder::encode_info_for_foreign_item,
1538 fn visit_variant(&mut self,
1539 v: &'tcx hir::Variant,
1540 g: &'tcx hir::Generics,
1542 intravisit::walk_variant(self, v, g, id);
1544 if let Some(discr) = v.node.disr_expr {
1545 let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1546 self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1549 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1550 intravisit::walk_generics(self, generics);
1551 self.index.encode_info_for_generics(generics);
1553 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1554 intravisit::walk_ty(self, ty);
1555 self.index.encode_info_for_ty(ty);
1557 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1558 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1559 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1563 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1564 fn encode_fields(&mut self, adt_def_id: DefId) {
1565 let def = self.tcx.adt_def(adt_def_id);
1566 for (variant_index, variant) in def.variants.iter().enumerate() {
1567 for (field_index, field) in variant.fields.iter().enumerate() {
1568 self.record(field.did,
1569 IsolatedEncoder::encode_field,
1570 (adt_def_id, Untracked((variant_index, field_index))));
1575 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1576 for ty_param in generics.ty_params() {
1577 let def_id = self.tcx.hir.local_def_id(ty_param.id);
1578 let has_default = Untracked(ty_param.default.is_some());
1579 self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
1583 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1585 hir::TyImplTraitExistential(..) => {
1586 let def_id = self.tcx.hir.local_def_id(ty.id);
1587 self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
1589 hir::TyArray(_, len) => {
1590 let def_id = self.tcx.hir.body_owner_def_id(len);
1591 self.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1597 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1599 hir::ExprClosure(..) => {
1600 let def_id = self.tcx.hir.local_def_id(expr.id);
1601 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1607 /// In some cases, along with the item itself, we also
1608 /// encode some sub-items. Usually we want some info from the item
1609 /// so it's easier to do that here then to wait until we would encounter
1610 /// normally in the visitor walk.
1611 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1612 let def_id = self.tcx.hir.local_def_id(item.id);
1614 hir::ItemStatic(..) |
1615 hir::ItemConst(..) |
1618 hir::ItemForeignMod(..) |
1619 hir::ItemGlobalAsm(..) |
1620 hir::ItemExternCrate(..) |
1623 hir::ItemTraitAlias(..) => {
1624 // no sub-item recording needed in these cases
1626 hir::ItemEnum(..) => {
1627 self.encode_fields(def_id);
1629 let def = self.tcx.adt_def(def_id);
1630 for (i, variant) in def.variants.iter().enumerate() {
1631 self.record(variant.did,
1632 IsolatedEncoder::encode_enum_variant_info,
1633 (def_id, Untracked(i)));
1636 hir::ItemStruct(ref struct_def, _) => {
1637 self.encode_fields(def_id);
1639 // If the struct has a constructor, encode it.
1640 if !struct_def.is_struct() {
1641 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1642 self.record(ctor_def_id,
1643 IsolatedEncoder::encode_struct_ctor,
1644 (def_id, ctor_def_id));
1647 hir::ItemUnion(..) => {
1648 self.encode_fields(def_id);
1650 hir::ItemImpl(..) => {
1651 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1652 self.record(trait_item_def_id,
1653 IsolatedEncoder::encode_info_for_impl_item,
1657 hir::ItemTrait(..) => {
1658 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1659 self.record(item_def_id,
1660 IsolatedEncoder::encode_info_for_trait_item,
1668 struct ImplVisitor<'a, 'tcx: 'a> {
1669 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1670 impls: FxHashMap<DefId, Vec<DefIndex>>,
1673 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1674 fn visit_item(&mut self, item: &hir::Item) {
1675 if let hir::ItemImpl(..) = item.node {
1676 let impl_id = self.tcx.hir.local_def_id(item.id);
1677 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1679 .entry(trait_ref.def_id)
1681 .push(impl_id.index);
1686 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1688 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1689 // handled in `visit_item` above
1693 // NOTE(eddyb) The following comment was preserved for posterity, even
1694 // though it's no longer relevant as EBML (which uses nested & tagged
1695 // "documents") was replaced with a scheme that can't go out of bounds.
1697 // And here we run into yet another obscure archive bug: in which metadata
1698 // loaded from archives may have trailing garbage bytes. Awhile back one of
1699 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1700 // and opt) by having ebml generate an out-of-bounds panic when looking at
1703 // Upon investigation it turned out that the metadata file inside of an rlib
1704 // (and ar archive) was being corrupted. Some compilations would generate a
1705 // metadata file which would end in a few extra bytes, while other
1706 // compilations would not have these extra bytes appended to the end. These
1707 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1708 // being interpreted causing the out-of-bounds.
1710 // The root cause of why these extra bytes were appearing was never
1711 // discovered, and in the meantime the solution we're employing is to insert
1712 // the length of the metadata to the start of the metadata. Later on this
1713 // will allow us to slice the metadata to the precise length that we just
1714 // generated regardless of trailing bytes that end up in it.
1716 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1717 link_meta: &LinkMeta)
1720 let mut cursor = Cursor::new(vec![]);
1721 cursor.write_all(METADATA_HEADER).unwrap();
1723 // Will be filled with the root position after encoding everything.
1724 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1727 let mut ecx = EncodeContext {
1728 opaque: opaque::Encoder::new(&mut cursor),
1731 lazy_state: LazyState::NoNode,
1732 type_shorthands: Default::default(),
1733 predicate_shorthands: Default::default(),
1734 filemap_cache: tcx.sess.codemap().files()[0].clone(),
1735 interpret_alloc_shorthands: Default::default(),
1738 // Encode the rustc version string in a predictable location.
1739 rustc_version().encode(&mut ecx).unwrap();
1741 // Encode all the entries and extra information in the crate,
1742 // culminating in the `CrateRoot` which points to all of it.
1743 ecx.encode_crate_root()
1745 let mut result = cursor.into_inner();
1747 // Encode the root position.
1748 let header = METADATA_HEADER.len();
1749 let pos = root.position;
1750 result[header + 0] = (pos >> 24) as u8;
1751 result[header + 1] = (pos >> 16) as u8;
1752 result[header + 2] = (pos >> 8) as u8;
1753 result[header + 3] = (pos >> 0) as u8;
1755 EncodedMetadata { raw_data: result }
1758 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1759 let ty = tcx.type_of(did);
1761 ty::TyAdt(ref def, _) => return def.repr,
1762 _ => bug!("{} is not an ADT", ty),