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_data_structures::indexed_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};
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<u128> = StableHasher::new();
372 adapted.name.hash(&mut hasher);
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 native libraries used
409 let native_libraries = self.encode_native_libraries();
410 let native_lib_bytes = self.position() - i;
412 let foreign_modules = self.encode_foreign_modules();
416 let source_map = self.encode_source_map();
417 let source_map_bytes = self.position() - i;
419 // Encode DefPathTable
421 let def_path_table = self.encode_def_path_table();
422 let def_path_table_bytes = self.position() - i;
424 // Encode the def IDs of impls, for coherence checking.
426 let impls = self.encode_impls();
427 let impl_bytes = self.position() - i;
429 // Encode exported symbols info.
431 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
432 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
433 let exported_symbols_bytes = self.position() - i;
439 self.encode_info_for_items();
440 let item_bytes = self.position() - i;
442 // Encode the allocation index
443 let interpret_alloc_index = {
444 let mut interpret_alloc_index = Vec::new();
446 trace!("beginning to encode alloc ids");
448 let new_n = self.interpret_allocs_inverse.len();
449 // if we have found new ids, serialize those, too
454 trace!("encoding {} further alloc ids", new_n - n);
455 for idx in n..new_n {
456 let id = self.interpret_allocs_inverse[idx];
457 let pos = self.position() as u32;
458 interpret_alloc_index.push(pos);
459 interpret::specialized_encode_alloc_id(
467 self.lazy(interpret_alloc_index)
472 let entries_index = self.entries_index.write_index(&mut self.opaque);
473 let entries_index_bytes = self.position() - i;
475 // Encode the proc macro data
477 let proc_macro_data = self.encode_proc_macros();
478 let proc_macro_data_bytes = self.position() - i;
481 let attrs = tcx.hir().krate_attrs();
482 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
483 let has_global_allocator = *tcx.sess.has_global_allocator.get();
484 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) -> Lazy<[ty::Variance]> {
566 debug!("EncodeContext::encode_variances_of({:?})", def_id);
568 self.lazy(&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(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: Lazy::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),
627 promoted_mir: self.encode_promoted_mir(def_id),
631 fn encode_enum_variant_ctor(
633 (enum_did, index): (DefId, VariantIdx),
636 let def = tcx.adt_def(enum_did);
637 let variant = &def.variants[index];
638 let def_id = variant.ctor_def_id.unwrap();
639 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
641 let data = VariantData {
642 ctor_kind: variant.ctor_kind,
643 discr: variant.discr,
644 ctor: Some(def_id.index),
645 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
646 Some(self.lazy(tcx.fn_sig(def_id)))
652 // Variant constructors have the same visibility as the parent enums, unless marked as
653 // non-exhaustive, in which case they are lowered to `pub(crate)`.
654 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
655 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
656 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
657 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
658 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
662 kind: EntryKind::Variant(self.lazy(data)),
663 visibility: self.lazy(ctor_vis),
664 span: self.lazy(tcx.def_span(def_id)),
665 attributes: Lazy::empty(),
666 children: Lazy::empty(),
667 stability: self.encode_stability(def_id),
668 deprecation: self.encode_deprecation(def_id),
670 ty: Some(self.encode_item_type(def_id)),
671 inherent_impls: Lazy::empty(),
672 variances: if variant.ctor_kind == CtorKind::Fn {
673 self.encode_variances_of(def_id)
677 generics: Some(self.encode_generics(def_id)),
678 predicates: Some(self.encode_predicates(def_id)),
679 predicates_defined_on: None,
681 mir: self.encode_optimized_mir(def_id),
682 promoted_mir: self.encode_promoted_mir(def_id),
686 fn encode_info_for_mod(
688 (id, md, attrs, vis): (hir::HirId, &hir::Mod, &[ast::Attribute], &hir::Visibility),
691 let def_id = tcx.hir().local_def_id(id);
692 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
695 reexports: match tcx.module_exports(def_id) {
696 Some(exports) => self.lazy(exports),
702 kind: EntryKind::Mod(self.lazy(data)),
703 visibility: self.lazy(ty::Visibility::from_hir(vis, id, tcx)),
704 span: self.lazy(tcx.def_span(def_id)),
705 attributes: self.encode_attributes(attrs),
706 children: self.lazy(md.item_ids.iter().map(|item_id| {
707 tcx.hir().local_def_id(item_id.id).index
709 stability: self.encode_stability(def_id),
710 deprecation: self.encode_deprecation(def_id),
713 inherent_impls: Lazy::empty(),
714 variances: Lazy::empty(),
717 predicates_defined_on: None,
726 (adt_def_id, variant_index, field_index): (DefId, VariantIdx, usize),
729 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
730 let field = &variant.fields[field_index];
732 let def_id = field.did;
733 debug!("EncodeContext::encode_field({:?})", def_id);
735 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
736 let variant_data = tcx.hir().expect_variant_data(variant_id);
739 kind: EntryKind::Field,
740 visibility: self.lazy(field.vis),
741 span: self.lazy(tcx.def_span(def_id)),
742 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
743 children: Lazy::empty(),
744 stability: self.encode_stability(def_id),
745 deprecation: self.encode_deprecation(def_id),
747 ty: Some(self.encode_item_type(def_id)),
748 inherent_impls: Lazy::empty(),
749 variances: Lazy::empty(),
750 generics: Some(self.encode_generics(def_id)),
751 predicates: Some(self.encode_predicates(def_id)),
752 predicates_defined_on: None,
759 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
760 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
762 let adt_def = tcx.adt_def(adt_def_id);
763 let variant = adt_def.non_enum_variant();
765 let data = VariantData {
766 ctor_kind: variant.ctor_kind,
767 discr: variant.discr,
768 ctor: Some(def_id.index),
769 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
770 Some(self.lazy(tcx.fn_sig(def_id)))
776 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
777 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
778 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
779 for field in &variant.fields {
780 if ctor_vis.is_at_least(field.vis, tcx) {
781 ctor_vis = field.vis;
785 // If the structure is marked as non_exhaustive then lower the visibility
786 // to within the crate.
787 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
788 ctor_vis == ty::Visibility::Public
790 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
793 let repr_options = get_repr_options(tcx, adt_def_id);
796 kind: EntryKind::Struct(self.lazy(data), repr_options),
797 visibility: self.lazy(ctor_vis),
798 span: self.lazy(tcx.def_span(def_id)),
799 attributes: Lazy::empty(),
800 children: Lazy::empty(),
801 stability: self.encode_stability(def_id),
802 deprecation: self.encode_deprecation(def_id),
804 ty: Some(self.encode_item_type(def_id)),
805 inherent_impls: Lazy::empty(),
806 variances: if variant.ctor_kind == CtorKind::Fn {
807 self.encode_variances_of(def_id)
811 generics: Some(self.encode_generics(def_id)),
812 predicates: Some(self.encode_predicates(def_id)),
813 predicates_defined_on: None,
815 mir: self.encode_optimized_mir(def_id),
816 promoted_mir: self.encode_promoted_mir(def_id),
820 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
821 debug!("EncodeContext::encode_generics({:?})", def_id);
823 self.lazy(tcx.generics_of(def_id))
826 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
827 debug!("EncodeContext::encode_predicates({:?})", def_id);
829 self.lazy(&*tcx.predicates_of(def_id))
832 fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
833 debug!("EncodeContext::encode_predicates_defined_on({:?})", def_id);
835 self.lazy(&*tcx.predicates_defined_on(def_id))
838 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
839 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
842 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
843 let ast_item = tcx.hir().expect_trait_item(hir_id);
844 let trait_item = tcx.associated_item(def_id);
846 let container = match trait_item.defaultness {
847 hir::Defaultness::Default { has_value: true } =>
848 AssocContainer::TraitWithDefault,
849 hir::Defaultness::Default { has_value: false } =>
850 AssocContainer::TraitRequired,
851 hir::Defaultness::Final =>
852 span_bug!(ast_item.span, "traits cannot have final items"),
855 let kind = match trait_item.kind {
856 ty::AssocKind::Const => {
858 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
859 self.const_qualif(0, body)
861 ConstQualif { mir: 0, ast_promotable: false }
865 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
866 let rendered_const = self.lazy(RenderedConst(rendered));
868 EntryKind::AssocConst(container, const_qualif, rendered_const)
870 ty::AssocKind::Method => {
871 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
872 let arg_names = match *m {
873 hir::TraitMethod::Required(ref names) => {
874 self.encode_fn_arg_names(names)
876 hir::TraitMethod::Provided(body) => {
877 self.encode_fn_arg_names_for_body(body)
881 constness: hir::Constness::NotConst,
883 sig: self.lazy(tcx.fn_sig(def_id)),
888 EntryKind::Method(self.lazy(MethodData {
891 has_self: trait_item.method_has_self_argument,
894 ty::AssocKind::Type => EntryKind::AssocType(container),
895 ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
900 visibility: self.lazy(trait_item.vis),
901 span: self.lazy(ast_item.span),
902 attributes: self.encode_attributes(&ast_item.attrs),
903 children: Lazy::empty(),
904 stability: self.encode_stability(def_id),
905 deprecation: self.encode_deprecation(def_id),
907 ty: match trait_item.kind {
908 ty::AssocKind::Const |
909 ty::AssocKind::Method => {
910 Some(self.encode_item_type(def_id))
912 ty::AssocKind::Type => {
913 if trait_item.defaultness.has_value() {
914 Some(self.encode_item_type(def_id))
919 ty::AssocKind::OpaqueTy => unreachable!(),
921 inherent_impls: Lazy::empty(),
922 variances: if trait_item.kind == ty::AssocKind::Method {
923 self.encode_variances_of(def_id)
927 generics: Some(self.encode_generics(def_id)),
928 predicates: Some(self.encode_predicates(def_id)),
929 predicates_defined_on: None,
931 mir: self.encode_optimized_mir(def_id),
932 promoted_mir: self.encode_promoted_mir(def_id),
936 fn metadata_output_only(&self) -> bool {
937 // MIR optimisation can be skipped when we're just interested in the metadata.
938 !self.tcx.sess.opts.output_types.should_codegen()
941 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
942 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
943 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
945 ConstQualif { mir, ast_promotable }
948 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
949 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
952 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
953 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
954 let impl_item = self.tcx.associated_item(def_id);
956 let container = match impl_item.defaultness {
957 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
958 hir::Defaultness::Final => AssocContainer::ImplFinal,
959 hir::Defaultness::Default { has_value: false } =>
960 span_bug!(ast_item.span, "impl items always have values (currently)"),
963 let kind = match impl_item.kind {
964 ty::AssocKind::Const => {
965 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
966 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
968 EntryKind::AssocConst(container,
969 self.const_qualif(mir, body_id),
970 self.encode_rendered_const_for_body(body_id))
975 ty::AssocKind::Method => {
976 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
978 constness: sig.header.constness,
979 arg_names: self.encode_fn_arg_names_for_body(body),
980 sig: self.lazy(tcx.fn_sig(def_id)),
985 EntryKind::Method(self.lazy(MethodData {
988 has_self: impl_item.method_has_self_argument,
991 ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
992 ty::AssocKind::Type => EntryKind::AssocType(container)
996 match ast_item.node {
997 hir::ImplItemKind::Const(..) => true,
998 hir::ImplItemKind::Method(ref sig, _) => {
999 let generics = self.tcx.generics_of(def_id);
1000 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
1001 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1002 !self.metadata_output_only();
1003 let is_const_fn = sig.header.constness == hir::Constness::Const;
1004 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1005 needs_inline || is_const_fn || always_encode_mir
1007 hir::ImplItemKind::OpaqueTy(..) |
1008 hir::ImplItemKind::TyAlias(..) => false,
1013 visibility: self.lazy(impl_item.vis),
1014 span: self.lazy(ast_item.span),
1015 attributes: self.encode_attributes(&ast_item.attrs),
1016 children: Lazy::empty(),
1017 stability: self.encode_stability(def_id),
1018 deprecation: self.encode_deprecation(def_id),
1020 ty: Some(self.encode_item_type(def_id)),
1021 inherent_impls: Lazy::empty(),
1022 variances: if impl_item.kind == ty::AssocKind::Method {
1023 self.encode_variances_of(def_id)
1027 generics: Some(self.encode_generics(def_id)),
1028 predicates: Some(self.encode_predicates(def_id)),
1029 predicates_defined_on: None,
1031 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
1032 promoted_mir: if mir { self.encode_promoted_mir(def_id) } else { None },
1036 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
1037 -> Lazy<[ast::Name]> {
1038 self.tcx.dep_graph.with_ignore(|| {
1039 let body = self.tcx.hir().body(body_id);
1040 self.lazy(body.arguments.iter().map(|arg| {
1041 match arg.pat.node {
1042 PatKind::Binding(_, _, ident, _) => ident.name,
1049 fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> Lazy<[ast::Name]> {
1050 self.lazy(param_names.iter().map(|ident| ident.name))
1053 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Body<'tcx>>> {
1054 debug!("EntryBuilder::encode_mir({:?})", def_id);
1055 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1056 let mir = self.tcx.optimized_mir(def_id);
1057 Some(self.lazy(mir))
1063 fn encode_promoted_mir(&mut self, def_id: DefId) ->
1064 Option<Lazy<IndexVec<mir::Promoted, mir::Body<'tcx>>>> {
1065 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1066 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1067 let promoted = self.tcx.promoted_mir(def_id);
1068 Some(self.lazy(promoted))
1074 // Encodes the inherent implementations of a structure, enumeration, or trait.
1075 fn encode_inherent_implementations(&mut self, def_id: DefId) -> Lazy<[DefIndex]> {
1076 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1077 let implementations = self.tcx.inherent_impls(def_id);
1078 if implementations.is_empty() {
1081 self.lazy(implementations.iter().map(|&def_id| {
1082 assert!(def_id.is_local());
1088 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1089 debug!("EncodeContext::encode_stability({:?})", def_id);
1090 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1093 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1094 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1095 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(depr))
1098 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1099 let body = self.tcx.hir().body(body_id);
1100 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1101 let rendered_const = &RenderedConst(rendered);
1102 self.lazy(rendered_const)
1105 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1108 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1110 let kind = match item.node {
1111 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1112 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1113 hir::ItemKind::Const(_, body_id) => {
1114 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1116 self.const_qualif(mir, body_id),
1117 self.encode_rendered_const_for_body(body_id)
1120 hir::ItemKind::Fn(_, header, .., body) => {
1122 constness: header.constness,
1123 arg_names: self.encode_fn_arg_names_for_body(body),
1124 sig: self.lazy(tcx.fn_sig(def_id)),
1127 EntryKind::Fn(self.lazy(data))
1129 hir::ItemKind::Mod(ref m) => {
1130 return self.encode_info_for_mod((item.hir_id, m, &item.attrs, &item.vis));
1132 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1133 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1134 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1135 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1136 hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(tcx, def_id)),
1137 hir::ItemKind::Struct(ref struct_def, _) => {
1138 let variant = tcx.adt_def(def_id).non_enum_variant();
1140 // Encode def_ids for each field and method
1141 // for methods, write all the stuff get_trait_method
1143 let ctor = struct_def.ctor_hir_id()
1144 .map(|ctor_hir_id| tcx.hir().local_def_id(ctor_hir_id).index);
1146 let repr_options = get_repr_options(tcx, def_id);
1148 EntryKind::Struct(self.lazy(VariantData {
1149 ctor_kind: variant.ctor_kind,
1150 discr: variant.discr,
1155 hir::ItemKind::Union(..) => {
1156 let variant = tcx.adt_def(def_id).non_enum_variant();
1157 let repr_options = get_repr_options(tcx, def_id);
1159 EntryKind::Union(self.lazy(VariantData {
1160 ctor_kind: variant.ctor_kind,
1161 discr: variant.discr,
1166 hir::ItemKind::Impl(_, polarity, defaultness, ..) => {
1167 let trait_ref = tcx.impl_trait_ref(def_id);
1168 let parent = if let Some(trait_ref) = trait_ref {
1169 let trait_def = tcx.trait_def(trait_ref.def_id);
1170 trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| {
1172 specialization_graph::Node::Impl(parent) => Some(parent),
1180 // if this is an impl of `CoerceUnsized`, create its
1181 // "unsized info", else just store None
1182 let coerce_unsized_info =
1183 trait_ref.and_then(|t| {
1184 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1185 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1191 let data = ImplData {
1194 parent_impl: parent,
1195 coerce_unsized_info,
1196 trait_ref: trait_ref.map(|trait_ref| self.lazy(trait_ref)),
1199 EntryKind::Impl(self.lazy(data))
1201 hir::ItemKind::Trait(..) => {
1202 let trait_def = tcx.trait_def(def_id);
1203 let data = TraitData {
1204 unsafety: trait_def.unsafety,
1205 paren_sugar: trait_def.paren_sugar,
1206 has_auto_impl: tcx.trait_is_auto(def_id),
1207 is_marker: trait_def.is_marker,
1208 super_predicates: self.lazy(&*tcx.super_predicates_of(def_id)),
1211 EntryKind::Trait(self.lazy(data))
1213 hir::ItemKind::TraitAlias(..) => {
1214 let data = TraitAliasData {
1215 super_predicates: self.lazy(&*tcx.super_predicates_of(def_id)),
1218 EntryKind::TraitAlias(self.lazy(data))
1220 hir::ItemKind::ExternCrate(_) |
1221 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1224 let mir = match item.node {
1225 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1226 hir::ItemKind::Fn(_, header, ..) => {
1227 let generics = tcx.generics_of(def_id);
1229 (generics.requires_monomorphization(tcx) ||
1230 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1231 !self.metadata_output_only();
1232 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1233 needs_inline || header.constness == hir::Constness::Const || always_encode_mir
1240 visibility: self.lazy(ty::Visibility::from_hir(&item.vis, item.hir_id, tcx)),
1241 span: self.lazy(item.span),
1242 attributes: self.encode_attributes(&item.attrs),
1243 children: match item.node {
1244 hir::ItemKind::ForeignMod(ref fm) => {
1247 .map(|foreign_item| tcx.hir().local_def_id(
1248 foreign_item.hir_id).index))
1250 hir::ItemKind::Enum(..) => {
1251 let def = self.tcx.adt_def(def_id);
1252 self.lazy(def.variants.iter().map(|v| {
1253 assert!(v.def_id.is_local());
1257 hir::ItemKind::Struct(..) |
1258 hir::ItemKind::Union(..) => {
1259 let def = self.tcx.adt_def(def_id);
1260 self.lazy(def.non_enum_variant().fields.iter().map(|f| {
1261 assert!(f.did.is_local());
1265 hir::ItemKind::Impl(..) |
1266 hir::ItemKind::Trait(..) => {
1267 self.lazy(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1268 assert!(def_id.is_local());
1274 stability: self.encode_stability(def_id),
1275 deprecation: self.encode_deprecation(def_id),
1277 ty: match item.node {
1278 hir::ItemKind::Static(..) |
1279 hir::ItemKind::Const(..) |
1280 hir::ItemKind::Fn(..) |
1281 hir::ItemKind::TyAlias(..) |
1282 hir::ItemKind::OpaqueTy(..) |
1283 hir::ItemKind::Enum(..) |
1284 hir::ItemKind::Struct(..) |
1285 hir::ItemKind::Union(..) |
1286 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1289 inherent_impls: self.encode_inherent_implementations(def_id),
1290 variances: match item.node {
1291 hir::ItemKind::Enum(..) |
1292 hir::ItemKind::Struct(..) |
1293 hir::ItemKind::Union(..) |
1294 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1297 generics: match item.node {
1298 hir::ItemKind::Static(..) |
1299 hir::ItemKind::Const(..) |
1300 hir::ItemKind::Fn(..) |
1301 hir::ItemKind::TyAlias(..) |
1302 hir::ItemKind::Enum(..) |
1303 hir::ItemKind::Struct(..) |
1304 hir::ItemKind::Union(..) |
1305 hir::ItemKind::Impl(..) |
1306 hir::ItemKind::OpaqueTy(..) |
1307 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1308 hir::ItemKind::TraitAlias(..) => Some(self.encode_generics(def_id)),
1311 predicates: match item.node {
1312 hir::ItemKind::Static(..) |
1313 hir::ItemKind::Const(..) |
1314 hir::ItemKind::Fn(..) |
1315 hir::ItemKind::TyAlias(..) |
1316 hir::ItemKind::Enum(..) |
1317 hir::ItemKind::Struct(..) |
1318 hir::ItemKind::Union(..) |
1319 hir::ItemKind::Impl(..) |
1320 hir::ItemKind::OpaqueTy(..) |
1321 hir::ItemKind::Trait(..) |
1322 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates(def_id)),
1326 // The only time that `predicates_defined_on` is used (on
1327 // an external item) is for traits, during chalk lowering,
1328 // so only encode it in that case as an efficiency
1329 // hack. (No reason not to expand it in the future if
1331 predicates_defined_on: match item.node {
1332 hir::ItemKind::Trait(..) |
1333 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates_defined_on(def_id)),
1334 _ => None, // not *wrong* for other kinds of items, but not needed
1337 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
1338 promoted_mir: if mir { self.encode_promoted_mir(def_id) } else { None },
1342 /// Serialize the text of exported macros
1343 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1344 use syntax::print::pprust;
1345 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1347 kind: EntryKind::MacroDef(self.lazy(MacroDef {
1348 body: pprust::tokens_to_string(macro_def.body.clone()),
1349 legacy: macro_def.legacy,
1351 visibility: self.lazy(ty::Visibility::Public),
1352 span: self.lazy(macro_def.span),
1353 attributes: self.encode_attributes(¯o_def.attrs),
1354 stability: self.encode_stability(def_id),
1355 deprecation: self.encode_deprecation(def_id),
1357 children: Lazy::empty(),
1359 inherent_impls: Lazy::empty(),
1360 variances: Lazy::empty(),
1363 predicates_defined_on: None,
1369 fn encode_info_for_generic_param(
1372 entry_kind: EntryKind<'tcx>,
1378 visibility: self.lazy(ty::Visibility::Public),
1379 span: self.lazy(tcx.def_span(def_id)),
1380 attributes: Lazy::empty(),
1381 children: Lazy::empty(),
1384 ty: if encode_type { Some(self.encode_item_type(def_id)) } else { None },
1385 inherent_impls: Lazy::empty(),
1386 variances: Lazy::empty(),
1389 predicates_defined_on: None,
1396 fn encode_info_for_ty_param(
1398 (def_id, encode_type): (DefId, bool),
1400 debug!("EncodeContext::encode_info_for_ty_param({:?})", def_id);
1401 self.encode_info_for_generic_param(def_id, EntryKind::TypeParam, encode_type)
1404 fn encode_info_for_const_param(
1408 debug!("EncodeContext::encode_info_for_const_param({:?})", def_id);
1409 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true)
1412 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1413 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1416 let tables = self.tcx.typeck_tables_of(def_id);
1417 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1418 let kind = match tables.node_type(hir_id).sty {
1419 ty::Generator(def_id, ..) => {
1420 let layout = self.tcx.generator_layout(def_id);
1421 let data = GeneratorData {
1422 layout: layout.clone(),
1424 EntryKind::Generator(self.lazy(data))
1427 ty::Closure(def_id, substs) => {
1428 let sig = substs.closure_sig(def_id, self.tcx);
1429 let data = ClosureData { sig: self.lazy(sig) };
1430 EntryKind::Closure(self.lazy(data))
1433 _ => bug!("closure that is neither generator nor closure")
1438 visibility: self.lazy(ty::Visibility::Public),
1439 span: self.lazy(tcx.def_span(def_id)),
1440 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1441 children: Lazy::empty(),
1445 ty: Some(self.encode_item_type(def_id)),
1446 inherent_impls: Lazy::empty(),
1447 variances: Lazy::empty(),
1448 generics: Some(self.encode_generics(def_id)),
1450 predicates_defined_on: None,
1452 mir: self.encode_optimized_mir(def_id),
1453 promoted_mir: self.encode_promoted_mir(def_id),
1457 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1458 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1460 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
1461 let body_id = tcx.hir().body_owned_by(id);
1462 let const_data = self.encode_rendered_const_for_body(body_id);
1463 let mir = tcx.mir_const_qualif(def_id).0;
1466 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1467 visibility: self.lazy(ty::Visibility::Public),
1468 span: self.lazy(tcx.def_span(def_id)),
1469 attributes: Lazy::empty(),
1470 children: Lazy::empty(),
1474 ty: Some(self.encode_item_type(def_id)),
1475 inherent_impls: Lazy::empty(),
1476 variances: Lazy::empty(),
1477 generics: Some(self.encode_generics(def_id)),
1478 predicates: Some(self.encode_predicates(def_id)),
1479 predicates_defined_on: None,
1481 mir: self.encode_optimized_mir(def_id),
1482 promoted_mir: self.encode_promoted_mir(def_id),
1486 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> Lazy<[ast::Attribute]> {
1490 fn encode_native_libraries(&mut self) -> Lazy<[NativeLibrary]> {
1491 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1492 self.lazy(used_libraries.iter().cloned())
1495 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1496 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1497 self.lazy(foreign_modules.iter().cloned())
1500 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1501 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
1504 Some(self.lazy(tcx.hir().krate().items.values().filter_map(|item| {
1505 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
1506 Some(item.hir_id.owner)
1516 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1517 let crates = self.tcx.crates();
1519 let mut deps = crates
1522 let dep = CrateDep {
1523 name: self.tcx.original_crate_name(cnum),
1524 hash: self.tcx.crate_hash(cnum),
1525 kind: self.tcx.dep_kind(cnum),
1526 extra_filename: self.tcx.extra_filename(cnum),
1530 .collect::<Vec<_>>();
1532 deps.sort_by_key(|&(cnum, _)| cnum);
1535 // Sanity-check the crate numbers
1536 let mut expected_cnum = 1;
1537 for &(n, _) in &deps {
1538 assert_eq!(n, CrateNum::new(expected_cnum));
1543 // We're just going to write a list of crate 'name-hash-version's, with
1544 // the assumption that they are numbered 1 to n.
1545 // FIXME (#2166): This is not nearly enough to support correct versioning
1546 // but is enough to get transitive crate dependencies working.
1547 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1550 fn encode_lib_features(&mut self) -> Lazy<[(ast::Name, Option<ast::Name>)]> {
1552 let lib_features = tcx.lib_features();
1553 self.lazy(lib_features.to_vec())
1556 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1558 let lang_items = tcx.lang_items();
1559 let lang_items = lang_items.items().iter();
1560 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1561 if let Some(def_id) = opt_def_id {
1562 if def_id.is_local() {
1563 return Some((def_id.index, i));
1570 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1572 self.lazy(&tcx.lang_items().missing)
1575 /// Encodes an index, mapping each trait to its (local) implementations.
1576 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1577 debug!("EncodeContext::encode_impls()");
1579 let mut visitor = ImplVisitor {
1581 impls: FxHashMap::default(),
1583 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1585 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1587 // Bring everything into deterministic order for hashing
1588 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1589 tcx.def_path_hash(trait_def_id)
1592 let all_impls: Vec<_> = all_impls
1594 .map(|(trait_def_id, mut impls)| {
1595 // Bring everything into deterministic order for hashing
1596 impls.sort_by_cached_key(|&def_index| {
1597 tcx.hir().definitions().def_path_hash(def_index)
1601 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1602 impls: self.lazy(&impls),
1607 self.lazy(&all_impls)
1610 // Encodes all symbols exported from this crate into the metadata.
1612 // This pass is seeded off the reachability list calculated in the
1613 // middle::reachable module but filters out items that either don't have a
1614 // symbol associated with them (they weren't translated) or if they're an FFI
1615 // definition (as that's not defined in this crate).
1616 fn encode_exported_symbols(&mut self,
1617 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)])
1618 -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1619 // The metadata symbol name is special. It should not show up in
1620 // downstream crates.
1621 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1623 self.lazy(exported_symbols
1625 .filter(|&&(ref exported_symbol, _)| {
1626 match *exported_symbol {
1627 ExportedSymbol::NoDefId(symbol_name) => {
1628 symbol_name != metadata_symbol_name
1636 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1637 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateType::Dylib) {
1639 self.lazy(arr.iter().map(|slot| {
1641 Linkage::NotLinked |
1642 Linkage::IncludedFromDylib => None,
1644 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1645 Linkage::Static => Some(LinkagePreference::RequireStatic),
1649 None => Lazy::empty(),
1653 fn encode_info_for_foreign_item(&mut self,
1654 (def_id, nitem): (DefId, &hir::ForeignItem))
1658 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1660 let kind = match nitem.node {
1661 hir::ForeignItemKind::Fn(_, ref names, _) => {
1663 constness: hir::Constness::NotConst,
1664 arg_names: self.encode_fn_arg_names(names),
1665 sig: self.lazy(tcx.fn_sig(def_id)),
1667 EntryKind::ForeignFn(self.lazy(data))
1669 hir::ForeignItemKind::Static(_, hir::MutMutable) => EntryKind::ForeignMutStatic,
1670 hir::ForeignItemKind::Static(_, hir::MutImmutable) => EntryKind::ForeignImmStatic,
1671 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1676 visibility: self.lazy(ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, tcx)),
1677 span: self.lazy(nitem.span),
1678 attributes: self.encode_attributes(&nitem.attrs),
1679 children: Lazy::empty(),
1680 stability: self.encode_stability(def_id),
1681 deprecation: self.encode_deprecation(def_id),
1683 ty: Some(self.encode_item_type(def_id)),
1684 inherent_impls: Lazy::empty(),
1685 variances: match nitem.node {
1686 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1689 generics: Some(self.encode_generics(def_id)),
1690 predicates: Some(self.encode_predicates(def_id)),
1691 predicates_defined_on: None,
1699 impl Visitor<'tcx> for EncodeContext<'tcx> {
1700 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1701 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1703 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1704 intravisit::walk_expr(self, ex);
1705 self.encode_info_for_expr(ex);
1707 fn visit_item(&mut self, item: &'tcx hir::Item) {
1708 intravisit::walk_item(self, item);
1709 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1711 hir::ItemKind::ExternCrate(_) |
1712 hir::ItemKind::Use(..) => {} // ignore these
1713 _ => self.record(def_id, EncodeContext::encode_info_for_item, (def_id, item)),
1715 self.encode_addl_info_for_item(item);
1717 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1718 intravisit::walk_foreign_item(self, ni);
1719 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1721 EncodeContext::encode_info_for_foreign_item,
1724 fn visit_variant(&mut self,
1725 v: &'tcx hir::Variant,
1726 g: &'tcx hir::Generics,
1728 intravisit::walk_variant(self, v, g, id);
1730 if let Some(ref discr) = v.disr_expr {
1731 let def_id = self.tcx.hir().local_def_id(discr.hir_id);
1732 self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id);
1735 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1736 intravisit::walk_generics(self, generics);
1737 self.encode_info_for_generics(generics);
1739 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1740 intravisit::walk_ty(self, ty);
1741 self.encode_info_for_ty(ty);
1743 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1744 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1745 self.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def);
1749 impl EncodeContext<'tcx> {
1750 fn encode_fields(&mut self, adt_def_id: DefId) {
1751 let def = self.tcx.adt_def(adt_def_id);
1752 for (variant_index, variant) in def.variants.iter_enumerated() {
1753 for (field_index, field) in variant.fields.iter().enumerate() {
1754 self.record(field.did,
1755 EncodeContext::encode_field,
1756 (adt_def_id, variant_index, field_index));
1761 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1762 for param in &generics.params {
1763 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1765 GenericParamKind::Lifetime { .. } => continue,
1766 GenericParamKind::Type { ref default, .. } => {
1769 EncodeContext::encode_info_for_ty_param,
1770 (def_id, default.is_some()),
1773 GenericParamKind::Const { .. } => {
1774 self.record(def_id, EncodeContext::encode_info_for_const_param, def_id);
1780 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1782 hir::TyKind::Array(_, ref length) => {
1783 let def_id = self.tcx.hir().local_def_id(length.hir_id);
1784 self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id);
1790 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1792 hir::ExprKind::Closure(..) => {
1793 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1794 self.record(def_id, EncodeContext::encode_info_for_closure, def_id);
1800 /// In some cases, along with the item itself, we also
1801 /// encode some sub-items. Usually we want some info from the item
1802 /// so it's easier to do that here then to wait until we would encounter
1803 /// normally in the visitor walk.
1804 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1805 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1807 hir::ItemKind::Static(..) |
1808 hir::ItemKind::Const(..) |
1809 hir::ItemKind::Fn(..) |
1810 hir::ItemKind::Mod(..) |
1811 hir::ItemKind::ForeignMod(..) |
1812 hir::ItemKind::GlobalAsm(..) |
1813 hir::ItemKind::ExternCrate(..) |
1814 hir::ItemKind::Use(..) |
1815 hir::ItemKind::TyAlias(..) |
1816 hir::ItemKind::OpaqueTy(..) |
1817 hir::ItemKind::TraitAlias(..) => {
1818 // no sub-item recording needed in these cases
1820 hir::ItemKind::Enum(..) => {
1821 self.encode_fields(def_id);
1823 let def = self.tcx.adt_def(def_id);
1824 for (i, variant) in def.variants.iter_enumerated() {
1825 self.record(variant.def_id,
1826 EncodeContext::encode_enum_variant_info,
1829 if let Some(ctor_def_id) = variant.ctor_def_id {
1830 self.record(ctor_def_id,
1831 EncodeContext::encode_enum_variant_ctor,
1836 hir::ItemKind::Struct(ref struct_def, _) => {
1837 self.encode_fields(def_id);
1839 // If the struct has a constructor, encode it.
1840 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1841 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1842 self.record(ctor_def_id,
1843 EncodeContext::encode_struct_ctor,
1844 (def_id, ctor_def_id));
1847 hir::ItemKind::Union(..) => {
1848 self.encode_fields(def_id);
1850 hir::ItemKind::Impl(..) => {
1851 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1852 self.record(trait_item_def_id,
1853 EncodeContext::encode_info_for_impl_item,
1857 hir::ItemKind::Trait(..) => {
1858 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1859 self.record(item_def_id,
1860 EncodeContext::encode_info_for_trait_item,
1868 struct ImplVisitor<'tcx> {
1870 impls: FxHashMap<DefId, Vec<DefIndex>>,
1873 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1874 fn visit_item(&mut self, item: &hir::Item) {
1875 if let hir::ItemKind::Impl(..) = item.node {
1876 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1877 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1879 .entry(trait_ref.def_id)
1881 .push(impl_id.index);
1886 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1888 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1889 // handled in `visit_item` above
1893 // NOTE(eddyb) The following comment was preserved for posterity, even
1894 // though it's no longer relevant as EBML (which uses nested & tagged
1895 // "documents") was replaced with a scheme that can't go out of bounds.
1897 // And here we run into yet another obscure archive bug: in which metadata
1898 // loaded from archives may have trailing garbage bytes. Awhile back one of
1899 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1900 // and opt) by having ebml generate an out-of-bounds panic when looking at
1903 // Upon investigation it turned out that the metadata file inside of an rlib
1904 // (and ar archive) was being corrupted. Some compilations would generate a
1905 // metadata file which would end in a few extra bytes, while other
1906 // compilations would not have these extra bytes appended to the end. These
1907 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1908 // being interpreted causing the out-of-bounds.
1910 // The root cause of why these extra bytes were appearing was never
1911 // discovered, and in the meantime the solution we're employing is to insert
1912 // the length of the metadata to the start of the metadata. Later on this
1913 // will allow us to slice the metadata to the precise length that we just
1914 // generated regardless of trailing bytes that end up in it.
1916 pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1917 let mut encoder = opaque::Encoder::new(vec![]);
1918 encoder.emit_raw_bytes(METADATA_HEADER);
1920 // Will be filled with the root position after encoding everything.
1921 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1923 // Since encoding metadata is not in a query, and nothing is cached,
1924 // there's no need to do dep-graph tracking for any of it.
1925 let (root, mut result) = tcx.dep_graph.with_ignore(move || {
1926 let mut ecx = EncodeContext {
1929 entries_index: Index::new(tcx.hir().definitions().def_index_count()),
1930 lazy_state: LazyState::NoNode,
1931 type_shorthands: Default::default(),
1932 predicate_shorthands: Default::default(),
1933 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1934 interpret_allocs: Default::default(),
1935 interpret_allocs_inverse: Default::default(),
1938 // Encode the rustc version string in a predictable location.
1939 rustc_version().encode(&mut ecx).unwrap();
1941 // Encode all the entries and extra information in the crate,
1942 // culminating in the `CrateRoot` which points to all of it.
1943 let root = ecx.encode_crate_root();
1944 (root, ecx.opaque.into_inner())
1947 // Encode the root position.
1948 let header = METADATA_HEADER.len();
1949 let pos = root.position;
1950 result[header + 0] = (pos >> 24) as u8;
1951 result[header + 1] = (pos >> 16) as u8;
1952 result[header + 2] = (pos >> 8) as u8;
1953 result[header + 3] = (pos >> 0) as u8;
1955 EncodedMetadata { raw_data: result }
1958 pub fn get_repr_options(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1959 let ty = tcx.type_of(did);
1961 ty::Adt(ref def, _) => return def.repr,
1962 _ => bug!("{} is not an ADT", ty),