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,
17 EncodedMetadata, ForeignModule};
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, hygiene, 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>,
63 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
64 interpret_allocs_inverse: Vec<interpret::AllocId>,
66 // This is used to speed up Span encoding.
67 filemap_cache: Lrc<FileMap>,
70 macro_rules! encoder_methods {
71 ($($name:ident($ty:ty);)*) => {
72 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
73 self.opaque.$name(value)
78 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
79 type Error = <opaque::Encoder<'a> as Encoder>::Error;
81 fn emit_nil(&mut self) -> Result<(), Self::Error> {
108 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
109 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
110 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
114 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
115 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
116 self.emit_usize(seq.len)?;
120 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
124 impl<'a, 'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'a, 'tcx> {
126 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
127 self.emit_u32(cnum.as_u32())
131 impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
133 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
144 impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
146 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
147 self.emit_u32(def_index.as_raw_u32())
151 impl<'a, 'tcx> SpecializedEncoder<Span> for EncodeContext<'a, 'tcx> {
152 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
153 if *span == DUMMY_SP {
154 return TAG_INVALID_SPAN.encode(self)
157 let span = span.data();
159 // The Span infrastructure should make sure that this invariant holds:
160 debug_assert!(span.lo <= span.hi);
162 if !self.filemap_cache.contains(span.lo) {
163 let codemap = self.tcx.sess.codemap();
164 let filemap_index = codemap.lookup_filemap_idx(span.lo);
165 self.filemap_cache = codemap.files()[filemap_index].clone();
168 if !self.filemap_cache.contains(span.hi) {
169 // Unfortunately, macro expansion still sometimes generates Spans
170 // that malformed in this way.
171 return TAG_INVALID_SPAN.encode(self)
174 TAG_VALID_SPAN.encode(self)?;
175 span.lo.encode(self)?;
177 // Encode length which is usually less than span.hi and profits more
178 // from the variable-length integer encoding that we use.
179 let len = span.hi - span.lo;
182 // Don't encode the expansion context.
186 impl<'a, 'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'a, 'tcx> {
188 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
189 self.specialized_encode(&def_id.to_def_id())
193 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
194 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
195 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
199 impl<'a, 'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'a, 'tcx> {
200 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
201 use std::collections::hash_map::Entry;
202 let index = match self.interpret_allocs.entry(*alloc_id) {
203 Entry::Occupied(e) => *e.get(),
204 Entry::Vacant(e) => {
205 let idx = self.interpret_allocs_inverse.len();
206 self.interpret_allocs_inverse.push(*alloc_id);
216 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
217 fn specialized_encode(&mut self,
218 predicates: &ty::GenericPredicates<'tcx>)
219 -> Result<(), Self::Error> {
220 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
224 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
225 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
226 f.encode_opaque(&mut self.opaque)
230 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
231 for EncodeContext<'a, 'tcx> {
232 fn specialized_encode(&mut self,
233 _: &mir::ClearCrossCrate<T>)
234 -> Result<(), Self::Error> {
239 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
240 fn position(&self) -> usize {
241 self.opaque.position()
245 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
247 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
248 assert_eq!(self.lazy_state, LazyState::NoNode);
249 let pos = self.position();
250 self.lazy_state = LazyState::NodeStart(pos);
251 let r = f(self, pos);
252 self.lazy_state = LazyState::NoNode;
256 fn emit_lazy_distance(&mut self,
259 -> Result<(), <Self as Encoder>::Error> {
260 let min_end = position + min_size;
261 let distance = match self.lazy_state {
262 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
263 LazyState::NodeStart(start) => {
264 assert!(min_end <= start);
267 LazyState::Previous(last_min_end) => {
269 last_min_end <= position,
270 "make sure that the calls to `lazy*` \
271 are in the same order as the metadata fields",
273 position - last_min_end
276 self.lazy_state = LazyState::Previous(min_end);
277 self.emit_usize(distance)
280 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
281 self.emit_node(|ecx, pos| {
282 value.encode(ecx).unwrap();
284 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
285 Lazy::with_position(pos)
289 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
290 where I: IntoIterator<Item = T>,
293 self.emit_node(|ecx, pos| {
294 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
296 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
297 LazySeq::with_position_and_length(pos, len)
301 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
302 where I: IntoIterator<Item = &'b T>,
305 self.emit_node(|ecx, pos| {
306 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
308 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
309 LazySeq::with_position_and_length(pos, len)
313 // Encodes something that corresponds to a single DepNode::GlobalMetaData
314 // and registers the Fingerprint in the `metadata_hashes` map.
315 pub fn tracked<'x, DATA, R>(&'x mut self,
316 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
319 op(&mut IsolatedEncoder::new(self), data)
322 fn encode_info_for_items(&mut self) -> Index {
323 let krate = self.tcx.hir.krate();
324 let mut index = IndexBuilder::new(self);
325 index.record(DefId::local(CRATE_DEF_INDEX),
326 IsolatedEncoder::encode_info_for_mod,
327 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
328 let mut visitor = EncodeVisitor { index: index };
329 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
330 for macro_def in &krate.exported_macros {
331 visitor.visit_macro_def(macro_def);
333 visitor.index.into_items()
336 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
337 let definitions = self.tcx.hir.definitions();
338 self.lazy(definitions.def_path_table())
341 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
342 let codemap = self.tcx.sess.codemap();
343 let all_filemaps = codemap.files();
345 let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
347 let adapted = all_filemaps.iter()
349 // No need to re-export imported filemaps, as any downstream
350 // crate will import them from their original source.
351 !filemap.is_imported()
354 // When exporting FileMaps, we expand all paths to absolute
355 // paths because any relative paths are potentially relative to
356 // a wrong directory.
357 // However, if a path has been modified via
358 // `--remap-path-prefix` we assume the user has already set
359 // things up the way they want and don't touch the path values
362 FileName::Real(ref name) => {
363 if filemap.name_was_remapped ||
364 (name.is_relative() && working_dir_was_remapped) {
365 // This path of this FileMap has been modified by
366 // path-remapping, so we use it verbatim (and avoid cloning
367 // the whole map in the process).
370 let mut adapted = (**filemap).clone();
371 adapted.name = Path::new(&working_dir).join(name).into();
372 adapted.name_hash = {
373 let mut hasher: StableHasher<u128> = StableHasher::new();
374 adapted.name.hash(&mut hasher);
380 // expanded code, not from a file
381 _ => filemap.clone(),
384 .collect::<Vec<_>>();
386 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
389 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
390 let mut i = self.position();
392 let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
393 let dylib_dependency_formats = self.tracked(
394 IsolatedEncoder::encode_dylib_dependency_formats,
396 let dep_bytes = self.position() - i;
398 // Encode the language items.
400 let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
401 let lang_items_missing = self.tracked(
402 IsolatedEncoder::encode_lang_items_missing,
404 let lang_item_bytes = self.position() - i;
406 // Encode the native libraries used
408 let native_libraries = self.tracked(
409 IsolatedEncoder::encode_native_libraries,
411 let native_lib_bytes = self.position() - i;
413 let foreign_modules = self.tracked(
414 IsolatedEncoder::encode_foreign_modules,
419 let codemap = self.encode_codemap();
420 let codemap_bytes = self.position() - i;
422 // Encode DefPathTable
424 let def_path_table = self.encode_def_path_table();
425 let def_path_table_bytes = self.position() - i;
427 // Encode the def IDs of impls, for coherence checking.
429 let impls = self.tracked(IsolatedEncoder::encode_impls, ());
430 let impl_bytes = self.position() - i;
432 // Encode exported symbols info.
434 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
435 let exported_symbols = self.tracked(
436 IsolatedEncoder::encode_exported_symbols,
438 let exported_symbols_bytes = self.position() - i;
440 // encode wasm custom sections
441 let wasm_custom_sections = self.tcx.wasm_custom_sections(LOCAL_CRATE);
442 let wasm_custom_sections = self.tracked(
443 IsolatedEncoder::encode_wasm_custom_sections,
444 &wasm_custom_sections);
450 let items = self.encode_info_for_items();
451 let item_bytes = self.position() - i;
453 // Encode the allocation index
454 let interpret_alloc_index = {
455 let mut interpret_alloc_index = Vec::new();
457 trace!("beginning to encode alloc ids");
459 let new_n = self.interpret_allocs_inverse.len();
460 // if we have found new ids, serialize those, too
465 trace!("encoding {} further alloc ids", new_n - n);
466 for idx in n..new_n {
467 let id = self.interpret_allocs_inverse[idx];
468 let pos = self.position() as u32;
469 interpret_alloc_index.push(pos);
470 interpret::specialized_encode_alloc_id(
478 self.lazy_seq(interpret_alloc_index)
483 let index = items.write_index(&mut self.opaque.cursor);
484 let index_bytes = self.position() - i;
486 let attrs = tcx.hir.krate_attrs();
487 let link_meta = self.link_meta;
488 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
489 let has_default_lib_allocator = attr::contains_name(&attrs, "default_lib_allocator");
490 let has_global_allocator = *tcx.sess.has_global_allocator.get();
492 let root = self.lazy(&CrateRoot {
493 name: tcx.crate_name(LOCAL_CRATE),
494 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
495 triple: tcx.sess.opts.target_triple.clone(),
496 hash: link_meta.crate_hash,
497 disambiguator: tcx.sess.local_crate_disambiguator(),
498 panic_strategy: tcx.sess.panic_strategy(),
499 edition: hygiene::default_edition(),
500 has_global_allocator: has_global_allocator,
501 has_default_lib_allocator: has_default_lib_allocator,
502 plugin_registrar_fn: tcx.sess
505 .map(|id| tcx.hir.local_def_id(id).index),
506 macro_derive_registrar: if is_proc_macro {
507 let id = tcx.sess.derive_registrar_fn.get().unwrap();
508 Some(tcx.hir.local_def_id(id).index)
513 compiler_builtins: attr::contains_name(&attrs, "compiler_builtins"),
514 needs_allocator: attr::contains_name(&attrs, "needs_allocator"),
515 needs_panic_runtime: attr::contains_name(&attrs, "needs_panic_runtime"),
516 no_builtins: attr::contains_name(&attrs, "no_builtins"),
517 panic_runtime: attr::contains_name(&attrs, "panic_runtime"),
518 profiler_runtime: attr::contains_name(&attrs, "profiler_runtime"),
519 sanitizer_runtime: attr::contains_name(&attrs, "sanitizer_runtime"),
522 dylib_dependency_formats,
531 wasm_custom_sections,
532 interpret_alloc_index,
536 let total_bytes = self.position();
538 if self.tcx.sess.meta_stats() {
539 let mut zero_bytes = 0;
540 for e in self.opaque.cursor.get_ref() {
546 println!("metadata stats:");
547 println!(" dep bytes: {}", dep_bytes);
548 println!(" lang item bytes: {}", lang_item_bytes);
549 println!(" native bytes: {}", native_lib_bytes);
550 println!(" codemap bytes: {}", codemap_bytes);
551 println!(" impl bytes: {}", impl_bytes);
552 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
553 println!(" def-path table bytes: {}", def_path_table_bytes);
554 println!(" item bytes: {}", item_bytes);
555 println!(" index bytes: {}", index_bytes);
556 println!(" zero bytes: {}", zero_bytes);
557 println!(" total bytes: {}", total_bytes);
564 // These are methods for encoding various things. They are meant to be used with
565 // IndexBuilder::record() and EncodeContext::tracked(). They actually
566 // would not have to be methods of IsolatedEncoder (free standing functions
567 // taking IsolatedEncoder as first argument would be just fine) but by making
568 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
569 // clause again and again.
570 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
571 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
572 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
574 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
577 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
579 let ty = tcx.type_of(def_id);
580 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
584 /// Encode data for the given variant of the given ADT. The
585 /// index of the variant is untracked: this is ok because we
586 /// will have to lookup the adt-def by its id, and that gives us
587 /// the right to access any information in the adt-def (including,
588 /// e.g., the length of the various vectors).
589 fn encode_enum_variant_info(&mut self,
590 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
593 let def = tcx.adt_def(enum_did);
594 let variant = &def.variants[index];
595 let def_id = variant.did;
596 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
598 let data = VariantData {
599 ctor_kind: variant.ctor_kind,
600 discr: variant.discr,
602 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
603 Some(self.lazy(&tcx.fn_sig(def_id)))
609 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
610 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
613 kind: EntryKind::Variant(self.lazy(&data)),
614 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
615 span: self.lazy(&tcx.def_span(def_id)),
616 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
617 children: self.lazy_seq(variant.fields.iter().map(|f| {
618 assert!(f.did.is_local());
621 stability: self.encode_stability(def_id),
622 deprecation: self.encode_deprecation(def_id),
624 ty: Some(self.encode_item_type(def_id)),
625 inherent_impls: LazySeq::empty(),
626 variances: if variant.ctor_kind == CtorKind::Fn {
627 self.encode_variances_of(def_id)
631 generics: Some(self.encode_generics(def_id)),
632 predicates: Some(self.encode_predicates(def_id)),
634 mir: self.encode_optimized_mir(def_id),
638 fn encode_info_for_mod(&mut self,
639 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
644 let def_id = tcx.hir.local_def_id(id);
645 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
648 reexports: match tcx.module_exports(def_id) {
649 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
650 _ => LazySeq::empty(),
655 kind: EntryKind::Mod(self.lazy(&data)),
656 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
657 span: self.lazy(&tcx.def_span(def_id)),
658 attributes: self.encode_attributes(attrs),
659 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
660 tcx.hir.local_def_id(item_id.id).index
662 stability: self.encode_stability(def_id),
663 deprecation: self.encode_deprecation(def_id),
666 inherent_impls: LazySeq::empty(),
667 variances: LazySeq::empty(),
675 /// Encode data for the given field of the given variant of the
676 /// given ADT. The indices of the variant/field are untracked:
677 /// this is ok because we will have to lookup the adt-def by its
678 /// id, and that gives us the right to access any information in
679 /// the adt-def (including, e.g., the length of the various
681 fn encode_field(&mut self,
682 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
687 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
688 let field = &variant.fields[field_index];
690 let def_id = field.did;
691 debug!("IsolatedEncoder::encode_field({:?})", def_id);
693 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
694 let variant_data = tcx.hir.expect_variant_data(variant_id);
697 kind: EntryKind::Field,
698 visibility: self.lazy(&field.vis),
699 span: self.lazy(&tcx.def_span(def_id)),
700 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
701 children: LazySeq::empty(),
702 stability: self.encode_stability(def_id),
703 deprecation: self.encode_deprecation(def_id),
705 ty: Some(self.encode_item_type(def_id)),
706 inherent_impls: LazySeq::empty(),
707 variances: LazySeq::empty(),
708 generics: Some(self.encode_generics(def_id)),
709 predicates: Some(self.encode_predicates(def_id)),
715 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
716 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
718 let adt_def = tcx.adt_def(adt_def_id);
719 let variant = adt_def.non_enum_variant();
721 let data = VariantData {
722 ctor_kind: variant.ctor_kind,
723 discr: variant.discr,
724 struct_ctor: Some(def_id.index),
725 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
726 Some(self.lazy(&tcx.fn_sig(def_id)))
732 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
733 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
734 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
735 for field in &variant.fields {
736 if ctor_vis.is_at_least(field.vis, tcx) {
737 ctor_vis = field.vis;
741 // If the structure is marked as non_exhaustive then lower the visibility
742 // to within the crate.
743 if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
744 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
747 let repr_options = get_repr_options(&tcx, adt_def_id);
750 kind: EntryKind::Struct(self.lazy(&data), repr_options),
751 visibility: self.lazy(&ctor_vis),
752 span: self.lazy(&tcx.def_span(def_id)),
753 attributes: LazySeq::empty(),
754 children: LazySeq::empty(),
755 stability: self.encode_stability(def_id),
756 deprecation: self.encode_deprecation(def_id),
758 ty: Some(self.encode_item_type(def_id)),
759 inherent_impls: LazySeq::empty(),
760 variances: if variant.ctor_kind == CtorKind::Fn {
761 self.encode_variances_of(def_id)
765 generics: Some(self.encode_generics(def_id)),
766 predicates: Some(self.encode_predicates(def_id)),
768 mir: self.encode_optimized_mir(def_id),
772 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
773 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
775 self.lazy(tcx.generics_of(def_id))
778 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
779 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
781 self.lazy(&tcx.predicates_of(def_id))
784 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
785 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
788 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
789 let ast_item = tcx.hir.expect_trait_item(node_id);
790 let trait_item = tcx.associated_item(def_id);
792 let container = match trait_item.defaultness {
793 hir::Defaultness::Default { has_value: true } =>
794 AssociatedContainer::TraitWithDefault,
795 hir::Defaultness::Default { has_value: false } =>
796 AssociatedContainer::TraitRequired,
797 hir::Defaultness::Final =>
798 span_bug!(ast_item.span, "traits cannot have final items"),
801 let kind = match trait_item.kind {
802 ty::AssociatedKind::Const => {
804 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
805 self.const_qualif(0, body)
807 ConstQualif { mir: 0, ast_promotable: false }
811 hir::print::to_string(&self.tcx.hir, |s| s.print_trait_item(ast_item));
812 let rendered_const = self.lazy(&RenderedConst(rendered));
814 EntryKind::AssociatedConst(container, const_qualif, rendered_const)
816 ty::AssociatedKind::Method => {
817 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
818 let arg_names = match *m {
819 hir::TraitMethod::Required(ref names) => {
820 self.encode_fn_arg_names(names)
822 hir::TraitMethod::Provided(body) => {
823 self.encode_fn_arg_names_for_body(body)
827 constness: hir::Constness::NotConst,
829 sig: self.lazy(&tcx.fn_sig(def_id)),
834 EntryKind::Method(self.lazy(&MethodData {
837 has_self: trait_item.method_has_self_argument,
840 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
845 visibility: self.lazy(&trait_item.vis),
846 span: self.lazy(&ast_item.span),
847 attributes: self.encode_attributes(&ast_item.attrs),
848 children: LazySeq::empty(),
849 stability: self.encode_stability(def_id),
850 deprecation: self.encode_deprecation(def_id),
852 ty: match trait_item.kind {
853 ty::AssociatedKind::Const |
854 ty::AssociatedKind::Method => {
855 Some(self.encode_item_type(def_id))
857 ty::AssociatedKind::Type => {
858 if trait_item.defaultness.has_value() {
859 Some(self.encode_item_type(def_id))
865 inherent_impls: LazySeq::empty(),
866 variances: if trait_item.kind == ty::AssociatedKind::Method {
867 self.encode_variances_of(def_id)
871 generics: Some(self.encode_generics(def_id)),
872 predicates: Some(self.encode_predicates(def_id)),
874 mir: self.encode_optimized_mir(def_id),
878 fn metadata_output_only(&self) -> bool {
879 // MIR optimisation can be skipped when we're just interested in the metadata.
880 !self.tcx.sess.opts.output_types.should_codegen()
883 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
884 let body_owner_def_id = self.tcx.hir.body_owner_def_id(body_id);
885 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
887 ConstQualif { mir, ast_promotable }
890 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
891 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
894 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
895 let ast_item = self.tcx.hir.expect_impl_item(node_id);
896 let impl_item = self.tcx.associated_item(def_id);
898 let container = match impl_item.defaultness {
899 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
900 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
901 hir::Defaultness::Default { has_value: false } =>
902 span_bug!(ast_item.span, "impl items always have values (currently)"),
905 let kind = match impl_item.kind {
906 ty::AssociatedKind::Const => {
907 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
908 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
910 EntryKind::AssociatedConst(container,
911 self.const_qualif(mir, body_id),
912 self.encode_rendered_const_for_body(body_id))
917 ty::AssociatedKind::Method => {
918 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
920 constness: sig.header.constness,
921 arg_names: self.encode_fn_arg_names_for_body(body),
922 sig: self.lazy(&tcx.fn_sig(def_id)),
927 EntryKind::Method(self.lazy(&MethodData {
930 has_self: impl_item.method_has_self_argument,
933 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
937 match ast_item.node {
938 hir::ImplItemKind::Const(..) => true,
939 hir::ImplItemKind::Method(ref sig, _) => {
940 let generics = self.tcx.generics_of(def_id);
941 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
942 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
943 !self.metadata_output_only();
944 let is_const_fn = sig.header.constness == hir::Constness::Const;
945 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
946 needs_inline || is_const_fn || always_encode_mir
948 hir::ImplItemKind::Type(..) => false,
953 visibility: self.lazy(&impl_item.vis),
954 span: self.lazy(&ast_item.span),
955 attributes: self.encode_attributes(&ast_item.attrs),
956 children: LazySeq::empty(),
957 stability: self.encode_stability(def_id),
958 deprecation: self.encode_deprecation(def_id),
960 ty: Some(self.encode_item_type(def_id)),
961 inherent_impls: LazySeq::empty(),
962 variances: if impl_item.kind == ty::AssociatedKind::Method {
963 self.encode_variances_of(def_id)
967 generics: Some(self.encode_generics(def_id)),
968 predicates: Some(self.encode_predicates(def_id)),
970 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
974 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
975 -> LazySeq<ast::Name> {
976 self.tcx.dep_graph.with_ignore(|| {
977 let body = self.tcx.hir.body(body_id);
978 self.lazy_seq(body.arguments.iter().map(|arg| {
980 PatKind::Binding(_, _, name, _) => name.node,
981 _ => Symbol::intern("")
987 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
988 -> LazySeq<ast::Name> {
989 self.lazy_seq(names.iter().map(|name| name.node))
992 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
993 debug!("EntryBuilder::encode_mir({:?})", def_id);
994 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
995 let mir = self.tcx.optimized_mir(def_id);
996 Some(self.lazy(&mir))
1002 // Encodes the inherent implementations of a structure, enumeration, or trait.
1003 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1004 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
1005 let implementations = self.tcx.inherent_impls(def_id);
1006 if implementations.is_empty() {
1009 self.lazy_seq(implementations.iter().map(|&def_id| {
1010 assert!(def_id.is_local());
1016 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1017 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
1018 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1021 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1022 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
1023 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1026 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1027 let body = self.tcx.hir.body(body_id);
1028 let rendered = hir::print::to_string(&self.tcx.hir, |s| s.print_expr(&body.value));
1029 let rendered_const = &RenderedConst(rendered);
1030 self.lazy(rendered_const)
1033 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1036 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
1038 let kind = match item.node {
1039 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
1040 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1041 hir::ItemConst(_, body_id) => {
1042 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1044 self.const_qualif(mir, body_id),
1045 self.encode_rendered_const_for_body(body_id)
1048 hir::ItemFn(_, header, .., body) => {
1050 constness: header.constness,
1051 arg_names: self.encode_fn_arg_names_for_body(body),
1052 sig: self.lazy(&tcx.fn_sig(def_id)),
1055 EntryKind::Fn(self.lazy(&data))
1057 hir::ItemMod(ref m) => {
1058 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
1060 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
1061 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
1062 hir::ItemTy(..) => EntryKind::Type,
1063 hir::ItemExistential(..) => EntryKind::Existential,
1064 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
1065 hir::ItemStruct(ref struct_def, _) => {
1066 let variant = tcx.adt_def(def_id).non_enum_variant();
1068 // Encode def_ids for each field and method
1069 // for methods, write all the stuff get_trait_method
1071 let struct_ctor = if !struct_def.is_struct() {
1072 Some(tcx.hir.local_def_id(struct_def.id()).index)
1077 let repr_options = get_repr_options(&tcx, def_id);
1079 EntryKind::Struct(self.lazy(&VariantData {
1080 ctor_kind: variant.ctor_kind,
1081 discr: variant.discr,
1086 hir::ItemUnion(..) => {
1087 let variant = tcx.adt_def(def_id).non_enum_variant();
1088 let repr_options = get_repr_options(&tcx, def_id);
1090 EntryKind::Union(self.lazy(&VariantData {
1091 ctor_kind: variant.ctor_kind,
1092 discr: variant.discr,
1097 hir::ItemImpl(_, polarity, defaultness, ..) => {
1098 let trait_ref = tcx.impl_trait_ref(def_id);
1099 let parent = if let Some(trait_ref) = trait_ref {
1100 let trait_def = tcx.trait_def(trait_ref.def_id);
1101 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
1103 specialization_graph::Node::Impl(parent) => Some(parent),
1111 // if this is an impl of `CoerceUnsized`, create its
1112 // "unsized info", else just store None
1113 let coerce_unsized_info =
1114 trait_ref.and_then(|t| {
1115 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1116 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1122 let data = ImplData {
1125 parent_impl: parent,
1126 coerce_unsized_info,
1127 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1130 EntryKind::Impl(self.lazy(&data))
1132 hir::ItemTrait(..) => {
1133 let trait_def = tcx.trait_def(def_id);
1134 let data = TraitData {
1135 unsafety: trait_def.unsafety,
1136 paren_sugar: trait_def.paren_sugar,
1137 has_auto_impl: tcx.trait_is_auto(def_id),
1138 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1141 EntryKind::Trait(self.lazy(&data))
1143 hir::ItemExternCrate(_) |
1144 hir::ItemTraitAlias(..) |
1145 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1150 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1151 span: self.lazy(&item.span),
1152 attributes: self.encode_attributes(&item.attrs),
1153 children: match item.node {
1154 hir::ItemForeignMod(ref fm) => {
1155 self.lazy_seq(fm.items
1157 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1159 hir::ItemEnum(..) => {
1160 let def = self.tcx.adt_def(def_id);
1161 self.lazy_seq(def.variants.iter().map(|v| {
1162 assert!(v.did.is_local());
1166 hir::ItemStruct(..) |
1167 hir::ItemUnion(..) => {
1168 let def = self.tcx.adt_def(def_id);
1169 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1170 assert!(f.did.is_local());
1175 hir::ItemTrait(..) => {
1176 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1177 assert!(def_id.is_local());
1181 _ => LazySeq::empty(),
1183 stability: self.encode_stability(def_id),
1184 deprecation: self.encode_deprecation(def_id),
1186 ty: match item.node {
1187 hir::ItemStatic(..) |
1188 hir::ItemConst(..) |
1191 hir::ItemExistential(..) |
1193 hir::ItemStruct(..) |
1194 hir::ItemUnion(..) |
1195 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1198 inherent_impls: self.encode_inherent_implementations(def_id),
1199 variances: match item.node {
1201 hir::ItemStruct(..) |
1202 hir::ItemUnion(..) |
1203 hir::ItemFn(..) => self.encode_variances_of(def_id),
1204 _ => LazySeq::empty(),
1206 generics: match item.node {
1207 hir::ItemStatic(..) |
1208 hir::ItemConst(..) |
1212 hir::ItemStruct(..) |
1213 hir::ItemUnion(..) |
1215 hir::ItemExistential(..) |
1216 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1219 predicates: match item.node {
1220 hir::ItemStatic(..) |
1221 hir::ItemConst(..) |
1225 hir::ItemStruct(..) |
1226 hir::ItemUnion(..) |
1228 hir::ItemExistential(..) |
1229 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1233 mir: match item.node {
1234 hir::ItemStatic(..) => {
1235 self.encode_optimized_mir(def_id)
1237 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1238 hir::ItemFn(_, header, ..) => {
1239 let generics = tcx.generics_of(def_id);
1240 let has_types = generics.params.iter().any(|param| match param.kind {
1241 ty::GenericParamDefKind::Type { .. } => true,
1245 (has_types || tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1246 !self.metadata_output_only();
1247 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1249 || header.constness == hir::Constness::Const
1250 || always_encode_mir
1252 self.encode_optimized_mir(def_id)
1262 /// Serialize the text of exported macros
1263 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1264 use syntax::print::pprust;
1265 let def_id = self.tcx.hir.local_def_id(macro_def.id);
1267 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1268 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1269 legacy: macro_def.legacy,
1271 visibility: self.lazy(&ty::Visibility::Public),
1272 span: self.lazy(¯o_def.span),
1273 attributes: self.encode_attributes(¯o_def.attrs),
1274 stability: self.encode_stability(def_id),
1275 deprecation: self.encode_deprecation(def_id),
1277 children: LazySeq::empty(),
1279 inherent_impls: LazySeq::empty(),
1280 variances: LazySeq::empty(),
1287 fn encode_info_for_ty_param(&mut self,
1288 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1290 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1293 kind: EntryKind::Type,
1294 visibility: self.lazy(&ty::Visibility::Public),
1295 span: self.lazy(&tcx.def_span(def_id)),
1296 attributes: LazySeq::empty(),
1297 children: LazySeq::empty(),
1301 ty: if has_default {
1302 Some(self.encode_item_type(def_id))
1306 inherent_impls: LazySeq::empty(),
1307 variances: LazySeq::empty(),
1315 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1316 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1319 let tables = self.tcx.typeck_tables_of(def_id);
1320 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1321 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1322 let kind = match tables.node_id_to_type(hir_id).sty {
1323 ty::TyGenerator(def_id, ..) => {
1324 let layout = self.tcx.generator_layout(def_id);
1325 let data = GeneratorData {
1326 layout: layout.clone(),
1328 EntryKind::Generator(self.lazy(&data))
1331 ty::TyClosure(def_id, substs) => {
1332 let sig = substs.closure_sig(def_id, self.tcx);
1333 let data = ClosureData { sig: self.lazy(&sig) };
1334 EntryKind::Closure(self.lazy(&data))
1337 _ => bug!("closure that is neither generator nor closure")
1342 visibility: self.lazy(&ty::Visibility::Public),
1343 span: self.lazy(&tcx.def_span(def_id)),
1344 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1345 children: LazySeq::empty(),
1349 ty: Some(self.encode_item_type(def_id)),
1350 inherent_impls: LazySeq::empty(),
1351 variances: LazySeq::empty(),
1352 generics: Some(self.encode_generics(def_id)),
1355 mir: self.encode_optimized_mir(def_id),
1359 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1360 debug!("IsolatedEncoder::encode_info_for_anon_const({:?})", def_id);
1362 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1363 let body_id = tcx.hir.body_owned_by(id);
1364 let const_data = self.encode_rendered_const_for_body(body_id);
1365 let mir = tcx.mir_const_qualif(def_id).0;
1368 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1369 visibility: self.lazy(&ty::Visibility::Public),
1370 span: self.lazy(&tcx.def_span(def_id)),
1371 attributes: LazySeq::empty(),
1372 children: LazySeq::empty(),
1376 ty: Some(self.encode_item_type(def_id)),
1377 inherent_impls: LazySeq::empty(),
1378 variances: LazySeq::empty(),
1379 generics: Some(self.encode_generics(def_id)),
1380 predicates: Some(self.encode_predicates(def_id)),
1382 mir: self.encode_optimized_mir(def_id),
1386 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1387 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1388 // we rely on the HashStable specialization for [Attribute]
1389 // to properly filter things out.
1390 self.lazy_seq_from_slice(attrs)
1393 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1394 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1395 self.lazy_seq(used_libraries.iter().cloned())
1398 fn encode_foreign_modules(&mut self, _: ()) -> LazySeq<ForeignModule> {
1399 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1400 self.lazy_seq(foreign_modules.iter().cloned())
1403 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1404 let crates = self.tcx.crates();
1406 let mut deps = crates
1409 let dep = CrateDep {
1410 name: self.tcx.original_crate_name(cnum),
1411 hash: self.tcx.crate_hash(cnum),
1412 kind: self.tcx.dep_kind(cnum),
1413 extra_filename: self.tcx.extra_filename(cnum),
1417 .collect::<Vec<_>>();
1419 deps.sort_by_key(|&(cnum, _)| cnum);
1422 // Sanity-check the crate numbers
1423 let mut expected_cnum = 1;
1424 for &(n, _) in &deps {
1425 assert_eq!(n, CrateNum::new(expected_cnum));
1430 // We're just going to write a list of crate 'name-hash-version's, with
1431 // the assumption that they are numbered 1 to n.
1432 // FIXME (#2166): This is not nearly enough to support correct versioning
1433 // but is enough to get transitive crate dependencies working.
1434 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1437 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1439 let lang_items = tcx.lang_items();
1440 let lang_items = lang_items.items().iter();
1441 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1442 if let Some(def_id) = opt_def_id {
1443 if def_id.is_local() {
1444 return Some((def_id.index, i));
1451 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1453 self.lazy_seq_ref(&tcx.lang_items().missing)
1456 /// Encodes an index, mapping each trait to its (local) implementations.
1457 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1458 debug!("IsolatedEncoder::encode_impls()");
1460 let mut visitor = ImplVisitor {
1464 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1466 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1468 // Bring everything into deterministic order for hashing
1469 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1470 tcx.def_path_hash(trait_def_id)
1473 let all_impls: Vec<_> = all_impls
1475 .map(|(trait_def_id, mut impls)| {
1476 // Bring everything into deterministic order for hashing
1477 impls.sort_by_cached_key(|&def_index| {
1478 tcx.hir.definitions().def_path_hash(def_index)
1482 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1483 impls: self.lazy_seq_from_slice(&impls[..]),
1488 self.lazy_seq_from_slice(&all_impls[..])
1491 // Encodes all symbols exported from this crate into the metadata.
1493 // This pass is seeded off the reachability list calculated in the
1494 // middle::reachable module but filters out items that either don't have a
1495 // symbol associated with them (they weren't translated) or if they're an FFI
1496 // definition (as that's not defined in this crate).
1497 fn encode_exported_symbols(&mut self,
1498 exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1499 -> EncodedExportedSymbols {
1500 // The metadata symbol name is special. It should not show up in
1501 // downstream crates.
1502 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1504 let lazy_seq = self.lazy_seq(exported_symbols
1506 .filter(|&&(ref exported_symbol, _)| {
1507 match *exported_symbol {
1508 ExportedSymbol::NoDefId(symbol_name) => {
1509 symbol_name != metadata_symbol_name
1516 EncodedExportedSymbols {
1518 position: lazy_seq.position,
1522 fn encode_wasm_custom_sections(&mut self, statics: &[DefId]) -> LazySeq<DefIndex> {
1523 info!("encoding custom wasm section constants {:?}", statics);
1524 self.lazy_seq(statics.iter().map(|id| id.index))
1527 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1528 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1530 self.lazy_seq(arr.iter().map(|slot| {
1532 Linkage::NotLinked |
1533 Linkage::IncludedFromDylib => None,
1535 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1536 Linkage::Static => Some(LinkagePreference::RequireStatic),
1540 None => LazySeq::empty(),
1544 fn encode_info_for_foreign_item(&mut self,
1545 (def_id, nitem): (DefId, &hir::ForeignItem))
1549 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1551 let kind = match nitem.node {
1552 hir::ForeignItemFn(_, ref names, _) => {
1554 constness: hir::Constness::NotConst,
1555 arg_names: self.encode_fn_arg_names(names),
1556 sig: self.lazy(&tcx.fn_sig(def_id)),
1558 EntryKind::ForeignFn(self.lazy(&data))
1560 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1561 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1562 hir::ForeignItemType => EntryKind::ForeignType,
1567 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1568 span: self.lazy(&nitem.span),
1569 attributes: self.encode_attributes(&nitem.attrs),
1570 children: LazySeq::empty(),
1571 stability: self.encode_stability(def_id),
1572 deprecation: self.encode_deprecation(def_id),
1574 ty: Some(self.encode_item_type(def_id)),
1575 inherent_impls: LazySeq::empty(),
1576 variances: match nitem.node {
1577 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1578 _ => LazySeq::empty(),
1580 generics: Some(self.encode_generics(def_id)),
1581 predicates: Some(self.encode_predicates(def_id)),
1588 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1589 index: IndexBuilder<'a, 'b, 'tcx>,
1592 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1593 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1594 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1596 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1597 intravisit::walk_expr(self, ex);
1598 self.index.encode_info_for_expr(ex);
1600 fn visit_item(&mut self, item: &'tcx hir::Item) {
1601 intravisit::walk_item(self, item);
1602 let def_id = self.index.tcx.hir.local_def_id(item.id);
1604 hir::ItemExternCrate(_) |
1605 hir::ItemUse(..) => (), // ignore these
1606 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1608 self.index.encode_addl_info_for_item(item);
1610 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1611 intravisit::walk_foreign_item(self, ni);
1612 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1613 self.index.record(def_id,
1614 IsolatedEncoder::encode_info_for_foreign_item,
1617 fn visit_variant(&mut self,
1618 v: &'tcx hir::Variant,
1619 g: &'tcx hir::Generics,
1621 intravisit::walk_variant(self, v, g, id);
1623 if let Some(ref discr) = v.node.disr_expr {
1624 let def_id = self.index.tcx.hir.local_def_id(discr.id);
1625 self.index.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1628 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1629 intravisit::walk_generics(self, generics);
1630 self.index.encode_info_for_generics(generics);
1632 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1633 intravisit::walk_ty(self, ty);
1634 self.index.encode_info_for_ty(ty);
1636 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1637 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1638 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1642 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1643 fn encode_fields(&mut self, adt_def_id: DefId) {
1644 let def = self.tcx.adt_def(adt_def_id);
1645 for (variant_index, variant) in def.variants.iter().enumerate() {
1646 for (field_index, field) in variant.fields.iter().enumerate() {
1647 self.record(field.did,
1648 IsolatedEncoder::encode_field,
1649 (adt_def_id, Untracked((variant_index, field_index))));
1654 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1655 generics.params.iter().for_each(|param| match param.kind {
1656 hir::GenericParamKind::Lifetime { .. } => {}
1657 hir::GenericParamKind::Type { ref default, .. } => {
1658 let def_id = self.tcx.hir.local_def_id(param.id);
1659 let has_default = Untracked(default.is_some());
1660 let encode_info = IsolatedEncoder::encode_info_for_ty_param;
1661 self.record(def_id, encode_info, (def_id, has_default));
1666 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1668 hir::TyArray(_, ref length) => {
1669 let def_id = self.tcx.hir.local_def_id(length.id);
1670 self.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1676 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1678 hir::ExprClosure(..) => {
1679 let def_id = self.tcx.hir.local_def_id(expr.id);
1680 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1686 /// In some cases, along with the item itself, we also
1687 /// encode some sub-items. Usually we want some info from the item
1688 /// so it's easier to do that here then to wait until we would encounter
1689 /// normally in the visitor walk.
1690 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1691 let def_id = self.tcx.hir.local_def_id(item.id);
1693 hir::ItemStatic(..) |
1694 hir::ItemConst(..) |
1697 hir::ItemForeignMod(..) |
1698 hir::ItemGlobalAsm(..) |
1699 hir::ItemExternCrate(..) |
1702 hir::ItemExistential(..) |
1703 hir::ItemTraitAlias(..) => {
1704 // no sub-item recording needed in these cases
1706 hir::ItemEnum(..) => {
1707 self.encode_fields(def_id);
1709 let def = self.tcx.adt_def(def_id);
1710 for (i, variant) in def.variants.iter().enumerate() {
1711 self.record(variant.did,
1712 IsolatedEncoder::encode_enum_variant_info,
1713 (def_id, Untracked(i)));
1716 hir::ItemStruct(ref struct_def, _) => {
1717 self.encode_fields(def_id);
1719 // If the struct has a constructor, encode it.
1720 if !struct_def.is_struct() {
1721 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1722 self.record(ctor_def_id,
1723 IsolatedEncoder::encode_struct_ctor,
1724 (def_id, ctor_def_id));
1727 hir::ItemUnion(..) => {
1728 self.encode_fields(def_id);
1730 hir::ItemImpl(..) => {
1731 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1732 self.record(trait_item_def_id,
1733 IsolatedEncoder::encode_info_for_impl_item,
1737 hir::ItemTrait(..) => {
1738 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1739 self.record(item_def_id,
1740 IsolatedEncoder::encode_info_for_trait_item,
1748 struct ImplVisitor<'a, 'tcx: 'a> {
1749 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1750 impls: FxHashMap<DefId, Vec<DefIndex>>,
1753 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1754 fn visit_item(&mut self, item: &hir::Item) {
1755 if let hir::ItemImpl(..) = item.node {
1756 let impl_id = self.tcx.hir.local_def_id(item.id);
1757 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1759 .entry(trait_ref.def_id)
1761 .push(impl_id.index);
1766 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1768 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1769 // handled in `visit_item` above
1773 // NOTE(eddyb) The following comment was preserved for posterity, even
1774 // though it's no longer relevant as EBML (which uses nested & tagged
1775 // "documents") was replaced with a scheme that can't go out of bounds.
1777 // And here we run into yet another obscure archive bug: in which metadata
1778 // loaded from archives may have trailing garbage bytes. Awhile back one of
1779 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1780 // and opt) by having ebml generate an out-of-bounds panic when looking at
1783 // Upon investigation it turned out that the metadata file inside of an rlib
1784 // (and ar archive) was being corrupted. Some compilations would generate a
1785 // metadata file which would end in a few extra bytes, while other
1786 // compilations would not have these extra bytes appended to the end. These
1787 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1788 // being interpreted causing the out-of-bounds.
1790 // The root cause of why these extra bytes were appearing was never
1791 // discovered, and in the meantime the solution we're employing is to insert
1792 // the length of the metadata to the start of the metadata. Later on this
1793 // will allow us to slice the metadata to the precise length that we just
1794 // generated regardless of trailing bytes that end up in it.
1796 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1797 link_meta: &LinkMeta)
1800 let mut cursor = Cursor::new(vec![]);
1801 cursor.write_all(METADATA_HEADER).unwrap();
1803 // Will be filled with the root position after encoding everything.
1804 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1807 let mut ecx = EncodeContext {
1808 opaque: opaque::Encoder::new(&mut cursor),
1811 lazy_state: LazyState::NoNode,
1812 type_shorthands: Default::default(),
1813 predicate_shorthands: Default::default(),
1814 filemap_cache: tcx.sess.codemap().files()[0].clone(),
1815 interpret_allocs: Default::default(),
1816 interpret_allocs_inverse: Default::default(),
1819 // Encode the rustc version string in a predictable location.
1820 rustc_version().encode(&mut ecx).unwrap();
1822 // Encode all the entries and extra information in the crate,
1823 // culminating in the `CrateRoot` which points to all of it.
1824 ecx.encode_crate_root()
1826 let mut result = cursor.into_inner();
1828 // Encode the root position.
1829 let header = METADATA_HEADER.len();
1830 let pos = root.position;
1831 result[header + 0] = (pos >> 24) as u8;
1832 result[header + 1] = (pos >> 16) as u8;
1833 result[header + 2] = (pos >> 8) as u8;
1834 result[header + 3] = (pos >> 0) as u8;
1836 EncodedMetadata { raw_data: result }
1839 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1840 let ty = tcx.type_of(did);
1842 ty::TyAdt(ref def, _) => return def.repr,
1843 _ => bug!("{} is not an ADT", ty),