]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/encoder.rs
2160a56257b59ae050aefacc3240bd8bc3f4fa14
[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                             EncodedMetadata, EncodedMetadataHash};
17 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LOCAL_CRATE};
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, ReprOptions};
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::path::Path;
34 use std::rc::Rc;
35 use std::u32;
36 use syntax::ast::{self, CRATE_NODE_ID};
37 use syntax::codemap::Spanned;
38 use syntax::attr;
39 use syntax::symbol::Symbol;
40 use syntax_pos;
41
42 use rustc::hir::{self, PatKind};
43 use rustc::hir::itemlikevisit::ItemLikeVisitor;
44 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
45 use rustc::hir::intravisit;
46
47 use super::index_builder::{FromId, IndexBuilder, Untracked, EntryBuilder};
48
49 pub struct EncodeContext<'a, 'tcx: 'a> {
50     opaque: opaque::Encoder<'a>,
51     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
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     pub metadata_hashes: Vec<EncodedMetadataHash>,
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     pub 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     pub 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
242 impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
243     fn encode_item_variances(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
244         debug!("EntryBuilder::encode_item_variances({:?})", def_id);
245         let tcx = self.tcx;
246         self.lazy_seq_from_slice(&tcx.variances_of(def_id))
247     }
248
249     fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
250         let tcx = self.tcx;
251         let ty = tcx.type_of(def_id);
252         debug!("EntryBuilder::encode_item_type({:?}) => {:?}", def_id, ty);
253         self.lazy(&ty)
254     }
255
256     /// Encode data for the given variant of the given ADT. The
257     /// index of the variant is untracked: this is ok because we
258     /// will have to lookup the adt-def by its id, and that gives us
259     /// the right to access any information in the adt-def (including,
260     /// e.g., the length of the various vectors).
261     fn encode_enum_variant_info(&mut self,
262                                 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
263                                 -> Entry<'tcx> {
264         let tcx = self.tcx;
265         let def = tcx.adt_def(enum_did);
266         let variant = &def.variants[index];
267         let def_id = variant.did;
268         debug!("EntryBuilder::encode_enum_variant_info({:?})", def_id);
269
270         let data = VariantData {
271             ctor_kind: variant.ctor_kind,
272             discr: variant.discr,
273             struct_ctor: None,
274         };
275
276         let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
277         let enum_vis = &tcx.hir.expect_item(enum_id).vis;
278
279         Entry {
280             kind: EntryKind::Variant(self.lazy(&data)),
281             visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
282             span: self.lazy(&tcx.def_span(def_id)),
283             attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
284             children: self.lazy_seq(variant.fields.iter().map(|f| {
285                 assert!(f.did.is_local());
286                 f.did.index
287             })),
288             stability: self.encode_stability(def_id),
289             deprecation: self.encode_deprecation(def_id),
290
291             ty: Some(self.encode_item_type(def_id)),
292             inherent_impls: LazySeq::empty(),
293             variances: LazySeq::empty(),
294             generics: Some(self.encode_generics(def_id)),
295             predicates: Some(self.encode_predicates(def_id)),
296
297             ast: None,
298             mir: self.encode_mir(def_id),
299         }
300     }
301
302     fn encode_info_for_mod(&mut self,
303                            FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
304                                                                  &[ast::Attribute],
305                                                                  &hir::Visibility)>)
306                            -> Entry<'tcx> {
307         let tcx = self.tcx;
308         let def_id = tcx.hir.local_def_id(id);
309         debug!("EntryBuilder::encode_info_for_mod({:?})", def_id);
310
311         let data = ModData {
312             reexports: match tcx.export_map.get(&id) {
313                 Some(exports) if *vis == hir::Public => {
314                     self.lazy_seq_from_slice(exports.as_slice())
315                 }
316                 _ => LazySeq::empty(),
317             },
318         };
319
320         Entry {
321             kind: EntryKind::Mod(self.lazy(&data)),
322             visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
323             span: self.lazy(&md.inner),
324             attributes: self.encode_attributes(attrs),
325             children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
326                 tcx.hir.local_def_id(item_id.id).index
327             })),
328             stability: self.encode_stability(def_id),
329             deprecation: self.encode_deprecation(def_id),
330
331             ty: None,
332             inherent_impls: LazySeq::empty(),
333             variances: LazySeq::empty(),
334             generics: None,
335             predicates: None,
336
337             ast: None,
338             mir: None
339         }
340     }
341 }
342
343 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
344     fn encode_fields(&mut self, adt_def_id: DefId) {
345         let def = self.tcx.adt_def(adt_def_id);
346         for (variant_index, variant) in def.variants.iter().enumerate() {
347             for (field_index, field) in variant.fields.iter().enumerate() {
348                 self.record(field.did,
349                             EntryBuilder::encode_field,
350                             (adt_def_id, Untracked((variant_index, field_index))));
351             }
352         }
353     }
354 }
355
356 impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
357     /// Encode data for the given field of the given variant of the
358     /// given ADT. The indices of the variant/field are untracked:
359     /// this is ok because we will have to lookup the adt-def by its
360     /// id, and that gives us the right to access any information in
361     /// the adt-def (including, e.g., the length of the various
362     /// vectors).
363     fn encode_field(&mut self,
364                     (adt_def_id, Untracked((variant_index, field_index))): (DefId,
365                                                                             Untracked<(usize,
366                                                                                        usize)>))
367                     -> Entry<'tcx> {
368         let tcx = self.tcx;
369         let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
370         let field = &variant.fields[field_index];
371
372         let def_id = field.did;
373         debug!("EntryBuilder::encode_field({:?})", def_id);
374
375         let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
376         let variant_data = tcx.hir.expect_variant_data(variant_id);
377
378         Entry {
379             kind: EntryKind::Field,
380             visibility: self.lazy(&field.vis),
381             span: self.lazy(&tcx.def_span(def_id)),
382             attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
383             children: LazySeq::empty(),
384             stability: self.encode_stability(def_id),
385             deprecation: self.encode_deprecation(def_id),
386
387             ty: Some(self.encode_item_type(def_id)),
388             inherent_impls: LazySeq::empty(),
389             variances: LazySeq::empty(),
390             generics: Some(self.encode_generics(def_id)),
391             predicates: Some(self.encode_predicates(def_id)),
392
393             ast: None,
394             mir: None,
395         }
396     }
397
398     fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
399         debug!("EntryBuilder::encode_struct_ctor({:?})", def_id);
400         let tcx = self.tcx;
401         let variant = tcx.adt_def(adt_def_id).struct_variant();
402
403         let data = VariantData {
404             ctor_kind: variant.ctor_kind,
405             discr: variant.discr,
406             struct_ctor: Some(def_id.index),
407         };
408
409         let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
410         let struct_vis = &tcx.hir.expect_item(struct_id).vis;
411         let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
412         for field in &variant.fields {
413             if ctor_vis.is_at_least(field.vis, tcx) {
414                 ctor_vis = field.vis;
415             }
416         }
417
418         let repr_options = get_repr_options(&tcx, adt_def_id);
419
420         Entry {
421             kind: EntryKind::Struct(self.lazy(&data), repr_options),
422             visibility: self.lazy(&ctor_vis),
423             span: self.lazy(&tcx.def_span(def_id)),
424             attributes: LazySeq::empty(),
425             children: LazySeq::empty(),
426             stability: self.encode_stability(def_id),
427             deprecation: self.encode_deprecation(def_id),
428
429             ty: Some(self.encode_item_type(def_id)),
430             inherent_impls: LazySeq::empty(),
431             variances: LazySeq::empty(),
432             generics: Some(self.encode_generics(def_id)),
433             predicates: Some(self.encode_predicates(def_id)),
434
435             ast: None,
436             mir: self.encode_mir(def_id),
437         }
438     }
439
440     fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
441         debug!("EntryBuilder::encode_generics({:?})", def_id);
442         let tcx = self.tcx;
443         self.lazy(tcx.generics_of(def_id))
444     }
445
446     fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
447         debug!("EntryBuilder::encode_predicates({:?})", def_id);
448         let tcx = self.tcx;
449         self.lazy(&tcx.predicates_of(def_id))
450     }
451
452     fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
453         debug!("EntryBuilder::encode_info_for_trait_item({:?})", def_id);
454         let tcx = self.tcx;
455
456         let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
457         let ast_item = tcx.hir.expect_trait_item(node_id);
458         let trait_item = tcx.associated_item(def_id);
459
460         let container = match trait_item.defaultness {
461             hir::Defaultness::Default { has_value: true } =>
462                 AssociatedContainer::TraitWithDefault,
463             hir::Defaultness::Default { has_value: false } =>
464                 AssociatedContainer::TraitRequired,
465             hir::Defaultness::Final =>
466                 span_bug!(ast_item.span, "traits cannot have final items"),
467         };
468
469         let kind = match trait_item.kind {
470             ty::AssociatedKind::Const => {
471                 EntryKind::AssociatedConst(container, 0)
472             }
473             ty::AssociatedKind::Method => {
474                 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
475                     let arg_names = match *m {
476                         hir::TraitMethod::Required(ref names) => {
477                             self.encode_fn_arg_names(names)
478                         }
479                         hir::TraitMethod::Provided(body) => {
480                             self.encode_fn_arg_names_for_body(body)
481                         }
482                     };
483                     FnData {
484                         constness: hir::Constness::NotConst,
485                         arg_names: arg_names
486                     }
487                 } else {
488                     bug!()
489                 };
490                 EntryKind::Method(self.lazy(&MethodData {
491                     fn_data: fn_data,
492                     container: container,
493                     has_self: trait_item.method_has_self_argument,
494                 }))
495             }
496             ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
497         };
498
499         Entry {
500             kind: kind,
501             visibility: self.lazy(&trait_item.vis),
502             span: self.lazy(&ast_item.span),
503             attributes: self.encode_attributes(&ast_item.attrs),
504             children: LazySeq::empty(),
505             stability: self.encode_stability(def_id),
506             deprecation: self.encode_deprecation(def_id),
507
508             ty: match trait_item.kind {
509                 ty::AssociatedKind::Const |
510                 ty::AssociatedKind::Method => {
511                     Some(self.encode_item_type(def_id))
512                 }
513                 ty::AssociatedKind::Type => {
514                     if trait_item.defaultness.has_value() {
515                         Some(self.encode_item_type(def_id))
516                     } else {
517                         None
518                     }
519                 }
520             },
521             inherent_impls: LazySeq::empty(),
522             variances: LazySeq::empty(),
523             generics: Some(self.encode_generics(def_id)),
524             predicates: Some(self.encode_predicates(def_id)),
525
526             ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
527                 Some(self.encode_body(body))
528             } else {
529                 None
530             },
531             mir: self.encode_mir(def_id),
532         }
533     }
534
535     fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
536         debug!("EntryBuilder::encode_info_for_impl_item({:?})", def_id);
537         let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
538         let ast_item = self.tcx.hir.expect_impl_item(node_id);
539         let impl_item = self.tcx.associated_item(def_id);
540
541         let container = match impl_item.defaultness {
542             hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
543             hir::Defaultness::Final => AssociatedContainer::ImplFinal,
544             hir::Defaultness::Default { has_value: false } =>
545                 span_bug!(ast_item.span, "impl items always have values (currently)"),
546         };
547
548         let kind = match impl_item.kind {
549             ty::AssociatedKind::Const => {
550                 EntryKind::AssociatedConst(container,
551                     self.tcx.at(ast_item.span).mir_const_qualif(def_id))
552             }
553             ty::AssociatedKind::Method => {
554                 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
555                     FnData {
556                         constness: sig.constness,
557                         arg_names: self.encode_fn_arg_names_for_body(body),
558                     }
559                 } else {
560                     bug!()
561                 };
562                 EntryKind::Method(self.lazy(&MethodData {
563                     fn_data: fn_data,
564                     container: container,
565                     has_self: impl_item.method_has_self_argument,
566                 }))
567             }
568             ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
569         };
570
571         let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
572             (Some(body), true)
573         } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
574             let generics = self.tcx.generics_of(def_id);
575             let types = generics.parent_types as usize + generics.types.len();
576             let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
577             let is_const_fn = sig.constness == hir::Constness::Const;
578             let ast = if is_const_fn { Some(body) } else { None };
579             let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
580             (ast, needs_inline || is_const_fn || always_encode_mir)
581         } else {
582             (None, false)
583         };
584
585         Entry {
586             kind: kind,
587             visibility: self.lazy(&impl_item.vis),
588             span: self.lazy(&ast_item.span),
589             attributes: self.encode_attributes(&ast_item.attrs),
590             children: LazySeq::empty(),
591             stability: self.encode_stability(def_id),
592             deprecation: self.encode_deprecation(def_id),
593
594             ty: Some(self.encode_item_type(def_id)),
595             inherent_impls: LazySeq::empty(),
596             variances: LazySeq::empty(),
597             generics: Some(self.encode_generics(def_id)),
598             predicates: Some(self.encode_predicates(def_id)),
599
600             ast: ast.map(|body| self.encode_body(body)),
601             mir: if mir { self.encode_mir(def_id) } else { None },
602         }
603     }
604
605     fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
606                                     -> LazySeq<ast::Name> {
607         let _ignore = self.tcx.dep_graph.in_ignore();
608         let body = self.tcx.hir.body(body_id);
609         self.lazy_seq(body.arguments.iter().map(|arg| {
610             match arg.pat.node {
611                 PatKind::Binding(_, _, name, _) => name.node,
612                 _ => Symbol::intern("")
613             }
614         }))
615     }
616
617     fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
618                            -> LazySeq<ast::Name> {
619         self.lazy_seq(names.iter().map(|name| name.node))
620     }
621
622     fn encode_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
623         debug!("EntryBuilder::encode_mir({:?})", def_id);
624         if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
625             let mir = self.tcx.item_mir(def_id);
626             Some(self.lazy(&mir))
627         } else {
628             None
629         }
630     }
631
632     // Encodes the inherent implementations of a structure, enumeration, or trait.
633     fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
634         debug!("EntryBuilder::encode_inherent_implementations({:?})", def_id);
635         let implementations = self.tcx.inherent_impls(def_id);
636         if implementations.is_empty() {
637             LazySeq::empty()
638         } else {
639             self.lazy_seq(implementations.iter().map(|&def_id| {
640                 assert!(def_id.is_local());
641                 def_id.index
642             }))
643         }
644     }
645
646     fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
647         debug!("EntryBuilder::encode_stability({:?})", def_id);
648         self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
649     }
650
651     fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
652         debug!("EntryBuilder::encode_deprecation({:?})", def_id);
653         self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
654     }
655
656     fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
657         let tcx = self.tcx;
658
659         debug!("EntryBuilder::encode_info_for_item({:?})", def_id);
660
661         let kind = match item.node {
662             hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
663             hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
664             hir::ItemConst(..) => {
665                 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id))
666             }
667             hir::ItemFn(_, _, constness, .., body) => {
668                 let data = FnData {
669                     constness: constness,
670                     arg_names: self.encode_fn_arg_names_for_body(body),
671                 };
672
673                 EntryKind::Fn(self.lazy(&data))
674             }
675             hir::ItemMod(ref m) => {
676                 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
677             }
678             hir::ItemForeignMod(_) => EntryKind::ForeignMod,
679             hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
680             hir::ItemTy(..) => EntryKind::Type,
681             hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
682             hir::ItemStruct(ref struct_def, _) => {
683                 let variant = tcx.adt_def(def_id).struct_variant();
684
685                 // Encode def_ids for each field and method
686                 // for methods, write all the stuff get_trait_method
687                 // needs to know
688                 let struct_ctor = if !struct_def.is_struct() {
689                     Some(tcx.hir.local_def_id(struct_def.id()).index)
690                 } else {
691                     None
692                 };
693
694                 let repr_options = get_repr_options(&tcx, def_id);
695
696                 EntryKind::Struct(self.lazy(&VariantData {
697                     ctor_kind: variant.ctor_kind,
698                     discr: variant.discr,
699                     struct_ctor: struct_ctor,
700                 }), repr_options)
701             }
702             hir::ItemUnion(..) => {
703                 let variant = tcx.adt_def(def_id).struct_variant();
704                 let repr_options = get_repr_options(&tcx, def_id);
705
706                 EntryKind::Union(self.lazy(&VariantData {
707                     ctor_kind: variant.ctor_kind,
708                     discr: variant.discr,
709                     struct_ctor: None,
710                 }), repr_options)
711             }
712             hir::ItemDefaultImpl(..) => {
713                 let data = ImplData {
714                     polarity: hir::ImplPolarity::Positive,
715                     defaultness: hir::Defaultness::Final,
716                     parent_impl: None,
717                     coerce_unsized_info: None,
718                     trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref)),
719                 };
720
721                 EntryKind::DefaultImpl(self.lazy(&data))
722             }
723             hir::ItemImpl(_, polarity, defaultness, ..) => {
724                 let trait_ref = tcx.impl_trait_ref(def_id);
725                 let parent = if let Some(trait_ref) = trait_ref {
726                     let trait_def = tcx.trait_def(trait_ref.def_id);
727                     trait_def.ancestors(def_id).skip(1).next().and_then(|node| {
728                         match node {
729                             specialization_graph::Node::Impl(parent) => Some(parent),
730                             _ => None,
731                         }
732                     })
733                 } else {
734                     None
735                 };
736
737                 // if this is an impl of `CoerceUnsized`, create its
738                 // "unsized info", else just store None
739                 let coerce_unsized_info =
740                     trait_ref.and_then(|t| {
741                         if Some(t.def_id) == tcx.lang_items.coerce_unsized_trait() {
742                             Some(tcx.at(item.span).coerce_unsized_info(def_id))
743                         } else {
744                             None
745                         }
746                     });
747
748                 let data = ImplData {
749                     polarity: polarity,
750                     defaultness: defaultness,
751                     parent_impl: parent,
752                     coerce_unsized_info: coerce_unsized_info,
753                     trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
754                 };
755
756                 EntryKind::Impl(self.lazy(&data))
757             }
758             hir::ItemTrait(..) => {
759                 let trait_def = tcx.trait_def(def_id);
760                 let data = TraitData {
761                     unsafety: trait_def.unsafety,
762                     paren_sugar: trait_def.paren_sugar,
763                     has_default_impl: tcx.trait_has_default_impl(def_id),
764                     super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
765                 };
766
767                 EntryKind::Trait(self.lazy(&data))
768             }
769             hir::ItemExternCrate(_) |
770             hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
771         };
772
773         Entry {
774             kind: kind,
775             visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
776             span: self.lazy(&item.span),
777             attributes: self.encode_attributes(&item.attrs),
778             children: match item.node {
779                 hir::ItemForeignMod(ref fm) => {
780                     self.lazy_seq(fm.items
781                         .iter()
782                         .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
783                 }
784                 hir::ItemEnum(..) => {
785                     let def = self.tcx.adt_def(def_id);
786                     self.lazy_seq(def.variants.iter().map(|v| {
787                         assert!(v.did.is_local());
788                         v.did.index
789                     }))
790                 }
791                 hir::ItemStruct(..) |
792                 hir::ItemUnion(..) => {
793                     let def = self.tcx.adt_def(def_id);
794                     self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
795                         assert!(f.did.is_local());
796                         f.did.index
797                     }))
798                 }
799                 hir::ItemImpl(..) |
800                 hir::ItemTrait(..) => {
801                     self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
802                         assert!(def_id.is_local());
803                         def_id.index
804                     }))
805                 }
806                 _ => LazySeq::empty(),
807             },
808             stability: self.encode_stability(def_id),
809             deprecation: self.encode_deprecation(def_id),
810
811             ty: match item.node {
812                 hir::ItemStatic(..) |
813                 hir::ItemConst(..) |
814                 hir::ItemFn(..) |
815                 hir::ItemTy(..) |
816                 hir::ItemEnum(..) |
817                 hir::ItemStruct(..) |
818                 hir::ItemUnion(..) |
819                 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
820                 _ => None,
821             },
822             inherent_impls: self.encode_inherent_implementations(def_id),
823             variances: match item.node {
824                 hir::ItemEnum(..) |
825                 hir::ItemStruct(..) |
826                 hir::ItemUnion(..) |
827                 hir::ItemTrait(..) => self.encode_item_variances(def_id),
828                 _ => LazySeq::empty(),
829             },
830             generics: match item.node {
831                 hir::ItemStatic(..) |
832                 hir::ItemConst(..) |
833                 hir::ItemFn(..) |
834                 hir::ItemTy(..) |
835                 hir::ItemEnum(..) |
836                 hir::ItemStruct(..) |
837                 hir::ItemUnion(..) |
838                 hir::ItemImpl(..) |
839                 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
840                 _ => None,
841             },
842             predicates: match item.node {
843                 hir::ItemStatic(..) |
844                 hir::ItemConst(..) |
845                 hir::ItemFn(..) |
846                 hir::ItemTy(..) |
847                 hir::ItemEnum(..) |
848                 hir::ItemStruct(..) |
849                 hir::ItemUnion(..) |
850                 hir::ItemImpl(..) |
851                 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
852                 _ => None,
853             },
854
855             ast: match item.node {
856                 hir::ItemConst(_, body) |
857                 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
858                     Some(self.encode_body(body))
859                 }
860                 _ => None,
861             },
862             mir: match item.node {
863                 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
864                     self.encode_mir(def_id)
865                 }
866                 hir::ItemConst(..) => self.encode_mir(def_id),
867                 hir::ItemFn(_, _, constness, _, ref generics, _) => {
868                     let tps_len = generics.ty_params.len();
869                     let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
870                     let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
871                     if needs_inline || constness == hir::Constness::Const || always_encode_mir {
872                         self.encode_mir(def_id)
873                     } else {
874                         None
875                     }
876                 }
877                 _ => None,
878             },
879         }
880     }
881
882     /// Serialize the text of exported macros
883     fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
884         use syntax::print::pprust;
885         Entry {
886             kind: EntryKind::MacroDef(self.lazy(&MacroDef {
887                 body: pprust::tts_to_string(&macro_def.body.trees().collect::<Vec<_>>()),
888             })),
889             visibility: self.lazy(&ty::Visibility::Public),
890             span: self.lazy(&macro_def.span),
891
892             attributes: self.encode_attributes(&macro_def.attrs),
893             children: LazySeq::empty(),
894             stability: None,
895             deprecation: None,
896             ty: None,
897             inherent_impls: LazySeq::empty(),
898             variances: LazySeq::empty(),
899             generics: None,
900             predicates: None,
901             ast: None,
902             mir: None,
903         }
904     }
905 }
906
907 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
908     /// In some cases, along with the item itself, we also
909     /// encode some sub-items. Usually we want some info from the item
910     /// so it's easier to do that here then to wait until we would encounter
911     /// normally in the visitor walk.
912     fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
913         let def_id = self.tcx.hir.local_def_id(item.id);
914         match item.node {
915             hir::ItemStatic(..) |
916             hir::ItemConst(..) |
917             hir::ItemFn(..) |
918             hir::ItemMod(..) |
919             hir::ItemForeignMod(..) |
920             hir::ItemGlobalAsm(..) |
921             hir::ItemExternCrate(..) |
922             hir::ItemUse(..) |
923             hir::ItemDefaultImpl(..) |
924             hir::ItemTy(..) => {
925                 // no sub-item recording needed in these cases
926             }
927             hir::ItemEnum(..) => {
928                 self.encode_fields(def_id);
929
930                 let def = self.tcx.adt_def(def_id);
931                 for (i, variant) in def.variants.iter().enumerate() {
932                     self.record(variant.did,
933                                 EntryBuilder::encode_enum_variant_info,
934                                 (def_id, Untracked(i)));
935                 }
936             }
937             hir::ItemStruct(ref struct_def, _) => {
938                 self.encode_fields(def_id);
939
940                 // If the struct has a constructor, encode it.
941                 if !struct_def.is_struct() {
942                     let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
943                     self.record(ctor_def_id,
944                                 EntryBuilder::encode_struct_ctor,
945                                 (def_id, ctor_def_id));
946                 }
947             }
948             hir::ItemUnion(..) => {
949                 self.encode_fields(def_id);
950             }
951             hir::ItemImpl(..) => {
952                 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
953                     self.record(trait_item_def_id,
954                                 EntryBuilder::encode_info_for_impl_item,
955                                 trait_item_def_id);
956                 }
957             }
958             hir::ItemTrait(..) => {
959                 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
960                     self.record(item_def_id,
961                                 EntryBuilder::encode_info_for_trait_item,
962                                 item_def_id);
963                 }
964             }
965         }
966     }
967 }
968
969 impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
970     fn encode_info_for_foreign_item(&mut self,
971                                     (def_id, nitem): (DefId, &hir::ForeignItem))
972                                     -> Entry<'tcx> {
973         let tcx = self.tcx;
974
975         debug!("EntryBuilder::encode_info_for_foreign_item({:?})", def_id);
976
977         let kind = match nitem.node {
978             hir::ForeignItemFn(_, ref names, _) => {
979                 let data = FnData {
980                     constness: hir::Constness::NotConst,
981                     arg_names: self.encode_fn_arg_names(names),
982                 };
983                 EntryKind::ForeignFn(self.lazy(&data))
984             }
985             hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
986             hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
987         };
988
989         Entry {
990             kind: kind,
991             visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
992             span: self.lazy(&nitem.span),
993             attributes: self.encode_attributes(&nitem.attrs),
994             children: LazySeq::empty(),
995             stability: self.encode_stability(def_id),
996             deprecation: self.encode_deprecation(def_id),
997
998             ty: Some(self.encode_item_type(def_id)),
999             inherent_impls: LazySeq::empty(),
1000             variances: LazySeq::empty(),
1001             generics: Some(self.encode_generics(def_id)),
1002             predicates: Some(self.encode_predicates(def_id)),
1003
1004             ast: None,
1005             mir: None,
1006         }
1007     }
1008 }
1009
1010 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1011     index: IndexBuilder<'a, 'b, 'tcx>,
1012 }
1013
1014 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1015     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1016         NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1017     }
1018     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1019         intravisit::walk_expr(self, ex);
1020         self.index.encode_info_for_expr(ex);
1021     }
1022     fn visit_item(&mut self, item: &'tcx hir::Item) {
1023         intravisit::walk_item(self, item);
1024         let def_id = self.index.tcx.hir.local_def_id(item.id);
1025         match item.node {
1026             hir::ItemExternCrate(_) |
1027             hir::ItemUse(..) => (), // ignore these
1028             _ => self.index.record(def_id, EntryBuilder::encode_info_for_item, (def_id, item)),
1029         }
1030         self.index.encode_addl_info_for_item(item);
1031     }
1032     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1033         intravisit::walk_foreign_item(self, ni);
1034         let def_id = self.index.tcx.hir.local_def_id(ni.id);
1035         self.index.record(def_id,
1036                           EntryBuilder::encode_info_for_foreign_item,
1037                           (def_id, ni));
1038     }
1039     fn visit_variant(&mut self,
1040                      v: &'tcx hir::Variant,
1041                      g: &'tcx hir::Generics,
1042                      id: ast::NodeId) {
1043         intravisit::walk_variant(self, v, g, id);
1044
1045         if let Some(discr) = v.node.disr_expr {
1046             let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1047             self.index.record(def_id, EntryBuilder::encode_info_for_embedded_const, def_id);
1048         }
1049     }
1050     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1051         intravisit::walk_generics(self, generics);
1052         self.index.encode_info_for_generics(generics);
1053     }
1054     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1055         intravisit::walk_ty(self, ty);
1056         self.index.encode_info_for_ty(ty);
1057     }
1058     fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1059         let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1060         self.index.record(def_id, EntryBuilder::encode_info_for_macro_def, macro_def);
1061     }
1062 }
1063
1064 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1065     fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1066         for ty_param in &generics.ty_params {
1067             let def_id = self.tcx.hir.local_def_id(ty_param.id);
1068             let has_default = Untracked(ty_param.default.is_some());
1069             self.record(def_id, EntryBuilder::encode_info_for_ty_param, (def_id, has_default));
1070         }
1071     }
1072
1073     fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1074         if let hir::TyImplTrait(_) = ty.node {
1075             let def_id = self.tcx.hir.local_def_id(ty.id);
1076             self.record(def_id, EntryBuilder::encode_info_for_anon_ty, def_id);
1077         }
1078     }
1079
1080     fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1081         match expr.node {
1082             hir::ExprClosure(..) => {
1083                 let def_id = self.tcx.hir.local_def_id(expr.id);
1084                 self.record(def_id, EntryBuilder::encode_info_for_closure, def_id);
1085             }
1086             _ => {}
1087         }
1088     }
1089 }
1090
1091 impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
1092     fn encode_info_for_ty_param(&mut self,
1093                                 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1094                                 -> Entry<'tcx> {
1095         debug!("EntryBuilder::encode_info_for_ty_param({:?})", def_id);
1096         let tcx = self.tcx;
1097         Entry {
1098             kind: EntryKind::Type,
1099             visibility: self.lazy(&ty::Visibility::Public),
1100             span: self.lazy(&tcx.def_span(def_id)),
1101             attributes: LazySeq::empty(),
1102             children: LazySeq::empty(),
1103             stability: None,
1104             deprecation: None,
1105
1106             ty: if has_default {
1107                 Some(self.encode_item_type(def_id))
1108             } else {
1109                 None
1110             },
1111             inherent_impls: LazySeq::empty(),
1112             variances: LazySeq::empty(),
1113             generics: None,
1114             predicates: None,
1115
1116             ast: None,
1117             mir: None,
1118         }
1119     }
1120
1121     fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1122         debug!("EntryBuilder::encode_info_for_anon_ty({:?})", def_id);
1123         let tcx = self.tcx;
1124         Entry {
1125             kind: EntryKind::Type,
1126             visibility: self.lazy(&ty::Visibility::Public),
1127             span: self.lazy(&tcx.def_span(def_id)),
1128             attributes: LazySeq::empty(),
1129             children: LazySeq::empty(),
1130             stability: None,
1131             deprecation: None,
1132
1133             ty: Some(self.encode_item_type(def_id)),
1134             inherent_impls: LazySeq::empty(),
1135             variances: LazySeq::empty(),
1136             generics: Some(self.encode_generics(def_id)),
1137             predicates: Some(self.encode_predicates(def_id)),
1138
1139             ast: None,
1140             mir: None,
1141         }
1142     }
1143
1144     fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1145         debug!("EntryBuilder::encode_info_for_closure({:?})", def_id);
1146         let tcx = self.tcx;
1147
1148         let data = ClosureData {
1149             kind: tcx.closure_kind(def_id),
1150             ty: self.lazy(&tcx.closure_type(def_id)),
1151         };
1152
1153         Entry {
1154             kind: EntryKind::Closure(self.lazy(&data)),
1155             visibility: self.lazy(&ty::Visibility::Public),
1156             span: self.lazy(&tcx.def_span(def_id)),
1157             attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1158             children: LazySeq::empty(),
1159             stability: None,
1160             deprecation: None,
1161
1162             ty: Some(self.encode_item_type(def_id)),
1163             inherent_impls: LazySeq::empty(),
1164             variances: LazySeq::empty(),
1165             generics: Some(self.encode_generics(def_id)),
1166             predicates: None,
1167
1168             ast: None,
1169             mir: self.encode_mir(def_id),
1170         }
1171     }
1172
1173     fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1174         debug!("EntryBuilder::encode_info_for_embedded_const({:?})", def_id);
1175         let tcx = self.tcx;
1176         let id = tcx.hir.as_local_node_id(def_id).unwrap();
1177         let body = tcx.hir.body_owned_by(id);
1178
1179         Entry {
1180             kind: EntryKind::Const(tcx.mir_const_qualif(def_id)),
1181             visibility: self.lazy(&ty::Visibility::Public),
1182             span: self.lazy(&tcx.def_span(def_id)),
1183             attributes: LazySeq::empty(),
1184             children: LazySeq::empty(),
1185             stability: None,
1186             deprecation: None,
1187
1188             ty: Some(self.encode_item_type(def_id)),
1189             inherent_impls: LazySeq::empty(),
1190             variances: LazySeq::empty(),
1191             generics: Some(self.encode_generics(def_id)),
1192             predicates: Some(self.encode_predicates(def_id)),
1193
1194             ast: Some(self.encode_body(body)),
1195             mir: self.encode_mir(def_id),
1196         }
1197     }
1198
1199     fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1200         // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1201         //       we really on the HashStable specialization for [Attribute]
1202         //       to properly filter things out.
1203         self.lazy_seq_from_slice(attrs)
1204     }
1205 }
1206
1207 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1208     fn encode_info_for_items(&mut self) -> Index {
1209         let krate = self.tcx.hir.krate();
1210         let mut index = IndexBuilder::new(self);
1211         index.record(DefId::local(CRATE_DEF_INDEX),
1212                      EntryBuilder::encode_info_for_mod,
1213                      FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
1214         let mut visitor = EncodeVisitor { index: index };
1215         krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
1216         for macro_def in &krate.exported_macros {
1217             visitor.visit_macro_def(macro_def);
1218         }
1219         visitor.index.into_items()
1220     }
1221
1222     fn encode_crate_deps(&mut self) -> LazySeq<CrateDep> {
1223         fn get_ordered_deps(cstore: &cstore::CStore) -> Vec<(CrateNum, Rc<cstore::CrateMetadata>)> {
1224             // Pull the cnums and name,vers,hash out of cstore
1225             let mut deps = Vec::new();
1226             cstore.iter_crate_data(|cnum, val| {
1227                 deps.push((cnum, val.clone()));
1228             });
1229
1230             // Sort by cnum
1231             deps.sort_by(|kv1, kv2| kv1.0.cmp(&kv2.0));
1232
1233             // Sanity-check the crate numbers
1234             let mut expected_cnum = 1;
1235             for &(n, _) in &deps {
1236                 assert_eq!(n, CrateNum::new(expected_cnum));
1237                 expected_cnum += 1;
1238             }
1239
1240             deps
1241         }
1242
1243         // We're just going to write a list of crate 'name-hash-version's, with
1244         // the assumption that they are numbered 1 to n.
1245         // FIXME (#2166): This is not nearly enough to support correct versioning
1246         // but is enough to get transitive crate dependencies working.
1247         let deps = get_ordered_deps(self.cstore);
1248         self.lazy_seq(deps.iter().map(|&(_, ref dep)| {
1249             CrateDep {
1250                 name: dep.name(),
1251                 hash: dep.hash(),
1252                 kind: dep.dep_kind.get(),
1253             }
1254         }))
1255     }
1256
1257     fn encode_lang_items(&mut self) -> (LazySeq<(DefIndex, usize)>, LazySeq<lang_items::LangItem>) {
1258         let tcx = self.tcx;
1259         let lang_items = tcx.lang_items.items().iter();
1260         (self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1261             if let Some(def_id) = opt_def_id {
1262                 if def_id.is_local() {
1263                     return Some((def_id.index, i));
1264                 }
1265             }
1266             None
1267         })),
1268          self.lazy_seq_ref(&tcx.lang_items.missing))
1269     }
1270
1271     fn encode_native_libraries(&mut self) -> LazySeq<NativeLibrary> {
1272         let used_libraries = self.tcx.sess.cstore.used_libraries();
1273         self.lazy_seq(used_libraries)
1274     }
1275
1276     fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
1277         let codemap = self.tcx.sess.codemap();
1278         let all_filemaps = codemap.files.borrow();
1279         let adapted = all_filemaps.iter()
1280             .filter(|filemap| {
1281                 // No need to re-export imported filemaps, as any downstream
1282                 // crate will import them from their original source.
1283                 !filemap.is_imported()
1284             })
1285             .map(|filemap| {
1286                 // When exporting FileMaps, we expand all paths to absolute
1287                 // paths because any relative paths are potentially relative to
1288                 // a wrong directory.
1289                 // However, if a path has been modified via
1290                 // `-Zremap-path-prefix` we assume the user has already set
1291                 // things up the way they want and don't touch the path values
1292                 // anymore.
1293                 let name = Path::new(&filemap.name);
1294                 let (ref working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir;
1295                 if filemap.name_was_remapped ||
1296                    (name.is_relative() && working_dir_was_remapped) {
1297                     // This path of this FileMap has been modified by
1298                     // path-remapping, so we use it verbatim (and avoid cloning
1299                     // the whole map in the process).
1300                     filemap.clone()
1301                 } else {
1302                     let mut adapted = (**filemap).clone();
1303                     let abs_path = Path::new(working_dir).join(name)
1304                                                          .to_string_lossy()
1305                                                          .into_owned();
1306                     adapted.name = abs_path;
1307                     Rc::new(adapted)
1308                 }
1309             })
1310             .collect::<Vec<_>>();
1311
1312         self.lazy_seq_ref(adapted.iter().map(|fm| &**fm))
1313     }
1314
1315     fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
1316         let definitions = self.tcx.hir.definitions();
1317         self.lazy(definitions.def_path_table())
1318     }
1319 }
1320
1321 struct ImplVisitor<'a, 'tcx: 'a> {
1322     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1323     impls: FxHashMap<DefId, Vec<DefIndex>>,
1324 }
1325
1326 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1327     fn visit_item(&mut self, item: &hir::Item) {
1328         if let hir::ItemImpl(..) = item.node {
1329             let impl_id = self.tcx.hir.local_def_id(item.id);
1330             if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1331                 self.impls
1332                     .entry(trait_ref.def_id)
1333                     .or_insert(vec![])
1334                     .push(impl_id.index);
1335             }
1336         }
1337     }
1338
1339     fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1340
1341     fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1342         // handled in `visit_item` above
1343     }
1344 }
1345
1346 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1347     /// Encodes an index, mapping each trait to its (local) implementations.
1348     fn encode_impls(&mut self) -> LazySeq<TraitImpls> {
1349         let mut visitor = ImplVisitor {
1350             tcx: self.tcx,
1351             impls: FxHashMap(),
1352         };
1353         self.tcx.hir.krate().visit_all_item_likes(&mut visitor);
1354
1355         let all_impls: Vec<_> = visitor.impls
1356             .into_iter()
1357             .map(|(trait_def_id, impls)| {
1358                 TraitImpls {
1359                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1360                     impls: self.lazy_seq(impls),
1361                 }
1362             })
1363             .collect();
1364
1365         self.lazy_seq(all_impls)
1366     }
1367
1368     // Encodes all symbols exported from this crate into the metadata.
1369     //
1370     // This pass is seeded off the reachability list calculated in the
1371     // middle::reachable module but filters out items that either don't have a
1372     // symbol associated with them (they weren't translated) or if they're an FFI
1373     // definition (as that's not defined in this crate).
1374     fn encode_exported_symbols(&mut self) -> LazySeq<DefIndex> {
1375         let exported_symbols = self.exported_symbols;
1376         let tcx = self.tcx;
1377         self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
1378     }
1379
1380     fn encode_dylib_dependency_formats(&mut self) -> LazySeq<Option<LinkagePreference>> {
1381         match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1382             Some(arr) => {
1383                 self.lazy_seq(arr.iter().map(|slot| {
1384                     match *slot {
1385                         Linkage::NotLinked |
1386                         Linkage::IncludedFromDylib => None,
1387
1388                         Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1389                         Linkage::Static => Some(LinkagePreference::RequireStatic),
1390                     }
1391                 }))
1392             }
1393             None => LazySeq::empty(),
1394         }
1395     }
1396 }
1397
1398 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1399     fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
1400         let mut i = self.position();
1401         let crate_deps = self.encode_crate_deps();
1402         let dylib_dependency_formats = self.encode_dylib_dependency_formats();
1403         let dep_bytes = self.position() - i;
1404
1405         // Encode the language items.
1406         i = self.position();
1407         let (lang_items, lang_items_missing) = self.encode_lang_items();
1408         let lang_item_bytes = self.position() - i;
1409
1410         // Encode the native libraries used
1411         i = self.position();
1412         let native_libraries = self.encode_native_libraries();
1413         let native_lib_bytes = self.position() - i;
1414
1415         // Encode codemap
1416         i = self.position();
1417         let codemap = self.encode_codemap();
1418         let codemap_bytes = self.position() - i;
1419
1420         // Encode DefPathTable
1421         i = self.position();
1422         let def_path_table = self.encode_def_path_table();
1423         let def_path_table_bytes = self.position() - i;
1424
1425         // Encode the def IDs of impls, for coherence checking.
1426         i = self.position();
1427         let impls = self.encode_impls();
1428         let impl_bytes = self.position() - i;
1429
1430         // Encode exported symbols info.
1431         i = self.position();
1432         let exported_symbols = self.encode_exported_symbols();
1433         let exported_symbols_bytes = self.position() - i;
1434
1435         // Encode and index the items.
1436         i = self.position();
1437         let items = self.encode_info_for_items();
1438         let item_bytes = self.position() - i;
1439
1440         i = self.position();
1441         let index = items.write_index(&mut self.opaque.cursor);
1442         let index_bytes = self.position() - i;
1443
1444         let tcx = self.tcx;
1445         let link_meta = self.link_meta;
1446         let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
1447         let root = self.lazy(&CrateRoot {
1448             name: tcx.crate_name(LOCAL_CRATE),
1449             triple: tcx.sess.opts.target_triple.clone(),
1450             hash: link_meta.crate_hash,
1451             disambiguator: tcx.sess.local_crate_disambiguator(),
1452             panic_strategy: tcx.sess.panic_strategy(),
1453             plugin_registrar_fn: tcx.sess
1454                 .plugin_registrar_fn
1455                 .get()
1456                 .map(|id| tcx.hir.local_def_id(id).index),
1457             macro_derive_registrar: if is_proc_macro {
1458                 let id = tcx.sess.derive_registrar_fn.get().unwrap();
1459                 Some(tcx.hir.local_def_id(id).index)
1460             } else {
1461                 None
1462             },
1463
1464             crate_deps: crate_deps,
1465             dylib_dependency_formats: dylib_dependency_formats,
1466             lang_items: lang_items,
1467             lang_items_missing: lang_items_missing,
1468             native_libraries: native_libraries,
1469             codemap: codemap,
1470             def_path_table: def_path_table,
1471             impls: impls,
1472             exported_symbols: exported_symbols,
1473             index: index,
1474         });
1475
1476         let total_bytes = self.position();
1477
1478         if self.tcx.sess.meta_stats() {
1479             let mut zero_bytes = 0;
1480             for e in self.opaque.cursor.get_ref() {
1481                 if *e == 0 {
1482                     zero_bytes += 1;
1483                 }
1484             }
1485
1486             println!("metadata stats:");
1487             println!("             dep bytes: {}", dep_bytes);
1488             println!("       lang item bytes: {}", lang_item_bytes);
1489             println!("          native bytes: {}", native_lib_bytes);
1490             println!("         codemap bytes: {}", codemap_bytes);
1491             println!("            impl bytes: {}", impl_bytes);
1492             println!("    exp. symbols bytes: {}", exported_symbols_bytes);
1493             println!("  def-path table bytes: {}", def_path_table_bytes);
1494             println!("            item bytes: {}", item_bytes);
1495             println!("           index bytes: {}", index_bytes);
1496             println!("            zero bytes: {}", zero_bytes);
1497             println!("           total bytes: {}", total_bytes);
1498         }
1499
1500         root
1501     }
1502 }
1503
1504 // NOTE(eddyb) The following comment was preserved for posterity, even
1505 // though it's no longer relevant as EBML (which uses nested & tagged
1506 // "documents") was replaced with a scheme that can't go out of bounds.
1507 //
1508 // And here we run into yet another obscure archive bug: in which metadata
1509 // loaded from archives may have trailing garbage bytes. Awhile back one of
1510 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1511 // and opt) by having ebml generate an out-of-bounds panic when looking at
1512 // metadata.
1513 //
1514 // Upon investigation it turned out that the metadata file inside of an rlib
1515 // (and ar archive) was being corrupted. Some compilations would generate a
1516 // metadata file which would end in a few extra bytes, while other
1517 // compilations would not have these extra bytes appended to the end. These
1518 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1519 // being interpreted causing the out-of-bounds.
1520 //
1521 // The root cause of why these extra bytes were appearing was never
1522 // discovered, and in the meantime the solution we're employing is to insert
1523 // the length of the metadata to the start of the metadata. Later on this
1524 // will allow us to slice the metadata to the precise length that we just
1525 // generated regardless of trailing bytes that end up in it.
1526
1527 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1528                                  cstore: &cstore::CStore,
1529                                  link_meta: &LinkMeta,
1530                                  exported_symbols: &NodeSet)
1531                                  -> EncodedMetadata
1532 {
1533     let mut cursor = Cursor::new(vec![]);
1534     cursor.write_all(METADATA_HEADER).unwrap();
1535
1536     // Will be filed with the root position after encoding everything.
1537     cursor.write_all(&[0, 0, 0, 0]).unwrap();
1538
1539     let (root, metadata_hashes) = {
1540         let mut ecx = EncodeContext {
1541             opaque: opaque::Encoder::new(&mut cursor),
1542             tcx: tcx,
1543             link_meta: link_meta,
1544             cstore: cstore,
1545             exported_symbols: exported_symbols,
1546             lazy_state: LazyState::NoNode,
1547             type_shorthands: Default::default(),
1548             predicate_shorthands: Default::default(),
1549             metadata_hashes: Vec::new(),
1550         };
1551
1552         // Encode the rustc version string in a predictable location.
1553         rustc_version().encode(&mut ecx).unwrap();
1554
1555         // Encode all the entries and extra information in the crate,
1556         // culminating in the `CrateRoot` which points to all of it.
1557         let root = ecx.encode_crate_root();
1558         (root, ecx.metadata_hashes)
1559     };
1560     let mut result = cursor.into_inner();
1561
1562     // Encode the root position.
1563     let header = METADATA_HEADER.len();
1564     let pos = root.position;
1565     result[header + 0] = (pos >> 24) as u8;
1566     result[header + 1] = (pos >> 16) as u8;
1567     result[header + 2] = (pos >> 8) as u8;
1568     result[header + 3] = (pos >> 0) as u8;
1569
1570     EncodedMetadata {
1571         raw_data: result,
1572         hashes: metadata_hashes,
1573     }
1574 }
1575
1576 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1577     let ty = tcx.type_of(did);
1578     match ty.sty {
1579         ty::TyAdt(ref def, _) => return def.repr,
1580         _ => bug!("{} is not an ADT", ty),
1581     }
1582 }