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