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::{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_data_structures::fingerprint::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};
30 use rustc::ty::layout::VariantIdx;
32 use rustc::session::config::{self, CrateType};
33 use rustc::util::nodemap::FxHashMap;
35 use rustc_data_structures::stable_hasher::StableHasher;
36 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
40 use rustc_data_structures::sync::Lrc;
42 use syntax::ast::{self, CRATE_NODE_ID};
44 use syntax::source_map::Spanned;
45 use syntax::symbol::keywords;
46 use syntax_pos::{self, hygiene, FileName, SourceFile, Span};
48 use rustc::hir::{self, PatKind};
49 use rustc::hir::itemlikevisit::ItemLikeVisitor;
50 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
51 use rustc::hir::intravisit;
53 pub struct EncodeContext<'a, 'tcx: 'a> {
54 opaque: opaque::Encoder,
55 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
57 lazy_state: LazyState,
58 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
59 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
61 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
62 interpret_allocs_inverse: Vec<interpret::AllocId>,
64 // This is used to speed up Span encoding.
65 source_file_cache: Lrc<SourceFile>,
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 as Encoder>::Error;
79 fn emit_unit(&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> {
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.source_file_cache.contains(span.lo) {
161 let source_map = self.tcx.sess.source_map();
162 let source_file_index = source_map.lookup_source_file_idx(span.lo);
163 self.source_file_cache = source_map.files()[source_file_index].clone();
166 if !self.source_file_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 use std::collections::hash_map::Entry;
200 let index = match self.interpret_allocs.entry(*alloc_id) {
201 Entry::Occupied(e) => *e.get(),
202 Entry::Vacant(e) => {
203 let idx = self.interpret_allocs_inverse.len();
204 self.interpret_allocs_inverse.push(*alloc_id);
214 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
215 fn specialized_encode(&mut self,
216 predicates: &ty::GenericPredicates<'tcx>)
217 -> Result<(), Self::Error> {
218 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
222 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
223 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
224 f.encode_opaque(&mut self.opaque)
228 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
229 for EncodeContext<'a, 'tcx> {
230 fn specialized_encode(&mut self,
231 _: &mir::ClearCrossCrate<T>)
232 -> Result<(), Self::Error> {
237 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
238 fn position(&self) -> usize {
239 self.opaque.position()
243 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
245 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
246 assert_eq!(self.lazy_state, LazyState::NoNode);
247 let pos = self.position();
248 self.lazy_state = LazyState::NodeStart(pos);
249 let r = f(self, pos);
250 self.lazy_state = LazyState::NoNode;
254 fn emit_lazy_distance(&mut self,
257 -> Result<(), <Self as Encoder>::Error> {
258 let min_end = position + min_size;
259 let distance = match self.lazy_state {
260 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
261 LazyState::NodeStart(start) => {
262 assert!(min_end <= start);
265 LazyState::Previous(last_min_end) => {
267 last_min_end <= position,
268 "make sure that the calls to `lazy*` \
269 are in the same order as the metadata fields",
271 position - last_min_end
274 self.lazy_state = LazyState::Previous(min_end);
275 self.emit_usize(distance)
278 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
279 self.emit_node(|ecx, pos| {
280 value.encode(ecx).unwrap();
282 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
283 Lazy::with_position(pos)
287 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
288 where I: IntoIterator<Item = T>,
291 self.emit_node(|ecx, pos| {
292 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
294 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
295 LazySeq::with_position_and_length(pos, len)
299 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
300 where I: IntoIterator<Item = &'b T>,
303 self.emit_node(|ecx, pos| {
304 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
306 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
307 LazySeq::with_position_and_length(pos, len)
311 // Encodes something that corresponds to a single DepNode::GlobalMetaData
312 // and registers the Fingerprint in the `metadata_hashes` map.
313 pub fn tracked<'x, DATA, R>(&'x mut self,
314 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
317 op(&mut IsolatedEncoder::new(self), data)
320 fn encode_info_for_items(&mut self) -> Index {
321 let krate = self.tcx.hir().krate();
322 let mut index = IndexBuilder::new(self);
323 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public };
324 index.record(DefId::local(CRATE_DEF_INDEX),
325 IsolatedEncoder::encode_info_for_mod,
326 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &vis)));
327 let mut visitor = EncodeVisitor { index };
328 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
329 for macro_def in &krate.exported_macros {
330 visitor.visit_macro_def(macro_def);
332 visitor.index.into_items()
335 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
336 let definitions = self.tcx.hir().definitions();
337 self.lazy(definitions.def_path_table())
340 fn encode_source_map(&mut self) -> LazySeq<syntax_pos::SourceFile> {
341 let source_map = self.tcx.sess.source_map();
342 let all_source_files = source_map.files();
344 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
346 let adapted = all_source_files.iter()
347 .filter(|source_file| {
348 // No need to re-export imported source_files, as any downstream
349 // crate will import them from their original source.
350 !source_file.is_imported()
353 match source_file.name {
354 // This path of this SourceFile has been modified by
355 // path-remapping, so we use it verbatim (and avoid
356 // cloning the whole map in the process).
357 _ if source_file.name_was_remapped => source_file.clone(),
359 // Otherwise expand all paths to absolute paths because
360 // any relative paths are potentially relative to a
362 FileName::Real(ref name) => {
363 let mut adapted = (**source_file).clone();
364 adapted.name = Path::new(&working_dir).join(name).into();
365 adapted.name_hash = {
366 let mut hasher: StableHasher<u128> = StableHasher::new();
367 adapted.name.hash(&mut hasher);
373 // expanded code, not from a file
374 _ => source_file.clone(),
377 .collect::<Vec<_>>();
379 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
382 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
383 let mut i = self.position();
385 let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
386 let dylib_dependency_formats = self.tracked(
387 IsolatedEncoder::encode_dylib_dependency_formats,
389 let dep_bytes = self.position() - i;
391 // Encode the lib features.
393 let lib_features = self.tracked(IsolatedEncoder::encode_lib_features, ());
394 let lib_feature_bytes = self.position() - i;
396 // Encode the language items.
398 let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
399 let lang_items_missing = self.tracked(
400 IsolatedEncoder::encode_lang_items_missing,
402 let lang_item_bytes = self.position() - i;
404 // Encode the native libraries used
406 let native_libraries = self.tracked(
407 IsolatedEncoder::encode_native_libraries,
409 let native_lib_bytes = self.position() - i;
411 let foreign_modules = self.tracked(
412 IsolatedEncoder::encode_foreign_modules,
417 let source_map = self.encode_source_map();
418 let source_map_bytes = self.position() - i;
420 // Encode DefPathTable
422 let def_path_table = self.encode_def_path_table();
423 let def_path_table_bytes = self.position() - i;
425 // Encode the def IDs of impls, for coherence checking.
427 let impls = self.tracked(IsolatedEncoder::encode_impls, ());
428 let impl_bytes = self.position() - i;
430 // Encode exported symbols info.
432 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
433 let exported_symbols = self.tracked(
434 IsolatedEncoder::encode_exported_symbols,
436 let exported_symbols_bytes = self.position() - i;
442 let items = self.encode_info_for_items();
443 let item_bytes = self.position() - i;
445 // Encode the allocation index
446 let interpret_alloc_index = {
447 let mut interpret_alloc_index = Vec::new();
449 trace!("beginning to encode alloc ids");
451 let new_n = self.interpret_allocs_inverse.len();
452 // if we have found new ids, serialize those, too
457 trace!("encoding {} further alloc ids", new_n - n);
458 for idx in n..new_n {
459 let id = self.interpret_allocs_inverse[idx];
460 let pos = self.position() as u32;
461 interpret_alloc_index.push(pos);
462 interpret::specialized_encode_alloc_id(
470 self.lazy_seq(interpret_alloc_index)
475 let index = items.write_index(&mut self.opaque);
476 let index_bytes = self.position() - i;
478 let attrs = tcx.hir().krate_attrs();
479 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
480 let has_default_lib_allocator = attr::contains_name(&attrs, "default_lib_allocator");
481 let has_global_allocator = *tcx.sess.has_global_allocator.get();
482 let has_panic_handler = *tcx.sess.has_panic_handler.try_get().unwrap_or(&false);
484 let root = self.lazy(&CrateRoot {
485 name: tcx.crate_name(LOCAL_CRATE),
486 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
487 triple: tcx.sess.opts.target_triple.clone(),
488 hash: tcx.crate_hash(LOCAL_CRATE),
489 disambiguator: tcx.sess.local_crate_disambiguator(),
490 panic_strategy: tcx.sess.panic_strategy(),
491 edition: hygiene::default_edition(),
492 has_global_allocator: has_global_allocator,
493 has_panic_handler: has_panic_handler,
494 has_default_lib_allocator: has_default_lib_allocator,
495 plugin_registrar_fn: tcx.sess
498 .map(|id| tcx.hir().local_def_id(id).index),
499 proc_macro_decls_static: if is_proc_macro {
500 let id = tcx.sess.proc_macro_decls_static.get().unwrap();
501 Some(tcx.hir().local_def_id(id).index)
506 compiler_builtins: attr::contains_name(&attrs, "compiler_builtins"),
507 needs_allocator: attr::contains_name(&attrs, "needs_allocator"),
508 needs_panic_runtime: attr::contains_name(&attrs, "needs_panic_runtime"),
509 no_builtins: attr::contains_name(&attrs, "no_builtins"),
510 panic_runtime: attr::contains_name(&attrs, "panic_runtime"),
511 profiler_runtime: attr::contains_name(&attrs, "profiler_runtime"),
512 sanitizer_runtime: attr::contains_name(&attrs, "sanitizer_runtime"),
515 dylib_dependency_formats,
525 interpret_alloc_index,
529 let total_bytes = self.position();
531 if self.tcx.sess.meta_stats() {
532 let mut zero_bytes = 0;
533 for e in self.opaque.data.iter() {
539 println!("metadata stats:");
540 println!(" dep bytes: {}", dep_bytes);
541 println!(" lib feature bytes: {}", lib_feature_bytes);
542 println!(" lang item bytes: {}", lang_item_bytes);
543 println!(" native bytes: {}", native_lib_bytes);
544 println!(" source_map bytes: {}", source_map_bytes);
545 println!(" impl bytes: {}", impl_bytes);
546 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
547 println!(" def-path table bytes: {}", def_path_table_bytes);
548 println!(" item bytes: {}", item_bytes);
549 println!(" index bytes: {}", index_bytes);
550 println!(" zero bytes: {}", zero_bytes);
551 println!(" total bytes: {}", total_bytes);
558 // These are methods for encoding various things. They are meant to be used with
559 // IndexBuilder::record() and EncodeContext::tracked(). They actually
560 // would not have to be methods of IsolatedEncoder (free standing functions
561 // taking IsolatedEncoder as first argument would be just fine) but by making
562 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
563 // clause again and again.
564 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
565 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
566 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
568 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
571 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
573 let ty = tcx.type_of(def_id);
574 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
578 /// Encode data for the given variant of the given ADT. The
579 /// index of the variant is untracked: this is ok because we
580 /// will have to lookup the adt-def by its id, and that gives us
581 /// the right to access any information in the adt-def (including,
582 /// e.g., the length of the various vectors).
583 fn encode_enum_variant_info(&mut self,
584 (enum_did, Untracked(index)): (DefId, Untracked<VariantIdx>))
587 let def = tcx.adt_def(enum_did);
588 let variant = &def.variants[index];
589 let def_id = variant.did;
590 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
592 let data = VariantData {
593 ctor_kind: variant.ctor_kind,
594 discr: variant.discr,
596 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
597 Some(self.lazy(&tcx.fn_sig(def_id)))
603 let enum_id = tcx.hir().as_local_node_id(enum_did).unwrap();
604 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
607 kind: EntryKind::Variant(self.lazy(&data)),
608 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
609 span: self.lazy(&tcx.def_span(def_id)),
610 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
611 children: self.lazy_seq(variant.fields.iter().map(|f| {
612 assert!(f.did.is_local());
615 stability: self.encode_stability(def_id),
616 deprecation: self.encode_deprecation(def_id),
618 ty: Some(self.encode_item_type(def_id)),
619 inherent_impls: LazySeq::empty(),
620 variances: if variant.ctor_kind == CtorKind::Fn {
621 self.encode_variances_of(def_id)
625 generics: Some(self.encode_generics(def_id)),
626 predicates: Some(self.encode_predicates(def_id)),
627 predicates_defined_on: None,
629 mir: self.encode_optimized_mir(def_id),
633 fn encode_info_for_mod(&mut self,
634 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
639 let def_id = tcx.hir().local_def_id(id);
640 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
643 reexports: match tcx.module_exports(def_id) {
644 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
645 _ => LazySeq::empty(),
650 kind: EntryKind::Mod(self.lazy(&data)),
651 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
652 span: self.lazy(&tcx.def_span(def_id)),
653 attributes: self.encode_attributes(attrs),
654 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
655 tcx.hir().local_def_id(item_id.id).index
657 stability: self.encode_stability(def_id),
658 deprecation: self.encode_deprecation(def_id),
661 inherent_impls: LazySeq::empty(),
662 variances: LazySeq::empty(),
665 predicates_defined_on: None,
671 /// Encode data for the given field of the given variant of the
672 /// given ADT. The indices of the variant/field are untracked:
673 /// this is ok because we will have to lookup the adt-def by its
674 /// id, and that gives us the right to access any information in
675 /// the adt-def (including, e.g., the length of the various
677 fn encode_field(&mut self,
678 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
679 Untracked<(VariantIdx,
683 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
684 let field = &variant.fields[field_index];
686 let def_id = field.did;
687 debug!("IsolatedEncoder::encode_field({:?})", def_id);
689 let variant_id = tcx.hir().as_local_node_id(variant.did).unwrap();
690 let variant_data = tcx.hir().expect_variant_data(variant_id);
693 kind: EntryKind::Field,
694 visibility: self.lazy(&field.vis),
695 span: self.lazy(&tcx.def_span(def_id)),
696 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
697 children: LazySeq::empty(),
698 stability: self.encode_stability(def_id),
699 deprecation: self.encode_deprecation(def_id),
701 ty: Some(self.encode_item_type(def_id)),
702 inherent_impls: LazySeq::empty(),
703 variances: LazySeq::empty(),
704 generics: Some(self.encode_generics(def_id)),
705 predicates: Some(self.encode_predicates(def_id)),
706 predicates_defined_on: None,
712 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
713 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
715 let adt_def = tcx.adt_def(adt_def_id);
716 let variant = adt_def.non_enum_variant();
718 let data = VariantData {
719 ctor_kind: variant.ctor_kind,
720 discr: variant.discr,
721 struct_ctor: Some(def_id.index),
722 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
723 Some(self.lazy(&tcx.fn_sig(def_id)))
729 let struct_id = tcx.hir().as_local_node_id(adt_def_id).unwrap();
730 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
731 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
732 for field in &variant.fields {
733 if ctor_vis.is_at_least(field.vis, tcx) {
734 ctor_vis = field.vis;
738 // If the structure is marked as non_exhaustive then lower the visibility
739 // to within the crate.
740 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
741 ctor_vis == ty::Visibility::Public
743 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
746 let repr_options = get_repr_options(&tcx, adt_def_id);
749 kind: EntryKind::Struct(self.lazy(&data), repr_options),
750 visibility: self.lazy(&ctor_vis),
751 span: self.lazy(&tcx.def_span(def_id)),
752 attributes: LazySeq::empty(),
753 children: LazySeq::empty(),
754 stability: self.encode_stability(def_id),
755 deprecation: self.encode_deprecation(def_id),
757 ty: Some(self.encode_item_type(def_id)),
758 inherent_impls: LazySeq::empty(),
759 variances: if variant.ctor_kind == CtorKind::Fn {
760 self.encode_variances_of(def_id)
764 generics: Some(self.encode_generics(def_id)),
765 predicates: Some(self.encode_predicates(def_id)),
766 predicates_defined_on: None,
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_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
785 debug!("IsolatedEncoder::encode_predicates_defined_on({:?})", def_id);
787 self.lazy(&tcx.predicates_defined_on(def_id))
790 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
791 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
794 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
795 let ast_item = tcx.hir().expect_trait_item(node_id);
796 let trait_item = tcx.associated_item(def_id);
798 let container = match trait_item.defaultness {
799 hir::Defaultness::Default { has_value: true } =>
800 AssociatedContainer::TraitWithDefault,
801 hir::Defaultness::Default { has_value: false } =>
802 AssociatedContainer::TraitRequired,
803 hir::Defaultness::Final =>
804 span_bug!(ast_item.span, "traits cannot have final items"),
807 let kind = match trait_item.kind {
808 ty::AssociatedKind::Const => {
810 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
811 self.const_qualif(0, body)
813 ConstQualif { mir: 0, ast_promotable: false }
817 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
818 let rendered_const = self.lazy(&RenderedConst(rendered));
820 EntryKind::AssociatedConst(container, const_qualif, rendered_const)
822 ty::AssociatedKind::Method => {
823 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
824 let arg_names = match *m {
825 hir::TraitMethod::Required(ref names) => {
826 self.encode_fn_arg_names(names)
828 hir::TraitMethod::Provided(body) => {
829 self.encode_fn_arg_names_for_body(body)
833 constness: hir::Constness::NotConst,
835 sig: self.lazy(&tcx.fn_sig(def_id)),
840 EntryKind::Method(self.lazy(&MethodData {
843 has_self: trait_item.method_has_self_argument,
846 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
847 ty::AssociatedKind::Existential =>
848 span_bug!(ast_item.span, "existential type in trait"),
853 visibility: self.lazy(&trait_item.vis),
854 span: self.lazy(&ast_item.span),
855 attributes: self.encode_attributes(&ast_item.attrs),
856 children: LazySeq::empty(),
857 stability: self.encode_stability(def_id),
858 deprecation: self.encode_deprecation(def_id),
860 ty: match trait_item.kind {
861 ty::AssociatedKind::Const |
862 ty::AssociatedKind::Method => {
863 Some(self.encode_item_type(def_id))
865 ty::AssociatedKind::Type => {
866 if trait_item.defaultness.has_value() {
867 Some(self.encode_item_type(def_id))
872 ty::AssociatedKind::Existential => unreachable!(),
874 inherent_impls: LazySeq::empty(),
875 variances: if trait_item.kind == ty::AssociatedKind::Method {
876 self.encode_variances_of(def_id)
880 generics: Some(self.encode_generics(def_id)),
881 predicates: Some(self.encode_predicates(def_id)),
882 predicates_defined_on: None,
884 mir: self.encode_optimized_mir(def_id),
888 fn metadata_output_only(&self) -> bool {
889 // MIR optimisation can be skipped when we're just interested in the metadata.
890 !self.tcx.sess.opts.output_types.should_codegen()
893 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
894 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
895 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
897 ConstQualif { mir, ast_promotable }
900 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
901 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
904 let node_id = self.tcx.hir().as_local_node_id(def_id).unwrap();
905 let ast_item = self.tcx.hir().expect_impl_item(node_id);
906 let impl_item = self.tcx.associated_item(def_id);
908 let container = match impl_item.defaultness {
909 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
910 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
911 hir::Defaultness::Default { has_value: false } =>
912 span_bug!(ast_item.span, "impl items always have values (currently)"),
915 let kind = match impl_item.kind {
916 ty::AssociatedKind::Const => {
917 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
918 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
920 EntryKind::AssociatedConst(container,
921 self.const_qualif(mir, body_id),
922 self.encode_rendered_const_for_body(body_id))
927 ty::AssociatedKind::Method => {
928 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
930 constness: sig.header.constness,
931 arg_names: self.encode_fn_arg_names_for_body(body),
932 sig: self.lazy(&tcx.fn_sig(def_id)),
937 EntryKind::Method(self.lazy(&MethodData {
940 has_self: impl_item.method_has_self_argument,
943 ty::AssociatedKind::Existential => EntryKind::AssociatedExistential(container),
944 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
948 match ast_item.node {
949 hir::ImplItemKind::Const(..) => true,
950 hir::ImplItemKind::Method(ref sig, _) => {
951 let generics = self.tcx.generics_of(def_id);
952 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
953 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
954 !self.metadata_output_only();
955 let is_const_fn = sig.header.constness == hir::Constness::Const;
956 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
957 needs_inline || is_const_fn || always_encode_mir
959 hir::ImplItemKind::Existential(..) |
960 hir::ImplItemKind::Type(..) => false,
965 visibility: self.lazy(&impl_item.vis),
966 span: self.lazy(&ast_item.span),
967 attributes: self.encode_attributes(&ast_item.attrs),
968 children: LazySeq::empty(),
969 stability: self.encode_stability(def_id),
970 deprecation: self.encode_deprecation(def_id),
972 ty: Some(self.encode_item_type(def_id)),
973 inherent_impls: LazySeq::empty(),
974 variances: if impl_item.kind == ty::AssociatedKind::Method {
975 self.encode_variances_of(def_id)
979 generics: Some(self.encode_generics(def_id)),
980 predicates: Some(self.encode_predicates(def_id)),
981 predicates_defined_on: None,
983 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
987 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
988 -> LazySeq<ast::Name> {
989 self.tcx.dep_graph.with_ignore(|| {
990 let body = self.tcx.hir().body(body_id);
991 self.lazy_seq(body.arguments.iter().map(|arg| {
993 PatKind::Binding(_, _, ident, _) => ident.name,
994 _ => keywords::Invalid.name(),
1000 fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> LazySeq<ast::Name> {
1001 self.lazy_seq(param_names.iter().map(|ident| ident.name))
1004 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
1005 debug!("EntryBuilder::encode_mir({:?})", def_id);
1006 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1007 let mir = self.tcx.optimized_mir(def_id);
1008 Some(self.lazy(&mir))
1014 // Encodes the inherent implementations of a structure, enumeration, or trait.
1015 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1016 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
1017 let implementations = self.tcx.inherent_impls(def_id);
1018 if implementations.is_empty() {
1021 self.lazy_seq(implementations.iter().map(|&def_id| {
1022 assert!(def_id.is_local());
1028 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1029 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
1030 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1033 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1034 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
1035 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1038 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1039 let body = self.tcx.hir().body(body_id);
1040 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1041 let rendered_const = &RenderedConst(rendered);
1042 self.lazy(rendered_const)
1045 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1048 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
1050 let kind = match item.node {
1051 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1052 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1053 hir::ItemKind::Const(_, body_id) => {
1054 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1056 self.const_qualif(mir, body_id),
1057 self.encode_rendered_const_for_body(body_id)
1060 hir::ItemKind::Fn(_, header, .., body) => {
1062 constness: header.constness,
1063 arg_names: self.encode_fn_arg_names_for_body(body),
1064 sig: self.lazy(&tcx.fn_sig(def_id)),
1067 EntryKind::Fn(self.lazy(&data))
1069 hir::ItemKind::Mod(ref m) => {
1070 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
1072 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1073 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1074 hir::ItemKind::Ty(..) => EntryKind::Type,
1075 hir::ItemKind::Existential(..) => EntryKind::Existential,
1076 hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
1077 hir::ItemKind::Struct(ref struct_def, _) => {
1078 let variant = tcx.adt_def(def_id).non_enum_variant();
1080 // Encode def_ids for each field and method
1081 // for methods, write all the stuff get_trait_method
1083 let struct_ctor = if !struct_def.is_struct() {
1084 Some(tcx.hir().local_def_id(struct_def.id()).index)
1089 let repr_options = get_repr_options(&tcx, def_id);
1091 EntryKind::Struct(self.lazy(&VariantData {
1092 ctor_kind: variant.ctor_kind,
1093 discr: variant.discr,
1098 hir::ItemKind::Union(..) => {
1099 let variant = tcx.adt_def(def_id).non_enum_variant();
1100 let repr_options = get_repr_options(&tcx, def_id);
1102 EntryKind::Union(self.lazy(&VariantData {
1103 ctor_kind: variant.ctor_kind,
1104 discr: variant.discr,
1109 hir::ItemKind::Impl(_, polarity, defaultness, ..) => {
1110 let trait_ref = tcx.impl_trait_ref(def_id);
1111 let parent = if let Some(trait_ref) = trait_ref {
1112 let trait_def = tcx.trait_def(trait_ref.def_id);
1113 trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| {
1115 specialization_graph::Node::Impl(parent) => Some(parent),
1123 // if this is an impl of `CoerceUnsized`, create its
1124 // "unsized info", else just store None
1125 let coerce_unsized_info =
1126 trait_ref.and_then(|t| {
1127 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1128 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1134 let data = ImplData {
1137 parent_impl: parent,
1138 coerce_unsized_info,
1139 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1142 EntryKind::Impl(self.lazy(&data))
1144 hir::ItemKind::Trait(..) |
1145 hir::ItemKind::TraitAlias(..) => {
1146 let trait_def = tcx.trait_def(def_id);
1147 let data = TraitData {
1148 unsafety: trait_def.unsafety,
1149 paren_sugar: trait_def.paren_sugar,
1150 has_auto_impl: tcx.trait_is_auto(def_id),
1151 is_marker: trait_def.is_marker,
1152 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1155 EntryKind::Trait(self.lazy(&data))
1157 hir::ItemKind::ExternCrate(_) |
1158 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1163 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1164 span: self.lazy(&item.span),
1165 attributes: self.encode_attributes(&item.attrs),
1166 children: match item.node {
1167 hir::ItemKind::ForeignMod(ref fm) => {
1168 self.lazy_seq(fm.items
1170 .map(|foreign_item| tcx.hir().local_def_id(foreign_item.id).index))
1172 hir::ItemKind::Enum(..) => {
1173 let def = self.tcx.adt_def(def_id);
1174 self.lazy_seq(def.variants.iter().map(|v| {
1175 assert!(v.did.is_local());
1179 hir::ItemKind::Struct(..) |
1180 hir::ItemKind::Union(..) => {
1181 let def = self.tcx.adt_def(def_id);
1182 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1183 assert!(f.did.is_local());
1187 hir::ItemKind::Impl(..) |
1188 hir::ItemKind::Trait(..) => {
1189 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1190 assert!(def_id.is_local());
1194 _ => LazySeq::empty(),
1196 stability: self.encode_stability(def_id),
1197 deprecation: self.encode_deprecation(def_id),
1199 ty: match item.node {
1200 hir::ItemKind::Static(..) |
1201 hir::ItemKind::Const(..) |
1202 hir::ItemKind::Fn(..) |
1203 hir::ItemKind::Ty(..) |
1204 hir::ItemKind::Existential(..) |
1205 hir::ItemKind::Enum(..) |
1206 hir::ItemKind::Struct(..) |
1207 hir::ItemKind::Union(..) |
1208 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1211 inherent_impls: self.encode_inherent_implementations(def_id),
1212 variances: match item.node {
1213 hir::ItemKind::Enum(..) |
1214 hir::ItemKind::Struct(..) |
1215 hir::ItemKind::Union(..) |
1216 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1217 _ => LazySeq::empty(),
1219 generics: match item.node {
1220 hir::ItemKind::Static(..) |
1221 hir::ItemKind::Const(..) |
1222 hir::ItemKind::Fn(..) |
1223 hir::ItemKind::Ty(..) |
1224 hir::ItemKind::Enum(..) |
1225 hir::ItemKind::Struct(..) |
1226 hir::ItemKind::Union(..) |
1227 hir::ItemKind::Impl(..) |
1228 hir::ItemKind::Existential(..) |
1229 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1232 predicates: match item.node {
1233 hir::ItemKind::Static(..) |
1234 hir::ItemKind::Const(..) |
1235 hir::ItemKind::Fn(..) |
1236 hir::ItemKind::Ty(..) |
1237 hir::ItemKind::Enum(..) |
1238 hir::ItemKind::Struct(..) |
1239 hir::ItemKind::Union(..) |
1240 hir::ItemKind::Impl(..) |
1241 hir::ItemKind::Existential(..) |
1242 hir::ItemKind::Trait(..) => Some(self.encode_predicates(def_id)),
1246 // The only time that `predicates_defined_on` is used (on
1247 // an external item) is for traits, during chalk lowering,
1248 // so only encode it in that case as an efficiency
1249 // hack. (No reason not to expand it in the future if
1251 predicates_defined_on: match item.node {
1252 hir::ItemKind::Trait(..) => Some(self.encode_predicates_defined_on(def_id)),
1253 _ => None, // not *wrong* for other kinds of items, but not needed
1256 mir: match item.node {
1257 hir::ItemKind::Static(..) => {
1258 self.encode_optimized_mir(def_id)
1260 hir::ItemKind::Const(..) => self.encode_optimized_mir(def_id),
1261 hir::ItemKind::Fn(_, header, ..) => {
1262 let generics = tcx.generics_of(def_id);
1264 (generics.requires_monomorphization(tcx) ||
1265 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1266 !self.metadata_output_only();
1267 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1269 || header.constness == hir::Constness::Const
1270 || always_encode_mir
1272 self.encode_optimized_mir(def_id)
1282 /// Serialize the text of exported macros
1283 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1284 use syntax::print::pprust;
1285 let def_id = self.tcx.hir().local_def_id(macro_def.id);
1287 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1288 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1289 legacy: macro_def.legacy,
1291 visibility: self.lazy(&ty::Visibility::Public),
1292 span: self.lazy(¯o_def.span),
1293 attributes: self.encode_attributes(¯o_def.attrs),
1294 stability: self.encode_stability(def_id),
1295 deprecation: self.encode_deprecation(def_id),
1297 children: LazySeq::empty(),
1299 inherent_impls: LazySeq::empty(),
1300 variances: LazySeq::empty(),
1303 predicates_defined_on: None,
1308 fn encode_info_for_ty_param(&mut self,
1309 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1311 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1314 kind: EntryKind::Type,
1315 visibility: self.lazy(&ty::Visibility::Public),
1316 span: self.lazy(&tcx.def_span(def_id)),
1317 attributes: LazySeq::empty(),
1318 children: LazySeq::empty(),
1322 ty: if has_default {
1323 Some(self.encode_item_type(def_id))
1327 inherent_impls: LazySeq::empty(),
1328 variances: LazySeq::empty(),
1331 predicates_defined_on: None,
1337 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1338 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1341 let tables = self.tcx.typeck_tables_of(def_id);
1342 let node_id = self.tcx.hir().as_local_node_id(def_id).unwrap();
1343 let hir_id = self.tcx.hir().node_to_hir_id(node_id);
1344 let kind = match tables.node_id_to_type(hir_id).sty {
1345 ty::Generator(def_id, ..) => {
1346 let layout = self.tcx.generator_layout(def_id);
1347 let data = GeneratorData {
1348 layout: layout.clone(),
1350 EntryKind::Generator(self.lazy(&data))
1353 ty::Closure(def_id, substs) => {
1354 let sig = substs.closure_sig(def_id, self.tcx);
1355 let data = ClosureData { sig: self.lazy(&sig) };
1356 EntryKind::Closure(self.lazy(&data))
1359 _ => bug!("closure that is neither generator nor closure")
1364 visibility: self.lazy(&ty::Visibility::Public),
1365 span: self.lazy(&tcx.def_span(def_id)),
1366 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1367 children: LazySeq::empty(),
1371 ty: Some(self.encode_item_type(def_id)),
1372 inherent_impls: LazySeq::empty(),
1373 variances: LazySeq::empty(),
1374 generics: Some(self.encode_generics(def_id)),
1376 predicates_defined_on: None,
1378 mir: self.encode_optimized_mir(def_id),
1382 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1383 debug!("IsolatedEncoder::encode_info_for_anon_const({:?})", def_id);
1385 let id = tcx.hir().as_local_node_id(def_id).unwrap();
1386 let body_id = tcx.hir().body_owned_by(id);
1387 let const_data = self.encode_rendered_const_for_body(body_id);
1388 let mir = tcx.mir_const_qualif(def_id).0;
1391 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1392 visibility: self.lazy(&ty::Visibility::Public),
1393 span: self.lazy(&tcx.def_span(def_id)),
1394 attributes: LazySeq::empty(),
1395 children: LazySeq::empty(),
1399 ty: Some(self.encode_item_type(def_id)),
1400 inherent_impls: LazySeq::empty(),
1401 variances: LazySeq::empty(),
1402 generics: Some(self.encode_generics(def_id)),
1403 predicates: Some(self.encode_predicates(def_id)),
1404 predicates_defined_on: None,
1406 mir: self.encode_optimized_mir(def_id),
1410 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1411 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1412 // we rely on the HashStable specialization for [Attribute]
1413 // to properly filter things out.
1414 self.lazy_seq_from_slice(attrs)
1417 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1418 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1419 self.lazy_seq(used_libraries.iter().cloned())
1422 fn encode_foreign_modules(&mut self, _: ()) -> LazySeq<ForeignModule> {
1423 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1424 self.lazy_seq(foreign_modules.iter().cloned())
1427 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1428 let crates = self.tcx.crates();
1430 let mut deps = crates
1433 let dep = CrateDep {
1434 name: self.tcx.original_crate_name(cnum),
1435 hash: self.tcx.crate_hash(cnum),
1436 kind: self.tcx.dep_kind(cnum),
1437 extra_filename: self.tcx.extra_filename(cnum),
1441 .collect::<Vec<_>>();
1443 deps.sort_by_key(|&(cnum, _)| cnum);
1446 // Sanity-check the crate numbers
1447 let mut expected_cnum = 1;
1448 for &(n, _) in &deps {
1449 assert_eq!(n, CrateNum::new(expected_cnum));
1454 // We're just going to write a list of crate 'name-hash-version's, with
1455 // the assumption that they are numbered 1 to n.
1456 // FIXME (#2166): This is not nearly enough to support correct versioning
1457 // but is enough to get transitive crate dependencies working.
1458 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1461 fn encode_lib_features(&mut self, _: ()) -> LazySeq<(ast::Name, Option<ast::Name>)> {
1463 let lib_features = tcx.lib_features();
1464 self.lazy_seq(lib_features.to_vec())
1467 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1469 let lang_items = tcx.lang_items();
1470 let lang_items = lang_items.items().iter();
1471 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1472 if let Some(def_id) = opt_def_id {
1473 if def_id.is_local() {
1474 return Some((def_id.index, i));
1481 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1483 self.lazy_seq_ref(&tcx.lang_items().missing)
1486 /// Encodes an index, mapping each trait to its (local) implementations.
1487 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1488 debug!("IsolatedEncoder::encode_impls()");
1490 let mut visitor = ImplVisitor {
1492 impls: FxHashMap::default(),
1494 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1496 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1498 // Bring everything into deterministic order for hashing
1499 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1500 tcx.def_path_hash(trait_def_id)
1503 let all_impls: Vec<_> = all_impls
1505 .map(|(trait_def_id, mut impls)| {
1506 // Bring everything into deterministic order for hashing
1507 impls.sort_by_cached_key(|&def_index| {
1508 tcx.hir().definitions().def_path_hash(def_index)
1512 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1513 impls: self.lazy_seq_from_slice(&impls[..]),
1518 self.lazy_seq_from_slice(&all_impls[..])
1521 // Encodes all symbols exported from this crate into the metadata.
1523 // This pass is seeded off the reachability list calculated in the
1524 // middle::reachable module but filters out items that either don't have a
1525 // symbol associated with them (they weren't translated) or if they're an FFI
1526 // definition (as that's not defined in this crate).
1527 fn encode_exported_symbols(&mut self,
1528 exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1529 -> EncodedExportedSymbols {
1530 // The metadata symbol name is special. It should not show up in
1531 // downstream crates.
1532 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1534 let lazy_seq = self.lazy_seq(exported_symbols
1536 .filter(|&&(ref exported_symbol, _)| {
1537 match *exported_symbol {
1538 ExportedSymbol::NoDefId(symbol_name) => {
1539 symbol_name != metadata_symbol_name
1546 EncodedExportedSymbols {
1548 position: lazy_seq.position,
1552 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1553 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateType::Dylib) {
1555 self.lazy_seq(arr.iter().map(|slot| {
1557 Linkage::NotLinked |
1558 Linkage::IncludedFromDylib => None,
1560 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1561 Linkage::Static => Some(LinkagePreference::RequireStatic),
1565 None => LazySeq::empty(),
1569 fn encode_info_for_foreign_item(&mut self,
1570 (def_id, nitem): (DefId, &hir::ForeignItem))
1574 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1576 let kind = match nitem.node {
1577 hir::ForeignItemKind::Fn(_, ref names, _) => {
1579 constness: hir::Constness::NotConst,
1580 arg_names: self.encode_fn_arg_names(names),
1581 sig: self.lazy(&tcx.fn_sig(def_id)),
1583 EntryKind::ForeignFn(self.lazy(&data))
1585 hir::ForeignItemKind::Static(_, true) => EntryKind::ForeignMutStatic,
1586 hir::ForeignItemKind::Static(_, false) => EntryKind::ForeignImmStatic,
1587 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1592 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1593 span: self.lazy(&nitem.span),
1594 attributes: self.encode_attributes(&nitem.attrs),
1595 children: LazySeq::empty(),
1596 stability: self.encode_stability(def_id),
1597 deprecation: self.encode_deprecation(def_id),
1599 ty: Some(self.encode_item_type(def_id)),
1600 inherent_impls: LazySeq::empty(),
1601 variances: match nitem.node {
1602 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1603 _ => LazySeq::empty(),
1605 generics: Some(self.encode_generics(def_id)),
1606 predicates: Some(self.encode_predicates(def_id)),
1607 predicates_defined_on: None,
1614 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1615 index: IndexBuilder<'a, 'b, 'tcx>,
1618 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1619 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1620 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir())
1622 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1623 intravisit::walk_expr(self, ex);
1624 self.index.encode_info_for_expr(ex);
1626 fn visit_item(&mut self, item: &'tcx hir::Item) {
1627 intravisit::walk_item(self, item);
1628 let def_id = self.index.tcx.hir().local_def_id(item.id);
1630 hir::ItemKind::ExternCrate(_) |
1631 hir::ItemKind::Use(..) => (), // ignore these
1632 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1634 self.index.encode_addl_info_for_item(item);
1636 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1637 intravisit::walk_foreign_item(self, ni);
1638 let def_id = self.index.tcx.hir().local_def_id(ni.id);
1639 self.index.record(def_id,
1640 IsolatedEncoder::encode_info_for_foreign_item,
1643 fn visit_variant(&mut self,
1644 v: &'tcx hir::Variant,
1645 g: &'tcx hir::Generics,
1647 intravisit::walk_variant(self, v, g, id);
1649 if let Some(ref discr) = v.node.disr_expr {
1650 let def_id = self.index.tcx.hir().local_def_id(discr.id);
1651 self.index.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1654 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1655 intravisit::walk_generics(self, generics);
1656 self.index.encode_info_for_generics(generics);
1658 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1659 intravisit::walk_ty(self, ty);
1660 self.index.encode_info_for_ty(ty);
1662 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1663 let def_id = self.index.tcx.hir().local_def_id(macro_def.id);
1664 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1668 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1669 fn encode_fields(&mut self, adt_def_id: DefId) {
1670 let def = self.tcx.adt_def(adt_def_id);
1671 for (variant_index, variant) in def.variants.iter_enumerated() {
1672 for (field_index, field) in variant.fields.iter().enumerate() {
1673 self.record(field.did,
1674 IsolatedEncoder::encode_field,
1675 (adt_def_id, Untracked((variant_index, field_index))));
1680 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1681 for param in &generics.params {
1683 hir::GenericParamKind::Lifetime { .. } => {}
1684 hir::GenericParamKind::Type { ref default, .. } => {
1685 let def_id = self.tcx.hir().local_def_id(param.id);
1686 let has_default = Untracked(default.is_some());
1687 let encode_info = IsolatedEncoder::encode_info_for_ty_param;
1688 self.record(def_id, encode_info, (def_id, has_default));
1694 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1696 hir::TyKind::Array(_, ref length) => {
1697 let def_id = self.tcx.hir().local_def_id(length.id);
1698 self.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1704 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1706 hir::ExprKind::Closure(..) => {
1707 let def_id = self.tcx.hir().local_def_id(expr.id);
1708 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1714 /// In some cases, along with the item itself, we also
1715 /// encode some sub-items. Usually we want some info from the item
1716 /// so it's easier to do that here then to wait until we would encounter
1717 /// normally in the visitor walk.
1718 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1719 let def_id = self.tcx.hir().local_def_id(item.id);
1721 hir::ItemKind::Static(..) |
1722 hir::ItemKind::Const(..) |
1723 hir::ItemKind::Fn(..) |
1724 hir::ItemKind::Mod(..) |
1725 hir::ItemKind::ForeignMod(..) |
1726 hir::ItemKind::GlobalAsm(..) |
1727 hir::ItemKind::ExternCrate(..) |
1728 hir::ItemKind::Use(..) |
1729 hir::ItemKind::Ty(..) |
1730 hir::ItemKind::Existential(..) |
1731 hir::ItemKind::TraitAlias(..) => {
1732 // no sub-item recording needed in these cases
1734 hir::ItemKind::Enum(..) => {
1735 self.encode_fields(def_id);
1737 let def = self.tcx.adt_def(def_id);
1738 for (i, variant) in def.variants.iter_enumerated() {
1739 self.record(variant.did,
1740 IsolatedEncoder::encode_enum_variant_info,
1741 (def_id, Untracked(i)));
1744 hir::ItemKind::Struct(ref struct_def, _) => {
1745 self.encode_fields(def_id);
1747 // If the struct has a constructor, encode it.
1748 if !struct_def.is_struct() {
1749 let ctor_def_id = self.tcx.hir().local_def_id(struct_def.id());
1750 self.record(ctor_def_id,
1751 IsolatedEncoder::encode_struct_ctor,
1752 (def_id, ctor_def_id));
1755 hir::ItemKind::Union(..) => {
1756 self.encode_fields(def_id);
1758 hir::ItemKind::Impl(..) => {
1759 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1760 self.record(trait_item_def_id,
1761 IsolatedEncoder::encode_info_for_impl_item,
1765 hir::ItemKind::Trait(..) => {
1766 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1767 self.record(item_def_id,
1768 IsolatedEncoder::encode_info_for_trait_item,
1776 struct ImplVisitor<'a, 'tcx: 'a> {
1777 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1778 impls: FxHashMap<DefId, Vec<DefIndex>>,
1781 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1782 fn visit_item(&mut self, item: &hir::Item) {
1783 if let hir::ItemKind::Impl(..) = item.node {
1784 let impl_id = self.tcx.hir().local_def_id(item.id);
1785 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1787 .entry(trait_ref.def_id)
1789 .push(impl_id.index);
1794 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1796 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1797 // handled in `visit_item` above
1801 // NOTE(eddyb) The following comment was preserved for posterity, even
1802 // though it's no longer relevant as EBML (which uses nested & tagged
1803 // "documents") was replaced with a scheme that can't go out of bounds.
1805 // And here we run into yet another obscure archive bug: in which metadata
1806 // loaded from archives may have trailing garbage bytes. Awhile back one of
1807 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1808 // and opt) by having ebml generate an out-of-bounds panic when looking at
1811 // Upon investigation it turned out that the metadata file inside of an rlib
1812 // (and ar archive) was being corrupted. Some compilations would generate a
1813 // metadata file which would end in a few extra bytes, while other
1814 // compilations would not have these extra bytes appended to the end. These
1815 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1816 // being interpreted causing the out-of-bounds.
1818 // The root cause of why these extra bytes were appearing was never
1819 // discovered, and in the meantime the solution we're employing is to insert
1820 // the length of the metadata to the start of the metadata. Later on this
1821 // will allow us to slice the metadata to the precise length that we just
1822 // generated regardless of trailing bytes that end up in it.
1824 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
1827 let mut encoder = opaque::Encoder::new(vec![]);
1828 encoder.emit_raw_bytes(METADATA_HEADER);
1830 // Will be filled with the root position after encoding everything.
1831 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1833 let (root, mut result) = {
1834 let mut ecx = EncodeContext {
1837 lazy_state: LazyState::NoNode,
1838 type_shorthands: Default::default(),
1839 predicate_shorthands: Default::default(),
1840 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1841 interpret_allocs: Default::default(),
1842 interpret_allocs_inverse: Default::default(),
1845 // Encode the rustc version string in a predictable location.
1846 rustc_version().encode(&mut ecx).unwrap();
1848 // Encode all the entries and extra information in the crate,
1849 // culminating in the `CrateRoot` which points to all of it.
1850 let root = ecx.encode_crate_root();
1851 (root, ecx.opaque.into_inner())
1854 // Encode the root position.
1855 let header = METADATA_HEADER.len();
1856 let pos = root.position;
1857 result[header + 0] = (pos >> 24) as u8;
1858 result[header + 1] = (pos >> 16) as u8;
1859 result[header + 2] = (pos >> 8) as u8;
1860 result[header + 3] = (pos >> 0) as u8;
1862 EncodedMetadata { raw_data: result }
1865 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1866 let ty = tcx.type_of(did);
1868 ty::Adt(ref def, _) => return def.repr,
1869 _ => bug!("{} is not an ADT", ty),