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