1 use crate::index::Index;
2 use crate::index_builder::{FromId, IndexBuilder, Untracked};
3 use crate::isolated_encoder::IsolatedEncoder;
6 use rustc::middle::cstore::{LinkagePreference, NativeLibrary,
7 EncodedMetadata, ForeignModule};
8 use rustc::hir::def::CtorKind;
9 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LocalDefId, LOCAL_CRATE};
10 use rustc::hir::GenericParamKind;
11 use rustc::hir::map::definitions::DefPathTable;
12 use rustc_data_structures::fingerprint::Fingerprint;
13 use rustc::middle::dependency_format::Linkage;
14 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel,
15 metadata_symbol_name};
16 use rustc::middle::lang_items;
17 use rustc::mir::{self, interpret};
18 use rustc::traits::specialization_graph;
19 use rustc::ty::{self, Ty, TyCtxt, ReprOptions, SymbolName};
20 use rustc::ty::codec::{self as ty_codec, TyEncoder};
21 use rustc::ty::layout::VariantIdx;
23 use rustc::session::config::{self, CrateType};
24 use rustc::util::nodemap::FxHashMap;
26 use rustc_data_structures::stable_hasher::StableHasher;
27 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
31 use rustc_data_structures::sync::Lrc;
35 use syntax::source_map::Spanned;
36 use syntax::symbol::keywords;
37 use syntax_pos::{self, hygiene, FileName, SourceFile, Span};
38 use log::{debug, trace};
40 use rustc::hir::{self, PatKind};
41 use rustc::hir::itemlikevisit::ItemLikeVisitor;
42 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
43 use rustc::hir::intravisit;
45 pub struct EncodeContext<'a, 'tcx: 'a> {
46 opaque: opaque::Encoder,
47 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
49 lazy_state: LazyState,
50 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
51 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
53 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
54 interpret_allocs_inverse: Vec<interpret::AllocId>,
56 // This is used to speed up Span encoding.
57 source_file_cache: Lrc<SourceFile>,
60 macro_rules! encoder_methods {
61 ($($name:ident($ty:ty);)*) => {
62 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
63 self.opaque.$name(value)
68 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
69 type Error = <opaque::Encoder as Encoder>::Error;
71 fn emit_unit(&mut self) -> Result<(), Self::Error> {
98 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
99 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
100 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
104 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
105 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
106 self.emit_usize(seq.len)?;
110 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
114 impl<'a, 'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'a, 'tcx> {
116 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
117 self.emit_u32(cnum.as_u32())
121 impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
123 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
134 impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
136 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
137 self.emit_u32(def_index.as_raw_u32())
141 impl<'a, 'tcx> SpecializedEncoder<Span> for EncodeContext<'a, 'tcx> {
142 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
144 return TAG_INVALID_SPAN.encode(self)
147 let span = span.data();
149 // The Span infrastructure should make sure that this invariant holds:
150 debug_assert!(span.lo <= span.hi);
152 if !self.source_file_cache.contains(span.lo) {
153 let source_map = self.tcx.sess.source_map();
154 let source_file_index = source_map.lookup_source_file_idx(span.lo);
155 self.source_file_cache = source_map.files()[source_file_index].clone();
158 if !self.source_file_cache.contains(span.hi) {
159 // Unfortunately, macro expansion still sometimes generates Spans
160 // that malformed in this way.
161 return TAG_INVALID_SPAN.encode(self)
164 TAG_VALID_SPAN.encode(self)?;
165 span.lo.encode(self)?;
167 // Encode length which is usually less than span.hi and profits more
168 // from the variable-length integer encoding that we use.
169 let len = span.hi - span.lo;
172 // Don't encode the expansion context.
176 impl<'a, 'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'a, 'tcx> {
178 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
179 self.specialized_encode(&def_id.to_def_id())
183 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
184 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
185 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
189 impl<'a, 'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'a, 'tcx> {
190 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
191 use std::collections::hash_map::Entry;
192 let index = match self.interpret_allocs.entry(*alloc_id) {
193 Entry::Occupied(e) => *e.get(),
194 Entry::Vacant(e) => {
195 let idx = self.interpret_allocs_inverse.len();
196 self.interpret_allocs_inverse.push(*alloc_id);
206 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
207 fn specialized_encode(&mut self,
208 predicates: &ty::GenericPredicates<'tcx>)
209 -> Result<(), Self::Error> {
210 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
214 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
215 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
216 f.encode_opaque(&mut self.opaque)
220 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
221 for EncodeContext<'a, 'tcx> {
222 fn specialized_encode(&mut self,
223 _: &mir::ClearCrossCrate<T>)
224 -> Result<(), Self::Error> {
229 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
230 fn position(&self) -> usize {
231 self.opaque.position()
235 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
237 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
238 assert_eq!(self.lazy_state, LazyState::NoNode);
239 let pos = self.position();
240 self.lazy_state = LazyState::NodeStart(pos);
241 let r = f(self, pos);
242 self.lazy_state = LazyState::NoNode;
246 fn emit_lazy_distance(&mut self,
249 -> Result<(), <Self as Encoder>::Error> {
250 let min_end = position + min_size;
251 let distance = match self.lazy_state {
252 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
253 LazyState::NodeStart(start) => {
254 assert!(min_end <= start);
257 LazyState::Previous(last_min_end) => {
259 last_min_end <= position,
260 "make sure that the calls to `lazy*` \
261 are in the same order as the metadata fields",
263 position - last_min_end
266 self.lazy_state = LazyState::Previous(min_end);
267 self.emit_usize(distance)
270 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
271 self.emit_node(|ecx, pos| {
272 value.encode(ecx).unwrap();
274 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
275 Lazy::with_position(pos)
279 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
280 where I: IntoIterator<Item = T>,
283 self.emit_node(|ecx, pos| {
284 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
286 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
287 LazySeq::with_position_and_length(pos, len)
291 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
292 where I: IntoIterator<Item = &'b T>,
295 self.emit_node(|ecx, pos| {
296 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
298 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
299 LazySeq::with_position_and_length(pos, len)
303 // Encodes something that corresponds to a single DepNode::GlobalMetaData
304 // and registers the Fingerprint in the `metadata_hashes` map.
305 pub fn tracked<'x, DATA, R>(&'x mut self,
306 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
309 op(&mut IsolatedEncoder::new(self), data)
312 fn encode_info_for_items(&mut self) -> Index {
313 let krate = self.tcx.hir().krate();
314 let mut index = IndexBuilder::new(self);
315 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public };
316 index.record(DefId::local(CRATE_DEF_INDEX),
317 IsolatedEncoder::encode_info_for_mod,
318 FromId(hir::CRATE_HIR_ID, (&krate.module, &krate.attrs, &vis)));
319 let mut visitor = EncodeVisitor { index };
320 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
321 for macro_def in &krate.exported_macros {
322 visitor.visit_macro_def(macro_def);
324 visitor.index.into_items()
327 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
328 let definitions = self.tcx.hir().definitions();
329 self.lazy(definitions.def_path_table())
332 fn encode_source_map(&mut self) -> LazySeq<syntax_pos::SourceFile> {
333 let source_map = self.tcx.sess.source_map();
334 let all_source_files = source_map.files();
336 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
338 let adapted = all_source_files.iter()
339 .filter(|source_file| {
340 // No need to re-export imported source_files, as any downstream
341 // crate will import them from their original source.
342 !source_file.is_imported()
345 match source_file.name {
346 // This path of this SourceFile has been modified by
347 // path-remapping, so we use it verbatim (and avoid
348 // cloning the whole map in the process).
349 _ if source_file.name_was_remapped => source_file.clone(),
351 // Otherwise expand all paths to absolute paths because
352 // any relative paths are potentially relative to a
354 FileName::Real(ref name) => {
355 let mut adapted = (**source_file).clone();
356 adapted.name = Path::new(&working_dir).join(name).into();
357 adapted.name_hash = {
358 let mut hasher: StableHasher<u128> = StableHasher::new();
359 adapted.name.hash(&mut hasher);
365 // expanded code, not from a file
366 _ => source_file.clone(),
369 .collect::<Vec<_>>();
371 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
374 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
375 let mut i = self.position();
377 let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
378 let dylib_dependency_formats = self.tracked(
379 IsolatedEncoder::encode_dylib_dependency_formats,
381 let dep_bytes = self.position() - i;
383 // Encode the lib features.
385 let lib_features = self.tracked(IsolatedEncoder::encode_lib_features, ());
386 let lib_feature_bytes = self.position() - i;
388 // Encode the language items.
390 let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
391 let lang_items_missing = self.tracked(
392 IsolatedEncoder::encode_lang_items_missing,
394 let lang_item_bytes = self.position() - i;
396 // Encode the native libraries used
398 let native_libraries = self.tracked(
399 IsolatedEncoder::encode_native_libraries,
401 let native_lib_bytes = self.position() - i;
403 let foreign_modules = self.tracked(
404 IsolatedEncoder::encode_foreign_modules,
409 let source_map = self.encode_source_map();
410 let source_map_bytes = self.position() - i;
412 // Encode DefPathTable
414 let def_path_table = self.encode_def_path_table();
415 let def_path_table_bytes = self.position() - i;
417 // Encode the def IDs of impls, for coherence checking.
419 let impls = self.tracked(IsolatedEncoder::encode_impls, ());
420 let impl_bytes = self.position() - i;
422 // Encode exported symbols info.
424 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
425 let exported_symbols = self.tracked(
426 IsolatedEncoder::encode_exported_symbols,
428 let exported_symbols_bytes = self.position() - i;
434 let items = self.encode_info_for_items();
435 let item_bytes = self.position() - i;
437 // Encode the allocation index
438 let interpret_alloc_index = {
439 let mut interpret_alloc_index = Vec::new();
441 trace!("beginning to encode alloc ids");
443 let new_n = self.interpret_allocs_inverse.len();
444 // if we have found new ids, serialize those, too
449 trace!("encoding {} further alloc ids", new_n - n);
450 for idx in n..new_n {
451 let id = self.interpret_allocs_inverse[idx];
452 let pos = self.position() as u32;
453 interpret_alloc_index.push(pos);
454 interpret::specialized_encode_alloc_id(
462 self.lazy_seq(interpret_alloc_index)
467 let index = items.write_index(&mut self.opaque);
468 let index_bytes = self.position() - i;
470 let attrs = tcx.hir().krate_attrs();
471 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
472 let has_default_lib_allocator = attr::contains_name(&attrs, "default_lib_allocator");
473 let has_global_allocator = *tcx.sess.has_global_allocator.get();
474 let has_panic_handler = *tcx.sess.has_panic_handler.try_get().unwrap_or(&false);
476 let root = self.lazy(&CrateRoot {
477 name: tcx.crate_name(LOCAL_CRATE),
478 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
479 triple: tcx.sess.opts.target_triple.clone(),
480 hash: tcx.crate_hash(LOCAL_CRATE),
481 disambiguator: tcx.sess.local_crate_disambiguator(),
482 panic_strategy: tcx.sess.panic_strategy(),
483 edition: hygiene::default_edition(),
484 has_global_allocator: has_global_allocator,
485 has_panic_handler: has_panic_handler,
486 has_default_lib_allocator: has_default_lib_allocator,
487 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
488 proc_macro_decls_static: if is_proc_macro {
489 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
494 proc_macro_stability: if is_proc_macro {
495 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).map(|stab| stab.clone())
499 compiler_builtins: attr::contains_name(&attrs, "compiler_builtins"),
500 needs_allocator: attr::contains_name(&attrs, "needs_allocator"),
501 needs_panic_runtime: attr::contains_name(&attrs, "needs_panic_runtime"),
502 no_builtins: attr::contains_name(&attrs, "no_builtins"),
503 panic_runtime: attr::contains_name(&attrs, "panic_runtime"),
504 profiler_runtime: attr::contains_name(&attrs, "profiler_runtime"),
505 sanitizer_runtime: attr::contains_name(&attrs, "sanitizer_runtime"),
508 dylib_dependency_formats,
518 interpret_alloc_index,
522 let total_bytes = self.position();
524 if self.tcx.sess.meta_stats() {
525 let mut zero_bytes = 0;
526 for e in self.opaque.data.iter() {
532 println!("metadata stats:");
533 println!(" dep bytes: {}", dep_bytes);
534 println!(" lib feature bytes: {}", lib_feature_bytes);
535 println!(" lang item bytes: {}", lang_item_bytes);
536 println!(" native bytes: {}", native_lib_bytes);
537 println!(" source_map bytes: {}", source_map_bytes);
538 println!(" impl bytes: {}", impl_bytes);
539 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
540 println!(" def-path table bytes: {}", def_path_table_bytes);
541 println!(" item bytes: {}", item_bytes);
542 println!(" index bytes: {}", index_bytes);
543 println!(" zero bytes: {}", zero_bytes);
544 println!(" total bytes: {}", total_bytes);
551 // These are methods for encoding various things. They are meant to be used with
552 // IndexBuilder::record() and EncodeContext::tracked(). They actually
553 // would not have to be methods of IsolatedEncoder (free standing functions
554 // taking IsolatedEncoder as first argument would be just fine) but by making
555 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
556 // clause again and again.
557 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
558 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
559 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
561 self.lazy_seq_from_slice(&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!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
571 /// Encode data for the given variant of the given ADT. The
572 /// index of the variant is untracked: this is ok because we
573 /// will have to lookup the adt-def by its id, and that gives us
574 /// the right to access any information in the adt-def (including,
575 /// e.g., the length of the various vectors).
576 fn encode_enum_variant_info(
578 (enum_did, Untracked(index)): (DefId, Untracked<VariantIdx>),
581 let def = tcx.adt_def(enum_did);
582 let variant = &def.variants[index];
583 let def_id = variant.def_id;
584 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
586 let data = VariantData {
587 ctor_kind: variant.ctor_kind,
588 discr: variant.discr,
589 // FIXME(eddyb) deduplicate these with `encode_enum_variant_ctor`.
590 ctor: variant.ctor_def_id.map(|did| did.index),
591 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
592 variant.ctor_def_id.map(|ctor_def_id| self.lazy(&tcx.fn_sig(ctor_def_id)))
598 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
599 let enum_vis = &tcx.hir().expect_item_by_hir_id(enum_id).vis;
602 kind: EntryKind::Variant(self.lazy(&data)),
603 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
604 span: self.lazy(&tcx.def_span(def_id)),
605 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
606 children: self.lazy_seq(variant.fields.iter().map(|f| {
607 assert!(f.did.is_local());
610 stability: self.encode_stability(def_id),
611 deprecation: self.encode_deprecation(def_id),
613 ty: Some(self.encode_item_type(def_id)),
614 inherent_impls: LazySeq::empty(),
615 variances: if variant.ctor_kind == CtorKind::Fn {
616 self.encode_variances_of(def_id)
620 generics: Some(self.encode_generics(def_id)),
621 predicates: Some(self.encode_predicates(def_id)),
622 predicates_defined_on: None,
624 mir: self.encode_optimized_mir(def_id),
628 /// Encode the constructor for the given variant of the given ADT. See
629 /// `encode_enum_variant_info` for an explanation about why the index is untracked.
630 fn encode_enum_variant_ctor(
632 (enum_did, Untracked(index)): (DefId, Untracked<VariantIdx>),
635 let def = tcx.adt_def(enum_did);
636 let variant = &def.variants[index];
637 let def_id = variant.ctor_def_id.unwrap();
638 debug!("IsolatedEncoder::encode_enum_variant_ctor({:?})", def_id);
640 let data = VariantData {
641 ctor_kind: variant.ctor_kind,
642 discr: variant.discr,
643 ctor: Some(def_id.index),
644 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
645 Some(self.lazy(&tcx.fn_sig(def_id)))
651 // Variant constructors have the same visibility as the parent enums, unless marked as
652 // non-exhaustive, in which case they are lowered to `pub(crate)`.
653 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
654 let enum_vis = &tcx.hir().expect_item_by_hir_id(enum_id).vis;
655 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
656 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
657 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
661 kind: EntryKind::Variant(self.lazy(&data)),
662 visibility: self.lazy(&ctor_vis),
663 span: self.lazy(&tcx.def_span(def_id)),
664 attributes: LazySeq::empty(),
665 children: LazySeq::empty(),
666 stability: self.encode_stability(def_id),
667 deprecation: self.encode_deprecation(def_id),
669 ty: Some(self.encode_item_type(def_id)),
670 inherent_impls: LazySeq::empty(),
671 variances: if variant.ctor_kind == CtorKind::Fn {
672 self.encode_variances_of(def_id)
676 generics: Some(self.encode_generics(def_id)),
677 predicates: Some(self.encode_predicates(def_id)),
678 predicates_defined_on: None,
680 mir: self.encode_optimized_mir(def_id),
684 fn encode_info_for_mod(&mut self,
685 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
690 let def_id = tcx.hir().local_def_id_from_hir_id(id);
691 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
694 reexports: match tcx.module_exports(def_id) {
695 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
696 _ => LazySeq::empty(),
701 kind: EntryKind::Mod(self.lazy(&data)),
702 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
703 span: self.lazy(&tcx.def_span(def_id)),
704 attributes: self.encode_attributes(attrs),
705 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
706 tcx.hir().local_def_id_from_hir_id(item_id.id).index
708 stability: self.encode_stability(def_id),
709 deprecation: self.encode_deprecation(def_id),
712 inherent_impls: LazySeq::empty(),
713 variances: LazySeq::empty(),
716 predicates_defined_on: None,
722 /// Encode data for the given field of the given variant of the
723 /// given ADT. The indices of the variant/field are untracked:
724 /// this is ok because we will have to lookup the adt-def by its
725 /// id, and that gives us the right to access any information in
726 /// the adt-def (including, e.g., the length of the various
728 fn encode_field(&mut self,
729 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
730 Untracked<(VariantIdx,
734 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
735 let field = &variant.fields[field_index];
737 let def_id = field.did;
738 debug!("IsolatedEncoder::encode_field({:?})", def_id);
740 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
741 let variant_data = tcx.hir().expect_variant_data(variant_id);
744 kind: EntryKind::Field,
745 visibility: self.lazy(&field.vis),
746 span: self.lazy(&tcx.def_span(def_id)),
747 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
748 children: LazySeq::empty(),
749 stability: self.encode_stability(def_id),
750 deprecation: self.encode_deprecation(def_id),
752 ty: Some(self.encode_item_type(def_id)),
753 inherent_impls: LazySeq::empty(),
754 variances: LazySeq::empty(),
755 generics: Some(self.encode_generics(def_id)),
756 predicates: Some(self.encode_predicates(def_id)),
757 predicates_defined_on: None,
763 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
764 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
766 let adt_def = tcx.adt_def(adt_def_id);
767 let variant = adt_def.non_enum_variant();
769 let data = VariantData {
770 ctor_kind: variant.ctor_kind,
771 discr: variant.discr,
772 ctor: Some(def_id.index),
773 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
774 Some(self.lazy(&tcx.fn_sig(def_id)))
780 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
781 let struct_vis = &tcx.hir().expect_item_by_hir_id(struct_id).vis;
782 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
783 for field in &variant.fields {
784 if ctor_vis.is_at_least(field.vis, tcx) {
785 ctor_vis = field.vis;
789 // If the structure is marked as non_exhaustive then lower the visibility
790 // to within the crate.
791 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
792 ctor_vis == ty::Visibility::Public
794 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
797 let repr_options = get_repr_options(tcx, adt_def_id);
800 kind: EntryKind::Struct(self.lazy(&data), repr_options),
801 visibility: self.lazy(&ctor_vis),
802 span: self.lazy(&tcx.def_span(def_id)),
803 attributes: LazySeq::empty(),
804 children: LazySeq::empty(),
805 stability: self.encode_stability(def_id),
806 deprecation: self.encode_deprecation(def_id),
808 ty: Some(self.encode_item_type(def_id)),
809 inherent_impls: LazySeq::empty(),
810 variances: if variant.ctor_kind == CtorKind::Fn {
811 self.encode_variances_of(def_id)
815 generics: Some(self.encode_generics(def_id)),
816 predicates: Some(self.encode_predicates(def_id)),
817 predicates_defined_on: None,
819 mir: self.encode_optimized_mir(def_id),
823 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
824 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
826 self.lazy(tcx.generics_of(def_id))
829 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
830 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
832 self.lazy(&tcx.predicates_of(def_id))
835 fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
836 debug!("IsolatedEncoder::encode_predicates_defined_on({:?})", def_id);
838 self.lazy(&tcx.predicates_defined_on(def_id))
841 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
842 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
845 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
846 let ast_item = tcx.hir().expect_trait_item(hir_id);
847 let trait_item = tcx.associated_item(def_id);
849 let container = match trait_item.defaultness {
850 hir::Defaultness::Default { has_value: true } =>
851 AssociatedContainer::TraitWithDefault,
852 hir::Defaultness::Default { has_value: false } =>
853 AssociatedContainer::TraitRequired,
854 hir::Defaultness::Final =>
855 span_bug!(ast_item.span, "traits cannot have final items"),
858 let kind = match trait_item.kind {
859 ty::AssociatedKind::Const => {
861 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
862 self.const_qualif(0, body)
864 ConstQualif { mir: 0, ast_promotable: false }
868 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
869 let rendered_const = self.lazy(&RenderedConst(rendered));
871 EntryKind::AssociatedConst(container, const_qualif, rendered_const)
873 ty::AssociatedKind::Method => {
874 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
875 let arg_names = match *m {
876 hir::TraitMethod::Required(ref names) => {
877 self.encode_fn_arg_names(names)
879 hir::TraitMethod::Provided(body) => {
880 self.encode_fn_arg_names_for_body(body)
884 constness: hir::Constness::NotConst,
886 sig: self.lazy(&tcx.fn_sig(def_id)),
891 EntryKind::Method(self.lazy(&MethodData {
894 has_self: trait_item.method_has_self_argument,
897 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
898 ty::AssociatedKind::Existential =>
899 span_bug!(ast_item.span, "existential type in trait"),
904 visibility: self.lazy(&trait_item.vis),
905 span: self.lazy(&ast_item.span),
906 attributes: self.encode_attributes(&ast_item.attrs),
907 children: LazySeq::empty(),
908 stability: self.encode_stability(def_id),
909 deprecation: self.encode_deprecation(def_id),
911 ty: match trait_item.kind {
912 ty::AssociatedKind::Const |
913 ty::AssociatedKind::Method => {
914 Some(self.encode_item_type(def_id))
916 ty::AssociatedKind::Type => {
917 if trait_item.defaultness.has_value() {
918 Some(self.encode_item_type(def_id))
923 ty::AssociatedKind::Existential => unreachable!(),
925 inherent_impls: LazySeq::empty(),
926 variances: if trait_item.kind == ty::AssociatedKind::Method {
927 self.encode_variances_of(def_id)
931 generics: Some(self.encode_generics(def_id)),
932 predicates: Some(self.encode_predicates(def_id)),
933 predicates_defined_on: None,
935 mir: self.encode_optimized_mir(def_id),
939 fn metadata_output_only(&self) -> bool {
940 // MIR optimisation can be skipped when we're just interested in the metadata.
941 !self.tcx.sess.opts.output_types.should_codegen()
944 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
945 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
946 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
948 ConstQualif { mir, ast_promotable }
951 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
952 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
955 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
956 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
957 let impl_item = self.tcx.associated_item(def_id);
959 let container = match impl_item.defaultness {
960 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
961 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
962 hir::Defaultness::Default { has_value: false } =>
963 span_bug!(ast_item.span, "impl items always have values (currently)"),
966 let kind = match impl_item.kind {
967 ty::AssociatedKind::Const => {
968 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
969 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
971 EntryKind::AssociatedConst(container,
972 self.const_qualif(mir, body_id),
973 self.encode_rendered_const_for_body(body_id))
978 ty::AssociatedKind::Method => {
979 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
981 constness: sig.header.constness,
982 arg_names: self.encode_fn_arg_names_for_body(body),
983 sig: self.lazy(&tcx.fn_sig(def_id)),
988 EntryKind::Method(self.lazy(&MethodData {
991 has_self: impl_item.method_has_self_argument,
994 ty::AssociatedKind::Existential => EntryKind::AssociatedExistential(container),
995 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
999 match ast_item.node {
1000 hir::ImplItemKind::Const(..) => true,
1001 hir::ImplItemKind::Method(ref sig, _) => {
1002 let generics = self.tcx.generics_of(def_id);
1003 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
1004 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1005 !self.metadata_output_only();
1006 let is_const_fn = sig.header.constness == hir::Constness::Const;
1007 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1008 needs_inline || is_const_fn || always_encode_mir
1010 hir::ImplItemKind::Existential(..) |
1011 hir::ImplItemKind::Type(..) => false,
1016 visibility: self.lazy(&impl_item.vis),
1017 span: self.lazy(&ast_item.span),
1018 attributes: self.encode_attributes(&ast_item.attrs),
1019 children: LazySeq::empty(),
1020 stability: self.encode_stability(def_id),
1021 deprecation: self.encode_deprecation(def_id),
1023 ty: Some(self.encode_item_type(def_id)),
1024 inherent_impls: LazySeq::empty(),
1025 variances: if impl_item.kind == ty::AssociatedKind::Method {
1026 self.encode_variances_of(def_id)
1030 generics: Some(self.encode_generics(def_id)),
1031 predicates: Some(self.encode_predicates(def_id)),
1032 predicates_defined_on: None,
1034 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
1038 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
1039 -> LazySeq<ast::Name> {
1040 self.tcx.dep_graph.with_ignore(|| {
1041 let body = self.tcx.hir().body(body_id);
1042 self.lazy_seq(body.arguments.iter().map(|arg| {
1043 match arg.pat.node {
1044 PatKind::Binding(_, _, ident, _) => ident.name,
1045 _ => keywords::Invalid.name(),
1051 fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> LazySeq<ast::Name> {
1052 self.lazy_seq(param_names.iter().map(|ident| ident.name))
1055 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
1056 debug!("EntryBuilder::encode_mir({:?})", def_id);
1057 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1058 let mir = self.tcx.optimized_mir(def_id);
1059 Some(self.lazy(&mir))
1065 // Encodes the inherent implementations of a structure, enumeration, or trait.
1066 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1067 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
1068 let implementations = self.tcx.inherent_impls(def_id);
1069 if implementations.is_empty() {
1072 self.lazy_seq(implementations.iter().map(|&def_id| {
1073 assert!(def_id.is_local());
1079 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1080 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
1081 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1084 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1085 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
1086 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1089 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1090 let body = self.tcx.hir().body(body_id);
1091 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1092 let rendered_const = &RenderedConst(rendered);
1093 self.lazy(rendered_const)
1096 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1099 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
1101 let kind = match item.node {
1102 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1103 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1104 hir::ItemKind::Const(_, body_id) => {
1105 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1107 self.const_qualif(mir, body_id),
1108 self.encode_rendered_const_for_body(body_id)
1111 hir::ItemKind::Fn(_, header, .., body) => {
1113 constness: header.constness,
1114 arg_names: self.encode_fn_arg_names_for_body(body),
1115 sig: self.lazy(&tcx.fn_sig(def_id)),
1118 EntryKind::Fn(self.lazy(&data))
1120 hir::ItemKind::Mod(ref m) => {
1121 return self.encode_info_for_mod(FromId(item.hir_id, (m, &item.attrs, &item.vis)));
1123 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1124 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1125 hir::ItemKind::Ty(..) => EntryKind::Type,
1126 hir::ItemKind::Existential(..) => EntryKind::Existential,
1127 hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(tcx, def_id)),
1128 hir::ItemKind::Struct(ref struct_def, _) => {
1129 let variant = tcx.adt_def(def_id).non_enum_variant();
1131 // Encode def_ids for each field and method
1132 // for methods, write all the stuff get_trait_method
1134 let ctor = struct_def.ctor_hir_id()
1135 .map(|ctor_hir_id| tcx.hir().local_def_id_from_hir_id(ctor_hir_id).index);
1137 let repr_options = get_repr_options(tcx, def_id);
1139 EntryKind::Struct(self.lazy(&VariantData {
1140 ctor_kind: variant.ctor_kind,
1141 discr: variant.discr,
1146 hir::ItemKind::Union(..) => {
1147 let variant = tcx.adt_def(def_id).non_enum_variant();
1148 let repr_options = get_repr_options(tcx, def_id);
1150 EntryKind::Union(self.lazy(&VariantData {
1151 ctor_kind: variant.ctor_kind,
1152 discr: variant.discr,
1157 hir::ItemKind::Impl(_, polarity, defaultness, ..) => {
1158 let trait_ref = tcx.impl_trait_ref(def_id);
1159 let parent = if let Some(trait_ref) = trait_ref {
1160 let trait_def = tcx.trait_def(trait_ref.def_id);
1161 trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| {
1163 specialization_graph::Node::Impl(parent) => Some(parent),
1171 // if this is an impl of `CoerceUnsized`, create its
1172 // "unsized info", else just store None
1173 let coerce_unsized_info =
1174 trait_ref.and_then(|t| {
1175 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1176 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1182 let data = ImplData {
1185 parent_impl: parent,
1186 coerce_unsized_info,
1187 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1190 EntryKind::Impl(self.lazy(&data))
1192 hir::ItemKind::Trait(..) => {
1193 let trait_def = tcx.trait_def(def_id);
1194 let data = TraitData {
1195 unsafety: trait_def.unsafety,
1196 paren_sugar: trait_def.paren_sugar,
1197 has_auto_impl: tcx.trait_is_auto(def_id),
1198 is_marker: trait_def.is_marker,
1199 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1202 EntryKind::Trait(self.lazy(&data))
1204 hir::ItemKind::TraitAlias(..) => {
1205 let data = TraitAliasData {
1206 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1209 EntryKind::TraitAlias(self.lazy(&data))
1211 hir::ItemKind::ExternCrate(_) |
1212 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1217 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.hir_id, tcx)),
1218 span: self.lazy(&item.span),
1219 attributes: self.encode_attributes(&item.attrs),
1220 children: match item.node {
1221 hir::ItemKind::ForeignMod(ref fm) => {
1222 self.lazy_seq(fm.items
1224 .map(|foreign_item| tcx.hir().local_def_id_from_hir_id(
1225 foreign_item.hir_id).index))
1227 hir::ItemKind::Enum(..) => {
1228 let def = self.tcx.adt_def(def_id);
1229 self.lazy_seq(def.variants.iter().map(|v| {
1230 assert!(v.def_id.is_local());
1234 hir::ItemKind::Struct(..) |
1235 hir::ItemKind::Union(..) => {
1236 let def = self.tcx.adt_def(def_id);
1237 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1238 assert!(f.did.is_local());
1242 hir::ItemKind::Impl(..) |
1243 hir::ItemKind::Trait(..) => {
1244 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1245 assert!(def_id.is_local());
1249 _ => LazySeq::empty(),
1251 stability: self.encode_stability(def_id),
1252 deprecation: self.encode_deprecation(def_id),
1254 ty: match item.node {
1255 hir::ItemKind::Static(..) |
1256 hir::ItemKind::Const(..) |
1257 hir::ItemKind::Fn(..) |
1258 hir::ItemKind::Ty(..) |
1259 hir::ItemKind::Existential(..) |
1260 hir::ItemKind::Enum(..) |
1261 hir::ItemKind::Struct(..) |
1262 hir::ItemKind::Union(..) |
1263 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1266 inherent_impls: self.encode_inherent_implementations(def_id),
1267 variances: match item.node {
1268 hir::ItemKind::Enum(..) |
1269 hir::ItemKind::Struct(..) |
1270 hir::ItemKind::Union(..) |
1271 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1272 _ => LazySeq::empty(),
1274 generics: match item.node {
1275 hir::ItemKind::Static(..) |
1276 hir::ItemKind::Const(..) |
1277 hir::ItemKind::Fn(..) |
1278 hir::ItemKind::Ty(..) |
1279 hir::ItemKind::Enum(..) |
1280 hir::ItemKind::Struct(..) |
1281 hir::ItemKind::Union(..) |
1282 hir::ItemKind::Impl(..) |
1283 hir::ItemKind::Existential(..) |
1284 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1285 hir::ItemKind::TraitAlias(..) => Some(self.encode_generics(def_id)),
1288 predicates: match item.node {
1289 hir::ItemKind::Static(..) |
1290 hir::ItemKind::Const(..) |
1291 hir::ItemKind::Fn(..) |
1292 hir::ItemKind::Ty(..) |
1293 hir::ItemKind::Enum(..) |
1294 hir::ItemKind::Struct(..) |
1295 hir::ItemKind::Union(..) |
1296 hir::ItemKind::Impl(..) |
1297 hir::ItemKind::Existential(..) |
1298 hir::ItemKind::Trait(..) |
1299 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates(def_id)),
1303 // The only time that `predicates_defined_on` is used (on
1304 // an external item) is for traits, during chalk lowering,
1305 // so only encode it in that case as an efficiency
1306 // hack. (No reason not to expand it in the future if
1308 predicates_defined_on: match item.node {
1309 hir::ItemKind::Trait(..) |
1310 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates_defined_on(def_id)),
1311 _ => None, // not *wrong* for other kinds of items, but not needed
1314 mir: match item.node {
1315 hir::ItemKind::Static(..) => {
1316 self.encode_optimized_mir(def_id)
1318 hir::ItemKind::Const(..) => self.encode_optimized_mir(def_id),
1319 hir::ItemKind::Fn(_, header, ..) => {
1320 let generics = tcx.generics_of(def_id);
1322 (generics.requires_monomorphization(tcx) ||
1323 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1324 !self.metadata_output_only();
1325 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1327 || header.constness == hir::Constness::Const
1328 || always_encode_mir
1330 self.encode_optimized_mir(def_id)
1340 /// Serialize the text of exported macros
1341 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1342 use syntax::print::pprust;
1343 let def_id = self.tcx.hir().local_def_id_from_hir_id(macro_def.hir_id);
1345 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1346 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1347 legacy: macro_def.legacy,
1349 visibility: self.lazy(&ty::Visibility::Public),
1350 span: self.lazy(¯o_def.span),
1351 attributes: self.encode_attributes(¯o_def.attrs),
1352 stability: self.encode_stability(def_id),
1353 deprecation: self.encode_deprecation(def_id),
1355 children: LazySeq::empty(),
1357 inherent_impls: LazySeq::empty(),
1358 variances: LazySeq::empty(),
1361 predicates_defined_on: None,
1366 fn encode_info_for_generic_param(
1369 entry_kind: EntryKind<'tcx>,
1375 visibility: self.lazy(&ty::Visibility::Public),
1376 span: self.lazy(&tcx.def_span(def_id)),
1377 attributes: LazySeq::empty(),
1378 children: LazySeq::empty(),
1381 ty: if encode_type { Some(self.encode_item_type(def_id)) } else { None },
1382 inherent_impls: LazySeq::empty(),
1383 variances: LazySeq::empty(),
1386 predicates_defined_on: None,
1392 fn encode_info_for_ty_param(
1394 (def_id, Untracked(encode_type)): (DefId, Untracked<bool>),
1396 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1397 self.encode_info_for_generic_param(def_id, EntryKind::TypeParam, encode_type)
1400 fn encode_info_for_const_param(
1404 debug!("IsolatedEncoder::encode_info_for_const_param({:?})", def_id);
1405 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true)
1408 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1409 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1412 let tables = self.tcx.typeck_tables_of(def_id);
1413 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1414 let kind = match tables.node_type(hir_id).sty {
1415 ty::Generator(def_id, ..) => {
1416 let layout = self.tcx.generator_layout(def_id);
1417 let data = GeneratorData {
1418 layout: layout.clone(),
1420 EntryKind::Generator(self.lazy(&data))
1423 ty::Closure(def_id, substs) => {
1424 let sig = substs.closure_sig(def_id, self.tcx);
1425 let data = ClosureData { sig: self.lazy(&sig) };
1426 EntryKind::Closure(self.lazy(&data))
1429 _ => bug!("closure that is neither generator nor closure")
1434 visibility: self.lazy(&ty::Visibility::Public),
1435 span: self.lazy(&tcx.def_span(def_id)),
1436 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1437 children: LazySeq::empty(),
1441 ty: Some(self.encode_item_type(def_id)),
1442 inherent_impls: LazySeq::empty(),
1443 variances: LazySeq::empty(),
1444 generics: Some(self.encode_generics(def_id)),
1446 predicates_defined_on: None,
1448 mir: self.encode_optimized_mir(def_id),
1452 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1453 debug!("IsolatedEncoder::encode_info_for_anon_const({:?})", def_id);
1455 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
1456 let body_id = tcx.hir().body_owned_by(id);
1457 let const_data = self.encode_rendered_const_for_body(body_id);
1458 let mir = tcx.mir_const_qualif(def_id).0;
1461 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1462 visibility: self.lazy(&ty::Visibility::Public),
1463 span: self.lazy(&tcx.def_span(def_id)),
1464 attributes: LazySeq::empty(),
1465 children: LazySeq::empty(),
1469 ty: Some(self.encode_item_type(def_id)),
1470 inherent_impls: LazySeq::empty(),
1471 variances: LazySeq::empty(),
1472 generics: Some(self.encode_generics(def_id)),
1473 predicates: Some(self.encode_predicates(def_id)),
1474 predicates_defined_on: None,
1476 mir: self.encode_optimized_mir(def_id),
1480 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1481 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1482 // we rely on the HashStable specialization for [Attribute]
1483 // to properly filter things out.
1484 self.lazy_seq_from_slice(attrs)
1487 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1488 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1489 self.lazy_seq(used_libraries.iter().cloned())
1492 fn encode_foreign_modules(&mut self, _: ()) -> LazySeq<ForeignModule> {
1493 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1494 self.lazy_seq(foreign_modules.iter().cloned())
1497 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1498 let crates = self.tcx.crates();
1500 let mut deps = crates
1503 let dep = CrateDep {
1504 name: self.tcx.original_crate_name(cnum),
1505 hash: self.tcx.crate_hash(cnum),
1506 kind: self.tcx.dep_kind(cnum),
1507 extra_filename: self.tcx.extra_filename(cnum),
1511 .collect::<Vec<_>>();
1513 deps.sort_by_key(|&(cnum, _)| cnum);
1516 // Sanity-check the crate numbers
1517 let mut expected_cnum = 1;
1518 for &(n, _) in &deps {
1519 assert_eq!(n, CrateNum::new(expected_cnum));
1524 // We're just going to write a list of crate 'name-hash-version's, with
1525 // the assumption that they are numbered 1 to n.
1526 // FIXME (#2166): This is not nearly enough to support correct versioning
1527 // but is enough to get transitive crate dependencies working.
1528 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1531 fn encode_lib_features(&mut self, _: ()) -> LazySeq<(ast::Name, Option<ast::Name>)> {
1533 let lib_features = tcx.lib_features();
1534 self.lazy_seq(lib_features.to_vec())
1537 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1539 let lang_items = tcx.lang_items();
1540 let lang_items = lang_items.items().iter();
1541 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1542 if let Some(def_id) = opt_def_id {
1543 if def_id.is_local() {
1544 return Some((def_id.index, i));
1551 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1553 self.lazy_seq_ref(&tcx.lang_items().missing)
1556 /// Encodes an index, mapping each trait to its (local) implementations.
1557 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1558 debug!("IsolatedEncoder::encode_impls()");
1560 let mut visitor = ImplVisitor {
1562 impls: FxHashMap::default(),
1564 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1566 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1568 // Bring everything into deterministic order for hashing
1569 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1570 tcx.def_path_hash(trait_def_id)
1573 let all_impls: Vec<_> = all_impls
1575 .map(|(trait_def_id, mut impls)| {
1576 // Bring everything into deterministic order for hashing
1577 impls.sort_by_cached_key(|&def_index| {
1578 tcx.hir().definitions().def_path_hash(def_index)
1582 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1583 impls: self.lazy_seq_from_slice(&impls[..]),
1588 self.lazy_seq_from_slice(&all_impls[..])
1591 // Encodes all symbols exported from this crate into the metadata.
1593 // This pass is seeded off the reachability list calculated in the
1594 // middle::reachable module but filters out items that either don't have a
1595 // symbol associated with them (they weren't translated) or if they're an FFI
1596 // definition (as that's not defined in this crate).
1597 fn encode_exported_symbols(&mut self,
1598 exported_symbols: &[(ExportedSymbol<'_>, SymbolExportLevel)])
1599 -> EncodedExportedSymbols {
1600 // The metadata symbol name is special. It should not show up in
1601 // downstream crates.
1602 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1604 let lazy_seq = self.lazy_seq(exported_symbols
1606 .filter(|&&(ref exported_symbol, _)| {
1607 match *exported_symbol {
1608 ExportedSymbol::NoDefId(symbol_name) => {
1609 symbol_name != metadata_symbol_name
1616 EncodedExportedSymbols {
1618 position: lazy_seq.position,
1622 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1623 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateType::Dylib) {
1625 self.lazy_seq(arr.iter().map(|slot| {
1627 Linkage::NotLinked |
1628 Linkage::IncludedFromDylib => None,
1630 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1631 Linkage::Static => Some(LinkagePreference::RequireStatic),
1635 None => LazySeq::empty(),
1639 fn encode_info_for_foreign_item(&mut self,
1640 (def_id, nitem): (DefId, &hir::ForeignItem))
1644 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1646 let kind = match nitem.node {
1647 hir::ForeignItemKind::Fn(_, ref names, _) => {
1649 constness: hir::Constness::NotConst,
1650 arg_names: self.encode_fn_arg_names(names),
1651 sig: self.lazy(&tcx.fn_sig(def_id)),
1653 EntryKind::ForeignFn(self.lazy(&data))
1655 hir::ForeignItemKind::Static(_, hir::MutMutable) => EntryKind::ForeignMutStatic,
1656 hir::ForeignItemKind::Static(_, hir::MutImmutable) => EntryKind::ForeignImmStatic,
1657 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1662 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, tcx)),
1663 span: self.lazy(&nitem.span),
1664 attributes: self.encode_attributes(&nitem.attrs),
1665 children: LazySeq::empty(),
1666 stability: self.encode_stability(def_id),
1667 deprecation: self.encode_deprecation(def_id),
1669 ty: Some(self.encode_item_type(def_id)),
1670 inherent_impls: LazySeq::empty(),
1671 variances: match nitem.node {
1672 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1673 _ => LazySeq::empty(),
1675 generics: Some(self.encode_generics(def_id)),
1676 predicates: Some(self.encode_predicates(def_id)),
1677 predicates_defined_on: None,
1684 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1685 index: IndexBuilder<'a, 'b, 'tcx>,
1688 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1689 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1690 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir())
1692 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1693 intravisit::walk_expr(self, ex);
1694 self.index.encode_info_for_expr(ex);
1696 fn visit_item(&mut self, item: &'tcx hir::Item) {
1697 intravisit::walk_item(self, item);
1698 let def_id = self.index.tcx.hir().local_def_id_from_hir_id(item.hir_id);
1700 hir::ItemKind::ExternCrate(_) |
1701 hir::ItemKind::Use(..) => (), // ignore these
1702 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1704 self.index.encode_addl_info_for_item(item);
1706 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1707 intravisit::walk_foreign_item(self, ni);
1708 let def_id = self.index.tcx.hir().local_def_id_from_hir_id(ni.hir_id);
1709 self.index.record(def_id,
1710 IsolatedEncoder::encode_info_for_foreign_item,
1713 fn visit_variant(&mut self,
1714 v: &'tcx hir::Variant,
1715 g: &'tcx hir::Generics,
1717 intravisit::walk_variant(self, v, g, id);
1719 if let Some(ref discr) = v.node.disr_expr {
1720 let def_id = self.index.tcx.hir().local_def_id_from_hir_id(discr.hir_id);
1721 self.index.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1724 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1725 intravisit::walk_generics(self, generics);
1726 self.index.encode_info_for_generics(generics);
1728 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1729 intravisit::walk_ty(self, ty);
1730 self.index.encode_info_for_ty(ty);
1732 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1733 let def_id = self.index.tcx.hir().local_def_id_from_hir_id(macro_def.hir_id);
1734 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1738 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1739 fn encode_fields(&mut self, adt_def_id: DefId) {
1740 let def = self.tcx.adt_def(adt_def_id);
1741 for (variant_index, variant) in def.variants.iter_enumerated() {
1742 for (field_index, field) in variant.fields.iter().enumerate() {
1743 self.record(field.did,
1744 IsolatedEncoder::encode_field,
1745 (adt_def_id, Untracked((variant_index, field_index))));
1750 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1751 for param in &generics.params {
1752 let def_id = self.tcx.hir().local_def_id_from_hir_id(param.hir_id);
1754 GenericParamKind::Lifetime { .. } => continue,
1755 GenericParamKind::Type { ref default, .. } => {
1758 IsolatedEncoder::encode_info_for_ty_param,
1759 (def_id, Untracked(default.is_some())),
1762 GenericParamKind::Const { .. } => {
1763 self.record(def_id, IsolatedEncoder::encode_info_for_const_param, def_id);
1769 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1771 hir::TyKind::Array(_, ref length) => {
1772 let def_id = self.tcx.hir().local_def_id_from_hir_id(length.hir_id);
1773 self.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1779 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1781 hir::ExprKind::Closure(..) => {
1782 let def_id = self.tcx.hir().local_def_id_from_hir_id(expr.hir_id);
1783 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1789 /// In some cases, along with the item itself, we also
1790 /// encode some sub-items. Usually we want some info from the item
1791 /// so it's easier to do that here then to wait until we would encounter
1792 /// normally in the visitor walk.
1793 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1794 let def_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id);
1796 hir::ItemKind::Static(..) |
1797 hir::ItemKind::Const(..) |
1798 hir::ItemKind::Fn(..) |
1799 hir::ItemKind::Mod(..) |
1800 hir::ItemKind::ForeignMod(..) |
1801 hir::ItemKind::GlobalAsm(..) |
1802 hir::ItemKind::ExternCrate(..) |
1803 hir::ItemKind::Use(..) |
1804 hir::ItemKind::Ty(..) |
1805 hir::ItemKind::Existential(..) |
1806 hir::ItemKind::TraitAlias(..) => {
1807 // no sub-item recording needed in these cases
1809 hir::ItemKind::Enum(..) => {
1810 self.encode_fields(def_id);
1812 let def = self.tcx.adt_def(def_id);
1813 for (i, variant) in def.variants.iter_enumerated() {
1814 self.record(variant.def_id,
1815 IsolatedEncoder::encode_enum_variant_info,
1816 (def_id, Untracked(i)));
1818 if let Some(ctor_def_id) = variant.ctor_def_id {
1819 self.record(ctor_def_id,
1820 IsolatedEncoder::encode_enum_variant_ctor,
1821 (def_id, Untracked(i)));
1825 hir::ItemKind::Struct(ref struct_def, _) => {
1826 self.encode_fields(def_id);
1828 // If the struct has a constructor, encode it.
1829 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1830 let ctor_def_id = self.tcx.hir().local_def_id_from_hir_id(ctor_hir_id);
1831 self.record(ctor_def_id,
1832 IsolatedEncoder::encode_struct_ctor,
1833 (def_id, ctor_def_id));
1836 hir::ItemKind::Union(..) => {
1837 self.encode_fields(def_id);
1839 hir::ItemKind::Impl(..) => {
1840 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1841 self.record(trait_item_def_id,
1842 IsolatedEncoder::encode_info_for_impl_item,
1846 hir::ItemKind::Trait(..) => {
1847 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1848 self.record(item_def_id,
1849 IsolatedEncoder::encode_info_for_trait_item,
1857 struct ImplVisitor<'a, 'tcx: 'a> {
1858 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1859 impls: FxHashMap<DefId, Vec<DefIndex>>,
1862 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1863 fn visit_item(&mut self, item: &hir::Item) {
1864 if let hir::ItemKind::Impl(..) = item.node {
1865 let impl_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id);
1866 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1868 .entry(trait_ref.def_id)
1870 .push(impl_id.index);
1875 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1877 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1878 // handled in `visit_item` above
1882 // NOTE(eddyb) The following comment was preserved for posterity, even
1883 // though it's no longer relevant as EBML (which uses nested & tagged
1884 // "documents") was replaced with a scheme that can't go out of bounds.
1886 // And here we run into yet another obscure archive bug: in which metadata
1887 // loaded from archives may have trailing garbage bytes. Awhile back one of
1888 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1889 // and opt) by having ebml generate an out-of-bounds panic when looking at
1892 // Upon investigation it turned out that the metadata file inside of an rlib
1893 // (and ar archive) was being corrupted. Some compilations would generate a
1894 // metadata file which would end in a few extra bytes, while other
1895 // compilations would not have these extra bytes appended to the end. These
1896 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1897 // being interpreted causing the out-of-bounds.
1899 // The root cause of why these extra bytes were appearing was never
1900 // discovered, and in the meantime the solution we're employing is to insert
1901 // the length of the metadata to the start of the metadata. Later on this
1902 // will allow us to slice the metadata to the precise length that we just
1903 // generated regardless of trailing bytes that end up in it.
1905 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
1908 let mut encoder = opaque::Encoder::new(vec![]);
1909 encoder.emit_raw_bytes(METADATA_HEADER);
1911 // Will be filled with the root position after encoding everything.
1912 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1914 let (root, mut result) = {
1915 let mut ecx = EncodeContext {
1918 lazy_state: LazyState::NoNode,
1919 type_shorthands: Default::default(),
1920 predicate_shorthands: Default::default(),
1921 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1922 interpret_allocs: Default::default(),
1923 interpret_allocs_inverse: Default::default(),
1926 // Encode the rustc version string in a predictable location.
1927 rustc_version().encode(&mut ecx).unwrap();
1929 // Encode all the entries and extra information in the crate,
1930 // culminating in the `CrateRoot` which points to all of it.
1931 let root = ecx.encode_crate_root();
1932 (root, ecx.opaque.into_inner())
1935 // Encode the root position.
1936 let header = METADATA_HEADER.len();
1937 let pos = root.position;
1938 result[header + 0] = (pos >> 24) as u8;
1939 result[header + 1] = (pos >> 16) as u8;
1940 result[header + 2] = (pos >> 8) as u8;
1941 result[header + 3] = (pos >> 0) as u8;
1943 EncodedMetadata { raw_data: result }
1946 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1947 let ty = tcx.type_of(did);
1949 ty::Adt(ref def, _) => return def.repr,
1950 _ => bug!("{} is not an ADT", ty),