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, LocalDefId, 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<LocalDefId> for EncodeContext<'a, 'tcx> {
186 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
187 self.specialized_encode(&def_id.to_def_id())
191 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
192 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
193 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
197 impl<'a, 'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'a, 'tcx> {
198 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
199 trace!("encoding {:?} at {}", alloc_id, self.position());
200 if let Some(shorthand) = self.interpret_alloc_shorthands.get(alloc_id).cloned() {
201 trace!("encoding {:?} as shorthand to {}", alloc_id, shorthand);
202 return shorthand.encode(self);
204 let start = self.position();
205 // cache the allocation shorthand now, because the allocation itself might recursively
207 self.interpret_alloc_shorthands.insert(*alloc_id, start);
208 let interpret_interner = self.tcx.interpret_interner.borrow();
209 if let Some(alloc) = interpret_interner.get_alloc(*alloc_id) {
210 trace!("encoding {:?} with {:#?}", alloc_id, alloc);
211 usize::max_value().encode(self)?;
213 let globals = interpret_interner.get_globals(*alloc_id);
214 globals.len().encode(self)?;
215 for glob in globals {
218 } else if let Some(fn_instance) = interpret_interner.get_fn(*alloc_id) {
219 trace!("encoding {:?} with {:#?}", alloc_id, fn_instance);
220 (usize::max_value() - 1).encode(self)?;
221 fn_instance.encode(self)?;
223 bug!("alloc id without corresponding allocation: {}", alloc_id);
229 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
230 fn specialized_encode(&mut self,
231 predicates: &ty::GenericPredicates<'tcx>)
232 -> Result<(), Self::Error> {
233 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
237 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
238 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
239 f.encode_opaque(&mut self.opaque)
243 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
244 for EncodeContext<'a, 'tcx> {
245 fn specialized_encode(&mut self,
246 _: &mir::ClearCrossCrate<T>)
247 -> Result<(), Self::Error> {
252 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
253 fn position(&self) -> usize {
254 self.opaque.position()
258 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
260 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
261 assert_eq!(self.lazy_state, LazyState::NoNode);
262 let pos = self.position();
263 self.lazy_state = LazyState::NodeStart(pos);
264 let r = f(self, pos);
265 self.lazy_state = LazyState::NoNode;
269 fn emit_lazy_distance(&mut self,
272 -> Result<(), <Self as Encoder>::Error> {
273 let min_end = position + min_size;
274 let distance = match self.lazy_state {
275 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
276 LazyState::NodeStart(start) => {
277 assert!(min_end <= start);
280 LazyState::Previous(last_min_end) => {
281 assert!(last_min_end <= position);
282 position - last_min_end
285 self.lazy_state = LazyState::Previous(min_end);
286 self.emit_usize(distance)
289 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
290 self.emit_node(|ecx, pos| {
291 value.encode(ecx).unwrap();
293 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
294 Lazy::with_position(pos)
298 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
299 where I: IntoIterator<Item = T>,
302 self.emit_node(|ecx, pos| {
303 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
305 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
306 LazySeq::with_position_and_length(pos, len)
310 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
311 where I: IntoIterator<Item = &'b T>,
314 self.emit_node(|ecx, pos| {
315 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
317 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
318 LazySeq::with_position_and_length(pos, len)
322 // Encodes something that corresponds to a single DepNode::GlobalMetaData
323 // and registers the Fingerprint in the `metadata_hashes` map.
324 pub fn tracked<'x, DATA, R>(&'x mut self,
325 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
328 op(&mut IsolatedEncoder::new(self), data)
331 fn encode_info_for_items(&mut self) -> Index {
332 let krate = self.tcx.hir.krate();
333 let mut index = IndexBuilder::new(self);
334 index.record(DefId::local(CRATE_DEF_INDEX),
335 IsolatedEncoder::encode_info_for_mod,
336 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
337 let mut visitor = EncodeVisitor { index: index };
338 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
339 for macro_def in &krate.exported_macros {
340 visitor.visit_macro_def(macro_def);
342 visitor.index.into_items()
345 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
346 let definitions = self.tcx.hir.definitions();
347 self.lazy(definitions.def_path_table())
350 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
351 let codemap = self.tcx.sess.codemap();
352 let all_filemaps = codemap.files();
354 let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
356 let adapted = all_filemaps.iter()
358 // No need to re-export imported filemaps, as any downstream
359 // crate will import them from their original source.
360 !filemap.is_imported()
363 // When exporting FileMaps, we expand all paths to absolute
364 // paths because any relative paths are potentially relative to
365 // a wrong directory.
366 // However, if a path has been modified via
367 // `--remap-path-prefix` we assume the user has already set
368 // things up the way they want and don't touch the path values
371 FileName::Real(ref name) => {
372 if filemap.name_was_remapped ||
373 (name.is_relative() && working_dir_was_remapped) {
374 // This path of this FileMap has been modified by
375 // path-remapping, so we use it verbatim (and avoid cloning
376 // the whole map in the process).
379 let mut adapted = (**filemap).clone();
380 adapted.name = Path::new(&working_dir).join(name).into();
381 adapted.name_hash = {
382 let mut hasher: StableHasher<u128> = StableHasher::new();
383 adapted.name.hash(&mut hasher);
389 // expanded code, not from a file
390 _ => filemap.clone(),
393 .collect::<Vec<_>>();
395 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
398 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
399 let mut i = self.position();
401 let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
402 let dylib_dependency_formats = self.tracked(
403 IsolatedEncoder::encode_dylib_dependency_formats,
405 let dep_bytes = self.position() - i;
407 // Encode the language items.
409 let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
410 let lang_items_missing = self.tracked(
411 IsolatedEncoder::encode_lang_items_missing,
413 let lang_item_bytes = self.position() - i;
415 // Encode the native libraries used
417 let native_libraries = self.tracked(
418 IsolatedEncoder::encode_native_libraries,
420 let native_lib_bytes = self.position() - i;
424 let codemap = self.encode_codemap();
425 let codemap_bytes = self.position() - i;
427 // Encode DefPathTable
429 let def_path_table = self.encode_def_path_table();
430 let def_path_table_bytes = self.position() - i;
432 // Encode the def IDs of impls, for coherence checking.
434 let impls = self.tracked(IsolatedEncoder::encode_impls, ());
435 let impl_bytes = self.position() - i;
437 // Encode exported symbols info.
439 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
440 let exported_symbols = self.tracked(
441 IsolatedEncoder::encode_exported_symbols,
443 let exported_symbols_bytes = self.position() - i;
445 // Encode and index the items.
447 let items = self.encode_info_for_items();
448 let item_bytes = self.position() - i;
451 let index = items.write_index(&mut self.opaque.cursor);
452 let index_bytes = self.position() - i;
455 let link_meta = self.link_meta;
456 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
457 let has_default_lib_allocator =
458 attr::contains_name(tcx.hir.krate_attrs(), "default_lib_allocator");
459 let has_global_allocator = tcx.sess.has_global_allocator.get();
460 let root = self.lazy(&CrateRoot {
461 name: tcx.crate_name(LOCAL_CRATE),
462 triple: tcx.sess.opts.target_triple.clone(),
463 hash: link_meta.crate_hash,
464 disambiguator: tcx.sess.local_crate_disambiguator(),
465 panic_strategy: tcx.sess.panic_strategy(),
466 has_global_allocator: has_global_allocator,
467 has_default_lib_allocator: has_default_lib_allocator,
468 plugin_registrar_fn: tcx.sess
471 .map(|id| tcx.hir.local_def_id(id).index),
472 macro_derive_registrar: if is_proc_macro {
473 let id = tcx.sess.derive_registrar_fn.get().unwrap();
474 Some(tcx.hir.local_def_id(id).index)
480 dylib_dependency_formats,
491 let total_bytes = self.position();
493 if self.tcx.sess.meta_stats() {
494 let mut zero_bytes = 0;
495 for e in self.opaque.cursor.get_ref() {
501 println!("metadata stats:");
502 println!(" dep bytes: {}", dep_bytes);
503 println!(" lang item bytes: {}", lang_item_bytes);
504 println!(" native bytes: {}", native_lib_bytes);
505 println!(" codemap bytes: {}", codemap_bytes);
506 println!(" impl bytes: {}", impl_bytes);
507 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
508 println!(" def-path table bytes: {}", def_path_table_bytes);
509 println!(" item bytes: {}", item_bytes);
510 println!(" index bytes: {}", index_bytes);
511 println!(" zero bytes: {}", zero_bytes);
512 println!(" total bytes: {}", total_bytes);
519 // These are methods for encoding various things. They are meant to be used with
520 // IndexBuilder::record() and EncodeContext::tracked(). They actually
521 // would not have to be methods of IsolatedEncoder (free standing functions
522 // taking IsolatedEncoder as first argument would be just fine) but by making
523 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
524 // clause again and again.
525 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
526 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
527 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
529 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
532 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
534 let ty = tcx.type_of(def_id);
535 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
539 /// Encode data for the given variant of the given ADT. The
540 /// index of the variant is untracked: this is ok because we
541 /// will have to lookup the adt-def by its id, and that gives us
542 /// the right to access any information in the adt-def (including,
543 /// e.g., the length of the various vectors).
544 fn encode_enum_variant_info(&mut self,
545 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
548 let def = tcx.adt_def(enum_did);
549 let variant = &def.variants[index];
550 let def_id = variant.did;
551 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
553 let data = VariantData {
554 ctor_kind: variant.ctor_kind,
555 discr: variant.discr,
557 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
558 Some(self.lazy(&tcx.fn_sig(def_id)))
564 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
565 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
568 kind: EntryKind::Variant(self.lazy(&data)),
569 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
570 span: self.lazy(&tcx.def_span(def_id)),
571 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
572 children: self.lazy_seq(variant.fields.iter().map(|f| {
573 assert!(f.did.is_local());
576 stability: self.encode_stability(def_id),
577 deprecation: self.encode_deprecation(def_id),
579 ty: Some(self.encode_item_type(def_id)),
580 inherent_impls: LazySeq::empty(),
581 variances: if variant.ctor_kind == CtorKind::Fn {
582 self.encode_variances_of(def_id)
586 generics: Some(self.encode_generics(def_id)),
587 predicates: Some(self.encode_predicates(def_id)),
590 mir: self.encode_optimized_mir(def_id),
594 fn encode_info_for_mod(&mut self,
595 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
600 let def_id = tcx.hir.local_def_id(id);
601 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
604 reexports: match tcx.module_exports(def_id) {
605 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
606 _ => LazySeq::empty(),
611 kind: EntryKind::Mod(self.lazy(&data)),
612 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
613 span: self.lazy(&tcx.def_span(def_id)),
614 attributes: self.encode_attributes(attrs),
615 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
616 tcx.hir.local_def_id(item_id.id).index
618 stability: self.encode_stability(def_id),
619 deprecation: self.encode_deprecation(def_id),
622 inherent_impls: LazySeq::empty(),
623 variances: LazySeq::empty(),
632 /// Encode data for the given field of the given variant of the
633 /// given ADT. The indices of the variant/field are untracked:
634 /// this is ok because we will have to lookup the adt-def by its
635 /// id, and that gives us the right to access any information in
636 /// the adt-def (including, e.g., the length of the various
638 fn encode_field(&mut self,
639 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
644 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
645 let field = &variant.fields[field_index];
647 let def_id = field.did;
648 debug!("IsolatedEncoder::encode_field({:?})", def_id);
650 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
651 let variant_data = tcx.hir.expect_variant_data(variant_id);
654 kind: EntryKind::Field,
655 visibility: self.lazy(&field.vis),
656 span: self.lazy(&tcx.def_span(def_id)),
657 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
658 children: LazySeq::empty(),
659 stability: self.encode_stability(def_id),
660 deprecation: self.encode_deprecation(def_id),
662 ty: Some(self.encode_item_type(def_id)),
663 inherent_impls: LazySeq::empty(),
664 variances: LazySeq::empty(),
665 generics: Some(self.encode_generics(def_id)),
666 predicates: Some(self.encode_predicates(def_id)),
673 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
674 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
676 let adt_def = tcx.adt_def(adt_def_id);
677 let variant = adt_def.non_enum_variant();
679 let data = VariantData {
680 ctor_kind: variant.ctor_kind,
681 discr: variant.discr,
682 struct_ctor: Some(def_id.index),
683 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
684 Some(self.lazy(&tcx.fn_sig(def_id)))
690 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
691 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
692 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
693 for field in &variant.fields {
694 if ctor_vis.is_at_least(field.vis, tcx) {
695 ctor_vis = field.vis;
699 // If the structure is marked as non_exhaustive then lower the visibility
700 // to within the crate.
701 if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
702 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
705 let repr_options = get_repr_options(&tcx, adt_def_id);
708 kind: EntryKind::Struct(self.lazy(&data), repr_options),
709 visibility: self.lazy(&ctor_vis),
710 span: self.lazy(&tcx.def_span(def_id)),
711 attributes: LazySeq::empty(),
712 children: LazySeq::empty(),
713 stability: self.encode_stability(def_id),
714 deprecation: self.encode_deprecation(def_id),
716 ty: Some(self.encode_item_type(def_id)),
717 inherent_impls: LazySeq::empty(),
718 variances: if variant.ctor_kind == CtorKind::Fn {
719 self.encode_variances_of(def_id)
723 generics: Some(self.encode_generics(def_id)),
724 predicates: Some(self.encode_predicates(def_id)),
727 mir: self.encode_optimized_mir(def_id),
731 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
732 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
734 self.lazy(tcx.generics_of(def_id))
737 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
738 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
740 self.lazy(&tcx.predicates_of(def_id))
743 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
744 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
747 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
748 let ast_item = tcx.hir.expect_trait_item(node_id);
749 let trait_item = tcx.associated_item(def_id);
751 let container = match trait_item.defaultness {
752 hir::Defaultness::Default { has_value: true } =>
753 AssociatedContainer::TraitWithDefault,
754 hir::Defaultness::Default { has_value: false } =>
755 AssociatedContainer::TraitRequired,
756 hir::Defaultness::Final =>
757 span_bug!(ast_item.span, "traits cannot have final items"),
760 let kind = match trait_item.kind {
761 ty::AssociatedKind::Const => {
762 EntryKind::AssociatedConst(container, 0)
764 ty::AssociatedKind::Method => {
765 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
766 let arg_names = match *m {
767 hir::TraitMethod::Required(ref names) => {
768 self.encode_fn_arg_names(names)
770 hir::TraitMethod::Provided(body) => {
771 self.encode_fn_arg_names_for_body(body)
775 constness: hir::Constness::NotConst,
777 sig: self.lazy(&tcx.fn_sig(def_id)),
782 EntryKind::Method(self.lazy(&MethodData {
785 has_self: trait_item.method_has_self_argument,
788 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
793 visibility: self.lazy(&trait_item.vis),
794 span: self.lazy(&ast_item.span),
795 attributes: self.encode_attributes(&ast_item.attrs),
796 children: LazySeq::empty(),
797 stability: self.encode_stability(def_id),
798 deprecation: self.encode_deprecation(def_id),
800 ty: match trait_item.kind {
801 ty::AssociatedKind::Const |
802 ty::AssociatedKind::Method => {
803 Some(self.encode_item_type(def_id))
805 ty::AssociatedKind::Type => {
806 if trait_item.defaultness.has_value() {
807 Some(self.encode_item_type(def_id))
813 inherent_impls: LazySeq::empty(),
814 variances: if trait_item.kind == ty::AssociatedKind::Method {
815 self.encode_variances_of(def_id)
819 generics: Some(self.encode_generics(def_id)),
820 predicates: Some(self.encode_predicates(def_id)),
822 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
823 Some(self.encode_body(body))
827 mir: self.encode_optimized_mir(def_id),
831 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
832 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
835 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
836 let ast_item = self.tcx.hir.expect_impl_item(node_id);
837 let impl_item = self.tcx.associated_item(def_id);
839 let container = match impl_item.defaultness {
840 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
841 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
842 hir::Defaultness::Default { has_value: false } =>
843 span_bug!(ast_item.span, "impl items always have values (currently)"),
846 let kind = match impl_item.kind {
847 ty::AssociatedKind::Const => {
848 EntryKind::AssociatedConst(container,
849 self.tcx.at(ast_item.span).mir_const_qualif(def_id).0)
851 ty::AssociatedKind::Method => {
852 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
854 constness: sig.constness,
855 arg_names: self.encode_fn_arg_names_for_body(body),
856 sig: self.lazy(&tcx.fn_sig(def_id)),
861 EntryKind::Method(self.lazy(&MethodData {
864 has_self: impl_item.method_has_self_argument,
867 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
870 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
872 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
873 let generics = self.tcx.generics_of(def_id);
874 let types = generics.parent_types as usize + generics.types.len();
875 let needs_inline = types > 0 || tcx.trans_fn_attrs(def_id).requests_inline();
876 let is_const_fn = sig.constness == hir::Constness::Const;
877 let ast = if is_const_fn { Some(body) } else { None };
878 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
879 (ast, needs_inline || is_const_fn || always_encode_mir)
886 visibility: self.lazy(&impl_item.vis),
887 span: self.lazy(&ast_item.span),
888 attributes: self.encode_attributes(&ast_item.attrs),
889 children: LazySeq::empty(),
890 stability: self.encode_stability(def_id),
891 deprecation: self.encode_deprecation(def_id),
893 ty: Some(self.encode_item_type(def_id)),
894 inherent_impls: LazySeq::empty(),
895 variances: if impl_item.kind == ty::AssociatedKind::Method {
896 self.encode_variances_of(def_id)
900 generics: Some(self.encode_generics(def_id)),
901 predicates: Some(self.encode_predicates(def_id)),
903 ast: ast.map(|body| self.encode_body(body)),
904 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
908 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
909 -> LazySeq<ast::Name> {
910 self.tcx.dep_graph.with_ignore(|| {
911 let body = self.tcx.hir.body(body_id);
912 self.lazy_seq(body.arguments.iter().map(|arg| {
914 PatKind::Binding(_, _, name, _) => name.node,
915 _ => Symbol::intern("")
921 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
922 -> LazySeq<ast::Name> {
923 self.lazy_seq(names.iter().map(|name| name.node))
926 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
927 debug!("EntryBuilder::encode_mir({:?})", def_id);
928 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
929 let mir = self.tcx.optimized_mir(def_id);
930 Some(self.lazy(&mir))
936 // Encodes the inherent implementations of a structure, enumeration, or trait.
937 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
938 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
939 let implementations = self.tcx.inherent_impls(def_id);
940 if implementations.is_empty() {
943 self.lazy_seq(implementations.iter().map(|&def_id| {
944 assert!(def_id.is_local());
950 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
951 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
952 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
955 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
956 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
957 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
960 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
963 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
965 let kind = match item.node {
966 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
967 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
968 hir::ItemConst(..) => {
969 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id).0)
971 hir::ItemFn(_, _, constness, .., body) => {
974 arg_names: self.encode_fn_arg_names_for_body(body),
975 sig: self.lazy(&tcx.fn_sig(def_id)),
978 EntryKind::Fn(self.lazy(&data))
980 hir::ItemMod(ref m) => {
981 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
983 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
984 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
985 hir::ItemTy(..) => EntryKind::Type,
986 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
987 hir::ItemStruct(ref struct_def, _) => {
988 let variant = tcx.adt_def(def_id).non_enum_variant();
990 // Encode def_ids for each field and method
991 // for methods, write all the stuff get_trait_method
993 let struct_ctor = if !struct_def.is_struct() {
994 Some(tcx.hir.local_def_id(struct_def.id()).index)
999 let repr_options = get_repr_options(&tcx, def_id);
1001 EntryKind::Struct(self.lazy(&VariantData {
1002 ctor_kind: variant.ctor_kind,
1003 discr: variant.discr,
1008 hir::ItemUnion(..) => {
1009 let variant = tcx.adt_def(def_id).non_enum_variant();
1010 let repr_options = get_repr_options(&tcx, def_id);
1012 EntryKind::Union(self.lazy(&VariantData {
1013 ctor_kind: variant.ctor_kind,
1014 discr: variant.discr,
1019 hir::ItemImpl(_, polarity, defaultness, ..) => {
1020 let trait_ref = tcx.impl_trait_ref(def_id);
1021 let parent = if let Some(trait_ref) = trait_ref {
1022 let trait_def = tcx.trait_def(trait_ref.def_id);
1023 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
1025 specialization_graph::Node::Impl(parent) => Some(parent),
1033 // if this is an impl of `CoerceUnsized`, create its
1034 // "unsized info", else just store None
1035 let coerce_unsized_info =
1036 trait_ref.and_then(|t| {
1037 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1038 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1044 let data = ImplData {
1047 parent_impl: parent,
1048 coerce_unsized_info,
1049 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1052 EntryKind::Impl(self.lazy(&data))
1054 hir::ItemTrait(..) => {
1055 let trait_def = tcx.trait_def(def_id);
1056 let data = TraitData {
1057 unsafety: trait_def.unsafety,
1058 paren_sugar: trait_def.paren_sugar,
1059 has_auto_impl: tcx.trait_is_auto(def_id),
1060 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1063 EntryKind::Trait(self.lazy(&data))
1065 hir::ItemExternCrate(_) |
1066 hir::ItemTraitAlias(..) |
1067 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1072 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1073 span: self.lazy(&item.span),
1074 attributes: self.encode_attributes(&item.attrs),
1075 children: match item.node {
1076 hir::ItemForeignMod(ref fm) => {
1077 self.lazy_seq(fm.items
1079 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1081 hir::ItemEnum(..) => {
1082 let def = self.tcx.adt_def(def_id);
1083 self.lazy_seq(def.variants.iter().map(|v| {
1084 assert!(v.did.is_local());
1088 hir::ItemStruct(..) |
1089 hir::ItemUnion(..) => {
1090 let def = self.tcx.adt_def(def_id);
1091 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1092 assert!(f.did.is_local());
1097 hir::ItemTrait(..) => {
1098 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1099 assert!(def_id.is_local());
1103 _ => LazySeq::empty(),
1105 stability: self.encode_stability(def_id),
1106 deprecation: self.encode_deprecation(def_id),
1108 ty: match item.node {
1109 hir::ItemStatic(..) |
1110 hir::ItemConst(..) |
1114 hir::ItemStruct(..) |
1115 hir::ItemUnion(..) |
1116 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1119 inherent_impls: self.encode_inherent_implementations(def_id),
1120 variances: match item.node {
1122 hir::ItemStruct(..) |
1123 hir::ItemUnion(..) |
1124 hir::ItemFn(..) => self.encode_variances_of(def_id),
1125 _ => LazySeq::empty(),
1127 generics: match item.node {
1128 hir::ItemStatic(..) |
1129 hir::ItemConst(..) |
1133 hir::ItemStruct(..) |
1134 hir::ItemUnion(..) |
1136 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1139 predicates: match item.node {
1140 hir::ItemStatic(..) |
1141 hir::ItemConst(..) |
1145 hir::ItemStruct(..) |
1146 hir::ItemUnion(..) |
1148 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1152 ast: match item.node {
1153 hir::ItemConst(_, body) |
1154 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
1155 Some(self.encode_body(body))
1159 mir: match item.node {
1160 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
1161 self.encode_optimized_mir(def_id)
1163 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1164 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1165 let has_tps = generics.ty_params().next().is_some();
1166 let needs_inline = has_tps || tcx.trans_fn_attrs(def_id).requests_inline();
1167 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1168 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
1169 self.encode_optimized_mir(def_id)
1179 /// Serialize the text of exported macros
1180 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1181 use syntax::print::pprust;
1182 let def_id = self.tcx.hir.local_def_id(macro_def.id);
1184 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1185 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1186 legacy: macro_def.legacy,
1188 visibility: self.lazy(&ty::Visibility::Public),
1189 span: self.lazy(¯o_def.span),
1190 attributes: self.encode_attributes(¯o_def.attrs),
1191 stability: self.encode_stability(def_id),
1192 deprecation: self.encode_deprecation(def_id),
1194 children: LazySeq::empty(),
1196 inherent_impls: LazySeq::empty(),
1197 variances: LazySeq::empty(),
1205 fn encode_info_for_ty_param(&mut self,
1206 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1208 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1211 kind: EntryKind::Type,
1212 visibility: self.lazy(&ty::Visibility::Public),
1213 span: self.lazy(&tcx.def_span(def_id)),
1214 attributes: LazySeq::empty(),
1215 children: LazySeq::empty(),
1219 ty: if has_default {
1220 Some(self.encode_item_type(def_id))
1224 inherent_impls: LazySeq::empty(),
1225 variances: LazySeq::empty(),
1234 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1235 debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
1238 kind: EntryKind::Type,
1239 visibility: self.lazy(&ty::Visibility::Public),
1240 span: self.lazy(&tcx.def_span(def_id)),
1241 attributes: LazySeq::empty(),
1242 children: LazySeq::empty(),
1246 ty: Some(self.encode_item_type(def_id)),
1247 inherent_impls: LazySeq::empty(),
1248 variances: LazySeq::empty(),
1249 generics: Some(self.encode_generics(def_id)),
1250 predicates: Some(self.encode_predicates(def_id)),
1257 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1258 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1261 let tables = self.tcx.typeck_tables_of(def_id);
1262 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1263 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1264 let kind = match tables.node_id_to_type(hir_id).sty {
1265 ty::TyGenerator(def_id, ..) => {
1266 let layout = self.tcx.generator_layout(def_id);
1267 let data = GeneratorData {
1268 layout: layout.clone(),
1270 EntryKind::Generator(self.lazy(&data))
1273 ty::TyClosure(def_id, substs) => {
1274 let sig = substs.closure_sig(def_id, self.tcx);
1275 let data = ClosureData { sig: self.lazy(&sig) };
1276 EntryKind::Closure(self.lazy(&data))
1279 _ => bug!("closure that is neither generator nor closure")
1284 visibility: self.lazy(&ty::Visibility::Public),
1285 span: self.lazy(&tcx.def_span(def_id)),
1286 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1287 children: LazySeq::empty(),
1291 ty: Some(self.encode_item_type(def_id)),
1292 inherent_impls: LazySeq::empty(),
1293 variances: LazySeq::empty(),
1294 generics: Some(self.encode_generics(def_id)),
1298 mir: self.encode_optimized_mir(def_id),
1302 fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1303 debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
1305 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1306 let body = tcx.hir.body_owned_by(id);
1309 kind: EntryKind::Const(tcx.mir_const_qualif(def_id).0),
1310 visibility: self.lazy(&ty::Visibility::Public),
1311 span: self.lazy(&tcx.def_span(def_id)),
1312 attributes: LazySeq::empty(),
1313 children: LazySeq::empty(),
1317 ty: Some(self.encode_item_type(def_id)),
1318 inherent_impls: LazySeq::empty(),
1319 variances: LazySeq::empty(),
1320 generics: Some(self.encode_generics(def_id)),
1321 predicates: Some(self.encode_predicates(def_id)),
1323 ast: Some(self.encode_body(body)),
1324 mir: self.encode_optimized_mir(def_id),
1328 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1329 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1330 // we rely on the HashStable specialization for [Attribute]
1331 // to properly filter things out.
1332 self.lazy_seq_from_slice(attrs)
1335 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1336 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1337 self.lazy_seq(used_libraries.iter().cloned())
1340 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1341 let crates = self.tcx.crates();
1343 let mut deps = crates
1346 let dep = CrateDep {
1347 name: self.tcx.original_crate_name(cnum),
1348 hash: self.tcx.crate_hash(cnum),
1349 kind: self.tcx.dep_kind(cnum),
1353 .collect::<Vec<_>>();
1355 deps.sort_by_key(|&(cnum, _)| cnum);
1358 // Sanity-check the crate numbers
1359 let mut expected_cnum = 1;
1360 for &(n, _) in &deps {
1361 assert_eq!(n, CrateNum::new(expected_cnum));
1366 // We're just going to write a list of crate 'name-hash-version's, with
1367 // the assumption that they are numbered 1 to n.
1368 // FIXME (#2166): This is not nearly enough to support correct versioning
1369 // but is enough to get transitive crate dependencies working.
1370 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1373 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1375 let lang_items = tcx.lang_items();
1376 let lang_items = lang_items.items().iter();
1377 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1378 if let Some(def_id) = opt_def_id {
1379 if def_id.is_local() {
1380 return Some((def_id.index, i));
1387 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1389 self.lazy_seq_ref(&tcx.lang_items().missing)
1392 /// Encodes an index, mapping each trait to its (local) implementations.
1393 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1394 debug!("IsolatedEncoder::encode_impls()");
1396 let mut visitor = ImplVisitor {
1400 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1402 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1404 // Bring everything into deterministic order for hashing
1405 all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1406 tcx.def_path_hash(trait_def_id)
1409 let all_impls: Vec<_> = all_impls
1411 .map(|(trait_def_id, mut impls)| {
1412 // Bring everything into deterministic order for hashing
1413 impls.sort_unstable_by_key(|&def_index| {
1414 tcx.hir.definitions().def_path_hash(def_index)
1418 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1419 impls: self.lazy_seq_from_slice(&impls[..]),
1424 self.lazy_seq_from_slice(&all_impls[..])
1427 // Encodes all symbols exported from this crate into the metadata.
1429 // This pass is seeded off the reachability list calculated in the
1430 // middle::reachable module but filters out items that either don't have a
1431 // symbol associated with them (they weren't translated) or if they're an FFI
1432 // definition (as that's not defined in this crate).
1433 fn encode_exported_symbols(&mut self,
1434 exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1435 -> LazySeq<(ExportedSymbol, SymbolExportLevel)> {
1437 // The metadata symbol name is special. It should not show up in
1438 // downstream crates.
1439 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1441 self.lazy_seq(exported_symbols
1443 .filter(|&&(ref exported_symbol, _)| {
1444 match *exported_symbol {
1445 ExportedSymbol::NoDefId(symbol_name) => {
1446 symbol_name != metadata_symbol_name
1454 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1455 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1457 self.lazy_seq(arr.iter().map(|slot| {
1459 Linkage::NotLinked |
1460 Linkage::IncludedFromDylib => None,
1462 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1463 Linkage::Static => Some(LinkagePreference::RequireStatic),
1467 None => LazySeq::empty(),
1471 fn encode_info_for_foreign_item(&mut self,
1472 (def_id, nitem): (DefId, &hir::ForeignItem))
1476 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1478 let kind = match nitem.node {
1479 hir::ForeignItemFn(_, ref names, _) => {
1481 constness: hir::Constness::NotConst,
1482 arg_names: self.encode_fn_arg_names(names),
1483 sig: self.lazy(&tcx.fn_sig(def_id)),
1485 EntryKind::ForeignFn(self.lazy(&data))
1487 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1488 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1489 hir::ForeignItemType => EntryKind::ForeignType,
1494 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1495 span: self.lazy(&nitem.span),
1496 attributes: self.encode_attributes(&nitem.attrs),
1497 children: LazySeq::empty(),
1498 stability: self.encode_stability(def_id),
1499 deprecation: self.encode_deprecation(def_id),
1501 ty: Some(self.encode_item_type(def_id)),
1502 inherent_impls: LazySeq::empty(),
1503 variances: match nitem.node {
1504 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1505 _ => LazySeq::empty(),
1507 generics: Some(self.encode_generics(def_id)),
1508 predicates: Some(self.encode_predicates(def_id)),
1516 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1517 index: IndexBuilder<'a, 'b, 'tcx>,
1520 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1521 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1522 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1524 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1525 intravisit::walk_expr(self, ex);
1526 self.index.encode_info_for_expr(ex);
1528 fn visit_item(&mut self, item: &'tcx hir::Item) {
1529 intravisit::walk_item(self, item);
1530 let def_id = self.index.tcx.hir.local_def_id(item.id);
1532 hir::ItemExternCrate(_) |
1533 hir::ItemUse(..) => (), // ignore these
1534 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1536 self.index.encode_addl_info_for_item(item);
1538 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1539 intravisit::walk_foreign_item(self, ni);
1540 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1541 self.index.record(def_id,
1542 IsolatedEncoder::encode_info_for_foreign_item,
1545 fn visit_variant(&mut self,
1546 v: &'tcx hir::Variant,
1547 g: &'tcx hir::Generics,
1549 intravisit::walk_variant(self, v, g, id);
1551 if let Some(discr) = v.node.disr_expr {
1552 let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1553 self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1556 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1557 intravisit::walk_generics(self, generics);
1558 self.index.encode_info_for_generics(generics);
1560 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1561 intravisit::walk_ty(self, ty);
1562 self.index.encode_info_for_ty(ty);
1564 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1565 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1566 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1570 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1571 fn encode_fields(&mut self, adt_def_id: DefId) {
1572 let def = self.tcx.adt_def(adt_def_id);
1573 for (variant_index, variant) in def.variants.iter().enumerate() {
1574 for (field_index, field) in variant.fields.iter().enumerate() {
1575 self.record(field.did,
1576 IsolatedEncoder::encode_field,
1577 (adt_def_id, Untracked((variant_index, field_index))));
1582 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1583 for ty_param in generics.ty_params() {
1584 let def_id = self.tcx.hir.local_def_id(ty_param.id);
1585 let has_default = Untracked(ty_param.default.is_some());
1586 self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
1590 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1592 hir::TyImplTraitExistential(..) => {
1593 let def_id = self.tcx.hir.local_def_id(ty.id);
1594 self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
1596 hir::TyArray(_, len) => {
1597 let def_id = self.tcx.hir.body_owner_def_id(len);
1598 self.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1604 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1606 hir::ExprClosure(..) => {
1607 let def_id = self.tcx.hir.local_def_id(expr.id);
1608 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1614 /// In some cases, along with the item itself, we also
1615 /// encode some sub-items. Usually we want some info from the item
1616 /// so it's easier to do that here then to wait until we would encounter
1617 /// normally in the visitor walk.
1618 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1619 let def_id = self.tcx.hir.local_def_id(item.id);
1621 hir::ItemStatic(..) |
1622 hir::ItemConst(..) |
1625 hir::ItemForeignMod(..) |
1626 hir::ItemGlobalAsm(..) |
1627 hir::ItemExternCrate(..) |
1630 hir::ItemTraitAlias(..) => {
1631 // no sub-item recording needed in these cases
1633 hir::ItemEnum(..) => {
1634 self.encode_fields(def_id);
1636 let def = self.tcx.adt_def(def_id);
1637 for (i, variant) in def.variants.iter().enumerate() {
1638 self.record(variant.did,
1639 IsolatedEncoder::encode_enum_variant_info,
1640 (def_id, Untracked(i)));
1643 hir::ItemStruct(ref struct_def, _) => {
1644 self.encode_fields(def_id);
1646 // If the struct has a constructor, encode it.
1647 if !struct_def.is_struct() {
1648 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1649 self.record(ctor_def_id,
1650 IsolatedEncoder::encode_struct_ctor,
1651 (def_id, ctor_def_id));
1654 hir::ItemUnion(..) => {
1655 self.encode_fields(def_id);
1657 hir::ItemImpl(..) => {
1658 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1659 self.record(trait_item_def_id,
1660 IsolatedEncoder::encode_info_for_impl_item,
1664 hir::ItemTrait(..) => {
1665 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1666 self.record(item_def_id,
1667 IsolatedEncoder::encode_info_for_trait_item,
1675 struct ImplVisitor<'a, 'tcx: 'a> {
1676 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1677 impls: FxHashMap<DefId, Vec<DefIndex>>,
1680 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1681 fn visit_item(&mut self, item: &hir::Item) {
1682 if let hir::ItemImpl(..) = item.node {
1683 let impl_id = self.tcx.hir.local_def_id(item.id);
1684 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1686 .entry(trait_ref.def_id)
1688 .push(impl_id.index);
1693 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1695 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1696 // handled in `visit_item` above
1700 // NOTE(eddyb) The following comment was preserved for posterity, even
1701 // though it's no longer relevant as EBML (which uses nested & tagged
1702 // "documents") was replaced with a scheme that can't go out of bounds.
1704 // And here we run into yet another obscure archive bug: in which metadata
1705 // loaded from archives may have trailing garbage bytes. Awhile back one of
1706 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1707 // and opt) by having ebml generate an out-of-bounds panic when looking at
1710 // Upon investigation it turned out that the metadata file inside of an rlib
1711 // (and ar archive) was being corrupted. Some compilations would generate a
1712 // metadata file which would end in a few extra bytes, while other
1713 // compilations would not have these extra bytes appended to the end. These
1714 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1715 // being interpreted causing the out-of-bounds.
1717 // The root cause of why these extra bytes were appearing was never
1718 // discovered, and in the meantime the solution we're employing is to insert
1719 // the length of the metadata to the start of the metadata. Later on this
1720 // will allow us to slice the metadata to the precise length that we just
1721 // generated regardless of trailing bytes that end up in it.
1723 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1724 link_meta: &LinkMeta)
1727 let mut cursor = Cursor::new(vec![]);
1728 cursor.write_all(METADATA_HEADER).unwrap();
1730 // Will be filled with the root position after encoding everything.
1731 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1734 let mut ecx = EncodeContext {
1735 opaque: opaque::Encoder::new(&mut cursor),
1738 lazy_state: LazyState::NoNode,
1739 type_shorthands: Default::default(),
1740 predicate_shorthands: Default::default(),
1741 filemap_cache: tcx.sess.codemap().files()[0].clone(),
1742 interpret_alloc_shorthands: Default::default(),
1745 // Encode the rustc version string in a predictable location.
1746 rustc_version().encode(&mut ecx).unwrap();
1748 // Encode all the entries and extra information in the crate,
1749 // culminating in the `CrateRoot` which points to all of it.
1750 ecx.encode_crate_root()
1752 let mut result = cursor.into_inner();
1754 // Encode the root position.
1755 let header = METADATA_HEADER.len();
1756 let pos = root.position;
1757 result[header + 0] = (pos >> 24) as u8;
1758 result[header + 1] = (pos >> 16) as u8;
1759 result[header + 2] = (pos >> 8) as u8;
1760 result[header + 3] = (pos >> 0) as u8;
1762 EncodedMetadata { raw_data: result }
1765 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1766 let ty = tcx.type_of(did);
1768 ty::TyAdt(ref def, _) => return def.repr,
1769 _ => bug!("{} is not an ADT", ty),