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