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.
15 use rustc::middle::cstore::{LinkMeta, LinkagePreference, NativeLibrary};
17 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId};
18 use rustc::hir::map::definitions::DefPathTable;
19 use rustc::middle::dependency_format::Linkage;
20 use rustc::middle::lang_items;
22 use rustc::traits::specialization_graph;
23 use rustc::ty::{self, Ty, TyCtxt};
25 use rustc::session::config::{self, CrateTypeProcMacro};
26 use rustc::util::nodemap::{FxHashMap, NodeSet};
28 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
31 use std::io::prelude::*;
35 use syntax::ast::{self, CRATE_NODE_ID};
36 use syntax::codemap::Spanned;
38 use syntax::symbol::Symbol;
41 use rustc::hir::{self, PatKind};
42 use rustc::hir::itemlikevisit::ItemLikeVisitor;
43 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
44 use rustc::hir::intravisit;
46 use rustc_i128::{u128, i128};
48 use super::index_builder::{FromId, IndexBuilder, Untracked};
50 pub struct EncodeContext<'a, 'tcx: 'a> {
51 opaque: opaque::Encoder<'a>,
52 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
53 reexports: &'a def::ExportMap,
54 link_meta: &'a LinkMeta,
55 cstore: &'a cstore::CStore,
56 exported_symbols: &'a NodeSet,
58 lazy_state: LazyState,
59 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
60 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
63 macro_rules! encoder_methods {
64 ($($name:ident($ty:ty);)*) => {
65 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
66 self.opaque.$name(value)
71 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
72 type Error = <opaque::Encoder<'a> as Encoder>::Error;
74 fn emit_nil(&mut self) -> Result<(), Self::Error> {
101 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
102 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
103 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
107 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
108 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
109 self.emit_usize(seq.len)?;
113 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
117 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
118 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
119 self.encode_with_shorthand(ty, &ty.sty, |ecx| &mut ecx.type_shorthands)
123 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
124 fn specialized_encode(&mut self,
125 predicates: &ty::GenericPredicates<'tcx>)
126 -> Result<(), Self::Error> {
127 predicates.parent.encode(self)?;
128 predicates.predicates.len().encode(self)?;
129 for predicate in &predicates.predicates {
130 self.encode_with_shorthand(predicate, predicate, |ecx| &mut ecx.predicate_shorthands)?
136 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
137 pub fn position(&self) -> usize {
138 self.opaque.position()
141 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
142 assert_eq!(self.lazy_state, LazyState::NoNode);
143 let pos = self.position();
144 self.lazy_state = LazyState::NodeStart(pos);
145 let r = f(self, pos);
146 self.lazy_state = LazyState::NoNode;
150 fn emit_lazy_distance(&mut self,
153 -> Result<(), <Self as Encoder>::Error> {
154 let min_end = position + min_size;
155 let distance = match self.lazy_state {
156 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
157 LazyState::NodeStart(start) => {
158 assert!(min_end <= start);
161 LazyState::Previous(last_min_end) => {
162 assert!(last_min_end <= position);
163 position - last_min_end
166 self.lazy_state = LazyState::Previous(min_end);
167 self.emit_usize(distance)
170 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
171 self.emit_node(|ecx, pos| {
172 value.encode(ecx).unwrap();
174 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
175 Lazy::with_position(pos)
179 fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
180 where I: IntoIterator<Item = T>,
183 self.emit_node(|ecx, pos| {
184 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
186 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
187 LazySeq::with_position_and_length(pos, len)
191 fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
192 where I: IntoIterator<Item = &'b T>,
195 self.emit_node(|ecx, pos| {
196 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
198 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
199 LazySeq::with_position_and_length(pos, len)
203 /// Encode the given value or a previously cached shorthand.
204 fn encode_with_shorthand<T, U, M>(&mut self,
208 -> Result<(), <Self as Encoder>::Error>
209 where M: for<'b> Fn(&'b mut Self) -> &'b mut FxHashMap<T, usize>,
210 T: Clone + Eq + Hash,
213 let existing_shorthand = map(self).get(value).cloned();
214 if let Some(shorthand) = existing_shorthand {
215 return self.emit_usize(shorthand);
218 let start = self.position();
219 variant.encode(self)?;
220 let len = self.position() - start;
222 // The shorthand encoding uses the same usize as the
223 // discriminant, with an offset so they can't conflict.
224 let discriminant = unsafe { intrinsics::discriminant_value(variant) };
225 assert!(discriminant < SHORTHAND_OFFSET as u64);
226 let shorthand = start + SHORTHAND_OFFSET;
228 // Get the number of bits that leb128 could fit
229 // in the same space as the fully encoded type.
230 let leb128_bits = len * 7;
232 // Check that the shorthand is a not longer than the
233 // full encoding itself, i.e. it's an obvious win.
234 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
235 map(self).insert(value.clone(), shorthand);
241 fn encode_item_variances(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
243 self.lazy_seq(tcx.item_variances(def_id).iter().cloned())
246 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
248 self.lazy(&tcx.item_type(def_id))
251 /// Encode data for the given variant of the given ADT. The
252 /// index of the variant is untracked: this is ok because we
253 /// will have to lookup the adt-def by its id, and that gives us
254 /// the right to access any information in the adt-def (including,
255 /// e.g., the length of the various vectors).
256 fn encode_enum_variant_info(&mut self,
257 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
260 let def = tcx.lookup_adt_def(enum_did);
261 let variant = &def.variants[index];
262 let def_id = variant.did;
264 let data = VariantData {
265 ctor_kind: variant.ctor_kind,
266 disr: variant.disr_val.to_u128_unchecked(),
270 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
271 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
274 kind: EntryKind::Variant(self.lazy(&data)),
275 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
276 span: self.lazy(&tcx.def_span(def_id)),
277 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
278 children: self.lazy_seq(variant.fields.iter().map(|f| {
279 assert!(f.did.is_local());
282 stability: self.encode_stability(def_id),
283 deprecation: self.encode_deprecation(def_id),
285 ty: Some(self.encode_item_type(def_id)),
286 inherent_impls: LazySeq::empty(),
287 variances: LazySeq::empty(),
288 generics: Some(self.encode_generics(def_id)),
289 predicates: Some(self.encode_predicates(def_id)),
296 fn encode_info_for_mod(&mut self,
297 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
302 let def_id = tcx.hir.local_def_id(id);
305 reexports: match self.reexports.get(&id) {
306 Some(exports) if *vis == hir::Public => self.lazy_seq_ref(exports),
307 _ => LazySeq::empty(),
312 kind: EntryKind::Mod(self.lazy(&data)),
313 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
314 span: self.lazy(&md.inner),
315 attributes: self.encode_attributes(attrs),
316 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
317 tcx.hir.local_def_id(item_id.id).index
319 stability: self.encode_stability(def_id),
320 deprecation: self.encode_deprecation(def_id),
323 inherent_impls: LazySeq::empty(),
324 variances: LazySeq::empty(),
334 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
335 fn encode_fields(&mut self, adt_def_id: DefId) {
336 let def = self.tcx.lookup_adt_def(adt_def_id);
337 for (variant_index, variant) in def.variants.iter().enumerate() {
338 for (field_index, field) in variant.fields.iter().enumerate() {
339 self.record(field.did,
340 EncodeContext::encode_field,
341 (adt_def_id, Untracked((variant_index, field_index))));
347 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
348 /// Encode data for the given field of the given variant of the
349 /// given ADT. The indices of the variant/field are untracked:
350 /// this is ok because we will have to lookup the adt-def by its
351 /// id, and that gives us the right to access any information in
352 /// the adt-def (including, e.g., the length of the various
354 fn encode_field(&mut self,
355 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
360 let variant = &tcx.lookup_adt_def(adt_def_id).variants[variant_index];
361 let field = &variant.fields[field_index];
363 let def_id = field.did;
364 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
365 let variant_data = tcx.hir.expect_variant_data(variant_id);
368 kind: EntryKind::Field,
369 visibility: self.lazy(&field.vis),
370 span: self.lazy(&tcx.def_span(def_id)),
371 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
372 children: LazySeq::empty(),
373 stability: self.encode_stability(def_id),
374 deprecation: self.encode_deprecation(def_id),
376 ty: Some(self.encode_item_type(def_id)),
377 inherent_impls: LazySeq::empty(),
378 variances: LazySeq::empty(),
379 generics: Some(self.encode_generics(def_id)),
380 predicates: Some(self.encode_predicates(def_id)),
387 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
389 let variant = tcx.lookup_adt_def(adt_def_id).struct_variant();
391 let data = VariantData {
392 ctor_kind: variant.ctor_kind,
393 disr: variant.disr_val.to_u128_unchecked(),
394 struct_ctor: Some(def_id.index),
397 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
398 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
401 kind: EntryKind::Struct(self.lazy(&data)),
402 visibility: self.lazy(&ty::Visibility::from_hir(struct_vis, struct_id, tcx)),
403 span: self.lazy(&tcx.def_span(def_id)),
404 attributes: LazySeq::empty(),
405 children: LazySeq::empty(),
406 stability: self.encode_stability(def_id),
407 deprecation: self.encode_deprecation(def_id),
409 ty: Some(self.encode_item_type(def_id)),
410 inherent_impls: LazySeq::empty(),
411 variances: LazySeq::empty(),
412 generics: Some(self.encode_generics(def_id)),
413 predicates: Some(self.encode_predicates(def_id)),
420 fn encode_generics(&mut self, def_id: DefId) -> Lazy<Generics<'tcx>> {
422 let g = tcx.item_generics(def_id);
423 let regions = self.lazy_seq_ref(&g.regions);
424 let types = self.lazy_seq_ref(&g.types);
425 self.lazy(&Generics {
427 parent_regions: g.parent_regions,
428 parent_types: g.parent_types,
431 has_self: g.has_self,
435 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
437 self.lazy(&tcx.item_predicates(def_id))
440 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
443 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
444 let ast_item = tcx.hir.expect_trait_item(node_id);
445 let trait_item = tcx.associated_item(def_id);
447 let container = match trait_item.defaultness {
448 hir::Defaultness::Default { has_value: true } =>
449 AssociatedContainer::TraitWithDefault,
450 hir::Defaultness::Default { has_value: false } =>
451 AssociatedContainer::TraitRequired,
452 hir::Defaultness::Final =>
453 span_bug!(ast_item.span, "traits cannot have final items"),
456 let kind = match trait_item.kind {
457 ty::AssociatedKind::Const => EntryKind::AssociatedConst(container),
458 ty::AssociatedKind::Method => {
459 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
460 let arg_names = match *m {
461 hir::TraitMethod::Required(ref names) => {
462 self.encode_fn_arg_names(names)
464 hir::TraitMethod::Provided(body) => {
465 self.encode_fn_arg_names_for_body(body)
469 constness: hir::Constness::NotConst,
475 EntryKind::Method(self.lazy(&MethodData {
477 container: container,
478 has_self: trait_item.method_has_self_argument,
481 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
486 visibility: self.lazy(&trait_item.vis),
487 span: self.lazy(&ast_item.span),
488 attributes: self.encode_attributes(&ast_item.attrs),
489 children: LazySeq::empty(),
490 stability: self.encode_stability(def_id),
491 deprecation: self.encode_deprecation(def_id),
493 ty: match trait_item.kind {
494 ty::AssociatedKind::Const |
495 ty::AssociatedKind::Method => {
496 Some(self.encode_item_type(def_id))
498 ty::AssociatedKind::Type => {
499 if trait_item.defaultness.has_value() {
500 Some(self.encode_item_type(def_id))
506 inherent_impls: LazySeq::empty(),
507 variances: LazySeq::empty(),
508 generics: Some(self.encode_generics(def_id)),
509 predicates: Some(self.encode_predicates(def_id)),
511 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
512 Some(self.encode_body(body))
516 mir: self.encode_mir(def_id),
520 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
521 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
522 let ast_item = self.tcx.hir.expect_impl_item(node_id);
523 let impl_item = self.tcx.associated_item(def_id);
525 let container = match impl_item.defaultness {
526 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
527 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
528 hir::Defaultness::Default { has_value: false } =>
529 span_bug!(ast_item.span, "impl items always have values (currently)"),
532 let kind = match impl_item.kind {
533 ty::AssociatedKind::Const => EntryKind::AssociatedConst(container),
534 ty::AssociatedKind::Method => {
535 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
537 constness: sig.constness,
538 arg_names: self.encode_fn_arg_names_for_body(body),
543 EntryKind::Method(self.lazy(&MethodData {
545 container: container,
546 has_self: impl_item.method_has_self_argument,
549 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
552 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
554 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
555 let generics = self.tcx.item_generics(def_id);
556 let types = generics.parent_types as usize + generics.types.len();
557 let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
558 let is_const_fn = sig.constness == hir::Constness::Const;
559 let ast = if is_const_fn { Some(body) } else { None };
560 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
561 (ast, needs_inline || is_const_fn || always_encode_mir)
568 visibility: self.lazy(&impl_item.vis),
569 span: self.lazy(&ast_item.span),
570 attributes: self.encode_attributes(&ast_item.attrs),
571 children: LazySeq::empty(),
572 stability: self.encode_stability(def_id),
573 deprecation: self.encode_deprecation(def_id),
575 ty: Some(self.encode_item_type(def_id)),
576 inherent_impls: LazySeq::empty(),
577 variances: LazySeq::empty(),
578 generics: Some(self.encode_generics(def_id)),
579 predicates: Some(self.encode_predicates(def_id)),
581 ast: ast.map(|body| self.encode_body(body)),
582 mir: if mir { self.encode_mir(def_id) } else { None },
586 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
587 -> LazySeq<ast::Name> {
588 let _ignore = self.tcx.dep_graph.in_ignore();
589 let body = self.tcx.hir.body(body_id);
590 self.lazy_seq(body.arguments.iter().map(|arg| {
592 PatKind::Binding(_, _, name, _) => name.node,
593 _ => Symbol::intern("")
598 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
599 -> LazySeq<ast::Name> {
600 self.lazy_seq(names.iter().map(|name| name.node))
603 fn encode_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
604 self.tcx.mir_map.borrow().get(&def_id).map(|mir| self.lazy(&*mir.borrow()))
607 // Encodes the inherent implementations of a structure, enumeration, or trait.
608 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
609 match self.tcx.inherent_impls.borrow().get(&def_id) {
610 None => LazySeq::empty(),
611 Some(implementations) => {
612 self.lazy_seq(implementations.iter().map(|&def_id| {
613 assert!(def_id.is_local());
620 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
621 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
624 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
625 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
628 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
631 debug!("encoding info for item at {}",
632 tcx.sess.codemap().span_to_string(item.span));
634 let kind = match item.node {
635 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
636 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
637 hir::ItemConst(..) => EntryKind::Const,
638 hir::ItemFn(_, _, constness, .., body) => {
640 constness: constness,
641 arg_names: self.encode_fn_arg_names_for_body(body),
644 EntryKind::Fn(self.lazy(&data))
646 hir::ItemMod(ref m) => {
647 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
649 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
650 hir::ItemTy(..) => EntryKind::Type,
651 hir::ItemEnum(..) => EntryKind::Enum,
652 hir::ItemStruct(ref struct_def, _) => {
653 let variant = tcx.lookup_adt_def(def_id).struct_variant();
655 // Encode def_ids for each field and method
656 // for methods, write all the stuff get_trait_method
658 let struct_ctor = if !struct_def.is_struct() {
659 Some(tcx.hir.local_def_id(struct_def.id()).index)
663 EntryKind::Struct(self.lazy(&VariantData {
664 ctor_kind: variant.ctor_kind,
665 disr: variant.disr_val.to_u128_unchecked(),
666 struct_ctor: struct_ctor,
669 hir::ItemUnion(..) => {
670 let variant = tcx.lookup_adt_def(def_id).struct_variant();
672 EntryKind::Union(self.lazy(&VariantData {
673 ctor_kind: variant.ctor_kind,
674 disr: variant.disr_val.to_u128_unchecked(),
678 hir::ItemDefaultImpl(..) => {
679 let data = ImplData {
680 polarity: hir::ImplPolarity::Positive,
682 coerce_unsized_kind: None,
683 trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref)),
686 EntryKind::DefaultImpl(self.lazy(&data))
688 hir::ItemImpl(_, polarity, ..) => {
689 let trait_ref = tcx.impl_trait_ref(def_id);
690 let parent = if let Some(trait_ref) = trait_ref {
691 let trait_def = tcx.lookup_trait_def(trait_ref.def_id);
692 trait_def.ancestors(def_id).skip(1).next().and_then(|node| {
694 specialization_graph::Node::Impl(parent) => Some(parent),
702 let data = ImplData {
705 coerce_unsized_kind: tcx.custom_coerce_unsized_kinds
709 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
712 EntryKind::Impl(self.lazy(&data))
714 hir::ItemTrait(..) => {
715 let trait_def = tcx.lookup_trait_def(def_id);
716 let data = TraitData {
717 unsafety: trait_def.unsafety,
718 paren_sugar: trait_def.paren_sugar,
719 has_default_impl: tcx.trait_has_default_impl(def_id),
720 super_predicates: self.lazy(&tcx.item_super_predicates(def_id)),
723 EntryKind::Trait(self.lazy(&data))
725 hir::ItemExternCrate(_) |
726 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
731 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
732 span: self.lazy(&item.span),
733 attributes: self.encode_attributes(&item.attrs),
734 children: match item.node {
735 hir::ItemForeignMod(ref fm) => {
736 self.lazy_seq(fm.items
738 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
740 hir::ItemEnum(..) => {
741 let def = self.tcx.lookup_adt_def(def_id);
742 self.lazy_seq(def.variants.iter().map(|v| {
743 assert!(v.did.is_local());
747 hir::ItemStruct(..) |
748 hir::ItemUnion(..) => {
749 let def = self.tcx.lookup_adt_def(def_id);
750 self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
751 assert!(f.did.is_local());
756 hir::ItemTrait(..) => {
757 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
758 assert!(def_id.is_local());
762 _ => LazySeq::empty(),
764 stability: self.encode_stability(def_id),
765 deprecation: self.encode_deprecation(def_id),
767 ty: match item.node {
768 hir::ItemStatic(..) |
773 hir::ItemStruct(..) |
775 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
778 inherent_impls: self.encode_inherent_implementations(def_id),
779 variances: match item.node {
781 hir::ItemStruct(..) |
783 hir::ItemTrait(..) => self.encode_item_variances(def_id),
784 _ => LazySeq::empty(),
786 generics: match item.node {
787 hir::ItemStatic(..) |
792 hir::ItemStruct(..) |
795 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
798 predicates: match item.node {
799 hir::ItemStatic(..) |
804 hir::ItemStruct(..) |
807 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
811 ast: match item.node {
812 hir::ItemConst(_, body) |
813 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
814 Some(self.encode_body(body))
818 mir: match item.node {
819 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
820 self.encode_mir(def_id)
822 hir::ItemConst(..) => self.encode_mir(def_id),
823 hir::ItemFn(_, _, constness, _, ref generics, _) => {
824 let tps_len = generics.ty_params.len();
825 let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
826 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
827 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
828 self.encode_mir(def_id)
838 /// Serialize the text of exported macros
839 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
841 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
842 body: ::syntax::print::pprust::tts_to_string(¯o_def.body)
844 visibility: self.lazy(&ty::Visibility::Public),
845 span: self.lazy(¯o_def.span),
847 attributes: self.encode_attributes(¯o_def.attrs),
848 children: LazySeq::empty(),
852 inherent_impls: LazySeq::empty(),
853 variances: LazySeq::empty(),
862 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
863 /// In some cases, along with the item itself, we also
864 /// encode some sub-items. Usually we want some info from the item
865 /// so it's easier to do that here then to wait until we would encounter
866 /// normally in the visitor walk.
867 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
868 let def_id = self.tcx.hir.local_def_id(item.id);
870 hir::ItemStatic(..) |
874 hir::ItemForeignMod(..) |
875 hir::ItemExternCrate(..) |
877 hir::ItemDefaultImpl(..) |
879 // no sub-item recording needed in these cases
881 hir::ItemEnum(..) => {
882 self.encode_fields(def_id);
884 let def = self.tcx.lookup_adt_def(def_id);
885 for (i, variant) in def.variants.iter().enumerate() {
886 self.record(variant.did,
887 EncodeContext::encode_enum_variant_info,
888 (def_id, Untracked(i)));
891 hir::ItemStruct(ref struct_def, _) => {
892 self.encode_fields(def_id);
894 // If the struct has a constructor, encode it.
895 if !struct_def.is_struct() {
896 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
897 self.record(ctor_def_id,
898 EncodeContext::encode_struct_ctor,
899 (def_id, ctor_def_id));
902 hir::ItemUnion(..) => {
903 self.encode_fields(def_id);
905 hir::ItemImpl(..) => {
906 for &trait_item_def_id in &self.tcx.associated_item_def_ids(def_id)[..] {
907 self.record(trait_item_def_id,
908 EncodeContext::encode_info_for_impl_item,
912 hir::ItemTrait(..) => {
913 for &item_def_id in &self.tcx.associated_item_def_ids(def_id)[..] {
914 self.record(item_def_id,
915 EncodeContext::encode_info_for_trait_item,
923 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
924 fn encode_info_for_foreign_item(&mut self,
925 (def_id, nitem): (DefId, &hir::ForeignItem))
929 debug!("writing foreign item {}", tcx.node_path_str(nitem.id));
931 let kind = match nitem.node {
932 hir::ForeignItemFn(_, ref names, _) => {
934 constness: hir::Constness::NotConst,
935 arg_names: self.encode_fn_arg_names(names),
937 EntryKind::ForeignFn(self.lazy(&data))
939 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
940 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
945 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
946 span: self.lazy(&nitem.span),
947 attributes: self.encode_attributes(&nitem.attrs),
948 children: LazySeq::empty(),
949 stability: self.encode_stability(def_id),
950 deprecation: self.encode_deprecation(def_id),
952 ty: Some(self.encode_item_type(def_id)),
953 inherent_impls: LazySeq::empty(),
954 variances: LazySeq::empty(),
955 generics: Some(self.encode_generics(def_id)),
956 predicates: Some(self.encode_predicates(def_id)),
964 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
965 index: IndexBuilder<'a, 'b, 'tcx>,
968 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
969 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
970 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
972 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
973 intravisit::walk_expr(self, ex);
974 self.index.encode_info_for_expr(ex);
976 fn visit_item(&mut self, item: &'tcx hir::Item) {
977 intravisit::walk_item(self, item);
978 let def_id = self.index.tcx.hir.local_def_id(item.id);
980 hir::ItemExternCrate(_) |
981 hir::ItemUse(..) => (), // ignore these
982 _ => self.index.record(def_id, EncodeContext::encode_info_for_item, (def_id, item)),
984 self.index.encode_addl_info_for_item(item);
986 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
987 intravisit::walk_foreign_item(self, ni);
988 let def_id = self.index.tcx.hir.local_def_id(ni.id);
989 self.index.record(def_id,
990 EncodeContext::encode_info_for_foreign_item,
993 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
994 intravisit::walk_ty(self, ty);
995 self.index.encode_info_for_ty(ty);
997 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
998 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
999 self.index.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def);
1003 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1004 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1005 if let hir::TyImplTrait(_) = ty.node {
1006 let def_id = self.tcx.hir.local_def_id(ty.id);
1007 self.record(def_id, EncodeContext::encode_info_for_anon_ty, def_id);
1011 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1013 hir::ExprClosure(..) => {
1014 let def_id = self.tcx.hir.local_def_id(expr.id);
1015 self.record(def_id, EncodeContext::encode_info_for_closure, def_id);
1022 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1023 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1026 kind: EntryKind::Type,
1027 visibility: self.lazy(&ty::Visibility::Public),
1028 span: self.lazy(&tcx.def_span(def_id)),
1029 attributes: LazySeq::empty(),
1030 children: LazySeq::empty(),
1034 ty: Some(self.encode_item_type(def_id)),
1035 inherent_impls: LazySeq::empty(),
1036 variances: LazySeq::empty(),
1037 generics: Some(self.encode_generics(def_id)),
1038 predicates: Some(self.encode_predicates(def_id)),
1045 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1048 let data = ClosureData {
1049 kind: tcx.closure_kind(def_id),
1050 ty: self.lazy(&tcx.closure_tys.borrow()[&def_id]),
1054 kind: EntryKind::Closure(self.lazy(&data)),
1055 visibility: self.lazy(&ty::Visibility::Public),
1056 span: self.lazy(&tcx.def_span(def_id)),
1057 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1058 children: LazySeq::empty(),
1062 ty: Some(self.encode_item_type(def_id)),
1063 inherent_impls: LazySeq::empty(),
1064 variances: LazySeq::empty(),
1065 generics: Some(self.encode_generics(def_id)),
1069 mir: self.encode_mir(def_id),
1073 fn encode_info_for_items(&mut self) -> Index {
1074 let krate = self.tcx.hir.krate();
1075 let mut index = IndexBuilder::new(self);
1076 index.record(DefId::local(CRATE_DEF_INDEX),
1077 EncodeContext::encode_info_for_mod,
1078 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
1079 let mut visitor = EncodeVisitor { index: index };
1080 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
1081 for macro_def in &krate.exported_macros {
1082 visitor.visit_macro_def(macro_def);
1084 visitor.index.into_items()
1087 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1088 self.lazy_seq_ref(attrs)
1091 fn encode_crate_deps(&mut self) -> LazySeq<CrateDep> {
1092 fn get_ordered_deps(cstore: &cstore::CStore) -> Vec<(CrateNum, Rc<cstore::CrateMetadata>)> {
1093 // Pull the cnums and name,vers,hash out of cstore
1094 let mut deps = Vec::new();
1095 cstore.iter_crate_data(|cnum, val| {
1096 deps.push((cnum, val.clone()));
1100 deps.sort_by(|kv1, kv2| kv1.0.cmp(&kv2.0));
1102 // Sanity-check the crate numbers
1103 let mut expected_cnum = 1;
1104 for &(n, _) in &deps {
1105 assert_eq!(n, CrateNum::new(expected_cnum));
1112 // We're just going to write a list of crate 'name-hash-version's, with
1113 // the assumption that they are numbered 1 to n.
1114 // FIXME (#2166): This is not nearly enough to support correct versioning
1115 // but is enough to get transitive crate dependencies working.
1116 let deps = get_ordered_deps(self.cstore);
1117 self.lazy_seq(deps.iter().map(|&(_, ref dep)| {
1121 kind: dep.dep_kind.get(),
1126 fn encode_lang_items(&mut self) -> (LazySeq<(DefIndex, usize)>, LazySeq<lang_items::LangItem>) {
1128 let lang_items = tcx.lang_items.items().iter();
1129 (self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1130 if let Some(def_id) = opt_def_id {
1131 if def_id.is_local() {
1132 return Some((def_id.index, i));
1137 self.lazy_seq_ref(&tcx.lang_items.missing))
1140 fn encode_native_libraries(&mut self) -> LazySeq<NativeLibrary> {
1141 let used_libraries = self.tcx.sess.cstore.used_libraries();
1142 self.lazy_seq(used_libraries)
1145 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
1146 let codemap = self.tcx.sess.codemap();
1147 let all_filemaps = codemap.files.borrow();
1148 self.lazy_seq_ref(all_filemaps.iter()
1150 // No need to re-export imported filemaps, as any downstream
1151 // crate will import them from their original source.
1152 !filemap.is_imported()
1154 .map(|filemap| &**filemap))
1157 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
1158 let definitions = self.tcx.hir.definitions();
1159 self.lazy(definitions.def_path_table())
1163 struct ImplVisitor<'a, 'tcx: 'a> {
1164 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1165 impls: FxHashMap<DefId, Vec<DefIndex>>,
1168 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1169 fn visit_item(&mut self, item: &hir::Item) {
1170 if let hir::ItemImpl(..) = item.node {
1171 let impl_id = self.tcx.hir.local_def_id(item.id);
1172 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1174 .entry(trait_ref.def_id)
1176 .push(impl_id.index);
1181 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1183 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1184 // handled in `visit_item` above
1188 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1189 /// Encodes an index, mapping each trait to its (local) implementations.
1190 fn encode_impls(&mut self) -> LazySeq<TraitImpls> {
1191 let mut visitor = ImplVisitor {
1195 self.tcx.hir.krate().visit_all_item_likes(&mut visitor);
1197 let all_impls: Vec<_> = visitor.impls
1199 .map(|(trait_def_id, impls)| {
1201 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1202 impls: self.lazy_seq(impls),
1207 self.lazy_seq(all_impls)
1210 // Encodes all symbols exported from this crate into the metadata.
1212 // This pass is seeded off the reachability list calculated in the
1213 // middle::reachable module but filters out items that either don't have a
1214 // symbol associated with them (they weren't translated) or if they're an FFI
1215 // definition (as that's not defined in this crate).
1216 fn encode_exported_symbols(&mut self) -> LazySeq<DefIndex> {
1217 let exported_symbols = self.exported_symbols;
1219 self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
1222 fn encode_dylib_dependency_formats(&mut self) -> LazySeq<Option<LinkagePreference>> {
1223 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1225 self.lazy_seq(arr.iter().map(|slot| {
1227 Linkage::NotLinked |
1228 Linkage::IncludedFromDylib => None,
1230 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1231 Linkage::Static => Some(LinkagePreference::RequireStatic),
1235 None => LazySeq::empty(),
1239 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
1240 let mut i = self.position();
1241 let crate_deps = self.encode_crate_deps();
1242 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
1243 let dep_bytes = self.position() - i;
1245 // Encode the language items.
1246 i = self.position();
1247 let (lang_items, lang_items_missing) = self.encode_lang_items();
1248 let lang_item_bytes = self.position() - i;
1250 // Encode the native libraries used
1251 i = self.position();
1252 let native_libraries = self.encode_native_libraries();
1253 let native_lib_bytes = self.position() - i;
1256 i = self.position();
1257 let codemap = self.encode_codemap();
1258 let codemap_bytes = self.position() - i;
1260 // Encode DefPathTable
1261 i = self.position();
1262 let def_path_table = self.encode_def_path_table();
1263 let def_path_table_bytes = self.position() - i;
1265 // Encode the def IDs of impls, for coherence checking.
1266 i = self.position();
1267 let impls = self.encode_impls();
1268 let impl_bytes = self.position() - i;
1270 // Encode exported symbols info.
1271 i = self.position();
1272 let exported_symbols = self.encode_exported_symbols();
1273 let exported_symbols_bytes = self.position() - i;
1275 // Encode and index the items.
1276 i = self.position();
1277 let items = self.encode_info_for_items();
1278 let item_bytes = self.position() - i;
1280 i = self.position();
1281 let index = items.write_index(&mut self.opaque.cursor);
1282 let index_bytes = self.position() - i;
1285 let link_meta = self.link_meta;
1286 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
1287 let root = self.lazy(&CrateRoot {
1288 name: link_meta.crate_name,
1289 triple: tcx.sess.opts.target_triple.clone(),
1290 hash: link_meta.crate_hash,
1291 disambiguator: tcx.sess.local_crate_disambiguator(),
1292 panic_strategy: tcx.sess.panic_strategy(),
1293 plugin_registrar_fn: tcx.sess
1294 .plugin_registrar_fn
1296 .map(|id| tcx.hir.local_def_id(id).index),
1297 macro_derive_registrar: if is_proc_macro {
1298 let id = tcx.sess.derive_registrar_fn.get().unwrap();
1299 Some(tcx.hir.local_def_id(id).index)
1304 crate_deps: crate_deps,
1305 dylib_dependency_formats: dylib_dependency_formats,
1306 lang_items: lang_items,
1307 lang_items_missing: lang_items_missing,
1308 native_libraries: native_libraries,
1310 def_path_table: def_path_table,
1312 exported_symbols: exported_symbols,
1316 let total_bytes = self.position();
1318 if self.tcx.sess.meta_stats() {
1319 let mut zero_bytes = 0;
1320 for e in self.opaque.cursor.get_ref() {
1326 println!("metadata stats:");
1327 println!(" dep bytes: {}", dep_bytes);
1328 println!(" lang item bytes: {}", lang_item_bytes);
1329 println!(" native bytes: {}", native_lib_bytes);
1330 println!(" codemap bytes: {}", codemap_bytes);
1331 println!(" impl bytes: {}", impl_bytes);
1332 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
1333 println!(" def-path table bytes: {}", def_path_table_bytes);
1334 println!(" item bytes: {}", item_bytes);
1335 println!(" index bytes: {}", index_bytes);
1336 println!(" zero bytes: {}", zero_bytes);
1337 println!(" total bytes: {}", total_bytes);
1344 // NOTE(eddyb) The following comment was preserved for posterity, even
1345 // though it's no longer relevant as EBML (which uses nested & tagged
1346 // "documents") was replaced with a scheme that can't go out of bounds.
1348 // And here we run into yet another obscure archive bug: in which metadata
1349 // loaded from archives may have trailing garbage bytes. Awhile back one of
1350 // our tests was failing sporadically on the OSX 64-bit builders (both nopt
1351 // and opt) by having ebml generate an out-of-bounds panic when looking at
1354 // Upon investigation it turned out that the metadata file inside of an rlib
1355 // (and ar archive) was being corrupted. Some compilations would generate a
1356 // metadata file which would end in a few extra bytes, while other
1357 // compilations would not have these extra bytes appended to the end. These
1358 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1359 // being interpreted causing the out-of-bounds.
1361 // The root cause of why these extra bytes were appearing was never
1362 // discovered, and in the meantime the solution we're employing is to insert
1363 // the length of the metadata to the start of the metadata. Later on this
1364 // will allow us to slice the metadata to the precise length that we just
1365 // generated regardless of trailing bytes that end up in it.
1367 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1368 cstore: &cstore::CStore,
1369 reexports: &def::ExportMap,
1370 link_meta: &LinkMeta,
1371 exported_symbols: &NodeSet)
1373 let mut cursor = Cursor::new(vec![]);
1374 cursor.write_all(METADATA_HEADER).unwrap();
1376 // Will be filed with the root position after encoding everything.
1377 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1380 let mut ecx = EncodeContext {
1381 opaque: opaque::Encoder::new(&mut cursor),
1383 reexports: reexports,
1384 link_meta: link_meta,
1386 exported_symbols: exported_symbols,
1387 lazy_state: LazyState::NoNode,
1388 type_shorthands: Default::default(),
1389 predicate_shorthands: Default::default(),
1392 // Encode the rustc version string in a predictable location.
1393 rustc_version().encode(&mut ecx).unwrap();
1395 // Encode all the entries and extra information in the crate,
1396 // culminating in the `CrateRoot` which points to all of it.
1397 ecx.encode_crate_root()
1399 let mut result = cursor.into_inner();
1401 // Encode the root position.
1402 let header = METADATA_HEADER.len();
1403 let pos = root.position;
1404 result[header + 0] = (pos >> 24) as u8;
1405 result[header + 1] = (pos >> 16) as u8;
1406 result[header + 2] = (pos >> 8) as u8;
1407 result[header + 3] = (pos >> 0) as u8;