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,
18 use rustc::hir::def::CtorKind;
19 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LOCAL_CRATE};
20 use rustc::hir::map::definitions::DefPathTable;
21 use rustc::middle::dependency_format::Linkage;
22 use rustc::middle::lang_items;
24 use rustc::traits::specialization_graph;
25 use rustc::ty::{self, Ty, TyCtxt, ReprOptions};
26 use rustc::ty::codec::{self as ty_codec, TyEncoder};
28 use rustc::session::config::{self, CrateTypeProcMacro};
29 use rustc::util::nodemap::{FxHashMap, NodeSet};
31 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
33 use std::io::prelude::*;
38 use syntax::ast::{self, CRATE_NODE_ID};
39 use syntax::codemap::Spanned;
41 use syntax::symbol::Symbol;
44 use rustc::hir::{self, PatKind};
45 use rustc::hir::itemlikevisit::ItemLikeVisitor;
46 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
47 use rustc::hir::intravisit;
49 pub struct EncodeContext<'a, 'tcx: 'a> {
50 opaque: opaque::Encoder<'a>,
51 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
52 link_meta: &'a LinkMeta,
53 exported_symbols: &'a NodeSet,
55 lazy_state: LazyState,
56 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
57 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
60 macro_rules! encoder_methods {
61 ($($name:ident($ty:ty);)*) => {
62 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
63 self.opaque.$name(value)
68 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
69 type Error = <opaque::Encoder<'a> as Encoder>::Error;
71 fn emit_nil(&mut self) -> Result<(), Self::Error> {
98 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
99 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
100 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
104 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
105 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
106 self.emit_usize(seq.len)?;
110 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
114 impl<'a, 'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'a, 'tcx> {
116 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
117 self.emit_u32(cnum.as_u32())
121 impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
123 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
134 impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
136 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
137 self.emit_u32(def_index.as_u32())
141 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
142 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
143 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
147 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
148 fn specialized_encode(&mut self,
149 predicates: &ty::GenericPredicates<'tcx>)
150 -> Result<(), Self::Error> {
151 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
155 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
156 for EncodeContext<'a, 'tcx> {
157 fn specialized_encode(&mut self,
158 _: &mir::ClearCrossCrate<T>)
159 -> Result<(), Self::Error> {
164 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
165 fn position(&self) -> usize {
166 self.opaque.position()
170 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
172 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
173 assert_eq!(self.lazy_state, LazyState::NoNode);
174 let pos = self.position();
175 self.lazy_state = LazyState::NodeStart(pos);
176 let r = f(self, pos);
177 self.lazy_state = LazyState::NoNode;
181 fn emit_lazy_distance(&mut self,
184 -> Result<(), <Self as Encoder>::Error> {
185 let min_end = position + min_size;
186 let distance = match self.lazy_state {
187 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
188 LazyState::NodeStart(start) => {
189 assert!(min_end <= start);
192 LazyState::Previous(last_min_end) => {
193 assert!(last_min_end <= position);
194 position - last_min_end
197 self.lazy_state = LazyState::Previous(min_end);
198 self.emit_usize(distance)
201 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
202 self.emit_node(|ecx, pos| {
203 value.encode(ecx).unwrap();
205 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
206 Lazy::with_position(pos)
210 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
211 where I: IntoIterator<Item = T>,
214 self.emit_node(|ecx, pos| {
215 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
217 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
218 LazySeq::with_position_and_length(pos, len)
222 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
223 where I: IntoIterator<Item = &'b T>,
226 self.emit_node(|ecx, pos| {
227 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
229 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
230 LazySeq::with_position_and_length(pos, len)
234 // Encodes something that corresponds to a single DepNode::GlobalMetaData
235 // and registers the Fingerprint in the `metadata_hashes` map.
236 pub fn tracked<'x, DATA, R>(&'x mut self,
237 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
240 op(&mut IsolatedEncoder::new(self), data)
243 fn encode_info_for_items(&mut self) -> Index {
244 let krate = self.tcx.hir.krate();
245 let mut index = IndexBuilder::new(self);
246 index.record(DefId::local(CRATE_DEF_INDEX),
247 IsolatedEncoder::encode_info_for_mod,
248 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
249 let mut visitor = EncodeVisitor { index: index };
250 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
251 for macro_def in &krate.exported_macros {
252 visitor.visit_macro_def(macro_def);
254 visitor.index.into_items()
257 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
258 let definitions = self.tcx.hir.definitions();
259 self.lazy(definitions.def_path_table())
262 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
263 let codemap = self.tcx.sess.codemap();
264 let all_filemaps = codemap.files();
266 let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
268 let adapted = all_filemaps.iter()
270 // No need to re-export imported filemaps, as any downstream
271 // crate will import them from their original source.
272 !filemap.is_imported()
275 // When exporting FileMaps, we expand all paths to absolute
276 // paths because any relative paths are potentially relative to
277 // a wrong directory.
278 // However, if a path has been modified via
279 // `-Zremap-path-prefix` we assume the user has already set
280 // things up the way they want and don't touch the path values
282 let name = Path::new(&filemap.name);
283 if filemap.name_was_remapped ||
284 (name.is_relative() && working_dir_was_remapped) {
285 // This path of this FileMap has been modified by
286 // path-remapping, so we use it verbatim (and avoid cloning
287 // the whole map in the process).
290 let mut adapted = (**filemap).clone();
291 let abs_path = Path::new(&working_dir).join(name)
294 adapted.name = abs_path;
298 .collect::<Vec<_>>();
300 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
303 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
304 let mut i = self.position();
306 let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
307 let dylib_dependency_formats = self.tracked(
308 IsolatedEncoder::encode_dylib_dependency_formats,
310 let dep_bytes = self.position() - i;
312 // Encode the language items.
314 let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
315 let lang_items_missing = self.tracked(
316 IsolatedEncoder::encode_lang_items_missing,
318 let lang_item_bytes = self.position() - i;
320 // Encode the native libraries used
322 let native_libraries = self.tracked(
323 IsolatedEncoder::encode_native_libraries,
325 let native_lib_bytes = self.position() - i;
329 let codemap = self.encode_codemap();
330 let codemap_bytes = self.position() - i;
332 // Encode DefPathTable
334 let def_path_table = self.encode_def_path_table();
335 let def_path_table_bytes = self.position() - i;
337 // Encode the def IDs of impls, for coherence checking.
339 let impls = self.tracked(IsolatedEncoder::encode_impls, ());
340 let impl_bytes = self.position() - i;
342 // Encode exported symbols info.
344 let exported_symbols = self.tracked(
345 IsolatedEncoder::encode_exported_symbols,
346 self.exported_symbols);
347 let exported_symbols_bytes = self.position() - i;
349 // Encode and index the items.
351 let items = self.encode_info_for_items();
352 let item_bytes = self.position() - i;
355 let index = items.write_index(&mut self.opaque.cursor);
356 let index_bytes = self.position() - i;
359 let link_meta = self.link_meta;
360 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
361 let has_default_lib_allocator =
362 attr::contains_name(tcx.hir.krate_attrs(), "default_lib_allocator");
363 let has_global_allocator = tcx.sess.has_global_allocator.get();
364 let root = self.lazy(&CrateRoot {
365 name: tcx.crate_name(LOCAL_CRATE),
366 triple: tcx.sess.opts.target_triple.clone(),
367 hash: link_meta.crate_hash,
368 disambiguator: tcx.sess.local_crate_disambiguator(),
369 panic_strategy: tcx.sess.panic_strategy(),
370 has_global_allocator: has_global_allocator,
371 has_default_lib_allocator: has_default_lib_allocator,
372 plugin_registrar_fn: tcx.sess
375 .map(|id| tcx.hir.local_def_id(id).index),
376 macro_derive_registrar: if is_proc_macro {
377 let id = tcx.sess.derive_registrar_fn.get().unwrap();
378 Some(tcx.hir.local_def_id(id).index)
384 dylib_dependency_formats,
395 let total_bytes = self.position();
397 if self.tcx.sess.meta_stats() {
398 let mut zero_bytes = 0;
399 for e in self.opaque.cursor.get_ref() {
405 println!("metadata stats:");
406 println!(" dep bytes: {}", dep_bytes);
407 println!(" lang item bytes: {}", lang_item_bytes);
408 println!(" native bytes: {}", native_lib_bytes);
409 println!(" codemap bytes: {}", codemap_bytes);
410 println!(" impl bytes: {}", impl_bytes);
411 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
412 println!(" def-path table bytes: {}", def_path_table_bytes);
413 println!(" item bytes: {}", item_bytes);
414 println!(" index bytes: {}", index_bytes);
415 println!(" zero bytes: {}", zero_bytes);
416 println!(" total bytes: {}", total_bytes);
423 // These are methods for encoding various things. They are meant to be used with
424 // IndexBuilder::record() and EncodeContext::tracked(). They actually
425 // would not have to be methods of IsolatedEncoder (free standing functions
426 // taking IsolatedEncoder as first argument would be just fine) but by making
427 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
428 // clause again and again.
429 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
430 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
431 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
433 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
436 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
438 let ty = tcx.type_of(def_id);
439 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
443 /// Encode data for the given variant of the given ADT. The
444 /// index of the variant is untracked: this is ok because we
445 /// will have to lookup the adt-def by its id, and that gives us
446 /// the right to access any information in the adt-def (including,
447 /// e.g., the length of the various vectors).
448 fn encode_enum_variant_info(&mut self,
449 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
452 let def = tcx.adt_def(enum_did);
453 let variant = &def.variants[index];
454 let def_id = variant.did;
455 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
457 let data = VariantData {
458 ctor_kind: variant.ctor_kind,
459 discr: variant.discr,
461 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
462 Some(self.lazy(&tcx.fn_sig(def_id)))
468 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
469 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
472 kind: EntryKind::Variant(self.lazy(&data)),
473 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
474 span: self.lazy(&tcx.def_span(def_id)),
475 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
476 children: self.lazy_seq(variant.fields.iter().map(|f| {
477 assert!(f.did.is_local());
480 stability: self.encode_stability(def_id),
481 deprecation: self.encode_deprecation(def_id),
483 ty: Some(self.encode_item_type(def_id)),
484 inherent_impls: LazySeq::empty(),
485 variances: if variant.ctor_kind == CtorKind::Fn {
486 self.encode_variances_of(def_id)
490 generics: Some(self.encode_generics(def_id)),
491 predicates: Some(self.encode_predicates(def_id)),
494 mir: self.encode_optimized_mir(def_id),
498 fn encode_info_for_mod(&mut self,
499 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
504 let def_id = tcx.hir.local_def_id(id);
505 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
508 reexports: match tcx.module_exports(def_id) {
509 Some(ref exports) if *vis == hir::Public => {
510 self.lazy_seq_from_slice(exports.as_slice())
512 _ => LazySeq::empty(),
517 kind: EntryKind::Mod(self.lazy(&data)),
518 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
519 span: self.lazy(&tcx.def_span(def_id)),
520 attributes: self.encode_attributes(attrs),
521 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
522 tcx.hir.local_def_id(item_id.id).index
524 stability: self.encode_stability(def_id),
525 deprecation: self.encode_deprecation(def_id),
528 inherent_impls: LazySeq::empty(),
529 variances: LazySeq::empty(),
538 /// Encode data for the given field of the given variant of the
539 /// given ADT. The indices of the variant/field are untracked:
540 /// this is ok because we will have to lookup the adt-def by its
541 /// id, and that gives us the right to access any information in
542 /// the adt-def (including, e.g., the length of the various
544 fn encode_field(&mut self,
545 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
550 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
551 let field = &variant.fields[field_index];
553 let def_id = field.did;
554 debug!("IsolatedEncoder::encode_field({:?})", def_id);
556 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
557 let variant_data = tcx.hir.expect_variant_data(variant_id);
560 kind: EntryKind::Field,
561 visibility: self.lazy(&field.vis),
562 span: self.lazy(&tcx.def_span(def_id)),
563 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
564 children: LazySeq::empty(),
565 stability: self.encode_stability(def_id),
566 deprecation: self.encode_deprecation(def_id),
568 ty: Some(self.encode_item_type(def_id)),
569 inherent_impls: LazySeq::empty(),
570 variances: LazySeq::empty(),
571 generics: Some(self.encode_generics(def_id)),
572 predicates: Some(self.encode_predicates(def_id)),
579 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
580 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
582 let adt_def = tcx.adt_def(adt_def_id);
583 let variant = adt_def.struct_variant();
585 let data = VariantData {
586 ctor_kind: variant.ctor_kind,
587 discr: variant.discr,
588 struct_ctor: Some(def_id.index),
589 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
590 Some(self.lazy(&tcx.fn_sig(def_id)))
596 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
597 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
598 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
599 for field in &variant.fields {
600 if ctor_vis.is_at_least(field.vis, tcx) {
601 ctor_vis = field.vis;
605 // If the structure is marked as non_exhaustive then lower the visibility
606 // to within the crate.
607 if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
608 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
611 let repr_options = get_repr_options(&tcx, adt_def_id);
614 kind: EntryKind::Struct(self.lazy(&data), repr_options),
615 visibility: self.lazy(&ctor_vis),
616 span: self.lazy(&tcx.def_span(def_id)),
617 attributes: LazySeq::empty(),
618 children: LazySeq::empty(),
619 stability: self.encode_stability(def_id),
620 deprecation: self.encode_deprecation(def_id),
622 ty: Some(self.encode_item_type(def_id)),
623 inherent_impls: LazySeq::empty(),
624 variances: if variant.ctor_kind == CtorKind::Fn {
625 self.encode_variances_of(def_id)
629 generics: Some(self.encode_generics(def_id)),
630 predicates: Some(self.encode_predicates(def_id)),
633 mir: self.encode_optimized_mir(def_id),
637 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
638 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
640 self.lazy(tcx.generics_of(def_id))
643 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
644 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
646 self.lazy(&tcx.predicates_of(def_id))
649 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
650 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
653 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
654 let ast_item = tcx.hir.expect_trait_item(node_id);
655 let trait_item = tcx.associated_item(def_id);
657 let container = match trait_item.defaultness {
658 hir::Defaultness::Default { has_value: true } =>
659 AssociatedContainer::TraitWithDefault,
660 hir::Defaultness::Default { has_value: false } =>
661 AssociatedContainer::TraitRequired,
662 hir::Defaultness::Final =>
663 span_bug!(ast_item.span, "traits cannot have final items"),
666 let kind = match trait_item.kind {
667 ty::AssociatedKind::Const => {
668 EntryKind::AssociatedConst(container, 0)
670 ty::AssociatedKind::Method => {
671 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
672 let arg_names = match *m {
673 hir::TraitMethod::Required(ref names) => {
674 self.encode_fn_arg_names(names)
676 hir::TraitMethod::Provided(body) => {
677 self.encode_fn_arg_names_for_body(body)
681 constness: hir::Constness::NotConst,
683 sig: self.lazy(&tcx.fn_sig(def_id)),
688 EntryKind::Method(self.lazy(&MethodData {
691 has_self: trait_item.method_has_self_argument,
694 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
699 visibility: self.lazy(&trait_item.vis),
700 span: self.lazy(&ast_item.span),
701 attributes: self.encode_attributes(&ast_item.attrs),
702 children: LazySeq::empty(),
703 stability: self.encode_stability(def_id),
704 deprecation: self.encode_deprecation(def_id),
706 ty: match trait_item.kind {
707 ty::AssociatedKind::Const |
708 ty::AssociatedKind::Method => {
709 Some(self.encode_item_type(def_id))
711 ty::AssociatedKind::Type => {
712 if trait_item.defaultness.has_value() {
713 Some(self.encode_item_type(def_id))
719 inherent_impls: LazySeq::empty(),
720 variances: if trait_item.kind == ty::AssociatedKind::Method {
721 self.encode_variances_of(def_id)
725 generics: Some(self.encode_generics(def_id)),
726 predicates: Some(self.encode_predicates(def_id)),
728 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
729 Some(self.encode_body(body))
733 mir: self.encode_optimized_mir(def_id),
737 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
738 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
741 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
742 let ast_item = self.tcx.hir.expect_impl_item(node_id);
743 let impl_item = self.tcx.associated_item(def_id);
745 let container = match impl_item.defaultness {
746 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
747 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
748 hir::Defaultness::Default { has_value: false } =>
749 span_bug!(ast_item.span, "impl items always have values (currently)"),
752 let kind = match impl_item.kind {
753 ty::AssociatedKind::Const => {
754 EntryKind::AssociatedConst(container,
755 self.tcx.at(ast_item.span).mir_const_qualif(def_id).0)
757 ty::AssociatedKind::Method => {
758 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
760 constness: sig.constness,
761 arg_names: self.encode_fn_arg_names_for_body(body),
762 sig: self.lazy(&tcx.fn_sig(def_id)),
767 EntryKind::Method(self.lazy(&MethodData {
770 has_self: impl_item.method_has_self_argument,
773 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
776 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
778 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
779 let generics = self.tcx.generics_of(def_id);
780 let types = generics.parent_types as usize + generics.types.len();
781 let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
782 let is_const_fn = sig.constness == hir::Constness::Const;
783 let ast = if is_const_fn { Some(body) } else { None };
784 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
785 (ast, needs_inline || is_const_fn || always_encode_mir)
792 visibility: self.lazy(&impl_item.vis),
793 span: self.lazy(&ast_item.span),
794 attributes: self.encode_attributes(&ast_item.attrs),
795 children: LazySeq::empty(),
796 stability: self.encode_stability(def_id),
797 deprecation: self.encode_deprecation(def_id),
799 ty: Some(self.encode_item_type(def_id)),
800 inherent_impls: LazySeq::empty(),
801 variances: if impl_item.kind == ty::AssociatedKind::Method {
802 self.encode_variances_of(def_id)
806 generics: Some(self.encode_generics(def_id)),
807 predicates: Some(self.encode_predicates(def_id)),
809 ast: ast.map(|body| self.encode_body(body)),
810 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
814 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
815 -> LazySeq<ast::Name> {
816 let _ignore = self.tcx.dep_graph.in_ignore();
817 let body = self.tcx.hir.body(body_id);
818 self.lazy_seq(body.arguments.iter().map(|arg| {
820 PatKind::Binding(_, _, name, _) => name.node,
821 _ => Symbol::intern("")
826 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
827 -> LazySeq<ast::Name> {
828 self.lazy_seq(names.iter().map(|name| name.node))
831 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
832 debug!("EntryBuilder::encode_mir({:?})", def_id);
833 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
834 let mir = self.tcx.optimized_mir(def_id);
835 Some(self.lazy(&mir))
841 // Encodes the inherent implementations of a structure, enumeration, or trait.
842 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
843 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
844 let implementations = self.tcx.inherent_impls(def_id);
845 if implementations.is_empty() {
848 self.lazy_seq(implementations.iter().map(|&def_id| {
849 assert!(def_id.is_local());
855 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
856 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
857 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
860 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
861 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
862 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
865 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
868 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
870 let kind = match item.node {
871 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
872 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
873 hir::ItemConst(..) => {
874 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id).0)
876 hir::ItemFn(_, _, constness, .., body) => {
879 arg_names: self.encode_fn_arg_names_for_body(body),
880 sig: self.lazy(&tcx.fn_sig(def_id)),
883 EntryKind::Fn(self.lazy(&data))
885 hir::ItemMod(ref m) => {
886 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
888 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
889 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
890 hir::ItemTy(..) => EntryKind::Type,
891 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
892 hir::ItemStruct(ref struct_def, _) => {
893 let variant = tcx.adt_def(def_id).struct_variant();
895 // Encode def_ids for each field and method
896 // for methods, write all the stuff get_trait_method
898 let struct_ctor = if !struct_def.is_struct() {
899 Some(tcx.hir.local_def_id(struct_def.id()).index)
904 let repr_options = get_repr_options(&tcx, def_id);
906 EntryKind::Struct(self.lazy(&VariantData {
907 ctor_kind: variant.ctor_kind,
908 discr: variant.discr,
913 hir::ItemUnion(..) => {
914 let variant = tcx.adt_def(def_id).struct_variant();
915 let repr_options = get_repr_options(&tcx, def_id);
917 EntryKind::Union(self.lazy(&VariantData {
918 ctor_kind: variant.ctor_kind,
919 discr: variant.discr,
924 hir::ItemAutoImpl(..) => {
925 let data = ImplData {
926 polarity: hir::ImplPolarity::Positive,
927 defaultness: hir::Defaultness::Final,
929 coerce_unsized_info: None,
930 trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref)),
933 EntryKind::AutoImpl(self.lazy(&data))
935 hir::ItemImpl(_, polarity, defaultness, ..) => {
936 let trait_ref = tcx.impl_trait_ref(def_id);
937 let parent = if let Some(trait_ref) = trait_ref {
938 let trait_def = tcx.trait_def(trait_ref.def_id);
939 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
941 specialization_graph::Node::Impl(parent) => Some(parent),
949 // if this is an impl of `CoerceUnsized`, create its
950 // "unsized info", else just store None
951 let coerce_unsized_info =
952 trait_ref.and_then(|t| {
953 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
954 Some(tcx.at(item.span).coerce_unsized_info(def_id))
960 let data = ImplData {
965 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
968 EntryKind::Impl(self.lazy(&data))
970 hir::ItemTrait(..) => {
971 let trait_def = tcx.trait_def(def_id);
972 let data = TraitData {
973 unsafety: trait_def.unsafety,
974 paren_sugar: trait_def.paren_sugar,
975 has_auto_impl: tcx.trait_is_auto(def_id),
976 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
979 EntryKind::Trait(self.lazy(&data))
981 hir::ItemExternCrate(_) |
982 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
987 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
988 span: self.lazy(&item.span),
989 attributes: self.encode_attributes(&item.attrs),
990 children: match item.node {
991 hir::ItemForeignMod(ref fm) => {
992 self.lazy_seq(fm.items
994 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
996 hir::ItemEnum(..) => {
997 let def = self.tcx.adt_def(def_id);
998 self.lazy_seq(def.variants.iter().map(|v| {
999 assert!(v.did.is_local());
1003 hir::ItemStruct(..) |
1004 hir::ItemUnion(..) => {
1005 let def = self.tcx.adt_def(def_id);
1006 self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
1007 assert!(f.did.is_local());
1012 hir::ItemTrait(..) => {
1013 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1014 assert!(def_id.is_local());
1018 _ => LazySeq::empty(),
1020 stability: self.encode_stability(def_id),
1021 deprecation: self.encode_deprecation(def_id),
1023 ty: match item.node {
1024 hir::ItemStatic(..) |
1025 hir::ItemConst(..) |
1029 hir::ItemStruct(..) |
1030 hir::ItemUnion(..) |
1031 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1034 inherent_impls: self.encode_inherent_implementations(def_id),
1035 variances: match item.node {
1037 hir::ItemStruct(..) |
1038 hir::ItemUnion(..) |
1039 hir::ItemFn(..) => self.encode_variances_of(def_id),
1040 _ => LazySeq::empty(),
1042 generics: match item.node {
1043 hir::ItemStatic(..) |
1044 hir::ItemConst(..) |
1048 hir::ItemStruct(..) |
1049 hir::ItemUnion(..) |
1051 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1054 predicates: match item.node {
1055 hir::ItemStatic(..) |
1056 hir::ItemConst(..) |
1060 hir::ItemStruct(..) |
1061 hir::ItemUnion(..) |
1063 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1067 ast: match item.node {
1068 hir::ItemConst(_, body) |
1069 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
1070 Some(self.encode_body(body))
1074 mir: match item.node {
1075 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
1076 self.encode_optimized_mir(def_id)
1078 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1079 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1080 let tps_len = generics.ty_params.len();
1081 let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
1082 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1083 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
1084 self.encode_optimized_mir(def_id)
1094 /// Serialize the text of exported macros
1095 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1096 use syntax::print::pprust;
1097 let def_id = self.tcx.hir.local_def_id(macro_def.id);
1099 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1100 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1101 legacy: macro_def.legacy,
1103 visibility: self.lazy(&ty::Visibility::Public),
1104 span: self.lazy(¯o_def.span),
1105 attributes: self.encode_attributes(¯o_def.attrs),
1106 stability: self.encode_stability(def_id),
1107 deprecation: self.encode_deprecation(def_id),
1109 children: LazySeq::empty(),
1111 inherent_impls: LazySeq::empty(),
1112 variances: LazySeq::empty(),
1120 fn encode_info_for_ty_param(&mut self,
1121 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1123 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1126 kind: EntryKind::Type,
1127 visibility: self.lazy(&ty::Visibility::Public),
1128 span: self.lazy(&tcx.def_span(def_id)),
1129 attributes: LazySeq::empty(),
1130 children: LazySeq::empty(),
1134 ty: if has_default {
1135 Some(self.encode_item_type(def_id))
1139 inherent_impls: LazySeq::empty(),
1140 variances: LazySeq::empty(),
1149 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1150 debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
1153 kind: EntryKind::Type,
1154 visibility: self.lazy(&ty::Visibility::Public),
1155 span: self.lazy(&tcx.def_span(def_id)),
1156 attributes: LazySeq::empty(),
1157 children: LazySeq::empty(),
1161 ty: Some(self.encode_item_type(def_id)),
1162 inherent_impls: LazySeq::empty(),
1163 variances: LazySeq::empty(),
1164 generics: Some(self.encode_generics(def_id)),
1165 predicates: Some(self.encode_predicates(def_id)),
1172 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1173 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1176 let tables = self.tcx.typeck_tables_of(def_id);
1177 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1178 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1179 let kind = match tables.node_id_to_type(hir_id).sty {
1180 ty::TyGenerator(def_id, ..) => {
1181 let layout = self.tcx.generator_layout(def_id);
1182 let data = GeneratorData {
1183 layout: layout.clone(),
1185 EntryKind::Generator(self.lazy(&data))
1188 ty::TyClosure(def_id, substs) => {
1189 let sig = substs.closure_sig(def_id, self.tcx);
1190 let data = ClosureData { sig: self.lazy(&sig) };
1191 EntryKind::Closure(self.lazy(&data))
1194 _ => bug!("closure that is neither generator nor closure")
1199 visibility: self.lazy(&ty::Visibility::Public),
1200 span: self.lazy(&tcx.def_span(def_id)),
1201 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1202 children: LazySeq::empty(),
1206 ty: Some(self.encode_item_type(def_id)),
1207 inherent_impls: LazySeq::empty(),
1208 variances: LazySeq::empty(),
1209 generics: Some(self.encode_generics(def_id)),
1213 mir: self.encode_optimized_mir(def_id),
1217 fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1218 debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
1220 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1221 let body = tcx.hir.body_owned_by(id);
1224 kind: EntryKind::Const(tcx.mir_const_qualif(def_id).0),
1225 visibility: self.lazy(&ty::Visibility::Public),
1226 span: self.lazy(&tcx.def_span(def_id)),
1227 attributes: LazySeq::empty(),
1228 children: LazySeq::empty(),
1232 ty: Some(self.encode_item_type(def_id)),
1233 inherent_impls: LazySeq::empty(),
1234 variances: LazySeq::empty(),
1235 generics: Some(self.encode_generics(def_id)),
1236 predicates: Some(self.encode_predicates(def_id)),
1238 ast: Some(self.encode_body(body)),
1239 mir: self.encode_optimized_mir(def_id),
1243 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1244 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1245 // we rely on the HashStable specialization for [Attribute]
1246 // to properly filter things out.
1247 self.lazy_seq_from_slice(attrs)
1250 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1251 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1252 self.lazy_seq(used_libraries.iter().cloned())
1255 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1256 let crates = self.tcx.crates();
1258 let mut deps = crates
1261 let dep = CrateDep {
1262 name: self.tcx.original_crate_name(cnum),
1263 hash: self.tcx.crate_hash(cnum),
1264 kind: self.tcx.dep_kind(cnum),
1268 .collect::<Vec<_>>();
1270 deps.sort_by_key(|&(cnum, _)| cnum);
1273 // Sanity-check the crate numbers
1274 let mut expected_cnum = 1;
1275 for &(n, _) in &deps {
1276 assert_eq!(n, CrateNum::new(expected_cnum));
1281 // We're just going to write a list of crate 'name-hash-version's, with
1282 // the assumption that they are numbered 1 to n.
1283 // FIXME (#2166): This is not nearly enough to support correct versioning
1284 // but is enough to get transitive crate dependencies working.
1285 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1288 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1290 let lang_items = tcx.lang_items();
1291 let lang_items = lang_items.items().iter();
1292 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1293 if let Some(def_id) = opt_def_id {
1294 if def_id.is_local() {
1295 return Some((def_id.index, i));
1302 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1304 self.lazy_seq_ref(&tcx.lang_items().missing)
1307 /// Encodes an index, mapping each trait to its (local) implementations.
1308 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1309 debug!("IsolatedEncoder::encode_impls()");
1311 let mut visitor = ImplVisitor {
1315 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1317 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1319 // Bring everything into deterministic order for hashing
1320 all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1321 tcx.def_path_hash(trait_def_id)
1324 let all_impls: Vec<_> = all_impls
1326 .map(|(trait_def_id, mut impls)| {
1327 // Bring everything into deterministic order for hashing
1328 impls.sort_unstable_by_key(|&def_index| {
1329 tcx.hir.definitions().def_path_hash(def_index)
1333 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1334 impls: self.lazy_seq_from_slice(&impls[..]),
1339 self.lazy_seq_from_slice(&all_impls[..])
1342 // Encodes all symbols exported from this crate into the metadata.
1344 // This pass is seeded off the reachability list calculated in the
1345 // middle::reachable module but filters out items that either don't have a
1346 // symbol associated with them (they weren't translated) or if they're an FFI
1347 // definition (as that's not defined in this crate).
1348 fn encode_exported_symbols(&mut self, exported_symbols: &NodeSet) -> LazySeq<DefIndex> {
1350 self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
1353 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1354 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1356 self.lazy_seq(arr.iter().map(|slot| {
1358 Linkage::NotLinked |
1359 Linkage::IncludedFromDylib => None,
1361 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1362 Linkage::Static => Some(LinkagePreference::RequireStatic),
1366 None => LazySeq::empty(),
1370 fn encode_info_for_foreign_item(&mut self,
1371 (def_id, nitem): (DefId, &hir::ForeignItem))
1375 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1377 let kind = match nitem.node {
1378 hir::ForeignItemFn(_, ref names, _) => {
1380 constness: hir::Constness::NotConst,
1381 arg_names: self.encode_fn_arg_names(names),
1382 sig: self.lazy(&tcx.fn_sig(def_id)),
1384 EntryKind::ForeignFn(self.lazy(&data))
1386 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1387 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1388 hir::ForeignItemType => EntryKind::ForeignType,
1393 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1394 span: self.lazy(&nitem.span),
1395 attributes: self.encode_attributes(&nitem.attrs),
1396 children: LazySeq::empty(),
1397 stability: self.encode_stability(def_id),
1398 deprecation: self.encode_deprecation(def_id),
1400 ty: Some(self.encode_item_type(def_id)),
1401 inherent_impls: LazySeq::empty(),
1402 variances: match nitem.node {
1403 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1404 _ => LazySeq::empty(),
1406 generics: Some(self.encode_generics(def_id)),
1407 predicates: Some(self.encode_predicates(def_id)),
1415 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1416 index: IndexBuilder<'a, 'b, 'tcx>,
1419 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1420 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1421 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1423 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1424 intravisit::walk_expr(self, ex);
1425 self.index.encode_info_for_expr(ex);
1427 fn visit_item(&mut self, item: &'tcx hir::Item) {
1428 intravisit::walk_item(self, item);
1429 let def_id = self.index.tcx.hir.local_def_id(item.id);
1431 hir::ItemExternCrate(_) |
1432 hir::ItemUse(..) => (), // ignore these
1433 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1435 self.index.encode_addl_info_for_item(item);
1437 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1438 intravisit::walk_foreign_item(self, ni);
1439 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1440 self.index.record(def_id,
1441 IsolatedEncoder::encode_info_for_foreign_item,
1444 fn visit_variant(&mut self,
1445 v: &'tcx hir::Variant,
1446 g: &'tcx hir::Generics,
1448 intravisit::walk_variant(self, v, g, id);
1450 if let Some(discr) = v.node.disr_expr {
1451 let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1452 self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1455 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1456 intravisit::walk_generics(self, generics);
1457 self.index.encode_info_for_generics(generics);
1459 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1460 intravisit::walk_ty(self, ty);
1461 self.index.encode_info_for_ty(ty);
1463 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1464 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1465 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1469 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1470 fn encode_fields(&mut self, adt_def_id: DefId) {
1471 let def = self.tcx.adt_def(adt_def_id);
1472 for (variant_index, variant) in def.variants.iter().enumerate() {
1473 for (field_index, field) in variant.fields.iter().enumerate() {
1474 self.record(field.did,
1475 IsolatedEncoder::encode_field,
1476 (adt_def_id, Untracked((variant_index, field_index))));
1481 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1482 for ty_param in &generics.ty_params {
1483 let def_id = self.tcx.hir.local_def_id(ty_param.id);
1484 let has_default = Untracked(ty_param.default.is_some());
1485 self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
1489 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1491 hir::TyImplTraitExistential(..) => {
1492 let def_id = self.tcx.hir.local_def_id(ty.id);
1493 self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
1495 hir::TyArray(_, len) => {
1496 let def_id = self.tcx.hir.body_owner_def_id(len);
1497 self.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1503 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1505 hir::ExprClosure(..) => {
1506 let def_id = self.tcx.hir.local_def_id(expr.id);
1507 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1513 /// In some cases, along with the item itself, we also
1514 /// encode some sub-items. Usually we want some info from the item
1515 /// so it's easier to do that here then to wait until we would encounter
1516 /// normally in the visitor walk.
1517 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1518 let def_id = self.tcx.hir.local_def_id(item.id);
1520 hir::ItemStatic(..) |
1521 hir::ItemConst(..) |
1524 hir::ItemForeignMod(..) |
1525 hir::ItemGlobalAsm(..) |
1526 hir::ItemExternCrate(..) |
1528 hir::ItemAutoImpl(..) |
1529 hir::ItemTy(..) => {
1530 // no sub-item recording needed in these cases
1532 hir::ItemEnum(..) => {
1533 self.encode_fields(def_id);
1535 let def = self.tcx.adt_def(def_id);
1536 for (i, variant) in def.variants.iter().enumerate() {
1537 self.record(variant.did,
1538 IsolatedEncoder::encode_enum_variant_info,
1539 (def_id, Untracked(i)));
1542 hir::ItemStruct(ref struct_def, _) => {
1543 self.encode_fields(def_id);
1545 // If the struct has a constructor, encode it.
1546 if !struct_def.is_struct() {
1547 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1548 self.record(ctor_def_id,
1549 IsolatedEncoder::encode_struct_ctor,
1550 (def_id, ctor_def_id));
1553 hir::ItemUnion(..) => {
1554 self.encode_fields(def_id);
1556 hir::ItemImpl(..) => {
1557 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1558 self.record(trait_item_def_id,
1559 IsolatedEncoder::encode_info_for_impl_item,
1563 hir::ItemTrait(..) => {
1564 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1565 self.record(item_def_id,
1566 IsolatedEncoder::encode_info_for_trait_item,
1574 struct ImplVisitor<'a, 'tcx: 'a> {
1575 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1576 impls: FxHashMap<DefId, Vec<DefIndex>>,
1579 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1580 fn visit_item(&mut self, item: &hir::Item) {
1581 if let hir::ItemImpl(..) = item.node {
1582 let impl_id = self.tcx.hir.local_def_id(item.id);
1583 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1585 .entry(trait_ref.def_id)
1587 .push(impl_id.index);
1592 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1594 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1595 // handled in `visit_item` above
1599 // NOTE(eddyb) The following comment was preserved for posterity, even
1600 // though it's no longer relevant as EBML (which uses nested & tagged
1601 // "documents") was replaced with a scheme that can't go out of bounds.
1603 // And here we run into yet another obscure archive bug: in which metadata
1604 // loaded from archives may have trailing garbage bytes. Awhile back one of
1605 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1606 // and opt) by having ebml generate an out-of-bounds panic when looking at
1609 // Upon investigation it turned out that the metadata file inside of an rlib
1610 // (and ar archive) was being corrupted. Some compilations would generate a
1611 // metadata file which would end in a few extra bytes, while other
1612 // compilations would not have these extra bytes appended to the end. These
1613 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1614 // being interpreted causing the out-of-bounds.
1616 // The root cause of why these extra bytes were appearing was never
1617 // discovered, and in the meantime the solution we're employing is to insert
1618 // the length of the metadata to the start of the metadata. Later on this
1619 // will allow us to slice the metadata to the precise length that we just
1620 // generated regardless of trailing bytes that end up in it.
1622 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1623 link_meta: &LinkMeta,
1624 exported_symbols: &NodeSet)
1627 let mut cursor = Cursor::new(vec![]);
1628 cursor.write_all(METADATA_HEADER).unwrap();
1630 // Will be filled with the root position after encoding everything.
1631 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1634 let mut ecx = EncodeContext {
1635 opaque: opaque::Encoder::new(&mut cursor),
1639 lazy_state: LazyState::NoNode,
1640 type_shorthands: Default::default(),
1641 predicate_shorthands: Default::default(),
1644 // Encode the rustc version string in a predictable location.
1645 rustc_version().encode(&mut ecx).unwrap();
1647 // Encode all the entries and extra information in the crate,
1648 // culminating in the `CrateRoot` which points to all of it.
1649 ecx.encode_crate_root()
1651 let mut result = cursor.into_inner();
1653 // Encode the root position.
1654 let header = METADATA_HEADER.len();
1655 let pos = root.position;
1656 result[header + 0] = (pos >> 24) as u8;
1657 result[header + 1] = (pos >> 16) as u8;
1658 result[header + 2] = (pos >> 8) as u8;
1659 result[header + 3] = (pos >> 0) as u8;
1661 EncodedMetadata { raw_data: result }
1664 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1665 let ty = tcx.type_of(did);
1667 ty::TyAdt(ref def, _) => return def.repr,
1668 _ => bug!("{} is not an ADT", ty),