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