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 has_default_lib_allocator =
404 attr::contains_name(tcx.hir.krate_attrs(), "default_lib_allocator");
405 let has_global_allocator = tcx.sess.has_global_allocator.get();
406 let root = self.lazy(&CrateRoot {
407 name: tcx.crate_name(LOCAL_CRATE),
408 triple: tcx.sess.opts.target_triple.clone(),
409 hash: link_meta.crate_hash,
410 disambiguator: tcx.sess.local_crate_disambiguator(),
411 panic_strategy: Tracked::new(tcx.sess.panic_strategy()),
412 has_global_allocator: Tracked::new(has_global_allocator),
413 has_default_lib_allocator: Tracked::new(has_default_lib_allocator),
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)
426 dylib_dependency_formats,
437 let total_bytes = self.position();
439 self.metadata_hashes.hashes.push(EncodedMetadataHash {
440 def_index: global_metadata_def_index(GlobalMetaDataKind::Krate),
441 hash: 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,
508 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
509 Some(self.lazy(&tcx.fn_sig(def_id)))
515 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
516 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
519 kind: EntryKind::Variant(self.lazy(&data)),
520 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
521 span: self.lazy(&tcx.def_span(def_id)),
522 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
523 children: self.lazy_seq(variant.fields.iter().map(|f| {
524 assert!(f.did.is_local());
527 stability: self.encode_stability(def_id),
528 deprecation: self.encode_deprecation(def_id),
530 ty: Some(self.encode_item_type(def_id)),
531 inherent_impls: LazySeq::empty(),
532 variances: if variant.ctor_kind == CtorKind::Fn {
533 self.encode_variances_of(def_id)
537 generics: Some(self.encode_generics(def_id)),
538 predicates: Some(self.encode_predicates(def_id)),
541 mir: self.encode_optimized_mir(def_id),
545 fn encode_info_for_mod(&mut self,
546 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
551 let hir_id = tcx.hir.node_to_hir_id(id);
552 let def_id = tcx.hir.local_def_id(id);
553 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
556 reexports: match tcx.module_exports(hir_id) {
557 Some(ref exports) if *vis == hir::Public => {
558 self.lazy_seq_from_slice(exports.as_slice())
560 _ => LazySeq::empty(),
565 kind: EntryKind::Mod(self.lazy(&data)),
566 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
567 span: self.lazy(&tcx.def_span(def_id)),
568 attributes: self.encode_attributes(attrs),
569 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
570 tcx.hir.local_def_id(item_id.id).index
572 stability: self.encode_stability(def_id),
573 deprecation: self.encode_deprecation(def_id),
576 inherent_impls: LazySeq::empty(),
577 variances: LazySeq::empty(),
586 /// Encode data for the given field of the given variant of the
587 /// given ADT. The indices of the variant/field are untracked:
588 /// this is ok because we will have to lookup the adt-def by its
589 /// id, and that gives us the right to access any information in
590 /// the adt-def (including, e.g., the length of the various
592 fn encode_field(&mut self,
593 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
598 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
599 let field = &variant.fields[field_index];
601 let def_id = field.did;
602 debug!("IsolatedEncoder::encode_field({:?})", def_id);
604 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
605 let variant_data = tcx.hir.expect_variant_data(variant_id);
608 kind: EntryKind::Field,
609 visibility: self.lazy(&field.vis),
610 span: self.lazy(&tcx.def_span(def_id)),
611 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
612 children: LazySeq::empty(),
613 stability: self.encode_stability(def_id),
614 deprecation: self.encode_deprecation(def_id),
616 ty: Some(self.encode_item_type(def_id)),
617 inherent_impls: LazySeq::empty(),
618 variances: LazySeq::empty(),
619 generics: Some(self.encode_generics(def_id)),
620 predicates: Some(self.encode_predicates(def_id)),
627 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
628 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
630 let variant = tcx.adt_def(adt_def_id).struct_variant();
632 let data = VariantData {
633 ctor_kind: variant.ctor_kind,
634 discr: variant.discr,
635 struct_ctor: Some(def_id.index),
636 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
637 Some(self.lazy(&tcx.fn_sig(def_id)))
643 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
644 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
645 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
646 for field in &variant.fields {
647 if ctor_vis.is_at_least(field.vis, tcx) {
648 ctor_vis = field.vis;
652 let repr_options = get_repr_options(&tcx, adt_def_id);
655 kind: EntryKind::Struct(self.lazy(&data), repr_options),
656 visibility: self.lazy(&ctor_vis),
657 span: self.lazy(&tcx.def_span(def_id)),
658 attributes: LazySeq::empty(),
659 children: LazySeq::empty(),
660 stability: self.encode_stability(def_id),
661 deprecation: self.encode_deprecation(def_id),
663 ty: Some(self.encode_item_type(def_id)),
664 inherent_impls: LazySeq::empty(),
665 variances: if variant.ctor_kind == CtorKind::Fn {
666 self.encode_variances_of(def_id)
670 generics: Some(self.encode_generics(def_id)),
671 predicates: Some(self.encode_predicates(def_id)),
674 mir: self.encode_optimized_mir(def_id),
678 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
679 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
681 self.lazy(tcx.generics_of(def_id))
684 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
685 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
687 self.lazy(&tcx.predicates_of(def_id))
690 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
691 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
694 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
695 let ast_item = tcx.hir.expect_trait_item(node_id);
696 let trait_item = tcx.associated_item(def_id);
698 let container = match trait_item.defaultness {
699 hir::Defaultness::Default { has_value: true } =>
700 AssociatedContainer::TraitWithDefault,
701 hir::Defaultness::Default { has_value: false } =>
702 AssociatedContainer::TraitRequired,
703 hir::Defaultness::Final =>
704 span_bug!(ast_item.span, "traits cannot have final items"),
707 let kind = match trait_item.kind {
708 ty::AssociatedKind::Const => {
709 EntryKind::AssociatedConst(container, 0)
711 ty::AssociatedKind::Method => {
712 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
713 let arg_names = match *m {
714 hir::TraitMethod::Required(ref names) => {
715 self.encode_fn_arg_names(names)
717 hir::TraitMethod::Provided(body) => {
718 self.encode_fn_arg_names_for_body(body)
722 constness: hir::Constness::NotConst,
724 sig: self.lazy(&tcx.fn_sig(def_id)),
729 EntryKind::Method(self.lazy(&MethodData {
732 has_self: trait_item.method_has_self_argument,
735 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
740 visibility: self.lazy(&trait_item.vis),
741 span: self.lazy(&ast_item.span),
742 attributes: self.encode_attributes(&ast_item.attrs),
743 children: LazySeq::empty(),
744 stability: self.encode_stability(def_id),
745 deprecation: self.encode_deprecation(def_id),
747 ty: match trait_item.kind {
748 ty::AssociatedKind::Const |
749 ty::AssociatedKind::Method => {
750 Some(self.encode_item_type(def_id))
752 ty::AssociatedKind::Type => {
753 if trait_item.defaultness.has_value() {
754 Some(self.encode_item_type(def_id))
760 inherent_impls: LazySeq::empty(),
761 variances: if trait_item.kind == ty::AssociatedKind::Method {
762 self.encode_variances_of(def_id)
766 generics: Some(self.encode_generics(def_id)),
767 predicates: Some(self.encode_predicates(def_id)),
769 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
770 Some(self.encode_body(body))
774 mir: self.encode_optimized_mir(def_id),
778 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
779 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
782 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
783 let ast_item = self.tcx.hir.expect_impl_item(node_id);
784 let impl_item = self.tcx.associated_item(def_id);
786 let container = match impl_item.defaultness {
787 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
788 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
789 hir::Defaultness::Default { has_value: false } =>
790 span_bug!(ast_item.span, "impl items always have values (currently)"),
793 let kind = match impl_item.kind {
794 ty::AssociatedKind::Const => {
795 EntryKind::AssociatedConst(container,
796 self.tcx.at(ast_item.span).mir_const_qualif(def_id).0)
798 ty::AssociatedKind::Method => {
799 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
801 constness: sig.constness,
802 arg_names: self.encode_fn_arg_names_for_body(body),
803 sig: self.lazy(&tcx.fn_sig(def_id)),
808 EntryKind::Method(self.lazy(&MethodData {
811 has_self: impl_item.method_has_self_argument,
814 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
817 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
819 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
820 let generics = self.tcx.generics_of(def_id);
821 let types = generics.parent_types as usize + generics.types.len();
822 let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
823 let is_const_fn = sig.constness == hir::Constness::Const;
824 let ast = if is_const_fn { Some(body) } else { None };
825 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
826 (ast, needs_inline || is_const_fn || always_encode_mir)
833 visibility: self.lazy(&impl_item.vis),
834 span: self.lazy(&ast_item.span),
835 attributes: self.encode_attributes(&ast_item.attrs),
836 children: LazySeq::empty(),
837 stability: self.encode_stability(def_id),
838 deprecation: self.encode_deprecation(def_id),
840 ty: Some(self.encode_item_type(def_id)),
841 inherent_impls: LazySeq::empty(),
842 variances: if impl_item.kind == ty::AssociatedKind::Method {
843 self.encode_variances_of(def_id)
847 generics: Some(self.encode_generics(def_id)),
848 predicates: Some(self.encode_predicates(def_id)),
850 ast: ast.map(|body| self.encode_body(body)),
851 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
855 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
856 -> LazySeq<ast::Name> {
857 let _ignore = self.tcx.dep_graph.in_ignore();
858 let body = self.tcx.hir.body(body_id);
859 self.lazy_seq(body.arguments.iter().map(|arg| {
861 PatKind::Binding(_, _, name, _) => name.node,
862 _ => Symbol::intern("")
867 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
868 -> LazySeq<ast::Name> {
869 self.lazy_seq(names.iter().map(|name| name.node))
872 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
873 debug!("EntryBuilder::encode_mir({:?})", def_id);
874 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
875 let mir = self.tcx.optimized_mir(def_id);
876 Some(self.lazy(&mir))
882 // Encodes the inherent implementations of a structure, enumeration, or trait.
883 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
884 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
885 let implementations = self.tcx.inherent_impls(def_id);
886 if implementations.is_empty() {
889 self.lazy_seq(implementations.iter().map(|&def_id| {
890 assert!(def_id.is_local());
896 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
897 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
898 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
901 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
902 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
903 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
906 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
909 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
911 let kind = match item.node {
912 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
913 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
914 hir::ItemConst(..) => {
915 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id).0)
917 hir::ItemFn(_, _, constness, .., body) => {
920 arg_names: self.encode_fn_arg_names_for_body(body),
921 sig: self.lazy(&tcx.fn_sig(def_id)),
924 EntryKind::Fn(self.lazy(&data))
926 hir::ItemMod(ref m) => {
927 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
929 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
930 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
931 hir::ItemTy(..) => EntryKind::Type,
932 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
933 hir::ItemStruct(ref struct_def, _) => {
934 let variant = tcx.adt_def(def_id).struct_variant();
936 // Encode def_ids for each field and method
937 // for methods, write all the stuff get_trait_method
939 let struct_ctor = if !struct_def.is_struct() {
940 Some(tcx.hir.local_def_id(struct_def.id()).index)
945 let repr_options = get_repr_options(&tcx, def_id);
947 EntryKind::Struct(self.lazy(&VariantData {
948 ctor_kind: variant.ctor_kind,
949 discr: variant.discr,
954 hir::ItemUnion(..) => {
955 let variant = tcx.adt_def(def_id).struct_variant();
956 let repr_options = get_repr_options(&tcx, def_id);
958 EntryKind::Union(self.lazy(&VariantData {
959 ctor_kind: variant.ctor_kind,
960 discr: variant.discr,
965 hir::ItemDefaultImpl(..) => {
966 let data = ImplData {
967 polarity: hir::ImplPolarity::Positive,
968 defaultness: hir::Defaultness::Final,
970 coerce_unsized_info: None,
971 trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref)),
974 EntryKind::DefaultImpl(self.lazy(&data))
976 hir::ItemImpl(_, polarity, defaultness, ..) => {
977 let trait_ref = tcx.impl_trait_ref(def_id);
978 let parent = if let Some(trait_ref) = trait_ref {
979 let trait_def = tcx.trait_def(trait_ref.def_id);
980 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
982 specialization_graph::Node::Impl(parent) => Some(parent),
990 // if this is an impl of `CoerceUnsized`, create its
991 // "unsized info", else just store None
992 let coerce_unsized_info =
993 trait_ref.and_then(|t| {
994 if Some(t.def_id) == tcx.lang_items.coerce_unsized_trait() {
995 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1001 let data = ImplData {
1004 parent_impl: parent,
1005 coerce_unsized_info,
1006 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1009 EntryKind::Impl(self.lazy(&data))
1011 hir::ItemTrait(..) => {
1012 let trait_def = tcx.trait_def(def_id);
1013 let data = TraitData {
1014 unsafety: trait_def.unsafety,
1015 paren_sugar: trait_def.paren_sugar,
1016 has_default_impl: tcx.trait_has_default_impl(def_id),
1017 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1020 EntryKind::Trait(self.lazy(&data))
1022 hir::ItemExternCrate(_) |
1023 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1028 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1029 span: self.lazy(&item.span),
1030 attributes: self.encode_attributes(&item.attrs),
1031 children: match item.node {
1032 hir::ItemForeignMod(ref fm) => {
1033 self.lazy_seq(fm.items
1035 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1037 hir::ItemEnum(..) => {
1038 let def = self.tcx.adt_def(def_id);
1039 self.lazy_seq(def.variants.iter().map(|v| {
1040 assert!(v.did.is_local());
1044 hir::ItemStruct(..) |
1045 hir::ItemUnion(..) => {
1046 let def = self.tcx.adt_def(def_id);
1047 self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
1048 assert!(f.did.is_local());
1053 hir::ItemTrait(..) => {
1054 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1055 assert!(def_id.is_local());
1059 _ => LazySeq::empty(),
1061 stability: self.encode_stability(def_id),
1062 deprecation: self.encode_deprecation(def_id),
1064 ty: match item.node {
1065 hir::ItemStatic(..) |
1066 hir::ItemConst(..) |
1070 hir::ItemStruct(..) |
1071 hir::ItemUnion(..) |
1072 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1075 inherent_impls: self.encode_inherent_implementations(def_id),
1076 variances: match item.node {
1078 hir::ItemStruct(..) |
1079 hir::ItemUnion(..) |
1080 hir::ItemFn(..) => self.encode_variances_of(def_id),
1081 _ => LazySeq::empty(),
1083 generics: match item.node {
1084 hir::ItemStatic(..) |
1085 hir::ItemConst(..) |
1089 hir::ItemStruct(..) |
1090 hir::ItemUnion(..) |
1092 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1095 predicates: match item.node {
1096 hir::ItemStatic(..) |
1097 hir::ItemConst(..) |
1101 hir::ItemStruct(..) |
1102 hir::ItemUnion(..) |
1104 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1108 ast: match item.node {
1109 hir::ItemConst(_, body) |
1110 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
1111 Some(self.encode_body(body))
1115 mir: match item.node {
1116 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
1117 self.encode_optimized_mir(def_id)
1119 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1120 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1121 let tps_len = generics.ty_params.len();
1122 let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
1123 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1124 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
1125 self.encode_optimized_mir(def_id)
1135 /// Serialize the text of exported macros
1136 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1137 use syntax::print::pprust;
1138 let def_id = self.tcx.hir.local_def_id(macro_def.id);
1140 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1141 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1142 legacy: macro_def.legacy,
1144 visibility: self.lazy(&ty::Visibility::Public),
1145 span: self.lazy(¯o_def.span),
1146 attributes: self.encode_attributes(¯o_def.attrs),
1147 stability: self.encode_stability(def_id),
1148 deprecation: self.encode_deprecation(def_id),
1150 children: LazySeq::empty(),
1152 inherent_impls: LazySeq::empty(),
1153 variances: LazySeq::empty(),
1161 fn encode_info_for_ty_param(&mut self,
1162 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1164 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1167 kind: EntryKind::Type,
1168 visibility: self.lazy(&ty::Visibility::Public),
1169 span: self.lazy(&tcx.def_span(def_id)),
1170 attributes: LazySeq::empty(),
1171 children: LazySeq::empty(),
1175 ty: if has_default {
1176 Some(self.encode_item_type(def_id))
1180 inherent_impls: LazySeq::empty(),
1181 variances: LazySeq::empty(),
1190 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1191 debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
1194 kind: EntryKind::Type,
1195 visibility: self.lazy(&ty::Visibility::Public),
1196 span: self.lazy(&tcx.def_span(def_id)),
1197 attributes: LazySeq::empty(),
1198 children: LazySeq::empty(),
1202 ty: Some(self.encode_item_type(def_id)),
1203 inherent_impls: LazySeq::empty(),
1204 variances: LazySeq::empty(),
1205 generics: Some(self.encode_generics(def_id)),
1206 predicates: Some(self.encode_predicates(def_id)),
1213 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1214 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1217 let kind = if let Some(sig) = self.tcx.generator_sig(def_id) {
1218 let layout = self.tcx.generator_layout(def_id);
1219 let data = GeneratorData {
1221 layout: layout.clone(),
1223 EntryKind::Generator(self.lazy(&data))
1225 let data = ClosureData {
1226 kind: tcx.closure_kind(def_id),
1227 sig: self.lazy(&tcx.fn_sig(def_id)),
1229 EntryKind::Closure(self.lazy(&data))
1234 visibility: self.lazy(&ty::Visibility::Public),
1235 span: self.lazy(&tcx.def_span(def_id)),
1236 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1237 children: LazySeq::empty(),
1241 ty: Some(self.encode_item_type(def_id)),
1242 inherent_impls: LazySeq::empty(),
1243 variances: LazySeq::empty(),
1244 generics: Some(self.encode_generics(def_id)),
1248 mir: self.encode_optimized_mir(def_id),
1252 fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1253 debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
1255 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1256 let body = tcx.hir.body_owned_by(id);
1259 kind: EntryKind::Const(tcx.mir_const_qualif(def_id).0),
1260 visibility: self.lazy(&ty::Visibility::Public),
1261 span: self.lazy(&tcx.def_span(def_id)),
1262 attributes: LazySeq::empty(),
1263 children: LazySeq::empty(),
1267 ty: Some(self.encode_item_type(def_id)),
1268 inherent_impls: LazySeq::empty(),
1269 variances: LazySeq::empty(),
1270 generics: Some(self.encode_generics(def_id)),
1271 predicates: Some(self.encode_predicates(def_id)),
1273 ast: Some(self.encode_body(body)),
1274 mir: self.encode_optimized_mir(def_id),
1278 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1279 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1280 // we rely on the HashStable specialization for [Attribute]
1281 // to properly filter things out.
1282 self.lazy_seq_from_slice(attrs)
1285 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1286 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1287 self.lazy_seq(used_libraries.iter().cloned())
1290 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1291 let cstore = &*self.tcx.sess.cstore;
1292 let crates = cstore.crates();
1294 let mut deps = crates
1297 let dep = CrateDep {
1298 name: self.tcx.original_crate_name(cnum),
1299 hash: self.tcx.crate_hash(cnum),
1300 kind: cstore.dep_kind(cnum),
1304 .collect::<Vec<_>>();
1306 deps.sort_by_key(|&(cnum, _)| cnum);
1309 // Sanity-check the crate numbers
1310 let mut expected_cnum = 1;
1311 for &(n, _) in &deps {
1312 assert_eq!(n, CrateNum::new(expected_cnum));
1317 // We're just going to write a list of crate 'name-hash-version's, with
1318 // the assumption that they are numbered 1 to n.
1319 // FIXME (#2166): This is not nearly enough to support correct versioning
1320 // but is enough to get transitive crate dependencies working.
1321 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1324 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1326 let lang_items = tcx.lang_items.items().iter();
1327 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1328 if let Some(def_id) = opt_def_id {
1329 if def_id.is_local() {
1330 return Some((def_id.index, i));
1337 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1339 self.lazy_seq_ref(&tcx.lang_items.missing)
1342 /// Encodes an index, mapping each trait to its (local) implementations.
1343 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1344 debug!("IsolatedEncoder::encode_impls()");
1346 let mut visitor = ImplVisitor {
1350 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1352 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1354 // Bring everything into deterministic order for hashing
1355 all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1356 tcx.def_path_hash(trait_def_id)
1359 let all_impls: Vec<_> = all_impls
1361 .map(|(trait_def_id, mut impls)| {
1362 // Bring everything into deterministic order for hashing
1363 impls.sort_unstable_by_key(|&def_index| {
1364 tcx.hir.definitions().def_path_hash(def_index)
1368 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1369 impls: self.lazy_seq_from_slice(&impls[..]),
1374 self.lazy_seq_from_slice(&all_impls[..])
1377 // Encodes all symbols exported from this crate into the metadata.
1379 // This pass is seeded off the reachability list calculated in the
1380 // middle::reachable module but filters out items that either don't have a
1381 // symbol associated with them (they weren't translated) or if they're an FFI
1382 // definition (as that's not defined in this crate).
1383 fn encode_exported_symbols(&mut self, exported_symbols: &NodeSet) -> LazySeq<DefIndex> {
1385 self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
1388 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1389 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1391 self.lazy_seq(arr.iter().map(|slot| {
1393 Linkage::NotLinked |
1394 Linkage::IncludedFromDylib => None,
1396 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1397 Linkage::Static => Some(LinkagePreference::RequireStatic),
1401 None => LazySeq::empty(),
1405 fn encode_info_for_foreign_item(&mut self,
1406 (def_id, nitem): (DefId, &hir::ForeignItem))
1410 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1412 let kind = match nitem.node {
1413 hir::ForeignItemFn(_, ref names, _) => {
1415 constness: hir::Constness::NotConst,
1416 arg_names: self.encode_fn_arg_names(names),
1417 sig: self.lazy(&tcx.fn_sig(def_id)),
1419 EntryKind::ForeignFn(self.lazy(&data))
1421 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1422 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1427 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1428 span: self.lazy(&nitem.span),
1429 attributes: self.encode_attributes(&nitem.attrs),
1430 children: LazySeq::empty(),
1431 stability: self.encode_stability(def_id),
1432 deprecation: self.encode_deprecation(def_id),
1434 ty: Some(self.encode_item_type(def_id)),
1435 inherent_impls: LazySeq::empty(),
1436 variances: match nitem.node {
1437 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1438 _ => LazySeq::empty(),
1440 generics: Some(self.encode_generics(def_id)),
1441 predicates: Some(self.encode_predicates(def_id)),
1449 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1450 index: IndexBuilder<'a, 'b, 'tcx>,
1453 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1454 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1455 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1457 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1458 intravisit::walk_expr(self, ex);
1459 self.index.encode_info_for_expr(ex);
1461 fn visit_item(&mut self, item: &'tcx hir::Item) {
1462 intravisit::walk_item(self, item);
1463 let def_id = self.index.tcx.hir.local_def_id(item.id);
1465 hir::ItemExternCrate(_) |
1466 hir::ItemUse(..) => (), // ignore these
1467 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1469 self.index.encode_addl_info_for_item(item);
1471 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1472 intravisit::walk_foreign_item(self, ni);
1473 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1474 self.index.record(def_id,
1475 IsolatedEncoder::encode_info_for_foreign_item,
1478 fn visit_variant(&mut self,
1479 v: &'tcx hir::Variant,
1480 g: &'tcx hir::Generics,
1482 intravisit::walk_variant(self, v, g, id);
1484 if let Some(discr) = v.node.disr_expr {
1485 let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1486 self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1489 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1490 intravisit::walk_generics(self, generics);
1491 self.index.encode_info_for_generics(generics);
1493 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1494 intravisit::walk_ty(self, ty);
1495 self.index.encode_info_for_ty(ty);
1497 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1498 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1499 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1503 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1504 fn encode_fields(&mut self, adt_def_id: DefId) {
1505 let def = self.tcx.adt_def(adt_def_id);
1506 for (variant_index, variant) in def.variants.iter().enumerate() {
1507 for (field_index, field) in variant.fields.iter().enumerate() {
1508 self.record(field.did,
1509 IsolatedEncoder::encode_field,
1510 (adt_def_id, Untracked((variant_index, field_index))));
1515 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1516 for ty_param in &generics.ty_params {
1517 let def_id = self.tcx.hir.local_def_id(ty_param.id);
1518 let has_default = Untracked(ty_param.default.is_some());
1519 self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
1523 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1524 if let hir::TyImplTrait(_) = ty.node {
1525 let def_id = self.tcx.hir.local_def_id(ty.id);
1526 self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
1530 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1532 hir::ExprClosure(..) => {
1533 let def_id = self.tcx.hir.local_def_id(expr.id);
1534 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1540 /// In some cases, along with the item itself, we also
1541 /// encode some sub-items. Usually we want some info from the item
1542 /// so it's easier to do that here then to wait until we would encounter
1543 /// normally in the visitor walk.
1544 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1545 let def_id = self.tcx.hir.local_def_id(item.id);
1547 hir::ItemStatic(..) |
1548 hir::ItemConst(..) |
1551 hir::ItemForeignMod(..) |
1552 hir::ItemGlobalAsm(..) |
1553 hir::ItemExternCrate(..) |
1555 hir::ItemDefaultImpl(..) |
1556 hir::ItemTy(..) => {
1557 // no sub-item recording needed in these cases
1559 hir::ItemEnum(..) => {
1560 self.encode_fields(def_id);
1562 let def = self.tcx.adt_def(def_id);
1563 for (i, variant) in def.variants.iter().enumerate() {
1564 self.record(variant.did,
1565 IsolatedEncoder::encode_enum_variant_info,
1566 (def_id, Untracked(i)));
1569 hir::ItemStruct(ref struct_def, _) => {
1570 self.encode_fields(def_id);
1572 // If the struct has a constructor, encode it.
1573 if !struct_def.is_struct() {
1574 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1575 self.record(ctor_def_id,
1576 IsolatedEncoder::encode_struct_ctor,
1577 (def_id, ctor_def_id));
1580 hir::ItemUnion(..) => {
1581 self.encode_fields(def_id);
1583 hir::ItemImpl(..) => {
1584 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1585 self.record(trait_item_def_id,
1586 IsolatedEncoder::encode_info_for_impl_item,
1590 hir::ItemTrait(..) => {
1591 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1592 self.record(item_def_id,
1593 IsolatedEncoder::encode_info_for_trait_item,
1601 struct ImplVisitor<'a, 'tcx: 'a> {
1602 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1603 impls: FxHashMap<DefId, Vec<DefIndex>>,
1606 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1607 fn visit_item(&mut self, item: &hir::Item) {
1608 if let hir::ItemImpl(..) = item.node {
1609 let impl_id = self.tcx.hir.local_def_id(item.id);
1610 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1612 .entry(trait_ref.def_id)
1614 .push(impl_id.index);
1619 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1621 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1622 // handled in `visit_item` above
1626 // NOTE(eddyb) The following comment was preserved for posterity, even
1627 // though it's no longer relevant as EBML (which uses nested & tagged
1628 // "documents") was replaced with a scheme that can't go out of bounds.
1630 // And here we run into yet another obscure archive bug: in which metadata
1631 // loaded from archives may have trailing garbage bytes. Awhile back one of
1632 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1633 // and opt) by having ebml generate an out-of-bounds panic when looking at
1636 // Upon investigation it turned out that the metadata file inside of an rlib
1637 // (and ar archive) was being corrupted. Some compilations would generate a
1638 // metadata file which would end in a few extra bytes, while other
1639 // compilations would not have these extra bytes appended to the end. These
1640 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1641 // being interpreted causing the out-of-bounds.
1643 // The root cause of why these extra bytes were appearing was never
1644 // discovered, and in the meantime the solution we're employing is to insert
1645 // the length of the metadata to the start of the metadata. Later on this
1646 // will allow us to slice the metadata to the precise length that we just
1647 // generated regardless of trailing bytes that end up in it.
1649 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1650 link_meta: &LinkMeta,
1651 exported_symbols: &NodeSet)
1652 -> (EncodedMetadata, EncodedMetadataHashes)
1654 let mut cursor = Cursor::new(vec![]);
1655 cursor.write_all(METADATA_HEADER).unwrap();
1657 // Will be filled with the root position after encoding everything.
1658 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1660 let compute_ich = (tcx.sess.opts.debugging_opts.query_dep_graph ||
1661 tcx.sess.opts.debugging_opts.incremental_cc) &&
1662 tcx.sess.opts.build_dep_graph();
1664 let (root, metadata_hashes) = {
1665 let mut ecx = EncodeContext {
1666 opaque: opaque::Encoder::new(&mut cursor),
1670 lazy_state: LazyState::NoNode,
1671 type_shorthands: Default::default(),
1672 predicate_shorthands: Default::default(),
1673 metadata_hashes: EncodedMetadataHashes::new(),
1677 // Encode the rustc version string in a predictable location.
1678 rustc_version().encode(&mut ecx).unwrap();
1680 // Encode all the entries and extra information in the crate,
1681 // culminating in the `CrateRoot` which points to all of it.
1682 let root = ecx.encode_crate_root();
1683 (root, ecx.metadata_hashes)
1685 let mut result = cursor.into_inner();
1687 // Encode the root position.
1688 let header = METADATA_HEADER.len();
1689 let pos = root.position;
1690 result[header + 0] = (pos >> 24) as u8;
1691 result[header + 1] = (pos >> 16) as u8;
1692 result[header + 2] = (pos >> 8) as u8;
1693 result[header + 3] = (pos >> 0) as u8;
1695 (EncodedMetadata { raw_data: result }, metadata_hashes)
1698 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1699 let ty = tcx.type_of(did);
1701 ty::TyAdt(ref def, _) => return def.repr,
1702 _ => bug!("{} is not an ADT", ty),