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;
30 use middle::ty::adjustment;
32 use middle::check_const::ConstQualif;
34 use middle::def_id::{DefId, LOCAL_CRATE};
35 use middle::privacy::{AllPublic, LastMod};
38 use middle::subst::VecPerParamSpace;
39 use middle::ty::{self, Ty};
41 use syntax::{ast, ast_util, codemap};
42 use syntax::codemap::Span;
46 use std::io::SeekFrom;
47 use std::io::prelude::*;
51 use rbml::writer::Encoder;
54 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
55 use serialize::EncoderHelpers;
57 #[cfg(test)] use std::io::Cursor;
58 #[cfg(test)] use syntax::parse;
59 #[cfg(test)] use rustc_front::print::pprust;
60 #[cfg(test)] use rustc_front::lowering::lower_item;
62 struct DecodeContext<'a, 'b, 'tcx: 'a> {
63 tcx: &'a ty::ctxt<'tcx>,
64 cdata: &'b cstore::crate_metadata,
65 from_id_range: ast_util::IdRange,
66 to_id_range: ast_util::IdRange,
67 // Cache the last used filemap for translating spans as an optimization.
68 last_filemap_index: Cell<usize>,
72 fn tr(&self, dcx: &DecodeContext) -> Self;
76 fn tr_intern(&self, dcx: &DecodeContext) -> DefId;
79 // ______________________________________________________________________
82 pub fn encode_inlined_item(ecx: &e::EncodeContext,
86 InlinedItemRef::Item(i) => i.id,
87 InlinedItemRef::Foreign(i) => i.id,
88 InlinedItemRef::TraitItem(_, ti) => ti.id,
89 InlinedItemRef::ImplItem(_, ii) => ii.id,
91 debug!("> Encoding inlined item: {} ({:?})",
92 ecx.tcx.map.path_to_string(id),
93 rbml_w.writer.seek(SeekFrom::Current(0)));
95 // Folding could be avoided with a smarter encoder.
96 let ii = simplify_ast(ii);
97 let id_range = ii.compute_id_range();
99 rbml_w.start_tag(c::tag_ast as usize);
100 id_range.encode(rbml_w);
101 encode_ast(rbml_w, &ii);
102 encode_side_tables_for_ii(ecx, rbml_w, &ii);
105 debug!("< Encoded inlined fn: {} ({:?})",
106 ecx.tcx.map.path_to_string(id),
107 rbml_w.writer.seek(SeekFrom::Current(0)));
110 impl<'a, 'b, 'c, 'tcx> ast_map::FoldOps for &'a DecodeContext<'b, 'c, 'tcx> {
111 fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
112 if id == ast::DUMMY_NODE_ID {
113 // Used by ast_map to map the NodeInlinedParent.
114 self.tcx.sess.next_node_id()
119 fn new_def_id(&self, def_id: DefId) -> DefId {
120 self.tr_def_id(def_id)
122 fn new_span(&self, span: Span) -> Span {
127 /// Decodes an item from its AST in the cdata's metadata and adds it to the
129 pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
130 tcx: &ty::ctxt<'tcx>,
131 path: Vec<ast_map::PathElem>,
133 -> Result<&'tcx InlinedItem, Vec<ast_map::PathElem>> {
134 match par_doc.opt_child(c::tag_ast) {
137 let mut path_as_str = None;
138 debug!("> Decoding inlined fn: {:?}::?",
140 // Do an Option dance to use the path after it is moved below.
141 let s = ast_map::path_to_string(path.iter().cloned());
142 path_as_str = Some(s);
143 path_as_str.as_ref().map(|x| &x[..])
145 let mut ast_dsr = reader::Decoder::new(ast_doc);
146 let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
147 let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
148 let dcx = &DecodeContext {
151 from_id_range: from_id_range,
152 to_id_range: to_id_range,
153 last_filemap_index: Cell::new(0)
155 let raw_ii = decode_ast(ast_doc);
156 let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, raw_ii, dcx);
158 let ident = match *ii {
159 InlinedItem::Item(ref i) => i.ident,
160 InlinedItem::Foreign(ref i) => i.ident,
161 InlinedItem::TraitItem(_, ref ti) => ti.ident,
162 InlinedItem::ImplItem(_, ref ii) => ii.ident
164 debug!("Fn named: {}", ident);
165 debug!("< Decoded inlined fn: {}::{}",
166 path_as_str.unwrap(),
168 region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
169 decode_side_tables(dcx, ast_doc);
171 InlinedItem::Item(ref i) => {
172 debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
173 ::rustc_front::print::pprust::item_to_string(&**i));
182 // ______________________________________________________________________
183 // Enumerating the IDs which appear in an AST
185 fn reserve_id_range(sess: &Session,
186 from_id_range: ast_util::IdRange) -> ast_util::IdRange {
187 // Handle the case of an empty range:
188 if from_id_range.empty() { return from_id_range; }
189 let cnt = from_id_range.max - from_id_range.min;
190 let to_id_min = sess.reserve_node_ids(cnt);
191 let to_id_max = to_id_min + cnt;
192 ast_util::IdRange { min: to_id_min, max: to_id_max }
195 impl<'a, 'b, 'tcx> DecodeContext<'a, 'b, 'tcx> {
196 /// Translates an internal id, meaning a node id that is known to refer to some part of the
197 /// item currently being inlined, such as a local variable or argument. All naked node-ids
198 /// that appear in types have this property, since if something might refer to an external item
199 /// we would use a def-id to allow for the possibility that the item resides in another crate.
200 pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
201 // from_id_range should be non-empty
202 assert!(!self.from_id_range.empty());
203 // Use wrapping arithmetic because otherwise it introduces control flow.
204 // Maybe we should just have the control flow? -- aatch
205 (id.wrapping_sub(self.from_id_range.min).wrapping_add(self.to_id_range.min))
208 /// Translates an EXTERNAL def-id, converting the crate number from the one used in the encoded
209 /// data to the current crate numbers.. By external, I mean that it be translated to a
210 /// reference to the item in its original crate, as opposed to being translated to a reference
211 /// to the inlined version of the item. This is typically, but not always, what you want,
212 /// because most def-ids refer to external things like types or other fns that may or may not
213 /// be inlined. Note that even when the inlined function is referencing itself recursively, we
214 /// would want `tr_def_id` for that reference--- conceptually the function calls the original,
215 /// non-inlined version, and trans deals with linking that recursive call to the inlined copy.
217 /// However, there are a *few* cases where def-ids are used but we know that the thing being
218 /// referenced is in fact *internal* to the item being inlined. In those cases, you should use
219 /// `tr_intern_def_id()` below.
220 pub fn tr_def_id(&self, did: DefId) -> DefId {
222 decoder::translate_def_id(self.cdata, did)
225 /// Translates an INTERNAL def-id, meaning a def-id that is
226 /// known to refer to some part of the item currently being
227 /// inlined. In that case, we want to convert the def-id to
228 /// refer to the current crate and to the new, inlined node-id.
229 pub fn tr_intern_def_id(&self, did: DefId) -> DefId {
230 assert_eq!(did.krate, LOCAL_CRATE);
231 DefId { krate: LOCAL_CRATE, node: self.tr_id(did.node) }
234 /// Translates a `Span` from an extern crate to the corresponding `Span`
235 /// within the local crate's codemap. `creader::import_codemap()` will
236 /// already have allocated any additionally needed FileMaps in the local
237 /// codemap as a side-effect of creating the crate_metadata's
238 /// `codemap_import_info`.
239 pub fn tr_span(&self, span: Span) -> Span {
240 let span = if span.lo > span.hi {
241 // Currently macro expansion sometimes produces invalid Span values
242 // where lo > hi. In order not to crash the compiler when trying to
243 // translate these values, let's transform them into something we
244 // can handle (and which will produce useful debug locations at
245 // least some of the time).
246 // This workaround is only necessary as long as macro expansion is
247 // not fixed. FIXME(#23480)
248 codemap::mk_sp(span.lo, span.lo)
253 let imported_filemaps = self.cdata.imported_filemaps(self.tcx.sess.codemap());
255 // Optimize for the case that most spans within a translated item
256 // originate from the same filemap.
257 let last_filemap_index = self.last_filemap_index.get();
258 let last_filemap = &imported_filemaps[last_filemap_index];
260 if span.lo >= last_filemap.original_start_pos &&
261 span.lo <= last_filemap.original_end_pos &&
262 span.hi >= last_filemap.original_start_pos &&
263 span.hi <= last_filemap.original_end_pos {
267 let mut b = imported_filemaps.len();
271 if imported_filemaps[m].original_start_pos > span.lo {
278 self.last_filemap_index.set(a);
279 &imported_filemaps[a]
283 let lo = (span.lo - filemap.original_start_pos) +
284 filemap.translated_filemap.start_pos;
285 let hi = (span.hi - filemap.original_start_pos) +
286 filemap.translated_filemap.start_pos;
288 codemap::mk_sp(lo, hi)
292 impl tr_intern for DefId {
293 fn tr_intern(&self, dcx: &DecodeContext) -> DefId {
294 dcx.tr_intern_def_id(*self)
299 fn tr(&self, dcx: &DecodeContext) -> DefId {
304 impl tr for Option<DefId> {
305 fn tr(&self, dcx: &DecodeContext) -> Option<DefId> {
306 self.map(|d| dcx.tr_def_id(d))
311 fn tr(&self, dcx: &DecodeContext) -> Span {
316 trait def_id_encoder_helpers {
317 fn emit_def_id(&mut self, did: DefId);
320 impl<S:serialize::Encoder> def_id_encoder_helpers for S
321 where <S as serialize::serialize::Encoder>::Error: Debug
323 fn emit_def_id(&mut self, did: DefId) {
324 did.encode(self).unwrap()
328 trait def_id_decoder_helpers {
329 fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId;
330 fn read_def_id_nodcx(&mut self,
331 cdata: &cstore::crate_metadata) -> DefId;
334 impl<D:serialize::Decoder> def_id_decoder_helpers for D
335 where <D as serialize::serialize::Decoder>::Error: Debug
337 fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId {
338 let did: DefId = Decodable::decode(self).unwrap();
342 fn read_def_id_nodcx(&mut self,
343 cdata: &cstore::crate_metadata)
345 let did: DefId = Decodable::decode(self).unwrap();
346 decoder::translate_def_id(cdata, did)
350 // ______________________________________________________________________
351 // Encoding and decoding the AST itself
353 // When decoding, we have to renumber the AST so that the node ids that
354 // appear within are disjoint from the node ids in our existing ASTs.
355 // We also have to adjust the spans: for now we just insert a dummy span,
356 // but eventually we should add entries to the local codemap as required.
358 fn encode_ast(rbml_w: &mut Encoder, item: &InlinedItem) {
359 rbml_w.start_tag(c::tag_tree as usize);
364 struct NestedItemsDropper;
366 impl Folder for NestedItemsDropper {
367 fn fold_block(&mut self, blk: P<hir::Block>) -> P<hir::Block> {
368 blk.and_then(|hir::Block {id, stmts, expr, rules, span, ..}| {
369 let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
370 let use_stmt = match stmt.node {
371 hir::StmtExpr(_, _) | hir::StmtSemi(_, _) => true,
372 hir::StmtDecl(ref decl, _) => {
374 hir::DeclLocal(_) => true,
375 hir::DeclItem(_) => false,
385 let blk_sans_items = P(hir::Block {
386 stmts: stmts_sans_items,
392 fold::noop_fold_block(blk_sans_items, self)
397 // Produces a simplified copy of the AST which does not include things
398 // that we do not need to or do not want to export. For example, we
399 // do not include any nested items: if these nested items are to be
400 // inlined, their AST will be exported separately (this only makes
401 // sense because, in Rust, nested items are independent except for
402 // their visibility).
404 // As it happens, trans relies on the fact that we do not export
405 // nested items, as otherwise it would get confused when translating
407 fn simplify_ast(ii: InlinedItemRef) -> InlinedItem {
408 let mut fld = NestedItemsDropper;
411 // HACK we're not dropping items.
412 InlinedItemRef::Item(i) => {
413 InlinedItem::Item(fold::noop_fold_item(P(i.clone()), &mut fld)
414 .expect_one("expected one item"))
416 InlinedItemRef::TraitItem(d, ti) => {
417 InlinedItem::TraitItem(d,
418 fold::noop_fold_trait_item(P(ti.clone()), &mut fld)
419 .expect_one("noop_fold_trait_item must produce \
420 exactly one trait item"))
422 InlinedItemRef::ImplItem(d, ii) => {
423 InlinedItem::ImplItem(d,
424 fold::noop_fold_impl_item(P(ii.clone()), &mut fld)
425 .expect_one("noop_fold_impl_item must produce \
426 exactly one impl item"))
428 InlinedItemRef::Foreign(i) => {
429 InlinedItem::Foreign(fold::noop_fold_foreign_item(P(i.clone()), &mut fld))
434 fn decode_ast(par_doc: rbml::Doc) -> InlinedItem {
435 let chi_doc = par_doc.get(c::tag_tree as usize);
436 let mut d = reader::Decoder::new(chi_doc);
437 Decodable::decode(&mut d).unwrap()
440 // ______________________________________________________________________
441 // Encoding and decoding of ast::def
443 fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> def::Def {
444 let def: def::Def = Decodable::decode(dsr).unwrap();
448 impl tr for def::Def {
449 fn tr(&self, dcx: &DecodeContext) -> def::Def {
451 def::DefFn(did, is_ctor) => def::DefFn(did.tr(dcx), is_ctor),
452 def::DefMethod(did) => def::DefMethod(did.tr(dcx)),
453 def::DefSelfTy(opt_did, impl_ids) => { def::DefSelfTy(opt_did.map(|did| did.tr(dcx)),
454 impl_ids.map(|(nid1, nid2)| {
458 def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
459 def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
460 def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
461 def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
462 def::DefAssociatedConst(did) => def::DefAssociatedConst(did.tr(dcx)),
463 def::DefLocal(nid) => { def::DefLocal(dcx.tr_id(nid)) }
464 def::DefVariant(e_did, v_did, is_s) => {
465 def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
467 def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
468 def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
469 def::DefAssociatedTy(trait_did, did) =>
470 def::DefAssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
471 def::DefPrimTy(p) => def::DefPrimTy(p),
472 def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
473 def::DefUse(did) => def::DefUse(did.tr(dcx)),
474 def::DefUpvar(nid1, index, nid2) => {
475 def::DefUpvar(dcx.tr_id(nid1), index, dcx.tr_id(nid2))
477 def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
478 def::DefRegion(nid) => def::DefRegion(dcx.tr_id(nid)),
479 def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
484 // ______________________________________________________________________
485 // Encoding and decoding of freevar information
487 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
488 (*fv).encode(rbml_w).unwrap();
491 trait rbml_decoder_helper {
492 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
494 fn read_capture_mode(&mut self) -> hir::CaptureClause;
497 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
498 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
500 let fv: ty::Freevar = Decodable::decode(self).unwrap();
504 fn read_capture_mode(&mut self) -> hir::CaptureClause {
505 let cm: hir::CaptureClause = Decodable::decode(self).unwrap();
510 impl tr for ty::Freevar {
511 fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
513 def: self.def.tr(dcx),
514 span: self.span.tr(dcx),
519 // ______________________________________________________________________
520 // Encoding and decoding of MethodCallee
522 trait read_method_callee_helper<'tcx> {
523 fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
524 -> (u32, ty::MethodCallee<'tcx>);
527 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
528 rbml_w: &mut Encoder,
530 method: &ty::MethodCallee<'tcx>) {
531 use serialize::Encoder;
533 rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
534 rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
535 autoderef.encode(rbml_w)
537 rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
538 Ok(rbml_w.emit_def_id(method.def_id))
540 rbml_w.emit_struct_field("ty", 2, |rbml_w| {
541 Ok(rbml_w.emit_ty(ecx, method.ty))
543 rbml_w.emit_struct_field("substs", 3, |rbml_w| {
544 Ok(rbml_w.emit_substs(ecx, &method.substs))
549 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
550 fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
551 -> (u32, ty::MethodCallee<'tcx>) {
553 self.read_struct("MethodCallee", 4, |this| {
554 let autoderef = this.read_struct_field("autoderef", 0,
555 Decodable::decode).unwrap();
556 Ok((autoderef, ty::MethodCallee {
557 def_id: this.read_struct_field("def_id", 1, |this| {
558 Ok(this.read_def_id(dcx))
560 ty: this.read_struct_field("ty", 2, |this| {
561 Ok(this.read_ty(dcx))
563 substs: this.read_struct_field("substs", 3, |this| {
564 Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
571 pub fn encode_closure_kind(ebml_w: &mut Encoder, kind: ty::ClosureKind) {
572 kind.encode(ebml_w).unwrap();
575 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
576 kind.encode(ebml_w).unwrap();
579 pub trait vtable_decoder_helpers<'tcx> {
580 fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
581 F: FnMut(&mut Self) -> T;
584 impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> {
585 fn read_vec_per_param_space<T, F>(&mut self, mut f: F) -> VecPerParamSpace<T> where
586 F: FnMut(&mut reader::Decoder<'a>) -> T,
588 let types = self.read_to_vec(|this| Ok(f(this))).unwrap();
589 let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap();
590 let fns = self.read_to_vec(|this| Ok(f(this))).unwrap();
591 VecPerParamSpace::new(types, selfs, fns)
595 // ___________________________________________________________________________
598 fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder,
599 v: &subst::VecPerParamSpace<T>,
601 F: FnMut(&mut Encoder, &T),
603 for &space in &subst::ParamSpace::all() {
604 rbml_w.emit_from_vec(v.get_slice(space),
605 |rbml_w, n| Ok(f(rbml_w, n))).unwrap();
609 // ______________________________________________________________________
610 // Encoding and decoding the side tables
612 trait get_ty_str_ctxt<'tcx> {
613 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
616 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
617 fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
619 diag: self.tcx.sess.diagnostic(),
620 ds: e::def_to_string,
622 abbrevs: &self.type_abbrevs
627 trait rbml_writer_helpers<'tcx> {
628 fn emit_closure_type<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
629 closure_type: &ty::ClosureTy<'tcx>);
630 fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region);
631 fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
632 fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
633 fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
634 type_param_def: &ty::TypeParameterDef<'tcx>);
635 fn emit_region_param_def(&mut self, ecx: &e::EncodeContext,
636 region_param_def: &ty::RegionParameterDef);
637 fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
638 predicate: &ty::Predicate<'tcx>);
639 fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
640 ty: &ty::TraitRef<'tcx>);
641 fn emit_type_scheme<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
642 type_scheme: ty::TypeScheme<'tcx>);
643 fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
644 substs: &subst::Substs<'tcx>);
645 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
646 bounds: &ty::ExistentialBounds<'tcx>);
647 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
648 fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture);
649 fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
650 adj: &adjustment::AutoAdjustment<'tcx>);
651 fn emit_autoref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
652 autoref: &adjustment::AutoRef<'tcx>);
653 fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
654 auto_deref_ref: &adjustment::AutoDerefRef<'tcx>);
657 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
658 fn emit_closure_type<'b>(&mut self,
659 ecx: &e::EncodeContext<'b, 'tcx>,
660 closure_type: &ty::ClosureTy<'tcx>) {
661 self.emit_opaque(|this| {
662 Ok(e::write_closure_type(ecx, this, closure_type))
666 fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region) {
667 self.emit_opaque(|this| Ok(e::write_region(ecx, this, r)));
670 fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
671 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
674 fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
675 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
678 fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
679 trait_ref: &ty::TraitRef<'tcx>) {
680 self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
683 fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
684 type_param_def: &ty::TypeParameterDef<'tcx>) {
685 self.emit_opaque(|this| {
686 Ok(tyencode::enc_type_param_def(this,
691 fn emit_region_param_def(&mut self, ecx: &e::EncodeContext,
692 region_param_def: &ty::RegionParameterDef) {
693 self.emit_opaque(|this| {
694 Ok(tyencode::enc_region_param_def(this,
699 fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
700 predicate: &ty::Predicate<'tcx>) {
701 self.emit_opaque(|this| {
702 Ok(tyencode::enc_predicate(this,
708 fn emit_type_scheme<'b>(&mut self,
709 ecx: &e::EncodeContext<'b, 'tcx>,
710 type_scheme: ty::TypeScheme<'tcx>) {
711 use serialize::Encoder;
713 self.emit_struct("TypeScheme", 2, |this| {
714 this.emit_struct_field("generics", 0, |this| {
715 this.emit_struct("Generics", 2, |this| {
716 this.emit_struct_field("types", 0, |this| {
717 Ok(encode_vec_per_param_space(
718 this, &type_scheme.generics.types,
719 |this, def| this.emit_type_param_def(ecx, def)))
721 this.emit_struct_field("regions", 1, |this| {
722 Ok(encode_vec_per_param_space(
723 this, &type_scheme.generics.regions,
724 |this, def| this.emit_region_param_def(ecx, def)))
728 this.emit_struct_field("ty", 1, |this| {
729 Ok(this.emit_ty(ecx, type_scheme.ty))
734 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
735 bounds: &ty::ExistentialBounds<'tcx>) {
736 self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
741 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
742 self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
747 fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture) {
748 use serialize::Encoder;
750 self.emit_enum("UpvarCapture", |this| {
752 ty::UpvarCapture::ByValue => {
753 this.emit_enum_variant("ByValue", 1, 0, |_| Ok(()))
755 ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind, region }) => {
756 this.emit_enum_variant("ByRef", 2, 0, |this| {
757 this.emit_enum_variant_arg(0,
758 |this| kind.encode(this));
759 this.emit_enum_variant_arg(1,
760 |this| Ok(this.emit_region(ecx, region)))
767 fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
768 substs: &subst::Substs<'tcx>) {
769 self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
774 fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
775 adj: &adjustment::AutoAdjustment<'tcx>) {
776 use serialize::Encoder;
778 self.emit_enum("AutoAdjustment", |this| {
780 adjustment::AdjustReifyFnPointer=> {
781 this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
784 adjustment::AdjustUnsafeFnPointer => {
785 this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
790 adjustment::AdjustDerefRef(ref auto_deref_ref) => {
791 this.emit_enum_variant("AdjustDerefRef", 3, 2, |this| {
792 this.emit_enum_variant_arg(0,
793 |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
800 fn emit_autoref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
801 autoref: &adjustment::AutoRef<'tcx>) {
802 use serialize::Encoder;
804 self.emit_enum("AutoRef", |this| {
806 &adjustment::AutoPtr(r, m) => {
807 this.emit_enum_variant("AutoPtr", 0, 2, |this| {
808 this.emit_enum_variant_arg(0,
809 |this| Ok(this.emit_region(ecx, *r)));
810 this.emit_enum_variant_arg(1, |this| m.encode(this))
813 &adjustment::AutoUnsafe(m) => {
814 this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
815 this.emit_enum_variant_arg(0, |this| m.encode(this))
822 fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
823 auto_deref_ref: &adjustment::AutoDerefRef<'tcx>) {
824 use serialize::Encoder;
826 self.emit_struct("AutoDerefRef", 2, |this| {
827 this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
829 this.emit_struct_field("autoref", 1, |this| {
830 this.emit_option(|this| {
831 match auto_deref_ref.autoref {
832 None => this.emit_option_none(),
833 Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a))),
838 this.emit_struct_field("unsize", 2, |this| {
839 this.emit_option(|this| {
840 match auto_deref_ref.unsize {
841 None => this.emit_option_none(),
842 Some(target) => this.emit_option_some(|this| {
843 Ok(this.emit_ty(ecx, target))
852 trait write_tag_and_id {
853 fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
854 fn id(&mut self, id: ast::NodeId);
857 impl<'a> write_tag_and_id for Encoder<'a> {
859 tag_id: c::astencode_tag,
861 F: FnOnce(&mut Encoder<'a>),
863 self.start_tag(tag_id as usize);
868 fn id(&mut self, id: ast::NodeId) {
869 id.encode(self).unwrap();
873 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
874 ecx: &'a e::EncodeContext<'c, 'tcx>,
875 rbml_w: &'a mut Encoder<'b>,
878 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
879 SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
880 fn visit_id(&mut self, id: ast::NodeId) {
881 encode_side_tables_for_id(self.ecx, self.rbml_w, id)
885 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
886 rbml_w: &mut Encoder,
888 rbml_w.start_tag(c::tag_table as usize);
889 ii.visit_ids(&mut SideTableEncodingIdVisitor {
896 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
897 rbml_w: &mut Encoder,
901 debug!("Encoding side tables for id {}", id);
903 if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
904 rbml_w.tag(c::tag_table_def, |rbml_w| {
906 def.encode(rbml_w).unwrap();
910 if let Some(ty) = tcx.node_types().get(&id) {
911 rbml_w.tag(c::tag_table_node_type, |rbml_w| {
913 rbml_w.emit_ty(ecx, *ty);
917 if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
918 rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
920 rbml_w.emit_substs(ecx, &item_substs.substs);
924 if let Some(fv) = tcx.freevars.borrow().get(&id) {
925 rbml_w.tag(c::tag_table_freevars, |rbml_w| {
927 rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
928 Ok(encode_freevar_entry(rbml_w, fv_entry))
933 rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
936 let var_id = freevar.def.def_id().node;
937 let upvar_id = ty::UpvarId {
941 let upvar_capture = tcx.tables
947 var_id.encode(rbml_w);
948 rbml_w.emit_upvar_capture(ecx, &upvar_capture);
953 let lid = DefId { krate: LOCAL_CRATE, node: id };
954 if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
955 rbml_w.tag(c::tag_table_tcache, |rbml_w| {
957 rbml_w.emit_type_scheme(ecx, type_scheme.clone());
961 if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
962 rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
964 rbml_w.emit_type_param_def(ecx, type_param_def)
968 let method_call = ty::MethodCall::expr(id);
969 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
970 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
972 encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
976 if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
978 adjustment::AdjustDerefRef(ref adj) => {
979 for autoderef in 0..adj.autoderefs {
980 let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
981 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
982 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
984 encode_method_callee(ecx, rbml_w,
985 method_call.autoderef, method)
993 rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
995 rbml_w.emit_auto_adjustment(ecx, adjustment);
999 if let Some(closure_type) = tcx.tables.borrow().closure_tys.get(&DefId::local(id)) {
1000 rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
1002 rbml_w.emit_closure_type(ecx, closure_type);
1006 if let Some(closure_kind) = tcx.tables.borrow().closure_kinds.get(&DefId::local(id)) {
1007 rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
1009 encode_closure_kind(rbml_w, *closure_kind)
1013 if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
1014 rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
1016 encode_cast_kind(rbml_w, *cast_kind)
1020 if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
1021 rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
1023 qualif.encode(rbml_w).unwrap()
1028 trait doc_decoder_helpers: Sized {
1029 fn as_int(&self) -> isize;
1030 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1033 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
1034 fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
1035 fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
1036 reader::maybe_get_doc(*self, tag as usize)
1040 trait rbml_decoder_decoder_helpers<'tcx> {
1041 fn read_ty_encoded<'a, 'b, F, R>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>,
1043 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x, 'tcx>) -> R;
1045 fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region;
1046 fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
1047 fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
1048 fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1049 -> ty::TraitRef<'tcx>;
1050 fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1051 -> ty::PolyTraitRef<'tcx>;
1052 fn read_type_param_def<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1053 -> ty::TypeParameterDef<'tcx>;
1054 fn read_region_param_def(&mut self, dcx: &DecodeContext)
1055 -> ty::RegionParameterDef;
1056 fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1057 -> ty::Predicate<'tcx>;
1058 fn read_type_scheme<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1059 -> ty::TypeScheme<'tcx>;
1060 fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1061 -> ty::ExistentialBounds<'tcx>;
1062 fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1063 -> subst::Substs<'tcx>;
1064 fn read_upvar_capture(&mut self, dcx: &DecodeContext)
1065 -> ty::UpvarCapture;
1066 fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1067 -> adjustment::AutoAdjustment<'tcx>;
1068 fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1070 fn read_closure_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1072 fn read_closure_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1073 -> ty::ClosureTy<'tcx>;
1074 fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1075 -> adjustment::AutoDerefRef<'tcx>;
1076 fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1077 -> adjustment::AutoRef<'tcx>;
1078 fn convert_def_id(&mut self,
1079 dcx: &DecodeContext,
1080 source: DefIdSource,
1084 // Versions of the type reading functions that don't need the full
1086 fn read_ty_nodcx(&mut self,
1087 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
1088 fn read_tys_nodcx(&mut self,
1089 tcx: &ty::ctxt<'tcx>,
1090 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
1091 fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
1092 cdata: &cstore::crate_metadata)
1093 -> subst::Substs<'tcx>;
1096 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
1097 fn read_ty_nodcx(&mut self,
1098 tcx: &ty::ctxt<'tcx>,
1099 cdata: &cstore::crate_metadata)
1101 self.read_opaque(|_, doc| {
1103 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
1104 &mut |_, id| decoder::translate_def_id(cdata, id))
1109 fn read_tys_nodcx(&mut self,
1110 tcx: &ty::ctxt<'tcx>,
1111 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
1112 self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
1118 fn read_substs_nodcx(&mut self,
1119 tcx: &ty::ctxt<'tcx>,
1120 cdata: &cstore::crate_metadata)
1121 -> subst::Substs<'tcx>
1123 self.read_opaque(|_, doc| {
1125 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
1126 &mut |_, id| decoder::translate_def_id(cdata, id))
1131 fn read_ty_encoded<'b, 'c, F, R>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>, op: F) -> R
1132 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x,'tcx>) -> R
1134 return self.read_opaque(|this, doc| {
1135 debug!("read_ty_encoded({})", type_string(doc));
1137 &mut tydecode::TyDecoder::with_doc(
1138 dcx.tcx, dcx.cdata.cnum, doc,
1139 &mut |s, a| this.convert_def_id(dcx, s, a))))
1142 fn type_string(doc: rbml::Doc) -> String {
1143 let mut str = String::new();
1144 for i in doc.start..doc.end {
1145 str.push(doc.data[i] as char);
1150 fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region {
1151 // Note: regions types embed local node ids. In principle, we
1152 // should translate these node ids into the new decode
1153 // context. However, we do not bother, because region types
1154 // are not used during trans. This also applies to read_ty.
1155 return self.read_ty_encoded(dcx, |decoder| decoder.parse_region());
1157 fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1158 return self.read_ty_encoded(dcx, |decoder| decoder.parse_ty());
1161 fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1163 self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1166 fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1167 -> ty::TraitRef<'tcx> {
1168 self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref())
1171 fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1172 -> ty::PolyTraitRef<'tcx> {
1173 ty::Binder(self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref()))
1176 fn read_type_param_def<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1177 -> ty::TypeParameterDef<'tcx> {
1178 self.read_ty_encoded(dcx, |decoder| decoder.parse_type_param_def())
1180 fn read_region_param_def(&mut self, dcx: &DecodeContext)
1181 -> ty::RegionParameterDef {
1182 self.read_ty_encoded(dcx, |decoder| decoder.parse_region_param_def())
1184 fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1185 -> ty::Predicate<'tcx>
1187 self.read_ty_encoded(dcx, |decoder| decoder.parse_predicate())
1190 fn read_type_scheme<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1191 -> ty::TypeScheme<'tcx> {
1192 self.read_struct("TypeScheme", 3, |this| {
1194 generics: this.read_struct_field("generics", 0, |this| {
1195 this.read_struct("Generics", 2, |this| {
1198 this.read_struct_field("types", 0, |this| {
1199 Ok(this.read_vec_per_param_space(
1200 |this| this.read_type_param_def(dcx)))
1204 this.read_struct_field("regions", 1, |this| {
1205 Ok(this.read_vec_per_param_space(
1206 |this| this.read_region_param_def(dcx)))
1211 ty: this.read_struct_field("ty", 1, |this| {
1212 Ok(this.read_ty(dcx))
1218 fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1219 -> ty::ExistentialBounds<'tcx>
1221 self.read_ty_encoded(dcx, |decoder| decoder.parse_existential_bounds())
1224 fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1225 -> subst::Substs<'tcx> {
1226 self.read_opaque(|this, doc| {
1227 Ok(tydecode::TyDecoder::with_doc(dcx.tcx, dcx.cdata.cnum, doc,
1228 &mut |s, a| this.convert_def_id(dcx, s, a))
1232 fn read_upvar_capture(&mut self, dcx: &DecodeContext) -> ty::UpvarCapture {
1233 self.read_enum("UpvarCapture", |this| {
1234 let variants = ["ByValue", "ByRef"];
1235 this.read_enum_variant(&variants, |this, i| {
1237 1 => ty::UpvarCapture::ByValue,
1238 2 => ty::UpvarCapture::ByRef(ty::UpvarBorrow {
1239 kind: this.read_enum_variant_arg(0,
1240 |this| Decodable::decode(this)).unwrap(),
1241 region: this.read_enum_variant_arg(1,
1242 |this| Ok(this.read_region(dcx))).unwrap()
1244 _ => panic!("bad enum variant for ty::UpvarCapture")
1249 fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1250 -> adjustment::AutoAdjustment<'tcx> {
1251 self.read_enum("AutoAdjustment", |this| {
1252 let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer", "AdjustDerefRef"];
1253 this.read_enum_variant(&variants, |this, i| {
1255 1 => adjustment::AdjustReifyFnPointer,
1256 2 => adjustment::AdjustUnsafeFnPointer,
1258 let auto_deref_ref: adjustment::AutoDerefRef =
1259 this.read_enum_variant_arg(0,
1260 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1262 adjustment::AdjustDerefRef(auto_deref_ref)
1264 _ => panic!("bad enum variant for adjustment::AutoAdjustment")
1270 fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1271 -> adjustment::AutoDerefRef<'tcx> {
1272 self.read_struct("AutoDerefRef", 2, |this| {
1273 Ok(adjustment::AutoDerefRef {
1274 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1275 Decodable::decode(this)
1277 autoref: this.read_struct_field("autoref", 1, |this| {
1278 this.read_option(|this, b| {
1280 Ok(Some(this.read_autoref(dcx)))
1286 unsize: this.read_struct_field("unsize", 2, |this| {
1287 this.read_option(|this, b| {
1289 Ok(Some(this.read_ty(dcx)))
1299 fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1300 -> adjustment::AutoRef<'tcx> {
1301 self.read_enum("AutoRef", |this| {
1302 let variants = ["AutoPtr", "AutoUnsafe"];
1303 this.read_enum_variant(&variants, |this, i| {
1307 this.read_enum_variant_arg(0, |this| {
1308 Ok(this.read_region(dcx))
1310 let m: hir::Mutability =
1311 this.read_enum_variant_arg(1, |this| {
1312 Decodable::decode(this)
1315 adjustment::AutoPtr(dcx.tcx.mk_region(r), m)
1318 let m: hir::Mutability =
1319 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1321 adjustment::AutoUnsafe(m)
1323 _ => panic!("bad enum variant for adjustment::AutoRef")
1329 fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1332 Decodable::decode(self).unwrap()
1335 fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1338 Decodable::decode(self).unwrap()
1341 fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1342 -> ty::ClosureTy<'tcx>
1344 self.read_ty_encoded(dcx, |decoder| decoder.parse_closure_ty())
1347 /// Converts a def-id that appears in a type. The correct
1348 /// translation will depend on what kind of def-id this is.
1349 /// This is a subtle point: type definitions are not
1350 /// inlined into the current crate, so if the def-id names
1351 /// a nominal type or type alias, then it should be
1352 /// translated to refer to the source crate.
1354 /// However, *type parameters* are cloned along with the function
1355 /// they are attached to. So we should translate those def-ids
1356 /// to refer to the new, cloned copy of the type parameter.
1357 /// We only see references to free type parameters in the body of
1358 /// an inlined function. In such cases, we need the def-id to
1359 /// be a local id so that the TypeContents code is able to lookup
1360 /// the relevant info in the ty_param_defs table.
1362 /// *Region parameters*, unfortunately, are another kettle of fish.
1363 /// In such cases, def_id's can appear in types to distinguish
1364 /// shadowed bound regions and so forth. It doesn't actually
1365 /// matter so much what we do to these, since regions are erased
1366 /// at trans time, but it's good to keep them consistent just in
1367 /// case. We translate them with `tr_def_id()` which will map
1368 /// the crate numbers back to the original source crate.
1370 /// Scopes will end up as being totally bogus. This can actually
1371 /// be fixed though.
1373 /// Unboxed closures are cloned along with the function being
1374 /// inlined, and all side tables use interned node IDs, so we
1375 /// translate their def IDs accordingly.
1377 /// It'd be really nice to refactor the type repr to not include
1378 /// def-ids so that all these distinctions were unnecessary.
1379 fn convert_def_id(&mut self,
1380 dcx: &DecodeContext,
1381 source: tydecode::DefIdSource,
1384 let r = match source {
1385 NominalType | TypeWithId | RegionParameter => dcx.tr_def_id(did),
1386 ClosureSource => dcx.tr_intern_def_id(did)
1388 debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1393 fn decode_side_tables(dcx: &DecodeContext,
1394 ast_doc: rbml::Doc) {
1395 let tbl_doc = ast_doc.get(c::tag_table as usize);
1396 for (tag, entry_doc) in reader::docs(tbl_doc) {
1397 let mut entry_dsr = reader::Decoder::new(entry_doc);
1398 let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1399 let id = dcx.tr_id(id0);
1401 debug!(">> Side table document with tag 0x{:x} \
1402 found for id {} (orig {})",
1404 let tag = tag as u32;
1405 let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1409 &format!("unknown tag found in side tables: {:x}",
1413 let val_dsr = &mut entry_dsr;
1416 c::tag_table_def => {
1417 let def = decode_def(dcx, val_dsr);
1418 dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
1420 // This doesn't matter cross-crate.
1421 last_private: LastMod(AllPublic),
1425 c::tag_table_node_type => {
1426 let ty = val_dsr.read_ty(dcx);
1427 debug!("inserting ty for node {}: {:?}",
1429 dcx.tcx.node_type_insert(id, ty);
1431 c::tag_table_item_subst => {
1432 let item_substs = ty::ItemSubsts {
1433 substs: val_dsr.read_substs(dcx)
1435 dcx.tcx.tables.borrow_mut().item_substs.insert(
1438 c::tag_table_freevars => {
1439 let fv_info = val_dsr.read_to_vec(|val_dsr| {
1440 Ok(val_dsr.read_freevar_entry(dcx))
1441 }).unwrap().into_iter().collect();
1442 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1444 c::tag_table_upvar_capture_map => {
1445 let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1446 let upvar_id = ty::UpvarId {
1447 var_id: dcx.tr_id(var_id),
1450 let ub = val_dsr.read_upvar_capture(dcx);
1451 dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub);
1453 c::tag_table_tcache => {
1454 let type_scheme = val_dsr.read_type_scheme(dcx);
1455 let lid = DefId { krate: LOCAL_CRATE, node: id };
1456 dcx.tcx.register_item_type(lid, type_scheme);
1458 c::tag_table_param_defs => {
1459 let bounds = val_dsr.read_type_param_def(dcx);
1460 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1462 c::tag_table_method_map => {
1463 let (autoderef, method) = val_dsr.read_method_callee(dcx);
1464 let method_call = ty::MethodCall {
1466 autoderef: autoderef
1468 dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1470 c::tag_table_adjustments => {
1472 val_dsr.read_auto_adjustment(dcx);
1473 dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1475 c::tag_table_closure_tys => {
1477 val_dsr.read_closure_ty(dcx);
1478 dcx.tcx.tables.borrow_mut().closure_tys.insert(DefId::local(id),
1481 c::tag_table_closure_kinds => {
1483 val_dsr.read_closure_kind(dcx);
1484 dcx.tcx.tables.borrow_mut().closure_kinds.insert(DefId::local(id),
1487 c::tag_table_cast_kinds => {
1489 val_dsr.read_cast_kind(dcx);
1490 dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1492 c::tag_table_const_qualif => {
1493 let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1494 dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1498 &format!("unknown tag found in side tables: {:x}",
1505 debug!(">< Side table doc loaded");
1509 // ______________________________________________________________________
1510 // Testing of astencode_gen
1513 fn encode_item_ast(rbml_w: &mut Encoder, item: &hir::Item) {
1514 rbml_w.start_tag(c::tag_tree as usize);
1515 (*item).encode(rbml_w);
1520 fn decode_item_ast(par_doc: rbml::Doc) -> hir::Item {
1521 let chi_doc = par_doc.get(c::tag_tree as usize);
1522 let mut d = reader::Decoder::new(chi_doc);
1523 Decodable::decode(&mut d).unwrap()
1528 fn call_site(&self) -> codemap::Span;
1529 fn cfg(&self) -> ast::CrateConfig;
1530 fn ident_of(&self, st: &str) -> ast::Ident;
1531 fn name_of(&self, st: &str) -> ast::Name;
1532 fn parse_sess(&self) -> &parse::ParseSess;
1536 impl FakeExtCtxt for parse::ParseSess {
1537 fn call_site(&self) -> codemap::Span {
1539 lo: codemap::BytePos(0),
1540 hi: codemap::BytePos(0),
1541 expn_id: codemap::NO_EXPANSION,
1544 fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1545 fn ident_of(&self, st: &str) -> ast::Ident {
1546 parse::token::str_to_ident(st)
1548 fn name_of(&self, st: &str) -> ast::Name {
1549 parse::token::intern(st)
1551 fn parse_sess(&self) -> &parse::ParseSess { self }
1555 fn mk_ctxt() -> parse::ParseSess {
1556 parse::ParseSess::new()
1560 fn roundtrip(in_item: P<hir::Item>) {
1561 let mut wr = Cursor::new(Vec::new());
1562 encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
1563 let rbml_doc = rbml::Doc::new(wr.get_ref());
1564 let out_item = decode_item_ast(rbml_doc);
1566 assert!(*in_item == out_item);
1572 roundtrip(lower_item("e_item!(&cx,
1578 fn test_smalltalk() {
1580 roundtrip(lower_item("e_item!(&cx,
1581 fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1588 roundtrip(lower_item("e_item!(&cx,
1589 fn foo(x: usize, y: usize) -> usize {
1597 fn test_simplification() {
1599 let item = quote_item!(&cx,
1600 fn new_int_alist<B>() -> alist<isize, B> {
1601 fn eq_int(a: isize, b: isize) -> bool { a == b }
1602 return alist {eq_fn: eq_int, data: Vec::new()};
1605 let hir_item = lower_item(&item);
1606 let item_in = InlinedItemRef::Item(&hir_item);
1607 let item_out = simplify_ast(item_in);
1608 let item_exp = InlinedItem::Item(lower_item("e_item!(&cx,
1609 fn new_int_alist<B>() -> alist<isize, B> {
1610 return alist {eq_fn: eq_int, data: Vec::new()};
1613 match (item_out, item_exp) {
1614 (InlinedItem::Item(item_out), InlinedItem::Item(item_exp)) => {
1615 assert!(pprust::item_to_string(&*item_out) ==
1616 pprust::item_to_string(&*item_exp));