]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/encoder.rs
Auto merge of #38551 - aidanhs:aphs-vec-in-place, r=brson
[rust.git] / src / librustc_metadata / encoder.rs
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.
4 //
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.
10
11 use cstore;
12 use index::Index;
13 use schema::*;
14
15 use rustc::middle::cstore::{LinkMeta, LinkagePreference, NativeLibrary};
16 use rustc::hir::def;
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;
21 use rustc::mir;
22 use rustc::traits::specialization_graph;
23 use rustc::ty::{self, Ty, TyCtxt};
24
25 use rustc::session::config::{self, CrateTypeProcMacro};
26 use rustc::util::nodemap::{FxHashMap, NodeSet};
27
28 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
29 use std::hash::Hash;
30 use std::intrinsics;
31 use std::io::prelude::*;
32 use std::io::Cursor;
33 use std::rc::Rc;
34 use std::u32;
35 use syntax::ast::{self, CRATE_NODE_ID};
36 use syntax::codemap::Spanned;
37 use syntax::attr;
38 use syntax::symbol::Symbol;
39 use syntax_pos;
40
41 use rustc::hir::{self, PatKind};
42 use rustc::hir::itemlikevisit::ItemLikeVisitor;
43 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
44 use rustc::hir::intravisit;
45
46 use rustc_i128::{u128, i128};
47
48 use super::index_builder::{FromId, IndexBuilder, Untracked};
49
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,
57
58     lazy_state: LazyState,
59     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
60     predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
61 }
62
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)
67         })*
68     }
69 }
70
71 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
72     type Error = <opaque::Encoder<'a> as Encoder>::Error;
73
74     fn emit_nil(&mut self) -> Result<(), Self::Error> {
75         Ok(())
76     }
77
78     encoder_methods! {
79         emit_usize(usize);
80         emit_u128(u128);
81         emit_u64(u64);
82         emit_u32(u32);
83         emit_u16(u16);
84         emit_u8(u8);
85
86         emit_isize(isize);
87         emit_i128(i128);
88         emit_i64(i64);
89         emit_i32(i32);
90         emit_i16(i16);
91         emit_i8(i8);
92
93         emit_bool(bool);
94         emit_f64(f64);
95         emit_f32(f32);
96         emit_char(char);
97         emit_str(&str);
98     }
99 }
100
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())
104     }
105 }
106
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)?;
110         if seq.len == 0 {
111             return Ok(());
112         }
113         self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
114     }
115 }
116
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)
120     }
121 }
122
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)?
131         }
132         Ok(())
133     }
134 }
135
136 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
137     pub fn position(&self) -> usize {
138         self.opaque.position()
139     }
140
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;
147         r
148     }
149
150     fn emit_lazy_distance(&mut self,
151                           position: usize,
152                           min_size: usize)
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);
159                 start - min_end
160             }
161             LazyState::Previous(last_min_end) => {
162                 assert!(last_min_end <= position);
163                 position - last_min_end
164             }
165         };
166         self.lazy_state = LazyState::Previous(min_end);
167         self.emit_usize(distance)
168     }
169
170     pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
171         self.emit_node(|ecx, pos| {
172             value.encode(ecx).unwrap();
173
174             assert!(pos + Lazy::<T>::min_size() <= ecx.position());
175             Lazy::with_position(pos)
176         })
177     }
178
179     fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
180         where I: IntoIterator<Item = T>,
181               T: Encodable
182     {
183         self.emit_node(|ecx, pos| {
184             let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
185
186             assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
187             LazySeq::with_position_and_length(pos, len)
188         })
189     }
190
191     fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
192         where I: IntoIterator<Item = &'b T>,
193               T: 'b + Encodable
194     {
195         self.emit_node(|ecx, pos| {
196             let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
197
198             assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
199             LazySeq::with_position_and_length(pos, len)
200         })
201     }
202
203     /// Encode the given value or a previously cached shorthand.
204     fn encode_with_shorthand<T, U, M>(&mut self,
205                                       value: &T,
206                                       variant: &U,
207                                       map: M)
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,
211               U: Encodable
212     {
213         let existing_shorthand = map(self).get(value).cloned();
214         if let Some(shorthand) = existing_shorthand {
215             return self.emit_usize(shorthand);
216         }
217
218         let start = self.position();
219         variant.encode(self)?;
220         let len = self.position() - start;
221
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;
227
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;
231
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);
236         }
237
238         Ok(())
239     }
240
241     fn encode_item_variances(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
242         let tcx = self.tcx;
243         self.lazy_seq(tcx.item_variances(def_id).iter().cloned())
244     }
245
246     fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
247         let tcx = self.tcx;
248         self.lazy(&tcx.item_type(def_id))
249     }
250
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>))
258                                 -> Entry<'tcx> {
259         let tcx = self.tcx;
260         let def = tcx.lookup_adt_def(enum_did);
261         let variant = &def.variants[index];
262         let def_id = variant.did;
263
264         let data = VariantData {
265             ctor_kind: variant.ctor_kind,
266             disr: variant.disr_val.to_u128_unchecked(),
267             struct_ctor: None,
268         };
269
270         let enum_id = tcx.map.as_local_node_id(enum_did).unwrap();
271         let enum_vis = &tcx.map.expect_item(enum_id).vis;
272
273         Entry {
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());
280                 f.did.index
281             })),
282             stability: self.encode_stability(def_id),
283             deprecation: self.encode_deprecation(def_id),
284
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)),
290
291             ast: None,
292             mir: None,
293         }
294     }
295
296     fn encode_info_for_mod(&mut self,
297                            FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
298                                                                  &[ast::Attribute],
299                                                                  &hir::Visibility)>)
300                            -> Entry<'tcx> {
301         let tcx = self.tcx;
302         let def_id = tcx.map.local_def_id(id);
303
304         let data = ModData {
305             reexports: match self.reexports.get(&id) {
306                 Some(exports) if *vis == hir::Public => self.lazy_seq_ref(exports),
307                 _ => LazySeq::empty(),
308             },
309         };
310
311         Entry {
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.map.local_def_id(item_id.id).index
318             })),
319             stability: self.encode_stability(def_id),
320             deprecation: self.encode_deprecation(def_id),
321
322             ty: None,
323             inherent_impls: LazySeq::empty(),
324             variances: LazySeq::empty(),
325             generics: None,
326             predicates: None,
327
328             ast: None,
329             mir: None
330         }
331     }
332 }
333
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))));
342             }
343         }
344     }
345 }
346
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
353     /// vectors).
354     fn encode_field(&mut self,
355                     (adt_def_id, Untracked((variant_index, field_index))): (DefId,
356                                                                             Untracked<(usize,
357                                                                                        usize)>))
358                     -> Entry<'tcx> {
359         let tcx = self.tcx;
360         let variant = &tcx.lookup_adt_def(adt_def_id).variants[variant_index];
361         let field = &variant.fields[field_index];
362
363         let def_id = field.did;
364         let variant_id = tcx.map.as_local_node_id(variant.did).unwrap();
365         let variant_data = tcx.map.expect_variant_data(variant_id);
366
367         Entry {
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),
375
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)),
381
382             ast: None,
383             mir: None,
384         }
385     }
386
387     fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
388         let tcx = self.tcx;
389         let variant = tcx.lookup_adt_def(adt_def_id).struct_variant();
390
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),
395         };
396
397         let struct_id = tcx.map.as_local_node_id(adt_def_id).unwrap();
398         let struct_vis = &tcx.map.expect_item(struct_id).vis;
399
400         Entry {
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),
408
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)),
414
415             ast: None,
416             mir: None,
417         }
418     }
419
420     fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics<'tcx>> {
421         let tcx = self.tcx;
422         self.lazy(tcx.item_generics(def_id))
423     }
424
425     fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
426         let tcx = self.tcx;
427         self.lazy(&tcx.item_predicates(def_id))
428     }
429
430     fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
431         let tcx = self.tcx;
432
433         let node_id = tcx.map.as_local_node_id(def_id).unwrap();
434         let ast_item = tcx.map.expect_trait_item(node_id);
435         let trait_item = tcx.associated_item(def_id);
436
437         let container = match trait_item.defaultness {
438             hir::Defaultness::Default { has_value: true } =>
439                 AssociatedContainer::TraitWithDefault,
440             hir::Defaultness::Default { has_value: false } =>
441                 AssociatedContainer::TraitRequired,
442             hir::Defaultness::Final =>
443                 span_bug!(ast_item.span, "traits cannot have final items"),
444         };
445
446         let kind = match trait_item.kind {
447             ty::AssociatedKind::Const => EntryKind::AssociatedConst(container),
448             ty::AssociatedKind::Method => {
449                 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
450                     let arg_names = match *m {
451                         hir::TraitMethod::Required(ref names) => {
452                             self.encode_fn_arg_names(names)
453                         }
454                         hir::TraitMethod::Provided(body) => {
455                             self.encode_fn_arg_names_for_body(body)
456                         }
457                     };
458                     FnData {
459                         constness: hir::Constness::NotConst,
460                         arg_names: arg_names
461                     }
462                 } else {
463                     bug!()
464                 };
465                 EntryKind::Method(self.lazy(&MethodData {
466                     fn_data: fn_data,
467                     container: container,
468                     has_self: trait_item.method_has_self_argument,
469                 }))
470             }
471             ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
472         };
473
474         Entry {
475             kind: kind,
476             visibility: self.lazy(&trait_item.vis),
477             span: self.lazy(&ast_item.span),
478             attributes: self.encode_attributes(&ast_item.attrs),
479             children: LazySeq::empty(),
480             stability: self.encode_stability(def_id),
481             deprecation: self.encode_deprecation(def_id),
482
483             ty: match trait_item.kind {
484                 ty::AssociatedKind::Const |
485                 ty::AssociatedKind::Method => {
486                     Some(self.encode_item_type(def_id))
487                 }
488                 ty::AssociatedKind::Type => {
489                     if trait_item.defaultness.has_value() {
490                         Some(self.encode_item_type(def_id))
491                     } else {
492                         None
493                     }
494                 }
495             },
496             inherent_impls: LazySeq::empty(),
497             variances: LazySeq::empty(),
498             generics: Some(self.encode_generics(def_id)),
499             predicates: Some(self.encode_predicates(def_id)),
500
501             ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
502                 Some(self.encode_body(body))
503             } else {
504                 None
505             },
506             mir: self.encode_mir(def_id),
507         }
508     }
509
510     fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
511         let node_id = self.tcx.map.as_local_node_id(def_id).unwrap();
512         let ast_item = self.tcx.map.expect_impl_item(node_id);
513         let impl_item = self.tcx.associated_item(def_id);
514
515         let container = match impl_item.defaultness {
516             hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
517             hir::Defaultness::Final => AssociatedContainer::ImplFinal,
518             hir::Defaultness::Default { has_value: false } =>
519                 span_bug!(ast_item.span, "impl items always have values (currently)"),
520         };
521
522         let kind = match impl_item.kind {
523             ty::AssociatedKind::Const => EntryKind::AssociatedConst(container),
524             ty::AssociatedKind::Method => {
525                 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
526                     FnData {
527                         constness: sig.constness,
528                         arg_names: self.encode_fn_arg_names_for_body(body),
529                     }
530                 } else {
531                     bug!()
532                 };
533                 EntryKind::Method(self.lazy(&MethodData {
534                     fn_data: fn_data,
535                     container: container,
536                     has_self: impl_item.method_has_self_argument,
537                 }))
538             }
539             ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
540         };
541
542         let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
543             (Some(body), true)
544         } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
545             let generics = self.tcx.item_generics(def_id);
546             let types = generics.parent_types as usize + generics.types.len();
547             let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
548             let is_const_fn = sig.constness == hir::Constness::Const;
549             let ast = if is_const_fn { Some(body) } else { None };
550             let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
551             (ast, needs_inline || is_const_fn || always_encode_mir)
552         } else {
553             (None, false)
554         };
555
556         Entry {
557             kind: kind,
558             visibility: self.lazy(&impl_item.vis),
559             span: self.lazy(&ast_item.span),
560             attributes: self.encode_attributes(&ast_item.attrs),
561             children: LazySeq::empty(),
562             stability: self.encode_stability(def_id),
563             deprecation: self.encode_deprecation(def_id),
564
565             ty: Some(self.encode_item_type(def_id)),
566             inherent_impls: LazySeq::empty(),
567             variances: LazySeq::empty(),
568             generics: Some(self.encode_generics(def_id)),
569             predicates: Some(self.encode_predicates(def_id)),
570
571             ast: ast.map(|body| self.encode_body(body)),
572             mir: if mir { self.encode_mir(def_id) } else { None },
573         }
574     }
575
576     fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
577                                     -> LazySeq<ast::Name> {
578         let _ignore = self.tcx.dep_graph.in_ignore();
579         let body = self.tcx.map.body(body_id);
580         self.lazy_seq(body.arguments.iter().map(|arg| {
581             match arg.pat.node {
582                 PatKind::Binding(_, _, name, _) => name.node,
583                 _ => Symbol::intern("")
584             }
585         }))
586     }
587
588     fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
589                            -> LazySeq<ast::Name> {
590         self.lazy_seq(names.iter().map(|name| name.node))
591     }
592
593     fn encode_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
594         self.tcx.mir_map.borrow().get(&def_id).map(|mir| self.lazy(&*mir.borrow()))
595     }
596
597     // Encodes the inherent implementations of a structure, enumeration, or trait.
598     fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
599         match self.tcx.inherent_impls.borrow().get(&def_id) {
600             None => LazySeq::empty(),
601             Some(implementations) => {
602                 self.lazy_seq(implementations.iter().map(|&def_id| {
603                     assert!(def_id.is_local());
604                     def_id.index
605                 }))
606             }
607         }
608     }
609
610     fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
611         self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
612     }
613
614     fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
615         self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
616     }
617
618     fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
619         let tcx = self.tcx;
620
621         debug!("encoding info for item at {}",
622                tcx.sess.codemap().span_to_string(item.span));
623
624         let kind = match item.node {
625             hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
626             hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
627             hir::ItemConst(..) => EntryKind::Const,
628             hir::ItemFn(_, _, constness, .., body) => {
629                 let data = FnData {
630                     constness: constness,
631                     arg_names: self.encode_fn_arg_names_for_body(body),
632                 };
633
634                 EntryKind::Fn(self.lazy(&data))
635             }
636             hir::ItemMod(ref m) => {
637                 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
638             }
639             hir::ItemForeignMod(_) => EntryKind::ForeignMod,
640             hir::ItemTy(..) => EntryKind::Type,
641             hir::ItemEnum(..) => EntryKind::Enum,
642             hir::ItemStruct(ref struct_def, _) => {
643                 let variant = tcx.lookup_adt_def(def_id).struct_variant();
644
645                 // Encode def_ids for each field and method
646                 // for methods, write all the stuff get_trait_method
647                 // needs to know
648                 let struct_ctor = if !struct_def.is_struct() {
649                     Some(tcx.map.local_def_id(struct_def.id()).index)
650                 } else {
651                     None
652                 };
653                 EntryKind::Struct(self.lazy(&VariantData {
654                     ctor_kind: variant.ctor_kind,
655                     disr: variant.disr_val.to_u128_unchecked(),
656                     struct_ctor: struct_ctor,
657                 }))
658             }
659             hir::ItemUnion(..) => {
660                 let variant = tcx.lookup_adt_def(def_id).struct_variant();
661
662                 EntryKind::Union(self.lazy(&VariantData {
663                     ctor_kind: variant.ctor_kind,
664                     disr: variant.disr_val.to_u128_unchecked(),
665                     struct_ctor: None,
666                 }))
667             }
668             hir::ItemDefaultImpl(..) => {
669                 let data = ImplData {
670                     polarity: hir::ImplPolarity::Positive,
671                     parent_impl: None,
672                     coerce_unsized_kind: None,
673                     trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref)),
674                 };
675
676                 EntryKind::DefaultImpl(self.lazy(&data))
677             }
678             hir::ItemImpl(_, polarity, ..) => {
679                 let trait_ref = tcx.impl_trait_ref(def_id);
680                 let parent = if let Some(trait_ref) = trait_ref {
681                     let trait_def = tcx.lookup_trait_def(trait_ref.def_id);
682                     trait_def.ancestors(def_id).skip(1).next().and_then(|node| {
683                         match node {
684                             specialization_graph::Node::Impl(parent) => Some(parent),
685                             _ => None,
686                         }
687                     })
688                 } else {
689                     None
690                 };
691
692                 let data = ImplData {
693                     polarity: polarity,
694                     parent_impl: parent,
695                     coerce_unsized_kind: tcx.custom_coerce_unsized_kinds
696                         .borrow()
697                         .get(&def_id)
698                         .cloned(),
699                     trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
700                 };
701
702                 EntryKind::Impl(self.lazy(&data))
703             }
704             hir::ItemTrait(..) => {
705                 let trait_def = tcx.lookup_trait_def(def_id);
706                 let data = TraitData {
707                     unsafety: trait_def.unsafety,
708                     paren_sugar: trait_def.paren_sugar,
709                     has_default_impl: tcx.trait_has_default_impl(def_id),
710                     super_predicates: self.lazy(&tcx.item_super_predicates(def_id)),
711                 };
712
713                 EntryKind::Trait(self.lazy(&data))
714             }
715             hir::ItemExternCrate(_) |
716             hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
717         };
718
719         Entry {
720             kind: kind,
721             visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
722             span: self.lazy(&item.span),
723             attributes: self.encode_attributes(&item.attrs),
724             children: match item.node {
725                 hir::ItemForeignMod(ref fm) => {
726                     self.lazy_seq(fm.items
727                         .iter()
728                         .map(|foreign_item| tcx.map.local_def_id(foreign_item.id).index))
729                 }
730                 hir::ItemEnum(..) => {
731                     let def = self.tcx.lookup_adt_def(def_id);
732                     self.lazy_seq(def.variants.iter().map(|v| {
733                         assert!(v.did.is_local());
734                         v.did.index
735                     }))
736                 }
737                 hir::ItemStruct(..) |
738                 hir::ItemUnion(..) => {
739                     let def = self.tcx.lookup_adt_def(def_id);
740                     self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
741                         assert!(f.did.is_local());
742                         f.did.index
743                     }))
744                 }
745                 hir::ItemImpl(..) |
746                 hir::ItemTrait(..) => {
747                     self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
748                         assert!(def_id.is_local());
749                         def_id.index
750                     }))
751                 }
752                 _ => LazySeq::empty(),
753             },
754             stability: self.encode_stability(def_id),
755             deprecation: self.encode_deprecation(def_id),
756
757             ty: match item.node {
758                 hir::ItemStatic(..) |
759                 hir::ItemConst(..) |
760                 hir::ItemFn(..) |
761                 hir::ItemTy(..) |
762                 hir::ItemEnum(..) |
763                 hir::ItemStruct(..) |
764                 hir::ItemUnion(..) |
765                 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
766                 _ => None,
767             },
768             inherent_impls: self.encode_inherent_implementations(def_id),
769             variances: match item.node {
770                 hir::ItemEnum(..) |
771                 hir::ItemStruct(..) |
772                 hir::ItemUnion(..) |
773                 hir::ItemTrait(..) => self.encode_item_variances(def_id),
774                 _ => LazySeq::empty(),
775             },
776             generics: match item.node {
777                 hir::ItemStatic(..) |
778                 hir::ItemConst(..) |
779                 hir::ItemFn(..) |
780                 hir::ItemTy(..) |
781                 hir::ItemEnum(..) |
782                 hir::ItemStruct(..) |
783                 hir::ItemUnion(..) |
784                 hir::ItemImpl(..) |
785                 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
786                 _ => None,
787             },
788             predicates: match item.node {
789                 hir::ItemStatic(..) |
790                 hir::ItemConst(..) |
791                 hir::ItemFn(..) |
792                 hir::ItemTy(..) |
793                 hir::ItemEnum(..) |
794                 hir::ItemStruct(..) |
795                 hir::ItemUnion(..) |
796                 hir::ItemImpl(..) |
797                 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
798                 _ => None,
799             },
800
801             ast: match item.node {
802                 hir::ItemConst(_, body) |
803                 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
804                     Some(self.encode_body(body))
805                 }
806                 _ => None,
807             },
808             mir: match item.node {
809                 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
810                     self.encode_mir(def_id)
811                 }
812                 hir::ItemConst(..) => self.encode_mir(def_id),
813                 hir::ItemFn(_, _, constness, _, ref generics, _) => {
814                     let tps_len = generics.ty_params.len();
815                     let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
816                     let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
817                     if needs_inline || constness == hir::Constness::Const || always_encode_mir {
818                         self.encode_mir(def_id)
819                     } else {
820                         None
821                     }
822                 }
823                 _ => None,
824             },
825         }
826     }
827
828     /// Serialize the text of exported macros
829     fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
830         Entry {
831             kind: EntryKind::MacroDef(self.lazy(&MacroDef {
832                 body: ::syntax::print::pprust::tts_to_string(&macro_def.body)
833             })),
834             visibility: self.lazy(&ty::Visibility::Public),
835             span: self.lazy(&macro_def.span),
836
837             attributes: self.encode_attributes(&macro_def.attrs),
838             children: LazySeq::empty(),
839             stability: None,
840             deprecation: None,
841             ty: None,
842             inherent_impls: LazySeq::empty(),
843             variances: LazySeq::empty(),
844             generics: None,
845             predicates: None,
846             ast: None,
847             mir: None,
848         }
849     }
850 }
851
852 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
853     /// In some cases, along with the item itself, we also
854     /// encode some sub-items. Usually we want some info from the item
855     /// so it's easier to do that here then to wait until we would encounter
856     /// normally in the visitor walk.
857     fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
858         let def_id = self.tcx.map.local_def_id(item.id);
859         match item.node {
860             hir::ItemStatic(..) |
861             hir::ItemConst(..) |
862             hir::ItemFn(..) |
863             hir::ItemMod(..) |
864             hir::ItemForeignMod(..) |
865             hir::ItemExternCrate(..) |
866             hir::ItemUse(..) |
867             hir::ItemDefaultImpl(..) |
868             hir::ItemTy(..) => {
869                 // no sub-item recording needed in these cases
870             }
871             hir::ItemEnum(..) => {
872                 self.encode_fields(def_id);
873
874                 let def = self.tcx.lookup_adt_def(def_id);
875                 for (i, variant) in def.variants.iter().enumerate() {
876                     self.record(variant.did,
877                                 EncodeContext::encode_enum_variant_info,
878                                 (def_id, Untracked(i)));
879                 }
880             }
881             hir::ItemStruct(ref struct_def, _) => {
882                 self.encode_fields(def_id);
883
884                 // If the struct has a constructor, encode it.
885                 if !struct_def.is_struct() {
886                     let ctor_def_id = self.tcx.map.local_def_id(struct_def.id());
887                     self.record(ctor_def_id,
888                                 EncodeContext::encode_struct_ctor,
889                                 (def_id, ctor_def_id));
890                 }
891             }
892             hir::ItemUnion(..) => {
893                 self.encode_fields(def_id);
894             }
895             hir::ItemImpl(..) => {
896                 for &trait_item_def_id in &self.tcx.associated_item_def_ids(def_id)[..] {
897                     self.record(trait_item_def_id,
898                                 EncodeContext::encode_info_for_impl_item,
899                                 trait_item_def_id);
900                 }
901             }
902             hir::ItemTrait(..) => {
903                 for &item_def_id in &self.tcx.associated_item_def_ids(def_id)[..] {
904                     self.record(item_def_id,
905                                 EncodeContext::encode_info_for_trait_item,
906                                 item_def_id);
907                 }
908             }
909         }
910     }
911 }
912
913 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
914     fn encode_info_for_foreign_item(&mut self,
915                                     (def_id, nitem): (DefId, &hir::ForeignItem))
916                                     -> Entry<'tcx> {
917         let tcx = self.tcx;
918
919         debug!("writing foreign item {}", tcx.node_path_str(nitem.id));
920
921         let kind = match nitem.node {
922             hir::ForeignItemFn(_, ref names, _) => {
923                 let data = FnData {
924                     constness: hir::Constness::NotConst,
925                     arg_names: self.encode_fn_arg_names(names),
926                 };
927                 EntryKind::ForeignFn(self.lazy(&data))
928             }
929             hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
930             hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
931         };
932
933         Entry {
934             kind: kind,
935             visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
936             span: self.lazy(&nitem.span),
937             attributes: self.encode_attributes(&nitem.attrs),
938             children: LazySeq::empty(),
939             stability: self.encode_stability(def_id),
940             deprecation: self.encode_deprecation(def_id),
941
942             ty: Some(self.encode_item_type(def_id)),
943             inherent_impls: LazySeq::empty(),
944             variances: LazySeq::empty(),
945             generics: Some(self.encode_generics(def_id)),
946             predicates: Some(self.encode_predicates(def_id)),
947
948             ast: None,
949             mir: None,
950         }
951     }
952 }
953
954 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
955     index: IndexBuilder<'a, 'b, 'tcx>,
956 }
957
958 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
959     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
960         NestedVisitorMap::OnlyBodies(&self.index.tcx.map)
961     }
962     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
963         intravisit::walk_expr(self, ex);
964         self.index.encode_info_for_expr(ex);
965     }
966     fn visit_item(&mut self, item: &'tcx hir::Item) {
967         intravisit::walk_item(self, item);
968         let def_id = self.index.tcx.map.local_def_id(item.id);
969         match item.node {
970             hir::ItemExternCrate(_) |
971             hir::ItemUse(..) => (), // ignore these
972             _ => self.index.record(def_id, EncodeContext::encode_info_for_item, (def_id, item)),
973         }
974         self.index.encode_addl_info_for_item(item);
975     }
976     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
977         intravisit::walk_foreign_item(self, ni);
978         let def_id = self.index.tcx.map.local_def_id(ni.id);
979         self.index.record(def_id,
980                           EncodeContext::encode_info_for_foreign_item,
981                           (def_id, ni));
982     }
983     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
984         intravisit::walk_ty(self, ty);
985         self.index.encode_info_for_ty(ty);
986     }
987     fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
988         let def_id = self.index.tcx.map.local_def_id(macro_def.id);
989         self.index.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def);
990     }
991 }
992
993 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
994     fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
995         if let hir::TyImplTrait(_) = ty.node {
996             let def_id = self.tcx.map.local_def_id(ty.id);
997             self.record(def_id, EncodeContext::encode_info_for_anon_ty, def_id);
998         }
999     }
1000
1001     fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1002         match expr.node {
1003             hir::ExprClosure(..) => {
1004                 let def_id = self.tcx.map.local_def_id(expr.id);
1005                 self.record(def_id, EncodeContext::encode_info_for_closure, def_id);
1006             }
1007             _ => {}
1008         }
1009     }
1010 }
1011
1012 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1013     fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1014         let tcx = self.tcx;
1015         Entry {
1016             kind: EntryKind::Type,
1017             visibility: self.lazy(&ty::Visibility::Public),
1018             span: self.lazy(&tcx.def_span(def_id)),
1019             attributes: LazySeq::empty(),
1020             children: LazySeq::empty(),
1021             stability: None,
1022             deprecation: None,
1023
1024             ty: Some(self.encode_item_type(def_id)),
1025             inherent_impls: LazySeq::empty(),
1026             variances: LazySeq::empty(),
1027             generics: Some(self.encode_generics(def_id)),
1028             predicates: Some(self.encode_predicates(def_id)),
1029
1030             ast: None,
1031             mir: None,
1032         }
1033     }
1034
1035     fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1036         let tcx = self.tcx;
1037
1038         let data = ClosureData {
1039             kind: tcx.closure_kind(def_id),
1040             ty: self.lazy(&tcx.tables().closure_tys[&def_id]),
1041         };
1042
1043         Entry {
1044             kind: EntryKind::Closure(self.lazy(&data)),
1045             visibility: self.lazy(&ty::Visibility::Public),
1046             span: self.lazy(&tcx.def_span(def_id)),
1047             attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1048             children: LazySeq::empty(),
1049             stability: None,
1050             deprecation: None,
1051
1052             ty: Some(self.encode_item_type(def_id)),
1053             inherent_impls: LazySeq::empty(),
1054             variances: LazySeq::empty(),
1055             generics: Some(self.encode_generics(def_id)),
1056             predicates: None,
1057
1058             ast: None,
1059             mir: self.encode_mir(def_id),
1060         }
1061     }
1062
1063     fn encode_info_for_items(&mut self) -> Index {
1064         let krate = self.tcx.map.krate();
1065         let mut index = IndexBuilder::new(self);
1066         index.record(DefId::local(CRATE_DEF_INDEX),
1067                      EncodeContext::encode_info_for_mod,
1068                      FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
1069         let mut visitor = EncodeVisitor { index: index };
1070         krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
1071         for macro_def in &krate.exported_macros {
1072             visitor.visit_macro_def(macro_def);
1073         }
1074         visitor.index.into_items()
1075     }
1076
1077     fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1078         self.lazy_seq_ref(attrs)
1079     }
1080
1081     fn encode_crate_deps(&mut self) -> LazySeq<CrateDep> {
1082         fn get_ordered_deps(cstore: &cstore::CStore) -> Vec<(CrateNum, Rc<cstore::CrateMetadata>)> {
1083             // Pull the cnums and name,vers,hash out of cstore
1084             let mut deps = Vec::new();
1085             cstore.iter_crate_data(|cnum, val| {
1086                 deps.push((cnum, val.clone()));
1087             });
1088
1089             // Sort by cnum
1090             deps.sort_by(|kv1, kv2| kv1.0.cmp(&kv2.0));
1091
1092             // Sanity-check the crate numbers
1093             let mut expected_cnum = 1;
1094             for &(n, _) in &deps {
1095                 assert_eq!(n, CrateNum::new(expected_cnum));
1096                 expected_cnum += 1;
1097             }
1098
1099             deps
1100         }
1101
1102         // We're just going to write a list of crate 'name-hash-version's, with
1103         // the assumption that they are numbered 1 to n.
1104         // FIXME (#2166): This is not nearly enough to support correct versioning
1105         // but is enough to get transitive crate dependencies working.
1106         let deps = get_ordered_deps(self.cstore);
1107         self.lazy_seq(deps.iter().map(|&(_, ref dep)| {
1108             CrateDep {
1109                 name: dep.name(),
1110                 hash: dep.hash(),
1111                 kind: dep.dep_kind.get(),
1112             }
1113         }))
1114     }
1115
1116     fn encode_lang_items(&mut self) -> (LazySeq<(DefIndex, usize)>, LazySeq<lang_items::LangItem>) {
1117         let tcx = self.tcx;
1118         let lang_items = tcx.lang_items.items().iter();
1119         (self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1120             if let Some(def_id) = opt_def_id {
1121                 if def_id.is_local() {
1122                     return Some((def_id.index, i));
1123                 }
1124             }
1125             None
1126         })),
1127          self.lazy_seq_ref(&tcx.lang_items.missing))
1128     }
1129
1130     fn encode_native_libraries(&mut self) -> LazySeq<NativeLibrary> {
1131         let used_libraries = self.tcx.sess.cstore.used_libraries();
1132         self.lazy_seq(used_libraries)
1133     }
1134
1135     fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
1136         let codemap = self.tcx.sess.codemap();
1137         let all_filemaps = codemap.files.borrow();
1138         self.lazy_seq_ref(all_filemaps.iter()
1139             .filter(|filemap| {
1140                 // No need to re-export imported filemaps, as any downstream
1141                 // crate will import them from their original source.
1142                 !filemap.is_imported()
1143             })
1144             .map(|filemap| &**filemap))
1145     }
1146
1147     fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
1148         let definitions = self.tcx.map.definitions();
1149         self.lazy(definitions.def_path_table())
1150     }
1151 }
1152
1153 struct ImplVisitor<'a, 'tcx: 'a> {
1154     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1155     impls: FxHashMap<DefId, Vec<DefIndex>>,
1156 }
1157
1158 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1159     fn visit_item(&mut self, item: &hir::Item) {
1160         if let hir::ItemImpl(..) = item.node {
1161             let impl_id = self.tcx.map.local_def_id(item.id);
1162             if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1163                 self.impls
1164                     .entry(trait_ref.def_id)
1165                     .or_insert(vec![])
1166                     .push(impl_id.index);
1167             }
1168         }
1169     }
1170
1171     fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1172
1173     fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1174         // handled in `visit_item` above
1175     }
1176 }
1177
1178 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1179     /// Encodes an index, mapping each trait to its (local) implementations.
1180     fn encode_impls(&mut self) -> LazySeq<TraitImpls> {
1181         let mut visitor = ImplVisitor {
1182             tcx: self.tcx,
1183             impls: FxHashMap(),
1184         };
1185         self.tcx.map.krate().visit_all_item_likes(&mut visitor);
1186
1187         let all_impls: Vec<_> = visitor.impls
1188             .into_iter()
1189             .map(|(trait_def_id, impls)| {
1190                 TraitImpls {
1191                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1192                     impls: self.lazy_seq(impls),
1193                 }
1194             })
1195             .collect();
1196
1197         self.lazy_seq(all_impls)
1198     }
1199
1200     // Encodes all symbols exported from this crate into the metadata.
1201     //
1202     // This pass is seeded off the reachability list calculated in the
1203     // middle::reachable module but filters out items that either don't have a
1204     // symbol associated with them (they weren't translated) or if they're an FFI
1205     // definition (as that's not defined in this crate).
1206     fn encode_exported_symbols(&mut self) -> LazySeq<DefIndex> {
1207         let exported_symbols = self.exported_symbols;
1208         let tcx = self.tcx;
1209         self.lazy_seq(exported_symbols.iter().map(|&id| tcx.map.local_def_id(id).index))
1210     }
1211
1212     fn encode_dylib_dependency_formats(&mut self) -> LazySeq<Option<LinkagePreference>> {
1213         match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1214             Some(arr) => {
1215                 self.lazy_seq(arr.iter().map(|slot| {
1216                     match *slot {
1217                         Linkage::NotLinked |
1218                         Linkage::IncludedFromDylib => None,
1219
1220                         Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1221                         Linkage::Static => Some(LinkagePreference::RequireStatic),
1222                     }
1223                 }))
1224             }
1225             None => LazySeq::empty(),
1226         }
1227     }
1228
1229     fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
1230         let mut i = self.position();
1231         let crate_deps = self.encode_crate_deps();
1232         let dylib_dependency_formats = self.encode_dylib_dependency_formats();
1233         let dep_bytes = self.position() - i;
1234
1235         // Encode the language items.
1236         i = self.position();
1237         let (lang_items, lang_items_missing) = self.encode_lang_items();
1238         let lang_item_bytes = self.position() - i;
1239
1240         // Encode the native libraries used
1241         i = self.position();
1242         let native_libraries = self.encode_native_libraries();
1243         let native_lib_bytes = self.position() - i;
1244
1245         // Encode codemap
1246         i = self.position();
1247         let codemap = self.encode_codemap();
1248         let codemap_bytes = self.position() - i;
1249
1250         // Encode DefPathTable
1251         i = self.position();
1252         let def_path_table = self.encode_def_path_table();
1253         let def_path_table_bytes = self.position() - i;
1254
1255         // Encode the def IDs of impls, for coherence checking.
1256         i = self.position();
1257         let impls = self.encode_impls();
1258         let impl_bytes = self.position() - i;
1259
1260         // Encode exported symbols info.
1261         i = self.position();
1262         let exported_symbols = self.encode_exported_symbols();
1263         let exported_symbols_bytes = self.position() - i;
1264
1265         // Encode and index the items.
1266         i = self.position();
1267         let items = self.encode_info_for_items();
1268         let item_bytes = self.position() - i;
1269
1270         i = self.position();
1271         let index = items.write_index(&mut self.opaque.cursor);
1272         let index_bytes = self.position() - i;
1273
1274         let tcx = self.tcx;
1275         let link_meta = self.link_meta;
1276         let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
1277         let root = self.lazy(&CrateRoot {
1278             name: link_meta.crate_name,
1279             triple: tcx.sess.opts.target_triple.clone(),
1280             hash: link_meta.crate_hash,
1281             disambiguator: tcx.sess.local_crate_disambiguator(),
1282             panic_strategy: tcx.sess.panic_strategy(),
1283             plugin_registrar_fn: tcx.sess
1284                 .plugin_registrar_fn
1285                 .get()
1286                 .map(|id| tcx.map.local_def_id(id).index),
1287             macro_derive_registrar: if is_proc_macro {
1288                 let id = tcx.sess.derive_registrar_fn.get().unwrap();
1289                 Some(tcx.map.local_def_id(id).index)
1290             } else {
1291                 None
1292             },
1293
1294             crate_deps: crate_deps,
1295             dylib_dependency_formats: dylib_dependency_formats,
1296             lang_items: lang_items,
1297             lang_items_missing: lang_items_missing,
1298             native_libraries: native_libraries,
1299             codemap: codemap,
1300             def_path_table: def_path_table,
1301             impls: impls,
1302             exported_symbols: exported_symbols,
1303             index: index,
1304         });
1305
1306         let total_bytes = self.position();
1307
1308         if self.tcx.sess.meta_stats() {
1309             let mut zero_bytes = 0;
1310             for e in self.opaque.cursor.get_ref() {
1311                 if *e == 0 {
1312                     zero_bytes += 1;
1313                 }
1314             }
1315
1316             println!("metadata stats:");
1317             println!("             dep bytes: {}", dep_bytes);
1318             println!("       lang item bytes: {}", lang_item_bytes);
1319             println!("          native bytes: {}", native_lib_bytes);
1320             println!("         codemap bytes: {}", codemap_bytes);
1321             println!("            impl bytes: {}", impl_bytes);
1322             println!("    exp. symbols bytes: {}", exported_symbols_bytes);
1323             println!("  def-path table bytes: {}", def_path_table_bytes);
1324             println!("            item bytes: {}", item_bytes);
1325             println!("           index bytes: {}", index_bytes);
1326             println!("            zero bytes: {}", zero_bytes);
1327             println!("           total bytes: {}", total_bytes);
1328         }
1329
1330         root
1331     }
1332 }
1333
1334 // NOTE(eddyb) The following comment was preserved for posterity, even
1335 // though it's no longer relevant as EBML (which uses nested & tagged
1336 // "documents") was replaced with a scheme that can't go out of bounds.
1337 //
1338 // And here we run into yet another obscure archive bug: in which metadata
1339 // loaded from archives may have trailing garbage bytes. Awhile back one of
1340 // our tests was failing sporadically on the OSX 64-bit builders (both nopt
1341 // and opt) by having ebml generate an out-of-bounds panic when looking at
1342 // metadata.
1343 //
1344 // Upon investigation it turned out that the metadata file inside of an rlib
1345 // (and ar archive) was being corrupted. Some compilations would generate a
1346 // metadata file which would end in a few extra bytes, while other
1347 // compilations would not have these extra bytes appended to the end. These
1348 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1349 // being interpreted causing the out-of-bounds.
1350 //
1351 // The root cause of why these extra bytes were appearing was never
1352 // discovered, and in the meantime the solution we're employing is to insert
1353 // the length of the metadata to the start of the metadata. Later on this
1354 // will allow us to slice the metadata to the precise length that we just
1355 // generated regardless of trailing bytes that end up in it.
1356
1357 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1358                                  cstore: &cstore::CStore,
1359                                  reexports: &def::ExportMap,
1360                                  link_meta: &LinkMeta,
1361                                  exported_symbols: &NodeSet)
1362                                  -> Vec<u8> {
1363     let mut cursor = Cursor::new(vec![]);
1364     cursor.write_all(METADATA_HEADER).unwrap();
1365
1366     // Will be filed with the root position after encoding everything.
1367     cursor.write_all(&[0, 0, 0, 0]).unwrap();
1368
1369     let root = {
1370         let mut ecx = EncodeContext {
1371             opaque: opaque::Encoder::new(&mut cursor),
1372             tcx: tcx,
1373             reexports: reexports,
1374             link_meta: link_meta,
1375             cstore: cstore,
1376             exported_symbols: exported_symbols,
1377             lazy_state: LazyState::NoNode,
1378             type_shorthands: Default::default(),
1379             predicate_shorthands: Default::default(),
1380         };
1381
1382         // Encode the rustc version string in a predictable location.
1383         rustc_version().encode(&mut ecx).unwrap();
1384
1385         // Encode all the entries and extra information in the crate,
1386         // culminating in the `CrateRoot` which points to all of it.
1387         ecx.encode_crate_root()
1388     };
1389     let mut result = cursor.into_inner();
1390
1391     // Encode the root position.
1392     let header = METADATA_HEADER.len();
1393     let pos = root.position;
1394     result[header + 0] = (pos >> 24) as u8;
1395     result[header + 1] = (pos >> 16) as u8;
1396     result[header + 2] = (pos >> 8) as u8;
1397     result[header + 3] = (pos >> 0) as u8;
1398
1399     result
1400 }