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.
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.
11 #![allow(non_camel_case_types)]
12 // FIXME: remove this after snapshot, and Results are handled
13 #![allow(unused_must_use)]
15 use front::map as ast_map;
17 use rustc_front::fold;
18 use rustc_front::fold::Folder;
20 use metadata::common as c;
21 use metadata::cstore as cstore;
23 use metadata::decoder;
24 use metadata::encoder as e;
25 use metadata::inline::{InlinedItem, InlinedItemRef};
26 use metadata::tydecode;
27 use metadata::tyencode;
28 use middle::ty::adjustment;
30 use middle::check_const::ConstQualif;
32 use middle::def_id::DefId;
33 use middle::privacy::{AllPublic, LastMod};
36 use middle::subst::VecPerParamSpace;
37 use middle::ty::{self, Ty};
39 use syntax::{ast, ast_util, codemap};
40 use syntax::codemap::Span;
44 use std::io::SeekFrom;
45 use std::io::prelude::*;
49 use rbml::writer::Encoder;
52 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
53 use serialize::EncoderHelpers;
55 #[cfg(test)] use std::io::Cursor;
56 #[cfg(test)] use syntax::parse;
57 #[cfg(test)] use rustc_front::print::pprust;
58 #[cfg(test)] use rustc_front::lowering::lower_item;
60 struct DecodeContext<'a, 'b, 'tcx: 'a> {
61 tcx: &'a ty::ctxt<'tcx>,
62 cdata: &'b cstore::crate_metadata,
63 from_id_range: ast_util::IdRange,
64 to_id_range: ast_util::IdRange,
65 // Cache the last used filemap for translating spans as an optimization.
66 last_filemap_index: Cell<usize>,
70 fn tr(&self, dcx: &DecodeContext) -> Self;
73 // ______________________________________________________________________
76 pub fn encode_inlined_item(ecx: &e::EncodeContext,
80 InlinedItemRef::Item(i) => i.id,
81 InlinedItemRef::Foreign(i) => i.id,
82 InlinedItemRef::TraitItem(_, ti) => ti.id,
83 InlinedItemRef::ImplItem(_, ii) => ii.id,
85 debug!("> Encoding inlined item: {} ({:?})",
86 ecx.tcx.map.path_to_string(id),
87 rbml_w.writer.seek(SeekFrom::Current(0)));
89 // Folding could be avoided with a smarter encoder.
90 let ii = simplify_ast(ii);
91 let id_range = ii.compute_id_range();
93 rbml_w.start_tag(c::tag_ast as usize);
94 id_range.encode(rbml_w);
95 encode_ast(rbml_w, &ii);
96 encode_side_tables_for_ii(ecx, rbml_w, &ii);
99 debug!("< Encoded inlined fn: {} ({:?})",
100 ecx.tcx.map.path_to_string(id),
101 rbml_w.writer.seek(SeekFrom::Current(0)));
104 impl<'a, 'b, 'c, 'tcx> ast_map::FoldOps for &'a DecodeContext<'b, 'c, 'tcx> {
105 fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
106 if id == ast::DUMMY_NODE_ID {
107 // Used by ast_map to map the NodeInlinedParent.
108 self.tcx.sess.next_node_id()
113 fn new_def_id(&self, def_id: DefId) -> DefId {
114 self.tr_def_id(def_id)
116 fn new_span(&self, span: Span) -> Span {
121 /// Decodes an item from its AST in the cdata's metadata and adds it to the
123 pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
124 tcx: &ty::ctxt<'tcx>,
125 path: Vec<ast_map::PathElem>,
126 def_path: ast_map::DefPath,
128 -> Result<&'tcx InlinedItem, (Vec<ast_map::PathElem>,
130 match par_doc.opt_child(c::tag_ast) {
131 None => Err((path, def_path)),
133 let mut path_as_str = None;
134 debug!("> Decoding inlined fn: {:?}::?",
136 // Do an Option dance to use the path after it is moved below.
137 let s = ast_map::path_to_string(path.iter().cloned());
138 path_as_str = Some(s);
139 path_as_str.as_ref().map(|x| &x[..])
141 let mut ast_dsr = reader::Decoder::new(ast_doc);
142 let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
143 let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
144 let dcx = &DecodeContext {
147 from_id_range: from_id_range,
148 to_id_range: to_id_range,
149 last_filemap_index: Cell::new(0)
151 let raw_ii = decode_ast(ast_doc);
152 let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, def_path, raw_ii, dcx);
154 let name = match *ii {
155 InlinedItem::Item(ref i) => i.name,
156 InlinedItem::Foreign(ref i) => i.name,
157 InlinedItem::TraitItem(_, ref ti) => ti.name,
158 InlinedItem::ImplItem(_, ref ii) => ii.name
160 debug!("Fn named: {}", name);
161 debug!("< Decoded inlined fn: {}::{}",
162 path_as_str.unwrap(),
164 region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
165 decode_side_tables(dcx, ast_doc);
167 InlinedItem::Item(ref i) => {
168 debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
169 ::rustc_front::print::pprust::item_to_string(&**i));
178 // ______________________________________________________________________
179 // Enumerating the IDs which appear in an AST
181 fn reserve_id_range(sess: &Session,
182 from_id_range: ast_util::IdRange) -> ast_util::IdRange {
183 // Handle the case of an empty range:
184 if from_id_range.empty() { return from_id_range; }
185 let cnt = from_id_range.max - from_id_range.min;
186 let to_id_min = sess.reserve_node_ids(cnt);
187 let to_id_max = to_id_min + cnt;
188 ast_util::IdRange { min: to_id_min, max: to_id_max }
191 impl<'a, 'b, 'tcx> DecodeContext<'a, 'b, 'tcx> {
192 /// Translates an internal id, meaning a node id that is known to refer to some part of the
193 /// item currently being inlined, such as a local variable or argument. All naked node-ids
194 /// that appear in types have this property, since if something might refer to an external item
195 /// we would use a def-id to allow for the possibility that the item resides in another crate.
196 pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
197 // from_id_range should be non-empty
198 assert!(!self.from_id_range.empty());
199 // Use wrapping arithmetic because otherwise it introduces control flow.
200 // Maybe we should just have the control flow? -- aatch
201 (id.wrapping_sub(self.from_id_range.min).wrapping_add(self.to_id_range.min))
204 /// Translates an EXTERNAL def-id, converting the crate number from the one used in the encoded
205 /// data to the current crate numbers.. By external, I mean that it be translated to a
206 /// reference to the item in its original crate, as opposed to being translated to a reference
207 /// to the inlined version of the item. This is typically, but not always, what you want,
208 /// because most def-ids refer to external things like types or other fns that may or may not
209 /// be inlined. Note that even when the inlined function is referencing itself recursively, we
210 /// would want `tr_def_id` for that reference--- conceptually the function calls the original,
211 /// non-inlined version, and trans deals with linking that recursive call to the inlined copy.
212 pub fn tr_def_id(&self, did: DefId) -> DefId {
213 decoder::translate_def_id(self.cdata, did)
216 /// Translates a `Span` from an extern crate to the corresponding `Span`
217 /// within the local crate's codemap. `creader::import_codemap()` will
218 /// already have allocated any additionally needed FileMaps in the local
219 /// codemap as a side-effect of creating the crate_metadata's
220 /// `codemap_import_info`.
221 pub fn tr_span(&self, span: Span) -> Span {
222 let span = if span.lo > span.hi {
223 // Currently macro expansion sometimes produces invalid Span values
224 // where lo > hi. In order not to crash the compiler when trying to
225 // translate these values, let's transform them into something we
226 // can handle (and which will produce useful debug locations at
227 // least some of the time).
228 // This workaround is only necessary as long as macro expansion is
229 // not fixed. FIXME(#23480)
230 codemap::mk_sp(span.lo, span.lo)
235 let imported_filemaps = self.cdata.imported_filemaps(self.tcx.sess.codemap());
237 // Optimize for the case that most spans within a translated item
238 // originate from the same filemap.
239 let last_filemap_index = self.last_filemap_index.get();
240 let last_filemap = &imported_filemaps[last_filemap_index];
242 if span.lo >= last_filemap.original_start_pos &&
243 span.lo <= last_filemap.original_end_pos &&
244 span.hi >= last_filemap.original_start_pos &&
245 span.hi <= last_filemap.original_end_pos {
249 let mut b = imported_filemaps.len();
253 if imported_filemaps[m].original_start_pos > span.lo {
260 self.last_filemap_index.set(a);
261 &imported_filemaps[a]
265 let lo = (span.lo - filemap.original_start_pos) +
266 filemap.translated_filemap.start_pos;
267 let hi = (span.hi - filemap.original_start_pos) +
268 filemap.translated_filemap.start_pos;
270 codemap::mk_sp(lo, hi)
275 fn tr(&self, dcx: &DecodeContext) -> DefId {
280 impl tr for Option<DefId> {
281 fn tr(&self, dcx: &DecodeContext) -> Option<DefId> {
282 self.map(|d| dcx.tr_def_id(d))
287 fn tr(&self, dcx: &DecodeContext) -> Span {
292 trait def_id_encoder_helpers {
293 fn emit_def_id(&mut self, did: DefId);
296 impl<S:serialize::Encoder> def_id_encoder_helpers for S
297 where <S as serialize::serialize::Encoder>::Error: Debug
299 fn emit_def_id(&mut self, did: DefId) {
300 did.encode(self).unwrap()
304 trait def_id_decoder_helpers {
305 fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId;
306 fn read_def_id_nodcx(&mut self,
307 cdata: &cstore::crate_metadata) -> DefId;
310 impl<D:serialize::Decoder> def_id_decoder_helpers for D
311 where <D as serialize::serialize::Decoder>::Error: Debug
313 fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId {
314 let did: DefId = Decodable::decode(self).unwrap();
318 fn read_def_id_nodcx(&mut self,
319 cdata: &cstore::crate_metadata)
321 let did: DefId = Decodable::decode(self).unwrap();
322 decoder::translate_def_id(cdata, did)
326 // ______________________________________________________________________
327 // Encoding and decoding the AST itself
329 // When decoding, we have to renumber the AST so that the node ids that
330 // appear within are disjoint from the node ids in our existing ASTs.
331 // We also have to adjust the spans: for now we just insert a dummy span,
332 // but eventually we should add entries to the local codemap as required.
334 fn encode_ast(rbml_w: &mut Encoder, item: &InlinedItem) {
335 rbml_w.start_tag(c::tag_tree as usize);
340 struct NestedItemsDropper;
342 impl Folder for NestedItemsDropper {
343 fn fold_block(&mut self, blk: P<hir::Block>) -> P<hir::Block> {
344 blk.and_then(|hir::Block {id, stmts, expr, rules, span, ..}| {
345 let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
346 let use_stmt = match stmt.node {
347 hir::StmtExpr(_, _) | hir::StmtSemi(_, _) => true,
348 hir::StmtDecl(ref decl, _) => {
350 hir::DeclLocal(_) => true,
351 hir::DeclItem(_) => false,
361 let blk_sans_items = P(hir::Block {
362 stmts: stmts_sans_items,
368 fold::noop_fold_block(blk_sans_items, self)
373 // Produces a simplified copy of the AST which does not include things
374 // that we do not need to or do not want to export. For example, we
375 // do not include any nested items: if these nested items are to be
376 // inlined, their AST will be exported separately (this only makes
377 // sense because, in Rust, nested items are independent except for
378 // their visibility).
380 // As it happens, trans relies on the fact that we do not export
381 // nested items, as otherwise it would get confused when translating
383 fn simplify_ast(ii: InlinedItemRef) -> InlinedItem {
384 let mut fld = NestedItemsDropper;
387 // HACK we're not dropping items.
388 InlinedItemRef::Item(i) => {
389 InlinedItem::Item(fold::noop_fold_item(P(i.clone()), &mut fld)
390 .expect_one("expected one item"))
392 InlinedItemRef::TraitItem(d, ti) => {
393 InlinedItem::TraitItem(d,
394 fold::noop_fold_trait_item(P(ti.clone()), &mut fld)
395 .expect_one("noop_fold_trait_item must produce \
396 exactly one trait item"))
398 InlinedItemRef::ImplItem(d, ii) => {
399 InlinedItem::ImplItem(d,
400 fold::noop_fold_impl_item(P(ii.clone()), &mut fld)
401 .expect_one("noop_fold_impl_item must produce \
402 exactly one impl item"))
404 InlinedItemRef::Foreign(i) => {
405 InlinedItem::Foreign(fold::noop_fold_foreign_item(P(i.clone()), &mut fld))
410 fn decode_ast(par_doc: rbml::Doc) -> InlinedItem {
411 let chi_doc = par_doc.get(c::tag_tree as usize);
412 let mut d = reader::Decoder::new(chi_doc);
413 Decodable::decode(&mut d).unwrap()
416 // ______________________________________________________________________
417 // Encoding and decoding of ast::def
419 fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> def::Def {
420 let def: def::Def = Decodable::decode(dsr).unwrap();
424 impl tr for def::Def {
425 fn tr(&self, dcx: &DecodeContext) -> def::Def {
427 def::DefFn(did, is_ctor) => def::DefFn(did.tr(dcx), is_ctor),
428 def::DefMethod(did) => def::DefMethod(did.tr(dcx)),
429 def::DefSelfTy(opt_did, impl_ids) => { def::DefSelfTy(opt_did.map(|did| did.tr(dcx)),
430 impl_ids.map(|(nid1, nid2)| {
434 def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
435 def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
436 def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
437 def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
438 def::DefAssociatedConst(did) => def::DefAssociatedConst(did.tr(dcx)),
439 def::DefLocal(_, nid) => {
440 let nid = dcx.tr_id(nid);
441 let did = dcx.tcx.map.local_def_id(nid);
442 def::DefLocal(did, nid)
444 def::DefVariant(e_did, v_did, is_s) => {
445 def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
447 def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
448 def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
449 def::DefAssociatedTy(trait_did, did) =>
450 def::DefAssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
451 def::DefPrimTy(p) => def::DefPrimTy(p),
452 def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
453 def::DefUse(did) => def::DefUse(did.tr(dcx)),
454 def::DefUpvar(_, nid1, index, nid2) => {
455 let nid1 = dcx.tr_id(nid1);
456 let nid2 = dcx.tr_id(nid2);
457 let did1 = dcx.tcx.map.local_def_id(nid1);
458 def::DefUpvar(did1, nid1, index, nid2)
460 def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
461 def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
466 // ______________________________________________________________________
467 // Encoding and decoding of freevar information
469 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
470 (*fv).encode(rbml_w).unwrap();
473 trait rbml_decoder_helper {
474 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
476 fn read_capture_mode(&mut self) -> hir::CaptureClause;
479 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
480 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
482 let fv: ty::Freevar = Decodable::decode(self).unwrap();
486 fn read_capture_mode(&mut self) -> hir::CaptureClause {
487 let cm: hir::CaptureClause = Decodable::decode(self).unwrap();
492 impl tr for ty::Freevar {
493 fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
495 def: self.def.tr(dcx),
496 span: self.span.tr(dcx),
501 // ______________________________________________________________________
502 // Encoding and decoding of MethodCallee
504 trait read_method_callee_helper<'tcx> {
505 fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
506 -> (u32, ty::MethodCallee<'tcx>);
509 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
510 rbml_w: &mut Encoder,
512 method: &ty::MethodCallee<'tcx>) {
513 use serialize::Encoder;
515 rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
516 rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
517 autoderef.encode(rbml_w)
519 rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
520 Ok(rbml_w.emit_def_id(method.def_id))
522 rbml_w.emit_struct_field("ty", 2, |rbml_w| {
523 Ok(rbml_w.emit_ty(ecx, method.ty))
525 rbml_w.emit_struct_field("substs", 3, |rbml_w| {
526 Ok(rbml_w.emit_substs(ecx, &method.substs))
531 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
532 fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
533 -> (u32, ty::MethodCallee<'tcx>) {
535 self.read_struct("MethodCallee", 4, |this| {
536 let autoderef = this.read_struct_field("autoderef", 0,
537 Decodable::decode).unwrap();
538 Ok((autoderef, ty::MethodCallee {
539 def_id: this.read_struct_field("def_id", 1, |this| {
540 Ok(this.read_def_id(dcx))
542 ty: this.read_struct_field("ty", 2, |this| {
543 Ok(this.read_ty(dcx))
545 substs: this.read_struct_field("substs", 3, |this| {
546 Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
553 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
554 kind.encode(ebml_w).unwrap();
557 pub trait vtable_decoder_helpers<'tcx> {
558 fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
559 F: FnMut(&mut Self) -> T;
562 impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> {
563 fn read_vec_per_param_space<T, F>(&mut self, mut f: F) -> VecPerParamSpace<T> where
564 F: FnMut(&mut reader::Decoder<'a>) -> T,
566 let types = self.read_to_vec(|this| Ok(f(this))).unwrap();
567 let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap();
568 let fns = self.read_to_vec(|this| Ok(f(this))).unwrap();
569 VecPerParamSpace::new(types, selfs, fns)
573 // ___________________________________________________________________________
576 fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder,
577 v: &subst::VecPerParamSpace<T>,
579 F: FnMut(&mut Encoder, &T),
581 for &space in &subst::ParamSpace::all() {
582 rbml_w.emit_from_vec(v.get_slice(space),
583 |rbml_w, n| Ok(f(rbml_w, n))).unwrap();
587 // ______________________________________________________________________
588 // Encoding and decoding the side tables
590 trait get_ty_str_ctxt<'tcx> {
591 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
594 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
595 fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
597 diag: self.tcx.sess.diagnostic(),
598 ds: e::def_to_string,
600 abbrevs: &self.type_abbrevs
605 trait rbml_writer_helpers<'tcx> {
606 fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region);
607 fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
608 fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
609 fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
610 type_param_def: &ty::TypeParameterDef<'tcx>);
611 fn emit_region_param_def(&mut self, ecx: &e::EncodeContext,
612 region_param_def: &ty::RegionParameterDef);
613 fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
614 predicate: &ty::Predicate<'tcx>);
615 fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
616 ty: &ty::TraitRef<'tcx>);
617 fn emit_type_scheme<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
618 type_scheme: ty::TypeScheme<'tcx>);
619 fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
620 substs: &subst::Substs<'tcx>);
621 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
622 bounds: &ty::ExistentialBounds<'tcx>);
623 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
624 fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture);
625 fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
626 adj: &adjustment::AutoAdjustment<'tcx>);
627 fn emit_autoref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
628 autoref: &adjustment::AutoRef<'tcx>);
629 fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
630 auto_deref_ref: &adjustment::AutoDerefRef<'tcx>);
633 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
634 fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region) {
635 self.emit_opaque(|this| Ok(e::write_region(ecx, this, r)));
638 fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
639 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
642 fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
643 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
646 fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
647 trait_ref: &ty::TraitRef<'tcx>) {
648 self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
651 fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
652 type_param_def: &ty::TypeParameterDef<'tcx>) {
653 self.emit_opaque(|this| {
654 Ok(tyencode::enc_type_param_def(this,
659 fn emit_region_param_def(&mut self, ecx: &e::EncodeContext,
660 region_param_def: &ty::RegionParameterDef) {
661 self.emit_opaque(|this| {
662 Ok(tyencode::enc_region_param_def(this,
667 fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
668 predicate: &ty::Predicate<'tcx>) {
669 self.emit_opaque(|this| {
670 Ok(tyencode::enc_predicate(this,
676 fn emit_type_scheme<'b>(&mut self,
677 ecx: &e::EncodeContext<'b, 'tcx>,
678 type_scheme: ty::TypeScheme<'tcx>) {
679 use serialize::Encoder;
681 self.emit_struct("TypeScheme", 2, |this| {
682 this.emit_struct_field("generics", 0, |this| {
683 this.emit_struct("Generics", 2, |this| {
684 this.emit_struct_field("types", 0, |this| {
685 Ok(encode_vec_per_param_space(
686 this, &type_scheme.generics.types,
687 |this, def| this.emit_type_param_def(ecx, def)))
689 this.emit_struct_field("regions", 1, |this| {
690 Ok(encode_vec_per_param_space(
691 this, &type_scheme.generics.regions,
692 |this, def| this.emit_region_param_def(ecx, def)))
696 this.emit_struct_field("ty", 1, |this| {
697 Ok(this.emit_ty(ecx, type_scheme.ty))
702 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
703 bounds: &ty::ExistentialBounds<'tcx>) {
704 self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
709 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
710 self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
715 fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture) {
716 use serialize::Encoder;
718 self.emit_enum("UpvarCapture", |this| {
720 ty::UpvarCapture::ByValue => {
721 this.emit_enum_variant("ByValue", 1, 0, |_| Ok(()))
723 ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind, region }) => {
724 this.emit_enum_variant("ByRef", 2, 0, |this| {
725 this.emit_enum_variant_arg(0,
726 |this| kind.encode(this));
727 this.emit_enum_variant_arg(1,
728 |this| Ok(this.emit_region(ecx, region)))
735 fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
736 substs: &subst::Substs<'tcx>) {
737 self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
742 fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
743 adj: &adjustment::AutoAdjustment<'tcx>) {
744 use serialize::Encoder;
746 self.emit_enum("AutoAdjustment", |this| {
748 adjustment::AdjustReifyFnPointer=> {
749 this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
752 adjustment::AdjustUnsafeFnPointer => {
753 this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
758 adjustment::AdjustDerefRef(ref auto_deref_ref) => {
759 this.emit_enum_variant("AdjustDerefRef", 3, 2, |this| {
760 this.emit_enum_variant_arg(0,
761 |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
768 fn emit_autoref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
769 autoref: &adjustment::AutoRef<'tcx>) {
770 use serialize::Encoder;
772 self.emit_enum("AutoRef", |this| {
774 &adjustment::AutoPtr(r, m) => {
775 this.emit_enum_variant("AutoPtr", 0, 2, |this| {
776 this.emit_enum_variant_arg(0,
777 |this| Ok(this.emit_region(ecx, *r)));
778 this.emit_enum_variant_arg(1, |this| m.encode(this))
781 &adjustment::AutoUnsafe(m) => {
782 this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
783 this.emit_enum_variant_arg(0, |this| m.encode(this))
790 fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
791 auto_deref_ref: &adjustment::AutoDerefRef<'tcx>) {
792 use serialize::Encoder;
794 self.emit_struct("AutoDerefRef", 2, |this| {
795 this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
797 this.emit_struct_field("autoref", 1, |this| {
798 this.emit_option(|this| {
799 match auto_deref_ref.autoref {
800 None => this.emit_option_none(),
801 Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a))),
806 this.emit_struct_field("unsize", 2, |this| {
807 this.emit_option(|this| {
808 match auto_deref_ref.unsize {
809 None => this.emit_option_none(),
810 Some(target) => this.emit_option_some(|this| {
811 Ok(this.emit_ty(ecx, target))
820 trait write_tag_and_id {
821 fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
822 fn id(&mut self, id: ast::NodeId);
825 impl<'a> write_tag_and_id for Encoder<'a> {
827 tag_id: c::astencode_tag,
829 F: FnOnce(&mut Encoder<'a>),
831 self.start_tag(tag_id as usize);
836 fn id(&mut self, id: ast::NodeId) {
837 id.encode(self).unwrap();
841 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
842 ecx: &'a e::EncodeContext<'c, 'tcx>,
843 rbml_w: &'a mut Encoder<'b>,
846 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
847 SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
848 fn visit_id(&mut self, id: ast::NodeId) {
849 encode_side_tables_for_id(self.ecx, self.rbml_w, id)
853 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
854 rbml_w: &mut Encoder,
856 rbml_w.start_tag(c::tag_table as usize);
857 ii.visit_ids(&mut SideTableEncodingIdVisitor {
864 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
865 rbml_w: &mut Encoder,
869 debug!("Encoding side tables for id {}", id);
871 if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
872 rbml_w.tag(c::tag_table_def, |rbml_w| {
874 def.encode(rbml_w).unwrap();
878 if let Some(ty) = tcx.node_types().get(&id) {
879 rbml_w.tag(c::tag_table_node_type, |rbml_w| {
881 rbml_w.emit_ty(ecx, *ty);
885 if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
886 rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
888 rbml_w.emit_substs(ecx, &item_substs.substs);
892 if let Some(fv) = tcx.freevars.borrow().get(&id) {
893 rbml_w.tag(c::tag_table_freevars, |rbml_w| {
895 rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
896 Ok(encode_freevar_entry(rbml_w, fv_entry))
901 rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
904 let var_id = freevar.def.var_id();
905 let upvar_id = ty::UpvarId {
909 let upvar_capture = tcx.tables
915 var_id.encode(rbml_w);
916 rbml_w.emit_upvar_capture(ecx, &upvar_capture);
921 let opt_def_id = tcx.map.opt_local_def_id(id);
922 if let Some(lid) = opt_def_id {
923 if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
924 rbml_w.tag(c::tag_table_tcache, |rbml_w| {
926 rbml_w.emit_type_scheme(ecx, type_scheme.clone());
931 if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
932 rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
934 rbml_w.emit_type_param_def(ecx, type_param_def)
938 let method_call = ty::MethodCall::expr(id);
939 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
940 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
942 encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
946 if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
948 adjustment::AdjustDerefRef(ref adj) => {
949 for autoderef in 0..adj.autoderefs {
950 let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
951 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
952 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
954 encode_method_callee(ecx, rbml_w,
955 method_call.autoderef, method)
963 rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
965 rbml_w.emit_auto_adjustment(ecx, adjustment);
969 if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
970 rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
972 encode_cast_kind(rbml_w, *cast_kind)
976 if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
977 rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
979 qualif.encode(rbml_w).unwrap()
984 trait doc_decoder_helpers: Sized {
985 fn as_int(&self) -> isize;
986 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
989 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
990 fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
991 fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
992 reader::maybe_get_doc(*self, tag as usize)
996 trait rbml_decoder_decoder_helpers<'tcx> {
997 fn read_ty_encoded<'a, 'b, F, R>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>,
999 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x, 'tcx>) -> R;
1001 fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region;
1002 fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
1003 fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
1004 fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1005 -> ty::TraitRef<'tcx>;
1006 fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1007 -> ty::PolyTraitRef<'tcx>;
1008 fn read_type_param_def<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1009 -> ty::TypeParameterDef<'tcx>;
1010 fn read_region_param_def(&mut self, dcx: &DecodeContext)
1011 -> ty::RegionParameterDef;
1012 fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1013 -> ty::Predicate<'tcx>;
1014 fn read_type_scheme<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1015 -> ty::TypeScheme<'tcx>;
1016 fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1017 -> ty::ExistentialBounds<'tcx>;
1018 fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1019 -> subst::Substs<'tcx>;
1020 fn read_upvar_capture(&mut self, dcx: &DecodeContext)
1021 -> ty::UpvarCapture;
1022 fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1023 -> adjustment::AutoAdjustment<'tcx>;
1024 fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1026 fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1027 -> adjustment::AutoDerefRef<'tcx>;
1028 fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1029 -> adjustment::AutoRef<'tcx>;
1030 fn convert_def_id(&mut self,
1031 dcx: &DecodeContext,
1035 // Versions of the type reading functions that don't need the full
1037 fn read_ty_nodcx(&mut self,
1038 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
1039 fn read_tys_nodcx(&mut self,
1040 tcx: &ty::ctxt<'tcx>,
1041 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
1042 fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
1043 cdata: &cstore::crate_metadata)
1044 -> subst::Substs<'tcx>;
1047 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
1048 fn read_ty_nodcx(&mut self,
1049 tcx: &ty::ctxt<'tcx>,
1050 cdata: &cstore::crate_metadata)
1052 self.read_opaque(|_, doc| {
1054 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
1055 &mut |id| decoder::translate_def_id(cdata, id))
1060 fn read_tys_nodcx(&mut self,
1061 tcx: &ty::ctxt<'tcx>,
1062 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
1063 self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
1069 fn read_substs_nodcx(&mut self,
1070 tcx: &ty::ctxt<'tcx>,
1071 cdata: &cstore::crate_metadata)
1072 -> subst::Substs<'tcx>
1074 self.read_opaque(|_, doc| {
1076 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
1077 &mut |id| decoder::translate_def_id(cdata, id))
1082 fn read_ty_encoded<'b, 'c, F, R>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>, op: F) -> R
1083 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x,'tcx>) -> R
1085 return self.read_opaque(|this, doc| {
1086 debug!("read_ty_encoded({})", type_string(doc));
1088 &mut tydecode::TyDecoder::with_doc(
1089 dcx.tcx, dcx.cdata.cnum, doc,
1090 &mut |a| this.convert_def_id(dcx, a))))
1093 fn type_string(doc: rbml::Doc) -> String {
1094 let mut str = String::new();
1095 for i in doc.start..doc.end {
1096 str.push(doc.data[i] as char);
1101 fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region {
1102 // Note: regions types embed local node ids. In principle, we
1103 // should translate these node ids into the new decode
1104 // context. However, we do not bother, because region types
1105 // are not used during trans. This also applies to read_ty.
1106 return self.read_ty_encoded(dcx, |decoder| decoder.parse_region());
1108 fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1109 return self.read_ty_encoded(dcx, |decoder| decoder.parse_ty());
1112 fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1114 self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1117 fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1118 -> ty::TraitRef<'tcx> {
1119 self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref())
1122 fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1123 -> ty::PolyTraitRef<'tcx> {
1124 ty::Binder(self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref()))
1127 fn read_type_param_def<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1128 -> ty::TypeParameterDef<'tcx> {
1129 self.read_ty_encoded(dcx, |decoder| decoder.parse_type_param_def())
1131 fn read_region_param_def(&mut self, dcx: &DecodeContext)
1132 -> ty::RegionParameterDef {
1133 self.read_ty_encoded(dcx, |decoder| decoder.parse_region_param_def())
1135 fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1136 -> ty::Predicate<'tcx>
1138 self.read_ty_encoded(dcx, |decoder| decoder.parse_predicate())
1141 fn read_type_scheme<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1142 -> ty::TypeScheme<'tcx> {
1143 self.read_struct("TypeScheme", 3, |this| {
1145 generics: this.read_struct_field("generics", 0, |this| {
1146 this.read_struct("Generics", 2, |this| {
1149 this.read_struct_field("types", 0, |this| {
1150 Ok(this.read_vec_per_param_space(
1151 |this| this.read_type_param_def(dcx)))
1155 this.read_struct_field("regions", 1, |this| {
1156 Ok(this.read_vec_per_param_space(
1157 |this| this.read_region_param_def(dcx)))
1162 ty: this.read_struct_field("ty", 1, |this| {
1163 Ok(this.read_ty(dcx))
1169 fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1170 -> ty::ExistentialBounds<'tcx>
1172 self.read_ty_encoded(dcx, |decoder| decoder.parse_existential_bounds())
1175 fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1176 -> subst::Substs<'tcx> {
1177 self.read_opaque(|this, doc| {
1178 Ok(tydecode::TyDecoder::with_doc(dcx.tcx, dcx.cdata.cnum, doc,
1179 &mut |a| this.convert_def_id(dcx, a))
1183 fn read_upvar_capture(&mut self, dcx: &DecodeContext) -> ty::UpvarCapture {
1184 self.read_enum("UpvarCapture", |this| {
1185 let variants = ["ByValue", "ByRef"];
1186 this.read_enum_variant(&variants, |this, i| {
1188 1 => ty::UpvarCapture::ByValue,
1189 2 => ty::UpvarCapture::ByRef(ty::UpvarBorrow {
1190 kind: this.read_enum_variant_arg(0,
1191 |this| Decodable::decode(this)).unwrap(),
1192 region: this.read_enum_variant_arg(1,
1193 |this| Ok(this.read_region(dcx))).unwrap()
1195 _ => panic!("bad enum variant for ty::UpvarCapture")
1200 fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1201 -> adjustment::AutoAdjustment<'tcx> {
1202 self.read_enum("AutoAdjustment", |this| {
1203 let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer", "AdjustDerefRef"];
1204 this.read_enum_variant(&variants, |this, i| {
1206 1 => adjustment::AdjustReifyFnPointer,
1207 2 => adjustment::AdjustUnsafeFnPointer,
1209 let auto_deref_ref: adjustment::AutoDerefRef =
1210 this.read_enum_variant_arg(0,
1211 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1213 adjustment::AdjustDerefRef(auto_deref_ref)
1215 _ => panic!("bad enum variant for adjustment::AutoAdjustment")
1221 fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1222 -> adjustment::AutoDerefRef<'tcx> {
1223 self.read_struct("AutoDerefRef", 2, |this| {
1224 Ok(adjustment::AutoDerefRef {
1225 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1226 Decodable::decode(this)
1228 autoref: this.read_struct_field("autoref", 1, |this| {
1229 this.read_option(|this, b| {
1231 Ok(Some(this.read_autoref(dcx)))
1237 unsize: this.read_struct_field("unsize", 2, |this| {
1238 this.read_option(|this, b| {
1240 Ok(Some(this.read_ty(dcx)))
1250 fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1251 -> adjustment::AutoRef<'tcx> {
1252 self.read_enum("AutoRef", |this| {
1253 let variants = ["AutoPtr", "AutoUnsafe"];
1254 this.read_enum_variant(&variants, |this, i| {
1258 this.read_enum_variant_arg(0, |this| {
1259 Ok(this.read_region(dcx))
1261 let m: hir::Mutability =
1262 this.read_enum_variant_arg(1, |this| {
1263 Decodable::decode(this)
1266 adjustment::AutoPtr(dcx.tcx.mk_region(r), m)
1269 let m: hir::Mutability =
1270 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1272 adjustment::AutoUnsafe(m)
1274 _ => panic!("bad enum variant for adjustment::AutoRef")
1280 fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1283 Decodable::decode(self).unwrap()
1286 /// Converts a def-id that appears in a type. The correct
1287 /// translation will depend on what kind of def-id this is.
1288 /// This is a subtle point: type definitions are not
1289 /// inlined into the current crate, so if the def-id names
1290 /// a nominal type or type alias, then it should be
1291 /// translated to refer to the source crate.
1293 /// However, *type parameters* are cloned along with the function
1294 /// they are attached to. So we should translate those def-ids
1295 /// to refer to the new, cloned copy of the type parameter.
1296 /// We only see references to free type parameters in the body of
1297 /// an inlined function. In such cases, we need the def-id to
1298 /// be a local id so that the TypeContents code is able to lookup
1299 /// the relevant info in the ty_param_defs table.
1301 /// *Region parameters*, unfortunately, are another kettle of fish.
1302 /// In such cases, def_id's can appear in types to distinguish
1303 /// shadowed bound regions and so forth. It doesn't actually
1304 /// matter so much what we do to these, since regions are erased
1305 /// at trans time, but it's good to keep them consistent just in
1306 /// case. We translate them with `tr_def_id()` which will map
1307 /// the crate numbers back to the original source crate.
1309 /// Scopes will end up as being totally bogus. This can actually
1310 /// be fixed though.
1312 /// Unboxed closures are cloned along with the function being
1313 /// inlined, and all side tables use interned node IDs, so we
1314 /// translate their def IDs accordingly.
1316 /// It'd be really nice to refactor the type repr to not include
1317 /// def-ids so that all these distinctions were unnecessary.
1318 fn convert_def_id(&mut self,
1319 dcx: &DecodeContext,
1322 let r = dcx.tr_def_id(did);
1323 debug!("convert_def_id(did={:?})={:?}", did, r);
1328 fn decode_side_tables(dcx: &DecodeContext,
1329 ast_doc: rbml::Doc) {
1330 let tbl_doc = ast_doc.get(c::tag_table as usize);
1331 for (tag, entry_doc) in reader::docs(tbl_doc) {
1332 let mut entry_dsr = reader::Decoder::new(entry_doc);
1333 let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1334 let id = dcx.tr_id(id0);
1336 debug!(">> Side table document with tag 0x{:x} \
1337 found for id {} (orig {})",
1339 let tag = tag as u32;
1340 let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1344 &format!("unknown tag found in side tables: {:x}",
1348 let val_dsr = &mut entry_dsr;
1351 c::tag_table_def => {
1352 let def = decode_def(dcx, val_dsr);
1353 dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
1355 // This doesn't matter cross-crate.
1356 last_private: LastMod(AllPublic),
1360 c::tag_table_node_type => {
1361 let ty = val_dsr.read_ty(dcx);
1362 debug!("inserting ty for node {}: {:?}",
1364 dcx.tcx.node_type_insert(id, ty);
1366 c::tag_table_item_subst => {
1367 let item_substs = ty::ItemSubsts {
1368 substs: val_dsr.read_substs(dcx)
1370 dcx.tcx.tables.borrow_mut().item_substs.insert(
1373 c::tag_table_freevars => {
1374 let fv_info = val_dsr.read_to_vec(|val_dsr| {
1375 Ok(val_dsr.read_freevar_entry(dcx))
1376 }).unwrap().into_iter().collect();
1377 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1379 c::tag_table_upvar_capture_map => {
1380 let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1381 let upvar_id = ty::UpvarId {
1382 var_id: dcx.tr_id(var_id),
1385 let ub = val_dsr.read_upvar_capture(dcx);
1386 dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub);
1388 c::tag_table_tcache => {
1389 let type_scheme = val_dsr.read_type_scheme(dcx);
1390 let lid = dcx.tcx.map.local_def_id(id);
1391 dcx.tcx.register_item_type(lid, type_scheme);
1393 c::tag_table_param_defs => {
1394 let bounds = val_dsr.read_type_param_def(dcx);
1395 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1397 c::tag_table_method_map => {
1398 let (autoderef, method) = val_dsr.read_method_callee(dcx);
1399 let method_call = ty::MethodCall {
1401 autoderef: autoderef
1403 dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1405 c::tag_table_adjustments => {
1407 val_dsr.read_auto_adjustment(dcx);
1408 dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1410 c::tag_table_cast_kinds => {
1412 val_dsr.read_cast_kind(dcx);
1413 dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1415 c::tag_table_const_qualif => {
1416 let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1417 dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1421 &format!("unknown tag found in side tables: {:x}",
1428 debug!(">< Side table doc loaded");
1432 // ______________________________________________________________________
1433 // Testing of astencode_gen
1436 fn encode_item_ast(rbml_w: &mut Encoder, item: &hir::Item) {
1437 rbml_w.start_tag(c::tag_tree as usize);
1438 (*item).encode(rbml_w);
1443 fn decode_item_ast(par_doc: rbml::Doc) -> hir::Item {
1444 let chi_doc = par_doc.get(c::tag_tree as usize);
1445 let mut d = reader::Decoder::new(chi_doc);
1446 Decodable::decode(&mut d).unwrap()
1451 fn call_site(&self) -> codemap::Span;
1452 fn cfg(&self) -> ast::CrateConfig;
1453 fn ident_of(&self, st: &str) -> ast::Ident;
1454 fn name_of(&self, st: &str) -> ast::Name;
1455 fn parse_sess(&self) -> &parse::ParseSess;
1459 impl FakeExtCtxt for parse::ParseSess {
1460 fn call_site(&self) -> codemap::Span {
1462 lo: codemap::BytePos(0),
1463 hi: codemap::BytePos(0),
1464 expn_id: codemap::NO_EXPANSION,
1467 fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1468 fn ident_of(&self, st: &str) -> ast::Ident {
1469 parse::token::str_to_ident(st)
1471 fn name_of(&self, st: &str) -> ast::Name {
1472 parse::token::intern(st)
1474 fn parse_sess(&self) -> &parse::ParseSess { self }
1478 fn mk_ctxt() -> parse::ParseSess {
1479 parse::ParseSess::new()
1483 fn roundtrip(in_item: P<hir::Item>) {
1484 let mut wr = Cursor::new(Vec::new());
1485 encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
1486 let rbml_doc = rbml::Doc::new(wr.get_ref());
1487 let out_item = decode_item_ast(rbml_doc);
1489 assert!(*in_item == out_item);
1495 roundtrip(lower_item("e_item!(&cx,
1501 fn test_smalltalk() {
1503 roundtrip(lower_item("e_item!(&cx,
1504 fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1511 roundtrip(lower_item("e_item!(&cx,
1512 fn foo(x: usize, y: usize) -> usize {
1520 fn test_simplification() {
1522 let item = quote_item!(&cx,
1523 fn new_int_alist<B>() -> alist<isize, B> {
1524 fn eq_int(a: isize, b: isize) -> bool { a == b }
1525 return alist {eq_fn: eq_int, data: Vec::new()};
1528 let hir_item = lower_item(&item);
1529 let item_in = InlinedItemRef::Item(&hir_item);
1530 let item_out = simplify_ast(item_in);
1531 let item_exp = InlinedItem::Item(lower_item("e_item!(&cx,
1532 fn new_int_alist<B>() -> alist<isize, B> {
1533 return alist {eq_fn: eq_int, data: Vec::new()};
1536 match (item_out, item_exp) {
1537 (InlinedItem::Item(item_out), InlinedItem::Item(item_exp)) => {
1538 assert!(pprust::item_to_string(&*item_out) ==
1539 pprust::item_to_string(&*item_exp));