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)]
16 use metadata::common as c;
17 use metadata::cstore as cstore;
19 use metadata::decoder;
20 use metadata::encoder as e;
21 use metadata::inline::{InlinedItem, InlinedItemRef};
22 use metadata::tydecode;
23 use metadata::tydecode::{DefIdSource, NominalType, TypeWithId};
24 use metadata::tydecode::{RegionParameter, ClosureSource};
25 use metadata::tyencode;
27 use middle::check_const::ConstQualif;
29 use middle::def_id::{DefId, LOCAL_CRATE};
30 use middle::privacy::{AllPublic, LastMod};
33 use middle::subst::VecPerParamSpace;
34 use middle::ty::{self, Ty};
36 use syntax::{ast, ast_util, codemap, fold};
37 use syntax::codemap::Span;
38 use syntax::fold::Folder;
43 use std::io::SeekFrom;
44 use std::io::prelude::*;
48 use rbml::writer::Encoder;
51 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
52 use serialize::EncoderHelpers;
54 #[cfg(test)] use std::io::Cursor;
55 #[cfg(test)] use syntax::parse;
56 #[cfg(test)] use syntax::print::pprust;
58 struct DecodeContext<'a, 'b, 'tcx: 'a> {
59 tcx: &'a ty::ctxt<'tcx>,
60 cdata: &'b cstore::crate_metadata,
61 from_id_range: ast_util::IdRange,
62 to_id_range: ast_util::IdRange,
63 // Cache the last used filemap for translating spans as an optimization.
64 last_filemap_index: Cell<usize>,
68 fn tr(&self, dcx: &DecodeContext) -> Self;
72 fn tr_intern(&self, dcx: &DecodeContext) -> DefId;
75 // ______________________________________________________________________
78 pub fn encode_inlined_item(ecx: &e::EncodeContext,
82 InlinedItemRef::Item(i) => i.id,
83 InlinedItemRef::Foreign(i) => i.id,
84 InlinedItemRef::TraitItem(_, ti) => ti.id,
85 InlinedItemRef::ImplItem(_, ii) => ii.id,
87 debug!("> Encoding inlined item: {} ({:?})",
88 ecx.tcx.map.path_to_string(id),
89 rbml_w.writer.seek(SeekFrom::Current(0)));
91 // Folding could be avoided with a smarter encoder.
92 let ii = simplify_ast(ii);
93 let id_range = ii.compute_id_range();
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);
101 debug!("< Encoded inlined fn: {} ({:?})",
102 ecx.tcx.map.path_to_string(id),
103 rbml_w.writer.seek(SeekFrom::Current(0)));
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()
115 fn new_def_id(&self, def_id: DefId) -> DefId {
116 self.tr_def_id(def_id)
118 fn new_span(&self, span: Span) -> Span {
123 /// Decodes an item from its AST in the cdata's metadata and adds it to the
125 pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
126 tcx: &ty::ctxt<'tcx>,
127 path: Vec<ast_map::PathElem>,
129 -> Result<&'tcx InlinedItem, Vec<ast_map::PathElem>> {
130 match par_doc.opt_child(c::tag_ast) {
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, raw_ii, dcx);
154 let ident = match *ii {
155 InlinedItem::Item(ref i) => i.ident,
156 InlinedItem::Foreign(ref i) => i.ident,
157 InlinedItem::TraitItem(_, ref ti) => ti.ident,
158 InlinedItem::ImplItem(_, ref ii) => ii.ident
160 debug!("Fn named: {}", ident);
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 syntax::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.
213 /// However, there are a *few* cases where def-ids are used but we know that the thing being
214 /// referenced is in fact *internal* to the item being inlined. In those cases, you should use
215 /// `tr_intern_def_id()` below.
216 pub fn tr_def_id(&self, did: DefId) -> DefId {
218 decoder::translate_def_id(self.cdata, did)
221 /// Translates an INTERNAL def-id, meaning a def-id that is
222 /// known to refer to some part of the item currently being
223 /// inlined. In that case, we want to convert the def-id to
224 /// refer to the current crate and to the new, inlined node-id.
225 pub fn tr_intern_def_id(&self, did: DefId) -> DefId {
226 assert_eq!(did.krate, LOCAL_CRATE);
227 DefId { krate: LOCAL_CRATE, node: self.tr_id(did.node) }
230 /// Translates a `Span` from an extern crate to the corresponding `Span`
231 /// within the local crate's codemap. `creader::import_codemap()` will
232 /// already have allocated any additionally needed FileMaps in the local
233 /// codemap as a side-effect of creating the crate_metadata's
234 /// `codemap_import_info`.
235 pub fn tr_span(&self, span: Span) -> Span {
236 let span = if span.lo > span.hi {
237 // Currently macro expansion sometimes produces invalid Span values
238 // where lo > hi. In order not to crash the compiler when trying to
239 // translate these values, let's transform them into something we
240 // can handle (and which will produce useful debug locations at
241 // least some of the time).
242 // This workaround is only necessary as long as macro expansion is
243 // not fixed. FIXME(#23480)
244 codemap::mk_sp(span.lo, span.lo)
249 let imported_filemaps = self.cdata.imported_filemaps(self.tcx.sess.codemap());
251 // Optimize for the case that most spans within a translated item
252 // originate from the same filemap.
253 let last_filemap_index = self.last_filemap_index.get();
254 let last_filemap = &imported_filemaps[last_filemap_index];
256 if span.lo >= last_filemap.original_start_pos &&
257 span.lo <= last_filemap.original_end_pos &&
258 span.hi >= last_filemap.original_start_pos &&
259 span.hi <= last_filemap.original_end_pos {
263 let mut b = imported_filemaps.len();
267 if imported_filemaps[m].original_start_pos > span.lo {
274 self.last_filemap_index.set(a);
275 &imported_filemaps[a]
279 let lo = (span.lo - filemap.original_start_pos) +
280 filemap.translated_filemap.start_pos;
281 let hi = (span.hi - filemap.original_start_pos) +
282 filemap.translated_filemap.start_pos;
284 codemap::mk_sp(lo, hi)
288 impl tr_intern for DefId {
289 fn tr_intern(&self, dcx: &DecodeContext) -> DefId {
290 dcx.tr_intern_def_id(*self)
295 fn tr(&self, dcx: &DecodeContext) -> DefId {
300 impl tr for Option<DefId> {
301 fn tr(&self, dcx: &DecodeContext) -> Option<DefId> {
302 self.map(|d| dcx.tr_def_id(d))
307 fn tr(&self, dcx: &DecodeContext) -> Span {
312 trait def_id_encoder_helpers {
313 fn emit_def_id(&mut self, did: DefId);
316 impl<S:serialize::Encoder> def_id_encoder_helpers for S
317 where <S as serialize::serialize::Encoder>::Error: Debug
319 fn emit_def_id(&mut self, did: DefId) {
320 did.encode(self).unwrap()
324 trait def_id_decoder_helpers {
325 fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId;
326 fn read_def_id_nodcx(&mut self,
327 cdata: &cstore::crate_metadata) -> DefId;
330 impl<D:serialize::Decoder> def_id_decoder_helpers for D
331 where <D as serialize::serialize::Decoder>::Error: Debug
333 fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId {
334 let did: DefId = Decodable::decode(self).unwrap();
338 fn read_def_id_nodcx(&mut self,
339 cdata: &cstore::crate_metadata)
341 let did: DefId = Decodable::decode(self).unwrap();
342 decoder::translate_def_id(cdata, did)
346 // ______________________________________________________________________
347 // Encoding and decoding the AST itself
349 // When decoding, we have to renumber the AST so that the node ids that
350 // appear within are disjoint from the node ids in our existing ASTs.
351 // We also have to adjust the spans: for now we just insert a dummy span,
352 // but eventually we should add entries to the local codemap as required.
354 fn encode_ast(rbml_w: &mut Encoder, item: &InlinedItem) {
355 rbml_w.start_tag(c::tag_tree as usize);
360 struct NestedItemsDropper;
362 impl Folder for NestedItemsDropper {
363 fn fold_block(&mut self, blk: P<ast::Block>) -> P<ast::Block> {
364 blk.and_then(|ast::Block {id, stmts, expr, rules, span, ..}| {
365 let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
366 let use_stmt = match stmt.node {
367 ast::StmtExpr(_, _) | ast::StmtSemi(_, _) => true,
368 ast::StmtDecl(ref decl, _) => {
370 ast::DeclLocal(_) => true,
371 ast::DeclItem(_) => false,
374 ast::StmtMac(..) => panic!("unexpanded macro in astencode")
382 let blk_sans_items = P(ast::Block {
383 stmts: stmts_sans_items,
389 fold::noop_fold_block(blk_sans_items, self)
394 // Produces a simplified copy of the AST which does not include things
395 // that we do not need to or do not want to export. For example, we
396 // do not include any nested items: if these nested items are to be
397 // inlined, their AST will be exported separately (this only makes
398 // sense because, in Rust, nested items are independent except for
399 // their visibility).
401 // As it happens, trans relies on the fact that we do not export
402 // nested items, as otherwise it would get confused when translating
404 fn simplify_ast(ii: InlinedItemRef) -> InlinedItem {
405 let mut fld = NestedItemsDropper;
408 // HACK we're not dropping items.
409 InlinedItemRef::Item(i) => {
410 InlinedItem::Item(fold::noop_fold_item(P(i.clone()), &mut fld)
411 .expect_one("expected one item"))
413 InlinedItemRef::TraitItem(d, ti) => {
414 InlinedItem::TraitItem(d,
415 fold::noop_fold_trait_item(P(ti.clone()), &mut fld)
416 .expect_one("noop_fold_trait_item must produce \
417 exactly one trait item"))
419 InlinedItemRef::ImplItem(d, ii) => {
420 InlinedItem::ImplItem(d,
421 fold::noop_fold_impl_item(P(ii.clone()), &mut fld)
422 .expect_one("noop_fold_impl_item must produce \
423 exactly one impl item"))
425 InlinedItemRef::Foreign(i) => {
426 InlinedItem::Foreign(fold::noop_fold_foreign_item(P(i.clone()), &mut fld))
431 fn decode_ast(par_doc: rbml::Doc) -> InlinedItem {
432 let chi_doc = par_doc.get(c::tag_tree as usize);
433 let mut d = reader::Decoder::new(chi_doc);
434 Decodable::decode(&mut d).unwrap()
437 // ______________________________________________________________________
438 // Encoding and decoding of ast::def
440 fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> def::Def {
441 let def: def::Def = Decodable::decode(dsr).unwrap();
445 impl tr for def::Def {
446 fn tr(&self, dcx: &DecodeContext) -> def::Def {
448 def::DefFn(did, is_ctor) => def::DefFn(did.tr(dcx), is_ctor),
449 def::DefMethod(did) => def::DefMethod(did.tr(dcx)),
450 def::DefSelfTy(opt_did, impl_ids) => { def::DefSelfTy(opt_did.map(|did| did.tr(dcx)),
451 impl_ids.map(|(nid1, nid2)| {
455 def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
456 def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
457 def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
458 def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
459 def::DefAssociatedConst(did) => def::DefAssociatedConst(did.tr(dcx)),
460 def::DefLocal(nid) => { def::DefLocal(dcx.tr_id(nid)) }
461 def::DefVariant(e_did, v_did, is_s) => {
462 def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
464 def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
465 def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
466 def::DefAssociatedTy(trait_did, did) =>
467 def::DefAssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
468 def::DefPrimTy(p) => def::DefPrimTy(p),
469 def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
470 def::DefUse(did) => def::DefUse(did.tr(dcx)),
471 def::DefUpvar(nid1, nid2) => {
472 def::DefUpvar(dcx.tr_id(nid1), dcx.tr_id(nid2))
474 def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
475 def::DefRegion(nid) => def::DefRegion(dcx.tr_id(nid)),
476 def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
481 // ______________________________________________________________________
482 // Encoding and decoding of ancillary information
484 impl tr for ty::Region {
485 fn tr(&self, dcx: &DecodeContext) -> ty::Region {
487 ty::ReLateBound(debruijn, br) => {
488 ty::ReLateBound(debruijn, br.tr(dcx))
490 ty::ReEarlyBound(data) => {
491 ty::ReEarlyBound(ty::EarlyBoundRegion {
492 param_id: dcx.tr_id(data.param_id),
498 ty::ReScope(scope) => {
499 ty::ReScope(scope.tr(dcx))
501 ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => {
504 ty::ReFree(ref fr) => {
505 ty::ReFree(fr.tr(dcx))
511 impl tr for ty::FreeRegion {
512 fn tr(&self, dcx: &DecodeContext) -> ty::FreeRegion {
513 ty::FreeRegion { scope: self.scope.tr(dcx),
514 bound_region: self.bound_region.tr(dcx) }
518 impl tr for region::CodeExtent {
519 fn tr(&self, dcx: &DecodeContext) -> region::CodeExtent {
520 self.map_id(|id| dcx.tr_id(id))
524 impl tr for region::DestructionScopeData {
525 fn tr(&self, dcx: &DecodeContext) -> region::DestructionScopeData {
526 region::DestructionScopeData { node_id: dcx.tr_id(self.node_id) }
530 impl tr for ty::BoundRegion {
531 fn tr(&self, dcx: &DecodeContext) -> ty::BoundRegion {
536 ty::BrNamed(id, ident) => ty::BrNamed(dcx.tr_def_id(id),
542 // ______________________________________________________________________
543 // Encoding and decoding of freevar information
545 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
546 (*fv).encode(rbml_w).unwrap();
549 trait rbml_decoder_helper {
550 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
552 fn read_capture_mode(&mut self) -> ast::CaptureClause;
555 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
556 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
558 let fv: ty::Freevar = Decodable::decode(self).unwrap();
562 fn read_capture_mode(&mut self) -> ast::CaptureClause {
563 let cm: ast::CaptureClause = Decodable::decode(self).unwrap();
568 impl tr for ty::Freevar {
569 fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
571 def: self.def.tr(dcx),
572 span: self.span.tr(dcx),
577 impl tr for ty::UpvarBorrow {
578 fn tr(&self, dcx: &DecodeContext) -> ty::UpvarBorrow {
581 region: self.region.tr(dcx)
586 impl tr for ty::UpvarCapture {
587 fn tr(&self, dcx: &DecodeContext) -> ty::UpvarCapture {
589 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
590 ty::UpvarCapture::ByRef(ref data) => ty::UpvarCapture::ByRef(data.tr(dcx)),
595 // ______________________________________________________________________
596 // Encoding and decoding of MethodCallee
598 trait read_method_callee_helper<'tcx> {
599 fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
600 -> (u32, ty::MethodCallee<'tcx>);
603 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
604 rbml_w: &mut Encoder,
606 method: &ty::MethodCallee<'tcx>) {
607 use serialize::Encoder;
609 rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
610 rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
611 autoderef.encode(rbml_w)
613 rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
614 Ok(rbml_w.emit_def_id(method.def_id))
616 rbml_w.emit_struct_field("ty", 2, |rbml_w| {
617 Ok(rbml_w.emit_ty(ecx, method.ty))
619 rbml_w.emit_struct_field("substs", 3, |rbml_w| {
620 Ok(rbml_w.emit_substs(ecx, &method.substs))
625 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
626 fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
627 -> (u32, ty::MethodCallee<'tcx>) {
629 self.read_struct("MethodCallee", 4, |this| {
630 let autoderef = this.read_struct_field("autoderef", 0,
631 Decodable::decode).unwrap();
632 Ok((autoderef, ty::MethodCallee {
633 def_id: this.read_struct_field("def_id", 1, |this| {
634 Ok(this.read_def_id(dcx))
636 ty: this.read_struct_field("ty", 2, |this| {
637 Ok(this.read_ty(dcx))
639 substs: this.read_struct_field("substs", 3, |this| {
640 Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
647 pub fn encode_closure_kind(ebml_w: &mut Encoder, kind: ty::ClosureKind) {
648 kind.encode(ebml_w).unwrap();
651 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
652 kind.encode(ebml_w).unwrap();
655 pub trait vtable_decoder_helpers<'tcx> {
656 fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
657 F: FnMut(&mut Self) -> T;
660 impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> {
661 fn read_vec_per_param_space<T, F>(&mut self, mut f: F) -> VecPerParamSpace<T> where
662 F: FnMut(&mut reader::Decoder<'a>) -> T,
664 let types = self.read_to_vec(|this| Ok(f(this))).unwrap();
665 let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap();
666 let fns = self.read_to_vec(|this| Ok(f(this))).unwrap();
667 VecPerParamSpace::new(types, selfs, fns)
671 // ___________________________________________________________________________
674 fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder,
675 v: &subst::VecPerParamSpace<T>,
677 F: FnMut(&mut Encoder, &T),
679 for &space in &subst::ParamSpace::all() {
680 rbml_w.emit_from_vec(v.get_slice(space),
681 |rbml_w, n| Ok(f(rbml_w, n))).unwrap();
685 // ______________________________________________________________________
686 // Encoding and decoding the side tables
688 trait get_ty_str_ctxt<'tcx> {
689 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
692 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
693 fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
695 diag: self.tcx.sess.diagnostic(),
696 ds: e::def_to_string,
698 abbrevs: &self.type_abbrevs
703 trait rbml_writer_helpers<'tcx> {
704 fn emit_closure_type<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
705 closure_type: &ty::ClosureTy<'tcx>);
706 fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
707 fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
708 fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
709 type_param_def: &ty::TypeParameterDef<'tcx>);
710 fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
711 predicate: &ty::Predicate<'tcx>);
712 fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
713 ty: &ty::TraitRef<'tcx>);
714 fn emit_type_scheme<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
715 type_scheme: ty::TypeScheme<'tcx>);
716 fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
717 substs: &subst::Substs<'tcx>);
718 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
719 bounds: &ty::ExistentialBounds<'tcx>);
720 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
721 fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
722 adj: &ty::AutoAdjustment<'tcx>);
723 fn emit_autoref<'a>(&mut self, autoref: &ty::AutoRef<'tcx>);
724 fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
725 auto_deref_ref: &ty::AutoDerefRef<'tcx>);
728 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
729 fn emit_closure_type<'b>(&mut self,
730 ecx: &e::EncodeContext<'b, 'tcx>,
731 closure_type: &ty::ClosureTy<'tcx>) {
732 self.emit_opaque(|this| {
733 Ok(e::write_closure_type(ecx, this, closure_type))
737 fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
738 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
741 fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
742 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
745 fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
746 trait_ref: &ty::TraitRef<'tcx>) {
747 self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
750 fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
751 type_param_def: &ty::TypeParameterDef<'tcx>) {
752 self.emit_opaque(|this| {
753 Ok(tyencode::enc_type_param_def(this,
759 fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
760 predicate: &ty::Predicate<'tcx>) {
761 self.emit_opaque(|this| {
762 Ok(tyencode::enc_predicate(this,
768 fn emit_type_scheme<'b>(&mut self,
769 ecx: &e::EncodeContext<'b, 'tcx>,
770 type_scheme: ty::TypeScheme<'tcx>) {
771 use serialize::Encoder;
773 self.emit_struct("TypeScheme", 2, |this| {
774 this.emit_struct_field("generics", 0, |this| {
775 this.emit_struct("Generics", 2, |this| {
776 this.emit_struct_field("types", 0, |this| {
777 Ok(encode_vec_per_param_space(
778 this, &type_scheme.generics.types,
779 |this, def| this.emit_type_param_def(ecx, def)))
781 this.emit_struct_field("regions", 1, |this| {
782 Ok(encode_vec_per_param_space(
783 this, &type_scheme.generics.regions,
784 |this, def| def.encode(this).unwrap()))
788 this.emit_struct_field("ty", 1, |this| {
789 Ok(this.emit_ty(ecx, type_scheme.ty))
794 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
795 bounds: &ty::ExistentialBounds<'tcx>) {
796 self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
801 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
802 self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
807 fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
808 substs: &subst::Substs<'tcx>) {
809 self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
814 fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
815 adj: &ty::AutoAdjustment<'tcx>) {
816 use serialize::Encoder;
818 self.emit_enum("AutoAdjustment", |this| {
820 ty::AdjustReifyFnPointer=> {
821 this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
824 ty::AdjustUnsafeFnPointer => {
825 this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
830 ty::AdjustDerefRef(ref auto_deref_ref) => {
831 this.emit_enum_variant("AdjustDerefRef", 3, 2, |this| {
832 this.emit_enum_variant_arg(0,
833 |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
840 fn emit_autoref<'b>(&mut self, autoref: &ty::AutoRef<'tcx>) {
841 use serialize::Encoder;
843 self.emit_enum("AutoRef", |this| {
845 &ty::AutoPtr(r, m) => {
846 this.emit_enum_variant("AutoPtr", 0, 2, |this| {
847 this.emit_enum_variant_arg(0, |this| r.encode(this));
848 this.emit_enum_variant_arg(1, |this| m.encode(this))
851 &ty::AutoUnsafe(m) => {
852 this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
853 this.emit_enum_variant_arg(0, |this| m.encode(this))
860 fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
861 auto_deref_ref: &ty::AutoDerefRef<'tcx>) {
862 use serialize::Encoder;
864 self.emit_struct("AutoDerefRef", 2, |this| {
865 this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
867 this.emit_struct_field("autoref", 1, |this| {
868 this.emit_option(|this| {
869 match auto_deref_ref.autoref {
870 None => this.emit_option_none(),
871 Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(a))),
876 this.emit_struct_field("unsize", 2, |this| {
877 this.emit_option(|this| {
878 match auto_deref_ref.unsize {
879 None => this.emit_option_none(),
880 Some(target) => this.emit_option_some(|this| {
881 Ok(this.emit_ty(ecx, target))
890 trait write_tag_and_id {
891 fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
892 fn id(&mut self, id: ast::NodeId);
895 impl<'a> write_tag_and_id for Encoder<'a> {
897 tag_id: c::astencode_tag,
899 F: FnOnce(&mut Encoder<'a>),
901 self.start_tag(tag_id as usize);
906 fn id(&mut self, id: ast::NodeId) {
907 id.encode(self).unwrap();
911 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
912 ecx: &'a e::EncodeContext<'c, 'tcx>,
913 rbml_w: &'a mut Encoder<'b>,
916 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
917 SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
918 fn visit_id(&mut self, id: ast::NodeId) {
919 encode_side_tables_for_id(self.ecx, self.rbml_w, id)
923 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
924 rbml_w: &mut Encoder,
926 rbml_w.start_tag(c::tag_table as usize);
927 ii.visit_ids(&mut SideTableEncodingIdVisitor {
934 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
935 rbml_w: &mut Encoder,
939 debug!("Encoding side tables for id {}", id);
941 if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
942 rbml_w.tag(c::tag_table_def, |rbml_w| {
944 def.encode(rbml_w).unwrap();
948 if let Some(ty) = tcx.node_types().get(&id) {
949 rbml_w.tag(c::tag_table_node_type, |rbml_w| {
951 rbml_w.emit_ty(ecx, *ty);
955 if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
956 rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
958 rbml_w.emit_substs(ecx, &item_substs.substs);
962 if let Some(fv) = tcx.freevars.borrow().get(&id) {
963 rbml_w.tag(c::tag_table_freevars, |rbml_w| {
965 rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
966 Ok(encode_freevar_entry(rbml_w, fv_entry))
971 rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
974 let var_id = freevar.def.def_id().node;
975 let upvar_id = ty::UpvarId {
979 let upvar_capture = tcx.tables
985 var_id.encode(rbml_w);
986 upvar_capture.encode(rbml_w);
991 let lid = DefId { krate: LOCAL_CRATE, node: id };
992 if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
993 rbml_w.tag(c::tag_table_tcache, |rbml_w| {
995 rbml_w.emit_type_scheme(ecx, type_scheme.clone());
999 if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
1000 rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
1002 rbml_w.emit_type_param_def(ecx, type_param_def)
1006 let method_call = ty::MethodCall::expr(id);
1007 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
1008 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1010 encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
1014 if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
1016 ty::AdjustDerefRef(ref adj) => {
1017 for autoderef in 0..adj.autoderefs {
1018 let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
1019 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
1020 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1022 encode_method_callee(ecx, rbml_w,
1023 method_call.autoderef, method)
1031 rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
1033 rbml_w.emit_auto_adjustment(ecx, adjustment);
1037 if let Some(closure_type) = tcx.tables.borrow().closure_tys.get(&DefId::local(id)) {
1038 rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
1040 rbml_w.emit_closure_type(ecx, closure_type);
1044 if let Some(closure_kind) = tcx.tables.borrow().closure_kinds.get(&DefId::local(id)) {
1045 rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
1047 encode_closure_kind(rbml_w, *closure_kind)
1051 if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
1052 rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
1054 encode_cast_kind(rbml_w, *cast_kind)
1058 if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
1059 rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
1061 qualif.encode(rbml_w).unwrap()
1066 trait doc_decoder_helpers: Sized {
1067 fn as_int(&self) -> isize;
1068 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1071 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
1072 fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
1073 fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
1074 reader::maybe_get_doc(*self, tag as usize)
1078 trait rbml_decoder_decoder_helpers<'tcx> {
1079 fn read_ty_encoded<'a, 'b, F, R>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>,
1081 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x, 'tcx>) -> R;
1083 fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
1084 fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
1085 fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1086 -> ty::TraitRef<'tcx>;
1087 fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1088 -> ty::PolyTraitRef<'tcx>;
1089 fn read_type_param_def<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1090 -> ty::TypeParameterDef<'tcx>;
1091 fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1092 -> ty::Predicate<'tcx>;
1093 fn read_type_scheme<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1094 -> ty::TypeScheme<'tcx>;
1095 fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1096 -> ty::ExistentialBounds<'tcx>;
1097 fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1098 -> subst::Substs<'tcx>;
1099 fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1100 -> ty::AutoAdjustment<'tcx>;
1101 fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1103 fn read_closure_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1105 fn read_closure_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1106 -> ty::ClosureTy<'tcx>;
1107 fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1108 -> ty::AutoDerefRef<'tcx>;
1109 fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1110 -> ty::AutoRef<'tcx>;
1111 fn convert_def_id(&mut self,
1112 dcx: &DecodeContext,
1113 source: DefIdSource,
1117 // Versions of the type reading functions that don't need the full
1119 fn read_ty_nodcx(&mut self,
1120 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
1121 fn read_tys_nodcx(&mut self,
1122 tcx: &ty::ctxt<'tcx>,
1123 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
1124 fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
1125 cdata: &cstore::crate_metadata)
1126 -> subst::Substs<'tcx>;
1129 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
1130 fn read_ty_nodcx(&mut self,
1131 tcx: &ty::ctxt<'tcx>,
1132 cdata: &cstore::crate_metadata)
1134 self.read_opaque(|_, doc| {
1136 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
1137 &mut |_, id| decoder::translate_def_id(cdata, id))
1142 fn read_tys_nodcx(&mut self,
1143 tcx: &ty::ctxt<'tcx>,
1144 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
1145 self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
1151 fn read_substs_nodcx(&mut self,
1152 tcx: &ty::ctxt<'tcx>,
1153 cdata: &cstore::crate_metadata)
1154 -> subst::Substs<'tcx>
1156 self.read_opaque(|_, doc| {
1158 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
1159 &mut |_, id| decoder::translate_def_id(cdata, id))
1164 fn read_ty_encoded<'b, 'c, F, R>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>, op: F) -> R
1165 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x,'tcx>) -> R
1167 return self.read_opaque(|this, doc| {
1168 debug!("read_ty_encoded({})", type_string(doc));
1170 &mut tydecode::TyDecoder::with_doc(
1171 dcx.tcx, dcx.cdata.cnum, doc,
1172 &mut |s, a| this.convert_def_id(dcx, s, a))))
1175 fn type_string(doc: rbml::Doc) -> String {
1176 let mut str = String::new();
1177 for i in doc.start..doc.end {
1178 str.push(doc.data[i] as char);
1184 fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1185 // Note: regions types embed local node ids. In principle, we
1186 // should translate these node ids into the new decode
1187 // context. However, we do not bother, because region types
1188 // are not used during trans.
1190 return self.read_ty_encoded(dcx, |decoder| decoder.parse_ty());
1193 fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1195 self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1198 fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1199 -> ty::TraitRef<'tcx> {
1200 self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref())
1203 fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1204 -> ty::PolyTraitRef<'tcx> {
1205 ty::Binder(self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref()))
1208 fn read_type_param_def<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1209 -> ty::TypeParameterDef<'tcx> {
1210 self.read_ty_encoded(dcx, |decoder| decoder.parse_type_param_def())
1213 fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1214 -> ty::Predicate<'tcx>
1216 self.read_ty_encoded(dcx, |decoder| decoder.parse_predicate())
1219 fn read_type_scheme<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1220 -> ty::TypeScheme<'tcx> {
1221 self.read_struct("TypeScheme", 3, |this| {
1223 generics: this.read_struct_field("generics", 0, |this| {
1224 this.read_struct("Generics", 2, |this| {
1227 this.read_struct_field("types", 0, |this| {
1228 Ok(this.read_vec_per_param_space(
1229 |this| this.read_type_param_def(dcx)))
1233 this.read_struct_field("regions", 1, |this| {
1234 Ok(this.read_vec_per_param_space(
1235 |this| Decodable::decode(this).unwrap()))
1240 ty: this.read_struct_field("ty", 1, |this| {
1241 Ok(this.read_ty(dcx))
1247 fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1248 -> ty::ExistentialBounds<'tcx>
1250 self.read_ty_encoded(dcx, |decoder| decoder.parse_existential_bounds())
1253 fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1254 -> subst::Substs<'tcx> {
1255 self.read_opaque(|this, doc| {
1256 Ok(tydecode::TyDecoder::with_doc(dcx.tcx, dcx.cdata.cnum, doc,
1257 &mut |s, a| this.convert_def_id(dcx, s, a))
1262 fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1263 -> ty::AutoAdjustment<'tcx> {
1264 self.read_enum("AutoAdjustment", |this| {
1265 let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer", "AdjustDerefRef"];
1266 this.read_enum_variant(&variants, |this, i| {
1268 1 => ty::AdjustReifyFnPointer,
1269 2 => ty::AdjustUnsafeFnPointer,
1271 let auto_deref_ref: ty::AutoDerefRef =
1272 this.read_enum_variant_arg(0,
1273 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1275 ty::AdjustDerefRef(auto_deref_ref)
1277 _ => panic!("bad enum variant for ty::AutoAdjustment")
1283 fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1284 -> ty::AutoDerefRef<'tcx> {
1285 self.read_struct("AutoDerefRef", 2, |this| {
1286 Ok(ty::AutoDerefRef {
1287 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1288 Decodable::decode(this)
1290 autoref: this.read_struct_field("autoref", 1, |this| {
1291 this.read_option(|this, b| {
1293 Ok(Some(this.read_autoref(dcx)))
1299 unsize: this.read_struct_field("unsize", 2, |this| {
1300 this.read_option(|this, b| {
1302 Ok(Some(this.read_ty(dcx)))
1312 fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1313 -> ty::AutoRef<'tcx> {
1314 self.read_enum("AutoRef", |this| {
1315 let variants = ["AutoPtr", "AutoUnsafe"];
1316 this.read_enum_variant(&variants, |this, i| {
1320 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1321 let m: ast::Mutability =
1322 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1324 ty::AutoPtr(dcx.tcx.mk_region(r.tr(dcx)), m)
1327 let m: ast::Mutability =
1328 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1332 _ => panic!("bad enum variant for ty::AutoRef")
1338 fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1341 Decodable::decode(self).unwrap()
1344 fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1347 Decodable::decode(self).unwrap()
1350 fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1351 -> ty::ClosureTy<'tcx>
1353 self.read_ty_encoded(dcx, |decoder| decoder.parse_closure_ty())
1356 /// Converts a def-id that appears in a type. The correct
1357 /// translation will depend on what kind of def-id this is.
1358 /// This is a subtle point: type definitions are not
1359 /// inlined into the current crate, so if the def-id names
1360 /// a nominal type or type alias, then it should be
1361 /// translated to refer to the source crate.
1363 /// However, *type parameters* are cloned along with the function
1364 /// they are attached to. So we should translate those def-ids
1365 /// to refer to the new, cloned copy of the type parameter.
1366 /// We only see references to free type parameters in the body of
1367 /// an inlined function. In such cases, we need the def-id to
1368 /// be a local id so that the TypeContents code is able to lookup
1369 /// the relevant info in the ty_param_defs table.
1371 /// *Region parameters*, unfortunately, are another kettle of fish.
1372 /// In such cases, def_id's can appear in types to distinguish
1373 /// shadowed bound regions and so forth. It doesn't actually
1374 /// matter so much what we do to these, since regions are erased
1375 /// at trans time, but it's good to keep them consistent just in
1376 /// case. We translate them with `tr_def_id()` which will map
1377 /// the crate numbers back to the original source crate.
1379 /// Unboxed closures are cloned along with the function being
1380 /// inlined, and all side tables use interned node IDs, so we
1381 /// translate their def IDs accordingly.
1383 /// It'd be really nice to refactor the type repr to not include
1384 /// def-ids so that all these distinctions were unnecessary.
1385 fn convert_def_id(&mut self,
1386 dcx: &DecodeContext,
1387 source: tydecode::DefIdSource,
1390 let r = match source {
1391 NominalType | TypeWithId | RegionParameter => dcx.tr_def_id(did),
1392 ClosureSource => dcx.tr_intern_def_id(did)
1394 debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1399 fn decode_side_tables(dcx: &DecodeContext,
1400 ast_doc: rbml::Doc) {
1401 let tbl_doc = ast_doc.get(c::tag_table as usize);
1402 for (tag, entry_doc) in reader::docs(tbl_doc) {
1403 let mut entry_dsr = reader::Decoder::new(entry_doc);
1404 let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1405 let id = dcx.tr_id(id0);
1407 debug!(">> Side table document with tag 0x{:x} \
1408 found for id {} (orig {})",
1410 let tag = tag as u32;
1411 let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1415 &format!("unknown tag found in side tables: {:x}",
1419 let val_dsr = &mut entry_dsr;
1422 c::tag_table_def => {
1423 let def = decode_def(dcx, val_dsr);
1424 dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
1426 // This doesn't matter cross-crate.
1427 last_private: LastMod(AllPublic),
1431 c::tag_table_node_type => {
1432 let ty = val_dsr.read_ty(dcx);
1433 debug!("inserting ty for node {}: {:?}",
1435 dcx.tcx.node_type_insert(id, ty);
1437 c::tag_table_item_subst => {
1438 let item_substs = ty::ItemSubsts {
1439 substs: val_dsr.read_substs(dcx)
1441 dcx.tcx.tables.borrow_mut().item_substs.insert(
1444 c::tag_table_freevars => {
1445 let fv_info = val_dsr.read_to_vec(|val_dsr| {
1446 Ok(val_dsr.read_freevar_entry(dcx))
1447 }).unwrap().into_iter().collect();
1448 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1450 c::tag_table_upvar_capture_map => {
1451 let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1452 let upvar_id = ty::UpvarId {
1453 var_id: dcx.tr_id(var_id),
1456 let ub: ty::UpvarCapture = Decodable::decode(val_dsr).unwrap();
1457 dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub.tr(dcx));
1459 c::tag_table_tcache => {
1460 let type_scheme = val_dsr.read_type_scheme(dcx);
1461 let lid = DefId { krate: LOCAL_CRATE, node: id };
1462 dcx.tcx.register_item_type(lid, type_scheme);
1464 c::tag_table_param_defs => {
1465 let bounds = val_dsr.read_type_param_def(dcx);
1466 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1468 c::tag_table_method_map => {
1469 let (autoderef, method) = val_dsr.read_method_callee(dcx);
1470 let method_call = ty::MethodCall {
1472 autoderef: autoderef
1474 dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1476 c::tag_table_adjustments => {
1477 let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(dcx);
1478 dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1480 c::tag_table_closure_tys => {
1482 val_dsr.read_closure_ty(dcx);
1483 dcx.tcx.tables.borrow_mut().closure_tys.insert(DefId::local(id),
1486 c::tag_table_closure_kinds => {
1488 val_dsr.read_closure_kind(dcx);
1489 dcx.tcx.tables.borrow_mut().closure_kinds.insert(DefId::local(id),
1492 c::tag_table_cast_kinds => {
1494 val_dsr.read_cast_kind(dcx);
1495 dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1497 c::tag_table_const_qualif => {
1498 let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1499 dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1503 &format!("unknown tag found in side tables: {:x}",
1510 debug!(">< Side table doc loaded");
1514 // ______________________________________________________________________
1515 // Testing of astencode_gen
1518 fn encode_item_ast(rbml_w: &mut Encoder, item: &ast::Item) {
1519 rbml_w.start_tag(c::tag_tree as usize);
1520 (*item).encode(rbml_w);
1525 fn decode_item_ast(par_doc: rbml::Doc) -> ast::Item {
1526 let chi_doc = par_doc.get(c::tag_tree as usize);
1527 let mut d = reader::Decoder::new(chi_doc);
1528 Decodable::decode(&mut d).unwrap()
1533 fn call_site(&self) -> codemap::Span;
1534 fn cfg(&self) -> ast::CrateConfig;
1535 fn ident_of(&self, st: &str) -> ast::Ident;
1536 fn name_of(&self, st: &str) -> ast::Name;
1537 fn parse_sess(&self) -> &parse::ParseSess;
1541 impl FakeExtCtxt for parse::ParseSess {
1542 fn call_site(&self) -> codemap::Span {
1544 lo: codemap::BytePos(0),
1545 hi: codemap::BytePos(0),
1546 expn_id: codemap::NO_EXPANSION,
1549 fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1550 fn ident_of(&self, st: &str) -> ast::Ident {
1551 parse::token::str_to_ident(st)
1553 fn name_of(&self, st: &str) -> ast::Name {
1554 parse::token::intern(st)
1556 fn parse_sess(&self) -> &parse::ParseSess { self }
1560 fn mk_ctxt() -> parse::ParseSess {
1561 parse::ParseSess::new()
1565 fn roundtrip(in_item: Option<P<ast::Item>>) {
1566 let in_item = in_item.unwrap();
1567 let mut wr = Cursor::new(Vec::new());
1568 encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
1569 let rbml_doc = rbml::Doc::new(wr.get_ref());
1570 let out_item = decode_item_ast(rbml_doc);
1572 assert!(*in_item == out_item);
1578 roundtrip(quote_item!(&cx,
1584 fn test_smalltalk() {
1586 roundtrip(quote_item!(&cx,
1587 fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1594 roundtrip(quote_item!(&cx,
1595 fn foo(x: usize, y: usize) -> usize {
1603 fn test_simplification() {
1605 let item = quote_item!(&cx,
1606 fn new_int_alist<B>() -> alist<isize, B> {
1607 fn eq_int(a: isize, b: isize) -> bool { a == b }
1608 return alist {eq_fn: eq_int, data: Vec::new()};
1611 let item_in = InlinedItemRef::Item(&*item);
1612 let item_out = simplify_ast(item_in);
1613 let item_exp = InlinedItem::Item(quote_item!(&cx,
1614 fn new_int_alist<B>() -> alist<isize, B> {
1615 return alist {eq_fn: eq_int, data: Vec::new()};
1618 match (item_out, item_exp) {
1619 (InlinedItem::Item(item_out), InlinedItem::Item(item_exp)) => {
1620 assert!(pprust::item_to_string(&*item_out) ==
1621 pprust::item_to_string(&*item_exp));