]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/astencode.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / librustc / middle / astencode.rs
1 // Copyright 2012-2014 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 #![allow(non_camel_case_types)]
12 // FIXME: remove this after snapshot, and Results are handled
13 #![allow(unused_must_use)]
14
15 use metadata::common as c;
16 use metadata::cstore as cstore;
17 use session::Session;
18 use metadata::decoder;
19 use middle::def;
20 use metadata::encoder as e;
21 use middle::region;
22 use metadata::tydecode;
23 use metadata::tydecode::{DefIdSource, NominalType, TypeWithId, TypeParameter};
24 use metadata::tydecode::{RegionParameter, ClosureSource};
25 use metadata::tyencode;
26 use middle::check_const::ConstQualif;
27 use middle::mem_categorization::Typer;
28 use middle::subst;
29 use middle::subst::VecPerParamSpace;
30 use middle::ty::{self, Ty, MethodCall, MethodCallee, MethodOrigin};
31 use util::ppaux::ty_to_string;
32
33 use syntax::{ast, ast_map, ast_util, codemap, fold};
34 use syntax::ast_util::PostExpansionMethod;
35 use syntax::codemap::Span;
36 use syntax::fold::Folder;
37 use syntax::parse::token;
38 use syntax::ptr::P;
39 use syntax;
40
41 use std::old_io::Seek;
42 use std::num::FromPrimitive;
43 use std::rc::Rc;
44
45 use rbml::io::SeekableMemWriter;
46 use rbml::{reader, writer};
47 use rbml;
48 use serialize;
49 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
50 use serialize::{EncoderHelpers};
51
52 #[cfg(test)] use syntax::parse;
53 #[cfg(test)] use syntax::print::pprust;
54
55 struct DecodeContext<'a, 'b, 'tcx: 'a> {
56     tcx: &'a ty::ctxt<'tcx>,
57     cdata: &'b cstore::crate_metadata,
58     from_id_range: ast_util::IdRange,
59     to_id_range: ast_util::IdRange
60 }
61
62 trait tr {
63     fn tr(&self, dcx: &DecodeContext) -> Self;
64 }
65
66 trait tr_intern {
67     fn tr_intern(&self, dcx: &DecodeContext) -> ast::DefId;
68 }
69
70 pub type Encoder<'a> = writer::Encoder<'a, SeekableMemWriter>;
71
72 // ______________________________________________________________________
73 // Top-level methods.
74
75 pub fn encode_inlined_item(ecx: &e::EncodeContext,
76                            rbml_w: &mut Encoder,
77                            ii: e::InlinedItemRef) {
78     let id = match ii {
79         e::IIItemRef(i) => i.id,
80         e::IIForeignRef(i) => i.id,
81         e::IITraitItemRef(_, &ast::ProvidedMethod(ref m)) => m.id,
82         e::IITraitItemRef(_, &ast::RequiredMethod(ref m)) => m.id,
83         e::IITraitItemRef(_, &ast::TypeTraitItem(ref ti)) => ti.ty_param.id,
84         e::IIImplItemRef(_, &ast::MethodImplItem(ref m)) => m.id,
85         e::IIImplItemRef(_, &ast::TypeImplItem(ref ti)) => ti.id,
86     };
87     debug!("> Encoding inlined item: {} ({:?})",
88            ecx.tcx.map.path_to_string(id),
89            rbml_w.writer.tell());
90
91     // Folding could be avoided with a smarter encoder.
92     let ii = simplify_ast(ii);
93     let id_range = ast_util::compute_id_range_for_inlined_item(&ii);
94
95     rbml_w.start_tag(c::tag_ast as uint);
96     id_range.encode(rbml_w);
97     encode_ast(rbml_w, &ii);
98     encode_side_tables_for_ii(ecx, rbml_w, &ii);
99     rbml_w.end_tag();
100
101     debug!("< Encoded inlined fn: {} ({:?})",
102            ecx.tcx.map.path_to_string(id),
103            rbml_w.writer.tell());
104 }
105
106 impl<'a, 'b, 'c, 'tcx> ast_map::FoldOps for &'a DecodeContext<'b, 'c, 'tcx> {
107     fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
108         if id == ast::DUMMY_NODE_ID {
109             // Used by ast_map to map the NodeInlinedParent.
110             self.tcx.sess.next_node_id()
111         } else {
112             self.tr_id(id)
113         }
114     }
115     fn new_def_id(&self, def_id: ast::DefId) -> ast::DefId {
116         self.tr_def_id(def_id)
117     }
118     fn new_span(&self, span: Span) -> Span {
119         self.tr_span(span)
120     }
121 }
122
123 pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
124                                  tcx: &ty::ctxt<'tcx>,
125                                  path: Vec<ast_map::PathElem>,
126                                  par_doc: rbml::Doc)
127                                  -> Result<&'tcx ast::InlinedItem, Vec<ast_map::PathElem>> {
128     match par_doc.opt_child(c::tag_ast) {
129       None => Err(path),
130       Some(ast_doc) => {
131         let mut path_as_str = None;
132         debug!("> Decoding inlined fn: {:?}::?",
133         {
134             // Do an Option dance to use the path after it is moved below.
135             let s = ast_map::path_to_string(path.iter().cloned());
136             path_as_str = Some(s);
137             path_as_str.as_ref().map(|x| &x[..])
138         });
139         let mut ast_dsr = reader::Decoder::new(ast_doc);
140         let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
141         let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
142         let dcx = &DecodeContext {
143             cdata: cdata,
144             tcx: tcx,
145             from_id_range: from_id_range,
146             to_id_range: to_id_range
147         };
148         let raw_ii = decode_ast(ast_doc);
149         let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, raw_ii, dcx);
150
151         let ident = match *ii {
152             ast::IIItem(ref i) => i.ident,
153             ast::IIForeign(ref i) => i.ident,
154             ast::IITraitItem(_, ref ti) => {
155                 match *ti {
156                     ast::ProvidedMethod(ref m) => m.pe_ident(),
157                     ast::RequiredMethod(ref ty_m) => ty_m.ident,
158                     ast::TypeTraitItem(ref ti) => ti.ty_param.ident,
159                 }
160             },
161             ast::IIImplItem(_, ref m) => {
162                 match *m {
163                     ast::MethodImplItem(ref m) => m.pe_ident(),
164                     ast::TypeImplItem(ref ti) => ti.ident,
165                 }
166             }
167         };
168         debug!("Fn named: {}", token::get_ident(ident));
169         debug!("< Decoded inlined fn: {}::{}",
170                path_as_str.unwrap(),
171                token::get_ident(ident));
172         region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
173         decode_side_tables(dcx, ast_doc);
174         match *ii {
175           ast::IIItem(ref i) => {
176             debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
177                    syntax::print::pprust::item_to_string(&**i));
178           }
179           _ => { }
180         }
181         Ok(ii)
182       }
183     }
184 }
185
186 // ______________________________________________________________________
187 // Enumerating the IDs which appear in an AST
188
189 fn reserve_id_range(sess: &Session,
190                     from_id_range: ast_util::IdRange) -> ast_util::IdRange {
191     // Handle the case of an empty range:
192     if from_id_range.empty() { return from_id_range; }
193     let cnt = from_id_range.max - from_id_range.min;
194     let to_id_min = sess.reserve_node_ids(cnt);
195     let to_id_max = to_id_min + cnt;
196     ast_util::IdRange { min: to_id_min, max: to_id_max }
197 }
198
199 impl<'a, 'b, 'tcx> DecodeContext<'a, 'b, 'tcx> {
200     /// Translates an internal id, meaning a node id that is known to refer to some part of the
201     /// item currently being inlined, such as a local variable or argument.  All naked node-ids
202     /// that appear in types have this property, since if something might refer to an external item
203     /// we would use a def-id to allow for the possibility that the item resides in another crate.
204     pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
205         // from_id_range should be non-empty
206         assert!(!self.from_id_range.empty());
207         (id - self.from_id_range.min + self.to_id_range.min)
208     }
209
210     /// Translates an EXTERNAL def-id, converting the crate number from the one used in the encoded
211     /// data to the current crate numbers..  By external, I mean that it be translated to a
212     /// reference to the item in its original crate, as opposed to being translated to a reference
213     /// to the inlined version of the item.  This is typically, but not always, what you want,
214     /// because most def-ids refer to external things like types or other fns that may or may not
215     /// be inlined.  Note that even when the inlined function is referencing itself recursively, we
216     /// would want `tr_def_id` for that reference--- conceptually the function calls the original,
217     /// non-inlined version, and trans deals with linking that recursive call to the inlined copy.
218     ///
219     /// However, there are a *few* cases where def-ids are used but we know that the thing being
220     /// referenced is in fact *internal* to the item being inlined.  In those cases, you should use
221     /// `tr_intern_def_id()` below.
222     pub fn tr_def_id(&self, did: ast::DefId) -> ast::DefId {
223
224         decoder::translate_def_id(self.cdata, did)
225     }
226
227     /// Translates an INTERNAL def-id, meaning a def-id that is
228     /// known to refer to some part of the item currently being
229     /// inlined.  In that case, we want to convert the def-id to
230     /// refer to the current crate and to the new, inlined node-id.
231     pub fn tr_intern_def_id(&self, did: ast::DefId) -> ast::DefId {
232         assert_eq!(did.krate, ast::LOCAL_CRATE);
233         ast::DefId { krate: ast::LOCAL_CRATE, node: self.tr_id(did.node) }
234     }
235     pub fn tr_span(&self, _span: Span) -> Span {
236         codemap::DUMMY_SP // FIXME (#1972): handle span properly
237     }
238 }
239
240 impl tr_intern for ast::DefId {
241     fn tr_intern(&self, dcx: &DecodeContext) -> ast::DefId {
242         dcx.tr_intern_def_id(*self)
243     }
244 }
245
246 impl tr for ast::DefId {
247     fn tr(&self, dcx: &DecodeContext) -> ast::DefId {
248         dcx.tr_def_id(*self)
249     }
250 }
251
252 impl tr for Option<ast::DefId> {
253     fn tr(&self, dcx: &DecodeContext) -> Option<ast::DefId> {
254         self.map(|d| dcx.tr_def_id(d))
255     }
256 }
257
258 impl tr for Span {
259     fn tr(&self, dcx: &DecodeContext) -> Span {
260         dcx.tr_span(*self)
261     }
262 }
263
264 trait def_id_encoder_helpers {
265     fn emit_def_id(&mut self, did: ast::DefId);
266 }
267
268 impl<S:serialize::Encoder> def_id_encoder_helpers for S {
269     fn emit_def_id(&mut self, did: ast::DefId) {
270         did.encode(self).ok().unwrap()
271     }
272 }
273
274 trait def_id_decoder_helpers {
275     fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId;
276     fn read_def_id_nodcx(&mut self,
277                          cdata: &cstore::crate_metadata) -> ast::DefId;
278 }
279
280 impl<D:serialize::Decoder> def_id_decoder_helpers for D {
281     fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId {
282         let did: ast::DefId = Decodable::decode(self).ok().unwrap();
283         did.tr(dcx)
284     }
285
286     fn read_def_id_nodcx(&mut self,
287                          cdata: &cstore::crate_metadata) -> ast::DefId {
288         let did: ast::DefId = Decodable::decode(self).ok().unwrap();
289         decoder::translate_def_id(cdata, did)
290     }
291 }
292
293 // ______________________________________________________________________
294 // Encoding and decoding the AST itself
295 //
296 // The hard work is done by an autogenerated module astencode_gen.  To
297 // regenerate astencode_gen, run src/etc/gen-astencode.  It will
298 // replace astencode_gen with a dummy file and regenerate its
299 // contents.  If you get compile errors, the dummy file
300 // remains---resolve the errors and then rerun astencode_gen.
301 // Annoying, I know, but hopefully only temporary.
302 //
303 // When decoding, we have to renumber the AST so that the node ids that
304 // appear within are disjoint from the node ids in our existing ASTs.
305 // We also have to adjust the spans: for now we just insert a dummy span,
306 // but eventually we should add entries to the local codemap as required.
307
308 fn encode_ast(rbml_w: &mut Encoder, item: &ast::InlinedItem) {
309     rbml_w.start_tag(c::tag_tree as uint);
310     item.encode(rbml_w);
311     rbml_w.end_tag();
312 }
313
314 struct NestedItemsDropper;
315
316 impl Folder for NestedItemsDropper {
317     fn fold_block(&mut self, blk: P<ast::Block>) -> P<ast::Block> {
318         blk.and_then(|ast::Block {id, stmts, expr, rules, span, ..}| {
319             let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
320                 let use_stmt = match stmt.node {
321                     ast::StmtExpr(_, _) | ast::StmtSemi(_, _) => true,
322                     ast::StmtDecl(ref decl, _) => {
323                         match decl.node {
324                             ast::DeclLocal(_) => true,
325                             ast::DeclItem(_) => false,
326                         }
327                     }
328                     ast::StmtMac(..) => panic!("unexpanded macro in astencode")
329                 };
330                 if use_stmt {
331                     Some(stmt)
332                 } else {
333                     None
334                 }
335             }).collect();
336             let blk_sans_items = P(ast::Block {
337                 stmts: stmts_sans_items,
338                 expr: expr,
339                 id: id,
340                 rules: rules,
341                 span: span,
342             });
343             fold::noop_fold_block(blk_sans_items, self)
344         })
345     }
346 }
347
348 // Produces a simplified copy of the AST which does not include things
349 // that we do not need to or do not want to export.  For example, we
350 // do not include any nested items: if these nested items are to be
351 // inlined, their AST will be exported separately (this only makes
352 // sense because, in Rust, nested items are independent except for
353 // their visibility).
354 //
355 // As it happens, trans relies on the fact that we do not export
356 // nested items, as otherwise it would get confused when translating
357 // inlined items.
358 fn simplify_ast(ii: e::InlinedItemRef) -> ast::InlinedItem {
359     let mut fld = NestedItemsDropper;
360
361     match ii {
362         // HACK we're not dropping items.
363         e::IIItemRef(i) => {
364             ast::IIItem(fold::noop_fold_item(P(i.clone()), &mut fld)
365                             .expect_one("expected one item"))
366         }
367         e::IITraitItemRef(d, ti) => {
368             ast::IITraitItem(d, match *ti {
369                 ast::ProvidedMethod(ref m) => {
370                     ast::ProvidedMethod(
371                         fold::noop_fold_method(m.clone(), &mut fld)
372                             .expect_one("noop_fold_method must produce \
373                                          exactly one method"))
374                 }
375                 ast::RequiredMethod(ref ty_m) => {
376                     ast::RequiredMethod(
377                         fold::noop_fold_type_method(ty_m.clone(), &mut fld))
378                 }
379                 ast::TypeTraitItem(ref associated_type) => {
380                     ast::TypeTraitItem(
381                         P(fold::noop_fold_associated_type(
382                             (**associated_type).clone(),
383                             &mut fld)))
384                 }
385             })
386         }
387         e::IIImplItemRef(d, m) => {
388             ast::IIImplItem(d, match *m {
389                 ast::MethodImplItem(ref m) => {
390                     ast::MethodImplItem(
391                         fold::noop_fold_method(m.clone(), &mut fld)
392                             .expect_one("noop_fold_method must produce \
393                                          exactly one method"))
394                 }
395                 ast::TypeImplItem(ref td) => {
396                     ast::TypeImplItem(
397                         P(fold::noop_fold_typedef((**td).clone(), &mut fld)))
398                 }
399             })
400         }
401         e::IIForeignRef(i) => {
402             ast::IIForeign(fold::noop_fold_foreign_item(P(i.clone()), &mut fld))
403         }
404     }
405 }
406
407 fn decode_ast(par_doc: rbml::Doc) -> ast::InlinedItem {
408     let chi_doc = par_doc.get(c::tag_tree as uint);
409     let mut d = reader::Decoder::new(chi_doc);
410     Decodable::decode(&mut d).unwrap()
411 }
412
413 // ______________________________________________________________________
414 // Encoding and decoding of ast::def
415
416 fn decode_def(dcx: &DecodeContext, doc: rbml::Doc) -> def::Def {
417     let mut dsr = reader::Decoder::new(doc);
418     let def: def::Def = Decodable::decode(&mut dsr).unwrap();
419     def.tr(dcx)
420 }
421
422 impl tr for def::Def {
423     fn tr(&self, dcx: &DecodeContext) -> def::Def {
424         match *self {
425           def::DefFn(did, is_ctor) => def::DefFn(did.tr(dcx), is_ctor),
426           def::DefStaticMethod(did, p) => {
427             def::DefStaticMethod(did.tr(dcx), p.map(|did2| did2.tr(dcx)))
428           }
429           def::DefMethod(did0, did1, p) => {
430             def::DefMethod(did0.tr(dcx),
431                            did1.map(|did1| did1.tr(dcx)),
432                            p.map(|did2| did2.tr(dcx)))
433           }
434           def::DefSelfTy(nid) => { def::DefSelfTy(dcx.tr_id(nid)) }
435           def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
436           def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
437           def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
438           def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
439           def::DefLocal(nid) => { def::DefLocal(dcx.tr_id(nid)) }
440           def::DefVariant(e_did, v_did, is_s) => {
441             def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
442           },
443           def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
444           def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
445           def::DefAssociatedTy(did) => def::DefAssociatedTy(did.tr(dcx)),
446           def::DefAssociatedPath(def::TyParamProvenance::FromSelf(did), ident) =>
447               def::DefAssociatedPath(def::TyParamProvenance::FromSelf(did.tr(dcx)), ident),
448           def::DefAssociatedPath(def::TyParamProvenance::FromParam(did), ident) =>
449               def::DefAssociatedPath(def::TyParamProvenance::FromParam(did.tr(dcx)), ident),
450           def::DefPrimTy(p) => def::DefPrimTy(p),
451           def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
452           def::DefUse(did) => def::DefUse(did.tr(dcx)),
453           def::DefUpvar(nid1, nid2) => {
454             def::DefUpvar(dcx.tr_id(nid1), dcx.tr_id(nid2))
455           }
456           def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
457           def::DefRegion(nid) => def::DefRegion(dcx.tr_id(nid)),
458           def::DefTyParamBinder(nid) => {
459             def::DefTyParamBinder(dcx.tr_id(nid))
460           }
461           def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
462         }
463     }
464 }
465
466 // ______________________________________________________________________
467 // Encoding and decoding of ancillary information
468
469 impl tr for ty::Region {
470     fn tr(&self, dcx: &DecodeContext) -> ty::Region {
471         match *self {
472             ty::ReLateBound(debruijn, br) => {
473                 ty::ReLateBound(debruijn, br.tr(dcx))
474             }
475             ty::ReEarlyBound(id, space, index, ident) => {
476                 ty::ReEarlyBound(dcx.tr_id(id), space, index, ident)
477             }
478             ty::ReScope(scope) => {
479                 ty::ReScope(scope.tr(dcx))
480             }
481             ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => {
482                 *self
483             }
484             ty::ReFree(ref fr) => {
485                 ty::ReFree(fr.tr(dcx))
486             }
487         }
488     }
489 }
490
491 impl tr for ty::FreeRegion {
492     fn tr(&self, dcx: &DecodeContext) -> ty::FreeRegion {
493         ty::FreeRegion { scope: self.scope.tr(dcx),
494                          bound_region: self.bound_region.tr(dcx) }
495     }
496 }
497
498 impl tr for region::CodeExtent {
499     fn tr(&self, dcx: &DecodeContext) -> region::CodeExtent {
500         self.map_id(|id| dcx.tr_id(id))
501     }
502 }
503
504 impl tr for region::DestructionScopeData {
505     fn tr(&self, dcx: &DecodeContext) -> region::DestructionScopeData {
506         region::DestructionScopeData { node_id: dcx.tr_id(self.node_id) }
507     }
508 }
509
510 impl tr for ty::BoundRegion {
511     fn tr(&self, dcx: &DecodeContext) -> ty::BoundRegion {
512         match *self {
513             ty::BrAnon(_) |
514             ty::BrFresh(_) |
515             ty::BrEnv => *self,
516             ty::BrNamed(id, ident) => ty::BrNamed(dcx.tr_def_id(id),
517                                                     ident),
518         }
519     }
520 }
521
522 // ______________________________________________________________________
523 // Encoding and decoding of freevar information
524
525 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
526     (*fv).encode(rbml_w).unwrap();
527 }
528
529 trait rbml_decoder_helper {
530     fn read_freevar_entry(&mut self, dcx: &DecodeContext)
531                           -> ty::Freevar;
532     fn read_capture_mode(&mut self) -> ast::CaptureClause;
533 }
534
535 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
536     fn read_freevar_entry(&mut self, dcx: &DecodeContext)
537                           -> ty::Freevar {
538         let fv: ty::Freevar = Decodable::decode(self).unwrap();
539         fv.tr(dcx)
540     }
541
542     fn read_capture_mode(&mut self) -> ast::CaptureClause {
543         let cm: ast::CaptureClause = Decodable::decode(self).unwrap();
544         cm
545     }
546 }
547
548 impl tr for ty::Freevar {
549     fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
550         ty::Freevar {
551             def: self.def.tr(dcx),
552             span: self.span.tr(dcx),
553         }
554     }
555 }
556
557 impl tr for ty::UpvarBorrow {
558     fn tr(&self, dcx: &DecodeContext) -> ty::UpvarBorrow {
559         ty::UpvarBorrow {
560             kind: self.kind,
561             region: self.region.tr(dcx)
562         }
563     }
564 }
565
566 impl tr for ty::UpvarCapture {
567     fn tr(&self, dcx: &DecodeContext) -> ty::UpvarCapture {
568         match *self {
569             ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
570             ty::UpvarCapture::ByRef(ref data) => ty::UpvarCapture::ByRef(data.tr(dcx)),
571         }
572     }
573 }
574
575 // ______________________________________________________________________
576 // Encoding and decoding of MethodCallee
577
578 trait read_method_callee_helper<'tcx> {
579     fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
580         -> (ty::ExprAdjustment, MethodCallee<'tcx>);
581 }
582
583 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
584                                   rbml_w: &mut Encoder,
585                                   adjustment: ty::ExprAdjustment,
586                                   method: &MethodCallee<'tcx>) {
587     use serialize::Encoder;
588
589     rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
590         rbml_w.emit_struct_field("adjustment", 0, |rbml_w| {
591             adjustment.encode(rbml_w)
592         });
593         rbml_w.emit_struct_field("origin", 1, |rbml_w| {
594             Ok(rbml_w.emit_method_origin(ecx, &method.origin))
595         });
596         rbml_w.emit_struct_field("ty", 2, |rbml_w| {
597             Ok(rbml_w.emit_ty(ecx, method.ty))
598         });
599         rbml_w.emit_struct_field("substs", 3, |rbml_w| {
600             Ok(rbml_w.emit_substs(ecx, &method.substs))
601         })
602     }).unwrap();
603 }
604
605 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
606     fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
607         -> (ty::ExprAdjustment, MethodCallee<'tcx>) {
608
609         self.read_struct("MethodCallee", 4, |this| {
610             let adjustment = this.read_struct_field("adjustment", 0, |this| {
611                 Decodable::decode(this)
612             }).unwrap();
613             Ok((adjustment, MethodCallee {
614                 origin: this.read_struct_field("origin", 1, |this| {
615                     Ok(this.read_method_origin(dcx))
616                 }).unwrap(),
617                 ty: this.read_struct_field("ty", 2, |this| {
618                     Ok(this.read_ty(dcx))
619                 }).unwrap(),
620                 substs: this.read_struct_field("substs", 3, |this| {
621                     Ok(this.read_substs(dcx))
622                 }).unwrap()
623             }))
624         }).unwrap()
625     }
626 }
627
628 impl<'tcx> tr for MethodOrigin<'tcx> {
629     fn tr(&self, dcx: &DecodeContext) -> MethodOrigin<'tcx> {
630         match *self {
631             ty::MethodStatic(did) => ty::MethodStatic(did.tr(dcx)),
632             ty::MethodStaticClosure(did) => {
633                 ty::MethodStaticClosure(did.tr(dcx))
634             }
635             ty::MethodTypeParam(ref mp) => {
636                 ty::MethodTypeParam(
637                     ty::MethodParam {
638                         // def-id is already translated when we read it out
639                         trait_ref: mp.trait_ref.clone(),
640                         method_num: mp.method_num,
641                         impl_def_id: mp.impl_def_id.tr(dcx),
642                     }
643                 )
644             }
645             ty::MethodTraitObject(ref mo) => {
646                 ty::MethodTraitObject(
647                     ty::MethodObject {
648                         trait_ref: mo.trait_ref.clone(),
649                         .. *mo
650                     }
651                 )
652             }
653         }
654     }
655 }
656
657 pub fn encode_closure_kind(ebml_w: &mut Encoder, kind: ty::ClosureKind) {
658     kind.encode(ebml_w).unwrap();
659 }
660
661 pub trait vtable_decoder_helpers<'tcx> {
662     fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
663         F: FnMut(&mut Self) -> T;
664     fn read_vtable_res_with_key(&mut self,
665                                 tcx: &ty::ctxt<'tcx>,
666                                 cdata: &cstore::crate_metadata)
667                                 -> (ty::ExprAdjustment, ty::vtable_res<'tcx>);
668     fn read_vtable_res(&mut self,
669                        tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata)
670                       -> ty::vtable_res<'tcx>;
671     fn read_vtable_param_res(&mut self,
672                        tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata)
673                       -> ty::vtable_param_res<'tcx>;
674     fn read_vtable_origin(&mut self,
675                           tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata)
676                           -> ty::vtable_origin<'tcx>;
677 }
678
679 impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> {
680     fn read_vec_per_param_space<T, F>(&mut self, mut f: F) -> VecPerParamSpace<T> where
681         F: FnMut(&mut reader::Decoder<'a>) -> T,
682     {
683         let types = self.read_to_vec(|this| Ok(f(this))).unwrap();
684         let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap();
685         let fns = self.read_to_vec(|this| Ok(f(this))).unwrap();
686         VecPerParamSpace::new(types, selfs, fns)
687     }
688
689     fn read_vtable_res_with_key(&mut self,
690                                 tcx: &ty::ctxt<'tcx>,
691                                 cdata: &cstore::crate_metadata)
692                                 -> (ty::ExprAdjustment, ty::vtable_res<'tcx>) {
693         self.read_struct("VtableWithKey", 2, |this| {
694             let adjustment = this.read_struct_field("adjustment", 0, |this| {
695                 Decodable::decode(this)
696             }).unwrap();
697             Ok((adjustment, this.read_struct_field("vtable_res", 1, |this| {
698                 Ok(this.read_vtable_res(tcx, cdata))
699             }).unwrap()))
700         }).unwrap()
701     }
702
703     fn read_vtable_res(&mut self,
704                        tcx: &ty::ctxt<'tcx>,
705                        cdata: &cstore::crate_metadata)
706                        -> ty::vtable_res<'tcx>
707     {
708         self.read_vec_per_param_space(
709             |this| this.read_vtable_param_res(tcx, cdata))
710     }
711
712     fn read_vtable_param_res(&mut self,
713                              tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata)
714                       -> ty::vtable_param_res<'tcx> {
715         self.read_to_vec(|this| Ok(this.read_vtable_origin(tcx, cdata)))
716              .unwrap().into_iter().collect()
717     }
718
719     fn read_vtable_origin(&mut self,
720                           tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata)
721         -> ty::vtable_origin<'tcx> {
722         self.read_enum("vtable_origin", |this| {
723             this.read_enum_variant(&["vtable_static",
724                                      "vtable_param",
725                                      "vtable_error",
726                                      "vtable_closure"],
727                                    |this, i| {
728                 Ok(match i {
729                   0 => {
730                     ty::vtable_static(
731                         this.read_enum_variant_arg(0, |this| {
732                             Ok(this.read_def_id_nodcx(cdata))
733                         }).unwrap(),
734                         this.read_enum_variant_arg(1, |this| {
735                             Ok(this.read_substs_nodcx(tcx, cdata))
736                         }).unwrap(),
737                         this.read_enum_variant_arg(2, |this| {
738                             Ok(this.read_vtable_res(tcx, cdata))
739                         }).unwrap()
740                     )
741                   }
742                   1 => {
743                     ty::vtable_param(
744                         this.read_enum_variant_arg(0, |this| {
745                             Decodable::decode(this)
746                         }).unwrap(),
747                         this.read_enum_variant_arg(1, |this| {
748                             this.read_uint()
749                         }).unwrap()
750                     )
751                   }
752                   2 => {
753                     ty::vtable_closure(
754                         this.read_enum_variant_arg(0, |this| {
755                             Ok(this.read_def_id_nodcx(cdata))
756                         }).unwrap()
757                     )
758                   }
759                   3 => {
760                     ty::vtable_error
761                   }
762                   _ => panic!("bad enum variant")
763                 })
764             })
765         }).unwrap()
766     }
767 }
768
769 // ___________________________________________________________________________
770 //
771
772 fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder,
773                                     v: &subst::VecPerParamSpace<T>,
774                                     mut f: F) where
775     F: FnMut(&mut Encoder, &T),
776 {
777     for &space in &subst::ParamSpace::all() {
778         rbml_w.emit_from_vec(v.get_slice(space),
779                              |rbml_w, n| Ok(f(rbml_w, n))).unwrap();
780     }
781 }
782
783 // ______________________________________________________________________
784 // Encoding and decoding the side tables
785
786 trait get_ty_str_ctxt<'tcx> {
787     fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
788 }
789
790 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
791     fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
792         tyencode::ctxt {
793             diag: self.tcx.sess.diagnostic(),
794             ds: e::def_to_string,
795             tcx: self.tcx,
796             abbrevs: &self.type_abbrevs
797         }
798     }
799 }
800
801 trait rbml_writer_helpers<'tcx> {
802     fn emit_closure_type<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
803                              closure_type: &ty::ClosureTy<'tcx>);
804     fn emit_method_origin<'a>(&mut self,
805                               ecx: &e::EncodeContext<'a, 'tcx>,
806                               method_origin: &ty::MethodOrigin<'tcx>);
807     fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
808     fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
809     fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
810                                type_param_def: &ty::TypeParameterDef<'tcx>);
811     fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
812                           predicate: &ty::Predicate<'tcx>);
813     fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
814                           ty: &ty::TraitRef<'tcx>);
815     fn emit_type_scheme<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
816                             type_scheme: ty::TypeScheme<'tcx>);
817     fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
818                        substs: &subst::Substs<'tcx>);
819     fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
820                                    bounds: &ty::ExistentialBounds<'tcx>);
821     fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
822     fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
823                                 adj: &ty::AutoAdjustment<'tcx>);
824     fn emit_autoref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
825                         autoref: &ty::AutoRef<'tcx>);
826     fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
827                                auto_deref_ref: &ty::AutoDerefRef<'tcx>);
828     fn emit_unsize_kind<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
829                             uk: &ty::UnsizeKind<'tcx>);
830 }
831
832 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
833     fn emit_closure_type<'b>(&mut self,
834                              ecx: &e::EncodeContext<'b, 'tcx>,
835                              closure_type: &ty::ClosureTy<'tcx>) {
836         self.emit_opaque(|this| {
837             Ok(e::write_closure_type(ecx, this, closure_type))
838         });
839     }
840
841     fn emit_method_origin<'b>(&mut self,
842                               ecx: &e::EncodeContext<'b, 'tcx>,
843                               method_origin: &ty::MethodOrigin<'tcx>)
844     {
845         use serialize::Encoder;
846
847         self.emit_enum("MethodOrigin", |this| {
848             match *method_origin {
849                 ty::MethodStatic(def_id) => {
850                     this.emit_enum_variant("MethodStatic", 0, 1, |this| {
851                         Ok(this.emit_def_id(def_id))
852                     })
853                 }
854
855                 ty::MethodStaticClosure(def_id) => {
856                     this.emit_enum_variant("MethodStaticClosure", 1, 1, |this| {
857                         Ok(this.emit_def_id(def_id))
858                     })
859                 }
860
861                 ty::MethodTypeParam(ref p) => {
862                     this.emit_enum_variant("MethodTypeParam", 2, 1, |this| {
863                         this.emit_struct("MethodParam", 2, |this| {
864                             try!(this.emit_struct_field("trait_ref", 0, |this| {
865                                 Ok(this.emit_trait_ref(ecx, &*p.trait_ref))
866                             }));
867                             try!(this.emit_struct_field("method_num", 0, |this| {
868                                 this.emit_uint(p.method_num)
869                             }));
870                             try!(this.emit_struct_field("impl_def_id", 0, |this| {
871                                 this.emit_option(|this| {
872                                     match p.impl_def_id {
873                                         None => this.emit_option_none(),
874                                         Some(did) => this.emit_option_some(|this| {
875                                             Ok(this.emit_def_id(did))
876                                         })
877                                     }
878                                 })
879                             }));
880                             Ok(())
881                         })
882                     })
883                 }
884
885                 ty::MethodTraitObject(ref o) => {
886                     this.emit_enum_variant("MethodTraitObject", 3, 1, |this| {
887                         this.emit_struct("MethodObject", 2, |this| {
888                             try!(this.emit_struct_field("trait_ref", 0, |this| {
889                                 Ok(this.emit_trait_ref(ecx, &*o.trait_ref))
890                             }));
891                             try!(this.emit_struct_field("object_trait_id", 0, |this| {
892                                 Ok(this.emit_def_id(o.object_trait_id))
893                             }));
894                             try!(this.emit_struct_field("method_num", 0, |this| {
895                                 this.emit_uint(o.method_num)
896                             }));
897                             try!(this.emit_struct_field("vtable_index", 0, |this| {
898                                 this.emit_uint(o.vtable_index)
899                             }));
900                             Ok(())
901                         })
902                     })
903                 }
904             }
905         });
906     }
907
908     fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
909         self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
910     }
911
912     fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
913         self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
914     }
915
916     fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
917                           trait_ref: &ty::TraitRef<'tcx>) {
918         self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
919     }
920
921     fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
922                                type_param_def: &ty::TypeParameterDef<'tcx>) {
923         self.emit_opaque(|this| {
924             Ok(tyencode::enc_type_param_def(this.writer,
925                                          &ecx.ty_str_ctxt(),
926                                          type_param_def))
927         });
928     }
929
930     fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
931                           predicate: &ty::Predicate<'tcx>) {
932         self.emit_opaque(|this| {
933             Ok(tyencode::enc_predicate(this.writer,
934                                        &ecx.ty_str_ctxt(),
935                                        predicate))
936         });
937     }
938
939     fn emit_type_scheme<'b>(&mut self,
940                             ecx: &e::EncodeContext<'b, 'tcx>,
941                             type_scheme: ty::TypeScheme<'tcx>) {
942         use serialize::Encoder;
943
944         self.emit_struct("TypeScheme", 2, |this| {
945             this.emit_struct_field("generics", 0, |this| {
946                 this.emit_struct("Generics", 2, |this| {
947                     this.emit_struct_field("types", 0, |this| {
948                         Ok(encode_vec_per_param_space(
949                             this, &type_scheme.generics.types,
950                             |this, def| this.emit_type_param_def(ecx, def)))
951                     });
952                     this.emit_struct_field("regions", 1, |this| {
953                         Ok(encode_vec_per_param_space(
954                             this, &type_scheme.generics.regions,
955                             |this, def| def.encode(this).unwrap()))
956                     })
957                 })
958             });
959             this.emit_struct_field("ty", 1, |this| {
960                 Ok(this.emit_ty(ecx, type_scheme.ty))
961             })
962         });
963     }
964
965     fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
966                                    bounds: &ty::ExistentialBounds<'tcx>) {
967         self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this.writer,
968                                                                     &ecx.ty_str_ctxt(),
969                                                                     bounds)));
970     }
971
972     fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
973         self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this.writer,
974                                                                 &ecx.ty_str_ctxt(),
975                                                                 bounds)));
976     }
977
978     fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
979                        substs: &subst::Substs<'tcx>) {
980         self.emit_opaque(|this| Ok(tyencode::enc_substs(this.writer,
981                                                            &ecx.ty_str_ctxt(),
982                                                            substs)));
983     }
984
985     fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
986                                 adj: &ty::AutoAdjustment<'tcx>) {
987         use serialize::Encoder;
988
989         self.emit_enum("AutoAdjustment", |this| {
990             match *adj {
991                 ty::AdjustReifyFnPointer(def_id) => {
992                     this.emit_enum_variant("AdjustReifyFnPointer", 1, 2, |this| {
993                         this.emit_enum_variant_arg(0, |this| def_id.encode(this))
994                     })
995                 }
996
997                 ty::AdjustDerefRef(ref auto_deref_ref) => {
998                     this.emit_enum_variant("AdjustDerefRef", 2, 2, |this| {
999                         this.emit_enum_variant_arg(0,
1000                             |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
1001                     })
1002                 }
1003             }
1004         });
1005     }
1006
1007     fn emit_autoref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
1008                         autoref: &ty::AutoRef<'tcx>) {
1009         use serialize::Encoder;
1010
1011         self.emit_enum("AutoRef", |this| {
1012             match autoref {
1013                 &ty::AutoPtr(r, m, None) => {
1014                     this.emit_enum_variant("AutoPtr", 0, 3, |this| {
1015                         this.emit_enum_variant_arg(0, |this| r.encode(this));
1016                         this.emit_enum_variant_arg(1, |this| m.encode(this));
1017                         this.emit_enum_variant_arg(2,
1018                             |this| this.emit_option(|this| this.emit_option_none()))
1019                     })
1020                 }
1021                 &ty::AutoPtr(r, m, Some(box ref a)) => {
1022                     this.emit_enum_variant("AutoPtr", 0, 3, |this| {
1023                         this.emit_enum_variant_arg(0, |this| r.encode(this));
1024                         this.emit_enum_variant_arg(1, |this| m.encode(this));
1025                         this.emit_enum_variant_arg(2, |this| this.emit_option(
1026                             |this| this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a)))))
1027                     })
1028                 }
1029                 &ty::AutoUnsize(ref uk) => {
1030                     this.emit_enum_variant("AutoUnsize", 1, 1, |this| {
1031                         this.emit_enum_variant_arg(0, |this| Ok(this.emit_unsize_kind(ecx, uk)))
1032                     })
1033                 }
1034                 &ty::AutoUnsizeUniq(ref uk) => {
1035                     this.emit_enum_variant("AutoUnsizeUniq", 2, 1, |this| {
1036                         this.emit_enum_variant_arg(0, |this| Ok(this.emit_unsize_kind(ecx, uk)))
1037                     })
1038                 }
1039                 &ty::AutoUnsafe(m, None) => {
1040                     this.emit_enum_variant("AutoUnsafe", 3, 2, |this| {
1041                         this.emit_enum_variant_arg(0, |this| m.encode(this));
1042                         this.emit_enum_variant_arg(1,
1043                             |this| this.emit_option(|this| this.emit_option_none()))
1044                     })
1045                 }
1046                 &ty::AutoUnsafe(m, Some(box ref a)) => {
1047                     this.emit_enum_variant("AutoUnsafe", 3, 2, |this| {
1048                         this.emit_enum_variant_arg(0, |this| m.encode(this));
1049                         this.emit_enum_variant_arg(1, |this| this.emit_option(
1050                             |this| this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a)))))
1051                     })
1052                 }
1053             }
1054         });
1055     }
1056
1057     fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
1058                                auto_deref_ref: &ty::AutoDerefRef<'tcx>) {
1059         use serialize::Encoder;
1060
1061         self.emit_struct("AutoDerefRef", 2, |this| {
1062             this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
1063             this.emit_struct_field("autoref", 1, |this| {
1064                 this.emit_option(|this| {
1065                     match auto_deref_ref.autoref {
1066                         None => this.emit_option_none(),
1067                         Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a))),
1068                     }
1069                 })
1070             })
1071         });
1072     }
1073
1074     fn emit_unsize_kind<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
1075                             uk: &ty::UnsizeKind<'tcx>) {
1076         use serialize::Encoder;
1077
1078         self.emit_enum("UnsizeKind", |this| {
1079             match *uk {
1080                 ty::UnsizeLength(len) => {
1081                     this.emit_enum_variant("UnsizeLength", 0, 1, |this| {
1082                         this.emit_enum_variant_arg(0, |this| len.encode(this))
1083                     })
1084                 }
1085                 ty::UnsizeStruct(box ref uk, idx) => {
1086                     this.emit_enum_variant("UnsizeStruct", 1, 2, |this| {
1087                         this.emit_enum_variant_arg(0, |this| Ok(this.emit_unsize_kind(ecx, uk)));
1088                         this.emit_enum_variant_arg(1, |this| idx.encode(this))
1089                     })
1090                 }
1091                 ty::UnsizeVtable(ty::TyTrait { ref principal,
1092                                                bounds: ref b },
1093                                  self_ty) => {
1094                     this.emit_enum_variant("UnsizeVtable", 2, 4, |this| {
1095                         this.emit_enum_variant_arg(0, |this| {
1096                             try!(this.emit_struct_field("principal", 0, |this| {
1097                                 Ok(this.emit_trait_ref(ecx, &*principal.0))
1098                             }));
1099                             this.emit_struct_field("bounds", 1, |this| {
1100                                 Ok(this.emit_existential_bounds(ecx, b))
1101                             })
1102                         });
1103                         this.emit_enum_variant_arg(1, |this| Ok(this.emit_ty(ecx, self_ty)))
1104                     })
1105                 }
1106             }
1107         });
1108     }
1109 }
1110
1111 trait write_tag_and_id {
1112     fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
1113     fn id(&mut self, id: ast::NodeId);
1114 }
1115
1116 impl<'a> write_tag_and_id for Encoder<'a> {
1117     fn tag<F>(&mut self,
1118               tag_id: c::astencode_tag,
1119               f: F) where
1120         F: FnOnce(&mut Encoder<'a>),
1121     {
1122         self.start_tag(tag_id as uint);
1123         f(self);
1124         self.end_tag();
1125     }
1126
1127     fn id(&mut self, id: ast::NodeId) {
1128         self.wr_tagged_u64(c::tag_table_id as uint, id as u64);
1129     }
1130 }
1131
1132 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
1133     ecx: &'a e::EncodeContext<'c, 'tcx>,
1134     rbml_w: &'a mut Encoder<'b>,
1135 }
1136
1137 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
1138         SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
1139     fn visit_id(&mut self, id: ast::NodeId) {
1140         encode_side_tables_for_id(self.ecx, self.rbml_w, id)
1141     }
1142 }
1143
1144 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
1145                              rbml_w: &mut Encoder,
1146                              ii: &ast::InlinedItem) {
1147     rbml_w.start_tag(c::tag_table as uint);
1148     ast_util::visit_ids_for_inlined_item(ii, &mut SideTableEncodingIdVisitor {
1149         ecx: ecx,
1150         rbml_w: rbml_w
1151     });
1152     rbml_w.end_tag();
1153 }
1154
1155 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
1156                              rbml_w: &mut Encoder,
1157                              id: ast::NodeId) {
1158     let tcx = ecx.tcx;
1159
1160     debug!("Encoding side tables for id {}", id);
1161
1162     if let Some(def) = tcx.def_map.borrow().get(&id) {
1163         rbml_w.tag(c::tag_table_def, |rbml_w| {
1164             rbml_w.id(id);
1165             rbml_w.tag(c::tag_table_val, |rbml_w| (*def).encode(rbml_w).unwrap());
1166         })
1167     }
1168
1169     if let Some(ty) = tcx.node_types.borrow().get(&id) {
1170         rbml_w.tag(c::tag_table_node_type, |rbml_w| {
1171             rbml_w.id(id);
1172             rbml_w.tag(c::tag_table_val, |rbml_w| {
1173                 rbml_w.emit_ty(ecx, *ty);
1174             })
1175         })
1176     }
1177
1178     if let Some(item_substs) = tcx.item_substs.borrow().get(&id) {
1179         rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
1180             rbml_w.id(id);
1181             rbml_w.tag(c::tag_table_val, |rbml_w| {
1182                 rbml_w.emit_substs(ecx, &item_substs.substs);
1183             })
1184         })
1185     }
1186
1187     if let Some(fv) = tcx.freevars.borrow().get(&id) {
1188         rbml_w.tag(c::tag_table_freevars, |rbml_w| {
1189             rbml_w.id(id);
1190             rbml_w.tag(c::tag_table_val, |rbml_w| {
1191                 rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
1192                     Ok(encode_freevar_entry(rbml_w, fv_entry))
1193                 });
1194             })
1195         });
1196
1197         for freevar in fv {
1198             rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
1199                 rbml_w.id(id);
1200                 rbml_w.tag(c::tag_table_val, |rbml_w| {
1201                     let var_id = freevar.def.def_id().node;
1202                     let upvar_id = ty::UpvarId {
1203                         var_id: var_id,
1204                         closure_expr_id: id
1205                     };
1206                     let upvar_capture = tcx.upvar_capture_map.borrow()[upvar_id].clone();
1207                     var_id.encode(rbml_w);
1208                     upvar_capture.encode(rbml_w);
1209                 })
1210             })
1211         }
1212     }
1213
1214     let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1215     if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
1216         rbml_w.tag(c::tag_table_tcache, |rbml_w| {
1217             rbml_w.id(id);
1218             rbml_w.tag(c::tag_table_val, |rbml_w| {
1219                 rbml_w.emit_type_scheme(ecx, type_scheme.clone());
1220             })
1221         })
1222     }
1223
1224     if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
1225         rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
1226             rbml_w.id(id);
1227             rbml_w.tag(c::tag_table_val, |rbml_w| {
1228                 rbml_w.emit_type_param_def(ecx, type_param_def)
1229             })
1230         })
1231     }
1232
1233     let method_call = MethodCall::expr(id);
1234     if let Some(method) = tcx.method_map.borrow().get(&method_call) {
1235         rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1236             rbml_w.id(id);
1237             rbml_w.tag(c::tag_table_val, |rbml_w| {
1238                 encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
1239             })
1240         })
1241     }
1242
1243     if let Some(trait_ref) = tcx.object_cast_map.borrow().get(&id) {
1244         rbml_w.tag(c::tag_table_object_cast_map, |rbml_w| {
1245             rbml_w.id(id);
1246             rbml_w.tag(c::tag_table_val, |rbml_w| {
1247                 rbml_w.emit_trait_ref(ecx, &*trait_ref.0);
1248             })
1249         })
1250     }
1251
1252     if let Some(adjustment) = tcx.adjustments.borrow().get(&id) {
1253         match *adjustment {
1254             _ if ty::adjust_is_object(adjustment) => {
1255                 let method_call = MethodCall::autoobject(id);
1256                 if let Some(method) = tcx.method_map.borrow().get(&method_call) {
1257                     rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1258                         rbml_w.id(id);
1259                         rbml_w.tag(c::tag_table_val, |rbml_w| {
1260                             encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
1261                         })
1262                     })
1263                 }
1264             }
1265             ty::AdjustDerefRef(ref adj) => {
1266                 assert!(!ty::adjust_is_object(adjustment));
1267                 for autoderef in 0..adj.autoderefs {
1268                     let method_call = MethodCall::autoderef(id, autoderef);
1269                     if let Some(method) = tcx.method_map.borrow().get(&method_call) {
1270                         rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1271                             rbml_w.id(id);
1272                             rbml_w.tag(c::tag_table_val, |rbml_w| {
1273                                 encode_method_callee(ecx, rbml_w,
1274                                                      method_call.adjustment, method)
1275                             })
1276                         })
1277                     }
1278                 }
1279             }
1280             _ => {
1281                 assert!(!ty::adjust_is_object(adjustment));
1282             }
1283         }
1284
1285         rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
1286             rbml_w.id(id);
1287             rbml_w.tag(c::tag_table_val, |rbml_w| {
1288                 rbml_w.emit_auto_adjustment(ecx, adjustment);
1289             })
1290         })
1291     }
1292
1293     if let Some(closure_type) = tcx.closure_tys.borrow().get(&ast_util::local_def(id)) {
1294         rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
1295             rbml_w.id(id);
1296             rbml_w.tag(c::tag_table_val, |rbml_w| {
1297                 rbml_w.emit_closure_type(ecx, closure_type);
1298             })
1299         })
1300     }
1301
1302     if let Some(closure_kind) = tcx.closure_kinds.borrow().get(&ast_util::local_def(id)) {
1303         rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
1304             rbml_w.id(id);
1305             rbml_w.tag(c::tag_table_val, |rbml_w| {
1306                 encode_closure_kind(rbml_w, *closure_kind)
1307             })
1308         })
1309     }
1310
1311     for &qualif in tcx.const_qualif_map.borrow().get(&id).iter() {
1312         rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
1313             rbml_w.id(id);
1314             rbml_w.tag(c::tag_table_val, |rbml_w| {
1315                 qualif.encode(rbml_w).unwrap()
1316             })
1317         })
1318     }
1319 }
1320
1321 trait doc_decoder_helpers {
1322     fn as_int(&self) -> int;
1323     fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1324 }
1325
1326 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
1327     fn as_int(&self) -> int { reader::doc_as_u64(*self) as int }
1328     fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
1329         reader::maybe_get_doc(*self, tag as uint)
1330     }
1331 }
1332
1333 trait rbml_decoder_decoder_helpers<'tcx> {
1334     fn read_method_origin<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1335                                   -> ty::MethodOrigin<'tcx>;
1336     fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
1337     fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
1338     fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1339                               -> Rc<ty::TraitRef<'tcx>>;
1340     fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1341                                    -> ty::PolyTraitRef<'tcx>;
1342     fn read_type_param_def<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1343                                    -> ty::TypeParameterDef<'tcx>;
1344     fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1345                               -> ty::Predicate<'tcx>;
1346     fn read_type_scheme<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1347                                 -> ty::TypeScheme<'tcx>;
1348     fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1349                                        -> ty::ExistentialBounds<'tcx>;
1350     fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1351                            -> subst::Substs<'tcx>;
1352     fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1353                                     -> ty::AutoAdjustment<'tcx>;
1354     fn read_closure_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1355                                  -> ty::ClosureKind;
1356     fn read_closure_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1357                                -> ty::ClosureTy<'tcx>;
1358     fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1359                                    -> ty::AutoDerefRef<'tcx>;
1360     fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1361                             -> ty::AutoRef<'tcx>;
1362     fn read_unsize_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1363                                 -> ty::UnsizeKind<'tcx>;
1364     fn convert_def_id(&mut self,
1365                       dcx: &DecodeContext,
1366                       source: DefIdSource,
1367                       did: ast::DefId)
1368                       -> ast::DefId;
1369
1370     // Versions of the type reading functions that don't need the full
1371     // DecodeContext.
1372     fn read_ty_nodcx(&mut self,
1373                      tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
1374     fn read_tys_nodcx(&mut self,
1375                       tcx: &ty::ctxt<'tcx>,
1376                       cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
1377     fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
1378                          cdata: &cstore::crate_metadata)
1379                          -> subst::Substs<'tcx>;
1380 }
1381
1382 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
1383     fn read_ty_nodcx(&mut self,
1384                      tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx> {
1385         self.read_opaque(|_, doc| {
1386             Ok(tydecode::parse_ty_data(
1387                 doc.data,
1388                 cdata.cnum,
1389                 doc.start,
1390                 tcx,
1391                 |_, id| decoder::translate_def_id(cdata, id)))
1392         }).unwrap()
1393     }
1394
1395     fn read_tys_nodcx(&mut self,
1396                       tcx: &ty::ctxt<'tcx>,
1397                       cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
1398         self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
1399             .unwrap()
1400             .into_iter()
1401             .collect()
1402     }
1403
1404     fn read_substs_nodcx(&mut self,
1405                          tcx: &ty::ctxt<'tcx>,
1406                          cdata: &cstore::crate_metadata)
1407                          -> subst::Substs<'tcx>
1408     {
1409         self.read_opaque(|_, doc| {
1410             Ok(tydecode::parse_substs_data(
1411                 doc.data,
1412                 cdata.cnum,
1413                 doc.start,
1414                 tcx,
1415                 |_, id| decoder::translate_def_id(cdata, id)))
1416         }).unwrap()
1417     }
1418
1419     fn read_method_origin<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1420                                   -> ty::MethodOrigin<'tcx>
1421     {
1422         self.read_enum("MethodOrigin", |this| {
1423             let variants = &["MethodStatic", "MethodStaticClosure",
1424                              "MethodTypeParam", "MethodTraitObject"];
1425             this.read_enum_variant(variants, |this, i| {
1426                 Ok(match i {
1427                     0 => {
1428                         let def_id = this.read_def_id(dcx);
1429                         ty::MethodStatic(def_id)
1430                     }
1431
1432                     1 => {
1433                         let def_id = this.read_def_id(dcx);
1434                         ty::MethodStaticClosure(def_id)
1435                     }
1436
1437                     2 => {
1438                         this.read_struct("MethodTypeParam", 2, |this| {
1439                             Ok(ty::MethodTypeParam(
1440                                 ty::MethodParam {
1441                                     trait_ref: {
1442                                         this.read_struct_field("trait_ref", 0, |this| {
1443                                             Ok(this.read_trait_ref(dcx))
1444                                         }).unwrap()
1445                                     },
1446                                     method_num: {
1447                                         this.read_struct_field("method_num", 1, |this| {
1448                                             this.read_uint()
1449                                         }).unwrap()
1450                                     },
1451                                     impl_def_id: {
1452                                         this.read_struct_field("impl_def_id", 2, |this| {
1453                                             this.read_option(|this, b| {
1454                                                 if b {
1455                                                     Ok(Some(this.read_def_id(dcx)))
1456                                                 } else {
1457                                                     Ok(None)
1458                                                 }
1459                                             })
1460                                         }).unwrap()
1461                                     }
1462                                 }))
1463                         }).unwrap()
1464                     }
1465
1466                     3 => {
1467                         this.read_struct("MethodTraitObject", 2, |this| {
1468                             Ok(ty::MethodTraitObject(
1469                                 ty::MethodObject {
1470                                     trait_ref: {
1471                                         this.read_struct_field("trait_ref", 0, |this| {
1472                                             Ok(this.read_trait_ref(dcx))
1473                                         }).unwrap()
1474                                     },
1475                                     object_trait_id: {
1476                                         this.read_struct_field("object_trait_id", 1, |this| {
1477                                             Ok(this.read_def_id(dcx))
1478                                         }).unwrap()
1479                                     },
1480                                     method_num: {
1481                                         this.read_struct_field("method_num", 2, |this| {
1482                                             this.read_uint()
1483                                         }).unwrap()
1484                                     },
1485                                     vtable_index: {
1486                                         this.read_struct_field("vtable_index", 3, |this| {
1487                                             this.read_uint()
1488                                         }).unwrap()
1489                                     },
1490                                 }))
1491                         }).unwrap()
1492                     }
1493
1494                     _ => panic!("..")
1495                 })
1496             })
1497         }).unwrap()
1498     }
1499
1500
1501     fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1502         // Note: regions types embed local node ids.  In principle, we
1503         // should translate these node ids into the new decode
1504         // context.  However, we do not bother, because region types
1505         // are not used during trans.
1506
1507         return self.read_opaque(|this, doc| {
1508             debug!("read_ty({})", type_string(doc));
1509
1510             let ty = tydecode::parse_ty_data(
1511                 doc.data,
1512                 dcx.cdata.cnum,
1513                 doc.start,
1514                 dcx.tcx,
1515                 |s, a| this.convert_def_id(dcx, s, a));
1516
1517             Ok(ty)
1518         }).unwrap();
1519
1520         fn type_string(doc: rbml::Doc) -> String {
1521             let mut str = String::new();
1522             for i in doc.start..doc.end {
1523                 str.push(doc.data[i] as char);
1524             }
1525             str
1526         }
1527     }
1528
1529     fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1530                         -> Vec<Ty<'tcx>> {
1531         self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1532     }
1533
1534     fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1535                               -> Rc<ty::TraitRef<'tcx>> {
1536         self.read_opaque(|this, doc| {
1537             let ty = tydecode::parse_trait_ref_data(
1538                 doc.data,
1539                 dcx.cdata.cnum,
1540                 doc.start,
1541                 dcx.tcx,
1542                 |s, a| this.convert_def_id(dcx, s, a));
1543             Ok(ty)
1544         }).unwrap()
1545     }
1546
1547     fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1548                                    -> ty::PolyTraitRef<'tcx> {
1549         ty::Binder(self.read_opaque(|this, doc| {
1550             let ty = tydecode::parse_trait_ref_data(
1551                 doc.data,
1552                 dcx.cdata.cnum,
1553                 doc.start,
1554                 dcx.tcx,
1555                 |s, a| this.convert_def_id(dcx, s, a));
1556             Ok(ty)
1557         }).unwrap())
1558     }
1559
1560     fn read_type_param_def<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1561                                    -> ty::TypeParameterDef<'tcx> {
1562         self.read_opaque(|this, doc| {
1563             Ok(tydecode::parse_type_param_def_data(
1564                 doc.data,
1565                 doc.start,
1566                 dcx.cdata.cnum,
1567                 dcx.tcx,
1568                 |s, a| this.convert_def_id(dcx, s, a)))
1569         }).unwrap()
1570     }
1571
1572     fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1573                               -> ty::Predicate<'tcx>
1574     {
1575         self.read_opaque(|this, doc| {
1576             Ok(tydecode::parse_predicate_data(doc.data, doc.start, dcx.cdata.cnum, dcx.tcx,
1577                                               |s, a| this.convert_def_id(dcx, s, a)))
1578         }).unwrap()
1579     }
1580
1581     fn read_type_scheme<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1582                                 -> ty::TypeScheme<'tcx> {
1583         self.read_struct("TypeScheme", 3, |this| {
1584             Ok(ty::TypeScheme {
1585                 generics: this.read_struct_field("generics", 0, |this| {
1586                     this.read_struct("Generics", 2, |this| {
1587                         Ok(ty::Generics {
1588                             types:
1589                             this.read_struct_field("types", 0, |this| {
1590                                 Ok(this.read_vec_per_param_space(
1591                                     |this| this.read_type_param_def(dcx)))
1592                             }).unwrap(),
1593
1594                             regions:
1595                             this.read_struct_field("regions", 1, |this| {
1596                                 Ok(this.read_vec_per_param_space(
1597                                     |this| Decodable::decode(this).unwrap()))
1598                             }).unwrap(),
1599                         })
1600                     })
1601                 }).unwrap(),
1602                 ty: this.read_struct_field("ty", 1, |this| {
1603                     Ok(this.read_ty(dcx))
1604                 }).unwrap()
1605             })
1606         }).unwrap()
1607     }
1608
1609     fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1610                                        -> ty::ExistentialBounds<'tcx>
1611     {
1612         self.read_opaque(|this, doc| {
1613             Ok(tydecode::parse_existential_bounds_data(doc.data,
1614                                                        dcx.cdata.cnum,
1615                                                        doc.start,
1616                                                        dcx.tcx,
1617                                                        |s, a| this.convert_def_id(dcx, s, a)))
1618         }).unwrap()
1619     }
1620
1621     fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1622                            -> subst::Substs<'tcx> {
1623         self.read_opaque(|this, doc| {
1624             Ok(tydecode::parse_substs_data(doc.data,
1625                                         dcx.cdata.cnum,
1626                                         doc.start,
1627                                         dcx.tcx,
1628                                         |s, a| this.convert_def_id(dcx, s, a)))
1629         }).unwrap()
1630     }
1631
1632     fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1633                                     -> ty::AutoAdjustment<'tcx> {
1634         self.read_enum("AutoAdjustment", |this| {
1635             let variants = ["AutoAddEnv", "AutoDerefRef"];
1636             this.read_enum_variant(&variants, |this, i| {
1637                 Ok(match i {
1638                     1 => {
1639                         let def_id: ast::DefId =
1640                             this.read_def_id(dcx);
1641
1642                         ty::AdjustReifyFnPointer(def_id)
1643                     }
1644                     2 => {
1645                         let auto_deref_ref: ty::AutoDerefRef =
1646                             this.read_enum_variant_arg(0,
1647                                 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1648
1649                         ty::AdjustDerefRef(auto_deref_ref)
1650                     }
1651                     _ => panic!("bad enum variant for ty::AutoAdjustment")
1652                 })
1653             })
1654         }).unwrap()
1655     }
1656
1657     fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1658                                    -> ty::AutoDerefRef<'tcx> {
1659         self.read_struct("AutoDerefRef", 2, |this| {
1660             Ok(ty::AutoDerefRef {
1661                 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1662                     Decodable::decode(this)
1663                 }).unwrap(),
1664                 autoref: this.read_struct_field("autoref", 1, |this| {
1665                     this.read_option(|this, b| {
1666                         if b {
1667                             Ok(Some(this.read_autoref(dcx)))
1668                         } else {
1669                             Ok(None)
1670                         }
1671                     })
1672                 }).unwrap(),
1673             })
1674         }).unwrap()
1675     }
1676
1677     fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> ty::AutoRef<'tcx> {
1678         self.read_enum("AutoRef", |this| {
1679             let variants = ["AutoPtr",
1680                             "AutoUnsize",
1681                             "AutoUnsizeUniq",
1682                             "AutoUnsafe"];
1683             this.read_enum_variant(&variants, |this, i| {
1684                 Ok(match i {
1685                     0 => {
1686                         let r: ty::Region =
1687                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1688                         let m: ast::Mutability =
1689                             this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1690                         let a: Option<Box<ty::AutoRef>> =
1691                             this.read_enum_variant_arg(2, |this| this.read_option(|this, b| {
1692                                 if b {
1693                                     Ok(Some(box this.read_autoref(dcx)))
1694                                 } else {
1695                                     Ok(None)
1696                                 }
1697                             })).unwrap();
1698
1699                         ty::AutoPtr(r.tr(dcx), m, a)
1700                     }
1701                     1 => {
1702                         let uk: ty::UnsizeKind =
1703                             this.read_enum_variant_arg(0,
1704                                 |this| Ok(this.read_unsize_kind(dcx))).unwrap();
1705
1706                         ty::AutoUnsize(uk)
1707                     }
1708                     2 => {
1709                         let uk: ty::UnsizeKind =
1710                             this.read_enum_variant_arg(0,
1711                                 |this| Ok(this.read_unsize_kind(dcx))).unwrap();
1712
1713                         ty::AutoUnsizeUniq(uk)
1714                     }
1715                     3 => {
1716                         let m: ast::Mutability =
1717                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1718                         let a: Option<Box<ty::AutoRef>> =
1719                             this.read_enum_variant_arg(1, |this| this.read_option(|this, b| {
1720                                 if b {
1721                                     Ok(Some(box this.read_autoref(dcx)))
1722                                 } else {
1723                                     Ok(None)
1724                                 }
1725                             })).unwrap();
1726
1727                         ty::AutoUnsafe(m, a)
1728                     }
1729                     _ => panic!("bad enum variant for ty::AutoRef")
1730                 })
1731             })
1732         }).unwrap()
1733     }
1734
1735     fn read_unsize_kind<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1736                                 -> ty::UnsizeKind<'tcx> {
1737         self.read_enum("UnsizeKind", |this| {
1738             let variants = &["UnsizeLength", "UnsizeStruct", "UnsizeVtable"];
1739             this.read_enum_variant(variants, |this, i| {
1740                 Ok(match i {
1741                     0 => {
1742                         let len: uint =
1743                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1744
1745                         ty::UnsizeLength(len)
1746                     }
1747                     1 => {
1748                         let uk: ty::UnsizeKind =
1749                             this.read_enum_variant_arg(0,
1750                                 |this| Ok(this.read_unsize_kind(dcx))).unwrap();
1751                         let idx: uint =
1752                             this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1753
1754                         ty::UnsizeStruct(box uk, idx)
1755                     }
1756                     2 => {
1757                         let ty_trait = try!(this.read_enum_variant_arg(0, |this| {
1758                             let principal = try!(this.read_struct_field("principal", 0, |this| {
1759                                 Ok(this.read_poly_trait_ref(dcx))
1760                             }));
1761                             Ok(ty::TyTrait {
1762                                 principal: principal,
1763                                 bounds: try!(this.read_struct_field("bounds", 1, |this| {
1764                                     Ok(this.read_existential_bounds(dcx))
1765                                 })),
1766                             })
1767                         }));
1768                         let self_ty =
1769                             this.read_enum_variant_arg(1, |this| Ok(this.read_ty(dcx))).unwrap();
1770                         ty::UnsizeVtable(ty_trait, self_ty)
1771                     }
1772                     _ => panic!("bad enum variant for ty::UnsizeKind")
1773                 })
1774             })
1775         }).unwrap()
1776     }
1777
1778     fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1779                                  -> ty::ClosureKind
1780     {
1781         Decodable::decode(self).ok().unwrap()
1782     }
1783
1784     fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1785                                -> ty::ClosureTy<'tcx>
1786     {
1787         self.read_opaque(|this, doc| {
1788             Ok(tydecode::parse_ty_closure_data(
1789                 doc.data,
1790                 dcx.cdata.cnum,
1791                 doc.start,
1792                 dcx.tcx,
1793                 |s, a| this.convert_def_id(dcx, s, a)))
1794         }).unwrap()
1795     }
1796
1797     /// Converts a def-id that appears in a type.  The correct
1798     /// translation will depend on what kind of def-id this is.
1799     /// This is a subtle point: type definitions are not
1800     /// inlined into the current crate, so if the def-id names
1801     /// a nominal type or type alias, then it should be
1802     /// translated to refer to the source crate.
1803     ///
1804     /// However, *type parameters* are cloned along with the function
1805     /// they are attached to.  So we should translate those def-ids
1806     /// to refer to the new, cloned copy of the type parameter.
1807     /// We only see references to free type parameters in the body of
1808     /// an inlined function. In such cases, we need the def-id to
1809     /// be a local id so that the TypeContents code is able to lookup
1810     /// the relevant info in the ty_param_defs table.
1811     ///
1812     /// *Region parameters*, unfortunately, are another kettle of fish.
1813     /// In such cases, def_id's can appear in types to distinguish
1814     /// shadowed bound regions and so forth. It doesn't actually
1815     /// matter so much what we do to these, since regions are erased
1816     /// at trans time, but it's good to keep them consistent just in
1817     /// case. We translate them with `tr_def_id()` which will map
1818     /// the crate numbers back to the original source crate.
1819     ///
1820     /// Unboxed closures are cloned along with the function being
1821     /// inlined, and all side tables use interned node IDs, so we
1822     /// translate their def IDs accordingly.
1823     ///
1824     /// It'd be really nice to refactor the type repr to not include
1825     /// def-ids so that all these distinctions were unnecessary.
1826     fn convert_def_id(&mut self,
1827                       dcx: &DecodeContext,
1828                       source: tydecode::DefIdSource,
1829                       did: ast::DefId)
1830                       -> ast::DefId {
1831         let r = match source {
1832             NominalType | TypeWithId | RegionParameter => dcx.tr_def_id(did),
1833             TypeParameter | ClosureSource => dcx.tr_intern_def_id(did)
1834         };
1835         debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1836         return r;
1837     }
1838 }
1839
1840 fn decode_side_tables(dcx: &DecodeContext,
1841                       ast_doc: rbml::Doc) {
1842     let tbl_doc = ast_doc.get(c::tag_table as uint);
1843     reader::docs(tbl_doc, |tag, entry_doc| {
1844         let id0 = entry_doc.get(c::tag_table_id as uint).as_int();
1845         let id = dcx.tr_id(id0 as ast::NodeId);
1846
1847         debug!(">> Side table document with tag 0x{:x} \
1848                 found for id {} (orig {})",
1849                tag, id, id0);
1850         let decoded_tag: Option<c::astencode_tag> = FromPrimitive::from_uint(tag);
1851         match decoded_tag {
1852             None => {
1853                 dcx.tcx.sess.bug(
1854                     &format!("unknown tag found in side tables: {:x}",
1855                             tag)[]);
1856             }
1857             Some(value) => {
1858                 let val_doc = entry_doc.get(c::tag_table_val as uint);
1859                 let mut val_dsr = reader::Decoder::new(val_doc);
1860                 let val_dsr = &mut val_dsr;
1861
1862                 match value {
1863                     c::tag_table_def => {
1864                         let def = decode_def(dcx, val_doc);
1865                         dcx.tcx.def_map.borrow_mut().insert(id, def);
1866                     }
1867                     c::tag_table_node_type => {
1868                         let ty = val_dsr.read_ty(dcx);
1869                         debug!("inserting ty for node {}: {}",
1870                                id, ty_to_string(dcx.tcx, ty));
1871                         dcx.tcx.node_types.borrow_mut().insert(id, ty);
1872                     }
1873                     c::tag_table_item_subst => {
1874                         let item_substs = ty::ItemSubsts {
1875                             substs: val_dsr.read_substs(dcx)
1876                         };
1877                         dcx.tcx.item_substs.borrow_mut().insert(
1878                             id, item_substs);
1879                     }
1880                     c::tag_table_freevars => {
1881                         let fv_info = val_dsr.read_to_vec(|val_dsr| {
1882                             Ok(val_dsr.read_freevar_entry(dcx))
1883                         }).unwrap().into_iter().collect();
1884                         dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1885                     }
1886                     c::tag_table_upvar_capture_map => {
1887                         let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1888                         let upvar_id = ty::UpvarId {
1889                             var_id: dcx.tr_id(var_id),
1890                             closure_expr_id: id
1891                         };
1892                         let ub: ty::UpvarCapture = Decodable::decode(val_dsr).unwrap();
1893                         dcx.tcx.upvar_capture_map.borrow_mut().insert(upvar_id, ub.tr(dcx));
1894                     }
1895                     c::tag_table_tcache => {
1896                         let type_scheme = val_dsr.read_type_scheme(dcx);
1897                         let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1898                         dcx.tcx.tcache.borrow_mut().insert(lid, type_scheme);
1899                     }
1900                     c::tag_table_param_defs => {
1901                         let bounds = val_dsr.read_type_param_def(dcx);
1902                         dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1903                     }
1904                     c::tag_table_method_map => {
1905                         let (adjustment, method) = val_dsr.read_method_callee(dcx);
1906                         let method_call = MethodCall {
1907                             expr_id: id,
1908                             adjustment: adjustment
1909                         };
1910                         dcx.tcx.method_map.borrow_mut().insert(method_call, method);
1911                     }
1912                     c::tag_table_object_cast_map => {
1913                         let trait_ref = val_dsr.read_poly_trait_ref(dcx);
1914                         dcx.tcx.object_cast_map.borrow_mut()
1915                                                .insert(id, trait_ref);
1916                     }
1917                     c::tag_table_adjustments => {
1918                         let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(dcx);
1919                         dcx.tcx.adjustments.borrow_mut().insert(id, adj);
1920                     }
1921                     c::tag_table_closure_tys => {
1922                         let closure_ty =
1923                             val_dsr.read_closure_ty(dcx);
1924                         dcx.tcx.closure_tys.borrow_mut().insert(ast_util::local_def(id),
1925                                                                 closure_ty);
1926                     }
1927                     c::tag_table_closure_kinds => {
1928                         let closure_kind =
1929                             val_dsr.read_closure_kind(dcx);
1930                         dcx.tcx.closure_kinds.borrow_mut().insert(ast_util::local_def(id),
1931                                                                   closure_kind);
1932                     }
1933                     c::tag_table_const_qualif => {
1934                         let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1935                         dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1936                     }
1937                     _ => {
1938                         dcx.tcx.sess.bug(
1939                             &format!("unknown tag found in side tables: {:x}",
1940                                     tag)[]);
1941                     }
1942                 }
1943             }
1944         }
1945
1946         debug!(">< Side table doc loaded");
1947         true
1948     });
1949 }
1950
1951 // ______________________________________________________________________
1952 // Testing of astencode_gen
1953
1954 #[cfg(test)]
1955 fn encode_item_ast(rbml_w: &mut Encoder, item: &ast::Item) {
1956     rbml_w.start_tag(c::tag_tree as uint);
1957     (*item).encode(rbml_w);
1958     rbml_w.end_tag();
1959 }
1960
1961 #[cfg(test)]
1962 fn decode_item_ast(par_doc: rbml::Doc) -> ast::Item {
1963     let chi_doc = par_doc.get(c::tag_tree as uint);
1964     let mut d = reader::Decoder::new(chi_doc);
1965     Decodable::decode(&mut d).unwrap()
1966 }
1967
1968 #[cfg(test)]
1969 trait fake_ext_ctxt {
1970     fn cfg(&self) -> ast::CrateConfig;
1971     fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess;
1972     fn call_site(&self) -> Span;
1973     fn ident_of(&self, st: &str) -> ast::Ident;
1974 }
1975
1976 #[cfg(test)]
1977 impl fake_ext_ctxt for parse::ParseSess {
1978     fn cfg(&self) -> ast::CrateConfig {
1979         Vec::new()
1980     }
1981     fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { self }
1982     fn call_site(&self) -> Span {
1983         codemap::Span {
1984             lo: codemap::BytePos(0),
1985             hi: codemap::BytePos(0),
1986             expn_id: codemap::NO_EXPANSION
1987         }
1988     }
1989     fn ident_of(&self, st: &str) -> ast::Ident {
1990         token::str_to_ident(st)
1991     }
1992 }
1993
1994 #[cfg(test)]
1995 fn mk_ctxt() -> parse::ParseSess {
1996     parse::new_parse_sess()
1997 }
1998
1999 #[cfg(test)]
2000 fn roundtrip(in_item: Option<P<ast::Item>>) {
2001     let in_item = in_item.unwrap();
2002     let mut wr = SeekableMemWriter::new();
2003     encode_item_ast(&mut writer::Encoder::new(&mut wr), &*in_item);
2004     let rbml_doc = rbml::Doc::new(wr.get_ref());
2005     let out_item = decode_item_ast(rbml_doc);
2006
2007     assert!(*in_item == out_item);
2008 }
2009
2010 #[test]
2011 fn test_basic() {
2012     let cx = mk_ctxt();
2013     roundtrip(quote_item!(&cx,
2014         fn foo() {}
2015     ));
2016 }
2017 /* NOTE: When there's a snapshot, update this (yay quasiquoter!)
2018 #[test]
2019 fn test_smalltalk() {
2020     let cx = mk_ctxt();
2021     roundtrip(quote_item!(&cx,
2022         fn foo() -> int { 3 + 4 } // first smalltalk program ever executed.
2023     ));
2024 }
2025 */
2026
2027 #[test]
2028 fn test_more() {
2029     let cx = mk_ctxt();
2030     roundtrip(quote_item!(&cx,
2031         fn foo(x: uint, y: uint) -> uint {
2032             let z = x + y;
2033             return z;
2034         }
2035     ));
2036 }
2037
2038 #[test]
2039 fn test_simplification() {
2040     let cx = mk_ctxt();
2041     let item = quote_item!(&cx,
2042         fn new_int_alist<B>() -> alist<int, B> {
2043             fn eq_int(a: int, b: int) -> bool { a == b }
2044             return alist {eq_fn: eq_int, data: Vec::new()};
2045         }
2046     ).unwrap();
2047     let item_in = e::IIItemRef(&*item);
2048     let item_out = simplify_ast(item_in);
2049     let item_exp = ast::IIItem(quote_item!(&cx,
2050         fn new_int_alist<B>() -> alist<int, B> {
2051             return alist {eq_fn: eq_int, data: Vec::new()};
2052         }
2053     ).unwrap());
2054     match (item_out, item_exp) {
2055       (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
2056         assert!(pprust::item_to_string(&*item_out) ==
2057                 pprust::item_to_string(&*item_exp));
2058       }
2059       _ => panic!()
2060     }
2061 }