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;
21 use metadata::encoder as e;
23 use metadata::tydecode;
24 use metadata::tydecode::{DefIdSource, NominalType, TypeWithId};
25 use metadata::tydecode::{RegionParameter, ClosureSource};
26 use metadata::tyencode;
28 use middle::check_const::ConstQualif;
29 use middle::privacy::{AllPublic, LastMod};
31 use middle::subst::VecPerParamSpace;
32 use middle::ty::{self, Ty};
34 use syntax::{ast, ast_util, codemap, fold};
35 use syntax::codemap::Span;
36 use syntax::fold::Folder;
41 use std::io::SeekFrom;
42 use std::io::prelude::*;
46 use rbml::writer::Encoder;
49 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
50 use serialize::EncoderHelpers;
52 #[cfg(test)] use std::io::Cursor;
53 #[cfg(test)] use syntax::parse;
54 #[cfg(test)] use syntax::print::pprust;
56 struct DecodeContext<'a, 'b, 'tcx: 'a> {
57 tcx: &'a ty::ctxt<'tcx>,
58 cdata: &'b cstore::crate_metadata,
59 from_id_range: ast_util::IdRange,
60 to_id_range: ast_util::IdRange,
61 // Cache the last used filemap for translating spans as an optimization.
62 last_filemap_index: Cell<usize>,
66 fn tr(&self, dcx: &DecodeContext) -> Self;
70 fn tr_intern(&self, dcx: &DecodeContext) -> ast::DefId;
73 // ______________________________________________________________________
76 pub fn encode_inlined_item(ecx: &e::EncodeContext,
78 ii: e::InlinedItemRef) {
80 e::IIItemRef(i) => i.id,
81 e::IIForeignRef(i) => i.id,
82 e::IITraitItemRef(_, ti) => ti.id,
83 e::IIImplItemRef(_, 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 = ast_util::compute_id_range_for_inlined_item(&ii);
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: ast::DefId) -> ast::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>,
127 -> Result<&'tcx ast::InlinedItem, Vec<ast_map::PathElem>> {
128 match par_doc.opt_child(c::tag_ast) {
131 let mut path_as_str = None;
132 debug!("> Decoding inlined fn: {:?}::?",
134 // Do an Option dance to use the path after it is moved below.
135 let s = ast_map::path_to_string(path.iter().cloned());
136 path_as_str = Some(s);
137 path_as_str.as_ref().map(|x| &x[..])
139 let mut ast_dsr = reader::Decoder::new(ast_doc);
140 let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
141 let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
142 let dcx = &DecodeContext {
145 from_id_range: from_id_range,
146 to_id_range: to_id_range,
147 last_filemap_index: Cell::new(0)
149 let raw_ii = decode_ast(ast_doc);
150 let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, raw_ii, dcx);
152 let ident = match *ii {
153 ast::IIItem(ref i) => i.ident,
154 ast::IIForeign(ref i) => i.ident,
155 ast::IITraitItem(_, ref ti) => ti.ident,
156 ast::IIImplItem(_, ref ii) => ii.ident
158 debug!("Fn named: {}", ident);
159 debug!("< Decoded inlined fn: {}::{}",
160 path_as_str.unwrap(),
162 region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
163 decode_side_tables(dcx, ast_doc);
165 ast::IIItem(ref i) => {
166 debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
167 syntax::print::pprust::item_to_string(&**i));
176 // ______________________________________________________________________
177 // Enumerating the IDs which appear in an AST
179 fn reserve_id_range(sess: &Session,
180 from_id_range: ast_util::IdRange) -> ast_util::IdRange {
181 // Handle the case of an empty range:
182 if from_id_range.empty() { return from_id_range; }
183 let cnt = from_id_range.max - from_id_range.min;
184 let to_id_min = sess.reserve_node_ids(cnt);
185 let to_id_max = to_id_min + cnt;
186 ast_util::IdRange { min: to_id_min, max: to_id_max }
189 impl<'a, 'b, 'tcx> DecodeContext<'a, 'b, 'tcx> {
190 /// Translates an internal id, meaning a node id that is known to refer to some part of the
191 /// item currently being inlined, such as a local variable or argument. All naked node-ids
192 /// that appear in types have this property, since if something might refer to an external item
193 /// we would use a def-id to allow for the possibility that the item resides in another crate.
194 pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
195 // from_id_range should be non-empty
196 assert!(!self.from_id_range.empty());
197 // Use wrapping arithmetic because otherwise it introduces control flow.
198 // Maybe we should just have the control flow? -- aatch
199 (id.wrapping_sub(self.from_id_range.min).wrapping_add(self.to_id_range.min))
202 /// Translates an EXTERNAL def-id, converting the crate number from the one used in the encoded
203 /// data to the current crate numbers.. By external, I mean that it be translated to a
204 /// reference to the item in its original crate, as opposed to being translated to a reference
205 /// to the inlined version of the item. This is typically, but not always, what you want,
206 /// because most def-ids refer to external things like types or other fns that may or may not
207 /// be inlined. Note that even when the inlined function is referencing itself recursively, we
208 /// would want `tr_def_id` for that reference--- conceptually the function calls the original,
209 /// non-inlined version, and trans deals with linking that recursive call to the inlined copy.
211 /// However, there are a *few* cases where def-ids are used but we know that the thing being
212 /// referenced is in fact *internal* to the item being inlined. In those cases, you should use
213 /// `tr_intern_def_id()` below.
214 pub fn tr_def_id(&self, did: ast::DefId) -> ast::DefId {
216 decoder::translate_def_id(self.cdata, did)
219 /// Translates an INTERNAL def-id, meaning a def-id that is
220 /// known to refer to some part of the item currently being
221 /// inlined. In that case, we want to convert the def-id to
222 /// refer to the current crate and to the new, inlined node-id.
223 pub fn tr_intern_def_id(&self, did: ast::DefId) -> ast::DefId {
224 assert_eq!(did.krate, ast::LOCAL_CRATE);
225 ast::DefId { krate: ast::LOCAL_CRATE, node: self.tr_id(did.node) }
228 /// Translates a `Span` from an extern crate to the corresponding `Span`
229 /// within the local crate's codemap. `creader::import_codemap()` will
230 /// already have allocated any additionally needed FileMaps in the local
231 /// codemap as a side-effect of creating the crate_metadata's
232 /// `codemap_import_info`.
233 pub fn tr_span(&self, span: Span) -> Span {
234 let span = if span.lo > span.hi {
235 // Currently macro expansion sometimes produces invalid Span values
236 // where lo > hi. In order not to crash the compiler when trying to
237 // translate these values, let's transform them into something we
238 // can handle (and which will produce useful debug locations at
239 // least some of the time).
240 // This workaround is only necessary as long as macro expansion is
241 // not fixed. FIXME(#23480)
242 codemap::mk_sp(span.lo, span.lo)
247 let imported_filemaps = self.cdata.imported_filemaps(self.tcx.sess.codemap());
249 // Optimize for the case that most spans within a translated item
250 // originate from the same filemap.
251 let last_filemap_index = self.last_filemap_index.get();
252 let last_filemap = &imported_filemaps[last_filemap_index];
254 if span.lo >= last_filemap.original_start_pos &&
255 span.lo <= last_filemap.original_end_pos &&
256 span.hi >= last_filemap.original_start_pos &&
257 span.hi <= last_filemap.original_end_pos {
261 let mut b = imported_filemaps.len();
265 if imported_filemaps[m].original_start_pos > span.lo {
272 self.last_filemap_index.set(a);
273 &imported_filemaps[a]
277 let lo = (span.lo - filemap.original_start_pos) +
278 filemap.translated_filemap.start_pos;
279 let hi = (span.hi - filemap.original_start_pos) +
280 filemap.translated_filemap.start_pos;
282 codemap::mk_sp(lo, hi)
286 impl tr_intern for ast::DefId {
287 fn tr_intern(&self, dcx: &DecodeContext) -> ast::DefId {
288 dcx.tr_intern_def_id(*self)
292 impl tr for ast::DefId {
293 fn tr(&self, dcx: &DecodeContext) -> ast::DefId {
298 impl tr for Option<ast::DefId> {
299 fn tr(&self, dcx: &DecodeContext) -> Option<ast::DefId> {
300 self.map(|d| dcx.tr_def_id(d))
305 fn tr(&self, dcx: &DecodeContext) -> Span {
310 trait def_id_encoder_helpers {
311 fn emit_def_id(&mut self, did: ast::DefId);
314 impl<S:serialize::Encoder> def_id_encoder_helpers for S
315 where <S as serialize::serialize::Encoder>::Error: Debug
317 fn emit_def_id(&mut self, did: ast::DefId) {
318 did.encode(self).unwrap()
322 trait def_id_decoder_helpers {
323 fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId;
324 fn read_def_id_nodcx(&mut self,
325 cdata: &cstore::crate_metadata) -> ast::DefId;
328 impl<D:serialize::Decoder> def_id_decoder_helpers for D
329 where <D as serialize::serialize::Decoder>::Error: Debug
331 fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId {
332 let did: ast::DefId = Decodable::decode(self).unwrap();
336 fn read_def_id_nodcx(&mut self,
337 cdata: &cstore::crate_metadata)
339 let did: ast::DefId = Decodable::decode(self).unwrap();
340 decoder::translate_def_id(cdata, did)
344 // ______________________________________________________________________
345 // Encoding and decoding the AST itself
347 // When decoding, we have to renumber the AST so that the node ids that
348 // appear within are disjoint from the node ids in our existing ASTs.
349 // We also have to adjust the spans: for now we just insert a dummy span,
350 // but eventually we should add entries to the local codemap as required.
352 fn encode_ast(rbml_w: &mut Encoder, item: &ast::InlinedItem) {
353 rbml_w.start_tag(c::tag_tree as usize);
358 struct NestedItemsDropper;
360 impl Folder for NestedItemsDropper {
361 fn fold_block(&mut self, blk: P<ast::Block>) -> P<ast::Block> {
362 blk.and_then(|ast::Block {id, stmts, expr, rules, span, ..}| {
363 let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
364 let use_stmt = match stmt.node {
365 ast::StmtExpr(_, _) | ast::StmtSemi(_, _) => true,
366 ast::StmtDecl(ref decl, _) => {
368 ast::DeclLocal(_) => true,
369 ast::DeclItem(_) => false,
372 ast::StmtMac(..) => panic!("unexpanded macro in astencode")
380 let blk_sans_items = P(ast::Block {
381 stmts: stmts_sans_items,
387 fold::noop_fold_block(blk_sans_items, self)
392 // Produces a simplified copy of the AST which does not include things
393 // that we do not need to or do not want to export. For example, we
394 // do not include any nested items: if these nested items are to be
395 // inlined, their AST will be exported separately (this only makes
396 // sense because, in Rust, nested items are independent except for
397 // their visibility).
399 // As it happens, trans relies on the fact that we do not export
400 // nested items, as otherwise it would get confused when translating
402 fn simplify_ast(ii: e::InlinedItemRef) -> ast::InlinedItem {
403 let mut fld = NestedItemsDropper;
406 // HACK we're not dropping items.
408 ast::IIItem(fold::noop_fold_item(P(i.clone()), &mut fld)
409 .expect_one("expected one item"))
411 e::IITraitItemRef(d, ti) => {
413 fold::noop_fold_trait_item(P(ti.clone()), &mut fld)
414 .expect_one("noop_fold_trait_item must produce \
415 exactly one trait item"))
417 e::IIImplItemRef(d, ii) => {
419 fold::noop_fold_impl_item(P(ii.clone()), &mut fld)
420 .expect_one("noop_fold_impl_item must produce \
421 exactly one impl item"))
423 e::IIForeignRef(i) => {
424 ast::IIForeign(fold::noop_fold_foreign_item(P(i.clone()), &mut fld))
429 fn decode_ast(par_doc: rbml::Doc) -> ast::InlinedItem {
430 let chi_doc = par_doc.get(c::tag_tree as usize);
431 let mut d = reader::Decoder::new(chi_doc);
432 Decodable::decode(&mut d).unwrap()
435 // ______________________________________________________________________
436 // Encoding and decoding of ast::def
438 fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> def::Def {
439 let def: def::Def = Decodable::decode(dsr).unwrap();
443 impl tr for def::Def {
444 fn tr(&self, dcx: &DecodeContext) -> def::Def {
446 def::DefFn(did, is_ctor) => def::DefFn(did.tr(dcx), is_ctor),
447 def::DefMethod(did, p) => {
448 def::DefMethod(did.tr(dcx), p.map(|did2| did2.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, p) => {
460 def::DefAssociatedConst(did.tr(dcx), p.map(|did2| did2.tr(dcx)))
462 def::DefLocal(nid) => { def::DefLocal(dcx.tr_id(nid)) }
463 def::DefVariant(e_did, v_did, is_s) => {
464 def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
466 def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
467 def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
468 def::DefAssociatedTy(trait_did, did) =>
469 def::DefAssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
470 def::DefPrimTy(p) => def::DefPrimTy(p),
471 def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
472 def::DefUse(did) => def::DefUse(did.tr(dcx)),
473 def::DefUpvar(nid1, nid2) => {
474 def::DefUpvar(dcx.tr_id(nid1), dcx.tr_id(nid2))
476 def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
477 def::DefRegion(nid) => def::DefRegion(dcx.tr_id(nid)),
478 def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
483 // ______________________________________________________________________
484 // Encoding and decoding of ancillary information
486 impl tr for ty::Region {
487 fn tr(&self, dcx: &DecodeContext) -> ty::Region {
489 ty::ReLateBound(debruijn, br) => {
490 ty::ReLateBound(debruijn, br.tr(dcx))
492 ty::ReEarlyBound(data) => {
493 ty::ReEarlyBound(ty::EarlyBoundRegion {
494 param_id: dcx.tr_id(data.param_id),
500 ty::ReScope(scope) => {
501 ty::ReScope(scope.tr(dcx))
503 ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => {
506 ty::ReFree(ref fr) => {
507 ty::ReFree(fr.tr(dcx))
513 impl tr for ty::FreeRegion {
514 fn tr(&self, dcx: &DecodeContext) -> ty::FreeRegion {
515 ty::FreeRegion { scope: self.scope.tr(dcx),
516 bound_region: self.bound_region.tr(dcx) }
520 impl tr for region::CodeExtent {
521 fn tr(&self, dcx: &DecodeContext) -> region::CodeExtent {
522 self.map_id(|id| dcx.tr_id(id))
526 impl tr for region::DestructionScopeData {
527 fn tr(&self, dcx: &DecodeContext) -> region::DestructionScopeData {
528 region::DestructionScopeData { node_id: dcx.tr_id(self.node_id) }
532 impl tr for ty::BoundRegion {
533 fn tr(&self, dcx: &DecodeContext) -> ty::BoundRegion {
538 ty::BrNamed(id, ident) => ty::BrNamed(dcx.tr_def_id(id),
544 // ______________________________________________________________________
545 // Encoding and decoding of freevar information
547 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
548 (*fv).encode(rbml_w).unwrap();
551 trait rbml_decoder_helper {
552 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
554 fn read_capture_mode(&mut self) -> ast::CaptureClause;
557 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
558 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
560 let fv: ty::Freevar = Decodable::decode(self).unwrap();
564 fn read_capture_mode(&mut self) -> ast::CaptureClause {
565 let cm: ast::CaptureClause = Decodable::decode(self).unwrap();
570 impl tr for ty::Freevar {
571 fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
573 def: self.def.tr(dcx),
574 span: self.span.tr(dcx),
579 impl tr for ty::UpvarBorrow {
580 fn tr(&self, dcx: &DecodeContext) -> ty::UpvarBorrow {
583 region: self.region.tr(dcx)
588 impl tr for ty::UpvarCapture {
589 fn tr(&self, dcx: &DecodeContext) -> ty::UpvarCapture {
591 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
592 ty::UpvarCapture::ByRef(ref data) => ty::UpvarCapture::ByRef(data.tr(dcx)),
597 // ______________________________________________________________________
598 // Encoding and decoding of MethodCallee
600 trait read_method_callee_helper<'tcx> {
601 fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
602 -> (u32, ty::MethodCallee<'tcx>);
605 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
606 rbml_w: &mut Encoder,
608 method: &ty::MethodCallee<'tcx>) {
609 use serialize::Encoder;
611 rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
612 rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
613 autoderef.encode(rbml_w)
615 rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
616 Ok(rbml_w.emit_def_id(method.def_id))
618 rbml_w.emit_struct_field("ty", 2, |rbml_w| {
619 Ok(rbml_w.emit_ty(ecx, method.ty))
621 rbml_w.emit_struct_field("substs", 3, |rbml_w| {
622 Ok(rbml_w.emit_substs(ecx, &method.substs))
627 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
628 fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
629 -> (u32, ty::MethodCallee<'tcx>) {
631 self.read_struct("MethodCallee", 4, |this| {
632 let autoderef = this.read_struct_field("autoderef", 0,
633 Decodable::decode).unwrap();
634 Ok((autoderef, ty::MethodCallee {
635 def_id: this.read_struct_field("def_id", 1, |this| {
636 Ok(this.read_def_id(dcx))
638 ty: this.read_struct_field("ty", 2, |this| {
639 Ok(this.read_ty(dcx))
641 substs: this.read_struct_field("substs", 3, |this| {
642 Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
649 pub fn encode_closure_kind(ebml_w: &mut Encoder, kind: ty::ClosureKind) {
650 kind.encode(ebml_w).unwrap();
653 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
654 kind.encode(ebml_w).unwrap();
657 pub trait vtable_decoder_helpers<'tcx> {
658 fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
659 F: FnMut(&mut Self) -> T;
662 impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> {
663 fn read_vec_per_param_space<T, F>(&mut self, mut f: F) -> VecPerParamSpace<T> where
664 F: FnMut(&mut reader::Decoder<'a>) -> T,
666 let types = self.read_to_vec(|this| Ok(f(this))).unwrap();
667 let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap();
668 let fns = self.read_to_vec(|this| Ok(f(this))).unwrap();
669 VecPerParamSpace::new(types, selfs, fns)
673 // ___________________________________________________________________________
676 fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder,
677 v: &subst::VecPerParamSpace<T>,
679 F: FnMut(&mut Encoder, &T),
681 for &space in &subst::ParamSpace::all() {
682 rbml_w.emit_from_vec(v.get_slice(space),
683 |rbml_w, n| Ok(f(rbml_w, n))).unwrap();
687 // ______________________________________________________________________
688 // Encoding and decoding the side tables
690 trait get_ty_str_ctxt<'tcx> {
691 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
694 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
695 fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
697 diag: self.tcx.sess.diagnostic(),
698 ds: e::def_to_string,
700 abbrevs: &self.type_abbrevs
705 trait rbml_writer_helpers<'tcx> {
706 fn emit_closure_type<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
707 closure_type: &ty::ClosureTy<'tcx>);
708 fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
709 fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
710 fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
711 type_param_def: &ty::TypeParameterDef<'tcx>);
712 fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
713 predicate: &ty::Predicate<'tcx>);
714 fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
715 ty: &ty::TraitRef<'tcx>);
716 fn emit_type_scheme<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
717 type_scheme: ty::TypeScheme<'tcx>);
718 fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
719 substs: &subst::Substs<'tcx>);
720 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
721 bounds: &ty::ExistentialBounds<'tcx>);
722 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
723 fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
724 adj: &ty::AutoAdjustment<'tcx>);
725 fn emit_autoref<'a>(&mut self, autoref: &ty::AutoRef<'tcx>);
726 fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
727 auto_deref_ref: &ty::AutoDerefRef<'tcx>);
730 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
731 fn emit_closure_type<'b>(&mut self,
732 ecx: &e::EncodeContext<'b, 'tcx>,
733 closure_type: &ty::ClosureTy<'tcx>) {
734 self.emit_opaque(|this| {
735 Ok(e::write_closure_type(ecx, this, closure_type))
739 fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
740 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
743 fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
744 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
747 fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
748 trait_ref: &ty::TraitRef<'tcx>) {
749 self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
752 fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
753 type_param_def: &ty::TypeParameterDef<'tcx>) {
754 self.emit_opaque(|this| {
755 Ok(tyencode::enc_type_param_def(this,
761 fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
762 predicate: &ty::Predicate<'tcx>) {
763 self.emit_opaque(|this| {
764 Ok(tyencode::enc_predicate(this,
770 fn emit_type_scheme<'b>(&mut self,
771 ecx: &e::EncodeContext<'b, 'tcx>,
772 type_scheme: ty::TypeScheme<'tcx>) {
773 use serialize::Encoder;
775 self.emit_struct("TypeScheme", 2, |this| {
776 this.emit_struct_field("generics", 0, |this| {
777 this.emit_struct("Generics", 2, |this| {
778 this.emit_struct_field("types", 0, |this| {
779 Ok(encode_vec_per_param_space(
780 this, &type_scheme.generics.types,
781 |this, def| this.emit_type_param_def(ecx, def)))
783 this.emit_struct_field("regions", 1, |this| {
784 Ok(encode_vec_per_param_space(
785 this, &type_scheme.generics.regions,
786 |this, def| def.encode(this).unwrap()))
790 this.emit_struct_field("ty", 1, |this| {
791 Ok(this.emit_ty(ecx, type_scheme.ty))
796 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
797 bounds: &ty::ExistentialBounds<'tcx>) {
798 self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
803 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
804 self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
809 fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
810 substs: &subst::Substs<'tcx>) {
811 self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
816 fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
817 adj: &ty::AutoAdjustment<'tcx>) {
818 use serialize::Encoder;
820 self.emit_enum("AutoAdjustment", |this| {
822 ty::AdjustReifyFnPointer=> {
823 this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
826 ty::AdjustUnsafeFnPointer => {
827 this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
832 ty::AdjustDerefRef(ref auto_deref_ref) => {
833 this.emit_enum_variant("AdjustDerefRef", 3, 2, |this| {
834 this.emit_enum_variant_arg(0,
835 |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
842 fn emit_autoref<'b>(&mut self, autoref: &ty::AutoRef<'tcx>) {
843 use serialize::Encoder;
845 self.emit_enum("AutoRef", |this| {
847 &ty::AutoPtr(r, m) => {
848 this.emit_enum_variant("AutoPtr", 0, 2, |this| {
849 this.emit_enum_variant_arg(0, |this| r.encode(this));
850 this.emit_enum_variant_arg(1, |this| m.encode(this))
853 &ty::AutoUnsafe(m) => {
854 this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
855 this.emit_enum_variant_arg(0, |this| m.encode(this))
862 fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
863 auto_deref_ref: &ty::AutoDerefRef<'tcx>) {
864 use serialize::Encoder;
866 self.emit_struct("AutoDerefRef", 2, |this| {
867 this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
869 this.emit_struct_field("autoref", 1, |this| {
870 this.emit_option(|this| {
871 match auto_deref_ref.autoref {
872 None => this.emit_option_none(),
873 Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(a))),
878 this.emit_struct_field("unsize", 2, |this| {
879 this.emit_option(|this| {
880 match auto_deref_ref.unsize {
881 None => this.emit_option_none(),
882 Some(target) => this.emit_option_some(|this| {
883 Ok(this.emit_ty(ecx, target))
892 trait write_tag_and_id {
893 fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
894 fn id(&mut self, id: ast::NodeId);
897 impl<'a> write_tag_and_id for Encoder<'a> {
899 tag_id: c::astencode_tag,
901 F: FnOnce(&mut Encoder<'a>),
903 self.start_tag(tag_id as usize);
908 fn id(&mut self, id: ast::NodeId) {
909 id.encode(self).unwrap();
913 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
914 ecx: &'a e::EncodeContext<'c, 'tcx>,
915 rbml_w: &'a mut Encoder<'b>,
918 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
919 SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
920 fn visit_id(&mut self, id: ast::NodeId) {
921 encode_side_tables_for_id(self.ecx, self.rbml_w, id)
925 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
926 rbml_w: &mut Encoder,
927 ii: &ast::InlinedItem) {
928 rbml_w.start_tag(c::tag_table as usize);
929 ast_util::visit_ids_for_inlined_item(ii, &mut SideTableEncodingIdVisitor {
936 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
937 rbml_w: &mut Encoder,
941 debug!("Encoding side tables for id {}", id);
943 if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
944 rbml_w.tag(c::tag_table_def, |rbml_w| {
946 def.encode(rbml_w).unwrap();
950 if let Some(ty) = tcx.node_types().get(&id) {
951 rbml_w.tag(c::tag_table_node_type, |rbml_w| {
953 rbml_w.emit_ty(ecx, *ty);
957 if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
958 rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
960 rbml_w.emit_substs(ecx, &item_substs.substs);
964 if let Some(fv) = tcx.freevars.borrow().get(&id) {
965 rbml_w.tag(c::tag_table_freevars, |rbml_w| {
967 rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
968 Ok(encode_freevar_entry(rbml_w, fv_entry))
973 rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
976 let var_id = freevar.def.def_id().node;
977 let upvar_id = ty::UpvarId {
981 let upvar_capture = tcx.tables
987 var_id.encode(rbml_w);
988 upvar_capture.encode(rbml_w);
993 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
994 if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
995 rbml_w.tag(c::tag_table_tcache, |rbml_w| {
997 rbml_w.emit_type_scheme(ecx, type_scheme.clone());
1001 if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
1002 rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
1004 rbml_w.emit_type_param_def(ecx, type_param_def)
1008 let method_call = ty::MethodCall::expr(id);
1009 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
1010 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1012 encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
1016 if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
1018 ty::AdjustDerefRef(ref adj) => {
1019 for autoderef in 0..adj.autoderefs {
1020 let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
1021 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
1022 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1024 encode_method_callee(ecx, rbml_w,
1025 method_call.autoderef, method)
1033 rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
1035 rbml_w.emit_auto_adjustment(ecx, adjustment);
1039 if let Some(closure_type) = tcx.tables.borrow().closure_tys.get(&ast_util::local_def(id)) {
1040 rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
1042 rbml_w.emit_closure_type(ecx, closure_type);
1046 if let Some(closure_kind) = tcx.tables.borrow().closure_kinds.get(&ast_util::local_def(id)) {
1047 rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
1049 encode_closure_kind(rbml_w, *closure_kind)
1053 if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
1054 rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
1056 encode_cast_kind(rbml_w, *cast_kind)
1060 if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
1061 rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
1063 qualif.encode(rbml_w).unwrap()
1068 trait doc_decoder_helpers {
1069 fn as_int(&self) -> isize;
1070 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1073 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
1074 fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
1075 fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
1076 reader::maybe_get_doc(*self, tag as usize)
1080 trait rbml_decoder_decoder_helpers<'tcx> {
1081 fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
1082 fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
1083 fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1084 -> ty::TraitRef<'tcx>;
1085 fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1086 -> ty::PolyTraitRef<'tcx>;
1087 fn read_type_param_def<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1088 -> ty::TypeParameterDef<'tcx>;
1089 fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1090 -> ty::Predicate<'tcx>;
1091 fn read_type_scheme<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1092 -> ty::TypeScheme<'tcx>;
1093 fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1094 -> ty::ExistentialBounds<'tcx>;
1095 fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1096 -> subst::Substs<'tcx>;
1097 fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1098 -> ty::AutoAdjustment<'tcx>;
1099 fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1101 fn read_closure_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1103 fn read_closure_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1104 -> ty::ClosureTy<'tcx>;
1105 fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1106 -> ty::AutoDerefRef<'tcx>;
1107 fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1108 -> ty::AutoRef<'tcx>;
1109 fn convert_def_id(&mut self,
1110 dcx: &DecodeContext,
1111 source: DefIdSource,
1115 // Versions of the type reading functions that don't need the full
1117 fn read_ty_nodcx(&mut self,
1118 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
1119 fn read_tys_nodcx(&mut self,
1120 tcx: &ty::ctxt<'tcx>,
1121 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
1122 fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
1123 cdata: &cstore::crate_metadata)
1124 -> subst::Substs<'tcx>;
1127 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
1128 fn read_ty_nodcx(&mut self,
1129 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx> {
1130 self.read_opaque(|_, doc| {
1131 Ok(tydecode::parse_ty_data(
1136 |_, id| decoder::translate_def_id(cdata, id)))
1140 fn read_tys_nodcx(&mut self,
1141 tcx: &ty::ctxt<'tcx>,
1142 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
1143 self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
1149 fn read_substs_nodcx(&mut self,
1150 tcx: &ty::ctxt<'tcx>,
1151 cdata: &cstore::crate_metadata)
1152 -> subst::Substs<'tcx>
1154 self.read_opaque(|_, doc| {
1155 Ok(tydecode::parse_substs_data(
1160 |_, id| decoder::translate_def_id(cdata, id)))
1164 fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1165 // Note: regions types embed local node ids. In principle, we
1166 // should translate these node ids into the new decode
1167 // context. However, we do not bother, because region types
1168 // are not used during trans.
1170 return self.read_opaque(|this, doc| {
1171 debug!("read_ty({})", type_string(doc));
1173 let ty = tydecode::parse_ty_data(
1178 |s, a| this.convert_def_id(dcx, s, a));
1183 fn type_string(doc: rbml::Doc) -> String {
1184 let mut str = String::new();
1185 for i in doc.start..doc.end {
1186 str.push(doc.data[i] as char);
1192 fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1194 self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1197 fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1198 -> ty::TraitRef<'tcx> {
1199 self.read_opaque(|this, doc| {
1200 let ty = tydecode::parse_trait_ref_data(
1205 |s, a| this.convert_def_id(dcx, s, a));
1210 fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1211 -> ty::PolyTraitRef<'tcx> {
1212 ty::Binder(self.read_opaque(|this, doc| {
1213 let ty = tydecode::parse_trait_ref_data(
1218 |s, a| this.convert_def_id(dcx, s, a));
1223 fn read_type_param_def<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1224 -> ty::TypeParameterDef<'tcx> {
1225 self.read_opaque(|this, doc| {
1226 Ok(tydecode::parse_type_param_def_data(
1231 |s, a| this.convert_def_id(dcx, s, a)))
1235 fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1236 -> ty::Predicate<'tcx>
1238 self.read_opaque(|this, doc| {
1239 Ok(tydecode::parse_predicate_data(doc.data, doc.start, dcx.cdata.cnum, dcx.tcx,
1240 |s, a| this.convert_def_id(dcx, s, a)))
1244 fn read_type_scheme<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1245 -> ty::TypeScheme<'tcx> {
1246 self.read_struct("TypeScheme", 3, |this| {
1248 generics: this.read_struct_field("generics", 0, |this| {
1249 this.read_struct("Generics", 2, |this| {
1252 this.read_struct_field("types", 0, |this| {
1253 Ok(this.read_vec_per_param_space(
1254 |this| this.read_type_param_def(dcx)))
1258 this.read_struct_field("regions", 1, |this| {
1259 Ok(this.read_vec_per_param_space(
1260 |this| Decodable::decode(this).unwrap()))
1265 ty: this.read_struct_field("ty", 1, |this| {
1266 Ok(this.read_ty(dcx))
1272 fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1273 -> ty::ExistentialBounds<'tcx>
1275 self.read_opaque(|this, doc| {
1276 Ok(tydecode::parse_existential_bounds_data(doc.data,
1280 |s, a| this.convert_def_id(dcx, s, a)))
1284 fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1285 -> subst::Substs<'tcx> {
1286 self.read_opaque(|this, doc| {
1287 Ok(tydecode::parse_substs_data(doc.data,
1291 |s, a| this.convert_def_id(dcx, s, a)))
1295 fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1296 -> ty::AutoAdjustment<'tcx> {
1297 self.read_enum("AutoAdjustment", |this| {
1298 let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer", "AdjustDerefRef"];
1299 this.read_enum_variant(&variants, |this, i| {
1301 1 => ty::AdjustReifyFnPointer,
1302 2 => ty::AdjustUnsafeFnPointer,
1304 let auto_deref_ref: ty::AutoDerefRef =
1305 this.read_enum_variant_arg(0,
1306 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1308 ty::AdjustDerefRef(auto_deref_ref)
1310 _ => panic!("bad enum variant for ty::AutoAdjustment")
1316 fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1317 -> ty::AutoDerefRef<'tcx> {
1318 self.read_struct("AutoDerefRef", 2, |this| {
1319 Ok(ty::AutoDerefRef {
1320 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1321 Decodable::decode(this)
1323 autoref: this.read_struct_field("autoref", 1, |this| {
1324 this.read_option(|this, b| {
1326 Ok(Some(this.read_autoref(dcx)))
1332 unsize: this.read_struct_field("unsize", 2, |this| {
1333 this.read_option(|this, b| {
1335 Ok(Some(this.read_ty(dcx)))
1345 fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1346 -> ty::AutoRef<'tcx> {
1347 self.read_enum("AutoRef", |this| {
1348 let variants = ["AutoPtr", "AutoUnsafe"];
1349 this.read_enum_variant(&variants, |this, i| {
1353 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1354 let m: ast::Mutability =
1355 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1357 ty::AutoPtr(dcx.tcx.mk_region(r.tr(dcx)), m)
1360 let m: ast::Mutability =
1361 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1365 _ => panic!("bad enum variant for ty::AutoRef")
1371 fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1374 Decodable::decode(self).unwrap()
1377 fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1380 Decodable::decode(self).unwrap()
1383 fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1384 -> ty::ClosureTy<'tcx>
1386 self.read_opaque(|this, doc| {
1387 Ok(tydecode::parse_ty_closure_data(
1392 |s, a| this.convert_def_id(dcx, s, a)))
1396 /// Converts a def-id that appears in a type. The correct
1397 /// translation will depend on what kind of def-id this is.
1398 /// This is a subtle point: type definitions are not
1399 /// inlined into the current crate, so if the def-id names
1400 /// a nominal type or type alias, then it should be
1401 /// translated to refer to the source crate.
1403 /// However, *type parameters* are cloned along with the function
1404 /// they are attached to. So we should translate those def-ids
1405 /// to refer to the new, cloned copy of the type parameter.
1406 /// We only see references to free type parameters in the body of
1407 /// an inlined function. In such cases, we need the def-id to
1408 /// be a local id so that the TypeContents code is able to lookup
1409 /// the relevant info in the ty_param_defs table.
1411 /// *Region parameters*, unfortunately, are another kettle of fish.
1412 /// In such cases, def_id's can appear in types to distinguish
1413 /// shadowed bound regions and so forth. It doesn't actually
1414 /// matter so much what we do to these, since regions are erased
1415 /// at trans time, but it's good to keep them consistent just in
1416 /// case. We translate them with `tr_def_id()` which will map
1417 /// the crate numbers back to the original source crate.
1419 /// Unboxed closures are cloned along with the function being
1420 /// inlined, and all side tables use interned node IDs, so we
1421 /// translate their def IDs accordingly.
1423 /// It'd be really nice to refactor the type repr to not include
1424 /// def-ids so that all these distinctions were unnecessary.
1425 fn convert_def_id(&mut self,
1426 dcx: &DecodeContext,
1427 source: tydecode::DefIdSource,
1430 let r = match source {
1431 NominalType | TypeWithId | RegionParameter => dcx.tr_def_id(did),
1432 ClosureSource => dcx.tr_intern_def_id(did)
1434 debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1439 fn decode_side_tables(dcx: &DecodeContext,
1440 ast_doc: rbml::Doc) {
1441 let tbl_doc = ast_doc.get(c::tag_table as usize);
1442 for (tag, entry_doc) in reader::docs(tbl_doc) {
1443 let mut entry_dsr = reader::Decoder::new(entry_doc);
1444 let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1445 let id = dcx.tr_id(id0);
1447 debug!(">> Side table document with tag 0x{:x} \
1448 found for id {} (orig {})",
1450 let tag = tag as u32;
1451 let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1455 &format!("unknown tag found in side tables: {:x}",
1459 let val_dsr = &mut entry_dsr;
1462 c::tag_table_def => {
1463 let def = decode_def(dcx, val_dsr);
1464 dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
1466 // This doesn't matter cross-crate.
1467 last_private: LastMod(AllPublic),
1471 c::tag_table_node_type => {
1472 let ty = val_dsr.read_ty(dcx);
1473 debug!("inserting ty for node {}: {:?}",
1475 dcx.tcx.node_type_insert(id, ty);
1477 c::tag_table_item_subst => {
1478 let item_substs = ty::ItemSubsts {
1479 substs: val_dsr.read_substs(dcx)
1481 dcx.tcx.tables.borrow_mut().item_substs.insert(
1484 c::tag_table_freevars => {
1485 let fv_info = val_dsr.read_to_vec(|val_dsr| {
1486 Ok(val_dsr.read_freevar_entry(dcx))
1487 }).unwrap().into_iter().collect();
1488 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1490 c::tag_table_upvar_capture_map => {
1491 let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1492 let upvar_id = ty::UpvarId {
1493 var_id: dcx.tr_id(var_id),
1496 let ub: ty::UpvarCapture = Decodable::decode(val_dsr).unwrap();
1497 dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub.tr(dcx));
1499 c::tag_table_tcache => {
1500 let type_scheme = val_dsr.read_type_scheme(dcx);
1501 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1502 dcx.tcx.register_item_type(lid, type_scheme);
1504 c::tag_table_param_defs => {
1505 let bounds = val_dsr.read_type_param_def(dcx);
1506 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1508 c::tag_table_method_map => {
1509 let (autoderef, method) = val_dsr.read_method_callee(dcx);
1510 let method_call = ty::MethodCall {
1512 autoderef: autoderef
1514 dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1516 c::tag_table_adjustments => {
1517 let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(dcx);
1518 dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1520 c::tag_table_closure_tys => {
1522 val_dsr.read_closure_ty(dcx);
1523 dcx.tcx.tables.borrow_mut().closure_tys.insert(ast_util::local_def(id),
1526 c::tag_table_closure_kinds => {
1528 val_dsr.read_closure_kind(dcx);
1529 dcx.tcx.tables.borrow_mut().closure_kinds.insert(ast_util::local_def(id),
1532 c::tag_table_cast_kinds => {
1534 val_dsr.read_cast_kind(dcx);
1535 dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1537 c::tag_table_const_qualif => {
1538 let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1539 dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1543 &format!("unknown tag found in side tables: {:x}",
1550 debug!(">< Side table doc loaded");
1554 // ______________________________________________________________________
1555 // Testing of astencode_gen
1558 fn encode_item_ast(rbml_w: &mut Encoder, item: &ast::Item) {
1559 rbml_w.start_tag(c::tag_tree as usize);
1560 (*item).encode(rbml_w);
1565 fn decode_item_ast(par_doc: rbml::Doc) -> ast::Item {
1566 let chi_doc = par_doc.get(c::tag_tree as usize);
1567 let mut d = reader::Decoder::new(chi_doc);
1568 Decodable::decode(&mut d).unwrap()
1573 fn call_site(&self) -> codemap::Span;
1574 fn cfg(&self) -> ast::CrateConfig;
1575 fn ident_of(&self, st: &str) -> ast::Ident;
1576 fn name_of(&self, st: &str) -> ast::Name;
1577 fn parse_sess(&self) -> &parse::ParseSess;
1581 impl FakeExtCtxt for parse::ParseSess {
1582 fn call_site(&self) -> codemap::Span {
1584 lo: codemap::BytePos(0),
1585 hi: codemap::BytePos(0),
1586 expn_id: codemap::NO_EXPANSION,
1589 fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1590 fn ident_of(&self, st: &str) -> ast::Ident {
1591 parse::token::str_to_ident(st)
1593 fn name_of(&self, st: &str) -> ast::Name {
1594 parse::token::intern(st)
1596 fn parse_sess(&self) -> &parse::ParseSess { self }
1600 fn mk_ctxt() -> parse::ParseSess {
1601 parse::ParseSess::new()
1605 fn roundtrip(in_item: Option<P<ast::Item>>) {
1606 let in_item = in_item.unwrap();
1607 let mut wr = Cursor::new(Vec::new());
1608 encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
1609 let rbml_doc = rbml::Doc::new(wr.get_ref());
1610 let out_item = decode_item_ast(rbml_doc);
1612 assert!(*in_item == out_item);
1618 roundtrip(quote_item!(&cx,
1624 fn test_smalltalk() {
1626 roundtrip(quote_item!(&cx,
1627 fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1634 roundtrip(quote_item!(&cx,
1635 fn foo(x: usize, y: usize) -> usize {
1643 fn test_simplification() {
1645 let item = quote_item!(&cx,
1646 fn new_int_alist<B>() -> alist<isize, B> {
1647 fn eq_int(a: isize, b: isize) -> bool { a == b }
1648 return alist {eq_fn: eq_int, data: Vec::new()};
1651 let item_in = e::IIItemRef(&*item);
1652 let item_out = simplify_ast(item_in);
1653 let item_exp = ast::IIItem(quote_item!(&cx,
1654 fn new_int_alist<B>() -> alist<isize, B> {
1655 return alist {eq_fn: eq_int, data: Vec::new()};
1658 match (item_out, item_exp) {
1659 (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
1660 assert!(pprust::item_to_string(&*item_out) ==
1661 pprust::item_to_string(&*item_exp));