1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use index_builder::{FromId, IndexBuilder, Untracked};
13 use isolated_encoder::IsolatedEncoder;
16 use rustc::middle::cstore::{LinkMeta, LinkagePreference, NativeLibrary,
17 EncodedMetadata, ForeignModule};
18 use rustc::hir::def::CtorKind;
19 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LocalDefId, LOCAL_CRATE};
20 use rustc::hir::map::definitions::DefPathTable;
21 use rustc::ich::Fingerprint;
22 use rustc::middle::dependency_format::Linkage;
23 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel,
24 metadata_symbol_name};
25 use rustc::middle::lang_items;
26 use rustc::mir::{self, interpret};
27 use rustc::traits::specialization_graph;
28 use rustc::ty::{self, Ty, TyCtxt, ReprOptions, SymbolName};
29 use rustc::ty::codec::{self as ty_codec, TyEncoder};
31 use rustc::session::config::{self, CrateTypeProcMacro};
32 use rustc::util::nodemap::FxHashMap;
34 use rustc_data_structures::stable_hasher::StableHasher;
35 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
39 use rustc_data_structures::sync::Lrc;
41 use syntax::ast::{self, CRATE_NODE_ID};
43 use syntax::codemap::Spanned;
44 use syntax::symbol::keywords;
45 use syntax_pos::{self, hygiene, FileName, FileMap, Span};
47 use rustc::hir::{self, PatKind};
48 use rustc::hir::itemlikevisit::ItemLikeVisitor;
49 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
50 use rustc::hir::intravisit;
52 pub struct EncodeContext<'a, 'tcx: 'a> {
53 opaque: opaque::Encoder,
54 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
55 link_meta: &'a LinkMeta,
57 lazy_state: LazyState,
58 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
59 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
61 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
62 interpret_allocs_inverse: Vec<interpret::AllocId>,
64 // This is used to speed up Span encoding.
65 filemap_cache: Lrc<FileMap>,
68 macro_rules! encoder_methods {
69 ($($name:ident($ty:ty);)*) => {
70 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
71 self.opaque.$name(value)
76 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
77 type Error = <opaque::Encoder as Encoder>::Error;
79 fn emit_nil(&mut self) -> Result<(), Self::Error> {
106 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
107 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
108 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
112 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
113 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
114 self.emit_usize(seq.len)?;
118 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
122 impl<'a, 'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'a, 'tcx> {
124 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
125 self.emit_u32(cnum.as_u32())
129 impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
131 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
142 impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
144 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
145 self.emit_u32(def_index.as_raw_u32())
149 impl<'a, 'tcx> SpecializedEncoder<Span> for EncodeContext<'a, 'tcx> {
150 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
152 return TAG_INVALID_SPAN.encode(self)
155 let span = span.data();
157 // The Span infrastructure should make sure that this invariant holds:
158 debug_assert!(span.lo <= span.hi);
160 if !self.filemap_cache.contains(span.lo) {
161 let codemap = self.tcx.sess.codemap();
162 let filemap_index = codemap.lookup_filemap_idx(span.lo);
163 self.filemap_cache = codemap.files()[filemap_index].clone();
166 if !self.filemap_cache.contains(span.hi) {
167 // Unfortunately, macro expansion still sometimes generates Spans
168 // that malformed in this way.
169 return TAG_INVALID_SPAN.encode(self)
172 TAG_VALID_SPAN.encode(self)?;
173 span.lo.encode(self)?;
175 // Encode length which is usually less than span.hi and profits more
176 // from the variable-length integer encoding that we use.
177 let len = span.hi - span.lo;
180 // Don't encode the expansion context.
184 impl<'a, 'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'a, 'tcx> {
186 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
187 self.specialized_encode(&def_id.to_def_id())
191 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
192 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
193 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
197 impl<'a, 'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'a, 'tcx> {
198 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
199 use std::collections::hash_map::Entry;
200 let index = match self.interpret_allocs.entry(*alloc_id) {
201 Entry::Occupied(e) => *e.get(),
202 Entry::Vacant(e) => {
203 let idx = self.interpret_allocs_inverse.len();
204 self.interpret_allocs_inverse.push(*alloc_id);
214 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
215 fn specialized_encode(&mut self,
216 predicates: &ty::GenericPredicates<'tcx>)
217 -> Result<(), Self::Error> {
218 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
222 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
223 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
224 f.encode_opaque(&mut self.opaque)
228 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
229 for EncodeContext<'a, 'tcx> {
230 fn specialized_encode(&mut self,
231 _: &mir::ClearCrossCrate<T>)
232 -> Result<(), Self::Error> {
237 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
238 fn position(&self) -> usize {
239 self.opaque.position()
243 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
245 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
246 assert_eq!(self.lazy_state, LazyState::NoNode);
247 let pos = self.position();
248 self.lazy_state = LazyState::NodeStart(pos);
249 let r = f(self, pos);
250 self.lazy_state = LazyState::NoNode;
254 fn emit_lazy_distance(&mut self,
257 -> Result<(), <Self as Encoder>::Error> {
258 let min_end = position + min_size;
259 let distance = match self.lazy_state {
260 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
261 LazyState::NodeStart(start) => {
262 assert!(min_end <= start);
265 LazyState::Previous(last_min_end) => {
267 last_min_end <= position,
268 "make sure that the calls to `lazy*` \
269 are in the same order as the metadata fields",
271 position - last_min_end
274 self.lazy_state = LazyState::Previous(min_end);
275 self.emit_usize(distance)
278 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
279 self.emit_node(|ecx, pos| {
280 value.encode(ecx).unwrap();
282 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
283 Lazy::with_position(pos)
287 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
288 where I: IntoIterator<Item = T>,
291 self.emit_node(|ecx, pos| {
292 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
294 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
295 LazySeq::with_position_and_length(pos, len)
299 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
300 where I: IntoIterator<Item = &'b T>,
303 self.emit_node(|ecx, pos| {
304 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
306 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
307 LazySeq::with_position_and_length(pos, len)
311 // Encodes something that corresponds to a single DepNode::GlobalMetaData
312 // and registers the Fingerprint in the `metadata_hashes` map.
313 pub fn tracked<'x, DATA, R>(&'x mut self,
314 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
317 op(&mut IsolatedEncoder::new(self), data)
320 fn encode_info_for_items(&mut self) -> Index {
321 let krate = self.tcx.hir.krate();
322 let mut index = IndexBuilder::new(self);
323 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public };
324 index.record(DefId::local(CRATE_DEF_INDEX),
325 IsolatedEncoder::encode_info_for_mod,
326 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &vis)));
327 let mut visitor = EncodeVisitor { index: index };
328 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
329 for macro_def in &krate.exported_macros {
330 visitor.visit_macro_def(macro_def);
332 visitor.index.into_items()
335 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
336 let definitions = self.tcx.hir.definitions();
337 self.lazy(definitions.def_path_table())
340 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
341 let codemap = self.tcx.sess.codemap();
342 let all_filemaps = codemap.files();
344 let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
346 let adapted = all_filemaps.iter()
348 // No need to re-export imported filemaps, as any downstream
349 // crate will import them from their original source.
350 !filemap.is_imported()
353 // When exporting FileMaps, we expand all paths to absolute
354 // paths because any relative paths are potentially relative to
355 // a wrong directory.
356 // However, if a path has been modified via
357 // `--remap-path-prefix` we assume the user has already set
358 // things up the way they want and don't touch the path values
361 FileName::Real(ref name) => {
362 if filemap.name_was_remapped ||
363 (name.is_relative() && working_dir_was_remapped) {
364 // This path of this FileMap has been modified by
365 // path-remapping, so we use it verbatim (and avoid cloning
366 // the whole map in the process).
369 let mut adapted = (**filemap).clone();
370 adapted.name = Path::new(&working_dir).join(name).into();
371 adapted.name_hash = {
372 let mut hasher: StableHasher<u128> = StableHasher::new();
373 adapted.name.hash(&mut hasher);
379 // expanded code, not from a file
380 _ => filemap.clone(),
383 .collect::<Vec<_>>();
385 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
388 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
389 let mut i = self.position();
391 let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
392 let dylib_dependency_formats = self.tracked(
393 IsolatedEncoder::encode_dylib_dependency_formats,
395 let dep_bytes = self.position() - i;
397 // Encode the language items.
399 let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
400 let lang_items_missing = self.tracked(
401 IsolatedEncoder::encode_lang_items_missing,
403 let lang_item_bytes = self.position() - i;
405 // Encode the native libraries used
407 let native_libraries = self.tracked(
408 IsolatedEncoder::encode_native_libraries,
410 let native_lib_bytes = self.position() - i;
412 let foreign_modules = self.tracked(
413 IsolatedEncoder::encode_foreign_modules,
418 let codemap = self.encode_codemap();
419 let codemap_bytes = self.position() - i;
421 // Encode DefPathTable
423 let def_path_table = self.encode_def_path_table();
424 let def_path_table_bytes = self.position() - i;
426 // Encode the def IDs of impls, for coherence checking.
428 let impls = self.tracked(IsolatedEncoder::encode_impls, ());
429 let impl_bytes = self.position() - i;
431 // Encode exported symbols info.
433 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
434 let exported_symbols = self.tracked(
435 IsolatedEncoder::encode_exported_symbols,
437 let exported_symbols_bytes = self.position() - i;
439 // encode wasm custom sections
440 let wasm_custom_sections = self.tcx.wasm_custom_sections(LOCAL_CRATE);
441 let wasm_custom_sections = self.tracked(
442 IsolatedEncoder::encode_wasm_custom_sections,
443 &wasm_custom_sections);
449 let items = self.encode_info_for_items();
450 let item_bytes = self.position() - i;
452 // Encode the allocation index
453 let interpret_alloc_index = {
454 let mut interpret_alloc_index = Vec::new();
456 trace!("beginning to encode alloc ids");
458 let new_n = self.interpret_allocs_inverse.len();
459 // if we have found new ids, serialize those, too
464 trace!("encoding {} further alloc ids", new_n - n);
465 for idx in n..new_n {
466 let id = self.interpret_allocs_inverse[idx];
467 let pos = self.position() as u32;
468 interpret_alloc_index.push(pos);
469 interpret::specialized_encode_alloc_id(
477 self.lazy_seq(interpret_alloc_index)
482 let index = items.write_index(&mut self.opaque);
483 let index_bytes = self.position() - i;
485 let attrs = tcx.hir.krate_attrs();
486 let link_meta = self.link_meta;
487 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
488 let has_default_lib_allocator = attr::contains_name(&attrs, "default_lib_allocator");
489 let has_global_allocator = *tcx.sess.has_global_allocator.get();
491 let root = self.lazy(&CrateRoot {
492 name: tcx.crate_name(LOCAL_CRATE),
493 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
494 triple: tcx.sess.opts.target_triple.clone(),
495 hash: link_meta.crate_hash,
496 disambiguator: tcx.sess.local_crate_disambiguator(),
497 panic_strategy: tcx.sess.panic_strategy(),
498 edition: hygiene::default_edition(),
499 has_global_allocator: has_global_allocator,
500 has_default_lib_allocator: has_default_lib_allocator,
501 plugin_registrar_fn: tcx.sess
504 .map(|id| tcx.hir.local_def_id(id).index),
505 macro_derive_registrar: if is_proc_macro {
506 let id = tcx.sess.derive_registrar_fn.get().unwrap();
507 Some(tcx.hir.local_def_id(id).index)
512 compiler_builtins: attr::contains_name(&attrs, "compiler_builtins"),
513 needs_allocator: attr::contains_name(&attrs, "needs_allocator"),
514 needs_panic_runtime: attr::contains_name(&attrs, "needs_panic_runtime"),
515 no_builtins: attr::contains_name(&attrs, "no_builtins"),
516 panic_runtime: attr::contains_name(&attrs, "panic_runtime"),
517 profiler_runtime: attr::contains_name(&attrs, "profiler_runtime"),
518 sanitizer_runtime: attr::contains_name(&attrs, "sanitizer_runtime"),
521 dylib_dependency_formats,
530 wasm_custom_sections,
531 interpret_alloc_index,
535 let total_bytes = self.position();
537 if self.tcx.sess.meta_stats() {
538 let mut zero_bytes = 0;
539 for e in self.opaque.data.iter() {
545 println!("metadata stats:");
546 println!(" dep bytes: {}", dep_bytes);
547 println!(" lang item bytes: {}", lang_item_bytes);
548 println!(" native bytes: {}", native_lib_bytes);
549 println!(" codemap bytes: {}", codemap_bytes);
550 println!(" impl bytes: {}", impl_bytes);
551 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
552 println!(" def-path table bytes: {}", def_path_table_bytes);
553 println!(" item bytes: {}", item_bytes);
554 println!(" index bytes: {}", index_bytes);
555 println!(" zero bytes: {}", zero_bytes);
556 println!(" total bytes: {}", total_bytes);
563 // These are methods for encoding various things. They are meant to be used with
564 // IndexBuilder::record() and EncodeContext::tracked(). They actually
565 // would not have to be methods of IsolatedEncoder (free standing functions
566 // taking IsolatedEncoder as first argument would be just fine) but by making
567 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
568 // clause again and again.
569 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
570 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
571 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
573 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
576 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
578 let ty = tcx.type_of(def_id);
579 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
583 /// Encode data for the given variant of the given ADT. The
584 /// index of the variant is untracked: this is ok because we
585 /// will have to lookup the adt-def by its id, and that gives us
586 /// the right to access any information in the adt-def (including,
587 /// e.g., the length of the various vectors).
588 fn encode_enum_variant_info(&mut self,
589 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
592 let def = tcx.adt_def(enum_did);
593 let variant = &def.variants[index];
594 let def_id = variant.did;
595 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
597 let data = VariantData {
598 ctor_kind: variant.ctor_kind,
599 discr: variant.discr,
601 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
602 Some(self.lazy(&tcx.fn_sig(def_id)))
608 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
609 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
612 kind: EntryKind::Variant(self.lazy(&data)),
613 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
614 span: self.lazy(&tcx.def_span(def_id)),
615 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
616 children: self.lazy_seq(variant.fields.iter().map(|f| {
617 assert!(f.did.is_local());
620 stability: self.encode_stability(def_id),
621 deprecation: self.encode_deprecation(def_id),
623 ty: Some(self.encode_item_type(def_id)),
624 inherent_impls: LazySeq::empty(),
625 variances: if variant.ctor_kind == CtorKind::Fn {
626 self.encode_variances_of(def_id)
630 generics: Some(self.encode_generics(def_id)),
631 predicates: Some(self.encode_predicates(def_id)),
632 predicates_defined_on: None,
634 mir: self.encode_optimized_mir(def_id),
638 fn encode_info_for_mod(&mut self,
639 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
644 let def_id = tcx.hir.local_def_id(id);
645 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
648 reexports: match tcx.module_exports(def_id) {
649 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
650 _ => LazySeq::empty(),
655 kind: EntryKind::Mod(self.lazy(&data)),
656 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
657 span: self.lazy(&tcx.def_span(def_id)),
658 attributes: self.encode_attributes(attrs),
659 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
660 tcx.hir.local_def_id(item_id.id).index
662 stability: self.encode_stability(def_id),
663 deprecation: self.encode_deprecation(def_id),
666 inherent_impls: LazySeq::empty(),
667 variances: LazySeq::empty(),
670 predicates_defined_on: None,
676 /// Encode data for the given field of the given variant of the
677 /// given ADT. The indices of the variant/field are untracked:
678 /// this is ok because we will have to lookup the adt-def by its
679 /// id, and that gives us the right to access any information in
680 /// the adt-def (including, e.g., the length of the various
682 fn encode_field(&mut self,
683 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
688 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
689 let field = &variant.fields[field_index];
691 let def_id = field.did;
692 debug!("IsolatedEncoder::encode_field({:?})", def_id);
694 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
695 let variant_data = tcx.hir.expect_variant_data(variant_id);
698 kind: EntryKind::Field,
699 visibility: self.lazy(&field.vis),
700 span: self.lazy(&tcx.def_span(def_id)),
701 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
702 children: LazySeq::empty(),
703 stability: self.encode_stability(def_id),
704 deprecation: self.encode_deprecation(def_id),
706 ty: Some(self.encode_item_type(def_id)),
707 inherent_impls: LazySeq::empty(),
708 variances: LazySeq::empty(),
709 generics: Some(self.encode_generics(def_id)),
710 predicates: Some(self.encode_predicates(def_id)),
711 predicates_defined_on: None,
717 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
718 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
720 let adt_def = tcx.adt_def(adt_def_id);
721 let variant = adt_def.non_enum_variant();
723 let data = VariantData {
724 ctor_kind: variant.ctor_kind,
725 discr: variant.discr,
726 struct_ctor: Some(def_id.index),
727 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
728 Some(self.lazy(&tcx.fn_sig(def_id)))
734 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
735 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
736 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
737 for field in &variant.fields {
738 if ctor_vis.is_at_least(field.vis, tcx) {
739 ctor_vis = field.vis;
743 // If the structure is marked as non_exhaustive then lower the visibility
744 // to within the crate.
745 if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
746 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
749 let repr_options = get_repr_options(&tcx, adt_def_id);
752 kind: EntryKind::Struct(self.lazy(&data), repr_options),
753 visibility: self.lazy(&ctor_vis),
754 span: self.lazy(&tcx.def_span(def_id)),
755 attributes: LazySeq::empty(),
756 children: LazySeq::empty(),
757 stability: self.encode_stability(def_id),
758 deprecation: self.encode_deprecation(def_id),
760 ty: Some(self.encode_item_type(def_id)),
761 inherent_impls: LazySeq::empty(),
762 variances: if variant.ctor_kind == CtorKind::Fn {
763 self.encode_variances_of(def_id)
767 generics: Some(self.encode_generics(def_id)),
768 predicates: Some(self.encode_predicates(def_id)),
769 predicates_defined_on: None,
771 mir: self.encode_optimized_mir(def_id),
775 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
776 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
778 self.lazy(tcx.generics_of(def_id))
781 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
782 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
784 self.lazy(&tcx.predicates_of(def_id))
787 fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
788 debug!("IsolatedEncoder::encode_predicates_defined_on({:?})", def_id);
790 self.lazy(&tcx.predicates_defined_on(def_id))
793 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
794 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
797 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
798 let ast_item = tcx.hir.expect_trait_item(node_id);
799 let trait_item = tcx.associated_item(def_id);
801 let container = match trait_item.defaultness {
802 hir::Defaultness::Default { has_value: true } =>
803 AssociatedContainer::TraitWithDefault,
804 hir::Defaultness::Default { has_value: false } =>
805 AssociatedContainer::TraitRequired,
806 hir::Defaultness::Final =>
807 span_bug!(ast_item.span, "traits cannot have final items"),
810 let kind = match trait_item.kind {
811 ty::AssociatedKind::Const => {
813 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
814 self.const_qualif(0, body)
816 ConstQualif { mir: 0, ast_promotable: false }
820 hir::print::to_string(&self.tcx.hir, |s| s.print_trait_item(ast_item));
821 let rendered_const = self.lazy(&RenderedConst(rendered));
823 EntryKind::AssociatedConst(container, const_qualif, rendered_const)
825 ty::AssociatedKind::Method => {
826 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
827 let arg_names = match *m {
828 hir::TraitMethod::Required(ref names) => {
829 self.encode_fn_arg_names(names)
831 hir::TraitMethod::Provided(body) => {
832 self.encode_fn_arg_names_for_body(body)
836 constness: hir::Constness::NotConst,
838 sig: self.lazy(&tcx.fn_sig(def_id)),
843 EntryKind::Method(self.lazy(&MethodData {
846 has_self: trait_item.method_has_self_argument,
849 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
854 visibility: self.lazy(&trait_item.vis),
855 span: self.lazy(&ast_item.span),
856 attributes: self.encode_attributes(&ast_item.attrs),
857 children: LazySeq::empty(),
858 stability: self.encode_stability(def_id),
859 deprecation: self.encode_deprecation(def_id),
861 ty: match trait_item.kind {
862 ty::AssociatedKind::Const |
863 ty::AssociatedKind::Method => {
864 Some(self.encode_item_type(def_id))
866 ty::AssociatedKind::Type => {
867 if trait_item.defaultness.has_value() {
868 Some(self.encode_item_type(def_id))
874 inherent_impls: LazySeq::empty(),
875 variances: if trait_item.kind == ty::AssociatedKind::Method {
876 self.encode_variances_of(def_id)
880 generics: Some(self.encode_generics(def_id)),
881 predicates: Some(self.encode_predicates(def_id)),
882 predicates_defined_on: None,
884 mir: self.encode_optimized_mir(def_id),
888 fn metadata_output_only(&self) -> bool {
889 // MIR optimisation can be skipped when we're just interested in the metadata.
890 !self.tcx.sess.opts.output_types.should_codegen()
893 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
894 let body_owner_def_id = self.tcx.hir.body_owner_def_id(body_id);
895 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
897 ConstQualif { mir, ast_promotable }
900 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
901 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
904 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
905 let ast_item = self.tcx.hir.expect_impl_item(node_id);
906 let impl_item = self.tcx.associated_item(def_id);
908 let container = match impl_item.defaultness {
909 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
910 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
911 hir::Defaultness::Default { has_value: false } =>
912 span_bug!(ast_item.span, "impl items always have values (currently)"),
915 let kind = match impl_item.kind {
916 ty::AssociatedKind::Const => {
917 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
918 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
920 EntryKind::AssociatedConst(container,
921 self.const_qualif(mir, body_id),
922 self.encode_rendered_const_for_body(body_id))
927 ty::AssociatedKind::Method => {
928 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
930 constness: sig.header.constness,
931 arg_names: self.encode_fn_arg_names_for_body(body),
932 sig: self.lazy(&tcx.fn_sig(def_id)),
937 EntryKind::Method(self.lazy(&MethodData {
940 has_self: impl_item.method_has_self_argument,
943 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
947 match ast_item.node {
948 hir::ImplItemKind::Const(..) => true,
949 hir::ImplItemKind::Method(ref sig, _) => {
950 let generics = self.tcx.generics_of(def_id);
951 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
952 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
953 !self.metadata_output_only();
954 let is_const_fn = sig.header.constness == hir::Constness::Const;
955 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
956 needs_inline || is_const_fn || always_encode_mir
958 hir::ImplItemKind::Type(..) => false,
963 visibility: self.lazy(&impl_item.vis),
964 span: self.lazy(&ast_item.span),
965 attributes: self.encode_attributes(&ast_item.attrs),
966 children: LazySeq::empty(),
967 stability: self.encode_stability(def_id),
968 deprecation: self.encode_deprecation(def_id),
970 ty: Some(self.encode_item_type(def_id)),
971 inherent_impls: LazySeq::empty(),
972 variances: if impl_item.kind == ty::AssociatedKind::Method {
973 self.encode_variances_of(def_id)
977 generics: Some(self.encode_generics(def_id)),
978 predicates: Some(self.encode_predicates(def_id)),
979 predicates_defined_on: None,
981 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
985 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
986 -> LazySeq<ast::Name> {
987 self.tcx.dep_graph.with_ignore(|| {
988 let body = self.tcx.hir.body(body_id);
989 self.lazy_seq(body.arguments.iter().map(|arg| {
991 PatKind::Binding(_, _, ident, _) => ident.name,
992 _ => keywords::Invalid.name(),
998 fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> LazySeq<ast::Name> {
999 self.lazy_seq(param_names.iter().map(|ident| ident.name))
1002 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
1003 debug!("EntryBuilder::encode_mir({:?})", def_id);
1004 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1005 let mir = self.tcx.optimized_mir(def_id);
1006 Some(self.lazy(&mir))
1012 // Encodes the inherent implementations of a structure, enumeration, or trait.
1013 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1014 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
1015 let implementations = self.tcx.inherent_impls(def_id);
1016 if implementations.is_empty() {
1019 self.lazy_seq(implementations.iter().map(|&def_id| {
1020 assert!(def_id.is_local());
1026 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1027 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
1028 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1031 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1032 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
1033 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1036 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1037 let body = self.tcx.hir.body(body_id);
1038 let rendered = hir::print::to_string(&self.tcx.hir, |s| s.print_expr(&body.value));
1039 let rendered_const = &RenderedConst(rendered);
1040 self.lazy(rendered_const)
1043 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1046 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
1048 let kind = match item.node {
1049 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
1050 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1051 hir::ItemConst(_, body_id) => {
1052 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1054 self.const_qualif(mir, body_id),
1055 self.encode_rendered_const_for_body(body_id)
1058 hir::ItemFn(_, header, .., body) => {
1060 constness: header.constness,
1061 arg_names: self.encode_fn_arg_names_for_body(body),
1062 sig: self.lazy(&tcx.fn_sig(def_id)),
1065 EntryKind::Fn(self.lazy(&data))
1067 hir::ItemMod(ref m) => {
1068 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
1070 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
1071 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
1072 hir::ItemTy(..) => EntryKind::Type,
1073 hir::ItemExistential(..) => EntryKind::Existential,
1074 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
1075 hir::ItemStruct(ref struct_def, _) => {
1076 let variant = tcx.adt_def(def_id).non_enum_variant();
1078 // Encode def_ids for each field and method
1079 // for methods, write all the stuff get_trait_method
1081 let struct_ctor = if !struct_def.is_struct() {
1082 Some(tcx.hir.local_def_id(struct_def.id()).index)
1087 let repr_options = get_repr_options(&tcx, def_id);
1089 EntryKind::Struct(self.lazy(&VariantData {
1090 ctor_kind: variant.ctor_kind,
1091 discr: variant.discr,
1096 hir::ItemUnion(..) => {
1097 let variant = tcx.adt_def(def_id).non_enum_variant();
1098 let repr_options = get_repr_options(&tcx, def_id);
1100 EntryKind::Union(self.lazy(&VariantData {
1101 ctor_kind: variant.ctor_kind,
1102 discr: variant.discr,
1107 hir::ItemImpl(_, polarity, defaultness, ..) => {
1108 let trait_ref = tcx.impl_trait_ref(def_id);
1109 let parent = if let Some(trait_ref) = trait_ref {
1110 let trait_def = tcx.trait_def(trait_ref.def_id);
1111 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
1113 specialization_graph::Node::Impl(parent) => Some(parent),
1121 // if this is an impl of `CoerceUnsized`, create its
1122 // "unsized info", else just store None
1123 let coerce_unsized_info =
1124 trait_ref.and_then(|t| {
1125 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1126 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1132 let data = ImplData {
1135 parent_impl: parent,
1136 coerce_unsized_info,
1137 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1140 EntryKind::Impl(self.lazy(&data))
1142 hir::ItemTrait(..) => {
1143 let trait_def = tcx.trait_def(def_id);
1144 let data = TraitData {
1145 unsafety: trait_def.unsafety,
1146 paren_sugar: trait_def.paren_sugar,
1147 has_auto_impl: tcx.trait_is_auto(def_id),
1148 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1151 EntryKind::Trait(self.lazy(&data))
1153 hir::ItemExternCrate(_) |
1154 hir::ItemTraitAlias(..) |
1155 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1160 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1161 span: self.lazy(&item.span),
1162 attributes: self.encode_attributes(&item.attrs),
1163 children: match item.node {
1164 hir::ItemForeignMod(ref fm) => {
1165 self.lazy_seq(fm.items
1167 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1169 hir::ItemEnum(..) => {
1170 let def = self.tcx.adt_def(def_id);
1171 self.lazy_seq(def.variants.iter().map(|v| {
1172 assert!(v.did.is_local());
1176 hir::ItemStruct(..) |
1177 hir::ItemUnion(..) => {
1178 let def = self.tcx.adt_def(def_id);
1179 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1180 assert!(f.did.is_local());
1185 hir::ItemTrait(..) => {
1186 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1187 assert!(def_id.is_local());
1191 _ => LazySeq::empty(),
1193 stability: self.encode_stability(def_id),
1194 deprecation: self.encode_deprecation(def_id),
1196 ty: match item.node {
1197 hir::ItemStatic(..) |
1198 hir::ItemConst(..) |
1201 hir::ItemExistential(..) |
1203 hir::ItemStruct(..) |
1204 hir::ItemUnion(..) |
1205 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1208 inherent_impls: self.encode_inherent_implementations(def_id),
1209 variances: match item.node {
1211 hir::ItemStruct(..) |
1212 hir::ItemUnion(..) |
1213 hir::ItemFn(..) => self.encode_variances_of(def_id),
1214 _ => LazySeq::empty(),
1216 generics: match item.node {
1217 hir::ItemStatic(..) |
1218 hir::ItemConst(..) |
1222 hir::ItemStruct(..) |
1223 hir::ItemUnion(..) |
1225 hir::ItemExistential(..) |
1226 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1229 predicates: match item.node {
1230 hir::ItemStatic(..) |
1231 hir::ItemConst(..) |
1235 hir::ItemStruct(..) |
1236 hir::ItemUnion(..) |
1238 hir::ItemExistential(..) |
1239 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1243 // The only time that `predicates_defined_on` is used (on
1244 // an external item) is for traits, during chalk lowering,
1245 // so only encode it in that case as an efficiency
1246 // hack. (No reason not to expand it in the future if
1248 predicates_defined_on: match item.node {
1249 hir::ItemTrait(..) => Some(self.encode_predicates_defined_on(def_id)),
1250 _ => None, // not *wrong* for other kinds of items, but not needed
1253 mir: match item.node {
1254 hir::ItemStatic(..) => {
1255 self.encode_optimized_mir(def_id)
1257 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1258 hir::ItemFn(_, header, ..) => {
1259 let generics = tcx.generics_of(def_id);
1260 let has_types = generics.params.iter().any(|param| match param.kind {
1261 ty::GenericParamDefKind::Type { .. } => true,
1265 (has_types || tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1266 !self.metadata_output_only();
1267 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1269 || header.constness == hir::Constness::Const
1270 || always_encode_mir
1272 self.encode_optimized_mir(def_id)
1282 /// Serialize the text of exported macros
1283 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1284 use syntax::print::pprust;
1285 let def_id = self.tcx.hir.local_def_id(macro_def.id);
1287 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1288 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1289 legacy: macro_def.legacy,
1291 visibility: self.lazy(&ty::Visibility::Public),
1292 span: self.lazy(¯o_def.span),
1293 attributes: self.encode_attributes(¯o_def.attrs),
1294 stability: self.encode_stability(def_id),
1295 deprecation: self.encode_deprecation(def_id),
1297 children: LazySeq::empty(),
1299 inherent_impls: LazySeq::empty(),
1300 variances: LazySeq::empty(),
1303 predicates_defined_on: None,
1308 fn encode_info_for_ty_param(&mut self,
1309 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1311 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1314 kind: EntryKind::Type,
1315 visibility: self.lazy(&ty::Visibility::Public),
1316 span: self.lazy(&tcx.def_span(def_id)),
1317 attributes: LazySeq::empty(),
1318 children: LazySeq::empty(),
1322 ty: if has_default {
1323 Some(self.encode_item_type(def_id))
1327 inherent_impls: LazySeq::empty(),
1328 variances: LazySeq::empty(),
1331 predicates_defined_on: None,
1337 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1338 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1341 let tables = self.tcx.typeck_tables_of(def_id);
1342 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1343 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1344 let kind = match tables.node_id_to_type(hir_id).sty {
1345 ty::TyGenerator(def_id, ..) => {
1346 let layout = self.tcx.generator_layout(def_id);
1347 let data = GeneratorData {
1348 layout: layout.clone(),
1350 EntryKind::Generator(self.lazy(&data))
1353 ty::TyClosure(def_id, substs) => {
1354 let sig = substs.closure_sig(def_id, self.tcx);
1355 let data = ClosureData { sig: self.lazy(&sig) };
1356 EntryKind::Closure(self.lazy(&data))
1359 _ => bug!("closure that is neither generator nor closure")
1364 visibility: self.lazy(&ty::Visibility::Public),
1365 span: self.lazy(&tcx.def_span(def_id)),
1366 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1367 children: LazySeq::empty(),
1371 ty: Some(self.encode_item_type(def_id)),
1372 inherent_impls: LazySeq::empty(),
1373 variances: LazySeq::empty(),
1374 generics: Some(self.encode_generics(def_id)),
1376 predicates_defined_on: None,
1378 mir: self.encode_optimized_mir(def_id),
1382 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1383 debug!("IsolatedEncoder::encode_info_for_anon_const({:?})", def_id);
1385 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1386 let body_id = tcx.hir.body_owned_by(id);
1387 let const_data = self.encode_rendered_const_for_body(body_id);
1388 let mir = tcx.mir_const_qualif(def_id).0;
1391 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1392 visibility: self.lazy(&ty::Visibility::Public),
1393 span: self.lazy(&tcx.def_span(def_id)),
1394 attributes: LazySeq::empty(),
1395 children: LazySeq::empty(),
1399 ty: Some(self.encode_item_type(def_id)),
1400 inherent_impls: LazySeq::empty(),
1401 variances: LazySeq::empty(),
1402 generics: Some(self.encode_generics(def_id)),
1403 predicates: Some(self.encode_predicates(def_id)),
1404 predicates_defined_on: None,
1406 mir: self.encode_optimized_mir(def_id),
1410 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1411 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1412 // we rely on the HashStable specialization for [Attribute]
1413 // to properly filter things out.
1414 self.lazy_seq_from_slice(attrs)
1417 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1418 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1419 self.lazy_seq(used_libraries.iter().cloned())
1422 fn encode_foreign_modules(&mut self, _: ()) -> LazySeq<ForeignModule> {
1423 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1424 self.lazy_seq(foreign_modules.iter().cloned())
1427 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1428 let crates = self.tcx.crates();
1430 let mut deps = crates
1433 let dep = CrateDep {
1434 name: self.tcx.original_crate_name(cnum),
1435 hash: self.tcx.crate_hash(cnum),
1436 kind: self.tcx.dep_kind(cnum),
1437 extra_filename: self.tcx.extra_filename(cnum),
1441 .collect::<Vec<_>>();
1443 deps.sort_by_key(|&(cnum, _)| cnum);
1446 // Sanity-check the crate numbers
1447 let mut expected_cnum = 1;
1448 for &(n, _) in &deps {
1449 assert_eq!(n, CrateNum::new(expected_cnum));
1454 // We're just going to write a list of crate 'name-hash-version's, with
1455 // the assumption that they are numbered 1 to n.
1456 // FIXME (#2166): This is not nearly enough to support correct versioning
1457 // but is enough to get transitive crate dependencies working.
1458 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1461 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1463 let lang_items = tcx.lang_items();
1464 let lang_items = lang_items.items().iter();
1465 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1466 if let Some(def_id) = opt_def_id {
1467 if def_id.is_local() {
1468 return Some((def_id.index, i));
1475 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1477 self.lazy_seq_ref(&tcx.lang_items().missing)
1480 /// Encodes an index, mapping each trait to its (local) implementations.
1481 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1482 debug!("IsolatedEncoder::encode_impls()");
1484 let mut visitor = ImplVisitor {
1488 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1490 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1492 // Bring everything into deterministic order for hashing
1493 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1494 tcx.def_path_hash(trait_def_id)
1497 let all_impls: Vec<_> = all_impls
1499 .map(|(trait_def_id, mut impls)| {
1500 // Bring everything into deterministic order for hashing
1501 impls.sort_by_cached_key(|&def_index| {
1502 tcx.hir.definitions().def_path_hash(def_index)
1506 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1507 impls: self.lazy_seq_from_slice(&impls[..]),
1512 self.lazy_seq_from_slice(&all_impls[..])
1515 // Encodes all symbols exported from this crate into the metadata.
1517 // This pass is seeded off the reachability list calculated in the
1518 // middle::reachable module but filters out items that either don't have a
1519 // symbol associated with them (they weren't translated) or if they're an FFI
1520 // definition (as that's not defined in this crate).
1521 fn encode_exported_symbols(&mut self,
1522 exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1523 -> EncodedExportedSymbols {
1524 // The metadata symbol name is special. It should not show up in
1525 // downstream crates.
1526 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1528 let lazy_seq = self.lazy_seq(exported_symbols
1530 .filter(|&&(ref exported_symbol, _)| {
1531 match *exported_symbol {
1532 ExportedSymbol::NoDefId(symbol_name) => {
1533 symbol_name != metadata_symbol_name
1540 EncodedExportedSymbols {
1542 position: lazy_seq.position,
1546 fn encode_wasm_custom_sections(&mut self, statics: &[DefId]) -> LazySeq<DefIndex> {
1547 info!("encoding custom wasm section constants {:?}", statics);
1548 self.lazy_seq(statics.iter().map(|id| id.index))
1551 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1552 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1554 self.lazy_seq(arr.iter().map(|slot| {
1556 Linkage::NotLinked |
1557 Linkage::IncludedFromDylib => None,
1559 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1560 Linkage::Static => Some(LinkagePreference::RequireStatic),
1564 None => LazySeq::empty(),
1568 fn encode_info_for_foreign_item(&mut self,
1569 (def_id, nitem): (DefId, &hir::ForeignItem))
1573 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1575 let kind = match nitem.node {
1576 hir::ForeignItemFn(_, ref names, _) => {
1578 constness: hir::Constness::NotConst,
1579 arg_names: self.encode_fn_arg_names(names),
1580 sig: self.lazy(&tcx.fn_sig(def_id)),
1582 EntryKind::ForeignFn(self.lazy(&data))
1584 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1585 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1586 hir::ForeignItemType => EntryKind::ForeignType,
1591 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1592 span: self.lazy(&nitem.span),
1593 attributes: self.encode_attributes(&nitem.attrs),
1594 children: LazySeq::empty(),
1595 stability: self.encode_stability(def_id),
1596 deprecation: self.encode_deprecation(def_id),
1598 ty: Some(self.encode_item_type(def_id)),
1599 inherent_impls: LazySeq::empty(),
1600 variances: match nitem.node {
1601 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1602 _ => LazySeq::empty(),
1604 generics: Some(self.encode_generics(def_id)),
1605 predicates: Some(self.encode_predicates(def_id)),
1606 predicates_defined_on: None,
1613 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1614 index: IndexBuilder<'a, 'b, 'tcx>,
1617 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1618 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1619 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1621 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1622 intravisit::walk_expr(self, ex);
1623 self.index.encode_info_for_expr(ex);
1625 fn visit_item(&mut self, item: &'tcx hir::Item) {
1626 intravisit::walk_item(self, item);
1627 let def_id = self.index.tcx.hir.local_def_id(item.id);
1629 hir::ItemExternCrate(_) |
1630 hir::ItemUse(..) => (), // ignore these
1631 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1633 self.index.encode_addl_info_for_item(item);
1635 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1636 intravisit::walk_foreign_item(self, ni);
1637 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1638 self.index.record(def_id,
1639 IsolatedEncoder::encode_info_for_foreign_item,
1642 fn visit_variant(&mut self,
1643 v: &'tcx hir::Variant,
1644 g: &'tcx hir::Generics,
1646 intravisit::walk_variant(self, v, g, id);
1648 if let Some(ref discr) = v.node.disr_expr {
1649 let def_id = self.index.tcx.hir.local_def_id(discr.id);
1650 self.index.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1653 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1654 intravisit::walk_generics(self, generics);
1655 self.index.encode_info_for_generics(generics);
1657 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1658 intravisit::walk_ty(self, ty);
1659 self.index.encode_info_for_ty(ty);
1661 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1662 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1663 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1667 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1668 fn encode_fields(&mut self, adt_def_id: DefId) {
1669 let def = self.tcx.adt_def(adt_def_id);
1670 for (variant_index, variant) in def.variants.iter().enumerate() {
1671 for (field_index, field) in variant.fields.iter().enumerate() {
1672 self.record(field.did,
1673 IsolatedEncoder::encode_field,
1674 (adt_def_id, Untracked((variant_index, field_index))));
1679 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1680 generics.params.iter().for_each(|param| match param.kind {
1681 hir::GenericParamKind::Lifetime { .. } => {}
1682 hir::GenericParamKind::Type { ref default, .. } => {
1683 let def_id = self.tcx.hir.local_def_id(param.id);
1684 let has_default = Untracked(default.is_some());
1685 let encode_info = IsolatedEncoder::encode_info_for_ty_param;
1686 self.record(def_id, encode_info, (def_id, has_default));
1691 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1693 hir::TyArray(_, ref length) => {
1694 let def_id = self.tcx.hir.local_def_id(length.id);
1695 self.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1701 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1703 hir::ExprClosure(..) => {
1704 let def_id = self.tcx.hir.local_def_id(expr.id);
1705 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1711 /// In some cases, along with the item itself, we also
1712 /// encode some sub-items. Usually we want some info from the item
1713 /// so it's easier to do that here then to wait until we would encounter
1714 /// normally in the visitor walk.
1715 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1716 let def_id = self.tcx.hir.local_def_id(item.id);
1718 hir::ItemStatic(..) |
1719 hir::ItemConst(..) |
1722 hir::ItemForeignMod(..) |
1723 hir::ItemGlobalAsm(..) |
1724 hir::ItemExternCrate(..) |
1727 hir::ItemExistential(..) |
1728 hir::ItemTraitAlias(..) => {
1729 // no sub-item recording needed in these cases
1731 hir::ItemEnum(..) => {
1732 self.encode_fields(def_id);
1734 let def = self.tcx.adt_def(def_id);
1735 for (i, variant) in def.variants.iter().enumerate() {
1736 self.record(variant.did,
1737 IsolatedEncoder::encode_enum_variant_info,
1738 (def_id, Untracked(i)));
1741 hir::ItemStruct(ref struct_def, _) => {
1742 self.encode_fields(def_id);
1744 // If the struct has a constructor, encode it.
1745 if !struct_def.is_struct() {
1746 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1747 self.record(ctor_def_id,
1748 IsolatedEncoder::encode_struct_ctor,
1749 (def_id, ctor_def_id));
1752 hir::ItemUnion(..) => {
1753 self.encode_fields(def_id);
1755 hir::ItemImpl(..) => {
1756 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1757 self.record(trait_item_def_id,
1758 IsolatedEncoder::encode_info_for_impl_item,
1762 hir::ItemTrait(..) => {
1763 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1764 self.record(item_def_id,
1765 IsolatedEncoder::encode_info_for_trait_item,
1773 struct ImplVisitor<'a, 'tcx: 'a> {
1774 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1775 impls: FxHashMap<DefId, Vec<DefIndex>>,
1778 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1779 fn visit_item(&mut self, item: &hir::Item) {
1780 if let hir::ItemImpl(..) = item.node {
1781 let impl_id = self.tcx.hir.local_def_id(item.id);
1782 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1784 .entry(trait_ref.def_id)
1786 .push(impl_id.index);
1791 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1793 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1794 // handled in `visit_item` above
1798 // NOTE(eddyb) The following comment was preserved for posterity, even
1799 // though it's no longer relevant as EBML (which uses nested & tagged
1800 // "documents") was replaced with a scheme that can't go out of bounds.
1802 // And here we run into yet another obscure archive bug: in which metadata
1803 // loaded from archives may have trailing garbage bytes. Awhile back one of
1804 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1805 // and opt) by having ebml generate an out-of-bounds panic when looking at
1808 // Upon investigation it turned out that the metadata file inside of an rlib
1809 // (and ar archive) was being corrupted. Some compilations would generate a
1810 // metadata file which would end in a few extra bytes, while other
1811 // compilations would not have these extra bytes appended to the end. These
1812 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1813 // being interpreted causing the out-of-bounds.
1815 // The root cause of why these extra bytes were appearing was never
1816 // discovered, and in the meantime the solution we're employing is to insert
1817 // the length of the metadata to the start of the metadata. Later on this
1818 // will allow us to slice the metadata to the precise length that we just
1819 // generated regardless of trailing bytes that end up in it.
1821 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1822 link_meta: &LinkMeta)
1825 let mut encoder = opaque::Encoder::new(vec![]);
1826 encoder.emit_raw_bytes(METADATA_HEADER);
1828 // Will be filled with the root position after encoding everything.
1829 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1831 let (root, mut result) = {
1832 let mut ecx = EncodeContext {
1836 lazy_state: LazyState::NoNode,
1837 type_shorthands: Default::default(),
1838 predicate_shorthands: Default::default(),
1839 filemap_cache: tcx.sess.codemap().files()[0].clone(),
1840 interpret_allocs: Default::default(),
1841 interpret_allocs_inverse: Default::default(),
1844 // Encode the rustc version string in a predictable location.
1845 rustc_version().encode(&mut ecx).unwrap();
1847 // Encode all the entries and extra information in the crate,
1848 // culminating in the `CrateRoot` which points to all of it.
1849 let root = ecx.encode_crate_root();
1850 (root, ecx.opaque.into_inner())
1853 // Encode the root position.
1854 let header = METADATA_HEADER.len();
1855 let pos = root.position;
1856 result[header + 0] = (pos >> 24) as u8;
1857 result[header + 1] = (pos >> 16) as u8;
1858 result[header + 2] = (pos >> 8) as u8;
1859 result[header + 3] = (pos >> 0) as u8;
1861 EncodedMetadata { raw_data: result }
1864 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1865 let ty = tcx.type_of(did);
1867 ty::TyAdt(ref def, _) => return def.repr,
1868 _ => bug!("{} is not an ADT", ty),