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,
19 use rustc::hir::def::CtorKind;
20 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LOCAL_CRATE};
21 use rustc::hir::map::definitions::{DefPathTable, GlobalMetaDataKind};
22 use rustc::ich::Fingerprint;
23 use rustc::middle::dependency_format::Linkage;
24 use rustc::middle::lang_items;
26 use rustc::traits::specialization_graph;
27 use rustc::ty::{self, Ty, TyCtxt, ReprOptions};
29 use rustc::session::config::{self, CrateTypeProcMacro};
30 use rustc::util::nodemap::{FxHashMap, NodeSet};
32 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
36 use std::io::prelude::*;
41 use syntax::ast::{self, CRATE_NODE_ID};
42 use syntax::codemap::Spanned;
44 use syntax::symbol::Symbol;
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<'a>,
54 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
55 link_meta: &'a LinkMeta,
56 exported_symbols: &'a NodeSet,
58 lazy_state: LazyState,
59 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
60 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
62 pub metadata_hashes: EncodedMetadataHashes,
63 pub compute_ich: bool,
66 macro_rules! encoder_methods {
67 ($($name:ident($ty:ty);)*) => {
68 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
69 self.opaque.$name(value)
74 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
75 type Error = <opaque::Encoder<'a> as Encoder>::Error;
77 fn emit_nil(&mut self) -> Result<(), Self::Error> {
104 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
105 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
106 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
110 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
111 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
112 self.emit_usize(seq.len)?;
116 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
120 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
121 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
122 self.encode_with_shorthand(ty, &ty.sty, |ecx| &mut ecx.type_shorthands)
126 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
127 fn specialized_encode(&mut self,
128 predicates: &ty::GenericPredicates<'tcx>)
129 -> Result<(), Self::Error> {
130 predicates.parent.encode(self)?;
131 predicates.predicates.len().encode(self)?;
132 for predicate in &predicates.predicates {
133 self.encode_with_shorthand(predicate, predicate, |ecx| &mut ecx.predicate_shorthands)?
139 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
141 pub fn position(&self) -> usize {
142 self.opaque.position()
145 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
146 assert_eq!(self.lazy_state, LazyState::NoNode);
147 let pos = self.position();
148 self.lazy_state = LazyState::NodeStart(pos);
149 let r = f(self, pos);
150 self.lazy_state = LazyState::NoNode;
154 fn emit_lazy_distance(&mut self,
157 -> Result<(), <Self as Encoder>::Error> {
158 let min_end = position + min_size;
159 let distance = match self.lazy_state {
160 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
161 LazyState::NodeStart(start) => {
162 assert!(min_end <= start);
165 LazyState::Previous(last_min_end) => {
166 assert!(last_min_end <= position);
167 position - last_min_end
170 self.lazy_state = LazyState::Previous(min_end);
171 self.emit_usize(distance)
174 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
175 self.emit_node(|ecx, pos| {
176 value.encode(ecx).unwrap();
178 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
179 Lazy::with_position(pos)
183 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
184 where I: IntoIterator<Item = T>,
187 self.emit_node(|ecx, pos| {
188 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
190 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
191 LazySeq::with_position_and_length(pos, len)
195 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
196 where I: IntoIterator<Item = &'b T>,
199 self.emit_node(|ecx, pos| {
200 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
202 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
203 LazySeq::with_position_and_length(pos, len)
207 /// Encode the given value or a previously cached shorthand.
208 fn encode_with_shorthand<T, U, M>(&mut self,
212 -> Result<(), <Self as Encoder>::Error>
213 where M: for<'b> Fn(&'b mut Self) -> &'b mut FxHashMap<T, usize>,
214 T: Clone + Eq + Hash,
217 let existing_shorthand = map(self).get(value).cloned();
218 if let Some(shorthand) = existing_shorthand {
219 return self.emit_usize(shorthand);
222 let start = self.position();
223 variant.encode(self)?;
224 let len = self.position() - start;
226 // The shorthand encoding uses the same usize as the
227 // discriminant, with an offset so they can't conflict.
228 let discriminant = unsafe { intrinsics::discriminant_value(variant) };
229 assert!(discriminant < SHORTHAND_OFFSET as u64);
230 let shorthand = start + SHORTHAND_OFFSET;
232 // Get the number of bits that leb128 could fit
233 // in the same space as the fully encoded type.
234 let leb128_bits = len * 7;
236 // Check that the shorthand is a not longer than the
237 // full encoding itself, i.e. it's an obvious win.
238 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
239 map(self).insert(value.clone(), shorthand);
245 // Encodes something that corresponds to a single DepNode::GlobalMetaData
246 // and registers the Fingerprint in the `metadata_hashes` map.
247 pub fn tracked<'x, DATA, R>(&'x mut self,
249 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
252 let mut entry_builder = IsolatedEncoder::new(self);
253 let ret = op(&mut entry_builder, data);
254 let (fingerprint, this) = entry_builder.finish();
256 if let Some(fingerprint) = fingerprint {
257 this.metadata_hashes.hashes.push(EncodedMetadataHash {
266 fn encode_info_for_items(&mut self) -> Index {
267 let krate = self.tcx.hir.krate();
268 let mut index = IndexBuilder::new(self);
269 index.record(DefId::local(CRATE_DEF_INDEX),
270 IsolatedEncoder::encode_info_for_mod,
271 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
272 let mut visitor = EncodeVisitor { index: index };
273 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
274 for macro_def in &krate.exported_macros {
275 visitor.visit_macro_def(macro_def);
277 visitor.index.into_items()
280 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
281 let definitions = self.tcx.hir.definitions();
282 self.lazy(definitions.def_path_table())
285 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
286 let codemap = self.tcx.sess.codemap();
287 let all_filemaps = codemap.files();
289 let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
291 let adapted = all_filemaps.iter()
293 // No need to re-export imported filemaps, as any downstream
294 // crate will import them from their original source.
295 !filemap.is_imported()
298 // When exporting FileMaps, we expand all paths to absolute
299 // paths because any relative paths are potentially relative to
300 // a wrong directory.
301 // However, if a path has been modified via
302 // `-Zremap-path-prefix` we assume the user has already set
303 // things up the way they want and don't touch the path values
305 let name = Path::new(&filemap.name);
306 if filemap.name_was_remapped ||
307 (name.is_relative() && working_dir_was_remapped) {
308 // This path of this FileMap has been modified by
309 // path-remapping, so we use it verbatim (and avoid cloning
310 // the whole map in the process).
313 let mut adapted = (**filemap).clone();
314 let abs_path = Path::new(&working_dir).join(name)
317 adapted.name = abs_path;
321 .collect::<Vec<_>>();
323 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
326 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
327 let mut i = self.position();
330 let global_metadata_def_index = move |kind: GlobalMetaDataKind| {
331 kind.def_index(tcx.hir.definitions().def_path_table())
334 let crate_deps = self.tracked(
335 global_metadata_def_index(GlobalMetaDataKind::CrateDeps),
336 IsolatedEncoder::encode_crate_deps,
338 let dylib_dependency_formats = self.tracked(
339 global_metadata_def_index(GlobalMetaDataKind::DylibDependencyFormats),
340 IsolatedEncoder::encode_dylib_dependency_formats,
342 let dep_bytes = self.position() - i;
344 // Encode the language items.
346 let lang_items = self.tracked(
347 global_metadata_def_index(GlobalMetaDataKind::LangItems),
348 IsolatedEncoder::encode_lang_items,
351 let lang_items_missing = self.tracked(
352 global_metadata_def_index(GlobalMetaDataKind::LangItemsMissing),
353 IsolatedEncoder::encode_lang_items_missing,
355 let lang_item_bytes = self.position() - i;
357 // Encode the native libraries used
359 let native_libraries = self.tracked(
360 global_metadata_def_index(GlobalMetaDataKind::NativeLibraries),
361 IsolatedEncoder::encode_native_libraries,
363 let native_lib_bytes = self.position() - i;
367 let codemap = self.encode_codemap();
368 let codemap_bytes = self.position() - i;
370 // Encode DefPathTable
372 let def_path_table = self.encode_def_path_table();
373 let def_path_table_bytes = self.position() - i;
375 // Encode the def IDs of impls, for coherence checking.
377 let impls = self.tracked(
378 global_metadata_def_index(GlobalMetaDataKind::Impls),
379 IsolatedEncoder::encode_impls,
381 let impl_bytes = self.position() - i;
383 // Encode exported symbols info.
385 let exported_symbols = self.tracked(
386 global_metadata_def_index(GlobalMetaDataKind::ExportedSymbols),
387 IsolatedEncoder::encode_exported_symbols,
388 self.exported_symbols);
389 let exported_symbols_bytes = self.position() - i;
391 // Encode and index the items.
393 let items = self.encode_info_for_items();
394 let item_bytes = self.position() - i;
397 let index = items.write_index(&mut self.opaque.cursor);
398 let index_bytes = self.position() - i;
401 let link_meta = self.link_meta;
402 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
403 let root = self.lazy(&CrateRoot {
404 name: tcx.crate_name(LOCAL_CRATE),
405 triple: tcx.sess.opts.target_triple.clone(),
406 hash: link_meta.crate_hash,
407 disambiguator: tcx.sess.local_crate_disambiguator(),
408 panic_strategy: Tracked::new(tcx.sess.panic_strategy()),
409 plugin_registrar_fn: tcx.sess
412 .map(|id| tcx.hir.local_def_id(id).index),
413 macro_derive_registrar: if is_proc_macro {
414 let id = tcx.sess.derive_registrar_fn.get().unwrap();
415 Some(tcx.hir.local_def_id(id).index)
420 crate_deps: crate_deps,
421 dylib_dependency_formats: dylib_dependency_formats,
422 lang_items: lang_items,
423 lang_items_missing: lang_items_missing,
424 native_libraries: native_libraries,
426 def_path_table: def_path_table,
428 exported_symbols: exported_symbols,
432 let total_bytes = self.position();
434 self.metadata_hashes.hashes.push(EncodedMetadataHash {
435 def_index: global_metadata_def_index(GlobalMetaDataKind::Krate),
436 hash: Fingerprint::from_smaller_hash(link_meta.crate_hash.as_u64())
439 if self.tcx.sess.meta_stats() {
440 let mut zero_bytes = 0;
441 for e in self.opaque.cursor.get_ref() {
447 println!("metadata stats:");
448 println!(" dep bytes: {}", dep_bytes);
449 println!(" lang item bytes: {}", lang_item_bytes);
450 println!(" native bytes: {}", native_lib_bytes);
451 println!(" codemap bytes: {}", codemap_bytes);
452 println!(" impl bytes: {}", impl_bytes);
453 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
454 println!(" def-path table bytes: {}", def_path_table_bytes);
455 println!(" item bytes: {}", item_bytes);
456 println!(" index bytes: {}", index_bytes);
457 println!(" zero bytes: {}", zero_bytes);
458 println!(" total bytes: {}", total_bytes);
465 // These are methods for encoding various things. They are meant to be used with
466 // IndexBuilder::record() and EncodeContext::tracked(). They actually
467 // would not have to be methods of IsolatedEncoder (free standing functions
468 // taking IsolatedEncoder as first argument would be just fine) but by making
469 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
470 // clause again and again.
471 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
472 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
473 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
475 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
478 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
480 let ty = tcx.type_of(def_id);
481 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
485 /// Encode data for the given variant of the given ADT. The
486 /// index of the variant is untracked: this is ok because we
487 /// will have to lookup the adt-def by its id, and that gives us
488 /// the right to access any information in the adt-def (including,
489 /// e.g., the length of the various vectors).
490 fn encode_enum_variant_info(&mut self,
491 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
494 let def = tcx.adt_def(enum_did);
495 let variant = &def.variants[index];
496 let def_id = variant.did;
497 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
499 let data = VariantData {
500 ctor_kind: variant.ctor_kind,
501 discr: variant.discr,
503 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
504 Some(self.lazy(&tcx.fn_sig(def_id)))
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: if variant.ctor_kind == CtorKind::Fn {
528 self.encode_variances_of(def_id)
532 generics: Some(self.encode_generics(def_id)),
533 predicates: Some(self.encode_predicates(def_id)),
536 mir: self.encode_optimized_mir(def_id),
540 fn encode_info_for_mod(&mut self,
541 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
546 let def_id = tcx.hir.local_def_id(id);
547 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
550 reexports: match tcx.export_map.get(&id) {
551 Some(exports) if *vis == hir::Public => {
552 self.lazy_seq_from_slice(exports.as_slice())
554 _ => LazySeq::empty(),
559 kind: EntryKind::Mod(self.lazy(&data)),
560 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
561 span: self.lazy(&md.inner),
562 attributes: self.encode_attributes(attrs),
563 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
564 tcx.hir.local_def_id(item_id.id).index
566 stability: self.encode_stability(def_id),
567 deprecation: self.encode_deprecation(def_id),
570 inherent_impls: LazySeq::empty(),
571 variances: LazySeq::empty(),
580 /// Encode data for the given field of the given variant of the
581 /// given ADT. The indices of the variant/field are untracked:
582 /// this is ok because we will have to lookup the adt-def by its
583 /// id, and that gives us the right to access any information in
584 /// the adt-def (including, e.g., the length of the various
586 fn encode_field(&mut self,
587 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
592 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
593 let field = &variant.fields[field_index];
595 let def_id = field.did;
596 debug!("IsolatedEncoder::encode_field({:?})", def_id);
598 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
599 let variant_data = tcx.hir.expect_variant_data(variant_id);
602 kind: EntryKind::Field,
603 visibility: self.lazy(&field.vis),
604 span: self.lazy(&tcx.def_span(def_id)),
605 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
606 children: LazySeq::empty(),
607 stability: self.encode_stability(def_id),
608 deprecation: self.encode_deprecation(def_id),
610 ty: Some(self.encode_item_type(def_id)),
611 inherent_impls: LazySeq::empty(),
612 variances: LazySeq::empty(),
613 generics: Some(self.encode_generics(def_id)),
614 predicates: Some(self.encode_predicates(def_id)),
621 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
622 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
624 let variant = tcx.adt_def(adt_def_id).struct_variant();
626 let data = VariantData {
627 ctor_kind: variant.ctor_kind,
628 discr: variant.discr,
629 struct_ctor: Some(def_id.index),
630 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
631 Some(self.lazy(&tcx.fn_sig(def_id)))
637 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
638 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
639 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
640 for field in &variant.fields {
641 if ctor_vis.is_at_least(field.vis, tcx) {
642 ctor_vis = field.vis;
646 let repr_options = get_repr_options(&tcx, adt_def_id);
649 kind: EntryKind::Struct(self.lazy(&data), repr_options),
650 visibility: self.lazy(&ctor_vis),
651 span: self.lazy(&tcx.def_span(def_id)),
652 attributes: LazySeq::empty(),
653 children: LazySeq::empty(),
654 stability: self.encode_stability(def_id),
655 deprecation: self.encode_deprecation(def_id),
657 ty: Some(self.encode_item_type(def_id)),
658 inherent_impls: LazySeq::empty(),
659 variances: if variant.ctor_kind == CtorKind::Fn {
660 self.encode_variances_of(def_id)
664 generics: Some(self.encode_generics(def_id)),
665 predicates: Some(self.encode_predicates(def_id)),
668 mir: self.encode_optimized_mir(def_id),
672 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
673 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
675 self.lazy(tcx.generics_of(def_id))
678 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
679 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
681 self.lazy(&tcx.predicates_of(def_id))
684 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
685 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
688 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
689 let ast_item = tcx.hir.expect_trait_item(node_id);
690 let trait_item = tcx.associated_item(def_id);
692 let container = match trait_item.defaultness {
693 hir::Defaultness::Default { has_value: true } =>
694 AssociatedContainer::TraitWithDefault,
695 hir::Defaultness::Default { has_value: false } =>
696 AssociatedContainer::TraitRequired,
697 hir::Defaultness::Final =>
698 span_bug!(ast_item.span, "traits cannot have final items"),
701 let kind = match trait_item.kind {
702 ty::AssociatedKind::Const => {
703 EntryKind::AssociatedConst(container, 0)
705 ty::AssociatedKind::Method => {
706 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
707 let arg_names = match *m {
708 hir::TraitMethod::Required(ref names) => {
709 self.encode_fn_arg_names(names)
711 hir::TraitMethod::Provided(body) => {
712 self.encode_fn_arg_names_for_body(body)
716 constness: hir::Constness::NotConst,
717 arg_names: arg_names,
718 sig: self.lazy(&tcx.fn_sig(def_id)),
723 EntryKind::Method(self.lazy(&MethodData {
725 container: container,
726 has_self: trait_item.method_has_self_argument,
729 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
734 visibility: self.lazy(&trait_item.vis),
735 span: self.lazy(&ast_item.span),
736 attributes: self.encode_attributes(&ast_item.attrs),
737 children: LazySeq::empty(),
738 stability: self.encode_stability(def_id),
739 deprecation: self.encode_deprecation(def_id),
741 ty: match trait_item.kind {
742 ty::AssociatedKind::Const |
743 ty::AssociatedKind::Method => {
744 Some(self.encode_item_type(def_id))
746 ty::AssociatedKind::Type => {
747 if trait_item.defaultness.has_value() {
748 Some(self.encode_item_type(def_id))
754 inherent_impls: LazySeq::empty(),
755 variances: if trait_item.kind == ty::AssociatedKind::Method {
756 self.encode_variances_of(def_id)
760 generics: Some(self.encode_generics(def_id)),
761 predicates: Some(self.encode_predicates(def_id)),
763 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
764 Some(self.encode_body(body))
768 mir: self.encode_optimized_mir(def_id),
772 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
773 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
776 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
777 let ast_item = self.tcx.hir.expect_impl_item(node_id);
778 let impl_item = self.tcx.associated_item(def_id);
780 let container = match impl_item.defaultness {
781 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
782 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
783 hir::Defaultness::Default { has_value: false } =>
784 span_bug!(ast_item.span, "impl items always have values (currently)"),
787 let kind = match impl_item.kind {
788 ty::AssociatedKind::Const => {
789 EntryKind::AssociatedConst(container,
790 self.tcx.at(ast_item.span).mir_const_qualif(def_id))
792 ty::AssociatedKind::Method => {
793 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
795 constness: sig.constness,
796 arg_names: self.encode_fn_arg_names_for_body(body),
797 sig: self.lazy(&tcx.fn_sig(def_id)),
802 EntryKind::Method(self.lazy(&MethodData {
804 container: container,
805 has_self: impl_item.method_has_self_argument,
808 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
811 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
813 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
814 let generics = self.tcx.generics_of(def_id);
815 let types = generics.parent_types as usize + generics.types.len();
816 let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
817 let is_const_fn = sig.constness == hir::Constness::Const;
818 let ast = if is_const_fn { Some(body) } else { None };
819 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
820 (ast, needs_inline || is_const_fn || always_encode_mir)
827 visibility: self.lazy(&impl_item.vis),
828 span: self.lazy(&ast_item.span),
829 attributes: self.encode_attributes(&ast_item.attrs),
830 children: LazySeq::empty(),
831 stability: self.encode_stability(def_id),
832 deprecation: self.encode_deprecation(def_id),
834 ty: Some(self.encode_item_type(def_id)),
835 inherent_impls: LazySeq::empty(),
836 variances: if impl_item.kind == ty::AssociatedKind::Method {
837 self.encode_variances_of(def_id)
841 generics: Some(self.encode_generics(def_id)),
842 predicates: Some(self.encode_predicates(def_id)),
844 ast: ast.map(|body| self.encode_body(body)),
845 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
849 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
850 -> LazySeq<ast::Name> {
851 let _ignore = self.tcx.dep_graph.in_ignore();
852 let body = self.tcx.hir.body(body_id);
853 self.lazy_seq(body.arguments.iter().map(|arg| {
855 PatKind::Binding(_, _, name, _) => name.node,
856 _ => Symbol::intern("")
861 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
862 -> LazySeq<ast::Name> {
863 self.lazy_seq(names.iter().map(|name| name.node))
866 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
867 debug!("EntryBuilder::encode_mir({:?})", def_id);
868 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
869 let mir = self.tcx.optimized_mir(def_id);
870 Some(self.lazy(&mir))
876 // Encodes the inherent implementations of a structure, enumeration, or trait.
877 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
878 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
879 let implementations = self.tcx.inherent_impls(def_id);
880 if implementations.is_empty() {
883 self.lazy_seq(implementations.iter().map(|&def_id| {
884 assert!(def_id.is_local());
890 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
891 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
892 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
895 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
896 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
897 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
900 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
903 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
905 let kind = match item.node {
906 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
907 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
908 hir::ItemConst(..) => {
909 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id))
911 hir::ItemFn(_, _, constness, .., body) => {
913 constness: constness,
914 arg_names: self.encode_fn_arg_names_for_body(body),
915 sig: self.lazy(&tcx.fn_sig(def_id)),
918 EntryKind::Fn(self.lazy(&data))
920 hir::ItemMod(ref m) => {
921 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
923 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
924 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
925 hir::ItemTy(..) => EntryKind::Type,
926 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
927 hir::ItemStruct(ref struct_def, _) => {
928 let variant = tcx.adt_def(def_id).struct_variant();
930 // Encode def_ids for each field and method
931 // for methods, write all the stuff get_trait_method
933 let struct_ctor = if !struct_def.is_struct() {
934 Some(tcx.hir.local_def_id(struct_def.id()).index)
939 let repr_options = get_repr_options(&tcx, def_id);
941 EntryKind::Struct(self.lazy(&VariantData {
942 ctor_kind: variant.ctor_kind,
943 discr: variant.discr,
944 struct_ctor: struct_ctor,
948 hir::ItemUnion(..) => {
949 let variant = tcx.adt_def(def_id).struct_variant();
950 let repr_options = get_repr_options(&tcx, def_id);
952 EntryKind::Union(self.lazy(&VariantData {
953 ctor_kind: variant.ctor_kind,
954 discr: variant.discr,
959 hir::ItemDefaultImpl(..) => {
960 let data = ImplData {
961 polarity: hir::ImplPolarity::Positive,
962 defaultness: hir::Defaultness::Final,
964 coerce_unsized_info: None,
965 trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref)),
968 EntryKind::DefaultImpl(self.lazy(&data))
970 hir::ItemImpl(_, polarity, defaultness, ..) => {
971 let trait_ref = tcx.impl_trait_ref(def_id);
972 let parent = if let Some(trait_ref) = trait_ref {
973 let trait_def = tcx.trait_def(trait_ref.def_id);
974 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
976 specialization_graph::Node::Impl(parent) => Some(parent),
984 // if this is an impl of `CoerceUnsized`, create its
985 // "unsized info", else just store None
986 let coerce_unsized_info =
987 trait_ref.and_then(|t| {
988 if Some(t.def_id) == tcx.lang_items.coerce_unsized_trait() {
989 Some(tcx.at(item.span).coerce_unsized_info(def_id))
995 let data = ImplData {
997 defaultness: defaultness,
999 coerce_unsized_info: coerce_unsized_info,
1000 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1003 EntryKind::Impl(self.lazy(&data))
1005 hir::ItemTrait(..) => {
1006 let trait_def = tcx.trait_def(def_id);
1007 let data = TraitData {
1008 unsafety: trait_def.unsafety,
1009 paren_sugar: trait_def.paren_sugar,
1010 has_default_impl: tcx.trait_has_default_impl(def_id),
1011 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1014 EntryKind::Trait(self.lazy(&data))
1016 hir::ItemExternCrate(_) |
1017 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1022 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1023 span: self.lazy(&item.span),
1024 attributes: self.encode_attributes(&item.attrs),
1025 children: match item.node {
1026 hir::ItemForeignMod(ref fm) => {
1027 self.lazy_seq(fm.items
1029 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1031 hir::ItemEnum(..) => {
1032 let def = self.tcx.adt_def(def_id);
1033 self.lazy_seq(def.variants.iter().map(|v| {
1034 assert!(v.did.is_local());
1038 hir::ItemStruct(..) |
1039 hir::ItemUnion(..) => {
1040 let def = self.tcx.adt_def(def_id);
1041 self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
1042 assert!(f.did.is_local());
1047 hir::ItemTrait(..) => {
1048 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1049 assert!(def_id.is_local());
1053 _ => LazySeq::empty(),
1055 stability: self.encode_stability(def_id),
1056 deprecation: self.encode_deprecation(def_id),
1058 ty: match item.node {
1059 hir::ItemStatic(..) |
1060 hir::ItemConst(..) |
1064 hir::ItemStruct(..) |
1065 hir::ItemUnion(..) |
1066 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1069 inherent_impls: self.encode_inherent_implementations(def_id),
1070 variances: match item.node {
1072 hir::ItemStruct(..) |
1073 hir::ItemUnion(..) |
1074 hir::ItemFn(..) => self.encode_variances_of(def_id),
1075 _ => LazySeq::empty(),
1077 generics: match item.node {
1078 hir::ItemStatic(..) |
1079 hir::ItemConst(..) |
1083 hir::ItemStruct(..) |
1084 hir::ItemUnion(..) |
1086 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1089 predicates: match item.node {
1090 hir::ItemStatic(..) |
1091 hir::ItemConst(..) |
1095 hir::ItemStruct(..) |
1096 hir::ItemUnion(..) |
1098 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1102 ast: match item.node {
1103 hir::ItemConst(_, body) |
1104 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
1105 Some(self.encode_body(body))
1109 mir: match item.node {
1110 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
1111 self.encode_optimized_mir(def_id)
1113 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1114 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1115 let tps_len = generics.ty_params.len();
1116 let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
1117 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1118 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
1119 self.encode_optimized_mir(def_id)
1129 /// Serialize the text of exported macros
1130 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1131 use syntax::print::pprust;
1133 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1134 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1135 legacy: macro_def.legacy,
1137 visibility: self.lazy(&ty::Visibility::Public),
1138 span: self.lazy(¯o_def.span),
1140 attributes: self.encode_attributes(¯o_def.attrs),
1141 children: LazySeq::empty(),
1145 inherent_impls: LazySeq::empty(),
1146 variances: LazySeq::empty(),
1154 fn encode_info_for_ty_param(&mut self,
1155 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1157 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1160 kind: EntryKind::Type,
1161 visibility: self.lazy(&ty::Visibility::Public),
1162 span: self.lazy(&tcx.def_span(def_id)),
1163 attributes: LazySeq::empty(),
1164 children: LazySeq::empty(),
1168 ty: if has_default {
1169 Some(self.encode_item_type(def_id))
1173 inherent_impls: LazySeq::empty(),
1174 variances: LazySeq::empty(),
1183 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1184 debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
1187 kind: EntryKind::Type,
1188 visibility: self.lazy(&ty::Visibility::Public),
1189 span: self.lazy(&tcx.def_span(def_id)),
1190 attributes: LazySeq::empty(),
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)),
1199 predicates: Some(self.encode_predicates(def_id)),
1206 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1207 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1210 let data = ClosureData {
1211 kind: tcx.closure_kind(def_id),
1212 sig: self.lazy(&tcx.fn_sig(def_id)),
1216 kind: EntryKind::Closure(self.lazy(&data)),
1217 visibility: self.lazy(&ty::Visibility::Public),
1218 span: self.lazy(&tcx.def_span(def_id)),
1219 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1220 children: LazySeq::empty(),
1224 ty: Some(self.encode_item_type(def_id)),
1225 inherent_impls: LazySeq::empty(),
1226 variances: LazySeq::empty(),
1227 generics: Some(self.encode_generics(def_id)),
1231 mir: self.encode_optimized_mir(def_id),
1235 fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1236 debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
1238 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1239 let body = tcx.hir.body_owned_by(id);
1242 kind: EntryKind::Const(tcx.mir_const_qualif(def_id)),
1243 visibility: self.lazy(&ty::Visibility::Public),
1244 span: self.lazy(&tcx.def_span(def_id)),
1245 attributes: LazySeq::empty(),
1246 children: LazySeq::empty(),
1250 ty: Some(self.encode_item_type(def_id)),
1251 inherent_impls: LazySeq::empty(),
1252 variances: LazySeq::empty(),
1253 generics: Some(self.encode_generics(def_id)),
1254 predicates: Some(self.encode_predicates(def_id)),
1256 ast: Some(self.encode_body(body)),
1257 mir: self.encode_optimized_mir(def_id),
1261 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1262 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1263 // we rely on the HashStable specialization for [Attribute]
1264 // to properly filter things out.
1265 self.lazy_seq_from_slice(attrs)
1268 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1269 let used_libraries = self.tcx.sess.cstore.used_libraries();
1270 self.lazy_seq(used_libraries)
1273 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1274 let cstore = &*self.tcx.sess.cstore;
1275 let crates = cstore.crates();
1277 let mut deps = crates
1280 let dep = CrateDep {
1281 name: cstore.original_crate_name(cnum),
1282 hash: cstore.crate_hash(cnum),
1283 kind: cstore.dep_kind(cnum),
1287 .collect::<Vec<_>>();
1289 deps.sort_by_key(|&(cnum, _)| cnum);
1292 // Sanity-check the crate numbers
1293 let mut expected_cnum = 1;
1294 for &(n, _) in &deps {
1295 assert_eq!(n, CrateNum::new(expected_cnum));
1300 // We're just going to write a list of crate 'name-hash-version's, with
1301 // the assumption that they are numbered 1 to n.
1302 // FIXME (#2166): This is not nearly enough to support correct versioning
1303 // but is enough to get transitive crate dependencies working.
1304 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1307 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1309 let lang_items = tcx.lang_items.items().iter();
1310 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1311 if let Some(def_id) = opt_def_id {
1312 if def_id.is_local() {
1313 return Some((def_id.index, i));
1320 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1322 self.lazy_seq_ref(&tcx.lang_items.missing)
1325 /// Encodes an index, mapping each trait to its (local) implementations.
1326 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1327 debug!("IsolatedEncoder::encode_impls()");
1329 let mut visitor = ImplVisitor {
1333 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1335 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1337 // Bring everything into deterministic order for hashing
1338 all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1339 tcx.def_path_hash(trait_def_id)
1342 let all_impls: Vec<_> = all_impls
1344 .map(|(trait_def_id, mut impls)| {
1345 // Bring everything into deterministic order for hashing
1346 impls.sort_unstable_by_key(|&def_index| {
1347 tcx.hir.definitions().def_path_hash(def_index)
1351 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1352 impls: self.lazy_seq_from_slice(&impls[..]),
1357 self.lazy_seq_from_slice(&all_impls[..])
1360 // Encodes all symbols exported from this crate into the metadata.
1362 // This pass is seeded off the reachability list calculated in the
1363 // middle::reachable module but filters out items that either don't have a
1364 // symbol associated with them (they weren't translated) or if they're an FFI
1365 // definition (as that's not defined in this crate).
1366 fn encode_exported_symbols(&mut self, exported_symbols: &NodeSet) -> LazySeq<DefIndex> {
1368 self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
1371 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1372 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1374 self.lazy_seq(arr.iter().map(|slot| {
1376 Linkage::NotLinked |
1377 Linkage::IncludedFromDylib => None,
1379 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1380 Linkage::Static => Some(LinkagePreference::RequireStatic),
1384 None => LazySeq::empty(),
1388 fn encode_info_for_foreign_item(&mut self,
1389 (def_id, nitem): (DefId, &hir::ForeignItem))
1393 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1395 let kind = match nitem.node {
1396 hir::ForeignItemFn(_, ref names, _) => {
1398 constness: hir::Constness::NotConst,
1399 arg_names: self.encode_fn_arg_names(names),
1400 sig: self.lazy(&tcx.fn_sig(def_id)),
1402 EntryKind::ForeignFn(self.lazy(&data))
1404 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1405 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1410 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1411 span: self.lazy(&nitem.span),
1412 attributes: self.encode_attributes(&nitem.attrs),
1413 children: LazySeq::empty(),
1414 stability: self.encode_stability(def_id),
1415 deprecation: self.encode_deprecation(def_id),
1417 ty: Some(self.encode_item_type(def_id)),
1418 inherent_impls: LazySeq::empty(),
1419 variances: match nitem.node {
1420 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1421 _ => LazySeq::empty(),
1423 generics: Some(self.encode_generics(def_id)),
1424 predicates: Some(self.encode_predicates(def_id)),
1432 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1433 index: IndexBuilder<'a, 'b, 'tcx>,
1436 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1437 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1438 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1440 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1441 intravisit::walk_expr(self, ex);
1442 self.index.encode_info_for_expr(ex);
1444 fn visit_item(&mut self, item: &'tcx hir::Item) {
1445 intravisit::walk_item(self, item);
1446 let def_id = self.index.tcx.hir.local_def_id(item.id);
1448 hir::ItemExternCrate(_) |
1449 hir::ItemUse(..) => (), // ignore these
1450 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1452 self.index.encode_addl_info_for_item(item);
1454 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1455 intravisit::walk_foreign_item(self, ni);
1456 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1457 self.index.record(def_id,
1458 IsolatedEncoder::encode_info_for_foreign_item,
1461 fn visit_variant(&mut self,
1462 v: &'tcx hir::Variant,
1463 g: &'tcx hir::Generics,
1465 intravisit::walk_variant(self, v, g, id);
1467 if let Some(discr) = v.node.disr_expr {
1468 let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1469 self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1472 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1473 intravisit::walk_generics(self, generics);
1474 self.index.encode_info_for_generics(generics);
1476 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1477 intravisit::walk_ty(self, ty);
1478 self.index.encode_info_for_ty(ty);
1480 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1481 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1482 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1486 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1487 fn encode_fields(&mut self, adt_def_id: DefId) {
1488 let def = self.tcx.adt_def(adt_def_id);
1489 for (variant_index, variant) in def.variants.iter().enumerate() {
1490 for (field_index, field) in variant.fields.iter().enumerate() {
1491 self.record(field.did,
1492 IsolatedEncoder::encode_field,
1493 (adt_def_id, Untracked((variant_index, field_index))));
1498 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1499 for ty_param in &generics.ty_params {
1500 let def_id = self.tcx.hir.local_def_id(ty_param.id);
1501 let has_default = Untracked(ty_param.default.is_some());
1502 self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
1506 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1507 if let hir::TyImplTrait(_) = ty.node {
1508 let def_id = self.tcx.hir.local_def_id(ty.id);
1509 self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
1513 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1515 hir::ExprClosure(..) => {
1516 let def_id = self.tcx.hir.local_def_id(expr.id);
1517 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1523 /// In some cases, along with the item itself, we also
1524 /// encode some sub-items. Usually we want some info from the item
1525 /// so it's easier to do that here then to wait until we would encounter
1526 /// normally in the visitor walk.
1527 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1528 let def_id = self.tcx.hir.local_def_id(item.id);
1530 hir::ItemStatic(..) |
1531 hir::ItemConst(..) |
1534 hir::ItemForeignMod(..) |
1535 hir::ItemGlobalAsm(..) |
1536 hir::ItemExternCrate(..) |
1538 hir::ItemDefaultImpl(..) |
1539 hir::ItemTy(..) => {
1540 // no sub-item recording needed in these cases
1542 hir::ItemEnum(..) => {
1543 self.encode_fields(def_id);
1545 let def = self.tcx.adt_def(def_id);
1546 for (i, variant) in def.variants.iter().enumerate() {
1547 self.record(variant.did,
1548 IsolatedEncoder::encode_enum_variant_info,
1549 (def_id, Untracked(i)));
1552 hir::ItemStruct(ref struct_def, _) => {
1553 self.encode_fields(def_id);
1555 // If the struct has a constructor, encode it.
1556 if !struct_def.is_struct() {
1557 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1558 self.record(ctor_def_id,
1559 IsolatedEncoder::encode_struct_ctor,
1560 (def_id, ctor_def_id));
1563 hir::ItemUnion(..) => {
1564 self.encode_fields(def_id);
1566 hir::ItemImpl(..) => {
1567 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1568 self.record(trait_item_def_id,
1569 IsolatedEncoder::encode_info_for_impl_item,
1573 hir::ItemTrait(..) => {
1574 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1575 self.record(item_def_id,
1576 IsolatedEncoder::encode_info_for_trait_item,
1584 struct ImplVisitor<'a, 'tcx: 'a> {
1585 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1586 impls: FxHashMap<DefId, Vec<DefIndex>>,
1589 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1590 fn visit_item(&mut self, item: &hir::Item) {
1591 if let hir::ItemImpl(..) = item.node {
1592 let impl_id = self.tcx.hir.local_def_id(item.id);
1593 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1595 .entry(trait_ref.def_id)
1597 .push(impl_id.index);
1602 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1604 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1605 // handled in `visit_item` above
1609 // NOTE(eddyb) The following comment was preserved for posterity, even
1610 // though it's no longer relevant as EBML (which uses nested & tagged
1611 // "documents") was replaced with a scheme that can't go out of bounds.
1613 // And here we run into yet another obscure archive bug: in which metadata
1614 // loaded from archives may have trailing garbage bytes. Awhile back one of
1615 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1616 // and opt) by having ebml generate an out-of-bounds panic when looking at
1619 // Upon investigation it turned out that the metadata file inside of an rlib
1620 // (and ar archive) was being corrupted. Some compilations would generate a
1621 // metadata file which would end in a few extra bytes, while other
1622 // compilations would not have these extra bytes appended to the end. These
1623 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1624 // being interpreted causing the out-of-bounds.
1626 // The root cause of why these extra bytes were appearing was never
1627 // discovered, and in the meantime the solution we're employing is to insert
1628 // the length of the metadata to the start of the metadata. Later on this
1629 // will allow us to slice the metadata to the precise length that we just
1630 // generated regardless of trailing bytes that end up in it.
1632 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1633 link_meta: &LinkMeta,
1634 exported_symbols: &NodeSet)
1637 let mut cursor = Cursor::new(vec![]);
1638 cursor.write_all(METADATA_HEADER).unwrap();
1640 // Will be filled with the root position after encoding everything.
1641 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1643 let compute_ich = (tcx.sess.opts.debugging_opts.query_dep_graph ||
1644 tcx.sess.opts.debugging_opts.incremental_cc) &&
1645 tcx.sess.opts.build_dep_graph();
1647 let (root, metadata_hashes) = {
1648 let mut ecx = EncodeContext {
1649 opaque: opaque::Encoder::new(&mut cursor),
1651 link_meta: link_meta,
1652 exported_symbols: exported_symbols,
1653 lazy_state: LazyState::NoNode,
1654 type_shorthands: Default::default(),
1655 predicate_shorthands: Default::default(),
1656 metadata_hashes: EncodedMetadataHashes::new(),
1657 compute_ich: compute_ich,
1660 // Encode the rustc version string in a predictable location.
1661 rustc_version().encode(&mut ecx).unwrap();
1663 // Encode all the entries and extra information in the crate,
1664 // culminating in the `CrateRoot` which points to all of it.
1665 let root = ecx.encode_crate_root();
1666 (root, ecx.metadata_hashes)
1668 let mut result = cursor.into_inner();
1670 // Encode the root position.
1671 let header = METADATA_HEADER.len();
1672 let pos = root.position;
1673 result[header + 0] = (pos >> 24) as u8;
1674 result[header + 1] = (pos >> 16) as u8;
1675 result[header + 2] = (pos >> 8) as u8;
1676 result[header + 3] = (pos >> 0) as u8;
1680 hashes: metadata_hashes,
1684 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1685 let ty = tcx.type_of(did);
1687 ty::TyAdt(ref def, _) => return def.repr,
1688 _ => bug!("{} is not an ADT", ty),