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;
443 let items = self.encode_info_for_items();
444 let item_bytes = self.position() - i;
446 // Encode the allocation index
447 let interpret_alloc_index = {
448 let mut interpret_alloc_index = Vec::new();
450 trace!("beginning to encode alloc ids");
452 let new_n = self.interpret_allocs_inverse.len();
453 // if we have found new ids, serialize those, too
458 trace!("encoding {} further alloc ids", new_n - n);
459 for idx in n..new_n {
460 let id = self.interpret_allocs_inverse[idx];
461 let pos = self.position() as u32;
462 interpret_alloc_index.push(pos);
463 interpret::specialized_encode_alloc_id(
471 self.lazy_seq(interpret_alloc_index)
476 let index = items.write_index(&mut self.opaque);
477 let index_bytes = self.position() - i;
479 let attrs = tcx.hir.krate_attrs();
480 let link_meta = self.link_meta;
481 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
482 let has_default_lib_allocator = attr::contains_name(&attrs, "default_lib_allocator");
483 let has_global_allocator = *tcx.sess.has_global_allocator.get();
485 let root = self.lazy(&CrateRoot {
486 name: tcx.crate_name(LOCAL_CRATE),
487 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
488 triple: tcx.sess.opts.target_triple.clone(),
489 hash: link_meta.crate_hash,
490 disambiguator: tcx.sess.local_crate_disambiguator(),
491 panic_strategy: tcx.sess.panic_strategy(),
492 edition: hygiene::default_edition(),
493 has_global_allocator: has_global_allocator,
494 has_default_lib_allocator: has_default_lib_allocator,
495 plugin_registrar_fn: tcx.sess
498 .map(|id| tcx.hir.local_def_id(id).index),
499 macro_derive_registrar: if is_proc_macro {
500 let id = tcx.sess.derive_registrar_fn.get().unwrap();
501 Some(tcx.hir.local_def_id(id).index)
506 compiler_builtins: attr::contains_name(&attrs, "compiler_builtins"),
507 needs_allocator: attr::contains_name(&attrs, "needs_allocator"),
508 needs_panic_runtime: attr::contains_name(&attrs, "needs_panic_runtime"),
509 no_builtins: attr::contains_name(&attrs, "no_builtins"),
510 panic_runtime: attr::contains_name(&attrs, "panic_runtime"),
511 profiler_runtime: attr::contains_name(&attrs, "profiler_runtime"),
512 sanitizer_runtime: attr::contains_name(&attrs, "sanitizer_runtime"),
515 dylib_dependency_formats,
524 interpret_alloc_index,
528 let total_bytes = self.position();
530 if self.tcx.sess.meta_stats() {
531 let mut zero_bytes = 0;
532 for e in self.opaque.data.iter() {
538 println!("metadata stats:");
539 println!(" dep bytes: {}", dep_bytes);
540 println!(" lang item bytes: {}", lang_item_bytes);
541 println!(" native bytes: {}", native_lib_bytes);
542 println!(" codemap bytes: {}", codemap_bytes);
543 println!(" impl bytes: {}", impl_bytes);
544 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
545 println!(" def-path table bytes: {}", def_path_table_bytes);
546 println!(" item bytes: {}", item_bytes);
547 println!(" index bytes: {}", index_bytes);
548 println!(" zero bytes: {}", zero_bytes);
549 println!(" total bytes: {}", total_bytes);
556 // These are methods for encoding various things. They are meant to be used with
557 // IndexBuilder::record() and EncodeContext::tracked(). They actually
558 // would not have to be methods of IsolatedEncoder (free standing functions
559 // taking IsolatedEncoder as first argument would be just fine) but by making
560 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
561 // clause again and again.
562 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
563 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
564 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
566 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
569 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
571 let ty = tcx.type_of(def_id);
572 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
576 /// Encode data for the given variant of the given ADT. The
577 /// index of the variant is untracked: this is ok because we
578 /// will have to lookup the adt-def by its id, and that gives us
579 /// the right to access any information in the adt-def (including,
580 /// e.g., the length of the various vectors).
581 fn encode_enum_variant_info(&mut self,
582 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
585 let def = tcx.adt_def(enum_did);
586 let variant = &def.variants[index];
587 let def_id = variant.did;
588 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
590 let data = VariantData {
591 ctor_kind: variant.ctor_kind,
592 discr: variant.discr,
594 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
595 Some(self.lazy(&tcx.fn_sig(def_id)))
601 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
602 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
605 kind: EntryKind::Variant(self.lazy(&data)),
606 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
607 span: self.lazy(&tcx.def_span(def_id)),
608 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
609 children: self.lazy_seq(variant.fields.iter().map(|f| {
610 assert!(f.did.is_local());
613 stability: self.encode_stability(def_id),
614 deprecation: self.encode_deprecation(def_id),
616 ty: Some(self.encode_item_type(def_id)),
617 inherent_impls: LazySeq::empty(),
618 variances: if variant.ctor_kind == CtorKind::Fn {
619 self.encode_variances_of(def_id)
623 generics: Some(self.encode_generics(def_id)),
624 predicates: Some(self.encode_predicates(def_id)),
625 predicates_defined_on: None,
627 mir: self.encode_optimized_mir(def_id),
631 fn encode_info_for_mod(&mut self,
632 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
637 let def_id = tcx.hir.local_def_id(id);
638 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
641 reexports: match tcx.module_exports(def_id) {
642 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
643 _ => LazySeq::empty(),
648 kind: EntryKind::Mod(self.lazy(&data)),
649 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
650 span: self.lazy(&tcx.def_span(def_id)),
651 attributes: self.encode_attributes(attrs),
652 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
653 tcx.hir.local_def_id(item_id.id).index
655 stability: self.encode_stability(def_id),
656 deprecation: self.encode_deprecation(def_id),
659 inherent_impls: LazySeq::empty(),
660 variances: LazySeq::empty(),
663 predicates_defined_on: None,
669 /// Encode data for the given field of the given variant of the
670 /// given ADT. The indices of the variant/field are untracked:
671 /// this is ok because we will have to lookup the adt-def by its
672 /// id, and that gives us the right to access any information in
673 /// the adt-def (including, e.g., the length of the various
675 fn encode_field(&mut self,
676 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
681 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
682 let field = &variant.fields[field_index];
684 let def_id = field.did;
685 debug!("IsolatedEncoder::encode_field({:?})", def_id);
687 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
688 let variant_data = tcx.hir.expect_variant_data(variant_id);
691 kind: EntryKind::Field,
692 visibility: self.lazy(&field.vis),
693 span: self.lazy(&tcx.def_span(def_id)),
694 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
695 children: LazySeq::empty(),
696 stability: self.encode_stability(def_id),
697 deprecation: self.encode_deprecation(def_id),
699 ty: Some(self.encode_item_type(def_id)),
700 inherent_impls: LazySeq::empty(),
701 variances: LazySeq::empty(),
702 generics: Some(self.encode_generics(def_id)),
703 predicates: Some(self.encode_predicates(def_id)),
704 predicates_defined_on: None,
710 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
711 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
713 let adt_def = tcx.adt_def(adt_def_id);
714 let variant = adt_def.non_enum_variant();
716 let data = VariantData {
717 ctor_kind: variant.ctor_kind,
718 discr: variant.discr,
719 struct_ctor: Some(def_id.index),
720 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
721 Some(self.lazy(&tcx.fn_sig(def_id)))
727 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
728 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
729 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
730 for field in &variant.fields {
731 if ctor_vis.is_at_least(field.vis, tcx) {
732 ctor_vis = field.vis;
736 // If the structure is marked as non_exhaustive then lower the visibility
737 // to within the crate.
738 if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
739 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
742 let repr_options = get_repr_options(&tcx, adt_def_id);
745 kind: EntryKind::Struct(self.lazy(&data), repr_options),
746 visibility: self.lazy(&ctor_vis),
747 span: self.lazy(&tcx.def_span(def_id)),
748 attributes: LazySeq::empty(),
749 children: LazySeq::empty(),
750 stability: self.encode_stability(def_id),
751 deprecation: self.encode_deprecation(def_id),
753 ty: Some(self.encode_item_type(def_id)),
754 inherent_impls: LazySeq::empty(),
755 variances: if variant.ctor_kind == CtorKind::Fn {
756 self.encode_variances_of(def_id)
760 generics: Some(self.encode_generics(def_id)),
761 predicates: Some(self.encode_predicates(def_id)),
762 predicates_defined_on: None,
764 mir: self.encode_optimized_mir(def_id),
768 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
769 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
771 self.lazy(tcx.generics_of(def_id))
774 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
775 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
777 self.lazy(&tcx.predicates_of(def_id))
780 fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
781 debug!("IsolatedEncoder::encode_predicates_defined_on({:?})", def_id);
783 self.lazy(&tcx.predicates_defined_on(def_id))
786 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
787 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
790 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
791 let ast_item = tcx.hir.expect_trait_item(node_id);
792 let trait_item = tcx.associated_item(def_id);
794 let container = match trait_item.defaultness {
795 hir::Defaultness::Default { has_value: true } =>
796 AssociatedContainer::TraitWithDefault,
797 hir::Defaultness::Default { has_value: false } =>
798 AssociatedContainer::TraitRequired,
799 hir::Defaultness::Final =>
800 span_bug!(ast_item.span, "traits cannot have final items"),
803 let kind = match trait_item.kind {
804 ty::AssociatedKind::Const => {
806 if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
807 self.const_qualif(0, body)
809 ConstQualif { mir: 0, ast_promotable: false }
813 hir::print::to_string(&self.tcx.hir, |s| s.print_trait_item(ast_item));
814 let rendered_const = self.lazy(&RenderedConst(rendered));
816 EntryKind::AssociatedConst(container, const_qualif, rendered_const)
818 ty::AssociatedKind::Method => {
819 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
820 let arg_names = match *m {
821 hir::TraitMethod::Required(ref names) => {
822 self.encode_fn_arg_names(names)
824 hir::TraitMethod::Provided(body) => {
825 self.encode_fn_arg_names_for_body(body)
829 constness: hir::Constness::NotConst,
831 sig: self.lazy(&tcx.fn_sig(def_id)),
836 EntryKind::Method(self.lazy(&MethodData {
839 has_self: trait_item.method_has_self_argument,
842 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
847 visibility: self.lazy(&trait_item.vis),
848 span: self.lazy(&ast_item.span),
849 attributes: self.encode_attributes(&ast_item.attrs),
850 children: LazySeq::empty(),
851 stability: self.encode_stability(def_id),
852 deprecation: self.encode_deprecation(def_id),
854 ty: match trait_item.kind {
855 ty::AssociatedKind::Const |
856 ty::AssociatedKind::Method => {
857 Some(self.encode_item_type(def_id))
859 ty::AssociatedKind::Type => {
860 if trait_item.defaultness.has_value() {
861 Some(self.encode_item_type(def_id))
867 inherent_impls: LazySeq::empty(),
868 variances: if trait_item.kind == ty::AssociatedKind::Method {
869 self.encode_variances_of(def_id)
873 generics: Some(self.encode_generics(def_id)),
874 predicates: Some(self.encode_predicates(def_id)),
875 predicates_defined_on: None,
877 mir: self.encode_optimized_mir(def_id),
881 fn metadata_output_only(&self) -> bool {
882 // MIR optimisation can be skipped when we're just interested in the metadata.
883 !self.tcx.sess.opts.output_types.should_codegen()
886 fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
887 let body_owner_def_id = self.tcx.hir.body_owner_def_id(body_id);
888 let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
890 ConstQualif { mir, ast_promotable }
893 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
894 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
897 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
898 let ast_item = self.tcx.hir.expect_impl_item(node_id);
899 let impl_item = self.tcx.associated_item(def_id);
901 let container = match impl_item.defaultness {
902 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
903 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
904 hir::Defaultness::Default { has_value: false } =>
905 span_bug!(ast_item.span, "impl items always have values (currently)"),
908 let kind = match impl_item.kind {
909 ty::AssociatedKind::Const => {
910 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
911 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
913 EntryKind::AssociatedConst(container,
914 self.const_qualif(mir, body_id),
915 self.encode_rendered_const_for_body(body_id))
920 ty::AssociatedKind::Method => {
921 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
923 constness: sig.header.constness,
924 arg_names: self.encode_fn_arg_names_for_body(body),
925 sig: self.lazy(&tcx.fn_sig(def_id)),
930 EntryKind::Method(self.lazy(&MethodData {
933 has_self: impl_item.method_has_self_argument,
936 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
940 match ast_item.node {
941 hir::ImplItemKind::Const(..) => true,
942 hir::ImplItemKind::Method(ref sig, _) => {
943 let generics = self.tcx.generics_of(def_id);
944 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
945 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
946 !self.metadata_output_only();
947 let is_const_fn = sig.header.constness == hir::Constness::Const;
948 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
949 needs_inline || is_const_fn || always_encode_mir
951 hir::ImplItemKind::Type(..) => false,
956 visibility: self.lazy(&impl_item.vis),
957 span: self.lazy(&ast_item.span),
958 attributes: self.encode_attributes(&ast_item.attrs),
959 children: LazySeq::empty(),
960 stability: self.encode_stability(def_id),
961 deprecation: self.encode_deprecation(def_id),
963 ty: Some(self.encode_item_type(def_id)),
964 inherent_impls: LazySeq::empty(),
965 variances: if impl_item.kind == ty::AssociatedKind::Method {
966 self.encode_variances_of(def_id)
970 generics: Some(self.encode_generics(def_id)),
971 predicates: Some(self.encode_predicates(def_id)),
972 predicates_defined_on: None,
974 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
978 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
979 -> LazySeq<ast::Name> {
980 self.tcx.dep_graph.with_ignore(|| {
981 let body = self.tcx.hir.body(body_id);
982 self.lazy_seq(body.arguments.iter().map(|arg| {
984 PatKind::Binding(_, _, ident, _) => ident.name,
985 _ => keywords::Invalid.name(),
991 fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> LazySeq<ast::Name> {
992 self.lazy_seq(param_names.iter().map(|ident| ident.name))
995 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
996 debug!("EntryBuilder::encode_mir({:?})", def_id);
997 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
998 let mir = self.tcx.optimized_mir(def_id);
999 Some(self.lazy(&mir))
1005 // Encodes the inherent implementations of a structure, enumeration, or trait.
1006 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1007 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
1008 let implementations = self.tcx.inherent_impls(def_id);
1009 if implementations.is_empty() {
1012 self.lazy_seq(implementations.iter().map(|&def_id| {
1013 assert!(def_id.is_local());
1019 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1020 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
1021 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1024 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1025 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
1026 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1029 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1030 let body = self.tcx.hir.body(body_id);
1031 let rendered = hir::print::to_string(&self.tcx.hir, |s| s.print_expr(&body.value));
1032 let rendered_const = &RenderedConst(rendered);
1033 self.lazy(rendered_const)
1036 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1039 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
1041 let kind = match item.node {
1042 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1043 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1044 hir::ItemKind::Const(_, body_id) => {
1045 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1047 self.const_qualif(mir, body_id),
1048 self.encode_rendered_const_for_body(body_id)
1051 hir::ItemKind::Fn(_, header, .., body) => {
1053 constness: header.constness,
1054 arg_names: self.encode_fn_arg_names_for_body(body),
1055 sig: self.lazy(&tcx.fn_sig(def_id)),
1058 EntryKind::Fn(self.lazy(&data))
1060 hir::ItemKind::Mod(ref m) => {
1061 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
1063 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1064 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1065 hir::ItemKind::Ty(..) => EntryKind::Type,
1066 hir::ItemKind::Existential(..) => EntryKind::Existential,
1067 hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
1068 hir::ItemKind::Struct(ref struct_def, _) => {
1069 let variant = tcx.adt_def(def_id).non_enum_variant();
1071 // Encode def_ids for each field and method
1072 // for methods, write all the stuff get_trait_method
1074 let struct_ctor = if !struct_def.is_struct() {
1075 Some(tcx.hir.local_def_id(struct_def.id()).index)
1080 let repr_options = get_repr_options(&tcx, def_id);
1082 EntryKind::Struct(self.lazy(&VariantData {
1083 ctor_kind: variant.ctor_kind,
1084 discr: variant.discr,
1089 hir::ItemKind::Union(..) => {
1090 let variant = tcx.adt_def(def_id).non_enum_variant();
1091 let repr_options = get_repr_options(&tcx, def_id);
1093 EntryKind::Union(self.lazy(&VariantData {
1094 ctor_kind: variant.ctor_kind,
1095 discr: variant.discr,
1100 hir::ItemKind::Impl(_, polarity, defaultness, ..) => {
1101 let trait_ref = tcx.impl_trait_ref(def_id);
1102 let parent = if let Some(trait_ref) = trait_ref {
1103 let trait_def = tcx.trait_def(trait_ref.def_id);
1104 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
1106 specialization_graph::Node::Impl(parent) => Some(parent),
1114 // if this is an impl of `CoerceUnsized`, create its
1115 // "unsized info", else just store None
1116 let coerce_unsized_info =
1117 trait_ref.and_then(|t| {
1118 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1119 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1125 let data = ImplData {
1128 parent_impl: parent,
1129 coerce_unsized_info,
1130 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1133 EntryKind::Impl(self.lazy(&data))
1135 hir::ItemKind::Trait(..) => {
1136 let trait_def = tcx.trait_def(def_id);
1137 let data = TraitData {
1138 unsafety: trait_def.unsafety,
1139 paren_sugar: trait_def.paren_sugar,
1140 has_auto_impl: tcx.trait_is_auto(def_id),
1141 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1144 EntryKind::Trait(self.lazy(&data))
1146 hir::ItemKind::ExternCrate(_) |
1147 hir::ItemKind::TraitAlias(..) |
1148 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1153 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1154 span: self.lazy(&item.span),
1155 attributes: self.encode_attributes(&item.attrs),
1156 children: match item.node {
1157 hir::ItemKind::ForeignMod(ref fm) => {
1158 self.lazy_seq(fm.items
1160 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1162 hir::ItemKind::Enum(..) => {
1163 let def = self.tcx.adt_def(def_id);
1164 self.lazy_seq(def.variants.iter().map(|v| {
1165 assert!(v.did.is_local());
1169 hir::ItemKind::Struct(..) |
1170 hir::ItemKind::Union(..) => {
1171 let def = self.tcx.adt_def(def_id);
1172 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1173 assert!(f.did.is_local());
1177 hir::ItemKind::Impl(..) |
1178 hir::ItemKind::Trait(..) => {
1179 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1180 assert!(def_id.is_local());
1184 _ => LazySeq::empty(),
1186 stability: self.encode_stability(def_id),
1187 deprecation: self.encode_deprecation(def_id),
1189 ty: match item.node {
1190 hir::ItemKind::Static(..) |
1191 hir::ItemKind::Const(..) |
1192 hir::ItemKind::Fn(..) |
1193 hir::ItemKind::Ty(..) |
1194 hir::ItemKind::Existential(..) |
1195 hir::ItemKind::Enum(..) |
1196 hir::ItemKind::Struct(..) |
1197 hir::ItemKind::Union(..) |
1198 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1201 inherent_impls: self.encode_inherent_implementations(def_id),
1202 variances: match item.node {
1203 hir::ItemKind::Enum(..) |
1204 hir::ItemKind::Struct(..) |
1205 hir::ItemKind::Union(..) |
1206 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1207 _ => LazySeq::empty(),
1209 generics: match item.node {
1210 hir::ItemKind::Static(..) |
1211 hir::ItemKind::Const(..) |
1212 hir::ItemKind::Fn(..) |
1213 hir::ItemKind::Ty(..) |
1214 hir::ItemKind::Enum(..) |
1215 hir::ItemKind::Struct(..) |
1216 hir::ItemKind::Union(..) |
1217 hir::ItemKind::Impl(..) |
1218 hir::ItemKind::Existential(..) |
1219 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1222 predicates: match item.node {
1223 hir::ItemKind::Static(..) |
1224 hir::ItemKind::Const(..) |
1225 hir::ItemKind::Fn(..) |
1226 hir::ItemKind::Ty(..) |
1227 hir::ItemKind::Enum(..) |
1228 hir::ItemKind::Struct(..) |
1229 hir::ItemKind::Union(..) |
1230 hir::ItemKind::Impl(..) |
1231 hir::ItemKind::Existential(..) |
1232 hir::ItemKind::Trait(..) => Some(self.encode_predicates(def_id)),
1236 // The only time that `predicates_defined_on` is used (on
1237 // an external item) is for traits, during chalk lowering,
1238 // so only encode it in that case as an efficiency
1239 // hack. (No reason not to expand it in the future if
1241 predicates_defined_on: match item.node {
1242 hir::ItemKind::Trait(..) => Some(self.encode_predicates_defined_on(def_id)),
1243 _ => None, // not *wrong* for other kinds of items, but not needed
1246 mir: match item.node {
1247 hir::ItemKind::Static(..) => {
1248 self.encode_optimized_mir(def_id)
1250 hir::ItemKind::Const(..) => self.encode_optimized_mir(def_id),
1251 hir::ItemKind::Fn(_, header, ..) => {
1252 let generics = tcx.generics_of(def_id);
1253 let has_types = generics.params.iter().any(|param| match param.kind {
1254 ty::GenericParamDefKind::Type { .. } => true,
1258 (has_types || tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1259 !self.metadata_output_only();
1260 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1262 || header.constness == hir::Constness::Const
1263 || always_encode_mir
1265 self.encode_optimized_mir(def_id)
1275 /// Serialize the text of exported macros
1276 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1277 use syntax::print::pprust;
1278 let def_id = self.tcx.hir.local_def_id(macro_def.id);
1280 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1281 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1282 legacy: macro_def.legacy,
1284 visibility: self.lazy(&ty::Visibility::Public),
1285 span: self.lazy(¯o_def.span),
1286 attributes: self.encode_attributes(¯o_def.attrs),
1287 stability: self.encode_stability(def_id),
1288 deprecation: self.encode_deprecation(def_id),
1290 children: LazySeq::empty(),
1292 inherent_impls: LazySeq::empty(),
1293 variances: LazySeq::empty(),
1296 predicates_defined_on: None,
1301 fn encode_info_for_ty_param(&mut self,
1302 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1304 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1307 kind: EntryKind::Type,
1308 visibility: self.lazy(&ty::Visibility::Public),
1309 span: self.lazy(&tcx.def_span(def_id)),
1310 attributes: LazySeq::empty(),
1311 children: LazySeq::empty(),
1315 ty: if has_default {
1316 Some(self.encode_item_type(def_id))
1320 inherent_impls: LazySeq::empty(),
1321 variances: LazySeq::empty(),
1324 predicates_defined_on: None,
1330 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1331 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1334 let tables = self.tcx.typeck_tables_of(def_id);
1335 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1336 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1337 let kind = match tables.node_id_to_type(hir_id).sty {
1338 ty::TyGenerator(def_id, ..) => {
1339 let layout = self.tcx.generator_layout(def_id);
1340 let data = GeneratorData {
1341 layout: layout.clone(),
1343 EntryKind::Generator(self.lazy(&data))
1346 ty::TyClosure(def_id, substs) => {
1347 let sig = substs.closure_sig(def_id, self.tcx);
1348 let data = ClosureData { sig: self.lazy(&sig) };
1349 EntryKind::Closure(self.lazy(&data))
1352 _ => bug!("closure that is neither generator nor closure")
1357 visibility: self.lazy(&ty::Visibility::Public),
1358 span: self.lazy(&tcx.def_span(def_id)),
1359 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1360 children: LazySeq::empty(),
1364 ty: Some(self.encode_item_type(def_id)),
1365 inherent_impls: LazySeq::empty(),
1366 variances: LazySeq::empty(),
1367 generics: Some(self.encode_generics(def_id)),
1369 predicates_defined_on: None,
1371 mir: self.encode_optimized_mir(def_id),
1375 fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1376 debug!("IsolatedEncoder::encode_info_for_anon_const({:?})", def_id);
1378 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1379 let body_id = tcx.hir.body_owned_by(id);
1380 let const_data = self.encode_rendered_const_for_body(body_id);
1381 let mir = tcx.mir_const_qualif(def_id).0;
1384 kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1385 visibility: self.lazy(&ty::Visibility::Public),
1386 span: self.lazy(&tcx.def_span(def_id)),
1387 attributes: LazySeq::empty(),
1388 children: LazySeq::empty(),
1392 ty: Some(self.encode_item_type(def_id)),
1393 inherent_impls: LazySeq::empty(),
1394 variances: LazySeq::empty(),
1395 generics: Some(self.encode_generics(def_id)),
1396 predicates: Some(self.encode_predicates(def_id)),
1397 predicates_defined_on: None,
1399 mir: self.encode_optimized_mir(def_id),
1403 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1404 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1405 // we rely on the HashStable specialization for [Attribute]
1406 // to properly filter things out.
1407 self.lazy_seq_from_slice(attrs)
1410 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1411 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1412 self.lazy_seq(used_libraries.iter().cloned())
1415 fn encode_foreign_modules(&mut self, _: ()) -> LazySeq<ForeignModule> {
1416 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1417 self.lazy_seq(foreign_modules.iter().cloned())
1420 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1421 let crates = self.tcx.crates();
1423 let mut deps = crates
1426 let dep = CrateDep {
1427 name: self.tcx.original_crate_name(cnum),
1428 hash: self.tcx.crate_hash(cnum),
1429 kind: self.tcx.dep_kind(cnum),
1430 extra_filename: self.tcx.extra_filename(cnum),
1434 .collect::<Vec<_>>();
1436 deps.sort_by_key(|&(cnum, _)| cnum);
1439 // Sanity-check the crate numbers
1440 let mut expected_cnum = 1;
1441 for &(n, _) in &deps {
1442 assert_eq!(n, CrateNum::new(expected_cnum));
1447 // We're just going to write a list of crate 'name-hash-version's, with
1448 // the assumption that they are numbered 1 to n.
1449 // FIXME (#2166): This is not nearly enough to support correct versioning
1450 // but is enough to get transitive crate dependencies working.
1451 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1454 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1456 let lang_items = tcx.lang_items();
1457 let lang_items = lang_items.items().iter();
1458 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1459 if let Some(def_id) = opt_def_id {
1460 if def_id.is_local() {
1461 return Some((def_id.index, i));
1468 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1470 self.lazy_seq_ref(&tcx.lang_items().missing)
1473 /// Encodes an index, mapping each trait to its (local) implementations.
1474 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1475 debug!("IsolatedEncoder::encode_impls()");
1477 let mut visitor = ImplVisitor {
1481 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1483 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1485 // Bring everything into deterministic order for hashing
1486 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1487 tcx.def_path_hash(trait_def_id)
1490 let all_impls: Vec<_> = all_impls
1492 .map(|(trait_def_id, mut impls)| {
1493 // Bring everything into deterministic order for hashing
1494 impls.sort_by_cached_key(|&def_index| {
1495 tcx.hir.definitions().def_path_hash(def_index)
1499 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1500 impls: self.lazy_seq_from_slice(&impls[..]),
1505 self.lazy_seq_from_slice(&all_impls[..])
1508 // Encodes all symbols exported from this crate into the metadata.
1510 // This pass is seeded off the reachability list calculated in the
1511 // middle::reachable module but filters out items that either don't have a
1512 // symbol associated with them (they weren't translated) or if they're an FFI
1513 // definition (as that's not defined in this crate).
1514 fn encode_exported_symbols(&mut self,
1515 exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1516 -> EncodedExportedSymbols {
1517 // The metadata symbol name is special. It should not show up in
1518 // downstream crates.
1519 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1521 let lazy_seq = self.lazy_seq(exported_symbols
1523 .filter(|&&(ref exported_symbol, _)| {
1524 match *exported_symbol {
1525 ExportedSymbol::NoDefId(symbol_name) => {
1526 symbol_name != metadata_symbol_name
1533 EncodedExportedSymbols {
1535 position: lazy_seq.position,
1539 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1540 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1542 self.lazy_seq(arr.iter().map(|slot| {
1544 Linkage::NotLinked |
1545 Linkage::IncludedFromDylib => None,
1547 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1548 Linkage::Static => Some(LinkagePreference::RequireStatic),
1552 None => LazySeq::empty(),
1556 fn encode_info_for_foreign_item(&mut self,
1557 (def_id, nitem): (DefId, &hir::ForeignItem))
1561 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1563 let kind = match nitem.node {
1564 hir::ForeignItemKind::Fn(_, ref names, _) => {
1566 constness: hir::Constness::NotConst,
1567 arg_names: self.encode_fn_arg_names(names),
1568 sig: self.lazy(&tcx.fn_sig(def_id)),
1570 EntryKind::ForeignFn(self.lazy(&data))
1572 hir::ForeignItemKind::Static(_, true) => EntryKind::ForeignMutStatic,
1573 hir::ForeignItemKind::Static(_, false) => EntryKind::ForeignImmStatic,
1574 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1579 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1580 span: self.lazy(&nitem.span),
1581 attributes: self.encode_attributes(&nitem.attrs),
1582 children: LazySeq::empty(),
1583 stability: self.encode_stability(def_id),
1584 deprecation: self.encode_deprecation(def_id),
1586 ty: Some(self.encode_item_type(def_id)),
1587 inherent_impls: LazySeq::empty(),
1588 variances: match nitem.node {
1589 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1590 _ => LazySeq::empty(),
1592 generics: Some(self.encode_generics(def_id)),
1593 predicates: Some(self.encode_predicates(def_id)),
1594 predicates_defined_on: None,
1601 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1602 index: IndexBuilder<'a, 'b, 'tcx>,
1605 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1606 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1607 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1609 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1610 intravisit::walk_expr(self, ex);
1611 self.index.encode_info_for_expr(ex);
1613 fn visit_item(&mut self, item: &'tcx hir::Item) {
1614 intravisit::walk_item(self, item);
1615 let def_id = self.index.tcx.hir.local_def_id(item.id);
1617 hir::ItemKind::ExternCrate(_) |
1618 hir::ItemKind::Use(..) => (), // ignore these
1619 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1621 self.index.encode_addl_info_for_item(item);
1623 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1624 intravisit::walk_foreign_item(self, ni);
1625 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1626 self.index.record(def_id,
1627 IsolatedEncoder::encode_info_for_foreign_item,
1630 fn visit_variant(&mut self,
1631 v: &'tcx hir::Variant,
1632 g: &'tcx hir::Generics,
1634 intravisit::walk_variant(self, v, g, id);
1636 if let Some(ref discr) = v.node.disr_expr {
1637 let def_id = self.index.tcx.hir.local_def_id(discr.id);
1638 self.index.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1641 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1642 intravisit::walk_generics(self, generics);
1643 self.index.encode_info_for_generics(generics);
1645 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1646 intravisit::walk_ty(self, ty);
1647 self.index.encode_info_for_ty(ty);
1649 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1650 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1651 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1655 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1656 fn encode_fields(&mut self, adt_def_id: DefId) {
1657 let def = self.tcx.adt_def(adt_def_id);
1658 for (variant_index, variant) in def.variants.iter().enumerate() {
1659 for (field_index, field) in variant.fields.iter().enumerate() {
1660 self.record(field.did,
1661 IsolatedEncoder::encode_field,
1662 (adt_def_id, Untracked((variant_index, field_index))));
1667 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1668 generics.params.iter().for_each(|param| match param.kind {
1669 hir::GenericParamKind::Lifetime { .. } => {}
1670 hir::GenericParamKind::Type { ref default, .. } => {
1671 let def_id = self.tcx.hir.local_def_id(param.id);
1672 let has_default = Untracked(default.is_some());
1673 let encode_info = IsolatedEncoder::encode_info_for_ty_param;
1674 self.record(def_id, encode_info, (def_id, has_default));
1679 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1681 hir::TyKind::Array(_, ref length) => {
1682 let def_id = self.tcx.hir.local_def_id(length.id);
1683 self.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1689 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1691 hir::ExprKind::Closure(..) => {
1692 let def_id = self.tcx.hir.local_def_id(expr.id);
1693 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1699 /// In some cases, along with the item itself, we also
1700 /// encode some sub-items. Usually we want some info from the item
1701 /// so it's easier to do that here then to wait until we would encounter
1702 /// normally in the visitor walk.
1703 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1704 let def_id = self.tcx.hir.local_def_id(item.id);
1706 hir::ItemKind::Static(..) |
1707 hir::ItemKind::Const(..) |
1708 hir::ItemKind::Fn(..) |
1709 hir::ItemKind::Mod(..) |
1710 hir::ItemKind::ForeignMod(..) |
1711 hir::ItemKind::GlobalAsm(..) |
1712 hir::ItemKind::ExternCrate(..) |
1713 hir::ItemKind::Use(..) |
1714 hir::ItemKind::Ty(..) |
1715 hir::ItemKind::Existential(..) |
1716 hir::ItemKind::TraitAlias(..) => {
1717 // no sub-item recording needed in these cases
1719 hir::ItemKind::Enum(..) => {
1720 self.encode_fields(def_id);
1722 let def = self.tcx.adt_def(def_id);
1723 for (i, variant) in def.variants.iter().enumerate() {
1724 self.record(variant.did,
1725 IsolatedEncoder::encode_enum_variant_info,
1726 (def_id, Untracked(i)));
1729 hir::ItemKind::Struct(ref struct_def, _) => {
1730 self.encode_fields(def_id);
1732 // If the struct has a constructor, encode it.
1733 if !struct_def.is_struct() {
1734 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1735 self.record(ctor_def_id,
1736 IsolatedEncoder::encode_struct_ctor,
1737 (def_id, ctor_def_id));
1740 hir::ItemKind::Union(..) => {
1741 self.encode_fields(def_id);
1743 hir::ItemKind::Impl(..) => {
1744 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1745 self.record(trait_item_def_id,
1746 IsolatedEncoder::encode_info_for_impl_item,
1750 hir::ItemKind::Trait(..) => {
1751 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1752 self.record(item_def_id,
1753 IsolatedEncoder::encode_info_for_trait_item,
1761 struct ImplVisitor<'a, 'tcx: 'a> {
1762 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1763 impls: FxHashMap<DefId, Vec<DefIndex>>,
1766 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1767 fn visit_item(&mut self, item: &hir::Item) {
1768 if let hir::ItemKind::Impl(..) = item.node {
1769 let impl_id = self.tcx.hir.local_def_id(item.id);
1770 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1772 .entry(trait_ref.def_id)
1774 .push(impl_id.index);
1779 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1781 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1782 // handled in `visit_item` above
1786 // NOTE(eddyb) The following comment was preserved for posterity, even
1787 // though it's no longer relevant as EBML (which uses nested & tagged
1788 // "documents") was replaced with a scheme that can't go out of bounds.
1790 // And here we run into yet another obscure archive bug: in which metadata
1791 // loaded from archives may have trailing garbage bytes. Awhile back one of
1792 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1793 // and opt) by having ebml generate an out-of-bounds panic when looking at
1796 // Upon investigation it turned out that the metadata file inside of an rlib
1797 // (and ar archive) was being corrupted. Some compilations would generate a
1798 // metadata file which would end in a few extra bytes, while other
1799 // compilations would not have these extra bytes appended to the end. These
1800 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1801 // being interpreted causing the out-of-bounds.
1803 // The root cause of why these extra bytes were appearing was never
1804 // discovered, and in the meantime the solution we're employing is to insert
1805 // the length of the metadata to the start of the metadata. Later on this
1806 // will allow us to slice the metadata to the precise length that we just
1807 // generated regardless of trailing bytes that end up in it.
1809 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1810 link_meta: &LinkMeta)
1813 let mut encoder = opaque::Encoder::new(vec![]);
1814 encoder.emit_raw_bytes(METADATA_HEADER);
1816 // Will be filled with the root position after encoding everything.
1817 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1819 let (root, mut result) = {
1820 let mut ecx = EncodeContext {
1824 lazy_state: LazyState::NoNode,
1825 type_shorthands: Default::default(),
1826 predicate_shorthands: Default::default(),
1827 filemap_cache: tcx.sess.codemap().files()[0].clone(),
1828 interpret_allocs: Default::default(),
1829 interpret_allocs_inverse: Default::default(),
1832 // Encode the rustc version string in a predictable location.
1833 rustc_version().encode(&mut ecx).unwrap();
1835 // Encode all the entries and extra information in the crate,
1836 // culminating in the `CrateRoot` which points to all of it.
1837 let root = ecx.encode_crate_root();
1838 (root, ecx.opaque.into_inner())
1841 // Encode the root position.
1842 let header = METADATA_HEADER.len();
1843 let pos = root.position;
1844 result[header + 0] = (pos >> 24) as u8;
1845 result[header + 1] = (pos >> 16) as u8;
1846 result[header + 2] = (pos >> 8) as u8;
1847 result[header + 3] = (pos >> 0) as u8;
1849 EncodedMetadata { raw_data: result }
1852 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1853 let ty = tcx.type_of(did);
1855 ty::TyAdt(ref def, _) => return def.repr,
1856 _ => bug!("{} is not an ADT", ty),