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