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