1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_camel_case_types)]
12 // FIXME: remove this after snapshot, and Results are handled
13 #![allow(unused_must_use)]
15 use front::map as ast_map;
17 use rustc_front::fold;
18 use rustc_front::fold::Folder;
20 use metadata::common as c;
21 use metadata::cstore as cstore;
23 use metadata::decoder;
24 use metadata::encoder as e;
25 use metadata::inline::{InlinedItem, InlinedItemRef};
26 use metadata::tydecode;
27 use metadata::tydecode::{DefIdSource, NominalType, TypeWithId};
28 use metadata::tydecode::{RegionParameter, ClosureSource};
29 use metadata::tyencode;
31 use middle::check_const::ConstQualif;
33 use middle::def_id::{DefId, LOCAL_CRATE};
34 use middle::privacy::{AllPublic, LastMod};
37 use middle::subst::VecPerParamSpace;
38 use middle::ty::{self, Ty};
40 use syntax::{ast, ast_util, codemap};
41 use syntax::codemap::Span;
45 use std::io::SeekFrom;
46 use std::io::prelude::*;
50 use rbml::writer::Encoder;
53 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
54 use serialize::EncoderHelpers;
56 #[cfg(test)] use std::io::Cursor;
57 #[cfg(test)] use syntax::parse;
58 #[cfg(test)] use rustc_front::print::pprust;
59 #[cfg(test)] use rustc_front::lowering::lower_item;
61 struct DecodeContext<'a, 'b, 'tcx: 'a> {
62 tcx: &'a ty::ctxt<'tcx>,
63 cdata: &'b cstore::crate_metadata,
64 from_id_range: ast_util::IdRange,
65 to_id_range: ast_util::IdRange,
66 // Cache the last used filemap for translating spans as an optimization.
67 last_filemap_index: Cell<usize>,
71 fn tr(&self, dcx: &DecodeContext) -> Self;
75 fn tr_intern(&self, dcx: &DecodeContext) -> DefId;
78 // ______________________________________________________________________
81 pub fn encode_inlined_item(ecx: &e::EncodeContext,
85 InlinedItemRef::Item(i) => i.id,
86 InlinedItemRef::Foreign(i) => i.id,
87 InlinedItemRef::TraitItem(_, ti) => ti.id,
88 InlinedItemRef::ImplItem(_, ii) => ii.id,
90 debug!("> Encoding inlined item: {} ({:?})",
91 ecx.tcx.map.path_to_string(id),
92 rbml_w.writer.seek(SeekFrom::Current(0)));
94 // Folding could be avoided with a smarter encoder.
95 let ii = simplify_ast(ii);
96 let id_range = ii.compute_id_range();
98 rbml_w.start_tag(c::tag_ast as usize);
99 id_range.encode(rbml_w);
100 encode_ast(rbml_w, &ii);
101 encode_side_tables_for_ii(ecx, rbml_w, &ii);
104 debug!("< Encoded inlined fn: {} ({:?})",
105 ecx.tcx.map.path_to_string(id),
106 rbml_w.writer.seek(SeekFrom::Current(0)));
109 impl<'a, 'b, 'c, 'tcx> ast_map::FoldOps for &'a DecodeContext<'b, 'c, 'tcx> {
110 fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
111 if id == ast::DUMMY_NODE_ID {
112 // Used by ast_map to map the NodeInlinedParent.
113 self.tcx.sess.next_node_id()
118 fn new_def_id(&self, def_id: DefId) -> DefId {
119 self.tr_def_id(def_id)
121 fn new_span(&self, span: Span) -> Span {
126 /// Decodes an item from its AST in the cdata's metadata and adds it to the
128 pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
129 tcx: &ty::ctxt<'tcx>,
130 path: Vec<ast_map::PathElem>,
132 -> Result<&'tcx InlinedItem, Vec<ast_map::PathElem>> {
133 match par_doc.opt_child(c::tag_ast) {
136 let mut path_as_str = None;
137 debug!("> Decoding inlined fn: {:?}::?",
139 // Do an Option dance to use the path after it is moved below.
140 let s = ast_map::path_to_string(path.iter().cloned());
141 path_as_str = Some(s);
142 path_as_str.as_ref().map(|x| &x[..])
144 let mut ast_dsr = reader::Decoder::new(ast_doc);
145 let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
146 let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
147 let dcx = &DecodeContext {
150 from_id_range: from_id_range,
151 to_id_range: to_id_range,
152 last_filemap_index: Cell::new(0)
154 let raw_ii = decode_ast(ast_doc);
155 let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, raw_ii, dcx);
157 let ident = match *ii {
158 InlinedItem::Item(ref i) => i.ident,
159 InlinedItem::Foreign(ref i) => i.ident,
160 InlinedItem::TraitItem(_, ref ti) => ti.ident,
161 InlinedItem::ImplItem(_, ref ii) => ii.ident
163 debug!("Fn named: {}", ident);
164 debug!("< Decoded inlined fn: {}::{}",
165 path_as_str.unwrap(),
167 region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
168 decode_side_tables(dcx, ast_doc);
170 InlinedItem::Item(ref i) => {
171 debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
172 ::rustc_front::print::pprust::item_to_string(&**i));
181 // ______________________________________________________________________
182 // Enumerating the IDs which appear in an AST
184 fn reserve_id_range(sess: &Session,
185 from_id_range: ast_util::IdRange) -> ast_util::IdRange {
186 // Handle the case of an empty range:
187 if from_id_range.empty() { return from_id_range; }
188 let cnt = from_id_range.max - from_id_range.min;
189 let to_id_min = sess.reserve_node_ids(cnt);
190 let to_id_max = to_id_min + cnt;
191 ast_util::IdRange { min: to_id_min, max: to_id_max }
194 impl<'a, 'b, 'tcx> DecodeContext<'a, 'b, 'tcx> {
195 /// Translates an internal id, meaning a node id that is known to refer to some part of the
196 /// item currently being inlined, such as a local variable or argument. All naked node-ids
197 /// that appear in types have this property, since if something might refer to an external item
198 /// we would use a def-id to allow for the possibility that the item resides in another crate.
199 pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
200 // from_id_range should be non-empty
201 assert!(!self.from_id_range.empty());
202 // Use wrapping arithmetic because otherwise it introduces control flow.
203 // Maybe we should just have the control flow? -- aatch
204 (id.wrapping_sub(self.from_id_range.min).wrapping_add(self.to_id_range.min))
207 /// Translates an EXTERNAL def-id, converting the crate number from the one used in the encoded
208 /// data to the current crate numbers.. By external, I mean that it be translated to a
209 /// reference to the item in its original crate, as opposed to being translated to a reference
210 /// to the inlined version of the item. This is typically, but not always, what you want,
211 /// because most def-ids refer to external things like types or other fns that may or may not
212 /// be inlined. Note that even when the inlined function is referencing itself recursively, we
213 /// would want `tr_def_id` for that reference--- conceptually the function calls the original,
214 /// non-inlined version, and trans deals with linking that recursive call to the inlined copy.
216 /// However, there are a *few* cases where def-ids are used but we know that the thing being
217 /// referenced is in fact *internal* to the item being inlined. In those cases, you should use
218 /// `tr_intern_def_id()` below.
219 pub fn tr_def_id(&self, did: DefId) -> DefId {
221 decoder::translate_def_id(self.cdata, did)
224 /// Translates an INTERNAL def-id, meaning a def-id that is
225 /// known to refer to some part of the item currently being
226 /// inlined. In that case, we want to convert the def-id to
227 /// refer to the current crate and to the new, inlined node-id.
228 pub fn tr_intern_def_id(&self, did: DefId) -> DefId {
229 assert_eq!(did.krate, LOCAL_CRATE);
230 DefId { krate: LOCAL_CRATE, node: self.tr_id(did.node) }
233 /// Translates a `Span` from an extern crate to the corresponding `Span`
234 /// within the local crate's codemap. `creader::import_codemap()` will
235 /// already have allocated any additionally needed FileMaps in the local
236 /// codemap as a side-effect of creating the crate_metadata's
237 /// `codemap_import_info`.
238 pub fn tr_span(&self, span: Span) -> Span {
239 let span = if span.lo > span.hi {
240 // Currently macro expansion sometimes produces invalid Span values
241 // where lo > hi. In order not to crash the compiler when trying to
242 // translate these values, let's transform them into something we
243 // can handle (and which will produce useful debug locations at
244 // least some of the time).
245 // This workaround is only necessary as long as macro expansion is
246 // not fixed. FIXME(#23480)
247 codemap::mk_sp(span.lo, span.lo)
252 let imported_filemaps = self.cdata.imported_filemaps(self.tcx.sess.codemap());
254 // Optimize for the case that most spans within a translated item
255 // originate from the same filemap.
256 let last_filemap_index = self.last_filemap_index.get();
257 let last_filemap = &imported_filemaps[last_filemap_index];
259 if span.lo >= last_filemap.original_start_pos &&
260 span.lo <= last_filemap.original_end_pos &&
261 span.hi >= last_filemap.original_start_pos &&
262 span.hi <= last_filemap.original_end_pos {
266 let mut b = imported_filemaps.len();
270 if imported_filemaps[m].original_start_pos > span.lo {
277 self.last_filemap_index.set(a);
278 &imported_filemaps[a]
282 let lo = (span.lo - filemap.original_start_pos) +
283 filemap.translated_filemap.start_pos;
284 let hi = (span.hi - filemap.original_start_pos) +
285 filemap.translated_filemap.start_pos;
287 codemap::mk_sp(lo, hi)
291 impl tr_intern for DefId {
292 fn tr_intern(&self, dcx: &DecodeContext) -> DefId {
293 dcx.tr_intern_def_id(*self)
298 fn tr(&self, dcx: &DecodeContext) -> DefId {
303 impl tr for Option<DefId> {
304 fn tr(&self, dcx: &DecodeContext) -> Option<DefId> {
305 self.map(|d| dcx.tr_def_id(d))
310 fn tr(&self, dcx: &DecodeContext) -> Span {
315 trait def_id_encoder_helpers {
316 fn emit_def_id(&mut self, did: DefId);
319 impl<S:serialize::Encoder> def_id_encoder_helpers for S
320 where <S as serialize::serialize::Encoder>::Error: Debug
322 fn emit_def_id(&mut self, did: DefId) {
323 did.encode(self).unwrap()
327 trait def_id_decoder_helpers {
328 fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId;
329 fn read_def_id_nodcx(&mut self,
330 cdata: &cstore::crate_metadata) -> DefId;
333 impl<D:serialize::Decoder> def_id_decoder_helpers for D
334 where <D as serialize::serialize::Decoder>::Error: Debug
336 fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId {
337 let did: DefId = Decodable::decode(self).unwrap();
341 fn read_def_id_nodcx(&mut self,
342 cdata: &cstore::crate_metadata)
344 let did: DefId = Decodable::decode(self).unwrap();
345 decoder::translate_def_id(cdata, did)
349 // ______________________________________________________________________
350 // Encoding and decoding the AST itself
352 // When decoding, we have to renumber the AST so that the node ids that
353 // appear within are disjoint from the node ids in our existing ASTs.
354 // We also have to adjust the spans: for now we just insert a dummy span,
355 // but eventually we should add entries to the local codemap as required.
357 fn encode_ast(rbml_w: &mut Encoder, item: &InlinedItem) {
358 rbml_w.start_tag(c::tag_tree as usize);
363 struct NestedItemsDropper;
365 impl Folder for NestedItemsDropper {
366 fn fold_block(&mut self, blk: P<hir::Block>) -> P<hir::Block> {
367 blk.and_then(|hir::Block {id, stmts, expr, rules, span, ..}| {
368 let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
369 let use_stmt = match stmt.node {
370 hir::StmtExpr(_, _) | hir::StmtSemi(_, _) => true,
371 hir::StmtDecl(ref decl, _) => {
373 hir::DeclLocal(_) => true,
374 hir::DeclItem(_) => false,
384 let blk_sans_items = P(hir::Block {
385 stmts: stmts_sans_items,
391 fold::noop_fold_block(blk_sans_items, self)
396 // Produces a simplified copy of the AST which does not include things
397 // that we do not need to or do not want to export. For example, we
398 // do not include any nested items: if these nested items are to be
399 // inlined, their AST will be exported separately (this only makes
400 // sense because, in Rust, nested items are independent except for
401 // their visibility).
403 // As it happens, trans relies on the fact that we do not export
404 // nested items, as otherwise it would get confused when translating
406 fn simplify_ast(ii: InlinedItemRef) -> InlinedItem {
407 let mut fld = NestedItemsDropper;
410 // HACK we're not dropping items.
411 InlinedItemRef::Item(i) => {
412 InlinedItem::Item(fold::noop_fold_item(P(i.clone()), &mut fld)
413 .expect_one("expected one item"))
415 InlinedItemRef::TraitItem(d, ti) => {
416 InlinedItem::TraitItem(d,
417 fold::noop_fold_trait_item(P(ti.clone()), &mut fld)
418 .expect_one("noop_fold_trait_item must produce \
419 exactly one trait item"))
421 InlinedItemRef::ImplItem(d, ii) => {
422 InlinedItem::ImplItem(d,
423 fold::noop_fold_impl_item(P(ii.clone()), &mut fld)
424 .expect_one("noop_fold_impl_item must produce \
425 exactly one impl item"))
427 InlinedItemRef::Foreign(i) => {
428 InlinedItem::Foreign(fold::noop_fold_foreign_item(P(i.clone()), &mut fld))
433 fn decode_ast(par_doc: rbml::Doc) -> InlinedItem {
434 let chi_doc = par_doc.get(c::tag_tree as usize);
435 let mut d = reader::Decoder::new(chi_doc);
436 Decodable::decode(&mut d).unwrap()
439 // ______________________________________________________________________
440 // Encoding and decoding of ast::def
442 fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> def::Def {
443 let def: def::Def = Decodable::decode(dsr).unwrap();
447 impl tr for def::Def {
448 fn tr(&self, dcx: &DecodeContext) -> def::Def {
450 def::DefFn(did, is_ctor) => def::DefFn(did.tr(dcx), is_ctor),
451 def::DefMethod(did) => def::DefMethod(did.tr(dcx)),
452 def::DefSelfTy(opt_did, impl_ids) => { def::DefSelfTy(opt_did.map(|did| did.tr(dcx)),
453 impl_ids.map(|(nid1, nid2)| {
457 def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
458 def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
459 def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
460 def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
461 def::DefAssociatedConst(did) => def::DefAssociatedConst(did.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, index, nid2) => {
474 def::DefUpvar(dcx.tr_id(nid1), index, 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 freevar information
486 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
487 (*fv).encode(rbml_w).unwrap();
490 trait rbml_decoder_helper {
491 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
493 fn read_capture_mode(&mut self) -> hir::CaptureClause;
496 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
497 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
499 let fv: ty::Freevar = Decodable::decode(self).unwrap();
503 fn read_capture_mode(&mut self) -> hir::CaptureClause {
504 let cm: hir::CaptureClause = Decodable::decode(self).unwrap();
509 impl tr for ty::Freevar {
510 fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
512 def: self.def.tr(dcx),
513 span: self.span.tr(dcx),
518 // ______________________________________________________________________
519 // Encoding and decoding of MethodCallee
521 trait read_method_callee_helper<'tcx> {
522 fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
523 -> (u32, ty::MethodCallee<'tcx>);
526 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
527 rbml_w: &mut Encoder,
529 method: &ty::MethodCallee<'tcx>) {
530 use serialize::Encoder;
532 rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
533 rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
534 autoderef.encode(rbml_w)
536 rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
537 Ok(rbml_w.emit_def_id(method.def_id))
539 rbml_w.emit_struct_field("ty", 2, |rbml_w| {
540 Ok(rbml_w.emit_ty(ecx, method.ty))
542 rbml_w.emit_struct_field("substs", 3, |rbml_w| {
543 Ok(rbml_w.emit_substs(ecx, &method.substs))
548 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
549 fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
550 -> (u32, ty::MethodCallee<'tcx>) {
552 self.read_struct("MethodCallee", 4, |this| {
553 let autoderef = this.read_struct_field("autoderef", 0,
554 Decodable::decode).unwrap();
555 Ok((autoderef, ty::MethodCallee {
556 def_id: this.read_struct_field("def_id", 1, |this| {
557 Ok(this.read_def_id(dcx))
559 ty: this.read_struct_field("ty", 2, |this| {
560 Ok(this.read_ty(dcx))
562 substs: this.read_struct_field("substs", 3, |this| {
563 Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
570 pub fn encode_closure_kind(ebml_w: &mut Encoder, kind: ty::ClosureKind) {
571 kind.encode(ebml_w).unwrap();
574 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
575 kind.encode(ebml_w).unwrap();
578 pub trait vtable_decoder_helpers<'tcx> {
579 fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
580 F: FnMut(&mut Self) -> T;
583 impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> {
584 fn read_vec_per_param_space<T, F>(&mut self, mut f: F) -> VecPerParamSpace<T> where
585 F: FnMut(&mut reader::Decoder<'a>) -> T,
587 let types = self.read_to_vec(|this| Ok(f(this))).unwrap();
588 let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap();
589 let fns = self.read_to_vec(|this| Ok(f(this))).unwrap();
590 VecPerParamSpace::new(types, selfs, fns)
594 // ___________________________________________________________________________
597 fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder,
598 v: &subst::VecPerParamSpace<T>,
600 F: FnMut(&mut Encoder, &T),
602 for &space in &subst::ParamSpace::all() {
603 rbml_w.emit_from_vec(v.get_slice(space),
604 |rbml_w, n| Ok(f(rbml_w, n))).unwrap();
608 // ______________________________________________________________________
609 // Encoding and decoding the side tables
611 trait get_ty_str_ctxt<'tcx> {
612 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
615 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
616 fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
618 diag: self.tcx.sess.diagnostic(),
619 ds: e::def_to_string,
621 abbrevs: &self.type_abbrevs
626 trait rbml_writer_helpers<'tcx> {
627 fn emit_closure_type<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
628 closure_type: &ty::ClosureTy<'tcx>);
629 fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region);
630 fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
631 fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
632 fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
633 type_param_def: &ty::TypeParameterDef<'tcx>);
634 fn emit_region_param_def(&mut self, ecx: &e::EncodeContext,
635 region_param_def: &ty::RegionParameterDef);
636 fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
637 predicate: &ty::Predicate<'tcx>);
638 fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
639 ty: &ty::TraitRef<'tcx>);
640 fn emit_type_scheme<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
641 type_scheme: ty::TypeScheme<'tcx>);
642 fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
643 substs: &subst::Substs<'tcx>);
644 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
645 bounds: &ty::ExistentialBounds<'tcx>);
646 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
647 fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture);
648 fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
649 adj: &ty::AutoAdjustment<'tcx>);
650 fn emit_autoref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
651 autoref: &ty::AutoRef<'tcx>);
652 fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
653 auto_deref_ref: &ty::AutoDerefRef<'tcx>);
656 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
657 fn emit_closure_type<'b>(&mut self,
658 ecx: &e::EncodeContext<'b, 'tcx>,
659 closure_type: &ty::ClosureTy<'tcx>) {
660 self.emit_opaque(|this| {
661 Ok(e::write_closure_type(ecx, this, closure_type))
665 fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region) {
666 self.emit_opaque(|this| Ok(e::write_region(ecx, this, r)));
669 fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
670 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
673 fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
674 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
677 fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
678 trait_ref: &ty::TraitRef<'tcx>) {
679 self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
682 fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
683 type_param_def: &ty::TypeParameterDef<'tcx>) {
684 self.emit_opaque(|this| {
685 Ok(tyencode::enc_type_param_def(this,
690 fn emit_region_param_def(&mut self, ecx: &e::EncodeContext,
691 region_param_def: &ty::RegionParameterDef) {
692 self.emit_opaque(|this| {
693 Ok(tyencode::enc_region_param_def(this,
698 fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
699 predicate: &ty::Predicate<'tcx>) {
700 self.emit_opaque(|this| {
701 Ok(tyencode::enc_predicate(this,
707 fn emit_type_scheme<'b>(&mut self,
708 ecx: &e::EncodeContext<'b, 'tcx>,
709 type_scheme: ty::TypeScheme<'tcx>) {
710 use serialize::Encoder;
712 self.emit_struct("TypeScheme", 2, |this| {
713 this.emit_struct_field("generics", 0, |this| {
714 this.emit_struct("Generics", 2, |this| {
715 this.emit_struct_field("types", 0, |this| {
716 Ok(encode_vec_per_param_space(
717 this, &type_scheme.generics.types,
718 |this, def| this.emit_type_param_def(ecx, def)))
720 this.emit_struct_field("regions", 1, |this| {
721 Ok(encode_vec_per_param_space(
722 this, &type_scheme.generics.regions,
723 |this, def| this.emit_region_param_def(ecx, def)))
727 this.emit_struct_field("ty", 1, |this| {
728 Ok(this.emit_ty(ecx, type_scheme.ty))
733 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
734 bounds: &ty::ExistentialBounds<'tcx>) {
735 self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
740 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
741 self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
746 fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture) {
747 use serialize::Encoder;
749 self.emit_enum("UpvarCapture", |this| {
751 ty::UpvarCapture::ByValue => {
752 this.emit_enum_variant("ByValue", 1, 0, |_| Ok(()))
754 ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind, region }) => {
755 this.emit_enum_variant("ByRef", 2, 0, |this| {
756 this.emit_enum_variant_arg(0,
757 |this| kind.encode(this));
758 this.emit_enum_variant_arg(1,
759 |this| Ok(this.emit_region(ecx, region)))
766 fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
767 substs: &subst::Substs<'tcx>) {
768 self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
773 fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
774 adj: &ty::AutoAdjustment<'tcx>) {
775 use serialize::Encoder;
777 self.emit_enum("AutoAdjustment", |this| {
779 ty::AdjustReifyFnPointer=> {
780 this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
783 ty::AdjustUnsafeFnPointer => {
784 this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
789 ty::AdjustDerefRef(ref auto_deref_ref) => {
790 this.emit_enum_variant("AdjustDerefRef", 3, 2, |this| {
791 this.emit_enum_variant_arg(0,
792 |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
799 fn emit_autoref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
800 autoref: &ty::AutoRef<'tcx>) {
801 use serialize::Encoder;
803 self.emit_enum("AutoRef", |this| {
805 &ty::AutoPtr(r, m) => {
806 this.emit_enum_variant("AutoPtr", 0, 2, |this| {
807 this.emit_enum_variant_arg(0,
808 |this| Ok(this.emit_region(ecx, *r)));
809 this.emit_enum_variant_arg(1, |this| m.encode(this))
812 &ty::AutoUnsafe(m) => {
813 this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
814 this.emit_enum_variant_arg(0, |this| m.encode(this))
821 fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
822 auto_deref_ref: &ty::AutoDerefRef<'tcx>) {
823 use serialize::Encoder;
825 self.emit_struct("AutoDerefRef", 2, |this| {
826 this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
828 this.emit_struct_field("autoref", 1, |this| {
829 this.emit_option(|this| {
830 match auto_deref_ref.autoref {
831 None => this.emit_option_none(),
832 Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a))),
837 this.emit_struct_field("unsize", 2, |this| {
838 this.emit_option(|this| {
839 match auto_deref_ref.unsize {
840 None => this.emit_option_none(),
841 Some(target) => this.emit_option_some(|this| {
842 Ok(this.emit_ty(ecx, target))
851 trait write_tag_and_id {
852 fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
853 fn id(&mut self, id: ast::NodeId);
856 impl<'a> write_tag_and_id for Encoder<'a> {
858 tag_id: c::astencode_tag,
860 F: FnOnce(&mut Encoder<'a>),
862 self.start_tag(tag_id as usize);
867 fn id(&mut self, id: ast::NodeId) {
868 id.encode(self).unwrap();
872 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
873 ecx: &'a e::EncodeContext<'c, 'tcx>,
874 rbml_w: &'a mut Encoder<'b>,
877 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
878 SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
879 fn visit_id(&mut self, id: ast::NodeId) {
880 encode_side_tables_for_id(self.ecx, self.rbml_w, id)
884 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
885 rbml_w: &mut Encoder,
887 rbml_w.start_tag(c::tag_table as usize);
888 ii.visit_ids(&mut SideTableEncodingIdVisitor {
895 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
896 rbml_w: &mut Encoder,
900 debug!("Encoding side tables for id {}", id);
902 if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
903 rbml_w.tag(c::tag_table_def, |rbml_w| {
905 def.encode(rbml_w).unwrap();
909 if let Some(ty) = tcx.node_types().get(&id) {
910 rbml_w.tag(c::tag_table_node_type, |rbml_w| {
912 rbml_w.emit_ty(ecx, *ty);
916 if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
917 rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
919 rbml_w.emit_substs(ecx, &item_substs.substs);
923 if let Some(fv) = tcx.freevars.borrow().get(&id) {
924 rbml_w.tag(c::tag_table_freevars, |rbml_w| {
926 rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
927 Ok(encode_freevar_entry(rbml_w, fv_entry))
932 rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
935 let var_id = freevar.def.def_id().node;
936 let upvar_id = ty::UpvarId {
940 let upvar_capture = tcx.tables
946 var_id.encode(rbml_w);
947 rbml_w.emit_upvar_capture(ecx, &upvar_capture);
952 let lid = DefId { krate: LOCAL_CRATE, node: id };
953 if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
954 rbml_w.tag(c::tag_table_tcache, |rbml_w| {
956 rbml_w.emit_type_scheme(ecx, type_scheme.clone());
960 if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
961 rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
963 rbml_w.emit_type_param_def(ecx, type_param_def)
967 let method_call = ty::MethodCall::expr(id);
968 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
969 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
971 encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
975 if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
977 ty::AdjustDerefRef(ref adj) => {
978 for autoderef in 0..adj.autoderefs {
979 let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
980 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
981 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
983 encode_method_callee(ecx, rbml_w,
984 method_call.autoderef, method)
992 rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
994 rbml_w.emit_auto_adjustment(ecx, adjustment);
998 if let Some(closure_type) = tcx.tables.borrow().closure_tys.get(&DefId::local(id)) {
999 rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
1001 rbml_w.emit_closure_type(ecx, closure_type);
1005 if let Some(closure_kind) = tcx.tables.borrow().closure_kinds.get(&DefId::local(id)) {
1006 rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
1008 encode_closure_kind(rbml_w, *closure_kind)
1012 if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
1013 rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
1015 encode_cast_kind(rbml_w, *cast_kind)
1019 if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
1020 rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
1022 qualif.encode(rbml_w).unwrap()
1027 trait doc_decoder_helpers: Sized {
1028 fn as_int(&self) -> isize;
1029 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1032 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
1033 fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
1034 fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
1035 reader::maybe_get_doc(*self, tag as usize)
1039 trait rbml_decoder_decoder_helpers<'tcx> {
1040 fn read_ty_encoded<'a, 'b, F, R>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>,
1042 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x, 'tcx>) -> R;
1044 fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region;
1045 fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
1046 fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
1047 fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1048 -> ty::TraitRef<'tcx>;
1049 fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1050 -> ty::PolyTraitRef<'tcx>;
1051 fn read_type_param_def<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1052 -> ty::TypeParameterDef<'tcx>;
1053 fn read_region_param_def(&mut self, dcx: &DecodeContext)
1054 -> ty::RegionParameterDef;
1055 fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1056 -> ty::Predicate<'tcx>;
1057 fn read_type_scheme<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1058 -> ty::TypeScheme<'tcx>;
1059 fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1060 -> ty::ExistentialBounds<'tcx>;
1061 fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1062 -> subst::Substs<'tcx>;
1063 fn read_upvar_capture(&mut self, dcx: &DecodeContext)
1064 -> ty::UpvarCapture;
1065 fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1066 -> ty::AutoAdjustment<'tcx>;
1067 fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1069 fn read_closure_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1071 fn read_closure_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1072 -> ty::ClosureTy<'tcx>;
1073 fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1074 -> ty::AutoDerefRef<'tcx>;
1075 fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1076 -> ty::AutoRef<'tcx>;
1077 fn convert_def_id(&mut self,
1078 dcx: &DecodeContext,
1079 source: DefIdSource,
1083 // Versions of the type reading functions that don't need the full
1085 fn read_ty_nodcx(&mut self,
1086 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
1087 fn read_tys_nodcx(&mut self,
1088 tcx: &ty::ctxt<'tcx>,
1089 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
1090 fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
1091 cdata: &cstore::crate_metadata)
1092 -> subst::Substs<'tcx>;
1095 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
1096 fn read_ty_nodcx(&mut self,
1097 tcx: &ty::ctxt<'tcx>,
1098 cdata: &cstore::crate_metadata)
1100 self.read_opaque(|_, doc| {
1102 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
1103 &mut |_, id| decoder::translate_def_id(cdata, id))
1108 fn read_tys_nodcx(&mut self,
1109 tcx: &ty::ctxt<'tcx>,
1110 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
1111 self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
1117 fn read_substs_nodcx(&mut self,
1118 tcx: &ty::ctxt<'tcx>,
1119 cdata: &cstore::crate_metadata)
1120 -> subst::Substs<'tcx>
1122 self.read_opaque(|_, doc| {
1124 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
1125 &mut |_, id| decoder::translate_def_id(cdata, id))
1130 fn read_ty_encoded<'b, 'c, F, R>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>, op: F) -> R
1131 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x,'tcx>) -> R
1133 return self.read_opaque(|this, doc| {
1134 debug!("read_ty_encoded({})", type_string(doc));
1136 &mut tydecode::TyDecoder::with_doc(
1137 dcx.tcx, dcx.cdata.cnum, doc,
1138 &mut |s, a| this.convert_def_id(dcx, s, a))))
1141 fn type_string(doc: rbml::Doc) -> String {
1142 let mut str = String::new();
1143 for i in doc.start..doc.end {
1144 str.push(doc.data[i] as char);
1149 fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region {
1150 // Note: regions types embed local node ids. In principle, we
1151 // should translate these node ids into the new decode
1152 // context. However, we do not bother, because region types
1153 // are not used during trans. This also applies to read_ty.
1154 return self.read_ty_encoded(dcx, |decoder| decoder.parse_region());
1156 fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1157 return self.read_ty_encoded(dcx, |decoder| decoder.parse_ty());
1160 fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1162 self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1165 fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1166 -> ty::TraitRef<'tcx> {
1167 self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref())
1170 fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1171 -> ty::PolyTraitRef<'tcx> {
1172 ty::Binder(self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref()))
1175 fn read_type_param_def<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1176 -> ty::TypeParameterDef<'tcx> {
1177 self.read_ty_encoded(dcx, |decoder| decoder.parse_type_param_def())
1179 fn read_region_param_def(&mut self, dcx: &DecodeContext)
1180 -> ty::RegionParameterDef {
1181 self.read_ty_encoded(dcx, |decoder| decoder.parse_region_param_def())
1183 fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1184 -> ty::Predicate<'tcx>
1186 self.read_ty_encoded(dcx, |decoder| decoder.parse_predicate())
1189 fn read_type_scheme<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1190 -> ty::TypeScheme<'tcx> {
1191 self.read_struct("TypeScheme", 3, |this| {
1193 generics: this.read_struct_field("generics", 0, |this| {
1194 this.read_struct("Generics", 2, |this| {
1197 this.read_struct_field("types", 0, |this| {
1198 Ok(this.read_vec_per_param_space(
1199 |this| this.read_type_param_def(dcx)))
1203 this.read_struct_field("regions", 1, |this| {
1204 Ok(this.read_vec_per_param_space(
1205 |this| this.read_region_param_def(dcx)))
1210 ty: this.read_struct_field("ty", 1, |this| {
1211 Ok(this.read_ty(dcx))
1217 fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1218 -> ty::ExistentialBounds<'tcx>
1220 self.read_ty_encoded(dcx, |decoder| decoder.parse_existential_bounds())
1223 fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1224 -> subst::Substs<'tcx> {
1225 self.read_opaque(|this, doc| {
1226 Ok(tydecode::TyDecoder::with_doc(dcx.tcx, dcx.cdata.cnum, doc,
1227 &mut |s, a| this.convert_def_id(dcx, s, a))
1231 fn read_upvar_capture(&mut self, dcx: &DecodeContext) -> ty::UpvarCapture {
1232 self.read_enum("UpvarCapture", |this| {
1233 let variants = ["ByValue", "ByRef"];
1234 this.read_enum_variant(&variants, |this, i| {
1236 1 => ty::UpvarCapture::ByValue,
1237 2 => ty::UpvarCapture::ByRef(ty::UpvarBorrow {
1238 kind: this.read_enum_variant_arg(0,
1239 |this| Decodable::decode(this)).unwrap(),
1240 region: this.read_enum_variant_arg(1,
1241 |this| Ok(this.read_region(dcx))).unwrap()
1243 _ => panic!("bad enum variant for ty::UpvarCapture")
1248 fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1249 -> ty::AutoAdjustment<'tcx> {
1250 self.read_enum("AutoAdjustment", |this| {
1251 let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer", "AdjustDerefRef"];
1252 this.read_enum_variant(&variants, |this, i| {
1254 1 => ty::AdjustReifyFnPointer,
1255 2 => ty::AdjustUnsafeFnPointer,
1257 let auto_deref_ref: ty::AutoDerefRef =
1258 this.read_enum_variant_arg(0,
1259 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1261 ty::AdjustDerefRef(auto_deref_ref)
1263 _ => panic!("bad enum variant for ty::AutoAdjustment")
1269 fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1270 -> ty::AutoDerefRef<'tcx> {
1271 self.read_struct("AutoDerefRef", 2, |this| {
1272 Ok(ty::AutoDerefRef {
1273 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1274 Decodable::decode(this)
1276 autoref: this.read_struct_field("autoref", 1, |this| {
1277 this.read_option(|this, b| {
1279 Ok(Some(this.read_autoref(dcx)))
1285 unsize: this.read_struct_field("unsize", 2, |this| {
1286 this.read_option(|this, b| {
1288 Ok(Some(this.read_ty(dcx)))
1298 fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1299 -> ty::AutoRef<'tcx> {
1300 self.read_enum("AutoRef", |this| {
1301 let variants = ["AutoPtr", "AutoUnsafe"];
1302 this.read_enum_variant(&variants, |this, i| {
1306 this.read_enum_variant_arg(0, |this| {
1307 Ok(this.read_region(dcx))
1309 let m: hir::Mutability =
1310 this.read_enum_variant_arg(1, |this| {
1311 Decodable::decode(this)
1314 ty::AutoPtr(dcx.tcx.mk_region(r), m)
1317 let m: hir::Mutability =
1318 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1322 _ => panic!("bad enum variant for ty::AutoRef")
1328 fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1331 Decodable::decode(self).unwrap()
1334 fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1337 Decodable::decode(self).unwrap()
1340 fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1341 -> ty::ClosureTy<'tcx>
1343 self.read_ty_encoded(dcx, |decoder| decoder.parse_closure_ty())
1346 /// Converts a def-id that appears in a type. The correct
1347 /// translation will depend on what kind of def-id this is.
1348 /// This is a subtle point: type definitions are not
1349 /// inlined into the current crate, so if the def-id names
1350 /// a nominal type or type alias, then it should be
1351 /// translated to refer to the source crate.
1353 /// However, *type parameters* are cloned along with the function
1354 /// they are attached to. So we should translate those def-ids
1355 /// to refer to the new, cloned copy of the type parameter.
1356 /// We only see references to free type parameters in the body of
1357 /// an inlined function. In such cases, we need the def-id to
1358 /// be a local id so that the TypeContents code is able to lookup
1359 /// the relevant info in the ty_param_defs table.
1361 /// *Region parameters*, unfortunately, are another kettle of fish.
1362 /// In such cases, def_id's can appear in types to distinguish
1363 /// shadowed bound regions and so forth. It doesn't actually
1364 /// matter so much what we do to these, since regions are erased
1365 /// at trans time, but it's good to keep them consistent just in
1366 /// case. We translate them with `tr_def_id()` which will map
1367 /// the crate numbers back to the original source crate.
1369 /// Scopes will end up as being totally bogus. This can actually
1370 /// be fixed though.
1372 /// Unboxed closures are cloned along with the function being
1373 /// inlined, and all side tables use interned node IDs, so we
1374 /// translate their def IDs accordingly.
1376 /// It'd be really nice to refactor the type repr to not include
1377 /// def-ids so that all these distinctions were unnecessary.
1378 fn convert_def_id(&mut self,
1379 dcx: &DecodeContext,
1380 source: tydecode::DefIdSource,
1383 let r = match source {
1384 NominalType | TypeWithId | RegionParameter => dcx.tr_def_id(did),
1385 ClosureSource => dcx.tr_intern_def_id(did)
1387 debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1392 fn decode_side_tables(dcx: &DecodeContext,
1393 ast_doc: rbml::Doc) {
1394 let tbl_doc = ast_doc.get(c::tag_table as usize);
1395 for (tag, entry_doc) in reader::docs(tbl_doc) {
1396 let mut entry_dsr = reader::Decoder::new(entry_doc);
1397 let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1398 let id = dcx.tr_id(id0);
1400 debug!(">> Side table document with tag 0x{:x} \
1401 found for id {} (orig {})",
1403 let tag = tag as u32;
1404 let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1408 &format!("unknown tag found in side tables: {:x}",
1412 let val_dsr = &mut entry_dsr;
1415 c::tag_table_def => {
1416 let def = decode_def(dcx, val_dsr);
1417 dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
1419 // This doesn't matter cross-crate.
1420 last_private: LastMod(AllPublic),
1424 c::tag_table_node_type => {
1425 let ty = val_dsr.read_ty(dcx);
1426 debug!("inserting ty for node {}: {:?}",
1428 dcx.tcx.node_type_insert(id, ty);
1430 c::tag_table_item_subst => {
1431 let item_substs = ty::ItemSubsts {
1432 substs: val_dsr.read_substs(dcx)
1434 dcx.tcx.tables.borrow_mut().item_substs.insert(
1437 c::tag_table_freevars => {
1438 let fv_info = val_dsr.read_to_vec(|val_dsr| {
1439 Ok(val_dsr.read_freevar_entry(dcx))
1440 }).unwrap().into_iter().collect();
1441 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1443 c::tag_table_upvar_capture_map => {
1444 let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1445 let upvar_id = ty::UpvarId {
1446 var_id: dcx.tr_id(var_id),
1449 let ub = val_dsr.read_upvar_capture(dcx);
1450 dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub);
1452 c::tag_table_tcache => {
1453 let type_scheme = val_dsr.read_type_scheme(dcx);
1454 let lid = DefId { krate: LOCAL_CRATE, node: id };
1455 dcx.tcx.register_item_type(lid, type_scheme);
1457 c::tag_table_param_defs => {
1458 let bounds = val_dsr.read_type_param_def(dcx);
1459 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1461 c::tag_table_method_map => {
1462 let (autoderef, method) = val_dsr.read_method_callee(dcx);
1463 let method_call = ty::MethodCall {
1465 autoderef: autoderef
1467 dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1469 c::tag_table_adjustments => {
1470 let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(dcx);
1471 dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1473 c::tag_table_closure_tys => {
1475 val_dsr.read_closure_ty(dcx);
1476 dcx.tcx.tables.borrow_mut().closure_tys.insert(DefId::local(id),
1479 c::tag_table_closure_kinds => {
1481 val_dsr.read_closure_kind(dcx);
1482 dcx.tcx.tables.borrow_mut().closure_kinds.insert(DefId::local(id),
1485 c::tag_table_cast_kinds => {
1487 val_dsr.read_cast_kind(dcx);
1488 dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1490 c::tag_table_const_qualif => {
1491 let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1492 dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1496 &format!("unknown tag found in side tables: {:x}",
1503 debug!(">< Side table doc loaded");
1507 // ______________________________________________________________________
1508 // Testing of astencode_gen
1511 fn encode_item_ast(rbml_w: &mut Encoder, item: &hir::Item) {
1512 rbml_w.start_tag(c::tag_tree as usize);
1513 (*item).encode(rbml_w);
1518 fn decode_item_ast(par_doc: rbml::Doc) -> hir::Item {
1519 let chi_doc = par_doc.get(c::tag_tree as usize);
1520 let mut d = reader::Decoder::new(chi_doc);
1521 Decodable::decode(&mut d).unwrap()
1526 fn call_site(&self) -> codemap::Span;
1527 fn cfg(&self) -> ast::CrateConfig;
1528 fn ident_of(&self, st: &str) -> ast::Ident;
1529 fn name_of(&self, st: &str) -> ast::Name;
1530 fn parse_sess(&self) -> &parse::ParseSess;
1534 impl FakeExtCtxt for parse::ParseSess {
1535 fn call_site(&self) -> codemap::Span {
1537 lo: codemap::BytePos(0),
1538 hi: codemap::BytePos(0),
1539 expn_id: codemap::NO_EXPANSION,
1542 fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1543 fn ident_of(&self, st: &str) -> ast::Ident {
1544 parse::token::str_to_ident(st)
1546 fn name_of(&self, st: &str) -> ast::Name {
1547 parse::token::intern(st)
1549 fn parse_sess(&self) -> &parse::ParseSess { self }
1553 fn mk_ctxt() -> parse::ParseSess {
1554 parse::ParseSess::new()
1558 fn roundtrip(in_item: P<hir::Item>) {
1559 let mut wr = Cursor::new(Vec::new());
1560 encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
1561 let rbml_doc = rbml::Doc::new(wr.get_ref());
1562 let out_item = decode_item_ast(rbml_doc);
1564 assert!(*in_item == out_item);
1570 roundtrip(lower_item("e_item!(&cx,
1576 fn test_smalltalk() {
1578 roundtrip(lower_item("e_item!(&cx,
1579 fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1586 roundtrip(lower_item("e_item!(&cx,
1587 fn foo(x: usize, y: usize) -> usize {
1595 fn test_simplification() {
1597 let item = quote_item!(&cx,
1598 fn new_int_alist<B>() -> alist<isize, B> {
1599 fn eq_int(a: isize, b: isize) -> bool { a == b }
1600 return alist {eq_fn: eq_int, data: Vec::new()};
1603 let hir_item = lower_item(&item);
1604 let item_in = InlinedItemRef::Item(&hir_item);
1605 let item_out = simplify_ast(item_in);
1606 let item_exp = InlinedItem::Item(lower_item("e_item!(&cx,
1607 fn new_int_alist<B>() -> alist<isize, B> {
1608 return alist {eq_fn: eq_int, data: Vec::new()};
1611 match (item_out, item_exp) {
1612 (InlinedItem::Item(item_out), InlinedItem::Item(item_exp)) => {
1613 assert!(pprust::item_to_string(&*item_out) ==
1614 pprust::item_to_string(&*item_exp));