]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/encoder.rs
Auto merge of #30457 - Manishearth:rollup, r=Manishearth
[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 // Metadata encoding
12
13 #![allow(unused_must_use)] // everything is just a MemWriter, can't fail
14 #![allow(non_camel_case_types)]
15
16 use common::*;
17 use cstore;
18 use decoder;
19 use tyencode;
20 use index::{self, IndexData};
21
22 use middle::cstore::{LOCAL_CRATE, CrateStore, InlinedItemRef, LinkMeta, tls};
23 use middle::def;
24 use middle::def_id::{CRATE_DEF_INDEX, DefId};
25 use middle::dependency_format::Linkage;
26 use middle::stability;
27 use middle::subst;
28 use middle::ty::{self, Ty};
29
30 use rustc::back::svh::Svh;
31 use rustc::front::map::{LinkedPath, PathElem, PathElems};
32 use rustc::front::map as ast_map;
33 use rustc::mir::repr::Mir;
34 use rustc::session::config;
35 use rustc::util::nodemap::{FnvHashMap, NodeMap, NodeSet};
36
37 use serialize::Encodable;
38 use std::cell::RefCell;
39 use std::io::prelude::*;
40 use std::io::{Cursor, SeekFrom};
41 use std::rc::Rc;
42 use std::u32;
43 use syntax::abi;
44 use syntax::ast::{self, NodeId, Name, CRATE_NODE_ID, CrateNum};
45 use syntax::attr;
46 use syntax::attr::AttrMetaMethods;
47 use syntax::errors::Handler;
48 use syntax::parse::token::special_idents;
49 use syntax;
50 use rbml::writer::Encoder;
51
52 use rustc_front::hir;
53 use rustc_front::intravisit::Visitor;
54 use rustc_front::intravisit;
55
56 pub type EncodeInlinedItem<'a> =
57     Box<FnMut(&EncodeContext, &mut Encoder, InlinedItemRef) + 'a>;
58
59 pub struct EncodeParams<'a, 'tcx: 'a> {
60     pub diag: &'a Handler,
61     pub tcx: &'a ty::ctxt<'tcx>,
62     pub reexports: &'a def::ExportMap,
63     pub item_symbols: &'a RefCell<NodeMap<String>>,
64     pub link_meta: &'a LinkMeta,
65     pub cstore: &'a cstore::CStore,
66     pub encode_inlined_item: EncodeInlinedItem<'a>,
67     pub reachable: &'a NodeSet,
68     pub mir_map: &'a NodeMap<Mir<'tcx>>,
69 }
70
71 pub struct EncodeContext<'a, 'tcx: 'a> {
72     pub diag: &'a Handler,
73     pub tcx: &'a ty::ctxt<'tcx>,
74     pub reexports: &'a def::ExportMap,
75     pub item_symbols: &'a RefCell<NodeMap<String>>,
76     pub link_meta: &'a LinkMeta,
77     pub cstore: &'a cstore::CStore,
78     pub encode_inlined_item: RefCell<EncodeInlinedItem<'a>>,
79     pub type_abbrevs: tyencode::abbrev_map<'tcx>,
80     pub reachable: &'a NodeSet,
81     pub mir_map: &'a NodeMap<Mir<'tcx>>,
82 }
83
84 impl<'a, 'tcx> EncodeContext<'a,'tcx> {
85     fn local_id(&self, def_id: DefId) -> NodeId {
86         self.tcx.map.as_local_node_id(def_id).unwrap()
87     }
88 }
89
90 /// "interned" entries referenced by id
91 #[derive(PartialEq, Eq, Hash)]
92 pub enum XRef<'tcx> { Predicate(ty::Predicate<'tcx>) }
93
94 struct CrateIndex<'tcx> {
95     items: IndexData,
96     xrefs: FnvHashMap<XRef<'tcx>, u32>, // sequentially-assigned
97 }
98
99 impl<'tcx> CrateIndex<'tcx> {
100     fn record(&mut self, id: DefId, rbml_w: &mut Encoder) {
101         let position = rbml_w.mark_stable_position();
102         self.items.record(id, position);
103     }
104
105     fn add_xref(&mut self, xref: XRef<'tcx>) -> u32 {
106         let old_len = self.xrefs.len() as u32;
107         *self.xrefs.entry(xref).or_insert(old_len)
108     }
109 }
110
111 fn encode_name(rbml_w: &mut Encoder, name: Name) {
112     rbml_w.wr_tagged_str(tag_paths_data_name, &name.as_str());
113 }
114
115 fn encode_def_id(rbml_w: &mut Encoder, id: DefId) {
116     rbml_w.wr_tagged_u64(tag_def_id, def_to_u64(id));
117 }
118
119 /// For every DefId that we create a metadata item for, we include a
120 /// serialized copy of its DefKey, which allows us to recreate a path.
121 fn encode_def_id_and_key(ecx: &EncodeContext,
122                          rbml_w: &mut Encoder,
123                          def_id: DefId)
124 {
125     encode_def_id(rbml_w, def_id);
126     encode_def_key(ecx, rbml_w, def_id);
127 }
128
129 fn encode_def_key(ecx: &EncodeContext,
130                   rbml_w: &mut Encoder,
131                   def_id: DefId)
132 {
133     rbml_w.start_tag(tag_def_key);
134     let def_key = ecx.tcx.map.def_key(def_id);
135     def_key.encode(rbml_w);
136     rbml_w.end_tag();
137 }
138
139 fn encode_trait_ref<'a, 'tcx>(rbml_w: &mut Encoder,
140                               ecx: &EncodeContext<'a, 'tcx>,
141                               trait_ref: ty::TraitRef<'tcx>,
142                               tag: usize) {
143     let ty_str_ctxt = &tyencode::ctxt {
144         diag: ecx.diag,
145         ds: def_to_string,
146         tcx: ecx.tcx,
147         abbrevs: &ecx.type_abbrevs
148     };
149
150     rbml_w.start_tag(tag);
151     tyencode::enc_trait_ref(rbml_w, ty_str_ctxt, trait_ref);
152     rbml_w.end_tag();
153 }
154
155 // Item info table encoding
156 fn encode_family(rbml_w: &mut Encoder, c: char) {
157     rbml_w.wr_tagged_u8(tag_items_data_item_family, c as u8);
158 }
159
160 pub fn def_to_u64(did: DefId) -> u64 {
161     assert!(did.index.as_u32() < u32::MAX);
162     (did.krate as u64) << 32 | (did.index.as_usize() as u64)
163 }
164
165 pub fn def_to_string(did: DefId) -> String {
166     format!("{}:{}", did.krate, did.index.as_usize())
167 }
168
169 fn encode_item_variances(rbml_w: &mut Encoder,
170                          ecx: &EncodeContext,
171                          id: NodeId) {
172     let v = ecx.tcx.item_variances(ecx.tcx.map.local_def_id(id));
173     rbml_w.start_tag(tag_item_variances);
174     v.encode(rbml_w);
175     rbml_w.end_tag();
176 }
177
178 fn encode_bounds_and_type_for_item<'a, 'tcx>(rbml_w: &mut Encoder,
179                                              ecx: &EncodeContext<'a, 'tcx>,
180                                              index: &mut CrateIndex<'tcx>,
181                                              id: NodeId) {
182     encode_bounds_and_type(rbml_w,
183                            ecx,
184                            index,
185                            &ecx.tcx.lookup_item_type(ecx.tcx.map.local_def_id(id)),
186                            &ecx.tcx.lookup_predicates(ecx.tcx.map.local_def_id(id)));
187 }
188
189 fn encode_bounds_and_type<'a, 'tcx>(rbml_w: &mut Encoder,
190                                     ecx: &EncodeContext<'a, 'tcx>,
191                                     index: &mut CrateIndex<'tcx>,
192                                     scheme: &ty::TypeScheme<'tcx>,
193                                     predicates: &ty::GenericPredicates<'tcx>) {
194     encode_generics(rbml_w, ecx, index,
195                     &scheme.generics, &predicates, tag_item_generics);
196     encode_type(ecx, rbml_w, scheme.ty);
197 }
198
199 fn encode_variant_id(rbml_w: &mut Encoder, vid: DefId) {
200     let id = def_to_u64(vid);
201     rbml_w.wr_tagged_u64(tag_items_data_item_variant, id);
202     rbml_w.wr_tagged_u64(tag_mod_child, id);
203 }
204
205 pub fn write_closure_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
206                                     rbml_w: &mut Encoder,
207                                     closure_type: &ty::ClosureTy<'tcx>) {
208     let ty_str_ctxt = &tyencode::ctxt {
209         diag: ecx.diag,
210         ds: def_to_string,
211         tcx: ecx.tcx,
212         abbrevs: &ecx.type_abbrevs
213     };
214     tyencode::enc_closure_ty(rbml_w, ty_str_ctxt, closure_type);
215 }
216
217 pub fn write_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
218                             rbml_w: &mut Encoder,
219                             typ: Ty<'tcx>) {
220     let ty_str_ctxt = &tyencode::ctxt {
221         diag: ecx.diag,
222         ds: def_to_string,
223         tcx: ecx.tcx,
224         abbrevs: &ecx.type_abbrevs
225     };
226     tyencode::enc_ty(rbml_w, ty_str_ctxt, typ);
227 }
228
229 pub fn write_trait_ref<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
230                                  rbml_w: &mut Encoder,
231                                 trait_ref: &ty::TraitRef<'tcx>) {
232     let ty_str_ctxt = &tyencode::ctxt {
233         diag: ecx.diag,
234         ds: def_to_string,
235         tcx: ecx.tcx,
236         abbrevs: &ecx.type_abbrevs
237     };
238     tyencode::enc_trait_ref(rbml_w, ty_str_ctxt, *trait_ref);
239 }
240
241 pub fn write_region(ecx: &EncodeContext,
242                     rbml_w: &mut Encoder,
243                     r: ty::Region) {
244     let ty_str_ctxt = &tyencode::ctxt {
245         diag: ecx.diag,
246         ds: def_to_string,
247         tcx: ecx.tcx,
248         abbrevs: &ecx.type_abbrevs
249     };
250     tyencode::enc_region(rbml_w, ty_str_ctxt, r);
251 }
252
253 fn encode_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
254                          rbml_w: &mut Encoder,
255                          typ: Ty<'tcx>) {
256     rbml_w.start_tag(tag_items_data_item_type);
257     write_type(ecx, rbml_w, typ);
258     rbml_w.end_tag();
259 }
260
261 fn encode_region(ecx: &EncodeContext,
262                  rbml_w: &mut Encoder,
263                  r: ty::Region) {
264     rbml_w.start_tag(tag_items_data_region);
265     write_region(ecx, rbml_w, r);
266     rbml_w.end_tag();
267 }
268
269 fn encode_symbol(ecx: &EncodeContext,
270                  rbml_w: &mut Encoder,
271                  id: NodeId) {
272     match ecx.item_symbols.borrow().get(&id) {
273         Some(x) => {
274             debug!("encode_symbol(id={}, str={})", id, *x);
275             rbml_w.wr_tagged_str(tag_items_data_item_symbol, x);
276         }
277         None => {
278             ecx.diag.bug(&format!("encode_symbol: id not found {}", id));
279         }
280     }
281 }
282
283 fn encode_disr_val(_: &EncodeContext,
284                    rbml_w: &mut Encoder,
285                    disr_val: ty::Disr) {
286     rbml_w.wr_tagged_str(tag_disr_val, &disr_val.to_string());
287 }
288
289 fn encode_parent_item(rbml_w: &mut Encoder, id: DefId) {
290     rbml_w.wr_tagged_u64(tag_items_data_parent_item, def_to_u64(id));
291 }
292
293 fn encode_struct_fields(rbml_w: &mut Encoder,
294                         variant: ty::VariantDef) {
295     for f in &variant.fields {
296         if f.name == special_idents::unnamed_field.name {
297             rbml_w.start_tag(tag_item_unnamed_field);
298         } else {
299             rbml_w.start_tag(tag_item_field);
300             encode_name(rbml_w, f.name);
301         }
302         encode_struct_field_family(rbml_w, f.vis);
303         encode_def_id(rbml_w, f.did);
304         rbml_w.end_tag();
305     }
306 }
307
308 fn encode_enum_variant_info<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
309                                       rbml_w: &mut Encoder,
310                                       id: NodeId,
311                                       vis: hir::Visibility,
312                                       index: &mut CrateIndex<'tcx>) {
313     debug!("encode_enum_variant_info(id={})", id);
314
315     let mut disr_val = 0;
316     let def = ecx.tcx.lookup_adt_def(ecx.tcx.map.local_def_id(id));
317     for variant in &def.variants {
318         let vid = variant.did;
319         let variant_node_id = ecx.local_id(vid);
320
321         if let ty::VariantKind::Struct = variant.kind() {
322             // tuple-like enum variant fields aren't really items so
323             // don't try to encode them.
324             for field in &variant.fields {
325                 encode_field(ecx, rbml_w, field, index);
326             }
327         }
328
329         index.record(vid, rbml_w);
330         rbml_w.start_tag(tag_items_data_item);
331         encode_def_id_and_key(ecx, rbml_w, vid);
332         encode_family(rbml_w, match variant.kind() {
333             ty::VariantKind::Unit | ty::VariantKind::Tuple => 'v',
334             ty::VariantKind::Struct => 'V'
335         });
336         encode_name(rbml_w, variant.name);
337         encode_parent_item(rbml_w, ecx.tcx.map.local_def_id(id));
338         encode_visibility(rbml_w, vis);
339
340         let attrs = ecx.tcx.get_attrs(vid);
341         encode_attributes(rbml_w, &attrs);
342         encode_repr_attrs(rbml_w, ecx, &attrs);
343
344         let stab = stability::lookup_stability(ecx.tcx, vid);
345         let depr = stability::lookup_deprecation(ecx.tcx, vid);
346         encode_stability(rbml_w, stab);
347         encode_deprecation(rbml_w, depr);
348
349         encode_struct_fields(rbml_w, variant);
350
351         let specified_disr_val = variant.disr_val;
352         if specified_disr_val != disr_val {
353             encode_disr_val(ecx, rbml_w, specified_disr_val);
354             disr_val = specified_disr_val;
355         }
356         encode_bounds_and_type_for_item(rbml_w, ecx, index, variant_node_id);
357
358         ecx.tcx.map.with_path(variant_node_id, |path| encode_path(rbml_w, path));
359         rbml_w.end_tag();
360         disr_val = disr_val.wrapping_add(1);
361     }
362 }
363
364 fn encode_path<PI: Iterator<Item=PathElem>>(rbml_w: &mut Encoder, path: PI) {
365     let path = path.collect::<Vec<_>>();
366     rbml_w.start_tag(tag_path);
367     rbml_w.wr_tagged_u32(tag_path_len, path.len() as u32);
368     for pe in &path {
369         let tag = match *pe {
370             ast_map::PathMod(_) => tag_path_elem_mod,
371             ast_map::PathName(_) => tag_path_elem_name
372         };
373         rbml_w.wr_tagged_str(tag, &pe.name().as_str());
374     }
375     rbml_w.end_tag();
376 }
377
378 /// Iterates through "auxiliary node IDs", which are node IDs that describe
379 /// top-level items that are sub-items of the given item. Specifically:
380 ///
381 /// * For newtype structs, iterates through the node ID of the constructor.
382 fn each_auxiliary_node_id<F>(item: &hir::Item, callback: F) -> bool where
383     F: FnOnce(NodeId) -> bool,
384 {
385     let mut continue_ = true;
386     match item.node {
387         hir::ItemStruct(ref struct_def, _) => {
388             // If this is a newtype struct, return the constructor.
389             if struct_def.is_tuple() {
390                 continue_ = callback(struct_def.id());
391             }
392         }
393         _ => {}
394     }
395
396     continue_
397 }
398
399 fn encode_reexports(ecx: &EncodeContext,
400                     rbml_w: &mut Encoder,
401                     id: NodeId) {
402     debug!("(encoding info for module) encoding reexports for {}", id);
403     match ecx.reexports.get(&id) {
404         Some(exports) => {
405             debug!("(encoding info for module) found reexports for {}", id);
406             for exp in exports {
407                 debug!("(encoding info for module) reexport '{}' ({:?}) for \
408                         {}",
409                        exp.name,
410                        exp.def_id,
411                        id);
412                 rbml_w.start_tag(tag_items_data_item_reexport);
413                 rbml_w.wr_tagged_u64(tag_items_data_item_reexport_def_id,
414                                      def_to_u64(exp.def_id));
415                 rbml_w.wr_tagged_str(tag_items_data_item_reexport_name,
416                                      &exp.name.as_str());
417                 rbml_w.end_tag();
418             }
419         },
420         None => debug!("(encoding info for module) found no reexports for {}", id),
421     }
422 }
423
424 fn encode_info_for_mod(ecx: &EncodeContext,
425                        rbml_w: &mut Encoder,
426                        md: &hir::Mod,
427                        attrs: &[ast::Attribute],
428                        id: NodeId,
429                        path: PathElems,
430                        name: Name,
431                        vis: hir::Visibility) {
432     rbml_w.start_tag(tag_items_data_item);
433     encode_def_id_and_key(ecx, rbml_w, ecx.tcx.map.local_def_id(id));
434     encode_family(rbml_w, 'm');
435     encode_name(rbml_w, name);
436     debug!("(encoding info for module) encoding info for module ID {}", id);
437
438     // Encode info about all the module children.
439     for item_id in &md.item_ids {
440         rbml_w.wr_tagged_u64(tag_mod_child,
441                              def_to_u64(ecx.tcx.map.local_def_id(item_id.id)));
442
443         let item = ecx.tcx.map.expect_item(item_id.id);
444         each_auxiliary_node_id(item, |auxiliary_node_id| {
445             rbml_w.wr_tagged_u64(tag_mod_child,
446                                  def_to_u64(ecx.tcx.map.local_def_id(auxiliary_node_id)));
447             true
448         });
449     }
450
451     encode_path(rbml_w, path.clone());
452     encode_visibility(rbml_w, vis);
453
454     let stab = stability::lookup_stability(ecx.tcx, ecx.tcx.map.local_def_id(id));
455     let depr = stability::lookup_deprecation(ecx.tcx, ecx.tcx.map.local_def_id(id));
456     encode_stability(rbml_w, stab);
457     encode_deprecation(rbml_w, depr);
458
459     // Encode the reexports of this module, if this module is public.
460     if vis == hir::Public {
461         debug!("(encoding info for module) encoding reexports for {}", id);
462         encode_reexports(ecx, rbml_w, id);
463     }
464     encode_attributes(rbml_w, attrs);
465
466     rbml_w.end_tag();
467 }
468
469 fn encode_struct_field_family(rbml_w: &mut Encoder,
470                               visibility: hir::Visibility) {
471     encode_family(rbml_w, match visibility {
472         hir::Public => 'g',
473         hir::Inherited => 'N'
474     });
475 }
476
477 fn encode_visibility(rbml_w: &mut Encoder, visibility: hir::Visibility) {
478     let ch = match visibility {
479         hir::Public => 'y',
480         hir::Inherited => 'i',
481     };
482     rbml_w.wr_tagged_u8(tag_items_data_item_visibility, ch as u8);
483 }
484
485 fn encode_constness(rbml_w: &mut Encoder, constness: hir::Constness) {
486     rbml_w.start_tag(tag_items_data_item_constness);
487     let ch = match constness {
488         hir::Constness::Const => 'c',
489         hir::Constness::NotConst => 'n',
490     };
491     rbml_w.wr_str(&ch.to_string());
492     rbml_w.end_tag();
493 }
494
495 fn encode_explicit_self(rbml_w: &mut Encoder,
496                         explicit_self: &ty::ExplicitSelfCategory) {
497     let tag = tag_item_trait_method_explicit_self;
498
499     // Encode the base self type.
500     match *explicit_self {
501         ty::StaticExplicitSelfCategory => {
502             rbml_w.wr_tagged_bytes(tag, &['s' as u8]);
503         }
504         ty::ByValueExplicitSelfCategory => {
505             rbml_w.wr_tagged_bytes(tag, &['v' as u8]);
506         }
507         ty::ByBoxExplicitSelfCategory => {
508             rbml_w.wr_tagged_bytes(tag, &['~' as u8]);
509         }
510         ty::ByReferenceExplicitSelfCategory(_, m) => {
511             // FIXME(#4846) encode custom lifetime
512             let ch = encode_mutability(m);
513             rbml_w.wr_tagged_bytes(tag, &['&' as u8, ch]);
514         }
515     }
516
517     fn encode_mutability(m: hir::Mutability) -> u8 {
518         match m {
519             hir::MutImmutable => 'i' as u8,
520             hir::MutMutable => 'm' as u8,
521         }
522     }
523 }
524
525 fn encode_item_sort(rbml_w: &mut Encoder, sort: char) {
526     rbml_w.wr_tagged_u8(tag_item_trait_item_sort, sort as u8);
527 }
528
529 fn encode_field<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
530                           rbml_w: &mut Encoder,
531                           field: ty::FieldDef<'tcx>,
532                           index: &mut CrateIndex<'tcx>) {
533     let nm = field.name;
534     let id = ecx.local_id(field.did);
535
536     index.record(field.did, rbml_w);
537     rbml_w.start_tag(tag_items_data_item);
538     debug!("encode_field: encoding {} {}", nm, id);
539     encode_struct_field_family(rbml_w, field.vis);
540     encode_name(rbml_w, nm);
541     encode_bounds_and_type_for_item(rbml_w, ecx, index, id);
542     encode_def_id_and_key(ecx, rbml_w, field.did);
543
544     let stab = stability::lookup_stability(ecx.tcx, field.did);
545     let depr = stability::lookup_deprecation(ecx.tcx, field.did);
546     encode_stability(rbml_w, stab);
547     encode_deprecation(rbml_w, depr);
548
549     rbml_w.end_tag();
550 }
551
552 fn encode_info_for_struct_ctor<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
553                                          rbml_w: &mut Encoder,
554                                          name: Name,
555                                          ctor_id: NodeId,
556                                          index: &mut CrateIndex<'tcx>,
557                                          struct_id: NodeId) {
558     let ctor_def_id = ecx.tcx.map.local_def_id(ctor_id);
559
560     index.record(ctor_def_id, rbml_w);
561     rbml_w.start_tag(tag_items_data_item);
562     encode_def_id_and_key(ecx, rbml_w, ctor_def_id);
563     encode_family(rbml_w, 'o');
564     encode_bounds_and_type_for_item(rbml_w, ecx, index, ctor_id);
565     encode_name(rbml_w, name);
566     ecx.tcx.map.with_path(ctor_id, |path| encode_path(rbml_w, path));
567     encode_parent_item(rbml_w, ecx.tcx.map.local_def_id(struct_id));
568
569     if ecx.item_symbols.borrow().contains_key(&ctor_id) {
570         encode_symbol(ecx, rbml_w, ctor_id);
571     }
572
573     let stab = stability::lookup_stability(ecx.tcx, ecx.tcx.map.local_def_id(ctor_id));
574     let depr= stability::lookup_deprecation(ecx.tcx, ecx.tcx.map.local_def_id(ctor_id));
575     encode_stability(rbml_w, stab);
576     encode_deprecation(rbml_w, depr);
577
578     // indicate that this is a tuple struct ctor, because downstream users will normally want
579     // the tuple struct definition, but without this there is no way for them to tell that
580     // they actually have a ctor rather than a normal function
581     rbml_w.wr_tagged_bytes(tag_items_data_item_is_tuple_struct_ctor, &[]);
582
583     rbml_w.end_tag();
584 }
585
586 fn encode_generics<'a, 'tcx>(rbml_w: &mut Encoder,
587                              ecx: &EncodeContext<'a, 'tcx>,
588                              index: &mut CrateIndex<'tcx>,
589                              generics: &ty::Generics<'tcx>,
590                              predicates: &ty::GenericPredicates<'tcx>,
591                              tag: usize)
592 {
593     rbml_w.start_tag(tag);
594
595     // Type parameters
596     let ty_str_ctxt = &tyencode::ctxt {
597         diag: ecx.diag,
598         ds: def_to_string,
599         tcx: ecx.tcx,
600         abbrevs: &ecx.type_abbrevs
601     };
602
603     for param in &generics.types {
604         rbml_w.start_tag(tag_type_param_def);
605         tyencode::enc_type_param_def(rbml_w, ty_str_ctxt, param);
606         rbml_w.end_tag();
607     }
608
609     // Region parameters
610     for param in &generics.regions {
611         rbml_w.start_tag(tag_region_param_def);
612
613         rbml_w.start_tag(tag_region_param_def_ident);
614         encode_name(rbml_w, param.name);
615         rbml_w.end_tag();
616
617         rbml_w.wr_tagged_u64(tag_region_param_def_def_id,
618                              def_to_u64(param.def_id));
619
620         rbml_w.wr_tagged_u64(tag_region_param_def_space,
621                              param.space.to_uint() as u64);
622
623         rbml_w.wr_tagged_u64(tag_region_param_def_index,
624                              param.index as u64);
625
626         for &bound_region in &param.bounds {
627             encode_region(ecx, rbml_w, bound_region);
628         }
629
630         rbml_w.end_tag();
631     }
632
633     encode_predicates_in_current_doc(rbml_w, ecx, index, predicates);
634
635     rbml_w.end_tag();
636 }
637
638 fn encode_predicates_in_current_doc<'a,'tcx>(rbml_w: &mut Encoder,
639                                              _ecx: &EncodeContext<'a,'tcx>,
640                                              index: &mut CrateIndex<'tcx>,
641                                              predicates: &ty::GenericPredicates<'tcx>)
642 {
643     for (space, _, predicate) in predicates.predicates.iter_enumerated() {
644         let tag = match space {
645             subst::TypeSpace => tag_type_predicate,
646             subst::SelfSpace => tag_self_predicate,
647             subst::FnSpace => tag_fn_predicate
648         };
649
650         rbml_w.wr_tagged_u32(tag,
651             index.add_xref(XRef::Predicate(predicate.clone())));
652     }
653 }
654
655 fn encode_predicates<'a,'tcx>(rbml_w: &mut Encoder,
656                               ecx: &EncodeContext<'a,'tcx>,
657                               index: &mut CrateIndex<'tcx>,
658                               predicates: &ty::GenericPredicates<'tcx>,
659                               tag: usize)
660 {
661     rbml_w.start_tag(tag);
662     encode_predicates_in_current_doc(rbml_w, ecx, index, predicates);
663     rbml_w.end_tag();
664 }
665
666 fn encode_method_ty_fields<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
667                                      rbml_w: &mut Encoder,
668                                      index: &mut CrateIndex<'tcx>,
669                                      method_ty: &ty::Method<'tcx>) {
670     encode_def_id_and_key(ecx, rbml_w, method_ty.def_id);
671     encode_name(rbml_w, method_ty.name);
672     encode_generics(rbml_w, ecx, index,
673                     &method_ty.generics, &method_ty.predicates,
674                     tag_method_ty_generics);
675     encode_visibility(rbml_w, method_ty.vis);
676     encode_explicit_self(rbml_w, &method_ty.explicit_self);
677     match method_ty.explicit_self {
678         ty::StaticExplicitSelfCategory => {
679             encode_family(rbml_w, STATIC_METHOD_FAMILY);
680         }
681         _ => encode_family(rbml_w, METHOD_FAMILY)
682     }
683 }
684
685 fn encode_info_for_associated_const<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
686                                               rbml_w: &mut Encoder,
687                                               index: &mut CrateIndex<'tcx>,
688                                               associated_const: &ty::AssociatedConst,
689                                               impl_path: PathElems,
690                                               parent_id: NodeId,
691                                               impl_item_opt: Option<&hir::ImplItem>) {
692     debug!("encode_info_for_associated_const({:?},{:?})",
693            associated_const.def_id,
694            associated_const.name);
695
696     index.record(associated_const.def_id, rbml_w);
697     rbml_w.start_tag(tag_items_data_item);
698
699     encode_def_id_and_key(ecx, rbml_w, associated_const.def_id);
700     encode_name(rbml_w, associated_const.name);
701     encode_visibility(rbml_w, associated_const.vis);
702     encode_family(rbml_w, 'C');
703
704     encode_parent_item(rbml_w, ecx.tcx.map.local_def_id(parent_id));
705     encode_item_sort(rbml_w, 'C');
706
707     encode_bounds_and_type_for_item(rbml_w, ecx, index,
708                                     ecx.local_id(associated_const.def_id));
709
710     let stab = stability::lookup_stability(ecx.tcx, associated_const.def_id);
711     let depr = stability::lookup_deprecation(ecx.tcx, associated_const.def_id);
712     encode_stability(rbml_w, stab);
713     encode_deprecation(rbml_w, depr);
714
715     let elem = ast_map::PathName(associated_const.name);
716     encode_path(rbml_w, impl_path.chain(Some(elem)));
717
718     if let Some(ii) = impl_item_opt {
719         encode_attributes(rbml_w, &ii.attrs);
720         encode_inlined_item(ecx,
721                             rbml_w,
722                             InlinedItemRef::ImplItem(ecx.tcx.map.local_def_id(parent_id),
723                                                      ii));
724     }
725
726     rbml_w.end_tag();
727 }
728
729 fn encode_info_for_method<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
730                                     rbml_w: &mut Encoder,
731                                     index: &mut CrateIndex<'tcx>,
732                                     m: &ty::Method<'tcx>,
733                                     impl_path: PathElems,
734                                     is_default_impl: bool,
735                                     parent_id: NodeId,
736                                     impl_item_opt: Option<&hir::ImplItem>) {
737
738     debug!("encode_info_for_method: {:?} {:?}", m.def_id,
739            m.name);
740     index.record(m.def_id, rbml_w);
741     rbml_w.start_tag(tag_items_data_item);
742
743     encode_method_ty_fields(ecx, rbml_w, index, m);
744     encode_parent_item(rbml_w, ecx.tcx.map.local_def_id(parent_id));
745     encode_item_sort(rbml_w, 'r');
746
747     let stab = stability::lookup_stability(ecx.tcx, m.def_id);
748     let depr = stability::lookup_deprecation(ecx.tcx, m.def_id);
749     encode_stability(rbml_w, stab);
750     encode_deprecation(rbml_w, depr);
751
752     let m_node_id = ecx.local_id(m.def_id);
753     encode_bounds_and_type_for_item(rbml_w, ecx, index, m_node_id);
754
755     let elem = ast_map::PathName(m.name);
756     encode_path(rbml_w, impl_path.chain(Some(elem)));
757     if let Some(impl_item) = impl_item_opt {
758         if let hir::ImplItemKind::Method(ref sig, _) = impl_item.node {
759             encode_attributes(rbml_w, &impl_item.attrs);
760             let scheme = ecx.tcx.lookup_item_type(m.def_id);
761             let any_types = !scheme.generics.types.is_empty();
762             let needs_inline = any_types || is_default_impl ||
763                                attr::requests_inline(&impl_item.attrs);
764             if needs_inline || sig.constness == hir::Constness::Const {
765                 encode_inlined_item(ecx,
766                                     rbml_w,
767                                     InlinedItemRef::ImplItem(ecx.tcx.map.local_def_id(parent_id),
768                                                              impl_item));
769             }
770             encode_constness(rbml_w, sig.constness);
771             if !any_types {
772                 let m_id = ecx.local_id(m.def_id);
773                 encode_symbol(ecx, rbml_w, m_id);
774             }
775             encode_method_argument_names(rbml_w, &sig.decl);
776         }
777     }
778
779     rbml_w.end_tag();
780 }
781
782 fn encode_info_for_associated_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
783                                              rbml_w: &mut Encoder,
784                                              index: &mut CrateIndex<'tcx>,
785                                              associated_type: &ty::AssociatedType<'tcx>,
786                                              impl_path: PathElems,
787                                              parent_id: NodeId,
788                                              impl_item_opt: Option<&hir::ImplItem>) {
789     debug!("encode_info_for_associated_type({:?},{:?})",
790            associated_type.def_id,
791            associated_type.name);
792
793     index.record(associated_type.def_id, rbml_w);
794     rbml_w.start_tag(tag_items_data_item);
795
796     encode_def_id_and_key(ecx, rbml_w, associated_type.def_id);
797     encode_name(rbml_w, associated_type.name);
798     encode_visibility(rbml_w, associated_type.vis);
799     encode_family(rbml_w, 'y');
800     encode_parent_item(rbml_w, ecx.tcx.map.local_def_id(parent_id));
801     encode_item_sort(rbml_w, 't');
802
803     let stab = stability::lookup_stability(ecx.tcx, associated_type.def_id);
804     let depr = stability::lookup_deprecation(ecx.tcx, associated_type.def_id);
805     encode_stability(rbml_w, stab);
806     encode_deprecation(rbml_w, depr);
807
808     let elem = ast_map::PathName(associated_type.name);
809     encode_path(rbml_w, impl_path.chain(Some(elem)));
810
811     if let Some(ii) = impl_item_opt {
812         encode_attributes(rbml_w, &ii.attrs);
813     } else {
814         encode_predicates(rbml_w, ecx, index,
815                           &ecx.tcx.lookup_predicates(associated_type.def_id),
816                           tag_item_generics);
817     }
818
819     if let Some(ty) = associated_type.ty {
820         encode_type(ecx, rbml_w, ty);
821     }
822
823     rbml_w.end_tag();
824 }
825
826 fn encode_method_argument_names(rbml_w: &mut Encoder,
827                                 decl: &hir::FnDecl) {
828     rbml_w.start_tag(tag_method_argument_names);
829     for arg in &decl.inputs {
830         let tag = tag_method_argument_name;
831         if let hir::PatIdent(_, ref path1, _) = arg.pat.node {
832             let name = path1.node.name.as_str();
833             rbml_w.wr_tagged_bytes(tag, name.as_bytes());
834         } else {
835             rbml_w.wr_tagged_bytes(tag, &[]);
836         }
837     }
838     rbml_w.end_tag();
839 }
840
841 fn encode_repr_attrs(rbml_w: &mut Encoder,
842                      ecx: &EncodeContext,
843                      attrs: &[ast::Attribute]) {
844     let mut repr_attrs = Vec::new();
845     for attr in attrs {
846         repr_attrs.extend(attr::find_repr_attrs(ecx.tcx.sess.diagnostic(),
847                                                 attr));
848     }
849     rbml_w.start_tag(tag_items_data_item_repr);
850     repr_attrs.encode(rbml_w);
851     rbml_w.end_tag();
852 }
853
854 fn encode_inlined_item(ecx: &EncodeContext,
855                        rbml_w: &mut Encoder,
856                        ii: InlinedItemRef) {
857     let mut eii = ecx.encode_inlined_item.borrow_mut();
858     let eii: &mut EncodeInlinedItem = &mut *eii;
859     eii(ecx, rbml_w, ii);
860
861     encode_mir(ecx, rbml_w, ii);
862 }
863
864 fn encode_mir(ecx: &EncodeContext, rbml_w: &mut Encoder, ii: InlinedItemRef) {
865     let id = match ii {
866         InlinedItemRef::Item(item) => item.id,
867         InlinedItemRef::TraitItem(_, trait_item) => trait_item.id,
868         InlinedItemRef::ImplItem(_, impl_item) => impl_item.id,
869         InlinedItemRef::Foreign(foreign_item) => foreign_item.id
870     };
871
872     if let Some(mir) = ecx.mir_map.get(&id) {
873         rbml_w.start_tag(tag_mir as usize);
874         Encodable::encode(mir, rbml_w).unwrap();
875         rbml_w.end_tag();
876     }
877 }
878
879 const FN_FAMILY: char = 'f';
880 const STATIC_METHOD_FAMILY: char = 'F';
881 const METHOD_FAMILY: char = 'h';
882
883 // Encodes the inherent implementations of a structure, enumeration, or trait.
884 fn encode_inherent_implementations(ecx: &EncodeContext,
885                                    rbml_w: &mut Encoder,
886                                    def_id: DefId) {
887     match ecx.tcx.inherent_impls.borrow().get(&def_id) {
888         None => {}
889         Some(implementations) => {
890             for &impl_def_id in implementations.iter() {
891                 rbml_w.start_tag(tag_items_data_item_inherent_impl);
892                 encode_def_id(rbml_w, impl_def_id);
893                 rbml_w.end_tag();
894             }
895         }
896     }
897 }
898
899 fn encode_stability(rbml_w: &mut Encoder, stab_opt: Option<&attr::Stability>) {
900     stab_opt.map(|stab| {
901         rbml_w.start_tag(tag_items_data_item_stability);
902         stab.encode(rbml_w).unwrap();
903         rbml_w.end_tag();
904     });
905 }
906
907 fn encode_deprecation(rbml_w: &mut Encoder, depr_opt: Option<attr::Deprecation>) {
908     depr_opt.map(|depr| {
909         rbml_w.start_tag(tag_items_data_item_deprecation);
910         depr.encode(rbml_w).unwrap();
911         rbml_w.end_tag();
912     });
913 }
914
915 fn encode_xrefs<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
916                           rbml_w: &mut Encoder,
917                           xrefs: FnvHashMap<XRef<'tcx>, u32>)
918 {
919     let ty_str_ctxt = &tyencode::ctxt {
920         diag: ecx.diag,
921         ds: def_to_string,
922         tcx: ecx.tcx,
923         abbrevs: &ecx.type_abbrevs
924     };
925
926     let mut xref_positions = vec![0; xrefs.len()];
927     rbml_w.start_tag(tag_xref_data);
928     for (xref, id) in xrefs.into_iter() {
929         xref_positions[id as usize] = rbml_w.mark_stable_position() as u32;
930         match xref {
931             XRef::Predicate(p) => {
932                 tyencode::enc_predicate(rbml_w, ty_str_ctxt, &p)
933             }
934         }
935     }
936     rbml_w.end_tag();
937
938     rbml_w.start_tag(tag_xref_index);
939     index::write_dense_index(xref_positions, rbml_w.writer);
940     rbml_w.end_tag();
941 }
942
943 fn encode_info_for_item<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
944                                   rbml_w: &mut Encoder,
945                                   item: &hir::Item,
946                                   index: &mut CrateIndex<'tcx>,
947                                   path: PathElems,
948                                   vis: hir::Visibility) {
949     let tcx = ecx.tcx;
950
951     debug!("encoding info for item at {}",
952            tcx.sess.codemap().span_to_string(item.span));
953
954     let def_id = ecx.tcx.map.local_def_id(item.id);
955     let stab = stability::lookup_stability(tcx, ecx.tcx.map.local_def_id(item.id));
956     let depr = stability::lookup_deprecation(tcx, ecx.tcx.map.local_def_id(item.id));
957
958     match item.node {
959       hir::ItemStatic(_, m, _) => {
960         index.record(def_id, rbml_w);
961         rbml_w.start_tag(tag_items_data_item);
962         encode_def_id_and_key(ecx, rbml_w, def_id);
963         if m == hir::MutMutable {
964             encode_family(rbml_w, 'b');
965         } else {
966             encode_family(rbml_w, 'c');
967         }
968         encode_bounds_and_type_for_item(rbml_w, ecx, index, item.id);
969         encode_symbol(ecx, rbml_w, item.id);
970         encode_name(rbml_w, item.name);
971         encode_path(rbml_w, path);
972         encode_visibility(rbml_w, vis);
973         encode_stability(rbml_w, stab);
974         encode_deprecation(rbml_w, depr);
975         encode_attributes(rbml_w, &item.attrs);
976         rbml_w.end_tag();
977       }
978       hir::ItemConst(_, _) => {
979         index.record(def_id, rbml_w);
980         rbml_w.start_tag(tag_items_data_item);
981         encode_def_id_and_key(ecx, rbml_w, def_id);
982         encode_family(rbml_w, 'C');
983         encode_bounds_and_type_for_item(rbml_w, ecx, index, item.id);
984         encode_name(rbml_w, item.name);
985         encode_path(rbml_w, path);
986         encode_attributes(rbml_w, &item.attrs);
987         encode_inlined_item(ecx, rbml_w, InlinedItemRef::Item(item));
988         encode_visibility(rbml_w, vis);
989         encode_stability(rbml_w, stab);
990         encode_deprecation(rbml_w, depr);
991         rbml_w.end_tag();
992       }
993       hir::ItemFn(ref decl, _, constness, _, ref generics, _) => {
994         index.record(def_id, rbml_w);
995         rbml_w.start_tag(tag_items_data_item);
996         encode_def_id_and_key(ecx, rbml_w, def_id);
997         encode_family(rbml_w, FN_FAMILY);
998         let tps_len = generics.ty_params.len();
999         encode_bounds_and_type_for_item(rbml_w, ecx, index, item.id);
1000         encode_name(rbml_w, item.name);
1001         encode_path(rbml_w, path);
1002         encode_attributes(rbml_w, &item.attrs);
1003         let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
1004         if needs_inline || constness == hir::Constness::Const {
1005             encode_inlined_item(ecx, rbml_w, InlinedItemRef::Item(item));
1006         }
1007         if tps_len == 0 {
1008             encode_symbol(ecx, rbml_w, item.id);
1009         }
1010         encode_constness(rbml_w, constness);
1011         encode_visibility(rbml_w, vis);
1012         encode_stability(rbml_w, stab);
1013         encode_deprecation(rbml_w, depr);
1014         encode_method_argument_names(rbml_w, &**decl);
1015         rbml_w.end_tag();
1016       }
1017       hir::ItemMod(ref m) => {
1018         index.record(def_id, rbml_w);
1019         encode_info_for_mod(ecx,
1020                             rbml_w,
1021                             m,
1022                             &item.attrs,
1023                             item.id,
1024                             path,
1025                             item.name,
1026                             item.vis);
1027       }
1028       hir::ItemForeignMod(ref fm) => {
1029         index.record(def_id, rbml_w);
1030         rbml_w.start_tag(tag_items_data_item);
1031         encode_def_id_and_key(ecx, rbml_w, def_id);
1032         encode_family(rbml_w, 'n');
1033         encode_name(rbml_w, item.name);
1034         encode_path(rbml_w, path);
1035
1036         // Encode all the items in this module.
1037         for foreign_item in &fm.items {
1038             rbml_w.wr_tagged_u64(tag_mod_child,
1039                                  def_to_u64(ecx.tcx.map.local_def_id(foreign_item.id)));
1040         }
1041         encode_visibility(rbml_w, vis);
1042         encode_stability(rbml_w, stab);
1043         encode_deprecation(rbml_w, depr);
1044         rbml_w.end_tag();
1045       }
1046       hir::ItemTy(..) => {
1047         index.record(def_id, rbml_w);
1048         rbml_w.start_tag(tag_items_data_item);
1049         encode_def_id_and_key(ecx, rbml_w, def_id);
1050         encode_family(rbml_w, 'y');
1051         encode_bounds_and_type_for_item(rbml_w, ecx, index, item.id);
1052         encode_name(rbml_w, item.name);
1053         encode_path(rbml_w, path);
1054         encode_visibility(rbml_w, vis);
1055         encode_stability(rbml_w, stab);
1056         encode_deprecation(rbml_w, depr);
1057         rbml_w.end_tag();
1058       }
1059       hir::ItemEnum(ref enum_definition, _) => {
1060         index.record(def_id, rbml_w);
1061
1062         rbml_w.start_tag(tag_items_data_item);
1063         encode_def_id_and_key(ecx, rbml_w, def_id);
1064         encode_family(rbml_w, 't');
1065         encode_item_variances(rbml_w, ecx, item.id);
1066         encode_bounds_and_type_for_item(rbml_w, ecx, index, item.id);
1067         encode_name(rbml_w, item.name);
1068         encode_attributes(rbml_w, &item.attrs);
1069         encode_repr_attrs(rbml_w, ecx, &item.attrs);
1070         for v in &enum_definition.variants {
1071             encode_variant_id(rbml_w, ecx.tcx.map.local_def_id(v.node.data.id()));
1072         }
1073         encode_inlined_item(ecx, rbml_w, InlinedItemRef::Item(item));
1074         encode_path(rbml_w, path);
1075
1076         // Encode inherent implementations for this enumeration.
1077         encode_inherent_implementations(ecx, rbml_w, def_id);
1078
1079         encode_visibility(rbml_w, vis);
1080         encode_stability(rbml_w, stab);
1081         encode_deprecation(rbml_w, depr);
1082         rbml_w.end_tag();
1083
1084         encode_enum_variant_info(ecx,
1085                                  rbml_w,
1086                                  item.id,
1087                                  vis,
1088                                  index);
1089       }
1090       hir::ItemStruct(ref struct_def, _) => {
1091         let def = ecx.tcx.lookup_adt_def(def_id);
1092         let variant = def.struct_variant();
1093
1094         /* Index the class*/
1095         index.record(def_id, rbml_w);
1096
1097         /* Now, make an item for the class itself */
1098         rbml_w.start_tag(tag_items_data_item);
1099         encode_def_id_and_key(ecx, rbml_w, def_id);
1100         encode_family(rbml_w, 'S');
1101         encode_bounds_and_type_for_item(rbml_w, ecx, index, item.id);
1102
1103         encode_item_variances(rbml_w, ecx, item.id);
1104         encode_name(rbml_w, item.name);
1105         encode_attributes(rbml_w, &item.attrs);
1106         encode_path(rbml_w, path.clone());
1107         encode_stability(rbml_w, stab);
1108         encode_deprecation(rbml_w, depr);
1109         encode_visibility(rbml_w, vis);
1110         encode_repr_attrs(rbml_w, ecx, &item.attrs);
1111
1112         /* Encode def_ids for each field and method
1113          for methods, write all the stuff get_trait_method
1114         needs to know*/
1115         encode_struct_fields(rbml_w, variant);
1116
1117         encode_inlined_item(ecx, rbml_w, InlinedItemRef::Item(item));
1118
1119         // Encode inherent implementations for this structure.
1120         encode_inherent_implementations(ecx, rbml_w, def_id);
1121
1122         if !struct_def.is_struct() {
1123             let ctor_did = ecx.tcx.map.local_def_id(struct_def.id());
1124             rbml_w.wr_tagged_u64(tag_items_data_item_struct_ctor,
1125                                  def_to_u64(ctor_did));
1126         }
1127
1128         rbml_w.end_tag();
1129
1130         for field in &variant.fields {
1131             encode_field(ecx, rbml_w, field, index);
1132         }
1133
1134         // If this is a tuple-like struct, encode the type of the constructor.
1135         if !struct_def.is_struct() {
1136             encode_info_for_struct_ctor(ecx, rbml_w, item.name, struct_def.id(), index, item.id);
1137         }
1138       }
1139       hir::ItemDefaultImpl(unsafety, _) => {
1140           index.record(def_id, rbml_w);
1141           rbml_w.start_tag(tag_items_data_item);
1142           encode_def_id_and_key(ecx, rbml_w, def_id);
1143           encode_family(rbml_w, 'd');
1144           encode_name(rbml_w, item.name);
1145           encode_unsafety(rbml_w, unsafety);
1146
1147           let trait_ref = tcx.impl_trait_ref(ecx.tcx.map.local_def_id(item.id)).unwrap();
1148           encode_trait_ref(rbml_w, ecx, trait_ref, tag_item_trait_ref);
1149           rbml_w.end_tag();
1150       }
1151       hir::ItemImpl(unsafety, polarity, _, _, _, ref ast_items) => {
1152         // We need to encode information about the default methods we
1153         // have inherited, so we drive this based on the impl structure.
1154         let impl_items = tcx.impl_items.borrow();
1155         let items = impl_items.get(&def_id).unwrap();
1156
1157         index.record(def_id, rbml_w);
1158         rbml_w.start_tag(tag_items_data_item);
1159         encode_def_id_and_key(ecx, rbml_w, def_id);
1160         encode_family(rbml_w, 'i');
1161         encode_bounds_and_type_for_item(rbml_w, ecx, index, item.id);
1162         encode_name(rbml_w, item.name);
1163         encode_attributes(rbml_w, &item.attrs);
1164         encode_unsafety(rbml_w, unsafety);
1165         encode_polarity(rbml_w, polarity);
1166
1167         match tcx.custom_coerce_unsized_kinds.borrow().get(&ecx.tcx.map.local_def_id(item.id)) {
1168             Some(&kind) => {
1169                 rbml_w.start_tag(tag_impl_coerce_unsized_kind);
1170                 kind.encode(rbml_w);
1171                 rbml_w.end_tag();
1172             }
1173             None => {}
1174         }
1175
1176         for &item_def_id in items {
1177             rbml_w.start_tag(tag_item_impl_item);
1178             match item_def_id {
1179                 ty::ConstTraitItemId(item_def_id) => {
1180                     encode_def_id(rbml_w, item_def_id);
1181                     encode_item_sort(rbml_w, 'C');
1182                 }
1183                 ty::MethodTraitItemId(item_def_id) => {
1184                     encode_def_id(rbml_w, item_def_id);
1185                     encode_item_sort(rbml_w, 'r');
1186                 }
1187                 ty::TypeTraitItemId(item_def_id) => {
1188                     encode_def_id(rbml_w, item_def_id);
1189                     encode_item_sort(rbml_w, 't');
1190                 }
1191             }
1192             rbml_w.end_tag();
1193         }
1194         if let Some(trait_ref) = tcx.impl_trait_ref(ecx.tcx.map.local_def_id(item.id)) {
1195             encode_trait_ref(rbml_w, ecx, trait_ref, tag_item_trait_ref);
1196         }
1197         encode_path(rbml_w, path.clone());
1198         encode_stability(rbml_w, stab);
1199         encode_deprecation(rbml_w, depr);
1200         rbml_w.end_tag();
1201
1202         // Iterate down the trait items, emitting them. We rely on the
1203         // assumption that all of the actually implemented trait items
1204         // appear first in the impl structure, in the same order they do
1205         // in the ast. This is a little sketchy.
1206         let num_implemented_methods = ast_items.len();
1207         for (i, &trait_item_def_id) in items.iter().enumerate() {
1208             let ast_item = if i < num_implemented_methods {
1209                 Some(&ast_items[i])
1210             } else {
1211                 None
1212             };
1213
1214             match tcx.impl_or_trait_item(trait_item_def_id.def_id()) {
1215                 ty::ConstTraitItem(ref associated_const) => {
1216                     encode_info_for_associated_const(ecx,
1217                                                      rbml_w,
1218                                                      index,
1219                                                      &*associated_const,
1220                                                      path.clone(),
1221                                                      item.id,
1222                                                      ast_item)
1223                 }
1224                 ty::MethodTraitItem(ref method_type) => {
1225                     encode_info_for_method(ecx,
1226                                            rbml_w,
1227                                            index,
1228                                            &**method_type,
1229                                            path.clone(),
1230                                            false,
1231                                            item.id,
1232                                            ast_item)
1233                 }
1234                 ty::TypeTraitItem(ref associated_type) => {
1235                     encode_info_for_associated_type(ecx,
1236                                                     rbml_w,
1237                                                     index,
1238                                                     &**associated_type,
1239                                                     path.clone(),
1240                                                     item.id,
1241                                                     ast_item)
1242                 }
1243             }
1244         }
1245       }
1246       hir::ItemTrait(_, _, _, ref ms) => {
1247         index.record(def_id, rbml_w);
1248         rbml_w.start_tag(tag_items_data_item);
1249         encode_def_id_and_key(ecx, rbml_w, def_id);
1250         encode_family(rbml_w, 'I');
1251         encode_item_variances(rbml_w, ecx, item.id);
1252         let trait_def = tcx.lookup_trait_def(def_id);
1253         let trait_predicates = tcx.lookup_predicates(def_id);
1254         encode_unsafety(rbml_w, trait_def.unsafety);
1255         encode_paren_sugar(rbml_w, trait_def.paren_sugar);
1256         encode_defaulted(rbml_w, tcx.trait_has_default_impl(def_id));
1257         encode_associated_type_names(rbml_w, &trait_def.associated_type_names);
1258         encode_generics(rbml_w, ecx, index,
1259                         &trait_def.generics, &trait_predicates,
1260                         tag_item_generics);
1261         encode_predicates(rbml_w, ecx, index,
1262                           &tcx.lookup_super_predicates(def_id),
1263                           tag_item_super_predicates);
1264         encode_trait_ref(rbml_w, ecx, trait_def.trait_ref, tag_item_trait_ref);
1265         encode_name(rbml_w, item.name);
1266         encode_attributes(rbml_w, &item.attrs);
1267         encode_visibility(rbml_w, vis);
1268         encode_stability(rbml_w, stab);
1269         encode_deprecation(rbml_w, depr);
1270         for &method_def_id in tcx.trait_item_def_ids(def_id).iter() {
1271             rbml_w.start_tag(tag_item_trait_item);
1272             match method_def_id {
1273                 ty::ConstTraitItemId(const_def_id) => {
1274                     encode_def_id(rbml_w, const_def_id);
1275                     encode_item_sort(rbml_w, 'C');
1276                 }
1277                 ty::MethodTraitItemId(method_def_id) => {
1278                     encode_def_id(rbml_w, method_def_id);
1279                     encode_item_sort(rbml_w, 'r');
1280                 }
1281                 ty::TypeTraitItemId(type_def_id) => {
1282                     encode_def_id(rbml_w, type_def_id);
1283                     encode_item_sort(rbml_w, 't');
1284                 }
1285             }
1286             rbml_w.end_tag();
1287
1288             rbml_w.wr_tagged_u64(tag_mod_child,
1289                                  def_to_u64(method_def_id.def_id()));
1290         }
1291         encode_path(rbml_w, path.clone());
1292
1293         // Encode inherent implementations for this trait.
1294         encode_inherent_implementations(ecx, rbml_w, def_id);
1295
1296         rbml_w.end_tag();
1297
1298         // Now output the trait item info for each trait item.
1299         let r = tcx.trait_item_def_ids(def_id);
1300         for (i, &item_def_id) in r.iter().enumerate() {
1301             assert_eq!(item_def_id.def_id().krate, LOCAL_CRATE);
1302
1303             index.record(item_def_id.def_id(), rbml_w);
1304             rbml_w.start_tag(tag_items_data_item);
1305
1306             encode_parent_item(rbml_w, def_id);
1307
1308             let stab = stability::lookup_stability(tcx, item_def_id.def_id());
1309             let depr = stability::lookup_deprecation(tcx, item_def_id.def_id());
1310             encode_stability(rbml_w, stab);
1311             encode_deprecation(rbml_w, depr);
1312
1313             let trait_item_type =
1314                 tcx.impl_or_trait_item(item_def_id.def_id());
1315             let is_nonstatic_method;
1316             match trait_item_type {
1317                 ty::ConstTraitItem(associated_const) => {
1318                     encode_name(rbml_w, associated_const.name);
1319                     encode_def_id_and_key(ecx, rbml_w, associated_const.def_id);
1320                     encode_visibility(rbml_w, associated_const.vis);
1321
1322                     let elem = ast_map::PathName(associated_const.name);
1323                     encode_path(rbml_w,
1324                                 path.clone().chain(Some(elem)));
1325
1326                     encode_family(rbml_w, 'C');
1327
1328                     encode_bounds_and_type_for_item(rbml_w, ecx, index,
1329                                                     ecx.local_id(associated_const.def_id));
1330
1331                     is_nonstatic_method = false;
1332                 }
1333                 ty::MethodTraitItem(method_ty) => {
1334                     let method_def_id = item_def_id.def_id();
1335
1336                     encode_method_ty_fields(ecx, rbml_w, index, &*method_ty);
1337
1338                     let elem = ast_map::PathName(method_ty.name);
1339                     encode_path(rbml_w,
1340                                 path.clone().chain(Some(elem)));
1341
1342                     match method_ty.explicit_self {
1343                         ty::StaticExplicitSelfCategory => {
1344                             encode_family(rbml_w,
1345                                           STATIC_METHOD_FAMILY);
1346                         }
1347                         _ => {
1348                             encode_family(rbml_w,
1349                                           METHOD_FAMILY);
1350                         }
1351                     }
1352                     encode_bounds_and_type_for_item(rbml_w, ecx, index,
1353                                                     ecx.local_id(method_def_id));
1354
1355                     is_nonstatic_method = method_ty.explicit_self !=
1356                         ty::StaticExplicitSelfCategory;
1357                 }
1358                 ty::TypeTraitItem(associated_type) => {
1359                     encode_name(rbml_w, associated_type.name);
1360                     encode_def_id_and_key(ecx, rbml_w, associated_type.def_id);
1361
1362                     let elem = ast_map::PathName(associated_type.name);
1363                     encode_path(rbml_w,
1364                                 path.clone().chain(Some(elem)));
1365
1366                     encode_item_sort(rbml_w, 't');
1367                     encode_family(rbml_w, 'y');
1368
1369                     if let Some(ty) = associated_type.ty {
1370                         encode_type(ecx, rbml_w, ty);
1371                     }
1372
1373                     is_nonstatic_method = false;
1374                 }
1375             }
1376
1377             let trait_item = &ms[i];
1378             encode_attributes(rbml_w, &trait_item.attrs);
1379             match trait_item.node {
1380                 hir::ConstTraitItem(_, ref default) => {
1381                     if default.is_some() {
1382                         encode_item_sort(rbml_w, 'C');
1383                     } else {
1384                         encode_item_sort(rbml_w, 'c');
1385                     }
1386
1387                     encode_inlined_item(ecx, rbml_w,
1388                                         InlinedItemRef::TraitItem(def_id, trait_item));
1389                 }
1390                 hir::MethodTraitItem(ref sig, ref body) => {
1391                     // If this is a static method, we've already
1392                     // encoded this.
1393                     if is_nonstatic_method {
1394                         // FIXME: I feel like there is something funny
1395                         // going on.
1396                         encode_bounds_and_type_for_item(rbml_w, ecx, index,
1397                                                         ecx.local_id(item_def_id.def_id()));
1398                     }
1399
1400                     if body.is_some() {
1401                         encode_item_sort(rbml_w, 'p');
1402                         encode_inlined_item(ecx, rbml_w,
1403                                             InlinedItemRef::TraitItem(def_id, trait_item));
1404                     } else {
1405                         encode_item_sort(rbml_w, 'r');
1406                     }
1407                     encode_method_argument_names(rbml_w, &sig.decl);
1408                 }
1409
1410                 hir::TypeTraitItem(..) => {}
1411             }
1412
1413             rbml_w.end_tag();
1414         }
1415       }
1416       hir::ItemExternCrate(_) | hir::ItemUse(_) => {
1417         // these are encoded separately
1418       }
1419     }
1420 }
1421
1422 fn encode_info_for_foreign_item<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
1423                                           rbml_w: &mut Encoder,
1424                                           nitem: &hir::ForeignItem,
1425                                           index: &mut CrateIndex<'tcx>,
1426                                           path: PathElems,
1427                                           abi: abi::Abi) {
1428     let def_id = ecx.tcx.map.local_def_id(nitem.id);
1429
1430     index.record(def_id, rbml_w);
1431     rbml_w.start_tag(tag_items_data_item);
1432     encode_def_id_and_key(ecx, rbml_w, def_id);
1433     encode_visibility(rbml_w, nitem.vis);
1434     match nitem.node {
1435       hir::ForeignItemFn(ref fndecl, _) => {
1436         encode_family(rbml_w, FN_FAMILY);
1437         encode_bounds_and_type_for_item(rbml_w, ecx, index, nitem.id);
1438         encode_name(rbml_w, nitem.name);
1439         if abi == abi::RustIntrinsic || abi == abi::PlatformIntrinsic {
1440             encode_inlined_item(ecx, rbml_w, InlinedItemRef::Foreign(nitem));
1441         }
1442         encode_attributes(rbml_w, &*nitem.attrs);
1443         let stab = stability::lookup_stability(ecx.tcx, ecx.tcx.map.local_def_id(nitem.id));
1444         let depr = stability::lookup_deprecation(ecx.tcx, ecx.tcx.map.local_def_id(nitem.id));
1445         encode_stability(rbml_w, stab);
1446         encode_deprecation(rbml_w, depr);
1447         encode_symbol(ecx, rbml_w, nitem.id);
1448         encode_method_argument_names(rbml_w, &*fndecl);
1449       }
1450       hir::ForeignItemStatic(_, mutbl) => {
1451         if mutbl {
1452             encode_family(rbml_w, 'b');
1453         } else {
1454             encode_family(rbml_w, 'c');
1455         }
1456         encode_bounds_and_type_for_item(rbml_w, ecx, index, nitem.id);
1457         encode_attributes(rbml_w, &*nitem.attrs);
1458         let stab = stability::lookup_stability(ecx.tcx, ecx.tcx.map.local_def_id(nitem.id));
1459         let depr = stability::lookup_deprecation(ecx.tcx, ecx.tcx.map.local_def_id(nitem.id));
1460         encode_stability(rbml_w, stab);
1461         encode_deprecation(rbml_w, depr);
1462         encode_symbol(ecx, rbml_w, nitem.id);
1463         encode_name(rbml_w, nitem.name);
1464       }
1465     }
1466     encode_path(rbml_w, path);
1467     rbml_w.end_tag();
1468 }
1469
1470 fn my_visit_expr(expr: &hir::Expr,
1471                  rbml_w: &mut Encoder,
1472                  ecx: &EncodeContext,
1473                  index: &mut CrateIndex) {
1474     match expr.node {
1475         hir::ExprClosure(..) => {
1476             let def_id = ecx.tcx.map.local_def_id(expr.id);
1477
1478             index.record(def_id, rbml_w);
1479
1480             rbml_w.start_tag(tag_items_data_item);
1481             encode_def_id_and_key(ecx, rbml_w, def_id);
1482
1483             rbml_w.start_tag(tag_items_closure_ty);
1484             write_closure_type(ecx, rbml_w, &ecx.tcx.tables.borrow().closure_tys[&def_id]);
1485             rbml_w.end_tag();
1486
1487             rbml_w.start_tag(tag_items_closure_kind);
1488             ecx.tcx.closure_kind(def_id).encode(rbml_w).unwrap();
1489             rbml_w.end_tag();
1490
1491             ecx.tcx.map.with_path(expr.id, |path| encode_path(rbml_w, path));
1492
1493             rbml_w.end_tag();
1494         }
1495         _ => { }
1496     }
1497 }
1498
1499 fn my_visit_item<'a, 'tcx>(i: &hir::Item,
1500                            rbml_w: &mut Encoder,
1501                            ecx: &EncodeContext<'a, 'tcx>,
1502                            index: &mut CrateIndex<'tcx>) {
1503     ecx.tcx.map.with_path(i.id, |path| {
1504         encode_info_for_item(ecx, rbml_w, i, index, path, i.vis);
1505     });
1506 }
1507
1508 fn my_visit_foreign_item<'a, 'tcx>(ni: &hir::ForeignItem,
1509                                    rbml_w: &mut Encoder,
1510                                    ecx: &EncodeContext<'a, 'tcx>,
1511                                    index: &mut CrateIndex<'tcx>) {
1512     debug!("writing foreign item {}::{}",
1513             ecx.tcx.map.path_to_string(ni.id),
1514             ni.name);
1515
1516     let abi = ecx.tcx.map.get_foreign_abi(ni.id);
1517     ecx.tcx.map.with_path(ni.id, |path| {
1518         encode_info_for_foreign_item(ecx, rbml_w,
1519                                      ni, index,
1520                                      path, abi);
1521     });
1522 }
1523
1524 struct EncodeVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
1525     rbml_w_for_visit_item: &'a mut Encoder<'b>,
1526     ecx: &'a EncodeContext<'c,'tcx>,
1527     index: &'a mut CrateIndex<'tcx>,
1528 }
1529
1530 impl<'a, 'b, 'c, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'c, 'tcx> {
1531     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1532         intravisit::walk_expr(self, ex);
1533         my_visit_expr(ex, self.rbml_w_for_visit_item, self.ecx, self.index);
1534     }
1535     fn visit_item(&mut self, i: &'tcx hir::Item) {
1536         intravisit::walk_item(self, i);
1537         my_visit_item(i, self.rbml_w_for_visit_item, self.ecx, self.index);
1538     }
1539     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1540         intravisit::walk_foreign_item(self, ni);
1541         my_visit_foreign_item(ni, self.rbml_w_for_visit_item, self.ecx, self.index);
1542     }
1543 }
1544
1545 fn encode_info_for_items<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
1546                                    rbml_w: &mut Encoder)
1547                                    -> CrateIndex<'tcx> {
1548     let krate = ecx.tcx.map.krate();
1549
1550     let mut index = CrateIndex {
1551         items: IndexData::new(ecx.tcx.map.num_local_def_ids()),
1552         xrefs: FnvHashMap()
1553     };
1554     rbml_w.start_tag(tag_items_data);
1555
1556     index.record(DefId::local(CRATE_DEF_INDEX), rbml_w);
1557     encode_info_for_mod(ecx,
1558                         rbml_w,
1559                         &krate.module,
1560                         &[],
1561                         CRATE_NODE_ID,
1562                         [].iter().cloned().chain(LinkedPath::empty()),
1563                         syntax::parse::token::intern(&ecx.link_meta.crate_name),
1564                         hir::Public);
1565
1566     krate.visit_all_items(&mut EncodeVisitor {
1567         index: &mut index,
1568         ecx: ecx,
1569         rbml_w_for_visit_item: &mut *rbml_w,
1570     });
1571
1572     rbml_w.end_tag();
1573     index
1574 }
1575
1576 fn encode_item_index(rbml_w: &mut Encoder, index: IndexData) {
1577     rbml_w.start_tag(tag_index);
1578     index.write_index(rbml_w.writer);
1579     rbml_w.end_tag();
1580 }
1581
1582 fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) {
1583     match mi.node {
1584       ast::MetaWord(ref name) => {
1585         rbml_w.start_tag(tag_meta_item_word);
1586         rbml_w.wr_tagged_str(tag_meta_item_name, name);
1587         rbml_w.end_tag();
1588       }
1589       ast::MetaNameValue(ref name, ref value) => {
1590         match value.node {
1591           ast::LitStr(ref value, _) => {
1592             rbml_w.start_tag(tag_meta_item_name_value);
1593             rbml_w.wr_tagged_str(tag_meta_item_name, name);
1594             rbml_w.wr_tagged_str(tag_meta_item_value, value);
1595             rbml_w.end_tag();
1596           }
1597           _ => {/* FIXME (#623): encode other variants */ }
1598         }
1599       }
1600       ast::MetaList(ref name, ref items) => {
1601         rbml_w.start_tag(tag_meta_item_list);
1602         rbml_w.wr_tagged_str(tag_meta_item_name, name);
1603         for inner_item in items {
1604             encode_meta_item(rbml_w, &**inner_item);
1605         }
1606         rbml_w.end_tag();
1607       }
1608     }
1609 }
1610
1611 fn encode_attributes(rbml_w: &mut Encoder, attrs: &[ast::Attribute]) {
1612     rbml_w.start_tag(tag_attributes);
1613     for attr in attrs {
1614         rbml_w.start_tag(tag_attribute);
1615         rbml_w.wr_tagged_u8(tag_attribute_is_sugared_doc, attr.node.is_sugared_doc as u8);
1616         encode_meta_item(rbml_w, &*attr.node.value);
1617         rbml_w.end_tag();
1618     }
1619     rbml_w.end_tag();
1620 }
1621
1622 fn encode_unsafety(rbml_w: &mut Encoder, unsafety: hir::Unsafety) {
1623     let byte: u8 = match unsafety {
1624         hir::Unsafety::Normal => 0,
1625         hir::Unsafety::Unsafe => 1,
1626     };
1627     rbml_w.wr_tagged_u8(tag_unsafety, byte);
1628 }
1629
1630 fn encode_paren_sugar(rbml_w: &mut Encoder, paren_sugar: bool) {
1631     let byte: u8 = if paren_sugar {1} else {0};
1632     rbml_w.wr_tagged_u8(tag_paren_sugar, byte);
1633 }
1634
1635 fn encode_defaulted(rbml_w: &mut Encoder, is_defaulted: bool) {
1636     let byte: u8 = if is_defaulted {1} else {0};
1637     rbml_w.wr_tagged_u8(tag_defaulted_trait, byte);
1638 }
1639
1640 fn encode_associated_type_names(rbml_w: &mut Encoder, names: &[Name]) {
1641     rbml_w.start_tag(tag_associated_type_names);
1642     for &name in names {
1643         rbml_w.wr_tagged_str(tag_associated_type_name, &name.as_str());
1644     }
1645     rbml_w.end_tag();
1646 }
1647
1648 fn encode_polarity(rbml_w: &mut Encoder, polarity: hir::ImplPolarity) {
1649     let byte: u8 = match polarity {
1650         hir::ImplPolarity::Positive => 0,
1651         hir::ImplPolarity::Negative => 1,
1652     };
1653     rbml_w.wr_tagged_u8(tag_polarity, byte);
1654 }
1655
1656 fn encode_crate_deps(rbml_w: &mut Encoder, cstore: &cstore::CStore) {
1657     fn get_ordered_deps(cstore: &cstore::CStore)
1658                         -> Vec<(CrateNum, Rc<cstore::crate_metadata>)> {
1659         // Pull the cnums and name,vers,hash out of cstore
1660         let mut deps = Vec::new();
1661         cstore.iter_crate_data(|cnum, val| {
1662             deps.push((cnum, val.clone()));
1663         });
1664
1665         // Sort by cnum
1666         deps.sort_by(|kv1, kv2| kv1.0.cmp(&kv2.0));
1667
1668         // Sanity-check the crate numbers
1669         let mut expected_cnum = 1;
1670         for &(n, _) in &deps {
1671             assert_eq!(n, expected_cnum);
1672             expected_cnum += 1;
1673         }
1674
1675         deps
1676     }
1677
1678     // We're just going to write a list of crate 'name-hash-version's, with
1679     // the assumption that they are numbered 1 to n.
1680     // FIXME (#2166): This is not nearly enough to support correct versioning
1681     // but is enough to get transitive crate dependencies working.
1682     rbml_w.start_tag(tag_crate_deps);
1683     for (_cnum, dep) in get_ordered_deps(cstore) {
1684         encode_crate_dep(rbml_w, &dep);
1685     }
1686     rbml_w.end_tag();
1687 }
1688
1689 fn encode_lang_items(ecx: &EncodeContext, rbml_w: &mut Encoder) {
1690     rbml_w.start_tag(tag_lang_items);
1691
1692     for (i, &opt_def_id) in ecx.tcx.lang_items.items() {
1693         if let Some(def_id) = opt_def_id {
1694             if def_id.is_local() {
1695                 rbml_w.start_tag(tag_lang_items_item);
1696                 rbml_w.wr_tagged_u32(tag_lang_items_item_id, i as u32);
1697                 rbml_w.wr_tagged_u32(tag_lang_items_item_index, def_id.index.as_u32());
1698                 rbml_w.end_tag();
1699             }
1700         }
1701     }
1702
1703     for i in &ecx.tcx.lang_items.missing {
1704         rbml_w.wr_tagged_u32(tag_lang_items_missing, *i as u32);
1705     }
1706
1707     rbml_w.end_tag();   // tag_lang_items
1708 }
1709
1710 fn encode_native_libraries(ecx: &EncodeContext, rbml_w: &mut Encoder) {
1711     rbml_w.start_tag(tag_native_libraries);
1712
1713     for &(ref lib, kind) in ecx.tcx.sess.cstore.used_libraries().iter() {
1714         match kind {
1715             cstore::NativeStatic => {} // these libraries are not propagated
1716             cstore::NativeFramework | cstore::NativeUnknown => {
1717                 rbml_w.start_tag(tag_native_libraries_lib);
1718                 rbml_w.wr_tagged_u32(tag_native_libraries_kind, kind as u32);
1719                 rbml_w.wr_tagged_str(tag_native_libraries_name, lib);
1720                 rbml_w.end_tag();
1721             }
1722         }
1723     }
1724
1725     rbml_w.end_tag();
1726 }
1727
1728 fn encode_plugin_registrar_fn(ecx: &EncodeContext, rbml_w: &mut Encoder) {
1729     match ecx.tcx.sess.plugin_registrar_fn.get() {
1730         Some(id) => {
1731             let def_id = ecx.tcx.map.local_def_id(id);
1732             rbml_w.wr_tagged_u32(tag_plugin_registrar_fn, def_id.index.as_u32());
1733         }
1734         None => {}
1735     }
1736 }
1737
1738 fn encode_codemap(ecx: &EncodeContext, rbml_w: &mut Encoder) {
1739     rbml_w.start_tag(tag_codemap);
1740     let codemap = ecx.tcx.sess.codemap();
1741
1742     for filemap in &codemap.files.borrow()[..] {
1743
1744         if filemap.lines.borrow().is_empty() || filemap.is_imported() {
1745             // No need to export empty filemaps, as they can't contain spans
1746             // that need translation.
1747             // Also no need to re-export imported filemaps, as any downstream
1748             // crate will import them from their original source.
1749             continue;
1750         }
1751
1752         rbml_w.start_tag(tag_codemap_filemap);
1753         filemap.encode(rbml_w);
1754         rbml_w.end_tag();
1755     }
1756
1757     rbml_w.end_tag();
1758 }
1759
1760 /// Serialize the text of the exported macros
1761 fn encode_macro_defs(rbml_w: &mut Encoder,
1762                      krate: &hir::Crate) {
1763     rbml_w.start_tag(tag_macro_defs);
1764     for def in &krate.exported_macros {
1765         rbml_w.start_tag(tag_macro_def);
1766
1767         encode_name(rbml_w, def.name);
1768         encode_attributes(rbml_w, &def.attrs);
1769
1770         rbml_w.wr_tagged_str(tag_macro_def_body,
1771                              &::syntax::print::pprust::tts_to_string(&def.body));
1772
1773         rbml_w.end_tag();
1774     }
1775     rbml_w.end_tag();
1776 }
1777
1778 fn encode_struct_field_attrs(ecx: &EncodeContext,
1779                              rbml_w: &mut Encoder,
1780                              krate: &hir::Crate) {
1781     struct StructFieldVisitor<'a, 'b:'a, 'c:'a, 'tcx:'b> {
1782         ecx: &'a EncodeContext<'b, 'tcx>,
1783         rbml_w: &'a mut Encoder<'c>,
1784     }
1785
1786     impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for StructFieldVisitor<'a, 'b, 'c, 'tcx> {
1787         fn visit_struct_field(&mut self, field: &hir::StructField) {
1788             self.rbml_w.start_tag(tag_struct_field);
1789             let def_id = self.ecx.tcx.map.local_def_id(field.node.id);
1790             encode_def_id(self.rbml_w, def_id);
1791             encode_attributes(self.rbml_w, &field.node.attrs);
1792             self.rbml_w.end_tag();
1793         }
1794     }
1795
1796     rbml_w.start_tag(tag_struct_fields);
1797     krate.visit_all_items(&mut StructFieldVisitor { ecx: ecx, rbml_w: rbml_w });
1798     rbml_w.end_tag();
1799 }
1800
1801
1802
1803 struct ImplVisitor<'a, 'tcx:'a> {
1804     tcx: &'a ty::ctxt<'tcx>,
1805     impls: FnvHashMap<DefId, Vec<DefId>>
1806 }
1807
1808 impl<'a, 'tcx, 'v> Visitor<'v> for ImplVisitor<'a, 'tcx> {
1809     fn visit_item(&mut self, item: &hir::Item) {
1810         if let hir::ItemImpl(..) = item.node {
1811             let impl_id = self.tcx.map.local_def_id(item.id);
1812             if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1813                 self.impls.entry(trait_ref.def_id)
1814                     .or_insert(vec![])
1815                     .push(impl_id);
1816             }
1817         }
1818     }
1819 }
1820
1821 /// Encodes an index, mapping each trait to its (local) implementations.
1822 fn encode_impls<'a>(ecx: &'a EncodeContext,
1823                     krate: &hir::Crate,
1824                     rbml_w: &'a mut Encoder) {
1825     let mut visitor = ImplVisitor {
1826         tcx: ecx.tcx,
1827         impls: FnvHashMap()
1828     };
1829     krate.visit_all_items(&mut visitor);
1830
1831     rbml_w.start_tag(tag_impls);
1832     for (trait_, trait_impls) in visitor.impls {
1833         rbml_w.start_tag(tag_impls_trait);
1834         encode_def_id(rbml_w, trait_);
1835         for impl_ in trait_impls {
1836             rbml_w.wr_tagged_u64(tag_impls_trait_impl, def_to_u64(impl_));
1837         }
1838         rbml_w.end_tag();
1839     }
1840     rbml_w.end_tag();
1841 }
1842
1843 fn encode_misc_info(ecx: &EncodeContext,
1844                     krate: &hir::Crate,
1845                     rbml_w: &mut Encoder) {
1846     rbml_w.start_tag(tag_misc_info);
1847     rbml_w.start_tag(tag_misc_info_crate_items);
1848     for item_id in &krate.module.item_ids {
1849         rbml_w.wr_tagged_u64(tag_mod_child,
1850                              def_to_u64(ecx.tcx.map.local_def_id(item_id.id)));
1851
1852         let item = ecx.tcx.map.expect_item(item_id.id);
1853         each_auxiliary_node_id(item, |auxiliary_node_id| {
1854             rbml_w.wr_tagged_u64(tag_mod_child,
1855                                  def_to_u64(ecx.tcx.map.local_def_id(auxiliary_node_id)));
1856             true
1857         });
1858     }
1859
1860     // Encode reexports for the root module.
1861     encode_reexports(ecx, rbml_w, 0);
1862
1863     rbml_w.end_tag();
1864     rbml_w.end_tag();
1865 }
1866
1867 // Encodes all reachable symbols in this crate into the metadata.
1868 //
1869 // This pass is seeded off the reachability list calculated in the
1870 // middle::reachable module but filters out items that either don't have a
1871 // symbol associated with them (they weren't translated) or if they're an FFI
1872 // definition (as that's not defined in this crate).
1873 fn encode_reachable(ecx: &EncodeContext, rbml_w: &mut Encoder) {
1874     rbml_w.start_tag(tag_reachable_ids);
1875     for &id in ecx.reachable {
1876         let def_id = ecx.tcx.map.local_def_id(id);
1877         rbml_w.wr_tagged_u32(tag_reachable_id, def_id.index.as_u32());
1878     }
1879     rbml_w.end_tag();
1880 }
1881
1882 fn encode_crate_dep(rbml_w: &mut Encoder,
1883                     dep: &cstore::crate_metadata) {
1884     rbml_w.start_tag(tag_crate_dep);
1885     rbml_w.wr_tagged_str(tag_crate_dep_crate_name, &dep.name());
1886     let hash = decoder::get_crate_hash(dep.data());
1887     rbml_w.wr_tagged_str(tag_crate_dep_hash, hash.as_str());
1888     rbml_w.wr_tagged_u8(tag_crate_dep_explicitly_linked,
1889                         dep.explicitly_linked.get() as u8);
1890     rbml_w.end_tag();
1891 }
1892
1893 fn encode_hash(rbml_w: &mut Encoder, hash: &Svh) {
1894     rbml_w.wr_tagged_str(tag_crate_hash, hash.as_str());
1895 }
1896
1897 fn encode_rustc_version(rbml_w: &mut Encoder) {
1898     rbml_w.wr_tagged_str(tag_rustc_version, &rustc_version());
1899 }
1900
1901 fn encode_crate_name(rbml_w: &mut Encoder, crate_name: &str) {
1902     rbml_w.wr_tagged_str(tag_crate_crate_name, crate_name);
1903 }
1904
1905 fn encode_crate_triple(rbml_w: &mut Encoder, triple: &str) {
1906     rbml_w.wr_tagged_str(tag_crate_triple, triple);
1907 }
1908
1909 fn encode_dylib_dependency_formats(rbml_w: &mut Encoder, ecx: &EncodeContext) {
1910     let tag = tag_dylib_dependency_formats;
1911     match ecx.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1912         Some(arr) => {
1913             let s = arr.iter().enumerate().filter_map(|(i, slot)| {
1914                 let kind = match *slot {
1915                     Linkage::NotLinked |
1916                     Linkage::IncludedFromDylib => return None,
1917                     Linkage::Dynamic => "d",
1918                     Linkage::Static => "s",
1919                 };
1920                 Some(format!("{}:{}", i + 1, kind))
1921             }).collect::<Vec<String>>();
1922             rbml_w.wr_tagged_str(tag, &s.join(","));
1923         }
1924         None => {
1925             rbml_w.wr_tagged_str(tag, "");
1926         }
1927     }
1928 }
1929
1930 // NB: Increment this as you change the metadata encoding version.
1931 #[allow(non_upper_case_globals)]
1932 pub const metadata_encoding_version : &'static [u8] = &[b'r', b'u', b's', b't', 0, 0, 0, 2 ];
1933
1934 pub fn encode_metadata(parms: EncodeParams, krate: &hir::Crate) -> Vec<u8> {
1935     let EncodeParams {
1936         item_symbols,
1937         diag,
1938         tcx,
1939         reexports,
1940         cstore,
1941         encode_inlined_item,
1942         link_meta,
1943         reachable,
1944         mir_map,
1945         ..
1946     } = parms;
1947     let ecx = EncodeContext {
1948         diag: diag,
1949         tcx: tcx,
1950         reexports: reexports,
1951         item_symbols: item_symbols,
1952         link_meta: link_meta,
1953         cstore: cstore,
1954         encode_inlined_item: RefCell::new(encode_inlined_item),
1955         type_abbrevs: RefCell::new(FnvHashMap()),
1956         reachable: reachable,
1957         mir_map: mir_map,
1958     };
1959
1960     let mut wr = Cursor::new(Vec::new());
1961
1962     {
1963         let mut rbml_w = Encoder::new(&mut wr);
1964         tls::enter_encoding_context(&ecx, &mut rbml_w, |_, rbml_w| {
1965             encode_metadata_inner(rbml_w, &ecx, krate)
1966         });
1967     }
1968
1969     // RBML compacts the encoded bytes whenever appropriate,
1970     // so there are some garbages left after the end of the data.
1971     let metalen = wr.seek(SeekFrom::Current(0)).unwrap() as usize;
1972     let mut v = wr.into_inner();
1973     v.truncate(metalen);
1974     assert_eq!(v.len(), metalen);
1975
1976     // And here we run into yet another obscure archive bug: in which metadata
1977     // loaded from archives may have trailing garbage bytes. Awhile back one of
1978     // our tests was failing sporadically on the OSX 64-bit builders (both nopt
1979     // and opt) by having rbml generate an out-of-bounds panic when looking at
1980     // metadata.
1981     //
1982     // Upon investigation it turned out that the metadata file inside of an rlib
1983     // (and ar archive) was being corrupted. Some compilations would generate a
1984     // metadata file which would end in a few extra bytes, while other
1985     // compilations would not have these extra bytes appended to the end. These
1986     // extra bytes were interpreted by rbml as an extra tag, so they ended up
1987     // being interpreted causing the out-of-bounds.
1988     //
1989     // The root cause of why these extra bytes were appearing was never
1990     // discovered, and in the meantime the solution we're employing is to insert
1991     // the length of the metadata to the start of the metadata. Later on this
1992     // will allow us to slice the metadata to the precise length that we just
1993     // generated regardless of trailing bytes that end up in it.
1994     let len = v.len() as u32;
1995     v.insert(0, (len >>  0) as u8);
1996     v.insert(0, (len >>  8) as u8);
1997     v.insert(0, (len >> 16) as u8);
1998     v.insert(0, (len >> 24) as u8);
1999     return v;
2000 }
2001
2002 fn encode_metadata_inner(rbml_w: &mut Encoder,
2003                          ecx: &EncodeContext,
2004                          krate: &hir::Crate) {
2005     struct Stats {
2006         attr_bytes: u64,
2007         dep_bytes: u64,
2008         lang_item_bytes: u64,
2009         native_lib_bytes: u64,
2010         plugin_registrar_fn_bytes: u64,
2011         codemap_bytes: u64,
2012         macro_defs_bytes: u64,
2013         impl_bytes: u64,
2014         misc_bytes: u64,
2015         item_bytes: u64,
2016         index_bytes: u64,
2017         xref_bytes: u64,
2018         zero_bytes: u64,
2019         total_bytes: u64,
2020     }
2021     let mut stats = Stats {
2022         attr_bytes: 0,
2023         dep_bytes: 0,
2024         lang_item_bytes: 0,
2025         native_lib_bytes: 0,
2026         plugin_registrar_fn_bytes: 0,
2027         codemap_bytes: 0,
2028         macro_defs_bytes: 0,
2029         impl_bytes: 0,
2030         misc_bytes: 0,
2031         item_bytes: 0,
2032         index_bytes: 0,
2033         xref_bytes: 0,
2034         zero_bytes: 0,
2035         total_bytes: 0,
2036     };
2037
2038     encode_rustc_version(rbml_w);
2039     encode_crate_name(rbml_w, &ecx.link_meta.crate_name);
2040     encode_crate_triple(rbml_w, &ecx.tcx.sess.opts.target_triple);
2041     encode_hash(rbml_w, &ecx.link_meta.crate_hash);
2042     encode_dylib_dependency_formats(rbml_w, &ecx);
2043
2044     let mut i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2045     encode_attributes(rbml_w, &krate.attrs);
2046     stats.attr_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2047
2048     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2049     encode_crate_deps(rbml_w, ecx.cstore);
2050     stats.dep_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2051
2052     // Encode the language items.
2053     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2054     encode_lang_items(&ecx, rbml_w);
2055     stats.lang_item_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2056
2057     // Encode the native libraries used
2058     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2059     encode_native_libraries(&ecx, rbml_w);
2060     stats.native_lib_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2061
2062     // Encode the plugin registrar function
2063     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2064     encode_plugin_registrar_fn(&ecx, rbml_w);
2065     stats.plugin_registrar_fn_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2066
2067     // Encode codemap
2068     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2069     encode_codemap(&ecx, rbml_w);
2070     stats.codemap_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2071
2072     // Encode macro definitions
2073     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2074     encode_macro_defs(rbml_w, krate);
2075     stats.macro_defs_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2076
2077     // Encode the def IDs of impls, for coherence checking.
2078     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2079     encode_impls(&ecx, krate, rbml_w);
2080     stats.impl_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2081
2082     // Encode miscellaneous info.
2083     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2084     encode_misc_info(&ecx, krate, rbml_w);
2085     encode_reachable(&ecx, rbml_w);
2086     stats.misc_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2087
2088     // Encode and index the items.
2089     rbml_w.start_tag(tag_items);
2090     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2091     let index = encode_info_for_items(&ecx, rbml_w);
2092     stats.item_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2093     rbml_w.end_tag();
2094
2095     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2096     encode_item_index(rbml_w, index.items);
2097     stats.index_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2098
2099     i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2100     encode_xrefs(&ecx, rbml_w, index.xrefs);
2101     stats.xref_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
2102
2103     encode_struct_field_attrs(&ecx, rbml_w, krate);
2104
2105     stats.total_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
2106
2107     if ecx.tcx.sess.meta_stats() {
2108         for e in rbml_w.writer.get_ref() {
2109             if *e == 0 {
2110                 stats.zero_bytes += 1;
2111             }
2112         }
2113
2114         println!("metadata stats:");
2115         println!("       attribute bytes: {}", stats.attr_bytes);
2116         println!("             dep bytes: {}", stats.dep_bytes);
2117         println!("       lang item bytes: {}", stats.lang_item_bytes);
2118         println!("          native bytes: {}", stats.native_lib_bytes);
2119         println!("plugin registrar bytes: {}", stats.plugin_registrar_fn_bytes);
2120         println!("         codemap bytes: {}", stats.codemap_bytes);
2121         println!("       macro def bytes: {}", stats.macro_defs_bytes);
2122         println!("            impl bytes: {}", stats.impl_bytes);
2123         println!("            misc bytes: {}", stats.misc_bytes);
2124         println!("            item bytes: {}", stats.item_bytes);
2125         println!("           index bytes: {}", stats.index_bytes);
2126         println!("            xref bytes: {}", stats.xref_bytes);
2127         println!("            zero bytes: {}", stats.zero_bytes);
2128         println!("           total bytes: {}", stats.total_bytes);
2129     }
2130 }
2131
2132 // Get the encoded string for a type
2133 pub fn encoded_ty<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> Vec<u8> {
2134     let mut wr = Cursor::new(Vec::new());
2135     tyencode::enc_ty(&mut Encoder::new(&mut wr), &tyencode::ctxt {
2136         diag: tcx.sess.diagnostic(),
2137         ds: def_to_string,
2138         tcx: tcx,
2139         abbrevs: &RefCell::new(FnvHashMap())
2140     }, t);
2141     wr.into_inner()
2142 }