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 // ______________________________________________________________________
518 // Encoding and decoding of freevar information
520 fn encode_freevar_entry(ebml_w: &mut Encoder, fv: @freevar_entry) {
521 (*fv).encode(ebml_w).unwrap();
524 trait ebml_decoder_helper {
525 fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
529 impl<'a> ebml_decoder_helper for reader::Decoder<'a> {
530 fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
532 let fv: freevar_entry = Decodable::decode(self).unwrap();
537 impl tr for freevar_entry {
538 fn tr(&self, xcx: &ExtendedDecodeContext) -> freevar_entry {
540 def: self.def.tr(xcx),
541 span: self.span.tr(xcx),
546 // ______________________________________________________________________
547 // Encoding and decoding of CaptureVar information
549 trait capture_var_helper {
550 fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
551 -> moves::CaptureVar;
554 impl<'a> capture_var_helper for reader::Decoder<'a> {
555 fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
556 -> moves::CaptureVar {
557 let cvar: moves::CaptureVar = Decodable::decode(self).unwrap();
562 impl tr for moves::CaptureVar {
563 fn tr(&self, xcx: &ExtendedDecodeContext) -> moves::CaptureVar {
565 def: self.def.tr(xcx),
566 span: self.span.tr(xcx),
572 // ______________________________________________________________________
573 // Encoding and decoding of MethodCallee
575 trait read_method_callee_helper {
576 fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee);
579 fn encode_method_callee(ecx: &e::EncodeContext,
580 ebml_w: &mut Encoder,
582 method: &MethodCallee) {
583 ebml_w.emit_struct("MethodCallee", 4, |ebml_w| {
584 ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
585 autoderef.encode(ebml_w)
587 ebml_w.emit_struct_field("origin", 1u, |ebml_w| {
588 method.origin.encode(ebml_w)
590 ebml_w.emit_struct_field("ty", 2u, |ebml_w| {
591 Ok(ebml_w.emit_ty(ecx, method.ty))
593 ebml_w.emit_struct_field("substs", 3u, |ebml_w| {
594 Ok(ebml_w.emit_substs(ecx, &method.substs))
599 impl<'a> read_method_callee_helper for reader::Decoder<'a> {
600 fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee) {
601 self.read_struct("MethodCallee", 4, |this| {
602 let autoderef = this.read_struct_field("autoderef", 0, |this| {
603 Decodable::decode(this)
605 Ok((autoderef, MethodCallee {
606 origin: this.read_struct_field("origin", 1, |this| {
607 let method_origin: MethodOrigin =
608 Decodable::decode(this).unwrap();
609 Ok(method_origin.tr(xcx))
611 ty: this.read_struct_field("ty", 2, |this| {
612 Ok(this.read_ty(xcx))
614 substs: this.read_struct_field("substs", 3, |this| {
615 Ok(this.read_substs(xcx))
622 impl tr for MethodOrigin {
623 fn tr(&self, xcx: &ExtendedDecodeContext) -> MethodOrigin {
625 typeck::MethodStatic(did) => typeck::MethodStatic(did.tr(xcx)),
626 typeck::MethodParam(ref mp) => {
628 typeck::MethodParam {
629 trait_id: mp.trait_id.tr(xcx),
634 typeck::MethodObject(ref mo) => {
635 typeck::MethodObject(
636 typeck::MethodObject {
637 trait_id: mo.trait_id.tr(xcx),
646 // ______________________________________________________________________
647 // Encoding and decoding vtable_res
649 fn encode_vtable_res_with_key(ecx: &e::EncodeContext,
650 ebml_w: &mut Encoder,
652 dr: typeck::vtable_res) {
653 ebml_w.emit_struct("VtableWithKey", 2, |ebml_w| {
654 ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
655 autoderef.encode(ebml_w)
657 ebml_w.emit_struct_field("vtable_res", 1u, |ebml_w| {
658 Ok(encode_vtable_res(ecx, ebml_w, dr))
663 pub fn encode_vtable_res(ecx: &e::EncodeContext,
664 ebml_w: &mut Encoder,
665 dr: typeck::vtable_res) {
666 // can't autogenerate this code because automatic code of
667 // ty::t doesn't work, and there is no way (atm) to have
668 // hand-written encoding routines combine with auto-generated
669 // ones. perhaps we should fix this.
670 ebml_w.emit_from_vec(dr.as_slice(), |ebml_w, param_tables| {
671 Ok(encode_vtable_param_res(ecx, ebml_w, *param_tables))
675 pub fn encode_vtable_param_res(ecx: &e::EncodeContext,
676 ebml_w: &mut Encoder,
677 param_tables: typeck::vtable_param_res) {
678 ebml_w.emit_from_vec(param_tables.as_slice(), |ebml_w, vtable_origin| {
679 Ok(encode_vtable_origin(ecx, ebml_w, vtable_origin))
684 pub fn encode_vtable_origin(ecx: &e::EncodeContext,
685 ebml_w: &mut Encoder,
686 vtable_origin: &typeck::vtable_origin) {
687 ebml_w.emit_enum("vtable_origin", |ebml_w| {
688 match *vtable_origin {
689 typeck::vtable_static(def_id, ref tys, vtable_res) => {
690 ebml_w.emit_enum_variant("vtable_static", 0u, 3u, |ebml_w| {
691 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
692 Ok(ebml_w.emit_def_id(def_id))
694 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
695 Ok(ebml_w.emit_tys(ecx, tys.as_slice()))
697 ebml_w.emit_enum_variant_arg(2u, |ebml_w| {
698 Ok(encode_vtable_res(ecx, ebml_w, vtable_res))
702 typeck::vtable_param(pn, bn) => {
703 ebml_w.emit_enum_variant("vtable_param", 1u, 2u, |ebml_w| {
704 ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
707 ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
716 pub trait vtable_decoder_helpers {
717 fn read_vtable_res_with_key(&mut self,
719 cdata: @cstore::crate_metadata)
720 -> (u32, typeck::vtable_res);
721 fn read_vtable_res(&mut self,
722 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
723 -> typeck::vtable_res;
724 fn read_vtable_param_res(&mut self,
725 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
726 -> typeck::vtable_param_res;
727 fn read_vtable_origin(&mut self,
728 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
729 -> typeck::vtable_origin;
732 impl<'a> vtable_decoder_helpers for reader::Decoder<'a> {
733 fn read_vtable_res_with_key(&mut self,
735 cdata: @cstore::crate_metadata)
736 -> (u32, typeck::vtable_res) {
737 self.read_struct("VtableWithKey", 2, |this| {
738 let autoderef = this.read_struct_field("autoderef", 0, |this| {
739 Decodable::decode(this)
741 Ok((autoderef, this.read_struct_field("vtable_res", 1, |this| {
742 Ok(this.read_vtable_res(tcx, cdata))
747 fn read_vtable_res(&mut self,
748 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
749 -> typeck::vtable_res {
750 @self.read_to_vec(|this|
751 Ok(this.read_vtable_param_res(tcx, cdata)))
757 fn read_vtable_param_res(&mut self,
758 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
759 -> typeck::vtable_param_res {
760 @self.read_to_vec(|this|
761 Ok(this.read_vtable_origin(tcx, cdata)))
767 fn read_vtable_origin(&mut self,
768 tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
769 -> typeck::vtable_origin {
770 self.read_enum("vtable_origin", |this| {
771 this.read_enum_variant(["vtable_static",
777 typeck::vtable_static(
778 this.read_enum_variant_arg(0u, |this| {
779 Ok(this.read_def_id_noxcx(cdata))
781 this.read_enum_variant_arg(1u, |this| {
782 Ok(this.read_tys_noxcx(tcx, cdata))
784 this.read_enum_variant_arg(2u, |this| {
785 Ok(this.read_vtable_res(tcx, cdata))
790 typeck::vtable_param(
791 this.read_enum_variant_arg(0u, |this| {
792 Decodable::decode(this)
794 this.read_enum_variant_arg(1u, |this| {
799 // hard to avoid - user input
800 _ => fail!("bad enum variant")
807 // ______________________________________________________________________
808 // Encoding and decoding the side tables
810 trait get_ty_str_ctxt {
811 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a>;
814 impl<'a> get_ty_str_ctxt for e::EncodeContext<'a> {
815 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a> {
817 diag: self.tcx.sess.diagnostic(),
820 abbrevs: tyencode::ac_use_abbrevs(self.type_abbrevs)
825 trait ebml_writer_helpers {
826 fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t);
827 fn emit_vstore(&mut self, ecx: &e::EncodeContext, vstore: ty::vstore);
828 fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]);
829 fn emit_type_param_def(&mut self,
830 ecx: &e::EncodeContext,
831 type_param_def: &ty::TypeParameterDef);
832 fn emit_tpbt(&mut self,
833 ecx: &e::EncodeContext,
834 tpbt: ty::ty_param_bounds_and_ty);
835 fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs);
836 fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment);
839 impl<'a> ebml_writer_helpers for Encoder<'a> {
840 fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t) {
841 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
844 fn emit_vstore(&mut self, ecx: &e::EncodeContext, vstore: ty::vstore) {
845 self.emit_opaque(|this| Ok(e::write_vstore(ecx, this, vstore)));
848 fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]) {
849 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
852 fn emit_type_param_def(&mut self,
853 ecx: &e::EncodeContext,
854 type_param_def: &ty::TypeParameterDef) {
855 self.emit_opaque(|this| {
856 Ok(tyencode::enc_type_param_def(this.writer,
862 fn emit_tpbt(&mut self,
863 ecx: &e::EncodeContext,
864 tpbt: ty::ty_param_bounds_and_ty) {
865 self.emit_struct("ty_param_bounds_and_ty", 2, |this| {
866 this.emit_struct_field("generics", 0, |this| {
867 this.emit_struct("Generics", 2, |this| {
868 this.emit_struct_field("type_param_defs", 0, |this| {
869 this.emit_from_vec(tpbt.generics.type_param_defs(),
870 |this, type_param_def| {
871 Ok(this.emit_type_param_def(ecx, type_param_def))
874 this.emit_struct_field("region_param_defs", 1, |this| {
875 tpbt.generics.region_param_defs().encode(this)
879 this.emit_struct_field("ty", 1, |this| {
880 Ok(this.emit_ty(ecx, tpbt.ty))
885 fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs) {
886 self.emit_opaque(|this| Ok(tyencode::enc_substs(this.writer,
891 fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment) {
892 self.emit_enum("AutoAdjustment", |this| {
894 ty::AutoAddEnv(region, sigil) => {
895 this.emit_enum_variant("AutoAddEnv", 0, 2, |this| {
896 this.emit_enum_variant_arg(0, |this| region.encode(this));
897 this.emit_enum_variant_arg(1, |this| sigil.encode(this))
901 ty::AutoDerefRef(ref auto_deref_ref) => {
902 this.emit_enum_variant("AutoDerefRef", 1, 1, |this| {
903 this.emit_enum_variant_arg(0, |this| auto_deref_ref.encode(this))
907 ty::AutoObject(sigil, region, m, b, def_id, ref substs) => {
908 this.emit_enum_variant("AutoObject", 2, 6, |this| {
909 this.emit_enum_variant_arg(0, |this| sigil.encode(this));
910 this.emit_enum_variant_arg(1, |this| region.encode(this));
911 this.emit_enum_variant_arg(2, |this| m.encode(this));
912 this.emit_enum_variant_arg(3, |this| b.encode(this));
913 this.emit_enum_variant_arg(4, |this| def_id.encode(this));
914 this.emit_enum_variant_arg(5, |this| Ok(this.emit_substs(ecx, substs)))
922 trait write_tag_and_id {
923 fn tag(&mut self, tag_id: c::astencode_tag, f: |&mut Self|);
924 fn id(&mut self, id: ast::NodeId);
927 impl<'a> write_tag_and_id for Encoder<'a> {
929 tag_id: c::astencode_tag,
930 f: |&mut Encoder<'a>|) {
931 self.start_tag(tag_id as uint);
936 fn id(&mut self, id: ast::NodeId) {
937 self.wr_tagged_u64(c::tag_table_id as uint, id as u64);
941 struct SideTableEncodingIdVisitor<'a,'b> {
942 ecx_ptr: *libc::c_void,
943 new_ebml_w: &'a mut Encoder<'b>,
947 impl<'a,'b> ast_util::IdVisitingOperation for
948 SideTableEncodingIdVisitor<'a,'b> {
949 fn visit_id(&self, id: ast::NodeId) {
950 // Note: this will cause a copy of ebml_w, which is bad as
951 // it is mutable. But I believe it's harmless since we generate
954 // FIXME(pcwalton): Don't copy this way.
955 let mut new_ebml_w = unsafe {
956 self.new_ebml_w.unsafe_clone()
959 let ecx: &e::EncodeContext = unsafe {
960 cast::transmute(self.ecx_ptr)
962 encode_side_tables_for_id(ecx, self.maps, &mut new_ebml_w, id)
966 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
968 ebml_w: &mut Encoder,
969 ii: &ast::InlinedItem) {
970 ebml_w.start_tag(c::tag_table as uint);
971 let mut new_ebml_w = unsafe {
972 ebml_w.unsafe_clone()
975 // Because the ast visitor uses @IdVisitingOperation, I can't pass in
976 // ecx directly, but /I/ know that it'll be fine since the lifetime is
977 // tied to the CrateContext that lives throughout this entire section.
978 ast_util::visit_ids_for_inlined_item(ii, &SideTableEncodingIdVisitor {
982 new_ebml_w: &mut new_ebml_w,
988 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
990 ebml_w: &mut Encoder,
994 debug!("Encoding side tables for id {}", id);
996 for def in tcx.def_map.borrow().find(&id).iter() {
997 ebml_w.tag(c::tag_table_def, |ebml_w| {
999 ebml_w.tag(c::tag_table_val, |ebml_w| (*def).encode(ebml_w).unwrap());
1003 for &ty in tcx.node_types.borrow().find(&(id as uint)).iter() {
1004 ebml_w.tag(c::tag_table_node_type, |ebml_w| {
1006 ebml_w.tag(c::tag_table_val, |ebml_w| {
1007 ebml_w.emit_ty(ecx, *ty);
1012 for tys in tcx.node_type_substs.borrow().find(&id).iter() {
1013 ebml_w.tag(c::tag_table_node_type_subst, |ebml_w| {
1015 ebml_w.tag(c::tag_table_val, |ebml_w| {
1016 ebml_w.emit_tys(ecx, tys.as_slice())
1021 for &fv in tcx.freevars.borrow().find(&id).iter() {
1022 ebml_w.tag(c::tag_table_freevars, |ebml_w| {
1024 ebml_w.tag(c::tag_table_val, |ebml_w| {
1025 ebml_w.emit_from_vec(fv.as_slice(), |ebml_w, fv_entry| {
1026 Ok(encode_freevar_entry(ebml_w, *fv_entry))
1032 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1033 for &tpbt in tcx.tcache.borrow().find(&lid).iter() {
1034 ebml_w.tag(c::tag_table_tcache, |ebml_w| {
1036 ebml_w.tag(c::tag_table_val, |ebml_w| {
1037 ebml_w.emit_tpbt(ecx, tpbt.clone());
1042 for &type_param_def in tcx.ty_param_defs.borrow().find(&id).iter() {
1043 ebml_w.tag(c::tag_table_param_defs, |ebml_w| {
1045 ebml_w.tag(c::tag_table_val, |ebml_w| {
1046 ebml_w.emit_type_param_def(ecx, type_param_def)
1051 let method_call = MethodCall::expr(id);
1052 for &method in maps.method_map.borrow().find(&method_call).iter() {
1053 ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1055 ebml_w.tag(c::tag_table_val, |ebml_w| {
1056 encode_method_callee(ecx, ebml_w, method_call.autoderef, method)
1061 for &dr in maps.vtable_map.borrow().find(&method_call).iter() {
1062 ebml_w.tag(c::tag_table_vtable_map, |ebml_w| {
1064 ebml_w.tag(c::tag_table_val, |ebml_w| {
1065 encode_vtable_res_with_key(ecx, ebml_w, method_call.autoderef, *dr);
1070 for adj in tcx.adjustments.borrow().find(&id).iter() {
1072 ty::AutoDerefRef(adj) => {
1073 for autoderef in range(0, adj.autoderefs) {
1074 let method_call = MethodCall::autoderef(id, autoderef as u32);
1075 for &method in maps.method_map.borrow().find(&method_call).iter() {
1076 ebml_w.tag(c::tag_table_method_map, |ebml_w| {
1078 ebml_w.tag(c::tag_table_val, |ebml_w| {
1079 encode_method_callee(ecx, ebml_w, method_call.autoderef, method)
1084 for &dr in maps.vtable_map.borrow().find(&method_call).iter() {
1085 ebml_w.tag(c::tag_table_vtable_map, |ebml_w| {
1087 ebml_w.tag(c::tag_table_val, |ebml_w| {
1088 encode_vtable_res_with_key(ecx, ebml_w,
1089 method_call.autoderef, *dr);
1098 ebml_w.tag(c::tag_table_adjustments, |ebml_w| {
1100 ebml_w.tag(c::tag_table_val, |ebml_w| {
1101 ebml_w.emit_auto_adjustment(ecx, **adj);
1106 for &cap_vars in maps.capture_map.borrow().find(&id).iter() {
1107 ebml_w.tag(c::tag_table_capture_map, |ebml_w| {
1109 ebml_w.tag(c::tag_table_val, |ebml_w| {
1110 ebml_w.emit_from_vec(cap_vars.as_slice(), |ebml_w, cap_var| {
1111 cap_var.encode(ebml_w)
1118 trait doc_decoder_helpers {
1119 fn as_int(&self) -> int;
1120 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1123 impl<'a> doc_decoder_helpers for ebml::Doc<'a> {
1124 fn as_int(&self) -> int { reader::doc_as_u64(*self) as int }
1125 fn opt_child(&self, tag: c::astencode_tag) -> Option<ebml::Doc<'a>> {
1126 reader::maybe_get_doc(*self, tag as uint)
1130 trait ebml_decoder_decoder_helpers {
1131 fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t;
1132 fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t>;
1133 fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
1134 -> ty::TypeParameterDef;
1135 fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
1136 -> ty::ty_param_bounds_and_ty;
1137 fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs;
1138 fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment;
1139 fn convert_def_id(&mut self,
1140 xcx: &ExtendedDecodeContext,
1141 source: DefIdSource,
1145 // Versions of the type reading functions that don't need the full
1146 // ExtendedDecodeContext.
1147 fn read_ty_noxcx(&mut self,
1148 tcx: &ty::ctxt, cdata: @cstore::crate_metadata) -> ty::t;
1149 fn read_tys_noxcx(&mut self,
1151 cdata: @cstore::crate_metadata) -> Vec<ty::t>;
1154 impl<'a> ebml_decoder_decoder_helpers for reader::Decoder<'a> {
1155 fn read_ty_noxcx(&mut self,
1156 tcx: &ty::ctxt, cdata: @cstore::crate_metadata) -> ty::t {
1157 self.read_opaque(|_, doc| {
1158 Ok(tydecode::parse_ty_data(
1163 |_, id| decoder::translate_def_id(cdata, id)))
1167 fn read_tys_noxcx(&mut self,
1169 cdata: @cstore::crate_metadata) -> Vec<ty::t> {
1170 self.read_to_vec(|this| Ok(this.read_ty_noxcx(tcx, cdata)) )
1176 fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t {
1177 // Note: regions types embed local node ids. In principle, we
1178 // should translate these node ids into the new decode
1179 // context. However, we do not bother, because region types
1180 // are not used during trans.
1182 return self.read_opaque(|this, doc| {
1183 debug!("read_ty({})", type_string(doc));
1185 let ty = tydecode::parse_ty_data(
1190 |s, a| this.convert_def_id(xcx, s, a));
1195 fn type_string(doc: ebml::Doc) -> ~str {
1196 let mut str = StrBuf::new();
1197 for i in range(doc.start, doc.end) {
1198 str.push_char(doc.data[i] as char);
1204 fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t> {
1205 self.read_to_vec(|this| Ok(this.read_ty(xcx))).unwrap().move_iter().collect()
1208 fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
1209 -> ty::TypeParameterDef {
1210 self.read_opaque(|this, doc| {
1211 Ok(tydecode::parse_type_param_def_data(
1216 |s, a| this.convert_def_id(xcx, s, a)))
1220 fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
1221 -> ty::ty_param_bounds_and_ty {
1222 self.read_struct("ty_param_bounds_and_ty", 2, |this| {
1223 Ok(ty::ty_param_bounds_and_ty {
1224 generics: this.read_struct_field("generics", 0, |this| {
1225 this.read_struct("Generics", 2, |this| {
1228 this.read_struct_field("type_param_defs",
1231 Ok(Rc::new(this.read_to_vec(|this|
1232 Ok(this.read_type_param_def(xcx)))
1238 this.read_struct_field("region_param_defs",
1241 Decodable::decode(this)
1246 ty: this.read_struct_field("ty", 1, |this| {
1247 Ok(this.read_ty(xcx))
1253 fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs {
1254 self.read_opaque(|this, doc| {
1255 Ok(tydecode::parse_substs_data(doc.data,
1259 |s, a| this.convert_def_id(xcx, s, a)))
1263 fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment {
1264 self.read_enum("AutoAdjustment", |this| {
1265 let variants = ["AutoAddEnv", "AutoDerefRef", "AutoObject"];
1266 this.read_enum_variant(variants, |this, i| {
1269 let region: ty::Region =
1270 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1271 let sigil: ast::Sigil =
1272 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1274 ty:: AutoAddEnv(region.tr(xcx), sigil)
1277 let auto_deref_ref: ty::AutoDerefRef =
1278 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1280 ty::AutoDerefRef(auto_deref_ref.tr(xcx))
1283 let sigil: ast::Sigil =
1284 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1285 let region: Option<ty::Region> =
1286 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1287 let m: ast::Mutability =
1288 this.read_enum_variant_arg(2, |this| Decodable::decode(this)).unwrap();
1289 let b: ty::BuiltinBounds =
1290 this.read_enum_variant_arg(3, |this| Decodable::decode(this)).unwrap();
1291 let def_id: ast::DefId =
1292 this.read_enum_variant_arg(4, |this| Decodable::decode(this)).unwrap();
1293 let substs = this.read_enum_variant_arg(5, |this| Ok(this.read_substs(xcx)))
1296 let region = match region {
1297 Some(r) => Some(r.tr(xcx)),
1301 ty::AutoObject(sigil, region, m, b, def_id.tr(xcx), substs)
1303 _ => fail!("bad enum variant for ty::AutoAdjustment")
1309 fn convert_def_id(&mut self,
1310 xcx: &ExtendedDecodeContext,
1311 source: tydecode::DefIdSource,
1315 * Converts a def-id that appears in a type. The correct
1316 * translation will depend on what kind of def-id this is.
1317 * This is a subtle point: type definitions are not
1318 * inlined into the current crate, so if the def-id names
1319 * a nominal type or type alias, then it should be
1320 * translated to refer to the source crate.
1322 * However, *type parameters* are cloned along with the function
1323 * they are attached to. So we should translate those def-ids
1324 * to refer to the new, cloned copy of the type parameter.
1325 * We only see references to free type parameters in the body of
1326 * an inlined function. In such cases, we need the def-id to
1327 * be a local id so that the TypeContents code is able to lookup
1328 * the relevant info in the ty_param_defs table.
1330 * *Region parameters*, unfortunately, are another kettle of fish.
1331 * In such cases, def_id's can appear in types to distinguish
1332 * shadowed bound regions and so forth. It doesn't actually
1333 * matter so much what we do to these, since regions are erased
1334 * at trans time, but it's good to keep them consistent just in
1335 * case. We translate them with `tr_def_id()` which will map
1336 * the crate numbers back to the original source crate.
1338 * It'd be really nice to refactor the type repr to not include
1339 * def-ids so that all these distinctions were unnecessary.
1342 let r = match source {
1343 NominalType | TypeWithId | RegionParameter => xcx.tr_def_id(did),
1344 TypeParameter => xcx.tr_intern_def_id(did)
1346 debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1351 fn decode_side_tables(xcx: &ExtendedDecodeContext,
1352 ast_doc: ebml::Doc) {
1354 let tbl_doc = ast_doc.get(c::tag_table as uint);
1355 reader::docs(tbl_doc, |tag, entry_doc| {
1356 let id0 = entry_doc.get(c::tag_table_id as uint).as_int();
1357 let id = xcx.tr_id(id0 as ast::NodeId);
1359 debug!(">> Side table document with tag 0x{:x} \
1360 found for id {} (orig {})",
1363 match c::astencode_tag::from_uint(tag) {
1365 xcx.dcx.tcx.sess.bug(
1366 format!("unknown tag found in side tables: {:x}", tag));
1369 let val_doc = entry_doc.get(c::tag_table_val as uint);
1370 let mut val_dsr = reader::Decoder(val_doc);
1371 let val_dsr = &mut val_dsr;
1374 c::tag_table_def => {
1375 let def = decode_def(xcx, val_doc);
1376 dcx.tcx.def_map.borrow_mut().insert(id, def);
1378 c::tag_table_node_type => {
1379 let ty = val_dsr.read_ty(xcx);
1380 debug!("inserting ty for node {:?}: {}",
1381 id, ty_to_str(dcx.tcx, ty));
1382 dcx.tcx.node_types.borrow_mut().insert(id as uint, ty);
1384 c::tag_table_node_type_subst => {
1385 let tys = val_dsr.read_tys(xcx);
1386 dcx.tcx.node_type_substs.borrow_mut().insert(id, tys);
1388 c::tag_table_freevars => {
1389 let fv_info = @val_dsr.read_to_vec(|val_dsr| {
1390 Ok(@val_dsr.read_freevar_entry(xcx))
1391 }).unwrap().move_iter().collect();
1392 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1394 c::tag_table_tcache => {
1395 let tpbt = val_dsr.read_ty_param_bounds_and_ty(xcx);
1396 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1397 dcx.tcx.tcache.borrow_mut().insert(lid, tpbt);
1399 c::tag_table_param_defs => {
1400 let bounds = val_dsr.read_type_param_def(xcx);
1401 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1403 c::tag_table_method_map => {
1404 let (autoderef, method) = val_dsr.read_method_callee(xcx);
1405 let method_call = MethodCall {
1407 autoderef: autoderef
1409 dcx.maps.method_map.borrow_mut().insert(method_call, method);
1411 c::tag_table_vtable_map => {
1412 let (autoderef, vtable_res) =
1413 val_dsr.read_vtable_res_with_key(xcx.dcx.tcx,
1415 let vtable_key = MethodCall {
1417 autoderef: autoderef
1419 dcx.maps.vtable_map.borrow_mut().insert(vtable_key, vtable_res);
1421 c::tag_table_adjustments => {
1422 let adj: @ty::AutoAdjustment = @val_dsr.read_auto_adjustment(xcx);
1423 dcx.tcx.adjustments.borrow_mut().insert(id, adj);
1425 c::tag_table_capture_map => {
1427 val_dsr.read_to_vec(
1428 |val_dsr| Ok(val_dsr.read_capture_var(xcx)))
1432 dcx.maps.capture_map.borrow_mut().insert(id, Rc::new(cvars));
1435 xcx.dcx.tcx.sess.bug(
1436 format!("unknown tag found in side tables: {:x}", tag));
1442 debug!(">< Side table doc loaded");
1447 // ______________________________________________________________________
1448 // Testing of astencode_gen
1451 fn encode_item_ast(ebml_w: &mut Encoder, item: @ast::Item) {
1452 ebml_w.start_tag(c::tag_tree as uint);
1453 (*item).encode(ebml_w);
1458 fn decode_item_ast(par_doc: ebml::Doc) -> @ast::Item {
1459 let chi_doc = par_doc.get(c::tag_tree as uint);
1460 let mut d = reader::Decoder(chi_doc);
1461 @Decodable::decode(&mut d).unwrap()
1465 trait fake_ext_ctxt {
1466 fn cfg(&self) -> ast::CrateConfig;
1467 fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess;
1468 fn call_site(&self) -> Span;
1469 fn ident_of(&self, st: &str) -> ast::Ident;
1473 impl fake_ext_ctxt for parse::ParseSess {
1474 fn cfg(&self) -> ast::CrateConfig {
1477 fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { self }
1478 fn call_site(&self) -> Span {
1480 lo: codemap::BytePos(0),
1481 hi: codemap::BytePos(0),
1485 fn ident_of(&self, st: &str) -> ast::Ident {
1486 token::str_to_ident(st)
1491 fn mk_ctxt() -> parse::ParseSess {
1492 parse::new_parse_sess()
1496 fn roundtrip(in_item: Option<@ast::Item>) {
1497 use std::io::MemWriter;
1499 let in_item = in_item.unwrap();
1500 let mut wr = MemWriter::new();
1502 let mut ebml_w = writer::Encoder(&mut wr);
1503 encode_item_ast(&mut ebml_w, in_item);
1505 let ebml_doc = reader::Doc(wr.get_ref());
1506 let out_item = decode_item_ast(ebml_doc);
1508 assert!(in_item == out_item);
1514 roundtrip(quote_item!(cx,
1520 fn test_smalltalk() {
1522 roundtrip(quote_item!(cx,
1523 fn foo() -> int { 3 + 4 } // first smalltalk program ever executed.
1530 roundtrip(quote_item!(cx,
1531 fn foo(x: uint, y: uint) -> uint {
1539 fn test_simplification() {
1541 let item = quote_item!(&cx,
1542 fn new_int_alist<B>() -> alist<int, B> {
1543 fn eq_int(a: int, b: int) -> bool { a == b }
1544 return alist {eq_fn: eq_int, data: Vec::new()};
1547 let item_in = e::IIItemRef(item);
1548 let item_out = simplify_ast(item_in);
1549 let item_exp = ast::IIItem(quote_item!(cx,
1550 fn new_int_alist<B>() -> alist<int, B> {
1551 return alist {eq_fn: eq_int, data: Vec::new()};
1554 match (item_out, item_exp) {
1555 (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
1556 assert!(pprust::item_to_str(item_out) == pprust::item_to_str(item_exp));