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.sess
488 .map(|id| tcx.hir().local_def_id(id).index),
489 proc_macro_decls_static: if is_proc_macro {
490 let id = tcx.sess.proc_macro_decls_static.get().unwrap();
491 Some(tcx.hir().local_def_id(id).index)
496 compiler_builtins: attr::contains_name(&attrs, "compiler_builtins"),
497 needs_allocator: attr::contains_name(&attrs, "needs_allocator"),
498 needs_panic_runtime: attr::contains_name(&attrs, "needs_panic_runtime"),
499 no_builtins: attr::contains_name(&attrs, "no_builtins"),
500 panic_runtime: attr::contains_name(&attrs, "panic_runtime"),
501 profiler_runtime: attr::contains_name(&attrs, "profiler_runtime"),
502 sanitizer_runtime: attr::contains_name(&attrs, "sanitizer_runtime"),
505 dylib_dependency_formats,
515 interpret_alloc_index,
519 let total_bytes = self.position();
521 if self.tcx.sess.meta_stats() {
522 let mut zero_bytes = 0;
523 for e in self.opaque.data.iter() {
529 println!("metadata stats:");
530 println!(" dep bytes: {}", dep_bytes);
531 println!(" lib feature bytes: {}", lib_feature_bytes);
532 println!(" lang item bytes: {}", lang_item_bytes);
533 println!(" native bytes: {}", native_lib_bytes);
534 println!(" source_map bytes: {}", source_map_bytes);
535 println!(" impl bytes: {}", impl_bytes);
536 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
537 println!(" def-path table bytes: {}", def_path_table_bytes);
538 println!(" item bytes: {}", item_bytes);
539 println!(" index bytes: {}", index_bytes);
540 println!(" zero bytes: {}", zero_bytes);
541 println!(" total bytes: {}", total_bytes);
548 // These are methods for encoding various things. They are meant to be used with
549 // IndexBuilder::record() and EncodeContext::tracked(). They actually
550 // would not have to be methods of IsolatedEncoder (free standing functions
551 // taking IsolatedEncoder as first argument would be just fine) but by making
552 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
553 // clause again and again.
554 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
555 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
556 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
558 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
561 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
563 let ty = tcx.type_of(def_id);
564 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
568 /// Encode data for the given variant of the given ADT. The
569 /// index of the variant is untracked: this is ok because we
570 /// will have to lookup the adt-def by its id, and that gives us
571 /// the right to access any information in the adt-def (including,
572 /// e.g., the length of the various vectors).
573 fn encode_enum_variant_info(&mut self,
574 (enum_did, Untracked(index)): (DefId, Untracked<VariantIdx>))
577 let def = tcx.adt_def(enum_did);
578 let variant = &def.variants[index];
579 let def_id = variant.did;
580 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
582 let data = VariantData {
583 ctor_kind: variant.ctor_kind,
584 discr: variant.discr,
586 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
587 Some(self.lazy(&tcx.fn_sig(def_id)))
593 let enum_id = tcx.hir().as_local_node_id(enum_did).unwrap();
594 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
597 kind: EntryKind::Variant(self.lazy(&data)),
598 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
599 span: self.lazy(&tcx.def_span(def_id)),
600 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
601 children: self.lazy_seq(variant.fields.iter().map(|f| {
602 assert!(f.did.is_local());
605 stability: self.encode_stability(def_id),
606 deprecation: self.encode_deprecation(def_id),
608 ty: Some(self.encode_item_type(def_id)),
609 inherent_impls: LazySeq::empty(),
610 variances: if variant.ctor_kind == CtorKind::Fn {
611 self.encode_variances_of(def_id)
615 generics: Some(self.encode_generics(def_id)),
616 predicates: Some(self.encode_predicates(def_id)),
617 predicates_defined_on: None,
619 mir: self.encode_optimized_mir(def_id),
623 fn encode_info_for_mod(&mut self,
624 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
629 let def_id = tcx.hir().local_def_id(id);
630 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
633 reexports: match tcx.module_exports(def_id) {
634 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
635 _ => LazySeq::empty(),
640 kind: EntryKind::Mod(self.lazy(&data)),
641 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
642 span: self.lazy(&tcx.def_span(def_id)),
643 attributes: self.encode_attributes(attrs),
644 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
645 tcx.hir().local_def_id(item_id.id).index
647 stability: self.encode_stability(def_id),
648 deprecation: self.encode_deprecation(def_id),
651 inherent_impls: LazySeq::empty(),
652 variances: LazySeq::empty(),
655 predicates_defined_on: None,
661 /// Encode data for the given field of the given variant of the
662 /// given ADT. The indices of the variant/field are untracked:
663 /// this is ok because we will have to lookup the adt-def by its
664 /// id, and that gives us the right to access any information in
665 /// the adt-def (including, e.g., the length of the various
667 fn encode_field(&mut self,
668 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
669 Untracked<(VariantIdx,
673 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
674 let field = &variant.fields[field_index];
676 let def_id = field.did;
677 debug!("IsolatedEncoder::encode_field({:?})", def_id);
679 let variant_id = tcx.hir().as_local_node_id(variant.did).unwrap();
680 let variant_data = tcx.hir().expect_variant_data(variant_id);
683 kind: EntryKind::Field,
684 visibility: self.lazy(&field.vis),
685 span: self.lazy(&tcx.def_span(def_id)),
686 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
687 children: LazySeq::empty(),
688 stability: self.encode_stability(def_id),
689 deprecation: self.encode_deprecation(def_id),
691 ty: Some(self.encode_item_type(def_id)),
692 inherent_impls: LazySeq::empty(),
693 variances: LazySeq::empty(),
694 generics: Some(self.encode_generics(def_id)),
695 predicates: Some(self.encode_predicates(def_id)),
696 predicates_defined_on: None,
702 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
703 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
705 let adt_def = tcx.adt_def(adt_def_id);
706 let variant = adt_def.non_enum_variant();
708 let data = VariantData {
709 ctor_kind: variant.ctor_kind,
710 discr: variant.discr,
711 struct_ctor: Some(def_id.index),
712 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
713 Some(self.lazy(&tcx.fn_sig(def_id)))
719 let struct_id = tcx.hir().as_local_node_id(adt_def_id).unwrap();
720 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
721 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
722 for field in &variant.fields {
723 if ctor_vis.is_at_least(field.vis, tcx) {
724 ctor_vis = field.vis;
728 // If the structure is marked as non_exhaustive then lower the visibility
729 // to within the crate.
730 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
731 ctor_vis == ty::Visibility::Public
733 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
736 let repr_options = get_repr_options(&tcx, adt_def_id);
739 kind: EntryKind::Struct(self.lazy(&data), repr_options),
740 visibility: self.lazy(&ctor_vis),
741 span: self.lazy(&tcx.def_span(def_id)),
742 attributes: LazySeq::empty(),
743 children: LazySeq::empty(),
744 stability: self.encode_stability(def_id),
745 deprecation: self.encode_deprecation(def_id),
747 ty: Some(self.encode_item_type(def_id)),
748 inherent_impls: LazySeq::empty(),
749 variances: if variant.ctor_kind == CtorKind::Fn {
750 self.encode_variances_of(def_id)
754 generics: Some(self.encode_generics(def_id)),
755 predicates: Some(self.encode_predicates(def_id)),
756 predicates_defined_on: None,
758 mir: self.encode_optimized_mir(def_id),
762 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
763 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
765 self.lazy(tcx.generics_of(def_id))
768 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
769 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
771 self.lazy(&tcx.predicates_of(def_id))
774 fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
775 debug!("IsolatedEncoder::encode_predicates_defined_on({:?})", def_id);
777 self.lazy(&tcx.predicates_defined_on(def_id))
780 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
781 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
784 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
785 let ast_item = tcx.hir().expect_trait_item(node_id);
786 let trait_item = tcx.associated_item(def_id);
788 let container = match trait_item.defaultness {
789 hir::Defaultness::Default { has_value: true } =>
790 AssociatedContainer::TraitWithDefault,
791 hir::Defaultness::Default { has_value: false } =>
792 AssociatedContainer::TraitRequired,
793 hir::Defaultness::Final =>
794 span_bug!(ast_item.span, "traits cannot have final items"),
797 let kind = match trait_item.kind {
798 ty::AssociatedKind::Const => {
800 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
801 self.const_qualif(0, body)
803 ConstQualif { mir: 0, ast_promotable: false }
807 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
808 let rendered_const = self.lazy(&RenderedConst(rendered));
810 EntryKind::AssociatedConst(container, const_qualif, rendered_const)
812 ty::AssociatedKind::Method => {
813 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
814 let arg_names = match *m {
815 hir::TraitMethod::Required(ref names) => {
816 self.encode_fn_arg_names(names)
818 hir::TraitMethod::Provided(body) => {
819 self.encode_fn_arg_names_for_body(body)
823 constness: hir::Constness::NotConst,
825 sig: self.lazy(&tcx.fn_sig(def_id)),
830 EntryKind::Method(self.lazy(&MethodData {
833 has_self: trait_item.method_has_self_argument,
836 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
837 ty::AssociatedKind::Existential =>
838 span_bug!(ast_item.span, "existential type in trait"),
843 visibility: self.lazy(&trait_item.vis),
844 span: self.lazy(&ast_item.span),
845 attributes: self.encode_attributes(&ast_item.attrs),
846 children: LazySeq::empty(),
847 stability: self.encode_stability(def_id),
848 deprecation: self.encode_deprecation(def_id),
850 ty: match trait_item.kind {
851 ty::AssociatedKind::Const |
852 ty::AssociatedKind::Method => {
853 Some(self.encode_item_type(def_id))
855 ty::AssociatedKind::Type => {
856 if trait_item.defaultness.has_value() {
857 Some(self.encode_item_type(def_id))
862 ty::AssociatedKind::Existential => unreachable!(),
864 inherent_impls: LazySeq::empty(),
865 variances: if trait_item.kind == ty::AssociatedKind::Method {
866 self.encode_variances_of(def_id)
870 generics: Some(self.encode_generics(def_id)),
871 predicates: Some(self.encode_predicates(def_id)),
872 predicates_defined_on: None,
874 mir: self.encode_optimized_mir(def_id),
878 fn metadata_output_only(&self) -> bool {
879 // MIR optimisation can be skipped when we're just interested in the metadata.
880 !self.tcx.sess.opts.output_types.should_codegen()
883 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
884 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
885 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
887 ConstQualif { mir, ast_promotable }
890 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
891 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
894 let node_id = self.tcx.hir().as_local_node_id(def_id).unwrap();
895 let ast_item = self.tcx.hir().expect_impl_item(node_id);
896 let impl_item = self.tcx.associated_item(def_id);
898 let container = match impl_item.defaultness {
899 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
900 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
901 hir::Defaultness::Default { has_value: false } =>
902 span_bug!(ast_item.span, "impl items always have values (currently)"),
905 let kind = match impl_item.kind {
906 ty::AssociatedKind::Const => {
907 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
908 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
910 EntryKind::AssociatedConst(container,
911 self.const_qualif(mir, body_id),
912 self.encode_rendered_const_for_body(body_id))
917 ty::AssociatedKind::Method => {
918 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
920 constness: sig.header.constness,
921 arg_names: self.encode_fn_arg_names_for_body(body),
922 sig: self.lazy(&tcx.fn_sig(def_id)),
927 EntryKind::Method(self.lazy(&MethodData {
930 has_self: impl_item.method_has_self_argument,
933 ty::AssociatedKind::Existential => EntryKind::AssociatedExistential(container),
934 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
938 match ast_item.node {
939 hir::ImplItemKind::Const(..) => true,
940 hir::ImplItemKind::Method(ref sig, _) => {
941 let generics = self.tcx.generics_of(def_id);
942 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
943 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
944 !self.metadata_output_only();
945 let is_const_fn = sig.header.constness == hir::Constness::Const;
946 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
947 needs_inline || is_const_fn || always_encode_mir
949 hir::ImplItemKind::Existential(..) |
950 hir::ImplItemKind::Type(..) => false,
955 visibility: self.lazy(&impl_item.vis),
956 span: self.lazy(&ast_item.span),
957 attributes: self.encode_attributes(&ast_item.attrs),
958 children: LazySeq::empty(),
959 stability: self.encode_stability(def_id),
960 deprecation: self.encode_deprecation(def_id),
962 ty: Some(self.encode_item_type(def_id)),
963 inherent_impls: LazySeq::empty(),
964 variances: if impl_item.kind == ty::AssociatedKind::Method {
965 self.encode_variances_of(def_id)
969 generics: Some(self.encode_generics(def_id)),
970 predicates: Some(self.encode_predicates(def_id)),
971 predicates_defined_on: None,
973 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
977 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
978 -> LazySeq<ast::Name> {
979 self.tcx.dep_graph.with_ignore(|| {
980 let body = self.tcx.hir().body(body_id);
981 self.lazy_seq(body.arguments.iter().map(|arg| {
983 PatKind::Binding(_, _, ident, _) => ident.name,
984 _ => keywords::Invalid.name(),
990 fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> LazySeq<ast::Name> {
991 self.lazy_seq(param_names.iter().map(|ident| ident.name))
994 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
995 debug!("EntryBuilder::encode_mir({:?})", def_id);
996 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
997 let mir = self.tcx.optimized_mir(def_id);
998 Some(self.lazy(&mir))
1004 // Encodes the inherent implementations of a structure, enumeration, or trait.
1005 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1006 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
1007 let implementations = self.tcx.inherent_impls(def_id);
1008 if implementations.is_empty() {
1011 self.lazy_seq(implementations.iter().map(|&def_id| {
1012 assert!(def_id.is_local());
1018 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1019 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
1020 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1023 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1024 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
1025 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1028 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1029 let body = self.tcx.hir().body(body_id);
1030 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1031 let rendered_const = &RenderedConst(rendered);
1032 self.lazy(rendered_const)
1035 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1038 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
1040 let kind = match item.node {
1041 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1042 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1043 hir::ItemKind::Const(_, body_id) => {
1044 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1046 self.const_qualif(mir, body_id),
1047 self.encode_rendered_const_for_body(body_id)
1050 hir::ItemKind::Fn(_, header, .., body) => {
1052 constness: header.constness,
1053 arg_names: self.encode_fn_arg_names_for_body(body),
1054 sig: self.lazy(&tcx.fn_sig(def_id)),
1057 EntryKind::Fn(self.lazy(&data))
1059 hir::ItemKind::Mod(ref m) => {
1060 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
1062 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1063 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1064 hir::ItemKind::Ty(..) => EntryKind::Type,
1065 hir::ItemKind::Existential(..) => EntryKind::Existential,
1066 hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
1067 hir::ItemKind::Struct(ref struct_def, _) => {
1068 let variant = tcx.adt_def(def_id).non_enum_variant();
1070 // Encode def_ids for each field and method
1071 // for methods, write all the stuff get_trait_method
1073 let struct_ctor = if !struct_def.is_struct() {
1074 Some(tcx.hir().local_def_id(struct_def.id()).index)
1079 let repr_options = get_repr_options(&tcx, def_id);
1081 EntryKind::Struct(self.lazy(&VariantData {
1082 ctor_kind: variant.ctor_kind,
1083 discr: variant.discr,
1088 hir::ItemKind::Union(..) => {
1089 let variant = tcx.adt_def(def_id).non_enum_variant();
1090 let repr_options = get_repr_options(&tcx, def_id);
1092 EntryKind::Union(self.lazy(&VariantData {
1093 ctor_kind: variant.ctor_kind,
1094 discr: variant.discr,
1099 hir::ItemKind::Impl(_, polarity, defaultness, ..) => {
1100 let trait_ref = tcx.impl_trait_ref(def_id);
1101 let parent = if let Some(trait_ref) = trait_ref {
1102 let trait_def = tcx.trait_def(trait_ref.def_id);
1103 trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| {
1105 specialization_graph::Node::Impl(parent) => Some(parent),
1113 // if this is an impl of `CoerceUnsized`, create its
1114 // "unsized info", else just store None
1115 let coerce_unsized_info =
1116 trait_ref.and_then(|t| {
1117 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1118 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1124 let data = ImplData {
1127 parent_impl: parent,
1128 coerce_unsized_info,
1129 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1132 EntryKind::Impl(self.lazy(&data))
1134 hir::ItemKind::Trait(..) |
1135 hir::ItemKind::TraitAlias(..) => {
1136 let trait_def = tcx.trait_def(def_id);
1137 let data = TraitData {
1138 unsafety: trait_def.unsafety,
1139 paren_sugar: trait_def.paren_sugar,
1140 has_auto_impl: tcx.trait_is_auto(def_id),
1141 is_marker: trait_def.is_marker,
1142 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1145 EntryKind::Trait(self.lazy(&data))
1147 hir::ItemKind::ExternCrate(_) |
1148 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1153 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1154 span: self.lazy(&item.span),
1155 attributes: self.encode_attributes(&item.attrs),
1156 children: match item.node {
1157 hir::ItemKind::ForeignMod(ref fm) => {
1158 self.lazy_seq(fm.items
1160 .map(|foreign_item| tcx.hir().local_def_id(foreign_item.id).index))
1162 hir::ItemKind::Enum(..) => {
1163 let def = self.tcx.adt_def(def_id);
1164 self.lazy_seq(def.variants.iter().map(|v| {
1165 assert!(v.did.is_local());
1169 hir::ItemKind::Struct(..) |
1170 hir::ItemKind::Union(..) => {
1171 let def = self.tcx.adt_def(def_id);
1172 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1173 assert!(f.did.is_local());
1177 hir::ItemKind::Impl(..) |
1178 hir::ItemKind::Trait(..) => {
1179 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1180 assert!(def_id.is_local());
1184 _ => LazySeq::empty(),
1186 stability: self.encode_stability(def_id),
1187 deprecation: self.encode_deprecation(def_id),
1189 ty: match item.node {
1190 hir::ItemKind::Static(..) |
1191 hir::ItemKind::Const(..) |
1192 hir::ItemKind::Fn(..) |
1193 hir::ItemKind::Ty(..) |
1194 hir::ItemKind::Existential(..) |
1195 hir::ItemKind::Enum(..) |
1196 hir::ItemKind::Struct(..) |
1197 hir::ItemKind::Union(..) |
1198 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1201 inherent_impls: self.encode_inherent_implementations(def_id),
1202 variances: match item.node {
1203 hir::ItemKind::Enum(..) |
1204 hir::ItemKind::Struct(..) |
1205 hir::ItemKind::Union(..) |
1206 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1207 _ => LazySeq::empty(),
1209 generics: match item.node {
1210 hir::ItemKind::Static(..) |
1211 hir::ItemKind::Const(..) |
1212 hir::ItemKind::Fn(..) |
1213 hir::ItemKind::Ty(..) |
1214 hir::ItemKind::Enum(..) |
1215 hir::ItemKind::Struct(..) |
1216 hir::ItemKind::Union(..) |
1217 hir::ItemKind::Impl(..) |
1218 hir::ItemKind::Existential(..) |
1219 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1222 predicates: match item.node {
1223 hir::ItemKind::Static(..) |
1224 hir::ItemKind::Const(..) |
1225 hir::ItemKind::Fn(..) |
1226 hir::ItemKind::Ty(..) |
1227 hir::ItemKind::Enum(..) |
1228 hir::ItemKind::Struct(..) |
1229 hir::ItemKind::Union(..) |
1230 hir::ItemKind::Impl(..) |
1231 hir::ItemKind::Existential(..) |
1232 hir::ItemKind::Trait(..) => Some(self.encode_predicates(def_id)),
1236 // The only time that `predicates_defined_on` is used (on
1237 // an external item) is for traits, during chalk lowering,
1238 // so only encode it in that case as an efficiency
1239 // hack. (No reason not to expand it in the future if
1241 predicates_defined_on: match item.node {
1242 hir::ItemKind::Trait(..) => Some(self.encode_predicates_defined_on(def_id)),
1243 _ => None, // not *wrong* for other kinds of items, but not needed
1246 mir: match item.node {
1247 hir::ItemKind::Static(..) => {
1248 self.encode_optimized_mir(def_id)
1250 hir::ItemKind::Const(..) => self.encode_optimized_mir(def_id),
1251 hir::ItemKind::Fn(_, header, ..) => {
1252 let generics = tcx.generics_of(def_id);
1254 (generics.requires_monomorphization(tcx) ||
1255 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1256 !self.metadata_output_only();
1257 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1259 || header.constness == hir::Constness::Const
1260 || always_encode_mir
1262 self.encode_optimized_mir(def_id)
1272 /// Serialize the text of exported macros
1273 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1274 use syntax::print::pprust;
1275 let def_id = self.tcx.hir().local_def_id(macro_def.id);
1277 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1278 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1279 legacy: macro_def.legacy,
1281 visibility: self.lazy(&ty::Visibility::Public),
1282 span: self.lazy(¯o_def.span),
1283 attributes: self.encode_attributes(¯o_def.attrs),
1284 stability: self.encode_stability(def_id),
1285 deprecation: self.encode_deprecation(def_id),
1287 children: LazySeq::empty(),
1289 inherent_impls: LazySeq::empty(),
1290 variances: LazySeq::empty(),
1293 predicates_defined_on: None,
1298 fn encode_info_for_ty_param(&mut self,
1299 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1301 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1304 kind: EntryKind::Type,
1305 visibility: self.lazy(&ty::Visibility::Public),
1306 span: self.lazy(&tcx.def_span(def_id)),
1307 attributes: LazySeq::empty(),
1308 children: LazySeq::empty(),
1312 ty: if has_default {
1313 Some(self.encode_item_type(def_id))
1317 inherent_impls: LazySeq::empty(),
1318 variances: LazySeq::empty(),
1321 predicates_defined_on: None,
1327 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1328 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1331 let tables = self.tcx.typeck_tables_of(def_id);
1332 let node_id = self.tcx.hir().as_local_node_id(def_id).unwrap();
1333 let hir_id = self.tcx.hir().node_to_hir_id(node_id);
1334 let kind = match tables.node_id_to_type(hir_id).sty {
1335 ty::Generator(def_id, ..) => {
1336 let layout = self.tcx.generator_layout(def_id);
1337 let data = GeneratorData {
1338 layout: layout.clone(),
1340 EntryKind::Generator(self.lazy(&data))
1343 ty::Closure(def_id, substs) => {
1344 let sig = substs.closure_sig(def_id, self.tcx);
1345 let data = ClosureData { sig: self.lazy(&sig) };
1346 EntryKind::Closure(self.lazy(&data))
1349 _ => bug!("closure that is neither generator nor closure")
1354 visibility: self.lazy(&ty::Visibility::Public),
1355 span: self.lazy(&tcx.def_span(def_id)),
1356 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1357 children: LazySeq::empty(),
1361 ty: Some(self.encode_item_type(def_id)),
1362 inherent_impls: LazySeq::empty(),
1363 variances: LazySeq::empty(),
1364 generics: Some(self.encode_generics(def_id)),
1366 predicates_defined_on: None,
1368 mir: self.encode_optimized_mir(def_id),
1372 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1373 debug!("IsolatedEncoder::encode_info_for_anon_const({:?})", def_id);
1375 let id = tcx.hir().as_local_node_id(def_id).unwrap();
1376 let body_id = tcx.hir().body_owned_by(id);
1377 let const_data = self.encode_rendered_const_for_body(body_id);
1378 let mir = tcx.mir_const_qualif(def_id).0;
1381 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1382 visibility: self.lazy(&ty::Visibility::Public),
1383 span: self.lazy(&tcx.def_span(def_id)),
1384 attributes: LazySeq::empty(),
1385 children: LazySeq::empty(),
1389 ty: Some(self.encode_item_type(def_id)),
1390 inherent_impls: LazySeq::empty(),
1391 variances: LazySeq::empty(),
1392 generics: Some(self.encode_generics(def_id)),
1393 predicates: Some(self.encode_predicates(def_id)),
1394 predicates_defined_on: None,
1396 mir: self.encode_optimized_mir(def_id),
1400 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1401 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1402 // we rely on the HashStable specialization for [Attribute]
1403 // to properly filter things out.
1404 self.lazy_seq_from_slice(attrs)
1407 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1408 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1409 self.lazy_seq(used_libraries.iter().cloned())
1412 fn encode_foreign_modules(&mut self, _: ()) -> LazySeq<ForeignModule> {
1413 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1414 self.lazy_seq(foreign_modules.iter().cloned())
1417 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1418 let crates = self.tcx.crates();
1420 let mut deps = crates
1423 let dep = CrateDep {
1424 name: self.tcx.original_crate_name(cnum),
1425 hash: self.tcx.crate_hash(cnum),
1426 kind: self.tcx.dep_kind(cnum),
1427 extra_filename: self.tcx.extra_filename(cnum),
1431 .collect::<Vec<_>>();
1433 deps.sort_by_key(|&(cnum, _)| cnum);
1436 // Sanity-check the crate numbers
1437 let mut expected_cnum = 1;
1438 for &(n, _) in &deps {
1439 assert_eq!(n, CrateNum::new(expected_cnum));
1444 // We're just going to write a list of crate 'name-hash-version's, with
1445 // the assumption that they are numbered 1 to n.
1446 // FIXME (#2166): This is not nearly enough to support correct versioning
1447 // but is enough to get transitive crate dependencies working.
1448 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1451 fn encode_lib_features(&mut self, _: ()) -> LazySeq<(ast::Name, Option<ast::Name>)> {
1453 let lib_features = tcx.lib_features();
1454 self.lazy_seq(lib_features.to_vec())
1457 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1459 let lang_items = tcx.lang_items();
1460 let lang_items = lang_items.items().iter();
1461 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1462 if let Some(def_id) = opt_def_id {
1463 if def_id.is_local() {
1464 return Some((def_id.index, i));
1471 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1473 self.lazy_seq_ref(&tcx.lang_items().missing)
1476 /// Encodes an index, mapping each trait to its (local) implementations.
1477 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1478 debug!("IsolatedEncoder::encode_impls()");
1480 let mut visitor = ImplVisitor {
1482 impls: FxHashMap::default(),
1484 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1486 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1488 // Bring everything into deterministic order for hashing
1489 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1490 tcx.def_path_hash(trait_def_id)
1493 let all_impls: Vec<_> = all_impls
1495 .map(|(trait_def_id, mut impls)| {
1496 // Bring everything into deterministic order for hashing
1497 impls.sort_by_cached_key(|&def_index| {
1498 tcx.hir().definitions().def_path_hash(def_index)
1502 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1503 impls: self.lazy_seq_from_slice(&impls[..]),
1508 self.lazy_seq_from_slice(&all_impls[..])
1511 // Encodes all symbols exported from this crate into the metadata.
1513 // This pass is seeded off the reachability list calculated in the
1514 // middle::reachable module but filters out items that either don't have a
1515 // symbol associated with them (they weren't translated) or if they're an FFI
1516 // definition (as that's not defined in this crate).
1517 fn encode_exported_symbols(&mut self,
1518 exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1519 -> EncodedExportedSymbols {
1520 // The metadata symbol name is special. It should not show up in
1521 // downstream crates.
1522 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1524 let lazy_seq = self.lazy_seq(exported_symbols
1526 .filter(|&&(ref exported_symbol, _)| {
1527 match *exported_symbol {
1528 ExportedSymbol::NoDefId(symbol_name) => {
1529 symbol_name != metadata_symbol_name
1536 EncodedExportedSymbols {
1538 position: lazy_seq.position,
1542 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1543 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateType::Dylib) {
1545 self.lazy_seq(arr.iter().map(|slot| {
1547 Linkage::NotLinked |
1548 Linkage::IncludedFromDylib => None,
1550 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1551 Linkage::Static => Some(LinkagePreference::RequireStatic),
1555 None => LazySeq::empty(),
1559 fn encode_info_for_foreign_item(&mut self,
1560 (def_id, nitem): (DefId, &hir::ForeignItem))
1564 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1566 let kind = match nitem.node {
1567 hir::ForeignItemKind::Fn(_, ref names, _) => {
1569 constness: hir::Constness::NotConst,
1570 arg_names: self.encode_fn_arg_names(names),
1571 sig: self.lazy(&tcx.fn_sig(def_id)),
1573 EntryKind::ForeignFn(self.lazy(&data))
1575 hir::ForeignItemKind::Static(_, true) => EntryKind::ForeignMutStatic,
1576 hir::ForeignItemKind::Static(_, false) => EntryKind::ForeignImmStatic,
1577 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1582 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1583 span: self.lazy(&nitem.span),
1584 attributes: self.encode_attributes(&nitem.attrs),
1585 children: LazySeq::empty(),
1586 stability: self.encode_stability(def_id),
1587 deprecation: self.encode_deprecation(def_id),
1589 ty: Some(self.encode_item_type(def_id)),
1590 inherent_impls: LazySeq::empty(),
1591 variances: match nitem.node {
1592 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1593 _ => LazySeq::empty(),
1595 generics: Some(self.encode_generics(def_id)),
1596 predicates: Some(self.encode_predicates(def_id)),
1597 predicates_defined_on: None,
1604 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1605 index: IndexBuilder<'a, 'b, 'tcx>,
1608 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1609 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1610 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir())
1612 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1613 intravisit::walk_expr(self, ex);
1614 self.index.encode_info_for_expr(ex);
1616 fn visit_item(&mut self, item: &'tcx hir::Item) {
1617 intravisit::walk_item(self, item);
1618 let def_id = self.index.tcx.hir().local_def_id(item.id);
1620 hir::ItemKind::ExternCrate(_) |
1621 hir::ItemKind::Use(..) => (), // ignore these
1622 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1624 self.index.encode_addl_info_for_item(item);
1626 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1627 intravisit::walk_foreign_item(self, ni);
1628 let def_id = self.index.tcx.hir().local_def_id(ni.id);
1629 self.index.record(def_id,
1630 IsolatedEncoder::encode_info_for_foreign_item,
1633 fn visit_variant(&mut self,
1634 v: &'tcx hir::Variant,
1635 g: &'tcx hir::Generics,
1637 intravisit::walk_variant(self, v, g, id);
1639 if let Some(ref discr) = v.node.disr_expr {
1640 let def_id = self.index.tcx.hir().local_def_id(discr.id);
1641 self.index.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1644 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1645 intravisit::walk_generics(self, generics);
1646 self.index.encode_info_for_generics(generics);
1648 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1649 intravisit::walk_ty(self, ty);
1650 self.index.encode_info_for_ty(ty);
1652 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1653 let def_id = self.index.tcx.hir().local_def_id(macro_def.id);
1654 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1658 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1659 fn encode_fields(&mut self, adt_def_id: DefId) {
1660 let def = self.tcx.adt_def(adt_def_id);
1661 for (variant_index, variant) in def.variants.iter_enumerated() {
1662 for (field_index, field) in variant.fields.iter().enumerate() {
1663 self.record(field.did,
1664 IsolatedEncoder::encode_field,
1665 (adt_def_id, Untracked((variant_index, field_index))));
1670 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1671 for param in &generics.params {
1673 hir::GenericParamKind::Lifetime { .. } => {}
1674 hir::GenericParamKind::Type { ref default, .. } => {
1675 let def_id = self.tcx.hir().local_def_id(param.id);
1676 let has_default = Untracked(default.is_some());
1677 let encode_info = IsolatedEncoder::encode_info_for_ty_param;
1678 self.record(def_id, encode_info, (def_id, has_default));
1684 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1686 hir::TyKind::Array(_, ref length) => {
1687 let def_id = self.tcx.hir().local_def_id(length.id);
1688 self.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1694 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1696 hir::ExprKind::Closure(..) => {
1697 let def_id = self.tcx.hir().local_def_id(expr.id);
1698 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1704 /// In some cases, along with the item itself, we also
1705 /// encode some sub-items. Usually we want some info from the item
1706 /// so it's easier to do that here then to wait until we would encounter
1707 /// normally in the visitor walk.
1708 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1709 let def_id = self.tcx.hir().local_def_id(item.id);
1711 hir::ItemKind::Static(..) |
1712 hir::ItemKind::Const(..) |
1713 hir::ItemKind::Fn(..) |
1714 hir::ItemKind::Mod(..) |
1715 hir::ItemKind::ForeignMod(..) |
1716 hir::ItemKind::GlobalAsm(..) |
1717 hir::ItemKind::ExternCrate(..) |
1718 hir::ItemKind::Use(..) |
1719 hir::ItemKind::Ty(..) |
1720 hir::ItemKind::Existential(..) |
1721 hir::ItemKind::TraitAlias(..) => {
1722 // no sub-item recording needed in these cases
1724 hir::ItemKind::Enum(..) => {
1725 self.encode_fields(def_id);
1727 let def = self.tcx.adt_def(def_id);
1728 for (i, variant) in def.variants.iter_enumerated() {
1729 self.record(variant.did,
1730 IsolatedEncoder::encode_enum_variant_info,
1731 (def_id, Untracked(i)));
1734 hir::ItemKind::Struct(ref struct_def, _) => {
1735 self.encode_fields(def_id);
1737 // If the struct has a constructor, encode it.
1738 if !struct_def.is_struct() {
1739 let ctor_def_id = self.tcx.hir().local_def_id(struct_def.id());
1740 self.record(ctor_def_id,
1741 IsolatedEncoder::encode_struct_ctor,
1742 (def_id, ctor_def_id));
1745 hir::ItemKind::Union(..) => {
1746 self.encode_fields(def_id);
1748 hir::ItemKind::Impl(..) => {
1749 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1750 self.record(trait_item_def_id,
1751 IsolatedEncoder::encode_info_for_impl_item,
1755 hir::ItemKind::Trait(..) => {
1756 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1757 self.record(item_def_id,
1758 IsolatedEncoder::encode_info_for_trait_item,
1766 struct ImplVisitor<'a, 'tcx: 'a> {
1767 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1768 impls: FxHashMap<DefId, Vec<DefIndex>>,
1771 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1772 fn visit_item(&mut self, item: &hir::Item) {
1773 if let hir::ItemKind::Impl(..) = item.node {
1774 let impl_id = self.tcx.hir().local_def_id(item.id);
1775 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1777 .entry(trait_ref.def_id)
1779 .push(impl_id.index);
1784 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1786 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1787 // handled in `visit_item` above
1791 // NOTE(eddyb) The following comment was preserved for posterity, even
1792 // though it's no longer relevant as EBML (which uses nested & tagged
1793 // "documents") was replaced with a scheme that can't go out of bounds.
1795 // And here we run into yet another obscure archive bug: in which metadata
1796 // loaded from archives may have trailing garbage bytes. Awhile back one of
1797 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1798 // and opt) by having ebml generate an out-of-bounds panic when looking at
1801 // Upon investigation it turned out that the metadata file inside of an rlib
1802 // (and ar archive) was being corrupted. Some compilations would generate a
1803 // metadata file which would end in a few extra bytes, while other
1804 // compilations would not have these extra bytes appended to the end. These
1805 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1806 // being interpreted causing the out-of-bounds.
1808 // The root cause of why these extra bytes were appearing was never
1809 // discovered, and in the meantime the solution we're employing is to insert
1810 // the length of the metadata to the start of the metadata. Later on this
1811 // will allow us to slice the metadata to the precise length that we just
1812 // generated regardless of trailing bytes that end up in it.
1814 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
1817 let mut encoder = opaque::Encoder::new(vec![]);
1818 encoder.emit_raw_bytes(METADATA_HEADER);
1820 // Will be filled with the root position after encoding everything.
1821 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1823 let (root, mut result) = {
1824 let mut ecx = EncodeContext {
1827 lazy_state: LazyState::NoNode,
1828 type_shorthands: Default::default(),
1829 predicate_shorthands: Default::default(),
1830 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1831 interpret_allocs: Default::default(),
1832 interpret_allocs_inverse: Default::default(),
1835 // Encode the rustc version string in a predictable location.
1836 rustc_version().encode(&mut ecx).unwrap();
1838 // Encode all the entries and extra information in the crate,
1839 // culminating in the `CrateRoot` which points to all of it.
1840 let root = ecx.encode_crate_root();
1841 (root, ecx.opaque.into_inner())
1844 // Encode the root position.
1845 let header = METADATA_HEADER.len();
1846 let pos = root.position;
1847 result[header + 0] = (pos >> 24) as u8;
1848 result[header + 1] = (pos >> 16) as u8;
1849 result[header + 2] = (pos >> 8) as u8;
1850 result[header + 3] = (pos >> 0) as u8;
1852 EncodedMetadata { raw_data: result }
1855 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1856 let ty = tcx.type_of(did);
1858 ty::Adt(ref def, _) => return def.repr,
1859 _ => bug!("{} is not an ADT", ty),