2 use index_builder::{FromId, IndexBuilder, Untracked};
3 use isolated_encoder::IsolatedEncoder;
6 use rustc::middle::cstore::{LinkagePreference, NativeLibrary,
7 EncodedMetadata, ForeignModule};
8 use rustc::hir::def::CtorKind;
9 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LocalDefId, LOCAL_CRATE};
10 use rustc::hir::map::definitions::DefPathTable;
11 use rustc_data_structures::fingerprint::Fingerprint;
12 use rustc::middle::dependency_format::Linkage;
13 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel,
14 metadata_symbol_name};
15 use rustc::middle::lang_items;
16 use rustc::mir::{self, interpret};
17 use rustc::traits::specialization_graph;
18 use rustc::ty::{self, Ty, TyCtxt, ReprOptions, SymbolName};
19 use rustc::ty::codec::{self as ty_codec, TyEncoder};
20 use rustc::ty::layout::VariantIdx;
22 use rustc::session::config::{self, CrateType};
23 use rustc::util::nodemap::FxHashMap;
25 use rustc_data_structures::stable_hasher::StableHasher;
26 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
30 use rustc_data_structures::sync::Lrc;
32 use syntax::ast::{self, CRATE_NODE_ID};
34 use syntax::source_map::Spanned;
35 use syntax::symbol::keywords;
36 use syntax_pos::{self, hygiene, FileName, SourceFile, Span};
38 use rustc::hir::{self, PatKind};
39 use rustc::hir::itemlikevisit::ItemLikeVisitor;
40 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
41 use rustc::hir::intravisit;
43 pub struct EncodeContext<'a, 'tcx: 'a> {
44 opaque: opaque::Encoder,
45 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
47 lazy_state: LazyState,
48 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
49 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
51 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
52 interpret_allocs_inverse: Vec<interpret::AllocId>,
54 // This is used to speed up Span encoding.
55 source_file_cache: Lrc<SourceFile>,
58 macro_rules! encoder_methods {
59 ($($name:ident($ty:ty);)*) => {
60 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
61 self.opaque.$name(value)
66 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
67 type Error = <opaque::Encoder as Encoder>::Error;
69 fn emit_unit(&mut self) -> Result<(), Self::Error> {
96 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
97 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
98 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
102 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
103 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
104 self.emit_usize(seq.len)?;
108 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
112 impl<'a, 'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'a, 'tcx> {
114 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
115 self.emit_u32(cnum.as_u32())
119 impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
121 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
132 impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
134 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
135 self.emit_u32(def_index.as_raw_u32())
139 impl<'a, 'tcx> SpecializedEncoder<Span> for EncodeContext<'a, 'tcx> {
140 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
142 return TAG_INVALID_SPAN.encode(self)
145 let span = span.data();
147 // The Span infrastructure should make sure that this invariant holds:
148 debug_assert!(span.lo <= span.hi);
150 if !self.source_file_cache.contains(span.lo) {
151 let source_map = self.tcx.sess.source_map();
152 let source_file_index = source_map.lookup_source_file_idx(span.lo);
153 self.source_file_cache = source_map.files()[source_file_index].clone();
156 if !self.source_file_cache.contains(span.hi) {
157 // Unfortunately, macro expansion still sometimes generates Spans
158 // that malformed in this way.
159 return TAG_INVALID_SPAN.encode(self)
162 TAG_VALID_SPAN.encode(self)?;
163 span.lo.encode(self)?;
165 // Encode length which is usually less than span.hi and profits more
166 // from the variable-length integer encoding that we use.
167 let len = span.hi - span.lo;
170 // Don't encode the expansion context.
174 impl<'a, 'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'a, 'tcx> {
176 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
177 self.specialized_encode(&def_id.to_def_id())
181 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
182 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
183 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
187 impl<'a, 'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'a, 'tcx> {
188 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
189 use std::collections::hash_map::Entry;
190 let index = match self.interpret_allocs.entry(*alloc_id) {
191 Entry::Occupied(e) => *e.get(),
192 Entry::Vacant(e) => {
193 let idx = self.interpret_allocs_inverse.len();
194 self.interpret_allocs_inverse.push(*alloc_id);
204 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
205 fn specialized_encode(&mut self,
206 predicates: &ty::GenericPredicates<'tcx>)
207 -> Result<(), Self::Error> {
208 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
212 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
213 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
214 f.encode_opaque(&mut self.opaque)
218 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
219 for EncodeContext<'a, 'tcx> {
220 fn specialized_encode(&mut self,
221 _: &mir::ClearCrossCrate<T>)
222 -> Result<(), Self::Error> {
227 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
228 fn position(&self) -> usize {
229 self.opaque.position()
233 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
235 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
236 assert_eq!(self.lazy_state, LazyState::NoNode);
237 let pos = self.position();
238 self.lazy_state = LazyState::NodeStart(pos);
239 let r = f(self, pos);
240 self.lazy_state = LazyState::NoNode;
244 fn emit_lazy_distance(&mut self,
247 -> Result<(), <Self as Encoder>::Error> {
248 let min_end = position + min_size;
249 let distance = match self.lazy_state {
250 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
251 LazyState::NodeStart(start) => {
252 assert!(min_end <= start);
255 LazyState::Previous(last_min_end) => {
257 last_min_end <= position,
258 "make sure that the calls to `lazy*` \
259 are in the same order as the metadata fields",
261 position - last_min_end
264 self.lazy_state = LazyState::Previous(min_end);
265 self.emit_usize(distance)
268 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
269 self.emit_node(|ecx, pos| {
270 value.encode(ecx).unwrap();
272 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
273 Lazy::with_position(pos)
277 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
278 where I: IntoIterator<Item = T>,
281 self.emit_node(|ecx, pos| {
282 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
284 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
285 LazySeq::with_position_and_length(pos, len)
289 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
290 where I: IntoIterator<Item = &'b 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 // Encodes something that corresponds to a single DepNode::GlobalMetaData
302 // and registers the Fingerprint in the `metadata_hashes` map.
303 pub fn tracked<'x, DATA, R>(&'x mut self,
304 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
307 op(&mut IsolatedEncoder::new(self), data)
310 fn encode_info_for_items(&mut self) -> Index {
311 let krate = self.tcx.hir().krate();
312 let mut index = IndexBuilder::new(self);
313 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public };
314 index.record(DefId::local(CRATE_DEF_INDEX),
315 IsolatedEncoder::encode_info_for_mod,
316 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &vis)));
317 let mut visitor = EncodeVisitor { index };
318 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
319 for macro_def in &krate.exported_macros {
320 visitor.visit_macro_def(macro_def);
322 visitor.index.into_items()
325 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
326 let definitions = self.tcx.hir().definitions();
327 self.lazy(definitions.def_path_table())
330 fn encode_source_map(&mut self) -> LazySeq<syntax_pos::SourceFile> {
331 let source_map = self.tcx.sess.source_map();
332 let all_source_files = source_map.files();
334 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
336 let adapted = all_source_files.iter()
337 .filter(|source_file| {
338 // No need to re-export imported source_files, as any downstream
339 // crate will import them from their original source.
340 !source_file.is_imported()
343 match source_file.name {
344 // This path of this SourceFile has been modified by
345 // path-remapping, so we use it verbatim (and avoid
346 // cloning the whole map in the process).
347 _ if source_file.name_was_remapped => source_file.clone(),
349 // Otherwise expand all paths to absolute paths because
350 // any relative paths are potentially relative to a
352 FileName::Real(ref name) => {
353 let mut adapted = (**source_file).clone();
354 adapted.name = Path::new(&working_dir).join(name).into();
355 adapted.name_hash = {
356 let mut hasher: StableHasher<u128> = StableHasher::new();
357 adapted.name.hash(&mut hasher);
363 // expanded code, not from a file
364 _ => source_file.clone(),
367 .collect::<Vec<_>>();
369 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
372 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
373 let mut i = self.position();
375 let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
376 let dylib_dependency_formats = self.tracked(
377 IsolatedEncoder::encode_dylib_dependency_formats,
379 let dep_bytes = self.position() - i;
381 // Encode the lib features.
383 let lib_features = self.tracked(IsolatedEncoder::encode_lib_features, ());
384 let lib_feature_bytes = self.position() - i;
386 // Encode the language items.
388 let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
389 let lang_items_missing = self.tracked(
390 IsolatedEncoder::encode_lang_items_missing,
392 let lang_item_bytes = self.position() - i;
394 // Encode the native libraries used
396 let native_libraries = self.tracked(
397 IsolatedEncoder::encode_native_libraries,
399 let native_lib_bytes = self.position() - i;
401 let foreign_modules = self.tracked(
402 IsolatedEncoder::encode_foreign_modules,
407 let source_map = self.encode_source_map();
408 let source_map_bytes = self.position() - i;
410 // Encode DefPathTable
412 let def_path_table = self.encode_def_path_table();
413 let def_path_table_bytes = self.position() - i;
415 // Encode the def IDs of impls, for coherence checking.
417 let impls = self.tracked(IsolatedEncoder::encode_impls, ());
418 let impl_bytes = self.position() - i;
420 // Encode exported symbols info.
422 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
423 let exported_symbols = self.tracked(
424 IsolatedEncoder::encode_exported_symbols,
426 let exported_symbols_bytes = self.position() - i;
432 let items = self.encode_info_for_items();
433 let item_bytes = self.position() - i;
435 // Encode the allocation index
436 let interpret_alloc_index = {
437 let mut interpret_alloc_index = Vec::new();
439 trace!("beginning to encode alloc ids");
441 let new_n = self.interpret_allocs_inverse.len();
442 // if we have found new ids, serialize those, too
447 trace!("encoding {} further alloc ids", new_n - n);
448 for idx in n..new_n {
449 let id = self.interpret_allocs_inverse[idx];
450 let pos = self.position() as u32;
451 interpret_alloc_index.push(pos);
452 interpret::specialized_encode_alloc_id(
460 self.lazy_seq(interpret_alloc_index)
465 let index = items.write_index(&mut self.opaque);
466 let index_bytes = self.position() - i;
468 let attrs = tcx.hir().krate_attrs();
469 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
470 let has_default_lib_allocator = attr::contains_name(&attrs, "default_lib_allocator");
471 let has_global_allocator = *tcx.sess.has_global_allocator.get();
472 let has_panic_handler = *tcx.sess.has_panic_handler.try_get().unwrap_or(&false);
474 let root = self.lazy(&CrateRoot {
475 name: tcx.crate_name(LOCAL_CRATE),
476 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
477 triple: tcx.sess.opts.target_triple.clone(),
478 hash: tcx.crate_hash(LOCAL_CRATE),
479 disambiguator: tcx.sess.local_crate_disambiguator(),
480 panic_strategy: tcx.sess.panic_strategy(),
481 edition: hygiene::default_edition(),
482 has_global_allocator: has_global_allocator,
483 has_panic_handler: has_panic_handler,
484 has_default_lib_allocator: has_default_lib_allocator,
485 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
486 proc_macro_decls_static: if is_proc_macro {
487 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
493 compiler_builtins: attr::contains_name(&attrs, "compiler_builtins"),
494 needs_allocator: attr::contains_name(&attrs, "needs_allocator"),
495 needs_panic_runtime: attr::contains_name(&attrs, "needs_panic_runtime"),
496 no_builtins: attr::contains_name(&attrs, "no_builtins"),
497 panic_runtime: attr::contains_name(&attrs, "panic_runtime"),
498 profiler_runtime: attr::contains_name(&attrs, "profiler_runtime"),
499 sanitizer_runtime: attr::contains_name(&attrs, "sanitizer_runtime"),
502 dylib_dependency_formats,
512 interpret_alloc_index,
516 let total_bytes = self.position();
518 if self.tcx.sess.meta_stats() {
519 let mut zero_bytes = 0;
520 for e in self.opaque.data.iter() {
526 println!("metadata stats:");
527 println!(" dep bytes: {}", dep_bytes);
528 println!(" lib feature bytes: {}", lib_feature_bytes);
529 println!(" lang item bytes: {}", lang_item_bytes);
530 println!(" native bytes: {}", native_lib_bytes);
531 println!(" source_map bytes: {}", source_map_bytes);
532 println!(" impl bytes: {}", impl_bytes);
533 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
534 println!(" def-path table bytes: {}", def_path_table_bytes);
535 println!(" item bytes: {}", item_bytes);
536 println!(" index bytes: {}", index_bytes);
537 println!(" zero bytes: {}", zero_bytes);
538 println!(" total bytes: {}", total_bytes);
545 // These are methods for encoding various things. They are meant to be used with
546 // IndexBuilder::record() and EncodeContext::tracked(). They actually
547 // would not have to be methods of IsolatedEncoder (free standing functions
548 // taking IsolatedEncoder as first argument would be just fine) but by making
549 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
550 // clause again and again.
551 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
552 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
553 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
555 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
558 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
560 let ty = tcx.type_of(def_id);
561 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
565 /// Encode data for the given variant of the given ADT. The
566 /// index of the variant is untracked: this is ok because we
567 /// will have to lookup the adt-def by its id, and that gives us
568 /// the right to access any information in the adt-def (including,
569 /// e.g., the length of the various vectors).
570 fn encode_enum_variant_info(&mut self,
571 (enum_did, Untracked(index)): (DefId, Untracked<VariantIdx>))
574 let def = tcx.adt_def(enum_did);
575 let variant = &def.variants[index];
576 let def_id = variant.did;
577 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
579 let data = VariantData {
580 ctor_kind: variant.ctor_kind,
581 discr: variant.discr,
583 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
584 Some(self.lazy(&tcx.fn_sig(def_id)))
590 let enum_id = tcx.hir().as_local_node_id(enum_did).unwrap();
591 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
594 kind: EntryKind::Variant(self.lazy(&data)),
595 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
596 span: self.lazy(&tcx.def_span(def_id)),
597 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
598 children: self.lazy_seq(variant.fields.iter().map(|f| {
599 assert!(f.did.is_local());
602 stability: self.encode_stability(def_id),
603 deprecation: self.encode_deprecation(def_id),
605 ty: Some(self.encode_item_type(def_id)),
606 inherent_impls: LazySeq::empty(),
607 variances: if variant.ctor_kind == CtorKind::Fn {
608 self.encode_variances_of(def_id)
612 generics: Some(self.encode_generics(def_id)),
613 predicates: Some(self.encode_predicates(def_id)),
614 predicates_defined_on: None,
616 mir: self.encode_optimized_mir(def_id),
620 fn encode_info_for_mod(&mut self,
621 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
626 let def_id = tcx.hir().local_def_id(id);
627 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
630 reexports: match tcx.module_exports(def_id) {
631 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
632 _ => LazySeq::empty(),
637 kind: EntryKind::Mod(self.lazy(&data)),
638 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
639 span: self.lazy(&tcx.def_span(def_id)),
640 attributes: self.encode_attributes(attrs),
641 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
642 tcx.hir().local_def_id(item_id.id).index
644 stability: self.encode_stability(def_id),
645 deprecation: self.encode_deprecation(def_id),
648 inherent_impls: LazySeq::empty(),
649 variances: LazySeq::empty(),
652 predicates_defined_on: None,
658 /// Encode data for the given field of the given variant of the
659 /// given ADT. The indices of the variant/field are untracked:
660 /// this is ok because we will have to lookup the adt-def by its
661 /// id, and that gives us the right to access any information in
662 /// the adt-def (including, e.g., the length of the various
664 fn encode_field(&mut self,
665 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
666 Untracked<(VariantIdx,
670 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
671 let field = &variant.fields[field_index];
673 let def_id = field.did;
674 debug!("IsolatedEncoder::encode_field({:?})", def_id);
676 let variant_id = tcx.hir().as_local_node_id(variant.did).unwrap();
677 let variant_data = tcx.hir().expect_variant_data(variant_id);
680 kind: EntryKind::Field,
681 visibility: self.lazy(&field.vis),
682 span: self.lazy(&tcx.def_span(def_id)),
683 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
684 children: LazySeq::empty(),
685 stability: self.encode_stability(def_id),
686 deprecation: self.encode_deprecation(def_id),
688 ty: Some(self.encode_item_type(def_id)),
689 inherent_impls: LazySeq::empty(),
690 variances: LazySeq::empty(),
691 generics: Some(self.encode_generics(def_id)),
692 predicates: Some(self.encode_predicates(def_id)),
693 predicates_defined_on: None,
699 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
700 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
702 let adt_def = tcx.adt_def(adt_def_id);
703 let variant = adt_def.non_enum_variant();
705 let data = VariantData {
706 ctor_kind: variant.ctor_kind,
707 discr: variant.discr,
708 struct_ctor: Some(def_id.index),
709 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
710 Some(self.lazy(&tcx.fn_sig(def_id)))
716 let struct_id = tcx.hir().as_local_node_id(adt_def_id).unwrap();
717 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
718 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
719 for field in &variant.fields {
720 if ctor_vis.is_at_least(field.vis, tcx) {
721 ctor_vis = field.vis;
725 // If the structure is marked as non_exhaustive then lower the visibility
726 // to within the crate.
727 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
728 ctor_vis == ty::Visibility::Public
730 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
733 let repr_options = get_repr_options(&tcx, adt_def_id);
736 kind: EntryKind::Struct(self.lazy(&data), repr_options),
737 visibility: self.lazy(&ctor_vis),
738 span: self.lazy(&tcx.def_span(def_id)),
739 attributes: LazySeq::empty(),
740 children: LazySeq::empty(),
741 stability: self.encode_stability(def_id),
742 deprecation: self.encode_deprecation(def_id),
744 ty: Some(self.encode_item_type(def_id)),
745 inherent_impls: LazySeq::empty(),
746 variances: if variant.ctor_kind == CtorKind::Fn {
747 self.encode_variances_of(def_id)
751 generics: Some(self.encode_generics(def_id)),
752 predicates: Some(self.encode_predicates(def_id)),
753 predicates_defined_on: None,
755 mir: self.encode_optimized_mir(def_id),
759 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
760 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
762 self.lazy(tcx.generics_of(def_id))
765 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
766 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
768 self.lazy(&tcx.predicates_of(def_id))
771 fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
772 debug!("IsolatedEncoder::encode_predicates_defined_on({:?})", def_id);
774 self.lazy(&tcx.predicates_defined_on(def_id))
777 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
778 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
781 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
782 let ast_item = tcx.hir().expect_trait_item(node_id);
783 let trait_item = tcx.associated_item(def_id);
785 let container = match trait_item.defaultness {
786 hir::Defaultness::Default { has_value: true } =>
787 AssociatedContainer::TraitWithDefault,
788 hir::Defaultness::Default { has_value: false } =>
789 AssociatedContainer::TraitRequired,
790 hir::Defaultness::Final =>
791 span_bug!(ast_item.span, "traits cannot have final items"),
794 let kind = match trait_item.kind {
795 ty::AssociatedKind::Const => {
797 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
798 self.const_qualif(0, body)
800 ConstQualif { mir: 0, ast_promotable: false }
804 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
805 let rendered_const = self.lazy(&RenderedConst(rendered));
807 EntryKind::AssociatedConst(container, const_qualif, rendered_const)
809 ty::AssociatedKind::Method => {
810 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
811 let arg_names = match *m {
812 hir::TraitMethod::Required(ref names) => {
813 self.encode_fn_arg_names(names)
815 hir::TraitMethod::Provided(body) => {
816 self.encode_fn_arg_names_for_body(body)
820 constness: hir::Constness::NotConst,
822 sig: self.lazy(&tcx.fn_sig(def_id)),
827 EntryKind::Method(self.lazy(&MethodData {
830 has_self: trait_item.method_has_self_argument,
833 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
834 ty::AssociatedKind::Existential =>
835 span_bug!(ast_item.span, "existential type in trait"),
840 visibility: self.lazy(&trait_item.vis),
841 span: self.lazy(&ast_item.span),
842 attributes: self.encode_attributes(&ast_item.attrs),
843 children: LazySeq::empty(),
844 stability: self.encode_stability(def_id),
845 deprecation: self.encode_deprecation(def_id),
847 ty: match trait_item.kind {
848 ty::AssociatedKind::Const |
849 ty::AssociatedKind::Method => {
850 Some(self.encode_item_type(def_id))
852 ty::AssociatedKind::Type => {
853 if trait_item.defaultness.has_value() {
854 Some(self.encode_item_type(def_id))
859 ty::AssociatedKind::Existential => unreachable!(),
861 inherent_impls: LazySeq::empty(),
862 variances: if trait_item.kind == ty::AssociatedKind::Method {
863 self.encode_variances_of(def_id)
867 generics: Some(self.encode_generics(def_id)),
868 predicates: Some(self.encode_predicates(def_id)),
869 predicates_defined_on: None,
871 mir: self.encode_optimized_mir(def_id),
875 fn metadata_output_only(&self) -> bool {
876 // MIR optimisation can be skipped when we're just interested in the metadata.
877 !self.tcx.sess.opts.output_types.should_codegen()
880 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
881 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
882 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
884 ConstQualif { mir, ast_promotable }
887 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
888 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
891 let node_id = self.tcx.hir().as_local_node_id(def_id).unwrap();
892 let ast_item = self.tcx.hir().expect_impl_item(node_id);
893 let impl_item = self.tcx.associated_item(def_id);
895 let container = match impl_item.defaultness {
896 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
897 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
898 hir::Defaultness::Default { has_value: false } =>
899 span_bug!(ast_item.span, "impl items always have values (currently)"),
902 let kind = match impl_item.kind {
903 ty::AssociatedKind::Const => {
904 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
905 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
907 EntryKind::AssociatedConst(container,
908 self.const_qualif(mir, body_id),
909 self.encode_rendered_const_for_body(body_id))
914 ty::AssociatedKind::Method => {
915 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
917 constness: sig.header.constness,
918 arg_names: self.encode_fn_arg_names_for_body(body),
919 sig: self.lazy(&tcx.fn_sig(def_id)),
924 EntryKind::Method(self.lazy(&MethodData {
927 has_self: impl_item.method_has_self_argument,
930 ty::AssociatedKind::Existential => EntryKind::AssociatedExistential(container),
931 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
935 match ast_item.node {
936 hir::ImplItemKind::Const(..) => true,
937 hir::ImplItemKind::Method(ref sig, _) => {
938 let generics = self.tcx.generics_of(def_id);
939 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
940 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
941 !self.metadata_output_only();
942 let is_const_fn = sig.header.constness == hir::Constness::Const;
943 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
944 needs_inline || is_const_fn || always_encode_mir
946 hir::ImplItemKind::Existential(..) |
947 hir::ImplItemKind::Type(..) => false,
952 visibility: self.lazy(&impl_item.vis),
953 span: self.lazy(&ast_item.span),
954 attributes: self.encode_attributes(&ast_item.attrs),
955 children: LazySeq::empty(),
956 stability: self.encode_stability(def_id),
957 deprecation: self.encode_deprecation(def_id),
959 ty: Some(self.encode_item_type(def_id)),
960 inherent_impls: LazySeq::empty(),
961 variances: if impl_item.kind == ty::AssociatedKind::Method {
962 self.encode_variances_of(def_id)
966 generics: Some(self.encode_generics(def_id)),
967 predicates: Some(self.encode_predicates(def_id)),
968 predicates_defined_on: None,
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(_, _, _, ident, _) => ident.name,
981 _ => keywords::Invalid.name(),
987 fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> LazySeq<ast::Name> {
988 self.lazy_seq(param_names.iter().map(|ident| ident.name))
991 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
992 debug!("EntryBuilder::encode_mir({:?})", def_id);
993 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
994 let mir = self.tcx.optimized_mir(def_id);
995 Some(self.lazy(&mir))
1001 // Encodes the inherent implementations of a structure, enumeration, or trait.
1002 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1003 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
1004 let implementations = self.tcx.inherent_impls(def_id);
1005 if implementations.is_empty() {
1008 self.lazy_seq(implementations.iter().map(|&def_id| {
1009 assert!(def_id.is_local());
1015 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1016 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
1017 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1020 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1021 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
1022 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1025 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1026 let body = self.tcx.hir().body(body_id);
1027 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1028 let rendered_const = &RenderedConst(rendered);
1029 self.lazy(rendered_const)
1032 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1035 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
1037 let kind = match item.node {
1038 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1039 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1040 hir::ItemKind::Const(_, body_id) => {
1041 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1043 self.const_qualif(mir, body_id),
1044 self.encode_rendered_const_for_body(body_id)
1047 hir::ItemKind::Fn(_, header, .., body) => {
1049 constness: header.constness,
1050 arg_names: self.encode_fn_arg_names_for_body(body),
1051 sig: self.lazy(&tcx.fn_sig(def_id)),
1054 EntryKind::Fn(self.lazy(&data))
1056 hir::ItemKind::Mod(ref m) => {
1057 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
1059 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1060 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1061 hir::ItemKind::Ty(..) => EntryKind::Type,
1062 hir::ItemKind::Existential(..) => EntryKind::Existential,
1063 hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
1064 hir::ItemKind::Struct(ref struct_def, _) => {
1065 let variant = tcx.adt_def(def_id).non_enum_variant();
1067 // Encode def_ids for each field and method
1068 // for methods, write all the stuff get_trait_method
1070 let struct_ctor = if !struct_def.is_struct() {
1071 Some(tcx.hir().local_def_id(struct_def.id()).index)
1076 let repr_options = get_repr_options(&tcx, def_id);
1078 EntryKind::Struct(self.lazy(&VariantData {
1079 ctor_kind: variant.ctor_kind,
1080 discr: variant.discr,
1085 hir::ItemKind::Union(..) => {
1086 let variant = tcx.adt_def(def_id).non_enum_variant();
1087 let repr_options = get_repr_options(&tcx, def_id);
1089 EntryKind::Union(self.lazy(&VariantData {
1090 ctor_kind: variant.ctor_kind,
1091 discr: variant.discr,
1096 hir::ItemKind::Impl(_, polarity, defaultness, ..) => {
1097 let trait_ref = tcx.impl_trait_ref(def_id);
1098 let parent = if let Some(trait_ref) = trait_ref {
1099 let trait_def = tcx.trait_def(trait_ref.def_id);
1100 trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| {
1102 specialization_graph::Node::Impl(parent) => Some(parent),
1110 // if this is an impl of `CoerceUnsized`, create its
1111 // "unsized info", else just store None
1112 let coerce_unsized_info =
1113 trait_ref.and_then(|t| {
1114 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1115 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1121 let data = ImplData {
1124 parent_impl: parent,
1125 coerce_unsized_info,
1126 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1129 EntryKind::Impl(self.lazy(&data))
1131 hir::ItemKind::Trait(..) => {
1132 let trait_def = tcx.trait_def(def_id);
1133 let data = TraitData {
1134 unsafety: trait_def.unsafety,
1135 paren_sugar: trait_def.paren_sugar,
1136 has_auto_impl: tcx.trait_is_auto(def_id),
1137 is_marker: trait_def.is_marker,
1138 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1141 EntryKind::Trait(self.lazy(&data))
1143 hir::ItemKind::TraitAlias(..) => {
1144 let data = TraitAliasData {
1145 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1148 EntryKind::TraitAlias(self.lazy(&data))
1150 hir::ItemKind::ExternCrate(_) |
1151 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1156 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1157 span: self.lazy(&item.span),
1158 attributes: self.encode_attributes(&item.attrs),
1159 children: match item.node {
1160 hir::ItemKind::ForeignMod(ref fm) => {
1161 self.lazy_seq(fm.items
1163 .map(|foreign_item| tcx.hir().local_def_id(foreign_item.id).index))
1165 hir::ItemKind::Enum(..) => {
1166 let def = self.tcx.adt_def(def_id);
1167 self.lazy_seq(def.variants.iter().map(|v| {
1168 assert!(v.did.is_local());
1172 hir::ItemKind::Struct(..) |
1173 hir::ItemKind::Union(..) => {
1174 let def = self.tcx.adt_def(def_id);
1175 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1176 assert!(f.did.is_local());
1180 hir::ItemKind::Impl(..) |
1181 hir::ItemKind::Trait(..) => {
1182 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1183 assert!(def_id.is_local());
1187 _ => LazySeq::empty(),
1189 stability: self.encode_stability(def_id),
1190 deprecation: self.encode_deprecation(def_id),
1192 ty: match item.node {
1193 hir::ItemKind::Static(..) |
1194 hir::ItemKind::Const(..) |
1195 hir::ItemKind::Fn(..) |
1196 hir::ItemKind::Ty(..) |
1197 hir::ItemKind::Existential(..) |
1198 hir::ItemKind::Enum(..) |
1199 hir::ItemKind::Struct(..) |
1200 hir::ItemKind::Union(..) |
1201 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1204 inherent_impls: self.encode_inherent_implementations(def_id),
1205 variances: match item.node {
1206 hir::ItemKind::Enum(..) |
1207 hir::ItemKind::Struct(..) |
1208 hir::ItemKind::Union(..) |
1209 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1210 _ => LazySeq::empty(),
1212 generics: match item.node {
1213 hir::ItemKind::Static(..) |
1214 hir::ItemKind::Const(..) |
1215 hir::ItemKind::Fn(..) |
1216 hir::ItemKind::Ty(..) |
1217 hir::ItemKind::Enum(..) |
1218 hir::ItemKind::Struct(..) |
1219 hir::ItemKind::Union(..) |
1220 hir::ItemKind::Impl(..) |
1221 hir::ItemKind::Existential(..) |
1222 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1223 hir::ItemKind::TraitAlias(..) => Some(self.encode_generics(def_id)),
1226 predicates: match item.node {
1227 hir::ItemKind::Static(..) |
1228 hir::ItemKind::Const(..) |
1229 hir::ItemKind::Fn(..) |
1230 hir::ItemKind::Ty(..) |
1231 hir::ItemKind::Enum(..) |
1232 hir::ItemKind::Struct(..) |
1233 hir::ItemKind::Union(..) |
1234 hir::ItemKind::Impl(..) |
1235 hir::ItemKind::Existential(..) |
1236 hir::ItemKind::Trait(..) |
1237 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates(def_id)),
1241 // The only time that `predicates_defined_on` is used (on
1242 // an external item) is for traits, during chalk lowering,
1243 // so only encode it in that case as an efficiency
1244 // hack. (No reason not to expand it in the future if
1246 predicates_defined_on: match item.node {
1247 hir::ItemKind::Trait(..) |
1248 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates_defined_on(def_id)),
1249 _ => None, // not *wrong* for other kinds of items, but not needed
1252 mir: match item.node {
1253 hir::ItemKind::Static(..) => {
1254 self.encode_optimized_mir(def_id)
1256 hir::ItemKind::Const(..) => self.encode_optimized_mir(def_id),
1257 hir::ItemKind::Fn(_, header, ..) => {
1258 let generics = tcx.generics_of(def_id);
1260 (generics.requires_monomorphization(tcx) ||
1261 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1262 !self.metadata_output_only();
1263 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1265 || header.constness == hir::Constness::Const
1266 || always_encode_mir
1268 self.encode_optimized_mir(def_id)
1278 /// Serialize the text of exported macros
1279 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1280 use syntax::print::pprust;
1281 let def_id = self.tcx.hir().local_def_id(macro_def.id);
1283 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1284 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1285 legacy: macro_def.legacy,
1287 visibility: self.lazy(&ty::Visibility::Public),
1288 span: self.lazy(¯o_def.span),
1289 attributes: self.encode_attributes(¯o_def.attrs),
1290 stability: self.encode_stability(def_id),
1291 deprecation: self.encode_deprecation(def_id),
1293 children: LazySeq::empty(),
1295 inherent_impls: LazySeq::empty(),
1296 variances: LazySeq::empty(),
1299 predicates_defined_on: None,
1304 fn encode_info_for_ty_param(&mut self,
1305 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1307 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1310 kind: EntryKind::Type,
1311 visibility: self.lazy(&ty::Visibility::Public),
1312 span: self.lazy(&tcx.def_span(def_id)),
1313 attributes: LazySeq::empty(),
1314 children: LazySeq::empty(),
1318 ty: if has_default {
1319 Some(self.encode_item_type(def_id))
1323 inherent_impls: LazySeq::empty(),
1324 variances: LazySeq::empty(),
1327 predicates_defined_on: None,
1333 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1334 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1337 let tables = self.tcx.typeck_tables_of(def_id);
1338 let node_id = self.tcx.hir().as_local_node_id(def_id).unwrap();
1339 let hir_id = self.tcx.hir().node_to_hir_id(node_id);
1340 let kind = match tables.node_id_to_type(hir_id).sty {
1341 ty::Generator(def_id, ..) => {
1342 let layout = self.tcx.generator_layout(def_id);
1343 let data = GeneratorData {
1344 layout: layout.clone(),
1346 EntryKind::Generator(self.lazy(&data))
1349 ty::Closure(def_id, substs) => {
1350 let sig = substs.closure_sig(def_id, self.tcx);
1351 let data = ClosureData { sig: self.lazy(&sig) };
1352 EntryKind::Closure(self.lazy(&data))
1355 _ => bug!("closure that is neither generator nor closure")
1360 visibility: self.lazy(&ty::Visibility::Public),
1361 span: self.lazy(&tcx.def_span(def_id)),
1362 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1363 children: LazySeq::empty(),
1367 ty: Some(self.encode_item_type(def_id)),
1368 inherent_impls: LazySeq::empty(),
1369 variances: LazySeq::empty(),
1370 generics: Some(self.encode_generics(def_id)),
1372 predicates_defined_on: None,
1374 mir: self.encode_optimized_mir(def_id),
1378 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1379 debug!("IsolatedEncoder::encode_info_for_anon_const({:?})", def_id);
1381 let id = tcx.hir().as_local_node_id(def_id).unwrap();
1382 let body_id = tcx.hir().body_owned_by(id);
1383 let const_data = self.encode_rendered_const_for_body(body_id);
1384 let mir = tcx.mir_const_qualif(def_id).0;
1387 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1388 visibility: self.lazy(&ty::Visibility::Public),
1389 span: self.lazy(&tcx.def_span(def_id)),
1390 attributes: LazySeq::empty(),
1391 children: LazySeq::empty(),
1395 ty: Some(self.encode_item_type(def_id)),
1396 inherent_impls: LazySeq::empty(),
1397 variances: LazySeq::empty(),
1398 generics: Some(self.encode_generics(def_id)),
1399 predicates: Some(self.encode_predicates(def_id)),
1400 predicates_defined_on: None,
1402 mir: self.encode_optimized_mir(def_id),
1406 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1407 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1408 // we rely on the HashStable specialization for [Attribute]
1409 // to properly filter things out.
1410 self.lazy_seq_from_slice(attrs)
1413 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1414 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1415 self.lazy_seq(used_libraries.iter().cloned())
1418 fn encode_foreign_modules(&mut self, _: ()) -> LazySeq<ForeignModule> {
1419 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1420 self.lazy_seq(foreign_modules.iter().cloned())
1423 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1424 let crates = self.tcx.crates();
1426 let mut deps = crates
1429 let dep = CrateDep {
1430 name: self.tcx.original_crate_name(cnum),
1431 hash: self.tcx.crate_hash(cnum),
1432 kind: self.tcx.dep_kind(cnum),
1433 extra_filename: self.tcx.extra_filename(cnum),
1437 .collect::<Vec<_>>();
1439 deps.sort_by_key(|&(cnum, _)| cnum);
1442 // Sanity-check the crate numbers
1443 let mut expected_cnum = 1;
1444 for &(n, _) in &deps {
1445 assert_eq!(n, CrateNum::new(expected_cnum));
1450 // We're just going to write a list of crate 'name-hash-version's, with
1451 // the assumption that they are numbered 1 to n.
1452 // FIXME (#2166): This is not nearly enough to support correct versioning
1453 // but is enough to get transitive crate dependencies working.
1454 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1457 fn encode_lib_features(&mut self, _: ()) -> LazySeq<(ast::Name, Option<ast::Name>)> {
1459 let lib_features = tcx.lib_features();
1460 self.lazy_seq(lib_features.to_vec())
1463 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1465 let lang_items = tcx.lang_items();
1466 let lang_items = lang_items.items().iter();
1467 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1468 if let Some(def_id) = opt_def_id {
1469 if def_id.is_local() {
1470 return Some((def_id.index, i));
1477 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1479 self.lazy_seq_ref(&tcx.lang_items().missing)
1482 /// Encodes an index, mapping each trait to its (local) implementations.
1483 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1484 debug!("IsolatedEncoder::encode_impls()");
1486 let mut visitor = ImplVisitor {
1488 impls: FxHashMap::default(),
1490 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1492 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1494 // Bring everything into deterministic order for hashing
1495 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1496 tcx.def_path_hash(trait_def_id)
1499 let all_impls: Vec<_> = all_impls
1501 .map(|(trait_def_id, mut impls)| {
1502 // Bring everything into deterministic order for hashing
1503 impls.sort_by_cached_key(|&def_index| {
1504 tcx.hir().definitions().def_path_hash(def_index)
1508 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1509 impls: self.lazy_seq_from_slice(&impls[..]),
1514 self.lazy_seq_from_slice(&all_impls[..])
1517 // Encodes all symbols exported from this crate into the metadata.
1519 // This pass is seeded off the reachability list calculated in the
1520 // middle::reachable module but filters out items that either don't have a
1521 // symbol associated with them (they weren't translated) or if they're an FFI
1522 // definition (as that's not defined in this crate).
1523 fn encode_exported_symbols(&mut self,
1524 exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1525 -> EncodedExportedSymbols {
1526 // The metadata symbol name is special. It should not show up in
1527 // downstream crates.
1528 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1530 let lazy_seq = self.lazy_seq(exported_symbols
1532 .filter(|&&(ref exported_symbol, _)| {
1533 match *exported_symbol {
1534 ExportedSymbol::NoDefId(symbol_name) => {
1535 symbol_name != metadata_symbol_name
1542 EncodedExportedSymbols {
1544 position: lazy_seq.position,
1548 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1549 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateType::Dylib) {
1551 self.lazy_seq(arr.iter().map(|slot| {
1553 Linkage::NotLinked |
1554 Linkage::IncludedFromDylib => None,
1556 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1557 Linkage::Static => Some(LinkagePreference::RequireStatic),
1561 None => LazySeq::empty(),
1565 fn encode_info_for_foreign_item(&mut self,
1566 (def_id, nitem): (DefId, &hir::ForeignItem))
1570 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1572 let kind = match nitem.node {
1573 hir::ForeignItemKind::Fn(_, ref names, _) => {
1575 constness: hir::Constness::NotConst,
1576 arg_names: self.encode_fn_arg_names(names),
1577 sig: self.lazy(&tcx.fn_sig(def_id)),
1579 EntryKind::ForeignFn(self.lazy(&data))
1581 hir::ForeignItemKind::Static(_, true) => EntryKind::ForeignMutStatic,
1582 hir::ForeignItemKind::Static(_, false) => EntryKind::ForeignImmStatic,
1583 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1588 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1589 span: self.lazy(&nitem.span),
1590 attributes: self.encode_attributes(&nitem.attrs),
1591 children: LazySeq::empty(),
1592 stability: self.encode_stability(def_id),
1593 deprecation: self.encode_deprecation(def_id),
1595 ty: Some(self.encode_item_type(def_id)),
1596 inherent_impls: LazySeq::empty(),
1597 variances: match nitem.node {
1598 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1599 _ => LazySeq::empty(),
1601 generics: Some(self.encode_generics(def_id)),
1602 predicates: Some(self.encode_predicates(def_id)),
1603 predicates_defined_on: None,
1610 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1611 index: IndexBuilder<'a, 'b, 'tcx>,
1614 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1615 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1616 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir())
1618 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1619 intravisit::walk_expr(self, ex);
1620 self.index.encode_info_for_expr(ex);
1622 fn visit_item(&mut self, item: &'tcx hir::Item) {
1623 intravisit::walk_item(self, item);
1624 let def_id = self.index.tcx.hir().local_def_id(item.id);
1626 hir::ItemKind::ExternCrate(_) |
1627 hir::ItemKind::Use(..) => (), // ignore these
1628 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1630 self.index.encode_addl_info_for_item(item);
1632 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1633 intravisit::walk_foreign_item(self, ni);
1634 let def_id = self.index.tcx.hir().local_def_id(ni.id);
1635 self.index.record(def_id,
1636 IsolatedEncoder::encode_info_for_foreign_item,
1639 fn visit_variant(&mut self,
1640 v: &'tcx hir::Variant,
1641 g: &'tcx hir::Generics,
1643 intravisit::walk_variant(self, v, g, id);
1645 if let Some(ref discr) = v.node.disr_expr {
1646 let def_id = self.index.tcx.hir().local_def_id(discr.id);
1647 self.index.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1650 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1651 intravisit::walk_generics(self, generics);
1652 self.index.encode_info_for_generics(generics);
1654 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1655 intravisit::walk_ty(self, ty);
1656 self.index.encode_info_for_ty(ty);
1658 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1659 let def_id = self.index.tcx.hir().local_def_id(macro_def.id);
1660 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1664 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1665 fn encode_fields(&mut self, adt_def_id: DefId) {
1666 let def = self.tcx.adt_def(adt_def_id);
1667 for (variant_index, variant) in def.variants.iter_enumerated() {
1668 for (field_index, field) in variant.fields.iter().enumerate() {
1669 self.record(field.did,
1670 IsolatedEncoder::encode_field,
1671 (adt_def_id, Untracked((variant_index, field_index))));
1676 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1677 for param in &generics.params {
1679 hir::GenericParamKind::Lifetime { .. } => {}
1680 hir::GenericParamKind::Type { ref default, .. } => {
1681 let def_id = self.tcx.hir().local_def_id(param.id);
1682 let has_default = Untracked(default.is_some());
1683 let encode_info = IsolatedEncoder::encode_info_for_ty_param;
1684 self.record(def_id, encode_info, (def_id, has_default));
1690 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1692 hir::TyKind::Array(_, ref length) => {
1693 let def_id = self.tcx.hir().local_def_id(length.id);
1694 self.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1700 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1702 hir::ExprKind::Closure(..) => {
1703 let def_id = self.tcx.hir().local_def_id(expr.id);
1704 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1710 /// In some cases, along with the item itself, we also
1711 /// encode some sub-items. Usually we want some info from the item
1712 /// so it's easier to do that here then to wait until we would encounter
1713 /// normally in the visitor walk.
1714 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1715 let def_id = self.tcx.hir().local_def_id(item.id);
1717 hir::ItemKind::Static(..) |
1718 hir::ItemKind::Const(..) |
1719 hir::ItemKind::Fn(..) |
1720 hir::ItemKind::Mod(..) |
1721 hir::ItemKind::ForeignMod(..) |
1722 hir::ItemKind::GlobalAsm(..) |
1723 hir::ItemKind::ExternCrate(..) |
1724 hir::ItemKind::Use(..) |
1725 hir::ItemKind::Ty(..) |
1726 hir::ItemKind::Existential(..) |
1727 hir::ItemKind::TraitAlias(..) => {
1728 // no sub-item recording needed in these cases
1730 hir::ItemKind::Enum(..) => {
1731 self.encode_fields(def_id);
1733 let def = self.tcx.adt_def(def_id);
1734 for (i, variant) in def.variants.iter_enumerated() {
1735 self.record(variant.did,
1736 IsolatedEncoder::encode_enum_variant_info,
1737 (def_id, Untracked(i)));
1740 hir::ItemKind::Struct(ref struct_def, _) => {
1741 self.encode_fields(def_id);
1743 // If the struct has a constructor, encode it.
1744 if !struct_def.is_struct() {
1745 let ctor_def_id = self.tcx.hir().local_def_id(struct_def.id());
1746 self.record(ctor_def_id,
1747 IsolatedEncoder::encode_struct_ctor,
1748 (def_id, ctor_def_id));
1751 hir::ItemKind::Union(..) => {
1752 self.encode_fields(def_id);
1754 hir::ItemKind::Impl(..) => {
1755 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1756 self.record(trait_item_def_id,
1757 IsolatedEncoder::encode_info_for_impl_item,
1761 hir::ItemKind::Trait(..) => {
1762 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1763 self.record(item_def_id,
1764 IsolatedEncoder::encode_info_for_trait_item,
1772 struct ImplVisitor<'a, 'tcx: 'a> {
1773 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1774 impls: FxHashMap<DefId, Vec<DefIndex>>,
1777 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1778 fn visit_item(&mut self, item: &hir::Item) {
1779 if let hir::ItemKind::Impl(..) = item.node {
1780 let impl_id = self.tcx.hir().local_def_id(item.id);
1781 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1783 .entry(trait_ref.def_id)
1785 .push(impl_id.index);
1790 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1792 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1793 // handled in `visit_item` above
1797 // NOTE(eddyb) The following comment was preserved for posterity, even
1798 // though it's no longer relevant as EBML (which uses nested & tagged
1799 // "documents") was replaced with a scheme that can't go out of bounds.
1801 // And here we run into yet another obscure archive bug: in which metadata
1802 // loaded from archives may have trailing garbage bytes. Awhile back one of
1803 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1804 // and opt) by having ebml generate an out-of-bounds panic when looking at
1807 // Upon investigation it turned out that the metadata file inside of an rlib
1808 // (and ar archive) was being corrupted. Some compilations would generate a
1809 // metadata file which would end in a few extra bytes, while other
1810 // compilations would not have these extra bytes appended to the end. These
1811 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1812 // being interpreted causing the out-of-bounds.
1814 // The root cause of why these extra bytes were appearing was never
1815 // discovered, and in the meantime the solution we're employing is to insert
1816 // the length of the metadata to the start of the metadata. Later on this
1817 // will allow us to slice the metadata to the precise length that we just
1818 // generated regardless of trailing bytes that end up in it.
1820 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
1823 let mut encoder = opaque::Encoder::new(vec![]);
1824 encoder.emit_raw_bytes(METADATA_HEADER);
1826 // Will be filled with the root position after encoding everything.
1827 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1829 let (root, mut result) = {
1830 let mut ecx = EncodeContext {
1833 lazy_state: LazyState::NoNode,
1834 type_shorthands: Default::default(),
1835 predicate_shorthands: Default::default(),
1836 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1837 interpret_allocs: Default::default(),
1838 interpret_allocs_inverse: Default::default(),
1841 // Encode the rustc version string in a predictable location.
1842 rustc_version().encode(&mut ecx).unwrap();
1844 // Encode all the entries and extra information in the crate,
1845 // culminating in the `CrateRoot` which points to all of it.
1846 let root = ecx.encode_crate_root();
1847 (root, ecx.opaque.into_inner())
1850 // Encode the root position.
1851 let header = METADATA_HEADER.len();
1852 let pos = root.position;
1853 result[header + 0] = (pos >> 24) as u8;
1854 result[header + 1] = (pos >> 16) as u8;
1855 result[header + 2] = (pos >> 8) as u8;
1856 result[header + 3] = (pos >> 0) as u8;
1858 EncodedMetadata { raw_data: result }
1861 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1862 let ty = tcx.type_of(did);
1864 ty::Adt(ref def, _) => return def.repr,
1865 _ => bug!("{} is not an ADT", ty),