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