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