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