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