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