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::tyencode;
28 use middle::ty::adjustment;
30 use middle::check_const::ConstQualif;
32 use middle::def_id::DefId;
33 use middle::privacy::{AllPublic, LastMod};
36 use middle::ty::{self, Ty};
38 use syntax::{ast, ast_util, codemap};
39 use syntax::ast::NodeIdAssigner;
40 use syntax::codemap::Span;
44 use std::io::SeekFrom;
45 use std::io::prelude::*;
49 use rbml::writer::Encoder;
52 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
53 use serialize::EncoderHelpers;
55 #[cfg(test)] use std::io::Cursor;
56 #[cfg(test)] use syntax::parse;
57 #[cfg(test)] use syntax::ast::NodeId;
58 #[cfg(test)] use rustc_front::print::pprust;
59 #[cfg(test)] use rustc_front::lowering::{lower_item, LoweringContext};
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;
74 // ______________________________________________________________________
77 pub fn encode_inlined_item(ecx: &e::EncodeContext,
81 InlinedItemRef::Item(i) => i.id,
82 InlinedItemRef::Foreign(i) => i.id,
83 InlinedItemRef::TraitItem(_, ti) => ti.id,
84 InlinedItemRef::ImplItem(_, ii) => ii.id,
86 debug!("> Encoding inlined item: {} ({:?})",
87 ecx.tcx.map.path_to_string(id),
88 rbml_w.writer.seek(SeekFrom::Current(0)));
90 // Folding could be avoided with a smarter encoder.
91 let ii = simplify_ast(ii);
92 let id_range = ii.compute_id_range();
94 rbml_w.start_tag(c::tag_ast as usize);
95 id_range.encode(rbml_w);
96 encode_ast(rbml_w, &ii);
97 encode_side_tables_for_ii(ecx, rbml_w, &ii);
100 debug!("< Encoded inlined fn: {} ({:?})",
101 ecx.tcx.map.path_to_string(id),
102 rbml_w.writer.seek(SeekFrom::Current(0)));
105 impl<'a, 'b, 'c, 'tcx> ast_map::FoldOps for &'a DecodeContext<'b, 'c, 'tcx> {
106 fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
107 if id == ast::DUMMY_NODE_ID {
108 // Used by ast_map to map the NodeInlinedParent.
109 self.tcx.sess.next_node_id()
114 fn new_def_id(&self, def_id: DefId) -> DefId {
115 self.tr_def_id(def_id)
117 fn new_span(&self, span: Span) -> Span {
122 /// Decodes an item from its AST in the cdata's metadata and adds it to the
124 pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
125 tcx: &ty::ctxt<'tcx>,
126 path: Vec<ast_map::PathElem>,
127 def_path: ast_map::DefPath,
130 -> Result<&'tcx InlinedItem, (Vec<ast_map::PathElem>,
132 match par_doc.opt_child(c::tag_ast) {
133 None => Err((path, def_path)),
135 let mut path_as_str = None;
136 debug!("> Decoding inlined fn: {:?}::?",
138 // Do an Option dance to use the path after it is moved below.
139 let s = ast_map::path_to_string(path.iter().cloned());
140 path_as_str = Some(s);
141 path_as_str.as_ref().map(|x| &x[..])
143 let mut ast_dsr = reader::Decoder::new(ast_doc);
144 let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
145 let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
146 let dcx = &DecodeContext {
149 from_id_range: from_id_range,
150 to_id_range: to_id_range,
151 last_filemap_index: Cell::new(0)
153 let raw_ii = decode_ast(ast_doc);
154 let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, def_path, raw_ii, dcx);
156 let name = match *ii {
157 InlinedItem::Item(ref i) => i.name,
158 InlinedItem::Foreign(ref i) => i.name,
159 InlinedItem::TraitItem(_, ref ti) => ti.name,
160 InlinedItem::ImplItem(_, ref ii) => ii.name
162 debug!("Fn named: {}", name);
163 debug!("< Decoded inlined fn: {}::{}",
164 path_as_str.unwrap(),
166 region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
167 decode_side_tables(dcx, ast_doc);
168 copy_item_types(dcx, ii, orig_did);
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.
215 pub fn tr_def_id(&self, did: DefId) -> DefId {
216 decoder::translate_def_id(self.cdata, did)
219 /// Translates a `Span` from an extern crate to the corresponding `Span`
220 /// within the local crate's codemap. `creader::import_codemap()` will
221 /// already have allocated any additionally needed FileMaps in the local
222 /// codemap as a side-effect of creating the crate_metadata's
223 /// `codemap_import_info`.
224 pub fn tr_span(&self, span: Span) -> Span {
225 let span = if span.lo > span.hi {
226 // Currently macro expansion sometimes produces invalid Span values
227 // where lo > hi. In order not to crash the compiler when trying to
228 // translate these values, let's transform them into something we
229 // can handle (and which will produce useful debug locations at
230 // least some of the time).
231 // This workaround is only necessary as long as macro expansion is
232 // not fixed. FIXME(#23480)
233 codemap::mk_sp(span.lo, span.lo)
238 let imported_filemaps = self.cdata.imported_filemaps(self.tcx.sess.codemap());
240 // Optimize for the case that most spans within a translated item
241 // originate from the same filemap.
242 let last_filemap_index = self.last_filemap_index.get();
243 let last_filemap = &imported_filemaps[last_filemap_index];
245 if span.lo >= last_filemap.original_start_pos &&
246 span.lo <= last_filemap.original_end_pos &&
247 span.hi >= last_filemap.original_start_pos &&
248 span.hi <= last_filemap.original_end_pos {
252 let mut b = imported_filemaps.len();
256 if imported_filemaps[m].original_start_pos > span.lo {
263 self.last_filemap_index.set(a);
264 &imported_filemaps[a]
268 let lo = (span.lo - filemap.original_start_pos) +
269 filemap.translated_filemap.start_pos;
270 let hi = (span.hi - filemap.original_start_pos) +
271 filemap.translated_filemap.start_pos;
273 codemap::mk_sp(lo, hi)
278 fn tr(&self, dcx: &DecodeContext) -> DefId {
283 impl tr for Option<DefId> {
284 fn tr(&self, dcx: &DecodeContext) -> Option<DefId> {
285 self.map(|d| dcx.tr_def_id(d))
290 fn tr(&self, dcx: &DecodeContext) -> Span {
295 trait def_id_encoder_helpers {
296 fn emit_def_id(&mut self, did: DefId);
299 impl<S:serialize::Encoder> def_id_encoder_helpers for S
300 where <S as serialize::serialize::Encoder>::Error: Debug
302 fn emit_def_id(&mut self, did: DefId) {
303 did.encode(self).unwrap()
307 trait def_id_decoder_helpers {
308 fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId;
309 fn read_def_id_nodcx(&mut self,
310 cdata: &cstore::crate_metadata) -> DefId;
313 impl<D:serialize::Decoder> def_id_decoder_helpers for D
314 where <D as serialize::serialize::Decoder>::Error: Debug
316 fn read_def_id(&mut self, dcx: &DecodeContext) -> DefId {
317 let did: DefId = Decodable::decode(self).unwrap();
321 fn read_def_id_nodcx(&mut self,
322 cdata: &cstore::crate_metadata)
324 let did: DefId = Decodable::decode(self).unwrap();
325 decoder::translate_def_id(cdata, did)
329 // ______________________________________________________________________
330 // Encoding and decoding the AST itself
332 // When decoding, we have to renumber the AST so that the node ids that
333 // appear within are disjoint from the node ids in our existing ASTs.
334 // We also have to adjust the spans: for now we just insert a dummy span,
335 // but eventually we should add entries to the local codemap as required.
337 fn encode_ast(rbml_w: &mut Encoder, item: &InlinedItem) {
338 rbml_w.start_tag(c::tag_tree as usize);
343 struct NestedItemsDropper;
345 impl Folder for NestedItemsDropper {
346 fn fold_block(&mut self, blk: P<hir::Block>) -> P<hir::Block> {
347 blk.and_then(|hir::Block {id, stmts, expr, rules, span, ..}| {
348 let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
349 let use_stmt = match stmt.node {
350 hir::StmtExpr(_, _) | hir::StmtSemi(_, _) => true,
351 hir::StmtDecl(ref decl, _) => {
353 hir::DeclLocal(_) => true,
354 hir::DeclItem(_) => false,
364 let blk_sans_items = P(hir::Block {
365 stmts: stmts_sans_items,
371 fold::noop_fold_block(blk_sans_items, self)
376 // Produces a simplified copy of the AST which does not include things
377 // that we do not need to or do not want to export. For example, we
378 // do not include any nested items: if these nested items are to be
379 // inlined, their AST will be exported separately (this only makes
380 // sense because, in Rust, nested items are independent except for
381 // their visibility).
383 // As it happens, trans relies on the fact that we do not export
384 // nested items, as otherwise it would get confused when translating
386 fn simplify_ast(ii: InlinedItemRef) -> InlinedItem {
387 let mut fld = NestedItemsDropper;
390 // HACK we're not dropping items.
391 InlinedItemRef::Item(i) => {
392 InlinedItem::Item(fold::noop_fold_item(P(i.clone()), &mut fld)
393 .expect_one("expected one item"))
395 InlinedItemRef::TraitItem(d, ti) => {
396 InlinedItem::TraitItem(d,
397 fold::noop_fold_trait_item(P(ti.clone()), &mut fld)
398 .expect_one("noop_fold_trait_item must produce \
399 exactly one trait item"))
401 InlinedItemRef::ImplItem(d, ii) => {
402 InlinedItem::ImplItem(d,
403 fold::noop_fold_impl_item(P(ii.clone()), &mut fld)
404 .expect_one("noop_fold_impl_item must produce \
405 exactly one impl item"))
407 InlinedItemRef::Foreign(i) => {
408 InlinedItem::Foreign(fold::noop_fold_foreign_item(P(i.clone()), &mut fld))
413 fn decode_ast(par_doc: rbml::Doc) -> InlinedItem {
414 let chi_doc = par_doc.get(c::tag_tree as usize);
415 let mut d = reader::Decoder::new(chi_doc);
416 Decodable::decode(&mut d).unwrap()
419 // ______________________________________________________________________
420 // Encoding and decoding of ast::def
422 fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> def::Def {
423 let def: def::Def = Decodable::decode(dsr).unwrap();
427 impl tr for def::Def {
428 fn tr(&self, dcx: &DecodeContext) -> def::Def {
430 def::DefFn(did, is_ctor) => def::DefFn(did.tr(dcx), is_ctor),
431 def::DefMethod(did) => def::DefMethod(did.tr(dcx)),
432 def::DefSelfTy(opt_did, impl_ids) => { def::DefSelfTy(opt_did.map(|did| did.tr(dcx)),
433 impl_ids.map(|(nid1, nid2)| {
437 def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
438 def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
439 def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
440 def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
441 def::DefAssociatedConst(did) => def::DefAssociatedConst(did.tr(dcx)),
442 def::DefLocal(_, nid) => {
443 let nid = dcx.tr_id(nid);
444 let did = dcx.tcx.map.local_def_id(nid);
445 def::DefLocal(did, nid)
447 def::DefVariant(e_did, v_did, is_s) => {
448 def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
450 def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
451 def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
452 def::DefAssociatedTy(trait_did, did) =>
453 def::DefAssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
454 def::DefPrimTy(p) => def::DefPrimTy(p),
455 def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
456 def::DefUse(did) => def::DefUse(did.tr(dcx)),
457 def::DefUpvar(_, nid1, index, nid2) => {
458 let nid1 = dcx.tr_id(nid1);
459 let nid2 = dcx.tr_id(nid2);
460 let did1 = dcx.tcx.map.local_def_id(nid1);
461 def::DefUpvar(did1, nid1, index, nid2)
463 def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
464 def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
469 // ______________________________________________________________________
470 // Encoding and decoding of freevar information
472 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
473 (*fv).encode(rbml_w).unwrap();
476 trait rbml_decoder_helper {
477 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
479 fn read_capture_mode(&mut self) -> hir::CaptureClause;
482 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
483 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
485 let fv: ty::Freevar = Decodable::decode(self).unwrap();
489 fn read_capture_mode(&mut self) -> hir::CaptureClause {
490 let cm: hir::CaptureClause = Decodable::decode(self).unwrap();
495 impl tr for ty::Freevar {
496 fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
498 def: self.def.tr(dcx),
499 span: self.span.tr(dcx),
504 // ______________________________________________________________________
505 // Encoding and decoding of MethodCallee
507 trait read_method_callee_helper<'tcx> {
508 fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
509 -> (u32, ty::MethodCallee<'tcx>);
512 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
513 rbml_w: &mut Encoder,
515 method: &ty::MethodCallee<'tcx>) {
516 use serialize::Encoder;
518 rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
519 rbml_w.emit_struct_field("autoderef", 0, |rbml_w| {
520 autoderef.encode(rbml_w)
522 rbml_w.emit_struct_field("def_id", 1, |rbml_w| {
523 Ok(rbml_w.emit_def_id(method.def_id))
525 rbml_w.emit_struct_field("ty", 2, |rbml_w| {
526 Ok(rbml_w.emit_ty(ecx, method.ty))
528 rbml_w.emit_struct_field("substs", 3, |rbml_w| {
529 Ok(rbml_w.emit_substs(ecx, &method.substs))
534 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
535 fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
536 -> (u32, ty::MethodCallee<'tcx>) {
538 self.read_struct("MethodCallee", 4, |this| {
539 let autoderef = this.read_struct_field("autoderef", 0,
540 Decodable::decode).unwrap();
541 Ok((autoderef, ty::MethodCallee {
542 def_id: this.read_struct_field("def_id", 1, |this| {
543 Ok(this.read_def_id(dcx))
545 ty: this.read_struct_field("ty", 2, |this| {
546 Ok(this.read_ty(dcx))
548 substs: this.read_struct_field("substs", 3, |this| {
549 Ok(dcx.tcx.mk_substs(this.read_substs(dcx)))
556 pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
557 kind.encode(ebml_w).unwrap();
560 // ______________________________________________________________________
561 // Encoding and decoding the side tables
563 trait get_ty_str_ctxt<'tcx> {
564 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
567 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
568 fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
570 diag: self.tcx.sess.diagnostic(),
571 ds: e::def_to_string,
573 abbrevs: &self.type_abbrevs
578 trait rbml_writer_helpers<'tcx> {
579 fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region);
580 fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
581 fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
582 fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
583 predicate: &ty::Predicate<'tcx>);
584 fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
585 ty: &ty::TraitRef<'tcx>);
586 fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
587 substs: &subst::Substs<'tcx>);
588 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
589 bounds: &ty::ExistentialBounds<'tcx>);
590 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
591 fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture);
592 fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
593 adj: &adjustment::AutoAdjustment<'tcx>);
594 fn emit_autoref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
595 autoref: &adjustment::AutoRef<'tcx>);
596 fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
597 auto_deref_ref: &adjustment::AutoDerefRef<'tcx>);
600 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
601 fn emit_region(&mut self, ecx: &e::EncodeContext, r: ty::Region) {
602 self.emit_opaque(|this| Ok(e::write_region(ecx, this, r)));
605 fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
606 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
609 fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
610 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
613 fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
614 trait_ref: &ty::TraitRef<'tcx>) {
615 self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
618 fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
619 predicate: &ty::Predicate<'tcx>) {
620 self.emit_opaque(|this| {
621 Ok(tyencode::enc_predicate(this,
627 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
628 bounds: &ty::ExistentialBounds<'tcx>) {
629 self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
634 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
635 self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
640 fn emit_upvar_capture(&mut self, ecx: &e::EncodeContext, capture: &ty::UpvarCapture) {
641 use serialize::Encoder;
643 self.emit_enum("UpvarCapture", |this| {
645 ty::UpvarCapture::ByValue => {
646 this.emit_enum_variant("ByValue", 1, 0, |_| Ok(()))
648 ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind, region }) => {
649 this.emit_enum_variant("ByRef", 2, 0, |this| {
650 this.emit_enum_variant_arg(0,
651 |this| kind.encode(this));
652 this.emit_enum_variant_arg(1,
653 |this| Ok(this.emit_region(ecx, region)))
660 fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
661 substs: &subst::Substs<'tcx>) {
662 self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
667 fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
668 adj: &adjustment::AutoAdjustment<'tcx>) {
669 use serialize::Encoder;
671 self.emit_enum("AutoAdjustment", |this| {
673 adjustment::AdjustReifyFnPointer=> {
674 this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
677 adjustment::AdjustUnsafeFnPointer => {
678 this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
683 adjustment::AdjustDerefRef(ref auto_deref_ref) => {
684 this.emit_enum_variant("AdjustDerefRef", 3, 2, |this| {
685 this.emit_enum_variant_arg(0,
686 |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
693 fn emit_autoref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
694 autoref: &adjustment::AutoRef<'tcx>) {
695 use serialize::Encoder;
697 self.emit_enum("AutoRef", |this| {
699 &adjustment::AutoPtr(r, m) => {
700 this.emit_enum_variant("AutoPtr", 0, 2, |this| {
701 this.emit_enum_variant_arg(0,
702 |this| Ok(this.emit_region(ecx, *r)));
703 this.emit_enum_variant_arg(1, |this| m.encode(this))
706 &adjustment::AutoUnsafe(m) => {
707 this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
708 this.emit_enum_variant_arg(0, |this| m.encode(this))
715 fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
716 auto_deref_ref: &adjustment::AutoDerefRef<'tcx>) {
717 use serialize::Encoder;
719 self.emit_struct("AutoDerefRef", 2, |this| {
720 this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
722 this.emit_struct_field("autoref", 1, |this| {
723 this.emit_option(|this| {
724 match auto_deref_ref.autoref {
725 None => this.emit_option_none(),
726 Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a))),
731 this.emit_struct_field("unsize", 2, |this| {
732 this.emit_option(|this| {
733 match auto_deref_ref.unsize {
734 None => this.emit_option_none(),
735 Some(target) => this.emit_option_some(|this| {
736 Ok(this.emit_ty(ecx, target))
745 trait write_tag_and_id {
746 fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
747 fn id(&mut self, id: ast::NodeId);
750 impl<'a> write_tag_and_id for Encoder<'a> {
752 tag_id: c::astencode_tag,
754 F: FnOnce(&mut Encoder<'a>),
756 self.start_tag(tag_id as usize);
761 fn id(&mut self, id: ast::NodeId) {
762 id.encode(self).unwrap();
766 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
767 ecx: &'a e::EncodeContext<'c, 'tcx>,
768 rbml_w: &'a mut Encoder<'b>,
771 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
772 SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
773 fn visit_id(&mut self, id: ast::NodeId) {
774 encode_side_tables_for_id(self.ecx, self.rbml_w, id)
778 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
779 rbml_w: &mut Encoder,
781 rbml_w.start_tag(c::tag_table as usize);
782 ii.visit_ids(&mut SideTableEncodingIdVisitor {
789 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
790 rbml_w: &mut Encoder,
794 debug!("Encoding side tables for id {}", id);
796 if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
797 rbml_w.tag(c::tag_table_def, |rbml_w| {
799 def.encode(rbml_w).unwrap();
803 if let Some(ty) = tcx.node_types().get(&id) {
804 rbml_w.tag(c::tag_table_node_type, |rbml_w| {
806 rbml_w.emit_ty(ecx, *ty);
810 if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
811 rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
813 rbml_w.emit_substs(ecx, &item_substs.substs);
817 if let Some(fv) = tcx.freevars.borrow().get(&id) {
818 rbml_w.tag(c::tag_table_freevars, |rbml_w| {
820 rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
821 Ok(encode_freevar_entry(rbml_w, fv_entry))
826 rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
829 let var_id = freevar.def.var_id();
830 let upvar_id = ty::UpvarId {
834 let upvar_capture = tcx.tables
840 var_id.encode(rbml_w);
841 rbml_w.emit_upvar_capture(ecx, &upvar_capture);
846 let method_call = ty::MethodCall::expr(id);
847 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
848 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
850 encode_method_callee(ecx, rbml_w, method_call.autoderef, method)
854 if let Some(adjustment) = tcx.tables.borrow().adjustments.get(&id) {
856 adjustment::AdjustDerefRef(ref adj) => {
857 for autoderef in 0..adj.autoderefs {
858 let method_call = ty::MethodCall::autoderef(id, autoderef as u32);
859 if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
860 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
862 encode_method_callee(ecx, rbml_w,
863 method_call.autoderef, method)
871 rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
873 rbml_w.emit_auto_adjustment(ecx, adjustment);
877 if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
878 rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
880 encode_cast_kind(rbml_w, *cast_kind)
884 if let Some(qualif) = tcx.const_qualif_map.borrow().get(&id) {
885 rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
887 qualif.encode(rbml_w).unwrap()
892 trait doc_decoder_helpers: Sized {
893 fn as_int(&self) -> isize;
894 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
897 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
898 fn as_int(&self) -> isize { reader::doc_as_u64(*self) as isize }
899 fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
900 reader::maybe_get_doc(*self, tag as usize)
904 trait rbml_decoder_decoder_helpers<'tcx> {
905 fn read_ty_encoded<'a, 'b, F, R>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>,
907 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x, 'tcx>) -> R;
909 fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region;
910 fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
911 fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
912 fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
913 -> ty::TraitRef<'tcx>;
914 fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
915 -> ty::PolyTraitRef<'tcx>;
916 fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
917 -> ty::Predicate<'tcx>;
918 fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
919 -> ty::ExistentialBounds<'tcx>;
920 fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
921 -> subst::Substs<'tcx>;
922 fn read_upvar_capture(&mut self, dcx: &DecodeContext)
924 fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
925 -> adjustment::AutoAdjustment<'tcx>;
926 fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
928 fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
929 -> adjustment::AutoDerefRef<'tcx>;
930 fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
931 -> adjustment::AutoRef<'tcx>;
932 fn convert_def_id(&mut self,
937 // Versions of the type reading functions that don't need the full
939 fn read_ty_nodcx(&mut self,
940 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
941 fn read_tys_nodcx(&mut self,
942 tcx: &ty::ctxt<'tcx>,
943 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
944 fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
945 cdata: &cstore::crate_metadata)
946 -> subst::Substs<'tcx>;
949 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
950 fn read_ty_nodcx(&mut self,
951 tcx: &ty::ctxt<'tcx>,
952 cdata: &cstore::crate_metadata)
954 self.read_opaque(|_, doc| {
956 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
957 &mut |id| decoder::translate_def_id(cdata, id))
962 fn read_tys_nodcx(&mut self,
963 tcx: &ty::ctxt<'tcx>,
964 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
965 self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
971 fn read_substs_nodcx(&mut self,
972 tcx: &ty::ctxt<'tcx>,
973 cdata: &cstore::crate_metadata)
974 -> subst::Substs<'tcx>
976 self.read_opaque(|_, doc| {
978 tydecode::TyDecoder::with_doc(tcx, cdata.cnum, doc,
979 &mut |id| decoder::translate_def_id(cdata, id))
984 fn read_ty_encoded<'b, 'c, F, R>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>, op: F) -> R
985 where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x,'tcx>) -> R
987 return self.read_opaque(|this, doc| {
988 debug!("read_ty_encoded({})", type_string(doc));
990 &mut tydecode::TyDecoder::with_doc(
991 dcx.tcx, dcx.cdata.cnum, doc,
992 &mut |a| this.convert_def_id(dcx, a))))
995 fn type_string(doc: rbml::Doc) -> String {
996 let mut str = String::new();
997 for i in doc.start..doc.end {
998 str.push(doc.data[i] as char);
1003 fn read_region(&mut self, dcx: &DecodeContext) -> ty::Region {
1004 // Note: regions types embed local node ids. In principle, we
1005 // should translate these node ids into the new decode
1006 // context. However, we do not bother, because region types
1007 // are not used during trans. This also applies to read_ty.
1008 return self.read_ty_encoded(dcx, |decoder| decoder.parse_region());
1010 fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1011 return self.read_ty_encoded(dcx, |decoder| decoder.parse_ty());
1014 fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1016 self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1019 fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1020 -> ty::TraitRef<'tcx> {
1021 self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref())
1024 fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1025 -> ty::PolyTraitRef<'tcx> {
1026 ty::Binder(self.read_ty_encoded(dcx, |decoder| decoder.parse_trait_ref()))
1029 fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1030 -> ty::Predicate<'tcx>
1032 self.read_ty_encoded(dcx, |decoder| decoder.parse_predicate())
1035 fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1036 -> ty::ExistentialBounds<'tcx>
1038 self.read_ty_encoded(dcx, |decoder| decoder.parse_existential_bounds())
1041 fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1042 -> subst::Substs<'tcx> {
1043 self.read_opaque(|this, doc| {
1044 Ok(tydecode::TyDecoder::with_doc(dcx.tcx, dcx.cdata.cnum, doc,
1045 &mut |a| this.convert_def_id(dcx, a))
1049 fn read_upvar_capture(&mut self, dcx: &DecodeContext) -> ty::UpvarCapture {
1050 self.read_enum("UpvarCapture", |this| {
1051 let variants = ["ByValue", "ByRef"];
1052 this.read_enum_variant(&variants, |this, i| {
1054 1 => ty::UpvarCapture::ByValue,
1055 2 => ty::UpvarCapture::ByRef(ty::UpvarBorrow {
1056 kind: this.read_enum_variant_arg(0,
1057 |this| Decodable::decode(this)).unwrap(),
1058 region: this.read_enum_variant_arg(1,
1059 |this| Ok(this.read_region(dcx))).unwrap()
1061 _ => panic!("bad enum variant for ty::UpvarCapture")
1066 fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1067 -> adjustment::AutoAdjustment<'tcx> {
1068 self.read_enum("AutoAdjustment", |this| {
1069 let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer", "AdjustDerefRef"];
1070 this.read_enum_variant(&variants, |this, i| {
1072 1 => adjustment::AdjustReifyFnPointer,
1073 2 => adjustment::AdjustUnsafeFnPointer,
1075 let auto_deref_ref: adjustment::AutoDerefRef =
1076 this.read_enum_variant_arg(0,
1077 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1079 adjustment::AdjustDerefRef(auto_deref_ref)
1081 _ => panic!("bad enum variant for adjustment::AutoAdjustment")
1087 fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1088 -> adjustment::AutoDerefRef<'tcx> {
1089 self.read_struct("AutoDerefRef", 2, |this| {
1090 Ok(adjustment::AutoDerefRef {
1091 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1092 Decodable::decode(this)
1094 autoref: this.read_struct_field("autoref", 1, |this| {
1095 this.read_option(|this, b| {
1097 Ok(Some(this.read_autoref(dcx)))
1103 unsize: this.read_struct_field("unsize", 2, |this| {
1104 this.read_option(|this, b| {
1106 Ok(Some(this.read_ty(dcx)))
1116 fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1117 -> adjustment::AutoRef<'tcx> {
1118 self.read_enum("AutoRef", |this| {
1119 let variants = ["AutoPtr", "AutoUnsafe"];
1120 this.read_enum_variant(&variants, |this, i| {
1124 this.read_enum_variant_arg(0, |this| {
1125 Ok(this.read_region(dcx))
1127 let m: hir::Mutability =
1128 this.read_enum_variant_arg(1, |this| {
1129 Decodable::decode(this)
1132 adjustment::AutoPtr(dcx.tcx.mk_region(r), m)
1135 let m: hir::Mutability =
1136 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1138 adjustment::AutoUnsafe(m)
1140 _ => panic!("bad enum variant for adjustment::AutoRef")
1146 fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1149 Decodable::decode(self).unwrap()
1152 /// Converts a def-id that appears in a type. The correct
1153 /// translation will depend on what kind of def-id this is.
1154 /// This is a subtle point: type definitions are not
1155 /// inlined into the current crate, so if the def-id names
1156 /// a nominal type or type alias, then it should be
1157 /// translated to refer to the source crate.
1159 /// However, *type parameters* are cloned along with the function
1160 /// they are attached to. So we should translate those def-ids
1161 /// to refer to the new, cloned copy of the type parameter.
1162 /// We only see references to free type parameters in the body of
1163 /// an inlined function. In such cases, we need the def-id to
1164 /// be a local id so that the TypeContents code is able to lookup
1165 /// the relevant info in the ty_param_defs table.
1167 /// *Region parameters*, unfortunately, are another kettle of fish.
1168 /// In such cases, def_id's can appear in types to distinguish
1169 /// shadowed bound regions and so forth. It doesn't actually
1170 /// matter so much what we do to these, since regions are erased
1171 /// at trans time, but it's good to keep them consistent just in
1172 /// case. We translate them with `tr_def_id()` which will map
1173 /// the crate numbers back to the original source crate.
1175 /// Scopes will end up as being totally bogus. This can actually
1176 /// be fixed though.
1178 /// Unboxed closures are cloned along with the function being
1179 /// inlined, and all side tables use interned node IDs, so we
1180 /// translate their def IDs accordingly.
1182 /// It'd be really nice to refactor the type repr to not include
1183 /// def-ids so that all these distinctions were unnecessary.
1184 fn convert_def_id(&mut self,
1185 dcx: &DecodeContext,
1188 let r = dcx.tr_def_id(did);
1189 debug!("convert_def_id(did={:?})={:?}", did, r);
1194 fn decode_side_tables(dcx: &DecodeContext,
1195 ast_doc: rbml::Doc) {
1196 let tbl_doc = ast_doc.get(c::tag_table as usize);
1197 for (tag, entry_doc) in reader::docs(tbl_doc) {
1198 let mut entry_dsr = reader::Decoder::new(entry_doc);
1199 let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
1200 let id = dcx.tr_id(id0);
1202 debug!(">> Side table document with tag 0x{:x} \
1203 found for id {} (orig {})",
1205 let tag = tag as u32;
1206 let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
1210 &format!("unknown tag found in side tables: {:x}",
1214 let val_dsr = &mut entry_dsr;
1217 c::tag_table_def => {
1218 let def = decode_def(dcx, val_dsr);
1219 dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
1221 // This doesn't matter cross-crate.
1222 last_private: LastMod(AllPublic),
1226 c::tag_table_node_type => {
1227 let ty = val_dsr.read_ty(dcx);
1228 debug!("inserting ty for node {}: {:?}",
1230 dcx.tcx.node_type_insert(id, ty);
1232 c::tag_table_item_subst => {
1233 let item_substs = ty::ItemSubsts {
1234 substs: val_dsr.read_substs(dcx)
1236 dcx.tcx.tables.borrow_mut().item_substs.insert(
1239 c::tag_table_freevars => {
1240 let fv_info = val_dsr.read_to_vec(|val_dsr| {
1241 Ok(val_dsr.read_freevar_entry(dcx))
1242 }).unwrap().into_iter().collect();
1243 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1245 c::tag_table_upvar_capture_map => {
1246 let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1247 let upvar_id = ty::UpvarId {
1248 var_id: dcx.tr_id(var_id),
1251 let ub = val_dsr.read_upvar_capture(dcx);
1252 dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub);
1254 c::tag_table_method_map => {
1255 let (autoderef, method) = val_dsr.read_method_callee(dcx);
1256 let method_call = ty::MethodCall {
1258 autoderef: autoderef
1260 dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
1262 c::tag_table_adjustments => {
1264 val_dsr.read_auto_adjustment(dcx);
1265 dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
1267 c::tag_table_cast_kinds => {
1269 val_dsr.read_cast_kind(dcx);
1270 dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1272 c::tag_table_const_qualif => {
1273 let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1274 dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1278 &format!("unknown tag found in side tables: {:x}",
1285 debug!(">< Side table doc loaded");
1289 // copy the tcache entries from the original item to the new
1291 fn copy_item_types(dcx: &DecodeContext, ii: &InlinedItem, orig_did: DefId) {
1292 fn copy_item_type(dcx: &DecodeContext,
1293 inlined_id: ast::NodeId,
1294 remote_did: DefId) {
1295 let inlined_did = dcx.tcx.map.local_def_id(inlined_id);
1296 dcx.tcx.register_item_type(inlined_did,
1297 dcx.tcx.lookup_item_type(remote_did));
1300 // copy the entry for the item itself
1301 let item_node_id = match ii {
1302 &InlinedItem::Item(ref i) => i.id,
1303 &InlinedItem::TraitItem(_, ref ti) => ti.id,
1304 &InlinedItem::ImplItem(_, ref ii) => ii.id,
1305 &InlinedItem::Foreign(ref fi) => fi.id
1307 copy_item_type(dcx, item_node_id, orig_did);
1309 // copy the entries of inner items
1310 if let &InlinedItem::Item(ref item) = ii {
1312 hir::ItemEnum(ref def, _) => {
1313 let orig_def = dcx.tcx.lookup_adt_def(orig_did);
1314 for (i_variant, orig_variant) in
1315 def.variants.iter().zip(orig_def.variants.iter())
1317 debug!("astencode: copying variant {:?} => {:?}",
1318 orig_variant.did, i_variant.node.id);
1319 copy_item_type(dcx, i_variant.node.def.id, orig_variant.did);
1322 hir::ItemStruct(ref def, _) => {
1323 if def.kind != hir::VariantKind::Dict {
1324 let ctor_did = dcx.tcx.lookup_adt_def(orig_did)
1325 .struct_variant().did;
1326 debug!("astencode: copying ctor {:?} => {:?}", ctor_did,
1328 copy_item_type(dcx, ctor_id, ctor_did);
1336 // ______________________________________________________________________
1337 // Testing of astencode_gen
1340 fn encode_item_ast(rbml_w: &mut Encoder, item: &hir::Item) {
1341 rbml_w.start_tag(c::tag_tree as usize);
1342 (*item).encode(rbml_w);
1347 fn decode_item_ast(par_doc: rbml::Doc) -> hir::Item {
1348 let chi_doc = par_doc.get(c::tag_tree as usize);
1349 let mut d = reader::Decoder::new(chi_doc);
1350 Decodable::decode(&mut d).unwrap()
1355 fn call_site(&self) -> codemap::Span;
1356 fn cfg(&self) -> ast::CrateConfig;
1357 fn ident_of(&self, st: &str) -> ast::Ident;
1358 fn name_of(&self, st: &str) -> ast::Name;
1359 fn parse_sess(&self) -> &parse::ParseSess;
1363 impl FakeExtCtxt for parse::ParseSess {
1364 fn call_site(&self) -> codemap::Span {
1366 lo: codemap::BytePos(0),
1367 hi: codemap::BytePos(0),
1368 expn_id: codemap::NO_EXPANSION,
1371 fn cfg(&self) -> ast::CrateConfig { Vec::new() }
1372 fn ident_of(&self, st: &str) -> ast::Ident {
1373 parse::token::str_to_ident(st)
1375 fn name_of(&self, st: &str) -> ast::Name {
1376 parse::token::intern(st)
1378 fn parse_sess(&self) -> &parse::ParseSess { self }
1382 struct FakeNodeIdAssigner;
1385 // It should go without saying that this may give unexpected results. Avoid
1386 // lowering anything which needs new nodes.
1387 impl NodeIdAssigner for FakeNodeIdAssigner {
1388 fn next_node_id(&self) -> NodeId {
1392 fn peek_node_id(&self) -> NodeId {
1398 fn mk_ctxt() -> parse::ParseSess {
1399 parse::ParseSess::new()
1403 fn roundtrip(in_item: P<hir::Item>) {
1404 let mut wr = Cursor::new(Vec::new());
1405 encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
1406 let rbml_doc = rbml::Doc::new(wr.get_ref());
1407 let out_item = decode_item_ast(rbml_doc);
1409 assert!(*in_item == out_item);
1415 let fnia = FakeNodeIdAssigner;
1416 let lcx = LoweringContext::new(&fnia, None);
1417 roundtrip(lower_item(&lcx, "e_item!(&cx,
1423 fn test_smalltalk() {
1425 let fnia = FakeNodeIdAssigner;
1426 let lcx = LoweringContext::new(&fnia, None);
1427 roundtrip(lower_item(&lcx, "e_item!(&cx,
1428 fn foo() -> isize { 3 + 4 } // first smalltalk program ever executed.
1435 let fnia = FakeNodeIdAssigner;
1436 let lcx = LoweringContext::new(&fnia, None);
1437 roundtrip(lower_item(&lcx, "e_item!(&cx,
1438 fn foo(x: usize, y: usize) -> usize {
1446 fn test_simplification() {
1448 let item = quote_item!(&cx,
1449 fn new_int_alist<B>() -> alist<isize, B> {
1450 fn eq_int(a: isize, b: isize) -> bool { a == b }
1451 return alist {eq_fn: eq_int, data: Vec::new()};
1454 let fnia = FakeNodeIdAssigner;
1455 let lcx = LoweringContext::new(&fnia, None);
1456 let hir_item = lower_item(&lcx, &item);
1457 let item_in = InlinedItemRef::Item(&hir_item);
1458 let item_out = simplify_ast(item_in);
1459 let item_exp = InlinedItem::Item(lower_item(&lcx, "e_item!(&cx,
1460 fn new_int_alist<B>() -> alist<isize, B> {
1461 return alist {eq_fn: eq_int, data: Vec::new()};
1464 match (item_out, item_exp) {
1465 (InlinedItem::Item(item_out), InlinedItem::Item(item_exp)) => {
1466 assert!(pprust::item_to_string(&*item_out) ==
1467 pprust::item_to_string(&*item_exp));