1 use crate::index::Index;
4 use rustc::middle::cstore::{LinkagePreference, NativeLibrary,
5 EncodedMetadata, ForeignModule};
6 use rustc::hir::def::CtorKind;
7 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LocalDefId, LOCAL_CRATE};
8 use rustc::hir::GenericParamKind;
9 use rustc::hir::map::definitions::DefPathTable;
10 use rustc_data_structures::fingerprint::Fingerprint;
11 use rustc::middle::dependency_format::Linkage;
12 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel,
13 metadata_symbol_name};
14 use rustc::middle::lang_items;
15 use rustc::mir::{self, interpret};
16 use rustc::traits::specialization_graph;
17 use rustc::ty::{self, Ty, TyCtxt, ReprOptions, SymbolName};
18 use rustc::ty::codec::{self as ty_codec, TyEncoder};
19 use rustc::ty::layout::VariantIdx;
21 use rustc::session::config::{self, CrateType};
22 use rustc::util::nodemap::FxHashMap;
24 use rustc_data_structures::stable_hasher::StableHasher;
25 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
29 use rustc_data_structures::sync::Lrc;
33 use syntax::ext::proc_macro::is_proc_macro_attr;
34 use syntax::source_map::Spanned;
35 use syntax::symbol::{kw, sym, Ident};
36 use syntax_pos::{self, FileName, SourceFile, Span};
37 use log::{debug, trace};
39 use rustc::hir::{self, PatKind};
40 use rustc::hir::itemlikevisit::ItemLikeVisitor;
41 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
42 use rustc::hir::intravisit;
44 pub struct EncodeContext<'tcx> {
45 opaque: opaque::Encoder,
46 pub tcx: TyCtxt<'tcx>,
48 entries_index: Index<'tcx>,
50 lazy_state: LazyState,
51 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
52 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
54 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
55 interpret_allocs_inverse: Vec<interpret::AllocId>,
57 // This is used to speed up Span encoding.
58 source_file_cache: Lrc<SourceFile>,
61 macro_rules! encoder_methods {
62 ($($name:ident($ty:ty);)*) => {
63 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
64 self.opaque.$name(value)
69 impl<'tcx> Encoder for EncodeContext<'tcx> {
70 type Error = <opaque::Encoder as Encoder>::Error;
72 fn emit_unit(&mut self) -> Result<(), Self::Error> {
99 impl<'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'tcx> {
100 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
101 self.emit_lazy_distance(*lazy)
105 impl<'tcx, T> SpecializedEncoder<Lazy<[T]>> for EncodeContext<'tcx> {
106 fn specialized_encode(&mut self, lazy: &Lazy<[T]>) -> Result<(), Self::Error> {
107 self.emit_usize(lazy.meta)?;
111 self.emit_lazy_distance(*lazy)
115 impl<'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'tcx> {
117 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
118 self.emit_u32(cnum.as_u32())
122 impl<'tcx> SpecializedEncoder<DefId> for EncodeContext<'tcx> {
124 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
135 impl<'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'tcx> {
137 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
138 self.emit_u32(def_index.as_u32())
142 impl<'tcx> SpecializedEncoder<Span> for EncodeContext<'tcx> {
143 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
145 return TAG_INVALID_SPAN.encode(self)
148 let span = span.data();
150 // The Span infrastructure should make sure that this invariant holds:
151 debug_assert!(span.lo <= span.hi);
153 if !self.source_file_cache.contains(span.lo) {
154 let source_map = self.tcx.sess.source_map();
155 let source_file_index = source_map.lookup_source_file_idx(span.lo);
156 self.source_file_cache = source_map.files()[source_file_index].clone();
159 if !self.source_file_cache.contains(span.hi) {
160 // Unfortunately, macro expansion still sometimes generates Spans
161 // that malformed in this way.
162 return TAG_INVALID_SPAN.encode(self)
165 TAG_VALID_SPAN.encode(self)?;
166 span.lo.encode(self)?;
168 // Encode length which is usually less than span.hi and profits more
169 // from the variable-length integer encoding that we use.
170 let len = span.hi - span.lo;
173 // Don't encode the expansion context.
177 impl SpecializedEncoder<Ident> for EncodeContext<'tcx> {
178 fn specialized_encode(&mut self, ident: &Ident) -> Result<(), Self::Error> {
179 // FIXME(jseyfried): intercrate hygiene
180 ident.name.encode(self)
184 impl<'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'tcx> {
186 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
187 self.specialized_encode(&def_id.to_def_id())
191 impl<'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'tcx> {
192 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
193 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
197 impl<'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'tcx> {
198 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
199 use std::collections::hash_map::Entry;
200 let index = match self.interpret_allocs.entry(*alloc_id) {
201 Entry::Occupied(e) => *e.get(),
202 Entry::Vacant(e) => {
203 let idx = self.interpret_allocs_inverse.len();
204 self.interpret_allocs_inverse.push(*alloc_id);
214 impl<'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'tcx> {
215 fn specialized_encode(&mut self,
216 predicates: &ty::GenericPredicates<'tcx>)
217 -> Result<(), Self::Error> {
218 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
222 impl<'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'tcx> {
223 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
224 f.encode_opaque(&mut self.opaque)
228 impl<'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'tcx> {
229 fn specialized_encode(&mut self,
230 _: &mir::ClearCrossCrate<T>)
231 -> Result<(), Self::Error> {
236 impl<'tcx> TyEncoder for EncodeContext<'tcx> {
237 fn position(&self) -> usize {
238 self.opaque.position()
242 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
243 trait EncodeContentsForLazy<T: ?Sized + LazyMeta> {
244 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> T::Meta;
247 impl<T: Encodable> EncodeContentsForLazy<T> for &T {
248 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
249 self.encode(ecx).unwrap()
253 impl<T: Encodable> EncodeContentsForLazy<T> for T {
254 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
255 self.encode(ecx).unwrap()
259 impl<I, T> EncodeContentsForLazy<[T]> for I
260 where I: IntoIterator,
261 I::Item: EncodeContentsForLazy<T>,
263 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> usize {
264 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
268 impl<'tcx> EncodeContext<'tcx> {
269 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
272 ) -> Result<(), <Self as Encoder>::Error> {
273 let min_end = lazy.position + T::min_size(lazy.meta);
274 let distance = match self.lazy_state {
275 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
276 LazyState::NodeStart(start) => {
277 assert!(min_end <= start);
280 LazyState::Previous(last_min_end) => {
282 last_min_end <= lazy.position,
283 "make sure that the calls to `lazy*` \
284 are in the same order as the metadata fields",
286 lazy.position - last_min_end
289 self.lazy_state = LazyState::Previous(min_end);
290 self.emit_usize(distance)
293 fn lazy<T: ?Sized + LazyMeta>(
295 value: impl EncodeContentsForLazy<T>,
297 let pos = self.position();
299 assert_eq!(self.lazy_state, LazyState::NoNode);
300 self.lazy_state = LazyState::NodeStart(pos);
301 let meta = value.encode_contents_for_lazy(self);
302 self.lazy_state = LazyState::NoNode;
304 assert!(pos + <T>::min_size(meta) <= self.position());
306 Lazy::from_position_and_meta(pos, meta)
309 /// Emit the data for a `DefId` to the metadata. The function to
310 /// emit the data is `op`, and it will be given `data` as
311 /// arguments. This `record` function will call `op` to generate
312 /// the `Entry` (which may point to other encoded information)
313 /// and will then record the `Lazy<Entry>` for use in the index.
314 // FIXME(eddyb) remove this.
315 pub fn record<DATA>(&mut self,
317 op: impl FnOnce(&mut Self, DATA) -> Entry<'tcx>,
320 assert!(id.is_local());
322 let entry = op(self, data);
323 let entry = self.lazy(entry);
324 self.entries_index.record(id, entry);
327 fn encode_info_for_items(&mut self) {
328 let krate = self.tcx.hir().krate();
329 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public };
330 self.record(DefId::local(CRATE_DEF_INDEX),
331 EncodeContext::encode_info_for_mod,
332 (hir::CRATE_HIR_ID, &krate.module, &krate.attrs, &vis));
333 krate.visit_all_item_likes(&mut self.as_deep_visitor());
334 for macro_def in &krate.exported_macros {
335 self.visit_macro_def(macro_def);
339 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
340 let definitions = self.tcx.hir().definitions();
341 self.lazy(definitions.def_path_table())
344 fn encode_source_map(&mut self) -> Lazy<[syntax_pos::SourceFile]> {
345 let source_map = self.tcx.sess.source_map();
346 let all_source_files = source_map.files();
348 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
350 let adapted = all_source_files.iter()
351 .filter(|source_file| {
352 // No need to re-export imported source_files, as any downstream
353 // crate will import them from their original source.
354 !source_file.is_imported()
357 match source_file.name {
358 // This path of this SourceFile has been modified by
359 // path-remapping, so we use it verbatim (and avoid
360 // cloning the whole map in the process).
361 _ if source_file.name_was_remapped => source_file.clone(),
363 // Otherwise expand all paths to absolute paths because
364 // any relative paths are potentially relative to a
366 FileName::Real(ref name) => {
367 let mut adapted = (**source_file).clone();
368 adapted.name = Path::new(&working_dir).join(name).into();
369 adapted.name_hash = {
370 let mut hasher: StableHasher<u128> = StableHasher::new();
371 adapted.name.hash(&mut hasher);
377 // expanded code, not from a file
378 _ => source_file.clone(),
381 .collect::<Vec<_>>();
383 self.lazy(adapted.iter().map(|rc| &**rc))
386 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
387 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
389 let mut i = self.position();
391 let crate_deps = self.encode_crate_deps();
392 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
393 let dep_bytes = self.position() - i;
395 // Encode the lib features.
397 let lib_features = self.encode_lib_features();
398 let lib_feature_bytes = self.position() - i;
400 // Encode the language items.
402 let lang_items = self.encode_lang_items();
403 let lang_items_missing = self.encode_lang_items_missing();
404 let lang_item_bytes = self.position() - i;
406 // Encode the native libraries used
408 let native_libraries = self.encode_native_libraries();
409 let native_lib_bytes = self.position() - i;
411 let foreign_modules = self.encode_foreign_modules();
415 let source_map = self.encode_source_map();
416 let source_map_bytes = self.position() - i;
418 // Encode DefPathTable
420 let def_path_table = self.encode_def_path_table();
421 let def_path_table_bytes = self.position() - i;
423 // Encode the def IDs of impls, for coherence checking.
425 let impls = self.encode_impls();
426 let impl_bytes = self.position() - i;
428 // Encode exported symbols info.
430 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
431 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
432 let exported_symbols_bytes = self.position() - i;
438 self.encode_info_for_items();
439 let item_bytes = self.position() - i;
441 // Encode the allocation index
442 let interpret_alloc_index = {
443 let mut interpret_alloc_index = Vec::new();
445 trace!("beginning to encode alloc ids");
447 let new_n = self.interpret_allocs_inverse.len();
448 // if we have found new ids, serialize those, too
453 trace!("encoding {} further alloc ids", new_n - n);
454 for idx in n..new_n {
455 let id = self.interpret_allocs_inverse[idx];
456 let pos = self.position() as u32;
457 interpret_alloc_index.push(pos);
458 interpret::specialized_encode_alloc_id(
466 self.lazy(interpret_alloc_index)
471 let entries_index = self.entries_index.write_index(&mut self.opaque);
472 let entries_index_bytes = self.position() - i;
474 // Encode the proc macro data
476 let proc_macro_data = self.encode_proc_macros();
477 let proc_macro_data_bytes = self.position() - i;
480 let attrs = tcx.hir().krate_attrs();
481 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
482 let has_global_allocator = *tcx.sess.has_global_allocator.get();
483 let has_panic_handler = *tcx.sess.has_panic_handler.try_get().unwrap_or(&false);
485 let root = self.lazy(CrateRoot {
486 name: tcx.crate_name(LOCAL_CRATE),
487 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
488 triple: tcx.sess.opts.target_triple.clone(),
489 hash: tcx.crate_hash(LOCAL_CRATE),
490 disambiguator: tcx.sess.local_crate_disambiguator(),
491 panic_strategy: tcx.sess.panic_strategy(),
492 edition: tcx.sess.edition(),
493 has_global_allocator: has_global_allocator,
494 has_panic_handler: has_panic_handler,
495 has_default_lib_allocator: has_default_lib_allocator,
496 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
497 proc_macro_decls_static: if is_proc_macro {
498 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
504 proc_macro_stability: if is_proc_macro {
505 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).map(|stab| stab.clone())
509 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
510 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
511 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
512 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
513 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
514 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
515 sanitizer_runtime: attr::contains_name(&attrs, sym::sanitizer_runtime),
516 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
519 dylib_dependency_formats,
529 interpret_alloc_index,
533 let total_bytes = self.position();
535 if self.tcx.sess.meta_stats() {
536 let mut zero_bytes = 0;
537 for e in self.opaque.data.iter() {
543 println!("metadata stats:");
544 println!(" dep bytes: {}", dep_bytes);
545 println!(" lib feature bytes: {}", lib_feature_bytes);
546 println!(" lang item bytes: {}", lang_item_bytes);
547 println!(" native bytes: {}", native_lib_bytes);
548 println!(" source_map bytes: {}", source_map_bytes);
549 println!(" impl bytes: {}", impl_bytes);
550 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
551 println!(" def-path table bytes: {}", def_path_table_bytes);
552 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
553 println!(" item bytes: {}", item_bytes);
554 println!(" entries index bytes: {}", entries_index_bytes);
555 println!(" zero bytes: {}", zero_bytes);
556 println!(" total bytes: {}", total_bytes);
563 impl EncodeContext<'tcx> {
564 fn encode_variances_of(&mut self, def_id: DefId) -> Lazy<[ty::Variance]> {
565 debug!("EncodeContext::encode_variances_of({:?})", def_id);
567 self.lazy(&tcx.variances_of(def_id)[..])
570 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
572 let ty = tcx.type_of(def_id);
573 debug!("EncodeContext::encode_item_type({:?}) => {:?}", def_id, ty);
577 fn encode_enum_variant_info(
579 (enum_did, index): (DefId, VariantIdx),
582 let def = tcx.adt_def(enum_did);
583 let variant = &def.variants[index];
584 let def_id = variant.def_id;
585 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
587 let data = VariantData {
588 ctor_kind: variant.ctor_kind,
589 discr: variant.discr,
590 // FIXME(eddyb) deduplicate these with `encode_enum_variant_ctor`.
591 ctor: variant.ctor_def_id.map(|did| did.index),
592 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
593 variant.ctor_def_id.map(|ctor_def_id| self.lazy(&tcx.fn_sig(ctor_def_id)))
599 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
600 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
603 kind: EntryKind::Variant(self.lazy(data)),
604 visibility: self.lazy(ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
605 span: self.lazy(tcx.def_span(def_id)),
606 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
607 children: self.lazy(variant.fields.iter().map(|f| {
608 assert!(f.did.is_local());
611 stability: self.encode_stability(def_id),
612 deprecation: self.encode_deprecation(def_id),
614 ty: Some(self.encode_item_type(def_id)),
615 inherent_impls: Lazy::empty(),
616 variances: if variant.ctor_kind == CtorKind::Fn {
617 self.encode_variances_of(def_id)
621 generics: Some(self.encode_generics(def_id)),
622 predicates: Some(self.encode_predicates(def_id)),
623 predicates_defined_on: None,
625 mir: self.encode_optimized_mir(def_id),
629 fn encode_enum_variant_ctor(
631 (enum_did, index): (DefId, VariantIdx),
634 let def = tcx.adt_def(enum_did);
635 let variant = &def.variants[index];
636 let def_id = variant.ctor_def_id.unwrap();
637 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
639 let data = VariantData {
640 ctor_kind: variant.ctor_kind,
641 discr: variant.discr,
642 ctor: Some(def_id.index),
643 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
644 Some(self.lazy(tcx.fn_sig(def_id)))
650 // Variant constructors have the same visibility as the parent enums, unless marked as
651 // non-exhaustive, in which case they are lowered to `pub(crate)`.
652 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
653 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
654 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
655 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
656 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
660 kind: EntryKind::Variant(self.lazy(data)),
661 visibility: self.lazy(ctor_vis),
662 span: self.lazy(tcx.def_span(def_id)),
663 attributes: Lazy::empty(),
664 children: Lazy::empty(),
665 stability: self.encode_stability(def_id),
666 deprecation: self.encode_deprecation(def_id),
668 ty: Some(self.encode_item_type(def_id)),
669 inherent_impls: Lazy::empty(),
670 variances: if variant.ctor_kind == CtorKind::Fn {
671 self.encode_variances_of(def_id)
675 generics: Some(self.encode_generics(def_id)),
676 predicates: Some(self.encode_predicates(def_id)),
677 predicates_defined_on: None,
679 mir: self.encode_optimized_mir(def_id),
683 fn encode_info_for_mod(
685 (id, md, attrs, vis): (hir::HirId, &hir::Mod, &[ast::Attribute], &hir::Visibility),
688 let def_id = tcx.hir().local_def_id(id);
689 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
692 reexports: match tcx.module_exports(def_id) {
693 Some(exports) => self.lazy(exports),
699 kind: EntryKind::Mod(self.lazy(data)),
700 visibility: self.lazy(ty::Visibility::from_hir(vis, id, tcx)),
701 span: self.lazy(tcx.def_span(def_id)),
702 attributes: self.encode_attributes(attrs),
703 children: self.lazy(md.item_ids.iter().map(|item_id| {
704 tcx.hir().local_def_id(item_id.id).index
706 stability: self.encode_stability(def_id),
707 deprecation: self.encode_deprecation(def_id),
710 inherent_impls: Lazy::empty(),
711 variances: Lazy::empty(),
714 predicates_defined_on: None,
722 (adt_def_id, variant_index, field_index): (DefId, VariantIdx, usize),
725 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
726 let field = &variant.fields[field_index];
728 let def_id = field.did;
729 debug!("EncodeContext::encode_field({:?})", def_id);
731 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
732 let variant_data = tcx.hir().expect_variant_data(variant_id);
735 kind: EntryKind::Field,
736 visibility: self.lazy(field.vis),
737 span: self.lazy(tcx.def_span(def_id)),
738 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
739 children: Lazy::empty(),
740 stability: self.encode_stability(def_id),
741 deprecation: self.encode_deprecation(def_id),
743 ty: Some(self.encode_item_type(def_id)),
744 inherent_impls: Lazy::empty(),
745 variances: Lazy::empty(),
746 generics: Some(self.encode_generics(def_id)),
747 predicates: Some(self.encode_predicates(def_id)),
748 predicates_defined_on: None,
754 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
755 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
757 let adt_def = tcx.adt_def(adt_def_id);
758 let variant = adt_def.non_enum_variant();
760 let data = VariantData {
761 ctor_kind: variant.ctor_kind,
762 discr: variant.discr,
763 ctor: Some(def_id.index),
764 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
765 Some(self.lazy(tcx.fn_sig(def_id)))
771 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
772 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
773 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
774 for field in &variant.fields {
775 if ctor_vis.is_at_least(field.vis, tcx) {
776 ctor_vis = field.vis;
780 // If the structure is marked as non_exhaustive then lower the visibility
781 // to within the crate.
782 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
783 ctor_vis == ty::Visibility::Public
785 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
788 let repr_options = get_repr_options(tcx, adt_def_id);
791 kind: EntryKind::Struct(self.lazy(data), repr_options),
792 visibility: self.lazy(ctor_vis),
793 span: self.lazy(tcx.def_span(def_id)),
794 attributes: Lazy::empty(),
795 children: Lazy::empty(),
796 stability: self.encode_stability(def_id),
797 deprecation: self.encode_deprecation(def_id),
799 ty: Some(self.encode_item_type(def_id)),
800 inherent_impls: Lazy::empty(),
801 variances: if variant.ctor_kind == CtorKind::Fn {
802 self.encode_variances_of(def_id)
806 generics: Some(self.encode_generics(def_id)),
807 predicates: Some(self.encode_predicates(def_id)),
808 predicates_defined_on: None,
810 mir: self.encode_optimized_mir(def_id),
814 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
815 debug!("EncodeContext::encode_generics({:?})", def_id);
817 self.lazy(tcx.generics_of(def_id))
820 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
821 debug!("EncodeContext::encode_predicates({:?})", def_id);
823 self.lazy(&*tcx.predicates_of(def_id))
826 fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
827 debug!("EncodeContext::encode_predicates_defined_on({:?})", def_id);
829 self.lazy(&*tcx.predicates_defined_on(def_id))
832 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
833 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
836 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
837 let ast_item = tcx.hir().expect_trait_item(hir_id);
838 let trait_item = tcx.associated_item(def_id);
840 let container = match trait_item.defaultness {
841 hir::Defaultness::Default { has_value: true } =>
842 AssocContainer::TraitWithDefault,
843 hir::Defaultness::Default { has_value: false } =>
844 AssocContainer::TraitRequired,
845 hir::Defaultness::Final =>
846 span_bug!(ast_item.span, "traits cannot have final items"),
849 let kind = match trait_item.kind {
850 ty::AssocKind::Const => {
852 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
853 self.const_qualif(0, body)
855 ConstQualif { mir: 0, ast_promotable: false }
859 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
860 let rendered_const = self.lazy(RenderedConst(rendered));
862 EntryKind::AssocConst(container, const_qualif, rendered_const)
864 ty::AssocKind::Method => {
865 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
866 let arg_names = match *m {
867 hir::TraitMethod::Required(ref names) => {
868 self.encode_fn_arg_names(names)
870 hir::TraitMethod::Provided(body) => {
871 self.encode_fn_arg_names_for_body(body)
875 constness: hir::Constness::NotConst,
877 sig: self.lazy(tcx.fn_sig(def_id)),
882 EntryKind::Method(self.lazy(MethodData {
885 has_self: trait_item.method_has_self_argument,
888 ty::AssocKind::Type => EntryKind::AssocType(container),
889 ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
894 visibility: self.lazy(trait_item.vis),
895 span: self.lazy(ast_item.span),
896 attributes: self.encode_attributes(&ast_item.attrs),
897 children: Lazy::empty(),
898 stability: self.encode_stability(def_id),
899 deprecation: self.encode_deprecation(def_id),
901 ty: match trait_item.kind {
902 ty::AssocKind::Const |
903 ty::AssocKind::Method => {
904 Some(self.encode_item_type(def_id))
906 ty::AssocKind::Type => {
907 if trait_item.defaultness.has_value() {
908 Some(self.encode_item_type(def_id))
913 ty::AssocKind::OpaqueTy => unreachable!(),
915 inherent_impls: Lazy::empty(),
916 variances: if trait_item.kind == ty::AssocKind::Method {
917 self.encode_variances_of(def_id)
921 generics: Some(self.encode_generics(def_id)),
922 predicates: Some(self.encode_predicates(def_id)),
923 predicates_defined_on: None,
925 mir: self.encode_optimized_mir(def_id),
929 fn metadata_output_only(&self) -> bool {
930 // MIR optimisation can be skipped when we're just interested in the metadata.
931 !self.tcx.sess.opts.output_types.should_codegen()
934 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
935 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
936 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
938 ConstQualif { mir, ast_promotable }
941 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
942 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
945 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
946 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
947 let impl_item = self.tcx.associated_item(def_id);
949 let container = match impl_item.defaultness {
950 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
951 hir::Defaultness::Final => AssocContainer::ImplFinal,
952 hir::Defaultness::Default { has_value: false } =>
953 span_bug!(ast_item.span, "impl items always have values (currently)"),
956 let kind = match impl_item.kind {
957 ty::AssocKind::Const => {
958 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
959 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
961 EntryKind::AssocConst(container,
962 self.const_qualif(mir, body_id),
963 self.encode_rendered_const_for_body(body_id))
968 ty::AssocKind::Method => {
969 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
971 constness: sig.header.constness,
972 arg_names: self.encode_fn_arg_names_for_body(body),
973 sig: self.lazy(tcx.fn_sig(def_id)),
978 EntryKind::Method(self.lazy(MethodData {
981 has_self: impl_item.method_has_self_argument,
984 ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
985 ty::AssocKind::Type => EntryKind::AssocType(container)
989 match ast_item.node {
990 hir::ImplItemKind::Const(..) => true,
991 hir::ImplItemKind::Method(ref sig, _) => {
992 let generics = self.tcx.generics_of(def_id);
993 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
994 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
995 !self.metadata_output_only();
996 let is_const_fn = sig.header.constness == hir::Constness::Const;
997 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
998 needs_inline || is_const_fn || always_encode_mir
1000 hir::ImplItemKind::OpaqueTy(..) |
1001 hir::ImplItemKind::TyAlias(..) => false,
1006 visibility: self.lazy(impl_item.vis),
1007 span: self.lazy(ast_item.span),
1008 attributes: self.encode_attributes(&ast_item.attrs),
1009 children: Lazy::empty(),
1010 stability: self.encode_stability(def_id),
1011 deprecation: self.encode_deprecation(def_id),
1013 ty: Some(self.encode_item_type(def_id)),
1014 inherent_impls: Lazy::empty(),
1015 variances: if impl_item.kind == ty::AssocKind::Method {
1016 self.encode_variances_of(def_id)
1020 generics: Some(self.encode_generics(def_id)),
1021 predicates: Some(self.encode_predicates(def_id)),
1022 predicates_defined_on: None,
1024 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
1028 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
1029 -> Lazy<[ast::Name]> {
1030 self.tcx.dep_graph.with_ignore(|| {
1031 let body = self.tcx.hir().body(body_id);
1032 self.lazy(body.arguments.iter().map(|arg| {
1033 match arg.pat.node {
1034 PatKind::Binding(_, _, ident, _) => ident.name,
1041 fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> Lazy<[ast::Name]> {
1042 self.lazy(param_names.iter().map(|ident| ident.name))
1045 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Body<'tcx>>> {
1046 debug!("EntryBuilder::encode_mir({:?})", def_id);
1047 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1048 let mir = self.tcx.optimized_mir(def_id);
1049 Some(self.lazy(mir))
1055 // Encodes the inherent implementations of a structure, enumeration, or trait.
1056 fn encode_inherent_implementations(&mut self, def_id: DefId) -> Lazy<[DefIndex]> {
1057 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1058 let implementations = self.tcx.inherent_impls(def_id);
1059 if implementations.is_empty() {
1062 self.lazy(implementations.iter().map(|&def_id| {
1063 assert!(def_id.is_local());
1069 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1070 debug!("EncodeContext::encode_stability({:?})", def_id);
1071 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1074 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1075 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1076 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(depr))
1079 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1080 let body = self.tcx.hir().body(body_id);
1081 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1082 let rendered_const = &RenderedConst(rendered);
1083 self.lazy(rendered_const)
1086 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1089 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1091 let kind = match item.node {
1092 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1093 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1094 hir::ItemKind::Const(_, body_id) => {
1095 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1097 self.const_qualif(mir, body_id),
1098 self.encode_rendered_const_for_body(body_id)
1101 hir::ItemKind::Fn(_, header, .., body) => {
1103 constness: header.constness,
1104 arg_names: self.encode_fn_arg_names_for_body(body),
1105 sig: self.lazy(tcx.fn_sig(def_id)),
1108 EntryKind::Fn(self.lazy(data))
1110 hir::ItemKind::Mod(ref m) => {
1111 return self.encode_info_for_mod((item.hir_id, m, &item.attrs, &item.vis));
1113 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1114 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1115 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1116 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1117 hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(tcx, def_id)),
1118 hir::ItemKind::Struct(ref struct_def, _) => {
1119 let variant = tcx.adt_def(def_id).non_enum_variant();
1121 // Encode def_ids for each field and method
1122 // for methods, write all the stuff get_trait_method
1124 let ctor = struct_def.ctor_hir_id()
1125 .map(|ctor_hir_id| tcx.hir().local_def_id(ctor_hir_id).index);
1127 let repr_options = get_repr_options(tcx, def_id);
1129 EntryKind::Struct(self.lazy(VariantData {
1130 ctor_kind: variant.ctor_kind,
1131 discr: variant.discr,
1136 hir::ItemKind::Union(..) => {
1137 let variant = tcx.adt_def(def_id).non_enum_variant();
1138 let repr_options = get_repr_options(tcx, def_id);
1140 EntryKind::Union(self.lazy(VariantData {
1141 ctor_kind: variant.ctor_kind,
1142 discr: variant.discr,
1147 hir::ItemKind::Impl(_, polarity, defaultness, ..) => {
1148 let trait_ref = tcx.impl_trait_ref(def_id);
1149 let parent = if let Some(trait_ref) = trait_ref {
1150 let trait_def = tcx.trait_def(trait_ref.def_id);
1151 trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| {
1153 specialization_graph::Node::Impl(parent) => Some(parent),
1161 // if this is an impl of `CoerceUnsized`, create its
1162 // "unsized info", else just store None
1163 let coerce_unsized_info =
1164 trait_ref.and_then(|t| {
1165 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1166 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1172 let data = ImplData {
1175 parent_impl: parent,
1176 coerce_unsized_info,
1177 trait_ref: trait_ref.map(|trait_ref| self.lazy(trait_ref)),
1180 EntryKind::Impl(self.lazy(data))
1182 hir::ItemKind::Trait(..) => {
1183 let trait_def = tcx.trait_def(def_id);
1184 let data = TraitData {
1185 unsafety: trait_def.unsafety,
1186 paren_sugar: trait_def.paren_sugar,
1187 has_auto_impl: tcx.trait_is_auto(def_id),
1188 is_marker: trait_def.is_marker,
1189 super_predicates: self.lazy(&*tcx.super_predicates_of(def_id)),
1192 EntryKind::Trait(self.lazy(data))
1194 hir::ItemKind::TraitAlias(..) => {
1195 let data = TraitAliasData {
1196 super_predicates: self.lazy(&*tcx.super_predicates_of(def_id)),
1199 EntryKind::TraitAlias(self.lazy(data))
1201 hir::ItemKind::ExternCrate(_) |
1202 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1207 visibility: self.lazy(ty::Visibility::from_hir(&item.vis, item.hir_id, tcx)),
1208 span: self.lazy(item.span),
1209 attributes: self.encode_attributes(&item.attrs),
1210 children: match item.node {
1211 hir::ItemKind::ForeignMod(ref fm) => {
1214 .map(|foreign_item| tcx.hir().local_def_id(
1215 foreign_item.hir_id).index))
1217 hir::ItemKind::Enum(..) => {
1218 let def = self.tcx.adt_def(def_id);
1219 self.lazy(def.variants.iter().map(|v| {
1220 assert!(v.def_id.is_local());
1224 hir::ItemKind::Struct(..) |
1225 hir::ItemKind::Union(..) => {
1226 let def = self.tcx.adt_def(def_id);
1227 self.lazy(def.non_enum_variant().fields.iter().map(|f| {
1228 assert!(f.did.is_local());
1232 hir::ItemKind::Impl(..) |
1233 hir::ItemKind::Trait(..) => {
1234 self.lazy(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1235 assert!(def_id.is_local());
1241 stability: self.encode_stability(def_id),
1242 deprecation: self.encode_deprecation(def_id),
1244 ty: match item.node {
1245 hir::ItemKind::Static(..) |
1246 hir::ItemKind::Const(..) |
1247 hir::ItemKind::Fn(..) |
1248 hir::ItemKind::TyAlias(..) |
1249 hir::ItemKind::OpaqueTy(..) |
1250 hir::ItemKind::Enum(..) |
1251 hir::ItemKind::Struct(..) |
1252 hir::ItemKind::Union(..) |
1253 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1256 inherent_impls: self.encode_inherent_implementations(def_id),
1257 variances: match item.node {
1258 hir::ItemKind::Enum(..) |
1259 hir::ItemKind::Struct(..) |
1260 hir::ItemKind::Union(..) |
1261 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1264 generics: match item.node {
1265 hir::ItemKind::Static(..) |
1266 hir::ItemKind::Const(..) |
1267 hir::ItemKind::Fn(..) |
1268 hir::ItemKind::TyAlias(..) |
1269 hir::ItemKind::Enum(..) |
1270 hir::ItemKind::Struct(..) |
1271 hir::ItemKind::Union(..) |
1272 hir::ItemKind::Impl(..) |
1273 hir::ItemKind::OpaqueTy(..) |
1274 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1275 hir::ItemKind::TraitAlias(..) => Some(self.encode_generics(def_id)),
1278 predicates: match item.node {
1279 hir::ItemKind::Static(..) |
1280 hir::ItemKind::Const(..) |
1281 hir::ItemKind::Fn(..) |
1282 hir::ItemKind::TyAlias(..) |
1283 hir::ItemKind::Enum(..) |
1284 hir::ItemKind::Struct(..) |
1285 hir::ItemKind::Union(..) |
1286 hir::ItemKind::Impl(..) |
1287 hir::ItemKind::OpaqueTy(..) |
1288 hir::ItemKind::Trait(..) |
1289 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates(def_id)),
1293 // The only time that `predicates_defined_on` is used (on
1294 // an external item) is for traits, during chalk lowering,
1295 // so only encode it in that case as an efficiency
1296 // hack. (No reason not to expand it in the future if
1298 predicates_defined_on: match item.node {
1299 hir::ItemKind::Trait(..) |
1300 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates_defined_on(def_id)),
1301 _ => None, // not *wrong* for other kinds of items, but not needed
1304 mir: match item.node {
1305 hir::ItemKind::Static(..) => {
1306 self.encode_optimized_mir(def_id)
1308 hir::ItemKind::Const(..) => self.encode_optimized_mir(def_id),
1309 hir::ItemKind::Fn(_, header, ..) => {
1310 let generics = tcx.generics_of(def_id);
1312 (generics.requires_monomorphization(tcx) ||
1313 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1314 !self.metadata_output_only();
1315 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1317 || header.constness == hir::Constness::Const
1318 || always_encode_mir
1320 self.encode_optimized_mir(def_id)
1330 /// Serialize the text of exported macros
1331 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1332 use syntax::print::pprust;
1333 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1335 kind: EntryKind::MacroDef(self.lazy(MacroDef {
1336 body: pprust::tokens_to_string(macro_def.body.clone()),
1337 legacy: macro_def.legacy,
1339 visibility: self.lazy(ty::Visibility::Public),
1340 span: self.lazy(macro_def.span),
1341 attributes: self.encode_attributes(¯o_def.attrs),
1342 stability: self.encode_stability(def_id),
1343 deprecation: self.encode_deprecation(def_id),
1345 children: Lazy::empty(),
1347 inherent_impls: Lazy::empty(),
1348 variances: Lazy::empty(),
1351 predicates_defined_on: None,
1356 fn encode_info_for_generic_param(
1359 entry_kind: EntryKind<'tcx>,
1365 visibility: self.lazy(ty::Visibility::Public),
1366 span: self.lazy(tcx.def_span(def_id)),
1367 attributes: Lazy::empty(),
1368 children: Lazy::empty(),
1371 ty: if encode_type { Some(self.encode_item_type(def_id)) } else { None },
1372 inherent_impls: Lazy::empty(),
1373 variances: Lazy::empty(),
1376 predicates_defined_on: None,
1382 fn encode_info_for_ty_param(
1384 (def_id, encode_type): (DefId, bool),
1386 debug!("EncodeContext::encode_info_for_ty_param({:?})", def_id);
1387 self.encode_info_for_generic_param(def_id, EntryKind::TypeParam, encode_type)
1390 fn encode_info_for_const_param(
1394 debug!("EncodeContext::encode_info_for_const_param({:?})", def_id);
1395 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true)
1398 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1399 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1402 let tables = self.tcx.typeck_tables_of(def_id);
1403 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1404 let kind = match tables.node_type(hir_id).sty {
1405 ty::Generator(def_id, ..) => {
1406 let layout = self.tcx.generator_layout(def_id);
1407 let data = GeneratorData {
1408 layout: layout.clone(),
1410 EntryKind::Generator(self.lazy(data))
1413 ty::Closure(def_id, substs) => {
1414 let sig = substs.closure_sig(def_id, self.tcx);
1415 let data = ClosureData { sig: self.lazy(sig) };
1416 EntryKind::Closure(self.lazy(data))
1419 _ => bug!("closure that is neither generator nor closure")
1424 visibility: self.lazy(ty::Visibility::Public),
1425 span: self.lazy(tcx.def_span(def_id)),
1426 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1427 children: Lazy::empty(),
1431 ty: Some(self.encode_item_type(def_id)),
1432 inherent_impls: Lazy::empty(),
1433 variances: Lazy::empty(),
1434 generics: Some(self.encode_generics(def_id)),
1436 predicates_defined_on: None,
1438 mir: self.encode_optimized_mir(def_id),
1442 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1443 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1445 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
1446 let body_id = tcx.hir().body_owned_by(id);
1447 let const_data = self.encode_rendered_const_for_body(body_id);
1448 let mir = tcx.mir_const_qualif(def_id).0;
1451 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1452 visibility: self.lazy(ty::Visibility::Public),
1453 span: self.lazy(tcx.def_span(def_id)),
1454 attributes: Lazy::empty(),
1455 children: Lazy::empty(),
1459 ty: Some(self.encode_item_type(def_id)),
1460 inherent_impls: Lazy::empty(),
1461 variances: Lazy::empty(),
1462 generics: Some(self.encode_generics(def_id)),
1463 predicates: Some(self.encode_predicates(def_id)),
1464 predicates_defined_on: None,
1466 mir: self.encode_optimized_mir(def_id),
1470 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> Lazy<[ast::Attribute]> {
1474 fn encode_native_libraries(&mut self) -> Lazy<[NativeLibrary]> {
1475 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1476 self.lazy(used_libraries.iter().cloned())
1479 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1480 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1481 self.lazy(foreign_modules.iter().cloned())
1484 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1485 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
1488 Some(self.lazy(tcx.hir().krate().items.values().filter_map(|item| {
1489 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
1490 Some(item.hir_id.owner)
1500 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1501 let crates = self.tcx.crates();
1503 let mut deps = crates
1506 let dep = CrateDep {
1507 name: self.tcx.original_crate_name(cnum),
1508 hash: self.tcx.crate_hash(cnum),
1509 kind: self.tcx.dep_kind(cnum),
1510 extra_filename: self.tcx.extra_filename(cnum),
1514 .collect::<Vec<_>>();
1516 deps.sort_by_key(|&(cnum, _)| cnum);
1519 // Sanity-check the crate numbers
1520 let mut expected_cnum = 1;
1521 for &(n, _) in &deps {
1522 assert_eq!(n, CrateNum::new(expected_cnum));
1527 // We're just going to write a list of crate 'name-hash-version's, with
1528 // the assumption that they are numbered 1 to n.
1529 // FIXME (#2166): This is not nearly enough to support correct versioning
1530 // but is enough to get transitive crate dependencies working.
1531 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1534 fn encode_lib_features(&mut self) -> Lazy<[(ast::Name, Option<ast::Name>)]> {
1536 let lib_features = tcx.lib_features();
1537 self.lazy(lib_features.to_vec())
1540 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1542 let lang_items = tcx.lang_items();
1543 let lang_items = lang_items.items().iter();
1544 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1545 if let Some(def_id) = opt_def_id {
1546 if def_id.is_local() {
1547 return Some((def_id.index, i));
1554 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1556 self.lazy(&tcx.lang_items().missing)
1559 /// Encodes an index, mapping each trait to its (local) implementations.
1560 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1561 debug!("EncodeContext::encode_impls()");
1563 let mut visitor = ImplVisitor {
1565 impls: FxHashMap::default(),
1567 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1569 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1571 // Bring everything into deterministic order for hashing
1572 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1573 tcx.def_path_hash(trait_def_id)
1576 let all_impls: Vec<_> = all_impls
1578 .map(|(trait_def_id, mut impls)| {
1579 // Bring everything into deterministic order for hashing
1580 impls.sort_by_cached_key(|&def_index| {
1581 tcx.hir().definitions().def_path_hash(def_index)
1585 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1586 impls: self.lazy(&impls),
1591 self.lazy(&all_impls)
1594 // Encodes all symbols exported from this crate into the metadata.
1596 // This pass is seeded off the reachability list calculated in the
1597 // middle::reachable module but filters out items that either don't have a
1598 // symbol associated with them (they weren't translated) or if they're an FFI
1599 // definition (as that's not defined in this crate).
1600 fn encode_exported_symbols(&mut self,
1601 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)])
1602 -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1603 // The metadata symbol name is special. It should not show up in
1604 // downstream crates.
1605 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1607 self.lazy(exported_symbols
1609 .filter(|&&(ref exported_symbol, _)| {
1610 match *exported_symbol {
1611 ExportedSymbol::NoDefId(symbol_name) => {
1612 symbol_name != metadata_symbol_name
1620 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1621 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateType::Dylib) {
1623 self.lazy(arr.iter().map(|slot| {
1625 Linkage::NotLinked |
1626 Linkage::IncludedFromDylib => None,
1628 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1629 Linkage::Static => Some(LinkagePreference::RequireStatic),
1633 None => Lazy::empty(),
1637 fn encode_info_for_foreign_item(&mut self,
1638 (def_id, nitem): (DefId, &hir::ForeignItem))
1642 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1644 let kind = match nitem.node {
1645 hir::ForeignItemKind::Fn(_, ref names, _) => {
1647 constness: hir::Constness::NotConst,
1648 arg_names: self.encode_fn_arg_names(names),
1649 sig: self.lazy(tcx.fn_sig(def_id)),
1651 EntryKind::ForeignFn(self.lazy(data))
1653 hir::ForeignItemKind::Static(_, hir::MutMutable) => EntryKind::ForeignMutStatic,
1654 hir::ForeignItemKind::Static(_, hir::MutImmutable) => EntryKind::ForeignImmStatic,
1655 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1660 visibility: self.lazy(ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, tcx)),
1661 span: self.lazy(nitem.span),
1662 attributes: self.encode_attributes(&nitem.attrs),
1663 children: Lazy::empty(),
1664 stability: self.encode_stability(def_id),
1665 deprecation: self.encode_deprecation(def_id),
1667 ty: Some(self.encode_item_type(def_id)),
1668 inherent_impls: Lazy::empty(),
1669 variances: match nitem.node {
1670 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1673 generics: Some(self.encode_generics(def_id)),
1674 predicates: Some(self.encode_predicates(def_id)),
1675 predicates_defined_on: None,
1682 impl Visitor<'tcx> for EncodeContext<'tcx> {
1683 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1684 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1686 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1687 intravisit::walk_expr(self, ex);
1688 self.encode_info_for_expr(ex);
1690 fn visit_item(&mut self, item: &'tcx hir::Item) {
1691 intravisit::walk_item(self, item);
1692 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1694 hir::ItemKind::ExternCrate(_) |
1695 hir::ItemKind::Use(..) => {} // ignore these
1696 _ => self.record(def_id, EncodeContext::encode_info_for_item, (def_id, item)),
1698 self.encode_addl_info_for_item(item);
1700 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1701 intravisit::walk_foreign_item(self, ni);
1702 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1704 EncodeContext::encode_info_for_foreign_item,
1707 fn visit_variant(&mut self,
1708 v: &'tcx hir::Variant,
1709 g: &'tcx hir::Generics,
1711 intravisit::walk_variant(self, v, g, id);
1713 if let Some(ref discr) = v.disr_expr {
1714 let def_id = self.tcx.hir().local_def_id(discr.hir_id);
1715 self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id);
1718 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1719 intravisit::walk_generics(self, generics);
1720 self.encode_info_for_generics(generics);
1722 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1723 intravisit::walk_ty(self, ty);
1724 self.encode_info_for_ty(ty);
1726 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1727 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1728 self.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def);
1732 impl EncodeContext<'tcx> {
1733 fn encode_fields(&mut self, adt_def_id: DefId) {
1734 let def = self.tcx.adt_def(adt_def_id);
1735 for (variant_index, variant) in def.variants.iter_enumerated() {
1736 for (field_index, field) in variant.fields.iter().enumerate() {
1737 self.record(field.did,
1738 EncodeContext::encode_field,
1739 (adt_def_id, variant_index, field_index));
1744 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1745 for param in &generics.params {
1746 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1748 GenericParamKind::Lifetime { .. } => continue,
1749 GenericParamKind::Type { ref default, .. } => {
1752 EncodeContext::encode_info_for_ty_param,
1753 (def_id, default.is_some()),
1756 GenericParamKind::Const { .. } => {
1757 self.record(def_id, EncodeContext::encode_info_for_const_param, def_id);
1763 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1765 hir::TyKind::Array(_, ref length) => {
1766 let def_id = self.tcx.hir().local_def_id(length.hir_id);
1767 self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id);
1773 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1775 hir::ExprKind::Closure(..) => {
1776 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1777 self.record(def_id, EncodeContext::encode_info_for_closure, def_id);
1783 /// In some cases, along with the item itself, we also
1784 /// encode some sub-items. Usually we want some info from the item
1785 /// so it's easier to do that here then to wait until we would encounter
1786 /// normally in the visitor walk.
1787 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1788 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1790 hir::ItemKind::Static(..) |
1791 hir::ItemKind::Const(..) |
1792 hir::ItemKind::Fn(..) |
1793 hir::ItemKind::Mod(..) |
1794 hir::ItemKind::ForeignMod(..) |
1795 hir::ItemKind::GlobalAsm(..) |
1796 hir::ItemKind::ExternCrate(..) |
1797 hir::ItemKind::Use(..) |
1798 hir::ItemKind::TyAlias(..) |
1799 hir::ItemKind::OpaqueTy(..) |
1800 hir::ItemKind::TraitAlias(..) => {
1801 // no sub-item recording needed in these cases
1803 hir::ItemKind::Enum(..) => {
1804 self.encode_fields(def_id);
1806 let def = self.tcx.adt_def(def_id);
1807 for (i, variant) in def.variants.iter_enumerated() {
1808 self.record(variant.def_id,
1809 EncodeContext::encode_enum_variant_info,
1812 if let Some(ctor_def_id) = variant.ctor_def_id {
1813 self.record(ctor_def_id,
1814 EncodeContext::encode_enum_variant_ctor,
1819 hir::ItemKind::Struct(ref struct_def, _) => {
1820 self.encode_fields(def_id);
1822 // If the struct has a constructor, encode it.
1823 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1824 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1825 self.record(ctor_def_id,
1826 EncodeContext::encode_struct_ctor,
1827 (def_id, ctor_def_id));
1830 hir::ItemKind::Union(..) => {
1831 self.encode_fields(def_id);
1833 hir::ItemKind::Impl(..) => {
1834 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1835 self.record(trait_item_def_id,
1836 EncodeContext::encode_info_for_impl_item,
1840 hir::ItemKind::Trait(..) => {
1841 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1842 self.record(item_def_id,
1843 EncodeContext::encode_info_for_trait_item,
1851 struct ImplVisitor<'tcx> {
1853 impls: FxHashMap<DefId, Vec<DefIndex>>,
1856 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1857 fn visit_item(&mut self, item: &hir::Item) {
1858 if let hir::ItemKind::Impl(..) = item.node {
1859 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1860 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1862 .entry(trait_ref.def_id)
1864 .push(impl_id.index);
1869 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1871 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1872 // handled in `visit_item` above
1876 // NOTE(eddyb) The following comment was preserved for posterity, even
1877 // though it's no longer relevant as EBML (which uses nested & tagged
1878 // "documents") was replaced with a scheme that can't go out of bounds.
1880 // And here we run into yet another obscure archive bug: in which metadata
1881 // loaded from archives may have trailing garbage bytes. Awhile back one of
1882 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1883 // and opt) by having ebml generate an out-of-bounds panic when looking at
1886 // Upon investigation it turned out that the metadata file inside of an rlib
1887 // (and ar archive) was being corrupted. Some compilations would generate a
1888 // metadata file which would end in a few extra bytes, while other
1889 // compilations would not have these extra bytes appended to the end. These
1890 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1891 // being interpreted causing the out-of-bounds.
1893 // The root cause of why these extra bytes were appearing was never
1894 // discovered, and in the meantime the solution we're employing is to insert
1895 // the length of the metadata to the start of the metadata. Later on this
1896 // will allow us to slice the metadata to the precise length that we just
1897 // generated regardless of trailing bytes that end up in it.
1899 pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1900 let mut encoder = opaque::Encoder::new(vec![]);
1901 encoder.emit_raw_bytes(METADATA_HEADER);
1903 // Will be filled with the root position after encoding everything.
1904 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1906 // Since encoding metadata is not in a query, and nothing is cached,
1907 // there's no need to do dep-graph tracking for any of it.
1908 let (root, mut result) = tcx.dep_graph.with_ignore(move || {
1909 let mut ecx = EncodeContext {
1912 entries_index: Index::new(tcx.hir().definitions().def_index_count()),
1913 lazy_state: LazyState::NoNode,
1914 type_shorthands: Default::default(),
1915 predicate_shorthands: Default::default(),
1916 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1917 interpret_allocs: Default::default(),
1918 interpret_allocs_inverse: Default::default(),
1921 // Encode the rustc version string in a predictable location.
1922 rustc_version().encode(&mut ecx).unwrap();
1924 // Encode all the entries and extra information in the crate,
1925 // culminating in the `CrateRoot` which points to all of it.
1926 let root = ecx.encode_crate_root();
1927 (root, ecx.opaque.into_inner())
1930 // Encode the root position.
1931 let header = METADATA_HEADER.len();
1932 let pos = root.position;
1933 result[header + 0] = (pos >> 24) as u8;
1934 result[header + 1] = (pos >> 16) as u8;
1935 result[header + 2] = (pos >> 8) as u8;
1936 result[header + 3] = (pos >> 0) as u8;
1938 EncodedMetadata { raw_data: result }
1941 pub fn get_repr_options(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1942 let ty = tcx.type_of(did);
1944 ty::Adt(ref def, _) => return def.repr,
1945 _ => bug!("{} is not an ADT", ty),