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