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