]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/astencode.rs
Auto merge of #34539 - arielb1:metadata-hash, r=alexcrichton
[rust.git] / src / librustc_metadata / 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 rustc::hir::map as ast_map;
16 use rustc::session::Session;
17
18 use rustc::hir;
19 use rustc::hir::fold;
20 use rustc::hir::fold::Folder;
21 use rustc::hir::intravisit::{IdRange, IdRangeComputingVisitor, IdVisitingOperation};
22
23 use common as c;
24 use cstore;
25 use decoder;
26 use encoder as e;
27 use tydecode;
28 use tyencode;
29
30 use middle::cstore::{InlinedItem, InlinedItemRef};
31 use rustc::ty::adjustment;
32 use rustc::ty::cast;
33 use middle::const_qualif::ConstQualif;
34 use rustc::hir::def::{self, Def};
35 use rustc::hir::def_id::DefId;
36 use middle::region;
37 use rustc::ty::subst;
38 use rustc::ty::{self, Ty, TyCtxt};
39
40 use syntax::ast;
41 use syntax::ptr::P;
42 use syntax_pos;
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 rustc_serialize as serialize;
53 use rustc_serialize::{Decodable, Decoder, DecoderHelpers};
54 use rustc_serialize::{Encodable, EncoderHelpers};
55
56 #[cfg(test)] use std::io::Cursor;
57 #[cfg(test)] use syntax::parse;
58 #[cfg(test)] use rustc::hir::print as pprust;
59 #[cfg(test)] use rustc::hir::lowering::{LoweringContext, DummyResolver};
60
61 struct DecodeContext<'a, 'b, 'tcx: 'a> {
62     tcx: TyCtxt<'a, 'tcx, 'tcx>,
63     cdata: &'b cstore::CrateMetadata,
64     from_id_range: IdRange,
65     to_id_range: 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 // ______________________________________________________________________
75 // Top-level methods.
76
77 pub fn encode_inlined_item(ecx: &e::EncodeContext,
78                            rbml_w: &mut Encoder,
79                            ii: InlinedItemRef) {
80     let id = match ii {
81         InlinedItemRef::Item(i) => i.id,
82         InlinedItemRef::Foreign(i) => i.id,
83         InlinedItemRef::TraitItem(_, ti) => ti.id,
84         InlinedItemRef::ImplItem(_, ii) => ii.id,
85     };
86     debug!("> Encoding inlined item: {} ({:?})",
87            ecx.tcx.node_path_str(id),
88            rbml_w.writer.seek(SeekFrom::Current(0)));
89
90     // Folding could be avoided with a smarter encoder.
91     let ii = simplify_ast(ii);
92     let id_range = inlined_item_id_range(&ii);
93
94     rbml_w.start_tag(c::tag_ast as usize);
95     id_range.encode(rbml_w);
96     encode_ast(rbml_w, &ii);
97     encode_side_tables_for_ii(ecx, rbml_w, &ii);
98     rbml_w.end_tag();
99
100     debug!("< Encoded inlined fn: {} ({:?})",
101            ecx.tcx.node_path_str(id),
102            rbml_w.writer.seek(SeekFrom::Current(0)));
103 }
104
105 impl<'a, 'b, 'c, 'tcx> ast_map::FoldOps for &'a DecodeContext<'b, 'c, 'tcx> {
106     fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
107         if id == ast::DUMMY_NODE_ID {
108             // Used by ast_map to map the NodeInlinedParent.
109             self.tcx.sess.next_node_id()
110         } else {
111             self.tr_id(id)
112         }
113     }
114     fn new_def_id(&self, def_id: DefId) -> DefId {
115         self.tr_def_id(def_id)
116     }
117     fn new_span(&self, span: syntax_pos::Span) -> syntax_pos::Span {
118         self.tr_span(span)
119     }
120 }
121
122 /// Decodes an item from its AST in the cdata's metadata and adds it to the
123 /// ast-map.
124 pub fn decode_inlined_item<'a, 'tcx>(cdata: &cstore::CrateMetadata,
125                                      tcx: TyCtxt<'a, 'tcx, 'tcx>,
126                                      parent_def_path: ast_map::DefPath,
127                                      parent_did: DefId,
128                                      ast_doc: rbml::Doc,
129                                      orig_did: DefId)
130                                      -> &'tcx InlinedItem {
131     debug!("> Decoding inlined fn: {:?}", tcx.item_path_str(orig_did));
132     let mut ast_dsr = reader::Decoder::new(ast_doc);
133     let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
134     let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
135     let dcx = &DecodeContext {
136         cdata: cdata,
137         tcx: tcx,
138         from_id_range: from_id_range,
139         to_id_range: to_id_range,
140         last_filemap_index: Cell::new(0)
141     };
142     let ii = ast_map::map_decoded_item(&dcx.tcx.map,
143                                        parent_def_path,
144                                        parent_did,
145                                        decode_ast(ast_doc),
146                                        dcx);
147     let name = match *ii {
148         InlinedItem::Item(ref i) => i.name,
149         InlinedItem::Foreign(ref i) => i.name,
150         InlinedItem::TraitItem(_, ref ti) => ti.name,
151         InlinedItem::ImplItem(_, ref ii) => ii.name
152     };
153     debug!("Fn named: {}", name);
154     debug!("< Decoded inlined fn: {}::{}",
155             tcx.item_path_str(parent_did),
156             name);
157     region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
158     decode_side_tables(dcx, ast_doc);
159     copy_item_types(dcx, ii, orig_did);
160     if let InlinedItem::Item(ref i) = *ii {
161         debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
162                ::rustc::hir::print::item_to_string(&i));
163     }
164
165     ii
166 }
167
168 // ______________________________________________________________________
169 // Enumerating the IDs which appear in an AST
170
171 fn reserve_id_range(sess: &Session,
172                     from_id_range: IdRange) -> IdRange {
173     // Handle the case of an empty range:
174     if from_id_range.empty() { return from_id_range; }
175     let cnt = from_id_range.max - from_id_range.min;
176     let to_id_min = sess.reserve_node_ids(cnt);
177     let to_id_max = to_id_min + cnt;
178     IdRange { min: to_id_min, max: to_id_max }
179 }
180
181 impl<'a, 'b, 'tcx> DecodeContext<'a, 'b, 'tcx> {
182     /// Translates an internal id, meaning a node id that is known to refer to some part of the
183     /// item currently being inlined, such as a local variable or argument.  All naked node-ids
184     /// that appear in types have this property, since if something might refer to an external item
185     /// we would use a def-id to allow for the possibility that the item resides in another crate.
186     pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
187         // from_id_range should be non-empty
188         assert!(!self.from_id_range.empty());
189         // Use wrapping arithmetic because otherwise it introduces control flow.
190         // Maybe we should just have the control flow? -- aatch
191         (id.wrapping_sub(self.from_id_range.min).wrapping_add(self.to_id_range.min))
192     }
193
194     /// Translates an EXTERNAL def-id, converting the crate number from the one used in the encoded
195     /// data to the current crate numbers..  By external, I mean that it be translated to a
196     /// reference to the item in its original crate, as opposed to being translated to a reference
197     /// to the inlined version of the item.  This is typically, but not always, what you want,
198     /// because most def-ids refer to external things like types or other fns that may or may not
199     /// be inlined.  Note that even when the inlined function is referencing itself recursively, we
200     /// would want `tr_def_id` for that reference--- conceptually the function calls the original,
201     /// non-inlined version, and trans deals with linking that recursive call to the inlined copy.
202     pub fn tr_def_id(&self, did: DefId) -> DefId {
203         decoder::translate_def_id(self.cdata, did)
204     }
205
206     /// Translates a `Span` from an extern crate to the corresponding `Span`
207     /// within the local crate's codemap.
208     pub fn tr_span(&self, span: syntax_pos::Span) -> syntax_pos::Span {
209         decoder::translate_span(self.cdata,
210                                 self.tcx.sess.codemap(),
211                                 &self.last_filemap_index,
212                                 span)
213     }
214 }
215
216 impl tr for DefId {
217     fn tr(&self, dcx: &DecodeContext) -> DefId {
218         dcx.tr_def_id(*self)
219     }
220 }
221
222 impl tr for Option<DefId> {
223     fn tr(&self, dcx: &DecodeContext) -> Option<DefId> {
224         self.map(|d| dcx.tr_def_id(d))
225     }
226 }
227
228 impl tr for syntax_pos::Span {
229     fn tr(&self, dcx: &DecodeContext) -> syntax_pos::Span {
230         dcx.tr_span(*self)
231     }
232 }
233
234 trait def_id_encoder_helpers {
235     fn emit_def_id(&mut self, did: DefId);
236 }
237
238 impl<S:serialize::Encoder> def_id_encoder_helpers for S
239     where <S as serialize::Encoder>::Error: Debug
240 {
241     fn emit_def_id(&mut self, did: DefId) {
242         did.encode(self).unwrap()
243     }
244 }
245
246 trait def_id_decoder_helpers {
247     fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId;
248     fn read_def_id_nodcx(&mut self,
249                          cdata: &cstore::CrateMetadata) -> DefId;
250 }
251
252 impl<D:serialize::Decoder> def_id_decoder_helpers for D
253     where <D as serialize::Decoder>::Error: Debug
254 {
255     fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId {
256         let did: DefId = Decodable::decode(self).unwrap();
257         did.tr(dcx)
258     }
259
260     fn read_def_id_nodcx(&mut self,
261                          cdata: &cstore::CrateMetadata)
262                          -> DefId {
263         let did: DefId = Decodable::decode(self).unwrap();
264         decoder::translate_def_id(cdata, did)
265     }
266 }
267
268 // ______________________________________________________________________
269 // Encoding and decoding the AST itself
270 //
271 // When decoding, we have to renumber the AST so that the node ids that
272 // appear within are disjoint from the node ids in our existing ASTs.
273 // We also have to adjust the spans: for now we just insert a dummy span,
274 // but eventually we should add entries to the local codemap as required.
275
276 fn encode_ast(rbml_w: &mut Encoder, item: &InlinedItem) {
277     rbml_w.start_tag(c::tag_tree as usize);
278     rbml_w.emit_opaque(|this| item.encode(this));
279     rbml_w.end_tag();
280 }
281
282 struct NestedItemsDropper;
283
284 impl Folder for NestedItemsDropper {
285     fn fold_block(&mut self, blk: P<hir::Block>) -> P<hir::Block> {
286         blk.and_then(|hir::Block {id, stmts, expr, rules, span, ..}| {
287             let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
288                 let use_stmt = match stmt.node {
289                     hir::StmtExpr(_, _) | hir::StmtSemi(_, _) => true,
290                     hir::StmtDecl(ref decl, _) => {
291                         match decl.node {
292                             hir::DeclLocal(_) => true,
293                             hir::DeclItem(_) => false,
294                         }
295                     }
296                 };
297                 if use_stmt {
298                     Some(stmt)
299                 } else {
300                     None
301                 }
302             }).collect();
303             let blk_sans_items = P(hir::Block {
304                 stmts: stmts_sans_items,
305                 expr: expr,
306                 id: id,
307                 rules: rules,
308                 span: span,
309             });
310             fold::noop_fold_block(blk_sans_items, self)
311         })
312     }
313 }
314
315 // Produces a simplified copy of the AST which does not include things
316 // that we do not need to or do not want to export.  For example, we
317 // do not include any nested items: if these nested items are to be
318 // inlined, their AST will be exported separately (this only makes
319 // sense because, in Rust, nested items are independent except for
320 // their visibility).
321 //
322 // As it happens, trans relies on the fact that we do not export
323 // nested items, as otherwise it would get confused when translating
324 // inlined items.
325 fn simplify_ast(ii: InlinedItemRef) -> InlinedItem {
326     let mut fld = NestedItemsDropper;
327
328     match ii {
329         // HACK we're not dropping items.
330         InlinedItemRef::Item(i) => {
331             InlinedItem::Item(P(fold::noop_fold_item(i.clone(), &mut fld)))
332         }
333         InlinedItemRef::TraitItem(d, ti) => {
334             InlinedItem::TraitItem(d, P(fold::noop_fold_trait_item(ti.clone(), &mut fld)))
335         }
336         InlinedItemRef::ImplItem(d, ii) => {
337             InlinedItem::ImplItem(d, P(fold::noop_fold_impl_item(ii.clone(), &mut fld)))
338         }
339         InlinedItemRef::Foreign(i) => {
340             InlinedItem::Foreign(P(fold::noop_fold_foreign_item(i.clone(), &mut fld)))
341         }
342     }
343 }
344
345 fn decode_ast(item_doc: rbml::Doc) -> InlinedItem {
346     let chi_doc = item_doc.get(c::tag_tree as usize);
347     let mut rbml_r = reader::Decoder::new(chi_doc);
348     rbml_r.read_opaque(|decoder, _| Decodable::decode(decoder)).unwrap()
349 }
350
351 // ______________________________________________________________________
352 // Encoding and decoding of ast::def
353
354 fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> Def {
355     let def: Def = Decodable::decode(dsr).unwrap();
356     def.tr(dcx)
357 }
358
359 impl tr for Def {
360     fn tr(&self, dcx: &DecodeContext) -> Def {
361         match *self {
362           Def::Fn(did) => Def::Fn(did.tr(dcx)),
363           Def::Method(did) => Def::Method(did.tr(dcx)),
364           Def::SelfTy(opt_did, impl_id) => { Def::SelfTy(opt_did.map(|did| did.tr(dcx)),
365                                                          impl_id.map(|id| dcx.tr_id(id))) }
366           Def::Mod(did) => { Def::Mod(did.tr(dcx)) }
367           Def::ForeignMod(did) => { Def::ForeignMod(did.tr(dcx)) }
368           Def::Static(did, m) => { Def::Static(did.tr(dcx), m) }
369           Def::Const(did) => { Def::Const(did.tr(dcx)) }
370           Def::AssociatedConst(did) => Def::AssociatedConst(did.tr(dcx)),
371           Def::Local(_, nid) => {
372               let nid = dcx.tr_id(nid);
373               let did = dcx.tcx.map.local_def_id(nid);
374               Def::Local(did, nid)
375           }
376           Def::Variant(e_did, v_did) => Def::Variant(e_did.tr(dcx), v_did.tr(dcx)),
377           Def::Trait(did) => Def::Trait(did.tr(dcx)),
378           Def::Enum(did) => Def::Enum(did.tr(dcx)),
379           Def::TyAlias(did) => Def::TyAlias(did.tr(dcx)),
380           Def::AssociatedTy(trait_did, did) =>
381               Def::AssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
382           Def::PrimTy(p) => Def::PrimTy(p),
383           Def::TyParam(s, index, def_id, n) => Def::TyParam(s, index, def_id.tr(dcx), n),
384           Def::Upvar(_, nid1, index, nid2) => {
385               let nid1 = dcx.tr_id(nid1);
386               let nid2 = dcx.tr_id(nid2);
387               let did1 = dcx.tcx.map.local_def_id(nid1);
388               Def::Upvar(did1, nid1, index, nid2)
389           }
390           Def::Struct(did) => Def::Struct(did.tr(dcx)),
391           Def::Label(nid) => Def::Label(dcx.tr_id(nid)),
392           Def::Err => Def::Err,
393         }
394     }
395 }
396
397 // ______________________________________________________________________
398 // Encoding and decoding of freevar information
399
400 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &hir::Freevar) {
401     (*fv).encode(rbml_w).unwrap();
402 }
403
404 trait rbml_decoder_helper {
405     fn read_freevar_entry(&mut self, dcx: &DecodeContext)
406                           -> hir::Freevar;
407     fn read_capture_mode(&mut self) -> hir::CaptureClause;
408 }
409
410 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
411     fn read_freevar_entry(&mut self, dcx: &DecodeContext)
412                           -> hir::Freevar {
413         let fv: hir::Freevar = Decodable::decode(self).unwrap();
414         fv.tr(dcx)
415     }
416
417     fn read_capture_mode(&mut self) -> hir::CaptureClause {
418         let cm: hir::CaptureClause = Decodable::decode(self).unwrap();
419         cm
420     }
421 }
422
423 impl tr for hir::Freevar {
424     fn tr(&self, dcx: &DecodeContext) -> hir::Freevar {
425         hir::Freevar {
426             def: self.def.tr(dcx),
427             span: self.span.tr(dcx),
428         }
429     }
430 }
431
432 // ______________________________________________________________________
433 // Encoding and decoding of MethodCallee
434
435 trait read_method_callee_helper<'tcx> {
436     fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
437                                   -> (u32, ty::MethodCallee<'tcx>);
438 }
439
440 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
441                                   rbml_w: &mut Encoder,
442                                   autoderef: u32,
443                                   method: &ty::MethodCallee<'tcx>) {
444     use rustc_serialize::Encoder;
445
446     rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
447         rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
448             autoderef.encode(rbml_w)
449         });
450         rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
451             Ok(rbml_w.emit_def_id(method.def_id))
452         });
453         rbml_w.emit_struct_field("ty", 2, |rbml_w| {
454             Ok(rbml_w.emit_ty(ecx, method.ty))
455         });
456         rbml_w.emit_struct_field("substs", 3, |rbml_w| {
457             Ok(rbml_w.emit_substs(ecx, &method.substs))
458         })
459     }).unwrap();
460 }
461
462 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
463     fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
464                                   -> (u32, ty::MethodCallee<'tcx>) {
465
466         self.read_struct("MethodCallee", 4, |this| {
467             let autoderef = this.read_struct_field("autoderef", 0,
468                                                    Decodable::decode).unwrap();
469             Ok((autoderef, ty::MethodCallee {
470                 def_id: this.read_struct_field("def_id", 1, |this| {
471                     Ok(this.read_def_id(dcx))
472                 }).unwrap(),
473                 ty: this.read_struct_field("ty", 2, |this| {
474                     Ok(this.read_ty(dcx))
475                 }).unwrap(),
476                 substs: this.read_struct_field("substs", 3, |this| {
477                     Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
478                 }).unwrap()
479             }))
480         }).unwrap()
481     }
482 }
483
484 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
485     kind.encode(ebml_w).unwrap();
486 }
487
488 // ______________________________________________________________________
489 // Encoding and decoding the side tables
490
491 trait rbml_writer_helpers<'tcx> {
492     fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region);
493     fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
494     fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
495     fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
496                           predicate: &ty::Predicate<'tcx>);
497     fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
498                           ty: &ty::TraitRef<'tcx>);
499     fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
500                        substs: &subst::Substs<'tcx>);
501     fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
502                                    bounds: &ty::ExistentialBounds<'tcx>);
503     fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
504     fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture);
505     fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
506                                 adj: &adjustment::AutoAdjustment<'tcx>);
507     fn emit_autoref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
508                         autoref: &adjustment::AutoRef<'tcx>);
509     fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
510                                auto_deref_ref: &adjustment::AutoDerefRef<'tcx>);
511 }
512
513 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
514     fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region) {
515         self.emit_opaque(|this| Ok(tyencode::enc_region(&mut this.cursor,
516                                                         &ecx.ty_str_ctxt(),
517                                                         r)));
518     }
519
520     fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
521         self.emit_opaque(|this| Ok(tyencode::enc_ty(&mut this.cursor,
522                                                     &ecx.ty_str_ctxt(),
523                                                     ty)));
524     }
525
526     fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
527         self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
528     }
529
530     fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
531                           trait_ref: &ty::TraitRef<'tcx>) {
532         self.emit_opaque(|this| Ok(tyencode::enc_trait_ref(&mut this.cursor,
533                                                            &ecx.ty_str_ctxt(),
534                                                            *trait_ref)));
535     }
536
537     fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
538                           predicate: &ty::Predicate<'tcx>) {
539         self.emit_opaque(|this| {
540             Ok(tyencode::enc_predicate(&mut this.cursor,
541                                        &ecx.ty_str_ctxt(),
542                                        predicate))
543         });
544     }
545
546     fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
547                                    bounds: &ty::ExistentialBounds<'tcx>) {
548         self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(&mut this.cursor,
549                                                                     &ecx.ty_str_ctxt(),
550                                                                     bounds)));
551     }
552
553     fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
554         self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(&mut this.cursor,
555                                                                 &ecx.ty_str_ctxt(),
556                                                                 bounds)));
557     }
558
559     fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture) {
560         use rustc_serialize::Encoder;
561
562         self.emit_enum("UpvarCapture", |this| {
563             match *capture {
564                 ty::UpvarCapture::ByValue => {
565                     this.emit_enum_variant("ByValue", 1, 0, |_| Ok(()))
566                 }
567                 ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind, region }) => {
568                     this.emit_enum_variant("ByRef", 2, 0, |this| {
569                         this.emit_enum_variant_arg(0,
570                             |this| kind.encode(this));
571                         this.emit_enum_variant_arg(1,
572                             |this| Ok(this.emit_region(ecx, region)))
573                     })
574                 }
575             }
576         }).unwrap()
577     }
578
579     fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
580                        substs: &subst::Substs<'tcx>) {
581         self.emit_opaque(|this| Ok(tyencode::enc_substs(&mut this.cursor,
582                                                         &ecx.ty_str_ctxt(),
583                                                         substs)));
584     }
585
586     fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
587                                 adj: &adjustment::AutoAdjustment<'tcx>) {
588         use rustc_serialize::Encoder;
589
590         self.emit_enum("AutoAdjustment", |this| {
591             match *adj {
592                 adjustment::AdjustReifyFnPointer => {
593                     this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
594                 }
595
596                 adjustment::AdjustUnsafeFnPointer => {
597                     this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
598                         Ok(())
599                     })
600                 }
601
602                 adjustment::AdjustMutToConstPointer => {
603                     this.emit_enum_variant("AdjustMutToConstPointer", 3, 0, |_| {
604                         Ok(())
605                     })
606                 }
607
608                 adjustment::AdjustDerefRef(ref auto_deref_ref) => {
609                     this.emit_enum_variant("AdjustDerefRef", 4, 2, |this| {
610                         this.emit_enum_variant_arg(0,
611                             |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
612                     })
613                 }
614             }
615         });
616     }
617
618     fn emit_autoref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
619                         autoref: &adjustment::AutoRef<'tcx>) {
620         use rustc_serialize::Encoder;
621
622         self.emit_enum("AutoRef", |this| {
623             match autoref {
624                 &adjustment::AutoPtr(r, m) => {
625                     this.emit_enum_variant("AutoPtr", 0, 2, |this| {
626                         this.emit_enum_variant_arg(0,
627                             |this| Ok(this.emit_region(ecx, *r)));
628                         this.emit_enum_variant_arg(1, |this| m.encode(this))
629                     })
630                 }
631                 &adjustment::AutoUnsafe(m) => {
632                     this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
633                         this.emit_enum_variant_arg(0, |this| m.encode(this))
634                     })
635                 }
636             }
637         });
638     }
639
640     fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
641                                auto_deref_ref: &adjustment::AutoDerefRef<'tcx>) {
642         use rustc_serialize::Encoder;
643
644         self.emit_struct("AutoDerefRef", 2, |this| {
645             this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
646
647             this.emit_struct_field("autoref", 1, |this| {
648                 this.emit_option(|this| {
649                     match auto_deref_ref.autoref {
650                         None => this.emit_option_none(),
651                         Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a))),
652                     }
653                 })
654             });
655
656             this.emit_struct_field("unsize", 2, |this| {
657                 this.emit_option(|this| {
658                     match auto_deref_ref.unsize {
659                         None => this.emit_option_none(),
660                         Some(target) => this.emit_option_some(|this| {
661                             Ok(this.emit_ty(ecx, target))
662                         })
663                     }
664                 })
665             })
666         });
667     }
668 }
669
670 trait write_tag_and_id {
671     fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
672     fn id(&mut self, id: ast::NodeId);
673 }
674
675 impl<'a> write_tag_and_id for Encoder<'a> {
676     fn tag<F>(&mut self,
677               tag_id: c::astencode_tag,
678               f: F) where
679         F: FnOnce(&mut Encoder<'a>),
680     {
681         self.start_tag(tag_id as usize);
682         f(self);
683         self.end_tag();
684     }
685
686     fn id(&mut self, id: ast::NodeId) {
687         id.encode(self).unwrap();
688     }
689 }
690
691 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
692     ecx: &'a e::EncodeContext<'c, 'tcx>,
693     rbml_w: &'a mut Encoder<'b>,
694 }
695
696 impl<'a, 'b, 'c, 'tcx> IdVisitingOperation for
697         SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
698     fn visit_id(&mut self, id: ast::NodeId) {
699         encode_side_tables_for_id(self.ecx, self.rbml_w, id)
700     }
701 }
702
703 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
704                              rbml_w: &mut Encoder,
705                              ii: &InlinedItem) {
706     rbml_w.start_tag(c::tag_table as usize);
707     ii.visit_ids(&mut SideTableEncodingIdVisitor {
708         ecx: ecx,
709         rbml_w: rbml_w
710     });
711     rbml_w.end_tag();
712 }
713
714 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
715                              rbml_w: &mut Encoder,
716                              id: ast::NodeId) {
717     let tcx = ecx.tcx;
718
719     debug!("Encoding side tables for id {}", id);
720
721     if let Some(def) = tcx.expect_def_or_none(id) {
722         rbml_w.tag(c::tag_table_def, |rbml_w| {
723             rbml_w.id(id);
724             def.encode(rbml_w).unwrap();
725         })
726     }
727
728     if let Some(ty) = tcx.node_types().get(&id) {
729         rbml_w.tag(c::tag_table_node_type, |rbml_w| {
730             rbml_w.id(id);
731             rbml_w.emit_ty(ecx, *ty);
732         })
733     }
734
735     if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
736         rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
737             rbml_w.id(id);
738             rbml_w.emit_substs(ecx, &item_substs.substs);
739         })
740     }
741
742     if let Some(fv) = tcx.freevars.borrow().get(&id) {
743         rbml_w.tag(c::tag_table_freevars, |rbml_w| {
744             rbml_w.id(id);
745             rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
746                 Ok(encode_freevar_entry(rbml_w, fv_entry))
747             });
748         });
749
750         for freevar in fv {
751             rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
752                 rbml_w.id(id);
753
754                 let var_id = freevar.def.var_id();
755                 let upvar_id = ty::UpvarId {
756                     var_id: var_id,
757                     closure_expr_id: id
758                 };
759                 let upvar_capture = tcx.tables
760                                        .borrow()
761                                        .upvar_capture_map
762                                        .get(&upvar_id)
763                                        .unwrap()
764                                        .clone();
765                 var_id.encode(rbml_w);
766                 rbml_w.emit_upvar_capture(ecx, &upvar_capture);
767             })
768         }
769     }
770
771     let method_call = ty::MethodCall::expr(id);
772     if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
773         rbml_w.tag(c::tag_table_method_map, |rbml_w| {
774             rbml_w.id(id);
775             encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
776         })
777     }
778
779     if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
780         match *adjustment {
781             adjustment::AdjustDerefRef(ref adj) => {
782                 for autoderef in 0..adj.autoderefs {
783                     let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
784                     if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
785                         rbml_w.tag(c::tag_table_method_map, |rbml_w| {
786                             rbml_w.id(id);
787                             encode_method_callee(ecx, rbml_w,
788                                                  method_call.autoderef, method)
789                         })
790                     }
791                 }
792             }
793             _ => {}
794         }
795
796         rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
797             rbml_w.id(id);
798             rbml_w.emit_auto_adjustment(ecx, adjustment);
799         })
800     }
801
802     if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
803         rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
804             rbml_w.id(id);
805             encode_cast_kind(rbml_w, *cast_kind)
806         })
807     }
808
809     if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
810         rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
811             rbml_w.id(id);
812             qualif.encode(rbml_w).unwrap()
813         })
814     }
815 }
816
817 trait doc_decoder_helpers: Sized {
818     fn as_int(&self) -> isize;
819     fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
820 }
821
822 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
823     fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
824     fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
825         reader::maybe_get_doc(*self, tag as usize)
826     }
827 }
828
829 trait rbml_decoder_decoder_helpers<'tcx> {
830     fn read_ty_encoded<'a, 'b, F, R>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>,
831                                      f: F) -> R
832         where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x, 'tcx>) -> R;
833
834     fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region;
835     fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
836     fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
837     fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
838                               -> ty::TraitRef<'tcx>;
839     fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
840                                    -> ty::PolyTraitRef<'tcx>;
841     fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
842                               -> ty::Predicate<'tcx>;
843     fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
844                                        -> ty::ExistentialBounds<'tcx>;
845     fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
846                            -> subst::Substs<'tcx>;
847     fn read_upvar_capture(&mut self, dcx: &DecodeContext)
848                           -> ty::UpvarCapture;
849     fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
850                                     -> adjustment::AutoAdjustment<'tcx>;
851     fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
852                                  -> cast::CastKind;
853     fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
854                                    -> adjustment::AutoDerefRef<'tcx>;
855     fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
856                             -> adjustment::AutoRef<'tcx>;
857
858     // Versions of the type reading functions that don't need the full
859     // DecodeContext.
860     fn read_ty_nodcx<'a>(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
861                          cdata: &cstore::CrateMetadata) -> Ty<'tcx>;
862     fn read_tys_nodcx<'a>(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
863                           cdata: &cstore::CrateMetadata) -> Vec<Ty<'tcx>>;
864     fn read_substs_nodcx<'a>(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
865                              cdata: &cstore::CrateMetadata)
866                              -> subst::Substs<'tcx>;
867 }
868
869 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
870     fn read_ty_nodcx<'b>(&mut self, tcx: TyCtxt<'b, 'tcx, 'tcx>,
871                          cdata: &cstore::CrateMetadata)
872                          -> Ty<'tcx> {
873         self.read_opaque(|_, doc| {
874             Ok(
875                 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
876                                               &mut |id| decoder::translate_def_id(cdata, id))
877                     .parse_ty())
878         }).unwrap()
879     }
880
881     fn read_tys_nodcx<'b>(&mut self, tcx: TyCtxt<'b, 'tcx, 'tcx>,
882                           cdata: &cstore::CrateMetadata) -> Vec<Ty<'tcx>> {
883         self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
884             .unwrap()
885             .into_iter()
886             .collect()
887     }
888
889     fn read_substs_nodcx<'b>(&mut self, tcx: TyCtxt<'b, 'tcx, 'tcx>,
890                              cdata: &cstore::CrateMetadata)
891                              -> subst::Substs<'tcx>
892     {
893         self.read_opaque(|_, doc| {
894             Ok(
895                 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
896                                               &mut |id| decoder::translate_def_id(cdata, id))
897                     .parse_substs())
898         }).unwrap()
899     }
900
901     fn read_ty_encoded<'b, 'c, F, R>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>, op: F) -> R
902         where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x,'tcx>) -> R
903     {
904         return self.read_opaque(|_, doc| {
905             debug!("read_ty_encoded({})", type_string(doc));
906             Ok(op(
907                 &mut tydecode::TyDecoder::with_doc(
908                     dcx.tcx, dcx.cdata.cnum, doc,
909                     &mut |d| convert_def_id(dcx, d))))
910         }).unwrap();
911
912         fn type_string(doc: rbml::Doc) -> String {
913             let mut str = String::new();
914             for i in doc.start..doc.end {
915                 str.push(doc.data[i] as char);
916             }
917             str
918         }
919     }
920     fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region {
921         // Note: regions types embed local node ids.  In principle, we
922         // should translate these node ids into the new decode
923         // context.  However, we do not bother, because region types
924         // are not used during trans. This also applies to read_ty.
925         return self.read_ty_encoded(dcx, |decoder| decoder.parse_region());
926     }
927     fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
928         return self.read_ty_encoded(dcx, |decoder| decoder.parse_ty());
929     }
930
931     fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
932                         -> Vec<Ty<'tcx>> {
933         self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
934     }
935
936     fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
937                               -> ty::TraitRef<'tcx> {
938         self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref())
939     }
940
941     fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
942                                    -> ty::PolyTraitRef<'tcx> {
943         ty::Binder(self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref()))
944     }
945
946     fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
947                               -> ty::Predicate<'tcx>
948     {
949         self.read_ty_encoded(dcx, |decoder| decoder.parse_predicate())
950     }
951
952     fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
953                                        -> ty::ExistentialBounds<'tcx>
954     {
955         self.read_ty_encoded(dcx, |decoder| decoder.parse_existential_bounds())
956     }
957
958     fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
959                            -> subst::Substs<'tcx> {
960         self.read_opaque(|_, doc| {
961             Ok(tydecode::TyDecoder::with_doc(dcx.tcx, dcx.cdata.cnum, doc,
962                                              &mut |d| convert_def_id(dcx, d))
963                .parse_substs())
964         }).unwrap()
965     }
966     fn read_upvar_capture(&mut self, dcx: &DecodeContext) -> ty::UpvarCapture {
967         self.read_enum("UpvarCapture", |this| {
968             let variants = ["ByValue", "ByRef"];
969             this.read_enum_variant(&variants, |this, i| {
970                 Ok(match i {
971                     1 => ty::UpvarCapture::ByValue,
972                     2 => ty::UpvarCapture::ByRef(ty::UpvarBorrow {
973                         kind: this.read_enum_variant_arg(0,
974                                   |this| Decodable::decode(this)).unwrap(),
975                         region: this.read_enum_variant_arg(1,
976                                     |this| Ok(this.read_region(dcx))).unwrap()
977                     }),
978                     _ => bug!("bad enum variant for ty::UpvarCapture")
979                 })
980             })
981         }).unwrap()
982     }
983     fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
984                                     -> adjustment::AutoAdjustment<'tcx> {
985         self.read_enum("AutoAdjustment", |this| {
986             let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer",
987                             "AdjustMutToConstPointer", "AdjustDerefRef"];
988             this.read_enum_variant(&variants, |this, i| {
989                 Ok(match i {
990                     1 => adjustment::AdjustReifyFnPointer,
991                     2 => adjustment::AdjustUnsafeFnPointer,
992                     3 => adjustment::AdjustMutToConstPointer,
993                     4 => {
994                         let auto_deref_ref: adjustment::AutoDerefRef =
995                             this.read_enum_variant_arg(0,
996                                 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
997
998                         adjustment::AdjustDerefRef(auto_deref_ref)
999                     }
1000                     _ => bug!("bad enum variant for adjustment::AutoAdjustment")
1001                 })
1002             })
1003         }).unwrap()
1004     }
1005
1006     fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1007                                    -> adjustment::AutoDerefRef<'tcx> {
1008         self.read_struct("AutoDerefRef", 2, |this| {
1009             Ok(adjustment::AutoDerefRef {
1010                 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1011                     Decodable::decode(this)
1012                 }).unwrap(),
1013                 autoref: this.read_struct_field("autoref", 1, |this| {
1014                     this.read_option(|this, b| {
1015                         if b {
1016                             Ok(Some(this.read_autoref(dcx)))
1017                         } else {
1018                             Ok(None)
1019                         }
1020                     })
1021                 }).unwrap(),
1022                 unsize: this.read_struct_field("unsize", 2, |this| {
1023                     this.read_option(|this, b| {
1024                         if b {
1025                             Ok(Some(this.read_ty(dcx)))
1026                         } else {
1027                             Ok(None)
1028                         }
1029                     })
1030                 }).unwrap(),
1031             })
1032         }).unwrap()
1033     }
1034
1035     fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1036                             -> adjustment::AutoRef<'tcx> {
1037         self.read_enum("AutoRef", |this| {
1038             let variants = ["AutoPtr", "AutoUnsafe"];
1039             this.read_enum_variant(&variants, |this, i| {
1040                 Ok(match i {
1041                     0 => {
1042                         let r: ty::Region =
1043                             this.read_enum_variant_arg(0, |this| {
1044                                 Ok(this.read_region(dcx))
1045                             }).unwrap();
1046                         let m: hir::Mutability =
1047                             this.read_enum_variant_arg(1, |this| {
1048                                 Decodable::decode(this)
1049                             }).unwrap();
1050
1051                         adjustment::AutoPtr(dcx.tcx.mk_region(r), m)
1052                     }
1053                     1 => {
1054                         let m: hir::Mutability =
1055                             this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1056
1057                         adjustment::AutoUnsafe(m)
1058                     }
1059                     _ => bug!("bad enum variant for adjustment::AutoRef")
1060                 })
1061             })
1062         }).unwrap()
1063     }
1064
1065     fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1066                               -> cast::CastKind
1067     {
1068         Decodable::decode(self).unwrap()
1069     }
1070 }
1071
1072 // Converts a def-id that appears in a type.  The correct
1073 // translation will depend on what kind of def-id this is.
1074 // This is a subtle point: type definitions are not
1075 // inlined into the current crate, so if the def-id names
1076 // a nominal type or type alias, then it should be
1077 // translated to refer to the source crate.
1078 //
1079 // However, *type parameters* are cloned along with the function
1080 // they are attached to.  So we should translate those def-ids
1081 // to refer to the new, cloned copy of the type parameter.
1082 // We only see references to free type parameters in the body of
1083 // an inlined function. In such cases, we need the def-id to
1084 // be a local id so that the TypeContents code is able to lookup
1085 // the relevant info in the ty_param_defs table.
1086 //
1087 // *Region parameters*, unfortunately, are another kettle of fish.
1088 // In such cases, def_id's can appear in types to distinguish
1089 // shadowed bound regions and so forth. It doesn't actually
1090 // matter so much what we do to these, since regions are erased
1091 // at trans time, but it's good to keep them consistent just in
1092 // case. We translate them with `tr_def_id()` which will map
1093 // the crate numbers back to the original source crate.
1094 //
1095 // Scopes will end up as being totally bogus. This can actually
1096 // be fixed though.
1097 //
1098 // Unboxed closures are cloned along with the function being
1099 // inlined, and all side tables use interned node IDs, so we
1100 // translate their def IDs accordingly.
1101 //
1102 // It'd be really nice to refactor the type repr to not include
1103 // def-ids so that all these distinctions were unnecessary.
1104 fn convert_def_id(dcx: &DecodeContext,
1105                   did: DefId)
1106                   -> DefId {
1107     let r = dcx.tr_def_id(did);
1108     debug!("convert_def_id(did={:?})={:?}", did, r);
1109     return r;
1110 }
1111
1112 fn decode_side_tables(dcx: &DecodeContext,
1113                       ast_doc: rbml::Doc) {
1114     let tbl_doc = ast_doc.get(c::tag_table as usize);
1115     for (tag, entry_doc) in reader::docs(tbl_doc) {
1116         let mut entry_dsr = reader::Decoder::new(entry_doc);
1117         let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1118         let id = dcx.tr_id(id0);
1119
1120         debug!(">> Side table document with tag 0x{:x} \
1121                 found for id {} (orig {})",
1122                tag, id, id0);
1123         let tag = tag as u32;
1124         let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1125         match decoded_tag {
1126             None => {
1127                 bug!("unknown tag found in side tables: {:x}", tag);
1128             }
1129             Some(value) => {
1130                 let val_dsr = &mut entry_dsr;
1131
1132                 match value {
1133                     c::tag_table_def => {
1134                         let def = decode_def(dcx, val_dsr);
1135                         dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution::new(def));
1136                     }
1137                     c::tag_table_node_type => {
1138                         let ty = val_dsr.read_ty(dcx);
1139                         debug!("inserting ty for node {}: {:?}",
1140                                id,  ty);
1141                         dcx.tcx.node_type_insert(id, ty);
1142                     }
1143                     c::tag_table_item_subst => {
1144                         let item_substs = ty::ItemSubsts {
1145                             substs: dcx.tcx.mk_substs(val_dsr.read_substs(dcx))
1146                         };
1147                         dcx.tcx.tables.borrow_mut().item_substs.insert(
1148                             id, item_substs);
1149                     }
1150                     c::tag_table_freevars => {
1151                         let fv_info = val_dsr.read_to_vec(|val_dsr| {
1152                             Ok(val_dsr.read_freevar_entry(dcx))
1153                         }).unwrap().into_iter().collect();
1154                         dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1155                     }
1156                     c::tag_table_upvar_capture_map => {
1157                         let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1158                         let upvar_id = ty::UpvarId {
1159                             var_id: dcx.tr_id(var_id),
1160                             closure_expr_id: id
1161                         };
1162                         let ub = val_dsr.read_upvar_capture(dcx);
1163                         dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub);
1164                     }
1165                     c::tag_table_method_map => {
1166                         let (autoderef, method) = val_dsr.read_method_callee(dcx);
1167                         let method_call = ty::MethodCall {
1168                             expr_id: id,
1169                             autoderef: autoderef
1170                         };
1171                         dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1172                     }
1173                     c::tag_table_adjustments => {
1174                         let adj =
1175                             val_dsr.read_auto_adjustment(dcx);
1176                         dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1177                     }
1178                     c::tag_table_cast_kinds => {
1179                         let cast_kind =
1180                             val_dsr.read_cast_kind(dcx);
1181                         dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1182                     }
1183                     c::tag_table_const_qualif => {
1184                         let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1185                         dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1186                     }
1187                     _ => {
1188                         bug!("unknown tag found in side tables: {:x}", tag);
1189                     }
1190                 }
1191             }
1192         }
1193
1194         debug!(">< Side table doc loaded");
1195     }
1196 }
1197
1198 // copy the tcache entries from the original item to the new
1199 // inlined item
1200 fn copy_item_types(dcx: &DecodeContext, ii: &InlinedItem, orig_did: DefId) {
1201     fn copy_item_type(dcx: &DecodeContext,
1202                       inlined_id: ast::NodeId,
1203                       remote_did: DefId) {
1204         let inlined_did = dcx.tcx.map.local_def_id(inlined_id);
1205         dcx.tcx.register_item_type(inlined_did,
1206                                    dcx.tcx.lookup_item_type(remote_did));
1207
1208     }
1209     // copy the entry for the item itself
1210     let item_node_id = match ii {
1211         &InlinedItem::Item(ref i) => i.id,
1212         &InlinedItem::TraitItem(_, ref ti) => ti.id,
1213         &InlinedItem::ImplItem(_, ref ii) => ii.id,
1214         &InlinedItem::Foreign(ref fi) => fi.id
1215     };
1216     copy_item_type(dcx, item_node_id, orig_did);
1217
1218     // copy the entries of inner items
1219     if let &InlinedItem::Item(ref item) = ii {
1220         match item.node {
1221             hir::ItemEnum(ref def, _) => {
1222                 let orig_def = dcx.tcx.lookup_adt_def(orig_did);
1223                 for (i_variant, orig_variant) in
1224                     def.variants.iter().zip(orig_def.variants.iter())
1225                 {
1226                     debug!("astencode: copying variant {:?} => {:?}",
1227                            orig_variant.did, i_variant.node.data.id());
1228                     copy_item_type(dcx, i_variant.node.data.id(), orig_variant.did);
1229                 }
1230             }
1231             hir::ItemStruct(ref def, _) => {
1232                 if !def.is_struct() {
1233                     let ctor_did = dcx.tcx.lookup_adt_def(orig_did)
1234                         .struct_variant().did;
1235                     debug!("astencode: copying ctor {:?} => {:?}", ctor_did,
1236                            def.id());
1237                     copy_item_type(dcx, def.id(), ctor_did);
1238                 }
1239             }
1240             _ => {}
1241         }
1242     }
1243 }
1244
1245 fn inlined_item_id_range(v: &InlinedItem) -> IdRange {
1246     let mut visitor = IdRangeComputingVisitor::new();
1247     v.visit_ids(&mut visitor);
1248     visitor.result()
1249 }
1250
1251 // ______________________________________________________________________
1252 // Testing of astencode_gen
1253
1254 #[cfg(test)]
1255 fn encode_item_ast(rbml_w: &mut Encoder, item: &hir::Item) {
1256     rbml_w.start_tag(c::tag_tree as usize);
1257     (*item).encode(rbml_w);
1258     rbml_w.end_tag();
1259 }
1260
1261 #[cfg(test)]
1262 fn decode_item_ast(item_doc: rbml::Doc) -> hir::Item {
1263     let chi_doc = item_doc.get(c::tag_tree as usize);
1264     let mut d = reader::Decoder::new(chi_doc);
1265     Decodable::decode(&mut d).unwrap()
1266 }
1267
1268 #[cfg(test)]
1269 trait FakeExtCtxt {
1270     fn call_site(&self) -> syntax_pos::Span;
1271     fn cfg(&self) -> ast::CrateConfig;
1272     fn ident_of(&self, st: &str) -> ast::Ident;
1273     fn name_of(&self, st: &str) -> ast::Name;
1274     fn parse_sess(&self) -> &parse::ParseSess;
1275 }
1276
1277 #[cfg(test)]
1278 impl FakeExtCtxt for parse::ParseSess {
1279     fn call_site(&self) -> syntax_pos::Span {
1280         syntax_pos::Span {
1281             lo: syntax_pos::BytePos(0),
1282             hi: syntax_pos::BytePos(0),
1283             expn_id: syntax_pos::NO_EXPANSION,
1284         }
1285     }
1286     fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1287     fn ident_of(&self, st: &str) -> ast::Ident {
1288         parse::token::str_to_ident(st)
1289     }
1290     fn name_of(&self, st: &str) -> ast::Name {
1291         parse::token::intern(st)
1292     }
1293     fn parse_sess(&self) -> &parse::ParseSess { self }
1294 }
1295
1296 #[cfg(test)]
1297 fn mk_ctxt() -> parse::ParseSess {
1298     parse::ParseSess::new()
1299 }
1300
1301 #[cfg(test)]
1302 fn with_testing_context<T, F: FnOnce(&mut LoweringContext) -> T>(f: F) -> T {
1303     let mut resolver = DummyResolver;
1304     let mut lcx = LoweringContext::testing_context(&mut resolver);
1305     f(&mut lcx)
1306 }
1307
1308 #[cfg(test)]
1309 fn roundtrip(in_item: hir::Item) {
1310     let mut wr = Cursor::new(Vec::new());
1311     encode_item_ast(&mut Encoder::new(&mut wr), &in_item);
1312     let rbml_doc = rbml::Doc::new(wr.get_ref());
1313     let out_item = decode_item_ast(rbml_doc);
1314
1315     assert!(in_item == out_item);
1316 }
1317
1318 #[test]
1319 fn test_basic() {
1320     let cx = mk_ctxt();
1321     with_testing_context(|lcx| {
1322         roundtrip(lcx.lower_item(&quote_item!(&cx,
1323             fn foo() {}
1324         ).unwrap()));
1325     });
1326 }
1327
1328 #[test]
1329 fn test_smalltalk() {
1330     let cx = mk_ctxt();
1331     with_testing_context(|lcx| {
1332         roundtrip(lcx.lower_item(&quote_item!(&cx,
1333             fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1334         ).unwrap()));
1335     });
1336 }
1337
1338 #[test]
1339 fn test_more() {
1340     let cx = mk_ctxt();
1341     with_testing_context(|lcx| {
1342         roundtrip(lcx.lower_item(&quote_item!(&cx,
1343             fn foo(x: usize, y: usize) -> usize {
1344                 let z = x + y;
1345                 return z;
1346             }
1347         ).unwrap()));
1348     });
1349 }
1350
1351 #[test]
1352 fn test_simplification() {
1353     let cx = mk_ctxt();
1354     let item = quote_item!(&cx,
1355         fn new_int_alist<B>() -> alist<isize, B> {
1356             fn eq_int(a: isize, b: isize) -> bool { a == b }
1357             return alist {eq_fn: eq_int, data: Vec::new()};
1358         }
1359     ).unwrap();
1360     let cx = mk_ctxt();
1361     with_testing_context(|lcx| {
1362         let hir_item = lcx.lower_item(&item);
1363         let item_in = InlinedItemRef::Item(&hir_item);
1364         let item_out = simplify_ast(item_in);
1365         let item_exp = InlinedItem::Item(P(lcx.lower_item(&quote_item!(&cx,
1366             fn new_int_alist<B>() -> alist<isize, B> {
1367                 return alist {eq_fn: eq_int, data: Vec::new()};
1368             }
1369         ).unwrap())));
1370         match (item_out, item_exp) {
1371             (InlinedItem::Item(item_out), InlinedItem::Item(item_exp)) => {
1372                  assert!(pprust::item_to_string(&item_out) ==
1373                          pprust::item_to_string(&item_exp));
1374             }
1375             _ => bug!()
1376         }
1377     });
1378 }