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};
36 use syntax_pos::{self, FileName, SourceFile, Span};
37 use log::{debug, trace};
39 use rustc::hir::{self, PatKind};
40 use rustc::hir::itemlikevisit::ItemLikeVisitor;
41 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
42 use rustc::hir::intravisit;
44 pub struct EncodeContext<'tcx> {
45 opaque: opaque::Encoder,
46 pub tcx: TyCtxt<'tcx>,
48 entries_index: Index<'tcx>,
50 lazy_state: LazyState,
51 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
52 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
54 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
55 interpret_allocs_inverse: Vec<interpret::AllocId>,
57 // This is used to speed up Span encoding.
58 source_file_cache: Lrc<SourceFile>,
61 macro_rules! encoder_methods {
62 ($($name:ident($ty:ty);)*) => {
63 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
64 self.opaque.$name(value)
69 impl<'tcx> Encoder for EncodeContext<'tcx> {
70 type Error = <opaque::Encoder as Encoder>::Error;
72 fn emit_unit(&mut self) -> Result<(), Self::Error> {
99 impl<'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'tcx> {
100 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
101 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
105 impl<'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'tcx> {
106 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
107 self.emit_usize(seq.len)?;
111 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
115 impl<'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'tcx> {
117 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
118 self.emit_u32(cnum.as_u32())
122 impl<'tcx> SpecializedEncoder<DefId> for EncodeContext<'tcx> {
124 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
135 impl<'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'tcx> {
137 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
138 self.emit_u32(def_index.as_u32())
142 impl<'tcx> SpecializedEncoder<Span> for EncodeContext<'tcx> {
143 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
145 return TAG_INVALID_SPAN.encode(self)
148 let span = span.data();
150 // The Span infrastructure should make sure that this invariant holds:
151 debug_assert!(span.lo <= span.hi);
153 if !self.source_file_cache.contains(span.lo) {
154 let source_map = self.tcx.sess.source_map();
155 let source_file_index = source_map.lookup_source_file_idx(span.lo);
156 self.source_file_cache = source_map.files()[source_file_index].clone();
159 if !self.source_file_cache.contains(span.hi) {
160 // Unfortunately, macro expansion still sometimes generates Spans
161 // that malformed in this way.
162 return TAG_INVALID_SPAN.encode(self)
165 TAG_VALID_SPAN.encode(self)?;
166 span.lo.encode(self)?;
168 // Encode length which is usually less than span.hi and profits more
169 // from the variable-length integer encoding that we use.
170 let len = span.hi - span.lo;
173 // Don't encode the expansion context.
177 impl<'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'tcx> {
179 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
180 self.specialized_encode(&def_id.to_def_id())
184 impl<'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'tcx> {
185 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
186 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
190 impl<'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'tcx> {
191 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
192 use std::collections::hash_map::Entry;
193 let index = match self.interpret_allocs.entry(*alloc_id) {
194 Entry::Occupied(e) => *e.get(),
195 Entry::Vacant(e) => {
196 let idx = self.interpret_allocs_inverse.len();
197 self.interpret_allocs_inverse.push(*alloc_id);
207 impl<'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'tcx> {
208 fn specialized_encode(&mut self,
209 predicates: &ty::GenericPredicates<'tcx>)
210 -> Result<(), Self::Error> {
211 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
215 impl<'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'tcx> {
216 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
217 f.encode_opaque(&mut self.opaque)
221 impl<'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'tcx> {
222 fn specialized_encode(&mut self,
223 _: &mir::ClearCrossCrate<T>)
224 -> Result<(), Self::Error> {
229 impl<'tcx> TyEncoder for EncodeContext<'tcx> {
230 fn position(&self) -> usize {
231 self.opaque.position()
235 impl<'tcx> EncodeContext<'tcx> {
236 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
237 assert_eq!(self.lazy_state, LazyState::NoNode);
238 let pos = self.position();
239 self.lazy_state = LazyState::NodeStart(pos);
240 let r = f(self, pos);
241 self.lazy_state = LazyState::NoNode;
245 fn emit_lazy_distance(&mut self,
248 -> Result<(), <Self as Encoder>::Error> {
249 let min_end = position + min_size;
250 let distance = match self.lazy_state {
251 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
252 LazyState::NodeStart(start) => {
253 assert!(min_end <= start);
256 LazyState::Previous(last_min_end) => {
258 last_min_end <= position,
259 "make sure that the calls to `lazy*` \
260 are in the same order as the metadata fields",
262 position - last_min_end
265 self.lazy_state = LazyState::Previous(min_end);
266 self.emit_usize(distance)
269 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
270 self.emit_node(|ecx, pos| {
271 value.encode(ecx).unwrap();
273 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
274 Lazy::with_position(pos)
278 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
279 where I: IntoIterator<Item = T>,
282 self.emit_node(|ecx, pos| {
283 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
285 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
286 LazySeq::with_position_and_length(pos, len)
290 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
291 where I: IntoIterator<Item = &'b T>,
294 self.emit_node(|ecx, pos| {
295 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
297 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
298 LazySeq::with_position_and_length(pos, len)
302 /// Emit the data for a `DefId` to the metadata. The function to
303 /// emit the data is `op`, and it will be given `data` as
304 /// arguments. This `record` function will call `op` to generate
305 /// the `Entry` (which may point to other encoded information)
306 /// and will then record the `Lazy<Entry>` for use in the index.
307 // FIXME(eddyb) remove this.
308 pub fn record<DATA>(&mut self,
310 op: impl FnOnce(&mut Self, DATA) -> Entry<'tcx>,
313 assert!(id.is_local());
315 let entry = op(self, data);
316 let entry = self.lazy(&entry);
317 self.entries_index.record(id, entry);
320 fn encode_info_for_items(&mut self) {
321 let krate = self.tcx.hir().krate();
322 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public };
323 self.record(DefId::local(CRATE_DEF_INDEX),
324 EncodeContext::encode_info_for_mod,
325 (hir::CRATE_HIR_ID, &krate.module, &krate.attrs, &vis));
326 krate.visit_all_item_likes(&mut self.as_deep_visitor());
327 for macro_def in &krate.exported_macros {
328 self.visit_macro_def(macro_def);
332 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
333 let definitions = self.tcx.hir().definitions();
334 self.lazy(definitions.def_path_table())
337 fn encode_source_map(&mut self) -> LazySeq<syntax_pos::SourceFile> {
338 let source_map = self.tcx.sess.source_map();
339 let all_source_files = source_map.files();
341 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
343 let adapted = all_source_files.iter()
344 .filter(|source_file| {
345 // No need to re-export imported source_files, as any downstream
346 // crate will import them from their original source.
347 !source_file.is_imported()
350 match source_file.name {
351 // This path of this SourceFile has been modified by
352 // path-remapping, so we use it verbatim (and avoid
353 // cloning the whole map in the process).
354 _ if source_file.name_was_remapped => source_file.clone(),
356 // Otherwise expand all paths to absolute paths because
357 // any relative paths are potentially relative to a
359 FileName::Real(ref name) => {
360 let mut adapted = (**source_file).clone();
361 adapted.name = Path::new(&working_dir).join(name).into();
362 adapted.name_hash = {
363 let mut hasher: StableHasher<u128> = StableHasher::new();
364 adapted.name.hash(&mut hasher);
370 // expanded code, not from a file
371 _ => source_file.clone(),
374 .collect::<Vec<_>>();
376 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
379 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
380 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
382 let mut i = self.position();
384 let crate_deps = self.encode_crate_deps();
385 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
386 let dep_bytes = self.position() - i;
388 // Encode the lib features.
390 let lib_features = self.encode_lib_features();
391 let lib_feature_bytes = self.position() - i;
393 // Encode the language items.
395 let lang_items = self.encode_lang_items();
396 let lang_items_missing = self.encode_lang_items_missing();
397 let lang_item_bytes = self.position() - i;
399 // Encode the native libraries used
401 let native_libraries = self.encode_native_libraries();
402 let native_lib_bytes = self.position() - i;
404 let foreign_modules = self.encode_foreign_modules();
408 let source_map = self.encode_source_map();
409 let source_map_bytes = self.position() - i;
411 // Encode DefPathTable
413 let def_path_table = self.encode_def_path_table();
414 let def_path_table_bytes = self.position() - i;
416 // Encode the def IDs of impls, for coherence checking.
418 let impls = self.encode_impls();
419 let impl_bytes = self.position() - i;
421 // Encode exported symbols info.
423 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
424 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
425 let exported_symbols_bytes = self.position() - i;
431 self.encode_info_for_items();
432 let item_bytes = self.position() - i;
434 // Encode the allocation index
435 let interpret_alloc_index = {
436 let mut interpret_alloc_index = Vec::new();
438 trace!("beginning to encode alloc ids");
440 let new_n = self.interpret_allocs_inverse.len();
441 // if we have found new ids, serialize those, too
446 trace!("encoding {} further alloc ids", new_n - n);
447 for idx in n..new_n {
448 let id = self.interpret_allocs_inverse[idx];
449 let pos = self.position() as u32;
450 interpret_alloc_index.push(pos);
451 interpret::specialized_encode_alloc_id(
459 self.lazy_seq(interpret_alloc_index)
464 let entries_index = self.entries_index.write_index(&mut self.opaque);
465 let entries_index_bytes = self.position() - i;
467 // Encode the proc macro data
469 let proc_macro_data = self.encode_proc_macros();
470 let proc_macro_data_bytes = self.position() - i;
473 let attrs = tcx.hir().krate_attrs();
474 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
475 let has_global_allocator = *tcx.sess.has_global_allocator.get();
476 let has_panic_handler = *tcx.sess.has_panic_handler.try_get().unwrap_or(&false);
479 let root = self.lazy(&CrateRoot {
480 name: tcx.crate_name(LOCAL_CRATE),
481 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
482 triple: tcx.sess.opts.target_triple.clone(),
483 hash: tcx.crate_hash(LOCAL_CRATE),
484 disambiguator: tcx.sess.local_crate_disambiguator(),
485 panic_strategy: tcx.sess.panic_strategy(),
486 edition: tcx.sess.edition(),
487 has_global_allocator: has_global_allocator,
488 has_panic_handler: has_panic_handler,
489 has_default_lib_allocator: has_default_lib_allocator,
490 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
491 proc_macro_decls_static: if is_proc_macro {
492 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
498 proc_macro_stability: if is_proc_macro {
499 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).map(|stab| stab.clone())
503 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
504 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
505 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
506 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
507 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
508 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
509 sanitizer_runtime: attr::contains_name(&attrs, sym::sanitizer_runtime),
510 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
513 dylib_dependency_formats,
523 interpret_alloc_index,
527 let total_bytes = self.position();
529 if self.tcx.sess.meta_stats() {
530 let mut zero_bytes = 0;
531 for e in self.opaque.data.iter() {
537 println!("metadata stats:");
538 println!(" dep bytes: {}", dep_bytes);
539 println!(" lib feature bytes: {}", lib_feature_bytes);
540 println!(" lang item bytes: {}", lang_item_bytes);
541 println!(" native bytes: {}", native_lib_bytes);
542 println!(" source_map bytes: {}", source_map_bytes);
543 println!(" impl bytes: {}", impl_bytes);
544 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
545 println!(" def-path table bytes: {}", def_path_table_bytes);
546 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
547 println!(" item bytes: {}", item_bytes);
548 println!(" entries index bytes: {}", entries_index_bytes);
549 println!(" zero bytes: {}", zero_bytes);
550 println!(" total bytes: {}", total_bytes);
557 impl EncodeContext<'tcx> {
558 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
559 debug!("EncodeContext::encode_variances_of({:?})", def_id);
561 self.lazy_seq_ref(&tcx.variances_of(def_id)[..])
564 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
566 let ty = tcx.type_of(def_id);
567 debug!("EncodeContext::encode_item_type({:?}) => {:?}", def_id, ty);
571 fn encode_enum_variant_info(
573 (enum_did, index): (DefId, VariantIdx),
576 let def = tcx.adt_def(enum_did);
577 let variant = &def.variants[index];
578 let def_id = variant.def_id;
579 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
581 let data = VariantData {
582 ctor_kind: variant.ctor_kind,
583 discr: variant.discr,
584 // FIXME(eddyb) deduplicate these with `encode_enum_variant_ctor`.
585 ctor: variant.ctor_def_id.map(|did| did.index),
586 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
587 variant.ctor_def_id.map(|ctor_def_id| self.lazy(&tcx.fn_sig(ctor_def_id)))
593 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
594 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
597 kind: EntryKind::Variant(self.lazy(&data)),
598 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
599 span: self.lazy(&tcx.def_span(def_id)),
600 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
601 children: self.lazy_seq(variant.fields.iter().map(|f| {
602 assert!(f.did.is_local());
605 stability: self.encode_stability(def_id),
606 deprecation: self.encode_deprecation(def_id),
608 ty: Some(self.encode_item_type(def_id)),
609 inherent_impls: LazySeq::empty(),
610 variances: if variant.ctor_kind == CtorKind::Fn {
611 self.encode_variances_of(def_id)
615 generics: Some(self.encode_generics(def_id)),
616 predicates: Some(self.encode_predicates(def_id)),
617 predicates_defined_on: None,
619 mir: self.encode_optimized_mir(def_id),
623 fn encode_enum_variant_ctor(
625 (enum_did, index): (DefId, VariantIdx),
628 let def = tcx.adt_def(enum_did);
629 let variant = &def.variants[index];
630 let def_id = variant.ctor_def_id.unwrap();
631 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
633 let data = VariantData {
634 ctor_kind: variant.ctor_kind,
635 discr: variant.discr,
636 ctor: Some(def_id.index),
637 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
638 Some(self.lazy(&tcx.fn_sig(def_id)))
644 // Variant constructors have the same visibility as the parent enums, unless marked as
645 // non-exhaustive, in which case they are lowered to `pub(crate)`.
646 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
647 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
648 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
649 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
650 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
654 kind: EntryKind::Variant(self.lazy(&data)),
655 visibility: self.lazy(&ctor_vis),
656 span: self.lazy(&tcx.def_span(def_id)),
657 attributes: LazySeq::empty(),
658 children: LazySeq::empty(),
659 stability: self.encode_stability(def_id),
660 deprecation: self.encode_deprecation(def_id),
662 ty: Some(self.encode_item_type(def_id)),
663 inherent_impls: LazySeq::empty(),
664 variances: if variant.ctor_kind == CtorKind::Fn {
665 self.encode_variances_of(def_id)
669 generics: Some(self.encode_generics(def_id)),
670 predicates: Some(self.encode_predicates(def_id)),
671 predicates_defined_on: None,
673 mir: self.encode_optimized_mir(def_id),
677 fn encode_info_for_mod(
679 (id, md, attrs, vis): (hir::HirId, &hir::Mod, &[ast::Attribute], &hir::Visibility),
682 let def_id = tcx.hir().local_def_id(id);
683 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
686 reexports: match tcx.module_exports(def_id) {
687 Some(exports) => self.lazy_seq_ref(exports),
688 _ => LazySeq::empty(),
693 kind: EntryKind::Mod(self.lazy(&data)),
694 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
695 span: self.lazy(&tcx.def_span(def_id)),
696 attributes: self.encode_attributes(attrs),
697 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
698 tcx.hir().local_def_id(item_id.id).index
700 stability: self.encode_stability(def_id),
701 deprecation: self.encode_deprecation(def_id),
704 inherent_impls: LazySeq::empty(),
705 variances: LazySeq::empty(),
708 predicates_defined_on: None,
716 (adt_def_id, variant_index, field_index): (DefId, VariantIdx, usize),
719 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
720 let field = &variant.fields[field_index];
722 let def_id = field.did;
723 debug!("EncodeContext::encode_field({:?})", def_id);
725 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
726 let variant_data = tcx.hir().expect_variant_data(variant_id);
729 kind: EntryKind::Field,
730 visibility: self.lazy(&field.vis),
731 span: self.lazy(&tcx.def_span(def_id)),
732 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
733 children: LazySeq::empty(),
734 stability: self.encode_stability(def_id),
735 deprecation: self.encode_deprecation(def_id),
737 ty: Some(self.encode_item_type(def_id)),
738 inherent_impls: LazySeq::empty(),
739 variances: LazySeq::empty(),
740 generics: Some(self.encode_generics(def_id)),
741 predicates: Some(self.encode_predicates(def_id)),
742 predicates_defined_on: None,
748 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
749 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
751 let adt_def = tcx.adt_def(adt_def_id);
752 let variant = adt_def.non_enum_variant();
754 let data = VariantData {
755 ctor_kind: variant.ctor_kind,
756 discr: variant.discr,
757 ctor: Some(def_id.index),
758 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
759 Some(self.lazy(&tcx.fn_sig(def_id)))
765 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
766 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
767 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
768 for field in &variant.fields {
769 if ctor_vis.is_at_least(field.vis, tcx) {
770 ctor_vis = field.vis;
774 // If the structure is marked as non_exhaustive then lower the visibility
775 // to within the crate.
776 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
777 ctor_vis == ty::Visibility::Public
779 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
782 let repr_options = get_repr_options(tcx, adt_def_id);
785 kind: EntryKind::Struct(self.lazy(&data), repr_options),
786 visibility: self.lazy(&ctor_vis),
787 span: self.lazy(&tcx.def_span(def_id)),
788 attributes: LazySeq::empty(),
789 children: LazySeq::empty(),
790 stability: self.encode_stability(def_id),
791 deprecation: self.encode_deprecation(def_id),
793 ty: Some(self.encode_item_type(def_id)),
794 inherent_impls: LazySeq::empty(),
795 variances: if variant.ctor_kind == CtorKind::Fn {
796 self.encode_variances_of(def_id)
800 generics: Some(self.encode_generics(def_id)),
801 predicates: Some(self.encode_predicates(def_id)),
802 predicates_defined_on: None,
804 mir: self.encode_optimized_mir(def_id),
808 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
809 debug!("EncodeContext::encode_generics({:?})", def_id);
811 self.lazy(tcx.generics_of(def_id))
814 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
815 debug!("EncodeContext::encode_predicates({:?})", def_id);
817 self.lazy(&tcx.predicates_of(def_id))
820 fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
821 debug!("EncodeContext::encode_predicates_defined_on({:?})", def_id);
823 self.lazy(&tcx.predicates_defined_on(def_id))
826 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
827 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
830 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
831 let ast_item = tcx.hir().expect_trait_item(hir_id);
832 let trait_item = tcx.associated_item(def_id);
834 let container = match trait_item.defaultness {
835 hir::Defaultness::Default { has_value: true } =>
836 AssocContainer::TraitWithDefault,
837 hir::Defaultness::Default { has_value: false } =>
838 AssocContainer::TraitRequired,
839 hir::Defaultness::Final =>
840 span_bug!(ast_item.span, "traits cannot have final items"),
843 let kind = match trait_item.kind {
844 ty::AssocKind::Const => {
846 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
847 self.const_qualif(0, body)
849 ConstQualif { mir: 0, ast_promotable: false }
853 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
854 let rendered_const = self.lazy(&RenderedConst(rendered));
856 EntryKind::AssocConst(container, const_qualif, rendered_const)
858 ty::AssocKind::Method => {
859 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
860 let arg_names = match *m {
861 hir::TraitMethod::Required(ref names) => {
862 self.encode_fn_arg_names(names)
864 hir::TraitMethod::Provided(body) => {
865 self.encode_fn_arg_names_for_body(body)
869 constness: hir::Constness::NotConst,
871 sig: self.lazy(&tcx.fn_sig(def_id)),
876 EntryKind::Method(self.lazy(&MethodData {
879 has_self: trait_item.method_has_self_argument,
882 ty::AssocKind::Type => EntryKind::AssocType(container),
883 ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
888 visibility: self.lazy(&trait_item.vis),
889 span: self.lazy(&ast_item.span),
890 attributes: self.encode_attributes(&ast_item.attrs),
891 children: LazySeq::empty(),
892 stability: self.encode_stability(def_id),
893 deprecation: self.encode_deprecation(def_id),
895 ty: match trait_item.kind {
896 ty::AssocKind::Const |
897 ty::AssocKind::Method => {
898 Some(self.encode_item_type(def_id))
900 ty::AssocKind::Type => {
901 if trait_item.defaultness.has_value() {
902 Some(self.encode_item_type(def_id))
907 ty::AssocKind::OpaqueTy => unreachable!(),
909 inherent_impls: LazySeq::empty(),
910 variances: if trait_item.kind == ty::AssocKind::Method {
911 self.encode_variances_of(def_id)
915 generics: Some(self.encode_generics(def_id)),
916 predicates: Some(self.encode_predicates(def_id)),
917 predicates_defined_on: None,
919 mir: self.encode_optimized_mir(def_id),
923 fn metadata_output_only(&self) -> bool {
924 // MIR optimisation can be skipped when we're just interested in the metadata.
925 !self.tcx.sess.opts.output_types.should_codegen()
928 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
929 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
930 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
932 ConstQualif { mir, ast_promotable }
935 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
936 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
939 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
940 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
941 let impl_item = self.tcx.associated_item(def_id);
943 let container = match impl_item.defaultness {
944 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
945 hir::Defaultness::Final => AssocContainer::ImplFinal,
946 hir::Defaultness::Default { has_value: false } =>
947 span_bug!(ast_item.span, "impl items always have values (currently)"),
950 let kind = match impl_item.kind {
951 ty::AssocKind::Const => {
952 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
953 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
955 EntryKind::AssocConst(container,
956 self.const_qualif(mir, body_id),
957 self.encode_rendered_const_for_body(body_id))
962 ty::AssocKind::Method => {
963 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
965 constness: sig.header.constness,
966 arg_names: self.encode_fn_arg_names_for_body(body),
967 sig: self.lazy(&tcx.fn_sig(def_id)),
972 EntryKind::Method(self.lazy(&MethodData {
975 has_self: impl_item.method_has_self_argument,
978 ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
979 ty::AssocKind::Type => EntryKind::AssocType(container)
983 match ast_item.node {
984 hir::ImplItemKind::Const(..) => true,
985 hir::ImplItemKind::Method(ref sig, _) => {
986 let generics = self.tcx.generics_of(def_id);
987 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
988 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
989 !self.metadata_output_only();
990 let is_const_fn = sig.header.constness == hir::Constness::Const;
991 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
992 needs_inline || is_const_fn || always_encode_mir
994 hir::ImplItemKind::OpaqueTy(..) |
995 hir::ImplItemKind::TyAlias(..) => false,
1000 visibility: self.lazy(&impl_item.vis),
1001 span: self.lazy(&ast_item.span),
1002 attributes: self.encode_attributes(&ast_item.attrs),
1003 children: LazySeq::empty(),
1004 stability: self.encode_stability(def_id),
1005 deprecation: self.encode_deprecation(def_id),
1007 ty: Some(self.encode_item_type(def_id)),
1008 inherent_impls: LazySeq::empty(),
1009 variances: if impl_item.kind == ty::AssocKind::Method {
1010 self.encode_variances_of(def_id)
1014 generics: Some(self.encode_generics(def_id)),
1015 predicates: Some(self.encode_predicates(def_id)),
1016 predicates_defined_on: None,
1018 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
1022 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
1023 -> LazySeq<ast::Name> {
1024 self.tcx.dep_graph.with_ignore(|| {
1025 let body = self.tcx.hir().body(body_id);
1026 self.lazy_seq(body.arguments.iter().map(|arg| {
1027 match arg.pat.node {
1028 PatKind::Binding(_, _, ident, _) => ident.name,
1035 fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> LazySeq<ast::Name> {
1036 self.lazy_seq(param_names.iter().map(|ident| ident.name))
1039 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Body<'tcx>>> {
1040 debug!("EntryBuilder::encode_mir({:?})", def_id);
1041 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1042 let mir = self.tcx.optimized_mir(def_id);
1043 Some(self.lazy(&mir))
1049 // Encodes the inherent implementations of a structure, enumeration, or trait.
1050 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1051 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1052 let implementations = self.tcx.inherent_impls(def_id);
1053 if implementations.is_empty() {
1056 self.lazy_seq(implementations.iter().map(|&def_id| {
1057 assert!(def_id.is_local());
1063 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1064 debug!("EncodeContext::encode_stability({:?})", def_id);
1065 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1068 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1069 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1070 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1073 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1074 let body = self.tcx.hir().body(body_id);
1075 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1076 let rendered_const = &RenderedConst(rendered);
1077 self.lazy(rendered_const)
1080 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1083 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1085 let kind = match item.node {
1086 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1087 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1088 hir::ItemKind::Const(_, body_id) => {
1089 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1091 self.const_qualif(mir, body_id),
1092 self.encode_rendered_const_for_body(body_id)
1095 hir::ItemKind::Fn(_, header, .., body) => {
1097 constness: header.constness,
1098 arg_names: self.encode_fn_arg_names_for_body(body),
1099 sig: self.lazy(&tcx.fn_sig(def_id)),
1102 EntryKind::Fn(self.lazy(&data))
1104 hir::ItemKind::Mod(ref m) => {
1105 return self.encode_info_for_mod((item.hir_id, m, &item.attrs, &item.vis));
1107 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1108 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1109 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1110 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1111 hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(tcx, def_id)),
1112 hir::ItemKind::Struct(ref struct_def, _) => {
1113 let variant = tcx.adt_def(def_id).non_enum_variant();
1115 // Encode def_ids for each field and method
1116 // for methods, write all the stuff get_trait_method
1118 let ctor = struct_def.ctor_hir_id()
1119 .map(|ctor_hir_id| tcx.hir().local_def_id(ctor_hir_id).index);
1121 let repr_options = get_repr_options(tcx, def_id);
1123 EntryKind::Struct(self.lazy(&VariantData {
1124 ctor_kind: variant.ctor_kind,
1125 discr: variant.discr,
1130 hir::ItemKind::Union(..) => {
1131 let variant = tcx.adt_def(def_id).non_enum_variant();
1132 let repr_options = get_repr_options(tcx, def_id);
1134 EntryKind::Union(self.lazy(&VariantData {
1135 ctor_kind: variant.ctor_kind,
1136 discr: variant.discr,
1141 hir::ItemKind::Impl(_, polarity, defaultness, ..) => {
1142 let trait_ref = tcx.impl_trait_ref(def_id);
1143 let parent = if let Some(trait_ref) = trait_ref {
1144 let trait_def = tcx.trait_def(trait_ref.def_id);
1145 trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| {
1147 specialization_graph::Node::Impl(parent) => Some(parent),
1155 // if this is an impl of `CoerceUnsized`, create its
1156 // "unsized info", else just store None
1157 let coerce_unsized_info =
1158 trait_ref.and_then(|t| {
1159 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1160 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1166 let data = ImplData {
1169 parent_impl: parent,
1170 coerce_unsized_info,
1171 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1174 EntryKind::Impl(self.lazy(&data))
1176 hir::ItemKind::Trait(..) => {
1177 let trait_def = tcx.trait_def(def_id);
1178 let data = TraitData {
1179 unsafety: trait_def.unsafety,
1180 paren_sugar: trait_def.paren_sugar,
1181 has_auto_impl: tcx.trait_is_auto(def_id),
1182 is_marker: trait_def.is_marker,
1183 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1186 EntryKind::Trait(self.lazy(&data))
1188 hir::ItemKind::TraitAlias(..) => {
1189 let data = TraitAliasData {
1190 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1193 EntryKind::TraitAlias(self.lazy(&data))
1195 hir::ItemKind::ExternCrate(_) |
1196 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1201 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.hir_id, tcx)),
1202 span: self.lazy(&item.span),
1203 attributes: self.encode_attributes(&item.attrs),
1204 children: match item.node {
1205 hir::ItemKind::ForeignMod(ref fm) => {
1206 self.lazy_seq(fm.items
1208 .map(|foreign_item| tcx.hir().local_def_id(
1209 foreign_item.hir_id).index))
1211 hir::ItemKind::Enum(..) => {
1212 let def = self.tcx.adt_def(def_id);
1213 self.lazy_seq(def.variants.iter().map(|v| {
1214 assert!(v.def_id.is_local());
1218 hir::ItemKind::Struct(..) |
1219 hir::ItemKind::Union(..) => {
1220 let def = self.tcx.adt_def(def_id);
1221 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1222 assert!(f.did.is_local());
1226 hir::ItemKind::Impl(..) |
1227 hir::ItemKind::Trait(..) => {
1228 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1229 assert!(def_id.is_local());
1233 _ => LazySeq::empty(),
1235 stability: self.encode_stability(def_id),
1236 deprecation: self.encode_deprecation(def_id),
1238 ty: match item.node {
1239 hir::ItemKind::Static(..) |
1240 hir::ItemKind::Const(..) |
1241 hir::ItemKind::Fn(..) |
1242 hir::ItemKind::TyAlias(..) |
1243 hir::ItemKind::OpaqueTy(..) |
1244 hir::ItemKind::Enum(..) |
1245 hir::ItemKind::Struct(..) |
1246 hir::ItemKind::Union(..) |
1247 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1250 inherent_impls: self.encode_inherent_implementations(def_id),
1251 variances: match item.node {
1252 hir::ItemKind::Enum(..) |
1253 hir::ItemKind::Struct(..) |
1254 hir::ItemKind::Union(..) |
1255 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1256 _ => LazySeq::empty(),
1258 generics: match item.node {
1259 hir::ItemKind::Static(..) |
1260 hir::ItemKind::Const(..) |
1261 hir::ItemKind::Fn(..) |
1262 hir::ItemKind::TyAlias(..) |
1263 hir::ItemKind::Enum(..) |
1264 hir::ItemKind::Struct(..) |
1265 hir::ItemKind::Union(..) |
1266 hir::ItemKind::Impl(..) |
1267 hir::ItemKind::OpaqueTy(..) |
1268 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1269 hir::ItemKind::TraitAlias(..) => Some(self.encode_generics(def_id)),
1272 predicates: match item.node {
1273 hir::ItemKind::Static(..) |
1274 hir::ItemKind::Const(..) |
1275 hir::ItemKind::Fn(..) |
1276 hir::ItemKind::TyAlias(..) |
1277 hir::ItemKind::Enum(..) |
1278 hir::ItemKind::Struct(..) |
1279 hir::ItemKind::Union(..) |
1280 hir::ItemKind::Impl(..) |
1281 hir::ItemKind::OpaqueTy(..) |
1282 hir::ItemKind::Trait(..) |
1283 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates(def_id)),
1287 // The only time that `predicates_defined_on` is used (on
1288 // an external item) is for traits, during chalk lowering,
1289 // so only encode it in that case as an efficiency
1290 // hack. (No reason not to expand it in the future if
1292 predicates_defined_on: match item.node {
1293 hir::ItemKind::Trait(..) |
1294 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates_defined_on(def_id)),
1295 _ => None, // not *wrong* for other kinds of items, but not needed
1298 mir: match item.node {
1299 hir::ItemKind::Static(..) => {
1300 self.encode_optimized_mir(def_id)
1302 hir::ItemKind::Const(..) => self.encode_optimized_mir(def_id),
1303 hir::ItemKind::Fn(_, header, ..) => {
1304 let generics = tcx.generics_of(def_id);
1306 (generics.requires_monomorphization(tcx) ||
1307 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1308 !self.metadata_output_only();
1309 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1311 || header.constness == hir::Constness::Const
1312 || always_encode_mir
1314 self.encode_optimized_mir(def_id)
1324 /// Serialize the text of exported macros
1325 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1326 use syntax::print::pprust;
1327 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1329 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1330 body: pprust::tokens_to_string(macro_def.body.clone()),
1331 legacy: macro_def.legacy,
1333 visibility: self.lazy(&ty::Visibility::Public),
1334 span: self.lazy(¯o_def.span),
1335 attributes: self.encode_attributes(¯o_def.attrs),
1336 stability: self.encode_stability(def_id),
1337 deprecation: self.encode_deprecation(def_id),
1339 children: LazySeq::empty(),
1341 inherent_impls: LazySeq::empty(),
1342 variances: LazySeq::empty(),
1345 predicates_defined_on: None,
1350 fn encode_info_for_generic_param(
1353 entry_kind: EntryKind<'tcx>,
1359 visibility: self.lazy(&ty::Visibility::Public),
1360 span: self.lazy(&tcx.def_span(def_id)),
1361 attributes: LazySeq::empty(),
1362 children: LazySeq::empty(),
1365 ty: if encode_type { Some(self.encode_item_type(def_id)) } else { None },
1366 inherent_impls: LazySeq::empty(),
1367 variances: LazySeq::empty(),
1370 predicates_defined_on: None,
1376 fn encode_info_for_ty_param(
1378 (def_id, encode_type): (DefId, bool),
1380 debug!("EncodeContext::encode_info_for_ty_param({:?})", def_id);
1381 self.encode_info_for_generic_param(def_id, EntryKind::TypeParam, encode_type)
1384 fn encode_info_for_const_param(
1388 debug!("EncodeContext::encode_info_for_const_param({:?})", def_id);
1389 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true)
1392 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1393 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1396 let tables = self.tcx.typeck_tables_of(def_id);
1397 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1398 let kind = match tables.node_type(hir_id).sty {
1399 ty::Generator(def_id, ..) => {
1400 let layout = self.tcx.generator_layout(def_id);
1401 let data = GeneratorData {
1402 layout: layout.clone(),
1404 EntryKind::Generator(self.lazy(&data))
1407 ty::Closure(def_id, substs) => {
1408 let sig = substs.closure_sig(def_id, self.tcx);
1409 let data = ClosureData { sig: self.lazy(&sig) };
1410 EntryKind::Closure(self.lazy(&data))
1413 _ => bug!("closure that is neither generator nor closure")
1418 visibility: self.lazy(&ty::Visibility::Public),
1419 span: self.lazy(&tcx.def_span(def_id)),
1420 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1421 children: LazySeq::empty(),
1425 ty: Some(self.encode_item_type(def_id)),
1426 inherent_impls: LazySeq::empty(),
1427 variances: LazySeq::empty(),
1428 generics: Some(self.encode_generics(def_id)),
1430 predicates_defined_on: None,
1432 mir: self.encode_optimized_mir(def_id),
1436 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1437 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1439 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
1440 let body_id = tcx.hir().body_owned_by(id);
1441 let const_data = self.encode_rendered_const_for_body(body_id);
1442 let mir = tcx.mir_const_qualif(def_id).0;
1445 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1446 visibility: self.lazy(&ty::Visibility::Public),
1447 span: self.lazy(&tcx.def_span(def_id)),
1448 attributes: LazySeq::empty(),
1449 children: LazySeq::empty(),
1453 ty: Some(self.encode_item_type(def_id)),
1454 inherent_impls: LazySeq::empty(),
1455 variances: LazySeq::empty(),
1456 generics: Some(self.encode_generics(def_id)),
1457 predicates: Some(self.encode_predicates(def_id)),
1458 predicates_defined_on: None,
1460 mir: self.encode_optimized_mir(def_id),
1464 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1465 self.lazy_seq_ref(attrs)
1468 fn encode_native_libraries(&mut self) -> LazySeq<NativeLibrary> {
1469 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1470 self.lazy_seq(used_libraries.iter().cloned())
1473 fn encode_foreign_modules(&mut self) -> LazySeq<ForeignModule> {
1474 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1475 self.lazy_seq(foreign_modules.iter().cloned())
1478 fn encode_proc_macros(&mut self) -> Option<LazySeq<DefIndex>> {
1479 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
1481 let proc_macros: Vec<_> = self.tcx.hir().krate().items.values().filter_map(|item| {
1482 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
1483 Some(item.hir_id.owner)
1488 Some(self.lazy_seq(proc_macros))
1494 fn encode_crate_deps(&mut self) -> LazySeq<CrateDep> {
1495 let crates = self.tcx.crates();
1497 let mut deps = crates
1500 let dep = CrateDep {
1501 name: self.tcx.original_crate_name(cnum),
1502 hash: self.tcx.crate_hash(cnum),
1503 kind: self.tcx.dep_kind(cnum),
1504 extra_filename: self.tcx.extra_filename(cnum),
1508 .collect::<Vec<_>>();
1510 deps.sort_by_key(|&(cnum, _)| cnum);
1513 // Sanity-check the crate numbers
1514 let mut expected_cnum = 1;
1515 for &(n, _) in &deps {
1516 assert_eq!(n, CrateNum::new(expected_cnum));
1521 // We're just going to write a list of crate 'name-hash-version's, with
1522 // the assumption that they are numbered 1 to n.
1523 // FIXME (#2166): This is not nearly enough to support correct versioning
1524 // but is enough to get transitive crate dependencies working.
1525 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1528 fn encode_lib_features(&mut self) -> LazySeq<(ast::Name, Option<ast::Name>)> {
1530 let lib_features = tcx.lib_features();
1531 self.lazy_seq(lib_features.to_vec())
1534 fn encode_lang_items(&mut self) -> LazySeq<(DefIndex, usize)> {
1536 let lang_items = tcx.lang_items();
1537 let lang_items = lang_items.items().iter();
1538 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1539 if let Some(def_id) = opt_def_id {
1540 if def_id.is_local() {
1541 return Some((def_id.index, i));
1548 fn encode_lang_items_missing(&mut self) -> LazySeq<lang_items::LangItem> {
1550 self.lazy_seq_ref(&tcx.lang_items().missing)
1553 /// Encodes an index, mapping each trait to its (local) implementations.
1554 fn encode_impls(&mut self) -> LazySeq<TraitImpls> {
1555 debug!("EncodeContext::encode_impls()");
1557 let mut visitor = ImplVisitor {
1559 impls: FxHashMap::default(),
1561 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1563 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1565 // Bring everything into deterministic order for hashing
1566 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1567 tcx.def_path_hash(trait_def_id)
1570 let all_impls: Vec<_> = all_impls
1572 .map(|(trait_def_id, mut impls)| {
1573 // Bring everything into deterministic order for hashing
1574 impls.sort_by_cached_key(|&def_index| {
1575 tcx.hir().definitions().def_path_hash(def_index)
1579 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1580 impls: self.lazy_seq_ref(&impls),
1585 self.lazy_seq_ref(&all_impls)
1588 // Encodes all symbols exported from this crate into the metadata.
1590 // This pass is seeded off the reachability list calculated in the
1591 // middle::reachable module but filters out items that either don't have a
1592 // symbol associated with them (they weren't translated) or if they're an FFI
1593 // definition (as that's not defined in this crate).
1594 fn encode_exported_symbols(&mut self,
1595 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)])
1596 -> LazySeq<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1597 // The metadata symbol name is special. It should not show up in
1598 // downstream crates.
1599 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1601 self.lazy_seq(exported_symbols
1603 .filter(|&&(ref exported_symbol, _)| {
1604 match *exported_symbol {
1605 ExportedSymbol::NoDefId(symbol_name) => {
1606 symbol_name != metadata_symbol_name
1614 fn encode_dylib_dependency_formats(&mut self) -> LazySeq<Option<LinkagePreference>> {
1615 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateType::Dylib) {
1617 self.lazy_seq(arr.iter().map(|slot| {
1619 Linkage::NotLinked |
1620 Linkage::IncludedFromDylib => None,
1622 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1623 Linkage::Static => Some(LinkagePreference::RequireStatic),
1627 None => LazySeq::empty(),
1631 fn encode_info_for_foreign_item(&mut self,
1632 (def_id, nitem): (DefId, &hir::ForeignItem))
1636 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1638 let kind = match nitem.node {
1639 hir::ForeignItemKind::Fn(_, ref names, _) => {
1641 constness: hir::Constness::NotConst,
1642 arg_names: self.encode_fn_arg_names(names),
1643 sig: self.lazy(&tcx.fn_sig(def_id)),
1645 EntryKind::ForeignFn(self.lazy(&data))
1647 hir::ForeignItemKind::Static(_, hir::MutMutable) => EntryKind::ForeignMutStatic,
1648 hir::ForeignItemKind::Static(_, hir::MutImmutable) => EntryKind::ForeignImmStatic,
1649 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1654 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, tcx)),
1655 span: self.lazy(&nitem.span),
1656 attributes: self.encode_attributes(&nitem.attrs),
1657 children: LazySeq::empty(),
1658 stability: self.encode_stability(def_id),
1659 deprecation: self.encode_deprecation(def_id),
1661 ty: Some(self.encode_item_type(def_id)),
1662 inherent_impls: LazySeq::empty(),
1663 variances: match nitem.node {
1664 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1665 _ => LazySeq::empty(),
1667 generics: Some(self.encode_generics(def_id)),
1668 predicates: Some(self.encode_predicates(def_id)),
1669 predicates_defined_on: None,
1676 impl Visitor<'tcx> for EncodeContext<'tcx> {
1677 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1678 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1680 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1681 intravisit::walk_expr(self, ex);
1682 self.encode_info_for_expr(ex);
1684 fn visit_item(&mut self, item: &'tcx hir::Item) {
1685 intravisit::walk_item(self, item);
1686 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1688 hir::ItemKind::ExternCrate(_) |
1689 hir::ItemKind::Use(..) => {} // ignore these
1690 _ => self.record(def_id, EncodeContext::encode_info_for_item, (def_id, item)),
1692 self.encode_addl_info_for_item(item);
1694 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1695 intravisit::walk_foreign_item(self, ni);
1696 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1698 EncodeContext::encode_info_for_foreign_item,
1701 fn visit_variant(&mut self,
1702 v: &'tcx hir::Variant,
1703 g: &'tcx hir::Generics,
1705 intravisit::walk_variant(self, v, g, id);
1707 if let Some(ref discr) = v.disr_expr {
1708 let def_id = self.tcx.hir().local_def_id(discr.hir_id);
1709 self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id);
1712 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1713 intravisit::walk_generics(self, generics);
1714 self.encode_info_for_generics(generics);
1716 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1717 intravisit::walk_ty(self, ty);
1718 self.encode_info_for_ty(ty);
1720 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1721 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1722 self.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def);
1726 impl EncodeContext<'tcx> {
1727 fn encode_fields(&mut self, adt_def_id: DefId) {
1728 let def = self.tcx.adt_def(adt_def_id);
1729 for (variant_index, variant) in def.variants.iter_enumerated() {
1730 for (field_index, field) in variant.fields.iter().enumerate() {
1731 self.record(field.did,
1732 EncodeContext::encode_field,
1733 (adt_def_id, variant_index, field_index));
1738 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1739 for param in &generics.params {
1740 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1742 GenericParamKind::Lifetime { .. } => continue,
1743 GenericParamKind::Type { ref default, .. } => {
1746 EncodeContext::encode_info_for_ty_param,
1747 (def_id, default.is_some()),
1750 GenericParamKind::Const { .. } => {
1751 self.record(def_id, EncodeContext::encode_info_for_const_param, def_id);
1757 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1759 hir::TyKind::Array(_, ref length) => {
1760 let def_id = self.tcx.hir().local_def_id(length.hir_id);
1761 self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id);
1767 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1769 hir::ExprKind::Closure(..) => {
1770 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1771 self.record(def_id, EncodeContext::encode_info_for_closure, def_id);
1777 /// In some cases, along with the item itself, we also
1778 /// encode some sub-items. Usually we want some info from the item
1779 /// so it's easier to do that here then to wait until we would encounter
1780 /// normally in the visitor walk.
1781 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1782 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1784 hir::ItemKind::Static(..) |
1785 hir::ItemKind::Const(..) |
1786 hir::ItemKind::Fn(..) |
1787 hir::ItemKind::Mod(..) |
1788 hir::ItemKind::ForeignMod(..) |
1789 hir::ItemKind::GlobalAsm(..) |
1790 hir::ItemKind::ExternCrate(..) |
1791 hir::ItemKind::Use(..) |
1792 hir::ItemKind::TyAlias(..) |
1793 hir::ItemKind::OpaqueTy(..) |
1794 hir::ItemKind::TraitAlias(..) => {
1795 // no sub-item recording needed in these cases
1797 hir::ItemKind::Enum(..) => {
1798 self.encode_fields(def_id);
1800 let def = self.tcx.adt_def(def_id);
1801 for (i, variant) in def.variants.iter_enumerated() {
1802 self.record(variant.def_id,
1803 EncodeContext::encode_enum_variant_info,
1806 if let Some(ctor_def_id) = variant.ctor_def_id {
1807 self.record(ctor_def_id,
1808 EncodeContext::encode_enum_variant_ctor,
1813 hir::ItemKind::Struct(ref struct_def, _) => {
1814 self.encode_fields(def_id);
1816 // If the struct has a constructor, encode it.
1817 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1818 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1819 self.record(ctor_def_id,
1820 EncodeContext::encode_struct_ctor,
1821 (def_id, ctor_def_id));
1824 hir::ItemKind::Union(..) => {
1825 self.encode_fields(def_id);
1827 hir::ItemKind::Impl(..) => {
1828 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1829 self.record(trait_item_def_id,
1830 EncodeContext::encode_info_for_impl_item,
1834 hir::ItemKind::Trait(..) => {
1835 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1836 self.record(item_def_id,
1837 EncodeContext::encode_info_for_trait_item,
1845 struct ImplVisitor<'tcx> {
1847 impls: FxHashMap<DefId, Vec<DefIndex>>,
1850 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1851 fn visit_item(&mut self, item: &hir::Item) {
1852 if let hir::ItemKind::Impl(..) = item.node {
1853 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1854 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1856 .entry(trait_ref.def_id)
1858 .push(impl_id.index);
1863 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1865 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1866 // handled in `visit_item` above
1870 // NOTE(eddyb) The following comment was preserved for posterity, even
1871 // though it's no longer relevant as EBML (which uses nested & tagged
1872 // "documents") was replaced with a scheme that can't go out of bounds.
1874 // And here we run into yet another obscure archive bug: in which metadata
1875 // loaded from archives may have trailing garbage bytes. Awhile back one of
1876 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1877 // and opt) by having ebml generate an out-of-bounds panic when looking at
1880 // Upon investigation it turned out that the metadata file inside of an rlib
1881 // (and ar archive) was being corrupted. Some compilations would generate a
1882 // metadata file which would end in a few extra bytes, while other
1883 // compilations would not have these extra bytes appended to the end. These
1884 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1885 // being interpreted causing the out-of-bounds.
1887 // The root cause of why these extra bytes were appearing was never
1888 // discovered, and in the meantime the solution we're employing is to insert
1889 // the length of the metadata to the start of the metadata. Later on this
1890 // will allow us to slice the metadata to the precise length that we just
1891 // generated regardless of trailing bytes that end up in it.
1893 pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1894 let mut encoder = opaque::Encoder::new(vec![]);
1895 encoder.emit_raw_bytes(METADATA_HEADER);
1897 // Will be filled with the root position after encoding everything.
1898 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1900 // Since encoding metadata is not in a query, and nothing is cached,
1901 // there's no need to do dep-graph tracking for any of it.
1902 let (root, mut result) = tcx.dep_graph.with_ignore(move || {
1903 let mut ecx = EncodeContext {
1906 entries_index: Index::new(tcx.hir().definitions().def_index_count()),
1907 lazy_state: LazyState::NoNode,
1908 type_shorthands: Default::default(),
1909 predicate_shorthands: Default::default(),
1910 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1911 interpret_allocs: Default::default(),
1912 interpret_allocs_inverse: Default::default(),
1915 // Encode the rustc version string in a predictable location.
1916 rustc_version().encode(&mut ecx).unwrap();
1918 // Encode all the entries and extra information in the crate,
1919 // culminating in the `CrateRoot` which points to all of it.
1920 let root = ecx.encode_crate_root();
1921 (root, ecx.opaque.into_inner())
1924 // Encode the root position.
1925 let header = METADATA_HEADER.len();
1926 let pos = root.position;
1927 result[header + 0] = (pos >> 24) as u8;
1928 result[header + 1] = (pos >> 16) as u8;
1929 result[header + 2] = (pos >> 8) as u8;
1930 result[header + 3] = (pos >> 0) as u8;
1932 EncodedMetadata { raw_data: result }
1935 pub fn get_repr_options(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1936 let ty = tcx.type_of(did);
1938 ty::Adt(ref def, _) => return def.repr,
1939 _ => bug!("{} is not an ADT", ty),