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::privacy::{AllPublic, LastMod};
32 use middle::subst::VecPerParamSpace;
33 use middle::ty::{self, Ty};
35 use syntax::{ast, ast_util, codemap, fold};
36 use syntax::codemap::Span;
37 use syntax::fold::Folder;
42 use std::io::SeekFrom;
43 use std::io::prelude::*;
47 use rbml::writer::Encoder;
50 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
51 use serialize::EncoderHelpers;
53 #[cfg(test)] use std::io::Cursor;
54 #[cfg(test)] use syntax::parse;
55 #[cfg(test)] use syntax::print::pprust;
57 struct DecodeContext<'a, 'b, 'tcx: 'a> {
58 tcx: &'a ty::ctxt<'tcx>,
59 cdata: &'b cstore::crate_metadata,
60 from_id_range: ast_util::IdRange,
61 to_id_range: ast_util::IdRange,
62 // Cache the last used filemap for translating spans as an optimization.
63 last_filemap_index: Cell<usize>,
67 fn tr(&self, dcx: &DecodeContext) -> Self;
71 fn tr_intern(&self, dcx: &DecodeContext) -> ast::DefId;
74 // ______________________________________________________________________
77 pub fn encode_inlined_item(ecx: &e::EncodeContext,
81 InlinedItemRef::Item(i) => i.id,
82 InlinedItemRef::Foreign(i) => i.id,
83 InlinedItemRef::TraitItem(_, ti) => ti.id,
84 InlinedItemRef::ImplItem(_, ii) => ii.id,
86 debug!("> Encoding inlined item: {} ({:?})",
87 ecx.tcx.map.path_to_string(id),
88 rbml_w.writer.seek(SeekFrom::Current(0)));
90 // Folding could be avoided with a smarter encoder.
91 let ii = simplify_ast(ii);
92 let id_range = ii.compute_id_range();
94 rbml_w.start_tag(c::tag_ast as usize);
95 id_range.encode(rbml_w);
96 encode_ast(rbml_w, &ii);
97 encode_side_tables_for_ii(ecx, rbml_w, &ii);
100 debug!("< Encoded inlined fn: {} ({:?})",
101 ecx.tcx.map.path_to_string(id),
102 rbml_w.writer.seek(SeekFrom::Current(0)));
105 impl<'a, 'b, 'c, 'tcx> ast_map::FoldOps for &'a DecodeContext<'b, 'c, 'tcx> {
106 fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
107 if id == ast::DUMMY_NODE_ID {
108 // Used by ast_map to map the NodeInlinedParent.
109 self.tcx.sess.next_node_id()
114 fn new_def_id(&self, def_id: ast::DefId) -> ast::DefId {
115 self.tr_def_id(def_id)
117 fn new_span(&self, span: Span) -> Span {
122 /// Decodes an item from its AST in the cdata's metadata and adds it to the
124 pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
125 tcx: &ty::ctxt<'tcx>,
126 path: Vec<ast_map::PathElem>,
128 -> Result<&'tcx InlinedItem, Vec<ast_map::PathElem>> {
129 match par_doc.opt_child(c::tag_ast) {
132 let mut path_as_str = None;
133 debug!("> Decoding inlined fn: {:?}::?",
135 // Do an Option dance to use the path after it is moved below.
136 let s = ast_map::path_to_string(path.iter().cloned());
137 path_as_str = Some(s);
138 path_as_str.as_ref().map(|x| &x[..])
140 let mut ast_dsr = reader::Decoder::new(ast_doc);
141 let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
142 let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
143 let dcx = &DecodeContext {
146 from_id_range: from_id_range,
147 to_id_range: to_id_range,
148 last_filemap_index: Cell::new(0)
150 let raw_ii = decode_ast(ast_doc);
151 let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, raw_ii, dcx);
153 let ident = match *ii {
154 InlinedItem::Item(ref i) => i.ident,
155 InlinedItem::Foreign(ref i) => i.ident,
156 InlinedItem::TraitItem(_, ref ti) => ti.ident,
157 InlinedItem::ImplItem(_, ref ii) => ii.ident
159 debug!("Fn named: {}", ident);
160 debug!("< Decoded inlined fn: {}::{}",
161 path_as_str.unwrap(),
163 region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
164 decode_side_tables(dcx, ast_doc);
166 InlinedItem::Item(ref i) => {
167 debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
168 syntax::print::pprust::item_to_string(&**i));
177 // ______________________________________________________________________
178 // Enumerating the IDs which appear in an AST
180 fn reserve_id_range(sess: &Session,
181 from_id_range: ast_util::IdRange) -> ast_util::IdRange {
182 // Handle the case of an empty range:
183 if from_id_range.empty() { return from_id_range; }
184 let cnt = from_id_range.max - from_id_range.min;
185 let to_id_min = sess.reserve_node_ids(cnt);
186 let to_id_max = to_id_min + cnt;
187 ast_util::IdRange { min: to_id_min, max: to_id_max }
190 impl<'a, 'b, 'tcx> DecodeContext<'a, 'b, 'tcx> {
191 /// Translates an internal id, meaning a node id that is known to refer to some part of the
192 /// item currently being inlined, such as a local variable or argument. All naked node-ids
193 /// that appear in types have this property, since if something might refer to an external item
194 /// we would use a def-id to allow for the possibility that the item resides in another crate.
195 pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
196 // from_id_range should be non-empty
197 assert!(!self.from_id_range.empty());
198 // Use wrapping arithmetic because otherwise it introduces control flow.
199 // Maybe we should just have the control flow? -- aatch
200 (id.wrapping_sub(self.from_id_range.min).wrapping_add(self.to_id_range.min))
203 /// Translates an EXTERNAL def-id, converting the crate number from the one used in the encoded
204 /// data to the current crate numbers.. By external, I mean that it be translated to a
205 /// reference to the item in its original crate, as opposed to being translated to a reference
206 /// to the inlined version of the item. This is typically, but not always, what you want,
207 /// because most def-ids refer to external things like types or other fns that may or may not
208 /// be inlined. Note that even when the inlined function is referencing itself recursively, we
209 /// would want `tr_def_id` for that reference--- conceptually the function calls the original,
210 /// non-inlined version, and trans deals with linking that recursive call to the inlined copy.
212 /// However, there are a *few* cases where def-ids are used but we know that the thing being
213 /// referenced is in fact *internal* to the item being inlined. In those cases, you should use
214 /// `tr_intern_def_id()` below.
215 pub fn tr_def_id(&self, did: ast::DefId) -> ast::DefId {
217 decoder::translate_def_id(self.cdata, did)
220 /// Translates an INTERNAL def-id, meaning a def-id that is
221 /// known to refer to some part of the item currently being
222 /// inlined. In that case, we want to convert the def-id to
223 /// refer to the current crate and to the new, inlined node-id.
224 pub fn tr_intern_def_id(&self, did: ast::DefId) -> ast::DefId {
225 assert_eq!(did.krate, ast::LOCAL_CRATE);
226 ast::DefId { krate: ast::LOCAL_CRATE, node: self.tr_id(did.node) }
229 /// Translates a `Span` from an extern crate to the corresponding `Span`
230 /// within the local crate's codemap. `creader::import_codemap()` will
231 /// already have allocated any additionally needed FileMaps in the local
232 /// codemap as a side-effect of creating the crate_metadata's
233 /// `codemap_import_info`.
234 pub fn tr_span(&self, span: Span) -> Span {
235 let span = if span.lo > span.hi {
236 // Currently macro expansion sometimes produces invalid Span values
237 // where lo > hi. In order not to crash the compiler when trying to
238 // translate these values, let's transform them into something we
239 // can handle (and which will produce useful debug locations at
240 // least some of the time).
241 // This workaround is only necessary as long as macro expansion is
242 // not fixed. FIXME(#23480)
243 codemap::mk_sp(span.lo, span.lo)
248 let imported_filemaps = self.cdata.imported_filemaps(self.tcx.sess.codemap());
250 // Optimize for the case that most spans within a translated item
251 // originate from the same filemap.
252 let last_filemap_index = self.last_filemap_index.get();
253 let last_filemap = &imported_filemaps[last_filemap_index];
255 if span.lo >= last_filemap.original_start_pos &&
256 span.lo <= last_filemap.original_end_pos &&
257 span.hi >= last_filemap.original_start_pos &&
258 span.hi <= last_filemap.original_end_pos {
262 let mut b = imported_filemaps.len();
266 if imported_filemaps[m].original_start_pos > span.lo {
273 self.last_filemap_index.set(a);
274 &imported_filemaps[a]
278 let lo = (span.lo - filemap.original_start_pos) +
279 filemap.translated_filemap.start_pos;
280 let hi = (span.hi - filemap.original_start_pos) +
281 filemap.translated_filemap.start_pos;
283 codemap::mk_sp(lo, hi)
287 impl tr_intern for ast::DefId {
288 fn tr_intern(&self, dcx: &DecodeContext) -> ast::DefId {
289 dcx.tr_intern_def_id(*self)
293 impl tr for ast::DefId {
294 fn tr(&self, dcx: &DecodeContext) -> ast::DefId {
299 impl tr for Option<ast::DefId> {
300 fn tr(&self, dcx: &DecodeContext) -> Option<ast::DefId> {
301 self.map(|d| dcx.tr_def_id(d))
306 fn tr(&self, dcx: &DecodeContext) -> Span {
311 trait def_id_encoder_helpers {
312 fn emit_def_id(&mut self, did: ast::DefId);
315 impl<S:serialize::Encoder> def_id_encoder_helpers for S
316 where <S as serialize::serialize::Encoder>::Error: Debug
318 fn emit_def_id(&mut self, did: ast::DefId) {
319 did.encode(self).unwrap()
323 trait def_id_decoder_helpers {
324 fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId;
325 fn read_def_id_nodcx(&mut self,
326 cdata: &cstore::crate_metadata) -> ast::DefId;
329 impl<D:serialize::Decoder> def_id_decoder_helpers for D
330 where <D as serialize::serialize::Decoder>::Error: Debug
332 fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId {
333 let did: ast::DefId = Decodable::decode(self).unwrap();
337 fn read_def_id_nodcx(&mut self,
338 cdata: &cstore::crate_metadata)
340 let did: ast::DefId = Decodable::decode(self).unwrap();
341 decoder::translate_def_id(cdata, did)
345 // ______________________________________________________________________
346 // Encoding and decoding the AST itself
348 // When decoding, we have to renumber the AST so that the node ids that
349 // appear within are disjoint from the node ids in our existing ASTs.
350 // We also have to adjust the spans: for now we just insert a dummy span,
351 // but eventually we should add entries to the local codemap as required.
353 fn encode_ast(rbml_w: &mut Encoder, item: &InlinedItem) {
354 rbml_w.start_tag(c::tag_tree as usize);
359 struct NestedItemsDropper;
361 impl Folder for NestedItemsDropper {
362 fn fold_block(&mut self, blk: P<ast::Block>) -> P<ast::Block> {
363 blk.and_then(|ast::Block {id, stmts, expr, rules, span, ..}| {
364 let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
365 let use_stmt = match stmt.node {
366 ast::StmtExpr(_, _) | ast::StmtSemi(_, _) => true,
367 ast::StmtDecl(ref decl, _) => {
369 ast::DeclLocal(_) => true,
370 ast::DeclItem(_) => false,
373 ast::StmtMac(..) => panic!("unexpanded macro in astencode")
381 let blk_sans_items = P(ast::Block {
382 stmts: stmts_sans_items,
388 fold::noop_fold_block(blk_sans_items, self)
393 // Produces a simplified copy of the AST which does not include things
394 // that we do not need to or do not want to export. For example, we
395 // do not include any nested items: if these nested items are to be
396 // inlined, their AST will be exported separately (this only makes
397 // sense because, in Rust, nested items are independent except for
398 // their visibility).
400 // As it happens, trans relies on the fact that we do not export
401 // nested items, as otherwise it would get confused when translating
403 fn simplify_ast(ii: InlinedItemRef) -> InlinedItem {
404 let mut fld = NestedItemsDropper;
407 // HACK we're not dropping items.
408 InlinedItemRef::Item(i) => {
409 InlinedItem::Item(fold::noop_fold_item(P(i.clone()), &mut fld)
410 .expect_one("expected one item"))
412 InlinedItemRef::TraitItem(d, ti) => {
413 InlinedItem::TraitItem(d,
414 fold::noop_fold_trait_item(P(ti.clone()), &mut fld)
415 .expect_one("noop_fold_trait_item must produce \
416 exactly one trait item"))
418 InlinedItemRef::ImplItem(d, ii) => {
419 InlinedItem::ImplItem(d,
420 fold::noop_fold_impl_item(P(ii.clone()), &mut fld)
421 .expect_one("noop_fold_impl_item must produce \
422 exactly one impl item"))
424 InlinedItemRef::Foreign(i) => {
425 InlinedItem::Foreign(fold::noop_fold_foreign_item(P(i.clone()), &mut fld))
430 fn decode_ast(par_doc: rbml::Doc) -> InlinedItem {
431 let chi_doc = par_doc.get(c::tag_tree as usize);
432 let mut d = reader::Decoder::new(chi_doc);
433 Decodable::decode(&mut d).unwrap()
436 // ______________________________________________________________________
437 // Encoding and decoding of ast::def
439 fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> def::Def {
440 let def: def::Def = Decodable::decode(dsr).unwrap();
444 impl tr for def::Def {
445 fn tr(&self, dcx: &DecodeContext) -> def::Def {
447 def::DefFn(did, is_ctor) => def::DefFn(did.tr(dcx), is_ctor),
448 def::DefMethod(did) => def::DefMethod(did.tr(dcx)),
449 def::DefSelfTy(opt_did, impl_ids) => { def::DefSelfTy(opt_did.map(|did| did.tr(dcx)),
450 impl_ids.map(|(nid1, nid2)| {
454 def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
455 def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
456 def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
457 def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
458 def::DefAssociatedConst(did) => def::DefAssociatedConst(did.tr(dcx)),
459 def::DefLocal(nid) => { def::DefLocal(dcx.tr_id(nid)) }
460 def::DefVariant(e_did, v_did, is_s) => {
461 def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
463 def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
464 def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
465 def::DefAssociatedTy(trait_did, did) =>
466 def::DefAssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
467 def::DefPrimTy(p) => def::DefPrimTy(p),
468 def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
469 def::DefUse(did) => def::DefUse(did.tr(dcx)),
470 def::DefUpvar(nid1, nid2) => {
471 def::DefUpvar(dcx.tr_id(nid1), dcx.tr_id(nid2))
473 def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
474 def::DefRegion(nid) => def::DefRegion(dcx.tr_id(nid)),
475 def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
480 // ______________________________________________________________________
481 // Encoding and decoding of ancillary information
483 impl tr for ty::Region {
484 fn tr(&self, dcx: &DecodeContext) -> ty::Region {
486 ty::ReLateBound(debruijn, br) => {
487 ty::ReLateBound(debruijn, br.tr(dcx))
489 ty::ReEarlyBound(data) => {
490 ty::ReEarlyBound(ty::EarlyBoundRegion {
491 param_id: dcx.tr_id(data.param_id),
497 ty::ReScope(scope) => {
498 ty::ReScope(scope.tr(dcx))
500 ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => {
503 ty::ReFree(ref fr) => {
504 ty::ReFree(fr.tr(dcx))
510 impl tr for ty::FreeRegion {
511 fn tr(&self, dcx: &DecodeContext) -> ty::FreeRegion {
512 ty::FreeRegion { scope: self.scope.tr(dcx),
513 bound_region: self.bound_region.tr(dcx) }
517 impl tr for region::CodeExtent {
518 fn tr(&self, dcx: &DecodeContext) -> region::CodeExtent {
519 self.map_id(|id| dcx.tr_id(id))
523 impl tr for region::DestructionScopeData {
524 fn tr(&self, dcx: &DecodeContext) -> region::DestructionScopeData {
525 region::DestructionScopeData { node_id: dcx.tr_id(self.node_id) }
529 impl tr for ty::BoundRegion {
530 fn tr(&self, dcx: &DecodeContext) -> ty::BoundRegion {
535 ty::BrNamed(id, ident) => ty::BrNamed(dcx.tr_def_id(id),
541 // ______________________________________________________________________
542 // Encoding and decoding of freevar information
544 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
545 (*fv).encode(rbml_w).unwrap();
548 trait rbml_decoder_helper {
549 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
551 fn read_capture_mode(&mut self) -> ast::CaptureClause;
554 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
555 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
557 let fv: ty::Freevar = Decodable::decode(self).unwrap();
561 fn read_capture_mode(&mut self) -> ast::CaptureClause {
562 let cm: ast::CaptureClause = Decodable::decode(self).unwrap();
567 impl tr for ty::Freevar {
568 fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
570 def: self.def.tr(dcx),
571 span: self.span.tr(dcx),
576 impl tr for ty::UpvarBorrow {
577 fn tr(&self, dcx: &DecodeContext) -> ty::UpvarBorrow {
580 region: self.region.tr(dcx)
585 impl tr for ty::UpvarCapture {
586 fn tr(&self, dcx: &DecodeContext) -> ty::UpvarCapture {
588 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
589 ty::UpvarCapture::ByRef(ref data) => ty::UpvarCapture::ByRef(data.tr(dcx)),
594 // ______________________________________________________________________
595 // Encoding and decoding of MethodCallee
597 trait read_method_callee_helper<'tcx> {
598 fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
599 -> (u32, ty::MethodCallee<'tcx>);
602 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
603 rbml_w: &mut Encoder,
605 method: &ty::MethodCallee<'tcx>) {
606 use serialize::Encoder;
608 rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
609 rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
610 autoderef.encode(rbml_w)
612 rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
613 Ok(rbml_w.emit_def_id(method.def_id))
615 rbml_w.emit_struct_field("ty", 2, |rbml_w| {
616 Ok(rbml_w.emit_ty(ecx, method.ty))
618 rbml_w.emit_struct_field("substs", 3, |rbml_w| {
619 Ok(rbml_w.emit_substs(ecx, &method.substs))
624 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
625 fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
626 -> (u32, ty::MethodCallee<'tcx>) {
628 self.read_struct("MethodCallee", 4, |this| {
629 let autoderef = this.read_struct_field("autoderef", 0,
630 Decodable::decode).unwrap();
631 Ok((autoderef, ty::MethodCallee {
632 def_id: this.read_struct_field("def_id", 1, |this| {
633 Ok(this.read_def_id(dcx))
635 ty: this.read_struct_field("ty", 2, |this| {
636 Ok(this.read_ty(dcx))
638 substs: this.read_struct_field("substs", 3, |this| {
639 Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
646 pub fn encode_closure_kind(ebml_w: &mut Encoder, kind: ty::ClosureKind) {
647 kind.encode(ebml_w).unwrap();
650 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
651 kind.encode(ebml_w).unwrap();
654 pub trait vtable_decoder_helpers<'tcx> {
655 fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
656 F: FnMut(&mut Self) -> T;
659 impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> {
660 fn read_vec_per_param_space<T, F>(&mut self, mut f: F) -> VecPerParamSpace<T> where
661 F: FnMut(&mut reader::Decoder<'a>) -> T,
663 let types = self.read_to_vec(|this| Ok(f(this))).unwrap();
664 let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap();
665 let fns = self.read_to_vec(|this| Ok(f(this))).unwrap();
666 VecPerParamSpace::new(types, selfs, fns)
670 // ___________________________________________________________________________
673 fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder,
674 v: &subst::VecPerParamSpace<T>,
676 F: FnMut(&mut Encoder, &T),
678 for &space in &subst::ParamSpace::all() {
679 rbml_w.emit_from_vec(v.get_slice(space),
680 |rbml_w, n| Ok(f(rbml_w, n))).unwrap();
684 // ______________________________________________________________________
685 // Encoding and decoding the side tables
687 trait get_ty_str_ctxt<'tcx> {
688 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
691 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
692 fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
694 diag: self.tcx.sess.diagnostic(),
695 ds: e::def_to_string,
697 abbrevs: &self.type_abbrevs
702 trait rbml_writer_helpers<'tcx> {
703 fn emit_closure_type<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
704 closure_type: &ty::ClosureTy<'tcx>);
705 fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
706 fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
707 fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
708 type_param_def: &ty::TypeParameterDef<'tcx>);
709 fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
710 predicate: &ty::Predicate<'tcx>);
711 fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
712 ty: &ty::TraitRef<'tcx>);
713 fn emit_type_scheme<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
714 type_scheme: ty::TypeScheme<'tcx>);
715 fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
716 substs: &subst::Substs<'tcx>);
717 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
718 bounds: &ty::ExistentialBounds<'tcx>);
719 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
720 fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
721 adj: &ty::AutoAdjustment<'tcx>);
722 fn emit_autoref<'a>(&mut self, autoref: &ty::AutoRef<'tcx>);
723 fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
724 auto_deref_ref: &ty::AutoDerefRef<'tcx>);
727 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
728 fn emit_closure_type<'b>(&mut self,
729 ecx: &e::EncodeContext<'b, 'tcx>,
730 closure_type: &ty::ClosureTy<'tcx>) {
731 self.emit_opaque(|this| {
732 Ok(e::write_closure_type(ecx, this, closure_type))
736 fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
737 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
740 fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
741 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
744 fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
745 trait_ref: &ty::TraitRef<'tcx>) {
746 self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
749 fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
750 type_param_def: &ty::TypeParameterDef<'tcx>) {
751 self.emit_opaque(|this| {
752 Ok(tyencode::enc_type_param_def(this,
758 fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
759 predicate: &ty::Predicate<'tcx>) {
760 self.emit_opaque(|this| {
761 Ok(tyencode::enc_predicate(this,
767 fn emit_type_scheme<'b>(&mut self,
768 ecx: &e::EncodeContext<'b, 'tcx>,
769 type_scheme: ty::TypeScheme<'tcx>) {
770 use serialize::Encoder;
772 self.emit_struct("TypeScheme", 2, |this| {
773 this.emit_struct_field("generics", 0, |this| {
774 this.emit_struct("Generics", 2, |this| {
775 this.emit_struct_field("types", 0, |this| {
776 Ok(encode_vec_per_param_space(
777 this, &type_scheme.generics.types,
778 |this, def| this.emit_type_param_def(ecx, def)))
780 this.emit_struct_field("regions", 1, |this| {
781 Ok(encode_vec_per_param_space(
782 this, &type_scheme.generics.regions,
783 |this, def| def.encode(this).unwrap()))
787 this.emit_struct_field("ty", 1, |this| {
788 Ok(this.emit_ty(ecx, type_scheme.ty))
793 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
794 bounds: &ty::ExistentialBounds<'tcx>) {
795 self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
800 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
801 self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
806 fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
807 substs: &subst::Substs<'tcx>) {
808 self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
813 fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
814 adj: &ty::AutoAdjustment<'tcx>) {
815 use serialize::Encoder;
817 self.emit_enum("AutoAdjustment", |this| {
819 ty::AdjustReifyFnPointer=> {
820 this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
823 ty::AdjustUnsafeFnPointer => {
824 this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
829 ty::AdjustDerefRef(ref auto_deref_ref) => {
830 this.emit_enum_variant("AdjustDerefRef", 3, 2, |this| {
831 this.emit_enum_variant_arg(0,
832 |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
839 fn emit_autoref<'b>(&mut self, autoref: &ty::AutoRef<'tcx>) {
840 use serialize::Encoder;
842 self.emit_enum("AutoRef", |this| {
844 &ty::AutoPtr(r, m) => {
845 this.emit_enum_variant("AutoPtr", 0, 2, |this| {
846 this.emit_enum_variant_arg(0, |this| r.encode(this));
847 this.emit_enum_variant_arg(1, |this| m.encode(this))
850 &ty::AutoUnsafe(m) => {
851 this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
852 this.emit_enum_variant_arg(0, |this| m.encode(this))
859 fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
860 auto_deref_ref: &ty::AutoDerefRef<'tcx>) {
861 use serialize::Encoder;
863 self.emit_struct("AutoDerefRef", 2, |this| {
864 this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
866 this.emit_struct_field("autoref", 1, |this| {
867 this.emit_option(|this| {
868 match auto_deref_ref.autoref {
869 None => this.emit_option_none(),
870 Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(a))),
875 this.emit_struct_field("unsize", 2, |this| {
876 this.emit_option(|this| {
877 match auto_deref_ref.unsize {
878 None => this.emit_option_none(),
879 Some(target) => this.emit_option_some(|this| {
880 Ok(this.emit_ty(ecx, target))
889 trait write_tag_and_id {
890 fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
891 fn id(&mut self, id: ast::NodeId);
894 impl<'a> write_tag_and_id for Encoder<'a> {
896 tag_id: c::astencode_tag,
898 F: FnOnce(&mut Encoder<'a>),
900 self.start_tag(tag_id as usize);
905 fn id(&mut self, id: ast::NodeId) {
906 id.encode(self).unwrap();
910 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
911 ecx: &'a e::EncodeContext<'c, 'tcx>,
912 rbml_w: &'a mut Encoder<'b>,
915 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
916 SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
917 fn visit_id(&mut self, id: ast::NodeId) {
918 encode_side_tables_for_id(self.ecx, self.rbml_w, id)
922 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
923 rbml_w: &mut Encoder,
925 rbml_w.start_tag(c::tag_table as usize);
926 ii.visit_ids(&mut SideTableEncodingIdVisitor {
933 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
934 rbml_w: &mut Encoder,
938 debug!("Encoding side tables for id {}", id);
940 if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
941 rbml_w.tag(c::tag_table_def, |rbml_w| {
943 def.encode(rbml_w).unwrap();
947 if let Some(ty) = tcx.node_types().get(&id) {
948 rbml_w.tag(c::tag_table_node_type, |rbml_w| {
950 rbml_w.emit_ty(ecx, *ty);
954 if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
955 rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
957 rbml_w.emit_substs(ecx, &item_substs.substs);
961 if let Some(fv) = tcx.freevars.borrow().get(&id) {
962 rbml_w.tag(c::tag_table_freevars, |rbml_w| {
964 rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
965 Ok(encode_freevar_entry(rbml_w, fv_entry))
970 rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
973 let var_id = freevar.def.def_id().node;
974 let upvar_id = ty::UpvarId {
978 let upvar_capture = tcx.tables
984 var_id.encode(rbml_w);
985 upvar_capture.encode(rbml_w);
990 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
991 if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
992 rbml_w.tag(c::tag_table_tcache, |rbml_w| {
994 rbml_w.emit_type_scheme(ecx, type_scheme.clone());
998 if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
999 rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
1001 rbml_w.emit_type_param_def(ecx, type_param_def)
1005 let method_call = ty::MethodCall::expr(id);
1006 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
1007 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1009 encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
1013 if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
1015 ty::AdjustDerefRef(ref adj) => {
1016 for autoderef in 0..adj.autoderefs {
1017 let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
1018 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
1019 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1021 encode_method_callee(ecx, rbml_w,
1022 method_call.autoderef, method)
1030 rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
1032 rbml_w.emit_auto_adjustment(ecx, adjustment);
1036 if let Some(closure_type) = tcx.tables.borrow().closure_tys.get(&ast_util::local_def(id)) {
1037 rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
1039 rbml_w.emit_closure_type(ecx, closure_type);
1043 if let Some(closure_kind) = tcx.tables.borrow().closure_kinds.get(&ast_util::local_def(id)) {
1044 rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
1046 encode_closure_kind(rbml_w, *closure_kind)
1050 if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
1051 rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
1053 encode_cast_kind(rbml_w, *cast_kind)
1057 if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
1058 rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
1060 qualif.encode(rbml_w).unwrap()
1065 trait doc_decoder_helpers: Sized {
1066 fn as_int(&self) -> isize;
1067 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1070 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
1071 fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
1072 fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
1073 reader::maybe_get_doc(*self, tag as usize)
1077 trait rbml_decoder_decoder_helpers<'tcx> {
1078 fn read_ty_encoded<'a, 'b, F, R>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>,
1080 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x, 'tcx>) -> R;
1082 fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
1083 fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
1084 fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1085 -> ty::TraitRef<'tcx>;
1086 fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1087 -> ty::PolyTraitRef<'tcx>;
1088 fn read_type_param_def<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1089 -> ty::TypeParameterDef<'tcx>;
1090 fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1091 -> ty::Predicate<'tcx>;
1092 fn read_type_scheme<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1093 -> ty::TypeScheme<'tcx>;
1094 fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1095 -> ty::ExistentialBounds<'tcx>;
1096 fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1097 -> subst::Substs<'tcx>;
1098 fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1099 -> ty::AutoAdjustment<'tcx>;
1100 fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1102 fn read_closure_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1104 fn read_closure_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1105 -> ty::ClosureTy<'tcx>;
1106 fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1107 -> ty::AutoDerefRef<'tcx>;
1108 fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1109 -> ty::AutoRef<'tcx>;
1110 fn convert_def_id(&mut self,
1111 dcx: &DecodeContext,
1112 source: DefIdSource,
1116 // Versions of the type reading functions that don't need the full
1118 fn read_ty_nodcx(&mut self,
1119 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
1120 fn read_tys_nodcx(&mut self,
1121 tcx: &ty::ctxt<'tcx>,
1122 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
1123 fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
1124 cdata: &cstore::crate_metadata)
1125 -> subst::Substs<'tcx>;
1128 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
1129 fn read_ty_nodcx(&mut self,
1130 tcx: &ty::ctxt<'tcx>,
1131 cdata: &cstore::crate_metadata)
1133 self.read_opaque(|_, doc| {
1135 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
1136 &mut |_, id| decoder::translate_def_id(cdata, id))
1141 fn read_tys_nodcx(&mut self,
1142 tcx: &ty::ctxt<'tcx>,
1143 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
1144 self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
1150 fn read_substs_nodcx(&mut self,
1151 tcx: &ty::ctxt<'tcx>,
1152 cdata: &cstore::crate_metadata)
1153 -> subst::Substs<'tcx>
1155 self.read_opaque(|_, doc| {
1157 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
1158 &mut |_, id| decoder::translate_def_id(cdata, id))
1163 fn read_ty_encoded<'b, 'c, F, R>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>, op: F) -> R
1164 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x,'tcx>) -> R
1166 return self.read_opaque(|this, doc| {
1167 debug!("read_ty_encoded({})", type_string(doc));
1169 &mut tydecode::TyDecoder::with_doc(
1170 dcx.tcx, dcx.cdata.cnum, doc,
1171 &mut |s, a| this.convert_def_id(dcx, s, a))))
1174 fn type_string(doc: rbml::Doc) -> String {
1175 let mut str = String::new();
1176 for i in doc.start..doc.end {
1177 str.push(doc.data[i] as char);
1183 fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1184 // Note: regions types embed local node ids. In principle, we
1185 // should translate these node ids into the new decode
1186 // context. However, we do not bother, because region types
1187 // are not used during trans.
1189 return self.read_ty_encoded(dcx, |decoder| decoder.parse_ty());
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_ty_encoded(dcx, |decoder| decoder.parse_trait_ref())
1202 fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1203 -> ty::PolyTraitRef<'tcx> {
1204 ty::Binder(self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref()))
1207 fn read_type_param_def<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1208 -> ty::TypeParameterDef<'tcx> {
1209 self.read_ty_encoded(dcx, |decoder| decoder.parse_type_param_def())
1212 fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1213 -> ty::Predicate<'tcx>
1215 self.read_ty_encoded(dcx, |decoder| decoder.parse_predicate())
1218 fn read_type_scheme<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1219 -> ty::TypeScheme<'tcx> {
1220 self.read_struct("TypeScheme", 3, |this| {
1222 generics: this.read_struct_field("generics", 0, |this| {
1223 this.read_struct("Generics", 2, |this| {
1226 this.read_struct_field("types", 0, |this| {
1227 Ok(this.read_vec_per_param_space(
1228 |this| this.read_type_param_def(dcx)))
1232 this.read_struct_field("regions", 1, |this| {
1233 Ok(this.read_vec_per_param_space(
1234 |this| Decodable::decode(this).unwrap()))
1239 ty: this.read_struct_field("ty", 1, |this| {
1240 Ok(this.read_ty(dcx))
1246 fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1247 -> ty::ExistentialBounds<'tcx>
1249 self.read_ty_encoded(dcx, |decoder| decoder.parse_existential_bounds())
1252 fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1253 -> subst::Substs<'tcx> {
1254 self.read_opaque(|this, doc| {
1255 Ok(tydecode::TyDecoder::with_doc(dcx.tcx, dcx.cdata.cnum, doc,
1256 &mut |s, a| this.convert_def_id(dcx, s, a))
1261 fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1262 -> ty::AutoAdjustment<'tcx> {
1263 self.read_enum("AutoAdjustment", |this| {
1264 let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer", "AdjustDerefRef"];
1265 this.read_enum_variant(&variants, |this, i| {
1267 1 => ty::AdjustReifyFnPointer,
1268 2 => ty::AdjustUnsafeFnPointer,
1270 let auto_deref_ref: ty::AutoDerefRef =
1271 this.read_enum_variant_arg(0,
1272 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1274 ty::AdjustDerefRef(auto_deref_ref)
1276 _ => panic!("bad enum variant for ty::AutoAdjustment")
1282 fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1283 -> ty::AutoDerefRef<'tcx> {
1284 self.read_struct("AutoDerefRef", 2, |this| {
1285 Ok(ty::AutoDerefRef {
1286 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1287 Decodable::decode(this)
1289 autoref: this.read_struct_field("autoref", 1, |this| {
1290 this.read_option(|this, b| {
1292 Ok(Some(this.read_autoref(dcx)))
1298 unsize: this.read_struct_field("unsize", 2, |this| {
1299 this.read_option(|this, b| {
1301 Ok(Some(this.read_ty(dcx)))
1311 fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1312 -> ty::AutoRef<'tcx> {
1313 self.read_enum("AutoRef", |this| {
1314 let variants = ["AutoPtr", "AutoUnsafe"];
1315 this.read_enum_variant(&variants, |this, i| {
1319 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1320 let m: ast::Mutability =
1321 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1323 ty::AutoPtr(dcx.tcx.mk_region(r.tr(dcx)), m)
1326 let m: ast::Mutability =
1327 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1331 _ => panic!("bad enum variant for ty::AutoRef")
1337 fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1340 Decodable::decode(self).unwrap()
1343 fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1346 Decodable::decode(self).unwrap()
1349 fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1350 -> ty::ClosureTy<'tcx>
1352 self.read_ty_encoded(dcx, |decoder| decoder.parse_closure_ty())
1355 /// Converts a def-id that appears in a type. The correct
1356 /// translation will depend on what kind of def-id this is.
1357 /// This is a subtle point: type definitions are not
1358 /// inlined into the current crate, so if the def-id names
1359 /// a nominal type or type alias, then it should be
1360 /// translated to refer to the source crate.
1362 /// However, *type parameters* are cloned along with the function
1363 /// they are attached to. So we should translate those def-ids
1364 /// to refer to the new, cloned copy of the type parameter.
1365 /// We only see references to free type parameters in the body of
1366 /// an inlined function. In such cases, we need the def-id to
1367 /// be a local id so that the TypeContents code is able to lookup
1368 /// the relevant info in the ty_param_defs table.
1370 /// *Region parameters*, unfortunately, are another kettle of fish.
1371 /// In such cases, def_id's can appear in types to distinguish
1372 /// shadowed bound regions and so forth. It doesn't actually
1373 /// matter so much what we do to these, since regions are erased
1374 /// at trans time, but it's good to keep them consistent just in
1375 /// case. We translate them with `tr_def_id()` which will map
1376 /// the crate numbers back to the original source crate.
1378 /// Unboxed closures are cloned along with the function being
1379 /// inlined, and all side tables use interned node IDs, so we
1380 /// translate their def IDs accordingly.
1382 /// It'd be really nice to refactor the type repr to not include
1383 /// def-ids so that all these distinctions were unnecessary.
1384 fn convert_def_id(&mut self,
1385 dcx: &DecodeContext,
1386 source: tydecode::DefIdSource,
1389 let r = match source {
1390 NominalType | TypeWithId | RegionParameter => dcx.tr_def_id(did),
1391 ClosureSource => dcx.tr_intern_def_id(did)
1393 debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1398 fn decode_side_tables(dcx: &DecodeContext,
1399 ast_doc: rbml::Doc) {
1400 let tbl_doc = ast_doc.get(c::tag_table as usize);
1401 for (tag, entry_doc) in reader::docs(tbl_doc) {
1402 let mut entry_dsr = reader::Decoder::new(entry_doc);
1403 let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1404 let id = dcx.tr_id(id0);
1406 debug!(">> Side table document with tag 0x{:x} \
1407 found for id {} (orig {})",
1409 let tag = tag as u32;
1410 let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1414 &format!("unknown tag found in side tables: {:x}",
1418 let val_dsr = &mut entry_dsr;
1421 c::tag_table_def => {
1422 let def = decode_def(dcx, val_dsr);
1423 dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
1425 // This doesn't matter cross-crate.
1426 last_private: LastMod(AllPublic),
1430 c::tag_table_node_type => {
1431 let ty = val_dsr.read_ty(dcx);
1432 debug!("inserting ty for node {}: {:?}",
1434 dcx.tcx.node_type_insert(id, ty);
1436 c::tag_table_item_subst => {
1437 let item_substs = ty::ItemSubsts {
1438 substs: val_dsr.read_substs(dcx)
1440 dcx.tcx.tables.borrow_mut().item_substs.insert(
1443 c::tag_table_freevars => {
1444 let fv_info = val_dsr.read_to_vec(|val_dsr| {
1445 Ok(val_dsr.read_freevar_entry(dcx))
1446 }).unwrap().into_iter().collect();
1447 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1449 c::tag_table_upvar_capture_map => {
1450 let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1451 let upvar_id = ty::UpvarId {
1452 var_id: dcx.tr_id(var_id),
1455 let ub: ty::UpvarCapture = Decodable::decode(val_dsr).unwrap();
1456 dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub.tr(dcx));
1458 c::tag_table_tcache => {
1459 let type_scheme = val_dsr.read_type_scheme(dcx);
1460 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1461 dcx.tcx.register_item_type(lid, type_scheme);
1463 c::tag_table_param_defs => {
1464 let bounds = val_dsr.read_type_param_def(dcx);
1465 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1467 c::tag_table_method_map => {
1468 let (autoderef, method) = val_dsr.read_method_callee(dcx);
1469 let method_call = ty::MethodCall {
1471 autoderef: autoderef
1473 dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1475 c::tag_table_adjustments => {
1476 let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(dcx);
1477 dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1479 c::tag_table_closure_tys => {
1481 val_dsr.read_closure_ty(dcx);
1482 dcx.tcx.tables.borrow_mut().closure_tys.insert(ast_util::local_def(id),
1485 c::tag_table_closure_kinds => {
1487 val_dsr.read_closure_kind(dcx);
1488 dcx.tcx.tables.borrow_mut().closure_kinds.insert(ast_util::local_def(id),
1491 c::tag_table_cast_kinds => {
1493 val_dsr.read_cast_kind(dcx);
1494 dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1496 c::tag_table_const_qualif => {
1497 let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1498 dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1502 &format!("unknown tag found in side tables: {:x}",
1509 debug!(">< Side table doc loaded");
1513 // ______________________________________________________________________
1514 // Testing of astencode_gen
1517 fn encode_item_ast(rbml_w: &mut Encoder, item: &ast::Item) {
1518 rbml_w.start_tag(c::tag_tree as usize);
1519 (*item).encode(rbml_w);
1524 fn decode_item_ast(par_doc: rbml::Doc) -> ast::Item {
1525 let chi_doc = par_doc.get(c::tag_tree as usize);
1526 let mut d = reader::Decoder::new(chi_doc);
1527 Decodable::decode(&mut d).unwrap()
1532 fn call_site(&self) -> codemap::Span;
1533 fn cfg(&self) -> ast::CrateConfig;
1534 fn ident_of(&self, st: &str) -> ast::Ident;
1535 fn name_of(&self, st: &str) -> ast::Name;
1536 fn parse_sess(&self) -> &parse::ParseSess;
1540 impl FakeExtCtxt for parse::ParseSess {
1541 fn call_site(&self) -> codemap::Span {
1543 lo: codemap::BytePos(0),
1544 hi: codemap::BytePos(0),
1545 expn_id: codemap::NO_EXPANSION,
1548 fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1549 fn ident_of(&self, st: &str) -> ast::Ident {
1550 parse::token::str_to_ident(st)
1552 fn name_of(&self, st: &str) -> ast::Name {
1553 parse::token::intern(st)
1555 fn parse_sess(&self) -> &parse::ParseSess { self }
1559 fn mk_ctxt() -> parse::ParseSess {
1560 parse::ParseSess::new()
1564 fn roundtrip(in_item: Option<P<ast::Item>>) {
1565 let in_item = in_item.unwrap();
1566 let mut wr = Cursor::new(Vec::new());
1567 encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
1568 let rbml_doc = rbml::Doc::new(wr.get_ref());
1569 let out_item = decode_item_ast(rbml_doc);
1571 assert!(*in_item == out_item);
1577 roundtrip(quote_item!(&cx,
1583 fn test_smalltalk() {
1585 roundtrip(quote_item!(&cx,
1586 fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1593 roundtrip(quote_item!(&cx,
1594 fn foo(x: usize, y: usize) -> usize {
1602 fn test_simplification() {
1604 let item = quote_item!(&cx,
1605 fn new_int_alist<B>() -> alist<isize, B> {
1606 fn eq_int(a: isize, b: isize) -> bool { a == b }
1607 return alist {eq_fn: eq_int, data: Vec::new()};
1610 let item_in = InlinedItemRef::Item(&*item);
1611 let item_out = simplify_ast(item_in);
1612 let item_exp = InlinedItem::Item(quote_item!(&cx,
1613 fn new_int_alist<B>() -> alist<isize, B> {
1614 return alist {eq_fn: eq_int, data: Vec::new()};
1617 match (item_out, item_exp) {
1618 (InlinedItem::Item(item_out), InlinedItem::Item(item_exp)) => {
1619 assert!(pprust::item_to_string(&*item_out) ==
1620 pprust::item_to_string(&*item_exp));