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::ich::Fingerprint;
22 use rustc::middle::dependency_format::Linkage;
23 use rustc::middle::lang_items;
25 use rustc::traits::specialization_graph;
26 use rustc::ty::{self, Ty, TyCtxt, ReprOptions};
27 use rustc::ty::codec::{self as ty_codec, TyEncoder};
29 use rustc::session::config::{self, CrateTypeProcMacro};
30 use rustc::util::nodemap::{FxHashMap, NodeSet};
32 use rustc_data_structures::stable_hasher::StableHasher;
33 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
36 use std::io::prelude::*;
39 use rustc_data_structures::sync::Lrc;
41 use syntax::ast::{self, CRATE_NODE_ID};
42 use syntax::codemap::Spanned;
44 use syntax::symbol::Symbol;
45 use syntax_pos::{self, FileName, FileMap, Span, DUMMY_SP};
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 // This is used to speed up Span encoding.
63 filemap_cache: Lrc<FileMap>,
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<CrateNum> for EncodeContext<'a, 'tcx> {
122 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
123 self.emit_u32(cnum.as_u32())
127 impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
129 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
140 impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
142 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
143 self.emit_u32(def_index.as_raw_u32())
147 impl<'a, 'tcx> SpecializedEncoder<Span> for EncodeContext<'a, 'tcx> {
148 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
149 if *span == DUMMY_SP {
150 return TAG_INVALID_SPAN.encode(self)
153 let span = span.data();
155 // The Span infrastructure should make sure that this invariant holds:
156 debug_assert!(span.lo <= span.hi);
158 if !self.filemap_cache.contains(span.lo) {
159 let codemap = self.tcx.sess.codemap();
160 let filemap_index = codemap.lookup_filemap_idx(span.lo);
161 self.filemap_cache = codemap.files()[filemap_index].clone();
164 if !self.filemap_cache.contains(span.hi) {
165 // Unfortunately, macro expansion still sometimes generates Spans
166 // that malformed in this way.
167 return TAG_INVALID_SPAN.encode(self)
170 TAG_VALID_SPAN.encode(self)?;
171 span.lo.encode(self)?;
173 // Encode length which is usually less than span.hi and profits more
174 // from the variable-length integer encoding that we use.
175 let len = span.hi - span.lo;
178 // Don't encode the expansion context.
182 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
183 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
184 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
188 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
189 fn specialized_encode(&mut self,
190 predicates: &ty::GenericPredicates<'tcx>)
191 -> Result<(), Self::Error> {
192 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
196 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
197 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
198 f.encode_opaque(&mut self.opaque)
202 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
203 for EncodeContext<'a, 'tcx> {
204 fn specialized_encode(&mut self,
205 _: &mir::ClearCrossCrate<T>)
206 -> Result<(), Self::Error> {
211 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
212 fn position(&self) -> usize {
213 self.opaque.position()
217 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
219 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
220 assert_eq!(self.lazy_state, LazyState::NoNode);
221 let pos = self.position();
222 self.lazy_state = LazyState::NodeStart(pos);
223 let r = f(self, pos);
224 self.lazy_state = LazyState::NoNode;
228 fn emit_lazy_distance(&mut self,
231 -> Result<(), <Self as Encoder>::Error> {
232 let min_end = position + min_size;
233 let distance = match self.lazy_state {
234 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
235 LazyState::NodeStart(start) => {
236 assert!(min_end <= start);
239 LazyState::Previous(last_min_end) => {
240 assert!(last_min_end <= position);
241 position - last_min_end
244 self.lazy_state = LazyState::Previous(min_end);
245 self.emit_usize(distance)
248 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
249 self.emit_node(|ecx, pos| {
250 value.encode(ecx).unwrap();
252 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
253 Lazy::with_position(pos)
257 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
258 where I: IntoIterator<Item = T>,
261 self.emit_node(|ecx, pos| {
262 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
264 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
265 LazySeq::with_position_and_length(pos, len)
269 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
270 where I: IntoIterator<Item = &'b T>,
273 self.emit_node(|ecx, pos| {
274 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
276 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
277 LazySeq::with_position_and_length(pos, len)
281 // Encodes something that corresponds to a single DepNode::GlobalMetaData
282 // and registers the Fingerprint in the `metadata_hashes` map.
283 pub fn tracked<'x, DATA, R>(&'x mut self,
284 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
287 op(&mut IsolatedEncoder::new(self), data)
290 fn encode_info_for_items(&mut self) -> Index {
291 let krate = self.tcx.hir.krate();
292 let mut index = IndexBuilder::new(self);
293 index.record(DefId::local(CRATE_DEF_INDEX),
294 IsolatedEncoder::encode_info_for_mod,
295 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
296 let mut visitor = EncodeVisitor { index: index };
297 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
298 for macro_def in &krate.exported_macros {
299 visitor.visit_macro_def(macro_def);
301 visitor.index.into_items()
304 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
305 let definitions = self.tcx.hir.definitions();
306 self.lazy(definitions.def_path_table())
309 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
310 let codemap = self.tcx.sess.codemap();
311 let all_filemaps = codemap.files();
313 let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
315 let adapted = all_filemaps.iter()
317 // No need to re-export imported filemaps, as any downstream
318 // crate will import them from their original source.
319 !filemap.is_imported()
322 // When exporting FileMaps, we expand all paths to absolute
323 // paths because any relative paths are potentially relative to
324 // a wrong directory.
325 // However, if a path has been modified via
326 // `--remap-path-prefix` we assume the user has already set
327 // things up the way they want and don't touch the path values
330 FileName::Real(ref name) => {
331 if filemap.name_was_remapped ||
332 (name.is_relative() && working_dir_was_remapped) {
333 // This path of this FileMap has been modified by
334 // path-remapping, so we use it verbatim (and avoid cloning
335 // the whole map in the process).
338 let mut adapted = (**filemap).clone();
339 adapted.name = Path::new(&working_dir).join(name).into();
340 adapted.name_hash = {
341 let mut hasher: StableHasher<u128> = StableHasher::new();
342 adapted.name.hash(&mut hasher);
348 // expanded code, not from a file
349 _ => filemap.clone(),
352 .collect::<Vec<_>>();
354 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
357 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
358 let mut i = self.position();
360 let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
361 let dylib_dependency_formats = self.tracked(
362 IsolatedEncoder::encode_dylib_dependency_formats,
364 let dep_bytes = self.position() - i;
366 // Encode the language items.
368 let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
369 let lang_items_missing = self.tracked(
370 IsolatedEncoder::encode_lang_items_missing,
372 let lang_item_bytes = self.position() - i;
374 // Encode the native libraries used
376 let native_libraries = self.tracked(
377 IsolatedEncoder::encode_native_libraries,
379 let native_lib_bytes = self.position() - i;
383 let codemap = self.encode_codemap();
384 let codemap_bytes = self.position() - i;
386 // Encode DefPathTable
388 let def_path_table = self.encode_def_path_table();
389 let def_path_table_bytes = self.position() - i;
391 // Encode the def IDs of impls, for coherence checking.
393 let impls = self.tracked(IsolatedEncoder::encode_impls, ());
394 let impl_bytes = self.position() - i;
396 // Encode exported symbols info.
398 let exported_symbols = self.tracked(
399 IsolatedEncoder::encode_exported_symbols,
400 self.exported_symbols);
401 let exported_symbols_bytes = self.position() - i;
403 // Encode and index the items.
405 let items = self.encode_info_for_items();
406 let item_bytes = self.position() - i;
409 let index = items.write_index(&mut self.opaque.cursor);
410 let index_bytes = self.position() - i;
413 let link_meta = self.link_meta;
414 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
415 let has_default_lib_allocator =
416 attr::contains_name(tcx.hir.krate_attrs(), "default_lib_allocator");
417 let has_global_allocator = tcx.sess.has_global_allocator.get();
418 let root = self.lazy(&CrateRoot {
419 name: tcx.crate_name(LOCAL_CRATE),
420 triple: tcx.sess.opts.target_triple.clone(),
421 hash: link_meta.crate_hash,
422 disambiguator: tcx.sess.local_crate_disambiguator(),
423 panic_strategy: tcx.sess.panic_strategy(),
424 has_global_allocator: has_global_allocator,
425 has_default_lib_allocator: has_default_lib_allocator,
426 plugin_registrar_fn: tcx.sess
429 .map(|id| tcx.hir.local_def_id(id).index),
430 macro_derive_registrar: if is_proc_macro {
431 let id = tcx.sess.derive_registrar_fn.get().unwrap();
432 Some(tcx.hir.local_def_id(id).index)
438 dylib_dependency_formats,
449 let total_bytes = self.position();
451 if self.tcx.sess.meta_stats() {
452 let mut zero_bytes = 0;
453 for e in self.opaque.cursor.get_ref() {
459 println!("metadata stats:");
460 println!(" dep bytes: {}", dep_bytes);
461 println!(" lang item bytes: {}", lang_item_bytes);
462 println!(" native bytes: {}", native_lib_bytes);
463 println!(" codemap bytes: {}", codemap_bytes);
464 println!(" impl bytes: {}", impl_bytes);
465 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
466 println!(" def-path table bytes: {}", def_path_table_bytes);
467 println!(" item bytes: {}", item_bytes);
468 println!(" index bytes: {}", index_bytes);
469 println!(" zero bytes: {}", zero_bytes);
470 println!(" total bytes: {}", total_bytes);
477 // These are methods for encoding various things. They are meant to be used with
478 // IndexBuilder::record() and EncodeContext::tracked(). They actually
479 // would not have to be methods of IsolatedEncoder (free standing functions
480 // taking IsolatedEncoder as first argument would be just fine) but by making
481 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
482 // clause again and again.
483 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
484 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
485 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
487 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
490 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
492 let ty = tcx.type_of(def_id);
493 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
497 /// Encode data for the given variant of the given ADT. The
498 /// index of the variant is untracked: this is ok because we
499 /// will have to lookup the adt-def by its id, and that gives us
500 /// the right to access any information in the adt-def (including,
501 /// e.g., the length of the various vectors).
502 fn encode_enum_variant_info(&mut self,
503 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
506 let def = tcx.adt_def(enum_did);
507 let variant = &def.variants[index];
508 let def_id = variant.did;
509 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
511 let data = VariantData {
512 ctor_kind: variant.ctor_kind,
513 discr: variant.discr,
515 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
516 Some(self.lazy(&tcx.fn_sig(def_id)))
522 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
523 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
526 kind: EntryKind::Variant(self.lazy(&data)),
527 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
528 span: self.lazy(&tcx.def_span(def_id)),
529 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
530 children: self.lazy_seq(variant.fields.iter().map(|f| {
531 assert!(f.did.is_local());
534 stability: self.encode_stability(def_id),
535 deprecation: self.encode_deprecation(def_id),
537 ty: Some(self.encode_item_type(def_id)),
538 inherent_impls: LazySeq::empty(),
539 variances: if variant.ctor_kind == CtorKind::Fn {
540 self.encode_variances_of(def_id)
544 generics: Some(self.encode_generics(def_id)),
545 predicates: Some(self.encode_predicates(def_id)),
548 mir: self.encode_optimized_mir(def_id),
552 fn encode_info_for_mod(&mut self,
553 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
558 let def_id = tcx.hir.local_def_id(id);
559 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
562 reexports: match tcx.module_exports(def_id) {
563 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
564 _ => LazySeq::empty(),
569 kind: EntryKind::Mod(self.lazy(&data)),
570 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
571 span: self.lazy(&tcx.def_span(def_id)),
572 attributes: self.encode_attributes(attrs),
573 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
574 tcx.hir.local_def_id(item_id.id).index
576 stability: self.encode_stability(def_id),
577 deprecation: self.encode_deprecation(def_id),
580 inherent_impls: LazySeq::empty(),
581 variances: LazySeq::empty(),
590 /// Encode data for the given field of the given variant of the
591 /// given ADT. The indices of the variant/field are untracked:
592 /// this is ok because we will have to lookup the adt-def by its
593 /// id, and that gives us the right to access any information in
594 /// the adt-def (including, e.g., the length of the various
596 fn encode_field(&mut self,
597 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
602 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
603 let field = &variant.fields[field_index];
605 let def_id = field.did;
606 debug!("IsolatedEncoder::encode_field({:?})", def_id);
608 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
609 let variant_data = tcx.hir.expect_variant_data(variant_id);
612 kind: EntryKind::Field,
613 visibility: self.lazy(&field.vis),
614 span: self.lazy(&tcx.def_span(def_id)),
615 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
616 children: LazySeq::empty(),
617 stability: self.encode_stability(def_id),
618 deprecation: self.encode_deprecation(def_id),
620 ty: Some(self.encode_item_type(def_id)),
621 inherent_impls: LazySeq::empty(),
622 variances: LazySeq::empty(),
623 generics: Some(self.encode_generics(def_id)),
624 predicates: Some(self.encode_predicates(def_id)),
631 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
632 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
634 let adt_def = tcx.adt_def(adt_def_id);
635 let variant = adt_def.non_enum_variant();
637 let data = VariantData {
638 ctor_kind: variant.ctor_kind,
639 discr: variant.discr,
640 struct_ctor: Some(def_id.index),
641 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
642 Some(self.lazy(&tcx.fn_sig(def_id)))
648 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
649 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
650 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
651 for field in &variant.fields {
652 if ctor_vis.is_at_least(field.vis, tcx) {
653 ctor_vis = field.vis;
657 // If the structure is marked as non_exhaustive then lower the visibility
658 // to within the crate.
659 if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
660 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
663 let repr_options = get_repr_options(&tcx, adt_def_id);
666 kind: EntryKind::Struct(self.lazy(&data), repr_options),
667 visibility: self.lazy(&ctor_vis),
668 span: self.lazy(&tcx.def_span(def_id)),
669 attributes: LazySeq::empty(),
670 children: LazySeq::empty(),
671 stability: self.encode_stability(def_id),
672 deprecation: self.encode_deprecation(def_id),
674 ty: Some(self.encode_item_type(def_id)),
675 inherent_impls: LazySeq::empty(),
676 variances: if variant.ctor_kind == CtorKind::Fn {
677 self.encode_variances_of(def_id)
681 generics: Some(self.encode_generics(def_id)),
682 predicates: Some(self.encode_predicates(def_id)),
685 mir: self.encode_optimized_mir(def_id),
689 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
690 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
692 self.lazy(tcx.generics_of(def_id))
695 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
696 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
698 self.lazy(&tcx.predicates_of(def_id))
701 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
702 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
705 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
706 let ast_item = tcx.hir.expect_trait_item(node_id);
707 let trait_item = tcx.associated_item(def_id);
709 let container = match trait_item.defaultness {
710 hir::Defaultness::Default { has_value: true } =>
711 AssociatedContainer::TraitWithDefault,
712 hir::Defaultness::Default { has_value: false } =>
713 AssociatedContainer::TraitRequired,
714 hir::Defaultness::Final =>
715 span_bug!(ast_item.span, "traits cannot have final items"),
718 let kind = match trait_item.kind {
719 ty::AssociatedKind::Const => {
720 EntryKind::AssociatedConst(container, 0)
722 ty::AssociatedKind::Method => {
723 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
724 let arg_names = match *m {
725 hir::TraitMethod::Required(ref names) => {
726 self.encode_fn_arg_names(names)
728 hir::TraitMethod::Provided(body) => {
729 self.encode_fn_arg_names_for_body(body)
733 constness: hir::Constness::NotConst,
735 sig: self.lazy(&tcx.fn_sig(def_id)),
740 EntryKind::Method(self.lazy(&MethodData {
743 has_self: trait_item.method_has_self_argument,
746 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
751 visibility: self.lazy(&trait_item.vis),
752 span: self.lazy(&ast_item.span),
753 attributes: self.encode_attributes(&ast_item.attrs),
754 children: LazySeq::empty(),
755 stability: self.encode_stability(def_id),
756 deprecation: self.encode_deprecation(def_id),
758 ty: match trait_item.kind {
759 ty::AssociatedKind::Const |
760 ty::AssociatedKind::Method => {
761 Some(self.encode_item_type(def_id))
763 ty::AssociatedKind::Type => {
764 if trait_item.defaultness.has_value() {
765 Some(self.encode_item_type(def_id))
771 inherent_impls: LazySeq::empty(),
772 variances: if trait_item.kind == ty::AssociatedKind::Method {
773 self.encode_variances_of(def_id)
777 generics: Some(self.encode_generics(def_id)),
778 predicates: Some(self.encode_predicates(def_id)),
780 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
781 Some(self.encode_body(body))
785 mir: self.encode_optimized_mir(def_id),
789 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
790 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
793 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
794 let ast_item = self.tcx.hir.expect_impl_item(node_id);
795 let impl_item = self.tcx.associated_item(def_id);
797 let container = match impl_item.defaultness {
798 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
799 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
800 hir::Defaultness::Default { has_value: false } =>
801 span_bug!(ast_item.span, "impl items always have values (currently)"),
804 let kind = match impl_item.kind {
805 ty::AssociatedKind::Const => {
806 EntryKind::AssociatedConst(container,
807 self.tcx.at(ast_item.span).mir_const_qualif(def_id).0)
809 ty::AssociatedKind::Method => {
810 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
812 constness: sig.constness,
813 arg_names: self.encode_fn_arg_names_for_body(body),
814 sig: self.lazy(&tcx.fn_sig(def_id)),
819 EntryKind::Method(self.lazy(&MethodData {
822 has_self: impl_item.method_has_self_argument,
825 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
828 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
830 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
831 let generics = self.tcx.generics_of(def_id);
832 let types = generics.parent_types as usize + generics.types.len();
833 let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
834 let is_const_fn = sig.constness == hir::Constness::Const;
835 let ast = if is_const_fn { Some(body) } else { None };
836 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
837 (ast, needs_inline || is_const_fn || always_encode_mir)
844 visibility: self.lazy(&impl_item.vis),
845 span: self.lazy(&ast_item.span),
846 attributes: self.encode_attributes(&ast_item.attrs),
847 children: LazySeq::empty(),
848 stability: self.encode_stability(def_id),
849 deprecation: self.encode_deprecation(def_id),
851 ty: Some(self.encode_item_type(def_id)),
852 inherent_impls: LazySeq::empty(),
853 variances: if impl_item.kind == ty::AssociatedKind::Method {
854 self.encode_variances_of(def_id)
858 generics: Some(self.encode_generics(def_id)),
859 predicates: Some(self.encode_predicates(def_id)),
861 ast: ast.map(|body| self.encode_body(body)),
862 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
866 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
867 -> LazySeq<ast::Name> {
868 self.tcx.dep_graph.with_ignore(|| {
869 let body = self.tcx.hir.body(body_id);
870 self.lazy_seq(body.arguments.iter().map(|arg| {
872 PatKind::Binding(_, _, name, _) => name.node,
873 _ => Symbol::intern("")
879 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
880 -> LazySeq<ast::Name> {
881 self.lazy_seq(names.iter().map(|name| name.node))
884 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
885 debug!("EntryBuilder::encode_mir({:?})", def_id);
886 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
887 let mir = self.tcx.optimized_mir(def_id);
888 Some(self.lazy(&mir))
894 // Encodes the inherent implementations of a structure, enumeration, or trait.
895 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
896 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
897 let implementations = self.tcx.inherent_impls(def_id);
898 if implementations.is_empty() {
901 self.lazy_seq(implementations.iter().map(|&def_id| {
902 assert!(def_id.is_local());
908 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
909 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
910 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
913 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
914 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
915 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
918 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
921 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
923 let kind = match item.node {
924 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
925 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
926 hir::ItemConst(..) => {
927 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id).0)
929 hir::ItemFn(_, _, constness, .., body) => {
932 arg_names: self.encode_fn_arg_names_for_body(body),
933 sig: self.lazy(&tcx.fn_sig(def_id)),
936 EntryKind::Fn(self.lazy(&data))
938 hir::ItemMod(ref m) => {
939 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
941 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
942 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
943 hir::ItemTy(..) => EntryKind::Type,
944 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
945 hir::ItemStruct(ref struct_def, _) => {
946 let variant = tcx.adt_def(def_id).non_enum_variant();
948 // Encode def_ids for each field and method
949 // for methods, write all the stuff get_trait_method
951 let struct_ctor = if !struct_def.is_struct() {
952 Some(tcx.hir.local_def_id(struct_def.id()).index)
957 let repr_options = get_repr_options(&tcx, def_id);
959 EntryKind::Struct(self.lazy(&VariantData {
960 ctor_kind: variant.ctor_kind,
961 discr: variant.discr,
966 hir::ItemUnion(..) => {
967 let variant = tcx.adt_def(def_id).non_enum_variant();
968 let repr_options = get_repr_options(&tcx, def_id);
970 EntryKind::Union(self.lazy(&VariantData {
971 ctor_kind: variant.ctor_kind,
972 discr: variant.discr,
977 hir::ItemImpl(_, polarity, defaultness, ..) => {
978 let trait_ref = tcx.impl_trait_ref(def_id);
979 let parent = if let Some(trait_ref) = trait_ref {
980 let trait_def = tcx.trait_def(trait_ref.def_id);
981 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
983 specialization_graph::Node::Impl(parent) => Some(parent),
991 // if this is an impl of `CoerceUnsized`, create its
992 // "unsized info", else just store None
993 let coerce_unsized_info =
994 trait_ref.and_then(|t| {
995 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
996 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1002 let data = ImplData {
1005 parent_impl: parent,
1006 coerce_unsized_info,
1007 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1010 EntryKind::Impl(self.lazy(&data))
1012 hir::ItemTrait(..) => {
1013 let trait_def = tcx.trait_def(def_id);
1014 let data = TraitData {
1015 unsafety: trait_def.unsafety,
1016 paren_sugar: trait_def.paren_sugar,
1017 has_auto_impl: tcx.trait_is_auto(def_id),
1018 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1021 EntryKind::Trait(self.lazy(&data))
1023 hir::ItemExternCrate(_) |
1024 hir::ItemTraitAlias(..) |
1025 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1030 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1031 span: self.lazy(&item.span),
1032 attributes: self.encode_attributes(&item.attrs),
1033 children: match item.node {
1034 hir::ItemForeignMod(ref fm) => {
1035 self.lazy_seq(fm.items
1037 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1039 hir::ItemEnum(..) => {
1040 let def = self.tcx.adt_def(def_id);
1041 self.lazy_seq(def.variants.iter().map(|v| {
1042 assert!(v.did.is_local());
1046 hir::ItemStruct(..) |
1047 hir::ItemUnion(..) => {
1048 let def = self.tcx.adt_def(def_id);
1049 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1050 assert!(f.did.is_local());
1055 hir::ItemTrait(..) => {
1056 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1057 assert!(def_id.is_local());
1061 _ => LazySeq::empty(),
1063 stability: self.encode_stability(def_id),
1064 deprecation: self.encode_deprecation(def_id),
1066 ty: match item.node {
1067 hir::ItemStatic(..) |
1068 hir::ItemConst(..) |
1072 hir::ItemStruct(..) |
1073 hir::ItemUnion(..) |
1074 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1077 inherent_impls: self.encode_inherent_implementations(def_id),
1078 variances: match item.node {
1080 hir::ItemStruct(..) |
1081 hir::ItemUnion(..) |
1082 hir::ItemFn(..) => self.encode_variances_of(def_id),
1083 _ => LazySeq::empty(),
1085 generics: match item.node {
1086 hir::ItemStatic(..) |
1087 hir::ItemConst(..) |
1091 hir::ItemStruct(..) |
1092 hir::ItemUnion(..) |
1094 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1097 predicates: match item.node {
1098 hir::ItemStatic(..) |
1099 hir::ItemConst(..) |
1103 hir::ItemStruct(..) |
1104 hir::ItemUnion(..) |
1106 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1110 ast: match item.node {
1111 hir::ItemConst(_, body) |
1112 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
1113 Some(self.encode_body(body))
1117 mir: match item.node {
1118 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
1119 self.encode_optimized_mir(def_id)
1121 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1122 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1123 let has_tps = generics.ty_params().next().is_some();
1124 let needs_inline = has_tps || attr::requests_inline(&item.attrs);
1125 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1126 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
1127 self.encode_optimized_mir(def_id)
1137 /// Serialize the text of exported macros
1138 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1139 use syntax::print::pprust;
1140 let def_id = self.tcx.hir.local_def_id(macro_def.id);
1142 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1143 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1144 legacy: macro_def.legacy,
1146 visibility: self.lazy(&ty::Visibility::Public),
1147 span: self.lazy(¯o_def.span),
1148 attributes: self.encode_attributes(¯o_def.attrs),
1149 stability: self.encode_stability(def_id),
1150 deprecation: self.encode_deprecation(def_id),
1152 children: LazySeq::empty(),
1154 inherent_impls: LazySeq::empty(),
1155 variances: LazySeq::empty(),
1163 fn encode_info_for_ty_param(&mut self,
1164 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1166 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1169 kind: EntryKind::Type,
1170 visibility: self.lazy(&ty::Visibility::Public),
1171 span: self.lazy(&tcx.def_span(def_id)),
1172 attributes: LazySeq::empty(),
1173 children: LazySeq::empty(),
1177 ty: if has_default {
1178 Some(self.encode_item_type(def_id))
1182 inherent_impls: LazySeq::empty(),
1183 variances: LazySeq::empty(),
1192 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1193 debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
1196 kind: EntryKind::Type,
1197 visibility: self.lazy(&ty::Visibility::Public),
1198 span: self.lazy(&tcx.def_span(def_id)),
1199 attributes: LazySeq::empty(),
1200 children: LazySeq::empty(),
1204 ty: Some(self.encode_item_type(def_id)),
1205 inherent_impls: LazySeq::empty(),
1206 variances: LazySeq::empty(),
1207 generics: Some(self.encode_generics(def_id)),
1208 predicates: Some(self.encode_predicates(def_id)),
1215 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1216 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1219 let tables = self.tcx.typeck_tables_of(def_id);
1220 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1221 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1222 let kind = match tables.node_id_to_type(hir_id).sty {
1223 ty::TyGenerator(def_id, ..) => {
1224 let layout = self.tcx.generator_layout(def_id);
1225 let data = GeneratorData {
1226 layout: layout.clone(),
1228 EntryKind::Generator(self.lazy(&data))
1231 ty::TyClosure(def_id, substs) => {
1232 let sig = substs.closure_sig(def_id, self.tcx);
1233 let data = ClosureData { sig: self.lazy(&sig) };
1234 EntryKind::Closure(self.lazy(&data))
1237 _ => bug!("closure that is neither generator nor closure")
1242 visibility: self.lazy(&ty::Visibility::Public),
1243 span: self.lazy(&tcx.def_span(def_id)),
1244 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1245 children: LazySeq::empty(),
1249 ty: Some(self.encode_item_type(def_id)),
1250 inherent_impls: LazySeq::empty(),
1251 variances: LazySeq::empty(),
1252 generics: Some(self.encode_generics(def_id)),
1256 mir: self.encode_optimized_mir(def_id),
1260 fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1261 debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
1263 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1264 let body = tcx.hir.body_owned_by(id);
1267 kind: EntryKind::Const(tcx.mir_const_qualif(def_id).0),
1268 visibility: self.lazy(&ty::Visibility::Public),
1269 span: self.lazy(&tcx.def_span(def_id)),
1270 attributes: LazySeq::empty(),
1271 children: LazySeq::empty(),
1275 ty: Some(self.encode_item_type(def_id)),
1276 inherent_impls: LazySeq::empty(),
1277 variances: LazySeq::empty(),
1278 generics: Some(self.encode_generics(def_id)),
1279 predicates: Some(self.encode_predicates(def_id)),
1281 ast: Some(self.encode_body(body)),
1282 mir: self.encode_optimized_mir(def_id),
1286 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1287 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1288 // we rely on the HashStable specialization for [Attribute]
1289 // to properly filter things out.
1290 self.lazy_seq_from_slice(attrs)
1293 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1294 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1295 self.lazy_seq(used_libraries.iter().cloned())
1298 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1299 let crates = self.tcx.crates();
1301 let mut deps = crates
1304 let dep = CrateDep {
1305 name: self.tcx.original_crate_name(cnum),
1306 hash: self.tcx.crate_hash(cnum),
1307 kind: self.tcx.dep_kind(cnum),
1311 .collect::<Vec<_>>();
1313 deps.sort_by_key(|&(cnum, _)| cnum);
1316 // Sanity-check the crate numbers
1317 let mut expected_cnum = 1;
1318 for &(n, _) in &deps {
1319 assert_eq!(n, CrateNum::new(expected_cnum));
1324 // We're just going to write a list of crate 'name-hash-version's, with
1325 // the assumption that they are numbered 1 to n.
1326 // FIXME (#2166): This is not nearly enough to support correct versioning
1327 // but is enough to get transitive crate dependencies working.
1328 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1331 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1333 let lang_items = tcx.lang_items();
1334 let lang_items = lang_items.items().iter();
1335 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1336 if let Some(def_id) = opt_def_id {
1337 if def_id.is_local() {
1338 return Some((def_id.index, i));
1345 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1347 self.lazy_seq_ref(&tcx.lang_items().missing)
1350 /// Encodes an index, mapping each trait to its (local) implementations.
1351 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1352 debug!("IsolatedEncoder::encode_impls()");
1354 let mut visitor = ImplVisitor {
1358 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1360 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1362 // Bring everything into deterministic order for hashing
1363 all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1364 tcx.def_path_hash(trait_def_id)
1367 let all_impls: Vec<_> = all_impls
1369 .map(|(trait_def_id, mut impls)| {
1370 // Bring everything into deterministic order for hashing
1371 impls.sort_unstable_by_key(|&def_index| {
1372 tcx.hir.definitions().def_path_hash(def_index)
1376 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1377 impls: self.lazy_seq_from_slice(&impls[..]),
1382 self.lazy_seq_from_slice(&all_impls[..])
1385 // Encodes all symbols exported from this crate into the metadata.
1387 // This pass is seeded off the reachability list calculated in the
1388 // middle::reachable module but filters out items that either don't have a
1389 // symbol associated with them (they weren't translated) or if they're an FFI
1390 // definition (as that's not defined in this crate).
1391 fn encode_exported_symbols(&mut self, exported_symbols: &NodeSet) -> LazySeq<DefIndex> {
1393 self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
1396 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1397 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1399 self.lazy_seq(arr.iter().map(|slot| {
1401 Linkage::NotLinked |
1402 Linkage::IncludedFromDylib => None,
1404 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1405 Linkage::Static => Some(LinkagePreference::RequireStatic),
1409 None => LazySeq::empty(),
1413 fn encode_info_for_foreign_item(&mut self,
1414 (def_id, nitem): (DefId, &hir::ForeignItem))
1418 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1420 let kind = match nitem.node {
1421 hir::ForeignItemFn(_, ref names, _) => {
1423 constness: hir::Constness::NotConst,
1424 arg_names: self.encode_fn_arg_names(names),
1425 sig: self.lazy(&tcx.fn_sig(def_id)),
1427 EntryKind::ForeignFn(self.lazy(&data))
1429 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1430 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1431 hir::ForeignItemType => EntryKind::ForeignType,
1436 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1437 span: self.lazy(&nitem.span),
1438 attributes: self.encode_attributes(&nitem.attrs),
1439 children: LazySeq::empty(),
1440 stability: self.encode_stability(def_id),
1441 deprecation: self.encode_deprecation(def_id),
1443 ty: Some(self.encode_item_type(def_id)),
1444 inherent_impls: LazySeq::empty(),
1445 variances: match nitem.node {
1446 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1447 _ => LazySeq::empty(),
1449 generics: Some(self.encode_generics(def_id)),
1450 predicates: Some(self.encode_predicates(def_id)),
1458 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1459 index: IndexBuilder<'a, 'b, 'tcx>,
1462 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1463 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1464 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1466 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1467 intravisit::walk_expr(self, ex);
1468 self.index.encode_info_for_expr(ex);
1470 fn visit_item(&mut self, item: &'tcx hir::Item) {
1471 intravisit::walk_item(self, item);
1472 let def_id = self.index.tcx.hir.local_def_id(item.id);
1474 hir::ItemExternCrate(_) |
1475 hir::ItemUse(..) => (), // ignore these
1476 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1478 self.index.encode_addl_info_for_item(item);
1480 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1481 intravisit::walk_foreign_item(self, ni);
1482 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1483 self.index.record(def_id,
1484 IsolatedEncoder::encode_info_for_foreign_item,
1487 fn visit_variant(&mut self,
1488 v: &'tcx hir::Variant,
1489 g: &'tcx hir::Generics,
1491 intravisit::walk_variant(self, v, g, id);
1493 if let Some(discr) = v.node.disr_expr {
1494 let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1495 self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1498 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1499 intravisit::walk_generics(self, generics);
1500 self.index.encode_info_for_generics(generics);
1502 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1503 intravisit::walk_ty(self, ty);
1504 self.index.encode_info_for_ty(ty);
1506 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1507 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1508 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1512 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1513 fn encode_fields(&mut self, adt_def_id: DefId) {
1514 let def = self.tcx.adt_def(adt_def_id);
1515 for (variant_index, variant) in def.variants.iter().enumerate() {
1516 for (field_index, field) in variant.fields.iter().enumerate() {
1517 self.record(field.did,
1518 IsolatedEncoder::encode_field,
1519 (adt_def_id, Untracked((variant_index, field_index))));
1524 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1525 for ty_param in generics.ty_params() {
1526 let def_id = self.tcx.hir.local_def_id(ty_param.id);
1527 let has_default = Untracked(ty_param.default.is_some());
1528 self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
1532 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1534 hir::TyImplTraitExistential(..) => {
1535 let def_id = self.tcx.hir.local_def_id(ty.id);
1536 self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
1538 hir::TyArray(_, len) => {
1539 let def_id = self.tcx.hir.body_owner_def_id(len);
1540 self.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1546 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1548 hir::ExprClosure(..) => {
1549 let def_id = self.tcx.hir.local_def_id(expr.id);
1550 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1556 /// In some cases, along with the item itself, we also
1557 /// encode some sub-items. Usually we want some info from the item
1558 /// so it's easier to do that here then to wait until we would encounter
1559 /// normally in the visitor walk.
1560 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1561 let def_id = self.tcx.hir.local_def_id(item.id);
1563 hir::ItemStatic(..) |
1564 hir::ItemConst(..) |
1567 hir::ItemForeignMod(..) |
1568 hir::ItemGlobalAsm(..) |
1569 hir::ItemExternCrate(..) |
1572 hir::ItemTraitAlias(..) => {
1573 // no sub-item recording needed in these cases
1575 hir::ItemEnum(..) => {
1576 self.encode_fields(def_id);
1578 let def = self.tcx.adt_def(def_id);
1579 for (i, variant) in def.variants.iter().enumerate() {
1580 self.record(variant.did,
1581 IsolatedEncoder::encode_enum_variant_info,
1582 (def_id, Untracked(i)));
1585 hir::ItemStruct(ref struct_def, _) => {
1586 self.encode_fields(def_id);
1588 // If the struct has a constructor, encode it.
1589 if !struct_def.is_struct() {
1590 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1591 self.record(ctor_def_id,
1592 IsolatedEncoder::encode_struct_ctor,
1593 (def_id, ctor_def_id));
1596 hir::ItemUnion(..) => {
1597 self.encode_fields(def_id);
1599 hir::ItemImpl(..) => {
1600 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1601 self.record(trait_item_def_id,
1602 IsolatedEncoder::encode_info_for_impl_item,
1606 hir::ItemTrait(..) => {
1607 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1608 self.record(item_def_id,
1609 IsolatedEncoder::encode_info_for_trait_item,
1617 struct ImplVisitor<'a, 'tcx: 'a> {
1618 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1619 impls: FxHashMap<DefId, Vec<DefIndex>>,
1622 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1623 fn visit_item(&mut self, item: &hir::Item) {
1624 if let hir::ItemImpl(..) = item.node {
1625 let impl_id = self.tcx.hir.local_def_id(item.id);
1626 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1628 .entry(trait_ref.def_id)
1630 .push(impl_id.index);
1635 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1637 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1638 // handled in `visit_item` above
1642 // NOTE(eddyb) The following comment was preserved for posterity, even
1643 // though it's no longer relevant as EBML (which uses nested & tagged
1644 // "documents") was replaced with a scheme that can't go out of bounds.
1646 // And here we run into yet another obscure archive bug: in which metadata
1647 // loaded from archives may have trailing garbage bytes. Awhile back one of
1648 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1649 // and opt) by having ebml generate an out-of-bounds panic when looking at
1652 // Upon investigation it turned out that the metadata file inside of an rlib
1653 // (and ar archive) was being corrupted. Some compilations would generate a
1654 // metadata file which would end in a few extra bytes, while other
1655 // compilations would not have these extra bytes appended to the end. These
1656 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1657 // being interpreted causing the out-of-bounds.
1659 // The root cause of why these extra bytes were appearing was never
1660 // discovered, and in the meantime the solution we're employing is to insert
1661 // the length of the metadata to the start of the metadata. Later on this
1662 // will allow us to slice the metadata to the precise length that we just
1663 // generated regardless of trailing bytes that end up in it.
1665 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1666 link_meta: &LinkMeta,
1667 exported_symbols: &NodeSet)
1670 let mut cursor = Cursor::new(vec![]);
1671 cursor.write_all(METADATA_HEADER).unwrap();
1673 // Will be filled with the root position after encoding everything.
1674 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1677 let mut ecx = EncodeContext {
1678 opaque: opaque::Encoder::new(&mut cursor),
1682 lazy_state: LazyState::NoNode,
1683 type_shorthands: Default::default(),
1684 predicate_shorthands: Default::default(),
1685 filemap_cache: tcx.sess.codemap().files()[0].clone(),
1688 // Encode the rustc version string in a predictable location.
1689 rustc_version().encode(&mut ecx).unwrap();
1691 // Encode all the entries and extra information in the crate,
1692 // culminating in the `CrateRoot` which points to all of it.
1693 ecx.encode_crate_root()
1695 let mut result = cursor.into_inner();
1697 // Encode the root position.
1698 let header = METADATA_HEADER.len();
1699 let pos = root.position;
1700 result[header + 0] = (pos >> 24) as u8;
1701 result[header + 1] = (pos >> 16) as u8;
1702 result[header + 2] = (pos >> 8) as u8;
1703 result[header + 3] = (pos >> 0) as u8;
1705 EncodedMetadata { raw_data: result }
1708 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1709 let ty = tcx.type_of(did);
1711 ty::TyAdt(ref def, _) => return def.repr,
1712 _ => bug!("{} is not an ADT", ty),