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