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::exported_symbols::{ExportedSymbol, SymbolExportLevel};
24 use rustc::middle::lang_items;
26 use rustc::traits::specialization_graph;
27 use rustc::ty::{self, Ty, TyCtxt, ReprOptions};
28 use rustc::ty::codec::{self as ty_codec, TyEncoder};
30 use rustc::session::config::{self, CrateTypeProcMacro};
31 use rustc::util::nodemap::FxHashMap;
33 use rustc_data_structures::stable_hasher::StableHasher;
34 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
37 use std::io::prelude::*;
40 use rustc_data_structures::sync::Lrc;
42 use syntax::ast::{self, CRATE_NODE_ID};
43 use syntax::codemap::Spanned;
45 use syntax::symbol::Symbol;
46 use syntax_pos::{self, FileName, FileMap, Span, DUMMY_SP};
48 use rustc::hir::{self, PatKind};
49 use rustc::hir::itemlikevisit::ItemLikeVisitor;
50 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
51 use rustc::hir::intravisit;
53 pub struct EncodeContext<'a, 'tcx: 'a> {
54 opaque: opaque::Encoder<'a>,
55 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
56 link_meta: &'a LinkMeta,
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.tcx.exported_symbols(LOCAL_CRATE);
399 let exported_symbols = self.tracked(
400 IsolatedEncoder::encode_exported_symbols,
402 let exported_symbols_bytes = self.position() - i;
404 // Encode and index the items.
406 let items = self.encode_info_for_items();
407 let item_bytes = self.position() - i;
410 let index = items.write_index(&mut self.opaque.cursor);
411 let index_bytes = self.position() - i;
414 let link_meta = self.link_meta;
415 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
416 let has_default_lib_allocator =
417 attr::contains_name(tcx.hir.krate_attrs(), "default_lib_allocator");
418 let has_global_allocator = tcx.sess.has_global_allocator.get();
419 let root = self.lazy(&CrateRoot {
420 name: tcx.crate_name(LOCAL_CRATE),
421 triple: tcx.sess.opts.target_triple.clone(),
422 hash: link_meta.crate_hash,
423 disambiguator: tcx.sess.local_crate_disambiguator(),
424 panic_strategy: tcx.sess.panic_strategy(),
425 has_global_allocator: has_global_allocator,
426 has_default_lib_allocator: has_default_lib_allocator,
427 plugin_registrar_fn: tcx.sess
430 .map(|id| tcx.hir.local_def_id(id).index),
431 macro_derive_registrar: if is_proc_macro {
432 let id = tcx.sess.derive_registrar_fn.get().unwrap();
433 Some(tcx.hir.local_def_id(id).index)
439 dylib_dependency_formats,
450 let total_bytes = self.position();
452 if self.tcx.sess.meta_stats() {
453 let mut zero_bytes = 0;
454 for e in self.opaque.cursor.get_ref() {
460 println!("metadata stats:");
461 println!(" dep bytes: {}", dep_bytes);
462 println!(" lang item bytes: {}", lang_item_bytes);
463 println!(" native bytes: {}", native_lib_bytes);
464 println!(" codemap bytes: {}", codemap_bytes);
465 println!(" impl bytes: {}", impl_bytes);
466 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
467 println!(" def-path table bytes: {}", def_path_table_bytes);
468 println!(" item bytes: {}", item_bytes);
469 println!(" index bytes: {}", index_bytes);
470 println!(" zero bytes: {}", zero_bytes);
471 println!(" total bytes: {}", total_bytes);
478 // These are methods for encoding various things. They are meant to be used with
479 // IndexBuilder::record() and EncodeContext::tracked(). They actually
480 // would not have to be methods of IsolatedEncoder (free standing functions
481 // taking IsolatedEncoder as first argument would be just fine) but by making
482 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
483 // clause again and again.
484 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
485 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
486 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
488 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
491 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
493 let ty = tcx.type_of(def_id);
494 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
498 /// Encode data for the given variant of the given ADT. The
499 /// index of the variant is untracked: this is ok because we
500 /// will have to lookup the adt-def by its id, and that gives us
501 /// the right to access any information in the adt-def (including,
502 /// e.g., the length of the various vectors).
503 fn encode_enum_variant_info(&mut self,
504 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
507 let def = tcx.adt_def(enum_did);
508 let variant = &def.variants[index];
509 let def_id = variant.did;
510 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
512 let data = VariantData {
513 ctor_kind: variant.ctor_kind,
514 discr: variant.discr,
516 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
517 Some(self.lazy(&tcx.fn_sig(def_id)))
523 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
524 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
527 kind: EntryKind::Variant(self.lazy(&data)),
528 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
529 span: self.lazy(&tcx.def_span(def_id)),
530 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
531 children: self.lazy_seq(variant.fields.iter().map(|f| {
532 assert!(f.did.is_local());
535 stability: self.encode_stability(def_id),
536 deprecation: self.encode_deprecation(def_id),
538 ty: Some(self.encode_item_type(def_id)),
539 inherent_impls: LazySeq::empty(),
540 variances: if variant.ctor_kind == CtorKind::Fn {
541 self.encode_variances_of(def_id)
545 generics: Some(self.encode_generics(def_id)),
546 predicates: Some(self.encode_predicates(def_id)),
549 mir: self.encode_optimized_mir(def_id),
553 fn encode_info_for_mod(&mut self,
554 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
559 let def_id = tcx.hir.local_def_id(id);
560 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
563 reexports: match tcx.module_exports(def_id) {
564 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
565 _ => LazySeq::empty(),
570 kind: EntryKind::Mod(self.lazy(&data)),
571 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
572 span: self.lazy(&tcx.def_span(def_id)),
573 attributes: self.encode_attributes(attrs),
574 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
575 tcx.hir.local_def_id(item_id.id).index
577 stability: self.encode_stability(def_id),
578 deprecation: self.encode_deprecation(def_id),
581 inherent_impls: LazySeq::empty(),
582 variances: LazySeq::empty(),
591 /// Encode data for the given field of the given variant of the
592 /// given ADT. The indices of the variant/field are untracked:
593 /// this is ok because we will have to lookup the adt-def by its
594 /// id, and that gives us the right to access any information in
595 /// the adt-def (including, e.g., the length of the various
597 fn encode_field(&mut self,
598 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
603 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
604 let field = &variant.fields[field_index];
606 let def_id = field.did;
607 debug!("IsolatedEncoder::encode_field({:?})", def_id);
609 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
610 let variant_data = tcx.hir.expect_variant_data(variant_id);
613 kind: EntryKind::Field,
614 visibility: self.lazy(&field.vis),
615 span: self.lazy(&tcx.def_span(def_id)),
616 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
617 children: LazySeq::empty(),
618 stability: self.encode_stability(def_id),
619 deprecation: self.encode_deprecation(def_id),
621 ty: Some(self.encode_item_type(def_id)),
622 inherent_impls: LazySeq::empty(),
623 variances: LazySeq::empty(),
624 generics: Some(self.encode_generics(def_id)),
625 predicates: Some(self.encode_predicates(def_id)),
632 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
633 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
635 let adt_def = tcx.adt_def(adt_def_id);
636 let variant = adt_def.non_enum_variant();
638 let data = VariantData {
639 ctor_kind: variant.ctor_kind,
640 discr: variant.discr,
641 struct_ctor: Some(def_id.index),
642 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
643 Some(self.lazy(&tcx.fn_sig(def_id)))
649 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
650 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
651 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
652 for field in &variant.fields {
653 if ctor_vis.is_at_least(field.vis, tcx) {
654 ctor_vis = field.vis;
658 // If the structure is marked as non_exhaustive then lower the visibility
659 // to within the crate.
660 if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
661 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
664 let repr_options = get_repr_options(&tcx, adt_def_id);
667 kind: EntryKind::Struct(self.lazy(&data), repr_options),
668 visibility: self.lazy(&ctor_vis),
669 span: self.lazy(&tcx.def_span(def_id)),
670 attributes: LazySeq::empty(),
671 children: LazySeq::empty(),
672 stability: self.encode_stability(def_id),
673 deprecation: self.encode_deprecation(def_id),
675 ty: Some(self.encode_item_type(def_id)),
676 inherent_impls: LazySeq::empty(),
677 variances: if variant.ctor_kind == CtorKind::Fn {
678 self.encode_variances_of(def_id)
682 generics: Some(self.encode_generics(def_id)),
683 predicates: Some(self.encode_predicates(def_id)),
686 mir: self.encode_optimized_mir(def_id),
690 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
691 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
693 self.lazy(tcx.generics_of(def_id))
696 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
697 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
699 self.lazy(&tcx.predicates_of(def_id))
702 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
703 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
706 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
707 let ast_item = tcx.hir.expect_trait_item(node_id);
708 let trait_item = tcx.associated_item(def_id);
710 let container = match trait_item.defaultness {
711 hir::Defaultness::Default { has_value: true } =>
712 AssociatedContainer::TraitWithDefault,
713 hir::Defaultness::Default { has_value: false } =>
714 AssociatedContainer::TraitRequired,
715 hir::Defaultness::Final =>
716 span_bug!(ast_item.span, "traits cannot have final items"),
719 let kind = match trait_item.kind {
720 ty::AssociatedKind::Const => {
721 EntryKind::AssociatedConst(container, 0)
723 ty::AssociatedKind::Method => {
724 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
725 let arg_names = match *m {
726 hir::TraitMethod::Required(ref names) => {
727 self.encode_fn_arg_names(names)
729 hir::TraitMethod::Provided(body) => {
730 self.encode_fn_arg_names_for_body(body)
734 constness: hir::Constness::NotConst,
736 sig: self.lazy(&tcx.fn_sig(def_id)),
741 EntryKind::Method(self.lazy(&MethodData {
744 has_self: trait_item.method_has_self_argument,
747 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
752 visibility: self.lazy(&trait_item.vis),
753 span: self.lazy(&ast_item.span),
754 attributes: self.encode_attributes(&ast_item.attrs),
755 children: LazySeq::empty(),
756 stability: self.encode_stability(def_id),
757 deprecation: self.encode_deprecation(def_id),
759 ty: match trait_item.kind {
760 ty::AssociatedKind::Const |
761 ty::AssociatedKind::Method => {
762 Some(self.encode_item_type(def_id))
764 ty::AssociatedKind::Type => {
765 if trait_item.defaultness.has_value() {
766 Some(self.encode_item_type(def_id))
772 inherent_impls: LazySeq::empty(),
773 variances: if trait_item.kind == ty::AssociatedKind::Method {
774 self.encode_variances_of(def_id)
778 generics: Some(self.encode_generics(def_id)),
779 predicates: Some(self.encode_predicates(def_id)),
781 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
782 Some(self.encode_body(body))
786 mir: self.encode_optimized_mir(def_id),
790 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
791 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
794 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
795 let ast_item = self.tcx.hir.expect_impl_item(node_id);
796 let impl_item = self.tcx.associated_item(def_id);
798 let container = match impl_item.defaultness {
799 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
800 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
801 hir::Defaultness::Default { has_value: false } =>
802 span_bug!(ast_item.span, "impl items always have values (currently)"),
805 let kind = match impl_item.kind {
806 ty::AssociatedKind::Const => {
807 EntryKind::AssociatedConst(container,
808 self.tcx.at(ast_item.span).mir_const_qualif(def_id).0)
810 ty::AssociatedKind::Method => {
811 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
813 constness: sig.constness,
814 arg_names: self.encode_fn_arg_names_for_body(body),
815 sig: self.lazy(&tcx.fn_sig(def_id)),
820 EntryKind::Method(self.lazy(&MethodData {
823 has_self: impl_item.method_has_self_argument,
826 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
829 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
831 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
832 let generics = self.tcx.generics_of(def_id);
833 let types = generics.parent_types as usize + generics.types.len();
834 let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
835 let is_const_fn = sig.constness == hir::Constness::Const;
836 let ast = if is_const_fn { Some(body) } else { None };
837 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
838 (ast, needs_inline || is_const_fn || always_encode_mir)
845 visibility: self.lazy(&impl_item.vis),
846 span: self.lazy(&ast_item.span),
847 attributes: self.encode_attributes(&ast_item.attrs),
848 children: LazySeq::empty(),
849 stability: self.encode_stability(def_id),
850 deprecation: self.encode_deprecation(def_id),
852 ty: Some(self.encode_item_type(def_id)),
853 inherent_impls: LazySeq::empty(),
854 variances: if impl_item.kind == ty::AssociatedKind::Method {
855 self.encode_variances_of(def_id)
859 generics: Some(self.encode_generics(def_id)),
860 predicates: Some(self.encode_predicates(def_id)),
862 ast: ast.map(|body| self.encode_body(body)),
863 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
867 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
868 -> LazySeq<ast::Name> {
869 self.tcx.dep_graph.with_ignore(|| {
870 let body = self.tcx.hir.body(body_id);
871 self.lazy_seq(body.arguments.iter().map(|arg| {
873 PatKind::Binding(_, _, name, _) => name.node,
874 _ => Symbol::intern("")
880 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
881 -> LazySeq<ast::Name> {
882 self.lazy_seq(names.iter().map(|name| name.node))
885 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
886 debug!("EntryBuilder::encode_mir({:?})", def_id);
887 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
888 let mir = self.tcx.optimized_mir(def_id);
889 Some(self.lazy(&mir))
895 // Encodes the inherent implementations of a structure, enumeration, or trait.
896 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
897 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
898 let implementations = self.tcx.inherent_impls(def_id);
899 if implementations.is_empty() {
902 self.lazy_seq(implementations.iter().map(|&def_id| {
903 assert!(def_id.is_local());
909 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
910 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
911 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
914 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
915 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
916 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
919 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
922 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
924 let kind = match item.node {
925 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
926 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
927 hir::ItemConst(..) => {
928 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id).0)
930 hir::ItemFn(_, _, constness, .., body) => {
933 arg_names: self.encode_fn_arg_names_for_body(body),
934 sig: self.lazy(&tcx.fn_sig(def_id)),
937 EntryKind::Fn(self.lazy(&data))
939 hir::ItemMod(ref m) => {
940 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
942 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
943 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
944 hir::ItemTy(..) => EntryKind::Type,
945 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
946 hir::ItemStruct(ref struct_def, _) => {
947 let variant = tcx.adt_def(def_id).non_enum_variant();
949 // Encode def_ids for each field and method
950 // for methods, write all the stuff get_trait_method
952 let struct_ctor = if !struct_def.is_struct() {
953 Some(tcx.hir.local_def_id(struct_def.id()).index)
958 let repr_options = get_repr_options(&tcx, def_id);
960 EntryKind::Struct(self.lazy(&VariantData {
961 ctor_kind: variant.ctor_kind,
962 discr: variant.discr,
967 hir::ItemUnion(..) => {
968 let variant = tcx.adt_def(def_id).non_enum_variant();
969 let repr_options = get_repr_options(&tcx, def_id);
971 EntryKind::Union(self.lazy(&VariantData {
972 ctor_kind: variant.ctor_kind,
973 discr: variant.discr,
978 hir::ItemImpl(_, polarity, defaultness, ..) => {
979 let trait_ref = tcx.impl_trait_ref(def_id);
980 let parent = if let Some(trait_ref) = trait_ref {
981 let trait_def = tcx.trait_def(trait_ref.def_id);
982 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
984 specialization_graph::Node::Impl(parent) => Some(parent),
992 // if this is an impl of `CoerceUnsized`, create its
993 // "unsized info", else just store None
994 let coerce_unsized_info =
995 trait_ref.and_then(|t| {
996 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
997 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1003 let data = ImplData {
1006 parent_impl: parent,
1007 coerce_unsized_info,
1008 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1011 EntryKind::Impl(self.lazy(&data))
1013 hir::ItemTrait(..) => {
1014 let trait_def = tcx.trait_def(def_id);
1015 let data = TraitData {
1016 unsafety: trait_def.unsafety,
1017 paren_sugar: trait_def.paren_sugar,
1018 has_auto_impl: tcx.trait_is_auto(def_id),
1019 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1022 EntryKind::Trait(self.lazy(&data))
1024 hir::ItemExternCrate(_) |
1025 hir::ItemTraitAlias(..) |
1026 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1031 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1032 span: self.lazy(&item.span),
1033 attributes: self.encode_attributes(&item.attrs),
1034 children: match item.node {
1035 hir::ItemForeignMod(ref fm) => {
1036 self.lazy_seq(fm.items
1038 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1040 hir::ItemEnum(..) => {
1041 let def = self.tcx.adt_def(def_id);
1042 self.lazy_seq(def.variants.iter().map(|v| {
1043 assert!(v.did.is_local());
1047 hir::ItemStruct(..) |
1048 hir::ItemUnion(..) => {
1049 let def = self.tcx.adt_def(def_id);
1050 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1051 assert!(f.did.is_local());
1056 hir::ItemTrait(..) => {
1057 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1058 assert!(def_id.is_local());
1062 _ => LazySeq::empty(),
1064 stability: self.encode_stability(def_id),
1065 deprecation: self.encode_deprecation(def_id),
1067 ty: match item.node {
1068 hir::ItemStatic(..) |
1069 hir::ItemConst(..) |
1073 hir::ItemStruct(..) |
1074 hir::ItemUnion(..) |
1075 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1078 inherent_impls: self.encode_inherent_implementations(def_id),
1079 variances: match item.node {
1081 hir::ItemStruct(..) |
1082 hir::ItemUnion(..) |
1083 hir::ItemFn(..) => self.encode_variances_of(def_id),
1084 _ => LazySeq::empty(),
1086 generics: match item.node {
1087 hir::ItemStatic(..) |
1088 hir::ItemConst(..) |
1092 hir::ItemStruct(..) |
1093 hir::ItemUnion(..) |
1095 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1098 predicates: match item.node {
1099 hir::ItemStatic(..) |
1100 hir::ItemConst(..) |
1104 hir::ItemStruct(..) |
1105 hir::ItemUnion(..) |
1107 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1111 ast: match item.node {
1112 hir::ItemConst(_, body) |
1113 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
1114 Some(self.encode_body(body))
1118 mir: match item.node {
1119 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
1120 self.encode_optimized_mir(def_id)
1122 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1123 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1124 let has_tps = generics.ty_params().next().is_some();
1125 let needs_inline = has_tps || attr::requests_inline(&item.attrs);
1126 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1127 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
1128 self.encode_optimized_mir(def_id)
1138 /// Serialize the text of exported macros
1139 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1140 use syntax::print::pprust;
1141 let def_id = self.tcx.hir.local_def_id(macro_def.id);
1143 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1144 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1145 legacy: macro_def.legacy,
1147 visibility: self.lazy(&ty::Visibility::Public),
1148 span: self.lazy(¯o_def.span),
1149 attributes: self.encode_attributes(¯o_def.attrs),
1150 stability: self.encode_stability(def_id),
1151 deprecation: self.encode_deprecation(def_id),
1153 children: LazySeq::empty(),
1155 inherent_impls: LazySeq::empty(),
1156 variances: LazySeq::empty(),
1164 fn encode_info_for_ty_param(&mut self,
1165 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1167 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1170 kind: EntryKind::Type,
1171 visibility: self.lazy(&ty::Visibility::Public),
1172 span: self.lazy(&tcx.def_span(def_id)),
1173 attributes: LazySeq::empty(),
1174 children: LazySeq::empty(),
1178 ty: if has_default {
1179 Some(self.encode_item_type(def_id))
1183 inherent_impls: LazySeq::empty(),
1184 variances: LazySeq::empty(),
1193 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1194 debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
1197 kind: EntryKind::Type,
1198 visibility: self.lazy(&ty::Visibility::Public),
1199 span: self.lazy(&tcx.def_span(def_id)),
1200 attributes: LazySeq::empty(),
1201 children: LazySeq::empty(),
1205 ty: Some(self.encode_item_type(def_id)),
1206 inherent_impls: LazySeq::empty(),
1207 variances: LazySeq::empty(),
1208 generics: Some(self.encode_generics(def_id)),
1209 predicates: Some(self.encode_predicates(def_id)),
1216 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1217 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1220 let tables = self.tcx.typeck_tables_of(def_id);
1221 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1222 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1223 let kind = match tables.node_id_to_type(hir_id).sty {
1224 ty::TyGenerator(def_id, ..) => {
1225 let layout = self.tcx.generator_layout(def_id);
1226 let data = GeneratorData {
1227 layout: layout.clone(),
1229 EntryKind::Generator(self.lazy(&data))
1232 ty::TyClosure(def_id, substs) => {
1233 let sig = substs.closure_sig(def_id, self.tcx);
1234 let data = ClosureData { sig: self.lazy(&sig) };
1235 EntryKind::Closure(self.lazy(&data))
1238 _ => bug!("closure that is neither generator nor closure")
1243 visibility: self.lazy(&ty::Visibility::Public),
1244 span: self.lazy(&tcx.def_span(def_id)),
1245 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1246 children: LazySeq::empty(),
1250 ty: Some(self.encode_item_type(def_id)),
1251 inherent_impls: LazySeq::empty(),
1252 variances: LazySeq::empty(),
1253 generics: Some(self.encode_generics(def_id)),
1257 mir: self.encode_optimized_mir(def_id),
1261 fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1262 debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
1264 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1265 let body = tcx.hir.body_owned_by(id);
1268 kind: EntryKind::Const(tcx.mir_const_qualif(def_id).0),
1269 visibility: self.lazy(&ty::Visibility::Public),
1270 span: self.lazy(&tcx.def_span(def_id)),
1271 attributes: LazySeq::empty(),
1272 children: LazySeq::empty(),
1276 ty: Some(self.encode_item_type(def_id)),
1277 inherent_impls: LazySeq::empty(),
1278 variances: LazySeq::empty(),
1279 generics: Some(self.encode_generics(def_id)),
1280 predicates: Some(self.encode_predicates(def_id)),
1282 ast: Some(self.encode_body(body)),
1283 mir: self.encode_optimized_mir(def_id),
1287 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1288 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1289 // we rely on the HashStable specialization for [Attribute]
1290 // to properly filter things out.
1291 self.lazy_seq_from_slice(attrs)
1294 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1295 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1296 self.lazy_seq(used_libraries.iter().cloned())
1299 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1300 let crates = self.tcx.crates();
1302 let mut deps = crates
1305 let dep = CrateDep {
1306 name: self.tcx.original_crate_name(cnum),
1307 hash: self.tcx.crate_hash(cnum),
1308 kind: self.tcx.dep_kind(cnum),
1312 .collect::<Vec<_>>();
1314 deps.sort_by_key(|&(cnum, _)| cnum);
1317 // Sanity-check the crate numbers
1318 let mut expected_cnum = 1;
1319 for &(n, _) in &deps {
1320 assert_eq!(n, CrateNum::new(expected_cnum));
1325 // We're just going to write a list of crate 'name-hash-version's, with
1326 // the assumption that they are numbered 1 to n.
1327 // FIXME (#2166): This is not nearly enough to support correct versioning
1328 // but is enough to get transitive crate dependencies working.
1329 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1332 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1334 let lang_items = tcx.lang_items();
1335 let lang_items = lang_items.items().iter();
1336 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1337 if let Some(def_id) = opt_def_id {
1338 if def_id.is_local() {
1339 return Some((def_id.index, i));
1346 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1348 self.lazy_seq_ref(&tcx.lang_items().missing)
1351 /// Encodes an index, mapping each trait to its (local) implementations.
1352 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1353 debug!("IsolatedEncoder::encode_impls()");
1355 let mut visitor = ImplVisitor {
1359 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1361 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1363 // Bring everything into deterministic order for hashing
1364 all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1365 tcx.def_path_hash(trait_def_id)
1368 let all_impls: Vec<_> = all_impls
1370 .map(|(trait_def_id, mut impls)| {
1371 // Bring everything into deterministic order for hashing
1372 impls.sort_unstable_by_key(|&def_index| {
1373 tcx.hir.definitions().def_path_hash(def_index)
1377 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1378 impls: self.lazy_seq_from_slice(&impls[..]),
1383 self.lazy_seq_from_slice(&all_impls[..])
1386 // Encodes all symbols exported from this crate into the metadata.
1388 // This pass is seeded off the reachability list calculated in the
1389 // middle::reachable module but filters out items that either don't have a
1390 // symbol associated with them (they weren't translated) or if they're an FFI
1391 // definition (as that's not defined in this crate).
1392 fn encode_exported_symbols(&mut self,
1393 exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1394 -> LazySeq<(ExportedSymbol, SymbolExportLevel)> {
1395 self.lazy_seq(exported_symbols.iter().cloned())
1398 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1399 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1401 self.lazy_seq(arr.iter().map(|slot| {
1403 Linkage::NotLinked |
1404 Linkage::IncludedFromDylib => None,
1406 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1407 Linkage::Static => Some(LinkagePreference::RequireStatic),
1411 None => LazySeq::empty(),
1415 fn encode_info_for_foreign_item(&mut self,
1416 (def_id, nitem): (DefId, &hir::ForeignItem))
1420 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1422 let kind = match nitem.node {
1423 hir::ForeignItemFn(_, ref names, _) => {
1425 constness: hir::Constness::NotConst,
1426 arg_names: self.encode_fn_arg_names(names),
1427 sig: self.lazy(&tcx.fn_sig(def_id)),
1429 EntryKind::ForeignFn(self.lazy(&data))
1431 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1432 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1433 hir::ForeignItemType => EntryKind::ForeignType,
1438 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1439 span: self.lazy(&nitem.span),
1440 attributes: self.encode_attributes(&nitem.attrs),
1441 children: LazySeq::empty(),
1442 stability: self.encode_stability(def_id),
1443 deprecation: self.encode_deprecation(def_id),
1445 ty: Some(self.encode_item_type(def_id)),
1446 inherent_impls: LazySeq::empty(),
1447 variances: match nitem.node {
1448 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1449 _ => LazySeq::empty(),
1451 generics: Some(self.encode_generics(def_id)),
1452 predicates: Some(self.encode_predicates(def_id)),
1460 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1461 index: IndexBuilder<'a, 'b, 'tcx>,
1464 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1465 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1466 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1468 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1469 intravisit::walk_expr(self, ex);
1470 self.index.encode_info_for_expr(ex);
1472 fn visit_item(&mut self, item: &'tcx hir::Item) {
1473 intravisit::walk_item(self, item);
1474 let def_id = self.index.tcx.hir.local_def_id(item.id);
1476 hir::ItemExternCrate(_) |
1477 hir::ItemUse(..) => (), // ignore these
1478 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1480 self.index.encode_addl_info_for_item(item);
1482 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1483 intravisit::walk_foreign_item(self, ni);
1484 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1485 self.index.record(def_id,
1486 IsolatedEncoder::encode_info_for_foreign_item,
1489 fn visit_variant(&mut self,
1490 v: &'tcx hir::Variant,
1491 g: &'tcx hir::Generics,
1493 intravisit::walk_variant(self, v, g, id);
1495 if let Some(discr) = v.node.disr_expr {
1496 let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1497 self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1500 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1501 intravisit::walk_generics(self, generics);
1502 self.index.encode_info_for_generics(generics);
1504 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1505 intravisit::walk_ty(self, ty);
1506 self.index.encode_info_for_ty(ty);
1508 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1509 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1510 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1514 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1515 fn encode_fields(&mut self, adt_def_id: DefId) {
1516 let def = self.tcx.adt_def(adt_def_id);
1517 for (variant_index, variant) in def.variants.iter().enumerate() {
1518 for (field_index, field) in variant.fields.iter().enumerate() {
1519 self.record(field.did,
1520 IsolatedEncoder::encode_field,
1521 (adt_def_id, Untracked((variant_index, field_index))));
1526 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1527 for ty_param in generics.ty_params() {
1528 let def_id = self.tcx.hir.local_def_id(ty_param.id);
1529 let has_default = Untracked(ty_param.default.is_some());
1530 self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
1534 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1536 hir::TyImplTraitExistential(..) => {
1537 let def_id = self.tcx.hir.local_def_id(ty.id);
1538 self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
1540 hir::TyArray(_, len) => {
1541 let def_id = self.tcx.hir.body_owner_def_id(len);
1542 self.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1548 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1550 hir::ExprClosure(..) => {
1551 let def_id = self.tcx.hir.local_def_id(expr.id);
1552 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1558 /// In some cases, along with the item itself, we also
1559 /// encode some sub-items. Usually we want some info from the item
1560 /// so it's easier to do that here then to wait until we would encounter
1561 /// normally in the visitor walk.
1562 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1563 let def_id = self.tcx.hir.local_def_id(item.id);
1565 hir::ItemStatic(..) |
1566 hir::ItemConst(..) |
1569 hir::ItemForeignMod(..) |
1570 hir::ItemGlobalAsm(..) |
1571 hir::ItemExternCrate(..) |
1574 hir::ItemTraitAlias(..) => {
1575 // no sub-item recording needed in these cases
1577 hir::ItemEnum(..) => {
1578 self.encode_fields(def_id);
1580 let def = self.tcx.adt_def(def_id);
1581 for (i, variant) in def.variants.iter().enumerate() {
1582 self.record(variant.did,
1583 IsolatedEncoder::encode_enum_variant_info,
1584 (def_id, Untracked(i)));
1587 hir::ItemStruct(ref struct_def, _) => {
1588 self.encode_fields(def_id);
1590 // If the struct has a constructor, encode it.
1591 if !struct_def.is_struct() {
1592 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1593 self.record(ctor_def_id,
1594 IsolatedEncoder::encode_struct_ctor,
1595 (def_id, ctor_def_id));
1598 hir::ItemUnion(..) => {
1599 self.encode_fields(def_id);
1601 hir::ItemImpl(..) => {
1602 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1603 self.record(trait_item_def_id,
1604 IsolatedEncoder::encode_info_for_impl_item,
1608 hir::ItemTrait(..) => {
1609 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1610 self.record(item_def_id,
1611 IsolatedEncoder::encode_info_for_trait_item,
1619 struct ImplVisitor<'a, 'tcx: 'a> {
1620 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1621 impls: FxHashMap<DefId, Vec<DefIndex>>,
1624 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1625 fn visit_item(&mut self, item: &hir::Item) {
1626 if let hir::ItemImpl(..) = item.node {
1627 let impl_id = self.tcx.hir.local_def_id(item.id);
1628 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1630 .entry(trait_ref.def_id)
1632 .push(impl_id.index);
1637 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1639 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1640 // handled in `visit_item` above
1644 // NOTE(eddyb) The following comment was preserved for posterity, even
1645 // though it's no longer relevant as EBML (which uses nested & tagged
1646 // "documents") was replaced with a scheme that can't go out of bounds.
1648 // And here we run into yet another obscure archive bug: in which metadata
1649 // loaded from archives may have trailing garbage bytes. Awhile back one of
1650 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1651 // and opt) by having ebml generate an out-of-bounds panic when looking at
1654 // Upon investigation it turned out that the metadata file inside of an rlib
1655 // (and ar archive) was being corrupted. Some compilations would generate a
1656 // metadata file which would end in a few extra bytes, while other
1657 // compilations would not have these extra bytes appended to the end. These
1658 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1659 // being interpreted causing the out-of-bounds.
1661 // The root cause of why these extra bytes were appearing was never
1662 // discovered, and in the meantime the solution we're employing is to insert
1663 // the length of the metadata to the start of the metadata. Later on this
1664 // will allow us to slice the metadata to the precise length that we just
1665 // generated regardless of trailing bytes that end up in it.
1667 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1668 link_meta: &LinkMeta)
1671 let mut cursor = Cursor::new(vec![]);
1672 cursor.write_all(METADATA_HEADER).unwrap();
1674 // Will be filled with the root position after encoding everything.
1675 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1678 let mut ecx = EncodeContext {
1679 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),