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, ReprOptions};
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 super::index_builder::{FromId, IndexBuilder, Untracked};
48 pub struct EncodeContext<'a, 'tcx: 'a> {
49 opaque: opaque::Encoder<'a>,
50 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
51 reexports: &'a def::ExportMap,
52 link_meta: &'a LinkMeta,
53 cstore: &'a cstore::CStore,
54 exported_symbols: &'a NodeSet,
56 lazy_state: LazyState,
57 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
58 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
61 macro_rules! encoder_methods {
62 ($($name:ident($ty:ty);)*) => {
63 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
64 self.opaque.$name(value)
69 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
70 type Error = <opaque::Encoder<'a> as Encoder>::Error;
72 fn emit_nil(&mut self) -> Result<(), Self::Error> {
99 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
100 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
101 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
105 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
106 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
107 self.emit_usize(seq.len)?;
111 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
115 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
116 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
117 self.encode_with_shorthand(ty, &ty.sty, |ecx| &mut ecx.type_shorthands)
121 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
122 fn specialized_encode(&mut self,
123 predicates: &ty::GenericPredicates<'tcx>)
124 -> Result<(), Self::Error> {
125 predicates.parent.encode(self)?;
126 predicates.predicates.len().encode(self)?;
127 for predicate in &predicates.predicates {
128 self.encode_with_shorthand(predicate, predicate, |ecx| &mut ecx.predicate_shorthands)?
134 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
135 pub fn position(&self) -> usize {
136 self.opaque.position()
139 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
140 assert_eq!(self.lazy_state, LazyState::NoNode);
141 let pos = self.position();
142 self.lazy_state = LazyState::NodeStart(pos);
143 let r = f(self, pos);
144 self.lazy_state = LazyState::NoNode;
148 fn emit_lazy_distance(&mut self,
151 -> Result<(), <Self as Encoder>::Error> {
152 let min_end = position + min_size;
153 let distance = match self.lazy_state {
154 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
155 LazyState::NodeStart(start) => {
156 assert!(min_end <= start);
159 LazyState::Previous(last_min_end) => {
160 assert!(last_min_end <= position);
161 position - last_min_end
164 self.lazy_state = LazyState::Previous(min_end);
165 self.emit_usize(distance)
168 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
169 self.emit_node(|ecx, pos| {
170 value.encode(ecx).unwrap();
172 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
173 Lazy::with_position(pos)
177 fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
178 where I: IntoIterator<Item = T>,
181 self.emit_node(|ecx, pos| {
182 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
184 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
185 LazySeq::with_position_and_length(pos, len)
189 fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
190 where I: IntoIterator<Item = &'b T>,
193 self.emit_node(|ecx, pos| {
194 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
196 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
197 LazySeq::with_position_and_length(pos, len)
201 /// Encode the given value or a previously cached shorthand.
202 fn encode_with_shorthand<T, U, M>(&mut self,
206 -> Result<(), <Self as Encoder>::Error>
207 where M: for<'b> Fn(&'b mut Self) -> &'b mut FxHashMap<T, usize>,
208 T: Clone + Eq + Hash,
211 let existing_shorthand = map(self).get(value).cloned();
212 if let Some(shorthand) = existing_shorthand {
213 return self.emit_usize(shorthand);
216 let start = self.position();
217 variant.encode(self)?;
218 let len = self.position() - start;
220 // The shorthand encoding uses the same usize as the
221 // discriminant, with an offset so they can't conflict.
222 let discriminant = unsafe { intrinsics::discriminant_value(variant) };
223 assert!(discriminant < SHORTHAND_OFFSET as u64);
224 let shorthand = start + SHORTHAND_OFFSET;
226 // Get the number of bits that leb128 could fit
227 // in the same space as the fully encoded type.
228 let leb128_bits = len * 7;
230 // Check that the shorthand is a not longer than the
231 // full encoding itself, i.e. it's an obvious win.
232 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
233 map(self).insert(value.clone(), shorthand);
239 fn encode_item_variances(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
241 self.lazy_seq(tcx.item_variances(def_id).iter().cloned())
244 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
246 self.lazy(&tcx.item_type(def_id))
249 /// Encode data for the given variant of the given ADT. The
250 /// index of the variant is untracked: this is ok because we
251 /// will have to lookup the adt-def by its id, and that gives us
252 /// the right to access any information in the adt-def (including,
253 /// e.g., the length of the various vectors).
254 fn encode_enum_variant_info(&mut self,
255 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
258 let def = tcx.lookup_adt_def(enum_did);
259 let variant = &def.variants[index];
260 let def_id = variant.did;
262 let data = VariantData {
263 ctor_kind: variant.ctor_kind,
264 disr: variant.disr_val.to_u128_unchecked(),
268 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
269 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
272 kind: EntryKind::Variant(self.lazy(&data)),
273 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
274 span: self.lazy(&tcx.def_span(def_id)),
275 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
276 children: self.lazy_seq(variant.fields.iter().map(|f| {
277 assert!(f.did.is_local());
280 stability: self.encode_stability(def_id),
281 deprecation: self.encode_deprecation(def_id),
283 ty: Some(self.encode_item_type(def_id)),
284 inherent_impls: LazySeq::empty(),
285 variances: LazySeq::empty(),
286 generics: Some(self.encode_generics(def_id)),
287 predicates: Some(self.encode_predicates(def_id)),
294 fn encode_info_for_mod(&mut self,
295 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
300 let def_id = tcx.hir.local_def_id(id);
303 reexports: match self.reexports.get(&id) {
304 Some(exports) if *vis == hir::Public => self.lazy_seq_ref(exports),
305 _ => LazySeq::empty(),
310 kind: EntryKind::Mod(self.lazy(&data)),
311 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
312 span: self.lazy(&md.inner),
313 attributes: self.encode_attributes(attrs),
314 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
315 tcx.hir.local_def_id(item_id.id).index
317 stability: self.encode_stability(def_id),
318 deprecation: self.encode_deprecation(def_id),
321 inherent_impls: LazySeq::empty(),
322 variances: LazySeq::empty(),
332 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
333 fn encode_fields(&mut self, adt_def_id: DefId) {
334 let def = self.tcx.lookup_adt_def(adt_def_id);
335 for (variant_index, variant) in def.variants.iter().enumerate() {
336 for (field_index, field) in variant.fields.iter().enumerate() {
337 self.record(field.did,
338 EncodeContext::encode_field,
339 (adt_def_id, Untracked((variant_index, field_index))));
345 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
346 /// Encode data for the given field of the given variant of the
347 /// given ADT. The indices of the variant/field are untracked:
348 /// this is ok because we will have to lookup the adt-def by its
349 /// id, and that gives us the right to access any information in
350 /// the adt-def (including, e.g., the length of the various
352 fn encode_field(&mut self,
353 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
358 let variant = &tcx.lookup_adt_def(adt_def_id).variants[variant_index];
359 let field = &variant.fields[field_index];
361 let def_id = field.did;
362 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
363 let variant_data = tcx.hir.expect_variant_data(variant_id);
366 kind: EntryKind::Field,
367 visibility: self.lazy(&field.vis),
368 span: self.lazy(&tcx.def_span(def_id)),
369 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
370 children: LazySeq::empty(),
371 stability: self.encode_stability(def_id),
372 deprecation: self.encode_deprecation(def_id),
374 ty: Some(self.encode_item_type(def_id)),
375 inherent_impls: LazySeq::empty(),
376 variances: LazySeq::empty(),
377 generics: Some(self.encode_generics(def_id)),
378 predicates: Some(self.encode_predicates(def_id)),
385 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
387 let variant = tcx.lookup_adt_def(adt_def_id).struct_variant();
389 let data = VariantData {
390 ctor_kind: variant.ctor_kind,
391 disr: variant.disr_val.to_u128_unchecked(),
392 struct_ctor: Some(def_id.index),
395 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
396 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
397 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
398 for field in &variant.fields {
399 if ctor_vis.is_at_least(field.vis, tcx) {
400 ctor_vis = field.vis;
404 let repr_options = get_repr_options(&tcx, adt_def_id);
407 kind: EntryKind::Struct(self.lazy(&data), repr_options),
408 visibility: self.lazy(&ctor_vis),
409 span: self.lazy(&tcx.def_span(def_id)),
410 attributes: LazySeq::empty(),
411 children: LazySeq::empty(),
412 stability: self.encode_stability(def_id),
413 deprecation: self.encode_deprecation(def_id),
415 ty: Some(self.encode_item_type(def_id)),
416 inherent_impls: LazySeq::empty(),
417 variances: LazySeq::empty(),
418 generics: Some(self.encode_generics(def_id)),
419 predicates: Some(self.encode_predicates(def_id)),
426 fn encode_generics(&mut self, def_id: DefId) -> Lazy<Generics<'tcx>> {
428 let g = tcx.item_generics(def_id);
429 let regions = self.lazy_seq_ref(&g.regions);
430 let types = self.lazy_seq_ref(&g.types);
431 let mut object_lifetime_defaults = LazySeq::empty();
432 if let Some(id) = tcx.hir.as_local_node_id(def_id) {
433 if let Some(o) = tcx.named_region_map.object_lifetime_defaults.get(&id) {
434 object_lifetime_defaults = self.lazy_seq_ref(o);
437 self.lazy(&Generics {
439 parent_regions: g.parent_regions,
440 parent_types: g.parent_types,
443 has_self: g.has_self,
444 object_lifetime_defaults: object_lifetime_defaults,
448 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
450 self.lazy(&tcx.item_predicates(def_id))
453 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
456 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
457 let ast_item = tcx.hir.expect_trait_item(node_id);
458 let trait_item = tcx.associated_item(def_id);
460 let container = match trait_item.defaultness {
461 hir::Defaultness::Default { has_value: true } =>
462 AssociatedContainer::TraitWithDefault,
463 hir::Defaultness::Default { has_value: false } =>
464 AssociatedContainer::TraitRequired,
465 hir::Defaultness::Final =>
466 span_bug!(ast_item.span, "traits cannot have final items"),
469 let kind = match trait_item.kind {
470 ty::AssociatedKind::Const => EntryKind::AssociatedConst(container),
471 ty::AssociatedKind::Method => {
472 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
473 let arg_names = match *m {
474 hir::TraitMethod::Required(ref names) => {
475 self.encode_fn_arg_names(names)
477 hir::TraitMethod::Provided(body) => {
478 self.encode_fn_arg_names_for_body(body)
482 constness: hir::Constness::NotConst,
488 EntryKind::Method(self.lazy(&MethodData {
490 container: container,
491 has_self: trait_item.method_has_self_argument,
494 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
499 visibility: self.lazy(&trait_item.vis),
500 span: self.lazy(&ast_item.span),
501 attributes: self.encode_attributes(&ast_item.attrs),
502 children: LazySeq::empty(),
503 stability: self.encode_stability(def_id),
504 deprecation: self.encode_deprecation(def_id),
506 ty: match trait_item.kind {
507 ty::AssociatedKind::Const |
508 ty::AssociatedKind::Method => {
509 Some(self.encode_item_type(def_id))
511 ty::AssociatedKind::Type => {
512 if trait_item.defaultness.has_value() {
513 Some(self.encode_item_type(def_id))
519 inherent_impls: LazySeq::empty(),
520 variances: LazySeq::empty(),
521 generics: Some(self.encode_generics(def_id)),
522 predicates: Some(self.encode_predicates(def_id)),
524 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
525 Some(self.encode_body(body))
529 mir: self.encode_mir(def_id),
533 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
534 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
535 let ast_item = self.tcx.hir.expect_impl_item(node_id);
536 let impl_item = self.tcx.associated_item(def_id);
538 let container = match impl_item.defaultness {
539 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
540 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
541 hir::Defaultness::Default { has_value: false } =>
542 span_bug!(ast_item.span, "impl items always have values (currently)"),
545 let kind = match impl_item.kind {
546 ty::AssociatedKind::Const => EntryKind::AssociatedConst(container),
547 ty::AssociatedKind::Method => {
548 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
550 constness: sig.constness,
551 arg_names: self.encode_fn_arg_names_for_body(body),
556 EntryKind::Method(self.lazy(&MethodData {
558 container: container,
559 has_self: impl_item.method_has_self_argument,
562 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
565 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
567 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
568 let generics = self.tcx.item_generics(def_id);
569 let types = generics.parent_types as usize + generics.types.len();
570 let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
571 let is_const_fn = sig.constness == hir::Constness::Const;
572 let ast = if is_const_fn { Some(body) } else { None };
573 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
574 (ast, needs_inline || is_const_fn || always_encode_mir)
581 visibility: self.lazy(&impl_item.vis),
582 span: self.lazy(&ast_item.span),
583 attributes: self.encode_attributes(&ast_item.attrs),
584 children: LazySeq::empty(),
585 stability: self.encode_stability(def_id),
586 deprecation: self.encode_deprecation(def_id),
588 ty: Some(self.encode_item_type(def_id)),
589 inherent_impls: LazySeq::empty(),
590 variances: LazySeq::empty(),
591 generics: Some(self.encode_generics(def_id)),
592 predicates: Some(self.encode_predicates(def_id)),
594 ast: ast.map(|body| self.encode_body(body)),
595 mir: if mir { self.encode_mir(def_id) } else { None },
599 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
600 -> LazySeq<ast::Name> {
601 let _ignore = self.tcx.dep_graph.in_ignore();
602 let body = self.tcx.hir.body(body_id);
603 self.lazy_seq(body.arguments.iter().map(|arg| {
605 PatKind::Binding(_, _, name, _) => name.node,
606 _ => Symbol::intern("")
611 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
612 -> LazySeq<ast::Name> {
613 self.lazy_seq(names.iter().map(|name| name.node))
616 fn encode_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
617 self.tcx.mir_map.borrow().get(&def_id).map(|mir| self.lazy(&*mir.borrow()))
620 // Encodes the inherent implementations of a structure, enumeration, or trait.
621 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
622 match self.tcx.inherent_impls.borrow().get(&def_id) {
623 None => LazySeq::empty(),
624 Some(implementations) => {
625 self.lazy_seq(implementations.iter().map(|&def_id| {
626 assert!(def_id.is_local());
633 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
634 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
637 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
638 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
641 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
644 debug!("encoding info for item at {}",
645 tcx.sess.codemap().span_to_string(item.span));
647 let kind = match item.node {
648 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
649 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
650 hir::ItemConst(..) => EntryKind::Const,
651 hir::ItemFn(_, _, constness, .., body) => {
653 constness: constness,
654 arg_names: self.encode_fn_arg_names_for_body(body),
657 EntryKind::Fn(self.lazy(&data))
659 hir::ItemMod(ref m) => {
660 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
662 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
663 hir::ItemTy(..) => EntryKind::Type,
664 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
665 hir::ItemStruct(ref struct_def, _) => {
666 let variant = tcx.lookup_adt_def(def_id).struct_variant();
668 // Encode def_ids for each field and method
669 // for methods, write all the stuff get_trait_method
671 let struct_ctor = if !struct_def.is_struct() {
672 Some(tcx.hir.local_def_id(struct_def.id()).index)
677 let repr_options = get_repr_options(&tcx, def_id);
679 EntryKind::Struct(self.lazy(&VariantData {
680 ctor_kind: variant.ctor_kind,
681 disr: variant.disr_val.to_u128_unchecked(),
682 struct_ctor: struct_ctor,
685 hir::ItemUnion(..) => {
686 let variant = tcx.lookup_adt_def(def_id).struct_variant();
687 let repr_options = get_repr_options(&tcx, def_id);
689 EntryKind::Union(self.lazy(&VariantData {
690 ctor_kind: variant.ctor_kind,
691 disr: variant.disr_val.to_u128_unchecked(),
695 hir::ItemDefaultImpl(..) => {
696 let data = ImplData {
697 polarity: hir::ImplPolarity::Positive,
699 coerce_unsized_kind: None,
700 trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref)),
703 EntryKind::DefaultImpl(self.lazy(&data))
705 hir::ItemImpl(_, polarity, ..) => {
706 let trait_ref = tcx.impl_trait_ref(def_id);
707 let parent = if let Some(trait_ref) = trait_ref {
708 let trait_def = tcx.lookup_trait_def(trait_ref.def_id);
709 trait_def.ancestors(def_id).skip(1).next().and_then(|node| {
711 specialization_graph::Node::Impl(parent) => Some(parent),
719 let data = ImplData {
722 coerce_unsized_kind: tcx.custom_coerce_unsized_kinds
726 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
729 EntryKind::Impl(self.lazy(&data))
731 hir::ItemTrait(..) => {
732 let trait_def = tcx.lookup_trait_def(def_id);
733 let data = TraitData {
734 unsafety: trait_def.unsafety,
735 paren_sugar: trait_def.paren_sugar,
736 has_default_impl: tcx.trait_has_default_impl(def_id),
737 super_predicates: self.lazy(&tcx.item_super_predicates(def_id)),
740 EntryKind::Trait(self.lazy(&data))
742 hir::ItemExternCrate(_) |
743 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
748 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
749 span: self.lazy(&item.span),
750 attributes: self.encode_attributes(&item.attrs),
751 children: match item.node {
752 hir::ItemForeignMod(ref fm) => {
753 self.lazy_seq(fm.items
755 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
757 hir::ItemEnum(..) => {
758 let def = self.tcx.lookup_adt_def(def_id);
759 self.lazy_seq(def.variants.iter().map(|v| {
760 assert!(v.did.is_local());
764 hir::ItemStruct(..) |
765 hir::ItemUnion(..) => {
766 let def = self.tcx.lookup_adt_def(def_id);
767 self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
768 assert!(f.did.is_local());
773 hir::ItemTrait(..) => {
774 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
775 assert!(def_id.is_local());
779 _ => LazySeq::empty(),
781 stability: self.encode_stability(def_id),
782 deprecation: self.encode_deprecation(def_id),
784 ty: match item.node {
785 hir::ItemStatic(..) |
790 hir::ItemStruct(..) |
792 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
795 inherent_impls: self.encode_inherent_implementations(def_id),
796 variances: match item.node {
798 hir::ItemStruct(..) |
800 hir::ItemTrait(..) => self.encode_item_variances(def_id),
801 _ => LazySeq::empty(),
803 generics: match item.node {
804 hir::ItemStatic(..) |
809 hir::ItemStruct(..) |
812 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
815 predicates: match item.node {
816 hir::ItemStatic(..) |
821 hir::ItemStruct(..) |
824 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
828 ast: match item.node {
829 hir::ItemConst(_, body) |
830 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
831 Some(self.encode_body(body))
835 mir: match item.node {
836 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
837 self.encode_mir(def_id)
839 hir::ItemConst(..) => self.encode_mir(def_id),
840 hir::ItemFn(_, _, constness, _, ref generics, _) => {
841 let tps_len = generics.ty_params.len();
842 let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
843 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
844 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
845 self.encode_mir(def_id)
855 /// Serialize the text of exported macros
856 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
858 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
859 body: ::syntax::print::pprust::tts_to_string(¯o_def.body)
861 visibility: self.lazy(&ty::Visibility::Public),
862 span: self.lazy(¯o_def.span),
864 attributes: self.encode_attributes(¯o_def.attrs),
865 children: LazySeq::empty(),
869 inherent_impls: LazySeq::empty(),
870 variances: LazySeq::empty(),
879 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
880 /// In some cases, along with the item itself, we also
881 /// encode some sub-items. Usually we want some info from the item
882 /// so it's easier to do that here then to wait until we would encounter
883 /// normally in the visitor walk.
884 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
885 let def_id = self.tcx.hir.local_def_id(item.id);
887 hir::ItemStatic(..) |
891 hir::ItemForeignMod(..) |
892 hir::ItemExternCrate(..) |
894 hir::ItemDefaultImpl(..) |
896 // no sub-item recording needed in these cases
898 hir::ItemEnum(..) => {
899 self.encode_fields(def_id);
901 let def = self.tcx.lookup_adt_def(def_id);
902 for (i, variant) in def.variants.iter().enumerate() {
903 self.record(variant.did,
904 EncodeContext::encode_enum_variant_info,
905 (def_id, Untracked(i)));
908 hir::ItemStruct(ref struct_def, _) => {
909 self.encode_fields(def_id);
911 // If the struct has a constructor, encode it.
912 if !struct_def.is_struct() {
913 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
914 self.record(ctor_def_id,
915 EncodeContext::encode_struct_ctor,
916 (def_id, ctor_def_id));
919 hir::ItemUnion(..) => {
920 self.encode_fields(def_id);
922 hir::ItemImpl(..) => {
923 for &trait_item_def_id in &self.tcx.associated_item_def_ids(def_id)[..] {
924 self.record(trait_item_def_id,
925 EncodeContext::encode_info_for_impl_item,
929 hir::ItemTrait(..) => {
930 for &item_def_id in &self.tcx.associated_item_def_ids(def_id)[..] {
931 self.record(item_def_id,
932 EncodeContext::encode_info_for_trait_item,
940 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
941 fn encode_info_for_foreign_item(&mut self,
942 (def_id, nitem): (DefId, &hir::ForeignItem))
946 debug!("writing foreign item {}", tcx.node_path_str(nitem.id));
948 let kind = match nitem.node {
949 hir::ForeignItemFn(_, ref names, _) => {
951 constness: hir::Constness::NotConst,
952 arg_names: self.encode_fn_arg_names(names),
954 EntryKind::ForeignFn(self.lazy(&data))
956 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
957 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
962 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
963 span: self.lazy(&nitem.span),
964 attributes: self.encode_attributes(&nitem.attrs),
965 children: LazySeq::empty(),
966 stability: self.encode_stability(def_id),
967 deprecation: self.encode_deprecation(def_id),
969 ty: Some(self.encode_item_type(def_id)),
970 inherent_impls: LazySeq::empty(),
971 variances: LazySeq::empty(),
972 generics: Some(self.encode_generics(def_id)),
973 predicates: Some(self.encode_predicates(def_id)),
981 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
982 index: IndexBuilder<'a, 'b, 'tcx>,
985 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
986 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
987 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
989 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
990 intravisit::walk_expr(self, ex);
991 self.index.encode_info_for_expr(ex);
993 fn visit_item(&mut self, item: &'tcx hir::Item) {
994 intravisit::walk_item(self, item);
995 let def_id = self.index.tcx.hir.local_def_id(item.id);
997 hir::ItemExternCrate(_) |
998 hir::ItemUse(..) => (), // ignore these
999 _ => self.index.record(def_id, EncodeContext::encode_info_for_item, (def_id, item)),
1001 self.index.encode_addl_info_for_item(item);
1003 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1004 intravisit::walk_foreign_item(self, ni);
1005 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1006 self.index.record(def_id,
1007 EncodeContext::encode_info_for_foreign_item,
1010 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1011 intravisit::walk_ty(self, ty);
1012 self.index.encode_info_for_ty(ty);
1014 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1015 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1016 self.index.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def);
1020 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1021 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1022 if let hir::TyImplTrait(_) = ty.node {
1023 let def_id = self.tcx.hir.local_def_id(ty.id);
1024 self.record(def_id, EncodeContext::encode_info_for_anon_ty, def_id);
1028 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1030 hir::ExprClosure(..) => {
1031 let def_id = self.tcx.hir.local_def_id(expr.id);
1032 self.record(def_id, EncodeContext::encode_info_for_closure, def_id);
1039 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1040 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1043 kind: EntryKind::Type,
1044 visibility: self.lazy(&ty::Visibility::Public),
1045 span: self.lazy(&tcx.def_span(def_id)),
1046 attributes: LazySeq::empty(),
1047 children: LazySeq::empty(),
1051 ty: Some(self.encode_item_type(def_id)),
1052 inherent_impls: LazySeq::empty(),
1053 variances: LazySeq::empty(),
1054 generics: Some(self.encode_generics(def_id)),
1055 predicates: Some(self.encode_predicates(def_id)),
1062 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1065 let data = ClosureData {
1066 kind: tcx.closure_kind(def_id),
1067 ty: self.lazy(&tcx.closure_tys.borrow()[&def_id]),
1071 kind: EntryKind::Closure(self.lazy(&data)),
1072 visibility: self.lazy(&ty::Visibility::Public),
1073 span: self.lazy(&tcx.def_span(def_id)),
1074 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1075 children: LazySeq::empty(),
1079 ty: Some(self.encode_item_type(def_id)),
1080 inherent_impls: LazySeq::empty(),
1081 variances: LazySeq::empty(),
1082 generics: Some(self.encode_generics(def_id)),
1086 mir: self.encode_mir(def_id),
1090 fn encode_info_for_items(&mut self) -> Index {
1091 let krate = self.tcx.hir.krate();
1092 let mut index = IndexBuilder::new(self);
1093 index.record(DefId::local(CRATE_DEF_INDEX),
1094 EncodeContext::encode_info_for_mod,
1095 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
1096 let mut visitor = EncodeVisitor { index: index };
1097 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
1098 for macro_def in &krate.exported_macros {
1099 visitor.visit_macro_def(macro_def);
1101 visitor.index.into_items()
1104 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1105 self.lazy_seq_ref(attrs)
1108 fn encode_crate_deps(&mut self) -> LazySeq<CrateDep> {
1109 fn get_ordered_deps(cstore: &cstore::CStore) -> Vec<(CrateNum, Rc<cstore::CrateMetadata>)> {
1110 // Pull the cnums and name,vers,hash out of cstore
1111 let mut deps = Vec::new();
1112 cstore.iter_crate_data(|cnum, val| {
1113 deps.push((cnum, val.clone()));
1117 deps.sort_by(|kv1, kv2| kv1.0.cmp(&kv2.0));
1119 // Sanity-check the crate numbers
1120 let mut expected_cnum = 1;
1121 for &(n, _) in &deps {
1122 assert_eq!(n, CrateNum::new(expected_cnum));
1129 // We're just going to write a list of crate 'name-hash-version's, with
1130 // the assumption that they are numbered 1 to n.
1131 // FIXME (#2166): This is not nearly enough to support correct versioning
1132 // but is enough to get transitive crate dependencies working.
1133 let deps = get_ordered_deps(self.cstore);
1134 self.lazy_seq(deps.iter().map(|&(_, ref dep)| {
1138 kind: dep.dep_kind.get(),
1143 fn encode_lang_items(&mut self) -> (LazySeq<(DefIndex, usize)>, LazySeq<lang_items::LangItem>) {
1145 let lang_items = tcx.lang_items.items().iter();
1146 (self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1147 if let Some(def_id) = opt_def_id {
1148 if def_id.is_local() {
1149 return Some((def_id.index, i));
1154 self.lazy_seq_ref(&tcx.lang_items.missing))
1157 fn encode_native_libraries(&mut self) -> LazySeq<NativeLibrary> {
1158 let used_libraries = self.tcx.sess.cstore.used_libraries();
1159 self.lazy_seq(used_libraries)
1162 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
1163 let codemap = self.tcx.sess.codemap();
1164 let all_filemaps = codemap.files.borrow();
1165 self.lazy_seq_ref(all_filemaps.iter()
1167 // No need to re-export imported filemaps, as any downstream
1168 // crate will import them from their original source.
1169 !filemap.is_imported()
1171 .map(|filemap| &**filemap))
1174 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
1175 let definitions = self.tcx.hir.definitions();
1176 self.lazy(definitions.def_path_table())
1180 struct ImplVisitor<'a, 'tcx: 'a> {
1181 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1182 impls: FxHashMap<DefId, Vec<DefIndex>>,
1185 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1186 fn visit_item(&mut self, item: &hir::Item) {
1187 if let hir::ItemImpl(..) = item.node {
1188 let impl_id = self.tcx.hir.local_def_id(item.id);
1189 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1191 .entry(trait_ref.def_id)
1193 .push(impl_id.index);
1198 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1200 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1201 // handled in `visit_item` above
1205 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1206 /// Encodes an index, mapping each trait to its (local) implementations.
1207 fn encode_impls(&mut self) -> LazySeq<TraitImpls> {
1208 let mut visitor = ImplVisitor {
1212 self.tcx.hir.krate().visit_all_item_likes(&mut visitor);
1214 let all_impls: Vec<_> = visitor.impls
1216 .map(|(trait_def_id, impls)| {
1218 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1219 impls: self.lazy_seq(impls),
1224 self.lazy_seq(all_impls)
1227 // Encodes all symbols exported from this crate into the metadata.
1229 // This pass is seeded off the reachability list calculated in the
1230 // middle::reachable module but filters out items that either don't have a
1231 // symbol associated with them (they weren't translated) or if they're an FFI
1232 // definition (as that's not defined in this crate).
1233 fn encode_exported_symbols(&mut self) -> LazySeq<DefIndex> {
1234 let exported_symbols = self.exported_symbols;
1236 self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
1239 fn encode_dylib_dependency_formats(&mut self) -> LazySeq<Option<LinkagePreference>> {
1240 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1242 self.lazy_seq(arr.iter().map(|slot| {
1244 Linkage::NotLinked |
1245 Linkage::IncludedFromDylib => None,
1247 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1248 Linkage::Static => Some(LinkagePreference::RequireStatic),
1252 None => LazySeq::empty(),
1256 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
1257 let mut i = self.position();
1258 let crate_deps = self.encode_crate_deps();
1259 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
1260 let dep_bytes = self.position() - i;
1262 // Encode the language items.
1263 i = self.position();
1264 let (lang_items, lang_items_missing) = self.encode_lang_items();
1265 let lang_item_bytes = self.position() - i;
1267 // Encode the native libraries used
1268 i = self.position();
1269 let native_libraries = self.encode_native_libraries();
1270 let native_lib_bytes = self.position() - i;
1273 i = self.position();
1274 let codemap = self.encode_codemap();
1275 let codemap_bytes = self.position() - i;
1277 // Encode DefPathTable
1278 i = self.position();
1279 let def_path_table = self.encode_def_path_table();
1280 let def_path_table_bytes = self.position() - i;
1282 // Encode the def IDs of impls, for coherence checking.
1283 i = self.position();
1284 let impls = self.encode_impls();
1285 let impl_bytes = self.position() - i;
1287 // Encode exported symbols info.
1288 i = self.position();
1289 let exported_symbols = self.encode_exported_symbols();
1290 let exported_symbols_bytes = self.position() - i;
1292 // Encode and index the items.
1293 i = self.position();
1294 let items = self.encode_info_for_items();
1295 let item_bytes = self.position() - i;
1297 i = self.position();
1298 let index = items.write_index(&mut self.opaque.cursor);
1299 let index_bytes = self.position() - i;
1302 let link_meta = self.link_meta;
1303 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
1304 let root = self.lazy(&CrateRoot {
1305 name: link_meta.crate_name,
1306 triple: tcx.sess.opts.target_triple.clone(),
1307 hash: link_meta.crate_hash,
1308 disambiguator: tcx.sess.local_crate_disambiguator(),
1309 panic_strategy: tcx.sess.panic_strategy(),
1310 plugin_registrar_fn: tcx.sess
1311 .plugin_registrar_fn
1313 .map(|id| tcx.hir.local_def_id(id).index),
1314 macro_derive_registrar: if is_proc_macro {
1315 let id = tcx.sess.derive_registrar_fn.get().unwrap();
1316 Some(tcx.hir.local_def_id(id).index)
1321 crate_deps: crate_deps,
1322 dylib_dependency_formats: dylib_dependency_formats,
1323 lang_items: lang_items,
1324 lang_items_missing: lang_items_missing,
1325 native_libraries: native_libraries,
1327 def_path_table: def_path_table,
1329 exported_symbols: exported_symbols,
1333 let total_bytes = self.position();
1335 if self.tcx.sess.meta_stats() {
1336 let mut zero_bytes = 0;
1337 for e in self.opaque.cursor.get_ref() {
1343 println!("metadata stats:");
1344 println!(" dep bytes: {}", dep_bytes);
1345 println!(" lang item bytes: {}", lang_item_bytes);
1346 println!(" native bytes: {}", native_lib_bytes);
1347 println!(" codemap bytes: {}", codemap_bytes);
1348 println!(" impl bytes: {}", impl_bytes);
1349 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
1350 println!(" def-path table bytes: {}", def_path_table_bytes);
1351 println!(" item bytes: {}", item_bytes);
1352 println!(" index bytes: {}", index_bytes);
1353 println!(" zero bytes: {}", zero_bytes);
1354 println!(" total bytes: {}", total_bytes);
1361 // NOTE(eddyb) The following comment was preserved for posterity, even
1362 // though it's no longer relevant as EBML (which uses nested & tagged
1363 // "documents") was replaced with a scheme that can't go out of bounds.
1365 // And here we run into yet another obscure archive bug: in which metadata
1366 // loaded from archives may have trailing garbage bytes. Awhile back one of
1367 // our tests was failing sporadically on the OSX 64-bit builders (both nopt
1368 // and opt) by having ebml generate an out-of-bounds panic when looking at
1371 // Upon investigation it turned out that the metadata file inside of an rlib
1372 // (and ar archive) was being corrupted. Some compilations would generate a
1373 // metadata file which would end in a few extra bytes, while other
1374 // compilations would not have these extra bytes appended to the end. These
1375 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1376 // being interpreted causing the out-of-bounds.
1378 // The root cause of why these extra bytes were appearing was never
1379 // discovered, and in the meantime the solution we're employing is to insert
1380 // the length of the metadata to the start of the metadata. Later on this
1381 // will allow us to slice the metadata to the precise length that we just
1382 // generated regardless of trailing bytes that end up in it.
1384 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1385 cstore: &cstore::CStore,
1386 reexports: &def::ExportMap,
1387 link_meta: &LinkMeta,
1388 exported_symbols: &NodeSet)
1390 let mut cursor = Cursor::new(vec![]);
1391 cursor.write_all(METADATA_HEADER).unwrap();
1393 // Will be filed with the root position after encoding everything.
1394 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1397 let mut ecx = EncodeContext {
1398 opaque: opaque::Encoder::new(&mut cursor),
1400 reexports: reexports,
1401 link_meta: link_meta,
1403 exported_symbols: exported_symbols,
1404 lazy_state: LazyState::NoNode,
1405 type_shorthands: Default::default(),
1406 predicate_shorthands: Default::default(),
1409 // Encode the rustc version string in a predictable location.
1410 rustc_version().encode(&mut ecx).unwrap();
1412 // Encode all the entries and extra information in the crate,
1413 // culminating in the `CrateRoot` which points to all of it.
1414 ecx.encode_crate_root()
1416 let mut result = cursor.into_inner();
1418 // Encode the root position.
1419 let header = METADATA_HEADER.len();
1420 let pos = root.position;
1421 result[header + 0] = (pos >> 24) as u8;
1422 result[header + 1] = (pos >> 16) as u8;
1423 result[header + 2] = (pos >> 8) as u8;
1424 result[header + 3] = (pos >> 0) as u8;
1429 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1430 let ty = tcx.item_type(did);
1432 ty::TyAdt(ref def, _) => return def.repr,
1433 _ => bug!("{} is not an ADT", ty),