1 use crate::index::Index;
4 use rustc::middle::cstore::{LinkagePreference, NativeLibrary,
5 EncodedMetadata, ForeignModule};
6 use rustc::hir::def::CtorKind;
7 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LocalDefId, LOCAL_CRATE};
8 use rustc::hir::GenericParamKind;
9 use rustc::hir::map::definitions::DefPathTable;
10 use rustc_data_structures::fingerprint::Fingerprint;
11 use rustc::middle::dependency_format::Linkage;
12 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel,
13 metadata_symbol_name};
14 use rustc::middle::lang_items;
15 use rustc::mir::{self, interpret};
16 use rustc::traits::specialization_graph;
17 use rustc::ty::{self, Ty, TyCtxt, ReprOptions, SymbolName};
18 use rustc::ty::codec::{self as ty_codec, TyEncoder};
19 use rustc::ty::layout::VariantIdx;
21 use rustc::session::config::{self, CrateType};
22 use rustc::util::nodemap::FxHashMap;
24 use rustc_data_structures::stable_hasher::StableHasher;
25 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
29 use rustc_data_structures::sync::Lrc;
33 use syntax::ext::proc_macro::is_proc_macro_attr;
34 use syntax::source_map::Spanned;
35 use syntax::symbol::{kw, sym, Ident};
36 use syntax_pos::{self, FileName, SourceFile, Span};
37 use log::{debug, trace};
39 use rustc::hir::{self, PatKind};
40 use rustc::hir::itemlikevisit::ItemLikeVisitor;
41 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
42 use rustc::hir::intravisit;
44 pub struct EncodeContext<'tcx> {
45 opaque: opaque::Encoder,
46 pub tcx: TyCtxt<'tcx>,
48 entries_index: Index<'tcx>,
50 lazy_state: LazyState,
51 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
52 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
54 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
55 interpret_allocs_inverse: Vec<interpret::AllocId>,
57 // This is used to speed up Span encoding.
58 source_file_cache: Lrc<SourceFile>,
61 macro_rules! encoder_methods {
62 ($($name:ident($ty:ty);)*) => {
63 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
64 self.opaque.$name(value)
69 impl<'tcx> Encoder for EncodeContext<'tcx> {
70 type Error = <opaque::Encoder as Encoder>::Error;
72 fn emit_unit(&mut self) -> Result<(), Self::Error> {
99 impl<'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'tcx> {
100 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
101 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
105 impl<'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'tcx> {
106 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
107 self.emit_usize(seq.len)?;
111 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
115 impl<'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'tcx> {
117 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
118 self.emit_u32(cnum.as_u32())
122 impl<'tcx> SpecializedEncoder<DefId> for EncodeContext<'tcx> {
124 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
135 impl<'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'tcx> {
137 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
138 self.emit_u32(def_index.as_u32())
142 impl<'tcx> SpecializedEncoder<Span> for EncodeContext<'tcx> {
143 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
145 return TAG_INVALID_SPAN.encode(self)
148 let span = span.data();
150 // The Span infrastructure should make sure that this invariant holds:
151 debug_assert!(span.lo <= span.hi);
153 if !self.source_file_cache.contains(span.lo) {
154 let source_map = self.tcx.sess.source_map();
155 let source_file_index = source_map.lookup_source_file_idx(span.lo);
156 self.source_file_cache = source_map.files()[source_file_index].clone();
159 if !self.source_file_cache.contains(span.hi) {
160 // Unfortunately, macro expansion still sometimes generates Spans
161 // that malformed in this way.
162 return TAG_INVALID_SPAN.encode(self)
165 TAG_VALID_SPAN.encode(self)?;
166 span.lo.encode(self)?;
168 // Encode length which is usually less than span.hi and profits more
169 // from the variable-length integer encoding that we use.
170 let len = span.hi - span.lo;
173 // Don't encode the expansion context.
177 impl SpecializedEncoder<Ident> for EncodeContext<'tcx> {
178 fn specialized_encode(&mut self, ident: &Ident) -> Result<(), Self::Error> {
179 // FIXME(jseyfried): intercrate hygiene
180 ident.name.encode(self)
184 impl<'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'tcx> {
186 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
187 self.specialized_encode(&def_id.to_def_id())
191 impl<'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'tcx> {
192 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
193 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
197 impl<'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'tcx> {
198 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
199 use std::collections::hash_map::Entry;
200 let index = match self.interpret_allocs.entry(*alloc_id) {
201 Entry::Occupied(e) => *e.get(),
202 Entry::Vacant(e) => {
203 let idx = self.interpret_allocs_inverse.len();
204 self.interpret_allocs_inverse.push(*alloc_id);
214 impl<'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'tcx> {
215 fn specialized_encode(&mut self,
216 predicates: &ty::GenericPredicates<'tcx>)
217 -> Result<(), Self::Error> {
218 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
222 impl<'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'tcx> {
223 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
224 f.encode_opaque(&mut self.opaque)
228 impl<'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'tcx> {
229 fn specialized_encode(&mut self,
230 _: &mir::ClearCrossCrate<T>)
231 -> Result<(), Self::Error> {
236 impl<'tcx> TyEncoder for EncodeContext<'tcx> {
237 fn position(&self) -> usize {
238 self.opaque.position()
242 impl<'tcx> EncodeContext<'tcx> {
243 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
244 assert_eq!(self.lazy_state, LazyState::NoNode);
245 let pos = self.position();
246 self.lazy_state = LazyState::NodeStart(pos);
247 let r = f(self, pos);
248 self.lazy_state = LazyState::NoNode;
252 fn emit_lazy_distance(&mut self,
255 -> Result<(), <Self as Encoder>::Error> {
256 let min_end = position + min_size;
257 let distance = match self.lazy_state {
258 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
259 LazyState::NodeStart(start) => {
260 assert!(min_end <= start);
263 LazyState::Previous(last_min_end) => {
265 last_min_end <= position,
266 "make sure that the calls to `lazy*` \
267 are in the same order as the metadata fields",
269 position - last_min_end
272 self.lazy_state = LazyState::Previous(min_end);
273 self.emit_usize(distance)
276 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
277 self.emit_node(|ecx, pos| {
278 value.encode(ecx).unwrap();
280 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
281 Lazy::with_position(pos)
285 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
286 where I: IntoIterator<Item = T>,
289 self.emit_node(|ecx, pos| {
290 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
292 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
293 LazySeq::with_position_and_length(pos, len)
297 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
298 where I: IntoIterator<Item = &'b T>,
301 self.emit_node(|ecx, pos| {
302 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
304 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
305 LazySeq::with_position_and_length(pos, len)
309 /// Emit the data for a `DefId` to the metadata. The function to
310 /// emit the data is `op`, and it will be given `data` as
311 /// arguments. This `record` function will call `op` to generate
312 /// the `Entry` (which may point to other encoded information)
313 /// and will then record the `Lazy<Entry>` for use in the index.
314 // FIXME(eddyb) remove this.
315 pub fn record<DATA>(&mut self,
317 op: impl FnOnce(&mut Self, DATA) -> Entry<'tcx>,
320 assert!(id.is_local());
322 let entry = op(self, data);
323 let entry = self.lazy(&entry);
324 self.entries_index.record(id, entry);
327 fn encode_info_for_items(&mut self) {
328 let krate = self.tcx.hir().krate();
329 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public };
330 self.record(DefId::local(CRATE_DEF_INDEX),
331 EncodeContext::encode_info_for_mod,
332 (hir::CRATE_HIR_ID, &krate.module, &krate.attrs, &vis));
333 krate.visit_all_item_likes(&mut self.as_deep_visitor());
334 for macro_def in &krate.exported_macros {
335 self.visit_macro_def(macro_def);
339 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
340 let definitions = self.tcx.hir().definitions();
341 self.lazy(definitions.def_path_table())
344 fn encode_source_map(&mut self) -> LazySeq<syntax_pos::SourceFile> {
345 let source_map = self.tcx.sess.source_map();
346 let all_source_files = source_map.files();
348 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
350 let adapted = all_source_files.iter()
351 .filter(|source_file| {
352 // No need to re-export imported source_files, as any downstream
353 // crate will import them from their original source.
354 !source_file.is_imported()
357 match source_file.name {
358 // This path of this SourceFile has been modified by
359 // path-remapping, so we use it verbatim (and avoid
360 // cloning the whole map in the process).
361 _ if source_file.name_was_remapped => source_file.clone(),
363 // Otherwise expand all paths to absolute paths because
364 // any relative paths are potentially relative to a
366 FileName::Real(ref name) => {
367 let mut adapted = (**source_file).clone();
368 adapted.name = Path::new(&working_dir).join(name).into();
369 adapted.name_hash = {
370 let mut hasher: StableHasher<u128> = StableHasher::new();
371 adapted.name.hash(&mut hasher);
377 // expanded code, not from a file
378 _ => source_file.clone(),
381 .collect::<Vec<_>>();
383 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
386 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
387 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
389 let mut i = self.position();
391 let crate_deps = self.encode_crate_deps();
392 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
393 let dep_bytes = self.position() - i;
395 // Encode the lib features.
397 let lib_features = self.encode_lib_features();
398 let lib_feature_bytes = self.position() - i;
400 // Encode the language items.
402 let lang_items = self.encode_lang_items();
403 let lang_items_missing = self.encode_lang_items_missing();
404 let lang_item_bytes = self.position() - i;
406 // Encode the native libraries used
408 let native_libraries = self.encode_native_libraries();
409 let native_lib_bytes = self.position() - i;
411 let foreign_modules = self.encode_foreign_modules();
415 let source_map = self.encode_source_map();
416 let source_map_bytes = self.position() - i;
418 // Encode DefPathTable
420 let def_path_table = self.encode_def_path_table();
421 let def_path_table_bytes = self.position() - i;
423 // Encode the def IDs of impls, for coherence checking.
425 let impls = self.encode_impls();
426 let impl_bytes = self.position() - i;
428 // Encode exported symbols info.
430 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
431 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
432 let exported_symbols_bytes = self.position() - i;
438 self.encode_info_for_items();
439 let item_bytes = self.position() - i;
441 // Encode the allocation index
442 let interpret_alloc_index = {
443 let mut interpret_alloc_index = Vec::new();
445 trace!("beginning to encode alloc ids");
447 let new_n = self.interpret_allocs_inverse.len();
448 // if we have found new ids, serialize those, too
453 trace!("encoding {} further alloc ids", new_n - n);
454 for idx in n..new_n {
455 let id = self.interpret_allocs_inverse[idx];
456 let pos = self.position() as u32;
457 interpret_alloc_index.push(pos);
458 interpret::specialized_encode_alloc_id(
466 self.lazy_seq(interpret_alloc_index)
471 let entries_index = self.entries_index.write_index(&mut self.opaque);
472 let entries_index_bytes = self.position() - i;
474 // Encode the proc macro data
476 let proc_macro_data = self.encode_proc_macros();
477 let proc_macro_data_bytes = self.position() - i;
480 let attrs = tcx.hir().krate_attrs();
481 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
482 let has_global_allocator = *tcx.sess.has_global_allocator.get();
483 let has_panic_handler = *tcx.sess.has_panic_handler.try_get().unwrap_or(&false);
486 let root = self.lazy(&CrateRoot {
487 name: tcx.crate_name(LOCAL_CRATE),
488 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
489 triple: tcx.sess.opts.target_triple.clone(),
490 hash: tcx.crate_hash(LOCAL_CRATE),
491 disambiguator: tcx.sess.local_crate_disambiguator(),
492 panic_strategy: tcx.sess.panic_strategy(),
493 edition: tcx.sess.edition(),
494 has_global_allocator: has_global_allocator,
495 has_panic_handler: has_panic_handler,
496 has_default_lib_allocator: has_default_lib_allocator,
497 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
498 proc_macro_decls_static: if is_proc_macro {
499 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
505 proc_macro_stability: if is_proc_macro {
506 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).map(|stab| stab.clone())
510 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
511 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
512 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
513 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
514 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
515 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
516 sanitizer_runtime: attr::contains_name(&attrs, sym::sanitizer_runtime),
517 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
520 dylib_dependency_formats,
530 interpret_alloc_index,
534 let total_bytes = self.position();
536 if self.tcx.sess.meta_stats() {
537 let mut zero_bytes = 0;
538 for e in self.opaque.data.iter() {
544 println!("metadata stats:");
545 println!(" dep bytes: {}", dep_bytes);
546 println!(" lib feature bytes: {}", lib_feature_bytes);
547 println!(" lang item bytes: {}", lang_item_bytes);
548 println!(" native bytes: {}", native_lib_bytes);
549 println!(" source_map bytes: {}", source_map_bytes);
550 println!(" impl bytes: {}", impl_bytes);
551 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
552 println!(" def-path table bytes: {}", def_path_table_bytes);
553 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
554 println!(" item bytes: {}", item_bytes);
555 println!(" entries index bytes: {}", entries_index_bytes);
556 println!(" zero bytes: {}", zero_bytes);
557 println!(" total bytes: {}", total_bytes);
564 impl EncodeContext<'tcx> {
565 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
566 debug!("EncodeContext::encode_variances_of({:?})", def_id);
568 self.lazy_seq_ref(&tcx.variances_of(def_id)[..])
571 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
573 let ty = tcx.type_of(def_id);
574 debug!("EncodeContext::encode_item_type({:?}) => {:?}", def_id, ty);
578 fn encode_enum_variant_info(
580 (enum_did, index): (DefId, VariantIdx),
583 let def = tcx.adt_def(enum_did);
584 let variant = &def.variants[index];
585 let def_id = variant.def_id;
586 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
588 let data = VariantData {
589 ctor_kind: variant.ctor_kind,
590 discr: variant.discr,
591 // FIXME(eddyb) deduplicate these with `encode_enum_variant_ctor`.
592 ctor: variant.ctor_def_id.map(|did| did.index),
593 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
594 variant.ctor_def_id.map(|ctor_def_id| self.lazy(&tcx.fn_sig(ctor_def_id)))
600 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
601 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
604 kind: EntryKind::Variant(self.lazy(&data)),
605 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
606 span: self.lazy(&tcx.def_span(def_id)),
607 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
608 children: self.lazy_seq(variant.fields.iter().map(|f| {
609 assert!(f.did.is_local());
612 stability: self.encode_stability(def_id),
613 deprecation: self.encode_deprecation(def_id),
615 ty: Some(self.encode_item_type(def_id)),
616 inherent_impls: LazySeq::empty(),
617 variances: if variant.ctor_kind == CtorKind::Fn {
618 self.encode_variances_of(def_id)
622 generics: Some(self.encode_generics(def_id)),
623 predicates: Some(self.encode_predicates(def_id)),
624 predicates_defined_on: None,
626 mir: self.encode_optimized_mir(def_id),
630 fn encode_enum_variant_ctor(
632 (enum_did, index): (DefId, VariantIdx),
635 let def = tcx.adt_def(enum_did);
636 let variant = &def.variants[index];
637 let def_id = variant.ctor_def_id.unwrap();
638 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
640 let data = VariantData {
641 ctor_kind: variant.ctor_kind,
642 discr: variant.discr,
643 ctor: Some(def_id.index),
644 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
645 Some(self.lazy(&tcx.fn_sig(def_id)))
651 // Variant constructors have the same visibility as the parent enums, unless marked as
652 // non-exhaustive, in which case they are lowered to `pub(crate)`.
653 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
654 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
655 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
656 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
657 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
661 kind: EntryKind::Variant(self.lazy(&data)),
662 visibility: self.lazy(&ctor_vis),
663 span: self.lazy(&tcx.def_span(def_id)),
664 attributes: LazySeq::empty(),
665 children: LazySeq::empty(),
666 stability: self.encode_stability(def_id),
667 deprecation: self.encode_deprecation(def_id),
669 ty: Some(self.encode_item_type(def_id)),
670 inherent_impls: LazySeq::empty(),
671 variances: if variant.ctor_kind == CtorKind::Fn {
672 self.encode_variances_of(def_id)
676 generics: Some(self.encode_generics(def_id)),
677 predicates: Some(self.encode_predicates(def_id)),
678 predicates_defined_on: None,
680 mir: self.encode_optimized_mir(def_id),
684 fn encode_info_for_mod(
686 (id, md, attrs, vis): (hir::HirId, &hir::Mod, &[ast::Attribute], &hir::Visibility),
689 let def_id = tcx.hir().local_def_id(id);
690 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
693 reexports: match tcx.module_exports(def_id) {
694 Some(exports) => self.lazy_seq_ref(exports),
695 _ => LazySeq::empty(),
700 kind: EntryKind::Mod(self.lazy(&data)),
701 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
702 span: self.lazy(&tcx.def_span(def_id)),
703 attributes: self.encode_attributes(attrs),
704 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
705 tcx.hir().local_def_id(item_id.id).index
707 stability: self.encode_stability(def_id),
708 deprecation: self.encode_deprecation(def_id),
711 inherent_impls: LazySeq::empty(),
712 variances: LazySeq::empty(),
715 predicates_defined_on: None,
723 (adt_def_id, variant_index, field_index): (DefId, VariantIdx, usize),
726 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
727 let field = &variant.fields[field_index];
729 let def_id = field.did;
730 debug!("EncodeContext::encode_field({:?})", def_id);
732 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
733 let variant_data = tcx.hir().expect_variant_data(variant_id);
736 kind: EntryKind::Field,
737 visibility: self.lazy(&field.vis),
738 span: self.lazy(&tcx.def_span(def_id)),
739 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
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: LazySeq::empty(),
747 generics: Some(self.encode_generics(def_id)),
748 predicates: Some(self.encode_predicates(def_id)),
749 predicates_defined_on: None,
755 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
756 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
758 let adt_def = tcx.adt_def(adt_def_id);
759 let variant = adt_def.non_enum_variant();
761 let data = VariantData {
762 ctor_kind: variant.ctor_kind,
763 discr: variant.discr,
764 ctor: Some(def_id.index),
765 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
766 Some(self.lazy(&tcx.fn_sig(def_id)))
772 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
773 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
774 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
775 for field in &variant.fields {
776 if ctor_vis.is_at_least(field.vis, tcx) {
777 ctor_vis = field.vis;
781 // If the structure is marked as non_exhaustive then lower the visibility
782 // to within the crate.
783 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
784 ctor_vis == ty::Visibility::Public
786 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
789 let repr_options = get_repr_options(tcx, adt_def_id);
792 kind: EntryKind::Struct(self.lazy(&data), repr_options),
793 visibility: self.lazy(&ctor_vis),
794 span: self.lazy(&tcx.def_span(def_id)),
795 attributes: LazySeq::empty(),
796 children: LazySeq::empty(),
797 stability: self.encode_stability(def_id),
798 deprecation: self.encode_deprecation(def_id),
800 ty: Some(self.encode_item_type(def_id)),
801 inherent_impls: LazySeq::empty(),
802 variances: if variant.ctor_kind == CtorKind::Fn {
803 self.encode_variances_of(def_id)
807 generics: Some(self.encode_generics(def_id)),
808 predicates: Some(self.encode_predicates(def_id)),
809 predicates_defined_on: None,
811 mir: self.encode_optimized_mir(def_id),
815 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
816 debug!("EncodeContext::encode_generics({:?})", def_id);
818 self.lazy(tcx.generics_of(def_id))
821 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
822 debug!("EncodeContext::encode_predicates({:?})", def_id);
824 self.lazy(&tcx.predicates_of(def_id))
827 fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
828 debug!("EncodeContext::encode_predicates_defined_on({:?})", def_id);
830 self.lazy(&tcx.predicates_defined_on(def_id))
833 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
834 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
837 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
838 let ast_item = tcx.hir().expect_trait_item(hir_id);
839 let trait_item = tcx.associated_item(def_id);
841 let container = match trait_item.defaultness {
842 hir::Defaultness::Default { has_value: true } =>
843 AssocContainer::TraitWithDefault,
844 hir::Defaultness::Default { has_value: false } =>
845 AssocContainer::TraitRequired,
846 hir::Defaultness::Final =>
847 span_bug!(ast_item.span, "traits cannot have final items"),
850 let kind = match trait_item.kind {
851 ty::AssocKind::Const => {
853 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
854 self.const_qualif(0, body)
856 ConstQualif { mir: 0, ast_promotable: false }
860 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
861 let rendered_const = self.lazy(&RenderedConst(rendered));
863 EntryKind::AssocConst(container, const_qualif, rendered_const)
865 ty::AssocKind::Method => {
866 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
867 let arg_names = match *m {
868 hir::TraitMethod::Required(ref names) => {
869 self.encode_fn_arg_names(names)
871 hir::TraitMethod::Provided(body) => {
872 self.encode_fn_arg_names_for_body(body)
876 constness: hir::Constness::NotConst,
878 sig: self.lazy(&tcx.fn_sig(def_id)),
883 EntryKind::Method(self.lazy(&MethodData {
886 has_self: trait_item.method_has_self_argument,
889 ty::AssocKind::Type => EntryKind::AssocType(container),
890 ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
895 visibility: self.lazy(&trait_item.vis),
896 span: self.lazy(&ast_item.span),
897 attributes: self.encode_attributes(&ast_item.attrs),
898 children: LazySeq::empty(),
899 stability: self.encode_stability(def_id),
900 deprecation: self.encode_deprecation(def_id),
902 ty: match trait_item.kind {
903 ty::AssocKind::Const |
904 ty::AssocKind::Method => {
905 Some(self.encode_item_type(def_id))
907 ty::AssocKind::Type => {
908 if trait_item.defaultness.has_value() {
909 Some(self.encode_item_type(def_id))
914 ty::AssocKind::OpaqueTy => unreachable!(),
916 inherent_impls: LazySeq::empty(),
917 variances: if trait_item.kind == ty::AssocKind::Method {
918 self.encode_variances_of(def_id)
922 generics: Some(self.encode_generics(def_id)),
923 predicates: Some(self.encode_predicates(def_id)),
924 predicates_defined_on: None,
926 mir: self.encode_optimized_mir(def_id),
930 fn metadata_output_only(&self) -> bool {
931 // MIR optimisation can be skipped when we're just interested in the metadata.
932 !self.tcx.sess.opts.output_types.should_codegen()
935 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
936 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
937 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
939 ConstQualif { mir, ast_promotable }
942 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
943 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
946 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
947 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
948 let impl_item = self.tcx.associated_item(def_id);
950 let container = match impl_item.defaultness {
951 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
952 hir::Defaultness::Final => AssocContainer::ImplFinal,
953 hir::Defaultness::Default { has_value: false } =>
954 span_bug!(ast_item.span, "impl items always have values (currently)"),
957 let kind = match impl_item.kind {
958 ty::AssocKind::Const => {
959 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
960 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
962 EntryKind::AssocConst(container,
963 self.const_qualif(mir, body_id),
964 self.encode_rendered_const_for_body(body_id))
969 ty::AssocKind::Method => {
970 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
972 constness: sig.header.constness,
973 arg_names: self.encode_fn_arg_names_for_body(body),
974 sig: self.lazy(&tcx.fn_sig(def_id)),
979 EntryKind::Method(self.lazy(&MethodData {
982 has_self: impl_item.method_has_self_argument,
985 ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
986 ty::AssocKind::Type => EntryKind::AssocType(container)
990 match ast_item.node {
991 hir::ImplItemKind::Const(..) => true,
992 hir::ImplItemKind::Method(ref sig, _) => {
993 let generics = self.tcx.generics_of(def_id);
994 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
995 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
996 !self.metadata_output_only();
997 let is_const_fn = sig.header.constness == hir::Constness::Const;
998 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
999 needs_inline || is_const_fn || always_encode_mir
1001 hir::ImplItemKind::OpaqueTy(..) |
1002 hir::ImplItemKind::TyAlias(..) => false,
1007 visibility: self.lazy(&impl_item.vis),
1008 span: self.lazy(&ast_item.span),
1009 attributes: self.encode_attributes(&ast_item.attrs),
1010 children: LazySeq::empty(),
1011 stability: self.encode_stability(def_id),
1012 deprecation: self.encode_deprecation(def_id),
1014 ty: Some(self.encode_item_type(def_id)),
1015 inherent_impls: LazySeq::empty(),
1016 variances: if impl_item.kind == ty::AssocKind::Method {
1017 self.encode_variances_of(def_id)
1021 generics: Some(self.encode_generics(def_id)),
1022 predicates: Some(self.encode_predicates(def_id)),
1023 predicates_defined_on: None,
1025 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
1029 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
1030 -> LazySeq<ast::Name> {
1031 self.tcx.dep_graph.with_ignore(|| {
1032 let body = self.tcx.hir().body(body_id);
1033 self.lazy_seq(body.arguments.iter().map(|arg| {
1034 match arg.pat.node {
1035 PatKind::Binding(_, _, ident, _) => ident.name,
1042 fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> LazySeq<ast::Name> {
1043 self.lazy_seq(param_names.iter().map(|ident| ident.name))
1046 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Body<'tcx>>> {
1047 debug!("EntryBuilder::encode_mir({:?})", def_id);
1048 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1049 let mir = self.tcx.optimized_mir(def_id);
1050 Some(self.lazy(&mir))
1056 // Encodes the inherent implementations of a structure, enumeration, or trait.
1057 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1058 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1059 let implementations = self.tcx.inherent_impls(def_id);
1060 if implementations.is_empty() {
1063 self.lazy_seq(implementations.iter().map(|&def_id| {
1064 assert!(def_id.is_local());
1070 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1071 debug!("EncodeContext::encode_stability({:?})", def_id);
1072 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1075 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1076 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1077 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1080 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1081 let body = self.tcx.hir().body(body_id);
1082 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1083 let rendered_const = &RenderedConst(rendered);
1084 self.lazy(rendered_const)
1087 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1090 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1092 let kind = match item.node {
1093 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1094 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1095 hir::ItemKind::Const(_, body_id) => {
1096 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1098 self.const_qualif(mir, body_id),
1099 self.encode_rendered_const_for_body(body_id)
1102 hir::ItemKind::Fn(_, header, .., body) => {
1104 constness: header.constness,
1105 arg_names: self.encode_fn_arg_names_for_body(body),
1106 sig: self.lazy(&tcx.fn_sig(def_id)),
1109 EntryKind::Fn(self.lazy(&data))
1111 hir::ItemKind::Mod(ref m) => {
1112 return self.encode_info_for_mod((item.hir_id, m, &item.attrs, &item.vis));
1114 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1115 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1116 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1117 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1118 hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(tcx, def_id)),
1119 hir::ItemKind::Struct(ref struct_def, _) => {
1120 let variant = tcx.adt_def(def_id).non_enum_variant();
1122 // Encode def_ids for each field and method
1123 // for methods, write all the stuff get_trait_method
1125 let ctor = struct_def.ctor_hir_id()
1126 .map(|ctor_hir_id| tcx.hir().local_def_id(ctor_hir_id).index);
1128 let repr_options = get_repr_options(tcx, def_id);
1130 EntryKind::Struct(self.lazy(&VariantData {
1131 ctor_kind: variant.ctor_kind,
1132 discr: variant.discr,
1137 hir::ItemKind::Union(..) => {
1138 let variant = tcx.adt_def(def_id).non_enum_variant();
1139 let repr_options = get_repr_options(tcx, def_id);
1141 EntryKind::Union(self.lazy(&VariantData {
1142 ctor_kind: variant.ctor_kind,
1143 discr: variant.discr,
1148 hir::ItemKind::Impl(_, polarity, defaultness, ..) => {
1149 let trait_ref = tcx.impl_trait_ref(def_id);
1150 let parent = if let Some(trait_ref) = trait_ref {
1151 let trait_def = tcx.trait_def(trait_ref.def_id);
1152 trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| {
1154 specialization_graph::Node::Impl(parent) => Some(parent),
1162 // if this is an impl of `CoerceUnsized`, create its
1163 // "unsized info", else just store None
1164 let coerce_unsized_info =
1165 trait_ref.and_then(|t| {
1166 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1167 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1173 let data = ImplData {
1176 parent_impl: parent,
1177 coerce_unsized_info,
1178 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1181 EntryKind::Impl(self.lazy(&data))
1183 hir::ItemKind::Trait(..) => {
1184 let trait_def = tcx.trait_def(def_id);
1185 let data = TraitData {
1186 unsafety: trait_def.unsafety,
1187 paren_sugar: trait_def.paren_sugar,
1188 has_auto_impl: tcx.trait_is_auto(def_id),
1189 is_marker: trait_def.is_marker,
1190 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1193 EntryKind::Trait(self.lazy(&data))
1195 hir::ItemKind::TraitAlias(..) => {
1196 let data = TraitAliasData {
1197 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1200 EntryKind::TraitAlias(self.lazy(&data))
1202 hir::ItemKind::ExternCrate(_) |
1203 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1208 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.hir_id, tcx)),
1209 span: self.lazy(&item.span),
1210 attributes: self.encode_attributes(&item.attrs),
1211 children: match item.node {
1212 hir::ItemKind::ForeignMod(ref fm) => {
1213 self.lazy_seq(fm.items
1215 .map(|foreign_item| tcx.hir().local_def_id(
1216 foreign_item.hir_id).index))
1218 hir::ItemKind::Enum(..) => {
1219 let def = self.tcx.adt_def(def_id);
1220 self.lazy_seq(def.variants.iter().map(|v| {
1221 assert!(v.def_id.is_local());
1225 hir::ItemKind::Struct(..) |
1226 hir::ItemKind::Union(..) => {
1227 let def = self.tcx.adt_def(def_id);
1228 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1229 assert!(f.did.is_local());
1233 hir::ItemKind::Impl(..) |
1234 hir::ItemKind::Trait(..) => {
1235 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1236 assert!(def_id.is_local());
1240 _ => LazySeq::empty(),
1242 stability: self.encode_stability(def_id),
1243 deprecation: self.encode_deprecation(def_id),
1245 ty: match item.node {
1246 hir::ItemKind::Static(..) |
1247 hir::ItemKind::Const(..) |
1248 hir::ItemKind::Fn(..) |
1249 hir::ItemKind::TyAlias(..) |
1250 hir::ItemKind::OpaqueTy(..) |
1251 hir::ItemKind::Enum(..) |
1252 hir::ItemKind::Struct(..) |
1253 hir::ItemKind::Union(..) |
1254 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1257 inherent_impls: self.encode_inherent_implementations(def_id),
1258 variances: match item.node {
1259 hir::ItemKind::Enum(..) |
1260 hir::ItemKind::Struct(..) |
1261 hir::ItemKind::Union(..) |
1262 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1263 _ => LazySeq::empty(),
1265 generics: match item.node {
1266 hir::ItemKind::Static(..) |
1267 hir::ItemKind::Const(..) |
1268 hir::ItemKind::Fn(..) |
1269 hir::ItemKind::TyAlias(..) |
1270 hir::ItemKind::Enum(..) |
1271 hir::ItemKind::Struct(..) |
1272 hir::ItemKind::Union(..) |
1273 hir::ItemKind::Impl(..) |
1274 hir::ItemKind::OpaqueTy(..) |
1275 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1276 hir::ItemKind::TraitAlias(..) => Some(self.encode_generics(def_id)),
1279 predicates: match item.node {
1280 hir::ItemKind::Static(..) |
1281 hir::ItemKind::Const(..) |
1282 hir::ItemKind::Fn(..) |
1283 hir::ItemKind::TyAlias(..) |
1284 hir::ItemKind::Enum(..) |
1285 hir::ItemKind::Struct(..) |
1286 hir::ItemKind::Union(..) |
1287 hir::ItemKind::Impl(..) |
1288 hir::ItemKind::OpaqueTy(..) |
1289 hir::ItemKind::Trait(..) |
1290 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates(def_id)),
1294 // The only time that `predicates_defined_on` is used (on
1295 // an external item) is for traits, during chalk lowering,
1296 // so only encode it in that case as an efficiency
1297 // hack. (No reason not to expand it in the future if
1299 predicates_defined_on: match item.node {
1300 hir::ItemKind::Trait(..) |
1301 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates_defined_on(def_id)),
1302 _ => None, // not *wrong* for other kinds of items, but not needed
1305 mir: match item.node {
1306 hir::ItemKind::Static(..) => {
1307 self.encode_optimized_mir(def_id)
1309 hir::ItemKind::Const(..) => self.encode_optimized_mir(def_id),
1310 hir::ItemKind::Fn(_, header, ..) => {
1311 let generics = tcx.generics_of(def_id);
1313 (generics.requires_monomorphization(tcx) ||
1314 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1315 !self.metadata_output_only();
1316 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1318 || header.constness == hir::Constness::Const
1319 || always_encode_mir
1321 self.encode_optimized_mir(def_id)
1331 /// Serialize the text of exported macros
1332 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1333 use syntax::print::pprust;
1334 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1336 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1337 body: pprust::tokens_to_string(macro_def.body.clone()),
1338 legacy: macro_def.legacy,
1340 visibility: self.lazy(&ty::Visibility::Public),
1341 span: self.lazy(¯o_def.span),
1342 attributes: self.encode_attributes(¯o_def.attrs),
1343 stability: self.encode_stability(def_id),
1344 deprecation: self.encode_deprecation(def_id),
1346 children: LazySeq::empty(),
1348 inherent_impls: LazySeq::empty(),
1349 variances: LazySeq::empty(),
1352 predicates_defined_on: None,
1357 fn encode_info_for_generic_param(
1360 entry_kind: EntryKind<'tcx>,
1366 visibility: self.lazy(&ty::Visibility::Public),
1367 span: self.lazy(&tcx.def_span(def_id)),
1368 attributes: LazySeq::empty(),
1369 children: LazySeq::empty(),
1372 ty: if encode_type { Some(self.encode_item_type(def_id)) } else { None },
1373 inherent_impls: LazySeq::empty(),
1374 variances: LazySeq::empty(),
1377 predicates_defined_on: None,
1383 fn encode_info_for_ty_param(
1385 (def_id, encode_type): (DefId, bool),
1387 debug!("EncodeContext::encode_info_for_ty_param({:?})", def_id);
1388 self.encode_info_for_generic_param(def_id, EntryKind::TypeParam, encode_type)
1391 fn encode_info_for_const_param(
1395 debug!("EncodeContext::encode_info_for_const_param({:?})", def_id);
1396 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true)
1399 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1400 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1403 let tables = self.tcx.typeck_tables_of(def_id);
1404 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1405 let kind = match tables.node_type(hir_id).sty {
1406 ty::Generator(def_id, ..) => {
1407 let layout = self.tcx.generator_layout(def_id);
1408 let data = GeneratorData {
1409 layout: layout.clone(),
1411 EntryKind::Generator(self.lazy(&data))
1414 ty::Closure(def_id, substs) => {
1415 let sig = substs.closure_sig(def_id, self.tcx);
1416 let data = ClosureData { sig: self.lazy(&sig) };
1417 EntryKind::Closure(self.lazy(&data))
1420 _ => bug!("closure that is neither generator nor closure")
1425 visibility: self.lazy(&ty::Visibility::Public),
1426 span: self.lazy(&tcx.def_span(def_id)),
1427 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1428 children: LazySeq::empty(),
1432 ty: Some(self.encode_item_type(def_id)),
1433 inherent_impls: LazySeq::empty(),
1434 variances: LazySeq::empty(),
1435 generics: Some(self.encode_generics(def_id)),
1437 predicates_defined_on: None,
1439 mir: self.encode_optimized_mir(def_id),
1443 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1444 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1446 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
1447 let body_id = tcx.hir().body_owned_by(id);
1448 let const_data = self.encode_rendered_const_for_body(body_id);
1449 let mir = tcx.mir_const_qualif(def_id).0;
1452 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1453 visibility: self.lazy(&ty::Visibility::Public),
1454 span: self.lazy(&tcx.def_span(def_id)),
1455 attributes: LazySeq::empty(),
1456 children: LazySeq::empty(),
1460 ty: Some(self.encode_item_type(def_id)),
1461 inherent_impls: LazySeq::empty(),
1462 variances: LazySeq::empty(),
1463 generics: Some(self.encode_generics(def_id)),
1464 predicates: Some(self.encode_predicates(def_id)),
1465 predicates_defined_on: None,
1467 mir: self.encode_optimized_mir(def_id),
1471 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1472 self.lazy_seq_ref(attrs)
1475 fn encode_native_libraries(&mut self) -> LazySeq<NativeLibrary> {
1476 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1477 self.lazy_seq(used_libraries.iter().cloned())
1480 fn encode_foreign_modules(&mut self) -> LazySeq<ForeignModule> {
1481 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1482 self.lazy_seq(foreign_modules.iter().cloned())
1485 fn encode_proc_macros(&mut self) -> Option<LazySeq<DefIndex>> {
1486 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
1488 let proc_macros: Vec<_> = self.tcx.hir().krate().items.values().filter_map(|item| {
1489 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
1490 Some(item.hir_id.owner)
1495 Some(self.lazy_seq(proc_macros))
1501 fn encode_crate_deps(&mut self) -> LazySeq<CrateDep> {
1502 let crates = self.tcx.crates();
1504 let mut deps = crates
1507 let dep = CrateDep {
1508 name: self.tcx.original_crate_name(cnum),
1509 hash: self.tcx.crate_hash(cnum),
1510 kind: self.tcx.dep_kind(cnum),
1511 extra_filename: self.tcx.extra_filename(cnum),
1515 .collect::<Vec<_>>();
1517 deps.sort_by_key(|&(cnum, _)| cnum);
1520 // Sanity-check the crate numbers
1521 let mut expected_cnum = 1;
1522 for &(n, _) in &deps {
1523 assert_eq!(n, CrateNum::new(expected_cnum));
1528 // We're just going to write a list of crate 'name-hash-version's, with
1529 // the assumption that they are numbered 1 to n.
1530 // FIXME (#2166): This is not nearly enough to support correct versioning
1531 // but is enough to get transitive crate dependencies working.
1532 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1535 fn encode_lib_features(&mut self) -> LazySeq<(ast::Name, Option<ast::Name>)> {
1537 let lib_features = tcx.lib_features();
1538 self.lazy_seq(lib_features.to_vec())
1541 fn encode_lang_items(&mut self) -> LazySeq<(DefIndex, usize)> {
1543 let lang_items = tcx.lang_items();
1544 let lang_items = lang_items.items().iter();
1545 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1546 if let Some(def_id) = opt_def_id {
1547 if def_id.is_local() {
1548 return Some((def_id.index, i));
1555 fn encode_lang_items_missing(&mut self) -> LazySeq<lang_items::LangItem> {
1557 self.lazy_seq_ref(&tcx.lang_items().missing)
1560 /// Encodes an index, mapping each trait to its (local) implementations.
1561 fn encode_impls(&mut self) -> LazySeq<TraitImpls> {
1562 debug!("EncodeContext::encode_impls()");
1564 let mut visitor = ImplVisitor {
1566 impls: FxHashMap::default(),
1568 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1570 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1572 // Bring everything into deterministic order for hashing
1573 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1574 tcx.def_path_hash(trait_def_id)
1577 let all_impls: Vec<_> = all_impls
1579 .map(|(trait_def_id, mut impls)| {
1580 // Bring everything into deterministic order for hashing
1581 impls.sort_by_cached_key(|&def_index| {
1582 tcx.hir().definitions().def_path_hash(def_index)
1586 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1587 impls: self.lazy_seq_ref(&impls),
1592 self.lazy_seq_ref(&all_impls)
1595 // Encodes all symbols exported from this crate into the metadata.
1597 // This pass is seeded off the reachability list calculated in the
1598 // middle::reachable module but filters out items that either don't have a
1599 // symbol associated with them (they weren't translated) or if they're an FFI
1600 // definition (as that's not defined in this crate).
1601 fn encode_exported_symbols(&mut self,
1602 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)])
1603 -> LazySeq<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1604 // The metadata symbol name is special. It should not show up in
1605 // downstream crates.
1606 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1608 self.lazy_seq(exported_symbols
1610 .filter(|&&(ref exported_symbol, _)| {
1611 match *exported_symbol {
1612 ExportedSymbol::NoDefId(symbol_name) => {
1613 symbol_name != metadata_symbol_name
1621 fn encode_dylib_dependency_formats(&mut self) -> LazySeq<Option<LinkagePreference>> {
1622 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateType::Dylib) {
1624 self.lazy_seq(arr.iter().map(|slot| {
1626 Linkage::NotLinked |
1627 Linkage::IncludedFromDylib => None,
1629 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1630 Linkage::Static => Some(LinkagePreference::RequireStatic),
1634 None => LazySeq::empty(),
1638 fn encode_info_for_foreign_item(&mut self,
1639 (def_id, nitem): (DefId, &hir::ForeignItem))
1643 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1645 let kind = match nitem.node {
1646 hir::ForeignItemKind::Fn(_, ref names, _) => {
1648 constness: hir::Constness::NotConst,
1649 arg_names: self.encode_fn_arg_names(names),
1650 sig: self.lazy(&tcx.fn_sig(def_id)),
1652 EntryKind::ForeignFn(self.lazy(&data))
1654 hir::ForeignItemKind::Static(_, hir::MutMutable) => EntryKind::ForeignMutStatic,
1655 hir::ForeignItemKind::Static(_, hir::MutImmutable) => EntryKind::ForeignImmStatic,
1656 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1661 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, tcx)),
1662 span: self.lazy(&nitem.span),
1663 attributes: self.encode_attributes(&nitem.attrs),
1664 children: LazySeq::empty(),
1665 stability: self.encode_stability(def_id),
1666 deprecation: self.encode_deprecation(def_id),
1668 ty: Some(self.encode_item_type(def_id)),
1669 inherent_impls: LazySeq::empty(),
1670 variances: match nitem.node {
1671 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1672 _ => LazySeq::empty(),
1674 generics: Some(self.encode_generics(def_id)),
1675 predicates: Some(self.encode_predicates(def_id)),
1676 predicates_defined_on: None,
1683 impl Visitor<'tcx> for EncodeContext<'tcx> {
1684 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1685 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1687 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1688 intravisit::walk_expr(self, ex);
1689 self.encode_info_for_expr(ex);
1691 fn visit_item(&mut self, item: &'tcx hir::Item) {
1692 intravisit::walk_item(self, item);
1693 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1695 hir::ItemKind::ExternCrate(_) |
1696 hir::ItemKind::Use(..) => {} // ignore these
1697 _ => self.record(def_id, EncodeContext::encode_info_for_item, (def_id, item)),
1699 self.encode_addl_info_for_item(item);
1701 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1702 intravisit::walk_foreign_item(self, ni);
1703 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1705 EncodeContext::encode_info_for_foreign_item,
1708 fn visit_variant(&mut self,
1709 v: &'tcx hir::Variant,
1710 g: &'tcx hir::Generics,
1712 intravisit::walk_variant(self, v, g, id);
1714 if let Some(ref discr) = v.disr_expr {
1715 let def_id = self.tcx.hir().local_def_id(discr.hir_id);
1716 self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id);
1719 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1720 intravisit::walk_generics(self, generics);
1721 self.encode_info_for_generics(generics);
1723 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1724 intravisit::walk_ty(self, ty);
1725 self.encode_info_for_ty(ty);
1727 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1728 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1729 self.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def);
1733 impl EncodeContext<'tcx> {
1734 fn encode_fields(&mut self, adt_def_id: DefId) {
1735 let def = self.tcx.adt_def(adt_def_id);
1736 for (variant_index, variant) in def.variants.iter_enumerated() {
1737 for (field_index, field) in variant.fields.iter().enumerate() {
1738 self.record(field.did,
1739 EncodeContext::encode_field,
1740 (adt_def_id, variant_index, field_index));
1745 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1746 for param in &generics.params {
1747 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1749 GenericParamKind::Lifetime { .. } => continue,
1750 GenericParamKind::Type { ref default, .. } => {
1753 EncodeContext::encode_info_for_ty_param,
1754 (def_id, default.is_some()),
1757 GenericParamKind::Const { .. } => {
1758 self.record(def_id, EncodeContext::encode_info_for_const_param, def_id);
1764 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1766 hir::TyKind::Array(_, ref length) => {
1767 let def_id = self.tcx.hir().local_def_id(length.hir_id);
1768 self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id);
1774 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1776 hir::ExprKind::Closure(..) => {
1777 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1778 self.record(def_id, EncodeContext::encode_info_for_closure, def_id);
1784 /// In some cases, along with the item itself, we also
1785 /// encode some sub-items. Usually we want some info from the item
1786 /// so it's easier to do that here then to wait until we would encounter
1787 /// normally in the visitor walk.
1788 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1789 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1791 hir::ItemKind::Static(..) |
1792 hir::ItemKind::Const(..) |
1793 hir::ItemKind::Fn(..) |
1794 hir::ItemKind::Mod(..) |
1795 hir::ItemKind::ForeignMod(..) |
1796 hir::ItemKind::GlobalAsm(..) |
1797 hir::ItemKind::ExternCrate(..) |
1798 hir::ItemKind::Use(..) |
1799 hir::ItemKind::TyAlias(..) |
1800 hir::ItemKind::OpaqueTy(..) |
1801 hir::ItemKind::TraitAlias(..) => {
1802 // no sub-item recording needed in these cases
1804 hir::ItemKind::Enum(..) => {
1805 self.encode_fields(def_id);
1807 let def = self.tcx.adt_def(def_id);
1808 for (i, variant) in def.variants.iter_enumerated() {
1809 self.record(variant.def_id,
1810 EncodeContext::encode_enum_variant_info,
1813 if let Some(ctor_def_id) = variant.ctor_def_id {
1814 self.record(ctor_def_id,
1815 EncodeContext::encode_enum_variant_ctor,
1820 hir::ItemKind::Struct(ref struct_def, _) => {
1821 self.encode_fields(def_id);
1823 // If the struct has a constructor, encode it.
1824 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1825 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1826 self.record(ctor_def_id,
1827 EncodeContext::encode_struct_ctor,
1828 (def_id, ctor_def_id));
1831 hir::ItemKind::Union(..) => {
1832 self.encode_fields(def_id);
1834 hir::ItemKind::Impl(..) => {
1835 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1836 self.record(trait_item_def_id,
1837 EncodeContext::encode_info_for_impl_item,
1841 hir::ItemKind::Trait(..) => {
1842 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1843 self.record(item_def_id,
1844 EncodeContext::encode_info_for_trait_item,
1852 struct ImplVisitor<'tcx> {
1854 impls: FxHashMap<DefId, Vec<DefIndex>>,
1857 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1858 fn visit_item(&mut self, item: &hir::Item) {
1859 if let hir::ItemKind::Impl(..) = item.node {
1860 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1861 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1863 .entry(trait_ref.def_id)
1865 .push(impl_id.index);
1870 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1872 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1873 // handled in `visit_item` above
1877 // NOTE(eddyb) The following comment was preserved for posterity, even
1878 // though it's no longer relevant as EBML (which uses nested & tagged
1879 // "documents") was replaced with a scheme that can't go out of bounds.
1881 // And here we run into yet another obscure archive bug: in which metadata
1882 // loaded from archives may have trailing garbage bytes. Awhile back one of
1883 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1884 // and opt) by having ebml generate an out-of-bounds panic when looking at
1887 // Upon investigation it turned out that the metadata file inside of an rlib
1888 // (and ar archive) was being corrupted. Some compilations would generate a
1889 // metadata file which would end in a few extra bytes, while other
1890 // compilations would not have these extra bytes appended to the end. These
1891 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1892 // being interpreted causing the out-of-bounds.
1894 // The root cause of why these extra bytes were appearing was never
1895 // discovered, and in the meantime the solution we're employing is to insert
1896 // the length of the metadata to the start of the metadata. Later on this
1897 // will allow us to slice the metadata to the precise length that we just
1898 // generated regardless of trailing bytes that end up in it.
1900 pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1901 let mut encoder = opaque::Encoder::new(vec![]);
1902 encoder.emit_raw_bytes(METADATA_HEADER);
1904 // Will be filled with the root position after encoding everything.
1905 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1907 // Since encoding metadata is not in a query, and nothing is cached,
1908 // there's no need to do dep-graph tracking for any of it.
1909 let (root, mut result) = tcx.dep_graph.with_ignore(move || {
1910 let mut ecx = EncodeContext {
1913 entries_index: Index::new(tcx.hir().definitions().def_index_count()),
1914 lazy_state: LazyState::NoNode,
1915 type_shorthands: Default::default(),
1916 predicate_shorthands: Default::default(),
1917 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1918 interpret_allocs: Default::default(),
1919 interpret_allocs_inverse: Default::default(),
1922 // Encode the rustc version string in a predictable location.
1923 rustc_version().encode(&mut ecx).unwrap();
1925 // Encode all the entries and extra information in the crate,
1926 // culminating in the `CrateRoot` which points to all of it.
1927 let root = ecx.encode_crate_root();
1928 (root, ecx.opaque.into_inner())
1931 // Encode the root position.
1932 let header = METADATA_HEADER.len();
1933 let pos = root.position;
1934 result[header + 0] = (pos >> 24) as u8;
1935 result[header + 1] = (pos >> 16) as u8;
1936 result[header + 2] = (pos >> 8) as u8;
1937 result[header + 3] = (pos >> 0) as u8;
1939 EncodedMetadata { raw_data: result }
1942 pub fn get_repr_options(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1943 let ty = tcx.type_of(did);
1945 ty::Adt(ref def, _) => return def.repr,
1946 _ => bug!("{} is not an ADT", ty),