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