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, EncodedMetadataHashes};
18 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LOCAL_CRATE};
19 use rustc::hir::map::definitions::DefPathTable;
20 use rustc::dep_graph::{DepNode, GlobalMetaDataKind};
21 use rustc::ich::{StableHashingContext, Fingerprint};
22 use rustc::middle::dependency_format::Linkage;
23 use rustc::middle::lang_items;
25 use rustc::traits::specialization_graph;
26 use rustc::ty::{self, Ty, TyCtxt, ReprOptions};
28 use rustc::session::config::{self, CrateTypeProcMacro};
29 use rustc::util::nodemap::{FxHashMap, NodeSet};
31 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
32 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
36 use std::io::prelude::*;
42 use syntax::ast::{self, CRATE_NODE_ID};
43 use syntax::codemap::Spanned;
45 use syntax::symbol::Symbol;
48 use rustc::hir::{self, PatKind};
49 use rustc::hir::itemlikevisit::ItemLikeVisitor;
50 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
51 use rustc::hir::intravisit;
53 pub struct EncodeContext<'a, 'tcx: 'a> {
54 opaque: opaque::Encoder<'a>,
55 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
56 link_meta: &'a LinkMeta,
57 exported_symbols: &'a NodeSet,
59 lazy_state: LazyState,
60 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
61 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
63 pub metadata_hashes: EncodedMetadataHashes,
64 pub compute_ich: bool,
67 macro_rules! encoder_methods {
68 ($($name:ident($ty:ty);)*) => {
69 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
70 self.opaque.$name(value)
75 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
76 type Error = <opaque::Encoder<'a> as Encoder>::Error;
78 fn emit_nil(&mut self) -> Result<(), Self::Error> {
105 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
106 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
107 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
111 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
112 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
113 self.emit_usize(seq.len)?;
117 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
121 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
122 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
123 self.encode_with_shorthand(ty, &ty.sty, |ecx| &mut ecx.type_shorthands)
127 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
128 fn specialized_encode(&mut self,
129 predicates: &ty::GenericPredicates<'tcx>)
130 -> Result<(), Self::Error> {
131 predicates.parent.encode(self)?;
132 predicates.predicates.len().encode(self)?;
133 for predicate in &predicates.predicates {
134 self.encode_with_shorthand(predicate, predicate, |ecx| &mut ecx.predicate_shorthands)?
140 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
142 pub fn position(&self) -> usize {
143 self.opaque.position()
146 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
147 assert_eq!(self.lazy_state, LazyState::NoNode);
148 let pos = self.position();
149 self.lazy_state = LazyState::NodeStart(pos);
150 let r = f(self, pos);
151 self.lazy_state = LazyState::NoNode;
155 fn emit_lazy_distance(&mut self,
158 -> Result<(), <Self as Encoder>::Error> {
159 let min_end = position + min_size;
160 let distance = match self.lazy_state {
161 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
162 LazyState::NodeStart(start) => {
163 assert!(min_end <= start);
166 LazyState::Previous(last_min_end) => {
167 assert!(last_min_end <= position);
168 position - last_min_end
171 self.lazy_state = LazyState::Previous(min_end);
172 self.emit_usize(distance)
175 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
176 self.emit_node(|ecx, pos| {
177 value.encode(ecx).unwrap();
179 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
180 Lazy::with_position(pos)
184 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
185 where I: IntoIterator<Item = T>,
188 self.emit_node(|ecx, pos| {
189 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
191 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
192 LazySeq::with_position_and_length(pos, len)
196 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
197 where I: IntoIterator<Item = &'b T>,
200 self.emit_node(|ecx, pos| {
201 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
203 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
204 LazySeq::with_position_and_length(pos, len)
208 /// Encode the given value or a previously cached shorthand.
209 fn encode_with_shorthand<T, U, M>(&mut self,
213 -> Result<(), <Self as Encoder>::Error>
214 where M: for<'b> Fn(&'b mut Self) -> &'b mut FxHashMap<T, usize>,
215 T: Clone + Eq + Hash,
218 let existing_shorthand = map(self).get(value).cloned();
219 if let Some(shorthand) = existing_shorthand {
220 return self.emit_usize(shorthand);
223 let start = self.position();
224 variant.encode(self)?;
225 let len = self.position() - start;
227 // The shorthand encoding uses the same usize as the
228 // discriminant, with an offset so they can't conflict.
229 let discriminant = unsafe { intrinsics::discriminant_value(variant) };
230 assert!(discriminant < SHORTHAND_OFFSET as u64);
231 let shorthand = start + SHORTHAND_OFFSET;
233 // Get the number of bits that leb128 could fit
234 // in the same space as the fully encoded type.
235 let leb128_bits = len * 7;
237 // Check that the shorthand is a not longer than the
238 // full encoding itself, i.e. it's an obvious win.
239 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
240 map(self).insert(value.clone(), shorthand);
246 // Encodes something that corresponds to a single DepNode::GlobalMetaData
247 // and registers the Fingerprint in the `metadata_hashes` map.
248 pub fn tracked<'x, DATA, R>(&'x mut self,
249 dep_node: DepNode<()>,
250 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
253 let mut entry_builder = IsolatedEncoder::new(self);
254 let ret = op(&mut entry_builder, data);
255 let (fingerprint, this) = entry_builder.finish();
257 if let Some(fingerprint) = fingerprint {
258 this.metadata_hashes.global_hashes.push((dep_node, fingerprint));
264 fn encode_info_for_items(&mut self) -> Index {
265 let krate = self.tcx.hir.krate();
266 let mut index = IndexBuilder::new(self);
267 index.record(DefId::local(CRATE_DEF_INDEX),
268 IsolatedEncoder::encode_info_for_mod,
269 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
270 let mut visitor = EncodeVisitor { index: index };
271 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
272 for macro_def in &krate.exported_macros {
273 visitor.visit_macro_def(macro_def);
275 visitor.index.into_items()
278 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
279 let definitions = self.tcx.hir.definitions();
280 self.lazy(definitions.def_path_table())
283 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
284 let codemap = self.tcx.sess.codemap();
285 let all_filemaps = codemap.files();
287 let hcx = &mut StableHashingContext::new(self.tcx);
288 let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
290 let adapted = all_filemaps.iter()
292 // No need to re-export imported filemaps, as any downstream
293 // crate will import them from their original source.
294 !filemap.is_imported()
297 // When exporting FileMaps, we expand all paths to absolute
298 // paths because any relative paths are potentially relative to
299 // a wrong directory.
300 // However, if a path has been modified via
301 // `-Zremap-path-prefix` we assume the user has already set
302 // things up the way they want and don't touch the path values
304 let name = Path::new(&filemap.name);
305 if filemap.name_was_remapped ||
306 (name.is_relative() && working_dir_was_remapped) {
307 // This path of this FileMap has been modified by
308 // path-remapping, so we use it verbatim (and avoid cloning
309 // the whole map in the process).
312 let mut adapted = (**filemap).clone();
313 let abs_path = Path::new(&working_dir).join(name)
316 adapted.name = abs_path;
321 let filemaps: Vec<_> = if self.compute_ich {
322 adapted.inspect(|filemap| {
323 let mut hasher = StableHasher::new();
324 filemap.hash_stable(hcx, &mut hasher);
325 let fingerprint = hasher.finish();
326 let dep_node = DepNode::FileMap((), Arc::new(filemap.name.clone()));
327 self.metadata_hashes.global_hashes.push((dep_node, fingerprint));
333 self.lazy_seq_ref(filemaps.iter().map(|fm| &**fm))
336 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
337 let mut i = self.position();
339 let crate_deps = self.tracked(
340 DepNode::GlobalMetaData((), GlobalMetaDataKind::CrateDeps),
341 IsolatedEncoder::encode_crate_deps,
343 let dylib_dependency_formats = self.tracked(
344 DepNode::GlobalMetaData((), GlobalMetaDataKind::DylibDependencyFormats),
345 IsolatedEncoder::encode_dylib_dependency_formats,
347 let dep_bytes = self.position() - i;
349 // Encode the language items.
351 let lang_items = self.tracked(
352 DepNode::GlobalMetaData((), GlobalMetaDataKind::LangItems),
353 IsolatedEncoder::encode_lang_items,
356 let lang_items_missing = self.tracked(
357 DepNode::GlobalMetaData((), GlobalMetaDataKind::LangItemsMissing),
358 IsolatedEncoder::encode_lang_items_missing,
360 let lang_item_bytes = self.position() - i;
362 // Encode the native libraries used
364 let native_libraries = self.tracked(
365 DepNode::GlobalMetaData((), GlobalMetaDataKind::NativeLibraries),
366 IsolatedEncoder::encode_native_libraries,
368 let native_lib_bytes = self.position() - i;
372 let codemap = self.encode_codemap();
373 let codemap_bytes = self.position() - i;
375 // Encode DefPathTable
377 let def_path_table = self.encode_def_path_table();
378 let def_path_table_bytes = self.position() - i;
380 // Encode the def IDs of impls, for coherence checking.
382 let impls = self.tracked(
383 DepNode::GlobalMetaData((), GlobalMetaDataKind::Impls),
384 IsolatedEncoder::encode_impls,
386 let impl_bytes = self.position() - i;
388 // Encode exported symbols info.
390 let exported_symbols = self.tracked(
391 DepNode::GlobalMetaData((), GlobalMetaDataKind::ExportedSymbols),
392 IsolatedEncoder::encode_exported_symbols,
393 self.exported_symbols);
394 let exported_symbols_bytes = self.position() - i;
396 // Encode and index the items.
398 let items = self.encode_info_for_items();
399 let item_bytes = self.position() - i;
402 let index = items.write_index(&mut self.opaque.cursor);
403 let index_bytes = self.position() - i;
406 let link_meta = self.link_meta;
407 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
408 let root = self.lazy(&CrateRoot {
409 name: tcx.crate_name(LOCAL_CRATE),
410 triple: tcx.sess.opts.target_triple.clone(),
411 hash: link_meta.crate_hash,
412 disambiguator: tcx.sess.local_crate_disambiguator(),
413 panic_strategy: Tracked::new(tcx.sess.panic_strategy()),
414 plugin_registrar_fn: tcx.sess
417 .map(|id| tcx.hir.local_def_id(id).index),
418 macro_derive_registrar: if is_proc_macro {
419 let id = tcx.sess.derive_registrar_fn.get().unwrap();
420 Some(tcx.hir.local_def_id(id).index)
425 crate_deps: crate_deps,
426 dylib_dependency_formats: dylib_dependency_formats,
427 lang_items: lang_items,
428 lang_items_missing: lang_items_missing,
429 native_libraries: native_libraries,
431 def_path_table: def_path_table,
433 exported_symbols: exported_symbols,
437 let total_bytes = self.position();
439 self.metadata_hashes.global_hashes.push((
440 DepNode::GlobalMetaData((), GlobalMetaDataKind::Krate),
441 Fingerprint::from_smaller_hash(link_meta.crate_hash.as_u64())
444 if self.tcx.sess.meta_stats() {
445 let mut zero_bytes = 0;
446 for e in self.opaque.cursor.get_ref() {
452 println!("metadata stats:");
453 println!(" dep bytes: {}", dep_bytes);
454 println!(" lang item bytes: {}", lang_item_bytes);
455 println!(" native bytes: {}", native_lib_bytes);
456 println!(" codemap bytes: {}", codemap_bytes);
457 println!(" impl bytes: {}", impl_bytes);
458 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
459 println!(" def-path table bytes: {}", def_path_table_bytes);
460 println!(" item bytes: {}", item_bytes);
461 println!(" index bytes: {}", index_bytes);
462 println!(" zero bytes: {}", zero_bytes);
463 println!(" total bytes: {}", total_bytes);
470 // These are methods for encoding various things. They are meant to be used with
471 // IndexBuilder::record() and EncodeContext::tracked(). They actually
472 // would not have to be methods of IsolatedEncoder (free standing functions
473 // taking IsolatedEncoder as first argument would be just fine) but by making
474 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
475 // clause again and again.
476 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
477 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
478 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
480 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
483 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
485 let ty = tcx.type_of(def_id);
486 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
490 /// Encode data for the given variant of the given ADT. The
491 /// index of the variant is untracked: this is ok because we
492 /// will have to lookup the adt-def by its id, and that gives us
493 /// the right to access any information in the adt-def (including,
494 /// e.g., the length of the various vectors).
495 fn encode_enum_variant_info(&mut self,
496 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
499 let def = tcx.adt_def(enum_did);
500 let variant = &def.variants[index];
501 let def_id = variant.did;
502 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
504 let data = VariantData {
505 ctor_kind: variant.ctor_kind,
506 discr: variant.discr,
510 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
511 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
514 kind: EntryKind::Variant(self.lazy(&data)),
515 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
516 span: self.lazy(&tcx.def_span(def_id)),
517 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
518 children: self.lazy_seq(variant.fields.iter().map(|f| {
519 assert!(f.did.is_local());
522 stability: self.encode_stability(def_id),
523 deprecation: self.encode_deprecation(def_id),
525 ty: Some(self.encode_item_type(def_id)),
526 inherent_impls: LazySeq::empty(),
527 variances: LazySeq::empty(),
528 generics: Some(self.encode_generics(def_id)),
529 predicates: Some(self.encode_predicates(def_id)),
532 mir: self.encode_optimized_mir(def_id),
536 fn encode_info_for_mod(&mut self,
537 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
542 let def_id = tcx.hir.local_def_id(id);
543 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
546 reexports: match tcx.export_map.get(&id) {
547 Some(exports) if *vis == hir::Public => {
548 self.lazy_seq_from_slice(exports.as_slice())
550 _ => LazySeq::empty(),
555 kind: EntryKind::Mod(self.lazy(&data)),
556 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
557 span: self.lazy(&md.inner),
558 attributes: self.encode_attributes(attrs),
559 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
560 tcx.hir.local_def_id(item_id.id).index
562 stability: self.encode_stability(def_id),
563 deprecation: self.encode_deprecation(def_id),
566 inherent_impls: LazySeq::empty(),
567 variances: LazySeq::empty(),
576 /// Encode data for the given field of the given variant of the
577 /// given ADT. The indices of the variant/field are untracked:
578 /// this is ok because we will have to lookup the adt-def by its
579 /// id, and that gives us the right to access any information in
580 /// the adt-def (including, e.g., the length of the various
582 fn encode_field(&mut self,
583 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
588 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
589 let field = &variant.fields[field_index];
591 let def_id = field.did;
592 debug!("IsolatedEncoder::encode_field({:?})", def_id);
594 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
595 let variant_data = tcx.hir.expect_variant_data(variant_id);
598 kind: EntryKind::Field,
599 visibility: self.lazy(&field.vis),
600 span: self.lazy(&tcx.def_span(def_id)),
601 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
602 children: LazySeq::empty(),
603 stability: self.encode_stability(def_id),
604 deprecation: self.encode_deprecation(def_id),
606 ty: Some(self.encode_item_type(def_id)),
607 inherent_impls: LazySeq::empty(),
608 variances: LazySeq::empty(),
609 generics: Some(self.encode_generics(def_id)),
610 predicates: Some(self.encode_predicates(def_id)),
617 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
618 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
620 let variant = tcx.adt_def(adt_def_id).struct_variant();
622 let data = VariantData {
623 ctor_kind: variant.ctor_kind,
624 discr: variant.discr,
625 struct_ctor: Some(def_id.index),
628 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
629 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
630 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
631 for field in &variant.fields {
632 if ctor_vis.is_at_least(field.vis, tcx) {
633 ctor_vis = field.vis;
637 let repr_options = get_repr_options(&tcx, adt_def_id);
640 kind: EntryKind::Struct(self.lazy(&data), repr_options),
641 visibility: self.lazy(&ctor_vis),
642 span: self.lazy(&tcx.def_span(def_id)),
643 attributes: LazySeq::empty(),
644 children: LazySeq::empty(),
645 stability: self.encode_stability(def_id),
646 deprecation: self.encode_deprecation(def_id),
648 ty: Some(self.encode_item_type(def_id)),
649 inherent_impls: LazySeq::empty(),
650 variances: LazySeq::empty(),
651 generics: Some(self.encode_generics(def_id)),
652 predicates: Some(self.encode_predicates(def_id)),
655 mir: self.encode_optimized_mir(def_id),
659 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
660 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
662 self.lazy(tcx.generics_of(def_id))
665 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
666 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
668 self.lazy(&tcx.predicates_of(def_id))
671 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
672 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
675 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
676 let ast_item = tcx.hir.expect_trait_item(node_id);
677 let trait_item = tcx.associated_item(def_id);
679 let container = match trait_item.defaultness {
680 hir::Defaultness::Default { has_value: true } =>
681 AssociatedContainer::TraitWithDefault,
682 hir::Defaultness::Default { has_value: false } =>
683 AssociatedContainer::TraitRequired,
684 hir::Defaultness::Final =>
685 span_bug!(ast_item.span, "traits cannot have final items"),
688 let kind = match trait_item.kind {
689 ty::AssociatedKind::Const => {
690 EntryKind::AssociatedConst(container, 0)
692 ty::AssociatedKind::Method => {
693 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
694 let arg_names = match *m {
695 hir::TraitMethod::Required(ref names) => {
696 self.encode_fn_arg_names(names)
698 hir::TraitMethod::Provided(body) => {
699 self.encode_fn_arg_names_for_body(body)
703 constness: hir::Constness::NotConst,
709 EntryKind::Method(self.lazy(&MethodData {
711 container: container,
712 has_self: trait_item.method_has_self_argument,
715 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
720 visibility: self.lazy(&trait_item.vis),
721 span: self.lazy(&ast_item.span),
722 attributes: self.encode_attributes(&ast_item.attrs),
723 children: LazySeq::empty(),
724 stability: self.encode_stability(def_id),
725 deprecation: self.encode_deprecation(def_id),
727 ty: match trait_item.kind {
728 ty::AssociatedKind::Const |
729 ty::AssociatedKind::Method => {
730 Some(self.encode_item_type(def_id))
732 ty::AssociatedKind::Type => {
733 if trait_item.defaultness.has_value() {
734 Some(self.encode_item_type(def_id))
740 inherent_impls: LazySeq::empty(),
741 variances: LazySeq::empty(),
742 generics: Some(self.encode_generics(def_id)),
743 predicates: Some(self.encode_predicates(def_id)),
745 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
746 Some(self.encode_body(body))
750 mir: self.encode_optimized_mir(def_id),
754 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
755 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
756 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
757 let ast_item = self.tcx.hir.expect_impl_item(node_id);
758 let impl_item = self.tcx.associated_item(def_id);
760 let container = match impl_item.defaultness {
761 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
762 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
763 hir::Defaultness::Default { has_value: false } =>
764 span_bug!(ast_item.span, "impl items always have values (currently)"),
767 let kind = match impl_item.kind {
768 ty::AssociatedKind::Const => {
769 EntryKind::AssociatedConst(container,
770 self.tcx.at(ast_item.span).mir_const_qualif(def_id))
772 ty::AssociatedKind::Method => {
773 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
775 constness: sig.constness,
776 arg_names: self.encode_fn_arg_names_for_body(body),
781 EntryKind::Method(self.lazy(&MethodData {
783 container: container,
784 has_self: impl_item.method_has_self_argument,
787 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
790 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
792 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
793 let generics = self.tcx.generics_of(def_id);
794 let types = generics.parent_types as usize + generics.types.len();
795 let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
796 let is_const_fn = sig.constness == hir::Constness::Const;
797 let ast = if is_const_fn { Some(body) } else { None };
798 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
799 (ast, needs_inline || is_const_fn || always_encode_mir)
806 visibility: self.lazy(&impl_item.vis),
807 span: self.lazy(&ast_item.span),
808 attributes: self.encode_attributes(&ast_item.attrs),
809 children: LazySeq::empty(),
810 stability: self.encode_stability(def_id),
811 deprecation: self.encode_deprecation(def_id),
813 ty: Some(self.encode_item_type(def_id)),
814 inherent_impls: LazySeq::empty(),
815 variances: LazySeq::empty(),
816 generics: Some(self.encode_generics(def_id)),
817 predicates: Some(self.encode_predicates(def_id)),
819 ast: ast.map(|body| self.encode_body(body)),
820 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
824 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
825 -> LazySeq<ast::Name> {
826 let _ignore = self.tcx.dep_graph.in_ignore();
827 let body = self.tcx.hir.body(body_id);
828 self.lazy_seq(body.arguments.iter().map(|arg| {
830 PatKind::Binding(_, _, name, _) => name.node,
831 _ => Symbol::intern("")
836 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
837 -> LazySeq<ast::Name> {
838 self.lazy_seq(names.iter().map(|name| name.node))
841 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
842 debug!("EntryBuilder::encode_mir({:?})", def_id);
843 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
844 let mir = self.tcx.optimized_mir(def_id);
845 Some(self.lazy(&mir))
851 // Encodes the inherent implementations of a structure, enumeration, or trait.
852 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
853 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
854 let implementations = self.tcx.inherent_impls(def_id);
855 if implementations.is_empty() {
858 self.lazy_seq(implementations.iter().map(|&def_id| {
859 assert!(def_id.is_local());
865 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
866 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
867 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
870 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
871 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
872 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
875 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
878 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
880 let kind = match item.node {
881 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
882 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
883 hir::ItemConst(..) => {
884 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id))
886 hir::ItemFn(_, _, constness, .., body) => {
888 constness: constness,
889 arg_names: self.encode_fn_arg_names_for_body(body),
892 EntryKind::Fn(self.lazy(&data))
894 hir::ItemMod(ref m) => {
895 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
897 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
898 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
899 hir::ItemTy(..) => EntryKind::Type,
900 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
901 hir::ItemStruct(ref struct_def, _) => {
902 let variant = tcx.adt_def(def_id).struct_variant();
904 // Encode def_ids for each field and method
905 // for methods, write all the stuff get_trait_method
907 let struct_ctor = if !struct_def.is_struct() {
908 Some(tcx.hir.local_def_id(struct_def.id()).index)
913 let repr_options = get_repr_options(&tcx, def_id);
915 EntryKind::Struct(self.lazy(&VariantData {
916 ctor_kind: variant.ctor_kind,
917 discr: variant.discr,
918 struct_ctor: struct_ctor,
921 hir::ItemUnion(..) => {
922 let variant = tcx.adt_def(def_id).struct_variant();
923 let repr_options = get_repr_options(&tcx, def_id);
925 EntryKind::Union(self.lazy(&VariantData {
926 ctor_kind: variant.ctor_kind,
927 discr: variant.discr,
931 hir::ItemDefaultImpl(..) => {
932 let data = ImplData {
933 polarity: hir::ImplPolarity::Positive,
934 defaultness: hir::Defaultness::Final,
936 coerce_unsized_info: None,
937 trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref)),
940 EntryKind::DefaultImpl(self.lazy(&data))
942 hir::ItemImpl(_, polarity, defaultness, ..) => {
943 let trait_ref = tcx.impl_trait_ref(def_id);
944 let parent = if let Some(trait_ref) = trait_ref {
945 let trait_def = tcx.trait_def(trait_ref.def_id);
946 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
948 specialization_graph::Node::Impl(parent) => Some(parent),
956 // if this is an impl of `CoerceUnsized`, create its
957 // "unsized info", else just store None
958 let coerce_unsized_info =
959 trait_ref.and_then(|t| {
960 if Some(t.def_id) == tcx.lang_items.coerce_unsized_trait() {
961 Some(tcx.at(item.span).coerce_unsized_info(def_id))
967 let data = ImplData {
969 defaultness: defaultness,
971 coerce_unsized_info: coerce_unsized_info,
972 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
975 EntryKind::Impl(self.lazy(&data))
977 hir::ItemTrait(..) => {
978 let trait_def = tcx.trait_def(def_id);
979 let data = TraitData {
980 unsafety: trait_def.unsafety,
981 paren_sugar: trait_def.paren_sugar,
982 has_default_impl: tcx.trait_has_default_impl(def_id),
983 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
986 EntryKind::Trait(self.lazy(&data))
988 hir::ItemExternCrate(_) |
989 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
994 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
995 span: self.lazy(&item.span),
996 attributes: self.encode_attributes(&item.attrs),
997 children: match item.node {
998 hir::ItemForeignMod(ref fm) => {
999 self.lazy_seq(fm.items
1001 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1003 hir::ItemEnum(..) => {
1004 let def = self.tcx.adt_def(def_id);
1005 self.lazy_seq(def.variants.iter().map(|v| {
1006 assert!(v.did.is_local());
1010 hir::ItemStruct(..) |
1011 hir::ItemUnion(..) => {
1012 let def = self.tcx.adt_def(def_id);
1013 self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
1014 assert!(f.did.is_local());
1019 hir::ItemTrait(..) => {
1020 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1021 assert!(def_id.is_local());
1025 _ => LazySeq::empty(),
1027 stability: self.encode_stability(def_id),
1028 deprecation: self.encode_deprecation(def_id),
1030 ty: match item.node {
1031 hir::ItemStatic(..) |
1032 hir::ItemConst(..) |
1036 hir::ItemStruct(..) |
1037 hir::ItemUnion(..) |
1038 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1041 inherent_impls: self.encode_inherent_implementations(def_id),
1042 variances: match item.node {
1044 hir::ItemStruct(..) |
1045 hir::ItemUnion(..) |
1046 hir::ItemTrait(..) => self.encode_variances_of(def_id),
1047 _ => LazySeq::empty(),
1049 generics: match item.node {
1050 hir::ItemStatic(..) |
1051 hir::ItemConst(..) |
1055 hir::ItemStruct(..) |
1056 hir::ItemUnion(..) |
1058 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1061 predicates: match item.node {
1062 hir::ItemStatic(..) |
1063 hir::ItemConst(..) |
1067 hir::ItemStruct(..) |
1068 hir::ItemUnion(..) |
1070 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1074 ast: match item.node {
1075 hir::ItemConst(_, body) |
1076 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
1077 Some(self.encode_body(body))
1081 mir: match item.node {
1082 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
1083 self.encode_optimized_mir(def_id)
1085 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1086 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1087 let tps_len = generics.ty_params.len();
1088 let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
1089 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1090 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
1091 self.encode_optimized_mir(def_id)
1101 /// Serialize the text of exported macros
1102 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1103 use syntax::print::pprust;
1105 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1106 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1108 visibility: self.lazy(&ty::Visibility::Public),
1109 span: self.lazy(¯o_def.span),
1111 attributes: self.encode_attributes(¯o_def.attrs),
1112 children: LazySeq::empty(),
1116 inherent_impls: LazySeq::empty(),
1117 variances: LazySeq::empty(),
1125 fn encode_info_for_ty_param(&mut self,
1126 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1128 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1131 kind: EntryKind::Type,
1132 visibility: self.lazy(&ty::Visibility::Public),
1133 span: self.lazy(&tcx.def_span(def_id)),
1134 attributes: LazySeq::empty(),
1135 children: LazySeq::empty(),
1139 ty: if has_default {
1140 Some(self.encode_item_type(def_id))
1144 inherent_impls: LazySeq::empty(),
1145 variances: LazySeq::empty(),
1154 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1155 debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
1158 kind: EntryKind::Type,
1159 visibility: self.lazy(&ty::Visibility::Public),
1160 span: self.lazy(&tcx.def_span(def_id)),
1161 attributes: LazySeq::empty(),
1162 children: LazySeq::empty(),
1166 ty: Some(self.encode_item_type(def_id)),
1167 inherent_impls: LazySeq::empty(),
1168 variances: LazySeq::empty(),
1169 generics: Some(self.encode_generics(def_id)),
1170 predicates: Some(self.encode_predicates(def_id)),
1177 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1178 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1181 let data = ClosureData {
1182 kind: tcx.closure_kind(def_id),
1183 ty: self.lazy(&tcx.closure_type(def_id)),
1187 kind: EntryKind::Closure(self.lazy(&data)),
1188 visibility: self.lazy(&ty::Visibility::Public),
1189 span: self.lazy(&tcx.def_span(def_id)),
1190 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1191 children: LazySeq::empty(),
1195 ty: Some(self.encode_item_type(def_id)),
1196 inherent_impls: LazySeq::empty(),
1197 variances: LazySeq::empty(),
1198 generics: Some(self.encode_generics(def_id)),
1202 mir: self.encode_optimized_mir(def_id),
1206 fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1207 debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
1209 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1210 let body = tcx.hir.body_owned_by(id);
1213 kind: EntryKind::Const(tcx.mir_const_qualif(def_id)),
1214 visibility: self.lazy(&ty::Visibility::Public),
1215 span: self.lazy(&tcx.def_span(def_id)),
1216 attributes: LazySeq::empty(),
1217 children: LazySeq::empty(),
1221 ty: Some(self.encode_item_type(def_id)),
1222 inherent_impls: LazySeq::empty(),
1223 variances: LazySeq::empty(),
1224 generics: Some(self.encode_generics(def_id)),
1225 predicates: Some(self.encode_predicates(def_id)),
1227 ast: Some(self.encode_body(body)),
1228 mir: self.encode_optimized_mir(def_id),
1232 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1233 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1234 // we rely on the HashStable specialization for [Attribute]
1235 // to properly filter things out.
1236 self.lazy_seq_from_slice(attrs)
1239 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1240 let used_libraries = self.tcx.sess.cstore.used_libraries();
1241 self.lazy_seq(used_libraries)
1244 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1245 let cstore = &*self.tcx.sess.cstore;
1246 let crates = cstore.crates();
1248 let mut deps = crates
1251 let dep = CrateDep {
1252 name: cstore.original_crate_name(cnum),
1253 hash: cstore.crate_hash(cnum),
1254 kind: cstore.dep_kind(cnum),
1258 .collect::<Vec<_>>();
1260 deps.sort_by_key(|&(cnum, _)| cnum);
1263 // Sanity-check the crate numbers
1264 let mut expected_cnum = 1;
1265 for &(n, _) in &deps {
1266 assert_eq!(n, CrateNum::new(expected_cnum));
1271 // We're just going to write a list of crate 'name-hash-version's, with
1272 // the assumption that they are numbered 1 to n.
1273 // FIXME (#2166): This is not nearly enough to support correct versioning
1274 // but is enough to get transitive crate dependencies working.
1275 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1278 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1280 let lang_items = tcx.lang_items.items().iter();
1281 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1282 if let Some(def_id) = opt_def_id {
1283 if def_id.is_local() {
1284 return Some((def_id.index, i));
1291 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1293 self.lazy_seq_ref(&tcx.lang_items.missing)
1296 /// Encodes an index, mapping each trait to its (local) implementations.
1297 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1298 debug!("IsolatedEncoder::encode_impls()");
1300 let mut visitor = ImplVisitor {
1304 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1306 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1308 // Bring everything into deterministic order for hashing
1309 all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1310 tcx.def_path_hash(trait_def_id)
1313 let all_impls: Vec<_> = all_impls
1315 .map(|(trait_def_id, mut impls)| {
1316 // Bring everything into deterministic order for hashing
1317 impls.sort_unstable_by_key(|&def_index| {
1318 tcx.hir.definitions().def_path_hash(def_index)
1322 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1323 impls: self.lazy_seq_from_slice(&impls[..]),
1328 self.lazy_seq_from_slice(&all_impls[..])
1331 // Encodes all symbols exported from this crate into the metadata.
1333 // This pass is seeded off the reachability list calculated in the
1334 // middle::reachable module but filters out items that either don't have a
1335 // symbol associated with them (they weren't translated) or if they're an FFI
1336 // definition (as that's not defined in this crate).
1337 fn encode_exported_symbols(&mut self, exported_symbols: &NodeSet) -> LazySeq<DefIndex> {
1339 self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
1342 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1343 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1345 self.lazy_seq(arr.iter().map(|slot| {
1347 Linkage::NotLinked |
1348 Linkage::IncludedFromDylib => None,
1350 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1351 Linkage::Static => Some(LinkagePreference::RequireStatic),
1355 None => LazySeq::empty(),
1359 fn encode_info_for_foreign_item(&mut self,
1360 (def_id, nitem): (DefId, &hir::ForeignItem))
1364 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1366 let kind = match nitem.node {
1367 hir::ForeignItemFn(_, ref names, _) => {
1369 constness: hir::Constness::NotConst,
1370 arg_names: self.encode_fn_arg_names(names),
1372 EntryKind::ForeignFn(self.lazy(&data))
1374 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1375 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1380 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1381 span: self.lazy(&nitem.span),
1382 attributes: self.encode_attributes(&nitem.attrs),
1383 children: LazySeq::empty(),
1384 stability: self.encode_stability(def_id),
1385 deprecation: self.encode_deprecation(def_id),
1387 ty: Some(self.encode_item_type(def_id)),
1388 inherent_impls: LazySeq::empty(),
1389 variances: LazySeq::empty(),
1390 generics: Some(self.encode_generics(def_id)),
1391 predicates: Some(self.encode_predicates(def_id)),
1399 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1400 index: IndexBuilder<'a, 'b, 'tcx>,
1403 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1404 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1405 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1407 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1408 intravisit::walk_expr(self, ex);
1409 self.index.encode_info_for_expr(ex);
1411 fn visit_item(&mut self, item: &'tcx hir::Item) {
1412 intravisit::walk_item(self, item);
1413 let def_id = self.index.tcx.hir.local_def_id(item.id);
1415 hir::ItemExternCrate(_) |
1416 hir::ItemUse(..) => (), // ignore these
1417 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1419 self.index.encode_addl_info_for_item(item);
1421 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1422 intravisit::walk_foreign_item(self, ni);
1423 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1424 self.index.record(def_id,
1425 IsolatedEncoder::encode_info_for_foreign_item,
1428 fn visit_variant(&mut self,
1429 v: &'tcx hir::Variant,
1430 g: &'tcx hir::Generics,
1432 intravisit::walk_variant(self, v, g, id);
1434 if let Some(discr) = v.node.disr_expr {
1435 let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1436 self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1439 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1440 intravisit::walk_generics(self, generics);
1441 self.index.encode_info_for_generics(generics);
1443 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1444 intravisit::walk_ty(self, ty);
1445 self.index.encode_info_for_ty(ty);
1447 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1448 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1449 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1453 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1454 fn encode_fields(&mut self, adt_def_id: DefId) {
1455 let def = self.tcx.adt_def(adt_def_id);
1456 for (variant_index, variant) in def.variants.iter().enumerate() {
1457 for (field_index, field) in variant.fields.iter().enumerate() {
1458 self.record(field.did,
1459 IsolatedEncoder::encode_field,
1460 (adt_def_id, Untracked((variant_index, field_index))));
1465 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1466 for ty_param in &generics.ty_params {
1467 let def_id = self.tcx.hir.local_def_id(ty_param.id);
1468 let has_default = Untracked(ty_param.default.is_some());
1469 self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
1473 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1474 if let hir::TyImplTrait(_) = ty.node {
1475 let def_id = self.tcx.hir.local_def_id(ty.id);
1476 self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
1480 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1482 hir::ExprClosure(..) => {
1483 let def_id = self.tcx.hir.local_def_id(expr.id);
1484 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1490 /// In some cases, along with the item itself, we also
1491 /// encode some sub-items. Usually we want some info from the item
1492 /// so it's easier to do that here then to wait until we would encounter
1493 /// normally in the visitor walk.
1494 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1495 let def_id = self.tcx.hir.local_def_id(item.id);
1497 hir::ItemStatic(..) |
1498 hir::ItemConst(..) |
1501 hir::ItemForeignMod(..) |
1502 hir::ItemGlobalAsm(..) |
1503 hir::ItemExternCrate(..) |
1505 hir::ItemDefaultImpl(..) |
1506 hir::ItemTy(..) => {
1507 // no sub-item recording needed in these cases
1509 hir::ItemEnum(..) => {
1510 self.encode_fields(def_id);
1512 let def = self.tcx.adt_def(def_id);
1513 for (i, variant) in def.variants.iter().enumerate() {
1514 self.record(variant.did,
1515 IsolatedEncoder::encode_enum_variant_info,
1516 (def_id, Untracked(i)));
1519 hir::ItemStruct(ref struct_def, _) => {
1520 self.encode_fields(def_id);
1522 // If the struct has a constructor, encode it.
1523 if !struct_def.is_struct() {
1524 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1525 self.record(ctor_def_id,
1526 IsolatedEncoder::encode_struct_ctor,
1527 (def_id, ctor_def_id));
1530 hir::ItemUnion(..) => {
1531 self.encode_fields(def_id);
1533 hir::ItemImpl(..) => {
1534 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1535 self.record(trait_item_def_id,
1536 IsolatedEncoder::encode_info_for_impl_item,
1540 hir::ItemTrait(..) => {
1541 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1542 self.record(item_def_id,
1543 IsolatedEncoder::encode_info_for_trait_item,
1551 struct ImplVisitor<'a, 'tcx: 'a> {
1552 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1553 impls: FxHashMap<DefId, Vec<DefIndex>>,
1556 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1557 fn visit_item(&mut self, item: &hir::Item) {
1558 if let hir::ItemImpl(..) = item.node {
1559 let impl_id = self.tcx.hir.local_def_id(item.id);
1560 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1562 .entry(trait_ref.def_id)
1564 .push(impl_id.index);
1569 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1571 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1572 // handled in `visit_item` above
1576 // NOTE(eddyb) The following comment was preserved for posterity, even
1577 // though it's no longer relevant as EBML (which uses nested & tagged
1578 // "documents") was replaced with a scheme that can't go out of bounds.
1580 // And here we run into yet another obscure archive bug: in which metadata
1581 // loaded from archives may have trailing garbage bytes. Awhile back one of
1582 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1583 // and opt) by having ebml generate an out-of-bounds panic when looking at
1586 // Upon investigation it turned out that the metadata file inside of an rlib
1587 // (and ar archive) was being corrupted. Some compilations would generate a
1588 // metadata file which would end in a few extra bytes, while other
1589 // compilations would not have these extra bytes appended to the end. These
1590 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1591 // being interpreted causing the out-of-bounds.
1593 // The root cause of why these extra bytes were appearing was never
1594 // discovered, and in the meantime the solution we're employing is to insert
1595 // the length of the metadata to the start of the metadata. Later on this
1596 // will allow us to slice the metadata to the precise length that we just
1597 // generated regardless of trailing bytes that end up in it.
1599 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1600 link_meta: &LinkMeta,
1601 exported_symbols: &NodeSet)
1604 let mut cursor = Cursor::new(vec![]);
1605 cursor.write_all(METADATA_HEADER).unwrap();
1607 // Will be filled with the root position after encoding everything.
1608 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1610 let compute_ich = (tcx.sess.opts.debugging_opts.query_dep_graph ||
1611 tcx.sess.opts.debugging_opts.incremental_cc) &&
1612 tcx.sess.opts.build_dep_graph();
1614 let (root, metadata_hashes) = {
1615 let mut ecx = EncodeContext {
1616 opaque: opaque::Encoder::new(&mut cursor),
1618 link_meta: link_meta,
1619 exported_symbols: exported_symbols,
1620 lazy_state: LazyState::NoNode,
1621 type_shorthands: Default::default(),
1622 predicate_shorthands: Default::default(),
1623 metadata_hashes: EncodedMetadataHashes::new(),
1624 compute_ich: compute_ich,
1627 // Encode the rustc version string in a predictable location.
1628 rustc_version().encode(&mut ecx).unwrap();
1630 // Encode all the entries and extra information in the crate,
1631 // culminating in the `CrateRoot` which points to all of it.
1632 let root = ecx.encode_crate_root();
1633 (root, ecx.metadata_hashes)
1635 let mut result = cursor.into_inner();
1637 // Encode the root position.
1638 let header = METADATA_HEADER.len();
1639 let pos = root.position;
1640 result[header + 0] = (pos >> 24) as u8;
1641 result[header + 1] = (pos >> 16) as u8;
1642 result[header + 2] = (pos >> 8) as u8;
1643 result[header + 3] = (pos >> 0) as u8;
1647 hashes: metadata_hashes,
1651 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1652 let ty = tcx.type_of(did);
1654 ty::TyAdt(ref def, _) => return def.repr,
1655 _ => bug!("{} is not an ADT", ty),