]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/astencode.rs
auto merge of #13424 : eddyb/rust/ty-mut-in-store, r=nikomatsakis
[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 impl tr for ty::TraitStore {
518     fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::TraitStore {
519         match *self {
520             ty::RegionTraitStore(r, m) => {
521                 ty::RegionTraitStore(r.tr(xcx), m)
522             }
523             ty::UniqTraitStore => ty::UniqTraitStore
524         }
525     }
526 }
527
528 // ______________________________________________________________________
529 // Encoding and decoding of freevar information
530
531 fn encode_freevar_entry(ebml_w: &mut Encoder, fv: @freevar_entry) {
532     (*fv).encode(ebml_w).unwrap();
533 }
534
535 trait ebml_decoder_helper {
536     fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
537                           -> freevar_entry;
538 }
539
540 impl<'a> ebml_decoder_helper for reader::Decoder<'a> {
541     fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
542                           -> freevar_entry {
543         let fv: freevar_entry = Decodable::decode(self).unwrap();
544         fv.tr(xcx)
545     }
546 }
547
548 impl tr for freevar_entry {
549     fn tr(&self, xcx: &ExtendedDecodeContext) -> freevar_entry {
550         freevar_entry {
551             def: self.def.tr(xcx),
552             span: self.span.tr(xcx),
553         }
554     }
555 }
556
557 // ______________________________________________________________________
558 // Encoding and decoding of CaptureVar information
559
560 trait capture_var_helper {
561     fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
562                         -> moves::CaptureVar;
563 }
564
565 impl<'a> capture_var_helper for reader::Decoder<'a> {
566     fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
567                         -> moves::CaptureVar {
568         let cvar: moves::CaptureVar = Decodable::decode(self).unwrap();
569         cvar.tr(xcx)
570     }
571 }
572
573 impl tr for moves::CaptureVar {
574     fn tr(&self, xcx: &ExtendedDecodeContext) -> moves::CaptureVar {
575         moves::CaptureVar {
576             def: self.def.tr(xcx),
577             span: self.span.tr(xcx),
578             mode: self.mode
579         }
580     }
581 }
582
583 // ______________________________________________________________________
584 // Encoding and decoding of MethodCallee
585
586 trait read_method_callee_helper {
587     fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee);
588 }
589
590 fn encode_method_callee(ecx: &e::EncodeContext,
591                         ebml_w: &mut Encoder,
592                         autoderef: u32,
593                         method: &MethodCallee) {
594     ebml_w.emit_struct("MethodCallee", 4, |ebml_w| {
595         ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
596             autoderef.encode(ebml_w)
597         });
598         ebml_w.emit_struct_field("origin", 1u, |ebml_w| {
599             method.origin.encode(ebml_w)
600         });
601         ebml_w.emit_struct_field("ty", 2u, |ebml_w| {
602             Ok(ebml_w.emit_ty(ecx, method.ty))
603         });
604         ebml_w.emit_struct_field("substs", 3u, |ebml_w| {
605             Ok(ebml_w.emit_substs(ecx, &method.substs))
606         })
607     }).unwrap();
608 }
609
610 impl<'a> read_method_callee_helper for reader::Decoder<'a> {
611     fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee) {
612         self.read_struct("MethodCallee", 4, |this| {
613             let autoderef = this.read_struct_field("autoderef", 0, |this| {
614                 Decodable::decode(this)
615             }).unwrap();
616             Ok((autoderef, MethodCallee {
617                 origin: this.read_struct_field("origin", 1, |this| {
618                     let method_origin: MethodOrigin =
619                         Decodable::decode(this).unwrap();
620                     Ok(method_origin.tr(xcx))
621                 }).unwrap(),
622                 ty: this.read_struct_field("ty", 2, |this| {
623                     Ok(this.read_ty(xcx))
624                 }).unwrap(),
625                 substs: this.read_struct_field("substs", 3, |this| {
626                     Ok(this.read_substs(xcx))
627                 }).unwrap()
628             }))
629         }).unwrap()
630     }
631 }
632
633 impl tr for MethodOrigin {
634     fn tr(&self, xcx: &ExtendedDecodeContext) -> MethodOrigin {
635         match *self {
636             typeck::MethodStatic(did) => typeck::MethodStatic(did.tr(xcx)),
637             typeck::MethodParam(ref mp) => {
638                 typeck::MethodParam(
639                     typeck::MethodParam {
640                         trait_id: mp.trait_id.tr(xcx),
641                         .. *mp
642                     }
643                 )
644             }
645             typeck::MethodObject(ref mo) => {
646                 typeck::MethodObject(
647                     typeck::MethodObject {
648                         trait_id: mo.trait_id.tr(xcx),
649                         .. *mo
650                     }
651                 )
652             }
653         }
654     }
655 }
656
657 // ______________________________________________________________________
658 // Encoding and decoding vtable_res
659
660 fn encode_vtable_res_with_key(ecx: &e::EncodeContext,
661                               ebml_w: &mut Encoder,
662                               autoderef: u32,
663                               dr: typeck::vtable_res) {
664     ebml_w.emit_struct("VtableWithKey", 2, |ebml_w| {
665         ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
666             autoderef.encode(ebml_w)
667         });
668         ebml_w.emit_struct_field("vtable_res", 1u, |ebml_w| {
669             Ok(encode_vtable_res(ecx, ebml_w, dr))
670         })
671     }).unwrap()
672 }
673
674 pub fn encode_vtable_res(ecx: &e::EncodeContext,
675                      ebml_w: &mut Encoder,
676                      dr: typeck::vtable_res) {
677     // can't autogenerate this code because automatic code of
678     // ty::t doesn't work, and there is no way (atm) to have
679     // hand-written encoding routines combine with auto-generated
680     // ones.  perhaps we should fix this.
681     ebml_w.emit_from_vec(dr.as_slice(), |ebml_w, param_tables| {
682         Ok(encode_vtable_param_res(ecx, ebml_w, *param_tables))
683     }).unwrap()
684 }
685
686 pub fn encode_vtable_param_res(ecx: &e::EncodeContext,
687                      ebml_w: &mut Encoder,
688                      param_tables: typeck::vtable_param_res) {
689     ebml_w.emit_from_vec(param_tables.as_slice(), |ebml_w, vtable_origin| {
690         Ok(encode_vtable_origin(ecx, ebml_w, vtable_origin))
691     }).unwrap()
692 }
693
694
695 pub fn encode_vtable_origin(ecx: &e::EncodeContext,
696                         ebml_w: &mut Encoder,
697                         vtable_origin: &typeck::vtable_origin) {
698     ebml_w.emit_enum("vtable_origin", |ebml_w| {
699         match *vtable_origin {
700           typeck::vtable_static(def_id, ref tys, vtable_res) => {
701             ebml_w.emit_enum_variant("vtable_static", 0u, 3u, |ebml_w| {
702                 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
703                     Ok(ebml_w.emit_def_id(def_id))
704                 });
705                 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
706                     Ok(ebml_w.emit_tys(ecx, tys.as_slice()))
707                 });
708                 ebml_w.emit_enum_variant_arg(2u, |ebml_w| {
709                     Ok(encode_vtable_res(ecx, ebml_w, vtable_res))
710                 })
711             })
712           }
713           typeck::vtable_param(pn, bn) => {
714             ebml_w.emit_enum_variant("vtable_param", 1u, 2u, |ebml_w| {
715                 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
716                     pn.encode(ebml_w)
717                 });
718                 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
719                     ebml_w.emit_uint(bn)
720                 })
721             })
722           }
723         }
724     }).unwrap()
725 }
726
727 pub trait vtable_decoder_helpers {
728     fn read_vtable_res_with_key(&mut self,
729                                 tcx: &ty::ctxt,
730                                 cdata: @cstore::crate_metadata)
731                                 -> (u32, typeck::vtable_res);
732     fn read_vtable_res(&mut self,
733                        tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
734                       -> typeck::vtable_res;
735     fn read_vtable_param_res(&mut self,
736                        tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
737                       -> typeck::vtable_param_res;
738     fn read_vtable_origin(&mut self,
739                           tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
740                           -> typeck::vtable_origin;
741 }
742
743 impl<'a> vtable_decoder_helpers for reader::Decoder<'a> {
744     fn read_vtable_res_with_key(&mut self,
745                                 tcx: &ty::ctxt,
746                                 cdata: @cstore::crate_metadata)
747                                 -> (u32, typeck::vtable_res) {
748         self.read_struct("VtableWithKey", 2, |this| {
749             let autoderef = this.read_struct_field("autoderef", 0, |this| {
750                 Decodable::decode(this)
751             }).unwrap();
752             Ok((autoderef, this.read_struct_field("vtable_res", 1, |this| {
753                 Ok(this.read_vtable_res(tcx, cdata))
754             }).unwrap()))
755         }).unwrap()
756     }
757
758     fn read_vtable_res(&mut self,
759                        tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
760                       -> typeck::vtable_res {
761         @self.read_to_vec(|this|
762                           Ok(this.read_vtable_param_res(tcx, cdata)))
763              .unwrap()
764              .move_iter()
765              .collect()
766     }
767
768     fn read_vtable_param_res(&mut self,
769                              tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
770                       -> typeck::vtable_param_res {
771         @self.read_to_vec(|this|
772                           Ok(this.read_vtable_origin(tcx, cdata)))
773              .unwrap()
774              .move_iter()
775              .collect()
776     }
777
778     fn read_vtable_origin(&mut self,
779                           tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
780         -> typeck::vtable_origin {
781         self.read_enum("vtable_origin", |this| {
782             this.read_enum_variant(["vtable_static",
783                                     "vtable_param",
784                                     "vtable_self"],
785                                    |this, i| {
786                 Ok(match i {
787                   0 => {
788                     typeck::vtable_static(
789                         this.read_enum_variant_arg(0u, |this| {
790                             Ok(this.read_def_id_noxcx(cdata))
791                         }).unwrap(),
792                         this.read_enum_variant_arg(1u, |this| {
793                             Ok(this.read_tys_noxcx(tcx, cdata))
794                         }).unwrap(),
795                         this.read_enum_variant_arg(2u, |this| {
796                             Ok(this.read_vtable_res(tcx, cdata))
797                         }).unwrap()
798                     )
799                   }
800                   1 => {
801                     typeck::vtable_param(
802                         this.read_enum_variant_arg(0u, |this| {
803                             Decodable::decode(this)
804                         }).unwrap(),
805                         this.read_enum_variant_arg(1u, |this| {
806                             this.read_uint()
807                         }).unwrap()
808                     )
809                   }
810                   // hard to avoid - user input
811                   _ => fail!("bad enum variant")
812                 })
813             })
814         }).unwrap()
815     }
816 }
817
818 // ______________________________________________________________________
819 // Encoding and decoding the side tables
820
821 trait get_ty_str_ctxt {
822     fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a>;
823 }
824
825 impl<'a> get_ty_str_ctxt for e::EncodeContext<'a> {
826     fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a> {
827         tyencode::ctxt {
828             diag: self.tcx.sess.diagnostic(),
829             ds: e::def_to_str,
830             tcx: self.tcx,
831             abbrevs: tyencode::ac_use_abbrevs(self.type_abbrevs)
832         }
833     }
834 }
835
836 trait ebml_writer_helpers {
837     fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t);
838     fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]);
839     fn emit_type_param_def(&mut self,
840                            ecx: &e::EncodeContext,
841                            type_param_def: &ty::TypeParameterDef);
842     fn emit_tpbt(&mut self,
843                  ecx: &e::EncodeContext,
844                  tpbt: ty::ty_param_bounds_and_ty);
845     fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs);
846     fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment);
847 }
848
849 impl<'a> ebml_writer_helpers for Encoder<'a> {
850     fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t) {
851         self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
852     }
853
854     fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]) {
855         self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
856     }
857
858     fn emit_type_param_def(&mut self,
859                            ecx: &e::EncodeContext,
860                            type_param_def: &ty::TypeParameterDef) {
861         self.emit_opaque(|this| {
862             Ok(tyencode::enc_type_param_def(this.writer,
863                                          &ecx.ty_str_ctxt(),
864                                          type_param_def))
865         });
866     }
867
868     fn emit_tpbt(&mut self,
869                  ecx: &e::EncodeContext,
870                  tpbt: ty::ty_param_bounds_and_ty) {
871         self.emit_struct("ty_param_bounds_and_ty", 2, |this| {
872             this.emit_struct_field("generics", 0, |this| {
873                 this.emit_struct("Generics", 2, |this| {
874                     this.emit_struct_field("type_param_defs", 0, |this| {
875                         this.emit_from_vec(tpbt.generics.type_param_defs(),
876                                            |this, type_param_def| {
877                             Ok(this.emit_type_param_def(ecx, type_param_def))
878                         })
879                     });
880                     this.emit_struct_field("region_param_defs", 1, |this| {
881                         tpbt.generics.region_param_defs().encode(this)
882                     })
883                 })
884             });
885             this.emit_struct_field("ty", 1, |this| {
886                 Ok(this.emit_ty(ecx, tpbt.ty))
887             })
888         });
889     }
890
891     fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs) {
892         self.emit_opaque(|this| Ok(tyencode::enc_substs(this.writer,
893                                                            &ecx.ty_str_ctxt(),
894                                                            substs)));
895     }
896
897     fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment) {
898         self.emit_enum("AutoAdjustment", |this| {
899             match *adj {
900                 ty::AutoAddEnv(region, sigil) => {
901                     this.emit_enum_variant("AutoAddEnv", 0, 2, |this| {
902                         this.emit_enum_variant_arg(0, |this| region.encode(this));
903                         this.emit_enum_variant_arg(1, |this| sigil.encode(this))
904                     })
905                 }
906
907                 ty::AutoDerefRef(ref auto_deref_ref) => {
908                     this.emit_enum_variant("AutoDerefRef", 1, 1, |this| {
909                         this.emit_enum_variant_arg(0, |this| auto_deref_ref.encode(this))
910                     })
911                 }
912
913                 ty::AutoObject(store, b, def_id, ref substs) => {
914                     this.emit_enum_variant("AutoObject", 2, 4, |this| {
915                         this.emit_enum_variant_arg(0, |this| store.encode(this));
916                         this.emit_enum_variant_arg(1, |this| b.encode(this));
917                         this.emit_enum_variant_arg(2, |this| def_id.encode(this));
918                         this.emit_enum_variant_arg(3, |this| Ok(this.emit_substs(ecx, substs)))
919                     })
920                 }
921             }
922         });
923     }
924 }
925
926 trait write_tag_and_id {
927     fn tag(&mut self, tag_id: c::astencode_tag, f: |&mut Self|);
928     fn id(&mut self, id: ast::NodeId);
929 }
930
931 impl<'a> write_tag_and_id for Encoder<'a> {
932     fn tag(&mut self,
933            tag_id: c::astencode_tag,
934            f: |&mut Encoder<'a>|) {
935         self.start_tag(tag_id as uint);
936         f(self);
937         self.end_tag();
938     }
939
940     fn id(&mut self, id: ast::NodeId) {
941         self.wr_tagged_u64(c::tag_table_id as uint, id as u64);
942     }
943 }
944
945 struct SideTableEncodingIdVisitor<'a,'b> {
946     ecx_ptr: *libc::c_void,
947     new_ebml_w: &'a mut Encoder<'b>,
948     maps: &'a Maps,
949 }
950
951 impl<'a,'b> ast_util::IdVisitingOperation for
952         SideTableEncodingIdVisitor<'a,'b> {
953     fn visit_id(&self, id: ast::NodeId) {
954         // Note: this will cause a copy of ebml_w, which is bad as
955         // it is mutable. But I believe it's harmless since we generate
956         // balanced EBML.
957         //
958         // FIXME(pcwalton): Don't copy this way.
959         let mut new_ebml_w = unsafe {
960             self.new_ebml_w.unsafe_clone()
961         };
962         // See above
963         let ecx: &e::EncodeContext = unsafe {
964             cast::transmute(self.ecx_ptr)
965         };
966         encode_side_tables_for_id(ecx, self.maps, &mut new_ebml_w, id)
967     }
968 }
969
970 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
971                              maps: &Maps,
972                              ebml_w: &mut Encoder,
973                              ii: &ast::InlinedItem) {
974     ebml_w.start_tag(c::tag_table as uint);
975     let mut new_ebml_w = unsafe {
976         ebml_w.unsafe_clone()
977     };
978
979     // Because the ast visitor uses @IdVisitingOperation, I can't pass in
980     // ecx directly, but /I/ know that it'll be fine since the lifetime is
981     // tied to the CrateContext that lives throughout this entire section.
982     ast_util::visit_ids_for_inlined_item(ii, &SideTableEncodingIdVisitor {
983         ecx_ptr: unsafe {
984             cast::transmute(ecx)
985         },
986         new_ebml_w: &mut new_ebml_w,
987         maps: maps,
988     });
989     ebml_w.end_tag();
990 }
991
992 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
993                              maps: &Maps,
994                              ebml_w: &mut Encoder,
995                              id: ast::NodeId) {
996     let tcx = ecx.tcx;
997
998     debug!("Encoding side tables for id {}", id);
999
1000     for def in tcx.def_map.borrow().find(&id).iter() {
1001         ebml_w.tag(c::tag_table_def, |ebml_w| {
1002             ebml_w.id(id);
1003             ebml_w.tag(c::tag_table_val, |ebml_w| (*def).encode(ebml_w).unwrap());
1004         })
1005     }
1006
1007     for &ty in tcx.node_types.borrow().find(&(id as uint)).iter() {
1008         ebml_w.tag(c::tag_table_node_type, |ebml_w| {
1009             ebml_w.id(id);
1010             ebml_w.tag(c::tag_table_val, |ebml_w| {
1011                 ebml_w.emit_ty(ecx, *ty);
1012             })
1013         })
1014     }
1015
1016     for tys in tcx.node_type_substs.borrow().find(&id).iter() {
1017         ebml_w.tag(c::tag_table_node_type_subst, |ebml_w| {
1018             ebml_w.id(id);
1019             ebml_w.tag(c::tag_table_val, |ebml_w| {
1020                 ebml_w.emit_tys(ecx, tys.as_slice())
1021             })
1022         })
1023     }
1024
1025     for &fv in tcx.freevars.borrow().find(&id).iter() {
1026         ebml_w.tag(c::tag_table_freevars, |ebml_w| {
1027             ebml_w.id(id);
1028             ebml_w.tag(c::tag_table_val, |ebml_w| {
1029                 ebml_w.emit_from_vec(fv.as_slice(), |ebml_w, fv_entry| {
1030                     Ok(encode_freevar_entry(ebml_w, *fv_entry))
1031                 });
1032             })
1033         })
1034     }
1035
1036     let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1037     for &tpbt in tcx.tcache.borrow().find(&lid).iter() {
1038         ebml_w.tag(c::tag_table_tcache, |ebml_w| {
1039             ebml_w.id(id);
1040             ebml_w.tag(c::tag_table_val, |ebml_w| {
1041                 ebml_w.emit_tpbt(ecx, tpbt.clone());
1042             })
1043         })
1044     }
1045
1046     for &type_param_def in tcx.ty_param_defs.borrow().find(&id).iter() {
1047         ebml_w.tag(c::tag_table_param_defs, |ebml_w| {
1048             ebml_w.id(id);
1049             ebml_w.tag(c::tag_table_val, |ebml_w| {
1050                 ebml_w.emit_type_param_def(ecx, type_param_def)
1051             })
1052         })
1053     }
1054
1055     let method_call = MethodCall::expr(id);
1056     for &method in maps.method_map.borrow().find(&method_call).iter() {
1057         ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1058             ebml_w.id(id);
1059             ebml_w.tag(c::tag_table_val, |ebml_w| {
1060                 encode_method_callee(ecx, ebml_w, method_call.autoderef, method)
1061             })
1062         })
1063     }
1064
1065     for &dr in maps.vtable_map.borrow().find(&method_call).iter() {
1066         ebml_w.tag(c::tag_table_vtable_map, |ebml_w| {
1067             ebml_w.id(id);
1068             ebml_w.tag(c::tag_table_val, |ebml_w| {
1069                 encode_vtable_res_with_key(ecx, ebml_w, method_call.autoderef, *dr);
1070             })
1071         })
1072     }
1073
1074     for adj in tcx.adjustments.borrow().find(&id).iter() {
1075         match ***adj {
1076             ty::AutoDerefRef(adj) => {
1077                 for autoderef in range(0, adj.autoderefs) {
1078                     let method_call = MethodCall::autoderef(id, autoderef as u32);
1079                     for &method in maps.method_map.borrow().find(&method_call).iter() {
1080                         ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1081                             ebml_w.id(id);
1082                             ebml_w.tag(c::tag_table_val, |ebml_w| {
1083                                 encode_method_callee(ecx, ebml_w, method_call.autoderef, method)
1084                             })
1085                         })
1086                     }
1087
1088                     for &dr in maps.vtable_map.borrow().find(&method_call).iter() {
1089                         ebml_w.tag(c::tag_table_vtable_map, |ebml_w| {
1090                             ebml_w.id(id);
1091                             ebml_w.tag(c::tag_table_val, |ebml_w| {
1092                                 encode_vtable_res_with_key(ecx, ebml_w,
1093                                                            method_call.autoderef, *dr);
1094                             })
1095                         })
1096                     }
1097                 }
1098             }
1099             _ => {}
1100         }
1101
1102         ebml_w.tag(c::tag_table_adjustments, |ebml_w| {
1103             ebml_w.id(id);
1104             ebml_w.tag(c::tag_table_val, |ebml_w| {
1105                 ebml_w.emit_auto_adjustment(ecx, **adj);
1106             })
1107         })
1108     }
1109
1110     for &cap_vars in maps.capture_map.borrow().find(&id).iter() {
1111         ebml_w.tag(c::tag_table_capture_map, |ebml_w| {
1112             ebml_w.id(id);
1113             ebml_w.tag(c::tag_table_val, |ebml_w| {
1114                 ebml_w.emit_from_vec(cap_vars.as_slice(), |ebml_w, cap_var| {
1115                     cap_var.encode(ebml_w)
1116                 });
1117             })
1118         })
1119     }
1120 }
1121
1122 trait doc_decoder_helpers {
1123     fn as_int(&self) -> int;
1124     fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1125 }
1126
1127 impl<'a> doc_decoder_helpers for ebml::Doc<'a> {
1128     fn as_int(&self) -> int { reader::doc_as_u64(*self) as int }
1129     fn opt_child(&self, tag: c::astencode_tag) -> Option<ebml::Doc<'a>> {
1130         reader::maybe_get_doc(*self, tag as uint)
1131     }
1132 }
1133
1134 trait ebml_decoder_decoder_helpers {
1135     fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t;
1136     fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t>;
1137     fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
1138                            -> ty::TypeParameterDef;
1139     fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
1140                                 -> ty::ty_param_bounds_and_ty;
1141     fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs;
1142     fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment;
1143     fn convert_def_id(&mut self,
1144                       xcx: &ExtendedDecodeContext,
1145                       source: DefIdSource,
1146                       did: ast::DefId)
1147                       -> ast::DefId;
1148
1149     // Versions of the type reading functions that don't need the full
1150     // ExtendedDecodeContext.
1151     fn read_ty_noxcx(&mut self,
1152                      tcx: &ty::ctxt, cdata: @cstore::crate_metadata) -> ty::t;
1153     fn read_tys_noxcx(&mut self,
1154                       tcx: &ty::ctxt,
1155                       cdata: @cstore::crate_metadata) -> Vec<ty::t>;
1156 }
1157
1158 impl<'a> ebml_decoder_decoder_helpers for reader::Decoder<'a> {
1159     fn read_ty_noxcx(&mut self,
1160                      tcx: &ty::ctxt, cdata: @cstore::crate_metadata) -> ty::t {
1161         self.read_opaque(|_, doc| {
1162             Ok(tydecode::parse_ty_data(
1163                 doc.data,
1164                 cdata.cnum,
1165                 doc.start,
1166                 tcx,
1167                 |_, id| decoder::translate_def_id(cdata, id)))
1168         }).unwrap()
1169     }
1170
1171     fn read_tys_noxcx(&mut self,
1172                       tcx: &ty::ctxt,
1173                       cdata: @cstore::crate_metadata) -> Vec<ty::t> {
1174         self.read_to_vec(|this| Ok(this.read_ty_noxcx(tcx, cdata)) )
1175             .unwrap()
1176             .move_iter()
1177             .collect()
1178     }
1179
1180     fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t {
1181         // Note: regions types embed local node ids.  In principle, we
1182         // should translate these node ids into the new decode
1183         // context.  However, we do not bother, because region types
1184         // are not used during trans.
1185
1186         return self.read_opaque(|this, doc| {
1187             debug!("read_ty({})", type_string(doc));
1188
1189             let ty = tydecode::parse_ty_data(
1190                 doc.data,
1191                 xcx.dcx.cdata.cnum,
1192                 doc.start,
1193                 xcx.dcx.tcx,
1194                 |s, a| this.convert_def_id(xcx, s, a));
1195
1196             Ok(ty)
1197         }).unwrap();
1198
1199         fn type_string(doc: ebml::Doc) -> ~str {
1200             let mut str = StrBuf::new();
1201             for i in range(doc.start, doc.end) {
1202                 str.push_char(doc.data[i] as char);
1203             }
1204             str.into_owned()
1205         }
1206     }
1207
1208     fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t> {
1209         self.read_to_vec(|this| Ok(this.read_ty(xcx))).unwrap().move_iter().collect()
1210     }
1211
1212     fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
1213                            -> ty::TypeParameterDef {
1214         self.read_opaque(|this, doc| {
1215             Ok(tydecode::parse_type_param_def_data(
1216                 doc.data,
1217                 doc.start,
1218                 xcx.dcx.cdata.cnum,
1219                 xcx.dcx.tcx,
1220                 |s, a| this.convert_def_id(xcx, s, a)))
1221         }).unwrap()
1222     }
1223
1224     fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
1225                                    -> ty::ty_param_bounds_and_ty {
1226         self.read_struct("ty_param_bounds_and_ty", 2, |this| {
1227             Ok(ty::ty_param_bounds_and_ty {
1228                 generics: this.read_struct_field("generics", 0, |this| {
1229                     this.read_struct("Generics", 2, |this| {
1230                         Ok(ty::Generics {
1231                             type_param_defs:
1232                                 this.read_struct_field("type_param_defs",
1233                                                        0,
1234                                                        |this| {
1235                                     Ok(Rc::new(this.read_to_vec(|this|
1236                                                              Ok(this.read_type_param_def(xcx)))
1237                                                 .unwrap()
1238                                                 .move_iter()
1239                                                 .collect()))
1240                             }).unwrap(),
1241                             region_param_defs:
1242                                 this.read_struct_field("region_param_defs",
1243                                                        1,
1244                                                        |this| {
1245                                     Decodable::decode(this)
1246                                 }).unwrap()
1247                         })
1248                     })
1249                 }).unwrap(),
1250                 ty: this.read_struct_field("ty", 1, |this| {
1251                     Ok(this.read_ty(xcx))
1252                 }).unwrap()
1253             })
1254         }).unwrap()
1255     }
1256
1257     fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs {
1258         self.read_opaque(|this, doc| {
1259             Ok(tydecode::parse_substs_data(doc.data,
1260                                         xcx.dcx.cdata.cnum,
1261                                         doc.start,
1262                                         xcx.dcx.tcx,
1263                                         |s, a| this.convert_def_id(xcx, s, a)))
1264         }).unwrap()
1265     }
1266
1267     fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment {
1268         self.read_enum("AutoAdjustment", |this| {
1269             let variants = ["AutoAddEnv", "AutoDerefRef", "AutoObject"];
1270             this.read_enum_variant(variants, |this, i| {
1271                 Ok(match i {
1272                     0 => {
1273                         let region: ty::Region =
1274                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1275                         let sigil: ast::Sigil =
1276                             this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1277
1278                         ty:: AutoAddEnv(region.tr(xcx), sigil)
1279                     }
1280                     1 => {
1281                         let auto_deref_ref: ty::AutoDerefRef =
1282                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1283
1284                         ty::AutoDerefRef(auto_deref_ref.tr(xcx))
1285                     }
1286                     2 => {
1287                         let store: ty::TraitStore =
1288                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1289                         let b: ty::BuiltinBounds =
1290                             this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1291                         let def_id: ast::DefId =
1292                             this.read_enum_variant_arg(2, |this| Decodable::decode(this)).unwrap();
1293                         let substs = this.read_enum_variant_arg(3, |this| Ok(this.read_substs(xcx)))
1294                                     .unwrap();
1295
1296                         ty::AutoObject(store.tr(xcx), b, def_id.tr(xcx), substs)
1297                     }
1298                     _ => fail!("bad enum variant for ty::AutoAdjustment")
1299                 })
1300             })
1301         }).unwrap()
1302     }
1303
1304     fn convert_def_id(&mut self,
1305                       xcx: &ExtendedDecodeContext,
1306                       source: tydecode::DefIdSource,
1307                       did: ast::DefId)
1308                       -> ast::DefId {
1309         /*!
1310          * Converts a def-id that appears in a type.  The correct
1311          * translation will depend on what kind of def-id this is.
1312          * This is a subtle point: type definitions are not
1313          * inlined into the current crate, so if the def-id names
1314          * a nominal type or type alias, then it should be
1315          * translated to refer to the source crate.
1316          *
1317          * However, *type parameters* are cloned along with the function
1318          * they are attached to.  So we should translate those def-ids
1319          * to refer to the new, cloned copy of the type parameter.
1320          * We only see references to free type parameters in the body of
1321          * an inlined function. In such cases, we need the def-id to
1322          * be a local id so that the TypeContents code is able to lookup
1323          * the relevant info in the ty_param_defs table.
1324          *
1325          * *Region parameters*, unfortunately, are another kettle of fish.
1326          * In such cases, def_id's can appear in types to distinguish
1327          * shadowed bound regions and so forth. It doesn't actually
1328          * matter so much what we do to these, since regions are erased
1329          * at trans time, but it's good to keep them consistent just in
1330          * case. We translate them with `tr_def_id()` which will map
1331          * the crate numbers back to the original source crate.
1332          *
1333          * It'd be really nice to refactor the type repr to not include
1334          * def-ids so that all these distinctions were unnecessary.
1335          */
1336
1337         let r = match source {
1338             NominalType | TypeWithId | RegionParameter => xcx.tr_def_id(did),
1339             TypeParameter => xcx.tr_intern_def_id(did)
1340         };
1341         debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1342         return r;
1343     }
1344 }
1345
1346 fn decode_side_tables(xcx: &ExtendedDecodeContext,
1347                       ast_doc: ebml::Doc) {
1348     let dcx = xcx.dcx;
1349     let tbl_doc = ast_doc.get(c::tag_table as uint);
1350     reader::docs(tbl_doc, |tag, entry_doc| {
1351         let id0 = entry_doc.get(c::tag_table_id as uint).as_int();
1352         let id = xcx.tr_id(id0 as ast::NodeId);
1353
1354         debug!(">> Side table document with tag 0x{:x} \
1355                 found for id {} (orig {})",
1356                tag, id, id0);
1357
1358         match c::astencode_tag::from_uint(tag) {
1359             None => {
1360                 xcx.dcx.tcx.sess.bug(
1361                     format!("unknown tag found in side tables: {:x}", tag));
1362             }
1363             Some(value) => {
1364                 let val_doc = entry_doc.get(c::tag_table_val as uint);
1365                 let mut val_dsr = reader::Decoder(val_doc);
1366                 let val_dsr = &mut val_dsr;
1367
1368                 match value {
1369                     c::tag_table_def => {
1370                         let def = decode_def(xcx, val_doc);
1371                         dcx.tcx.def_map.borrow_mut().insert(id, def);
1372                     }
1373                     c::tag_table_node_type => {
1374                         let ty = val_dsr.read_ty(xcx);
1375                         debug!("inserting ty for node {:?}: {}",
1376                                id, ty_to_str(dcx.tcx, ty));
1377                         dcx.tcx.node_types.borrow_mut().insert(id as uint, ty);
1378                     }
1379                     c::tag_table_node_type_subst => {
1380                         let tys = val_dsr.read_tys(xcx);
1381                         dcx.tcx.node_type_substs.borrow_mut().insert(id, tys);
1382                     }
1383                     c::tag_table_freevars => {
1384                         let fv_info = @val_dsr.read_to_vec(|val_dsr| {
1385                             Ok(@val_dsr.read_freevar_entry(xcx))
1386                         }).unwrap().move_iter().collect();
1387                         dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1388                     }
1389                     c::tag_table_tcache => {
1390                         let tpbt = val_dsr.read_ty_param_bounds_and_ty(xcx);
1391                         let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1392                         dcx.tcx.tcache.borrow_mut().insert(lid, tpbt);
1393                     }
1394                     c::tag_table_param_defs => {
1395                         let bounds = val_dsr.read_type_param_def(xcx);
1396                         dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1397                     }
1398                     c::tag_table_method_map => {
1399                         let (autoderef, method) = val_dsr.read_method_callee(xcx);
1400                         let method_call = MethodCall {
1401                             expr_id: id,
1402                             autoderef: autoderef
1403                         };
1404                         dcx.maps.method_map.borrow_mut().insert(method_call, method);
1405                     }
1406                     c::tag_table_vtable_map => {
1407                         let (autoderef, vtable_res) =
1408                             val_dsr.read_vtable_res_with_key(xcx.dcx.tcx,
1409                                                              xcx.dcx.cdata);
1410                         let vtable_key = MethodCall {
1411                             expr_id: id,
1412                             autoderef: autoderef
1413                         };
1414                         dcx.maps.vtable_map.borrow_mut().insert(vtable_key, vtable_res);
1415                     }
1416                     c::tag_table_adjustments => {
1417                         let adj: @ty::AutoAdjustment = @val_dsr.read_auto_adjustment(xcx);
1418                         dcx.tcx.adjustments.borrow_mut().insert(id, adj);
1419                     }
1420                     c::tag_table_capture_map => {
1421                         let cvars =
1422                                 val_dsr.read_to_vec(
1423                                             |val_dsr| Ok(val_dsr.read_capture_var(xcx)))
1424                                        .unwrap()
1425                                        .move_iter()
1426                                        .collect();
1427                         dcx.maps.capture_map.borrow_mut().insert(id, Rc::new(cvars));
1428                     }
1429                     _ => {
1430                         xcx.dcx.tcx.sess.bug(
1431                             format!("unknown tag found in side tables: {:x}", tag));
1432                     }
1433                 }
1434             }
1435         }
1436
1437         debug!(">< Side table doc loaded");
1438         true
1439     });
1440 }
1441
1442 // ______________________________________________________________________
1443 // Testing of astencode_gen
1444
1445 #[cfg(test)]
1446 fn encode_item_ast(ebml_w: &mut Encoder, item: @ast::Item) {
1447     ebml_w.start_tag(c::tag_tree as uint);
1448     (*item).encode(ebml_w);
1449     ebml_w.end_tag();
1450 }
1451
1452 #[cfg(test)]
1453 fn decode_item_ast(par_doc: ebml::Doc) -> @ast::Item {
1454     let chi_doc = par_doc.get(c::tag_tree as uint);
1455     let mut d = reader::Decoder(chi_doc);
1456     @Decodable::decode(&mut d).unwrap()
1457 }
1458
1459 #[cfg(test)]
1460 trait fake_ext_ctxt {
1461     fn cfg(&self) -> ast::CrateConfig;
1462     fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess;
1463     fn call_site(&self) -> Span;
1464     fn ident_of(&self, st: &str) -> ast::Ident;
1465 }
1466
1467 #[cfg(test)]
1468 impl fake_ext_ctxt for parse::ParseSess {
1469     fn cfg(&self) -> ast::CrateConfig {
1470         Vec::new()
1471     }
1472     fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { self }
1473     fn call_site(&self) -> Span {
1474         codemap::Span {
1475             lo: codemap::BytePos(0),
1476             hi: codemap::BytePos(0),
1477             expn_info: None
1478         }
1479     }
1480     fn ident_of(&self, st: &str) -> ast::Ident {
1481         token::str_to_ident(st)
1482     }
1483 }
1484
1485 #[cfg(test)]
1486 fn mk_ctxt() -> parse::ParseSess {
1487     parse::new_parse_sess()
1488 }
1489
1490 #[cfg(test)]
1491 fn roundtrip(in_item: Option<@ast::Item>) {
1492     use std::io::MemWriter;
1493
1494     let in_item = in_item.unwrap();
1495     let mut wr = MemWriter::new();
1496     {
1497         let mut ebml_w = writer::Encoder(&mut wr);
1498         encode_item_ast(&mut ebml_w, in_item);
1499     }
1500     let ebml_doc = reader::Doc(wr.get_ref());
1501     let out_item = decode_item_ast(ebml_doc);
1502
1503     assert!(in_item == out_item);
1504 }
1505
1506 #[test]
1507 fn test_basic() {
1508     let cx = mk_ctxt();
1509     roundtrip(quote_item!(cx,
1510         fn foo() {}
1511     ));
1512 }
1513
1514 #[test]
1515 fn test_smalltalk() {
1516     let cx = mk_ctxt();
1517     roundtrip(quote_item!(cx,
1518         fn foo() -> int { 3 + 4 } // first smalltalk program ever executed.
1519     ));
1520 }
1521
1522 #[test]
1523 fn test_more() {
1524     let cx = mk_ctxt();
1525     roundtrip(quote_item!(cx,
1526         fn foo(x: uint, y: uint) -> uint {
1527             let z = x + y;
1528             return z;
1529         }
1530     ));
1531 }
1532
1533 #[test]
1534 fn test_simplification() {
1535     let cx = mk_ctxt();
1536     let item = quote_item!(&cx,
1537         fn new_int_alist<B>() -> alist<int, B> {
1538             fn eq_int(a: int, b: int) -> bool { a == b }
1539             return alist {eq_fn: eq_int, data: Vec::new()};
1540         }
1541     ).unwrap();
1542     let item_in = e::IIItemRef(item);
1543     let item_out = simplify_ast(item_in);
1544     let item_exp = ast::IIItem(quote_item!(cx,
1545         fn new_int_alist<B>() -> alist<int, B> {
1546             return alist {eq_fn: eq_int, data: Vec::new()};
1547         }
1548     ).unwrap());
1549     match (item_out, item_exp) {
1550       (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
1551         assert!(pprust::item_to_str(item_out) == pprust::item_to_str(item_exp));
1552       }
1553       _ => fail!()
1554     }
1555 }