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