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