]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/encoder.rs
Don't recompute SymbolExportLevel for upstream crates.
[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::exported_symbols::{ExportedSymbol, SymbolExportLevel};
24 use rustc::middle::lang_items;
25 use rustc::mir;
26 use rustc::traits::specialization_graph;
27 use rustc::ty::{self, Ty, TyCtxt, ReprOptions};
28 use rustc::ty::codec::{self as ty_codec, TyEncoder};
29
30 use rustc::session::config::{self, CrateTypeProcMacro};
31 use rustc::util::nodemap::FxHashMap;
32
33 use rustc_data_structures::stable_hasher::StableHasher;
34 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
35
36 use std::hash::Hash;
37 use std::io::prelude::*;
38 use std::io::Cursor;
39 use std::path::Path;
40 use rustc_data_structures::sync::Lrc;
41 use std::u32;
42 use syntax::ast::{self, CRATE_NODE_ID};
43 use syntax::codemap::Spanned;
44 use syntax::attr;
45 use syntax::symbol::Symbol;
46 use syntax_pos::{self, FileName, FileMap, Span, DUMMY_SP};
47
48 use rustc::hir::{self, PatKind};
49 use rustc::hir::itemlikevisit::ItemLikeVisitor;
50 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
51 use rustc::hir::intravisit;
52
53 pub struct EncodeContext<'a, 'tcx: 'a> {
54     opaque: opaque::Encoder<'a>,
55     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
56     link_meta: &'a LinkMeta,
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: Lrc<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                 // `--remap-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                             Lrc::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.tcx.exported_symbols(LOCAL_CRATE);
399         let exported_symbols = self.tracked(
400             IsolatedEncoder::encode_exported_symbols,
401             &exported_symbols);
402         let exported_symbols_bytes = self.position() - i;
403
404         // Encode and index the items.
405         i = self.position();
406         let items = self.encode_info_for_items();
407         let item_bytes = self.position() - i;
408
409         i = self.position();
410         let index = items.write_index(&mut self.opaque.cursor);
411         let index_bytes = self.position() - i;
412
413         let tcx = self.tcx;
414         let link_meta = self.link_meta;
415         let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
416         let has_default_lib_allocator =
417             attr::contains_name(tcx.hir.krate_attrs(), "default_lib_allocator");
418         let has_global_allocator = tcx.sess.has_global_allocator.get();
419         let root = self.lazy(&CrateRoot {
420             name: tcx.crate_name(LOCAL_CRATE),
421             triple: tcx.sess.opts.target_triple.clone(),
422             hash: link_meta.crate_hash,
423             disambiguator: tcx.sess.local_crate_disambiguator(),
424             panic_strategy: tcx.sess.panic_strategy(),
425             has_global_allocator: has_global_allocator,
426             has_default_lib_allocator: has_default_lib_allocator,
427             plugin_registrar_fn: tcx.sess
428                 .plugin_registrar_fn
429                 .get()
430                 .map(|id| tcx.hir.local_def_id(id).index),
431             macro_derive_registrar: if is_proc_macro {
432                 let id = tcx.sess.derive_registrar_fn.get().unwrap();
433                 Some(tcx.hir.local_def_id(id).index)
434             } else {
435                 None
436             },
437
438             crate_deps,
439             dylib_dependency_formats,
440             lang_items,
441             lang_items_missing,
442             native_libraries,
443             codemap,
444             def_path_table,
445             impls,
446             exported_symbols,
447             index,
448         });
449
450         let total_bytes = self.position();
451
452         if self.tcx.sess.meta_stats() {
453             let mut zero_bytes = 0;
454             for e in self.opaque.cursor.get_ref() {
455                 if *e == 0 {
456                     zero_bytes += 1;
457                 }
458             }
459
460             println!("metadata stats:");
461             println!("             dep bytes: {}", dep_bytes);
462             println!("       lang item bytes: {}", lang_item_bytes);
463             println!("          native bytes: {}", native_lib_bytes);
464             println!("         codemap bytes: {}", codemap_bytes);
465             println!("            impl bytes: {}", impl_bytes);
466             println!("    exp. symbols bytes: {}", exported_symbols_bytes);
467             println!("  def-path table bytes: {}", def_path_table_bytes);
468             println!("            item bytes: {}", item_bytes);
469             println!("           index bytes: {}", index_bytes);
470             println!("            zero bytes: {}", zero_bytes);
471             println!("           total bytes: {}", total_bytes);
472         }
473
474         root
475     }
476 }
477
478 // These are methods for encoding various things. They are meant to be used with
479 // IndexBuilder::record() and EncodeContext::tracked(). They actually
480 // would not have to be methods of IsolatedEncoder (free standing functions
481 // taking IsolatedEncoder as first argument would be just fine) but by making
482 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
483 // clause again and again.
484 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
485     fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
486         debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
487         let tcx = self.tcx;
488         self.lazy_seq_from_slice(&tcx.variances_of(def_id))
489     }
490
491     fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
492         let tcx = self.tcx;
493         let ty = tcx.type_of(def_id);
494         debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
495         self.lazy(&ty)
496     }
497
498     /// Encode data for the given variant of the given ADT. The
499     /// index of the variant is untracked: this is ok because we
500     /// will have to lookup the adt-def by its id, and that gives us
501     /// the right to access any information in the adt-def (including,
502     /// e.g., the length of the various vectors).
503     fn encode_enum_variant_info(&mut self,
504                                 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
505                                 -> Entry<'tcx> {
506         let tcx = self.tcx;
507         let def = tcx.adt_def(enum_did);
508         let variant = &def.variants[index];
509         let def_id = variant.did;
510         debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
511
512         let data = VariantData {
513             ctor_kind: variant.ctor_kind,
514             discr: variant.discr,
515             struct_ctor: None,
516             ctor_sig: if variant.ctor_kind == CtorKind::Fn {
517                 Some(self.lazy(&tcx.fn_sig(def_id)))
518             } else {
519                 None
520             }
521         };
522
523         let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
524         let enum_vis = &tcx.hir.expect_item(enum_id).vis;
525
526         Entry {
527             kind: EntryKind::Variant(self.lazy(&data)),
528             visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
529             span: self.lazy(&tcx.def_span(def_id)),
530             attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
531             children: self.lazy_seq(variant.fields.iter().map(|f| {
532                 assert!(f.did.is_local());
533                 f.did.index
534             })),
535             stability: self.encode_stability(def_id),
536             deprecation: self.encode_deprecation(def_id),
537
538             ty: Some(self.encode_item_type(def_id)),
539             inherent_impls: LazySeq::empty(),
540             variances: if variant.ctor_kind == CtorKind::Fn {
541                 self.encode_variances_of(def_id)
542             } else {
543                 LazySeq::empty()
544             },
545             generics: Some(self.encode_generics(def_id)),
546             predicates: Some(self.encode_predicates(def_id)),
547
548             ast: None,
549             mir: self.encode_optimized_mir(def_id),
550         }
551     }
552
553     fn encode_info_for_mod(&mut self,
554                            FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
555                                                                  &[ast::Attribute],
556                                                                  &hir::Visibility)>)
557                            -> Entry<'tcx> {
558         let tcx = self.tcx;
559         let def_id = tcx.hir.local_def_id(id);
560         debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
561
562         let data = ModData {
563             reexports: match tcx.module_exports(def_id) {
564                 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
565                 _ => LazySeq::empty(),
566             },
567         };
568
569         Entry {
570             kind: EntryKind::Mod(self.lazy(&data)),
571             visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
572             span: self.lazy(&tcx.def_span(def_id)),
573             attributes: self.encode_attributes(attrs),
574             children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
575                 tcx.hir.local_def_id(item_id.id).index
576             })),
577             stability: self.encode_stability(def_id),
578             deprecation: self.encode_deprecation(def_id),
579
580             ty: None,
581             inherent_impls: LazySeq::empty(),
582             variances: LazySeq::empty(),
583             generics: None,
584             predicates: None,
585
586             ast: None,
587             mir: None
588         }
589     }
590
591     /// Encode data for the given field of the given variant of the
592     /// given ADT. The indices of the variant/field are untracked:
593     /// this is ok because we will have to lookup the adt-def by its
594     /// id, and that gives us the right to access any information in
595     /// the adt-def (including, e.g., the length of the various
596     /// vectors).
597     fn encode_field(&mut self,
598                     (adt_def_id, Untracked((variant_index, field_index))): (DefId,
599                                                                             Untracked<(usize,
600                                                                                        usize)>))
601                     -> Entry<'tcx> {
602         let tcx = self.tcx;
603         let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
604         let field = &variant.fields[field_index];
605
606         let def_id = field.did;
607         debug!("IsolatedEncoder::encode_field({:?})", def_id);
608
609         let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
610         let variant_data = tcx.hir.expect_variant_data(variant_id);
611
612         Entry {
613             kind: EntryKind::Field,
614             visibility: self.lazy(&field.vis),
615             span: self.lazy(&tcx.def_span(def_id)),
616             attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
617             children: LazySeq::empty(),
618             stability: self.encode_stability(def_id),
619             deprecation: self.encode_deprecation(def_id),
620
621             ty: Some(self.encode_item_type(def_id)),
622             inherent_impls: LazySeq::empty(),
623             variances: LazySeq::empty(),
624             generics: Some(self.encode_generics(def_id)),
625             predicates: Some(self.encode_predicates(def_id)),
626
627             ast: None,
628             mir: None,
629         }
630     }
631
632     fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
633         debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
634         let tcx = self.tcx;
635         let adt_def = tcx.adt_def(adt_def_id);
636         let variant = adt_def.non_enum_variant();
637
638         let data = VariantData {
639             ctor_kind: variant.ctor_kind,
640             discr: variant.discr,
641             struct_ctor: Some(def_id.index),
642             ctor_sig: if variant.ctor_kind == CtorKind::Fn {
643                 Some(self.lazy(&tcx.fn_sig(def_id)))
644             } else {
645                 None
646             }
647         };
648
649         let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
650         let struct_vis = &tcx.hir.expect_item(struct_id).vis;
651         let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
652         for field in &variant.fields {
653             if ctor_vis.is_at_least(field.vis, tcx) {
654                 ctor_vis = field.vis;
655             }
656         }
657
658         // If the structure is marked as non_exhaustive then lower the visibility
659         // to within the crate.
660         if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
661             ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
662         }
663
664         let repr_options = get_repr_options(&tcx, adt_def_id);
665
666         Entry {
667             kind: EntryKind::Struct(self.lazy(&data), repr_options),
668             visibility: self.lazy(&ctor_vis),
669             span: self.lazy(&tcx.def_span(def_id)),
670             attributes: LazySeq::empty(),
671             children: LazySeq::empty(),
672             stability: self.encode_stability(def_id),
673             deprecation: self.encode_deprecation(def_id),
674
675             ty: Some(self.encode_item_type(def_id)),
676             inherent_impls: LazySeq::empty(),
677             variances: if variant.ctor_kind == CtorKind::Fn {
678                 self.encode_variances_of(def_id)
679             } else {
680                 LazySeq::empty()
681             },
682             generics: Some(self.encode_generics(def_id)),
683             predicates: Some(self.encode_predicates(def_id)),
684
685             ast: None,
686             mir: self.encode_optimized_mir(def_id),
687         }
688     }
689
690     fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
691         debug!("IsolatedEncoder::encode_generics({:?})", def_id);
692         let tcx = self.tcx;
693         self.lazy(tcx.generics_of(def_id))
694     }
695
696     fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
697         debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
698         let tcx = self.tcx;
699         self.lazy(&tcx.predicates_of(def_id))
700     }
701
702     fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
703         debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
704         let tcx = self.tcx;
705
706         let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
707         let ast_item = tcx.hir.expect_trait_item(node_id);
708         let trait_item = tcx.associated_item(def_id);
709
710         let container = match trait_item.defaultness {
711             hir::Defaultness::Default { has_value: true } =>
712                 AssociatedContainer::TraitWithDefault,
713             hir::Defaultness::Default { has_value: false } =>
714                 AssociatedContainer::TraitRequired,
715             hir::Defaultness::Final =>
716                 span_bug!(ast_item.span, "traits cannot have final items"),
717         };
718
719         let kind = match trait_item.kind {
720             ty::AssociatedKind::Const => {
721                 EntryKind::AssociatedConst(container, 0)
722             }
723             ty::AssociatedKind::Method => {
724                 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
725                     let arg_names = match *m {
726                         hir::TraitMethod::Required(ref names) => {
727                             self.encode_fn_arg_names(names)
728                         }
729                         hir::TraitMethod::Provided(body) => {
730                             self.encode_fn_arg_names_for_body(body)
731                         }
732                     };
733                     FnData {
734                         constness: hir::Constness::NotConst,
735                         arg_names,
736                         sig: self.lazy(&tcx.fn_sig(def_id)),
737                     }
738                 } else {
739                     bug!()
740                 };
741                 EntryKind::Method(self.lazy(&MethodData {
742                     fn_data,
743                     container,
744                     has_self: trait_item.method_has_self_argument,
745                 }))
746             }
747             ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
748         };
749
750         Entry {
751             kind,
752             visibility: self.lazy(&trait_item.vis),
753             span: self.lazy(&ast_item.span),
754             attributes: self.encode_attributes(&ast_item.attrs),
755             children: LazySeq::empty(),
756             stability: self.encode_stability(def_id),
757             deprecation: self.encode_deprecation(def_id),
758
759             ty: match trait_item.kind {
760                 ty::AssociatedKind::Const |
761                 ty::AssociatedKind::Method => {
762                     Some(self.encode_item_type(def_id))
763                 }
764                 ty::AssociatedKind::Type => {
765                     if trait_item.defaultness.has_value() {
766                         Some(self.encode_item_type(def_id))
767                     } else {
768                         None
769                     }
770                 }
771             },
772             inherent_impls: LazySeq::empty(),
773             variances: if trait_item.kind == ty::AssociatedKind::Method {
774                 self.encode_variances_of(def_id)
775             } else {
776                 LazySeq::empty()
777             },
778             generics: Some(self.encode_generics(def_id)),
779             predicates: Some(self.encode_predicates(def_id)),
780
781             ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
782                 Some(self.encode_body(body))
783             } else {
784                 None
785             },
786             mir: self.encode_optimized_mir(def_id),
787         }
788     }
789
790     fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
791         debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
792         let tcx = self.tcx;
793
794         let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
795         let ast_item = self.tcx.hir.expect_impl_item(node_id);
796         let impl_item = self.tcx.associated_item(def_id);
797
798         let container = match impl_item.defaultness {
799             hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
800             hir::Defaultness::Final => AssociatedContainer::ImplFinal,
801             hir::Defaultness::Default { has_value: false } =>
802                 span_bug!(ast_item.span, "impl items always have values (currently)"),
803         };
804
805         let kind = match impl_item.kind {
806             ty::AssociatedKind::Const => {
807                 EntryKind::AssociatedConst(container,
808                     self.tcx.at(ast_item.span).mir_const_qualif(def_id).0)
809             }
810             ty::AssociatedKind::Method => {
811                 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
812                     FnData {
813                         constness: sig.constness,
814                         arg_names: self.encode_fn_arg_names_for_body(body),
815                         sig: self.lazy(&tcx.fn_sig(def_id)),
816                     }
817                 } else {
818                     bug!()
819                 };
820                 EntryKind::Method(self.lazy(&MethodData {
821                     fn_data,
822                     container,
823                     has_self: impl_item.method_has_self_argument,
824                 }))
825             }
826             ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
827         };
828
829         let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
830             (Some(body), true)
831         } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
832             let generics = self.tcx.generics_of(def_id);
833             let types = generics.parent_types as usize + generics.types.len();
834             let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
835             let is_const_fn = sig.constness == hir::Constness::Const;
836             let ast = if is_const_fn { Some(body) } else { None };
837             let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
838             (ast, needs_inline || is_const_fn || always_encode_mir)
839         } else {
840             (None, false)
841         };
842
843         Entry {
844             kind,
845             visibility: self.lazy(&impl_item.vis),
846             span: self.lazy(&ast_item.span),
847             attributes: self.encode_attributes(&ast_item.attrs),
848             children: LazySeq::empty(),
849             stability: self.encode_stability(def_id),
850             deprecation: self.encode_deprecation(def_id),
851
852             ty: Some(self.encode_item_type(def_id)),
853             inherent_impls: LazySeq::empty(),
854             variances: if impl_item.kind == ty::AssociatedKind::Method {
855                 self.encode_variances_of(def_id)
856             } else {
857                 LazySeq::empty()
858             },
859             generics: Some(self.encode_generics(def_id)),
860             predicates: Some(self.encode_predicates(def_id)),
861
862             ast: ast.map(|body| self.encode_body(body)),
863             mir: if mir { self.encode_optimized_mir(def_id) } else { None },
864         }
865     }
866
867     fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
868                                     -> LazySeq<ast::Name> {
869         self.tcx.dep_graph.with_ignore(|| {
870             let body = self.tcx.hir.body(body_id);
871             self.lazy_seq(body.arguments.iter().map(|arg| {
872                 match arg.pat.node {
873                     PatKind::Binding(_, _, name, _) => name.node,
874                     _ => Symbol::intern("")
875                 }
876             }))
877         })
878     }
879
880     fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
881                            -> LazySeq<ast::Name> {
882         self.lazy_seq(names.iter().map(|name| name.node))
883     }
884
885     fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
886         debug!("EntryBuilder::encode_mir({:?})", def_id);
887         if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
888             let mir = self.tcx.optimized_mir(def_id);
889             Some(self.lazy(&mir))
890         } else {
891             None
892         }
893     }
894
895     // Encodes the inherent implementations of a structure, enumeration, or trait.
896     fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
897         debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
898         let implementations = self.tcx.inherent_impls(def_id);
899         if implementations.is_empty() {
900             LazySeq::empty()
901         } else {
902             self.lazy_seq(implementations.iter().map(|&def_id| {
903                 assert!(def_id.is_local());
904                 def_id.index
905             }))
906         }
907     }
908
909     fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
910         debug!("IsolatedEncoder::encode_stability({:?})", def_id);
911         self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
912     }
913
914     fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
915         debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
916         self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
917     }
918
919     fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
920         let tcx = self.tcx;
921
922         debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
923
924         let kind = match item.node {
925             hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
926             hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
927             hir::ItemConst(..) => {
928                 EntryKind::Const(tcx.at(item.span).mir_const_qualif(def_id).0)
929             }
930             hir::ItemFn(_, _, constness, .., body) => {
931                 let data = FnData {
932                     constness,
933                     arg_names: self.encode_fn_arg_names_for_body(body),
934                     sig: self.lazy(&tcx.fn_sig(def_id)),
935                 };
936
937                 EntryKind::Fn(self.lazy(&data))
938             }
939             hir::ItemMod(ref m) => {
940                 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
941             }
942             hir::ItemForeignMod(_) => EntryKind::ForeignMod,
943             hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
944             hir::ItemTy(..) => EntryKind::Type,
945             hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
946             hir::ItemStruct(ref struct_def, _) => {
947                 let variant = tcx.adt_def(def_id).non_enum_variant();
948
949                 // Encode def_ids for each field and method
950                 // for methods, write all the stuff get_trait_method
951                 // needs to know
952                 let struct_ctor = if !struct_def.is_struct() {
953                     Some(tcx.hir.local_def_id(struct_def.id()).index)
954                 } else {
955                     None
956                 };
957
958                 let repr_options = get_repr_options(&tcx, def_id);
959
960                 EntryKind::Struct(self.lazy(&VariantData {
961                     ctor_kind: variant.ctor_kind,
962                     discr: variant.discr,
963                     struct_ctor,
964                     ctor_sig: None,
965                 }), repr_options)
966             }
967             hir::ItemUnion(..) => {
968                 let variant = tcx.adt_def(def_id).non_enum_variant();
969                 let repr_options = get_repr_options(&tcx, def_id);
970
971                 EntryKind::Union(self.lazy(&VariantData {
972                     ctor_kind: variant.ctor_kind,
973                     discr: variant.discr,
974                     struct_ctor: None,
975                     ctor_sig: None,
976                 }), repr_options)
977             }
978             hir::ItemImpl(_, polarity, defaultness, ..) => {
979                 let trait_ref = tcx.impl_trait_ref(def_id);
980                 let parent = if let Some(trait_ref) = trait_ref {
981                     let trait_def = tcx.trait_def(trait_ref.def_id);
982                     trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
983                         match node {
984                             specialization_graph::Node::Impl(parent) => Some(parent),
985                             _ => None,
986                         }
987                     })
988                 } else {
989                     None
990                 };
991
992                 // if this is an impl of `CoerceUnsized`, create its
993                 // "unsized info", else just store None
994                 let coerce_unsized_info =
995                     trait_ref.and_then(|t| {
996                         if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
997                             Some(tcx.at(item.span).coerce_unsized_info(def_id))
998                         } else {
999                             None
1000                         }
1001                     });
1002
1003                 let data = ImplData {
1004                     polarity,
1005                     defaultness,
1006                     parent_impl: parent,
1007                     coerce_unsized_info,
1008                     trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1009                 };
1010
1011                 EntryKind::Impl(self.lazy(&data))
1012             }
1013             hir::ItemTrait(..) => {
1014                 let trait_def = tcx.trait_def(def_id);
1015                 let data = TraitData {
1016                     unsafety: trait_def.unsafety,
1017                     paren_sugar: trait_def.paren_sugar,
1018                     has_auto_impl: tcx.trait_is_auto(def_id),
1019                     super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1020                 };
1021
1022                 EntryKind::Trait(self.lazy(&data))
1023             }
1024             hir::ItemExternCrate(_) |
1025             hir::ItemTraitAlias(..) |
1026             hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1027         };
1028
1029         Entry {
1030             kind,
1031             visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1032             span: self.lazy(&item.span),
1033             attributes: self.encode_attributes(&item.attrs),
1034             children: match item.node {
1035                 hir::ItemForeignMod(ref fm) => {
1036                     self.lazy_seq(fm.items
1037                         .iter()
1038                         .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1039                 }
1040                 hir::ItemEnum(..) => {
1041                     let def = self.tcx.adt_def(def_id);
1042                     self.lazy_seq(def.variants.iter().map(|v| {
1043                         assert!(v.did.is_local());
1044                         v.did.index
1045                     }))
1046                 }
1047                 hir::ItemStruct(..) |
1048                 hir::ItemUnion(..) => {
1049                     let def = self.tcx.adt_def(def_id);
1050                     self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1051                         assert!(f.did.is_local());
1052                         f.did.index
1053                     }))
1054                 }
1055                 hir::ItemImpl(..) |
1056                 hir::ItemTrait(..) => {
1057                     self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1058                         assert!(def_id.is_local());
1059                         def_id.index
1060                     }))
1061                 }
1062                 _ => LazySeq::empty(),
1063             },
1064             stability: self.encode_stability(def_id),
1065             deprecation: self.encode_deprecation(def_id),
1066
1067             ty: match item.node {
1068                 hir::ItemStatic(..) |
1069                 hir::ItemConst(..) |
1070                 hir::ItemFn(..) |
1071                 hir::ItemTy(..) |
1072                 hir::ItemEnum(..) |
1073                 hir::ItemStruct(..) |
1074                 hir::ItemUnion(..) |
1075                 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1076                 _ => None,
1077             },
1078             inherent_impls: self.encode_inherent_implementations(def_id),
1079             variances: match item.node {
1080                 hir::ItemEnum(..) |
1081                 hir::ItemStruct(..) |
1082                 hir::ItemUnion(..) |
1083                 hir::ItemFn(..) => self.encode_variances_of(def_id),
1084                 _ => LazySeq::empty(),
1085             },
1086             generics: match item.node {
1087                 hir::ItemStatic(..) |
1088                 hir::ItemConst(..) |
1089                 hir::ItemFn(..) |
1090                 hir::ItemTy(..) |
1091                 hir::ItemEnum(..) |
1092                 hir::ItemStruct(..) |
1093                 hir::ItemUnion(..) |
1094                 hir::ItemImpl(..) |
1095                 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1096                 _ => None,
1097             },
1098             predicates: match item.node {
1099                 hir::ItemStatic(..) |
1100                 hir::ItemConst(..) |
1101                 hir::ItemFn(..) |
1102                 hir::ItemTy(..) |
1103                 hir::ItemEnum(..) |
1104                 hir::ItemStruct(..) |
1105                 hir::ItemUnion(..) |
1106                 hir::ItemImpl(..) |
1107                 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1108                 _ => None,
1109             },
1110
1111             ast: match item.node {
1112                 hir::ItemConst(_, body) |
1113                 hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
1114                     Some(self.encode_body(body))
1115                 }
1116                 _ => None,
1117             },
1118             mir: match item.node {
1119                 hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
1120                     self.encode_optimized_mir(def_id)
1121                 }
1122                 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1123                 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1124                     let has_tps = generics.ty_params().next().is_some();
1125                     let needs_inline = has_tps || attr::requests_inline(&item.attrs);
1126                     let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1127                     if needs_inline || constness == hir::Constness::Const || always_encode_mir {
1128                         self.encode_optimized_mir(def_id)
1129                     } else {
1130                         None
1131                     }
1132                 }
1133                 _ => None,
1134             },
1135         }
1136     }
1137
1138     /// Serialize the text of exported macros
1139     fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1140         use syntax::print::pprust;
1141         let def_id = self.tcx.hir.local_def_id(macro_def.id);
1142         Entry {
1143             kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1144                 body: pprust::tts_to_string(&macro_def.body.trees().collect::<Vec<_>>()),
1145                 legacy: macro_def.legacy,
1146             })),
1147             visibility: self.lazy(&ty::Visibility::Public),
1148             span: self.lazy(&macro_def.span),
1149             attributes: self.encode_attributes(&macro_def.attrs),
1150             stability: self.encode_stability(def_id),
1151             deprecation: self.encode_deprecation(def_id),
1152
1153             children: LazySeq::empty(),
1154             ty: None,
1155             inherent_impls: LazySeq::empty(),
1156             variances: LazySeq::empty(),
1157             generics: None,
1158             predicates: None,
1159             ast: None,
1160             mir: None,
1161         }
1162     }
1163
1164     fn encode_info_for_ty_param(&mut self,
1165                                 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1166                                 -> Entry<'tcx> {
1167         debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1168         let tcx = self.tcx;
1169         Entry {
1170             kind: EntryKind::Type,
1171             visibility: self.lazy(&ty::Visibility::Public),
1172             span: self.lazy(&tcx.def_span(def_id)),
1173             attributes: LazySeq::empty(),
1174             children: LazySeq::empty(),
1175             stability: None,
1176             deprecation: None,
1177
1178             ty: if has_default {
1179                 Some(self.encode_item_type(def_id))
1180             } else {
1181                 None
1182             },
1183             inherent_impls: LazySeq::empty(),
1184             variances: LazySeq::empty(),
1185             generics: None,
1186             predicates: None,
1187
1188             ast: None,
1189             mir: None,
1190         }
1191     }
1192
1193     fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
1194         debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
1195         let tcx = self.tcx;
1196         Entry {
1197             kind: EntryKind::Type,
1198             visibility: self.lazy(&ty::Visibility::Public),
1199             span: self.lazy(&tcx.def_span(def_id)),
1200             attributes: LazySeq::empty(),
1201             children: LazySeq::empty(),
1202             stability: None,
1203             deprecation: None,
1204
1205             ty: Some(self.encode_item_type(def_id)),
1206             inherent_impls: LazySeq::empty(),
1207             variances: LazySeq::empty(),
1208             generics: Some(self.encode_generics(def_id)),
1209             predicates: Some(self.encode_predicates(def_id)),
1210
1211             ast: None,
1212             mir: None,
1213         }
1214     }
1215
1216     fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1217         debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1218         let tcx = self.tcx;
1219
1220         let tables = self.tcx.typeck_tables_of(def_id);
1221         let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1222         let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1223         let kind = match tables.node_id_to_type(hir_id).sty {
1224             ty::TyGenerator(def_id, ..) => {
1225                 let layout = self.tcx.generator_layout(def_id);
1226                 let data = GeneratorData {
1227                     layout: layout.clone(),
1228                 };
1229                 EntryKind::Generator(self.lazy(&data))
1230             }
1231
1232             ty::TyClosure(def_id, substs) => {
1233                 let sig = substs.closure_sig(def_id, self.tcx);
1234                 let data = ClosureData { sig: self.lazy(&sig) };
1235                 EntryKind::Closure(self.lazy(&data))
1236             }
1237
1238             _ => bug!("closure that is neither generator nor closure")
1239         };
1240
1241         Entry {
1242             kind,
1243             visibility: self.lazy(&ty::Visibility::Public),
1244             span: self.lazy(&tcx.def_span(def_id)),
1245             attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1246             children: LazySeq::empty(),
1247             stability: None,
1248             deprecation: None,
1249
1250             ty: Some(self.encode_item_type(def_id)),
1251             inherent_impls: LazySeq::empty(),
1252             variances: LazySeq::empty(),
1253             generics: Some(self.encode_generics(def_id)),
1254             predicates: None,
1255
1256             ast: None,
1257             mir: self.encode_optimized_mir(def_id),
1258         }
1259     }
1260
1261     fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1262         debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
1263         let tcx = self.tcx;
1264         let id = tcx.hir.as_local_node_id(def_id).unwrap();
1265         let body = tcx.hir.body_owned_by(id);
1266
1267         Entry {
1268             kind: EntryKind::Const(tcx.mir_const_qualif(def_id).0),
1269             visibility: self.lazy(&ty::Visibility::Public),
1270             span: self.lazy(&tcx.def_span(def_id)),
1271             attributes: LazySeq::empty(),
1272             children: LazySeq::empty(),
1273             stability: None,
1274             deprecation: None,
1275
1276             ty: Some(self.encode_item_type(def_id)),
1277             inherent_impls: LazySeq::empty(),
1278             variances: LazySeq::empty(),
1279             generics: Some(self.encode_generics(def_id)),
1280             predicates: Some(self.encode_predicates(def_id)),
1281
1282             ast: Some(self.encode_body(body)),
1283             mir: self.encode_optimized_mir(def_id),
1284         }
1285     }
1286
1287     fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1288         // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1289         //       we rely on the HashStable specialization for [Attribute]
1290         //       to properly filter things out.
1291         self.lazy_seq_from_slice(attrs)
1292     }
1293
1294     fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1295         let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1296         self.lazy_seq(used_libraries.iter().cloned())
1297     }
1298
1299     fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1300         let crates = self.tcx.crates();
1301
1302         let mut deps = crates
1303             .iter()
1304             .map(|&cnum| {
1305                 let dep = CrateDep {
1306                     name: self.tcx.original_crate_name(cnum),
1307                     hash: self.tcx.crate_hash(cnum),
1308                     kind: self.tcx.dep_kind(cnum),
1309                 };
1310                 (cnum, dep)
1311             })
1312             .collect::<Vec<_>>();
1313
1314         deps.sort_by_key(|&(cnum, _)| cnum);
1315
1316         {
1317             // Sanity-check the crate numbers
1318             let mut expected_cnum = 1;
1319             for &(n, _) in &deps {
1320                 assert_eq!(n, CrateNum::new(expected_cnum));
1321                 expected_cnum += 1;
1322             }
1323         }
1324
1325         // We're just going to write a list of crate 'name-hash-version's, with
1326         // the assumption that they are numbered 1 to n.
1327         // FIXME (#2166): This is not nearly enough to support correct versioning
1328         // but is enough to get transitive crate dependencies working.
1329         self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1330     }
1331
1332     fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1333         let tcx = self.tcx;
1334         let lang_items = tcx.lang_items();
1335         let lang_items = lang_items.items().iter();
1336         self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1337             if let Some(def_id) = opt_def_id {
1338                 if def_id.is_local() {
1339                     return Some((def_id.index, i));
1340                 }
1341             }
1342             None
1343         }))
1344     }
1345
1346     fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1347         let tcx = self.tcx;
1348         self.lazy_seq_ref(&tcx.lang_items().missing)
1349     }
1350
1351     /// Encodes an index, mapping each trait to its (local) implementations.
1352     fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1353         debug!("IsolatedEncoder::encode_impls()");
1354         let tcx = self.tcx;
1355         let mut visitor = ImplVisitor {
1356             tcx,
1357             impls: FxHashMap(),
1358         };
1359         tcx.hir.krate().visit_all_item_likes(&mut visitor);
1360
1361         let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1362
1363         // Bring everything into deterministic order for hashing
1364         all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1365             tcx.def_path_hash(trait_def_id)
1366         });
1367
1368         let all_impls: Vec<_> = all_impls
1369             .into_iter()
1370             .map(|(trait_def_id, mut impls)| {
1371                 // Bring everything into deterministic order for hashing
1372                 impls.sort_unstable_by_key(|&def_index| {
1373                     tcx.hir.definitions().def_path_hash(def_index)
1374                 });
1375
1376                 TraitImpls {
1377                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1378                     impls: self.lazy_seq_from_slice(&impls[..]),
1379                 }
1380             })
1381             .collect();
1382
1383         self.lazy_seq_from_slice(&all_impls[..])
1384     }
1385
1386     // Encodes all symbols exported from this crate into the metadata.
1387     //
1388     // This pass is seeded off the reachability list calculated in the
1389     // middle::reachable module but filters out items that either don't have a
1390     // symbol associated with them (they weren't translated) or if they're an FFI
1391     // definition (as that's not defined in this crate).
1392     fn encode_exported_symbols(&mut self,
1393                                exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1394                                -> LazySeq<(ExportedSymbol, SymbolExportLevel)> {
1395         self.lazy_seq(exported_symbols.iter().cloned())
1396     }
1397
1398     fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1399         match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1400             Some(arr) => {
1401                 self.lazy_seq(arr.iter().map(|slot| {
1402                     match *slot {
1403                         Linkage::NotLinked |
1404                         Linkage::IncludedFromDylib => None,
1405
1406                         Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1407                         Linkage::Static => Some(LinkagePreference::RequireStatic),
1408                     }
1409                 }))
1410             }
1411             None => LazySeq::empty(),
1412         }
1413     }
1414
1415     fn encode_info_for_foreign_item(&mut self,
1416                                     (def_id, nitem): (DefId, &hir::ForeignItem))
1417                                     -> Entry<'tcx> {
1418         let tcx = self.tcx;
1419
1420         debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1421
1422         let kind = match nitem.node {
1423             hir::ForeignItemFn(_, ref names, _) => {
1424                 let data = FnData {
1425                     constness: hir::Constness::NotConst,
1426                     arg_names: self.encode_fn_arg_names(names),
1427                     sig: self.lazy(&tcx.fn_sig(def_id)),
1428                 };
1429                 EntryKind::ForeignFn(self.lazy(&data))
1430             }
1431             hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1432             hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1433             hir::ForeignItemType => EntryKind::ForeignType,
1434         };
1435
1436         Entry {
1437             kind,
1438             visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1439             span: self.lazy(&nitem.span),
1440             attributes: self.encode_attributes(&nitem.attrs),
1441             children: LazySeq::empty(),
1442             stability: self.encode_stability(def_id),
1443             deprecation: self.encode_deprecation(def_id),
1444
1445             ty: Some(self.encode_item_type(def_id)),
1446             inherent_impls: LazySeq::empty(),
1447             variances: match nitem.node {
1448                 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1449                 _ => LazySeq::empty(),
1450             },
1451             generics: Some(self.encode_generics(def_id)),
1452             predicates: Some(self.encode_predicates(def_id)),
1453
1454             ast: None,
1455             mir: None,
1456         }
1457     }
1458 }
1459
1460 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1461     index: IndexBuilder<'a, 'b, 'tcx>,
1462 }
1463
1464 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1465     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1466         NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1467     }
1468     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1469         intravisit::walk_expr(self, ex);
1470         self.index.encode_info_for_expr(ex);
1471     }
1472     fn visit_item(&mut self, item: &'tcx hir::Item) {
1473         intravisit::walk_item(self, item);
1474         let def_id = self.index.tcx.hir.local_def_id(item.id);
1475         match item.node {
1476             hir::ItemExternCrate(_) |
1477             hir::ItemUse(..) => (), // ignore these
1478             _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1479         }
1480         self.index.encode_addl_info_for_item(item);
1481     }
1482     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1483         intravisit::walk_foreign_item(self, ni);
1484         let def_id = self.index.tcx.hir.local_def_id(ni.id);
1485         self.index.record(def_id,
1486                           IsolatedEncoder::encode_info_for_foreign_item,
1487                           (def_id, ni));
1488     }
1489     fn visit_variant(&mut self,
1490                      v: &'tcx hir::Variant,
1491                      g: &'tcx hir::Generics,
1492                      id: ast::NodeId) {
1493         intravisit::walk_variant(self, v, g, id);
1494
1495         if let Some(discr) = v.node.disr_expr {
1496             let def_id = self.index.tcx.hir.body_owner_def_id(discr);
1497             self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1498         }
1499     }
1500     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1501         intravisit::walk_generics(self, generics);
1502         self.index.encode_info_for_generics(generics);
1503     }
1504     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1505         intravisit::walk_ty(self, ty);
1506         self.index.encode_info_for_ty(ty);
1507     }
1508     fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1509         let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1510         self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1511     }
1512 }
1513
1514 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1515     fn encode_fields(&mut self, adt_def_id: DefId) {
1516         let def = self.tcx.adt_def(adt_def_id);
1517         for (variant_index, variant) in def.variants.iter().enumerate() {
1518             for (field_index, field) in variant.fields.iter().enumerate() {
1519                 self.record(field.did,
1520                             IsolatedEncoder::encode_field,
1521                             (adt_def_id, Untracked((variant_index, field_index))));
1522             }
1523         }
1524     }
1525
1526     fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1527         for ty_param in generics.ty_params() {
1528             let def_id = self.tcx.hir.local_def_id(ty_param.id);
1529             let has_default = Untracked(ty_param.default.is_some());
1530             self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
1531         }
1532     }
1533
1534     fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1535         match ty.node {
1536             hir::TyImplTraitExistential(..) => {
1537                 let def_id = self.tcx.hir.local_def_id(ty.id);
1538                 self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
1539             }
1540             hir::TyArray(_, len) => {
1541                 let def_id = self.tcx.hir.body_owner_def_id(len);
1542                 self.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
1543             }
1544             _ => {}
1545         }
1546     }
1547
1548     fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1549         match expr.node {
1550             hir::ExprClosure(..) => {
1551                 let def_id = self.tcx.hir.local_def_id(expr.id);
1552                 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1553             }
1554             _ => {}
1555         }
1556     }
1557
1558     /// In some cases, along with the item itself, we also
1559     /// encode some sub-items. Usually we want some info from the item
1560     /// so it's easier to do that here then to wait until we would encounter
1561     /// normally in the visitor walk.
1562     fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1563         let def_id = self.tcx.hir.local_def_id(item.id);
1564         match item.node {
1565             hir::ItemStatic(..) |
1566             hir::ItemConst(..) |
1567             hir::ItemFn(..) |
1568             hir::ItemMod(..) |
1569             hir::ItemForeignMod(..) |
1570             hir::ItemGlobalAsm(..) |
1571             hir::ItemExternCrate(..) |
1572             hir::ItemUse(..) |
1573             hir::ItemTy(..) |
1574             hir::ItemTraitAlias(..) => {
1575                 // no sub-item recording needed in these cases
1576             }
1577             hir::ItemEnum(..) => {
1578                 self.encode_fields(def_id);
1579
1580                 let def = self.tcx.adt_def(def_id);
1581                 for (i, variant) in def.variants.iter().enumerate() {
1582                     self.record(variant.did,
1583                                 IsolatedEncoder::encode_enum_variant_info,
1584                                 (def_id, Untracked(i)));
1585                 }
1586             }
1587             hir::ItemStruct(ref struct_def, _) => {
1588                 self.encode_fields(def_id);
1589
1590                 // If the struct has a constructor, encode it.
1591                 if !struct_def.is_struct() {
1592                     let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1593                     self.record(ctor_def_id,
1594                                 IsolatedEncoder::encode_struct_ctor,
1595                                 (def_id, ctor_def_id));
1596                 }
1597             }
1598             hir::ItemUnion(..) => {
1599                 self.encode_fields(def_id);
1600             }
1601             hir::ItemImpl(..) => {
1602                 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1603                     self.record(trait_item_def_id,
1604                                 IsolatedEncoder::encode_info_for_impl_item,
1605                                 trait_item_def_id);
1606                 }
1607             }
1608             hir::ItemTrait(..) => {
1609                 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1610                     self.record(item_def_id,
1611                                 IsolatedEncoder::encode_info_for_trait_item,
1612                                 item_def_id);
1613                 }
1614             }
1615         }
1616     }
1617 }
1618
1619 struct ImplVisitor<'a, 'tcx: 'a> {
1620     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1621     impls: FxHashMap<DefId, Vec<DefIndex>>,
1622 }
1623
1624 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1625     fn visit_item(&mut self, item: &hir::Item) {
1626         if let hir::ItemImpl(..) = item.node {
1627             let impl_id = self.tcx.hir.local_def_id(item.id);
1628             if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1629                 self.impls
1630                     .entry(trait_ref.def_id)
1631                     .or_insert(vec![])
1632                     .push(impl_id.index);
1633             }
1634         }
1635     }
1636
1637     fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1638
1639     fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1640         // handled in `visit_item` above
1641     }
1642 }
1643
1644 // NOTE(eddyb) The following comment was preserved for posterity, even
1645 // though it's no longer relevant as EBML (which uses nested & tagged
1646 // "documents") was replaced with a scheme that can't go out of bounds.
1647 //
1648 // And here we run into yet another obscure archive bug: in which metadata
1649 // loaded from archives may have trailing garbage bytes. Awhile back one of
1650 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1651 // and opt) by having ebml generate an out-of-bounds panic when looking at
1652 // metadata.
1653 //
1654 // Upon investigation it turned out that the metadata file inside of an rlib
1655 // (and ar archive) was being corrupted. Some compilations would generate a
1656 // metadata file which would end in a few extra bytes, while other
1657 // compilations would not have these extra bytes appended to the end. These
1658 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1659 // being interpreted causing the out-of-bounds.
1660 //
1661 // The root cause of why these extra bytes were appearing was never
1662 // discovered, and in the meantime the solution we're employing is to insert
1663 // the length of the metadata to the start of the metadata. Later on this
1664 // will allow us to slice the metadata to the precise length that we just
1665 // generated regardless of trailing bytes that end up in it.
1666
1667 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1668                                  link_meta: &LinkMeta)
1669                                  -> EncodedMetadata
1670 {
1671     let mut cursor = Cursor::new(vec![]);
1672     cursor.write_all(METADATA_HEADER).unwrap();
1673
1674     // Will be filled with the root position after encoding everything.
1675     cursor.write_all(&[0, 0, 0, 0]).unwrap();
1676
1677     let root = {
1678         let mut ecx = EncodeContext {
1679             opaque: opaque::Encoder::new(&mut cursor),
1680             tcx,
1681             link_meta,
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 }