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) => def::DefMethod(did.tr(dcx)),
448 def::DefSelfTy(opt_did, impl_ids) => { def::DefSelfTy(opt_did.map(|did| did.tr(dcx)),
449 impl_ids.map(|(nid1, nid2)| {
453 def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
454 def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
455 def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
456 def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
457 def::DefAssociatedConst(did) => def::DefAssociatedConst(did.tr(dcx)),
458 def::DefLocal(nid) => { def::DefLocal(dcx.tr_id(nid)) }
459 def::DefVariant(e_did, v_did, is_s) => {
460 def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
462 def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
463 def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
464 def::DefAssociatedTy(trait_did, did) =>
465 def::DefAssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
466 def::DefPrimTy(p) => def::DefPrimTy(p),
467 def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
468 def::DefUse(did) => def::DefUse(did.tr(dcx)),
469 def::DefUpvar(nid1, nid2) => {
470 def::DefUpvar(dcx.tr_id(nid1), dcx.tr_id(nid2))
472 def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
473 def::DefRegion(nid) => def::DefRegion(dcx.tr_id(nid)),
474 def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
479 // ______________________________________________________________________
480 // Encoding and decoding of ancillary information
482 impl tr for ty::Region {
483 fn tr(&self, dcx: &DecodeContext) -> ty::Region {
485 ty::ReLateBound(debruijn, br) => {
486 ty::ReLateBound(debruijn, br.tr(dcx))
488 ty::ReEarlyBound(data) => {
489 ty::ReEarlyBound(ty::EarlyBoundRegion {
490 param_id: dcx.tr_id(data.param_id),
496 ty::ReScope(scope) => {
497 ty::ReScope(scope.tr(dcx))
499 ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => {
502 ty::ReFree(ref fr) => {
503 ty::ReFree(fr.tr(dcx))
509 impl tr for ty::FreeRegion {
510 fn tr(&self, dcx: &DecodeContext) -> ty::FreeRegion {
511 ty::FreeRegion { scope: self.scope.tr(dcx),
512 bound_region: self.bound_region.tr(dcx) }
516 impl tr for region::CodeExtent {
517 fn tr(&self, dcx: &DecodeContext) -> region::CodeExtent {
518 self.map_id(|id| dcx.tr_id(id))
522 impl tr for region::DestructionScopeData {
523 fn tr(&self, dcx: &DecodeContext) -> region::DestructionScopeData {
524 region::DestructionScopeData { node_id: dcx.tr_id(self.node_id) }
528 impl tr for ty::BoundRegion {
529 fn tr(&self, dcx: &DecodeContext) -> ty::BoundRegion {
534 ty::BrNamed(id, ident) => ty::BrNamed(dcx.tr_def_id(id),
540 // ______________________________________________________________________
541 // Encoding and decoding of freevar information
543 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
544 (*fv).encode(rbml_w).unwrap();
547 trait rbml_decoder_helper {
548 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
550 fn read_capture_mode(&mut self) -> ast::CaptureClause;
553 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
554 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
556 let fv: ty::Freevar = Decodable::decode(self).unwrap();
560 fn read_capture_mode(&mut self) -> ast::CaptureClause {
561 let cm: ast::CaptureClause = Decodable::decode(self).unwrap();
566 impl tr for ty::Freevar {
567 fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
569 def: self.def.tr(dcx),
570 span: self.span.tr(dcx),
575 impl tr for ty::UpvarBorrow {
576 fn tr(&self, dcx: &DecodeContext) -> ty::UpvarBorrow {
579 region: self.region.tr(dcx)
584 impl tr for ty::UpvarCapture {
585 fn tr(&self, dcx: &DecodeContext) -> ty::UpvarCapture {
587 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
588 ty::UpvarCapture::ByRef(ref data) => ty::UpvarCapture::ByRef(data.tr(dcx)),
593 // ______________________________________________________________________
594 // Encoding and decoding of MethodCallee
596 trait read_method_callee_helper<'tcx> {
597 fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
598 -> (u32, ty::MethodCallee<'tcx>);
601 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
602 rbml_w: &mut Encoder,
604 method: &ty::MethodCallee<'tcx>) {
605 use serialize::Encoder;
607 rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
608 rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
609 autoderef.encode(rbml_w)
611 rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
612 Ok(rbml_w.emit_def_id(method.def_id))
614 rbml_w.emit_struct_field("ty", 2, |rbml_w| {
615 Ok(rbml_w.emit_ty(ecx, method.ty))
617 rbml_w.emit_struct_field("substs", 3, |rbml_w| {
618 Ok(rbml_w.emit_substs(ecx, &method.substs))
623 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
624 fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
625 -> (u32, ty::MethodCallee<'tcx>) {
627 self.read_struct("MethodCallee", 4, |this| {
628 let autoderef = this.read_struct_field("autoderef", 0,
629 Decodable::decode).unwrap();
630 Ok((autoderef, ty::MethodCallee {
631 def_id: this.read_struct_field("def_id", 1, |this| {
632 Ok(this.read_def_id(dcx))
634 ty: this.read_struct_field("ty", 2, |this| {
635 Ok(this.read_ty(dcx))
637 substs: this.read_struct_field("substs", 3, |this| {
638 Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
645 pub fn encode_closure_kind(ebml_w: &mut Encoder, kind: ty::ClosureKind) {
646 kind.encode(ebml_w).unwrap();
649 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
650 kind.encode(ebml_w).unwrap();
653 pub trait vtable_decoder_helpers<'tcx> {
654 fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
655 F: FnMut(&mut Self) -> T;
658 impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> {
659 fn read_vec_per_param_space<T, F>(&mut self, mut f: F) -> VecPerParamSpace<T> where
660 F: FnMut(&mut reader::Decoder<'a>) -> T,
662 let types = self.read_to_vec(|this| Ok(f(this))).unwrap();
663 let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap();
664 let fns = self.read_to_vec(|this| Ok(f(this))).unwrap();
665 VecPerParamSpace::new(types, selfs, fns)
669 // ___________________________________________________________________________
672 fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder,
673 v: &subst::VecPerParamSpace<T>,
675 F: FnMut(&mut Encoder, &T),
677 for &space in &subst::ParamSpace::all() {
678 rbml_w.emit_from_vec(v.get_slice(space),
679 |rbml_w, n| Ok(f(rbml_w, n))).unwrap();
683 // ______________________________________________________________________
684 // Encoding and decoding the side tables
686 trait get_ty_str_ctxt<'tcx> {
687 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
690 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
691 fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
693 diag: self.tcx.sess.diagnostic(),
694 ds: e::def_to_string,
696 abbrevs: &self.type_abbrevs
701 trait rbml_writer_helpers<'tcx> {
702 fn emit_closure_type<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
703 closure_type: &ty::ClosureTy<'tcx>);
704 fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
705 fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
706 fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
707 type_param_def: &ty::TypeParameterDef<'tcx>);
708 fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
709 predicate: &ty::Predicate<'tcx>);
710 fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
711 ty: &ty::TraitRef<'tcx>);
712 fn emit_type_scheme<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
713 type_scheme: ty::TypeScheme<'tcx>);
714 fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
715 substs: &subst::Substs<'tcx>);
716 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
717 bounds: &ty::ExistentialBounds<'tcx>);
718 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
719 fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
720 adj: &ty::AutoAdjustment<'tcx>);
721 fn emit_autoref<'a>(&mut self, autoref: &ty::AutoRef<'tcx>);
722 fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
723 auto_deref_ref: &ty::AutoDerefRef<'tcx>);
726 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
727 fn emit_closure_type<'b>(&mut self,
728 ecx: &e::EncodeContext<'b, 'tcx>,
729 closure_type: &ty::ClosureTy<'tcx>) {
730 self.emit_opaque(|this| {
731 Ok(e::write_closure_type(ecx, this, closure_type))
735 fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
736 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
739 fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
740 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
743 fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
744 trait_ref: &ty::TraitRef<'tcx>) {
745 self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
748 fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
749 type_param_def: &ty::TypeParameterDef<'tcx>) {
750 self.emit_opaque(|this| {
751 Ok(tyencode::enc_type_param_def(this,
757 fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
758 predicate: &ty::Predicate<'tcx>) {
759 self.emit_opaque(|this| {
760 Ok(tyencode::enc_predicate(this,
766 fn emit_type_scheme<'b>(&mut self,
767 ecx: &e::EncodeContext<'b, 'tcx>,
768 type_scheme: ty::TypeScheme<'tcx>) {
769 use serialize::Encoder;
771 self.emit_struct("TypeScheme", 2, |this| {
772 this.emit_struct_field("generics", 0, |this| {
773 this.emit_struct("Generics", 2, |this| {
774 this.emit_struct_field("types", 0, |this| {
775 Ok(encode_vec_per_param_space(
776 this, &type_scheme.generics.types,
777 |this, def| this.emit_type_param_def(ecx, def)))
779 this.emit_struct_field("regions", 1, |this| {
780 Ok(encode_vec_per_param_space(
781 this, &type_scheme.generics.regions,
782 |this, def| def.encode(this).unwrap()))
786 this.emit_struct_field("ty", 1, |this| {
787 Ok(this.emit_ty(ecx, type_scheme.ty))
792 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
793 bounds: &ty::ExistentialBounds<'tcx>) {
794 self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
799 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
800 self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
805 fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
806 substs: &subst::Substs<'tcx>) {
807 self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
812 fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
813 adj: &ty::AutoAdjustment<'tcx>) {
814 use serialize::Encoder;
816 self.emit_enum("AutoAdjustment", |this| {
818 ty::AdjustReifyFnPointer=> {
819 this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
822 ty::AdjustUnsafeFnPointer => {
823 this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
828 ty::AdjustDerefRef(ref auto_deref_ref) => {
829 this.emit_enum_variant("AdjustDerefRef", 3, 2, |this| {
830 this.emit_enum_variant_arg(0,
831 |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
838 fn emit_autoref<'b>(&mut self, autoref: &ty::AutoRef<'tcx>) {
839 use serialize::Encoder;
841 self.emit_enum("AutoRef", |this| {
843 &ty::AutoPtr(r, m) => {
844 this.emit_enum_variant("AutoPtr", 0, 2, |this| {
845 this.emit_enum_variant_arg(0, |this| r.encode(this));
846 this.emit_enum_variant_arg(1, |this| m.encode(this))
849 &ty::AutoUnsafe(m) => {
850 this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
851 this.emit_enum_variant_arg(0, |this| m.encode(this))
858 fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
859 auto_deref_ref: &ty::AutoDerefRef<'tcx>) {
860 use serialize::Encoder;
862 self.emit_struct("AutoDerefRef", 2, |this| {
863 this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
865 this.emit_struct_field("autoref", 1, |this| {
866 this.emit_option(|this| {
867 match auto_deref_ref.autoref {
868 None => this.emit_option_none(),
869 Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(a))),
874 this.emit_struct_field("unsize", 2, |this| {
875 this.emit_option(|this| {
876 match auto_deref_ref.unsize {
877 None => this.emit_option_none(),
878 Some(target) => this.emit_option_some(|this| {
879 Ok(this.emit_ty(ecx, target))
888 trait write_tag_and_id {
889 fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
890 fn id(&mut self, id: ast::NodeId);
893 impl<'a> write_tag_and_id for Encoder<'a> {
895 tag_id: c::astencode_tag,
897 F: FnOnce(&mut Encoder<'a>),
899 self.start_tag(tag_id as usize);
904 fn id(&mut self, id: ast::NodeId) {
905 id.encode(self).unwrap();
909 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
910 ecx: &'a e::EncodeContext<'c, 'tcx>,
911 rbml_w: &'a mut Encoder<'b>,
914 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
915 SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
916 fn visit_id(&mut self, id: ast::NodeId) {
917 encode_side_tables_for_id(self.ecx, self.rbml_w, id)
921 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
922 rbml_w: &mut Encoder,
923 ii: &ast::InlinedItem) {
924 rbml_w.start_tag(c::tag_table as usize);
925 ast_util::visit_ids_for_inlined_item(ii, &mut SideTableEncodingIdVisitor {
932 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
933 rbml_w: &mut Encoder,
937 debug!("Encoding side tables for id {}", id);
939 if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
940 rbml_w.tag(c::tag_table_def, |rbml_w| {
942 def.encode(rbml_w).unwrap();
946 if let Some(ty) = tcx.node_types().get(&id) {
947 rbml_w.tag(c::tag_table_node_type, |rbml_w| {
949 rbml_w.emit_ty(ecx, *ty);
953 if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
954 rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
956 rbml_w.emit_substs(ecx, &item_substs.substs);
960 if let Some(fv) = tcx.freevars.borrow().get(&id) {
961 rbml_w.tag(c::tag_table_freevars, |rbml_w| {
963 rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
964 Ok(encode_freevar_entry(rbml_w, fv_entry))
969 rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
972 let var_id = freevar.def.def_id().node;
973 let upvar_id = ty::UpvarId {
977 let upvar_capture = tcx.tables
983 var_id.encode(rbml_w);
984 upvar_capture.encode(rbml_w);
989 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
990 if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
991 rbml_w.tag(c::tag_table_tcache, |rbml_w| {
993 rbml_w.emit_type_scheme(ecx, type_scheme.clone());
997 if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
998 rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
1000 rbml_w.emit_type_param_def(ecx, type_param_def)
1004 let method_call = ty::MethodCall::expr(id);
1005 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
1006 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1008 encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
1012 if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
1014 ty::AdjustDerefRef(ref adj) => {
1015 for autoderef in 0..adj.autoderefs {
1016 let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
1017 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
1018 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1020 encode_method_callee(ecx, rbml_w,
1021 method_call.autoderef, method)
1029 rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
1031 rbml_w.emit_auto_adjustment(ecx, adjustment);
1035 if let Some(closure_type) = tcx.tables.borrow().closure_tys.get(&ast_util::local_def(id)) {
1036 rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
1038 rbml_w.emit_closure_type(ecx, closure_type);
1042 if let Some(closure_kind) = tcx.tables.borrow().closure_kinds.get(&ast_util::local_def(id)) {
1043 rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
1045 encode_closure_kind(rbml_w, *closure_kind)
1049 if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
1050 rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
1052 encode_cast_kind(rbml_w, *cast_kind)
1056 if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
1057 rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
1059 qualif.encode(rbml_w).unwrap()
1064 trait doc_decoder_helpers {
1065 fn as_int(&self) -> isize;
1066 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1069 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
1070 fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
1071 fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
1072 reader::maybe_get_doc(*self, tag as usize)
1076 trait rbml_decoder_decoder_helpers<'tcx> {
1077 fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
1078 fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
1079 fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1080 -> ty::TraitRef<'tcx>;
1081 fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1082 -> ty::PolyTraitRef<'tcx>;
1083 fn read_type_param_def<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1084 -> ty::TypeParameterDef<'tcx>;
1085 fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1086 -> ty::Predicate<'tcx>;
1087 fn read_type_scheme<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1088 -> ty::TypeScheme<'tcx>;
1089 fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1090 -> ty::ExistentialBounds<'tcx>;
1091 fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1092 -> subst::Substs<'tcx>;
1093 fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1094 -> ty::AutoAdjustment<'tcx>;
1095 fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1097 fn read_closure_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1099 fn read_closure_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1100 -> ty::ClosureTy<'tcx>;
1101 fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1102 -> ty::AutoDerefRef<'tcx>;
1103 fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1104 -> ty::AutoRef<'tcx>;
1105 fn convert_def_id(&mut self,
1106 dcx: &DecodeContext,
1107 source: DefIdSource,
1111 // Versions of the type reading functions that don't need the full
1113 fn read_ty_nodcx(&mut self,
1114 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
1115 fn read_tys_nodcx(&mut self,
1116 tcx: &ty::ctxt<'tcx>,
1117 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
1118 fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
1119 cdata: &cstore::crate_metadata)
1120 -> subst::Substs<'tcx>;
1123 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
1124 fn read_ty_nodcx(&mut self,
1125 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx> {
1126 self.read_opaque(|_, doc| {
1127 Ok(tydecode::parse_ty_data(
1132 |_, id| decoder::translate_def_id(cdata, id)))
1136 fn read_tys_nodcx(&mut self,
1137 tcx: &ty::ctxt<'tcx>,
1138 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
1139 self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
1145 fn read_substs_nodcx(&mut self,
1146 tcx: &ty::ctxt<'tcx>,
1147 cdata: &cstore::crate_metadata)
1148 -> subst::Substs<'tcx>
1150 self.read_opaque(|_, doc| {
1151 Ok(tydecode::parse_substs_data(
1156 |_, id| decoder::translate_def_id(cdata, id)))
1160 fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1161 // Note: regions types embed local node ids. In principle, we
1162 // should translate these node ids into the new decode
1163 // context. However, we do not bother, because region types
1164 // are not used during trans.
1166 return self.read_opaque(|this, doc| {
1167 debug!("read_ty({})", type_string(doc));
1169 let ty = tydecode::parse_ty_data(
1174 |s, a| this.convert_def_id(dcx, s, a));
1179 fn type_string(doc: rbml::Doc) -> String {
1180 let mut str = String::new();
1181 for i in doc.start..doc.end {
1182 str.push(doc.data[i] as char);
1188 fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1190 self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1193 fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1194 -> ty::TraitRef<'tcx> {
1195 self.read_opaque(|this, doc| {
1196 let ty = tydecode::parse_trait_ref_data(
1201 |s, a| this.convert_def_id(dcx, s, a));
1206 fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1207 -> ty::PolyTraitRef<'tcx> {
1208 ty::Binder(self.read_opaque(|this, doc| {
1209 let ty = tydecode::parse_trait_ref_data(
1214 |s, a| this.convert_def_id(dcx, s, a));
1219 fn read_type_param_def<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1220 -> ty::TypeParameterDef<'tcx> {
1221 self.read_opaque(|this, doc| {
1222 Ok(tydecode::parse_type_param_def_data(
1227 |s, a| this.convert_def_id(dcx, s, a)))
1231 fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1232 -> ty::Predicate<'tcx>
1234 self.read_opaque(|this, doc| {
1235 Ok(tydecode::parse_predicate_data(doc.data, doc.start, dcx.cdata.cnum, dcx.tcx,
1236 |s, a| this.convert_def_id(dcx, s, a)))
1240 fn read_type_scheme<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1241 -> ty::TypeScheme<'tcx> {
1242 self.read_struct("TypeScheme", 3, |this| {
1244 generics: this.read_struct_field("generics", 0, |this| {
1245 this.read_struct("Generics", 2, |this| {
1248 this.read_struct_field("types", 0, |this| {
1249 Ok(this.read_vec_per_param_space(
1250 |this| this.read_type_param_def(dcx)))
1254 this.read_struct_field("regions", 1, |this| {
1255 Ok(this.read_vec_per_param_space(
1256 |this| Decodable::decode(this).unwrap()))
1261 ty: this.read_struct_field("ty", 1, |this| {
1262 Ok(this.read_ty(dcx))
1268 fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1269 -> ty::ExistentialBounds<'tcx>
1271 self.read_opaque(|this, doc| {
1272 Ok(tydecode::parse_existential_bounds_data(doc.data,
1276 |s, a| this.convert_def_id(dcx, s, a)))
1280 fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1281 -> subst::Substs<'tcx> {
1282 self.read_opaque(|this, doc| {
1283 Ok(tydecode::parse_substs_data(doc.data,
1287 |s, a| this.convert_def_id(dcx, s, a)))
1291 fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1292 -> ty::AutoAdjustment<'tcx> {
1293 self.read_enum("AutoAdjustment", |this| {
1294 let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer", "AdjustDerefRef"];
1295 this.read_enum_variant(&variants, |this, i| {
1297 1 => ty::AdjustReifyFnPointer,
1298 2 => ty::AdjustUnsafeFnPointer,
1300 let auto_deref_ref: ty::AutoDerefRef =
1301 this.read_enum_variant_arg(0,
1302 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1304 ty::AdjustDerefRef(auto_deref_ref)
1306 _ => panic!("bad enum variant for ty::AutoAdjustment")
1312 fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1313 -> ty::AutoDerefRef<'tcx> {
1314 self.read_struct("AutoDerefRef", 2, |this| {
1315 Ok(ty::AutoDerefRef {
1316 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1317 Decodable::decode(this)
1319 autoref: this.read_struct_field("autoref", 1, |this| {
1320 this.read_option(|this, b| {
1322 Ok(Some(this.read_autoref(dcx)))
1328 unsize: this.read_struct_field("unsize", 2, |this| {
1329 this.read_option(|this, b| {
1331 Ok(Some(this.read_ty(dcx)))
1341 fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1342 -> ty::AutoRef<'tcx> {
1343 self.read_enum("AutoRef", |this| {
1344 let variants = ["AutoPtr", "AutoUnsafe"];
1345 this.read_enum_variant(&variants, |this, i| {
1349 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1350 let m: ast::Mutability =
1351 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1353 ty::AutoPtr(dcx.tcx.mk_region(r.tr(dcx)), m)
1356 let m: ast::Mutability =
1357 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1361 _ => panic!("bad enum variant for ty::AutoRef")
1367 fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1370 Decodable::decode(self).unwrap()
1373 fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1376 Decodable::decode(self).unwrap()
1379 fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1380 -> ty::ClosureTy<'tcx>
1382 self.read_opaque(|this, doc| {
1383 Ok(tydecode::parse_ty_closure_data(
1388 |s, a| this.convert_def_id(dcx, s, a)))
1392 /// Converts a def-id that appears in a type. The correct
1393 /// translation will depend on what kind of def-id this is.
1394 /// This is a subtle point: type definitions are not
1395 /// inlined into the current crate, so if the def-id names
1396 /// a nominal type or type alias, then it should be
1397 /// translated to refer to the source crate.
1399 /// However, *type parameters* are cloned along with the function
1400 /// they are attached to. So we should translate those def-ids
1401 /// to refer to the new, cloned copy of the type parameter.
1402 /// We only see references to free type parameters in the body of
1403 /// an inlined function. In such cases, we need the def-id to
1404 /// be a local id so that the TypeContents code is able to lookup
1405 /// the relevant info in the ty_param_defs table.
1407 /// *Region parameters*, unfortunately, are another kettle of fish.
1408 /// In such cases, def_id's can appear in types to distinguish
1409 /// shadowed bound regions and so forth. It doesn't actually
1410 /// matter so much what we do to these, since regions are erased
1411 /// at trans time, but it's good to keep them consistent just in
1412 /// case. We translate them with `tr_def_id()` which will map
1413 /// the crate numbers back to the original source crate.
1415 /// Unboxed closures are cloned along with the function being
1416 /// inlined, and all side tables use interned node IDs, so we
1417 /// translate their def IDs accordingly.
1419 /// It'd be really nice to refactor the type repr to not include
1420 /// def-ids so that all these distinctions were unnecessary.
1421 fn convert_def_id(&mut self,
1422 dcx: &DecodeContext,
1423 source: tydecode::DefIdSource,
1426 let r = match source {
1427 NominalType | TypeWithId | RegionParameter => dcx.tr_def_id(did),
1428 ClosureSource => dcx.tr_intern_def_id(did)
1430 debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1435 fn decode_side_tables(dcx: &DecodeContext,
1436 ast_doc: rbml::Doc) {
1437 let tbl_doc = ast_doc.get(c::tag_table as usize);
1438 for (tag, entry_doc) in reader::docs(tbl_doc) {
1439 let mut entry_dsr = reader::Decoder::new(entry_doc);
1440 let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1441 let id = dcx.tr_id(id0);
1443 debug!(">> Side table document with tag 0x{:x} \
1444 found for id {} (orig {})",
1446 let tag = tag as u32;
1447 let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1451 &format!("unknown tag found in side tables: {:x}",
1455 let val_dsr = &mut entry_dsr;
1458 c::tag_table_def => {
1459 let def = decode_def(dcx, val_dsr);
1460 dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
1462 // This doesn't matter cross-crate.
1463 last_private: LastMod(AllPublic),
1467 c::tag_table_node_type => {
1468 let ty = val_dsr.read_ty(dcx);
1469 debug!("inserting ty for node {}: {:?}",
1471 dcx.tcx.node_type_insert(id, ty);
1473 c::tag_table_item_subst => {
1474 let item_substs = ty::ItemSubsts {
1475 substs: val_dsr.read_substs(dcx)
1477 dcx.tcx.tables.borrow_mut().item_substs.insert(
1480 c::tag_table_freevars => {
1481 let fv_info = val_dsr.read_to_vec(|val_dsr| {
1482 Ok(val_dsr.read_freevar_entry(dcx))
1483 }).unwrap().into_iter().collect();
1484 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1486 c::tag_table_upvar_capture_map => {
1487 let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1488 let upvar_id = ty::UpvarId {
1489 var_id: dcx.tr_id(var_id),
1492 let ub: ty::UpvarCapture = Decodable::decode(val_dsr).unwrap();
1493 dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub.tr(dcx));
1495 c::tag_table_tcache => {
1496 let type_scheme = val_dsr.read_type_scheme(dcx);
1497 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1498 dcx.tcx.register_item_type(lid, type_scheme);
1500 c::tag_table_param_defs => {
1501 let bounds = val_dsr.read_type_param_def(dcx);
1502 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1504 c::tag_table_method_map => {
1505 let (autoderef, method) = val_dsr.read_method_callee(dcx);
1506 let method_call = ty::MethodCall {
1508 autoderef: autoderef
1510 dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1512 c::tag_table_adjustments => {
1513 let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(dcx);
1514 dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1516 c::tag_table_closure_tys => {
1518 val_dsr.read_closure_ty(dcx);
1519 dcx.tcx.tables.borrow_mut().closure_tys.insert(ast_util::local_def(id),
1522 c::tag_table_closure_kinds => {
1524 val_dsr.read_closure_kind(dcx);
1525 dcx.tcx.tables.borrow_mut().closure_kinds.insert(ast_util::local_def(id),
1528 c::tag_table_cast_kinds => {
1530 val_dsr.read_cast_kind(dcx);
1531 dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1533 c::tag_table_const_qualif => {
1534 let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1535 dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1539 &format!("unknown tag found in side tables: {:x}",
1546 debug!(">< Side table doc loaded");
1550 // ______________________________________________________________________
1551 // Testing of astencode_gen
1554 fn encode_item_ast(rbml_w: &mut Encoder, item: &ast::Item) {
1555 rbml_w.start_tag(c::tag_tree as usize);
1556 (*item).encode(rbml_w);
1561 fn decode_item_ast(par_doc: rbml::Doc) -> ast::Item {
1562 let chi_doc = par_doc.get(c::tag_tree as usize);
1563 let mut d = reader::Decoder::new(chi_doc);
1564 Decodable::decode(&mut d).unwrap()
1569 fn call_site(&self) -> codemap::Span;
1570 fn cfg(&self) -> ast::CrateConfig;
1571 fn ident_of(&self, st: &str) -> ast::Ident;
1572 fn name_of(&self, st: &str) -> ast::Name;
1573 fn parse_sess(&self) -> &parse::ParseSess;
1577 impl FakeExtCtxt for parse::ParseSess {
1578 fn call_site(&self) -> codemap::Span {
1580 lo: codemap::BytePos(0),
1581 hi: codemap::BytePos(0),
1582 expn_id: codemap::NO_EXPANSION,
1585 fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1586 fn ident_of(&self, st: &str) -> ast::Ident {
1587 parse::token::str_to_ident(st)
1589 fn name_of(&self, st: &str) -> ast::Name {
1590 parse::token::intern(st)
1592 fn parse_sess(&self) -> &parse::ParseSess { self }
1596 fn mk_ctxt() -> parse::ParseSess {
1597 parse::ParseSess::new()
1601 fn roundtrip(in_item: Option<P<ast::Item>>) {
1602 let in_item = in_item.unwrap();
1603 let mut wr = Cursor::new(Vec::new());
1604 encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
1605 let rbml_doc = rbml::Doc::new(wr.get_ref());
1606 let out_item = decode_item_ast(rbml_doc);
1608 assert!(*in_item == out_item);
1614 roundtrip(quote_item!(&cx,
1620 fn test_smalltalk() {
1622 roundtrip(quote_item!(&cx,
1623 fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1630 roundtrip(quote_item!(&cx,
1631 fn foo(x: usize, y: usize) -> usize {
1639 fn test_simplification() {
1641 let item = quote_item!(&cx,
1642 fn new_int_alist<B>() -> alist<isize, B> {
1643 fn eq_int(a: isize, b: isize) -> bool { a == b }
1644 return alist {eq_fn: eq_int, data: Vec::new()};
1647 let item_in = e::IIItemRef(&*item);
1648 let item_out = simplify_ast(item_in);
1649 let item_exp = ast::IIItem(quote_item!(&cx,
1650 fn new_int_alist<B>() -> alist<isize, B> {
1651 return alist {eq_fn: eq_int, data: Vec::new()};
1654 match (item_out, item_exp) {
1655 (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
1656 assert!(pprust::item_to_string(&*item_out) ==
1657 pprust::item_to_string(&*item_exp));