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 root_map: middle::borrowck::root_map,
58 pub method_map: middle::typeck::MethodMap,
59 pub vtable_map: middle::typeck::vtable_map,
60 pub capture_map: RefCell<middle::moves::CaptureMap>,
63 struct DecodeContext<'a> {
64 cdata: @cstore::crate_metadata,
69 struct ExtendedDecodeContext<'a> {
70 dcx: &'a DecodeContext<'a>,
71 from_id_range: ast_util::IdRange,
72 to_id_range: ast_util::IdRange
76 fn tr(&self, xcx: &ExtendedDecodeContext) -> Self;
80 fn tr_intern(&self, xcx: &ExtendedDecodeContext) -> ast::DefId;
83 pub type Encoder<'a> = writer::Encoder<'a, MemWriter>;
85 // ______________________________________________________________________
88 pub fn encode_inlined_item(ecx: &e::EncodeContext,
90 ii: e::InlinedItemRef,
93 e::IIItemRef(i) => i.id,
94 e::IIForeignRef(i) => i.id,
95 e::IIMethodRef(_, _, m) => m.id,
97 debug!("> Encoding inlined item: {} ({})",
98 ecx.tcx.map.path_to_str(id),
99 ebml_w.writer.tell());
101 let ii = simplify_ast(ii);
102 let id_range = ast_util::compute_id_range_for_inlined_item(&ii);
104 ebml_w.start_tag(c::tag_ast as uint);
105 id_range.encode(ebml_w);
106 encode_ast(ebml_w, ii);
107 encode_side_tables_for_ii(ecx, maps, ebml_w, &ii);
110 debug!("< Encoded inlined fn: {} ({})",
111 ecx.tcx.map.path_to_str(id),
112 ebml_w.writer.tell());
115 pub fn decode_inlined_item(cdata: @cstore::crate_metadata,
118 path: Vec<ast_map::PathElem>,
120 -> Result<ast::InlinedItem, Vec<ast_map::PathElem>> {
121 let dcx = &DecodeContext {
126 match par_doc.opt_child(c::tag_ast) {
129 let mut path_as_str = None;
130 debug!("> Decoding inlined fn: {}::?",
132 // Do an Option dance to use the path after it is moved below.
133 let s = ast_map::path_to_str(ast_map::Values(path.iter()));
134 path_as_str = Some(s);
135 path_as_str.as_ref().map(|x| x.as_slice())
137 let mut ast_dsr = reader::Decoder(ast_doc);
138 let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
139 let to_id_range = reserve_id_range(&dcx.tcx.sess, from_id_range);
140 let xcx = &ExtendedDecodeContext {
142 from_id_range: from_id_range,
143 to_id_range: to_id_range
145 let raw_ii = decode_ast(ast_doc);
146 let ii = renumber_and_map_ast(xcx, &dcx.tcx.map, path, raw_ii);
147 let ident = match ii {
148 ast::IIItem(i) => i.ident,
149 ast::IIForeign(i) => i.ident,
150 ast::IIMethod(_, _, m) => m.ident,
152 debug!("Fn named: {}", token::get_ident(ident));
153 debug!("< Decoded inlined fn: {}::{}",
154 path_as_str.unwrap(),
155 token::get_ident(ident));
156 region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, &ii);
157 decode_side_tables(xcx, ast_doc);
160 debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
161 syntax::print::pprust::item_to_str(i));
170 // ______________________________________________________________________
171 // Enumerating the IDs which appear in an AST
173 fn reserve_id_range(sess: &Session,
174 from_id_range: ast_util::IdRange) -> ast_util::IdRange {
175 // Handle the case of an empty range:
176 if from_id_range.empty() { return from_id_range; }
177 let cnt = from_id_range.max - from_id_range.min;
178 let to_id_min = sess.reserve_node_ids(cnt);
179 let to_id_max = to_id_min + cnt;
180 ast_util::IdRange { min: to_id_min, max: to_id_max }
183 impl<'a> ExtendedDecodeContext<'a> {
184 pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
186 * Translates an internal id, meaning a node id that is known
187 * to refer to some part of the item currently being inlined,
188 * such as a local variable or argument. All naked node-ids
189 * that appear in types have this property, since if something
190 * might refer to an external item we would use a def-id to
191 * allow for the possibility that the item resides in another
195 // from_id_range should be non-empty
196 assert!(!self.from_id_range.empty());
197 (id - self.from_id_range.min + self.to_id_range.min)
199 pub fn tr_def_id(&self, did: ast::DefId) -> ast::DefId {
201 * Translates an EXTERNAL def-id, converting the crate number
202 * from the one used in the encoded data to the current crate
203 * numbers.. By external, I mean that it be translated to a
204 * reference to the item in its original crate, as opposed to
205 * being translated to a reference to the inlined version of
206 * the item. This is typically, but not always, what you
207 * want, because most def-ids refer to external things like
208 * types or other fns that may or may not be inlined. Note
209 * that even when the inlined function is referencing itself
210 * recursively, we would want `tr_def_id` for that
211 * reference--- conceptually the function calls the original,
212 * non-inlined version, and trans deals with linking that
213 * recursive call to the inlined copy.
215 * However, there are a *few* cases where def-ids are used but
216 * we know that the thing being referenced is in fact *internal*
217 * to the item being inlined. In those cases, you should use
218 * `tr_intern_def_id()` below.
221 decoder::translate_def_id(self.dcx.cdata, did)
223 pub fn tr_intern_def_id(&self, did: ast::DefId) -> ast::DefId {
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.
231 assert_eq!(did.krate, ast::LOCAL_CRATE);
232 ast::DefId { krate: ast::LOCAL_CRATE, node: self.tr_id(did.node) }
234 pub fn tr_span(&self, _span: Span) -> Span {
235 codemap::DUMMY_SP // FIXME (#1972): handle span properly
239 impl tr_intern for ast::DefId {
240 fn tr_intern(&self, xcx: &ExtendedDecodeContext) -> ast::DefId {
241 xcx.tr_intern_def_id(*self)
245 impl tr for ast::DefId {
246 fn tr(&self, xcx: &ExtendedDecodeContext) -> ast::DefId {
251 impl tr for Option<ast::DefId> {
252 fn tr(&self, xcx: &ExtendedDecodeContext) -> Option<ast::DefId> {
253 self.map(|d| xcx.tr_def_id(d))
258 fn tr(&self, xcx: &ExtendedDecodeContext) -> Span {
263 trait def_id_encoder_helpers {
264 fn emit_def_id(&mut self, did: ast::DefId);
267 impl<S:serialize::Encoder<E>, E> def_id_encoder_helpers for S {
268 fn emit_def_id(&mut self, did: ast::DefId) {
269 did.encode(self).unwrap()
273 trait def_id_decoder_helpers {
274 fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId;
275 fn read_def_id_noxcx(&mut self,
276 cdata: @cstore::crate_metadata) -> ast::DefId;
279 impl<D:serialize::Decoder<E>, E> def_id_decoder_helpers for D {
280 fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId {
281 let did: ast::DefId = Decodable::decode(self).unwrap();
285 fn read_def_id_noxcx(&mut self,
286 cdata: @cstore::crate_metadata) -> ast::DefId {
287 let did: ast::DefId = Decodable::decode(self).unwrap();
288 decoder::translate_def_id(cdata, did)
292 // ______________________________________________________________________
293 // Encoding and decoding the AST itself
295 // The hard work is done by an autogenerated module astencode_gen. To
296 // regenerate astencode_gen, run src/etc/gen-astencode. It will
297 // replace astencode_gen with a dummy file and regenerate its
298 // contents. If you get compile errors, the dummy file
299 // remains---resolve the errors and then rerun astencode_gen.
300 // Annoying, I know, but hopefully only temporary.
302 // When decoding, we have to renumber the AST so that the node ids that
303 // appear within are disjoint from the node ids in our existing ASTs.
304 // We also have to adjust the spans: for now we just insert a dummy span,
305 // but eventually we should add entries to the local codemap as required.
307 fn encode_ast(ebml_w: &mut Encoder, item: ast::InlinedItem) {
308 ebml_w.start_tag(c::tag_tree as uint);
313 struct NestedItemsDropper;
315 impl Folder for NestedItemsDropper {
316 fn fold_block(&mut self, blk: ast::P<ast::Block>) -> ast::P<ast::Block> {
317 let stmts_sans_items = blk.stmts.iter().filter_map(|stmt| {
319 ast::StmtExpr(_, _) | ast::StmtSemi(_, _) => Some(*stmt),
320 ast::StmtDecl(decl, _) => {
322 ast::DeclLocal(_) => Some(*stmt),
323 ast::DeclItem(_) => None,
326 ast::StmtMac(..) => fail!("unexpanded macro in astencode")
329 let blk_sans_items = ast::P(ast::Block {
330 view_items: Vec::new(), // I don't know if we need the view_items
331 // here, but it doesn't break tests!
332 stmts: stmts_sans_items,
338 fold::noop_fold_block(blk_sans_items, self)
342 // Produces a simplified copy of the AST which does not include things
343 // that we do not need to or do not want to export. For example, we
344 // do not include any nested items: if these nested items are to be
345 // inlined, their AST will be exported separately (this only makes
346 // sense because, in Rust, nested items are independent except for
347 // their visibility).
349 // As it happens, trans relies on the fact that we do not export
350 // nested items, as otherwise it would get confused when translating
352 fn simplify_ast(ii: e::InlinedItemRef) -> ast::InlinedItem {
353 let mut fld = NestedItemsDropper;
356 // HACK we're not dropping items.
357 e::IIItemRef(i) => ast::IIItem(fold::noop_fold_item(i, &mut fld)
358 .expect_one("expected one item")),
359 e::IIMethodRef(d, p, m) => ast::IIMethod(d, p, fold::noop_fold_method(m, &mut fld)),
360 e::IIForeignRef(i) => ast::IIForeign(fold::noop_fold_foreign_item(i, &mut fld))
364 fn decode_ast(par_doc: ebml::Doc) -> ast::InlinedItem {
365 let chi_doc = par_doc.get(c::tag_tree as uint);
366 let mut d = reader::Decoder(chi_doc);
367 Decodable::decode(&mut d).unwrap()
370 struct AstRenumberer<'a> {
371 xcx: &'a ExtendedDecodeContext<'a>,
374 impl<'a> ast_map::FoldOps for AstRenumberer<'a> {
375 fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
376 if id == ast::DUMMY_NODE_ID {
377 // Used by ast_map to map the NodeInlinedParent.
378 self.xcx.dcx.tcx.sess.next_node_id()
383 fn new_span(&self, span: Span) -> Span {
384 self.xcx.tr_span(span)
388 fn renumber_and_map_ast(xcx: &ExtendedDecodeContext,
390 path: Vec<ast_map::PathElem> ,
391 ii: ast::InlinedItem) -> ast::InlinedItem {
392 ast_map::map_decoded_item(map,
393 path.move_iter().collect(),
394 AstRenumberer { xcx: xcx },
398 ast::IIItem(fld.fold_item(i).expect_one("expected one item"))
400 ast::IIMethod(d, is_provided, m) => {
401 ast::IIMethod(xcx.tr_def_id(d), is_provided, fld.fold_method(m))
403 ast::IIForeign(i) => ast::IIForeign(fld.fold_foreign_item(i))
408 // ______________________________________________________________________
409 // Encoding and decoding of ast::def
411 fn decode_def(xcx: &ExtendedDecodeContext, doc: ebml::Doc) -> ast::Def {
412 let mut dsr = reader::Decoder(doc);
413 let def: ast::Def = Decodable::decode(&mut dsr).unwrap();
417 impl tr for ast::Def {
418 fn tr(&self, xcx: &ExtendedDecodeContext) -> ast::Def {
420 ast::DefFn(did, p) => ast::DefFn(did.tr(xcx), p),
421 ast::DefStaticMethod(did, wrapped_did2, p) => {
422 ast::DefStaticMethod(did.tr(xcx),
424 ast::FromTrait(did2) => {
425 ast::FromTrait(did2.tr(xcx))
427 ast::FromImpl(did2) => {
428 ast::FromImpl(did2.tr(xcx))
433 ast::DefMethod(did0, did1) => {
434 ast::DefMethod(did0.tr(xcx), did1.map(|did1| did1.tr(xcx)))
436 ast::DefSelfTy(nid) => { ast::DefSelfTy(xcx.tr_id(nid)) }
437 ast::DefMod(did) => { ast::DefMod(did.tr(xcx)) }
438 ast::DefForeignMod(did) => { ast::DefForeignMod(did.tr(xcx)) }
439 ast::DefStatic(did, m) => { ast::DefStatic(did.tr(xcx), m) }
440 ast::DefArg(nid, b) => { ast::DefArg(xcx.tr_id(nid), b) }
441 ast::DefLocal(nid, b) => { ast::DefLocal(xcx.tr_id(nid), b) }
442 ast::DefVariant(e_did, v_did, is_s) => {
443 ast::DefVariant(e_did.tr(xcx), v_did.tr(xcx), is_s)
445 ast::DefTrait(did) => ast::DefTrait(did.tr(xcx)),
446 ast::DefTy(did) => ast::DefTy(did.tr(xcx)),
447 ast::DefPrimTy(p) => ast::DefPrimTy(p),
448 ast::DefTyParam(did, v) => ast::DefTyParam(did.tr(xcx), v),
449 ast::DefBinding(nid, bm) => ast::DefBinding(xcx.tr_id(nid), bm),
450 ast::DefUse(did) => ast::DefUse(did.tr(xcx)),
451 ast::DefUpvar(nid1, def, nid2, nid3) => {
452 ast::DefUpvar(xcx.tr_id(nid1),
457 ast::DefStruct(did) => ast::DefStruct(did.tr(xcx)),
458 ast::DefRegion(nid) => ast::DefRegion(xcx.tr_id(nid)),
459 ast::DefTyParamBinder(nid) => {
460 ast::DefTyParamBinder(xcx.tr_id(nid))
462 ast::DefLabel(nid) => ast::DefLabel(xcx.tr_id(nid))
467 // ______________________________________________________________________
468 // Encoding and decoding of adjustment information
470 impl tr for ty::AutoDerefRef {
471 fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::AutoDerefRef {
473 autoderefs: self.autoderefs,
474 autoref: match self.autoref {
475 Some(ref autoref) => Some(autoref.tr(xcx)),
482 impl tr for ty::AutoRef {
483 fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::AutoRef {
484 self.map_region(|r| r.tr(xcx))
488 impl tr for ty::Region {
489 fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::Region {
491 ty::ReLateBound(id, br) => ty::ReLateBound(xcx.tr_id(id),
493 ty::ReEarlyBound(id, index, ident) => ty::ReEarlyBound(xcx.tr_id(id),
496 ty::ReScope(id) => ty::ReScope(xcx.tr_id(id)),
497 ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => *self,
498 ty::ReFree(ref fr) => {
499 ty::ReFree(ty::FreeRegion {scope_id: xcx.tr_id(fr.scope_id),
500 bound_region: fr.bound_region.tr(xcx)})
506 impl tr for ty::BoundRegion {
507 fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::BoundRegion {
510 ty::BrFresh(_) => *self,
511 ty::BrNamed(id, ident) => ty::BrNamed(xcx.tr_def_id(id),
517 impl tr for ty::TraitStore {
518 fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::TraitStore {
520 ty::RegionTraitStore(r, m) => {
521 ty::RegionTraitStore(r.tr(xcx), m)
523 ty::UniqTraitStore => ty::UniqTraitStore
528 // ______________________________________________________________________
529 // Encoding and decoding of freevar information
531 fn encode_freevar_entry(ebml_w: &mut Encoder, fv: @freevar_entry) {
532 (*fv).encode(ebml_w).unwrap();
535 trait ebml_decoder_helper {
536 fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
540 impl<'a> ebml_decoder_helper for reader::Decoder<'a> {
541 fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
543 let fv: freevar_entry = Decodable::decode(self).unwrap();
548 impl tr for freevar_entry {
549 fn tr(&self, xcx: &ExtendedDecodeContext) -> freevar_entry {
551 def: self.def.tr(xcx),
552 span: self.span.tr(xcx),
557 // ______________________________________________________________________
558 // Encoding and decoding of CaptureVar information
560 trait capture_var_helper {
561 fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
562 -> moves::CaptureVar;
565 impl<'a> capture_var_helper for reader::Decoder<'a> {
566 fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
567 -> moves::CaptureVar {
568 let cvar: moves::CaptureVar = Decodable::decode(self).unwrap();
573 impl tr for moves::CaptureVar {
574 fn tr(&self, xcx: &ExtendedDecodeContext) -> moves::CaptureVar {
576 def: self.def.tr(xcx),
577 span: self.span.tr(xcx),
583 // ______________________________________________________________________
584 // Encoding and decoding of MethodCallee
586 trait read_method_callee_helper {
587 fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee);
590 fn encode_method_callee(ecx: &e::EncodeContext,
591 ebml_w: &mut Encoder,
593 method: &MethodCallee) {
594 ebml_w.emit_struct("MethodCallee", 4, |ebml_w| {
595 ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
596 autoderef.encode(ebml_w)
598 ebml_w.emit_struct_field("origin", 1u, |ebml_w| {
599 method.origin.encode(ebml_w)
601 ebml_w.emit_struct_field("ty", 2u, |ebml_w| {
602 Ok(ebml_w.emit_ty(ecx, method.ty))
604 ebml_w.emit_struct_field("substs", 3u, |ebml_w| {
605 Ok(ebml_w.emit_substs(ecx, &method.substs))
610 impl<'a> read_method_callee_helper for reader::Decoder<'a> {
611 fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee) {
612 self.read_struct("MethodCallee", 4, |this| {
613 let autoderef = this.read_struct_field("autoderef", 0, |this| {
614 Decodable::decode(this)
616 Ok((autoderef, MethodCallee {
617 origin: this.read_struct_field("origin", 1, |this| {
618 let method_origin: MethodOrigin =
619 Decodable::decode(this).unwrap();
620 Ok(method_origin.tr(xcx))
622 ty: this.read_struct_field("ty", 2, |this| {
623 Ok(this.read_ty(xcx))
625 substs: this.read_struct_field("substs", 3, |this| {
626 Ok(this.read_substs(xcx))
633 impl tr for MethodOrigin {
634 fn tr(&self, xcx: &ExtendedDecodeContext) -> MethodOrigin {
636 typeck::MethodStatic(did) => typeck::MethodStatic(did.tr(xcx)),
637 typeck::MethodParam(ref mp) => {
639 typeck::MethodParam {
640 trait_id: mp.trait_id.tr(xcx),
645 typeck::MethodObject(ref mo) => {
646 typeck::MethodObject(
647 typeck::MethodObject {
648 trait_id: mo.trait_id.tr(xcx),
657 // ______________________________________________________________________
658 // Encoding and decoding vtable_res
660 fn encode_vtable_res_with_key(ecx: &e::EncodeContext,
661 ebml_w: &mut Encoder,
663 dr: typeck::vtable_res) {
664 ebml_w.emit_struct("VtableWithKey", 2, |ebml_w| {
665 ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
666 autoderef.encode(ebml_w)
668 ebml_w.emit_struct_field("vtable_res", 1u, |ebml_w| {
669 Ok(encode_vtable_res(ecx, ebml_w, dr))
674 pub fn encode_vtable_res(ecx: &e::EncodeContext,
675 ebml_w: &mut Encoder,
676 dr: typeck::vtable_res) {
677 // can't autogenerate this code because automatic code of
678 // ty::t doesn't work, and there is no way (atm) to have
679 // hand-written encoding routines combine with auto-generated
680 // ones. perhaps we should fix this.
681 ebml_w.emit_from_vec(dr.as_slice(), |ebml_w, param_tables| {
682 Ok(encode_vtable_param_res(ecx, ebml_w, *param_tables))
686 pub fn encode_vtable_param_res(ecx: &e::EncodeContext,
687 ebml_w: &mut Encoder,
688 param_tables: typeck::vtable_param_res) {
689 ebml_w.emit_from_vec(param_tables.as_slice(), |ebml_w, vtable_origin| {
690 Ok(encode_vtable_origin(ecx, ebml_w, vtable_origin))
695 pub fn encode_vtable_origin(ecx: &e::EncodeContext,
696 ebml_w: &mut Encoder,
697 vtable_origin: &typeck::vtable_origin) {
698 ebml_w.emit_enum("vtable_origin", |ebml_w| {
699 match *vtable_origin {
700 typeck::vtable_static(def_id, ref tys, vtable_res) => {
701 ebml_w.emit_enum_variant("vtable_static", 0u, 3u, |ebml_w| {
702 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
703 Ok(ebml_w.emit_def_id(def_id))
705 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
706 Ok(ebml_w.emit_tys(ecx, tys.as_slice()))
708 ebml_w.emit_enum_variant_arg(2u, |ebml_w| {
709 Ok(encode_vtable_res(ecx, ebml_w, vtable_res))
713 typeck::vtable_param(pn, bn) => {
714 ebml_w.emit_enum_variant("vtable_param", 1u, 2u, |ebml_w| {
715 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
718 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
727 pub trait vtable_decoder_helpers {
728 fn read_vtable_res_with_key(&mut self,
730 cdata: @cstore::crate_metadata)
731 -> (u32, typeck::vtable_res);
732 fn read_vtable_res(&mut self,
733 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
734 -> typeck::vtable_res;
735 fn read_vtable_param_res(&mut self,
736 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
737 -> typeck::vtable_param_res;
738 fn read_vtable_origin(&mut self,
739 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
740 -> typeck::vtable_origin;
743 impl<'a> vtable_decoder_helpers for reader::Decoder<'a> {
744 fn read_vtable_res_with_key(&mut self,
746 cdata: @cstore::crate_metadata)
747 -> (u32, typeck::vtable_res) {
748 self.read_struct("VtableWithKey", 2, |this| {
749 let autoderef = this.read_struct_field("autoderef", 0, |this| {
750 Decodable::decode(this)
752 Ok((autoderef, this.read_struct_field("vtable_res", 1, |this| {
753 Ok(this.read_vtable_res(tcx, cdata))
758 fn read_vtable_res(&mut self,
759 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
760 -> typeck::vtable_res {
761 @self.read_to_vec(|this|
762 Ok(this.read_vtable_param_res(tcx, cdata)))
768 fn read_vtable_param_res(&mut self,
769 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
770 -> typeck::vtable_param_res {
771 @self.read_to_vec(|this|
772 Ok(this.read_vtable_origin(tcx, cdata)))
778 fn read_vtable_origin(&mut self,
779 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
780 -> typeck::vtable_origin {
781 self.read_enum("vtable_origin", |this| {
782 this.read_enum_variant(["vtable_static",
788 typeck::vtable_static(
789 this.read_enum_variant_arg(0u, |this| {
790 Ok(this.read_def_id_noxcx(cdata))
792 this.read_enum_variant_arg(1u, |this| {
793 Ok(this.read_tys_noxcx(tcx, cdata))
795 this.read_enum_variant_arg(2u, |this| {
796 Ok(this.read_vtable_res(tcx, cdata))
801 typeck::vtable_param(
802 this.read_enum_variant_arg(0u, |this| {
803 Decodable::decode(this)
805 this.read_enum_variant_arg(1u, |this| {
810 // hard to avoid - user input
811 _ => fail!("bad enum variant")
818 // ______________________________________________________________________
819 // Encoding and decoding the side tables
821 trait get_ty_str_ctxt {
822 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a>;
825 impl<'a> get_ty_str_ctxt for e::EncodeContext<'a> {
826 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a> {
828 diag: self.tcx.sess.diagnostic(),
831 abbrevs: tyencode::ac_use_abbrevs(self.type_abbrevs)
836 trait ebml_writer_helpers {
837 fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t);
838 fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]);
839 fn emit_type_param_def(&mut self,
840 ecx: &e::EncodeContext,
841 type_param_def: &ty::TypeParameterDef);
842 fn emit_tpbt(&mut self,
843 ecx: &e::EncodeContext,
844 tpbt: ty::ty_param_bounds_and_ty);
845 fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs);
846 fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment);
849 impl<'a> ebml_writer_helpers for Encoder<'a> {
850 fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t) {
851 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
854 fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]) {
855 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
858 fn emit_type_param_def(&mut self,
859 ecx: &e::EncodeContext,
860 type_param_def: &ty::TypeParameterDef) {
861 self.emit_opaque(|this| {
862 Ok(tyencode::enc_type_param_def(this.writer,
868 fn emit_tpbt(&mut self,
869 ecx: &e::EncodeContext,
870 tpbt: ty::ty_param_bounds_and_ty) {
871 self.emit_struct("ty_param_bounds_and_ty", 2, |this| {
872 this.emit_struct_field("generics", 0, |this| {
873 this.emit_struct("Generics", 2, |this| {
874 this.emit_struct_field("type_param_defs", 0, |this| {
875 this.emit_from_vec(tpbt.generics.type_param_defs(),
876 |this, type_param_def| {
877 Ok(this.emit_type_param_def(ecx, type_param_def))
880 this.emit_struct_field("region_param_defs", 1, |this| {
881 tpbt.generics.region_param_defs().encode(this)
885 this.emit_struct_field("ty", 1, |this| {
886 Ok(this.emit_ty(ecx, tpbt.ty))
891 fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs) {
892 self.emit_opaque(|this| Ok(tyencode::enc_substs(this.writer,
897 fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment) {
898 self.emit_enum("AutoAdjustment", |this| {
900 ty::AutoAddEnv(region, sigil) => {
901 this.emit_enum_variant("AutoAddEnv", 0, 2, |this| {
902 this.emit_enum_variant_arg(0, |this| region.encode(this));
903 this.emit_enum_variant_arg(1, |this| sigil.encode(this))
907 ty::AutoDerefRef(ref auto_deref_ref) => {
908 this.emit_enum_variant("AutoDerefRef", 1, 1, |this| {
909 this.emit_enum_variant_arg(0, |this| auto_deref_ref.encode(this))
913 ty::AutoObject(store, b, def_id, ref substs) => {
914 this.emit_enum_variant("AutoObject", 2, 4, |this| {
915 this.emit_enum_variant_arg(0, |this| store.encode(this));
916 this.emit_enum_variant_arg(1, |this| b.encode(this));
917 this.emit_enum_variant_arg(2, |this| def_id.encode(this));
918 this.emit_enum_variant_arg(3, |this| Ok(this.emit_substs(ecx, substs)))
926 trait write_tag_and_id {
927 fn tag(&mut self, tag_id: c::astencode_tag, f: |&mut Self|);
928 fn id(&mut self, id: ast::NodeId);
931 impl<'a> write_tag_and_id for Encoder<'a> {
933 tag_id: c::astencode_tag,
934 f: |&mut Encoder<'a>|) {
935 self.start_tag(tag_id as uint);
940 fn id(&mut self, id: ast::NodeId) {
941 self.wr_tagged_u64(c::tag_table_id as uint, id as u64);
945 struct SideTableEncodingIdVisitor<'a,'b> {
946 ecx_ptr: *libc::c_void,
947 new_ebml_w: &'a mut Encoder<'b>,
951 impl<'a,'b> ast_util::IdVisitingOperation for
952 SideTableEncodingIdVisitor<'a,'b> {
953 fn visit_id(&self, id: ast::NodeId) {
954 // Note: this will cause a copy of ebml_w, which is bad as
955 // it is mutable. But I believe it's harmless since we generate
958 // FIXME(pcwalton): Don't copy this way.
959 let mut new_ebml_w = unsafe {
960 self.new_ebml_w.unsafe_clone()
963 let ecx: &e::EncodeContext = unsafe {
964 cast::transmute(self.ecx_ptr)
966 encode_side_tables_for_id(ecx, self.maps, &mut new_ebml_w, id)
970 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
972 ebml_w: &mut Encoder,
973 ii: &ast::InlinedItem) {
974 ebml_w.start_tag(c::tag_table as uint);
975 let mut new_ebml_w = unsafe {
976 ebml_w.unsafe_clone()
979 // Because the ast visitor uses @IdVisitingOperation, I can't pass in
980 // ecx directly, but /I/ know that it'll be fine since the lifetime is
981 // tied to the CrateContext that lives throughout this entire section.
982 ast_util::visit_ids_for_inlined_item(ii, &SideTableEncodingIdVisitor {
986 new_ebml_w: &mut new_ebml_w,
992 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
994 ebml_w: &mut Encoder,
998 debug!("Encoding side tables for id {}", id);
1000 for def in tcx.def_map.borrow().find(&id).iter() {
1001 ebml_w.tag(c::tag_table_def, |ebml_w| {
1003 ebml_w.tag(c::tag_table_val, |ebml_w| (*def).encode(ebml_w).unwrap());
1007 for &ty in tcx.node_types.borrow().find(&(id as uint)).iter() {
1008 ebml_w.tag(c::tag_table_node_type, |ebml_w| {
1010 ebml_w.tag(c::tag_table_val, |ebml_w| {
1011 ebml_w.emit_ty(ecx, *ty);
1016 for tys in tcx.node_type_substs.borrow().find(&id).iter() {
1017 ebml_w.tag(c::tag_table_node_type_subst, |ebml_w| {
1019 ebml_w.tag(c::tag_table_val, |ebml_w| {
1020 ebml_w.emit_tys(ecx, tys.as_slice())
1025 for &fv in tcx.freevars.borrow().find(&id).iter() {
1026 ebml_w.tag(c::tag_table_freevars, |ebml_w| {
1028 ebml_w.tag(c::tag_table_val, |ebml_w| {
1029 ebml_w.emit_from_vec(fv.as_slice(), |ebml_w, fv_entry| {
1030 Ok(encode_freevar_entry(ebml_w, *fv_entry))
1036 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1037 for &tpbt in tcx.tcache.borrow().find(&lid).iter() {
1038 ebml_w.tag(c::tag_table_tcache, |ebml_w| {
1040 ebml_w.tag(c::tag_table_val, |ebml_w| {
1041 ebml_w.emit_tpbt(ecx, tpbt.clone());
1046 for &type_param_def in tcx.ty_param_defs.borrow().find(&id).iter() {
1047 ebml_w.tag(c::tag_table_param_defs, |ebml_w| {
1049 ebml_w.tag(c::tag_table_val, |ebml_w| {
1050 ebml_w.emit_type_param_def(ecx, type_param_def)
1055 let method_call = MethodCall::expr(id);
1056 for &method in maps.method_map.borrow().find(&method_call).iter() {
1057 ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1059 ebml_w.tag(c::tag_table_val, |ebml_w| {
1060 encode_method_callee(ecx, ebml_w, method_call.autoderef, method)
1065 for &dr in maps.vtable_map.borrow().find(&method_call).iter() {
1066 ebml_w.tag(c::tag_table_vtable_map, |ebml_w| {
1068 ebml_w.tag(c::tag_table_val, |ebml_w| {
1069 encode_vtable_res_with_key(ecx, ebml_w, method_call.autoderef, *dr);
1074 for adj in tcx.adjustments.borrow().find(&id).iter() {
1076 ty::AutoDerefRef(adj) => {
1077 for autoderef in range(0, adj.autoderefs) {
1078 let method_call = MethodCall::autoderef(id, autoderef as u32);
1079 for &method in maps.method_map.borrow().find(&method_call).iter() {
1080 ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1082 ebml_w.tag(c::tag_table_val, |ebml_w| {
1083 encode_method_callee(ecx, ebml_w, method_call.autoderef, method)
1088 for &dr in maps.vtable_map.borrow().find(&method_call).iter() {
1089 ebml_w.tag(c::tag_table_vtable_map, |ebml_w| {
1091 ebml_w.tag(c::tag_table_val, |ebml_w| {
1092 encode_vtable_res_with_key(ecx, ebml_w,
1093 method_call.autoderef, *dr);
1102 ebml_w.tag(c::tag_table_adjustments, |ebml_w| {
1104 ebml_w.tag(c::tag_table_val, |ebml_w| {
1105 ebml_w.emit_auto_adjustment(ecx, **adj);
1110 for &cap_vars in maps.capture_map.borrow().find(&id).iter() {
1111 ebml_w.tag(c::tag_table_capture_map, |ebml_w| {
1113 ebml_w.tag(c::tag_table_val, |ebml_w| {
1114 ebml_w.emit_from_vec(cap_vars.as_slice(), |ebml_w, cap_var| {
1115 cap_var.encode(ebml_w)
1122 trait doc_decoder_helpers {
1123 fn as_int(&self) -> int;
1124 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1127 impl<'a> doc_decoder_helpers for ebml::Doc<'a> {
1128 fn as_int(&self) -> int { reader::doc_as_u64(*self) as int }
1129 fn opt_child(&self, tag: c::astencode_tag) -> Option<ebml::Doc<'a>> {
1130 reader::maybe_get_doc(*self, tag as uint)
1134 trait ebml_decoder_decoder_helpers {
1135 fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t;
1136 fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t>;
1137 fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
1138 -> ty::TypeParameterDef;
1139 fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
1140 -> ty::ty_param_bounds_and_ty;
1141 fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs;
1142 fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment;
1143 fn convert_def_id(&mut self,
1144 xcx: &ExtendedDecodeContext,
1145 source: DefIdSource,
1149 // Versions of the type reading functions that don't need the full
1150 // ExtendedDecodeContext.
1151 fn read_ty_noxcx(&mut self,
1152 tcx: &ty::ctxt, cdata: @cstore::crate_metadata) -> ty::t;
1153 fn read_tys_noxcx(&mut self,
1155 cdata: @cstore::crate_metadata) -> Vec<ty::t>;
1158 impl<'a> ebml_decoder_decoder_helpers for reader::Decoder<'a> {
1159 fn read_ty_noxcx(&mut self,
1160 tcx: &ty::ctxt, cdata: @cstore::crate_metadata) -> ty::t {
1161 self.read_opaque(|_, doc| {
1162 Ok(tydecode::parse_ty_data(
1167 |_, id| decoder::translate_def_id(cdata, id)))
1171 fn read_tys_noxcx(&mut self,
1173 cdata: @cstore::crate_metadata) -> Vec<ty::t> {
1174 self.read_to_vec(|this| Ok(this.read_ty_noxcx(tcx, cdata)) )
1180 fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t {
1181 // Note: regions types embed local node ids. In principle, we
1182 // should translate these node ids into the new decode
1183 // context. However, we do not bother, because region types
1184 // are not used during trans.
1186 return self.read_opaque(|this, doc| {
1187 debug!("read_ty({})", type_string(doc));
1189 let ty = tydecode::parse_ty_data(
1194 |s, a| this.convert_def_id(xcx, s, a));
1199 fn type_string(doc: ebml::Doc) -> ~str {
1200 let mut str = StrBuf::new();
1201 for i in range(doc.start, doc.end) {
1202 str.push_char(doc.data[i] as char);
1208 fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t> {
1209 self.read_to_vec(|this| Ok(this.read_ty(xcx))).unwrap().move_iter().collect()
1212 fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
1213 -> ty::TypeParameterDef {
1214 self.read_opaque(|this, doc| {
1215 Ok(tydecode::parse_type_param_def_data(
1220 |s, a| this.convert_def_id(xcx, s, a)))
1224 fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
1225 -> ty::ty_param_bounds_and_ty {
1226 self.read_struct("ty_param_bounds_and_ty", 2, |this| {
1227 Ok(ty::ty_param_bounds_and_ty {
1228 generics: this.read_struct_field("generics", 0, |this| {
1229 this.read_struct("Generics", 2, |this| {
1232 this.read_struct_field("type_param_defs",
1235 Ok(Rc::new(this.read_to_vec(|this|
1236 Ok(this.read_type_param_def(xcx)))
1242 this.read_struct_field("region_param_defs",
1245 Decodable::decode(this)
1250 ty: this.read_struct_field("ty", 1, |this| {
1251 Ok(this.read_ty(xcx))
1257 fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs {
1258 self.read_opaque(|this, doc| {
1259 Ok(tydecode::parse_substs_data(doc.data,
1263 |s, a| this.convert_def_id(xcx, s, a)))
1267 fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment {
1268 self.read_enum("AutoAdjustment", |this| {
1269 let variants = ["AutoAddEnv", "AutoDerefRef", "AutoObject"];
1270 this.read_enum_variant(variants, |this, i| {
1273 let region: ty::Region =
1274 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1275 let sigil: ast::Sigil =
1276 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1278 ty:: AutoAddEnv(region.tr(xcx), sigil)
1281 let auto_deref_ref: ty::AutoDerefRef =
1282 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1284 ty::AutoDerefRef(auto_deref_ref.tr(xcx))
1287 let store: ty::TraitStore =
1288 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1289 let b: ty::BuiltinBounds =
1290 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1291 let def_id: ast::DefId =
1292 this.read_enum_variant_arg(2, |this| Decodable::decode(this)).unwrap();
1293 let substs = this.read_enum_variant_arg(3, |this| Ok(this.read_substs(xcx)))
1296 ty::AutoObject(store.tr(xcx), b, def_id.tr(xcx), substs)
1298 _ => fail!("bad enum variant for ty::AutoAdjustment")
1304 fn convert_def_id(&mut self,
1305 xcx: &ExtendedDecodeContext,
1306 source: tydecode::DefIdSource,
1310 * Converts a def-id that appears in a type. The correct
1311 * translation will depend on what kind of def-id this is.
1312 * This is a subtle point: type definitions are not
1313 * inlined into the current crate, so if the def-id names
1314 * a nominal type or type alias, then it should be
1315 * translated to refer to the source crate.
1317 * However, *type parameters* are cloned along with the function
1318 * they are attached to. So we should translate those def-ids
1319 * to refer to the new, cloned copy of the type parameter.
1320 * We only see references to free type parameters in the body of
1321 * an inlined function. In such cases, we need the def-id to
1322 * be a local id so that the TypeContents code is able to lookup
1323 * the relevant info in the ty_param_defs table.
1325 * *Region parameters*, unfortunately, are another kettle of fish.
1326 * In such cases, def_id's can appear in types to distinguish
1327 * shadowed bound regions and so forth. It doesn't actually
1328 * matter so much what we do to these, since regions are erased
1329 * at trans time, but it's good to keep them consistent just in
1330 * case. We translate them with `tr_def_id()` which will map
1331 * the crate numbers back to the original source crate.
1333 * It'd be really nice to refactor the type repr to not include
1334 * def-ids so that all these distinctions were unnecessary.
1337 let r = match source {
1338 NominalType | TypeWithId | RegionParameter => xcx.tr_def_id(did),
1339 TypeParameter => xcx.tr_intern_def_id(did)
1341 debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1346 fn decode_side_tables(xcx: &ExtendedDecodeContext,
1347 ast_doc: ebml::Doc) {
1349 let tbl_doc = ast_doc.get(c::tag_table as uint);
1350 reader::docs(tbl_doc, |tag, entry_doc| {
1351 let id0 = entry_doc.get(c::tag_table_id as uint).as_int();
1352 let id = xcx.tr_id(id0 as ast::NodeId);
1354 debug!(">> Side table document with tag 0x{:x} \
1355 found for id {} (orig {})",
1358 match c::astencode_tag::from_uint(tag) {
1360 xcx.dcx.tcx.sess.bug(
1361 format!("unknown tag found in side tables: {:x}", tag));
1364 let val_doc = entry_doc.get(c::tag_table_val as uint);
1365 let mut val_dsr = reader::Decoder(val_doc);
1366 let val_dsr = &mut val_dsr;
1369 c::tag_table_def => {
1370 let def = decode_def(xcx, val_doc);
1371 dcx.tcx.def_map.borrow_mut().insert(id, def);
1373 c::tag_table_node_type => {
1374 let ty = val_dsr.read_ty(xcx);
1375 debug!("inserting ty for node {:?}: {}",
1376 id, ty_to_str(dcx.tcx, ty));
1377 dcx.tcx.node_types.borrow_mut().insert(id as uint, ty);
1379 c::tag_table_node_type_subst => {
1380 let tys = val_dsr.read_tys(xcx);
1381 dcx.tcx.node_type_substs.borrow_mut().insert(id, tys);
1383 c::tag_table_freevars => {
1384 let fv_info = @val_dsr.read_to_vec(|val_dsr| {
1385 Ok(@val_dsr.read_freevar_entry(xcx))
1386 }).unwrap().move_iter().collect();
1387 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1389 c::tag_table_tcache => {
1390 let tpbt = val_dsr.read_ty_param_bounds_and_ty(xcx);
1391 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1392 dcx.tcx.tcache.borrow_mut().insert(lid, tpbt);
1394 c::tag_table_param_defs => {
1395 let bounds = val_dsr.read_type_param_def(xcx);
1396 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1398 c::tag_table_method_map => {
1399 let (autoderef, method) = val_dsr.read_method_callee(xcx);
1400 let method_call = MethodCall {
1402 autoderef: autoderef
1404 dcx.maps.method_map.borrow_mut().insert(method_call, method);
1406 c::tag_table_vtable_map => {
1407 let (autoderef, vtable_res) =
1408 val_dsr.read_vtable_res_with_key(xcx.dcx.tcx,
1410 let vtable_key = MethodCall {
1412 autoderef: autoderef
1414 dcx.maps.vtable_map.borrow_mut().insert(vtable_key, vtable_res);
1416 c::tag_table_adjustments => {
1417 let adj: @ty::AutoAdjustment = @val_dsr.read_auto_adjustment(xcx);
1418 dcx.tcx.adjustments.borrow_mut().insert(id, adj);
1420 c::tag_table_capture_map => {
1422 val_dsr.read_to_vec(
1423 |val_dsr| Ok(val_dsr.read_capture_var(xcx)))
1427 dcx.maps.capture_map.borrow_mut().insert(id, Rc::new(cvars));
1430 xcx.dcx.tcx.sess.bug(
1431 format!("unknown tag found in side tables: {:x}", tag));
1437 debug!(">< Side table doc loaded");
1442 // ______________________________________________________________________
1443 // Testing of astencode_gen
1446 fn encode_item_ast(ebml_w: &mut Encoder, item: @ast::Item) {
1447 ebml_w.start_tag(c::tag_tree as uint);
1448 (*item).encode(ebml_w);
1453 fn decode_item_ast(par_doc: ebml::Doc) -> @ast::Item {
1454 let chi_doc = par_doc.get(c::tag_tree as uint);
1455 let mut d = reader::Decoder(chi_doc);
1456 @Decodable::decode(&mut d).unwrap()
1460 trait fake_ext_ctxt {
1461 fn cfg(&self) -> ast::CrateConfig;
1462 fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess;
1463 fn call_site(&self) -> Span;
1464 fn ident_of(&self, st: &str) -> ast::Ident;
1468 impl fake_ext_ctxt for parse::ParseSess {
1469 fn cfg(&self) -> ast::CrateConfig {
1472 fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { self }
1473 fn call_site(&self) -> Span {
1475 lo: codemap::BytePos(0),
1476 hi: codemap::BytePos(0),
1480 fn ident_of(&self, st: &str) -> ast::Ident {
1481 token::str_to_ident(st)
1486 fn mk_ctxt() -> parse::ParseSess {
1487 parse::new_parse_sess()
1491 fn roundtrip(in_item: Option<@ast::Item>) {
1492 use std::io::MemWriter;
1494 let in_item = in_item.unwrap();
1495 let mut wr = MemWriter::new();
1497 let mut ebml_w = writer::Encoder(&mut wr);
1498 encode_item_ast(&mut ebml_w, in_item);
1500 let ebml_doc = reader::Doc(wr.get_ref());
1501 let out_item = decode_item_ast(ebml_doc);
1503 assert!(in_item == out_item);
1509 roundtrip(quote_item!(cx,
1515 fn test_smalltalk() {
1517 roundtrip(quote_item!(cx,
1518 fn foo() -> int { 3 + 4 } // first smalltalk program ever executed.
1525 roundtrip(quote_item!(cx,
1526 fn foo(x: uint, y: uint) -> uint {
1534 fn test_simplification() {
1536 let item = quote_item!(&cx,
1537 fn new_int_alist<B>() -> alist<int, B> {
1538 fn eq_int(a: int, b: int) -> bool { a == b }
1539 return alist {eq_fn: eq_int, data: Vec::new()};
1542 let item_in = e::IIItemRef(item);
1543 let item_out = simplify_ast(item_in);
1544 let item_exp = ast::IIItem(quote_item!(cx,
1545 fn new_int_alist<B>() -> alist<int, B> {
1546 return alist {eq_fn: eq_int, data: Vec::new()};
1549 match (item_out, item_exp) {
1550 (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
1551 assert!(pprust::item_to_str(item_out) == pprust::item_to_str(item_exp));