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