]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/astencode.rs
auto merge of #11598 : alexcrichton/rust/io-export, r=brson
[rust.git] / src / librustc / middle / astencode.rs
1 // Copyright 2012-2013 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
12 use c = metadata::common;
13 use cstore = metadata::cstore;
14 use driver::session::Session;
15 use metadata::decoder;
16 use e = metadata::encoder;
17 use middle::freevars::freevar_entry;
18 use middle::region;
19 use metadata::tydecode;
20 use metadata::tydecode::{DefIdSource, NominalType, TypeWithId, TypeParameter,
21                          RegionParameter};
22 use metadata::tyencode;
23 use middle::typeck::{method_origin, method_map_entry};
24 use middle::{ty, typeck, moves};
25 use middle;
26 use util::ppaux::ty_to_str;
27
28 use syntax::{ast, ast_map, ast_util, codemap, fold};
29 use syntax::codemap::Span;
30 use syntax::diagnostic::SpanHandler;
31 use syntax::fold::Folder;
32 use syntax::parse::token;
33 use syntax;
34
35 use std::at_vec;
36 use std::libc;
37 use std::cast;
38 use std::io::Seek;
39
40 use extra::ebml::reader;
41 use extra::ebml;
42 use extra::serialize;
43 use extra::serialize::{Encoder, Encodable, EncoderHelpers, DecoderHelpers};
44 use extra::serialize::{Decoder, Decodable};
45 use writer = extra::ebml::writer;
46
47 #[cfg(test)] use syntax::parse;
48 #[cfg(test)] use syntax::print::pprust;
49
50 // Auxiliary maps of things to be encoded
51 pub struct Maps {
52     root_map: middle::borrowck::root_map,
53     method_map: middle::typeck::method_map,
54     vtable_map: middle::typeck::vtable_map,
55     capture_map: middle::moves::CaptureMap,
56 }
57
58 struct DecodeContext {
59     cdata: @cstore::crate_metadata,
60     tcx: ty::ctxt,
61     maps: Maps
62 }
63
64 struct ExtendedDecodeContext {
65     dcx: @DecodeContext,
66     from_id_range: ast_util::IdRange,
67     to_id_range: ast_util::IdRange
68 }
69
70 trait tr {
71     fn tr(&self, xcx: @ExtendedDecodeContext) -> Self;
72 }
73
74 trait tr_intern {
75     fn tr_intern(&self, xcx: @ExtendedDecodeContext) -> ast::DefId;
76 }
77
78 // ______________________________________________________________________
79 // Top-level methods.
80
81 pub fn encode_inlined_item(ecx: &e::EncodeContext,
82                            ebml_w: &mut writer::Encoder,
83                            path: &[ast_map::PathElem],
84                            ii: e::InlinedItemRef,
85                            maps: Maps) {
86     let ident = match ii {
87         e::IIItemRef(i) => i.ident,
88         e::IIForeignRef(i) => i.ident,
89         e::IIMethodRef(_, _, m) => m.ident,
90     };
91     debug!("> Encoding inlined item: {}::{} ({})",
92            ast_map::path_to_str(path, token::get_ident_interner()),
93            ecx.tcx.sess.str_of(ident),
94            ebml_w.writer.tell());
95
96     let ii = simplify_ast(ii);
97     let id_range = ast_util::compute_id_range_for_inlined_item(&ii);
98
99     ebml_w.start_tag(c::tag_ast as uint);
100     id_range.encode(ebml_w);
101     encode_ast(ebml_w, ii);
102     encode_side_tables_for_ii(ecx, maps, ebml_w, &ii);
103     ebml_w.end_tag();
104
105     debug!("< Encoded inlined fn: {}::{} ({})",
106            ast_map::path_to_str(path, token::get_ident_interner()),
107            ecx.tcx.sess.str_of(ident),
108            ebml_w.writer.tell());
109 }
110
111 pub fn encode_exported_macro(ebml_w: &mut writer::Encoder, i: &ast::Item) {
112     match i.node {
113         ast::ItemMac(..) => encode_ast(ebml_w, ast::IIItem(@i.clone())),
114         _ => fail!("expected a macro")
115     }
116 }
117
118 pub fn decode_inlined_item(cdata: @cstore::crate_metadata,
119                            tcx: ty::ctxt,
120                            maps: Maps,
121                            path: &[ast_map::PathElem],
122                            par_doc: ebml::Doc)
123                         -> Option<ast::InlinedItem> {
124     let dcx = @DecodeContext {
125         cdata: cdata,
126         tcx: tcx,
127         maps: maps
128     };
129     match par_doc.opt_child(c::tag_ast) {
130       None => None,
131       Some(ast_doc) => {
132         debug!("> Decoding inlined fn: {}::?",
133                ast_map::path_to_str(path, token::get_ident_interner()));
134         let mut ast_dsr = reader::Decoder(ast_doc);
135         let from_id_range = Decodable::decode(&mut ast_dsr);
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,
144                                       tcx.sess.diagnostic(),
145                                       dcx.tcx.items,
146                                       path.to_owned(),
147                                       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: {}", tcx.sess.str_of(ident));
154         debug!("< Decoded inlined fn: {}::{}",
155                ast_map::path_to_str(path, token::get_ident_interner()),
156                tcx.sess.str_of(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, tcx.sess.intr()));
163           }
164           _ => { }
165         }
166         Some(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.crate, ast::LOCAL_CRATE);
240         ast::DefId { crate: 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: ~[], // I don't know if we need the view_items here,
339                              // 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         self.xcx.tr_id(id)
385     }
386     fn new_span(&self, span: Span) -> Span {
387         self.xcx.tr_span(span)
388     }
389 }
390
391 fn renumber_and_map_ast(xcx: @ExtendedDecodeContext,
392                         diag: @SpanHandler,
393                         map: ast_map::Map,
394                         path: ast_map::Path,
395                         ii: ast::InlinedItem) -> ast::InlinedItem {
396     ast_map::map_decoded_item(diag, map, path, AstRenumberer { xcx: xcx }, |fld| {
397         match ii {
398             ast::IIItem(i) => {
399                 ast::IIItem(fld.fold_item(i).expect_one("expected one item"))
400             }
401             ast::IIMethod(d, is_provided, m) => {
402                 ast::IIMethod(xcx.tr_def_id(d), is_provided, fld.fold_method(m))
403             }
404             ast::IIForeign(i) => ast::IIForeign(fld.fold_foreign_item(i))
405         }
406     })
407 }
408
409 // ______________________________________________________________________
410 // Encoding and decoding of ast::def
411
412 fn decode_def(xcx: @ExtendedDecodeContext, doc: ebml::Doc) -> ast::Def {
413     let mut dsr = reader::Decoder(doc);
414     let def: ast::Def = Decodable::decode(&mut dsr);
415     def.tr(xcx)
416 }
417
418 impl tr for ast::Def {
419     fn tr(&self, xcx: @ExtendedDecodeContext) -> ast::Def {
420         match *self {
421           ast::DefFn(did, p) => ast::DefFn(did.tr(xcx), p),
422           ast::DefStaticMethod(did, wrapped_did2, p) => {
423             ast::DefStaticMethod(did.tr(xcx),
424                                    match wrapped_did2 {
425                                     ast::FromTrait(did2) => {
426                                         ast::FromTrait(did2.tr(xcx))
427                                     }
428                                     ast::FromImpl(did2) => {
429                                         ast::FromImpl(did2.tr(xcx))
430                                     }
431                                    },
432                                    p)
433           }
434           ast::DefMethod(did0, did1) => {
435             ast::DefMethod(did0.tr(xcx), did1.map(|did1| did1.tr(xcx)))
436           }
437           ast::DefSelfTy(nid) => { ast::DefSelfTy(xcx.tr_id(nid)) }
438           ast::DefSelf(nid, m) => { ast::DefSelf(xcx.tr_id(nid), m) }
439           ast::DefMod(did) => { ast::DefMod(did.tr(xcx)) }
440           ast::DefForeignMod(did) => { ast::DefForeignMod(did.tr(xcx)) }
441           ast::DefStatic(did, m) => { ast::DefStatic(did.tr(xcx), m) }
442           ast::DefArg(nid, b) => { ast::DefArg(xcx.tr_id(nid), b) }
443           ast::DefLocal(nid, b) => { ast::DefLocal(xcx.tr_id(nid), b) }
444           ast::DefVariant(e_did, v_did, is_s) => {
445             ast::DefVariant(e_did.tr(xcx), v_did.tr(xcx), is_s)
446           },
447           ast::DefTrait(did) => ast::DefTrait(did.tr(xcx)),
448           ast::DefTy(did) => ast::DefTy(did.tr(xcx)),
449           ast::DefPrimTy(p) => ast::DefPrimTy(p),
450           ast::DefTyParam(did, v) => ast::DefTyParam(did.tr(xcx), v),
451           ast::DefBinding(nid, bm) => ast::DefBinding(xcx.tr_id(nid), bm),
452           ast::DefUse(did) => ast::DefUse(did.tr(xcx)),
453           ast::DefUpvar(nid1, def, nid2, nid3) => {
454             ast::DefUpvar(xcx.tr_id(nid1),
455                            @(*def).tr(xcx),
456                            xcx.tr_id(nid2),
457                            xcx.tr_id(nid3))
458           }
459           ast::DefStruct(did) => ast::DefStruct(did.tr(xcx)),
460           ast::DefRegion(nid) => ast::DefRegion(xcx.tr_id(nid)),
461           ast::DefTyParamBinder(nid) => {
462             ast::DefTyParamBinder(xcx.tr_id(nid))
463           }
464           ast::DefLabel(nid) => ast::DefLabel(xcx.tr_id(nid))
465         }
466     }
467 }
468
469 // ______________________________________________________________________
470 // Encoding and decoding of adjustment information
471
472 impl tr for ty::AutoDerefRef {
473     fn tr(&self, xcx: @ExtendedDecodeContext) -> ty::AutoDerefRef {
474         ty::AutoDerefRef {
475             autoderefs: self.autoderefs,
476             autoref: match self.autoref {
477                 Some(ref autoref) => Some(autoref.tr(xcx)),
478                 None => None
479             }
480         }
481     }
482 }
483
484 impl tr for ty::AutoRef {
485     fn tr(&self, xcx: @ExtendedDecodeContext) -> ty::AutoRef {
486         self.map_region(|r| r.tr(xcx))
487     }
488 }
489
490 impl tr for ty::Region {
491     fn tr(&self, xcx: @ExtendedDecodeContext) -> ty::Region {
492         match *self {
493             ty::ReLateBound(id, br) => ty::ReLateBound(xcx.tr_id(id),
494                                                        br.tr(xcx)),
495             ty::ReEarlyBound(id, index, ident) => ty::ReEarlyBound(xcx.tr_id(id),
496                                                                      index,
497                                                                      ident),
498             ty::ReScope(id) => ty::ReScope(xcx.tr_id(id)),
499             ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => *self,
500             ty::ReFree(ref fr) => {
501                 ty::ReFree(ty::FreeRegion {scope_id: xcx.tr_id(fr.scope_id),
502                                             bound_region: fr.bound_region.tr(xcx)})
503             }
504         }
505     }
506 }
507
508 impl tr for ty::BoundRegion {
509     fn tr(&self, xcx: @ExtendedDecodeContext) -> ty::BoundRegion {
510         match *self {
511             ty::BrAnon(_) |
512             ty::BrFresh(_) => *self,
513             ty::BrNamed(id, ident) => ty::BrNamed(xcx.tr_def_id(id),
514                                                     ident),
515         }
516     }
517 }
518
519 // ______________________________________________________________________
520 // Encoding and decoding of freevar information
521
522 fn encode_freevar_entry(ebml_w: &mut writer::Encoder, fv: @freevar_entry) {
523     (*fv).encode(ebml_w)
524 }
525
526 trait ebml_decoder_helper {
527     fn read_freevar_entry(&mut self, xcx: @ExtendedDecodeContext)
528                           -> freevar_entry;
529 }
530
531 impl<'a> ebml_decoder_helper for reader::Decoder<'a> {
532     fn read_freevar_entry(&mut self, xcx: @ExtendedDecodeContext)
533                           -> freevar_entry {
534         let fv: freevar_entry = Decodable::decode(self);
535         fv.tr(xcx)
536     }
537 }
538
539 impl tr for freevar_entry {
540     fn tr(&self, xcx: @ExtendedDecodeContext) -> freevar_entry {
541         freevar_entry {
542             def: self.def.tr(xcx),
543             span: self.span.tr(xcx),
544         }
545     }
546 }
547
548 // ______________________________________________________________________
549 // Encoding and decoding of CaptureVar information
550
551 trait capture_var_helper {
552     fn read_capture_var(&mut self, xcx: @ExtendedDecodeContext)
553                         -> moves::CaptureVar;
554 }
555
556 impl<'a> capture_var_helper for reader::Decoder<'a> {
557     fn read_capture_var(&mut self, xcx: @ExtendedDecodeContext)
558                         -> moves::CaptureVar {
559         let cvar: moves::CaptureVar = Decodable::decode(self);
560         cvar.tr(xcx)
561     }
562 }
563
564 impl tr for moves::CaptureVar {
565     fn tr(&self, xcx: @ExtendedDecodeContext) -> moves::CaptureVar {
566         moves::CaptureVar {
567             def: self.def.tr(xcx),
568             span: self.span.tr(xcx),
569             mode: self.mode
570         }
571     }
572 }
573
574 // ______________________________________________________________________
575 // Encoding and decoding of method_map_entry
576
577 trait read_method_map_entry_helper {
578     fn read_method_map_entry(&mut self, xcx: @ExtendedDecodeContext)
579                              -> method_map_entry;
580 }
581
582 fn encode_method_map_entry(ecx: &e::EncodeContext,
583                            ebml_w: &mut writer::Encoder,
584                            mme: method_map_entry) {
585     ebml_w.emit_struct("method_map_entry", 3, |ebml_w| {
586         ebml_w.emit_struct_field("self_ty", 0u, |ebml_w| {
587             ebml_w.emit_ty(ecx, mme.self_ty);
588         });
589         ebml_w.emit_struct_field("explicit_self", 2u, |ebml_w| {
590             mme.explicit_self.encode(ebml_w);
591         });
592         ebml_w.emit_struct_field("origin", 1u, |ebml_w| {
593             mme.origin.encode(ebml_w);
594         });
595     })
596 }
597
598 impl<'a> read_method_map_entry_helper for reader::Decoder<'a> {
599     fn read_method_map_entry(&mut self, xcx: @ExtendedDecodeContext)
600                              -> method_map_entry {
601         self.read_struct("method_map_entry", 3, |this| {
602             method_map_entry {
603                 self_ty: this.read_struct_field("self_ty", 0u, |this| {
604                     this.read_ty(xcx)
605                 }),
606                 explicit_self: this.read_struct_field("explicit_self",
607                                                       2,
608                                                       |this| {
609                     let explicit_self: ast::ExplicitSelf_ = Decodable::decode(this);
610                     explicit_self
611                 }),
612                 origin: this.read_struct_field("origin", 1, |this| {
613                     let method_origin: method_origin =
614                         Decodable::decode(this);
615                     method_origin.tr(xcx)
616                 })
617             }
618         })
619     }
620 }
621
622 impl tr for method_origin {
623     fn tr(&self, xcx: @ExtendedDecodeContext) -> method_origin {
624         match *self {
625           typeck::method_static(did) => {
626               typeck::method_static(did.tr(xcx))
627           }
628           typeck::method_param(ref mp) => {
629             typeck::method_param(
630                 typeck::method_param {
631                     trait_id: mp.trait_id.tr(xcx),
632                     .. *mp
633                 }
634             )
635           }
636           typeck::method_object(ref mo) => {
637             typeck::method_object(
638                 typeck::method_object {
639                     trait_id: mo.trait_id.tr(xcx),
640                     .. *mo
641                 }
642             )
643           }
644         }
645     }
646 }
647
648 // ______________________________________________________________________
649 // Encoding and decoding vtable_res
650
651 pub fn encode_vtable_res(ecx: &e::EncodeContext,
652                      ebml_w: &mut writer::Encoder,
653                      dr: typeck::vtable_res) {
654     // can't autogenerate this code because automatic code of
655     // ty::t doesn't work, and there is no way (atm) to have
656     // hand-written encoding routines combine with auto-generated
657     // ones.  perhaps we should fix this.
658     ebml_w.emit_from_vec(*dr, |ebml_w, param_tables| {
659         encode_vtable_param_res(ecx, ebml_w, *param_tables);
660     })
661 }
662
663 pub fn encode_vtable_param_res(ecx: &e::EncodeContext,
664                      ebml_w: &mut writer::Encoder,
665                      param_tables: typeck::vtable_param_res) {
666     ebml_w.emit_from_vec(*param_tables, |ebml_w, vtable_origin| {
667         encode_vtable_origin(ecx, ebml_w, vtable_origin)
668     })
669 }
670
671
672 pub fn encode_vtable_origin(ecx: &e::EncodeContext,
673                         ebml_w: &mut writer::Encoder,
674                         vtable_origin: &typeck::vtable_origin) {
675     ebml_w.emit_enum("vtable_origin", |ebml_w| {
676         match *vtable_origin {
677           typeck::vtable_static(def_id, ref tys, vtable_res) => {
678             ebml_w.emit_enum_variant("vtable_static", 0u, 3u, |ebml_w| {
679                 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
680                     ebml_w.emit_def_id(def_id)
681                 });
682                 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
683                     ebml_w.emit_tys(ecx, *tys);
684                 });
685                 ebml_w.emit_enum_variant_arg(2u, |ebml_w| {
686                     encode_vtable_res(ecx, ebml_w, vtable_res);
687                 })
688             })
689           }
690           typeck::vtable_param(pn, bn) => {
691             ebml_w.emit_enum_variant("vtable_param", 1u, 2u, |ebml_w| {
692                 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
693                     pn.encode(ebml_w);
694                 });
695                 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
696                     ebml_w.emit_uint(bn);
697                 })
698             })
699           }
700         }
701     })
702 }
703
704 pub trait vtable_decoder_helpers {
705     fn read_vtable_res(&mut self,
706                        tcx: ty::ctxt, cdata: @cstore::crate_metadata)
707                       -> typeck::vtable_res;
708     fn read_vtable_param_res(&mut self,
709                        tcx: ty::ctxt, cdata: @cstore::crate_metadata)
710                       -> typeck::vtable_param_res;
711     fn read_vtable_origin(&mut self,
712                           tcx: ty::ctxt, cdata: @cstore::crate_metadata)
713                           -> typeck::vtable_origin;
714 }
715
716 impl<'a> vtable_decoder_helpers for reader::Decoder<'a> {
717     fn read_vtable_res(&mut self,
718                        tcx: ty::ctxt, cdata: @cstore::crate_metadata)
719                       -> typeck::vtable_res {
720         @self.read_to_vec(|this|
721                           this.read_vtable_param_res(tcx, cdata))
722     }
723
724     fn read_vtable_param_res(&mut self,
725                              tcx: ty::ctxt, cdata: @cstore::crate_metadata)
726                       -> typeck::vtable_param_res {
727         @self.read_to_vec(|this|
728                           this.read_vtable_origin(tcx, cdata))
729     }
730
731     fn read_vtable_origin(&mut self,
732                           tcx: ty::ctxt, cdata: @cstore::crate_metadata)
733         -> typeck::vtable_origin {
734         self.read_enum("vtable_origin", |this| {
735             this.read_enum_variant(["vtable_static",
736                                     "vtable_param",
737                                     "vtable_self"],
738                                    |this, i| {
739                 match i {
740                   0 => {
741                     typeck::vtable_static(
742                         this.read_enum_variant_arg(0u, |this| {
743                             this.read_def_id_noxcx(cdata)
744                         }),
745                         this.read_enum_variant_arg(1u, |this| {
746                             this.read_tys_noxcx(tcx, cdata)
747                         }),
748                         this.read_enum_variant_arg(2u, |this| {
749                             this.read_vtable_res(tcx, cdata)
750                         })
751                     )
752                   }
753                   1 => {
754                     typeck::vtable_param(
755                         this.read_enum_variant_arg(0u, |this| {
756                             Decodable::decode(this)
757                         }),
758                         this.read_enum_variant_arg(1u, |this| {
759                             this.read_uint()
760                         })
761                     )
762                   }
763                   // hard to avoid - user input
764                   _ => fail!("bad enum variant")
765                 }
766             })
767         })
768     }
769 }
770
771 // ______________________________________________________________________
772 // Encoding and decoding the side tables
773
774 trait get_ty_str_ctxt {
775     fn ty_str_ctxt(&self) -> @tyencode::ctxt;
776 }
777
778 impl<'a> get_ty_str_ctxt for e::EncodeContext<'a> {
779     fn ty_str_ctxt(&self) -> @tyencode::ctxt {
780         @tyencode::ctxt {
781             diag: self.tcx.sess.diagnostic(),
782             ds: e::def_to_str,
783             tcx: self.tcx,
784             abbrevs: tyencode::ac_use_abbrevs(self.type_abbrevs)
785         }
786     }
787 }
788
789 trait ebml_writer_helpers {
790     fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t);
791     fn emit_vstore(&mut self, ecx: &e::EncodeContext, vstore: ty::vstore);
792     fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]);
793     fn emit_type_param_def(&mut self,
794                            ecx: &e::EncodeContext,
795                            type_param_def: &ty::TypeParameterDef);
796     fn emit_tpbt(&mut self,
797                  ecx: &e::EncodeContext,
798                  tpbt: ty::ty_param_bounds_and_ty);
799     fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs);
800     fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment);
801 }
802
803 impl<'a> ebml_writer_helpers for writer::Encoder<'a> {
804     fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t) {
805         self.emit_opaque(|this| e::write_type(ecx, this, ty))
806     }
807
808     fn emit_vstore(&mut self, ecx: &e::EncodeContext, vstore: ty::vstore) {
809         self.emit_opaque(|this| e::write_vstore(ecx, this, vstore))
810     }
811
812     fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]) {
813         self.emit_from_vec(tys, |this, ty| this.emit_ty(ecx, *ty))
814     }
815
816     fn emit_type_param_def(&mut self,
817                            ecx: &e::EncodeContext,
818                            type_param_def: &ty::TypeParameterDef) {
819         self.emit_opaque(|this| {
820             tyencode::enc_type_param_def(this.writer,
821                                          ecx.ty_str_ctxt(),
822                                          type_param_def)
823         })
824     }
825
826     fn emit_tpbt(&mut self,
827                  ecx: &e::EncodeContext,
828                  tpbt: ty::ty_param_bounds_and_ty) {
829         self.emit_struct("ty_param_bounds_and_ty", 2, |this| {
830             this.emit_struct_field("generics", 0, |this| {
831                 this.emit_struct("Generics", 2, |this| {
832                     this.emit_struct_field("type_param_defs", 0, |this| {
833                         this.emit_from_vec(*tpbt.generics.type_param_defs,
834                                            |this, type_param_def| {
835                             this.emit_type_param_def(ecx, type_param_def);
836                         })
837                     });
838                     this.emit_struct_field("region_param_defs", 1, |this| {
839                         tpbt.generics.region_param_defs.encode(this);
840                     })
841                 })
842             });
843             this.emit_struct_field("ty", 1, |this| {
844                 this.emit_ty(ecx, tpbt.ty);
845             })
846         })
847     }
848
849     fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs) {
850         self.emit_opaque(|this| tyencode::enc_substs(this.writer, ecx.ty_str_ctxt(), substs))
851     }
852
853     fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment) {
854         self.emit_enum("AutoAdjustment", |this| {
855             match *adj {
856                 ty::AutoAddEnv(region, sigil) => {
857                     this.emit_enum_variant("AutoAddEnv", 0, 2, |this| {
858                         this.emit_enum_variant_arg(0, |this| region.encode(this));
859                         this.emit_enum_variant_arg(1, |this| sigil.encode(this));
860                     });
861                 }
862
863                 ty::AutoDerefRef(ref auto_deref_ref) => {
864                     this.emit_enum_variant("AutoDerefRef", 1, 1, |this| {
865                         this.emit_enum_variant_arg(0, |this| auto_deref_ref.encode(this));
866                     });
867                 }
868
869                 ty::AutoObject(sigil, region, m, b, def_id, ref substs) => {
870                     this.emit_enum_variant("AutoObject", 2, 6, |this| {
871                         this.emit_enum_variant_arg(0, |this| sigil.encode(this));
872                         this.emit_enum_variant_arg(1, |this| region.encode(this));
873                         this.emit_enum_variant_arg(2, |this| m.encode(this));
874                         this.emit_enum_variant_arg(3, |this| b.encode(this));
875                         this.emit_enum_variant_arg(4, |this| def_id.encode(this));
876                         this.emit_enum_variant_arg(5, |this| this.emit_substs(ecx, substs));
877                     });
878                 }
879             }
880         });
881     }
882 }
883
884 trait write_tag_and_id {
885     fn tag(&mut self, tag_id: c::astencode_tag, f: |&mut Self|);
886     fn id(&mut self, id: ast::NodeId);
887 }
888
889 impl<'a> write_tag_and_id for writer::Encoder<'a> {
890     fn tag(&mut self,
891            tag_id: c::astencode_tag,
892            f: |&mut writer::Encoder<'a>|) {
893         self.start_tag(tag_id as uint);
894         f(self);
895         self.end_tag();
896     }
897
898     fn id(&mut self, id: ast::NodeId) {
899         self.wr_tagged_u64(c::tag_table_id as uint, id as u64)
900     }
901 }
902
903 struct SideTableEncodingIdVisitor<'a,'b> {
904     ecx_ptr: *libc::c_void,
905     new_ebml_w: &'a mut writer::Encoder<'b>,
906     maps: Maps,
907 }
908
909 impl<'a,'b> ast_util::IdVisitingOperation for
910         SideTableEncodingIdVisitor<'a,'b> {
911     fn visit_id(&self, id: ast::NodeId) {
912         // Note: this will cause a copy of ebml_w, which is bad as
913         // it is mutable. But I believe it's harmless since we generate
914         // balanced EBML.
915         //
916         // XXX(pcwalton): Don't copy this way.
917         let mut new_ebml_w = unsafe {
918             self.new_ebml_w.unsafe_clone()
919         };
920         // See above
921         let ecx: &e::EncodeContext = unsafe {
922             cast::transmute(self.ecx_ptr)
923         };
924         encode_side_tables_for_id(ecx, self.maps, &mut new_ebml_w, id)
925     }
926 }
927
928 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
929                              maps: Maps,
930                              ebml_w: &mut writer::Encoder,
931                              ii: &ast::InlinedItem) {
932     ebml_w.start_tag(c::tag_table as uint);
933     let mut new_ebml_w = unsafe {
934         ebml_w.unsafe_clone()
935     };
936
937     // Because the ast visitor uses @IdVisitingOperation, I can't pass in
938     // ecx directly, but /I/ know that it'll be fine since the lifetime is
939     // tied to the CrateContext that lives throughout this entire section.
940     ast_util::visit_ids_for_inlined_item(ii, &SideTableEncodingIdVisitor {
941         ecx_ptr: unsafe {
942             cast::transmute(ecx)
943         },
944         new_ebml_w: &mut new_ebml_w,
945         maps: maps,
946     });
947     ebml_w.end_tag();
948 }
949
950 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
951                              maps: Maps,
952                              ebml_w: &mut writer::Encoder,
953                              id: ast::NodeId) {
954     let tcx = ecx.tcx;
955
956     debug!("Encoding side tables for id {}", id);
957
958     {
959         let def_map = tcx.def_map.borrow();
960         let r = def_map.get().find(&id);
961         for def in r.iter() {
962             ebml_w.tag(c::tag_table_def, |ebml_w| {
963                 ebml_w.id(id);
964                 ebml_w.tag(c::tag_table_val, |ebml_w| (*def).encode(ebml_w));
965             })
966         }
967     }
968
969     {
970         let node_types = tcx.node_types.borrow();
971         let r = node_types.get().find(&(id as uint));
972         for &ty in r.iter() {
973             ebml_w.tag(c::tag_table_node_type, |ebml_w| {
974                 ebml_w.id(id);
975                 ebml_w.tag(c::tag_table_val, |ebml_w| {
976                     ebml_w.emit_ty(ecx, *ty);
977                 })
978             })
979         }
980     }
981
982     {
983         let node_type_substs = tcx.node_type_substs.borrow();
984         let r = node_type_substs.get().find(&id);
985         for tys in r.iter() {
986             ebml_w.tag(c::tag_table_node_type_subst, |ebml_w| {
987                 ebml_w.id(id);
988                 ebml_w.tag(c::tag_table_val, |ebml_w| {
989                     ebml_w.emit_tys(ecx, **tys)
990                 })
991             })
992         }
993     }
994
995     {
996         let freevars = tcx.freevars.borrow();
997         let r = freevars.get().find(&id);
998         for &fv in r.iter() {
999             ebml_w.tag(c::tag_table_freevars, |ebml_w| {
1000                 ebml_w.id(id);
1001                 ebml_w.tag(c::tag_table_val, |ebml_w| {
1002                     ebml_w.emit_from_vec(**fv, |ebml_w, fv_entry| {
1003                         encode_freevar_entry(ebml_w, *fv_entry)
1004                     })
1005                 })
1006             })
1007         }
1008     }
1009
1010     let lid = ast::DefId { crate: ast::LOCAL_CRATE, node: id };
1011     {
1012         let tcache = tcx.tcache.borrow();
1013         let r = tcache.get().find(&lid);
1014         for &tpbt in r.iter() {
1015             ebml_w.tag(c::tag_table_tcache, |ebml_w| {
1016                 ebml_w.id(id);
1017                 ebml_w.tag(c::tag_table_val, |ebml_w| {
1018                     ebml_w.emit_tpbt(ecx, *tpbt);
1019                 })
1020             })
1021         }
1022     }
1023
1024     {
1025         let r = {
1026             let ty_param_defs = tcx.ty_param_defs.borrow();
1027             ty_param_defs.get().find(&id).map(|def| *def)
1028         };
1029         for type_param_def in r.iter() {
1030             ebml_w.tag(c::tag_table_param_defs, |ebml_w| {
1031                 ebml_w.id(id);
1032                 ebml_w.tag(c::tag_table_val, |ebml_w| {
1033                     ebml_w.emit_type_param_def(ecx, type_param_def)
1034                 })
1035             })
1036         }
1037     }
1038
1039     {
1040         let method_map = maps.method_map.borrow();
1041         let r = method_map.get().find(&id);
1042         for &mme in r.iter() {
1043             ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1044                 ebml_w.id(id);
1045                 ebml_w.tag(c::tag_table_val, |ebml_w| {
1046                     encode_method_map_entry(ecx, ebml_w, *mme)
1047                 })
1048             })
1049         }
1050     }
1051
1052     {
1053         let vtable_map = maps.vtable_map.borrow();
1054         let r = vtable_map.get().find(&id);
1055         for &dr in r.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(ecx, ebml_w, *dr);
1060                 })
1061             })
1062         }
1063     }
1064
1065     {
1066         let adjustments = tcx.adjustments.borrow();
1067         let r = adjustments.get().find(&id);
1068         for adj in r.iter() {
1069             ebml_w.tag(c::tag_table_adjustments, |ebml_w| {
1070                 ebml_w.id(id);
1071                 ebml_w.tag(c::tag_table_val, |ebml_w| {
1072                     ebml_w.emit_auto_adjustment(ecx, **adj);
1073                 })
1074             })
1075         }
1076     }
1077
1078     {
1079         let capture_map = maps.capture_map.borrow();
1080         let r = capture_map.get().find(&id);
1081         for &cap_vars in r.iter() {
1082             ebml_w.tag(c::tag_table_capture_map, |ebml_w| {
1083                 ebml_w.id(id);
1084                 ebml_w.tag(c::tag_table_val, |ebml_w| {
1085                     ebml_w.emit_from_vec(*cap_vars, |ebml_w, cap_var| {
1086                         cap_var.encode(ebml_w);
1087                     })
1088                 })
1089             })
1090         }
1091     }
1092 }
1093
1094 trait doc_decoder_helpers {
1095     fn as_int(&self) -> int;
1096     fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1097 }
1098
1099 impl<'a> doc_decoder_helpers for ebml::Doc<'a> {
1100     fn as_int(&self) -> int { reader::doc_as_u64(*self) as int }
1101     fn opt_child(&self, tag: c::astencode_tag) -> Option<ebml::Doc<'a>> {
1102         reader::maybe_get_doc(*self, tag as uint)
1103     }
1104 }
1105
1106 trait ebml_decoder_decoder_helpers {
1107     fn read_ty(&mut self, xcx: @ExtendedDecodeContext) -> ty::t;
1108     fn read_tys(&mut self, xcx: @ExtendedDecodeContext) -> ~[ty::t];
1109     fn read_type_param_def(&mut self, xcx: @ExtendedDecodeContext)
1110                            -> ty::TypeParameterDef;
1111     fn read_ty_param_bounds_and_ty(&mut self, xcx: @ExtendedDecodeContext)
1112                                 -> ty::ty_param_bounds_and_ty;
1113     fn read_substs(&mut self, xcx: @ExtendedDecodeContext) -> ty::substs;
1114     fn read_auto_adjustment(&mut self, xcx: @ExtendedDecodeContext) -> ty::AutoAdjustment;
1115     fn convert_def_id(&mut self,
1116                       xcx: @ExtendedDecodeContext,
1117                       source: DefIdSource,
1118                       did: ast::DefId)
1119                       -> ast::DefId;
1120
1121     // Versions of the type reading functions that don't need the full
1122     // ExtendedDecodeContext.
1123     fn read_ty_noxcx(&mut self,
1124                      tcx: ty::ctxt, cdata: @cstore::crate_metadata) -> ty::t;
1125     fn read_tys_noxcx(&mut self,
1126                       tcx: ty::ctxt,
1127                       cdata: @cstore::crate_metadata) -> ~[ty::t];
1128 }
1129
1130 impl<'a> ebml_decoder_decoder_helpers for reader::Decoder<'a> {
1131     fn read_ty_noxcx(&mut self,
1132                      tcx: ty::ctxt, cdata: @cstore::crate_metadata) -> ty::t {
1133         self.read_opaque(|_, doc| {
1134             tydecode::parse_ty_data(
1135                 doc.data,
1136                 cdata.cnum,
1137                 doc.start,
1138                 tcx,
1139                 |_, id| decoder::translate_def_id(cdata, id))
1140         })
1141     }
1142
1143     fn read_tys_noxcx(&mut self,
1144                       tcx: ty::ctxt,
1145                       cdata: @cstore::crate_metadata) -> ~[ty::t] {
1146         self.read_to_vec(|this| this.read_ty_noxcx(tcx, cdata) )
1147     }
1148
1149     fn read_ty(&mut self, xcx: @ExtendedDecodeContext) -> ty::t {
1150         // Note: regions types embed local node ids.  In principle, we
1151         // should translate these node ids into the new decode
1152         // context.  However, we do not bother, because region types
1153         // are not used during trans.
1154
1155         return self.read_opaque(|this, doc| {
1156             debug!("read_ty({})", type_string(doc));
1157
1158             let ty = tydecode::parse_ty_data(
1159                 doc.data,
1160                 xcx.dcx.cdata.cnum,
1161                 doc.start,
1162                 xcx.dcx.tcx,
1163                 |s, a| this.convert_def_id(xcx, s, a));
1164
1165             ty
1166         });
1167
1168         fn type_string(doc: ebml::Doc) -> ~str {
1169             let mut str = ~"";
1170             for i in range(doc.start, doc.end) {
1171                 str.push_char(doc.data[i] as char);
1172             }
1173             str
1174         }
1175     }
1176
1177     fn read_tys(&mut self, xcx: @ExtendedDecodeContext) -> ~[ty::t] {
1178         self.read_to_vec(|this| this.read_ty(xcx) )
1179     }
1180
1181     fn read_type_param_def(&mut self, xcx: @ExtendedDecodeContext)
1182                            -> ty::TypeParameterDef {
1183         self.read_opaque(|this, doc| {
1184             tydecode::parse_type_param_def_data(
1185                 doc.data,
1186                 doc.start,
1187                 xcx.dcx.cdata.cnum,
1188                 xcx.dcx.tcx,
1189                 |s, a| this.convert_def_id(xcx, s, a))
1190         })
1191     }
1192
1193     fn read_ty_param_bounds_and_ty(&mut self, xcx: @ExtendedDecodeContext)
1194                                    -> ty::ty_param_bounds_and_ty {
1195         self.read_struct("ty_param_bounds_and_ty", 2, |this| {
1196             ty::ty_param_bounds_and_ty {
1197                 generics: this.read_struct_field("generics", 0, |this| {
1198                     this.read_struct("Generics", 2, |this| {
1199                         ty::Generics {
1200                             type_param_defs:
1201                                 this.read_struct_field("type_param_defs",
1202                                                        0,
1203                                                        |this| {
1204                                     @this.read_to_vec(|this|
1205                                         this.read_type_param_def(xcx))
1206                             }),
1207                             region_param_defs:
1208                                 this.read_struct_field("region_param_defs",
1209                                                        1,
1210                                                        |this| {
1211                                     Decodable::decode(this)
1212                                 })
1213                         }
1214                     })
1215                 }),
1216                 ty: this.read_struct_field("ty", 1, |this| {
1217                     this.read_ty(xcx)
1218                 })
1219             }
1220         })
1221     }
1222
1223     fn read_substs(&mut self, xcx: @ExtendedDecodeContext) -> ty::substs {
1224         self.read_opaque(|this, doc| {
1225             tydecode::parse_substs_data(doc.data,
1226                                         xcx.dcx.cdata.cnum,
1227                                         doc.start,
1228                                         xcx.dcx.tcx,
1229                                         |s, a| this.convert_def_id(xcx, s, a))
1230         })
1231     }
1232
1233     fn read_auto_adjustment(&mut self, xcx: @ExtendedDecodeContext) -> ty::AutoAdjustment {
1234         self.read_enum("AutoAdjustment", |this| {
1235             let variants = ["AutoAddEnv", "AutoDerefRef", "AutoObject"];
1236             this.read_enum_variant(variants, |this, i| {
1237                 match i {
1238                     0 => {
1239                         let region: ty::Region =
1240                             this.read_enum_variant_arg(0, |this| Decodable::decode(this));
1241                         let sigil: ast::Sigil =
1242                             this.read_enum_variant_arg(1, |this| Decodable::decode(this));
1243
1244                         ty:: AutoAddEnv(region.tr(xcx), sigil)
1245                     }
1246                     1 => {
1247                         let auto_deref_ref: ty::AutoDerefRef =
1248                             this.read_enum_variant_arg(0, |this| Decodable::decode(this));
1249
1250                         ty::AutoDerefRef(auto_deref_ref.tr(xcx))
1251                     }
1252                     2 => {
1253                         let sigil: ast::Sigil =
1254                             this.read_enum_variant_arg(0, |this| Decodable::decode(this));
1255                         let region: Option<ty::Region> =
1256                             this.read_enum_variant_arg(1, |this| Decodable::decode(this));
1257                         let m: ast::Mutability =
1258                             this.read_enum_variant_arg(2, |this| Decodable::decode(this));
1259                         let b: ty::BuiltinBounds =
1260                             this.read_enum_variant_arg(3, |this| Decodable::decode(this));
1261                         let def_id: ast::DefId =
1262                             this.read_enum_variant_arg(4, |this| Decodable::decode(this));
1263                         let substs = this.read_enum_variant_arg(5, |this| this.read_substs(xcx));
1264
1265                         let region = match region {
1266                             Some(r) => Some(r.tr(xcx)),
1267                             None => None
1268                         };
1269
1270                         ty::AutoObject(sigil, region, m, b, def_id.tr(xcx), substs)
1271                     }
1272                     _ => fail!("bad enum variant for ty::AutoAdjustment")
1273                 }
1274             })
1275         })
1276     }
1277
1278     fn convert_def_id(&mut self,
1279                       xcx: @ExtendedDecodeContext,
1280                       source: tydecode::DefIdSource,
1281                       did: ast::DefId)
1282                       -> ast::DefId {
1283         /*!
1284          * Converts a def-id that appears in a type.  The correct
1285          * translation will depend on what kind of def-id this is.
1286          * This is a subtle point: type definitions are not
1287          * inlined into the current crate, so if the def-id names
1288          * a nominal type or type alias, then it should be
1289          * translated to refer to the source crate.
1290          *
1291          * However, *type parameters* are cloned along with the function
1292          * they are attached to.  So we should translate those def-ids
1293          * to refer to the new, cloned copy of the type parameter.
1294          * We only see references to free type parameters in the body of
1295          * an inlined function. In such cases, we need the def-id to
1296          * be a local id so that the TypeContents code is able to lookup
1297          * the relevant info in the ty_param_defs table.
1298          *
1299          * *Region parameters*, unfortunately, are another kettle of fish.
1300          * In such cases, def_id's can appear in types to distinguish
1301          * shadowed bound regions and so forth. It doesn't actually
1302          * matter so much what we do to these, since regions are erased
1303          * at trans time, but it's good to keep them consistent just in
1304          * case. We translate them with `tr_def_id()` which will map
1305          * the crate numbers back to the original source crate.
1306          *
1307          * It'd be really nice to refactor the type repr to not include
1308          * def-ids so that all these distinctions were unnecessary.
1309          */
1310
1311         let r = match source {
1312             NominalType | TypeWithId | RegionParameter => xcx.tr_def_id(did),
1313             TypeParameter => xcx.tr_intern_def_id(did)
1314         };
1315         debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1316         return r;
1317     }
1318 }
1319
1320 fn decode_side_tables(xcx: @ExtendedDecodeContext,
1321                       ast_doc: ebml::Doc) {
1322     let dcx = xcx.dcx;
1323     let tbl_doc = ast_doc.get(c::tag_table as uint);
1324     reader::docs(tbl_doc, |tag, entry_doc| {
1325         let id0 = entry_doc.get(c::tag_table_id as uint).as_int();
1326         let id = xcx.tr_id(id0 as ast::NodeId);
1327
1328         debug!(">> Side table document with tag 0x{:x} \
1329                 found for id {} (orig {})",
1330                tag, id, id0);
1331
1332         match c::astencode_tag::from_uint(tag) {
1333             None => {
1334                 xcx.dcx.tcx.sess.bug(
1335                     format!("unknown tag found in side tables: {:x}", tag));
1336             }
1337             Some(value) => {
1338                 let val_doc = entry_doc.get(c::tag_table_val as uint);
1339                 let mut val_dsr = reader::Decoder(val_doc);
1340                 let val_dsr = &mut val_dsr;
1341
1342                 match value {
1343                     c::tag_table_def => {
1344                         let def = decode_def(xcx, val_doc);
1345                         let mut def_map = dcx.tcx.def_map.borrow_mut();
1346                         def_map.get().insert(id, def);
1347                     }
1348                     c::tag_table_node_type => {
1349                         let ty = val_dsr.read_ty(xcx);
1350                         debug!("inserting ty for node {:?}: {}",
1351                                id, ty_to_str(dcx.tcx, ty));
1352                         let mut node_types = dcx.tcx.node_types.borrow_mut();
1353                         node_types.get().insert(id as uint, ty);
1354                     }
1355                     c::tag_table_node_type_subst => {
1356                         let tys = val_dsr.read_tys(xcx);
1357                         let mut node_type_substs = dcx.tcx
1358                                                       .node_type_substs
1359                                                       .borrow_mut();
1360                         node_type_substs.get().insert(id, tys);
1361                     }
1362                     c::tag_table_freevars => {
1363                         let fv_info = @val_dsr.read_to_vec(|val_dsr| {
1364                             @val_dsr.read_freevar_entry(xcx)
1365                         });
1366                         let mut freevars = dcx.tcx.freevars.borrow_mut();
1367                         freevars.get().insert(id, fv_info);
1368                     }
1369                     c::tag_table_tcache => {
1370                         let tpbt = val_dsr.read_ty_param_bounds_and_ty(xcx);
1371                         let lid = ast::DefId { crate: ast::LOCAL_CRATE, node: id };
1372                         let mut tcache = dcx.tcx.tcache.borrow_mut();
1373                         tcache.get().insert(lid, tpbt);
1374                     }
1375                     c::tag_table_param_defs => {
1376                         let bounds = val_dsr.read_type_param_def(xcx);
1377                         let mut ty_param_defs = dcx.tcx
1378                                                    .ty_param_defs
1379                                                    .borrow_mut();
1380                         ty_param_defs.get().insert(id, bounds);
1381                     }
1382                     c::tag_table_method_map => {
1383                         let entry = val_dsr.read_method_map_entry(xcx);
1384                         let mut method_map = dcx.maps.method_map.borrow_mut();
1385                         method_map.get().insert(id, entry);
1386                     }
1387                     c::tag_table_vtable_map => {
1388                         let vtable_res =
1389                             val_dsr.read_vtable_res(xcx.dcx.tcx,
1390                                                     xcx.dcx.cdata);
1391                         let mut vtable_map = dcx.maps.vtable_map.borrow_mut();
1392                         vtable_map.get().insert(id, vtable_res);
1393                     }
1394                     c::tag_table_adjustments => {
1395                         let adj: @ty::AutoAdjustment = @val_dsr.read_auto_adjustment(xcx);
1396                         let mut adjustments = dcx.tcx
1397                                                  .adjustments
1398                                                  .borrow_mut();
1399                         adjustments.get().insert(id, adj);
1400                     }
1401                     c::tag_table_capture_map => {
1402                         let cvars =
1403                             at_vec::to_managed_move(
1404                                 val_dsr.read_to_vec(
1405                                     |val_dsr| val_dsr.read_capture_var(xcx)));
1406                         let mut capture_map = dcx.maps
1407                                                  .capture_map
1408                                                  .borrow_mut();
1409                         capture_map.get().insert(id, cvars);
1410                     }
1411                     _ => {
1412                         xcx.dcx.tcx.sess.bug(
1413                             format!("unknown tag found in side tables: {:x}", tag));
1414                     }
1415                 }
1416             }
1417         }
1418
1419         debug!(">< Side table doc loaded");
1420         true
1421     });
1422 }
1423
1424 // ______________________________________________________________________
1425 // Testing of astencode_gen
1426
1427 #[cfg(test)]
1428 fn encode_item_ast(ebml_w: &mut writer::Encoder, item: @ast::Item) {
1429     ebml_w.start_tag(c::tag_tree as uint);
1430     (*item).encode(ebml_w);
1431     ebml_w.end_tag();
1432 }
1433
1434 #[cfg(test)]
1435 fn decode_item_ast(par_doc: ebml::Doc) -> @ast::Item {
1436     let chi_doc = par_doc.get(c::tag_tree as uint);
1437     let mut d = reader::Decoder(chi_doc);
1438     @Decodable::decode(&mut d)
1439 }
1440
1441 #[cfg(test)]
1442 trait fake_ext_ctxt {
1443     fn cfg(&self) -> ast::CrateConfig;
1444     fn parse_sess(&self) -> @parse::ParseSess;
1445     fn call_site(&self) -> Span;
1446     fn ident_of(&self, st: &str) -> ast::Ident;
1447 }
1448
1449 #[cfg(test)]
1450 type fake_session = @parse::ParseSess;
1451
1452 #[cfg(test)]
1453 impl fake_ext_ctxt for fake_session {
1454     fn cfg(&self) -> ast::CrateConfig { ~[] }
1455     fn parse_sess(&self) -> @parse::ParseSess { *self }
1456     fn call_site(&self) -> Span {
1457         codemap::Span {
1458             lo: codemap::BytePos(0),
1459             hi: codemap::BytePos(0),
1460             expn_info: None
1461         }
1462     }
1463     fn ident_of(&self, st: &str) -> ast::Ident {
1464         token::str_to_ident(st)
1465     }
1466 }
1467
1468 #[cfg(test)]
1469 fn mk_ctxt() -> @fake_ext_ctxt {
1470     @parse::new_parse_sess(None) as @fake_ext_ctxt
1471 }
1472
1473 #[cfg(test)]
1474 fn roundtrip(in_item: Option<@ast::Item>) {
1475     use std::io::MemWriter;
1476
1477     let in_item = in_item.unwrap();
1478     let mut wr = MemWriter::new();
1479     {
1480         let mut ebml_w = writer::Encoder(&mut wr);
1481         encode_item_ast(&mut ebml_w, in_item);
1482     }
1483     let ebml_doc = reader::Doc(wr.get_ref());
1484     let out_item = decode_item_ast(ebml_doc);
1485
1486     assert_eq!(in_item, out_item);
1487 }
1488
1489 #[test]
1490 fn test_basic() {
1491     let cx = mk_ctxt();
1492     roundtrip(quote_item!(cx,
1493         fn foo() {}
1494     ));
1495 }
1496
1497 #[test]
1498 fn test_smalltalk() {
1499     let cx = mk_ctxt();
1500     roundtrip(quote_item!(cx,
1501         fn foo() -> int { 3 + 4 } // first smalltalk program ever executed.
1502     ));
1503 }
1504
1505 #[test]
1506 fn test_more() {
1507     let cx = mk_ctxt();
1508     roundtrip(quote_item!(cx,
1509         fn foo(x: uint, y: uint) -> uint {
1510             let z = x + y;
1511             return z;
1512         }
1513     ));
1514 }
1515
1516 #[test]
1517 fn test_simplification() {
1518     let cx = mk_ctxt();
1519     let item = quote_item!(cx,
1520         fn new_int_alist<B>() -> alist<int, B> {
1521             fn eq_int(a: int, b: int) -> bool { a == b }
1522             return alist {eq_fn: eq_int, data: ~[]};
1523         }
1524     ).unwrap();
1525     let item_in = e::IIItemRef(item);
1526     let item_out = simplify_ast(item_in);
1527     let item_exp = ast::IIItem(quote_item!(cx,
1528         fn new_int_alist<B>() -> alist<int, B> {
1529             return alist {eq_fn: eq_int, data: ~[]};
1530         }
1531     ).unwrap());
1532     match (item_out, item_exp) {
1533       (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
1534         assert!(pprust::item_to_str(item_out,
1535                                     token::get_ident_interner())
1536                      == pprust::item_to_str(item_exp,
1537                                             token::get_ident_interner()));
1538       }
1539       _ => fail!()
1540     }
1541 }