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