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 metadata_symbol_name};
25 use rustc::middle::lang_items;
27 use rustc::traits::specialization_graph;
28 use rustc::ty::{self, Ty, TyCtxt, ReprOptions, SymbolName};
29 use rustc::ty::codec::{self as ty_codec, TyEncoder};
31 use rustc::session::config::{self, CrateTypeProcMacro};
32 use rustc::util::nodemap::FxHashMap;
34 use rustc_data_structures::stable_hasher::StableHasher;
35 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
38 use std::io::prelude::*;
41 use rustc_data_structures::sync::Lrc;
43 use syntax::ast::{self, CRATE_NODE_ID};
44 use syntax::codemap::Spanned;
46 use syntax::symbol::Symbol;
47 use syntax_pos::{self, FileName, FileMap, Span, DUMMY_SP};
49 use rustc::hir::{self, PatKind};
50 use rustc::hir::itemlikevisit::ItemLikeVisitor;
51 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
52 use rustc::hir::intravisit;
54 pub struct EncodeContext<'a, 'tcx: 'a> {
55 opaque: opaque::Encoder<'a>,
56 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
57 link_meta: &'a LinkMeta,
59 lazy_state: LazyState,
60 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
61 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
63 // This is used to speed up Span encoding.
64 filemap_cache: Lrc<FileMap>,
67 macro_rules! encoder_methods {
68 ($($name:ident($ty:ty);)*) => {
69 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
70 self.opaque.$name(value)
75 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
76 type Error = <opaque::Encoder<'a> as Encoder>::Error;
78 fn emit_nil(&mut self) -> Result<(), Self::Error> {
105 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
106 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
107 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
111 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
112 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
113 self.emit_usize(seq.len)?;
117 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
121 impl<'a, 'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'a, 'tcx> {
123 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
124 self.emit_u32(cnum.as_u32())
128 impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
130 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
141 impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
143 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
144 self.emit_u32(def_index.as_raw_u32())
148 impl<'a, 'tcx> SpecializedEncoder<Span> for EncodeContext<'a, 'tcx> {
149 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
150 if *span == DUMMY_SP {
151 return TAG_INVALID_SPAN.encode(self)
154 let span = span.data();
156 // The Span infrastructure should make sure that this invariant holds:
157 debug_assert!(span.lo <= span.hi);
159 if !self.filemap_cache.contains(span.lo) {
160 let codemap = self.tcx.sess.codemap();
161 let filemap_index = codemap.lookup_filemap_idx(span.lo);
162 self.filemap_cache = codemap.files()[filemap_index].clone();
165 if !self.filemap_cache.contains(span.hi) {
166 // Unfortunately, macro expansion still sometimes generates Spans
167 // that malformed in this way.
168 return TAG_INVALID_SPAN.encode(self)
171 TAG_VALID_SPAN.encode(self)?;
172 span.lo.encode(self)?;
174 // Encode length which is usually less than span.hi and profits more
175 // from the variable-length integer encoding that we use.
176 let len = span.hi - span.lo;
179 // Don't encode the expansion context.
183 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
184 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
185 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
189 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
190 fn specialized_encode(&mut self,
191 predicates: &ty::GenericPredicates<'tcx>)
192 -> Result<(), Self::Error> {
193 ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
197 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
198 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
199 f.encode_opaque(&mut self.opaque)
203 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
204 for EncodeContext<'a, 'tcx> {
205 fn specialized_encode(&mut self,
206 _: &mir::ClearCrossCrate<T>)
207 -> Result<(), Self::Error> {
212 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
213 fn position(&self) -> usize {
214 self.opaque.position()
218 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
220 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
221 assert_eq!(self.lazy_state, LazyState::NoNode);
222 let pos = self.position();
223 self.lazy_state = LazyState::NodeStart(pos);
224 let r = f(self, pos);
225 self.lazy_state = LazyState::NoNode;
229 fn emit_lazy_distance(&mut self,
232 -> Result<(), <Self as Encoder>::Error> {
233 let min_end = position + min_size;
234 let distance = match self.lazy_state {
235 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
236 LazyState::NodeStart(start) => {
237 assert!(min_end <= start);
240 LazyState::Previous(last_min_end) => {
241 assert!(last_min_end <= position);
242 position - last_min_end
245 self.lazy_state = LazyState::Previous(min_end);
246 self.emit_usize(distance)
249 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
250 self.emit_node(|ecx, pos| {
251 value.encode(ecx).unwrap();
253 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
254 Lazy::with_position(pos)
258 pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
259 where I: IntoIterator<Item = T>,
262 self.emit_node(|ecx, pos| {
263 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
265 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
266 LazySeq::with_position_and_length(pos, len)
270 pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
271 where I: IntoIterator<Item = &'b T>,
274 self.emit_node(|ecx, pos| {
275 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
277 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
278 LazySeq::with_position_and_length(pos, len)
282 // Encodes something that corresponds to a single DepNode::GlobalMetaData
283 // and registers the Fingerprint in the `metadata_hashes` map.
284 pub fn tracked<'x, DATA, R>(&'x mut self,
285 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
288 op(&mut IsolatedEncoder::new(self), data)
291 fn encode_info_for_items(&mut self) -> Index {
292 let krate = self.tcx.hir.krate();
293 let mut index = IndexBuilder::new(self);
294 index.record(DefId::local(CRATE_DEF_INDEX),
295 IsolatedEncoder::encode_info_for_mod,
296 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
297 let mut visitor = EncodeVisitor { index: index };
298 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
299 for macro_def in &krate.exported_macros {
300 visitor.visit_macro_def(macro_def);
302 visitor.index.into_items()
305 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
306 let definitions = self.tcx.hir.definitions();
307 self.lazy(definitions.def_path_table())
310 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
311 let codemap = self.tcx.sess.codemap();
312 let all_filemaps = codemap.files();
314 let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
316 let adapted = all_filemaps.iter()
318 // No need to re-export imported filemaps, as any downstream
319 // crate will import them from their original source.
320 !filemap.is_imported()
323 // When exporting FileMaps, we expand all paths to absolute
324 // paths because any relative paths are potentially relative to
325 // a wrong directory.
326 // However, if a path has been modified via
327 // `--remap-path-prefix` we assume the user has already set
328 // things up the way they want and don't touch the path values
331 FileName::Real(ref name) => {
332 if filemap.name_was_remapped ||
333 (name.is_relative() && working_dir_was_remapped) {
334 // This path of this FileMap has been modified by
335 // path-remapping, so we use it verbatim (and avoid cloning
336 // the whole map in the process).
339 let mut adapted = (**filemap).clone();
340 adapted.name = Path::new(&working_dir).join(name).into();
341 adapted.name_hash = {
342 let mut hasher: StableHasher<u128> = StableHasher::new();
343 adapted.name.hash(&mut hasher);
349 // expanded code, not from a file
350 _ => filemap.clone(),
353 .collect::<Vec<_>>();
355 self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
358 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
359 let mut i = self.position();
361 let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
362 let dylib_dependency_formats = self.tracked(
363 IsolatedEncoder::encode_dylib_dependency_formats,
365 let dep_bytes = self.position() - i;
367 // Encode the language items.
369 let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
370 let lang_items_missing = self.tracked(
371 IsolatedEncoder::encode_lang_items_missing,
373 let lang_item_bytes = self.position() - i;
375 // Encode the native libraries used
377 let native_libraries = self.tracked(
378 IsolatedEncoder::encode_native_libraries,
380 let native_lib_bytes = self.position() - i;
384 let codemap = self.encode_codemap();
385 let codemap_bytes = self.position() - i;
387 // Encode DefPathTable
389 let def_path_table = self.encode_def_path_table();
390 let def_path_table_bytes = self.position() - i;
392 // Encode the def IDs of impls, for coherence checking.
394 let impls = self.tracked(IsolatedEncoder::encode_impls, ());
395 let impl_bytes = self.position() - i;
397 // Encode exported symbols info.
399 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
400 let exported_symbols = self.tracked(
401 IsolatedEncoder::encode_exported_symbols,
403 let exported_symbols_bytes = self.position() - i;
405 // Encode and index the items.
407 let items = self.encode_info_for_items();
408 let item_bytes = self.position() - i;
411 let index = items.write_index(&mut self.opaque.cursor);
412 let index_bytes = self.position() - i;
415 let link_meta = self.link_meta;
416 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
417 let has_default_lib_allocator =
418 attr::contains_name(tcx.hir.krate_attrs(), "default_lib_allocator");
419 let has_global_allocator = tcx.sess.has_global_allocator.get();
420 let root = self.lazy(&CrateRoot {
421 name: tcx.crate_name(LOCAL_CRATE),
422 triple: tcx.sess.opts.target_triple.clone(),
423 hash: link_meta.crate_hash,
424 disambiguator: tcx.sess.local_crate_disambiguator(),
425 panic_strategy: tcx.sess.panic_strategy(),
426 has_global_allocator: has_global_allocator,
427 has_default_lib_allocator: has_default_lib_allocator,
428 plugin_registrar_fn: tcx.sess
431 .map(|id| tcx.hir.local_def_id(id).index),
432 macro_derive_registrar: if is_proc_macro {
433 let id = tcx.sess.derive_registrar_fn.get().unwrap();
434 Some(tcx.hir.local_def_id(id).index)
440 dylib_dependency_formats,
451 let total_bytes = self.position();
453 if self.tcx.sess.meta_stats() {
454 let mut zero_bytes = 0;
455 for e in self.opaque.cursor.get_ref() {
461 println!("metadata stats:");
462 println!(" dep bytes: {}", dep_bytes);
463 println!(" lang item bytes: {}", lang_item_bytes);
464 println!(" native bytes: {}", native_lib_bytes);
465 println!(" codemap bytes: {}", codemap_bytes);
466 println!(" impl bytes: {}", impl_bytes);
467 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
468 println!(" def-path table bytes: {}", def_path_table_bytes);
469 println!(" item bytes: {}", item_bytes);
470 println!(" index bytes: {}", index_bytes);
471 println!(" zero bytes: {}", zero_bytes);
472 println!(" total bytes: {}", total_bytes);
479 // These are methods for encoding various things. They are meant to be used with
480 // IndexBuilder::record() and EncodeContext::tracked(). They actually
481 // would not have to be methods of IsolatedEncoder (free standing functions
482 // taking IsolatedEncoder as first argument would be just fine) but by making
483 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
484 // clause again and again.
485 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
486 fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
487 debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
489 self.lazy_seq_from_slice(&tcx.variances_of(def_id))
492 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
494 let ty = tcx.type_of(def_id);
495 debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
499 /// Encode data for the given variant of the given ADT. The
500 /// index of the variant is untracked: this is ok because we
501 /// will have to lookup the adt-def by its id, and that gives us
502 /// the right to access any information in the adt-def (including,
503 /// e.g., the length of the various vectors).
504 fn encode_enum_variant_info(&mut self,
505 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
508 let def = tcx.adt_def(enum_did);
509 let variant = &def.variants[index];
510 let def_id = variant.did;
511 debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
513 let data = VariantData {
514 ctor_kind: variant.ctor_kind,
515 discr: variant.discr,
517 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
518 Some(self.lazy(&tcx.fn_sig(def_id)))
524 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
525 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
528 kind: EntryKind::Variant(self.lazy(&data)),
529 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
530 span: self.lazy(&tcx.def_span(def_id)),
531 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
532 children: self.lazy_seq(variant.fields.iter().map(|f| {
533 assert!(f.did.is_local());
536 stability: self.encode_stability(def_id),
537 deprecation: self.encode_deprecation(def_id),
539 ty: Some(self.encode_item_type(def_id)),
540 inherent_impls: LazySeq::empty(),
541 variances: if variant.ctor_kind == CtorKind::Fn {
542 self.encode_variances_of(def_id)
546 generics: Some(self.encode_generics(def_id)),
547 predicates: Some(self.encode_predicates(def_id)),
550 mir: self.encode_optimized_mir(def_id),
554 fn encode_info_for_mod(&mut self,
555 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
560 let def_id = tcx.hir.local_def_id(id);
561 debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
564 reexports: match tcx.module_exports(def_id) {
565 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
566 _ => LazySeq::empty(),
571 kind: EntryKind::Mod(self.lazy(&data)),
572 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
573 span: self.lazy(&tcx.def_span(def_id)),
574 attributes: self.encode_attributes(attrs),
575 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
576 tcx.hir.local_def_id(item_id.id).index
578 stability: self.encode_stability(def_id),
579 deprecation: self.encode_deprecation(def_id),
582 inherent_impls: LazySeq::empty(),
583 variances: LazySeq::empty(),
592 /// Encode data for the given field of the given variant of the
593 /// given ADT. The indices of the variant/field are untracked:
594 /// this is ok because we will have to lookup the adt-def by its
595 /// id, and that gives us the right to access any information in
596 /// the adt-def (including, e.g., the length of the various
598 fn encode_field(&mut self,
599 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
604 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
605 let field = &variant.fields[field_index];
607 let def_id = field.did;
608 debug!("IsolatedEncoder::encode_field({:?})", def_id);
610 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
611 let variant_data = tcx.hir.expect_variant_data(variant_id);
614 kind: EntryKind::Field,
615 visibility: self.lazy(&field.vis),
616 span: self.lazy(&tcx.def_span(def_id)),
617 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
618 children: LazySeq::empty(),
619 stability: self.encode_stability(def_id),
620 deprecation: self.encode_deprecation(def_id),
622 ty: Some(self.encode_item_type(def_id)),
623 inherent_impls: LazySeq::empty(),
624 variances: LazySeq::empty(),
625 generics: Some(self.encode_generics(def_id)),
626 predicates: Some(self.encode_predicates(def_id)),
633 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
634 debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
636 let adt_def = tcx.adt_def(adt_def_id);
637 let variant = adt_def.non_enum_variant();
639 let data = VariantData {
640 ctor_kind: variant.ctor_kind,
641 discr: variant.discr,
642 struct_ctor: Some(def_id.index),
643 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
644 Some(self.lazy(&tcx.fn_sig(def_id)))
650 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
651 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
652 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
653 for field in &variant.fields {
654 if ctor_vis.is_at_least(field.vis, tcx) {
655 ctor_vis = field.vis;
659 // If the structure is marked as non_exhaustive then lower the visibility
660 // to within the crate.
661 if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
662 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
665 let repr_options = get_repr_options(&tcx, adt_def_id);
668 kind: EntryKind::Struct(self.lazy(&data), repr_options),
669 visibility: self.lazy(&ctor_vis),
670 span: self.lazy(&tcx.def_span(def_id)),
671 attributes: LazySeq::empty(),
672 children: LazySeq::empty(),
673 stability: self.encode_stability(def_id),
674 deprecation: self.encode_deprecation(def_id),
676 ty: Some(self.encode_item_type(def_id)),
677 inherent_impls: LazySeq::empty(),
678 variances: if variant.ctor_kind == CtorKind::Fn {
679 self.encode_variances_of(def_id)
683 generics: Some(self.encode_generics(def_id)),
684 predicates: Some(self.encode_predicates(def_id)),
687 mir: self.encode_optimized_mir(def_id),
691 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
692 debug!("IsolatedEncoder::encode_generics({:?})", def_id);
694 self.lazy(tcx.generics_of(def_id))
697 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
698 debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
700 self.lazy(&tcx.predicates_of(def_id))
703 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
704 debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
707 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
708 let ast_item = tcx.hir.expect_trait_item(node_id);
709 let trait_item = tcx.associated_item(def_id);
711 let container = match trait_item.defaultness {
712 hir::Defaultness::Default { has_value: true } =>
713 AssociatedContainer::TraitWithDefault,
714 hir::Defaultness::Default { has_value: false } =>
715 AssociatedContainer::TraitRequired,
716 hir::Defaultness::Final =>
717 span_bug!(ast_item.span, "traits cannot have final items"),
720 let kind = match trait_item.kind {
721 ty::AssociatedKind::Const => {
722 EntryKind::AssociatedConst(container, 0)
724 ty::AssociatedKind::Method => {
725 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
726 let arg_names = match *m {
727 hir::TraitMethod::Required(ref names) => {
728 self.encode_fn_arg_names(names)
730 hir::TraitMethod::Provided(body) => {
731 self.encode_fn_arg_names_for_body(body)
735 constness: hir::Constness::NotConst,
737 sig: self.lazy(&tcx.fn_sig(def_id)),
742 EntryKind::Method(self.lazy(&MethodData {
745 has_self: trait_item.method_has_self_argument,
748 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
753 visibility: self.lazy(&trait_item.vis),
754 span: self.lazy(&ast_item.span),
755 attributes: self.encode_attributes(&ast_item.attrs),
756 children: LazySeq::empty(),
757 stability: self.encode_stability(def_id),
758 deprecation: self.encode_deprecation(def_id),
760 ty: match trait_item.kind {
761 ty::AssociatedKind::Const |
762 ty::AssociatedKind::Method => {
763 Some(self.encode_item_type(def_id))
765 ty::AssociatedKind::Type => {
766 if trait_item.defaultness.has_value() {
767 Some(self.encode_item_type(def_id))
773 inherent_impls: LazySeq::empty(),
774 variances: if trait_item.kind == ty::AssociatedKind::Method {
775 self.encode_variances_of(def_id)
779 generics: Some(self.encode_generics(def_id)),
780 predicates: Some(self.encode_predicates(def_id)),
782 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
783 Some(self.encode_body(body))
787 mir: self.encode_optimized_mir(def_id),
791 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
792 debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
795 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
796 let ast_item = self.tcx.hir.expect_impl_item(node_id);
797 let impl_item = self.tcx.associated_item(def_id);
799 let container = match impl_item.defaultness {
800 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
801 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
802 hir::Defaultness::Default { has_value: false } =>
803 span_bug!(ast_item.span, "impl items always have values (currently)"),
806 let kind = match impl_item.kind {
807 ty::AssociatedKind::Const => {
808 EntryKind::AssociatedConst(container,
809 self.tcx.at(ast_item.span).mir_const_qualif(def_id).0)
811 ty::AssociatedKind::Method => {
812 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
814 constness: sig.constness,
815 arg_names: self.encode_fn_arg_names_for_body(body),
816 sig: self.lazy(&tcx.fn_sig(def_id)),
821 EntryKind::Method(self.lazy(&MethodData {
824 has_self: impl_item.method_has_self_argument,
827 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
830 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
832 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
833 let generics = self.tcx.generics_of(def_id);
834 let types = generics.parent_types as usize + generics.types.len();
835 let needs_inline = types > 0 || tcx.trans_fn_attrs(def_id).requests_inline();
836 let is_const_fn = sig.constness == hir::Constness::Const;
837 let ast = if is_const_fn { Some(body) } else { None };
838 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
839 (ast, needs_inline || is_const_fn || always_encode_mir)
846 visibility: self.lazy(&impl_item.vis),
847 span: self.lazy(&ast_item.span),
848 attributes: self.encode_attributes(&ast_item.attrs),
849 children: LazySeq::empty(),
850 stability: self.encode_stability(def_id),
851 deprecation: self.encode_deprecation(def_id),
853 ty: Some(self.encode_item_type(def_id)),
854 inherent_impls: LazySeq::empty(),
855 variances: if impl_item.kind == ty::AssociatedKind::Method {
856 self.encode_variances_of(def_id)
860 generics: Some(self.encode_generics(def_id)),
861 predicates: Some(self.encode_predicates(def_id)),
863 ast: ast.map(|body| self.encode_body(body)),
864 mir: if mir { self.encode_optimized_mir(def_id) } else { None },
868 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
869 -> LazySeq<ast::Name> {
870 self.tcx.dep_graph.with_ignore(|| {
871 let body = self.tcx.hir.body(body_id);
872 self.lazy_seq(body.arguments.iter().map(|arg| {
874 PatKind::Binding(_, _, name, _) => name.node,
875 _ => Symbol::intern("")
881 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
882 -> LazySeq<ast::Name> {
883 self.lazy_seq(names.iter().map(|name| name.node))
886 fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
887 debug!("EntryBuilder::encode_mir({:?})", def_id);
888 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
889 let mir = self.tcx.optimized_mir(def_id);
890 Some(self.lazy(&mir))
896 // Encodes the inherent implementations of a structure, enumeration, or trait.
897 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
898 debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
899 let implementations = self.tcx.inherent_impls(def_id);
900 if implementations.is_empty() {
903 self.lazy_seq(implementations.iter().map(|&def_id| {
904 assert!(def_id.is_local());
910 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
911 debug!("IsolatedEncoder::encode_stability({:?})", def_id);
912 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
915 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
916 debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
917 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
920 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
923 debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
925 let kind = match item.node {
926 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
927 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
928 hir::ItemConst(..) => {
929 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id).0)
931 hir::ItemFn(_, _, constness, .., body) => {
934 arg_names: self.encode_fn_arg_names_for_body(body),
935 sig: self.lazy(&tcx.fn_sig(def_id)),
938 EntryKind::Fn(self.lazy(&data))
940 hir::ItemMod(ref m) => {
941 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
943 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
944 hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
945 hir::ItemTy(..) => EntryKind::Type,
946 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
947 hir::ItemStruct(ref struct_def, _) => {
948 let variant = tcx.adt_def(def_id).non_enum_variant();
950 // Encode def_ids for each field and method
951 // for methods, write all the stuff get_trait_method
953 let struct_ctor = if !struct_def.is_struct() {
954 Some(tcx.hir.local_def_id(struct_def.id()).index)
959 let repr_options = get_repr_options(&tcx, def_id);
961 EntryKind::Struct(self.lazy(&VariantData {
962 ctor_kind: variant.ctor_kind,
963 discr: variant.discr,
968 hir::ItemUnion(..) => {
969 let variant = tcx.adt_def(def_id).non_enum_variant();
970 let repr_options = get_repr_options(&tcx, def_id);
972 EntryKind::Union(self.lazy(&VariantData {
973 ctor_kind: variant.ctor_kind,
974 discr: variant.discr,
979 hir::ItemImpl(_, polarity, defaultness, ..) => {
980 let trait_ref = tcx.impl_trait_ref(def_id);
981 let parent = if let Some(trait_ref) = trait_ref {
982 let trait_def = tcx.trait_def(trait_ref.def_id);
983 trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
985 specialization_graph::Node::Impl(parent) => Some(parent),
993 // if this is an impl of `CoerceUnsized`, create its
994 // "unsized info", else just store None
995 let coerce_unsized_info =
996 trait_ref.and_then(|t| {
997 if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
998 Some(tcx.at(item.span).coerce_unsized_info(def_id))
1004 let data = ImplData {
1007 parent_impl: parent,
1008 coerce_unsized_info,
1009 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1012 EntryKind::Impl(self.lazy(&data))
1014 hir::ItemTrait(..) => {
1015 let trait_def = tcx.trait_def(def_id);
1016 let data = TraitData {
1017 unsafety: trait_def.unsafety,
1018 paren_sugar: trait_def.paren_sugar,
1019 has_auto_impl: tcx.trait_is_auto(def_id),
1020 super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1023 EntryKind::Trait(self.lazy(&data))
1025 hir::ItemExternCrate(_) |
1026 hir::ItemTraitAlias(..) |
1027 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1032 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1033 span: self.lazy(&item.span),
1034 attributes: self.encode_attributes(&item.attrs),
1035 children: match item.node {
1036 hir::ItemForeignMod(ref fm) => {
1037 self.lazy_seq(fm.items
1039 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1041 hir::ItemEnum(..) => {
1042 let def = self.tcx.adt_def(def_id);
1043 self.lazy_seq(def.variants.iter().map(|v| {
1044 assert!(v.did.is_local());
1048 hir::ItemStruct(..) |
1049 hir::ItemUnion(..) => {
1050 let def = self.tcx.adt_def(def_id);
1051 self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1052 assert!(f.did.is_local());
1057 hir::ItemTrait(..) => {
1058 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1059 assert!(def_id.is_local());
1063 _ => LazySeq::empty(),
1065 stability: self.encode_stability(def_id),
1066 deprecation: self.encode_deprecation(def_id),
1068 ty: match item.node {
1069 hir::ItemStatic(..) |
1070 hir::ItemConst(..) |
1074 hir::ItemStruct(..) |
1075 hir::ItemUnion(..) |
1076 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1079 inherent_impls: self.encode_inherent_implementations(def_id),
1080 variances: match item.node {
1082 hir::ItemStruct(..) |
1083 hir::ItemUnion(..) |
1084 hir::ItemFn(..) => self.encode_variances_of(def_id),
1085 _ => LazySeq::empty(),
1087 generics: match item.node {
1088 hir::ItemStatic(..) |
1089 hir::ItemConst(..) |
1093 hir::ItemStruct(..) |
1094 hir::ItemUnion(..) |
1096 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1099 predicates: match item.node {
1100 hir::ItemStatic(..) |
1101 hir::ItemConst(..) |
1105 hir::ItemStruct(..) |
1106 hir::ItemUnion(..) |
1108 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1112 ast: match item.node {
1113 hir::ItemConst(_, body) |
1114 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
1115 Some(self.encode_body(body))
1119 mir: match item.node {
1120 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
1121 self.encode_optimized_mir(def_id)
1123 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1124 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1125 let has_tps = generics.ty_params().next().is_some();
1126 let needs_inline = has_tps || tcx.trans_fn_attrs(def_id).requests_inline();
1127 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1128 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
1129 self.encode_optimized_mir(def_id)
1139 /// Serialize the text of exported macros
1140 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1141 use syntax::print::pprust;
1142 let def_id = self.tcx.hir.local_def_id(macro_def.id);
1144 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1145 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
1146 legacy: macro_def.legacy,
1148 visibility: self.lazy(&ty::Visibility::Public),
1149 span: self.lazy(¯o_def.span),
1150 attributes: self.encode_attributes(¯o_def.attrs),
1151 stability: self.encode_stability(def_id),
1152 deprecation: self.encode_deprecation(def_id),
1154 children: LazySeq::empty(),
1156 inherent_impls: LazySeq::empty(),
1157 variances: LazySeq::empty(),
1165 fn encode_info_for_ty_param(&mut self,
1166 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1168 debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1171 kind: EntryKind::Type,
1172 visibility: self.lazy(&ty::Visibility::Public),
1173 span: self.lazy(&tcx.def_span(def_id)),
1174 attributes: LazySeq::empty(),
1175 children: LazySeq::empty(),
1179 ty: if has_default {
1180 Some(self.encode_item_type(def_id))
1184 inherent_impls: LazySeq::empty(),
1185 variances: LazySeq::empty(),
1194 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1195 debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
1198 kind: EntryKind::Type,
1199 visibility: self.lazy(&ty::Visibility::Public),
1200 span: self.lazy(&tcx.def_span(def_id)),
1201 attributes: LazySeq::empty(),
1202 children: LazySeq::empty(),
1206 ty: Some(self.encode_item_type(def_id)),
1207 inherent_impls: LazySeq::empty(),
1208 variances: LazySeq::empty(),
1209 generics: Some(self.encode_generics(def_id)),
1210 predicates: Some(self.encode_predicates(def_id)),
1217 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1218 debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1221 let tables = self.tcx.typeck_tables_of(def_id);
1222 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1223 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1224 let kind = match tables.node_id_to_type(hir_id).sty {
1225 ty::TyGenerator(def_id, ..) => {
1226 let layout = self.tcx.generator_layout(def_id);
1227 let data = GeneratorData {
1228 layout: layout.clone(),
1230 EntryKind::Generator(self.lazy(&data))
1233 ty::TyClosure(def_id, substs) => {
1234 let sig = substs.closure_sig(def_id, self.tcx);
1235 let data = ClosureData { sig: self.lazy(&sig) };
1236 EntryKind::Closure(self.lazy(&data))
1239 _ => bug!("closure that is neither generator nor closure")
1244 visibility: self.lazy(&ty::Visibility::Public),
1245 span: self.lazy(&tcx.def_span(def_id)),
1246 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1247 children: LazySeq::empty(),
1251 ty: Some(self.encode_item_type(def_id)),
1252 inherent_impls: LazySeq::empty(),
1253 variances: LazySeq::empty(),
1254 generics: Some(self.encode_generics(def_id)),
1258 mir: self.encode_optimized_mir(def_id),
1262 fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1263 debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
1265 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1266 let body = tcx.hir.body_owned_by(id);
1269 kind: EntryKind::Const(tcx.mir_const_qualif(def_id).0),
1270 visibility: self.lazy(&ty::Visibility::Public),
1271 span: self.lazy(&tcx.def_span(def_id)),
1272 attributes: LazySeq::empty(),
1273 children: LazySeq::empty(),
1277 ty: Some(self.encode_item_type(def_id)),
1278 inherent_impls: LazySeq::empty(),
1279 variances: LazySeq::empty(),
1280 generics: Some(self.encode_generics(def_id)),
1281 predicates: Some(self.encode_predicates(def_id)),
1283 ast: Some(self.encode_body(body)),
1284 mir: self.encode_optimized_mir(def_id),
1288 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1289 // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1290 // we rely on the HashStable specialization for [Attribute]
1291 // to properly filter things out.
1292 self.lazy_seq_from_slice(attrs)
1295 fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1296 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1297 self.lazy_seq(used_libraries.iter().cloned())
1300 fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1301 let crates = self.tcx.crates();
1303 let mut deps = crates
1306 let dep = CrateDep {
1307 name: self.tcx.original_crate_name(cnum),
1308 hash: self.tcx.crate_hash(cnum),
1309 kind: self.tcx.dep_kind(cnum),
1313 .collect::<Vec<_>>();
1315 deps.sort_by_key(|&(cnum, _)| cnum);
1318 // Sanity-check the crate numbers
1319 let mut expected_cnum = 1;
1320 for &(n, _) in &deps {
1321 assert_eq!(n, CrateNum::new(expected_cnum));
1326 // We're just going to write a list of crate 'name-hash-version's, with
1327 // the assumption that they are numbered 1 to n.
1328 // FIXME (#2166): This is not nearly enough to support correct versioning
1329 // but is enough to get transitive crate dependencies working.
1330 self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1333 fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1335 let lang_items = tcx.lang_items();
1336 let lang_items = lang_items.items().iter();
1337 self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1338 if let Some(def_id) = opt_def_id {
1339 if def_id.is_local() {
1340 return Some((def_id.index, i));
1347 fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1349 self.lazy_seq_ref(&tcx.lang_items().missing)
1352 /// Encodes an index, mapping each trait to its (local) implementations.
1353 fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1354 debug!("IsolatedEncoder::encode_impls()");
1356 let mut visitor = ImplVisitor {
1360 tcx.hir.krate().visit_all_item_likes(&mut visitor);
1362 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1364 // Bring everything into deterministic order for hashing
1365 all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1366 tcx.def_path_hash(trait_def_id)
1369 let all_impls: Vec<_> = all_impls
1371 .map(|(trait_def_id, mut impls)| {
1372 // Bring everything into deterministic order for hashing
1373 impls.sort_unstable_by_key(|&def_index| {
1374 tcx.hir.definitions().def_path_hash(def_index)
1378 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1379 impls: self.lazy_seq_from_slice(&impls[..]),
1384 self.lazy_seq_from_slice(&all_impls[..])
1387 // Encodes all symbols exported from this crate into the metadata.
1389 // This pass is seeded off the reachability list calculated in the
1390 // middle::reachable module but filters out items that either don't have a
1391 // symbol associated with them (they weren't translated) or if they're an FFI
1392 // definition (as that's not defined in this crate).
1393 fn encode_exported_symbols(&mut self,
1394 exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1395 -> LazySeq<(ExportedSymbol, SymbolExportLevel)> {
1397 // The metadata symbol name is special. It should not show up in
1398 // downstream crates.
1399 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1401 self.lazy_seq(exported_symbols
1403 .filter(|&&(ref exported_symbol, _)| {
1404 match *exported_symbol {
1405 ExportedSymbol::NoDefId(symbol_name) => {
1406 symbol_name != metadata_symbol_name
1414 fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1415 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1417 self.lazy_seq(arr.iter().map(|slot| {
1419 Linkage::NotLinked |
1420 Linkage::IncludedFromDylib => None,
1422 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1423 Linkage::Static => Some(LinkagePreference::RequireStatic),
1427 None => LazySeq::empty(),
1431 fn encode_info_for_foreign_item(&mut self,
1432 (def_id, nitem): (DefId, &hir::ForeignItem))
1436 debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1438 let kind = match nitem.node {
1439 hir::ForeignItemFn(_, ref names, _) => {
1441 constness: hir::Constness::NotConst,
1442 arg_names: self.encode_fn_arg_names(names),
1443 sig: self.lazy(&tcx.fn_sig(def_id)),
1445 EntryKind::ForeignFn(self.lazy(&data))
1447 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1448 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1449 hir::ForeignItemType => EntryKind::ForeignType,
1454 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1455 span: self.lazy(&nitem.span),
1456 attributes: self.encode_attributes(&nitem.attrs),
1457 children: LazySeq::empty(),
1458 stability: self.encode_stability(def_id),
1459 deprecation: self.encode_deprecation(def_id),
1461 ty: Some(self.encode_item_type(def_id)),
1462 inherent_impls: LazySeq::empty(),
1463 variances: match nitem.node {
1464 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1465 _ => LazySeq::empty(),
1467 generics: Some(self.encode_generics(def_id)),
1468 predicates: Some(self.encode_predicates(def_id)),
1476 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1477 index: IndexBuilder<'a, 'b, 'tcx>,
1480 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1481 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1482 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1484 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1485 intravisit::walk_expr(self, ex);
1486 self.index.encode_info_for_expr(ex);
1488 fn visit_item(&mut self, item: &'tcx hir::Item) {
1489 intravisit::walk_item(self, item);
1490 let def_id = self.index.tcx.hir.local_def_id(item.id);
1492 hir::ItemExternCrate(_) |
1493 hir::ItemUse(..) => (), // ignore these
1494 _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1496 self.index.encode_addl_info_for_item(item);
1498 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1499 intravisit::walk_foreign_item(self, ni);
1500 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1501 self.index.record(def_id,
1502 IsolatedEncoder::encode_info_for_foreign_item,
1505 fn visit_variant(&mut self,
1506 v: &'tcx hir::Variant,
1507 g: &'tcx hir::Generics,
1509 intravisit::walk_variant(self, v, g, id);
1511 if let Some(discr) = v.node.disr_expr {
1512 let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1513 self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1516 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1517 intravisit::walk_generics(self, generics);
1518 self.index.encode_info_for_generics(generics);
1520 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1521 intravisit::walk_ty(self, ty);
1522 self.index.encode_info_for_ty(ty);
1524 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1525 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1526 self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1530 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1531 fn encode_fields(&mut self, adt_def_id: DefId) {
1532 let def = self.tcx.adt_def(adt_def_id);
1533 for (variant_index, variant) in def.variants.iter().enumerate() {
1534 for (field_index, field) in variant.fields.iter().enumerate() {
1535 self.record(field.did,
1536 IsolatedEncoder::encode_field,
1537 (adt_def_id, Untracked((variant_index, field_index))));
1542 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1543 for ty_param in generics.ty_params() {
1544 let def_id = self.tcx.hir.local_def_id(ty_param.id);
1545 let has_default = Untracked(ty_param.default.is_some());
1546 self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
1550 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1552 hir::TyImplTraitExistential(..) => {
1553 let def_id = self.tcx.hir.local_def_id(ty.id);
1554 self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
1556 hir::TyArray(_, len) => {
1557 let def_id = self.tcx.hir.body_owner_def_id(len);
1558 self.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1564 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1566 hir::ExprClosure(..) => {
1567 let def_id = self.tcx.hir.local_def_id(expr.id);
1568 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1574 /// In some cases, along with the item itself, we also
1575 /// encode some sub-items. Usually we want some info from the item
1576 /// so it's easier to do that here then to wait until we would encounter
1577 /// normally in the visitor walk.
1578 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1579 let def_id = self.tcx.hir.local_def_id(item.id);
1581 hir::ItemStatic(..) |
1582 hir::ItemConst(..) |
1585 hir::ItemForeignMod(..) |
1586 hir::ItemGlobalAsm(..) |
1587 hir::ItemExternCrate(..) |
1590 hir::ItemTraitAlias(..) => {
1591 // no sub-item recording needed in these cases
1593 hir::ItemEnum(..) => {
1594 self.encode_fields(def_id);
1596 let def = self.tcx.adt_def(def_id);
1597 for (i, variant) in def.variants.iter().enumerate() {
1598 self.record(variant.did,
1599 IsolatedEncoder::encode_enum_variant_info,
1600 (def_id, Untracked(i)));
1603 hir::ItemStruct(ref struct_def, _) => {
1604 self.encode_fields(def_id);
1606 // If the struct has a constructor, encode it.
1607 if !struct_def.is_struct() {
1608 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1609 self.record(ctor_def_id,
1610 IsolatedEncoder::encode_struct_ctor,
1611 (def_id, ctor_def_id));
1614 hir::ItemUnion(..) => {
1615 self.encode_fields(def_id);
1617 hir::ItemImpl(..) => {
1618 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1619 self.record(trait_item_def_id,
1620 IsolatedEncoder::encode_info_for_impl_item,
1624 hir::ItemTrait(..) => {
1625 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1626 self.record(item_def_id,
1627 IsolatedEncoder::encode_info_for_trait_item,
1635 struct ImplVisitor<'a, 'tcx: 'a> {
1636 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1637 impls: FxHashMap<DefId, Vec<DefIndex>>,
1640 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1641 fn visit_item(&mut self, item: &hir::Item) {
1642 if let hir::ItemImpl(..) = item.node {
1643 let impl_id = self.tcx.hir.local_def_id(item.id);
1644 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1646 .entry(trait_ref.def_id)
1648 .push(impl_id.index);
1653 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1655 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1656 // handled in `visit_item` above
1660 // NOTE(eddyb) The following comment was preserved for posterity, even
1661 // though it's no longer relevant as EBML (which uses nested & tagged
1662 // "documents") was replaced with a scheme that can't go out of bounds.
1664 // And here we run into yet another obscure archive bug: in which metadata
1665 // loaded from archives may have trailing garbage bytes. Awhile back one of
1666 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1667 // and opt) by having ebml generate an out-of-bounds panic when looking at
1670 // Upon investigation it turned out that the metadata file inside of an rlib
1671 // (and ar archive) was being corrupted. Some compilations would generate a
1672 // metadata file which would end in a few extra bytes, while other
1673 // compilations would not have these extra bytes appended to the end. These
1674 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1675 // being interpreted causing the out-of-bounds.
1677 // The root cause of why these extra bytes were appearing was never
1678 // discovered, and in the meantime the solution we're employing is to insert
1679 // the length of the metadata to the start of the metadata. Later on this
1680 // will allow us to slice the metadata to the precise length that we just
1681 // generated regardless of trailing bytes that end up in it.
1683 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1684 link_meta: &LinkMeta)
1687 let mut cursor = Cursor::new(vec![]);
1688 cursor.write_all(METADATA_HEADER).unwrap();
1690 // Will be filled with the root position after encoding everything.
1691 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1694 let mut ecx = EncodeContext {
1695 opaque: opaque::Encoder::new(&mut cursor),
1698 lazy_state: LazyState::NoNode,
1699 type_shorthands: Default::default(),
1700 predicate_shorthands: Default::default(),
1701 filemap_cache: tcx.sess.codemap().files()[0].clone(),
1704 // Encode the rustc version string in a predictable location.
1705 rustc_version().encode(&mut ecx).unwrap();
1707 // Encode all the entries and extra information in the crate,
1708 // culminating in the `CrateRoot` which points to all of it.
1709 ecx.encode_crate_root()
1711 let mut result = cursor.into_inner();
1713 // Encode the root position.
1714 let header = METADATA_HEADER.len();
1715 let pos = root.position;
1716 result[header + 0] = (pos >> 24) as u8;
1717 result[header + 1] = (pos >> 16) as u8;
1718 result[header + 2] = (pos >> 8) as u8;
1719 result[header + 3] = (pos >> 0) as u8;
1721 EncodedMetadata { raw_data: result }
1724 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1725 let ty = tcx.type_of(did);
1727 ty::TyAdt(ref def, _) => return def.repr,
1728 _ => bug!("{} is not an ADT", ty),