]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/astencode.rs
auto merge of #13711 : alexcrichton/rust/snapshots, r=brson
[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 c = metadata::common;
16 use cstore = metadata::cstore;
17 use driver::session::Session;
18 use metadata::decoder;
19 use e = metadata::encoder;
20 use middle::freevars::freevar_entry;
21 use middle::region;
22 use metadata::tydecode;
23 use metadata::tydecode::{DefIdSource, NominalType, TypeWithId, TypeParameter,
24                          RegionParameter};
25 use metadata::tyencode;
26 use middle::typeck::{MethodCall, MethodCallee, MethodOrigin};
27 use middle::{ty, typeck, moves};
28 use middle;
29 use util::ppaux::ty_to_str;
30
31 use syntax::{ast, ast_map, ast_util, codemap, fold};
32 use syntax::codemap::Span;
33 use syntax::fold::Folder;
34 use syntax::parse::token;
35 use syntax;
36
37 use libc;
38 use std::cast;
39 use std::cell::RefCell;
40 use std::io::Seek;
41 use std::io::MemWriter;
42 use std::rc::Rc;
43 use std::strbuf::StrBuf;
44
45 use serialize::ebml::reader;
46 use serialize::ebml;
47 use serialize;
48 use serialize::{Encoder, Encodable, EncoderHelpers, DecoderHelpers};
49 use serialize::{Decoder, Decodable};
50 use writer = serialize::ebml::writer;
51
52 #[cfg(test)] use syntax::parse;
53 #[cfg(test)] use syntax::print::pprust;
54
55 // Auxiliary maps of things to be encoded
56 pub struct Maps {
57     pub capture_map: RefCell<middle::moves::CaptureMap>,
58 }
59
60 struct DecodeContext<'a> {
61     cdata: &'a cstore::crate_metadata,
62     tcx: &'a ty::ctxt,
63     maps: &'a Maps
64 }
65
66 struct ExtendedDecodeContext<'a> {
67     dcx: &'a DecodeContext<'a>,
68     from_id_range: ast_util::IdRange,
69     to_id_range: ast_util::IdRange
70 }
71
72 trait tr {
73     fn tr(&self, xcx: &ExtendedDecodeContext) -> Self;
74 }
75
76 trait tr_intern {
77     fn tr_intern(&self, xcx: &ExtendedDecodeContext) -> ast::DefId;
78 }
79
80 pub type Encoder<'a> = writer::Encoder<'a, MemWriter>;
81
82 // ______________________________________________________________________
83 // Top-level methods.
84
85 pub fn encode_inlined_item(ecx: &e::EncodeContext,
86                            ebml_w: &mut Encoder,
87                            ii: e::InlinedItemRef,
88                            maps: &Maps) {
89     let id = match ii {
90         e::IIItemRef(i) => i.id,
91         e::IIForeignRef(i) => i.id,
92         e::IIMethodRef(_, _, m) => m.id,
93     };
94     debug!("> Encoding inlined item: {} ({})",
95            ecx.tcx.map.path_to_str(id),
96            ebml_w.writer.tell());
97
98     let ii = simplify_ast(ii);
99     let id_range = ast_util::compute_id_range_for_inlined_item(&ii);
100
101     ebml_w.start_tag(c::tag_ast as uint);
102     id_range.encode(ebml_w);
103     encode_ast(ebml_w, ii);
104     encode_side_tables_for_ii(ecx, maps, ebml_w, &ii);
105     ebml_w.end_tag();
106
107     debug!("< Encoded inlined fn: {} ({})",
108            ecx.tcx.map.path_to_str(id),
109            ebml_w.writer.tell());
110 }
111
112 pub fn decode_inlined_item(cdata: &cstore::crate_metadata,
113                            tcx: &ty::ctxt,
114                            maps: &Maps,
115                            path: Vec<ast_map::PathElem>,
116                            par_doc: ebml::Doc)
117                            -> Result<ast::InlinedItem, Vec<ast_map::PathElem>> {
118     let dcx = &DecodeContext {
119         cdata: cdata,
120         tcx: tcx,
121         maps: maps
122     };
123     match par_doc.opt_child(c::tag_ast) {
124       None => Err(path),
125       Some(ast_doc) => {
126         let mut path_as_str = None;
127         debug!("> Decoding inlined fn: {}::?",
128         {
129             // Do an Option dance to use the path after it is moved below.
130             let s = ast_map::path_to_str(ast_map::Values(path.iter()));
131             path_as_str = Some(s);
132             path_as_str.as_ref().map(|x| x.as_slice())
133         });
134         let mut ast_dsr = reader::Decoder(ast_doc);
135         let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
136         let to_id_range = reserve_id_range(&dcx.tcx.sess, from_id_range);
137         let xcx = &ExtendedDecodeContext {
138             dcx: dcx,
139             from_id_range: from_id_range,
140             to_id_range: to_id_range
141         };
142         let raw_ii = decode_ast(ast_doc);
143         let ii = renumber_and_map_ast(xcx, &dcx.tcx.map, path, raw_ii);
144         let ident = match ii {
145             ast::IIItem(i) => i.ident,
146             ast::IIForeign(i) => i.ident,
147             ast::IIMethod(_, _, m) => m.ident,
148         };
149         debug!("Fn named: {}", token::get_ident(ident));
150         debug!("< Decoded inlined fn: {}::{}",
151                path_as_str.unwrap(),
152                token::get_ident(ident));
153         region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, &ii);
154         decode_side_tables(xcx, ast_doc);
155         match ii {
156           ast::IIItem(i) => {
157             debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
158                    syntax::print::pprust::item_to_str(i));
159           }
160           _ => { }
161         }
162         Ok(ii)
163       }
164     }
165 }
166
167 // ______________________________________________________________________
168 // Enumerating the IDs which appear in an AST
169
170 fn reserve_id_range(sess: &Session,
171                     from_id_range: ast_util::IdRange) -> ast_util::IdRange {
172     // Handle the case of an empty range:
173     if from_id_range.empty() { return from_id_range; }
174     let cnt = from_id_range.max - from_id_range.min;
175     let to_id_min = sess.reserve_node_ids(cnt);
176     let to_id_max = to_id_min + cnt;
177     ast_util::IdRange { min: to_id_min, max: to_id_max }
178 }
179
180 impl<'a> ExtendedDecodeContext<'a> {
181     pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
182         /*!
183          * Translates an internal id, meaning a node id that is known
184          * to refer to some part of the item currently being inlined,
185          * such as a local variable or argument.  All naked node-ids
186          * that appear in types have this property, since if something
187          * might refer to an external item we would use a def-id to
188          * allow for the possibility that the item resides in another
189          * crate.
190          */
191
192         // from_id_range should be non-empty
193         assert!(!self.from_id_range.empty());
194         (id - self.from_id_range.min + self.to_id_range.min)
195     }
196     pub fn tr_def_id(&self, did: ast::DefId) -> ast::DefId {
197         /*!
198          * Translates an EXTERNAL def-id, converting the crate number
199          * from the one used in the encoded data to the current crate
200          * numbers..  By external, I mean that it be translated to a
201          * reference to the item in its original crate, as opposed to
202          * being translated to a reference to the inlined version of
203          * the item.  This is typically, but not always, what you
204          * want, because most def-ids refer to external things like
205          * types or other fns that may or may not be inlined.  Note
206          * that even when the inlined function is referencing itself
207          * recursively, we would want `tr_def_id` for that
208          * reference--- conceptually the function calls the original,
209          * non-inlined version, and trans deals with linking that
210          * recursive call to the inlined copy.
211          *
212          * However, there are a *few* cases where def-ids are used but
213          * we know that the thing being referenced is in fact *internal*
214          * to the item being inlined.  In those cases, you should use
215          * `tr_intern_def_id()` below.
216          */
217
218         decoder::translate_def_id(self.dcx.cdata, did)
219     }
220     pub fn tr_intern_def_id(&self, did: ast::DefId) -> ast::DefId {
221         /*!
222          * Translates an INTERNAL def-id, meaning a def-id that is
223          * known to refer to some part of the item currently being
224          * inlined.  In that case, we want to convert the def-id to
225          * refer to the current crate and to the new, inlined node-id.
226          */
227
228         assert_eq!(did.krate, ast::LOCAL_CRATE);
229         ast::DefId { krate: ast::LOCAL_CRATE, node: self.tr_id(did.node) }
230     }
231     pub fn tr_span(&self, _span: Span) -> Span {
232         codemap::DUMMY_SP // FIXME (#1972): handle span properly
233     }
234 }
235
236 impl tr_intern for ast::DefId {
237     fn tr_intern(&self, xcx: &ExtendedDecodeContext) -> ast::DefId {
238         xcx.tr_intern_def_id(*self)
239     }
240 }
241
242 impl tr for ast::DefId {
243     fn tr(&self, xcx: &ExtendedDecodeContext) -> ast::DefId {
244         xcx.tr_def_id(*self)
245     }
246 }
247
248 impl tr for Option<ast::DefId> {
249     fn tr(&self, xcx: &ExtendedDecodeContext) -> Option<ast::DefId> {
250         self.map(|d| xcx.tr_def_id(d))
251     }
252 }
253
254 impl tr for Span {
255     fn tr(&self, xcx: &ExtendedDecodeContext) -> Span {
256         xcx.tr_span(*self)
257     }
258 }
259
260 trait def_id_encoder_helpers {
261     fn emit_def_id(&mut self, did: ast::DefId);
262 }
263
264 impl<S:serialize::Encoder<E>, E> def_id_encoder_helpers for S {
265     fn emit_def_id(&mut self, did: ast::DefId) {
266         did.encode(self).ok().unwrap()
267     }
268 }
269
270 trait def_id_decoder_helpers {
271     fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId;
272     fn read_def_id_noxcx(&mut self,
273                          cdata: &cstore::crate_metadata) -> ast::DefId;
274 }
275
276 impl<D:serialize::Decoder<E>, E> def_id_decoder_helpers for D {
277     fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId {
278         let did: ast::DefId = Decodable::decode(self).ok().unwrap();
279         did.tr(xcx)
280     }
281
282     fn read_def_id_noxcx(&mut self,
283                          cdata: &cstore::crate_metadata) -> ast::DefId {
284         let did: ast::DefId = Decodable::decode(self).ok().unwrap();
285         decoder::translate_def_id(cdata, did)
286     }
287 }
288
289 // ______________________________________________________________________
290 // Encoding and decoding the AST itself
291 //
292 // The hard work is done by an autogenerated module astencode_gen.  To
293 // regenerate astencode_gen, run src/etc/gen-astencode.  It will
294 // replace astencode_gen with a dummy file and regenerate its
295 // contents.  If you get compile errors, the dummy file
296 // remains---resolve the errors and then rerun astencode_gen.
297 // Annoying, I know, but hopefully only temporary.
298 //
299 // When decoding, we have to renumber the AST so that the node ids that
300 // appear within are disjoint from the node ids in our existing ASTs.
301 // We also have to adjust the spans: for now we just insert a dummy span,
302 // but eventually we should add entries to the local codemap as required.
303
304 fn encode_ast(ebml_w: &mut Encoder, item: ast::InlinedItem) {
305     ebml_w.start_tag(c::tag_tree as uint);
306     item.encode(ebml_w);
307     ebml_w.end_tag();
308 }
309
310 struct NestedItemsDropper;
311
312 impl Folder for NestedItemsDropper {
313     fn fold_block(&mut self, blk: ast::P<ast::Block>) -> ast::P<ast::Block> {
314         let stmts_sans_items = blk.stmts.iter().filter_map(|stmt| {
315             match stmt.node {
316                 ast::StmtExpr(_, _) | ast::StmtSemi(_, _) => Some(*stmt),
317                 ast::StmtDecl(decl, _) => {
318                     match decl.node {
319                         ast::DeclLocal(_) => Some(*stmt),
320                         ast::DeclItem(_) => None,
321                     }
322                 }
323                 ast::StmtMac(..) => fail!("unexpanded macro in astencode")
324             }
325         }).collect();
326         let blk_sans_items = ast::P(ast::Block {
327             view_items: Vec::new(), // I don't know if we need the view_items
328                                     // here, but it doesn't break tests!
329             stmts: stmts_sans_items,
330             expr: blk.expr,
331             id: blk.id,
332             rules: blk.rules,
333             span: blk.span,
334         });
335         fold::noop_fold_block(blk_sans_items, self)
336     }
337 }
338
339 // Produces a simplified copy of the AST which does not include things
340 // that we do not need to or do not want to export.  For example, we
341 // do not include any nested items: if these nested items are to be
342 // inlined, their AST will be exported separately (this only makes
343 // sense because, in Rust, nested items are independent except for
344 // their visibility).
345 //
346 // As it happens, trans relies on the fact that we do not export
347 // nested items, as otherwise it would get confused when translating
348 // inlined items.
349 fn simplify_ast(ii: e::InlinedItemRef) -> ast::InlinedItem {
350     let mut fld = NestedItemsDropper;
351
352     match ii {
353         // HACK we're not dropping items.
354         e::IIItemRef(i) => ast::IIItem(fold::noop_fold_item(i, &mut fld)
355                                        .expect_one("expected one item")),
356         e::IIMethodRef(d, p, m) => ast::IIMethod(d, p, fold::noop_fold_method(m, &mut fld)),
357         e::IIForeignRef(i) => ast::IIForeign(fold::noop_fold_foreign_item(i, &mut fld))
358     }
359 }
360
361 fn decode_ast(par_doc: ebml::Doc) -> ast::InlinedItem {
362     let chi_doc = par_doc.get(c::tag_tree as uint);
363     let mut d = reader::Decoder(chi_doc);
364     Decodable::decode(&mut d).unwrap()
365 }
366
367 struct AstRenumberer<'a> {
368     xcx: &'a ExtendedDecodeContext<'a>,
369 }
370
371 impl<'a> ast_map::FoldOps for AstRenumberer<'a> {
372     fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
373         if id == ast::DUMMY_NODE_ID {
374             // Used by ast_map to map the NodeInlinedParent.
375             self.xcx.dcx.tcx.sess.next_node_id()
376         } else {
377             self.xcx.tr_id(id)
378         }
379     }
380     fn new_span(&self, span: Span) -> Span {
381         self.xcx.tr_span(span)
382     }
383 }
384
385 fn renumber_and_map_ast(xcx: &ExtendedDecodeContext,
386                         map: &ast_map::Map,
387                         path: Vec<ast_map::PathElem> ,
388                         ii: ast::InlinedItem) -> ast::InlinedItem {
389     ast_map::map_decoded_item(map,
390                               path.move_iter().collect(),
391                               AstRenumberer { xcx: xcx },
392                               |fld| {
393         match ii {
394             ast::IIItem(i) => {
395                 ast::IIItem(fld.fold_item(i).expect_one("expected one item"))
396             }
397             ast::IIMethod(d, is_provided, m) => {
398                 ast::IIMethod(xcx.tr_def_id(d), is_provided, fld.fold_method(m))
399             }
400             ast::IIForeign(i) => ast::IIForeign(fld.fold_foreign_item(i))
401         }
402     })
403 }
404
405 // ______________________________________________________________________
406 // Encoding and decoding of ast::def
407
408 fn decode_def(xcx: &ExtendedDecodeContext, doc: ebml::Doc) -> ast::Def {
409     let mut dsr = reader::Decoder(doc);
410     let def: ast::Def = Decodable::decode(&mut dsr).unwrap();
411     def.tr(xcx)
412 }
413
414 impl tr for ast::Def {
415     fn tr(&self, xcx: &ExtendedDecodeContext) -> ast::Def {
416         match *self {
417           ast::DefFn(did, p) => ast::DefFn(did.tr(xcx), p),
418           ast::DefStaticMethod(did, wrapped_did2, p) => {
419             ast::DefStaticMethod(did.tr(xcx),
420                                    match wrapped_did2 {
421                                     ast::FromTrait(did2) => {
422                                         ast::FromTrait(did2.tr(xcx))
423                                     }
424                                     ast::FromImpl(did2) => {
425                                         ast::FromImpl(did2.tr(xcx))
426                                     }
427                                    },
428                                    p)
429           }
430           ast::DefMethod(did0, did1) => {
431             ast::DefMethod(did0.tr(xcx), did1.map(|did1| did1.tr(xcx)))
432           }
433           ast::DefSelfTy(nid) => { ast::DefSelfTy(xcx.tr_id(nid)) }
434           ast::DefMod(did) => { ast::DefMod(did.tr(xcx)) }
435           ast::DefForeignMod(did) => { ast::DefForeignMod(did.tr(xcx)) }
436           ast::DefStatic(did, m) => { ast::DefStatic(did.tr(xcx), m) }
437           ast::DefArg(nid, b) => { ast::DefArg(xcx.tr_id(nid), b) }
438           ast::DefLocal(nid, b) => { ast::DefLocal(xcx.tr_id(nid), b) }
439           ast::DefVariant(e_did, v_did, is_s) => {
440             ast::DefVariant(e_did.tr(xcx), v_did.tr(xcx), is_s)
441           },
442           ast::DefTrait(did) => ast::DefTrait(did.tr(xcx)),
443           ast::DefTy(did) => ast::DefTy(did.tr(xcx)),
444           ast::DefPrimTy(p) => ast::DefPrimTy(p),
445           ast::DefTyParam(did, v) => ast::DefTyParam(did.tr(xcx), v),
446           ast::DefBinding(nid, bm) => ast::DefBinding(xcx.tr_id(nid), bm),
447           ast::DefUse(did) => ast::DefUse(did.tr(xcx)),
448           ast::DefUpvar(nid1, def, nid2, nid3) => {
449             ast::DefUpvar(xcx.tr_id(nid1),
450                            @(*def).tr(xcx),
451                            xcx.tr_id(nid2),
452                            xcx.tr_id(nid3))
453           }
454           ast::DefStruct(did) => ast::DefStruct(did.tr(xcx)),
455           ast::DefRegion(nid) => ast::DefRegion(xcx.tr_id(nid)),
456           ast::DefTyParamBinder(nid) => {
457             ast::DefTyParamBinder(xcx.tr_id(nid))
458           }
459           ast::DefLabel(nid) => ast::DefLabel(xcx.tr_id(nid))
460         }
461     }
462 }
463
464 // ______________________________________________________________________
465 // Encoding and decoding of adjustment information
466
467 impl tr for ty::AutoDerefRef {
468     fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::AutoDerefRef {
469         ty::AutoDerefRef {
470             autoderefs: self.autoderefs,
471             autoref: match self.autoref {
472                 Some(ref autoref) => Some(autoref.tr(xcx)),
473                 None => None
474             }
475         }
476     }
477 }
478
479 impl tr for ty::AutoRef {
480     fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::AutoRef {
481         self.map_region(|r| r.tr(xcx))
482     }
483 }
484
485 impl tr for ty::Region {
486     fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::Region {
487         match *self {
488             ty::ReLateBound(id, br) => ty::ReLateBound(xcx.tr_id(id),
489                                                        br.tr(xcx)),
490             ty::ReEarlyBound(id, index, ident) => ty::ReEarlyBound(xcx.tr_id(id),
491                                                                      index,
492                                                                      ident),
493             ty::ReScope(id) => ty::ReScope(xcx.tr_id(id)),
494             ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => *self,
495             ty::ReFree(ref fr) => {
496                 ty::ReFree(ty::FreeRegion {scope_id: xcx.tr_id(fr.scope_id),
497                                             bound_region: fr.bound_region.tr(xcx)})
498             }
499         }
500     }
501 }
502
503 impl tr for ty::BoundRegion {
504     fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::BoundRegion {
505         match *self {
506             ty::BrAnon(_) |
507             ty::BrFresh(_) => *self,
508             ty::BrNamed(id, ident) => ty::BrNamed(xcx.tr_def_id(id),
509                                                     ident),
510         }
511     }
512 }
513
514 impl tr for ty::TraitStore {
515     fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::TraitStore {
516         match *self {
517             ty::RegionTraitStore(r, m) => {
518                 ty::RegionTraitStore(r.tr(xcx), m)
519             }
520             ty::UniqTraitStore => ty::UniqTraitStore
521         }
522     }
523 }
524
525 // ______________________________________________________________________
526 // Encoding and decoding of freevar information
527
528 fn encode_freevar_entry(ebml_w: &mut Encoder, fv: &freevar_entry) {
529     (*fv).encode(ebml_w).unwrap();
530 }
531
532 trait ebml_decoder_helper {
533     fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
534                           -> freevar_entry;
535 }
536
537 impl<'a> ebml_decoder_helper for reader::Decoder<'a> {
538     fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
539                           -> freevar_entry {
540         let fv: freevar_entry = Decodable::decode(self).unwrap();
541         fv.tr(xcx)
542     }
543 }
544
545 impl tr for freevar_entry {
546     fn tr(&self, xcx: &ExtendedDecodeContext) -> freevar_entry {
547         freevar_entry {
548             def: self.def.tr(xcx),
549             span: self.span.tr(xcx),
550         }
551     }
552 }
553
554 // ______________________________________________________________________
555 // Encoding and decoding of CaptureVar information
556
557 trait capture_var_helper {
558     fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
559                         -> moves::CaptureVar;
560 }
561
562 impl<'a> capture_var_helper for reader::Decoder<'a> {
563     fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
564                         -> moves::CaptureVar {
565         let cvar: moves::CaptureVar = Decodable::decode(self).unwrap();
566         cvar.tr(xcx)
567     }
568 }
569
570 impl tr for moves::CaptureVar {
571     fn tr(&self, xcx: &ExtendedDecodeContext) -> moves::CaptureVar {
572         moves::CaptureVar {
573             def: self.def.tr(xcx),
574             span: self.span.tr(xcx),
575             mode: self.mode
576         }
577     }
578 }
579
580 // ______________________________________________________________________
581 // Encoding and decoding of MethodCallee
582
583 trait read_method_callee_helper {
584     fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee);
585 }
586
587 fn encode_method_callee(ecx: &e::EncodeContext,
588                         ebml_w: &mut Encoder,
589                         autoderef: u32,
590                         method: &MethodCallee) {
591     ebml_w.emit_struct("MethodCallee", 4, |ebml_w| {
592         ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
593             autoderef.encode(ebml_w)
594         });
595         ebml_w.emit_struct_field("origin", 1u, |ebml_w| {
596             method.origin.encode(ebml_w)
597         });
598         ebml_w.emit_struct_field("ty", 2u, |ebml_w| {
599             Ok(ebml_w.emit_ty(ecx, method.ty))
600         });
601         ebml_w.emit_struct_field("substs", 3u, |ebml_w| {
602             Ok(ebml_w.emit_substs(ecx, &method.substs))
603         })
604     }).unwrap();
605 }
606
607 impl<'a> read_method_callee_helper for reader::Decoder<'a> {
608     fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee) {
609         self.read_struct("MethodCallee", 4, |this| {
610             let autoderef = this.read_struct_field("autoderef", 0, |this| {
611                 Decodable::decode(this)
612             }).unwrap();
613             Ok((autoderef, MethodCallee {
614                 origin: this.read_struct_field("origin", 1, |this| {
615                     let method_origin: MethodOrigin =
616                         Decodable::decode(this).unwrap();
617                     Ok(method_origin.tr(xcx))
618                 }).unwrap(),
619                 ty: this.read_struct_field("ty", 2, |this| {
620                     Ok(this.read_ty(xcx))
621                 }).unwrap(),
622                 substs: this.read_struct_field("substs", 3, |this| {
623                     Ok(this.read_substs(xcx))
624                 }).unwrap()
625             }))
626         }).unwrap()
627     }
628 }
629
630 impl tr for MethodOrigin {
631     fn tr(&self, xcx: &ExtendedDecodeContext) -> MethodOrigin {
632         match *self {
633             typeck::MethodStatic(did) => typeck::MethodStatic(did.tr(xcx)),
634             typeck::MethodParam(ref mp) => {
635                 typeck::MethodParam(
636                     typeck::MethodParam {
637                         trait_id: mp.trait_id.tr(xcx),
638                         .. *mp
639                     }
640                 )
641             }
642             typeck::MethodObject(ref mo) => {
643                 typeck::MethodObject(
644                     typeck::MethodObject {
645                         trait_id: mo.trait_id.tr(xcx),
646                         .. *mo
647                     }
648                 )
649             }
650         }
651     }
652 }
653
654 // ______________________________________________________________________
655 // Encoding and decoding vtable_res
656
657 fn encode_vtable_res_with_key(ecx: &e::EncodeContext,
658                               ebml_w: &mut Encoder,
659                               autoderef: u32,
660                               dr: &typeck::vtable_res) {
661     ebml_w.emit_struct("VtableWithKey", 2, |ebml_w| {
662         ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
663             autoderef.encode(ebml_w)
664         });
665         ebml_w.emit_struct_field("vtable_res", 1u, |ebml_w| {
666             Ok(encode_vtable_res(ecx, ebml_w, dr))
667         })
668     }).unwrap()
669 }
670
671 pub fn encode_vtable_res(ecx: &e::EncodeContext,
672                      ebml_w: &mut Encoder,
673                      dr: &typeck::vtable_res) {
674     // can't autogenerate this code because automatic code of
675     // ty::t doesn't work, and there is no way (atm) to have
676     // hand-written encoding routines combine with auto-generated
677     // ones.  perhaps we should fix this.
678     ebml_w.emit_from_vec(dr.as_slice(), |ebml_w, param_tables| {
679         Ok(encode_vtable_param_res(ecx, ebml_w, param_tables))
680     }).unwrap()
681 }
682
683 pub fn encode_vtable_param_res(ecx: &e::EncodeContext,
684                      ebml_w: &mut Encoder,
685                      param_tables: &typeck::vtable_param_res) {
686     ebml_w.emit_from_vec(param_tables.as_slice(), |ebml_w, vtable_origin| {
687         Ok(encode_vtable_origin(ecx, ebml_w, vtable_origin))
688     }).unwrap()
689 }
690
691
692 pub fn encode_vtable_origin(ecx: &e::EncodeContext,
693                         ebml_w: &mut Encoder,
694                         vtable_origin: &typeck::vtable_origin) {
695     ebml_w.emit_enum("vtable_origin", |ebml_w| {
696         match *vtable_origin {
697           typeck::vtable_static(def_id, ref tys, ref vtable_res) => {
698             ebml_w.emit_enum_variant("vtable_static", 0u, 3u, |ebml_w| {
699                 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
700                     Ok(ebml_w.emit_def_id(def_id))
701                 });
702                 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
703                     Ok(ebml_w.emit_tys(ecx, tys.as_slice()))
704                 });
705                 ebml_w.emit_enum_variant_arg(2u, |ebml_w| {
706                     Ok(encode_vtable_res(ecx, ebml_w, vtable_res))
707                 })
708             })
709           }
710           typeck::vtable_param(pn, bn) => {
711             ebml_w.emit_enum_variant("vtable_param", 1u, 2u, |ebml_w| {
712                 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
713                     pn.encode(ebml_w)
714                 });
715                 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
716                     ebml_w.emit_uint(bn)
717                 })
718             })
719           }
720         }
721     }).unwrap()
722 }
723
724 pub trait vtable_decoder_helpers {
725     fn read_vtable_res_with_key(&mut self,
726                                 tcx: &ty::ctxt,
727                                 cdata: &cstore::crate_metadata)
728                                 -> (u32, typeck::vtable_res);
729     fn read_vtable_res(&mut self,
730                        tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
731                       -> typeck::vtable_res;
732     fn read_vtable_param_res(&mut self,
733                        tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
734                       -> typeck::vtable_param_res;
735     fn read_vtable_origin(&mut self,
736                           tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
737                           -> typeck::vtable_origin;
738 }
739
740 impl<'a> vtable_decoder_helpers for reader::Decoder<'a> {
741     fn read_vtable_res_with_key(&mut self,
742                                 tcx: &ty::ctxt,
743                                 cdata: &cstore::crate_metadata)
744                                 -> (u32, typeck::vtable_res) {
745         self.read_struct("VtableWithKey", 2, |this| {
746             let autoderef = this.read_struct_field("autoderef", 0, |this| {
747                 Decodable::decode(this)
748             }).unwrap();
749             Ok((autoderef, this.read_struct_field("vtable_res", 1, |this| {
750                 Ok(this.read_vtable_res(tcx, cdata))
751             }).unwrap()))
752         }).unwrap()
753     }
754
755     fn read_vtable_res(&mut self,
756                        tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
757                       -> typeck::vtable_res {
758         self.read_to_vec(|this| Ok(this.read_vtable_param_res(tcx, cdata)))
759              .unwrap().move_iter().collect()
760     }
761
762     fn read_vtable_param_res(&mut self,
763                              tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
764                       -> typeck::vtable_param_res {
765         self.read_to_vec(|this| Ok(this.read_vtable_origin(tcx, cdata)))
766              .unwrap().move_iter().collect()
767     }
768
769     fn read_vtable_origin(&mut self,
770                           tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
771         -> typeck::vtable_origin {
772         self.read_enum("vtable_origin", |this| {
773             this.read_enum_variant(["vtable_static",
774                                     "vtable_param",
775                                     "vtable_self"],
776                                    |this, i| {
777                 Ok(match i {
778                   0 => {
779                     typeck::vtable_static(
780                         this.read_enum_variant_arg(0u, |this| {
781                             Ok(this.read_def_id_noxcx(cdata))
782                         }).unwrap(),
783                         this.read_enum_variant_arg(1u, |this| {
784                             Ok(this.read_tys_noxcx(tcx, cdata))
785                         }).unwrap(),
786                         this.read_enum_variant_arg(2u, |this| {
787                             Ok(this.read_vtable_res(tcx, cdata))
788                         }).unwrap()
789                     )
790                   }
791                   1 => {
792                     typeck::vtable_param(
793                         this.read_enum_variant_arg(0u, |this| {
794                             Decodable::decode(this)
795                         }).unwrap(),
796                         this.read_enum_variant_arg(1u, |this| {
797                             this.read_uint()
798                         }).unwrap()
799                     )
800                   }
801                   // hard to avoid - user input
802                   _ => fail!("bad enum variant")
803                 })
804             })
805         }).unwrap()
806     }
807 }
808
809 // ______________________________________________________________________
810 // Encoding and decoding the side tables
811
812 trait get_ty_str_ctxt {
813     fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a>;
814 }
815
816 impl<'a> get_ty_str_ctxt for e::EncodeContext<'a> {
817     fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a> {
818         tyencode::ctxt {
819             diag: self.tcx.sess.diagnostic(),
820             ds: e::def_to_str,
821             tcx: self.tcx,
822             abbrevs: &self.type_abbrevs
823         }
824     }
825 }
826
827 trait ebml_writer_helpers {
828     fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t);
829     fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]);
830     fn emit_type_param_def(&mut self,
831                            ecx: &e::EncodeContext,
832                            type_param_def: &ty::TypeParameterDef);
833     fn emit_tpbt(&mut self,
834                  ecx: &e::EncodeContext,
835                  tpbt: ty::ty_param_bounds_and_ty);
836     fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs);
837     fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment);
838 }
839
840 impl<'a> ebml_writer_helpers for Encoder<'a> {
841     fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t) {
842         self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
843     }
844
845     fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]) {
846         self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
847     }
848
849     fn emit_type_param_def(&mut self,
850                            ecx: &e::EncodeContext,
851                            type_param_def: &ty::TypeParameterDef) {
852         self.emit_opaque(|this| {
853             Ok(tyencode::enc_type_param_def(this.writer,
854                                          &ecx.ty_str_ctxt(),
855                                          type_param_def))
856         });
857     }
858
859     fn emit_tpbt(&mut self,
860                  ecx: &e::EncodeContext,
861                  tpbt: ty::ty_param_bounds_and_ty) {
862         self.emit_struct("ty_param_bounds_and_ty", 2, |this| {
863             this.emit_struct_field("generics", 0, |this| {
864                 this.emit_struct("Generics", 2, |this| {
865                     this.emit_struct_field("type_param_defs", 0, |this| {
866                         this.emit_from_vec(tpbt.generics.type_param_defs(),
867                                            |this, type_param_def| {
868                             Ok(this.emit_type_param_def(ecx, type_param_def))
869                         })
870                     });
871                     this.emit_struct_field("region_param_defs", 1, |this| {
872                         tpbt.generics.region_param_defs().encode(this)
873                     })
874                 })
875             });
876             this.emit_struct_field("ty", 1, |this| {
877                 Ok(this.emit_ty(ecx, tpbt.ty))
878             })
879         });
880     }
881
882     fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs) {
883         self.emit_opaque(|this| Ok(tyencode::enc_substs(this.writer,
884                                                            &ecx.ty_str_ctxt(),
885                                                            substs)));
886     }
887
888     fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment) {
889         self.emit_enum("AutoAdjustment", |this| {
890             match *adj {
891                 ty::AutoAddEnv(store) => {
892                     this.emit_enum_variant("AutoAddEnv", 0, 1, |this| {
893                         this.emit_enum_variant_arg(0, |this| store.encode(this))
894                     })
895                 }
896
897                 ty::AutoDerefRef(ref auto_deref_ref) => {
898                     this.emit_enum_variant("AutoDerefRef", 1, 1, |this| {
899                         this.emit_enum_variant_arg(0, |this| auto_deref_ref.encode(this))
900                     })
901                 }
902
903                 ty::AutoObject(store, b, def_id, ref substs) => {
904                     this.emit_enum_variant("AutoObject", 2, 4, |this| {
905                         this.emit_enum_variant_arg(0, |this| store.encode(this));
906                         this.emit_enum_variant_arg(1, |this| b.encode(this));
907                         this.emit_enum_variant_arg(2, |this| def_id.encode(this));
908                         this.emit_enum_variant_arg(3, |this| Ok(this.emit_substs(ecx, substs)))
909                     })
910                 }
911             }
912         });
913     }
914 }
915
916 trait write_tag_and_id {
917     fn tag(&mut self, tag_id: c::astencode_tag, f: |&mut Self|);
918     fn id(&mut self, id: ast::NodeId);
919 }
920
921 impl<'a> write_tag_and_id for Encoder<'a> {
922     fn tag(&mut self,
923            tag_id: c::astencode_tag,
924            f: |&mut Encoder<'a>|) {
925         self.start_tag(tag_id as uint);
926         f(self);
927         self.end_tag();
928     }
929
930     fn id(&mut self, id: ast::NodeId) {
931         self.wr_tagged_u64(c::tag_table_id as uint, id as u64);
932     }
933 }
934
935 struct SideTableEncodingIdVisitor<'a,'b> {
936     ecx_ptr: *libc::c_void,
937     new_ebml_w: &'a mut Encoder<'b>,
938     maps: &'a Maps,
939 }
940
941 impl<'a,'b> ast_util::IdVisitingOperation for
942         SideTableEncodingIdVisitor<'a,'b> {
943     fn visit_id(&self, id: ast::NodeId) {
944         // Note: this will cause a copy of ebml_w, which is bad as
945         // it is mutable. But I believe it's harmless since we generate
946         // balanced EBML.
947         //
948         // FIXME(pcwalton): Don't copy this way.
949         let mut new_ebml_w = unsafe {
950             self.new_ebml_w.unsafe_clone()
951         };
952         // See above
953         let ecx: &e::EncodeContext = unsafe {
954             cast::transmute(self.ecx_ptr)
955         };
956         encode_side_tables_for_id(ecx, self.maps, &mut new_ebml_w, id)
957     }
958 }
959
960 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
961                              maps: &Maps,
962                              ebml_w: &mut Encoder,
963                              ii: &ast::InlinedItem) {
964     ebml_w.start_tag(c::tag_table as uint);
965     let mut new_ebml_w = unsafe {
966         ebml_w.unsafe_clone()
967     };
968
969     // Because the ast visitor uses @IdVisitingOperation, I can't pass in
970     // ecx directly, but /I/ know that it'll be fine since the lifetime is
971     // tied to the CrateContext that lives throughout this entire section.
972     ast_util::visit_ids_for_inlined_item(ii, &SideTableEncodingIdVisitor {
973         ecx_ptr: unsafe {
974             cast::transmute(ecx)
975         },
976         new_ebml_w: &mut new_ebml_w,
977         maps: maps,
978     });
979     ebml_w.end_tag();
980 }
981
982 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
983                              maps: &Maps,
984                              ebml_w: &mut Encoder,
985                              id: ast::NodeId) {
986     let tcx = ecx.tcx;
987
988     debug!("Encoding side tables for id {}", id);
989
990     for def in tcx.def_map.borrow().find(&id).iter() {
991         ebml_w.tag(c::tag_table_def, |ebml_w| {
992             ebml_w.id(id);
993             ebml_w.tag(c::tag_table_val, |ebml_w| (*def).encode(ebml_w).unwrap());
994         })
995     }
996
997     for &ty in tcx.node_types.borrow().find(&(id as uint)).iter() {
998         ebml_w.tag(c::tag_table_node_type, |ebml_w| {
999             ebml_w.id(id);
1000             ebml_w.tag(c::tag_table_val, |ebml_w| {
1001                 ebml_w.emit_ty(ecx, *ty);
1002             })
1003         })
1004     }
1005
1006     for tys in tcx.node_type_substs.borrow().find(&id).iter() {
1007         ebml_w.tag(c::tag_table_node_type_subst, |ebml_w| {
1008             ebml_w.id(id);
1009             ebml_w.tag(c::tag_table_val, |ebml_w| {
1010                 ebml_w.emit_tys(ecx, tys.as_slice())
1011             })
1012         })
1013     }
1014
1015     for &fv in tcx.freevars.borrow().find(&id).iter() {
1016         ebml_w.tag(c::tag_table_freevars, |ebml_w| {
1017             ebml_w.id(id);
1018             ebml_w.tag(c::tag_table_val, |ebml_w| {
1019                 ebml_w.emit_from_vec(fv.as_slice(), |ebml_w, fv_entry| {
1020                     Ok(encode_freevar_entry(ebml_w, fv_entry))
1021                 });
1022             })
1023         })
1024     }
1025
1026     let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1027     for &tpbt in tcx.tcache.borrow().find(&lid).iter() {
1028         ebml_w.tag(c::tag_table_tcache, |ebml_w| {
1029             ebml_w.id(id);
1030             ebml_w.tag(c::tag_table_val, |ebml_w| {
1031                 ebml_w.emit_tpbt(ecx, tpbt.clone());
1032             })
1033         })
1034     }
1035
1036     for &type_param_def in tcx.ty_param_defs.borrow().find(&id).iter() {
1037         ebml_w.tag(c::tag_table_param_defs, |ebml_w| {
1038             ebml_w.id(id);
1039             ebml_w.tag(c::tag_table_val, |ebml_w| {
1040                 ebml_w.emit_type_param_def(ecx, type_param_def)
1041             })
1042         })
1043     }
1044
1045     let method_call = MethodCall::expr(id);
1046     for &method in tcx.method_map.borrow().find(&method_call).iter() {
1047         ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1048             ebml_w.id(id);
1049             ebml_w.tag(c::tag_table_val, |ebml_w| {
1050                 encode_method_callee(ecx, ebml_w, method_call.autoderef, method)
1051             })
1052         })
1053     }
1054
1055     for &dr in tcx.vtable_map.borrow().find(&method_call).iter() {
1056         ebml_w.tag(c::tag_table_vtable_map, |ebml_w| {
1057             ebml_w.id(id);
1058             ebml_w.tag(c::tag_table_val, |ebml_w| {
1059                 encode_vtable_res_with_key(ecx, ebml_w, method_call.autoderef, dr);
1060             })
1061         })
1062     }
1063
1064     for &adj in tcx.adjustments.borrow().find(&id).iter() {
1065         match *adj {
1066             ty::AutoDerefRef(adj) => {
1067                 for autoderef in range(0, adj.autoderefs) {
1068                     let method_call = MethodCall::autoderef(id, autoderef as u32);
1069                     for &method in tcx.method_map.borrow().find(&method_call).iter() {
1070                         ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1071                             ebml_w.id(id);
1072                             ebml_w.tag(c::tag_table_val, |ebml_w| {
1073                                 encode_method_callee(ecx, ebml_w, method_call.autoderef, method)
1074                             })
1075                         })
1076                     }
1077
1078                     for &dr in tcx.vtable_map.borrow().find(&method_call).iter() {
1079                         ebml_w.tag(c::tag_table_vtable_map, |ebml_w| {
1080                             ebml_w.id(id);
1081                             ebml_w.tag(c::tag_table_val, |ebml_w| {
1082                                 encode_vtable_res_with_key(ecx, ebml_w,
1083                                                            method_call.autoderef, dr);
1084                             })
1085                         })
1086                     }
1087                 }
1088             }
1089             _ => {}
1090         }
1091
1092         ebml_w.tag(c::tag_table_adjustments, |ebml_w| {
1093             ebml_w.id(id);
1094             ebml_w.tag(c::tag_table_val, |ebml_w| {
1095                 ebml_w.emit_auto_adjustment(ecx, adj);
1096             })
1097         })
1098     }
1099
1100     for &cap_vars in maps.capture_map.borrow().find(&id).iter() {
1101         ebml_w.tag(c::tag_table_capture_map, |ebml_w| {
1102             ebml_w.id(id);
1103             ebml_w.tag(c::tag_table_val, |ebml_w| {
1104                 ebml_w.emit_from_vec(cap_vars.as_slice(), |ebml_w, cap_var| {
1105                     cap_var.encode(ebml_w)
1106                 });
1107             })
1108         })
1109     }
1110 }
1111
1112 trait doc_decoder_helpers {
1113     fn as_int(&self) -> int;
1114     fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1115 }
1116
1117 impl<'a> doc_decoder_helpers for ebml::Doc<'a> {
1118     fn as_int(&self) -> int { reader::doc_as_u64(*self) as int }
1119     fn opt_child(&self, tag: c::astencode_tag) -> Option<ebml::Doc<'a>> {
1120         reader::maybe_get_doc(*self, tag as uint)
1121     }
1122 }
1123
1124 trait ebml_decoder_decoder_helpers {
1125     fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t;
1126     fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t>;
1127     fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
1128                            -> ty::TypeParameterDef;
1129     fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
1130                                 -> ty::ty_param_bounds_and_ty;
1131     fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs;
1132     fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment;
1133     fn convert_def_id(&mut self,
1134                       xcx: &ExtendedDecodeContext,
1135                       source: DefIdSource,
1136                       did: ast::DefId)
1137                       -> ast::DefId;
1138
1139     // Versions of the type reading functions that don't need the full
1140     // ExtendedDecodeContext.
1141     fn read_ty_noxcx(&mut self,
1142                      tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> ty::t;
1143     fn read_tys_noxcx(&mut self,
1144                       tcx: &ty::ctxt,
1145                       cdata: &cstore::crate_metadata) -> Vec<ty::t>;
1146 }
1147
1148 impl<'a> ebml_decoder_decoder_helpers for reader::Decoder<'a> {
1149     fn read_ty_noxcx(&mut self,
1150                      tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> ty::t {
1151         self.read_opaque(|_, doc| {
1152             Ok(tydecode::parse_ty_data(
1153                 doc.data,
1154                 cdata.cnum,
1155                 doc.start,
1156                 tcx,
1157                 |_, id| decoder::translate_def_id(cdata, id)))
1158         }).unwrap()
1159     }
1160
1161     fn read_tys_noxcx(&mut self,
1162                       tcx: &ty::ctxt,
1163                       cdata: &cstore::crate_metadata) -> Vec<ty::t> {
1164         self.read_to_vec(|this| Ok(this.read_ty_noxcx(tcx, cdata)) )
1165             .unwrap()
1166             .move_iter()
1167             .collect()
1168     }
1169
1170     fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t {
1171         // Note: regions types embed local node ids.  In principle, we
1172         // should translate these node ids into the new decode
1173         // context.  However, we do not bother, because region types
1174         // are not used during trans.
1175
1176         return self.read_opaque(|this, doc| {
1177             debug!("read_ty({})", type_string(doc));
1178
1179             let ty = tydecode::parse_ty_data(
1180                 doc.data,
1181                 xcx.dcx.cdata.cnum,
1182                 doc.start,
1183                 xcx.dcx.tcx,
1184                 |s, a| this.convert_def_id(xcx, s, a));
1185
1186             Ok(ty)
1187         }).unwrap();
1188
1189         fn type_string(doc: ebml::Doc) -> ~str {
1190             let mut str = StrBuf::new();
1191             for i in range(doc.start, doc.end) {
1192                 str.push_char(doc.data[i] as char);
1193             }
1194             str.into_owned()
1195         }
1196     }
1197
1198     fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t> {
1199         self.read_to_vec(|this| Ok(this.read_ty(xcx))).unwrap().move_iter().collect()
1200     }
1201
1202     fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
1203                            -> ty::TypeParameterDef {
1204         self.read_opaque(|this, doc| {
1205             Ok(tydecode::parse_type_param_def_data(
1206                 doc.data,
1207                 doc.start,
1208                 xcx.dcx.cdata.cnum,
1209                 xcx.dcx.tcx,
1210                 |s, a| this.convert_def_id(xcx, s, a)))
1211         }).unwrap()
1212     }
1213
1214     fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
1215                                    -> ty::ty_param_bounds_and_ty {
1216         self.read_struct("ty_param_bounds_and_ty", 2, |this| {
1217             Ok(ty::ty_param_bounds_and_ty {
1218                 generics: this.read_struct_field("generics", 0, |this| {
1219                     this.read_struct("Generics", 2, |this| {
1220                         Ok(ty::Generics {
1221                             type_param_defs:
1222                                 this.read_struct_field("type_param_defs",
1223                                                        0,
1224                                                        |this| {
1225                                     Ok(Rc::new(this.read_to_vec(|this|
1226                                                              Ok(this.read_type_param_def(xcx)))
1227                                                 .unwrap()
1228                                                 .move_iter()
1229                                                 .collect()))
1230                             }).unwrap(),
1231                             region_param_defs:
1232                                 this.read_struct_field("region_param_defs",
1233                                                        1,
1234                                                        |this| {
1235                                     Decodable::decode(this)
1236                                 }).unwrap()
1237                         })
1238                     })
1239                 }).unwrap(),
1240                 ty: this.read_struct_field("ty", 1, |this| {
1241                     Ok(this.read_ty(xcx))
1242                 }).unwrap()
1243             })
1244         }).unwrap()
1245     }
1246
1247     fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs {
1248         self.read_opaque(|this, doc| {
1249             Ok(tydecode::parse_substs_data(doc.data,
1250                                         xcx.dcx.cdata.cnum,
1251                                         doc.start,
1252                                         xcx.dcx.tcx,
1253                                         |s, a| this.convert_def_id(xcx, s, a)))
1254         }).unwrap()
1255     }
1256
1257     fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment {
1258         self.read_enum("AutoAdjustment", |this| {
1259             let variants = ["AutoAddEnv", "AutoDerefRef", "AutoObject"];
1260             this.read_enum_variant(variants, |this, i| {
1261                 Ok(match i {
1262                     0 => {
1263                         let store: ty::TraitStore =
1264                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1265
1266                         ty:: AutoAddEnv(store.tr(xcx))
1267                     }
1268                     1 => {
1269                         let auto_deref_ref: ty::AutoDerefRef =
1270                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1271
1272                         ty::AutoDerefRef(auto_deref_ref.tr(xcx))
1273                     }
1274                     2 => {
1275                         let store: ty::TraitStore =
1276                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1277                         let b: ty::BuiltinBounds =
1278                             this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1279                         let def_id: ast::DefId =
1280                             this.read_enum_variant_arg(2, |this| Decodable::decode(this)).unwrap();
1281                         let substs = this.read_enum_variant_arg(3, |this| Ok(this.read_substs(xcx)))
1282                                     .unwrap();
1283
1284                         ty::AutoObject(store.tr(xcx), b, def_id.tr(xcx), substs)
1285                     }
1286                     _ => fail!("bad enum variant for ty::AutoAdjustment")
1287                 })
1288             })
1289         }).unwrap()
1290     }
1291
1292     fn convert_def_id(&mut self,
1293                       xcx: &ExtendedDecodeContext,
1294                       source: tydecode::DefIdSource,
1295                       did: ast::DefId)
1296                       -> ast::DefId {
1297         /*!
1298          * Converts a def-id that appears in a type.  The correct
1299          * translation will depend on what kind of def-id this is.
1300          * This is a subtle point: type definitions are not
1301          * inlined into the current crate, so if the def-id names
1302          * a nominal type or type alias, then it should be
1303          * translated to refer to the source crate.
1304          *
1305          * However, *type parameters* are cloned along with the function
1306          * they are attached to.  So we should translate those def-ids
1307          * to refer to the new, cloned copy of the type parameter.
1308          * We only see references to free type parameters in the body of
1309          * an inlined function. In such cases, we need the def-id to
1310          * be a local id so that the TypeContents code is able to lookup
1311          * the relevant info in the ty_param_defs table.
1312          *
1313          * *Region parameters*, unfortunately, are another kettle of fish.
1314          * In such cases, def_id's can appear in types to distinguish
1315          * shadowed bound regions and so forth. It doesn't actually
1316          * matter so much what we do to these, since regions are erased
1317          * at trans time, but it's good to keep them consistent just in
1318          * case. We translate them with `tr_def_id()` which will map
1319          * the crate numbers back to the original source crate.
1320          *
1321          * It'd be really nice to refactor the type repr to not include
1322          * def-ids so that all these distinctions were unnecessary.
1323          */
1324
1325         let r = match source {
1326             NominalType | TypeWithId | RegionParameter => xcx.tr_def_id(did),
1327             TypeParameter => xcx.tr_intern_def_id(did)
1328         };
1329         debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1330         return r;
1331     }
1332 }
1333
1334 fn decode_side_tables(xcx: &ExtendedDecodeContext,
1335                       ast_doc: ebml::Doc) {
1336     let dcx = xcx.dcx;
1337     let tbl_doc = ast_doc.get(c::tag_table as uint);
1338     reader::docs(tbl_doc, |tag, entry_doc| {
1339         let id0 = entry_doc.get(c::tag_table_id as uint).as_int();
1340         let id = xcx.tr_id(id0 as ast::NodeId);
1341
1342         debug!(">> Side table document with tag 0x{:x} \
1343                 found for id {} (orig {})",
1344                tag, id, id0);
1345
1346         match c::astencode_tag::from_uint(tag) {
1347             None => {
1348                 xcx.dcx.tcx.sess.bug(
1349                     format!("unknown tag found in side tables: {:x}", tag));
1350             }
1351             Some(value) => {
1352                 let val_doc = entry_doc.get(c::tag_table_val as uint);
1353                 let mut val_dsr = reader::Decoder(val_doc);
1354                 let val_dsr = &mut val_dsr;
1355
1356                 match value {
1357                     c::tag_table_def => {
1358                         let def = decode_def(xcx, val_doc);
1359                         dcx.tcx.def_map.borrow_mut().insert(id, def);
1360                     }
1361                     c::tag_table_node_type => {
1362                         let ty = val_dsr.read_ty(xcx);
1363                         debug!("inserting ty for node {:?}: {}",
1364                                id, ty_to_str(dcx.tcx, ty));
1365                         dcx.tcx.node_types.borrow_mut().insert(id as uint, ty);
1366                     }
1367                     c::tag_table_node_type_subst => {
1368                         let tys = val_dsr.read_tys(xcx);
1369                         dcx.tcx.node_type_substs.borrow_mut().insert(id, tys);
1370                     }
1371                     c::tag_table_freevars => {
1372                         let fv_info = val_dsr.read_to_vec(|val_dsr| {
1373                             Ok(val_dsr.read_freevar_entry(xcx))
1374                         }).unwrap().move_iter().collect();
1375                         dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1376                     }
1377                     c::tag_table_tcache => {
1378                         let tpbt = val_dsr.read_ty_param_bounds_and_ty(xcx);
1379                         let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1380                         dcx.tcx.tcache.borrow_mut().insert(lid, tpbt);
1381                     }
1382                     c::tag_table_param_defs => {
1383                         let bounds = val_dsr.read_type_param_def(xcx);
1384                         dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1385                     }
1386                     c::tag_table_method_map => {
1387                         let (autoderef, method) = val_dsr.read_method_callee(xcx);
1388                         let method_call = MethodCall {
1389                             expr_id: id,
1390                             autoderef: autoderef
1391                         };
1392                         dcx.tcx.method_map.borrow_mut().insert(method_call, method);
1393                     }
1394                     c::tag_table_vtable_map => {
1395                         let (autoderef, vtable_res) =
1396                             val_dsr.read_vtable_res_with_key(xcx.dcx.tcx,
1397                                                              xcx.dcx.cdata);
1398                         let vtable_key = MethodCall {
1399                             expr_id: id,
1400                             autoderef: autoderef
1401                         };
1402                         dcx.tcx.vtable_map.borrow_mut().insert(vtable_key, vtable_res);
1403                     }
1404                     c::tag_table_adjustments => {
1405                         let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(xcx);
1406                         dcx.tcx.adjustments.borrow_mut().insert(id, adj);
1407                     }
1408                     c::tag_table_capture_map => {
1409                         let cvars =
1410                                 val_dsr.read_to_vec(
1411                                             |val_dsr| Ok(val_dsr.read_capture_var(xcx)))
1412                                        .unwrap()
1413                                        .move_iter()
1414                                        .collect();
1415                         dcx.maps.capture_map.borrow_mut().insert(id, Rc::new(cvars));
1416                     }
1417                     _ => {
1418                         xcx.dcx.tcx.sess.bug(
1419                             format!("unknown tag found in side tables: {:x}", tag));
1420                     }
1421                 }
1422             }
1423         }
1424
1425         debug!(">< Side table doc loaded");
1426         true
1427     });
1428 }
1429
1430 // ______________________________________________________________________
1431 // Testing of astencode_gen
1432
1433 #[cfg(test)]
1434 fn encode_item_ast(ebml_w: &mut Encoder, item: @ast::Item) {
1435     ebml_w.start_tag(c::tag_tree as uint);
1436     (*item).encode(ebml_w);
1437     ebml_w.end_tag();
1438 }
1439
1440 #[cfg(test)]
1441 fn decode_item_ast(par_doc: ebml::Doc) -> @ast::Item {
1442     let chi_doc = par_doc.get(c::tag_tree as uint);
1443     let mut d = reader::Decoder(chi_doc);
1444     @Decodable::decode(&mut d).unwrap()
1445 }
1446
1447 #[cfg(test)]
1448 trait fake_ext_ctxt {
1449     fn cfg(&self) -> ast::CrateConfig;
1450     fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess;
1451     fn call_site(&self) -> Span;
1452     fn ident_of(&self, st: &str) -> ast::Ident;
1453 }
1454
1455 #[cfg(test)]
1456 impl fake_ext_ctxt for parse::ParseSess {
1457     fn cfg(&self) -> ast::CrateConfig {
1458         Vec::new()
1459     }
1460     fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { self }
1461     fn call_site(&self) -> Span {
1462         codemap::Span {
1463             lo: codemap::BytePos(0),
1464             hi: codemap::BytePos(0),
1465             expn_info: None
1466         }
1467     }
1468     fn ident_of(&self, st: &str) -> ast::Ident {
1469         token::str_to_ident(st)
1470     }
1471 }
1472
1473 #[cfg(test)]
1474 fn mk_ctxt() -> parse::ParseSess {
1475     parse::new_parse_sess()
1476 }
1477
1478 #[cfg(test)]
1479 fn roundtrip(in_item: Option<@ast::Item>) {
1480     use std::io::MemWriter;
1481
1482     let in_item = in_item.unwrap();
1483     let mut wr = MemWriter::new();
1484     {
1485         let mut ebml_w = writer::Encoder(&mut wr);
1486         encode_item_ast(&mut ebml_w, in_item);
1487     }
1488     let ebml_doc = reader::Doc(wr.get_ref());
1489     let out_item = decode_item_ast(ebml_doc);
1490
1491     assert!(in_item == out_item);
1492 }
1493
1494 #[test]
1495 fn test_basic() {
1496     let cx = mk_ctxt();
1497     roundtrip(quote_item!(cx,
1498         fn foo() {}
1499     ));
1500 }
1501
1502 #[test]
1503 fn test_smalltalk() {
1504     let cx = mk_ctxt();
1505     roundtrip(quote_item!(cx,
1506         fn foo() -> int { 3 + 4 } // first smalltalk program ever executed.
1507     ));
1508 }
1509
1510 #[test]
1511 fn test_more() {
1512     let cx = mk_ctxt();
1513     roundtrip(quote_item!(cx,
1514         fn foo(x: uint, y: uint) -> uint {
1515             let z = x + y;
1516             return z;
1517         }
1518     ));
1519 }
1520
1521 #[test]
1522 fn test_simplification() {
1523     let cx = mk_ctxt();
1524     let item = quote_item!(&cx,
1525         fn new_int_alist<B>() -> alist<int, B> {
1526             fn eq_int(a: int, b: int) -> bool { a == b }
1527             return alist {eq_fn: eq_int, data: Vec::new()};
1528         }
1529     ).unwrap();
1530     let item_in = e::IIItemRef(item);
1531     let item_out = simplify_ast(item_in);
1532     let item_exp = ast::IIItem(quote_item!(cx,
1533         fn new_int_alist<B>() -> alist<int, B> {
1534             return alist {eq_fn: eq_int, data: Vec::new()};
1535         }
1536     ).unwrap());
1537     match (item_out, item_exp) {
1538       (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
1539         assert!(pprust::item_to_str(item_out) == pprust::item_to_str(item_exp));
1540       }
1541       _ => fail!()
1542     }
1543 }