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};
16 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId};
17 use rustc::hir::map::definitions::DefPathTable;
18 use rustc::middle::dependency_format::Linkage;
19 use rustc::middle::lang_items;
21 use rustc::traits::specialization_graph;
22 use rustc::ty::{self, Ty, TyCtxt, ReprOptions};
24 use rustc::session::config::{self, CrateTypeProcMacro};
25 use rustc::util::nodemap::{FxHashMap, NodeSet};
27 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
30 use std::io::prelude::*;
34 use syntax::ast::{self, CRATE_NODE_ID};
35 use syntax::codemap::Spanned;
37 use syntax::symbol::Symbol;
38 use syntax_pos::{self, DUMMY_SP};
40 use rustc::hir::{self, PatKind};
41 use rustc::hir::itemlikevisit::ItemLikeVisitor;
42 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
43 use rustc::hir::intravisit;
45 use super::index_builder::{FromId, IndexBuilder, Untracked};
47 pub struct EncodeContext<'a, 'tcx: 'a> {
48 opaque: opaque::Encoder<'a>,
49 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
50 link_meta: &'a LinkMeta,
51 cstore: &'a cstore::CStore,
52 exported_symbols: &'a NodeSet,
54 lazy_state: LazyState,
55 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
56 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
59 macro_rules! encoder_methods {
60 ($($name:ident($ty:ty);)*) => {
61 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
62 self.opaque.$name(value)
67 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
68 type Error = <opaque::Encoder<'a> as Encoder>::Error;
70 fn emit_nil(&mut self) -> Result<(), Self::Error> {
97 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
98 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
99 self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
103 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
104 fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
105 self.emit_usize(seq.len)?;
109 self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
113 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
114 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
115 self.encode_with_shorthand(ty, &ty.sty, |ecx| &mut ecx.type_shorthands)
119 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
120 fn specialized_encode(&mut self,
121 predicates: &ty::GenericPredicates<'tcx>)
122 -> Result<(), Self::Error> {
123 predicates.parent.encode(self)?;
124 predicates.predicates.len().encode(self)?;
125 for predicate in &predicates.predicates {
126 self.encode_with_shorthand(predicate, predicate, |ecx| &mut ecx.predicate_shorthands)?
132 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
133 pub fn position(&self) -> usize {
134 self.opaque.position()
137 fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
138 assert_eq!(self.lazy_state, LazyState::NoNode);
139 let pos = self.position();
140 self.lazy_state = LazyState::NodeStart(pos);
141 let r = f(self, pos);
142 self.lazy_state = LazyState::NoNode;
146 fn emit_lazy_distance(&mut self,
149 -> Result<(), <Self as Encoder>::Error> {
150 let min_end = position + min_size;
151 let distance = match self.lazy_state {
152 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
153 LazyState::NodeStart(start) => {
154 assert!(min_end <= start);
157 LazyState::Previous(last_min_end) => {
158 assert!(last_min_end <= position);
159 position - last_min_end
162 self.lazy_state = LazyState::Previous(min_end);
163 self.emit_usize(distance)
166 pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
167 self.emit_node(|ecx, pos| {
168 value.encode(ecx).unwrap();
170 assert!(pos + Lazy::<T>::min_size() <= ecx.position());
171 Lazy::with_position(pos)
175 fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
176 where I: IntoIterator<Item = T>,
179 self.emit_node(|ecx, pos| {
180 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
182 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
183 LazySeq::with_position_and_length(pos, len)
187 fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
188 where I: IntoIterator<Item = &'b T>,
191 self.emit_node(|ecx, pos| {
192 let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
194 assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
195 LazySeq::with_position_and_length(pos, len)
199 /// Encode the given value or a previously cached shorthand.
200 fn encode_with_shorthand<T, U, M>(&mut self,
204 -> Result<(), <Self as Encoder>::Error>
205 where M: for<'b> Fn(&'b mut Self) -> &'b mut FxHashMap<T, usize>,
206 T: Clone + Eq + Hash,
209 let existing_shorthand = map(self).get(value).cloned();
210 if let Some(shorthand) = existing_shorthand {
211 return self.emit_usize(shorthand);
214 let start = self.position();
215 variant.encode(self)?;
216 let len = self.position() - start;
218 // The shorthand encoding uses the same usize as the
219 // discriminant, with an offset so they can't conflict.
220 let discriminant = unsafe { intrinsics::discriminant_value(variant) };
221 assert!(discriminant < SHORTHAND_OFFSET as u64);
222 let shorthand = start + SHORTHAND_OFFSET;
224 // Get the number of bits that leb128 could fit
225 // in the same space as the fully encoded type.
226 let leb128_bits = len * 7;
228 // Check that the shorthand is a not longer than the
229 // full encoding itself, i.e. it's an obvious win.
230 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
231 map(self).insert(value.clone(), shorthand);
237 fn encode_item_variances(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
239 self.lazy_seq(tcx.item_variances(def_id).iter().cloned())
242 fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
244 self.lazy(&tcx.item_type(def_id))
247 /// Encode data for the given variant of the given ADT. The
248 /// index of the variant is untracked: this is ok because we
249 /// will have to lookup the adt-def by its id, and that gives us
250 /// the right to access any information in the adt-def (including,
251 /// e.g., the length of the various vectors).
252 fn encode_enum_variant_info(&mut self,
253 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
256 let def = tcx.lookup_adt_def(enum_did);
257 let variant = &def.variants[index];
258 let def_id = variant.did;
260 let data = VariantData {
261 ctor_kind: variant.ctor_kind,
262 discr: variant.discr,
263 evaluated_discr: match variant.discr {
264 ty::VariantDiscr::Explicit(def_id) => {
265 ty::queries::monomorphic_const_eval::get(tcx, DUMMY_SP, def_id).ok()
267 ty::VariantDiscr::Relative(_) => None
272 let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
273 let enum_vis = &tcx.hir.expect_item(enum_id).vis;
276 kind: EntryKind::Variant(self.lazy(&data)),
277 visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
278 span: self.lazy(&tcx.def_span(def_id)),
279 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
280 children: self.lazy_seq(variant.fields.iter().map(|f| {
281 assert!(f.did.is_local());
284 stability: self.encode_stability(def_id),
285 deprecation: self.encode_deprecation(def_id),
287 ty: Some(self.encode_item_type(def_id)),
288 inherent_impls: LazySeq::empty(),
289 variances: LazySeq::empty(),
290 generics: Some(self.encode_generics(def_id)),
291 predicates: Some(self.encode_predicates(def_id)),
294 mir: self.encode_mir(def_id),
298 fn encode_info_for_mod(&mut self,
299 FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
304 let def_id = tcx.hir.local_def_id(id);
307 reexports: match tcx.export_map.get(&id) {
308 Some(exports) if *vis == hir::Public => self.lazy_seq_ref(exports),
309 _ => LazySeq::empty(),
314 kind: EntryKind::Mod(self.lazy(&data)),
315 visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
316 span: self.lazy(&md.inner),
317 attributes: self.encode_attributes(attrs),
318 children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
319 tcx.hir.local_def_id(item_id.id).index
321 stability: self.encode_stability(def_id),
322 deprecation: self.encode_deprecation(def_id),
325 inherent_impls: LazySeq::empty(),
326 variances: LazySeq::empty(),
336 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
337 fn encode_fields(&mut self, adt_def_id: DefId) {
338 let def = self.tcx.lookup_adt_def(adt_def_id);
339 for (variant_index, variant) in def.variants.iter().enumerate() {
340 for (field_index, field) in variant.fields.iter().enumerate() {
341 self.record(field.did,
342 EncodeContext::encode_field,
343 (adt_def_id, Untracked((variant_index, field_index))));
349 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
350 /// Encode data for the given field of the given variant of the
351 /// given ADT. The indices of the variant/field are untracked:
352 /// this is ok because we will have to lookup the adt-def by its
353 /// id, and that gives us the right to access any information in
354 /// the adt-def (including, e.g., the length of the various
356 fn encode_field(&mut self,
357 (adt_def_id, Untracked((variant_index, field_index))): (DefId,
362 let variant = &tcx.lookup_adt_def(adt_def_id).variants[variant_index];
363 let field = &variant.fields[field_index];
365 let def_id = field.did;
366 let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
367 let variant_data = tcx.hir.expect_variant_data(variant_id);
370 kind: EntryKind::Field,
371 visibility: self.lazy(&field.vis),
372 span: self.lazy(&tcx.def_span(def_id)),
373 attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
374 children: LazySeq::empty(),
375 stability: self.encode_stability(def_id),
376 deprecation: self.encode_deprecation(def_id),
378 ty: Some(self.encode_item_type(def_id)),
379 inherent_impls: LazySeq::empty(),
380 variances: LazySeq::empty(),
381 generics: Some(self.encode_generics(def_id)),
382 predicates: Some(self.encode_predicates(def_id)),
389 fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
391 let variant = tcx.lookup_adt_def(adt_def_id).struct_variant();
393 let data = VariantData {
394 ctor_kind: variant.ctor_kind,
395 discr: variant.discr,
396 evaluated_discr: None,
397 struct_ctor: Some(def_id.index),
400 let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
401 let struct_vis = &tcx.hir.expect_item(struct_id).vis;
402 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
403 for field in &variant.fields {
404 if ctor_vis.is_at_least(field.vis, tcx) {
405 ctor_vis = field.vis;
409 let repr_options = get_repr_options(&tcx, adt_def_id);
412 kind: EntryKind::Struct(self.lazy(&data), repr_options),
413 visibility: self.lazy(&ctor_vis),
414 span: self.lazy(&tcx.def_span(def_id)),
415 attributes: LazySeq::empty(),
416 children: LazySeq::empty(),
417 stability: self.encode_stability(def_id),
418 deprecation: self.encode_deprecation(def_id),
420 ty: Some(self.encode_item_type(def_id)),
421 inherent_impls: LazySeq::empty(),
422 variances: LazySeq::empty(),
423 generics: Some(self.encode_generics(def_id)),
424 predicates: Some(self.encode_predicates(def_id)),
427 mir: self.encode_mir(def_id),
431 fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
433 self.lazy(tcx.item_generics(def_id))
436 fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
438 self.lazy(&tcx.item_predicates(def_id))
441 fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
444 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
445 let ast_item = tcx.hir.expect_trait_item(node_id);
446 let trait_item = tcx.associated_item(def_id);
448 let container = match trait_item.defaultness {
449 hir::Defaultness::Default { has_value: true } =>
450 AssociatedContainer::TraitWithDefault,
451 hir::Defaultness::Default { has_value: false } =>
452 AssociatedContainer::TraitRequired,
453 hir::Defaultness::Final =>
454 span_bug!(ast_item.span, "traits cannot have final items"),
457 let kind = match trait_item.kind {
458 ty::AssociatedKind::Const => {
459 EntryKind::AssociatedConst(container, 0)
461 ty::AssociatedKind::Method => {
462 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
463 let arg_names = match *m {
464 hir::TraitMethod::Required(ref names) => {
465 self.encode_fn_arg_names(names)
467 hir::TraitMethod::Provided(body) => {
468 self.encode_fn_arg_names_for_body(body)
472 constness: hir::Constness::NotConst,
478 EntryKind::Method(self.lazy(&MethodData {
480 container: container,
481 has_self: trait_item.method_has_self_argument,
484 ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
489 visibility: self.lazy(&trait_item.vis),
490 span: self.lazy(&ast_item.span),
491 attributes: self.encode_attributes(&ast_item.attrs),
492 children: LazySeq::empty(),
493 stability: self.encode_stability(def_id),
494 deprecation: self.encode_deprecation(def_id),
496 ty: match trait_item.kind {
497 ty::AssociatedKind::Const |
498 ty::AssociatedKind::Method => {
499 Some(self.encode_item_type(def_id))
501 ty::AssociatedKind::Type => {
502 if trait_item.defaultness.has_value() {
503 Some(self.encode_item_type(def_id))
509 inherent_impls: LazySeq::empty(),
510 variances: LazySeq::empty(),
511 generics: Some(self.encode_generics(def_id)),
512 predicates: Some(self.encode_predicates(def_id)),
514 ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
515 Some(self.encode_body(body))
519 mir: self.encode_mir(def_id),
523 fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
524 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
525 let ast_item = self.tcx.hir.expect_impl_item(node_id);
526 let impl_item = self.tcx.associated_item(def_id);
528 let container = match impl_item.defaultness {
529 hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
530 hir::Defaultness::Final => AssociatedContainer::ImplFinal,
531 hir::Defaultness::Default { has_value: false } =>
532 span_bug!(ast_item.span, "impl items always have values (currently)"),
535 let kind = match impl_item.kind {
536 ty::AssociatedKind::Const => {
537 EntryKind::AssociatedConst(container,
538 ty::queries::mir_const_qualif::get(self.tcx, ast_item.span, def_id))
540 ty::AssociatedKind::Method => {
541 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
543 constness: sig.constness,
544 arg_names: self.encode_fn_arg_names_for_body(body),
549 EntryKind::Method(self.lazy(&MethodData {
551 container: container,
552 has_self: impl_item.method_has_self_argument,
555 ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
558 let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
560 } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
561 let generics = self.tcx.item_generics(def_id);
562 let types = generics.parent_types as usize + generics.types.len();
563 let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
564 let is_const_fn = sig.constness == hir::Constness::Const;
565 let ast = if is_const_fn { Some(body) } else { None };
566 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
567 (ast, needs_inline || is_const_fn || always_encode_mir)
574 visibility: self.lazy(&impl_item.vis),
575 span: self.lazy(&ast_item.span),
576 attributes: self.encode_attributes(&ast_item.attrs),
577 children: LazySeq::empty(),
578 stability: self.encode_stability(def_id),
579 deprecation: self.encode_deprecation(def_id),
581 ty: Some(self.encode_item_type(def_id)),
582 inherent_impls: LazySeq::empty(),
583 variances: LazySeq::empty(),
584 generics: Some(self.encode_generics(def_id)),
585 predicates: Some(self.encode_predicates(def_id)),
587 ast: ast.map(|body| self.encode_body(body)),
588 mir: if mir { self.encode_mir(def_id) } else { None },
592 fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
593 -> LazySeq<ast::Name> {
594 let _ignore = self.tcx.dep_graph.in_ignore();
595 let body = self.tcx.hir.body(body_id);
596 self.lazy_seq(body.arguments.iter().map(|arg| {
598 PatKind::Binding(_, _, name, _) => name.node,
599 _ => Symbol::intern("")
604 fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
605 -> LazySeq<ast::Name> {
606 self.lazy_seq(names.iter().map(|name| name.node))
609 fn encode_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
610 self.tcx.maps.mir.borrow().get(&def_id).map(|mir| self.lazy(&*mir.borrow()))
613 // Encodes the inherent implementations of a structure, enumeration, or trait.
614 fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
615 match self.tcx.maps.inherent_impls.borrow().get(&def_id) {
616 None => LazySeq::empty(),
617 Some(implementations) => {
618 self.lazy_seq(implementations.iter().map(|&def_id| {
619 assert!(def_id.is_local());
626 fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
627 self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
630 fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
631 self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
634 fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
637 debug!("encoding info for item at {}",
638 tcx.sess.codemap().span_to_string(item.span));
640 let kind = match item.node {
641 hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
642 hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
643 hir::ItemConst(..) => {
644 EntryKind::Const(ty::queries::mir_const_qualif::get(tcx, item.span, def_id))
646 hir::ItemFn(_, _, constness, .., body) => {
648 constness: constness,
649 arg_names: self.encode_fn_arg_names_for_body(body),
652 EntryKind::Fn(self.lazy(&data))
654 hir::ItemMod(ref m) => {
655 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
657 hir::ItemForeignMod(_) => EntryKind::ForeignMod,
658 hir::ItemTy(..) => EntryKind::Type,
659 hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
660 hir::ItemStruct(ref struct_def, _) => {
661 let variant = tcx.lookup_adt_def(def_id).struct_variant();
663 // Encode def_ids for each field and method
664 // for methods, write all the stuff get_trait_method
666 let struct_ctor = if !struct_def.is_struct() {
667 Some(tcx.hir.local_def_id(struct_def.id()).index)
672 let repr_options = get_repr_options(&tcx, def_id);
674 EntryKind::Struct(self.lazy(&VariantData {
675 ctor_kind: variant.ctor_kind,
676 discr: variant.discr,
677 evaluated_discr: None,
678 struct_ctor: struct_ctor,
681 hir::ItemUnion(..) => {
682 let variant = tcx.lookup_adt_def(def_id).struct_variant();
683 let repr_options = get_repr_options(&tcx, def_id);
685 EntryKind::Union(self.lazy(&VariantData {
686 ctor_kind: variant.ctor_kind,
687 discr: variant.discr,
688 evaluated_discr: None,
692 hir::ItemDefaultImpl(..) => {
693 let data = ImplData {
694 polarity: hir::ImplPolarity::Positive,
696 coerce_unsized_kind: None,
697 trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref)),
700 EntryKind::DefaultImpl(self.lazy(&data))
702 hir::ItemImpl(_, polarity, ..) => {
703 let trait_ref = tcx.impl_trait_ref(def_id);
704 let parent = if let Some(trait_ref) = trait_ref {
705 let trait_def = tcx.lookup_trait_def(trait_ref.def_id);
706 trait_def.ancestors(def_id).skip(1).next().and_then(|node| {
708 specialization_graph::Node::Impl(parent) => Some(parent),
716 let data = ImplData {
719 coerce_unsized_kind: tcx.maps.custom_coerce_unsized_kind
723 trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
726 EntryKind::Impl(self.lazy(&data))
728 hir::ItemTrait(..) => {
729 let trait_def = tcx.lookup_trait_def(def_id);
730 let data = TraitData {
731 unsafety: trait_def.unsafety,
732 paren_sugar: trait_def.paren_sugar,
733 has_default_impl: tcx.trait_has_default_impl(def_id),
734 super_predicates: self.lazy(&tcx.item_super_predicates(def_id)),
737 EntryKind::Trait(self.lazy(&data))
739 hir::ItemExternCrate(_) |
740 hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
745 visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
746 span: self.lazy(&item.span),
747 attributes: self.encode_attributes(&item.attrs),
748 children: match item.node {
749 hir::ItemForeignMod(ref fm) => {
750 self.lazy_seq(fm.items
752 .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
754 hir::ItemEnum(..) => {
755 let def = self.tcx.lookup_adt_def(def_id);
756 self.lazy_seq(def.variants.iter().map(|v| {
757 assert!(v.did.is_local());
761 hir::ItemStruct(..) |
762 hir::ItemUnion(..) => {
763 let def = self.tcx.lookup_adt_def(def_id);
764 self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
765 assert!(f.did.is_local());
770 hir::ItemTrait(..) => {
771 self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
772 assert!(def_id.is_local());
776 _ => LazySeq::empty(),
778 stability: self.encode_stability(def_id),
779 deprecation: self.encode_deprecation(def_id),
781 ty: match item.node {
782 hir::ItemStatic(..) |
787 hir::ItemStruct(..) |
789 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
792 inherent_impls: self.encode_inherent_implementations(def_id),
793 variances: match item.node {
795 hir::ItemStruct(..) |
797 hir::ItemTrait(..) => self.encode_item_variances(def_id),
798 _ => LazySeq::empty(),
800 generics: match item.node {
801 hir::ItemStatic(..) |
806 hir::ItemStruct(..) |
809 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
812 predicates: match item.node {
813 hir::ItemStatic(..) |
818 hir::ItemStruct(..) |
821 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
825 ast: match item.node {
826 hir::ItemConst(_, body) |
827 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
828 Some(self.encode_body(body))
832 mir: match item.node {
833 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
834 self.encode_mir(def_id)
836 hir::ItemConst(..) => self.encode_mir(def_id),
837 hir::ItemFn(_, _, constness, _, ref generics, _) => {
838 let tps_len = generics.ty_params.len();
839 let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
840 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
841 if needs_inline || constness == hir::Constness::Const || always_encode_mir {
842 self.encode_mir(def_id)
852 /// Serialize the text of exported macros
853 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
854 use syntax::print::pprust;
856 kind: EntryKind::MacroDef(self.lazy(&MacroDef {
857 body: pprust::tts_to_string(¯o_def.body.trees().collect::<Vec<_>>()),
859 visibility: self.lazy(&ty::Visibility::Public),
860 span: self.lazy(¯o_def.span),
862 attributes: self.encode_attributes(¯o_def.attrs),
863 children: LazySeq::empty(),
867 inherent_impls: LazySeq::empty(),
868 variances: LazySeq::empty(),
877 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
878 /// In some cases, along with the item itself, we also
879 /// encode some sub-items. Usually we want some info from the item
880 /// so it's easier to do that here then to wait until we would encounter
881 /// normally in the visitor walk.
882 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
883 let def_id = self.tcx.hir.local_def_id(item.id);
885 hir::ItemStatic(..) |
889 hir::ItemForeignMod(..) |
890 hir::ItemExternCrate(..) |
892 hir::ItemDefaultImpl(..) |
894 // no sub-item recording needed in these cases
896 hir::ItemEnum(..) => {
897 self.encode_fields(def_id);
899 let def = self.tcx.lookup_adt_def(def_id);
900 for (i, variant) in def.variants.iter().enumerate() {
901 self.record(variant.did,
902 EncodeContext::encode_enum_variant_info,
903 (def_id, Untracked(i)));
906 hir::ItemStruct(ref struct_def, _) => {
907 self.encode_fields(def_id);
909 // If the struct has a constructor, encode it.
910 if !struct_def.is_struct() {
911 let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
912 self.record(ctor_def_id,
913 EncodeContext::encode_struct_ctor,
914 (def_id, ctor_def_id));
917 hir::ItemUnion(..) => {
918 self.encode_fields(def_id);
920 hir::ItemImpl(..) => {
921 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
922 self.record(trait_item_def_id,
923 EncodeContext::encode_info_for_impl_item,
927 hir::ItemTrait(..) => {
928 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
929 self.record(item_def_id,
930 EncodeContext::encode_info_for_trait_item,
938 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
939 fn encode_info_for_foreign_item(&mut self,
940 (def_id, nitem): (DefId, &hir::ForeignItem))
944 debug!("writing foreign item {}", tcx.node_path_str(nitem.id));
946 let kind = match nitem.node {
947 hir::ForeignItemFn(_, ref names, _) => {
949 constness: hir::Constness::NotConst,
950 arg_names: self.encode_fn_arg_names(names),
952 EntryKind::ForeignFn(self.lazy(&data))
954 hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
955 hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
960 visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
961 span: self.lazy(&nitem.span),
962 attributes: self.encode_attributes(&nitem.attrs),
963 children: LazySeq::empty(),
964 stability: self.encode_stability(def_id),
965 deprecation: self.encode_deprecation(def_id),
967 ty: Some(self.encode_item_type(def_id)),
968 inherent_impls: LazySeq::empty(),
969 variances: LazySeq::empty(),
970 generics: Some(self.encode_generics(def_id)),
971 predicates: Some(self.encode_predicates(def_id)),
979 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
980 index: IndexBuilder<'a, 'b, 'tcx>,
983 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
984 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
985 NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
987 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
988 intravisit::walk_expr(self, ex);
989 self.index.encode_info_for_expr(ex);
991 fn visit_item(&mut self, item: &'tcx hir::Item) {
992 intravisit::walk_item(self, item);
993 let def_id = self.index.tcx.hir.local_def_id(item.id);
995 hir::ItemExternCrate(_) |
996 hir::ItemUse(..) => (), // ignore these
997 _ => self.index.record(def_id, EncodeContext::encode_info_for_item, (def_id, item)),
999 self.index.encode_addl_info_for_item(item);
1001 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1002 intravisit::walk_foreign_item(self, ni);
1003 let def_id = self.index.tcx.hir.local_def_id(ni.id);
1004 self.index.record(def_id,
1005 EncodeContext::encode_info_for_foreign_item,
1008 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1009 intravisit::walk_generics(self, generics);
1010 self.index.encode_info_for_generics(generics);
1012 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1013 intravisit::walk_ty(self, ty);
1014 self.index.encode_info_for_ty(ty);
1016 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1017 let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1018 self.index.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def);
1022 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1023 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1024 for ty_param in &generics.ty_params {
1025 let def_id = self.tcx.hir.local_def_id(ty_param.id);
1026 let has_default = Untracked(ty_param.default.is_some());
1027 self.record(def_id, EncodeContext::encode_info_for_ty_param, (def_id, has_default));
1031 fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1032 if let hir::TyImplTrait(_) = ty.node {
1033 let def_id = self.tcx.hir.local_def_id(ty.id);
1034 self.record(def_id, EncodeContext::encode_info_for_anon_ty, def_id);
1038 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1040 hir::ExprClosure(..) => {
1041 let def_id = self.tcx.hir.local_def_id(expr.id);
1042 self.record(def_id, EncodeContext::encode_info_for_closure, def_id);
1049 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1050 fn encode_info_for_ty_param(&mut self,
1051 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1055 kind: EntryKind::Type,
1056 visibility: self.lazy(&ty::Visibility::Public),
1057 span: self.lazy(&tcx.def_span(def_id)),
1058 attributes: LazySeq::empty(),
1059 children: LazySeq::empty(),
1063 ty: if has_default {
1064 Some(self.encode_item_type(def_id))
1068 inherent_impls: LazySeq::empty(),
1069 variances: LazySeq::empty(),
1078 fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1081 kind: EntryKind::Type,
1082 visibility: self.lazy(&ty::Visibility::Public),
1083 span: self.lazy(&tcx.def_span(def_id)),
1084 attributes: LazySeq::empty(),
1085 children: LazySeq::empty(),
1089 ty: Some(self.encode_item_type(def_id)),
1090 inherent_impls: LazySeq::empty(),
1091 variances: LazySeq::empty(),
1092 generics: Some(self.encode_generics(def_id)),
1093 predicates: Some(self.encode_predicates(def_id)),
1100 fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1103 let data = ClosureData {
1104 kind: tcx.closure_kind(def_id),
1105 ty: self.lazy(&tcx.closure_type(def_id)),
1109 kind: EntryKind::Closure(self.lazy(&data)),
1110 visibility: self.lazy(&ty::Visibility::Public),
1111 span: self.lazy(&tcx.def_span(def_id)),
1112 attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1113 children: LazySeq::empty(),
1117 ty: Some(self.encode_item_type(def_id)),
1118 inherent_impls: LazySeq::empty(),
1119 variances: LazySeq::empty(),
1120 generics: Some(self.encode_generics(def_id)),
1124 mir: self.encode_mir(def_id),
1128 fn encode_info_for_items(&mut self) -> Index {
1129 let krate = self.tcx.hir.krate();
1130 let mut index = IndexBuilder::new(self);
1131 index.record(DefId::local(CRATE_DEF_INDEX),
1132 EncodeContext::encode_info_for_mod,
1133 FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
1134 let mut visitor = EncodeVisitor { index: index };
1135 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
1136 for macro_def in &krate.exported_macros {
1137 visitor.visit_macro_def(macro_def);
1139 visitor.index.into_items()
1142 fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1143 self.lazy_seq_ref(attrs)
1146 fn encode_crate_deps(&mut self) -> LazySeq<CrateDep> {
1147 fn get_ordered_deps(cstore: &cstore::CStore) -> Vec<(CrateNum, Rc<cstore::CrateMetadata>)> {
1148 // Pull the cnums and name,vers,hash out of cstore
1149 let mut deps = Vec::new();
1150 cstore.iter_crate_data(|cnum, val| {
1151 deps.push((cnum, val.clone()));
1155 deps.sort_by(|kv1, kv2| kv1.0.cmp(&kv2.0));
1157 // Sanity-check the crate numbers
1158 let mut expected_cnum = 1;
1159 for &(n, _) in &deps {
1160 assert_eq!(n, CrateNum::new(expected_cnum));
1167 // We're just going to write a list of crate 'name-hash-version's, with
1168 // the assumption that they are numbered 1 to n.
1169 // FIXME (#2166): This is not nearly enough to support correct versioning
1170 // but is enough to get transitive crate dependencies working.
1171 let deps = get_ordered_deps(self.cstore);
1172 self.lazy_seq(deps.iter().map(|&(_, ref dep)| {
1176 kind: dep.dep_kind.get(),
1181 fn encode_lang_items(&mut self) -> (LazySeq<(DefIndex, usize)>, LazySeq<lang_items::LangItem>) {
1183 let lang_items = tcx.lang_items.items().iter();
1184 (self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1185 if let Some(def_id) = opt_def_id {
1186 if def_id.is_local() {
1187 return Some((def_id.index, i));
1192 self.lazy_seq_ref(&tcx.lang_items.missing))
1195 fn encode_native_libraries(&mut self) -> LazySeq<NativeLibrary> {
1196 let used_libraries = self.tcx.sess.cstore.used_libraries();
1197 self.lazy_seq(used_libraries)
1200 fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
1201 let codemap = self.tcx.sess.codemap();
1202 let all_filemaps = codemap.files.borrow();
1203 self.lazy_seq_ref(all_filemaps.iter()
1205 // No need to re-export imported filemaps, as any downstream
1206 // crate will import them from their original source.
1207 !filemap.is_imported()
1209 .map(|filemap| &**filemap))
1212 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
1213 let definitions = self.tcx.hir.definitions();
1214 self.lazy(definitions.def_path_table())
1218 struct ImplVisitor<'a, 'tcx: 'a> {
1219 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1220 impls: FxHashMap<DefId, Vec<DefIndex>>,
1223 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1224 fn visit_item(&mut self, item: &hir::Item) {
1225 if let hir::ItemImpl(..) = item.node {
1226 let impl_id = self.tcx.hir.local_def_id(item.id);
1227 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1229 .entry(trait_ref.def_id)
1231 .push(impl_id.index);
1236 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1238 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1239 // handled in `visit_item` above
1243 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1244 /// Encodes an index, mapping each trait to its (local) implementations.
1245 fn encode_impls(&mut self) -> LazySeq<TraitImpls> {
1246 let mut visitor = ImplVisitor {
1250 self.tcx.hir.krate().visit_all_item_likes(&mut visitor);
1252 let all_impls: Vec<_> = visitor.impls
1254 .map(|(trait_def_id, impls)| {
1256 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1257 impls: self.lazy_seq(impls),
1262 self.lazy_seq(all_impls)
1265 // Encodes all symbols exported from this crate into the metadata.
1267 // This pass is seeded off the reachability list calculated in the
1268 // middle::reachable module but filters out items that either don't have a
1269 // symbol associated with them (they weren't translated) or if they're an FFI
1270 // definition (as that's not defined in this crate).
1271 fn encode_exported_symbols(&mut self) -> LazySeq<DefIndex> {
1272 let exported_symbols = self.exported_symbols;
1274 self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
1277 fn encode_dylib_dependency_formats(&mut self) -> LazySeq<Option<LinkagePreference>> {
1278 match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1280 self.lazy_seq(arr.iter().map(|slot| {
1282 Linkage::NotLinked |
1283 Linkage::IncludedFromDylib => None,
1285 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1286 Linkage::Static => Some(LinkagePreference::RequireStatic),
1290 None => LazySeq::empty(),
1294 fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
1295 let mut i = self.position();
1296 let crate_deps = self.encode_crate_deps();
1297 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
1298 let dep_bytes = self.position() - i;
1300 // Encode the language items.
1301 i = self.position();
1302 let (lang_items, lang_items_missing) = self.encode_lang_items();
1303 let lang_item_bytes = self.position() - i;
1305 // Encode the native libraries used
1306 i = self.position();
1307 let native_libraries = self.encode_native_libraries();
1308 let native_lib_bytes = self.position() - i;
1311 i = self.position();
1312 let codemap = self.encode_codemap();
1313 let codemap_bytes = self.position() - i;
1315 // Encode DefPathTable
1316 i = self.position();
1317 let def_path_table = self.encode_def_path_table();
1318 let def_path_table_bytes = self.position() - i;
1320 // Encode the def IDs of impls, for coherence checking.
1321 i = self.position();
1322 let impls = self.encode_impls();
1323 let impl_bytes = self.position() - i;
1325 // Encode exported symbols info.
1326 i = self.position();
1327 let exported_symbols = self.encode_exported_symbols();
1328 let exported_symbols_bytes = self.position() - i;
1330 // Encode and index the items.
1331 i = self.position();
1332 let items = self.encode_info_for_items();
1333 let item_bytes = self.position() - i;
1335 i = self.position();
1336 let index = items.write_index(&mut self.opaque.cursor);
1337 let index_bytes = self.position() - i;
1340 let link_meta = self.link_meta;
1341 let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
1342 let root = self.lazy(&CrateRoot {
1343 name: link_meta.crate_name,
1344 triple: tcx.sess.opts.target_triple.clone(),
1345 hash: link_meta.crate_hash,
1346 disambiguator: tcx.sess.local_crate_disambiguator(),
1347 panic_strategy: tcx.sess.panic_strategy(),
1348 plugin_registrar_fn: tcx.sess
1349 .plugin_registrar_fn
1351 .map(|id| tcx.hir.local_def_id(id).index),
1352 macro_derive_registrar: if is_proc_macro {
1353 let id = tcx.sess.derive_registrar_fn.get().unwrap();
1354 Some(tcx.hir.local_def_id(id).index)
1359 crate_deps: crate_deps,
1360 dylib_dependency_formats: dylib_dependency_formats,
1361 lang_items: lang_items,
1362 lang_items_missing: lang_items_missing,
1363 native_libraries: native_libraries,
1365 def_path_table: def_path_table,
1367 exported_symbols: exported_symbols,
1371 let total_bytes = self.position();
1373 if self.tcx.sess.meta_stats() {
1374 let mut zero_bytes = 0;
1375 for e in self.opaque.cursor.get_ref() {
1381 println!("metadata stats:");
1382 println!(" dep bytes: {}", dep_bytes);
1383 println!(" lang item bytes: {}", lang_item_bytes);
1384 println!(" native bytes: {}", native_lib_bytes);
1385 println!(" codemap bytes: {}", codemap_bytes);
1386 println!(" impl bytes: {}", impl_bytes);
1387 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
1388 println!(" def-path table bytes: {}", def_path_table_bytes);
1389 println!(" item bytes: {}", item_bytes);
1390 println!(" index bytes: {}", index_bytes);
1391 println!(" zero bytes: {}", zero_bytes);
1392 println!(" total bytes: {}", total_bytes);
1399 // NOTE(eddyb) The following comment was preserved for posterity, even
1400 // though it's no longer relevant as EBML (which uses nested & tagged
1401 // "documents") was replaced with a scheme that can't go out of bounds.
1403 // And here we run into yet another obscure archive bug: in which metadata
1404 // loaded from archives may have trailing garbage bytes. Awhile back one of
1405 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1406 // and opt) by having ebml generate an out-of-bounds panic when looking at
1409 // Upon investigation it turned out that the metadata file inside of an rlib
1410 // (and ar archive) was being corrupted. Some compilations would generate a
1411 // metadata file which would end in a few extra bytes, while other
1412 // compilations would not have these extra bytes appended to the end. These
1413 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1414 // being interpreted causing the out-of-bounds.
1416 // The root cause of why these extra bytes were appearing was never
1417 // discovered, and in the meantime the solution we're employing is to insert
1418 // the length of the metadata to the start of the metadata. Later on this
1419 // will allow us to slice the metadata to the precise length that we just
1420 // generated regardless of trailing bytes that end up in it.
1422 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1423 cstore: &cstore::CStore,
1424 link_meta: &LinkMeta,
1425 exported_symbols: &NodeSet)
1427 let mut cursor = Cursor::new(vec![]);
1428 cursor.write_all(METADATA_HEADER).unwrap();
1430 // Will be filed with the root position after encoding everything.
1431 cursor.write_all(&[0, 0, 0, 0]).unwrap();
1434 let mut ecx = EncodeContext {
1435 opaque: opaque::Encoder::new(&mut cursor),
1437 link_meta: link_meta,
1439 exported_symbols: exported_symbols,
1440 lazy_state: LazyState::NoNode,
1441 type_shorthands: Default::default(),
1442 predicate_shorthands: Default::default(),
1445 // Encode the rustc version string in a predictable location.
1446 rustc_version().encode(&mut ecx).unwrap();
1448 // Encode all the entries and extra information in the crate,
1449 // culminating in the `CrateRoot` which points to all of it.
1450 ecx.encode_crate_root()
1452 let mut result = cursor.into_inner();
1454 // Encode the root position.
1455 let header = METADATA_HEADER.len();
1456 let pos = root.position;
1457 result[header + 0] = (pos >> 24) as u8;
1458 result[header + 1] = (pos >> 16) as u8;
1459 result[header + 2] = (pos >> 8) as u8;
1460 result[header + 3] = (pos >> 0) as u8;
1465 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1466 let ty = tcx.item_type(did);
1468 ty::TyAdt(ref def, _) => return def.repr,
1469 _ => bug!("{} is not an ADT", ty),