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_index::vec::IndexVec;
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;
34 use syntax::ext::proc_macro::is_proc_macro_attr;
35 use syntax::source_map::Spanned;
36 use syntax::symbol::{kw, sym, Ident, Symbol};
37 use syntax_pos::{self, FileName, SourceFile, Span};
38 use log::{debug, trace};
40 use rustc::hir::{self, PatKind};
41 use rustc::hir::itemlikevisit::ItemLikeVisitor;
42 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
43 use rustc::hir::intravisit;
45 pub struct EncodeContext<'tcx> {
46 opaque: opaque::Encoder,
47 pub tcx: TyCtxt<'tcx>,
49 entries_index: Index<'tcx>,
51 lazy_state: LazyState,
52 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
53 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
55 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
56 interpret_allocs_inverse: Vec<interpret::AllocId>,
58 // This is used to speed up Span encoding.
59 source_file_cache: Lrc<SourceFile>,
62 macro_rules! encoder_methods {
63 ($($name:ident($ty:ty);)*) => {
64 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
65 self.opaque.$name(value)
70 impl<'tcx> Encoder for EncodeContext<'tcx> {
71 type Error = <opaque::Encoder as Encoder>::Error;
73 fn emit_unit(&mut self) -> Result<(), Self::Error> {
100 impl<'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'tcx> {
101 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
102 self.emit_lazy_distance(*lazy)
106 impl<'tcx, T> SpecializedEncoder<Lazy<[T]>> for EncodeContext<'tcx> {
107 fn specialized_encode(&mut self, lazy: &Lazy<[T]>) -> Result<(), Self::Error> {
108 self.emit_usize(lazy.meta)?;
112 self.emit_lazy_distance(*lazy)
116 impl<'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'tcx> {
118 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
119 self.emit_u32(cnum.as_u32())
123 impl<'tcx> SpecializedEncoder<DefId> for EncodeContext<'tcx> {
125 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
136 impl<'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'tcx> {
138 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
139 self.emit_u32(def_index.as_u32())
143 impl<'tcx> SpecializedEncoder<Span> for EncodeContext<'tcx> {
144 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
146 return TAG_INVALID_SPAN.encode(self)
149 let span = span.data();
151 // The Span infrastructure should make sure that this invariant holds:
152 debug_assert!(span.lo <= span.hi);
154 if !self.source_file_cache.contains(span.lo) {
155 let source_map = self.tcx.sess.source_map();
156 let source_file_index = source_map.lookup_source_file_idx(span.lo);
157 self.source_file_cache = source_map.files()[source_file_index].clone();
160 if !self.source_file_cache.contains(span.hi) {
161 // Unfortunately, macro expansion still sometimes generates Spans
162 // that malformed in this way.
163 return TAG_INVALID_SPAN.encode(self)
166 TAG_VALID_SPAN.encode(self)?;
167 span.lo.encode(self)?;
169 // Encode length which is usually less than span.hi and profits more
170 // from the variable-length integer encoding that we use.
171 let len = span.hi - span.lo;
174 // Don't encode the expansion context.
178 impl SpecializedEncoder<Ident> for EncodeContext<'tcx> {
179 fn specialized_encode(&mut self, ident: &Ident) -> Result<(), Self::Error> {
180 // FIXME(jseyfried): intercrate hygiene
181 ident.name.encode(self)
185 impl<'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'tcx> {
187 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
188 self.specialized_encode(&def_id.to_def_id())
192 impl<'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'tcx> {
193 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
194 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
198 impl<'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'tcx> {
199 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
200 use std::collections::hash_map::Entry;
201 let index = match self.interpret_allocs.entry(*alloc_id) {
202 Entry::Occupied(e) => *e.get(),
203 Entry::Vacant(e) => {
204 let idx = self.interpret_allocs_inverse.len();
205 self.interpret_allocs_inverse.push(*alloc_id);
215 impl<'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'tcx> {
216 fn specialized_encode(&mut self,
217 predicates: &ty::GenericPredicates<'tcx>)
218 -> Result<(), Self::Error> {
219 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
223 impl<'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'tcx> {
224 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
225 f.encode_opaque(&mut self.opaque)
229 impl<'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'tcx> {
230 fn specialized_encode(&mut self,
231 _: &mir::ClearCrossCrate<T>)
232 -> Result<(), Self::Error> {
237 impl<'tcx> TyEncoder for EncodeContext<'tcx> {
238 fn position(&self) -> usize {
239 self.opaque.position()
243 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
244 trait EncodeContentsForLazy<T: ?Sized + LazyMeta> {
245 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> T::Meta;
248 impl<T: Encodable> EncodeContentsForLazy<T> for &T {
249 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
250 self.encode(ecx).unwrap()
254 impl<T: Encodable> EncodeContentsForLazy<T> for T {
255 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
256 self.encode(ecx).unwrap()
260 impl<I, T> EncodeContentsForLazy<[T]> for I
261 where I: IntoIterator,
262 I::Item: EncodeContentsForLazy<T>,
264 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> usize {
265 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
269 impl<'tcx> EncodeContext<'tcx> {
270 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
273 ) -> Result<(), <Self as Encoder>::Error> {
274 let min_end = lazy.position + T::min_size(lazy.meta);
275 let distance = match self.lazy_state {
276 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
277 LazyState::NodeStart(start) => {
278 assert!(min_end <= start);
281 LazyState::Previous(last_min_end) => {
283 last_min_end <= lazy.position,
284 "make sure that the calls to `lazy*` \
285 are in the same order as the metadata fields",
287 lazy.position - last_min_end
290 self.lazy_state = LazyState::Previous(min_end);
291 self.emit_usize(distance)
294 fn lazy<T: ?Sized + LazyMeta>(
296 value: impl EncodeContentsForLazy<T>,
298 let pos = self.position();
300 assert_eq!(self.lazy_state, LazyState::NoNode);
301 self.lazy_state = LazyState::NodeStart(pos);
302 let meta = value.encode_contents_for_lazy(self);
303 self.lazy_state = LazyState::NoNode;
305 assert!(pos + <T>::min_size(meta) <= self.position());
307 Lazy::from_position_and_meta(pos, meta)
310 /// Emit the data for a `DefId` to the metadata. The function to
311 /// emit the data is `op`, and it will be given `data` as
312 /// arguments. This `record` function will call `op` to generate
313 /// the `Entry` (which may point to other encoded information)
314 /// and will then record the `Lazy<Entry>` for use in the index.
315 // FIXME(eddyb) remove this.
316 pub fn record<DATA>(&mut self,
318 op: impl FnOnce(&mut Self, DATA) -> Entry<'tcx>,
321 assert!(id.is_local());
323 let entry = op(self, data);
324 let entry = self.lazy(entry);
325 self.entries_index.record(id, entry);
328 fn encode_info_for_items(&mut self) {
329 let krate = self.tcx.hir().krate();
330 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public };
331 self.record(DefId::local(CRATE_DEF_INDEX),
332 EncodeContext::encode_info_for_mod,
333 (hir::CRATE_HIR_ID, &krate.module, &krate.attrs, &vis));
334 krate.visit_all_item_likes(&mut self.as_deep_visitor());
335 for macro_def in &krate.exported_macros {
336 self.visit_macro_def(macro_def);
340 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
341 let definitions = self.tcx.hir().definitions();
342 self.lazy(definitions.def_path_table())
345 fn encode_source_map(&mut self) -> Lazy<[syntax_pos::SourceFile]> {
346 let source_map = self.tcx.sess.source_map();
347 let all_source_files = source_map.files();
349 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
351 let adapted = all_source_files.iter()
352 .filter(|source_file| {
353 // No need to re-export imported source_files, as any downstream
354 // crate will import them from their original source.
355 !source_file.is_imported()
358 match source_file.name {
359 // This path of this SourceFile has been modified by
360 // path-remapping, so we use it verbatim (and avoid
361 // cloning the whole map in the process).
362 _ if source_file.name_was_remapped => source_file.clone(),
364 // Otherwise expand all paths to absolute paths because
365 // any relative paths are potentially relative to a
367 FileName::Real(ref name) => {
368 let mut adapted = (**source_file).clone();
369 adapted.name = Path::new(&working_dir).join(name).into();
370 adapted.name_hash = {
371 let mut hasher: StableHasher = StableHasher::new();
372 adapted.name.hash(&mut hasher);
373 hasher.finish::<u128>()
378 // expanded code, not from a file
379 _ => source_file.clone(),
382 .collect::<Vec<_>>();
384 self.lazy(adapted.iter().map(|rc| &**rc))
387 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
388 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
390 let mut i = self.position();
392 let crate_deps = self.encode_crate_deps();
393 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
394 let dep_bytes = self.position() - i;
396 // Encode the lib features.
398 let lib_features = self.encode_lib_features();
399 let lib_feature_bytes = self.position() - i;
401 // Encode the language items.
403 let lang_items = self.encode_lang_items();
404 let lang_items_missing = self.encode_lang_items_missing();
405 let lang_item_bytes = self.position() - i;
407 // Encode the diagnostic items.
409 let diagnostic_items = self.encode_diagnostic_items();
410 let diagnostic_item_bytes = self.position() - i;
412 // Encode the native libraries used
414 let native_libraries = self.encode_native_libraries();
415 let native_lib_bytes = self.position() - i;
417 let foreign_modules = self.encode_foreign_modules();
421 let source_map = self.encode_source_map();
422 let source_map_bytes = self.position() - i;
424 // Encode DefPathTable
426 let def_path_table = self.encode_def_path_table();
427 let def_path_table_bytes = self.position() - i;
429 // Encode the def IDs of impls, for coherence checking.
431 let impls = self.encode_impls();
432 let impl_bytes = self.position() - i;
434 // Encode exported symbols info.
436 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
437 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
438 let exported_symbols_bytes = self.position() - i;
444 self.encode_info_for_items();
445 let item_bytes = self.position() - i;
447 // Encode the allocation index
448 let interpret_alloc_index = {
449 let mut interpret_alloc_index = Vec::new();
451 trace!("beginning to encode alloc ids");
453 let new_n = self.interpret_allocs_inverse.len();
454 // if we have found new ids, serialize those, too
459 trace!("encoding {} further alloc ids", new_n - n);
460 for idx in n..new_n {
461 let id = self.interpret_allocs_inverse[idx];
462 let pos = self.position() as u32;
463 interpret_alloc_index.push(pos);
464 interpret::specialized_encode_alloc_id(
472 self.lazy(interpret_alloc_index)
477 let entries_index = self.entries_index.write_index(&mut self.opaque);
478 let entries_index_bytes = self.position() - i;
480 // Encode the proc macro data
482 let proc_macro_data = self.encode_proc_macros();
483 let proc_macro_data_bytes = self.position() - i;
486 let attrs = tcx.hir().krate_attrs();
487 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
488 let has_global_allocator = *tcx.sess.has_global_allocator.get();
489 let has_panic_handler = *tcx.sess.has_panic_handler.try_get().unwrap_or(&false);
491 let root = self.lazy(CrateRoot {
492 name: tcx.crate_name(LOCAL_CRATE),
493 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
494 triple: tcx.sess.opts.target_triple.clone(),
495 hash: tcx.crate_hash(LOCAL_CRATE),
496 disambiguator: tcx.sess.local_crate_disambiguator(),
497 panic_strategy: tcx.sess.panic_strategy(),
498 edition: tcx.sess.edition(),
499 has_global_allocator: has_global_allocator,
500 has_panic_handler: has_panic_handler,
501 has_default_lib_allocator: has_default_lib_allocator,
502 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
503 proc_macro_decls_static: if is_proc_macro {
504 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
510 proc_macro_stability: if is_proc_macro {
511 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).map(|stab| stab.clone())
515 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
516 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
517 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
518 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
519 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
520 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
521 sanitizer_runtime: attr::contains_name(&attrs, sym::sanitizer_runtime),
522 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
525 dylib_dependency_formats,
536 interpret_alloc_index,
540 let total_bytes = self.position();
542 if self.tcx.sess.meta_stats() {
543 let mut zero_bytes = 0;
544 for e in self.opaque.data.iter() {
550 println!("metadata stats:");
551 println!(" dep bytes: {}", dep_bytes);
552 println!(" lib feature bytes: {}", lib_feature_bytes);
553 println!(" lang item bytes: {}", lang_item_bytes);
554 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
555 println!(" native bytes: {}", native_lib_bytes);
556 println!(" source_map bytes: {}", source_map_bytes);
557 println!(" impl bytes: {}", impl_bytes);
558 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
559 println!(" def-path table bytes: {}", def_path_table_bytes);
560 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
561 println!(" item bytes: {}", item_bytes);
562 println!(" entries index bytes: {}", entries_index_bytes);
563 println!(" zero bytes: {}", zero_bytes);
564 println!(" total bytes: {}", total_bytes);
571 impl EncodeContext<'tcx> {
572 fn encode_variances_of(&mut self, def_id: DefId) -> Lazy<[ty::Variance]> {
573 debug!("EncodeContext::encode_variances_of({:?})", def_id);
575 self.lazy(&tcx.variances_of(def_id)[..])
578 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
580 let ty = tcx.type_of(def_id);
581 debug!("EncodeContext::encode_item_type({:?}) => {:?}", def_id, ty);
585 fn encode_enum_variant_info(
587 (enum_did, index): (DefId, VariantIdx),
590 let def = tcx.adt_def(enum_did);
591 let variant = &def.variants[index];
592 let def_id = variant.def_id;
593 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
595 let data = VariantData {
596 ctor_kind: variant.ctor_kind,
597 discr: variant.discr,
598 // FIXME(eddyb) deduplicate these with `encode_enum_variant_ctor`.
599 ctor: variant.ctor_def_id.map(|did| did.index),
600 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
601 variant.ctor_def_id.map(|ctor_def_id| self.lazy(&tcx.fn_sig(ctor_def_id)))
607 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
608 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
611 kind: EntryKind::Variant(self.lazy(data)),
612 visibility: self.lazy(ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
613 span: self.lazy(tcx.def_span(def_id)),
614 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
615 children: self.lazy(variant.fields.iter().map(|f| {
616 assert!(f.did.is_local());
619 stability: self.encode_stability(def_id),
620 deprecation: self.encode_deprecation(def_id),
622 ty: Some(self.encode_item_type(def_id)),
623 inherent_impls: Lazy::empty(),
624 variances: if variant.ctor_kind == CtorKind::Fn {
625 self.encode_variances_of(def_id)
629 generics: Some(self.encode_generics(def_id)),
630 predicates: Some(self.encode_predicates(def_id)),
631 predicates_defined_on: None,
633 mir: self.encode_optimized_mir(def_id),
634 promoted_mir: self.encode_promoted_mir(def_id),
638 fn encode_enum_variant_ctor(
640 (enum_did, index): (DefId, VariantIdx),
643 let def = tcx.adt_def(enum_did);
644 let variant = &def.variants[index];
645 let def_id = variant.ctor_def_id.unwrap();
646 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
648 let data = VariantData {
649 ctor_kind: variant.ctor_kind,
650 discr: variant.discr,
651 ctor: Some(def_id.index),
652 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
653 Some(self.lazy(tcx.fn_sig(def_id)))
659 // Variant constructors have the same visibility as the parent enums, unless marked as
660 // non-exhaustive, in which case they are lowered to `pub(crate)`.
661 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
662 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
663 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
664 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
665 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
669 kind: EntryKind::Variant(self.lazy(data)),
670 visibility: self.lazy(ctor_vis),
671 span: self.lazy(tcx.def_span(def_id)),
672 attributes: Lazy::empty(),
673 children: Lazy::empty(),
674 stability: self.encode_stability(def_id),
675 deprecation: self.encode_deprecation(def_id),
677 ty: Some(self.encode_item_type(def_id)),
678 inherent_impls: Lazy::empty(),
679 variances: if variant.ctor_kind == CtorKind::Fn {
680 self.encode_variances_of(def_id)
684 generics: Some(self.encode_generics(def_id)),
685 predicates: Some(self.encode_predicates(def_id)),
686 predicates_defined_on: None,
688 mir: self.encode_optimized_mir(def_id),
689 promoted_mir: self.encode_promoted_mir(def_id),
693 fn encode_info_for_mod(
695 (id, md, attrs, vis): (hir::HirId, &hir::Mod, &[ast::Attribute], &hir::Visibility),
698 let def_id = tcx.hir().local_def_id(id);
699 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
702 reexports: match tcx.module_exports(def_id) {
703 Some(exports) => self.lazy(exports),
709 kind: EntryKind::Mod(self.lazy(data)),
710 visibility: self.lazy(ty::Visibility::from_hir(vis, id, tcx)),
711 span: self.lazy(tcx.def_span(def_id)),
712 attributes: self.encode_attributes(attrs),
713 children: self.lazy(md.item_ids.iter().map(|item_id| {
714 tcx.hir().local_def_id(item_id.id).index
716 stability: self.encode_stability(def_id),
717 deprecation: self.encode_deprecation(def_id),
720 inherent_impls: Lazy::empty(),
721 variances: Lazy::empty(),
724 predicates_defined_on: None,
733 (adt_def_id, variant_index, field_index): (DefId, VariantIdx, usize),
736 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
737 let field = &variant.fields[field_index];
739 let def_id = field.did;
740 debug!("EncodeContext::encode_field({:?})", def_id);
742 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
743 let variant_data = tcx.hir().expect_variant_data(variant_id);
746 kind: EntryKind::Field,
747 visibility: self.lazy(field.vis),
748 span: self.lazy(tcx.def_span(def_id)),
749 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
750 children: Lazy::empty(),
751 stability: self.encode_stability(def_id),
752 deprecation: self.encode_deprecation(def_id),
754 ty: Some(self.encode_item_type(def_id)),
755 inherent_impls: Lazy::empty(),
756 variances: Lazy::empty(),
757 generics: Some(self.encode_generics(def_id)),
758 predicates: Some(self.encode_predicates(def_id)),
759 predicates_defined_on: None,
766 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
767 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
769 let adt_def = tcx.adt_def(adt_def_id);
770 let variant = adt_def.non_enum_variant();
772 let data = VariantData {
773 ctor_kind: variant.ctor_kind,
774 discr: variant.discr,
775 ctor: Some(def_id.index),
776 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
777 Some(self.lazy(tcx.fn_sig(def_id)))
783 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
784 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
785 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
786 for field in &variant.fields {
787 if ctor_vis.is_at_least(field.vis, tcx) {
788 ctor_vis = field.vis;
792 // If the structure is marked as non_exhaustive then lower the visibility
793 // to within the crate.
794 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
795 ctor_vis == ty::Visibility::Public
797 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
800 let repr_options = get_repr_options(tcx, adt_def_id);
803 kind: EntryKind::Struct(self.lazy(data), repr_options),
804 visibility: self.lazy(ctor_vis),
805 span: self.lazy(tcx.def_span(def_id)),
806 attributes: Lazy::empty(),
807 children: Lazy::empty(),
808 stability: self.encode_stability(def_id),
809 deprecation: self.encode_deprecation(def_id),
811 ty: Some(self.encode_item_type(def_id)),
812 inherent_impls: Lazy::empty(),
813 variances: if variant.ctor_kind == CtorKind::Fn {
814 self.encode_variances_of(def_id)
818 generics: Some(self.encode_generics(def_id)),
819 predicates: Some(self.encode_predicates(def_id)),
820 predicates_defined_on: None,
822 mir: self.encode_optimized_mir(def_id),
823 promoted_mir: self.encode_promoted_mir(def_id),
827 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
828 debug!("EncodeContext::encode_generics({:?})", def_id);
830 self.lazy(tcx.generics_of(def_id))
833 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
834 debug!("EncodeContext::encode_predicates({:?})", def_id);
836 self.lazy(&*tcx.predicates_of(def_id))
839 fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
840 debug!("EncodeContext::encode_predicates_defined_on({:?})", def_id);
842 self.lazy(&*tcx.predicates_defined_on(def_id))
845 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
846 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
849 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
850 let ast_item = tcx.hir().expect_trait_item(hir_id);
851 let trait_item = tcx.associated_item(def_id);
853 let container = match trait_item.defaultness {
854 hir::Defaultness::Default { has_value: true } =>
855 AssocContainer::TraitWithDefault,
856 hir::Defaultness::Default { has_value: false } =>
857 AssocContainer::TraitRequired,
858 hir::Defaultness::Final =>
859 span_bug!(ast_item.span, "traits cannot have final items"),
862 let kind = match trait_item.kind {
863 ty::AssocKind::Const => {
865 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.kind {
866 self.const_qualif(0, body)
868 ConstQualif { mir: 0, ast_promotable: false }
872 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
873 let rendered_const = self.lazy(RenderedConst(rendered));
875 EntryKind::AssocConst(container, const_qualif, rendered_const)
877 ty::AssocKind::Method => {
878 let fn_data = if let hir::TraitItemKind::Method(method_sig, m) = &ast_item.kind {
879 let param_names = match *m {
880 hir::TraitMethod::Required(ref names) => {
881 self.encode_fn_param_names(names)
883 hir::TraitMethod::Provided(body) => {
884 self.encode_fn_param_names_for_body(body)
888 asyncness: method_sig.header.asyncness,
889 constness: hir::Constness::NotConst,
891 sig: self.lazy(&tcx.fn_sig(def_id)),
896 EntryKind::Method(self.lazy(MethodData {
899 has_self: trait_item.method_has_self_argument,
902 ty::AssocKind::Type => EntryKind::AssocType(container),
903 ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
908 visibility: self.lazy(trait_item.vis),
909 span: self.lazy(ast_item.span),
910 attributes: self.encode_attributes(&ast_item.attrs),
911 children: Lazy::empty(),
912 stability: self.encode_stability(def_id),
913 deprecation: self.encode_deprecation(def_id),
915 ty: match trait_item.kind {
916 ty::AssocKind::Const |
917 ty::AssocKind::Method => {
918 Some(self.encode_item_type(def_id))
920 ty::AssocKind::Type => {
921 if trait_item.defaultness.has_value() {
922 Some(self.encode_item_type(def_id))
927 ty::AssocKind::OpaqueTy => unreachable!(),
929 inherent_impls: Lazy::empty(),
930 variances: if trait_item.kind == ty::AssocKind::Method {
931 self.encode_variances_of(def_id)
935 generics: Some(self.encode_generics(def_id)),
936 predicates: Some(self.encode_predicates(def_id)),
937 predicates_defined_on: None,
939 mir: self.encode_optimized_mir(def_id),
940 promoted_mir: self.encode_promoted_mir(def_id),
944 fn metadata_output_only(&self) -> bool {
945 // MIR optimisation can be skipped when we're just interested in the metadata.
946 !self.tcx.sess.opts.output_types.should_codegen()
949 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
950 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
951 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
953 ConstQualif { mir, ast_promotable }
956 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
957 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
960 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
961 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
962 let impl_item = self.tcx.associated_item(def_id);
964 let container = match impl_item.defaultness {
965 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
966 hir::Defaultness::Final => AssocContainer::ImplFinal,
967 hir::Defaultness::Default { has_value: false } =>
968 span_bug!(ast_item.span, "impl items always have values (currently)"),
971 let kind = match impl_item.kind {
972 ty::AssocKind::Const => {
973 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
974 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
976 EntryKind::AssocConst(container,
977 self.const_qualif(mir, body_id),
978 self.encode_rendered_const_for_body(body_id))
983 ty::AssocKind::Method => {
984 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.kind {
986 asyncness: sig.header.asyncness,
987 constness: sig.header.constness,
988 param_names: self.encode_fn_param_names_for_body(body),
989 sig: self.lazy(&tcx.fn_sig(def_id)),
994 EntryKind::Method(self.lazy(MethodData {
997 has_self: impl_item.method_has_self_argument,
1000 ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
1001 ty::AssocKind::Type => EntryKind::AssocType(container)
1004 let mir = match ast_item.kind {
1005 hir::ImplItemKind::Const(..) => true,
1006 hir::ImplItemKind::Method(ref sig, _) => {
1007 let generics = self.tcx.generics_of(def_id);
1008 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
1009 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1010 !self.metadata_output_only();
1011 let is_const_fn = sig.header.constness == hir::Constness::Const;
1012 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1013 needs_inline || is_const_fn || always_encode_mir
1015 hir::ImplItemKind::OpaqueTy(..) |
1016 hir::ImplItemKind::TyAlias(..) => false,
1021 visibility: self.lazy(impl_item.vis),
1022 span: self.lazy(ast_item.span),
1023 attributes: self.encode_attributes(&ast_item.attrs),
1024 children: Lazy::empty(),
1025 stability: self.encode_stability(def_id),
1026 deprecation: self.encode_deprecation(def_id),
1028 ty: Some(self.encode_item_type(def_id)),
1029 inherent_impls: Lazy::empty(),
1030 variances: if impl_item.kind == ty::AssocKind::Method {
1031 self.encode_variances_of(def_id)
1035 generics: Some(self.encode_generics(def_id)),
1036 predicates: Some(self.encode_predicates(def_id)),
1037 predicates_defined_on: None,
1039 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
1040 promoted_mir: if mir { self.encode_promoted_mir(def_id) } else { None },
1044 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId)
1045 -> Lazy<[ast::Name]> {
1046 self.tcx.dep_graph.with_ignore(|| {
1047 let body = self.tcx.hir().body(body_id);
1048 self.lazy(body.params.iter().map(|arg| {
1049 match arg.pat.kind {
1050 PatKind::Binding(_, _, ident, _) => ident.name,
1057 fn encode_fn_param_names(&mut self, param_names: &[ast::Ident]) -> Lazy<[ast::Name]> {
1058 self.lazy(param_names.iter().map(|ident| ident.name))
1061 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Body<'tcx>>> {
1062 debug!("EntryBuilder::encode_mir({:?})", def_id);
1063 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1064 let mir = self.tcx.optimized_mir(def_id);
1065 Some(self.lazy(mir))
1071 fn encode_promoted_mir(
1074 ) -> Option<Lazy<IndexVec<mir::Promoted, mir::Body<'tcx>>>> {
1075 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1076 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1077 let promoted = self.tcx.promoted_mir(def_id);
1078 Some(self.lazy(promoted))
1084 // Encodes the inherent implementations of a structure, enumeration, or trait.
1085 fn encode_inherent_implementations(&mut self, def_id: DefId) -> Lazy<[DefIndex]> {
1086 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1087 let implementations = self.tcx.inherent_impls(def_id);
1088 if implementations.is_empty() {
1091 self.lazy(implementations.iter().map(|&def_id| {
1092 assert!(def_id.is_local());
1098 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1099 debug!("EncodeContext::encode_stability({:?})", def_id);
1100 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1103 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1104 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1105 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(depr))
1108 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1109 let body = self.tcx.hir().body(body_id);
1110 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1111 let rendered_const = &RenderedConst(rendered);
1112 self.lazy(rendered_const)
1115 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1118 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1120 let kind = match item.kind {
1121 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1122 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1123 hir::ItemKind::Const(_, body_id) => {
1124 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1126 self.const_qualif(mir, body_id),
1127 self.encode_rendered_const_for_body(body_id)
1130 hir::ItemKind::Fn(_, header, .., body) => {
1132 asyncness: header.asyncness,
1133 constness: header.constness,
1134 param_names: self.encode_fn_param_names_for_body(body),
1135 sig: self.lazy(tcx.fn_sig(def_id)),
1138 EntryKind::Fn(self.lazy(data))
1140 hir::ItemKind::Mod(ref m) => {
1141 return self.encode_info_for_mod((item.hir_id, m, &item.attrs, &item.vis));
1143 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1144 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1145 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1146 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1147 hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(tcx, def_id)),
1148 hir::ItemKind::Struct(ref struct_def, _) => {
1149 let variant = tcx.adt_def(def_id).non_enum_variant();
1151 // Encode def_ids for each field and method
1152 // for methods, write all the stuff get_trait_method
1154 let ctor = struct_def.ctor_hir_id()
1155 .map(|ctor_hir_id| tcx.hir().local_def_id(ctor_hir_id).index);
1157 let repr_options = get_repr_options(tcx, def_id);
1159 EntryKind::Struct(self.lazy(VariantData {
1160 ctor_kind: variant.ctor_kind,
1161 discr: variant.discr,
1166 hir::ItemKind::Union(..) => {
1167 let variant = tcx.adt_def(def_id).non_enum_variant();
1168 let repr_options = get_repr_options(tcx, def_id);
1170 EntryKind::Union(self.lazy(VariantData {
1171 ctor_kind: variant.ctor_kind,
1172 discr: variant.discr,
1177 hir::ItemKind::Impl(_, _, defaultness, ..) => {
1178 let trait_ref = tcx.impl_trait_ref(def_id);
1179 let polarity = tcx.impl_polarity(def_id);
1180 let parent = if let Some(trait_ref) = trait_ref {
1181 let trait_def = tcx.trait_def(trait_ref.def_id);
1182 trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| {
1184 specialization_graph::Node::Impl(parent) => Some(parent),
1192 // if this is an impl of `CoerceUnsized`, create its
1193 // "unsized info", else just store None
1194 let coerce_unsized_info =
1195 trait_ref.and_then(|t| {
1196 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1197 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1203 let data = ImplData {
1206 parent_impl: parent,
1207 coerce_unsized_info,
1208 trait_ref: trait_ref.map(|trait_ref| self.lazy(trait_ref)),
1211 EntryKind::Impl(self.lazy(data))
1213 hir::ItemKind::Trait(..) => {
1214 let trait_def = tcx.trait_def(def_id);
1215 let data = TraitData {
1216 unsafety: trait_def.unsafety,
1217 paren_sugar: trait_def.paren_sugar,
1218 has_auto_impl: tcx.trait_is_auto(def_id),
1219 is_marker: trait_def.is_marker,
1220 super_predicates: self.lazy(&*tcx.super_predicates_of(def_id)),
1223 EntryKind::Trait(self.lazy(data))
1225 hir::ItemKind::TraitAlias(..) => {
1226 let data = TraitAliasData {
1227 super_predicates: self.lazy(&*tcx.super_predicates_of(def_id)),
1230 EntryKind::TraitAlias(self.lazy(data))
1232 hir::ItemKind::ExternCrate(_) |
1233 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1236 let mir = match item.kind {
1237 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1238 hir::ItemKind::Fn(_, header, ..) => {
1239 let generics = tcx.generics_of(def_id);
1241 (generics.requires_monomorphization(tcx) ||
1242 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1243 !self.metadata_output_only();
1244 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1245 needs_inline || header.constness == hir::Constness::Const || always_encode_mir
1252 visibility: self.lazy(ty::Visibility::from_hir(&item.vis, item.hir_id, tcx)),
1253 span: self.lazy(item.span),
1254 attributes: self.encode_attributes(&item.attrs),
1255 children: match item.kind {
1256 hir::ItemKind::ForeignMod(ref fm) => {
1259 .map(|foreign_item| tcx.hir().local_def_id(
1260 foreign_item.hir_id).index))
1262 hir::ItemKind::Enum(..) => {
1263 let def = self.tcx.adt_def(def_id);
1264 self.lazy(def.variants.iter().map(|v| {
1265 assert!(v.def_id.is_local());
1269 hir::ItemKind::Struct(..) |
1270 hir::ItemKind::Union(..) => {
1271 let def = self.tcx.adt_def(def_id);
1272 self.lazy(def.non_enum_variant().fields.iter().map(|f| {
1273 assert!(f.did.is_local());
1277 hir::ItemKind::Impl(..) |
1278 hir::ItemKind::Trait(..) => {
1279 self.lazy(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1280 assert!(def_id.is_local());
1286 stability: self.encode_stability(def_id),
1287 deprecation: self.encode_deprecation(def_id),
1289 ty: match item.kind {
1290 hir::ItemKind::Static(..) |
1291 hir::ItemKind::Const(..) |
1292 hir::ItemKind::Fn(..) |
1293 hir::ItemKind::TyAlias(..) |
1294 hir::ItemKind::OpaqueTy(..) |
1295 hir::ItemKind::Enum(..) |
1296 hir::ItemKind::Struct(..) |
1297 hir::ItemKind::Union(..) |
1298 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1301 inherent_impls: self.encode_inherent_implementations(def_id),
1302 variances: match item.kind {
1303 hir::ItemKind::Enum(..) |
1304 hir::ItemKind::Struct(..) |
1305 hir::ItemKind::Union(..) |
1306 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1309 generics: match item.kind {
1310 hir::ItemKind::Static(..) |
1311 hir::ItemKind::Const(..) |
1312 hir::ItemKind::Fn(..) |
1313 hir::ItemKind::TyAlias(..) |
1314 hir::ItemKind::Enum(..) |
1315 hir::ItemKind::Struct(..) |
1316 hir::ItemKind::Union(..) |
1317 hir::ItemKind::Impl(..) |
1318 hir::ItemKind::OpaqueTy(..) |
1319 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1320 hir::ItemKind::TraitAlias(..) => Some(self.encode_generics(def_id)),
1323 predicates: match item.kind {
1324 hir::ItemKind::Static(..) |
1325 hir::ItemKind::Const(..) |
1326 hir::ItemKind::Fn(..) |
1327 hir::ItemKind::TyAlias(..) |
1328 hir::ItemKind::Enum(..) |
1329 hir::ItemKind::Struct(..) |
1330 hir::ItemKind::Union(..) |
1331 hir::ItemKind::Impl(..) |
1332 hir::ItemKind::OpaqueTy(..) |
1333 hir::ItemKind::Trait(..) |
1334 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates(def_id)),
1338 // The only time that `predicates_defined_on` is used (on
1339 // an external item) is for traits, during chalk lowering,
1340 // so only encode it in that case as an efficiency
1341 // hack. (No reason not to expand it in the future if
1343 predicates_defined_on: match item.kind {
1344 hir::ItemKind::Trait(..) |
1345 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates_defined_on(def_id)),
1346 _ => None, // not *wrong* for other kinds of items, but not needed
1349 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
1350 promoted_mir: if mir { self.encode_promoted_mir(def_id) } else { None },
1354 /// Serialize the text of exported macros
1355 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1356 use syntax::print::pprust;
1357 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1359 kind: EntryKind::MacroDef(self.lazy(MacroDef {
1360 body: pprust::tts_to_string(macro_def.body.clone()),
1361 legacy: macro_def.legacy,
1363 visibility: self.lazy(ty::Visibility::Public),
1364 span: self.lazy(macro_def.span),
1365 attributes: self.encode_attributes(¯o_def.attrs),
1366 stability: self.encode_stability(def_id),
1367 deprecation: self.encode_deprecation(def_id),
1369 children: Lazy::empty(),
1371 inherent_impls: Lazy::empty(),
1372 variances: Lazy::empty(),
1375 predicates_defined_on: None,
1381 fn encode_info_for_generic_param(
1384 entry_kind: EntryKind<'tcx>,
1390 visibility: self.lazy(ty::Visibility::Public),
1391 span: self.lazy(tcx.def_span(def_id)),
1392 attributes: Lazy::empty(),
1393 children: Lazy::empty(),
1396 ty: if encode_type { Some(self.encode_item_type(def_id)) } else { None },
1397 inherent_impls: Lazy::empty(),
1398 variances: Lazy::empty(),
1401 predicates_defined_on: None,
1408 fn encode_info_for_ty_param(
1410 (def_id, encode_type): (DefId, bool),
1412 debug!("EncodeContext::encode_info_for_ty_param({:?})", def_id);
1413 self.encode_info_for_generic_param(def_id, EntryKind::TypeParam, encode_type)
1416 fn encode_info_for_const_param(
1420 debug!("EncodeContext::encode_info_for_const_param({:?})", def_id);
1421 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true)
1424 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1425 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1428 let tables = self.tcx.typeck_tables_of(def_id);
1429 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1430 let kind = match tables.node_type(hir_id).kind {
1431 ty::Generator(def_id, ..) => {
1432 let layout = self.tcx.generator_layout(def_id);
1433 let data = GeneratorData {
1434 layout: layout.clone(),
1436 EntryKind::Generator(self.lazy(data))
1439 ty::Closure(def_id, substs) => {
1440 let sig = substs.closure_sig(def_id, self.tcx);
1441 let data = ClosureData { sig: self.lazy(sig) };
1442 EntryKind::Closure(self.lazy(data))
1445 _ => bug!("closure that is neither generator nor closure")
1450 visibility: self.lazy(ty::Visibility::Public),
1451 span: self.lazy(tcx.def_span(def_id)),
1452 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1453 children: Lazy::empty(),
1457 ty: Some(self.encode_item_type(def_id)),
1458 inherent_impls: Lazy::empty(),
1459 variances: Lazy::empty(),
1460 generics: Some(self.encode_generics(def_id)),
1462 predicates_defined_on: None,
1464 mir: self.encode_optimized_mir(def_id),
1465 promoted_mir: self.encode_promoted_mir(def_id),
1469 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1470 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1472 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
1473 let body_id = tcx.hir().body_owned_by(id);
1474 let const_data = self.encode_rendered_const_for_body(body_id);
1475 let mir = tcx.mir_const_qualif(def_id).0;
1478 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1479 visibility: self.lazy(ty::Visibility::Public),
1480 span: self.lazy(tcx.def_span(def_id)),
1481 attributes: Lazy::empty(),
1482 children: Lazy::empty(),
1486 ty: Some(self.encode_item_type(def_id)),
1487 inherent_impls: Lazy::empty(),
1488 variances: Lazy::empty(),
1489 generics: Some(self.encode_generics(def_id)),
1490 predicates: Some(self.encode_predicates(def_id)),
1491 predicates_defined_on: None,
1493 mir: self.encode_optimized_mir(def_id),
1494 promoted_mir: self.encode_promoted_mir(def_id),
1498 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> Lazy<[ast::Attribute]> {
1502 fn encode_native_libraries(&mut self) -> Lazy<[NativeLibrary]> {
1503 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1504 self.lazy(used_libraries.iter().cloned())
1507 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1508 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1509 self.lazy(foreign_modules.iter().cloned())
1512 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1513 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
1516 Some(self.lazy(tcx.hir().krate().items.values().filter_map(|item| {
1517 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
1518 Some(item.hir_id.owner)
1528 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1529 let crates = self.tcx.crates();
1531 let mut deps = crates
1534 let dep = CrateDep {
1535 name: self.tcx.original_crate_name(cnum),
1536 hash: self.tcx.crate_hash(cnum),
1537 kind: self.tcx.dep_kind(cnum),
1538 extra_filename: self.tcx.extra_filename(cnum),
1542 .collect::<Vec<_>>();
1544 deps.sort_by_key(|&(cnum, _)| cnum);
1547 // Sanity-check the crate numbers
1548 let mut expected_cnum = 1;
1549 for &(n, _) in &deps {
1550 assert_eq!(n, CrateNum::new(expected_cnum));
1555 // We're just going to write a list of crate 'name-hash-version's, with
1556 // the assumption that they are numbered 1 to n.
1557 // FIXME (#2166): This is not nearly enough to support correct versioning
1558 // but is enough to get transitive crate dependencies working.
1559 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1562 fn encode_lib_features(&mut self) -> Lazy<[(ast::Name, Option<ast::Name>)]> {
1564 let lib_features = tcx.lib_features();
1565 self.lazy(lib_features.to_vec())
1568 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1570 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1571 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1574 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1576 let lang_items = tcx.lang_items();
1577 let lang_items = lang_items.items().iter();
1578 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1579 if let Some(def_id) = opt_def_id {
1580 if def_id.is_local() {
1581 return Some((def_id.index, i));
1588 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1590 self.lazy(&tcx.lang_items().missing)
1593 /// Encodes an index, mapping each trait to its (local) implementations.
1594 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1595 debug!("EncodeContext::encode_impls()");
1597 let mut visitor = ImplVisitor {
1599 impls: FxHashMap::default(),
1601 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1603 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1605 // Bring everything into deterministic order for hashing
1606 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1607 tcx.def_path_hash(trait_def_id)
1610 let all_impls: Vec<_> = all_impls
1612 .map(|(trait_def_id, mut impls)| {
1613 // Bring everything into deterministic order for hashing
1614 impls.sort_by_cached_key(|&def_index| {
1615 tcx.hir().definitions().def_path_hash(def_index)
1619 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1620 impls: self.lazy(&impls),
1625 self.lazy(&all_impls)
1628 // Encodes all symbols exported from this crate into the metadata.
1630 // This pass is seeded off the reachability list calculated in the
1631 // middle::reachable module but filters out items that either don't have a
1632 // symbol associated with them (they weren't translated) or if they're an FFI
1633 // definition (as that's not defined in this crate).
1634 fn encode_exported_symbols(&mut self,
1635 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)])
1636 -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1637 // The metadata symbol name is special. It should not show up in
1638 // downstream crates.
1639 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1641 self.lazy(exported_symbols
1643 .filter(|&&(ref exported_symbol, _)| {
1644 match *exported_symbol {
1645 ExportedSymbol::NoDefId(symbol_name) => {
1646 symbol_name != metadata_symbol_name
1654 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1655 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1656 for (ty, arr) in formats.iter() {
1657 if *ty != config::CrateType::Dylib {
1660 return self.lazy(arr.iter().map(|slot| {
1662 Linkage::NotLinked |
1663 Linkage::IncludedFromDylib => None,
1665 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1666 Linkage::Static => Some(LinkagePreference::RequireStatic),
1673 fn encode_info_for_foreign_item(&mut self,
1674 (def_id, nitem): (DefId, &hir::ForeignItem))
1678 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1680 let kind = match nitem.kind {
1681 hir::ForeignItemKind::Fn(_, ref names, _) => {
1683 asyncness: hir::IsAsync::NotAsync,
1684 constness: hir::Constness::NotConst,
1685 param_names: self.encode_fn_param_names(names),
1686 sig: self.lazy(tcx.fn_sig(def_id)),
1688 EntryKind::ForeignFn(self.lazy(data))
1690 hir::ForeignItemKind::Static(_, hir::MutMutable) => EntryKind::ForeignMutStatic,
1691 hir::ForeignItemKind::Static(_, hir::MutImmutable) => EntryKind::ForeignImmStatic,
1692 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1697 visibility: self.lazy(ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, tcx)),
1698 span: self.lazy(nitem.span),
1699 attributes: self.encode_attributes(&nitem.attrs),
1700 children: Lazy::empty(),
1701 stability: self.encode_stability(def_id),
1702 deprecation: self.encode_deprecation(def_id),
1704 ty: Some(self.encode_item_type(def_id)),
1705 inherent_impls: Lazy::empty(),
1706 variances: match nitem.kind {
1707 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1710 generics: Some(self.encode_generics(def_id)),
1711 predicates: Some(self.encode_predicates(def_id)),
1712 predicates_defined_on: None,
1720 impl Visitor<'tcx> for EncodeContext<'tcx> {
1721 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1722 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1724 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1725 intravisit::walk_expr(self, ex);
1726 self.encode_info_for_expr(ex);
1728 fn visit_item(&mut self, item: &'tcx hir::Item) {
1729 intravisit::walk_item(self, item);
1730 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1732 hir::ItemKind::ExternCrate(_) |
1733 hir::ItemKind::Use(..) => {} // ignore these
1734 _ => self.record(def_id, EncodeContext::encode_info_for_item, (def_id, item)),
1736 self.encode_addl_info_for_item(item);
1738 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1739 intravisit::walk_foreign_item(self, ni);
1740 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1742 EncodeContext::encode_info_for_foreign_item,
1745 fn visit_variant(&mut self,
1746 v: &'tcx hir::Variant,
1747 g: &'tcx hir::Generics,
1749 intravisit::walk_variant(self, v, g, id);
1751 if let Some(ref discr) = v.disr_expr {
1752 let def_id = self.tcx.hir().local_def_id(discr.hir_id);
1753 self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id);
1756 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1757 intravisit::walk_generics(self, generics);
1758 self.encode_info_for_generics(generics);
1760 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1761 intravisit::walk_ty(self, ty);
1762 self.encode_info_for_ty(ty);
1764 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1765 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1766 self.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def);
1770 impl EncodeContext<'tcx> {
1771 fn encode_fields(&mut self, adt_def_id: DefId) {
1772 let def = self.tcx.adt_def(adt_def_id);
1773 for (variant_index, variant) in def.variants.iter_enumerated() {
1774 for (field_index, field) in variant.fields.iter().enumerate() {
1775 self.record(field.did,
1776 EncodeContext::encode_field,
1777 (adt_def_id, variant_index, field_index));
1782 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1783 for param in &generics.params {
1784 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1786 GenericParamKind::Lifetime { .. } => continue,
1787 GenericParamKind::Type { ref default, .. } => {
1790 EncodeContext::encode_info_for_ty_param,
1791 (def_id, default.is_some()),
1794 GenericParamKind::Const { .. } => {
1795 self.record(def_id, EncodeContext::encode_info_for_const_param, def_id);
1801 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1803 hir::TyKind::Array(_, ref length) => {
1804 let def_id = self.tcx.hir().local_def_id(length.hir_id);
1805 self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id);
1811 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1813 hir::ExprKind::Closure(..) => {
1814 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1815 self.record(def_id, EncodeContext::encode_info_for_closure, def_id);
1821 /// In some cases, along with the item itself, we also
1822 /// encode some sub-items. Usually we want some info from the item
1823 /// so it's easier to do that here then to wait until we would encounter
1824 /// normally in the visitor walk.
1825 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1826 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1828 hir::ItemKind::Static(..) |
1829 hir::ItemKind::Const(..) |
1830 hir::ItemKind::Fn(..) |
1831 hir::ItemKind::Mod(..) |
1832 hir::ItemKind::ForeignMod(..) |
1833 hir::ItemKind::GlobalAsm(..) |
1834 hir::ItemKind::ExternCrate(..) |
1835 hir::ItemKind::Use(..) |
1836 hir::ItemKind::TyAlias(..) |
1837 hir::ItemKind::OpaqueTy(..) |
1838 hir::ItemKind::TraitAlias(..) => {
1839 // no sub-item recording needed in these cases
1841 hir::ItemKind::Enum(..) => {
1842 self.encode_fields(def_id);
1844 let def = self.tcx.adt_def(def_id);
1845 for (i, variant) in def.variants.iter_enumerated() {
1846 self.record(variant.def_id,
1847 EncodeContext::encode_enum_variant_info,
1850 if let Some(ctor_def_id) = variant.ctor_def_id {
1851 self.record(ctor_def_id,
1852 EncodeContext::encode_enum_variant_ctor,
1857 hir::ItemKind::Struct(ref struct_def, _) => {
1858 self.encode_fields(def_id);
1860 // If the struct has a constructor, encode it.
1861 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1862 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1863 self.record(ctor_def_id,
1864 EncodeContext::encode_struct_ctor,
1865 (def_id, ctor_def_id));
1868 hir::ItemKind::Union(..) => {
1869 self.encode_fields(def_id);
1871 hir::ItemKind::Impl(..) => {
1872 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1873 self.record(trait_item_def_id,
1874 EncodeContext::encode_info_for_impl_item,
1878 hir::ItemKind::Trait(..) => {
1879 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1880 self.record(item_def_id,
1881 EncodeContext::encode_info_for_trait_item,
1889 struct ImplVisitor<'tcx> {
1891 impls: FxHashMap<DefId, Vec<DefIndex>>,
1894 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1895 fn visit_item(&mut self, item: &hir::Item) {
1896 if let hir::ItemKind::Impl(..) = item.kind {
1897 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1898 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1900 .entry(trait_ref.def_id)
1902 .push(impl_id.index);
1907 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1909 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1910 // handled in `visit_item` above
1914 // NOTE(eddyb) The following comment was preserved for posterity, even
1915 // though it's no longer relevant as EBML (which uses nested & tagged
1916 // "documents") was replaced with a scheme that can't go out of bounds.
1918 // And here we run into yet another obscure archive bug: in which metadata
1919 // loaded from archives may have trailing garbage bytes. Awhile back one of
1920 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1921 // and opt) by having ebml generate an out-of-bounds panic when looking at
1924 // Upon investigation it turned out that the metadata file inside of an rlib
1925 // (and ar archive) was being corrupted. Some compilations would generate a
1926 // metadata file which would end in a few extra bytes, while other
1927 // compilations would not have these extra bytes appended to the end. These
1928 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1929 // being interpreted causing the out-of-bounds.
1931 // The root cause of why these extra bytes were appearing was never
1932 // discovered, and in the meantime the solution we're employing is to insert
1933 // the length of the metadata to the start of the metadata. Later on this
1934 // will allow us to slice the metadata to the precise length that we just
1935 // generated regardless of trailing bytes that end up in it.
1937 pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1938 let mut encoder = opaque::Encoder::new(vec![]);
1939 encoder.emit_raw_bytes(METADATA_HEADER);
1941 // Will be filled with the root position after encoding everything.
1942 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1944 // Since encoding metadata is not in a query, and nothing is cached,
1945 // there's no need to do dep-graph tracking for any of it.
1946 let (root, mut result) = tcx.dep_graph.with_ignore(move || {
1947 let mut ecx = EncodeContext {
1950 entries_index: Index::new(tcx.hir().definitions().def_index_count()),
1951 lazy_state: LazyState::NoNode,
1952 type_shorthands: Default::default(),
1953 predicate_shorthands: Default::default(),
1954 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1955 interpret_allocs: Default::default(),
1956 interpret_allocs_inverse: Default::default(),
1959 // Encode the rustc version string in a predictable location.
1960 rustc_version().encode(&mut ecx).unwrap();
1962 // Encode all the entries and extra information in the crate,
1963 // culminating in the `CrateRoot` which points to all of it.
1964 let root = ecx.encode_crate_root();
1965 (root, ecx.opaque.into_inner())
1968 // Encode the root position.
1969 let header = METADATA_HEADER.len();
1970 let pos = root.position;
1971 result[header + 0] = (pos >> 24) as u8;
1972 result[header + 1] = (pos >> 16) as u8;
1973 result[header + 2] = (pos >> 8) as u8;
1974 result[header + 3] = (pos >> 0) as u8;
1976 EncodedMetadata { raw_data: result }
1979 pub fn get_repr_options(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1980 let ty = tcx.type_of(did);
1982 ty::Adt(ref def, _) => return def.repr,
1983 _ => bug!("{} is not an ADT", ty),