1 // Copyright 2012-2014 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 c = metadata::common;
16 use cstore = metadata::cstore;
17 use driver::session::Session;
18 use metadata::decoder;
19 use e = metadata::encoder;
20 use middle::freevars::freevar_entry;
22 use metadata::tydecode;
23 use metadata::tydecode::{DefIdSource, NominalType, TypeWithId, TypeParameter,
25 use metadata::tyencode;
26 use middle::typeck::{MethodCall, MethodCallee, MethodOrigin};
27 use middle::{ty, typeck, moves};
29 use util::ppaux::ty_to_str;
31 use syntax::{ast, ast_map, ast_util, codemap, fold};
32 use syntax::codemap::Span;
33 use syntax::fold::Folder;
34 use syntax::parse::token;
39 use std::cell::RefCell;
41 use std::io::MemWriter;
43 use std::strbuf::StrBuf;
45 use serialize::ebml::reader;
48 use serialize::{Encoder, Encodable, EncoderHelpers, DecoderHelpers};
49 use serialize::{Decoder, Decodable};
50 use writer = serialize::ebml::writer;
52 #[cfg(test)] use syntax::parse;
53 #[cfg(test)] use syntax::print::pprust;
55 // Auxiliary maps of things to be encoded
57 pub capture_map: RefCell<middle::moves::CaptureMap>,
60 struct DecodeContext<'a> {
61 cdata: &'a cstore::crate_metadata,
66 struct ExtendedDecodeContext<'a> {
67 dcx: &'a DecodeContext<'a>,
68 from_id_range: ast_util::IdRange,
69 to_id_range: ast_util::IdRange
73 fn tr(&self, xcx: &ExtendedDecodeContext) -> Self;
77 fn tr_intern(&self, xcx: &ExtendedDecodeContext) -> ast::DefId;
80 pub type Encoder<'a> = writer::Encoder<'a, MemWriter>;
82 // ______________________________________________________________________
85 pub fn encode_inlined_item(ecx: &e::EncodeContext,
87 ii: e::InlinedItemRef,
90 e::IIItemRef(i) => i.id,
91 e::IIForeignRef(i) => i.id,
92 e::IIMethodRef(_, _, m) => m.id,
94 debug!("> Encoding inlined item: {} ({})",
95 ecx.tcx.map.path_to_str(id),
96 ebml_w.writer.tell());
98 let ii = simplify_ast(ii);
99 let id_range = ast_util::compute_id_range_for_inlined_item(&ii);
101 ebml_w.start_tag(c::tag_ast as uint);
102 id_range.encode(ebml_w);
103 encode_ast(ebml_w, ii);
104 encode_side_tables_for_ii(ecx, maps, ebml_w, &ii);
107 debug!("< Encoded inlined fn: {} ({})",
108 ecx.tcx.map.path_to_str(id),
109 ebml_w.writer.tell());
112 pub fn decode_inlined_item(cdata: &cstore::crate_metadata,
115 path: Vec<ast_map::PathElem>,
117 -> Result<ast::InlinedItem, Vec<ast_map::PathElem>> {
118 let dcx = &DecodeContext {
123 match par_doc.opt_child(c::tag_ast) {
126 let mut path_as_str = None;
127 debug!("> Decoding inlined fn: {}::?",
129 // Do an Option dance to use the path after it is moved below.
130 let s = ast_map::path_to_str(ast_map::Values(path.iter()));
131 path_as_str = Some(s);
132 path_as_str.as_ref().map(|x| x.as_slice())
134 let mut ast_dsr = reader::Decoder(ast_doc);
135 let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
136 let to_id_range = reserve_id_range(&dcx.tcx.sess, from_id_range);
137 let xcx = &ExtendedDecodeContext {
139 from_id_range: from_id_range,
140 to_id_range: to_id_range
142 let raw_ii = decode_ast(ast_doc);
143 let ii = renumber_and_map_ast(xcx, &dcx.tcx.map, path, raw_ii);
144 let ident = match ii {
145 ast::IIItem(i) => i.ident,
146 ast::IIForeign(i) => i.ident,
147 ast::IIMethod(_, _, m) => m.ident,
149 debug!("Fn named: {}", token::get_ident(ident));
150 debug!("< Decoded inlined fn: {}::{}",
151 path_as_str.unwrap(),
152 token::get_ident(ident));
153 region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, &ii);
154 decode_side_tables(xcx, ast_doc);
157 debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
158 syntax::print::pprust::item_to_str(i));
167 // ______________________________________________________________________
168 // Enumerating the IDs which appear in an AST
170 fn reserve_id_range(sess: &Session,
171 from_id_range: ast_util::IdRange) -> ast_util::IdRange {
172 // Handle the case of an empty range:
173 if from_id_range.empty() { return from_id_range; }
174 let cnt = from_id_range.max - from_id_range.min;
175 let to_id_min = sess.reserve_node_ids(cnt);
176 let to_id_max = to_id_min + cnt;
177 ast_util::IdRange { min: to_id_min, max: to_id_max }
180 impl<'a> ExtendedDecodeContext<'a> {
181 pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
183 * Translates an internal id, meaning a node id that is known
184 * to refer to some part of the item currently being inlined,
185 * such as a local variable or argument. All naked node-ids
186 * that appear in types have this property, since if something
187 * might refer to an external item we would use a def-id to
188 * allow for the possibility that the item resides in another
192 // from_id_range should be non-empty
193 assert!(!self.from_id_range.empty());
194 (id - self.from_id_range.min + self.to_id_range.min)
196 pub fn tr_def_id(&self, did: ast::DefId) -> ast::DefId {
198 * Translates an EXTERNAL def-id, converting the crate number
199 * from the one used in the encoded data to the current crate
200 * numbers.. By external, I mean that it be translated to a
201 * reference to the item in its original crate, as opposed to
202 * being translated to a reference to the inlined version of
203 * the item. This is typically, but not always, what you
204 * want, because most def-ids refer to external things like
205 * types or other fns that may or may not be inlined. Note
206 * that even when the inlined function is referencing itself
207 * recursively, we would want `tr_def_id` for that
208 * reference--- conceptually the function calls the original,
209 * non-inlined version, and trans deals with linking that
210 * recursive call to the inlined copy.
212 * However, there are a *few* cases where def-ids are used but
213 * we know that the thing being referenced is in fact *internal*
214 * to the item being inlined. In those cases, you should use
215 * `tr_intern_def_id()` below.
218 decoder::translate_def_id(self.dcx.cdata, did)
220 pub fn tr_intern_def_id(&self, did: ast::DefId) -> ast::DefId {
222 * Translates an INTERNAL def-id, meaning a def-id that is
223 * known to refer to some part of the item currently being
224 * inlined. In that case, we want to convert the def-id to
225 * refer to the current crate and to the new, inlined node-id.
228 assert_eq!(did.krate, ast::LOCAL_CRATE);
229 ast::DefId { krate: ast::LOCAL_CRATE, node: self.tr_id(did.node) }
231 pub fn tr_span(&self, _span: Span) -> Span {
232 codemap::DUMMY_SP // FIXME (#1972): handle span properly
236 impl tr_intern for ast::DefId {
237 fn tr_intern(&self, xcx: &ExtendedDecodeContext) -> ast::DefId {
238 xcx.tr_intern_def_id(*self)
242 impl tr for ast::DefId {
243 fn tr(&self, xcx: &ExtendedDecodeContext) -> ast::DefId {
248 impl tr for Option<ast::DefId> {
249 fn tr(&self, xcx: &ExtendedDecodeContext) -> Option<ast::DefId> {
250 self.map(|d| xcx.tr_def_id(d))
255 fn tr(&self, xcx: &ExtendedDecodeContext) -> Span {
260 trait def_id_encoder_helpers {
261 fn emit_def_id(&mut self, did: ast::DefId);
264 impl<S:serialize::Encoder<E>, E> def_id_encoder_helpers for S {
265 fn emit_def_id(&mut self, did: ast::DefId) {
266 did.encode(self).ok().unwrap()
270 trait def_id_decoder_helpers {
271 fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId;
272 fn read_def_id_noxcx(&mut self,
273 cdata: &cstore::crate_metadata) -> ast::DefId;
276 impl<D:serialize::Decoder<E>, E> def_id_decoder_helpers for D {
277 fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId {
278 let did: ast::DefId = Decodable::decode(self).ok().unwrap();
282 fn read_def_id_noxcx(&mut self,
283 cdata: &cstore::crate_metadata) -> ast::DefId {
284 let did: ast::DefId = Decodable::decode(self).ok().unwrap();
285 decoder::translate_def_id(cdata, did)
289 // ______________________________________________________________________
290 // Encoding and decoding the AST itself
292 // The hard work is done by an autogenerated module astencode_gen. To
293 // regenerate astencode_gen, run src/etc/gen-astencode. It will
294 // replace astencode_gen with a dummy file and regenerate its
295 // contents. If you get compile errors, the dummy file
296 // remains---resolve the errors and then rerun astencode_gen.
297 // Annoying, I know, but hopefully only temporary.
299 // When decoding, we have to renumber the AST so that the node ids that
300 // appear within are disjoint from the node ids in our existing ASTs.
301 // We also have to adjust the spans: for now we just insert a dummy span,
302 // but eventually we should add entries to the local codemap as required.
304 fn encode_ast(ebml_w: &mut Encoder, item: ast::InlinedItem) {
305 ebml_w.start_tag(c::tag_tree as uint);
310 struct NestedItemsDropper;
312 impl Folder for NestedItemsDropper {
313 fn fold_block(&mut self, blk: ast::P<ast::Block>) -> ast::P<ast::Block> {
314 let stmts_sans_items = blk.stmts.iter().filter_map(|stmt| {
316 ast::StmtExpr(_, _) | ast::StmtSemi(_, _) => Some(*stmt),
317 ast::StmtDecl(decl, _) => {
319 ast::DeclLocal(_) => Some(*stmt),
320 ast::DeclItem(_) => None,
323 ast::StmtMac(..) => fail!("unexpanded macro in astencode")
326 let blk_sans_items = ast::P(ast::Block {
327 view_items: Vec::new(), // I don't know if we need the view_items
328 // here, but it doesn't break tests!
329 stmts: stmts_sans_items,
335 fold::noop_fold_block(blk_sans_items, self)
339 // Produces a simplified copy of the AST which does not include things
340 // that we do not need to or do not want to export. For example, we
341 // do not include any nested items: if these nested items are to be
342 // inlined, their AST will be exported separately (this only makes
343 // sense because, in Rust, nested items are independent except for
344 // their visibility).
346 // As it happens, trans relies on the fact that we do not export
347 // nested items, as otherwise it would get confused when translating
349 fn simplify_ast(ii: e::InlinedItemRef) -> ast::InlinedItem {
350 let mut fld = NestedItemsDropper;
353 // HACK we're not dropping items.
354 e::IIItemRef(i) => ast::IIItem(fold::noop_fold_item(i, &mut fld)
355 .expect_one("expected one item")),
356 e::IIMethodRef(d, p, m) => ast::IIMethod(d, p, fold::noop_fold_method(m, &mut fld)),
357 e::IIForeignRef(i) => ast::IIForeign(fold::noop_fold_foreign_item(i, &mut fld))
361 fn decode_ast(par_doc: ebml::Doc) -> ast::InlinedItem {
362 let chi_doc = par_doc.get(c::tag_tree as uint);
363 let mut d = reader::Decoder(chi_doc);
364 Decodable::decode(&mut d).unwrap()
367 struct AstRenumberer<'a> {
368 xcx: &'a ExtendedDecodeContext<'a>,
371 impl<'a> ast_map::FoldOps for AstRenumberer<'a> {
372 fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
373 if id == ast::DUMMY_NODE_ID {
374 // Used by ast_map to map the NodeInlinedParent.
375 self.xcx.dcx.tcx.sess.next_node_id()
380 fn new_span(&self, span: Span) -> Span {
381 self.xcx.tr_span(span)
385 fn renumber_and_map_ast(xcx: &ExtendedDecodeContext,
387 path: Vec<ast_map::PathElem> ,
388 ii: ast::InlinedItem) -> ast::InlinedItem {
389 ast_map::map_decoded_item(map,
390 path.move_iter().collect(),
391 AstRenumberer { xcx: xcx },
395 ast::IIItem(fld.fold_item(i).expect_one("expected one item"))
397 ast::IIMethod(d, is_provided, m) => {
398 ast::IIMethod(xcx.tr_def_id(d), is_provided, fld.fold_method(m))
400 ast::IIForeign(i) => ast::IIForeign(fld.fold_foreign_item(i))
405 // ______________________________________________________________________
406 // Encoding and decoding of ast::def
408 fn decode_def(xcx: &ExtendedDecodeContext, doc: ebml::Doc) -> ast::Def {
409 let mut dsr = reader::Decoder(doc);
410 let def: ast::Def = Decodable::decode(&mut dsr).unwrap();
414 impl tr for ast::Def {
415 fn tr(&self, xcx: &ExtendedDecodeContext) -> ast::Def {
417 ast::DefFn(did, p) => ast::DefFn(did.tr(xcx), p),
418 ast::DefStaticMethod(did, wrapped_did2, p) => {
419 ast::DefStaticMethod(did.tr(xcx),
421 ast::FromTrait(did2) => {
422 ast::FromTrait(did2.tr(xcx))
424 ast::FromImpl(did2) => {
425 ast::FromImpl(did2.tr(xcx))
430 ast::DefMethod(did0, did1) => {
431 ast::DefMethod(did0.tr(xcx), did1.map(|did1| did1.tr(xcx)))
433 ast::DefSelfTy(nid) => { ast::DefSelfTy(xcx.tr_id(nid)) }
434 ast::DefMod(did) => { ast::DefMod(did.tr(xcx)) }
435 ast::DefForeignMod(did) => { ast::DefForeignMod(did.tr(xcx)) }
436 ast::DefStatic(did, m) => { ast::DefStatic(did.tr(xcx), m) }
437 ast::DefArg(nid, b) => { ast::DefArg(xcx.tr_id(nid), b) }
438 ast::DefLocal(nid, b) => { ast::DefLocal(xcx.tr_id(nid), b) }
439 ast::DefVariant(e_did, v_did, is_s) => {
440 ast::DefVariant(e_did.tr(xcx), v_did.tr(xcx), is_s)
442 ast::DefTrait(did) => ast::DefTrait(did.tr(xcx)),
443 ast::DefTy(did) => ast::DefTy(did.tr(xcx)),
444 ast::DefPrimTy(p) => ast::DefPrimTy(p),
445 ast::DefTyParam(did, v) => ast::DefTyParam(did.tr(xcx), v),
446 ast::DefBinding(nid, bm) => ast::DefBinding(xcx.tr_id(nid), bm),
447 ast::DefUse(did) => ast::DefUse(did.tr(xcx)),
448 ast::DefUpvar(nid1, def, nid2, nid3) => {
449 ast::DefUpvar(xcx.tr_id(nid1),
454 ast::DefStruct(did) => ast::DefStruct(did.tr(xcx)),
455 ast::DefRegion(nid) => ast::DefRegion(xcx.tr_id(nid)),
456 ast::DefTyParamBinder(nid) => {
457 ast::DefTyParamBinder(xcx.tr_id(nid))
459 ast::DefLabel(nid) => ast::DefLabel(xcx.tr_id(nid))
464 // ______________________________________________________________________
465 // Encoding and decoding of adjustment information
467 impl tr for ty::AutoDerefRef {
468 fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::AutoDerefRef {
470 autoderefs: self.autoderefs,
471 autoref: match self.autoref {
472 Some(ref autoref) => Some(autoref.tr(xcx)),
479 impl tr for ty::AutoRef {
480 fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::AutoRef {
481 self.map_region(|r| r.tr(xcx))
485 impl tr for ty::Region {
486 fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::Region {
488 ty::ReLateBound(id, br) => ty::ReLateBound(xcx.tr_id(id),
490 ty::ReEarlyBound(id, index, ident) => ty::ReEarlyBound(xcx.tr_id(id),
493 ty::ReScope(id) => ty::ReScope(xcx.tr_id(id)),
494 ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => *self,
495 ty::ReFree(ref fr) => {
496 ty::ReFree(ty::FreeRegion {scope_id: xcx.tr_id(fr.scope_id),
497 bound_region: fr.bound_region.tr(xcx)})
503 impl tr for ty::BoundRegion {
504 fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::BoundRegion {
507 ty::BrFresh(_) => *self,
508 ty::BrNamed(id, ident) => ty::BrNamed(xcx.tr_def_id(id),
514 impl tr for ty::TraitStore {
515 fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::TraitStore {
517 ty::RegionTraitStore(r, m) => {
518 ty::RegionTraitStore(r.tr(xcx), m)
520 ty::UniqTraitStore => ty::UniqTraitStore
525 // ______________________________________________________________________
526 // Encoding and decoding of freevar information
528 fn encode_freevar_entry(ebml_w: &mut Encoder, fv: &freevar_entry) {
529 (*fv).encode(ebml_w).unwrap();
532 trait ebml_decoder_helper {
533 fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
537 impl<'a> ebml_decoder_helper for reader::Decoder<'a> {
538 fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
540 let fv: freevar_entry = Decodable::decode(self).unwrap();
545 impl tr for freevar_entry {
546 fn tr(&self, xcx: &ExtendedDecodeContext) -> freevar_entry {
548 def: self.def.tr(xcx),
549 span: self.span.tr(xcx),
554 // ______________________________________________________________________
555 // Encoding and decoding of CaptureVar information
557 trait capture_var_helper {
558 fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
559 -> moves::CaptureVar;
562 impl<'a> capture_var_helper for reader::Decoder<'a> {
563 fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
564 -> moves::CaptureVar {
565 let cvar: moves::CaptureVar = Decodable::decode(self).unwrap();
570 impl tr for moves::CaptureVar {
571 fn tr(&self, xcx: &ExtendedDecodeContext) -> moves::CaptureVar {
573 def: self.def.tr(xcx),
574 span: self.span.tr(xcx),
580 // ______________________________________________________________________
581 // Encoding and decoding of MethodCallee
583 trait read_method_callee_helper {
584 fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee);
587 fn encode_method_callee(ecx: &e::EncodeContext,
588 ebml_w: &mut Encoder,
590 method: &MethodCallee) {
591 ebml_w.emit_struct("MethodCallee", 4, |ebml_w| {
592 ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
593 autoderef.encode(ebml_w)
595 ebml_w.emit_struct_field("origin", 1u, |ebml_w| {
596 method.origin.encode(ebml_w)
598 ebml_w.emit_struct_field("ty", 2u, |ebml_w| {
599 Ok(ebml_w.emit_ty(ecx, method.ty))
601 ebml_w.emit_struct_field("substs", 3u, |ebml_w| {
602 Ok(ebml_w.emit_substs(ecx, &method.substs))
607 impl<'a> read_method_callee_helper for reader::Decoder<'a> {
608 fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee) {
609 self.read_struct("MethodCallee", 4, |this| {
610 let autoderef = this.read_struct_field("autoderef", 0, |this| {
611 Decodable::decode(this)
613 Ok((autoderef, MethodCallee {
614 origin: this.read_struct_field("origin", 1, |this| {
615 let method_origin: MethodOrigin =
616 Decodable::decode(this).unwrap();
617 Ok(method_origin.tr(xcx))
619 ty: this.read_struct_field("ty", 2, |this| {
620 Ok(this.read_ty(xcx))
622 substs: this.read_struct_field("substs", 3, |this| {
623 Ok(this.read_substs(xcx))
630 impl tr for MethodOrigin {
631 fn tr(&self, xcx: &ExtendedDecodeContext) -> MethodOrigin {
633 typeck::MethodStatic(did) => typeck::MethodStatic(did.tr(xcx)),
634 typeck::MethodParam(ref mp) => {
636 typeck::MethodParam {
637 trait_id: mp.trait_id.tr(xcx),
642 typeck::MethodObject(ref mo) => {
643 typeck::MethodObject(
644 typeck::MethodObject {
645 trait_id: mo.trait_id.tr(xcx),
654 // ______________________________________________________________________
655 // Encoding and decoding vtable_res
657 fn encode_vtable_res_with_key(ecx: &e::EncodeContext,
658 ebml_w: &mut Encoder,
660 dr: &typeck::vtable_res) {
661 ebml_w.emit_struct("VtableWithKey", 2, |ebml_w| {
662 ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
663 autoderef.encode(ebml_w)
665 ebml_w.emit_struct_field("vtable_res", 1u, |ebml_w| {
666 Ok(encode_vtable_res(ecx, ebml_w, dr))
671 pub fn encode_vtable_res(ecx: &e::EncodeContext,
672 ebml_w: &mut Encoder,
673 dr: &typeck::vtable_res) {
674 // can't autogenerate this code because automatic code of
675 // ty::t doesn't work, and there is no way (atm) to have
676 // hand-written encoding routines combine with auto-generated
677 // ones. perhaps we should fix this.
678 ebml_w.emit_from_vec(dr.as_slice(), |ebml_w, param_tables| {
679 Ok(encode_vtable_param_res(ecx, ebml_w, param_tables))
683 pub fn encode_vtable_param_res(ecx: &e::EncodeContext,
684 ebml_w: &mut Encoder,
685 param_tables: &typeck::vtable_param_res) {
686 ebml_w.emit_from_vec(param_tables.as_slice(), |ebml_w, vtable_origin| {
687 Ok(encode_vtable_origin(ecx, ebml_w, vtable_origin))
692 pub fn encode_vtable_origin(ecx: &e::EncodeContext,
693 ebml_w: &mut Encoder,
694 vtable_origin: &typeck::vtable_origin) {
695 ebml_w.emit_enum("vtable_origin", |ebml_w| {
696 match *vtable_origin {
697 typeck::vtable_static(def_id, ref tys, ref vtable_res) => {
698 ebml_w.emit_enum_variant("vtable_static", 0u, 3u, |ebml_w| {
699 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
700 Ok(ebml_w.emit_def_id(def_id))
702 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
703 Ok(ebml_w.emit_tys(ecx, tys.as_slice()))
705 ebml_w.emit_enum_variant_arg(2u, |ebml_w| {
706 Ok(encode_vtable_res(ecx, ebml_w, vtable_res))
710 typeck::vtable_param(pn, bn) => {
711 ebml_w.emit_enum_variant("vtable_param", 1u, 2u, |ebml_w| {
712 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
715 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
724 pub trait vtable_decoder_helpers {
725 fn read_vtable_res_with_key(&mut self,
727 cdata: &cstore::crate_metadata)
728 -> (u32, typeck::vtable_res);
729 fn read_vtable_res(&mut self,
730 tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
731 -> typeck::vtable_res;
732 fn read_vtable_param_res(&mut self,
733 tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
734 -> typeck::vtable_param_res;
735 fn read_vtable_origin(&mut self,
736 tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
737 -> typeck::vtable_origin;
740 impl<'a> vtable_decoder_helpers for reader::Decoder<'a> {
741 fn read_vtable_res_with_key(&mut self,
743 cdata: &cstore::crate_metadata)
744 -> (u32, typeck::vtable_res) {
745 self.read_struct("VtableWithKey", 2, |this| {
746 let autoderef = this.read_struct_field("autoderef", 0, |this| {
747 Decodable::decode(this)
749 Ok((autoderef, this.read_struct_field("vtable_res", 1, |this| {
750 Ok(this.read_vtable_res(tcx, cdata))
755 fn read_vtable_res(&mut self,
756 tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
757 -> typeck::vtable_res {
758 self.read_to_vec(|this| Ok(this.read_vtable_param_res(tcx, cdata)))
759 .unwrap().move_iter().collect()
762 fn read_vtable_param_res(&mut self,
763 tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
764 -> typeck::vtable_param_res {
765 self.read_to_vec(|this| Ok(this.read_vtable_origin(tcx, cdata)))
766 .unwrap().move_iter().collect()
769 fn read_vtable_origin(&mut self,
770 tcx: &ty::ctxt, cdata: &cstore::crate_metadata)
771 -> typeck::vtable_origin {
772 self.read_enum("vtable_origin", |this| {
773 this.read_enum_variant(["vtable_static",
779 typeck::vtable_static(
780 this.read_enum_variant_arg(0u, |this| {
781 Ok(this.read_def_id_noxcx(cdata))
783 this.read_enum_variant_arg(1u, |this| {
784 Ok(this.read_tys_noxcx(tcx, cdata))
786 this.read_enum_variant_arg(2u, |this| {
787 Ok(this.read_vtable_res(tcx, cdata))
792 typeck::vtable_param(
793 this.read_enum_variant_arg(0u, |this| {
794 Decodable::decode(this)
796 this.read_enum_variant_arg(1u, |this| {
801 // hard to avoid - user input
802 _ => fail!("bad enum variant")
809 // ______________________________________________________________________
810 // Encoding and decoding the side tables
812 trait get_ty_str_ctxt {
813 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a>;
816 impl<'a> get_ty_str_ctxt for e::EncodeContext<'a> {
817 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a> {
819 diag: self.tcx.sess.diagnostic(),
822 abbrevs: &self.type_abbrevs
827 trait ebml_writer_helpers {
828 fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t);
829 fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]);
830 fn emit_type_param_def(&mut self,
831 ecx: &e::EncodeContext,
832 type_param_def: &ty::TypeParameterDef);
833 fn emit_tpbt(&mut self,
834 ecx: &e::EncodeContext,
835 tpbt: ty::ty_param_bounds_and_ty);
836 fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs);
837 fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment);
840 impl<'a> ebml_writer_helpers for Encoder<'a> {
841 fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t) {
842 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
845 fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]) {
846 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
849 fn emit_type_param_def(&mut self,
850 ecx: &e::EncodeContext,
851 type_param_def: &ty::TypeParameterDef) {
852 self.emit_opaque(|this| {
853 Ok(tyencode::enc_type_param_def(this.writer,
859 fn emit_tpbt(&mut self,
860 ecx: &e::EncodeContext,
861 tpbt: ty::ty_param_bounds_and_ty) {
862 self.emit_struct("ty_param_bounds_and_ty", 2, |this| {
863 this.emit_struct_field("generics", 0, |this| {
864 this.emit_struct("Generics", 2, |this| {
865 this.emit_struct_field("type_param_defs", 0, |this| {
866 this.emit_from_vec(tpbt.generics.type_param_defs(),
867 |this, type_param_def| {
868 Ok(this.emit_type_param_def(ecx, type_param_def))
871 this.emit_struct_field("region_param_defs", 1, |this| {
872 tpbt.generics.region_param_defs().encode(this)
876 this.emit_struct_field("ty", 1, |this| {
877 Ok(this.emit_ty(ecx, tpbt.ty))
882 fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs) {
883 self.emit_opaque(|this| Ok(tyencode::enc_substs(this.writer,
888 fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment) {
889 self.emit_enum("AutoAdjustment", |this| {
891 ty::AutoAddEnv(store) => {
892 this.emit_enum_variant("AutoAddEnv", 0, 1, |this| {
893 this.emit_enum_variant_arg(0, |this| store.encode(this))
897 ty::AutoDerefRef(ref auto_deref_ref) => {
898 this.emit_enum_variant("AutoDerefRef", 1, 1, |this| {
899 this.emit_enum_variant_arg(0, |this| auto_deref_ref.encode(this))
903 ty::AutoObject(store, b, def_id, ref substs) => {
904 this.emit_enum_variant("AutoObject", 2, 4, |this| {
905 this.emit_enum_variant_arg(0, |this| store.encode(this));
906 this.emit_enum_variant_arg(1, |this| b.encode(this));
907 this.emit_enum_variant_arg(2, |this| def_id.encode(this));
908 this.emit_enum_variant_arg(3, |this| Ok(this.emit_substs(ecx, substs)))
916 trait write_tag_and_id {
917 fn tag(&mut self, tag_id: c::astencode_tag, f: |&mut Self|);
918 fn id(&mut self, id: ast::NodeId);
921 impl<'a> write_tag_and_id for Encoder<'a> {
923 tag_id: c::astencode_tag,
924 f: |&mut Encoder<'a>|) {
925 self.start_tag(tag_id as uint);
930 fn id(&mut self, id: ast::NodeId) {
931 self.wr_tagged_u64(c::tag_table_id as uint, id as u64);
935 struct SideTableEncodingIdVisitor<'a,'b> {
936 ecx_ptr: *libc::c_void,
937 new_ebml_w: &'a mut Encoder<'b>,
941 impl<'a,'b> ast_util::IdVisitingOperation for
942 SideTableEncodingIdVisitor<'a,'b> {
943 fn visit_id(&self, id: ast::NodeId) {
944 // Note: this will cause a copy of ebml_w, which is bad as
945 // it is mutable. But I believe it's harmless since we generate
948 // FIXME(pcwalton): Don't copy this way.
949 let mut new_ebml_w = unsafe {
950 self.new_ebml_w.unsafe_clone()
953 let ecx: &e::EncodeContext = unsafe {
954 cast::transmute(self.ecx_ptr)
956 encode_side_tables_for_id(ecx, self.maps, &mut new_ebml_w, id)
960 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
962 ebml_w: &mut Encoder,
963 ii: &ast::InlinedItem) {
964 ebml_w.start_tag(c::tag_table as uint);
965 let mut new_ebml_w = unsafe {
966 ebml_w.unsafe_clone()
969 // Because the ast visitor uses @IdVisitingOperation, I can't pass in
970 // ecx directly, but /I/ know that it'll be fine since the lifetime is
971 // tied to the CrateContext that lives throughout this entire section.
972 ast_util::visit_ids_for_inlined_item(ii, &SideTableEncodingIdVisitor {
976 new_ebml_w: &mut new_ebml_w,
982 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
984 ebml_w: &mut Encoder,
988 debug!("Encoding side tables for id {}", id);
990 for def in tcx.def_map.borrow().find(&id).iter() {
991 ebml_w.tag(c::tag_table_def, |ebml_w| {
993 ebml_w.tag(c::tag_table_val, |ebml_w| (*def).encode(ebml_w).unwrap());
997 for &ty in tcx.node_types.borrow().find(&(id as uint)).iter() {
998 ebml_w.tag(c::tag_table_node_type, |ebml_w| {
1000 ebml_w.tag(c::tag_table_val, |ebml_w| {
1001 ebml_w.emit_ty(ecx, *ty);
1006 for tys in tcx.node_type_substs.borrow().find(&id).iter() {
1007 ebml_w.tag(c::tag_table_node_type_subst, |ebml_w| {
1009 ebml_w.tag(c::tag_table_val, |ebml_w| {
1010 ebml_w.emit_tys(ecx, tys.as_slice())
1015 for &fv in tcx.freevars.borrow().find(&id).iter() {
1016 ebml_w.tag(c::tag_table_freevars, |ebml_w| {
1018 ebml_w.tag(c::tag_table_val, |ebml_w| {
1019 ebml_w.emit_from_vec(fv.as_slice(), |ebml_w, fv_entry| {
1020 Ok(encode_freevar_entry(ebml_w, fv_entry))
1026 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1027 for &tpbt in tcx.tcache.borrow().find(&lid).iter() {
1028 ebml_w.tag(c::tag_table_tcache, |ebml_w| {
1030 ebml_w.tag(c::tag_table_val, |ebml_w| {
1031 ebml_w.emit_tpbt(ecx, tpbt.clone());
1036 for &type_param_def in tcx.ty_param_defs.borrow().find(&id).iter() {
1037 ebml_w.tag(c::tag_table_param_defs, |ebml_w| {
1039 ebml_w.tag(c::tag_table_val, |ebml_w| {
1040 ebml_w.emit_type_param_def(ecx, type_param_def)
1045 let method_call = MethodCall::expr(id);
1046 for &method in tcx.method_map.borrow().find(&method_call).iter() {
1047 ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1049 ebml_w.tag(c::tag_table_val, |ebml_w| {
1050 encode_method_callee(ecx, ebml_w, method_call.autoderef, method)
1055 for &dr in tcx.vtable_map.borrow().find(&method_call).iter() {
1056 ebml_w.tag(c::tag_table_vtable_map, |ebml_w| {
1058 ebml_w.tag(c::tag_table_val, |ebml_w| {
1059 encode_vtable_res_with_key(ecx, ebml_w, method_call.autoderef, dr);
1064 for &adj in tcx.adjustments.borrow().find(&id).iter() {
1066 ty::AutoDerefRef(adj) => {
1067 for autoderef in range(0, adj.autoderefs) {
1068 let method_call = MethodCall::autoderef(id, autoderef as u32);
1069 for &method in tcx.method_map.borrow().find(&method_call).iter() {
1070 ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1072 ebml_w.tag(c::tag_table_val, |ebml_w| {
1073 encode_method_callee(ecx, ebml_w, method_call.autoderef, method)
1078 for &dr in tcx.vtable_map.borrow().find(&method_call).iter() {
1079 ebml_w.tag(c::tag_table_vtable_map, |ebml_w| {
1081 ebml_w.tag(c::tag_table_val, |ebml_w| {
1082 encode_vtable_res_with_key(ecx, ebml_w,
1083 method_call.autoderef, dr);
1092 ebml_w.tag(c::tag_table_adjustments, |ebml_w| {
1094 ebml_w.tag(c::tag_table_val, |ebml_w| {
1095 ebml_w.emit_auto_adjustment(ecx, adj);
1100 for &cap_vars in maps.capture_map.borrow().find(&id).iter() {
1101 ebml_w.tag(c::tag_table_capture_map, |ebml_w| {
1103 ebml_w.tag(c::tag_table_val, |ebml_w| {
1104 ebml_w.emit_from_vec(cap_vars.as_slice(), |ebml_w, cap_var| {
1105 cap_var.encode(ebml_w)
1112 trait doc_decoder_helpers {
1113 fn as_int(&self) -> int;
1114 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1117 impl<'a> doc_decoder_helpers for ebml::Doc<'a> {
1118 fn as_int(&self) -> int { reader::doc_as_u64(*self) as int }
1119 fn opt_child(&self, tag: c::astencode_tag) -> Option<ebml::Doc<'a>> {
1120 reader::maybe_get_doc(*self, tag as uint)
1124 trait ebml_decoder_decoder_helpers {
1125 fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t;
1126 fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t>;
1127 fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
1128 -> ty::TypeParameterDef;
1129 fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
1130 -> ty::ty_param_bounds_and_ty;
1131 fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs;
1132 fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment;
1133 fn convert_def_id(&mut self,
1134 xcx: &ExtendedDecodeContext,
1135 source: DefIdSource,
1139 // Versions of the type reading functions that don't need the full
1140 // ExtendedDecodeContext.
1141 fn read_ty_noxcx(&mut self,
1142 tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> ty::t;
1143 fn read_tys_noxcx(&mut self,
1145 cdata: &cstore::crate_metadata) -> Vec<ty::t>;
1148 impl<'a> ebml_decoder_decoder_helpers for reader::Decoder<'a> {
1149 fn read_ty_noxcx(&mut self,
1150 tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> ty::t {
1151 self.read_opaque(|_, doc| {
1152 Ok(tydecode::parse_ty_data(
1157 |_, id| decoder::translate_def_id(cdata, id)))
1161 fn read_tys_noxcx(&mut self,
1163 cdata: &cstore::crate_metadata) -> Vec<ty::t> {
1164 self.read_to_vec(|this| Ok(this.read_ty_noxcx(tcx, cdata)) )
1170 fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t {
1171 // Note: regions types embed local node ids. In principle, we
1172 // should translate these node ids into the new decode
1173 // context. However, we do not bother, because region types
1174 // are not used during trans.
1176 return self.read_opaque(|this, doc| {
1177 debug!("read_ty({})", type_string(doc));
1179 let ty = tydecode::parse_ty_data(
1184 |s, a| this.convert_def_id(xcx, s, a));
1189 fn type_string(doc: ebml::Doc) -> ~str {
1190 let mut str = StrBuf::new();
1191 for i in range(doc.start, doc.end) {
1192 str.push_char(doc.data[i] as char);
1198 fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t> {
1199 self.read_to_vec(|this| Ok(this.read_ty(xcx))).unwrap().move_iter().collect()
1202 fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
1203 -> ty::TypeParameterDef {
1204 self.read_opaque(|this, doc| {
1205 Ok(tydecode::parse_type_param_def_data(
1210 |s, a| this.convert_def_id(xcx, s, a)))
1214 fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
1215 -> ty::ty_param_bounds_and_ty {
1216 self.read_struct("ty_param_bounds_and_ty", 2, |this| {
1217 Ok(ty::ty_param_bounds_and_ty {
1218 generics: this.read_struct_field("generics", 0, |this| {
1219 this.read_struct("Generics", 2, |this| {
1222 this.read_struct_field("type_param_defs",
1225 Ok(Rc::new(this.read_to_vec(|this|
1226 Ok(this.read_type_param_def(xcx)))
1232 this.read_struct_field("region_param_defs",
1235 Decodable::decode(this)
1240 ty: this.read_struct_field("ty", 1, |this| {
1241 Ok(this.read_ty(xcx))
1247 fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs {
1248 self.read_opaque(|this, doc| {
1249 Ok(tydecode::parse_substs_data(doc.data,
1253 |s, a| this.convert_def_id(xcx, s, a)))
1257 fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment {
1258 self.read_enum("AutoAdjustment", |this| {
1259 let variants = ["AutoAddEnv", "AutoDerefRef", "AutoObject"];
1260 this.read_enum_variant(variants, |this, i| {
1263 let store: ty::TraitStore =
1264 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1266 ty:: AutoAddEnv(store.tr(xcx))
1269 let auto_deref_ref: ty::AutoDerefRef =
1270 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1272 ty::AutoDerefRef(auto_deref_ref.tr(xcx))
1275 let store: ty::TraitStore =
1276 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1277 let b: ty::BuiltinBounds =
1278 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1279 let def_id: ast::DefId =
1280 this.read_enum_variant_arg(2, |this| Decodable::decode(this)).unwrap();
1281 let substs = this.read_enum_variant_arg(3, |this| Ok(this.read_substs(xcx)))
1284 ty::AutoObject(store.tr(xcx), b, def_id.tr(xcx), substs)
1286 _ => fail!("bad enum variant for ty::AutoAdjustment")
1292 fn convert_def_id(&mut self,
1293 xcx: &ExtendedDecodeContext,
1294 source: tydecode::DefIdSource,
1298 * Converts a def-id that appears in a type. The correct
1299 * translation will depend on what kind of def-id this is.
1300 * This is a subtle point: type definitions are not
1301 * inlined into the current crate, so if the def-id names
1302 * a nominal type or type alias, then it should be
1303 * translated to refer to the source crate.
1305 * However, *type parameters* are cloned along with the function
1306 * they are attached to. So we should translate those def-ids
1307 * to refer to the new, cloned copy of the type parameter.
1308 * We only see references to free type parameters in the body of
1309 * an inlined function. In such cases, we need the def-id to
1310 * be a local id so that the TypeContents code is able to lookup
1311 * the relevant info in the ty_param_defs table.
1313 * *Region parameters*, unfortunately, are another kettle of fish.
1314 * In such cases, def_id's can appear in types to distinguish
1315 * shadowed bound regions and so forth. It doesn't actually
1316 * matter so much what we do to these, since regions are erased
1317 * at trans time, but it's good to keep them consistent just in
1318 * case. We translate them with `tr_def_id()` which will map
1319 * the crate numbers back to the original source crate.
1321 * It'd be really nice to refactor the type repr to not include
1322 * def-ids so that all these distinctions were unnecessary.
1325 let r = match source {
1326 NominalType | TypeWithId | RegionParameter => xcx.tr_def_id(did),
1327 TypeParameter => xcx.tr_intern_def_id(did)
1329 debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1334 fn decode_side_tables(xcx: &ExtendedDecodeContext,
1335 ast_doc: ebml::Doc) {
1337 let tbl_doc = ast_doc.get(c::tag_table as uint);
1338 reader::docs(tbl_doc, |tag, entry_doc| {
1339 let id0 = entry_doc.get(c::tag_table_id as uint).as_int();
1340 let id = xcx.tr_id(id0 as ast::NodeId);
1342 debug!(">> Side table document with tag 0x{:x} \
1343 found for id {} (orig {})",
1346 match c::astencode_tag::from_uint(tag) {
1348 xcx.dcx.tcx.sess.bug(
1349 format!("unknown tag found in side tables: {:x}", tag));
1352 let val_doc = entry_doc.get(c::tag_table_val as uint);
1353 let mut val_dsr = reader::Decoder(val_doc);
1354 let val_dsr = &mut val_dsr;
1357 c::tag_table_def => {
1358 let def = decode_def(xcx, val_doc);
1359 dcx.tcx.def_map.borrow_mut().insert(id, def);
1361 c::tag_table_node_type => {
1362 let ty = val_dsr.read_ty(xcx);
1363 debug!("inserting ty for node {:?}: {}",
1364 id, ty_to_str(dcx.tcx, ty));
1365 dcx.tcx.node_types.borrow_mut().insert(id as uint, ty);
1367 c::tag_table_node_type_subst => {
1368 let tys = val_dsr.read_tys(xcx);
1369 dcx.tcx.node_type_substs.borrow_mut().insert(id, tys);
1371 c::tag_table_freevars => {
1372 let fv_info = val_dsr.read_to_vec(|val_dsr| {
1373 Ok(val_dsr.read_freevar_entry(xcx))
1374 }).unwrap().move_iter().collect();
1375 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1377 c::tag_table_tcache => {
1378 let tpbt = val_dsr.read_ty_param_bounds_and_ty(xcx);
1379 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1380 dcx.tcx.tcache.borrow_mut().insert(lid, tpbt);
1382 c::tag_table_param_defs => {
1383 let bounds = val_dsr.read_type_param_def(xcx);
1384 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1386 c::tag_table_method_map => {
1387 let (autoderef, method) = val_dsr.read_method_callee(xcx);
1388 let method_call = MethodCall {
1390 autoderef: autoderef
1392 dcx.tcx.method_map.borrow_mut().insert(method_call, method);
1394 c::tag_table_vtable_map => {
1395 let (autoderef, vtable_res) =
1396 val_dsr.read_vtable_res_with_key(xcx.dcx.tcx,
1398 let vtable_key = MethodCall {
1400 autoderef: autoderef
1402 dcx.tcx.vtable_map.borrow_mut().insert(vtable_key, vtable_res);
1404 c::tag_table_adjustments => {
1405 let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(xcx);
1406 dcx.tcx.adjustments.borrow_mut().insert(id, adj);
1408 c::tag_table_capture_map => {
1410 val_dsr.read_to_vec(
1411 |val_dsr| Ok(val_dsr.read_capture_var(xcx)))
1415 dcx.maps.capture_map.borrow_mut().insert(id, Rc::new(cvars));
1418 xcx.dcx.tcx.sess.bug(
1419 format!("unknown tag found in side tables: {:x}", tag));
1425 debug!(">< Side table doc loaded");
1430 // ______________________________________________________________________
1431 // Testing of astencode_gen
1434 fn encode_item_ast(ebml_w: &mut Encoder, item: @ast::Item) {
1435 ebml_w.start_tag(c::tag_tree as uint);
1436 (*item).encode(ebml_w);
1441 fn decode_item_ast(par_doc: ebml::Doc) -> @ast::Item {
1442 let chi_doc = par_doc.get(c::tag_tree as uint);
1443 let mut d = reader::Decoder(chi_doc);
1444 @Decodable::decode(&mut d).unwrap()
1448 trait fake_ext_ctxt {
1449 fn cfg(&self) -> ast::CrateConfig;
1450 fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess;
1451 fn call_site(&self) -> Span;
1452 fn ident_of(&self, st: &str) -> ast::Ident;
1456 impl fake_ext_ctxt for parse::ParseSess {
1457 fn cfg(&self) -> ast::CrateConfig {
1460 fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { self }
1461 fn call_site(&self) -> Span {
1463 lo: codemap::BytePos(0),
1464 hi: codemap::BytePos(0),
1468 fn ident_of(&self, st: &str) -> ast::Ident {
1469 token::str_to_ident(st)
1474 fn mk_ctxt() -> parse::ParseSess {
1475 parse::new_parse_sess()
1479 fn roundtrip(in_item: Option<@ast::Item>) {
1480 use std::io::MemWriter;
1482 let in_item = in_item.unwrap();
1483 let mut wr = MemWriter::new();
1485 let mut ebml_w = writer::Encoder(&mut wr);
1486 encode_item_ast(&mut ebml_w, in_item);
1488 let ebml_doc = reader::Doc(wr.get_ref());
1489 let out_item = decode_item_ast(ebml_doc);
1491 assert!(in_item == out_item);
1497 roundtrip(quote_item!(cx,
1503 fn test_smalltalk() {
1505 roundtrip(quote_item!(cx,
1506 fn foo() -> int { 3 + 4 } // first smalltalk program ever executed.
1513 roundtrip(quote_item!(cx,
1514 fn foo(x: uint, y: uint) -> uint {
1522 fn test_simplification() {
1524 let item = quote_item!(&cx,
1525 fn new_int_alist<B>() -> alist<int, B> {
1526 fn eq_int(a: int, b: int) -> bool { a == b }
1527 return alist {eq_fn: eq_int, data: Vec::new()};
1530 let item_in = e::IIItemRef(item);
1531 let item_out = simplify_ast(item_in);
1532 let item_exp = ast::IIItem(quote_item!(cx,
1533 fn new_int_alist<B>() -> alist<int, B> {
1534 return alist {eq_fn: eq_int, data: Vec::new()};
1537 match (item_out, item_exp) {
1538 (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
1539 assert!(pprust::item_to_str(item_out) == pprust::item_to_str(item_exp));