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