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