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