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