]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/astencode.rs
remove `get_ident` and `get_name`, make `as_str` sound
[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, p) => {
448             def::DefMethod(did.tr(dcx), p.map(|did2| did2.tr(dcx)))
449           }
450           def::DefSelfTy(opt_did, impl_ids) => { def::DefSelfTy(opt_did.map(|did| did.tr(dcx)),
451                                                                 impl_ids.map(|(nid1, nid2)| {
452                                                                     (dcx.tr_id(nid1),
453                                                                      dcx.tr_id(nid2))
454                                                                 })) }
455           def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
456           def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
457           def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
458           def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
459           def::DefAssociatedConst(did, p) => {
460               def::DefAssociatedConst(did.tr(dcx), p.map(|did2| did2.tr(dcx)))
461           }
462           def::DefLocal(nid) => { def::DefLocal(dcx.tr_id(nid)) }
463           def::DefVariant(e_did, v_did, is_s) => {
464             def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
465           },
466           def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
467           def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
468           def::DefAssociatedTy(trait_did, did) =>
469               def::DefAssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
470           def::DefPrimTy(p) => def::DefPrimTy(p),
471           def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
472           def::DefUse(did) => def::DefUse(did.tr(dcx)),
473           def::DefUpvar(nid1, nid2) => {
474             def::DefUpvar(dcx.tr_id(nid1), dcx.tr_id(nid2))
475           }
476           def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
477           def::DefRegion(nid) => def::DefRegion(dcx.tr_id(nid)),
478           def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
479         }
480     }
481 }
482
483 // ______________________________________________________________________
484 // Encoding and decoding of ancillary information
485
486 impl tr for ty::Region {
487     fn tr(&self, dcx: &DecodeContext) -> ty::Region {
488         match *self {
489             ty::ReLateBound(debruijn, br) => {
490                 ty::ReLateBound(debruijn, br.tr(dcx))
491             }
492             ty::ReEarlyBound(data) => {
493                 ty::ReEarlyBound(ty::EarlyBoundRegion {
494                     param_id: dcx.tr_id(data.param_id),
495                     space: data.space,
496                     index: data.index,
497                     name: data.name,
498                 })
499             }
500             ty::ReScope(scope) => {
501                 ty::ReScope(scope.tr(dcx))
502             }
503             ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => {
504                 *self
505             }
506             ty::ReFree(ref fr) => {
507                 ty::ReFree(fr.tr(dcx))
508             }
509         }
510     }
511 }
512
513 impl tr for ty::FreeRegion {
514     fn tr(&self, dcx: &DecodeContext) -> ty::FreeRegion {
515         ty::FreeRegion { scope: self.scope.tr(dcx),
516                          bound_region: self.bound_region.tr(dcx) }
517     }
518 }
519
520 impl tr for region::CodeExtent {
521     fn tr(&self, dcx: &DecodeContext) -> region::CodeExtent {
522         self.map_id(|id| dcx.tr_id(id))
523     }
524 }
525
526 impl tr for region::DestructionScopeData {
527     fn tr(&self, dcx: &DecodeContext) -> region::DestructionScopeData {
528         region::DestructionScopeData { node_id: dcx.tr_id(self.node_id) }
529     }
530 }
531
532 impl tr for ty::BoundRegion {
533     fn tr(&self, dcx: &DecodeContext) -> ty::BoundRegion {
534         match *self {
535             ty::BrAnon(_) |
536             ty::BrFresh(_) |
537             ty::BrEnv => *self,
538             ty::BrNamed(id, ident) => ty::BrNamed(dcx.tr_def_id(id),
539                                                     ident),
540         }
541     }
542 }
543
544 // ______________________________________________________________________
545 // Encoding and decoding of freevar information
546
547 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
548     (*fv).encode(rbml_w).unwrap();
549 }
550
551 trait rbml_decoder_helper {
552     fn read_freevar_entry(&mut self, dcx: &DecodeContext)
553                           -> ty::Freevar;
554     fn read_capture_mode(&mut self) -> ast::CaptureClause;
555 }
556
557 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
558     fn read_freevar_entry(&mut self, dcx: &DecodeContext)
559                           -> ty::Freevar {
560         let fv: ty::Freevar = Decodable::decode(self).unwrap();
561         fv.tr(dcx)
562     }
563
564     fn read_capture_mode(&mut self) -> ast::CaptureClause {
565         let cm: ast::CaptureClause = Decodable::decode(self).unwrap();
566         cm
567     }
568 }
569
570 impl tr for ty::Freevar {
571     fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
572         ty::Freevar {
573             def: self.def.tr(dcx),
574             span: self.span.tr(dcx),
575         }
576     }
577 }
578
579 impl tr for ty::UpvarBorrow {
580     fn tr(&self, dcx: &DecodeContext) -> ty::UpvarBorrow {
581         ty::UpvarBorrow {
582             kind: self.kind,
583             region: self.region.tr(dcx)
584         }
585     }
586 }
587
588 impl tr for ty::UpvarCapture {
589     fn tr(&self, dcx: &DecodeContext) -> ty::UpvarCapture {
590         match *self {
591             ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
592             ty::UpvarCapture::ByRef(ref data) => ty::UpvarCapture::ByRef(data.tr(dcx)),
593         }
594     }
595 }
596
597 // ______________________________________________________________________
598 // Encoding and decoding of MethodCallee
599
600 trait read_method_callee_helper<'tcx> {
601     fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
602                                   -> (u32, ty::MethodCallee<'tcx>);
603 }
604
605 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
606                                   rbml_w: &mut Encoder,
607                                   autoderef: u32,
608                                   method: &ty::MethodCallee<'tcx>) {
609     use serialize::Encoder;
610
611     rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
612         rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
613             autoderef.encode(rbml_w)
614         });
615         rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
616             Ok(rbml_w.emit_def_id(method.def_id))
617         });
618         rbml_w.emit_struct_field("ty", 2, |rbml_w| {
619             Ok(rbml_w.emit_ty(ecx, method.ty))
620         });
621         rbml_w.emit_struct_field("substs", 3, |rbml_w| {
622             Ok(rbml_w.emit_substs(ecx, &method.substs))
623         })
624     }).unwrap();
625 }
626
627 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
628     fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
629                                   -> (u32, ty::MethodCallee<'tcx>) {
630
631         self.read_struct("MethodCallee", 4, |this| {
632             let autoderef = this.read_struct_field("autoderef", 0,
633                                                    Decodable::decode).unwrap();
634             Ok((autoderef, ty::MethodCallee {
635                 def_id: this.read_struct_field("def_id", 1, |this| {
636                     Ok(this.read_def_id(dcx))
637                 }).unwrap(),
638                 ty: this.read_struct_field("ty", 2, |this| {
639                     Ok(this.read_ty(dcx))
640                 }).unwrap(),
641                 substs: this.read_struct_field("substs", 3, |this| {
642                     Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
643                 }).unwrap()
644             }))
645         }).unwrap()
646     }
647 }
648
649 pub fn encode_closure_kind(ebml_w: &mut Encoder, kind: ty::ClosureKind) {
650     kind.encode(ebml_w).unwrap();
651 }
652
653 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
654     kind.encode(ebml_w).unwrap();
655 }
656
657 pub trait vtable_decoder_helpers<'tcx> {
658     fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
659         F: FnMut(&mut Self) -> T;
660 }
661
662 impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> {
663     fn read_vec_per_param_space<T, F>(&mut self, mut f: F) -> VecPerParamSpace<T> where
664         F: FnMut(&mut reader::Decoder<'a>) -> T,
665     {
666         let types = self.read_to_vec(|this| Ok(f(this))).unwrap();
667         let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap();
668         let fns = self.read_to_vec(|this| Ok(f(this))).unwrap();
669         VecPerParamSpace::new(types, selfs, fns)
670     }
671 }
672
673 // ___________________________________________________________________________
674 //
675
676 fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder,
677                                     v: &subst::VecPerParamSpace<T>,
678                                     mut f: F) where
679     F: FnMut(&mut Encoder, &T),
680 {
681     for &space in &subst::ParamSpace::all() {
682         rbml_w.emit_from_vec(v.get_slice(space),
683                              |rbml_w, n| Ok(f(rbml_w, n))).unwrap();
684     }
685 }
686
687 // ______________________________________________________________________
688 // Encoding and decoding the side tables
689
690 trait get_ty_str_ctxt<'tcx> {
691     fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
692 }
693
694 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
695     fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
696         tyencode::ctxt {
697             diag: self.tcx.sess.diagnostic(),
698             ds: e::def_to_string,
699             tcx: self.tcx,
700             abbrevs: &self.type_abbrevs
701         }
702     }
703 }
704
705 trait rbml_writer_helpers<'tcx> {
706     fn emit_closure_type<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
707                              closure_type: &ty::ClosureTy<'tcx>);
708     fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
709     fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
710     fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
711                                type_param_def: &ty::TypeParameterDef<'tcx>);
712     fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
713                           predicate: &ty::Predicate<'tcx>);
714     fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
715                           ty: &ty::TraitRef<'tcx>);
716     fn emit_type_scheme<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
717                             type_scheme: ty::TypeScheme<'tcx>);
718     fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
719                        substs: &subst::Substs<'tcx>);
720     fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
721                                    bounds: &ty::ExistentialBounds<'tcx>);
722     fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
723     fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
724                                 adj: &ty::AutoAdjustment<'tcx>);
725     fn emit_autoref<'a>(&mut self, autoref: &ty::AutoRef<'tcx>);
726     fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
727                                auto_deref_ref: &ty::AutoDerefRef<'tcx>);
728 }
729
730 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
731     fn emit_closure_type<'b>(&mut self,
732                              ecx: &e::EncodeContext<'b, 'tcx>,
733                              closure_type: &ty::ClosureTy<'tcx>) {
734         self.emit_opaque(|this| {
735             Ok(e::write_closure_type(ecx, this, closure_type))
736         });
737     }
738
739     fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
740         self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
741     }
742
743     fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
744         self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
745     }
746
747     fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
748                           trait_ref: &ty::TraitRef<'tcx>) {
749         self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
750     }
751
752     fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
753                                type_param_def: &ty::TypeParameterDef<'tcx>) {
754         self.emit_opaque(|this| {
755             Ok(tyencode::enc_type_param_def(this,
756                                          &ecx.ty_str_ctxt(),
757                                          type_param_def))
758         });
759     }
760
761     fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
762                           predicate: &ty::Predicate<'tcx>) {
763         self.emit_opaque(|this| {
764             Ok(tyencode::enc_predicate(this,
765                                        &ecx.ty_str_ctxt(),
766                                        predicate))
767         });
768     }
769
770     fn emit_type_scheme<'b>(&mut self,
771                             ecx: &e::EncodeContext<'b, 'tcx>,
772                             type_scheme: ty::TypeScheme<'tcx>) {
773         use serialize::Encoder;
774
775         self.emit_struct("TypeScheme", 2, |this| {
776             this.emit_struct_field("generics", 0, |this| {
777                 this.emit_struct("Generics", 2, |this| {
778                     this.emit_struct_field("types", 0, |this| {
779                         Ok(encode_vec_per_param_space(
780                             this, &type_scheme.generics.types,
781                             |this, def| this.emit_type_param_def(ecx, def)))
782                     });
783                     this.emit_struct_field("regions", 1, |this| {
784                         Ok(encode_vec_per_param_space(
785                             this, &type_scheme.generics.regions,
786                             |this, def| def.encode(this).unwrap()))
787                     })
788                 })
789             });
790             this.emit_struct_field("ty", 1, |this| {
791                 Ok(this.emit_ty(ecx, type_scheme.ty))
792             })
793         });
794     }
795
796     fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
797                                    bounds: &ty::ExistentialBounds<'tcx>) {
798         self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
799                                                                     &ecx.ty_str_ctxt(),
800                                                                     bounds)));
801     }
802
803     fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
804         self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
805                                                                 &ecx.ty_str_ctxt(),
806                                                                 bounds)));
807     }
808
809     fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
810                        substs: &subst::Substs<'tcx>) {
811         self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
812                                                            &ecx.ty_str_ctxt(),
813                                                            substs)));
814     }
815
816     fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
817                                 adj: &ty::AutoAdjustment<'tcx>) {
818         use serialize::Encoder;
819
820         self.emit_enum("AutoAdjustment", |this| {
821             match *adj {
822                 ty::AdjustReifyFnPointer=> {
823                     this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
824                 }
825
826                 ty::AdjustUnsafeFnPointer => {
827                     this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
828                         Ok(())
829                     })
830                 }
831
832                 ty::AdjustDerefRef(ref auto_deref_ref) => {
833                     this.emit_enum_variant("AdjustDerefRef", 3, 2, |this| {
834                         this.emit_enum_variant_arg(0,
835                             |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
836                     })
837                 }
838             }
839         });
840     }
841
842     fn emit_autoref<'b>(&mut self, autoref: &ty::AutoRef<'tcx>) {
843         use serialize::Encoder;
844
845         self.emit_enum("AutoRef", |this| {
846             match autoref {
847                 &ty::AutoPtr(r, m) => {
848                     this.emit_enum_variant("AutoPtr", 0, 2, |this| {
849                         this.emit_enum_variant_arg(0, |this| r.encode(this));
850                         this.emit_enum_variant_arg(1, |this| m.encode(this))
851                     })
852                 }
853                 &ty::AutoUnsafe(m) => {
854                     this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
855                         this.emit_enum_variant_arg(0, |this| m.encode(this))
856                     })
857                 }
858             }
859         });
860     }
861
862     fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
863                                auto_deref_ref: &ty::AutoDerefRef<'tcx>) {
864         use serialize::Encoder;
865
866         self.emit_struct("AutoDerefRef", 2, |this| {
867             this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
868
869             this.emit_struct_field("autoref", 1, |this| {
870                 this.emit_option(|this| {
871                     match auto_deref_ref.autoref {
872                         None => this.emit_option_none(),
873                         Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(a))),
874                     }
875                 })
876             });
877
878             this.emit_struct_field("unsize", 2, |this| {
879                 this.emit_option(|this| {
880                     match auto_deref_ref.unsize {
881                         None => this.emit_option_none(),
882                         Some(target) => this.emit_option_some(|this| {
883                             Ok(this.emit_ty(ecx, target))
884                         })
885                     }
886                 })
887             })
888         });
889     }
890 }
891
892 trait write_tag_and_id {
893     fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
894     fn id(&mut self, id: ast::NodeId);
895 }
896
897 impl<'a> write_tag_and_id for Encoder<'a> {
898     fn tag<F>(&mut self,
899               tag_id: c::astencode_tag,
900               f: F) where
901         F: FnOnce(&mut Encoder<'a>),
902     {
903         self.start_tag(tag_id as usize);
904         f(self);
905         self.end_tag();
906     }
907
908     fn id(&mut self, id: ast::NodeId) {
909         id.encode(self).unwrap();
910     }
911 }
912
913 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
914     ecx: &'a e::EncodeContext<'c, 'tcx>,
915     rbml_w: &'a mut Encoder<'b>,
916 }
917
918 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
919         SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
920     fn visit_id(&mut self, id: ast::NodeId) {
921         encode_side_tables_for_id(self.ecx, self.rbml_w, id)
922     }
923 }
924
925 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
926                              rbml_w: &mut Encoder,
927                              ii: &ast::InlinedItem) {
928     rbml_w.start_tag(c::tag_table as usize);
929     ast_util::visit_ids_for_inlined_item(ii, &mut SideTableEncodingIdVisitor {
930         ecx: ecx,
931         rbml_w: rbml_w
932     });
933     rbml_w.end_tag();
934 }
935
936 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
937                              rbml_w: &mut Encoder,
938                              id: ast::NodeId) {
939     let tcx = ecx.tcx;
940
941     debug!("Encoding side tables for id {}", id);
942
943     if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
944         rbml_w.tag(c::tag_table_def, |rbml_w| {
945             rbml_w.id(id);
946             def.encode(rbml_w).unwrap();
947         })
948     }
949
950     if let Some(ty) = tcx.node_types().get(&id) {
951         rbml_w.tag(c::tag_table_node_type, |rbml_w| {
952             rbml_w.id(id);
953             rbml_w.emit_ty(ecx, *ty);
954         })
955     }
956
957     if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
958         rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
959             rbml_w.id(id);
960             rbml_w.emit_substs(ecx, &item_substs.substs);
961         })
962     }
963
964     if let Some(fv) = tcx.freevars.borrow().get(&id) {
965         rbml_w.tag(c::tag_table_freevars, |rbml_w| {
966             rbml_w.id(id);
967             rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
968                 Ok(encode_freevar_entry(rbml_w, fv_entry))
969             });
970         });
971
972         for freevar in fv {
973             rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
974                 rbml_w.id(id);
975
976                 let var_id = freevar.def.def_id().node;
977                 let upvar_id = ty::UpvarId {
978                     var_id: var_id,
979                     closure_expr_id: id
980                 };
981                 let upvar_capture = tcx.tables
982                                        .borrow()
983                                        .upvar_capture_map
984                                        .get(&upvar_id)
985                                        .unwrap()
986                                        .clone();
987                 var_id.encode(rbml_w);
988                 upvar_capture.encode(rbml_w);
989             })
990         }
991     }
992
993     let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
994     if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
995         rbml_w.tag(c::tag_table_tcache, |rbml_w| {
996             rbml_w.id(id);
997             rbml_w.emit_type_scheme(ecx, type_scheme.clone());
998         })
999     }
1000
1001     if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
1002         rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
1003             rbml_w.id(id);
1004             rbml_w.emit_type_param_def(ecx, type_param_def)
1005         })
1006     }
1007
1008     let method_call = ty::MethodCall::expr(id);
1009     if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
1010         rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1011             rbml_w.id(id);
1012             encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
1013         })
1014     }
1015
1016     if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
1017         match *adjustment {
1018             ty::AdjustDerefRef(ref adj) => {
1019                 for autoderef in 0..adj.autoderefs {
1020                     let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
1021                     if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
1022                         rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1023                             rbml_w.id(id);
1024                             encode_method_callee(ecx, rbml_w,
1025                                                  method_call.autoderef, method)
1026                         })
1027                     }
1028                 }
1029             }
1030             _ => {}
1031         }
1032
1033         rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
1034             rbml_w.id(id);
1035             rbml_w.emit_auto_adjustment(ecx, adjustment);
1036         })
1037     }
1038
1039     if let Some(closure_type) = tcx.tables.borrow().closure_tys.get(&ast_util::local_def(id)) {
1040         rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
1041             rbml_w.id(id);
1042             rbml_w.emit_closure_type(ecx, closure_type);
1043         })
1044     }
1045
1046     if let Some(closure_kind) = tcx.tables.borrow().closure_kinds.get(&ast_util::local_def(id)) {
1047         rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
1048             rbml_w.id(id);
1049             encode_closure_kind(rbml_w, *closure_kind)
1050         })
1051     }
1052
1053     if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
1054         rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
1055             rbml_w.id(id);
1056             encode_cast_kind(rbml_w, *cast_kind)
1057         })
1058     }
1059
1060     if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
1061         rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
1062             rbml_w.id(id);
1063             qualif.encode(rbml_w).unwrap()
1064         })
1065     }
1066 }
1067
1068 trait doc_decoder_helpers {
1069     fn as_int(&self) -> isize;
1070     fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1071 }
1072
1073 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
1074     fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
1075     fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
1076         reader::maybe_get_doc(*self, tag as usize)
1077     }
1078 }
1079
1080 trait rbml_decoder_decoder_helpers<'tcx> {
1081     fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
1082     fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
1083     fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1084                               -> ty::TraitRef<'tcx>;
1085     fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1086                                    -> ty::PolyTraitRef<'tcx>;
1087     fn read_type_param_def<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1088                                    -> ty::TypeParameterDef<'tcx>;
1089     fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1090                               -> ty::Predicate<'tcx>;
1091     fn read_type_scheme<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1092                                 -> ty::TypeScheme<'tcx>;
1093     fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1094                                        -> ty::ExistentialBounds<'tcx>;
1095     fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1096                            -> subst::Substs<'tcx>;
1097     fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1098                                     -> ty::AutoAdjustment<'tcx>;
1099     fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1100                                  -> cast::CastKind;
1101     fn read_closure_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1102                                  -> ty::ClosureKind;
1103     fn read_closure_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1104                                -> ty::ClosureTy<'tcx>;
1105     fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1106                                    -> ty::AutoDerefRef<'tcx>;
1107     fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1108                             -> ty::AutoRef<'tcx>;
1109     fn convert_def_id(&mut self,
1110                       dcx: &DecodeContext,
1111                       source: DefIdSource,
1112                       did: ast::DefId)
1113                       -> ast::DefId;
1114
1115     // Versions of the type reading functions that don't need the full
1116     // DecodeContext.
1117     fn read_ty_nodcx(&mut self,
1118                      tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
1119     fn read_tys_nodcx(&mut self,
1120                       tcx: &ty::ctxt<'tcx>,
1121                       cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
1122     fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
1123                          cdata: &cstore::crate_metadata)
1124                          -> subst::Substs<'tcx>;
1125 }
1126
1127 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
1128     fn read_ty_nodcx(&mut self,
1129                      tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx> {
1130         self.read_opaque(|_, doc| {
1131             Ok(tydecode::parse_ty_data(
1132                 doc.data,
1133                 cdata.cnum,
1134                 doc.start,
1135                 tcx,
1136                 |_, id| decoder::translate_def_id(cdata, id)))
1137         }).unwrap()
1138     }
1139
1140     fn read_tys_nodcx(&mut self,
1141                       tcx: &ty::ctxt<'tcx>,
1142                       cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
1143         self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
1144             .unwrap()
1145             .into_iter()
1146             .collect()
1147     }
1148
1149     fn read_substs_nodcx(&mut self,
1150                          tcx: &ty::ctxt<'tcx>,
1151                          cdata: &cstore::crate_metadata)
1152                          -> subst::Substs<'tcx>
1153     {
1154         self.read_opaque(|_, doc| {
1155             Ok(tydecode::parse_substs_data(
1156                 doc.data,
1157                 cdata.cnum,
1158                 doc.start,
1159                 tcx,
1160                 |_, id| decoder::translate_def_id(cdata, id)))
1161         }).unwrap()
1162     }
1163
1164     fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1165         // Note: regions types embed local node ids.  In principle, we
1166         // should translate these node ids into the new decode
1167         // context.  However, we do not bother, because region types
1168         // are not used during trans.
1169
1170         return self.read_opaque(|this, doc| {
1171             debug!("read_ty({})", type_string(doc));
1172
1173             let ty = tydecode::parse_ty_data(
1174                 doc.data,
1175                 dcx.cdata.cnum,
1176                 doc.start,
1177                 dcx.tcx,
1178                 |s, a| this.convert_def_id(dcx, s, a));
1179
1180             Ok(ty)
1181         }).unwrap();
1182
1183         fn type_string(doc: rbml::Doc) -> String {
1184             let mut str = String::new();
1185             for i in doc.start..doc.end {
1186                 str.push(doc.data[i] as char);
1187             }
1188             str
1189         }
1190     }
1191
1192     fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1193                         -> Vec<Ty<'tcx>> {
1194         self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1195     }
1196
1197     fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1198                               -> ty::TraitRef<'tcx> {
1199         self.read_opaque(|this, doc| {
1200             let ty = tydecode::parse_trait_ref_data(
1201                 doc.data,
1202                 dcx.cdata.cnum,
1203                 doc.start,
1204                 dcx.tcx,
1205                 |s, a| this.convert_def_id(dcx, s, a));
1206             Ok(ty)
1207         }).unwrap()
1208     }
1209
1210     fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1211                                    -> ty::PolyTraitRef<'tcx> {
1212         ty::Binder(self.read_opaque(|this, doc| {
1213             let ty = tydecode::parse_trait_ref_data(
1214                 doc.data,
1215                 dcx.cdata.cnum,
1216                 doc.start,
1217                 dcx.tcx,
1218                 |s, a| this.convert_def_id(dcx, s, a));
1219             Ok(ty)
1220         }).unwrap())
1221     }
1222
1223     fn read_type_param_def<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1224                                    -> ty::TypeParameterDef<'tcx> {
1225         self.read_opaque(|this, doc| {
1226             Ok(tydecode::parse_type_param_def_data(
1227                 doc.data,
1228                 doc.start,
1229                 dcx.cdata.cnum,
1230                 dcx.tcx,
1231                 |s, a| this.convert_def_id(dcx, s, a)))
1232         }).unwrap()
1233     }
1234
1235     fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1236                               -> ty::Predicate<'tcx>
1237     {
1238         self.read_opaque(|this, doc| {
1239             Ok(tydecode::parse_predicate_data(doc.data, doc.start, dcx.cdata.cnum, dcx.tcx,
1240                                               |s, a| this.convert_def_id(dcx, s, a)))
1241         }).unwrap()
1242     }
1243
1244     fn read_type_scheme<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1245                                 -> ty::TypeScheme<'tcx> {
1246         self.read_struct("TypeScheme", 3, |this| {
1247             Ok(ty::TypeScheme {
1248                 generics: this.read_struct_field("generics", 0, |this| {
1249                     this.read_struct("Generics", 2, |this| {
1250                         Ok(ty::Generics {
1251                             types:
1252                             this.read_struct_field("types", 0, |this| {
1253                                 Ok(this.read_vec_per_param_space(
1254                                     |this| this.read_type_param_def(dcx)))
1255                             }).unwrap(),
1256
1257                             regions:
1258                             this.read_struct_field("regions", 1, |this| {
1259                                 Ok(this.read_vec_per_param_space(
1260                                     |this| Decodable::decode(this).unwrap()))
1261                             }).unwrap(),
1262                         })
1263                     })
1264                 }).unwrap(),
1265                 ty: this.read_struct_field("ty", 1, |this| {
1266                     Ok(this.read_ty(dcx))
1267                 }).unwrap()
1268             })
1269         }).unwrap()
1270     }
1271
1272     fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1273                                        -> ty::ExistentialBounds<'tcx>
1274     {
1275         self.read_opaque(|this, doc| {
1276             Ok(tydecode::parse_existential_bounds_data(doc.data,
1277                                                        dcx.cdata.cnum,
1278                                                        doc.start,
1279                                                        dcx.tcx,
1280                                                        |s, a| this.convert_def_id(dcx, s, a)))
1281         }).unwrap()
1282     }
1283
1284     fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1285                            -> subst::Substs<'tcx> {
1286         self.read_opaque(|this, doc| {
1287             Ok(tydecode::parse_substs_data(doc.data,
1288                                            dcx.cdata.cnum,
1289                                            doc.start,
1290                                            dcx.tcx,
1291                                            |s, a| this.convert_def_id(dcx, s, a)))
1292         }).unwrap()
1293     }
1294
1295     fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1296                                     -> ty::AutoAdjustment<'tcx> {
1297         self.read_enum("AutoAdjustment", |this| {
1298             let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer", "AdjustDerefRef"];
1299             this.read_enum_variant(&variants, |this, i| {
1300                 Ok(match i {
1301                     1 => ty::AdjustReifyFnPointer,
1302                     2 => ty::AdjustUnsafeFnPointer,
1303                     3 => {
1304                         let auto_deref_ref: ty::AutoDerefRef =
1305                             this.read_enum_variant_arg(0,
1306                                 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1307
1308                         ty::AdjustDerefRef(auto_deref_ref)
1309                     }
1310                     _ => panic!("bad enum variant for ty::AutoAdjustment")
1311                 })
1312             })
1313         }).unwrap()
1314     }
1315
1316     fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1317                                    -> ty::AutoDerefRef<'tcx> {
1318         self.read_struct("AutoDerefRef", 2, |this| {
1319             Ok(ty::AutoDerefRef {
1320                 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1321                     Decodable::decode(this)
1322                 }).unwrap(),
1323                 autoref: this.read_struct_field("autoref", 1, |this| {
1324                     this.read_option(|this, b| {
1325                         if b {
1326                             Ok(Some(this.read_autoref(dcx)))
1327                         } else {
1328                             Ok(None)
1329                         }
1330                     })
1331                 }).unwrap(),
1332                 unsize: this.read_struct_field("unsize", 2, |this| {
1333                     this.read_option(|this, b| {
1334                         if b {
1335                             Ok(Some(this.read_ty(dcx)))
1336                         } else {
1337                             Ok(None)
1338                         }
1339                     })
1340                 }).unwrap(),
1341             })
1342         }).unwrap()
1343     }
1344
1345     fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1346                             -> ty::AutoRef<'tcx> {
1347         self.read_enum("AutoRef", |this| {
1348             let variants = ["AutoPtr", "AutoUnsafe"];
1349             this.read_enum_variant(&variants, |this, i| {
1350                 Ok(match i {
1351                     0 => {
1352                         let r: ty::Region =
1353                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1354                         let m: ast::Mutability =
1355                             this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1356
1357                         ty::AutoPtr(dcx.tcx.mk_region(r.tr(dcx)), m)
1358                     }
1359                     1 => {
1360                         let m: ast::Mutability =
1361                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1362
1363                         ty::AutoUnsafe(m)
1364                     }
1365                     _ => panic!("bad enum variant for ty::AutoRef")
1366                 })
1367             })
1368         }).unwrap()
1369     }
1370
1371     fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1372                               -> cast::CastKind
1373     {
1374         Decodable::decode(self).unwrap()
1375     }
1376
1377     fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1378                                  -> ty::ClosureKind
1379     {
1380         Decodable::decode(self).unwrap()
1381     }
1382
1383     fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1384                                -> ty::ClosureTy<'tcx>
1385     {
1386         self.read_opaque(|this, doc| {
1387             Ok(tydecode::parse_ty_closure_data(
1388                 doc.data,
1389                 dcx.cdata.cnum,
1390                 doc.start,
1391                 dcx.tcx,
1392                 |s, a| this.convert_def_id(dcx, s, a)))
1393         }).unwrap()
1394     }
1395
1396     /// Converts a def-id that appears in a type.  The correct
1397     /// translation will depend on what kind of def-id this is.
1398     /// This is a subtle point: type definitions are not
1399     /// inlined into the current crate, so if the def-id names
1400     /// a nominal type or type alias, then it should be
1401     /// translated to refer to the source crate.
1402     ///
1403     /// However, *type parameters* are cloned along with the function
1404     /// they are attached to.  So we should translate those def-ids
1405     /// to refer to the new, cloned copy of the type parameter.
1406     /// We only see references to free type parameters in the body of
1407     /// an inlined function. In such cases, we need the def-id to
1408     /// be a local id so that the TypeContents code is able to lookup
1409     /// the relevant info in the ty_param_defs table.
1410     ///
1411     /// *Region parameters*, unfortunately, are another kettle of fish.
1412     /// In such cases, def_id's can appear in types to distinguish
1413     /// shadowed bound regions and so forth. It doesn't actually
1414     /// matter so much what we do to these, since regions are erased
1415     /// at trans time, but it's good to keep them consistent just in
1416     /// case. We translate them with `tr_def_id()` which will map
1417     /// the crate numbers back to the original source crate.
1418     ///
1419     /// Unboxed closures are cloned along with the function being
1420     /// inlined, and all side tables use interned node IDs, so we
1421     /// translate their def IDs accordingly.
1422     ///
1423     /// It'd be really nice to refactor the type repr to not include
1424     /// def-ids so that all these distinctions were unnecessary.
1425     fn convert_def_id(&mut self,
1426                       dcx: &DecodeContext,
1427                       source: tydecode::DefIdSource,
1428                       did: ast::DefId)
1429                       -> ast::DefId {
1430         let r = match source {
1431             NominalType | TypeWithId | RegionParameter => dcx.tr_def_id(did),
1432             ClosureSource => dcx.tr_intern_def_id(did)
1433         };
1434         debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1435         return r;
1436     }
1437 }
1438
1439 fn decode_side_tables(dcx: &DecodeContext,
1440                       ast_doc: rbml::Doc) {
1441     let tbl_doc = ast_doc.get(c::tag_table as usize);
1442     for (tag, entry_doc) in reader::docs(tbl_doc) {
1443         let mut entry_dsr = reader::Decoder::new(entry_doc);
1444         let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1445         let id = dcx.tr_id(id0);
1446
1447         debug!(">> Side table document with tag 0x{:x} \
1448                 found for id {} (orig {})",
1449                tag, id, id0);
1450         let tag = tag as u32;
1451         let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1452         match decoded_tag {
1453             None => {
1454                 dcx.tcx.sess.bug(
1455                     &format!("unknown tag found in side tables: {:x}",
1456                             tag));
1457             }
1458             Some(value) => {
1459                 let val_dsr = &mut entry_dsr;
1460
1461                 match value {
1462                     c::tag_table_def => {
1463                         let def = decode_def(dcx, val_dsr);
1464                         dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
1465                             base_def: def,
1466                             // This doesn't matter cross-crate.
1467                             last_private: LastMod(AllPublic),
1468                             depth: 0
1469                         });
1470                     }
1471                     c::tag_table_node_type => {
1472                         let ty = val_dsr.read_ty(dcx);
1473                         debug!("inserting ty for node {}: {:?}",
1474                                id,  ty);
1475                         dcx.tcx.node_type_insert(id, ty);
1476                     }
1477                     c::tag_table_item_subst => {
1478                         let item_substs = ty::ItemSubsts {
1479                             substs: val_dsr.read_substs(dcx)
1480                         };
1481                         dcx.tcx.tables.borrow_mut().item_substs.insert(
1482                             id, item_substs);
1483                     }
1484                     c::tag_table_freevars => {
1485                         let fv_info = val_dsr.read_to_vec(|val_dsr| {
1486                             Ok(val_dsr.read_freevar_entry(dcx))
1487                         }).unwrap().into_iter().collect();
1488                         dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1489                     }
1490                     c::tag_table_upvar_capture_map => {
1491                         let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1492                         let upvar_id = ty::UpvarId {
1493                             var_id: dcx.tr_id(var_id),
1494                             closure_expr_id: id
1495                         };
1496                         let ub: ty::UpvarCapture = Decodable::decode(val_dsr).unwrap();
1497                         dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub.tr(dcx));
1498                     }
1499                     c::tag_table_tcache => {
1500                         let type_scheme = val_dsr.read_type_scheme(dcx);
1501                         let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1502                         dcx.tcx.register_item_type(lid, type_scheme);
1503                     }
1504                     c::tag_table_param_defs => {
1505                         let bounds = val_dsr.read_type_param_def(dcx);
1506                         dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1507                     }
1508                     c::tag_table_method_map => {
1509                         let (autoderef, method) = val_dsr.read_method_callee(dcx);
1510                         let method_call = ty::MethodCall {
1511                             expr_id: id,
1512                             autoderef: autoderef
1513                         };
1514                         dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1515                     }
1516                     c::tag_table_adjustments => {
1517                         let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(dcx);
1518                         dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1519                     }
1520                     c::tag_table_closure_tys => {
1521                         let closure_ty =
1522                             val_dsr.read_closure_ty(dcx);
1523                         dcx.tcx.tables.borrow_mut().closure_tys.insert(ast_util::local_def(id),
1524                                                                 closure_ty);
1525                     }
1526                     c::tag_table_closure_kinds => {
1527                         let closure_kind =
1528                             val_dsr.read_closure_kind(dcx);
1529                         dcx.tcx.tables.borrow_mut().closure_kinds.insert(ast_util::local_def(id),
1530                                                                   closure_kind);
1531                     }
1532                     c::tag_table_cast_kinds => {
1533                         let cast_kind =
1534                             val_dsr.read_cast_kind(dcx);
1535                         dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1536                     }
1537                     c::tag_table_const_qualif => {
1538                         let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1539                         dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1540                     }
1541                     _ => {
1542                         dcx.tcx.sess.bug(
1543                             &format!("unknown tag found in side tables: {:x}",
1544                                     tag));
1545                     }
1546                 }
1547             }
1548         }
1549
1550         debug!(">< Side table doc loaded");
1551     }
1552 }
1553
1554 // ______________________________________________________________________
1555 // Testing of astencode_gen
1556
1557 #[cfg(test)]
1558 fn encode_item_ast(rbml_w: &mut Encoder, item: &ast::Item) {
1559     rbml_w.start_tag(c::tag_tree as usize);
1560     (*item).encode(rbml_w);
1561     rbml_w.end_tag();
1562 }
1563
1564 #[cfg(test)]
1565 fn decode_item_ast(par_doc: rbml::Doc) -> ast::Item {
1566     let chi_doc = par_doc.get(c::tag_tree as usize);
1567     let mut d = reader::Decoder::new(chi_doc);
1568     Decodable::decode(&mut d).unwrap()
1569 }
1570
1571 #[cfg(test)]
1572 trait FakeExtCtxt {
1573     fn call_site(&self) -> codemap::Span;
1574     fn cfg(&self) -> ast::CrateConfig;
1575     fn ident_of(&self, st: &str) -> ast::Ident;
1576     fn name_of(&self, st: &str) -> ast::Name;
1577     fn parse_sess(&self) -> &parse::ParseSess;
1578 }
1579
1580 #[cfg(test)]
1581 impl FakeExtCtxt for parse::ParseSess {
1582     fn call_site(&self) -> codemap::Span {
1583         codemap::Span {
1584             lo: codemap::BytePos(0),
1585             hi: codemap::BytePos(0),
1586             expn_id: codemap::NO_EXPANSION,
1587         }
1588     }
1589     fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1590     fn ident_of(&self, st: &str) -> ast::Ident {
1591         parse::token::str_to_ident(st)
1592     }
1593     fn name_of(&self, st: &str) -> ast::Name {
1594         parse::token::intern(st)
1595     }
1596     fn parse_sess(&self) -> &parse::ParseSess { self }
1597 }
1598
1599 #[cfg(test)]
1600 fn mk_ctxt() -> parse::ParseSess {
1601     parse::ParseSess::new()
1602 }
1603
1604 #[cfg(test)]
1605 fn roundtrip(in_item: Option<P<ast::Item>>) {
1606     let in_item = in_item.unwrap();
1607     let mut wr = Cursor::new(Vec::new());
1608     encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
1609     let rbml_doc = rbml::Doc::new(wr.get_ref());
1610     let out_item = decode_item_ast(rbml_doc);
1611
1612     assert!(*in_item == out_item);
1613 }
1614
1615 #[test]
1616 fn test_basic() {
1617     let cx = mk_ctxt();
1618     roundtrip(quote_item!(&cx,
1619         fn foo() {}
1620     ));
1621 }
1622
1623 #[test]
1624 fn test_smalltalk() {
1625     let cx = mk_ctxt();
1626     roundtrip(quote_item!(&cx,
1627         fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1628     ));
1629 }
1630
1631 #[test]
1632 fn test_more() {
1633     let cx = mk_ctxt();
1634     roundtrip(quote_item!(&cx,
1635         fn foo(x: usize, y: usize) -> usize {
1636             let z = x + y;
1637             return z;
1638         }
1639     ));
1640 }
1641
1642 #[test]
1643 fn test_simplification() {
1644     let cx = mk_ctxt();
1645     let item = quote_item!(&cx,
1646         fn new_int_alist<B>() -> alist<isize, B> {
1647             fn eq_int(a: isize, b: isize) -> bool { a == b }
1648             return alist {eq_fn: eq_int, data: Vec::new()};
1649         }
1650     ).unwrap();
1651     let item_in = e::IIItemRef(&*item);
1652     let item_out = simplify_ast(item_in);
1653     let item_exp = ast::IIItem(quote_item!(&cx,
1654         fn new_int_alist<B>() -> alist<isize, B> {
1655             return alist {eq_fn: eq_int, data: Vec::new()};
1656         }
1657     ).unwrap());
1658     match (item_out, item_exp) {
1659       (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
1660         assert!(pprust::item_to_string(&*item_out) ==
1661                 pprust::item_to_string(&*item_exp));
1662       }
1663       _ => panic!()
1664     }
1665 }