]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/astencode.rs
a92fe1a0f2b5bcf7b3488abd13455b364dc17656
[rust.git] / src / librustc / middle / astencode.rs
1 // Copyright 2012-2015 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 front::map as ast_map;
16 use rustc_front::hir;
17 use rustc_front::fold;
18 use rustc_front::fold::Folder;
19
20 use metadata::common as c;
21 use metadata::cstore as cstore;
22 use session::Session;
23 use metadata::decoder;
24 use metadata::encoder as e;
25 use metadata::inline::{InlinedItem, InlinedItemRef};
26 use metadata::tydecode;
27 use metadata::tyencode;
28 use middle::ty::adjustment;
29 use middle::ty::cast;
30 use middle::check_const::ConstQualif;
31 use middle::def;
32 use middle::def_id::DefId;
33 use middle::privacy::{AllPublic, LastMod};
34 use middle::region;
35 use middle::subst;
36 use middle::ty::{self, Ty};
37
38 use syntax::{ast, ast_util, codemap};
39 use syntax::ast::NodeIdAssigner;
40 use syntax::codemap::Span;
41 use syntax::ptr::P;
42
43 use std::cell::Cell;
44 use std::io::SeekFrom;
45 use std::io::prelude::*;
46 use std::fmt::Debug;
47
48 use rbml::reader;
49 use rbml::writer::Encoder;
50 use rbml;
51 use serialize;
52 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
53 use serialize::EncoderHelpers;
54
55 #[cfg(test)] use std::io::Cursor;
56 #[cfg(test)] use syntax::parse;
57 #[cfg(test)] use syntax::ast::NodeId;
58 #[cfg(test)] use rustc_front::print::pprust;
59 #[cfg(test)] use rustc_front::lowering::{lower_item, LoweringContext};
60
61 struct DecodeContext<'a, 'b, 'tcx: 'a> {
62     tcx: &'a ty::ctxt<'tcx>,
63     cdata: &'b cstore::crate_metadata,
64     from_id_range: ast_util::IdRange,
65     to_id_range: ast_util::IdRange,
66     // Cache the last used filemap for translating spans as an optimization.
67     last_filemap_index: Cell<usize>,
68 }
69
70 trait tr {
71     fn tr(&self, dcx: &DecodeContext) -> Self;
72 }
73
74 // ______________________________________________________________________
75 // Top-level methods.
76
77 pub fn encode_inlined_item(ecx: &e::EncodeContext,
78                            rbml_w: &mut Encoder,
79                            ii: InlinedItemRef) {
80     let id = match ii {
81         InlinedItemRef::Item(i) => i.id,
82         InlinedItemRef::Foreign(i) => i.id,
83         InlinedItemRef::TraitItem(_, ti) => ti.id,
84         InlinedItemRef::ImplItem(_, ii) => ii.id,
85     };
86     debug!("> Encoding inlined item: {} ({:?})",
87            ecx.tcx.map.path_to_string(id),
88            rbml_w.writer.seek(SeekFrom::Current(0)));
89
90     // Folding could be avoided with a smarter encoder.
91     let ii = simplify_ast(ii);
92     let id_range = ii.compute_id_range();
93
94     rbml_w.start_tag(c::tag_ast as usize);
95     id_range.encode(rbml_w);
96     encode_ast(rbml_w, &ii);
97     encode_side_tables_for_ii(ecx, rbml_w, &ii);
98     rbml_w.end_tag();
99
100     debug!("< Encoded inlined fn: {} ({:?})",
101            ecx.tcx.map.path_to_string(id),
102            rbml_w.writer.seek(SeekFrom::Current(0)));
103 }
104
105 impl<'a, 'b, 'c, 'tcx> ast_map::FoldOps for &'a DecodeContext<'b, 'c, 'tcx> {
106     fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
107         if id == ast::DUMMY_NODE_ID {
108             // Used by ast_map to map the NodeInlinedParent.
109             self.tcx.sess.next_node_id()
110         } else {
111             self.tr_id(id)
112         }
113     }
114     fn new_def_id(&self, def_id: DefId) -> DefId {
115         self.tr_def_id(def_id)
116     }
117     fn new_span(&self, span: Span) -> Span {
118         self.tr_span(span)
119     }
120 }
121
122 /// Decodes an item from its AST in the cdata's metadata and adds it to the
123 /// ast-map.
124 pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
125                                  tcx: &ty::ctxt<'tcx>,
126                                  path: Vec<ast_map::PathElem>,
127                                  def_path: ast_map::DefPath,
128                                  par_doc: rbml::Doc,
129                                  orig_did: DefId)
130                                  -> Result<&'tcx InlinedItem, (Vec<ast_map::PathElem>,
131                                                                ast_map::DefPath)> {
132     match par_doc.opt_child(c::tag_ast) {
133       None => Err((path, def_path)),
134       Some(ast_doc) => {
135         let mut path_as_str = None;
136         debug!("> Decoding inlined fn: {:?}::?",
137         {
138             // Do an Option dance to use the path after it is moved below.
139             let s = ast_map::path_to_string(path.iter().cloned());
140             path_as_str = Some(s);
141             path_as_str.as_ref().map(|x| &x[..])
142         });
143         let mut ast_dsr = reader::Decoder::new(ast_doc);
144         let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
145         let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
146         let dcx = &DecodeContext {
147             cdata: cdata,
148             tcx: tcx,
149             from_id_range: from_id_range,
150             to_id_range: to_id_range,
151             last_filemap_index: Cell::new(0)
152         };
153         let raw_ii = decode_ast(ast_doc);
154         let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, def_path, raw_ii, dcx);
155
156         let name = match *ii {
157             InlinedItem::Item(ref i) => i.name,
158             InlinedItem::Foreign(ref i) => i.name,
159             InlinedItem::TraitItem(_, ref ti) => ti.name,
160             InlinedItem::ImplItem(_, ref ii) => ii.name
161         };
162         debug!("Fn named: {}", name);
163         debug!("< Decoded inlined fn: {}::{}",
164                path_as_str.unwrap(),
165                name);
166         region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
167         decode_side_tables(dcx, ast_doc);
168         copy_item_types(dcx, ii, orig_did);
169         match *ii {
170           InlinedItem::Item(ref i) => {
171             debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
172                    ::rustc_front::print::pprust::item_to_string(&**i));
173           }
174           _ => { }
175         }
176         Ok(ii)
177       }
178     }
179 }
180
181 // ______________________________________________________________________
182 // Enumerating the IDs which appear in an AST
183
184 fn reserve_id_range(sess: &Session,
185                     from_id_range: ast_util::IdRange) -> ast_util::IdRange {
186     // Handle the case of an empty range:
187     if from_id_range.empty() { return from_id_range; }
188     let cnt = from_id_range.max - from_id_range.min;
189     let to_id_min = sess.reserve_node_ids(cnt);
190     let to_id_max = to_id_min + cnt;
191     ast_util::IdRange { min: to_id_min, max: to_id_max }
192 }
193
194 impl<'a, 'b, 'tcx> DecodeContext<'a, 'b, 'tcx> {
195     /// Translates an internal id, meaning a node id that is known to refer to some part of the
196     /// item currently being inlined, such as a local variable or argument.  All naked node-ids
197     /// that appear in types have this property, since if something might refer to an external item
198     /// we would use a def-id to allow for the possibility that the item resides in another crate.
199     pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
200         // from_id_range should be non-empty
201         assert!(!self.from_id_range.empty());
202         // Use wrapping arithmetic because otherwise it introduces control flow.
203         // Maybe we should just have the control flow? -- aatch
204         (id.wrapping_sub(self.from_id_range.min).wrapping_add(self.to_id_range.min))
205     }
206
207     /// Translates an EXTERNAL def-id, converting the crate number from the one used in the encoded
208     /// data to the current crate numbers..  By external, I mean that it be translated to a
209     /// reference to the item in its original crate, as opposed to being translated to a reference
210     /// to the inlined version of the item.  This is typically, but not always, what you want,
211     /// because most def-ids refer to external things like types or other fns that may or may not
212     /// be inlined.  Note that even when the inlined function is referencing itself recursively, we
213     /// would want `tr_def_id` for that reference--- conceptually the function calls the original,
214     /// non-inlined version, and trans deals with linking that recursive call to the inlined copy.
215     pub fn tr_def_id(&self, did: DefId) -> DefId {
216         decoder::translate_def_id(self.cdata, did)
217     }
218
219     /// Translates a `Span` from an extern crate to the corresponding `Span`
220     /// within the local crate's codemap. `creader::import_codemap()` will
221     /// already have allocated any additionally needed FileMaps in the local
222     /// codemap as a side-effect of creating the crate_metadata's
223     /// `codemap_import_info`.
224     pub fn tr_span(&self, span: Span) -> Span {
225         let span = if span.lo > span.hi {
226             // Currently macro expansion sometimes produces invalid Span values
227             // where lo > hi. In order not to crash the compiler when trying to
228             // translate these values, let's transform them into something we
229             // can handle (and which will produce useful debug locations at
230             // least some of the time).
231             // This workaround is only necessary as long as macro expansion is
232             // not fixed. FIXME(#23480)
233             codemap::mk_sp(span.lo, span.lo)
234         } else {
235             span
236         };
237
238         let imported_filemaps = self.cdata.imported_filemaps(self.tcx.sess.codemap());
239         let filemap = {
240             // Optimize for the case that most spans within a translated item
241             // originate from the same filemap.
242             let last_filemap_index = self.last_filemap_index.get();
243             let last_filemap = &imported_filemaps[last_filemap_index];
244
245             if span.lo >= last_filemap.original_start_pos &&
246                span.lo <= last_filemap.original_end_pos &&
247                span.hi >= last_filemap.original_start_pos &&
248                span.hi <= last_filemap.original_end_pos {
249                 last_filemap
250             } else {
251                 let mut a = 0;
252                 let mut b = imported_filemaps.len();
253
254                 while b - a > 1 {
255                     let m = (a + b) / 2;
256                     if imported_filemaps[m].original_start_pos > span.lo {
257                         b = m;
258                     } else {
259                         a = m;
260                     }
261                 }
262
263                 self.last_filemap_index.set(a);
264                 &imported_filemaps[a]
265             }
266         };
267
268         let lo = (span.lo - filemap.original_start_pos) +
269                   filemap.translated_filemap.start_pos;
270         let hi = (span.hi - filemap.original_start_pos) +
271                   filemap.translated_filemap.start_pos;
272
273         codemap::mk_sp(lo, hi)
274     }
275 }
276
277 impl tr for DefId {
278     fn tr(&self, dcx: &DecodeContext) -> DefId {
279         dcx.tr_def_id(*self)
280     }
281 }
282
283 impl tr for Option<DefId> {
284     fn tr(&self, dcx: &DecodeContext) -> Option<DefId> {
285         self.map(|d| dcx.tr_def_id(d))
286     }
287 }
288
289 impl tr for Span {
290     fn tr(&self, dcx: &DecodeContext) -> Span {
291         dcx.tr_span(*self)
292     }
293 }
294
295 trait def_id_encoder_helpers {
296     fn emit_def_id(&mut self, did: DefId);
297 }
298
299 impl<S:serialize::Encoder> def_id_encoder_helpers for S
300     where <S as serialize::serialize::Encoder>::Error: Debug
301 {
302     fn emit_def_id(&mut self, did: DefId) {
303         did.encode(self).unwrap()
304     }
305 }
306
307 trait def_id_decoder_helpers {
308     fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId;
309     fn read_def_id_nodcx(&mut self,
310                          cdata: &cstore::crate_metadata) -> DefId;
311 }
312
313 impl<D:serialize::Decoder> def_id_decoder_helpers for D
314     where <D as serialize::serialize::Decoder>::Error: Debug
315 {
316     fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId {
317         let did: DefId = Decodable::decode(self).unwrap();
318         did.tr(dcx)
319     }
320
321     fn read_def_id_nodcx(&mut self,
322                          cdata: &cstore::crate_metadata)
323                          -> DefId {
324         let did: DefId = Decodable::decode(self).unwrap();
325         decoder::translate_def_id(cdata, did)
326     }
327 }
328
329 // ______________________________________________________________________
330 // Encoding and decoding the AST itself
331 //
332 // When decoding, we have to renumber the AST so that the node ids that
333 // appear within are disjoint from the node ids in our existing ASTs.
334 // We also have to adjust the spans: for now we just insert a dummy span,
335 // but eventually we should add entries to the local codemap as required.
336
337 fn encode_ast(rbml_w: &mut Encoder, item: &InlinedItem) {
338     rbml_w.start_tag(c::tag_tree as usize);
339     item.encode(rbml_w);
340     rbml_w.end_tag();
341 }
342
343 struct NestedItemsDropper;
344
345 impl Folder for NestedItemsDropper {
346     fn fold_block(&mut self, blk: P<hir::Block>) -> P<hir::Block> {
347         blk.and_then(|hir::Block {id, stmts, expr, rules, span, ..}| {
348             let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
349                 let use_stmt = match stmt.node {
350                     hir::StmtExpr(_, _) | hir::StmtSemi(_, _) => true,
351                     hir::StmtDecl(ref decl, _) => {
352                         match decl.node {
353                             hir::DeclLocal(_) => true,
354                             hir::DeclItem(_) => false,
355                         }
356                     }
357                 };
358                 if use_stmt {
359                     Some(stmt)
360                 } else {
361                     None
362                 }
363             }).collect();
364             let blk_sans_items = P(hir::Block {
365                 stmts: stmts_sans_items,
366                 expr: expr,
367                 id: id,
368                 rules: rules,
369                 span: span,
370             });
371             fold::noop_fold_block(blk_sans_items, self)
372         })
373     }
374 }
375
376 // Produces a simplified copy of the AST which does not include things
377 // that we do not need to or do not want to export.  For example, we
378 // do not include any nested items: if these nested items are to be
379 // inlined, their AST will be exported separately (this only makes
380 // sense because, in Rust, nested items are independent except for
381 // their visibility).
382 //
383 // As it happens, trans relies on the fact that we do not export
384 // nested items, as otherwise it would get confused when translating
385 // inlined items.
386 fn simplify_ast(ii: InlinedItemRef) -> InlinedItem {
387     let mut fld = NestedItemsDropper;
388
389     match ii {
390         // HACK we're not dropping items.
391         InlinedItemRef::Item(i) => {
392             InlinedItem::Item(fold::noop_fold_item(P(i.clone()), &mut fld))
393         }
394         InlinedItemRef::TraitItem(d, ti) => {
395             InlinedItem::TraitItem(d, fold::noop_fold_trait_item(P(ti.clone()), &mut fld))
396         }
397         InlinedItemRef::ImplItem(d, ii) => {
398             InlinedItem::ImplItem(d, fold::noop_fold_impl_item(P(ii.clone()), &mut fld))
399         }
400         InlinedItemRef::Foreign(i) => {
401             InlinedItem::Foreign(fold::noop_fold_foreign_item(P(i.clone()), &mut fld))
402         }
403     }
404 }
405
406 fn decode_ast(par_doc: rbml::Doc) -> InlinedItem {
407     let chi_doc = par_doc.get(c::tag_tree as usize);
408     let mut d = reader::Decoder::new(chi_doc);
409     Decodable::decode(&mut d).unwrap()
410 }
411
412 // ______________________________________________________________________
413 // Encoding and decoding of ast::def
414
415 fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> def::Def {
416     let def: def::Def = Decodable::decode(dsr).unwrap();
417     def.tr(dcx)
418 }
419
420 impl tr for def::Def {
421     fn tr(&self, dcx: &DecodeContext) -> def::Def {
422         match *self {
423           def::DefFn(did, is_ctor) => def::DefFn(did.tr(dcx), is_ctor),
424           def::DefMethod(did) => def::DefMethod(did.tr(dcx)),
425           def::DefSelfTy(opt_did, impl_ids) => { def::DefSelfTy(opt_did.map(|did| did.tr(dcx)),
426                                                                 impl_ids.map(|(nid1, nid2)| {
427                                                                     (dcx.tr_id(nid1),
428                                                                      dcx.tr_id(nid2))
429                                                                 })) }
430           def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
431           def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
432           def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
433           def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
434           def::DefAssociatedConst(did) => def::DefAssociatedConst(did.tr(dcx)),
435           def::DefLocal(_, nid) => {
436               let nid = dcx.tr_id(nid);
437               let did = dcx.tcx.map.local_def_id(nid);
438               def::DefLocal(did, nid)
439           }
440           def::DefVariant(e_did, v_did, is_s) => {
441             def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
442           },
443           def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
444           def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
445           def::DefAssociatedTy(trait_did, did) =>
446               def::DefAssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
447           def::DefPrimTy(p) => def::DefPrimTy(p),
448           def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
449           def::DefUse(did) => def::DefUse(did.tr(dcx)),
450           def::DefUpvar(_, nid1, index, nid2) => {
451               let nid1 = dcx.tr_id(nid1);
452               let nid2 = dcx.tr_id(nid2);
453               let did1 = dcx.tcx.map.local_def_id(nid1);
454               def::DefUpvar(did1, nid1, index, nid2)
455           }
456           def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
457           def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
458         }
459     }
460 }
461
462 // ______________________________________________________________________
463 // Encoding and decoding of freevar information
464
465 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
466     (*fv).encode(rbml_w).unwrap();
467 }
468
469 trait rbml_decoder_helper {
470     fn read_freevar_entry(&mut self, dcx: &DecodeContext)
471                           -> ty::Freevar;
472     fn read_capture_mode(&mut self) -> hir::CaptureClause;
473 }
474
475 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
476     fn read_freevar_entry(&mut self, dcx: &DecodeContext)
477                           -> ty::Freevar {
478         let fv: ty::Freevar = Decodable::decode(self).unwrap();
479         fv.tr(dcx)
480     }
481
482     fn read_capture_mode(&mut self) -> hir::CaptureClause {
483         let cm: hir::CaptureClause = Decodable::decode(self).unwrap();
484         cm
485     }
486 }
487
488 impl tr for ty::Freevar {
489     fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
490         ty::Freevar {
491             def: self.def.tr(dcx),
492             span: self.span.tr(dcx),
493         }
494     }
495 }
496
497 // ______________________________________________________________________
498 // Encoding and decoding of MethodCallee
499
500 trait read_method_callee_helper<'tcx> {
501     fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
502                                   -> (u32, ty::MethodCallee<'tcx>);
503 }
504
505 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
506                                   rbml_w: &mut Encoder,
507                                   autoderef: u32,
508                                   method: &ty::MethodCallee<'tcx>) {
509     use serialize::Encoder;
510
511     rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
512         rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
513             autoderef.encode(rbml_w)
514         });
515         rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
516             Ok(rbml_w.emit_def_id(method.def_id))
517         });
518         rbml_w.emit_struct_field("ty", 2, |rbml_w| {
519             Ok(rbml_w.emit_ty(ecx, method.ty))
520         });
521         rbml_w.emit_struct_field("substs", 3, |rbml_w| {
522             Ok(rbml_w.emit_substs(ecx, &method.substs))
523         })
524     }).unwrap();
525 }
526
527 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
528     fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
529                                   -> (u32, ty::MethodCallee<'tcx>) {
530
531         self.read_struct("MethodCallee", 4, |this| {
532             let autoderef = this.read_struct_field("autoderef", 0,
533                                                    Decodable::decode).unwrap();
534             Ok((autoderef, ty::MethodCallee {
535                 def_id: this.read_struct_field("def_id", 1, |this| {
536                     Ok(this.read_def_id(dcx))
537                 }).unwrap(),
538                 ty: this.read_struct_field("ty", 2, |this| {
539                     Ok(this.read_ty(dcx))
540                 }).unwrap(),
541                 substs: this.read_struct_field("substs", 3, |this| {
542                     Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
543                 }).unwrap()
544             }))
545         }).unwrap()
546     }
547 }
548
549 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
550     kind.encode(ebml_w).unwrap();
551 }
552
553 // ______________________________________________________________________
554 // Encoding and decoding the side tables
555
556 trait get_ty_str_ctxt<'tcx> {
557     fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
558 }
559
560 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
561     fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
562         tyencode::ctxt {
563             diag: self.tcx.sess.diagnostic(),
564             ds: e::def_to_string,
565             tcx: self.tcx,
566             abbrevs: &self.type_abbrevs
567         }
568     }
569 }
570
571 trait rbml_writer_helpers<'tcx> {
572     fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region);
573     fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
574     fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
575     fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
576                           predicate: &ty::Predicate<'tcx>);
577     fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
578                           ty: &ty::TraitRef<'tcx>);
579     fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
580                        substs: &subst::Substs<'tcx>);
581     fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
582                                    bounds: &ty::ExistentialBounds<'tcx>);
583     fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
584     fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture);
585     fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
586                                 adj: &adjustment::AutoAdjustment<'tcx>);
587     fn emit_autoref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
588                         autoref: &adjustment::AutoRef<'tcx>);
589     fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
590                                auto_deref_ref: &adjustment::AutoDerefRef<'tcx>);
591 }
592
593 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
594     fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region) {
595         self.emit_opaque(|this| Ok(e::write_region(ecx, this, r)));
596     }
597
598     fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
599         self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
600     }
601
602     fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
603         self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
604     }
605
606     fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
607                           trait_ref: &ty::TraitRef<'tcx>) {
608         self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
609     }
610
611     fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
612                           predicate: &ty::Predicate<'tcx>) {
613         self.emit_opaque(|this| {
614             Ok(tyencode::enc_predicate(this,
615                                        &ecx.ty_str_ctxt(),
616                                        predicate))
617         });
618     }
619
620     fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
621                                    bounds: &ty::ExistentialBounds<'tcx>) {
622         self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
623                                                                     &ecx.ty_str_ctxt(),
624                                                                     bounds)));
625     }
626
627     fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
628         self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
629                                                                 &ecx.ty_str_ctxt(),
630                                                                 bounds)));
631     }
632
633     fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture) {
634         use serialize::Encoder;
635
636         self.emit_enum("UpvarCapture", |this| {
637             match *capture {
638                 ty::UpvarCapture::ByValue => {
639                     this.emit_enum_variant("ByValue", 1, 0, |_| Ok(()))
640                 }
641                 ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind, region }) => {
642                     this.emit_enum_variant("ByRef", 2, 0, |this| {
643                         this.emit_enum_variant_arg(0,
644                             |this| kind.encode(this));
645                         this.emit_enum_variant_arg(1,
646                             |this| Ok(this.emit_region(ecx, region)))
647                     })
648                 }
649             }
650         }).unwrap()
651     }
652
653     fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
654                        substs: &subst::Substs<'tcx>) {
655         self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
656                                                            &ecx.ty_str_ctxt(),
657                                                            substs)));
658     }
659
660     fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
661                                 adj: &adjustment::AutoAdjustment<'tcx>) {
662         use serialize::Encoder;
663
664         self.emit_enum("AutoAdjustment", |this| {
665             match *adj {
666                 adjustment::AdjustReifyFnPointer=> {
667                     this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
668                 }
669
670                 adjustment::AdjustUnsafeFnPointer => {
671                     this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
672                         Ok(())
673                     })
674                 }
675
676                 adjustment::AdjustDerefRef(ref auto_deref_ref) => {
677                     this.emit_enum_variant("AdjustDerefRef", 3, 2, |this| {
678                         this.emit_enum_variant_arg(0,
679                             |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
680                     })
681                 }
682             }
683         });
684     }
685
686     fn emit_autoref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
687                         autoref: &adjustment::AutoRef<'tcx>) {
688         use serialize::Encoder;
689
690         self.emit_enum("AutoRef", |this| {
691             match autoref {
692                 &adjustment::AutoPtr(r, m) => {
693                     this.emit_enum_variant("AutoPtr", 0, 2, |this| {
694                         this.emit_enum_variant_arg(0,
695                             |this| Ok(this.emit_region(ecx, *r)));
696                         this.emit_enum_variant_arg(1, |this| m.encode(this))
697                     })
698                 }
699                 &adjustment::AutoUnsafe(m) => {
700                     this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
701                         this.emit_enum_variant_arg(0, |this| m.encode(this))
702                     })
703                 }
704             }
705         });
706     }
707
708     fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
709                                auto_deref_ref: &adjustment::AutoDerefRef<'tcx>) {
710         use serialize::Encoder;
711
712         self.emit_struct("AutoDerefRef", 2, |this| {
713             this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
714
715             this.emit_struct_field("autoref", 1, |this| {
716                 this.emit_option(|this| {
717                     match auto_deref_ref.autoref {
718                         None => this.emit_option_none(),
719                         Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a))),
720                     }
721                 })
722             });
723
724             this.emit_struct_field("unsize", 2, |this| {
725                 this.emit_option(|this| {
726                     match auto_deref_ref.unsize {
727                         None => this.emit_option_none(),
728                         Some(target) => this.emit_option_some(|this| {
729                             Ok(this.emit_ty(ecx, target))
730                         })
731                     }
732                 })
733             })
734         });
735     }
736 }
737
738 trait write_tag_and_id {
739     fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
740     fn id(&mut self, id: ast::NodeId);
741 }
742
743 impl<'a> write_tag_and_id for Encoder<'a> {
744     fn tag<F>(&mut self,
745               tag_id: c::astencode_tag,
746               f: F) where
747         F: FnOnce(&mut Encoder<'a>),
748     {
749         self.start_tag(tag_id as usize);
750         f(self);
751         self.end_tag();
752     }
753
754     fn id(&mut self, id: ast::NodeId) {
755         id.encode(self).unwrap();
756     }
757 }
758
759 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
760     ecx: &'a e::EncodeContext<'c, 'tcx>,
761     rbml_w: &'a mut Encoder<'b>,
762 }
763
764 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
765         SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
766     fn visit_id(&mut self, id: ast::NodeId) {
767         encode_side_tables_for_id(self.ecx, self.rbml_w, id)
768     }
769 }
770
771 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
772                              rbml_w: &mut Encoder,
773                              ii: &InlinedItem) {
774     rbml_w.start_tag(c::tag_table as usize);
775     ii.visit_ids(&mut SideTableEncodingIdVisitor {
776         ecx: ecx,
777         rbml_w: rbml_w
778     });
779     rbml_w.end_tag();
780 }
781
782 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
783                              rbml_w: &mut Encoder,
784                              id: ast::NodeId) {
785     let tcx = ecx.tcx;
786
787     debug!("Encoding side tables for id {}", id);
788
789     if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
790         rbml_w.tag(c::tag_table_def, |rbml_w| {
791             rbml_w.id(id);
792             def.encode(rbml_w).unwrap();
793         })
794     }
795
796     if let Some(ty) = tcx.node_types().get(&id) {
797         rbml_w.tag(c::tag_table_node_type, |rbml_w| {
798             rbml_w.id(id);
799             rbml_w.emit_ty(ecx, *ty);
800         })
801     }
802
803     if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
804         rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
805             rbml_w.id(id);
806             rbml_w.emit_substs(ecx, &item_substs.substs);
807         })
808     }
809
810     if let Some(fv) = tcx.freevars.borrow().get(&id) {
811         rbml_w.tag(c::tag_table_freevars, |rbml_w| {
812             rbml_w.id(id);
813             rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
814                 Ok(encode_freevar_entry(rbml_w, fv_entry))
815             });
816         });
817
818         for freevar in fv {
819             rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
820                 rbml_w.id(id);
821
822                 let var_id = freevar.def.var_id();
823                 let upvar_id = ty::UpvarId {
824                     var_id: var_id,
825                     closure_expr_id: id
826                 };
827                 let upvar_capture = tcx.tables
828                                        .borrow()
829                                        .upvar_capture_map
830                                        .get(&upvar_id)
831                                        .unwrap()
832                                        .clone();
833                 var_id.encode(rbml_w);
834                 rbml_w.emit_upvar_capture(ecx, &upvar_capture);
835             })
836         }
837     }
838
839     let method_call = ty::MethodCall::expr(id);
840     if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
841         rbml_w.tag(c::tag_table_method_map, |rbml_w| {
842             rbml_w.id(id);
843             encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
844         })
845     }
846
847     if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
848         match *adjustment {
849             adjustment::AdjustDerefRef(ref adj) => {
850                 for autoderef in 0..adj.autoderefs {
851                     let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
852                     if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
853                         rbml_w.tag(c::tag_table_method_map, |rbml_w| {
854                             rbml_w.id(id);
855                             encode_method_callee(ecx, rbml_w,
856                                                  method_call.autoderef, method)
857                         })
858                     }
859                 }
860             }
861             _ => {}
862         }
863
864         rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
865             rbml_w.id(id);
866             rbml_w.emit_auto_adjustment(ecx, adjustment);
867         })
868     }
869
870     if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
871         rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
872             rbml_w.id(id);
873             encode_cast_kind(rbml_w, *cast_kind)
874         })
875     }
876
877     if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
878         rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
879             rbml_w.id(id);
880             qualif.encode(rbml_w).unwrap()
881         })
882     }
883 }
884
885 trait doc_decoder_helpers: Sized {
886     fn as_int(&self) -> isize;
887     fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
888 }
889
890 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
891     fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
892     fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
893         reader::maybe_get_doc(*self, tag as usize)
894     }
895 }
896
897 trait rbml_decoder_decoder_helpers<'tcx> {
898     fn read_ty_encoded<'a, 'b, F, R>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>,
899                                      f: F) -> R
900         where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x, 'tcx>) -> R;
901
902     fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region;
903     fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
904     fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
905     fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
906                               -> ty::TraitRef<'tcx>;
907     fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
908                                    -> ty::PolyTraitRef<'tcx>;
909     fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
910                               -> ty::Predicate<'tcx>;
911     fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
912                                        -> ty::ExistentialBounds<'tcx>;
913     fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
914                            -> subst::Substs<'tcx>;
915     fn read_upvar_capture(&mut self, dcx: &DecodeContext)
916                           -> ty::UpvarCapture;
917     fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
918                                     -> adjustment::AutoAdjustment<'tcx>;
919     fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
920                                  -> cast::CastKind;
921     fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
922                                    -> adjustment::AutoDerefRef<'tcx>;
923     fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
924                             -> adjustment::AutoRef<'tcx>;
925     fn convert_def_id(&mut self,
926                       dcx: &DecodeContext,
927                       did: DefId)
928                       -> DefId;
929
930     // Versions of the type reading functions that don't need the full
931     // DecodeContext.
932     fn read_ty_nodcx(&mut self,
933                      tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
934     fn read_tys_nodcx(&mut self,
935                       tcx: &ty::ctxt<'tcx>,
936                       cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
937     fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
938                          cdata: &cstore::crate_metadata)
939                          -> subst::Substs<'tcx>;
940 }
941
942 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
943     fn read_ty_nodcx(&mut self,
944                      tcx: &ty::ctxt<'tcx>,
945                      cdata: &cstore::crate_metadata)
946                      -> Ty<'tcx> {
947         self.read_opaque(|_, doc| {
948             Ok(
949                 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
950                                               &mut |id| decoder::translate_def_id(cdata, id))
951                     .parse_ty())
952         }).unwrap()
953     }
954
955     fn read_tys_nodcx(&mut self,
956                       tcx: &ty::ctxt<'tcx>,
957                       cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
958         self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
959             .unwrap()
960             .into_iter()
961             .collect()
962     }
963
964     fn read_substs_nodcx(&mut self,
965                          tcx: &ty::ctxt<'tcx>,
966                          cdata: &cstore::crate_metadata)
967                          -> subst::Substs<'tcx>
968     {
969         self.read_opaque(|_, doc| {
970             Ok(
971                 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
972                                               &mut |id| decoder::translate_def_id(cdata, id))
973                     .parse_substs())
974         }).unwrap()
975     }
976
977     fn read_ty_encoded<'b, 'c, F, R>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>, op: F) -> R
978         where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x,'tcx>) -> R
979     {
980         return self.read_opaque(|this, doc| {
981             debug!("read_ty_encoded({})", type_string(doc));
982             Ok(op(
983                 &mut tydecode::TyDecoder::with_doc(
984                     dcx.tcx, dcx.cdata.cnum, doc,
985                     &mut |a| this.convert_def_id(dcx, a))))
986         }).unwrap();
987
988         fn type_string(doc: rbml::Doc) -> String {
989             let mut str = String::new();
990             for i in doc.start..doc.end {
991                 str.push(doc.data[i] as char);
992             }
993             str
994         }
995     }
996     fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region {
997         // Note: regions types embed local node ids.  In principle, we
998         // should translate these node ids into the new decode
999         // context.  However, we do not bother, because region types
1000         // are not used during trans. This also applies to read_ty.
1001         return self.read_ty_encoded(dcx, |decoder| decoder.parse_region());
1002     }
1003     fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1004         return self.read_ty_encoded(dcx, |decoder| decoder.parse_ty());
1005     }
1006
1007     fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1008                         -> Vec<Ty<'tcx>> {
1009         self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1010     }
1011
1012     fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1013                               -> ty::TraitRef<'tcx> {
1014         self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref())
1015     }
1016
1017     fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1018                                    -> ty::PolyTraitRef<'tcx> {
1019         ty::Binder(self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref()))
1020     }
1021
1022     fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1023                               -> ty::Predicate<'tcx>
1024     {
1025         self.read_ty_encoded(dcx, |decoder| decoder.parse_predicate())
1026     }
1027
1028     fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1029                                        -> ty::ExistentialBounds<'tcx>
1030     {
1031         self.read_ty_encoded(dcx, |decoder| decoder.parse_existential_bounds())
1032     }
1033
1034     fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1035                            -> subst::Substs<'tcx> {
1036         self.read_opaque(|this, doc| {
1037             Ok(tydecode::TyDecoder::with_doc(dcx.tcx, dcx.cdata.cnum, doc,
1038                                              &mut |a| this.convert_def_id(dcx, a))
1039                .parse_substs())
1040         }).unwrap()
1041     }
1042     fn read_upvar_capture(&mut self, dcx: &DecodeContext) -> ty::UpvarCapture {
1043         self.read_enum("UpvarCapture", |this| {
1044             let variants = ["ByValue", "ByRef"];
1045             this.read_enum_variant(&variants, |this, i| {
1046                 Ok(match i {
1047                     1 => ty::UpvarCapture::ByValue,
1048                     2 => ty::UpvarCapture::ByRef(ty::UpvarBorrow {
1049                         kind: this.read_enum_variant_arg(0,
1050                                   |this| Decodable::decode(this)).unwrap(),
1051                         region: this.read_enum_variant_arg(1,
1052                                     |this| Ok(this.read_region(dcx))).unwrap()
1053                     }),
1054                     _ => panic!("bad enum variant for ty::UpvarCapture")
1055                 })
1056             })
1057         }).unwrap()
1058     }
1059     fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1060                                     -> adjustment::AutoAdjustment<'tcx> {
1061         self.read_enum("AutoAdjustment", |this| {
1062             let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer", "AdjustDerefRef"];
1063             this.read_enum_variant(&variants, |this, i| {
1064                 Ok(match i {
1065                     1 => adjustment::AdjustReifyFnPointer,
1066                     2 => adjustment::AdjustUnsafeFnPointer,
1067                     3 => {
1068                         let auto_deref_ref: adjustment::AutoDerefRef =
1069                             this.read_enum_variant_arg(0,
1070                                 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1071
1072                         adjustment::AdjustDerefRef(auto_deref_ref)
1073                     }
1074                     _ => panic!("bad enum variant for adjustment::AutoAdjustment")
1075                 })
1076             })
1077         }).unwrap()
1078     }
1079
1080     fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1081                                    -> adjustment::AutoDerefRef<'tcx> {
1082         self.read_struct("AutoDerefRef", 2, |this| {
1083             Ok(adjustment::AutoDerefRef {
1084                 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1085                     Decodable::decode(this)
1086                 }).unwrap(),
1087                 autoref: this.read_struct_field("autoref", 1, |this| {
1088                     this.read_option(|this, b| {
1089                         if b {
1090                             Ok(Some(this.read_autoref(dcx)))
1091                         } else {
1092                             Ok(None)
1093                         }
1094                     })
1095                 }).unwrap(),
1096                 unsize: this.read_struct_field("unsize", 2, |this| {
1097                     this.read_option(|this, b| {
1098                         if b {
1099                             Ok(Some(this.read_ty(dcx)))
1100                         } else {
1101                             Ok(None)
1102                         }
1103                     })
1104                 }).unwrap(),
1105             })
1106         }).unwrap()
1107     }
1108
1109     fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1110                             -> adjustment::AutoRef<'tcx> {
1111         self.read_enum("AutoRef", |this| {
1112             let variants = ["AutoPtr", "AutoUnsafe"];
1113             this.read_enum_variant(&variants, |this, i| {
1114                 Ok(match i {
1115                     0 => {
1116                         let r: ty::Region =
1117                             this.read_enum_variant_arg(0, |this| {
1118                                 Ok(this.read_region(dcx))
1119                             }).unwrap();
1120                         let m: hir::Mutability =
1121                             this.read_enum_variant_arg(1, |this| {
1122                                 Decodable::decode(this)
1123                             }).unwrap();
1124
1125                         adjustment::AutoPtr(dcx.tcx.mk_region(r), m)
1126                     }
1127                     1 => {
1128                         let m: hir::Mutability =
1129                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1130
1131                         adjustment::AutoUnsafe(m)
1132                     }
1133                     _ => panic!("bad enum variant for adjustment::AutoRef")
1134                 })
1135             })
1136         }).unwrap()
1137     }
1138
1139     fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1140                               -> cast::CastKind
1141     {
1142         Decodable::decode(self).unwrap()
1143     }
1144
1145     /// Converts a def-id that appears in a type.  The correct
1146     /// translation will depend on what kind of def-id this is.
1147     /// This is a subtle point: type definitions are not
1148     /// inlined into the current crate, so if the def-id names
1149     /// a nominal type or type alias, then it should be
1150     /// translated to refer to the source crate.
1151     ///
1152     /// However, *type parameters* are cloned along with the function
1153     /// they are attached to.  So we should translate those def-ids
1154     /// to refer to the new, cloned copy of the type parameter.
1155     /// We only see references to free type parameters in the body of
1156     /// an inlined function. In such cases, we need the def-id to
1157     /// be a local id so that the TypeContents code is able to lookup
1158     /// the relevant info in the ty_param_defs table.
1159     ///
1160     /// *Region parameters*, unfortunately, are another kettle of fish.
1161     /// In such cases, def_id's can appear in types to distinguish
1162     /// shadowed bound regions and so forth. It doesn't actually
1163     /// matter so much what we do to these, since regions are erased
1164     /// at trans time, but it's good to keep them consistent just in
1165     /// case. We translate them with `tr_def_id()` which will map
1166     /// the crate numbers back to the original source crate.
1167     ///
1168     /// Scopes will end up as being totally bogus. This can actually
1169     /// be fixed though.
1170     ///
1171     /// Unboxed closures are cloned along with the function being
1172     /// inlined, and all side tables use interned node IDs, so we
1173     /// translate their def IDs accordingly.
1174     ///
1175     /// It'd be really nice to refactor the type repr to not include
1176     /// def-ids so that all these distinctions were unnecessary.
1177     fn convert_def_id(&mut self,
1178                       dcx: &DecodeContext,
1179                       did: DefId)
1180                       -> DefId {
1181         let r = dcx.tr_def_id(did);
1182         debug!("convert_def_id(did={:?})={:?}", did, r);
1183         return r;
1184     }
1185 }
1186
1187 fn decode_side_tables(dcx: &DecodeContext,
1188                       ast_doc: rbml::Doc) {
1189     let tbl_doc = ast_doc.get(c::tag_table as usize);
1190     for (tag, entry_doc) in reader::docs(tbl_doc) {
1191         let mut entry_dsr = reader::Decoder::new(entry_doc);
1192         let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1193         let id = dcx.tr_id(id0);
1194
1195         debug!(">> Side table document with tag 0x{:x} \
1196                 found for id {} (orig {})",
1197                tag, id, id0);
1198         let tag = tag as u32;
1199         let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1200         match decoded_tag {
1201             None => {
1202                 dcx.tcx.sess.bug(
1203                     &format!("unknown tag found in side tables: {:x}",
1204                             tag));
1205             }
1206             Some(value) => {
1207                 let val_dsr = &mut entry_dsr;
1208
1209                 match value {
1210                     c::tag_table_def => {
1211                         let def = decode_def(dcx, val_dsr);
1212                         dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
1213                             base_def: def,
1214                             // This doesn't matter cross-crate.
1215                             last_private: LastMod(AllPublic),
1216                             depth: 0
1217                         });
1218                     }
1219                     c::tag_table_node_type => {
1220                         let ty = val_dsr.read_ty(dcx);
1221                         debug!("inserting ty for node {}: {:?}",
1222                                id,  ty);
1223                         dcx.tcx.node_type_insert(id, ty);
1224                     }
1225                     c::tag_table_item_subst => {
1226                         let item_substs = ty::ItemSubsts {
1227                             substs: val_dsr.read_substs(dcx)
1228                         };
1229                         dcx.tcx.tables.borrow_mut().item_substs.insert(
1230                             id, item_substs);
1231                     }
1232                     c::tag_table_freevars => {
1233                         let fv_info = val_dsr.read_to_vec(|val_dsr| {
1234                             Ok(val_dsr.read_freevar_entry(dcx))
1235                         }).unwrap().into_iter().collect();
1236                         dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1237                     }
1238                     c::tag_table_upvar_capture_map => {
1239                         let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1240                         let upvar_id = ty::UpvarId {
1241                             var_id: dcx.tr_id(var_id),
1242                             closure_expr_id: id
1243                         };
1244                         let ub = val_dsr.read_upvar_capture(dcx);
1245                         dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub);
1246                     }
1247                     c::tag_table_method_map => {
1248                         let (autoderef, method) = val_dsr.read_method_callee(dcx);
1249                         let method_call = ty::MethodCall {
1250                             expr_id: id,
1251                             autoderef: autoderef
1252                         };
1253                         dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1254                     }
1255                     c::tag_table_adjustments => {
1256                         let adj =
1257                             val_dsr.read_auto_adjustment(dcx);
1258                         dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1259                     }
1260                     c::tag_table_cast_kinds => {
1261                         let cast_kind =
1262                             val_dsr.read_cast_kind(dcx);
1263                         dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1264                     }
1265                     c::tag_table_const_qualif => {
1266                         let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1267                         dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1268                     }
1269                     _ => {
1270                         dcx.tcx.sess.bug(
1271                             &format!("unknown tag found in side tables: {:x}",
1272                                     tag));
1273                     }
1274                 }
1275             }
1276         }
1277
1278         debug!(">< Side table doc loaded");
1279     }
1280 }
1281
1282 // copy the tcache entries from the original item to the new
1283 // inlined item
1284 fn copy_item_types(dcx: &DecodeContext, ii: &InlinedItem, orig_did: DefId) {
1285     fn copy_item_type(dcx: &DecodeContext,
1286                       inlined_id: ast::NodeId,
1287                       remote_did: DefId) {
1288         let inlined_did = dcx.tcx.map.local_def_id(inlined_id);
1289         dcx.tcx.register_item_type(inlined_did,
1290                                    dcx.tcx.lookup_item_type(remote_did));
1291
1292     }
1293     // copy the entry for the item itself
1294     let item_node_id = match ii {
1295         &InlinedItem::Item(ref i) => i.id,
1296         &InlinedItem::TraitItem(_, ref ti) => ti.id,
1297         &InlinedItem::ImplItem(_, ref ii) => ii.id,
1298         &InlinedItem::Foreign(ref fi) => fi.id
1299     };
1300     copy_item_type(dcx, item_node_id, orig_did);
1301
1302     // copy the entries of inner items
1303     if let &InlinedItem::Item(ref item) = ii {
1304         match item.node {
1305             hir::ItemEnum(ref def, _) => {
1306                 let orig_def = dcx.tcx.lookup_adt_def(orig_did);
1307                 for (i_variant, orig_variant) in
1308                     def.variants.iter().zip(orig_def.variants.iter())
1309                 {
1310                     debug!("astencode: copying variant {:?} => {:?}",
1311                            orig_variant.did, i_variant.node.data.id());
1312                     copy_item_type(dcx, i_variant.node.data.id(), orig_variant.did);
1313                 }
1314             }
1315             hir::ItemStruct(ref def, _) => {
1316                 if !def.is_struct() {
1317                     let ctor_did = dcx.tcx.lookup_adt_def(orig_did)
1318                         .struct_variant().did;
1319                     debug!("astencode: copying ctor {:?} => {:?}", ctor_did,
1320                            def.id());
1321                     copy_item_type(dcx, def.id(), ctor_did);
1322                 }
1323             }
1324             _ => {}
1325         }
1326     }
1327 }
1328
1329 // ______________________________________________________________________
1330 // Testing of astencode_gen
1331
1332 #[cfg(test)]
1333 fn encode_item_ast(rbml_w: &mut Encoder, item: &hir::Item) {
1334     rbml_w.start_tag(c::tag_tree as usize);
1335     (*item).encode(rbml_w);
1336     rbml_w.end_tag();
1337 }
1338
1339 #[cfg(test)]
1340 fn decode_item_ast(par_doc: rbml::Doc) -> hir::Item {
1341     let chi_doc = par_doc.get(c::tag_tree as usize);
1342     let mut d = reader::Decoder::new(chi_doc);
1343     Decodable::decode(&mut d).unwrap()
1344 }
1345
1346 #[cfg(test)]
1347 trait FakeExtCtxt {
1348     fn call_site(&self) -> codemap::Span;
1349     fn cfg(&self) -> ast::CrateConfig;
1350     fn ident_of(&self, st: &str) -> ast::Ident;
1351     fn name_of(&self, st: &str) -> ast::Name;
1352     fn parse_sess(&self) -> &parse::ParseSess;
1353 }
1354
1355 #[cfg(test)]
1356 impl FakeExtCtxt for parse::ParseSess {
1357     fn call_site(&self) -> codemap::Span {
1358         codemap::Span {
1359             lo: codemap::BytePos(0),
1360             hi: codemap::BytePos(0),
1361             expn_id: codemap::NO_EXPANSION,
1362         }
1363     }
1364     fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1365     fn ident_of(&self, st: &str) -> ast::Ident {
1366         parse::token::str_to_ident(st)
1367     }
1368     fn name_of(&self, st: &str) -> ast::Name {
1369         parse::token::intern(st)
1370     }
1371     fn parse_sess(&self) -> &parse::ParseSess { self }
1372 }
1373
1374 #[cfg(test)]
1375 struct FakeNodeIdAssigner;
1376
1377 #[cfg(test)]
1378 // It should go without saying that this may give unexpected results. Avoid
1379 // lowering anything which needs new nodes.
1380 impl NodeIdAssigner for FakeNodeIdAssigner {
1381     fn next_node_id(&self) -> NodeId {
1382         0
1383     }
1384
1385     fn peek_node_id(&self) -> NodeId {
1386         0
1387     }
1388 }
1389
1390 #[cfg(test)]
1391 fn mk_ctxt() -> parse::ParseSess {
1392     parse::ParseSess::new()
1393 }
1394
1395 #[cfg(test)]
1396 fn roundtrip(in_item: P<hir::Item>) {
1397     let mut wr = Cursor::new(Vec::new());
1398     encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
1399     let rbml_doc = rbml::Doc::new(wr.get_ref());
1400     let out_item = decode_item_ast(rbml_doc);
1401
1402     assert!(*in_item == out_item);
1403 }
1404
1405 #[test]
1406 fn test_basic() {
1407     let cx = mk_ctxt();
1408     let fnia = FakeNodeIdAssigner;
1409     let lcx = LoweringContext::new(&fnia, None);
1410     roundtrip(lower_item(&lcx, &quote_item!(&cx,
1411         fn foo() {}
1412     ).unwrap()));
1413 }
1414
1415 #[test]
1416 fn test_smalltalk() {
1417     let cx = mk_ctxt();
1418     let fnia = FakeNodeIdAssigner;
1419     let lcx = LoweringContext::new(&fnia, None);
1420     roundtrip(lower_item(&lcx, &quote_item!(&cx,
1421         fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1422     ).unwrap()));
1423 }
1424
1425 #[test]
1426 fn test_more() {
1427     let cx = mk_ctxt();
1428     let fnia = FakeNodeIdAssigner;
1429     let lcx = LoweringContext::new(&fnia, None);
1430     roundtrip(lower_item(&lcx, &quote_item!(&cx,
1431         fn foo(x: usize, y: usize) -> usize {
1432             let z = x + y;
1433             return z;
1434         }
1435     ).unwrap()));
1436 }
1437
1438 #[test]
1439 fn test_simplification() {
1440     let cx = mk_ctxt();
1441     let item = quote_item!(&cx,
1442         fn new_int_alist<B>() -> alist<isize, B> {
1443             fn eq_int(a: isize, b: isize) -> bool { a == b }
1444             return alist {eq_fn: eq_int, data: Vec::new()};
1445         }
1446     ).unwrap();
1447     let fnia = FakeNodeIdAssigner;
1448     let lcx = LoweringContext::new(&fnia, None);
1449     let hir_item = lower_item(&lcx, &item);
1450     let item_in = InlinedItemRef::Item(&hir_item);
1451     let item_out = simplify_ast(item_in);
1452     let item_exp = InlinedItem::Item(lower_item(&lcx, &quote_item!(&cx,
1453         fn new_int_alist<B>() -> alist<isize, B> {
1454             return alist {eq_fn: eq_int, data: Vec::new()};
1455         }
1456     ).unwrap()));
1457     match (item_out, item_exp) {
1458       (InlinedItem::Item(item_out), InlinedItem::Item(item_exp)) => {
1459         assert!(pprust::item_to_string(&*item_out) ==
1460                 pprust::item_to_string(&*item_exp));
1461       }
1462       _ => panic!()
1463     }
1464 }