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 metadata::common as c;
16 use metadata::cstore as cstore;
18 use metadata::decoder;
20 use metadata::encoder as e;
22 use metadata::tydecode;
23 use metadata::tydecode::{DefIdSource, NominalType, TypeWithId, TypeParameter};
24 use metadata::tydecode::{RegionParameter, ClosureSource};
25 use metadata::tyencode;
26 use middle::check_const::ConstQualif;
27 use middle::mem_categorization::Typer;
29 use middle::subst::VecPerParamSpace;
30 use middle::ty::{self, Ty, MethodCall, MethodCallee, MethodOrigin};
31 use util::ppaux::ty_to_string;
33 use syntax::{ast, ast_map, ast_util, codemap, fold};
34 use syntax::ast_util::PostExpansionMethod;
35 use syntax::codemap::Span;
36 use syntax::fold::Folder;
37 use syntax::parse::token;
41 use std::old_io::Seek;
42 use std::num::FromPrimitive;
45 use rbml::io::SeekableMemWriter;
46 use rbml::{reader, writer};
49 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
50 use serialize::{EncoderHelpers};
52 #[cfg(test)] use syntax::parse;
53 #[cfg(test)] use syntax::print::pprust;
55 struct DecodeContext<'a, 'b, 'tcx: 'a> {
56 tcx: &'a ty::ctxt<'tcx>,
57 cdata: &'b cstore::crate_metadata,
58 from_id_range: ast_util::IdRange,
59 to_id_range: ast_util::IdRange
63 fn tr(&self, dcx: &DecodeContext) -> Self;
67 fn tr_intern(&self, dcx: &DecodeContext) -> ast::DefId;
70 pub type Encoder<'a> = writer::Encoder<'a, SeekableMemWriter>;
72 // ______________________________________________________________________
75 pub fn encode_inlined_item(ecx: &e::EncodeContext,
77 ii: e::InlinedItemRef) {
79 e::IIItemRef(i) => i.id,
80 e::IIForeignRef(i) => i.id,
81 e::IITraitItemRef(_, &ast::ProvidedMethod(ref m)) => m.id,
82 e::IITraitItemRef(_, &ast::RequiredMethod(ref m)) => m.id,
83 e::IITraitItemRef(_, &ast::TypeTraitItem(ref ti)) => ti.ty_param.id,
84 e::IIImplItemRef(_, &ast::MethodImplItem(ref m)) => m.id,
85 e::IIImplItemRef(_, &ast::TypeImplItem(ref ti)) => ti.id,
87 debug!("> Encoding inlined item: {} ({:?})",
88 ecx.tcx.map.path_to_string(id),
89 rbml_w.writer.tell());
91 // Folding could be avoided with a smarter encoder.
92 let ii = simplify_ast(ii);
93 let id_range = ast_util::compute_id_range_for_inlined_item(&ii);
95 rbml_w.start_tag(c::tag_ast as uint);
96 id_range.encode(rbml_w);
97 encode_ast(rbml_w, &ii);
98 encode_side_tables_for_ii(ecx, rbml_w, &ii);
101 debug!("< Encoded inlined fn: {} ({:?})",
102 ecx.tcx.map.path_to_string(id),
103 rbml_w.writer.tell());
106 impl<'a, 'b, 'c, 'tcx> ast_map::FoldOps for &'a DecodeContext<'b, 'c, 'tcx> {
107 fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
108 if id == ast::DUMMY_NODE_ID {
109 // Used by ast_map to map the NodeInlinedParent.
110 self.tcx.sess.next_node_id()
115 fn new_def_id(&self, def_id: ast::DefId) -> ast::DefId {
116 self.tr_def_id(def_id)
118 fn new_span(&self, span: Span) -> Span {
123 pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
124 tcx: &ty::ctxt<'tcx>,
125 path: Vec<ast_map::PathElem>,
127 -> Result<&'tcx ast::InlinedItem, Vec<ast_map::PathElem>> {
128 match par_doc.opt_child(c::tag_ast) {
131 let mut path_as_str = None;
132 debug!("> Decoding inlined fn: {:?}::?",
134 // Do an Option dance to use the path after it is moved below.
135 let s = ast_map::path_to_string(path.iter().cloned());
136 path_as_str = Some(s);
137 path_as_str.as_ref().map(|x| &x[..])
139 let mut ast_dsr = reader::Decoder::new(ast_doc);
140 let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
141 let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
142 let dcx = &DecodeContext {
145 from_id_range: from_id_range,
146 to_id_range: to_id_range
148 let raw_ii = decode_ast(ast_doc);
149 let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, raw_ii, dcx);
151 let ident = match *ii {
152 ast::IIItem(ref i) => i.ident,
153 ast::IIForeign(ref i) => i.ident,
154 ast::IITraitItem(_, ref ti) => {
156 ast::ProvidedMethod(ref m) => m.pe_ident(),
157 ast::RequiredMethod(ref ty_m) => ty_m.ident,
158 ast::TypeTraitItem(ref ti) => ti.ty_param.ident,
161 ast::IIImplItem(_, ref m) => {
163 ast::MethodImplItem(ref m) => m.pe_ident(),
164 ast::TypeImplItem(ref ti) => ti.ident,
168 debug!("Fn named: {}", token::get_ident(ident));
169 debug!("< Decoded inlined fn: {}::{}",
170 path_as_str.unwrap(),
171 token::get_ident(ident));
172 region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
173 decode_side_tables(dcx, ast_doc);
175 ast::IIItem(ref i) => {
176 debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
177 syntax::print::pprust::item_to_string(&**i));
186 // ______________________________________________________________________
187 // Enumerating the IDs which appear in an AST
189 fn reserve_id_range(sess: &Session,
190 from_id_range: ast_util::IdRange) -> ast_util::IdRange {
191 // Handle the case of an empty range:
192 if from_id_range.empty() { return from_id_range; }
193 let cnt = from_id_range.max - from_id_range.min;
194 let to_id_min = sess.reserve_node_ids(cnt);
195 let to_id_max = to_id_min + cnt;
196 ast_util::IdRange { min: to_id_min, max: to_id_max }
199 impl<'a, 'b, 'tcx> DecodeContext<'a, 'b, 'tcx> {
200 /// Translates an internal id, meaning a node id that is known to refer to some part of the
201 /// item currently being inlined, such as a local variable or argument. All naked node-ids
202 /// that appear in types have this property, since if something might refer to an external item
203 /// we would use a def-id to allow for the possibility that the item resides in another crate.
204 pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
205 // from_id_range should be non-empty
206 assert!(!self.from_id_range.empty());
207 (id - self.from_id_range.min + self.to_id_range.min)
210 /// Translates an EXTERNAL def-id, converting the crate number from the one used in the encoded
211 /// data to the current crate numbers.. By external, I mean that it be translated to a
212 /// reference to the item in its original crate, as opposed to being translated to a reference
213 /// to the inlined version of the item. This is typically, but not always, what you want,
214 /// because most def-ids refer to external things like types or other fns that may or may not
215 /// be inlined. Note that even when the inlined function is referencing itself recursively, we
216 /// would want `tr_def_id` for that reference--- conceptually the function calls the original,
217 /// non-inlined version, and trans deals with linking that recursive call to the inlined copy.
219 /// However, there are a *few* cases where def-ids are used but we know that the thing being
220 /// referenced is in fact *internal* to the item being inlined. In those cases, you should use
221 /// `tr_intern_def_id()` below.
222 pub fn tr_def_id(&self, did: ast::DefId) -> ast::DefId {
224 decoder::translate_def_id(self.cdata, did)
227 /// Translates an INTERNAL def-id, meaning a def-id that is
228 /// known to refer to some part of the item currently being
229 /// inlined. In that case, we want to convert the def-id to
230 /// refer to the current crate and to the new, inlined node-id.
231 pub fn tr_intern_def_id(&self, did: ast::DefId) -> ast::DefId {
232 assert_eq!(did.krate, ast::LOCAL_CRATE);
233 ast::DefId { krate: ast::LOCAL_CRATE, node: self.tr_id(did.node) }
235 pub fn tr_span(&self, _span: Span) -> Span {
236 codemap::DUMMY_SP // FIXME (#1972): handle span properly
240 impl tr_intern for ast::DefId {
241 fn tr_intern(&self, dcx: &DecodeContext) -> ast::DefId {
242 dcx.tr_intern_def_id(*self)
246 impl tr for ast::DefId {
247 fn tr(&self, dcx: &DecodeContext) -> ast::DefId {
252 impl tr for Option<ast::DefId> {
253 fn tr(&self, dcx: &DecodeContext) -> Option<ast::DefId> {
254 self.map(|d| dcx.tr_def_id(d))
259 fn tr(&self, dcx: &DecodeContext) -> Span {
264 trait def_id_encoder_helpers {
265 fn emit_def_id(&mut self, did: ast::DefId);
268 impl<S:serialize::Encoder> def_id_encoder_helpers for S {
269 fn emit_def_id(&mut self, did: ast::DefId) {
270 did.encode(self).ok().unwrap()
274 trait def_id_decoder_helpers {
275 fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId;
276 fn read_def_id_nodcx(&mut self,
277 cdata: &cstore::crate_metadata) -> ast::DefId;
280 impl<D:serialize::Decoder> def_id_decoder_helpers for D {
281 fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId {
282 let did: ast::DefId = Decodable::decode(self).ok().unwrap();
286 fn read_def_id_nodcx(&mut self,
287 cdata: &cstore::crate_metadata) -> ast::DefId {
288 let did: ast::DefId = Decodable::decode(self).ok().unwrap();
289 decoder::translate_def_id(cdata, did)
293 // ______________________________________________________________________
294 // Encoding and decoding the AST itself
296 // The hard work is done by an autogenerated module astencode_gen. To
297 // regenerate astencode_gen, run src/etc/gen-astencode. It will
298 // replace astencode_gen with a dummy file and regenerate its
299 // contents. If you get compile errors, the dummy file
300 // remains---resolve the errors and then rerun astencode_gen.
301 // Annoying, I know, but hopefully only temporary.
303 // When decoding, we have to renumber the AST so that the node ids that
304 // appear within are disjoint from the node ids in our existing ASTs.
305 // We also have to adjust the spans: for now we just insert a dummy span,
306 // but eventually we should add entries to the local codemap as required.
308 fn encode_ast(rbml_w: &mut Encoder, item: &ast::InlinedItem) {
309 rbml_w.start_tag(c::tag_tree as uint);
314 struct NestedItemsDropper;
316 impl Folder for NestedItemsDropper {
317 fn fold_block(&mut self, blk: P<ast::Block>) -> P<ast::Block> {
318 blk.and_then(|ast::Block {id, stmts, expr, rules, span, ..}| {
319 let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
320 let use_stmt = match stmt.node {
321 ast::StmtExpr(_, _) | ast::StmtSemi(_, _) => true,
322 ast::StmtDecl(ref decl, _) => {
324 ast::DeclLocal(_) => true,
325 ast::DeclItem(_) => false,
328 ast::StmtMac(..) => panic!("unexpanded macro in astencode")
336 let blk_sans_items = P(ast::Block {
337 stmts: stmts_sans_items,
343 fold::noop_fold_block(blk_sans_items, self)
348 // Produces a simplified copy of the AST which does not include things
349 // that we do not need to or do not want to export. For example, we
350 // do not include any nested items: if these nested items are to be
351 // inlined, their AST will be exported separately (this only makes
352 // sense because, in Rust, nested items are independent except for
353 // their visibility).
355 // As it happens, trans relies on the fact that we do not export
356 // nested items, as otherwise it would get confused when translating
358 fn simplify_ast(ii: e::InlinedItemRef) -> ast::InlinedItem {
359 let mut fld = NestedItemsDropper;
362 // HACK we're not dropping items.
364 ast::IIItem(fold::noop_fold_item(P(i.clone()), &mut fld)
365 .expect_one("expected one item"))
367 e::IITraitItemRef(d, ti) => {
368 ast::IITraitItem(d, match *ti {
369 ast::ProvidedMethod(ref m) => {
371 fold::noop_fold_method(m.clone(), &mut fld)
372 .expect_one("noop_fold_method must produce \
373 exactly one method"))
375 ast::RequiredMethod(ref ty_m) => {
377 fold::noop_fold_type_method(ty_m.clone(), &mut fld))
379 ast::TypeTraitItem(ref associated_type) => {
381 P(fold::noop_fold_associated_type(
382 (**associated_type).clone(),
387 e::IIImplItemRef(d, m) => {
388 ast::IIImplItem(d, match *m {
389 ast::MethodImplItem(ref m) => {
391 fold::noop_fold_method(m.clone(), &mut fld)
392 .expect_one("noop_fold_method must produce \
393 exactly one method"))
395 ast::TypeImplItem(ref td) => {
397 P(fold::noop_fold_typedef((**td).clone(), &mut fld)))
401 e::IIForeignRef(i) => {
402 ast::IIForeign(fold::noop_fold_foreign_item(P(i.clone()), &mut fld))
407 fn decode_ast(par_doc: rbml::Doc) -> ast::InlinedItem {
408 let chi_doc = par_doc.get(c::tag_tree as uint);
409 let mut d = reader::Decoder::new(chi_doc);
410 Decodable::decode(&mut d).unwrap()
413 // ______________________________________________________________________
414 // Encoding and decoding of ast::def
416 fn decode_def(dcx: &DecodeContext, doc: rbml::Doc) -> def::Def {
417 let mut dsr = reader::Decoder::new(doc);
418 let def: def::Def = Decodable::decode(&mut dsr).unwrap();
422 impl tr for def::Def {
423 fn tr(&self, dcx: &DecodeContext) -> def::Def {
425 def::DefFn(did, is_ctor) => def::DefFn(did.tr(dcx), is_ctor),
426 def::DefStaticMethod(did, p) => {
427 def::DefStaticMethod(did.tr(dcx), p.map(|did2| did2.tr(dcx)))
429 def::DefMethod(did0, did1, p) => {
430 def::DefMethod(did0.tr(dcx),
431 did1.map(|did1| did1.tr(dcx)),
432 p.map(|did2| did2.tr(dcx)))
434 def::DefSelfTy(nid) => { def::DefSelfTy(dcx.tr_id(nid)) }
435 def::DefMod(did) => { def::DefMod(did.tr(dcx)) }
436 def::DefForeignMod(did) => { def::DefForeignMod(did.tr(dcx)) }
437 def::DefStatic(did, m) => { def::DefStatic(did.tr(dcx), m) }
438 def::DefConst(did) => { def::DefConst(did.tr(dcx)) }
439 def::DefLocal(nid) => { def::DefLocal(dcx.tr_id(nid)) }
440 def::DefVariant(e_did, v_did, is_s) => {
441 def::DefVariant(e_did.tr(dcx), v_did.tr(dcx), is_s)
443 def::DefTrait(did) => def::DefTrait(did.tr(dcx)),
444 def::DefTy(did, is_enum) => def::DefTy(did.tr(dcx), is_enum),
445 def::DefAssociatedTy(did) => def::DefAssociatedTy(did.tr(dcx)),
446 def::DefAssociatedPath(def::TyParamProvenance::FromSelf(did), ident) =>
447 def::DefAssociatedPath(def::TyParamProvenance::FromSelf(did.tr(dcx)), ident),
448 def::DefAssociatedPath(def::TyParamProvenance::FromParam(did), ident) =>
449 def::DefAssociatedPath(def::TyParamProvenance::FromParam(did.tr(dcx)), ident),
450 def::DefPrimTy(p) => def::DefPrimTy(p),
451 def::DefTyParam(s, index, def_id, n) => def::DefTyParam(s, index, def_id.tr(dcx), n),
452 def::DefUse(did) => def::DefUse(did.tr(dcx)),
453 def::DefUpvar(nid1, nid2) => {
454 def::DefUpvar(dcx.tr_id(nid1), dcx.tr_id(nid2))
456 def::DefStruct(did) => def::DefStruct(did.tr(dcx)),
457 def::DefRegion(nid) => def::DefRegion(dcx.tr_id(nid)),
458 def::DefTyParamBinder(nid) => {
459 def::DefTyParamBinder(dcx.tr_id(nid))
461 def::DefLabel(nid) => def::DefLabel(dcx.tr_id(nid))
466 // ______________________________________________________________________
467 // Encoding and decoding of ancillary information
469 impl tr for ty::Region {
470 fn tr(&self, dcx: &DecodeContext) -> ty::Region {
472 ty::ReLateBound(debruijn, br) => {
473 ty::ReLateBound(debruijn, br.tr(dcx))
475 ty::ReEarlyBound(id, space, index, ident) => {
476 ty::ReEarlyBound(dcx.tr_id(id), space, index, ident)
478 ty::ReScope(scope) => {
479 ty::ReScope(scope.tr(dcx))
481 ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => {
484 ty::ReFree(ref fr) => {
485 ty::ReFree(fr.tr(dcx))
491 impl tr for ty::FreeRegion {
492 fn tr(&self, dcx: &DecodeContext) -> ty::FreeRegion {
493 ty::FreeRegion { scope: self.scope.tr(dcx),
494 bound_region: self.bound_region.tr(dcx) }
498 impl tr for region::CodeExtent {
499 fn tr(&self, dcx: &DecodeContext) -> region::CodeExtent {
500 self.map_id(|id| dcx.tr_id(id))
504 impl tr for region::DestructionScopeData {
505 fn tr(&self, dcx: &DecodeContext) -> region::DestructionScopeData {
506 region::DestructionScopeData { node_id: dcx.tr_id(self.node_id) }
510 impl tr for ty::BoundRegion {
511 fn tr(&self, dcx: &DecodeContext) -> ty::BoundRegion {
516 ty::BrNamed(id, ident) => ty::BrNamed(dcx.tr_def_id(id),
522 // ______________________________________________________________________
523 // Encoding and decoding of freevar information
525 fn encode_freevar_entry(rbml_w: &mut Encoder, fv: &ty::Freevar) {
526 (*fv).encode(rbml_w).unwrap();
529 trait rbml_decoder_helper {
530 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
532 fn read_capture_mode(&mut self) -> ast::CaptureClause;
535 impl<'a> rbml_decoder_helper for reader::Decoder<'a> {
536 fn read_freevar_entry(&mut self, dcx: &DecodeContext)
538 let fv: ty::Freevar = Decodable::decode(self).unwrap();
542 fn read_capture_mode(&mut self) -> ast::CaptureClause {
543 let cm: ast::CaptureClause = Decodable::decode(self).unwrap();
548 impl tr for ty::Freevar {
549 fn tr(&self, dcx: &DecodeContext) -> ty::Freevar {
551 def: self.def.tr(dcx),
552 span: self.span.tr(dcx),
557 impl tr for ty::UpvarBorrow {
558 fn tr(&self, dcx: &DecodeContext) -> ty::UpvarBorrow {
561 region: self.region.tr(dcx)
566 impl tr for ty::UpvarCapture {
567 fn tr(&self, dcx: &DecodeContext) -> ty::UpvarCapture {
569 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
570 ty::UpvarCapture::ByRef(ref data) => ty::UpvarCapture::ByRef(data.tr(dcx)),
575 // ______________________________________________________________________
576 // Encoding and decoding of MethodCallee
578 trait read_method_callee_helper<'tcx> {
579 fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
580 -> (ty::ExprAdjustment, MethodCallee<'tcx>);
583 fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>,
584 rbml_w: &mut Encoder,
585 adjustment: ty::ExprAdjustment,
586 method: &MethodCallee<'tcx>) {
587 use serialize::Encoder;
589 rbml_w.emit_struct("MethodCallee", 4, |rbml_w| {
590 rbml_w.emit_struct_field("adjustment", 0, |rbml_w| {
591 adjustment.encode(rbml_w)
593 rbml_w.emit_struct_field("origin", 1, |rbml_w| {
594 Ok(rbml_w.emit_method_origin(ecx, &method.origin))
596 rbml_w.emit_struct_field("ty", 2, |rbml_w| {
597 Ok(rbml_w.emit_ty(ecx, method.ty))
599 rbml_w.emit_struct_field("substs", 3, |rbml_w| {
600 Ok(rbml_w.emit_substs(ecx, &method.substs))
605 impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> {
606 fn read_method_callee<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
607 -> (ty::ExprAdjustment, MethodCallee<'tcx>) {
609 self.read_struct("MethodCallee", 4, |this| {
610 let adjustment = this.read_struct_field("adjustment", 0, |this| {
611 Decodable::decode(this)
613 Ok((adjustment, MethodCallee {
614 origin: this.read_struct_field("origin", 1, |this| {
615 Ok(this.read_method_origin(dcx))
617 ty: this.read_struct_field("ty", 2, |this| {
618 Ok(this.read_ty(dcx))
620 substs: this.read_struct_field("substs", 3, |this| {
621 Ok(this.read_substs(dcx))
628 impl<'tcx> tr for MethodOrigin<'tcx> {
629 fn tr(&self, dcx: &DecodeContext) -> MethodOrigin<'tcx> {
631 ty::MethodStatic(did) => ty::MethodStatic(did.tr(dcx)),
632 ty::MethodStaticClosure(did) => {
633 ty::MethodStaticClosure(did.tr(dcx))
635 ty::MethodTypeParam(ref mp) => {
638 // def-id is already translated when we read it out
639 trait_ref: mp.trait_ref.clone(),
640 method_num: mp.method_num,
641 impl_def_id: mp.impl_def_id.tr(dcx),
645 ty::MethodTraitObject(ref mo) => {
646 ty::MethodTraitObject(
648 trait_ref: mo.trait_ref.clone(),
657 pub fn encode_closure_kind(ebml_w: &mut Encoder, kind: ty::ClosureKind) {
658 kind.encode(ebml_w).unwrap();
661 pub trait vtable_decoder_helpers<'tcx> {
662 fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
663 F: FnMut(&mut Self) -> T;
664 fn read_vtable_res_with_key(&mut self,
665 tcx: &ty::ctxt<'tcx>,
666 cdata: &cstore::crate_metadata)
667 -> (ty::ExprAdjustment, ty::vtable_res<'tcx>);
668 fn read_vtable_res(&mut self,
669 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata)
670 -> ty::vtable_res<'tcx>;
671 fn read_vtable_param_res(&mut self,
672 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata)
673 -> ty::vtable_param_res<'tcx>;
674 fn read_vtable_origin(&mut self,
675 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata)
676 -> ty::vtable_origin<'tcx>;
679 impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> {
680 fn read_vec_per_param_space<T, F>(&mut self, mut f: F) -> VecPerParamSpace<T> where
681 F: FnMut(&mut reader::Decoder<'a>) -> T,
683 let types = self.read_to_vec(|this| Ok(f(this))).unwrap();
684 let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap();
685 let fns = self.read_to_vec(|this| Ok(f(this))).unwrap();
686 VecPerParamSpace::new(types, selfs, fns)
689 fn read_vtable_res_with_key(&mut self,
690 tcx: &ty::ctxt<'tcx>,
691 cdata: &cstore::crate_metadata)
692 -> (ty::ExprAdjustment, ty::vtable_res<'tcx>) {
693 self.read_struct("VtableWithKey", 2, |this| {
694 let adjustment = this.read_struct_field("adjustment", 0, |this| {
695 Decodable::decode(this)
697 Ok((adjustment, this.read_struct_field("vtable_res", 1, |this| {
698 Ok(this.read_vtable_res(tcx, cdata))
703 fn read_vtable_res(&mut self,
704 tcx: &ty::ctxt<'tcx>,
705 cdata: &cstore::crate_metadata)
706 -> ty::vtable_res<'tcx>
708 self.read_vec_per_param_space(
709 |this| this.read_vtable_param_res(tcx, cdata))
712 fn read_vtable_param_res(&mut self,
713 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata)
714 -> ty::vtable_param_res<'tcx> {
715 self.read_to_vec(|this| Ok(this.read_vtable_origin(tcx, cdata)))
716 .unwrap().into_iter().collect()
719 fn read_vtable_origin(&mut self,
720 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata)
721 -> ty::vtable_origin<'tcx> {
722 self.read_enum("vtable_origin", |this| {
723 this.read_enum_variant(&["vtable_static",
731 this.read_enum_variant_arg(0, |this| {
732 Ok(this.read_def_id_nodcx(cdata))
734 this.read_enum_variant_arg(1, |this| {
735 Ok(this.read_substs_nodcx(tcx, cdata))
737 this.read_enum_variant_arg(2, |this| {
738 Ok(this.read_vtable_res(tcx, cdata))
744 this.read_enum_variant_arg(0, |this| {
745 Decodable::decode(this)
747 this.read_enum_variant_arg(1, |this| {
754 this.read_enum_variant_arg(0, |this| {
755 Ok(this.read_def_id_nodcx(cdata))
762 _ => panic!("bad enum variant")
769 // ___________________________________________________________________________
772 fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder,
773 v: &subst::VecPerParamSpace<T>,
775 F: FnMut(&mut Encoder, &T),
777 for &space in &subst::ParamSpace::all() {
778 rbml_w.emit_from_vec(v.get_slice(space),
779 |rbml_w, n| Ok(f(rbml_w, n))).unwrap();
783 // ______________________________________________________________________
784 // Encoding and decoding the side tables
786 trait get_ty_str_ctxt<'tcx> {
787 fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a, 'tcx>;
790 impl<'a, 'tcx> get_ty_str_ctxt<'tcx> for e::EncodeContext<'a, 'tcx> {
791 fn ty_str_ctxt<'b>(&'b self) -> tyencode::ctxt<'b, 'tcx> {
793 diag: self.tcx.sess.diagnostic(),
794 ds: e::def_to_string,
796 abbrevs: &self.type_abbrevs
801 trait rbml_writer_helpers<'tcx> {
802 fn emit_closure_type<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
803 closure_type: &ty::ClosureTy<'tcx>);
804 fn emit_method_origin<'a>(&mut self,
805 ecx: &e::EncodeContext<'a, 'tcx>,
806 method_origin: &ty::MethodOrigin<'tcx>);
807 fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>);
808 fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]);
809 fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
810 type_param_def: &ty::TypeParameterDef<'tcx>);
811 fn emit_predicate<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
812 predicate: &ty::Predicate<'tcx>);
813 fn emit_trait_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
814 ty: &ty::TraitRef<'tcx>);
815 fn emit_type_scheme<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
816 type_scheme: ty::TypeScheme<'tcx>);
817 fn emit_substs<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
818 substs: &subst::Substs<'tcx>);
819 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
820 bounds: &ty::ExistentialBounds<'tcx>);
821 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds);
822 fn emit_auto_adjustment<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
823 adj: &ty::AutoAdjustment<'tcx>);
824 fn emit_autoref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
825 autoref: &ty::AutoRef<'tcx>);
826 fn emit_auto_deref_ref<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
827 auto_deref_ref: &ty::AutoDerefRef<'tcx>);
828 fn emit_unsize_kind<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>,
829 uk: &ty::UnsizeKind<'tcx>);
832 impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> {
833 fn emit_closure_type<'b>(&mut self,
834 ecx: &e::EncodeContext<'b, 'tcx>,
835 closure_type: &ty::ClosureTy<'tcx>) {
836 self.emit_opaque(|this| {
837 Ok(e::write_closure_type(ecx, this, closure_type))
841 fn emit_method_origin<'b>(&mut self,
842 ecx: &e::EncodeContext<'b, 'tcx>,
843 method_origin: &ty::MethodOrigin<'tcx>)
845 use serialize::Encoder;
847 self.emit_enum("MethodOrigin", |this| {
848 match *method_origin {
849 ty::MethodStatic(def_id) => {
850 this.emit_enum_variant("MethodStatic", 0, 1, |this| {
851 Ok(this.emit_def_id(def_id))
855 ty::MethodStaticClosure(def_id) => {
856 this.emit_enum_variant("MethodStaticClosure", 1, 1, |this| {
857 Ok(this.emit_def_id(def_id))
861 ty::MethodTypeParam(ref p) => {
862 this.emit_enum_variant("MethodTypeParam", 2, 1, |this| {
863 this.emit_struct("MethodParam", 2, |this| {
864 try!(this.emit_struct_field("trait_ref", 0, |this| {
865 Ok(this.emit_trait_ref(ecx, &*p.trait_ref))
867 try!(this.emit_struct_field("method_num", 0, |this| {
868 this.emit_uint(p.method_num)
870 try!(this.emit_struct_field("impl_def_id", 0, |this| {
871 this.emit_option(|this| {
872 match p.impl_def_id {
873 None => this.emit_option_none(),
874 Some(did) => this.emit_option_some(|this| {
875 Ok(this.emit_def_id(did))
885 ty::MethodTraitObject(ref o) => {
886 this.emit_enum_variant("MethodTraitObject", 3, 1, |this| {
887 this.emit_struct("MethodObject", 2, |this| {
888 try!(this.emit_struct_field("trait_ref", 0, |this| {
889 Ok(this.emit_trait_ref(ecx, &*o.trait_ref))
891 try!(this.emit_struct_field("object_trait_id", 0, |this| {
892 Ok(this.emit_def_id(o.object_trait_id))
894 try!(this.emit_struct_field("method_num", 0, |this| {
895 this.emit_uint(o.method_num)
897 try!(this.emit_struct_field("vtable_index", 0, |this| {
898 this.emit_uint(o.vtable_index)
908 fn emit_ty<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, ty: Ty<'tcx>) {
909 self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty)));
912 fn emit_tys<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>, tys: &[Ty<'tcx>]) {
913 self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty)));
916 fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
917 trait_ref: &ty::TraitRef<'tcx>) {
918 self.emit_opaque(|this| Ok(e::write_trait_ref(ecx, this, trait_ref)));
921 fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
922 type_param_def: &ty::TypeParameterDef<'tcx>) {
923 self.emit_opaque(|this| {
924 Ok(tyencode::enc_type_param_def(this.writer,
930 fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
931 predicate: &ty::Predicate<'tcx>) {
932 self.emit_opaque(|this| {
933 Ok(tyencode::enc_predicate(this.writer,
939 fn emit_type_scheme<'b>(&mut self,
940 ecx: &e::EncodeContext<'b, 'tcx>,
941 type_scheme: ty::TypeScheme<'tcx>) {
942 use serialize::Encoder;
944 self.emit_struct("TypeScheme", 2, |this| {
945 this.emit_struct_field("generics", 0, |this| {
946 this.emit_struct("Generics", 2, |this| {
947 this.emit_struct_field("types", 0, |this| {
948 Ok(encode_vec_per_param_space(
949 this, &type_scheme.generics.types,
950 |this, def| this.emit_type_param_def(ecx, def)))
952 this.emit_struct_field("regions", 1, |this| {
953 Ok(encode_vec_per_param_space(
954 this, &type_scheme.generics.regions,
955 |this, def| def.encode(this).unwrap()))
959 this.emit_struct_field("ty", 1, |this| {
960 Ok(this.emit_ty(ecx, type_scheme.ty))
965 fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
966 bounds: &ty::ExistentialBounds<'tcx>) {
967 self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this.writer,
972 fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
973 self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this.writer,
978 fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
979 substs: &subst::Substs<'tcx>) {
980 self.emit_opaque(|this| Ok(tyencode::enc_substs(this.writer,
985 fn emit_auto_adjustment<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
986 adj: &ty::AutoAdjustment<'tcx>) {
987 use serialize::Encoder;
989 self.emit_enum("AutoAdjustment", |this| {
991 ty::AdjustReifyFnPointer(def_id) => {
992 this.emit_enum_variant("AdjustReifyFnPointer", 1, 2, |this| {
993 this.emit_enum_variant_arg(0, |this| def_id.encode(this))
997 ty::AdjustDerefRef(ref auto_deref_ref) => {
998 this.emit_enum_variant("AdjustDerefRef", 2, 2, |this| {
999 this.emit_enum_variant_arg(0,
1000 |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref)))
1007 fn emit_autoref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
1008 autoref: &ty::AutoRef<'tcx>) {
1009 use serialize::Encoder;
1011 self.emit_enum("AutoRef", |this| {
1013 &ty::AutoPtr(r, m, None) => {
1014 this.emit_enum_variant("AutoPtr", 0, 3, |this| {
1015 this.emit_enum_variant_arg(0, |this| r.encode(this));
1016 this.emit_enum_variant_arg(1, |this| m.encode(this));
1017 this.emit_enum_variant_arg(2,
1018 |this| this.emit_option(|this| this.emit_option_none()))
1021 &ty::AutoPtr(r, m, Some(box ref a)) => {
1022 this.emit_enum_variant("AutoPtr", 0, 3, |this| {
1023 this.emit_enum_variant_arg(0, |this| r.encode(this));
1024 this.emit_enum_variant_arg(1, |this| m.encode(this));
1025 this.emit_enum_variant_arg(2, |this| this.emit_option(
1026 |this| this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a)))))
1029 &ty::AutoUnsize(ref uk) => {
1030 this.emit_enum_variant("AutoUnsize", 1, 1, |this| {
1031 this.emit_enum_variant_arg(0, |this| Ok(this.emit_unsize_kind(ecx, uk)))
1034 &ty::AutoUnsizeUniq(ref uk) => {
1035 this.emit_enum_variant("AutoUnsizeUniq", 2, 1, |this| {
1036 this.emit_enum_variant_arg(0, |this| Ok(this.emit_unsize_kind(ecx, uk)))
1039 &ty::AutoUnsafe(m, None) => {
1040 this.emit_enum_variant("AutoUnsafe", 3, 2, |this| {
1041 this.emit_enum_variant_arg(0, |this| m.encode(this));
1042 this.emit_enum_variant_arg(1,
1043 |this| this.emit_option(|this| this.emit_option_none()))
1046 &ty::AutoUnsafe(m, Some(box ref a)) => {
1047 this.emit_enum_variant("AutoUnsafe", 3, 2, |this| {
1048 this.emit_enum_variant_arg(0, |this| m.encode(this));
1049 this.emit_enum_variant_arg(1, |this| this.emit_option(
1050 |this| this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a)))))
1057 fn emit_auto_deref_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
1058 auto_deref_ref: &ty::AutoDerefRef<'tcx>) {
1059 use serialize::Encoder;
1061 self.emit_struct("AutoDerefRef", 2, |this| {
1062 this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
1063 this.emit_struct_field("autoref", 1, |this| {
1064 this.emit_option(|this| {
1065 match auto_deref_ref.autoref {
1066 None => this.emit_option_none(),
1067 Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(ecx, a))),
1074 fn emit_unsize_kind<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
1075 uk: &ty::UnsizeKind<'tcx>) {
1076 use serialize::Encoder;
1078 self.emit_enum("UnsizeKind", |this| {
1080 ty::UnsizeLength(len) => {
1081 this.emit_enum_variant("UnsizeLength", 0, 1, |this| {
1082 this.emit_enum_variant_arg(0, |this| len.encode(this))
1085 ty::UnsizeStruct(box ref uk, idx) => {
1086 this.emit_enum_variant("UnsizeStruct", 1, 2, |this| {
1087 this.emit_enum_variant_arg(0, |this| Ok(this.emit_unsize_kind(ecx, uk)));
1088 this.emit_enum_variant_arg(1, |this| idx.encode(this))
1091 ty::UnsizeVtable(ty::TyTrait { ref principal,
1094 this.emit_enum_variant("UnsizeVtable", 2, 4, |this| {
1095 this.emit_enum_variant_arg(0, |this| {
1096 try!(this.emit_struct_field("principal", 0, |this| {
1097 Ok(this.emit_trait_ref(ecx, &*principal.0))
1099 this.emit_struct_field("bounds", 1, |this| {
1100 Ok(this.emit_existential_bounds(ecx, b))
1103 this.emit_enum_variant_arg(1, |this| Ok(this.emit_ty(ecx, self_ty)))
1111 trait write_tag_and_id {
1112 fn tag<F>(&mut self, tag_id: c::astencode_tag, f: F) where F: FnOnce(&mut Self);
1113 fn id(&mut self, id: ast::NodeId);
1116 impl<'a> write_tag_and_id for Encoder<'a> {
1117 fn tag<F>(&mut self,
1118 tag_id: c::astencode_tag,
1120 F: FnOnce(&mut Encoder<'a>),
1122 self.start_tag(tag_id as uint);
1127 fn id(&mut self, id: ast::NodeId) {
1128 self.wr_tagged_u64(c::tag_table_id as uint, id as u64);
1132 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
1133 ecx: &'a e::EncodeContext<'c, 'tcx>,
1134 rbml_w: &'a mut Encoder<'b>,
1137 impl<'a, 'b, 'c, 'tcx> ast_util::IdVisitingOperation for
1138 SideTableEncodingIdVisitor<'a, 'b, 'c, 'tcx> {
1139 fn visit_id(&mut self, id: ast::NodeId) {
1140 encode_side_tables_for_id(self.ecx, self.rbml_w, id)
1144 fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
1145 rbml_w: &mut Encoder,
1146 ii: &ast::InlinedItem) {
1147 rbml_w.start_tag(c::tag_table as uint);
1148 ast_util::visit_ids_for_inlined_item(ii, &mut SideTableEncodingIdVisitor {
1155 fn encode_side_tables_for_id(ecx: &e::EncodeContext,
1156 rbml_w: &mut Encoder,
1160 debug!("Encoding side tables for id {}", id);
1162 if let Some(def) = tcx.def_map.borrow().get(&id) {
1163 rbml_w.tag(c::tag_table_def, |rbml_w| {
1165 rbml_w.tag(c::tag_table_val, |rbml_w| (*def).encode(rbml_w).unwrap());
1169 if let Some(ty) = tcx.node_types.borrow().get(&id) {
1170 rbml_w.tag(c::tag_table_node_type, |rbml_w| {
1172 rbml_w.tag(c::tag_table_val, |rbml_w| {
1173 rbml_w.emit_ty(ecx, *ty);
1178 if let Some(item_substs) = tcx.item_substs.borrow().get(&id) {
1179 rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
1181 rbml_w.tag(c::tag_table_val, |rbml_w| {
1182 rbml_w.emit_substs(ecx, &item_substs.substs);
1187 if let Some(fv) = tcx.freevars.borrow().get(&id) {
1188 rbml_w.tag(c::tag_table_freevars, |rbml_w| {
1190 rbml_w.tag(c::tag_table_val, |rbml_w| {
1191 rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
1192 Ok(encode_freevar_entry(rbml_w, fv_entry))
1198 rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
1200 rbml_w.tag(c::tag_table_val, |rbml_w| {
1201 let var_id = freevar.def.def_id().node;
1202 let upvar_id = ty::UpvarId {
1206 let upvar_capture = tcx.upvar_capture_map.borrow()[upvar_id].clone();
1207 var_id.encode(rbml_w);
1208 upvar_capture.encode(rbml_w);
1214 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1215 if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
1216 rbml_w.tag(c::tag_table_tcache, |rbml_w| {
1218 rbml_w.tag(c::tag_table_val, |rbml_w| {
1219 rbml_w.emit_type_scheme(ecx, type_scheme.clone());
1224 if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
1225 rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
1227 rbml_w.tag(c::tag_table_val, |rbml_w| {
1228 rbml_w.emit_type_param_def(ecx, type_param_def)
1233 let method_call = MethodCall::expr(id);
1234 if let Some(method) = tcx.method_map.borrow().get(&method_call) {
1235 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1237 rbml_w.tag(c::tag_table_val, |rbml_w| {
1238 encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
1243 if let Some(trait_ref) = tcx.object_cast_map.borrow().get(&id) {
1244 rbml_w.tag(c::tag_table_object_cast_map, |rbml_w| {
1246 rbml_w.tag(c::tag_table_val, |rbml_w| {
1247 rbml_w.emit_trait_ref(ecx, &*trait_ref.0);
1252 if let Some(adjustment) = tcx.adjustments.borrow().get(&id) {
1254 _ if ty::adjust_is_object(adjustment) => {
1255 let method_call = MethodCall::autoobject(id);
1256 if let Some(method) = tcx.method_map.borrow().get(&method_call) {
1257 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1259 rbml_w.tag(c::tag_table_val, |rbml_w| {
1260 encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
1265 ty::AdjustDerefRef(ref adj) => {
1266 assert!(!ty::adjust_is_object(adjustment));
1267 for autoderef in 0..adj.autoderefs {
1268 let method_call = MethodCall::autoderef(id, autoderef);
1269 if let Some(method) = tcx.method_map.borrow().get(&method_call) {
1270 rbml_w.tag(c::tag_table_method_map, |rbml_w| {
1272 rbml_w.tag(c::tag_table_val, |rbml_w| {
1273 encode_method_callee(ecx, rbml_w,
1274 method_call.adjustment, method)
1281 assert!(!ty::adjust_is_object(adjustment));
1285 rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
1287 rbml_w.tag(c::tag_table_val, |rbml_w| {
1288 rbml_w.emit_auto_adjustment(ecx, adjustment);
1293 if let Some(closure_type) = tcx.closure_tys.borrow().get(&ast_util::local_def(id)) {
1294 rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
1296 rbml_w.tag(c::tag_table_val, |rbml_w| {
1297 rbml_w.emit_closure_type(ecx, closure_type);
1302 if let Some(closure_kind) = tcx.closure_kinds.borrow().get(&ast_util::local_def(id)) {
1303 rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
1305 rbml_w.tag(c::tag_table_val, |rbml_w| {
1306 encode_closure_kind(rbml_w, *closure_kind)
1311 for &qualif in tcx.const_qualif_map.borrow().get(&id).iter() {
1312 rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
1314 rbml_w.tag(c::tag_table_val, |rbml_w| {
1315 qualif.encode(rbml_w).unwrap()
1321 trait doc_decoder_helpers {
1322 fn as_int(&self) -> int;
1323 fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>;
1326 impl<'a> doc_decoder_helpers for rbml::Doc<'a> {
1327 fn as_int(&self) -> int { reader::doc_as_u64(*self) as int }
1328 fn opt_child(&self, tag: c::astencode_tag) -> Option<rbml::Doc<'a>> {
1329 reader::maybe_get_doc(*self, tag as uint)
1333 trait rbml_decoder_decoder_helpers<'tcx> {
1334 fn read_method_origin<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1335 -> ty::MethodOrigin<'tcx>;
1336 fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>;
1337 fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec<Ty<'tcx>>;
1338 fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1339 -> Rc<ty::TraitRef<'tcx>>;
1340 fn read_poly_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1341 -> ty::PolyTraitRef<'tcx>;
1342 fn read_type_param_def<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1343 -> ty::TypeParameterDef<'tcx>;
1344 fn read_predicate<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1345 -> ty::Predicate<'tcx>;
1346 fn read_type_scheme<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1347 -> ty::TypeScheme<'tcx>;
1348 fn read_existential_bounds<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1349 -> ty::ExistentialBounds<'tcx>;
1350 fn read_substs<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1351 -> subst::Substs<'tcx>;
1352 fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1353 -> ty::AutoAdjustment<'tcx>;
1354 fn read_closure_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1356 fn read_closure_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1357 -> ty::ClosureTy<'tcx>;
1358 fn read_auto_deref_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1359 -> ty::AutoDerefRef<'tcx>;
1360 fn read_autoref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1361 -> ty::AutoRef<'tcx>;
1362 fn read_unsize_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1363 -> ty::UnsizeKind<'tcx>;
1364 fn convert_def_id(&mut self,
1365 dcx: &DecodeContext,
1366 source: DefIdSource,
1370 // Versions of the type reading functions that don't need the full
1372 fn read_ty_nodcx(&mut self,
1373 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx>;
1374 fn read_tys_nodcx(&mut self,
1375 tcx: &ty::ctxt<'tcx>,
1376 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>>;
1377 fn read_substs_nodcx(&mut self, tcx: &ty::ctxt<'tcx>,
1378 cdata: &cstore::crate_metadata)
1379 -> subst::Substs<'tcx>;
1382 impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
1383 fn read_ty_nodcx(&mut self,
1384 tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) -> Ty<'tcx> {
1385 self.read_opaque(|_, doc| {
1386 Ok(tydecode::parse_ty_data(
1391 |_, id| decoder::translate_def_id(cdata, id)))
1395 fn read_tys_nodcx(&mut self,
1396 tcx: &ty::ctxt<'tcx>,
1397 cdata: &cstore::crate_metadata) -> Vec<Ty<'tcx>> {
1398 self.read_to_vec(|this| Ok(this.read_ty_nodcx(tcx, cdata)) )
1404 fn read_substs_nodcx(&mut self,
1405 tcx: &ty::ctxt<'tcx>,
1406 cdata: &cstore::crate_metadata)
1407 -> subst::Substs<'tcx>
1409 self.read_opaque(|_, doc| {
1410 Ok(tydecode::parse_substs_data(
1415 |_, id| decoder::translate_def_id(cdata, id)))
1419 fn read_method_origin<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1420 -> ty::MethodOrigin<'tcx>
1422 self.read_enum("MethodOrigin", |this| {
1423 let variants = &["MethodStatic", "MethodStaticClosure",
1424 "MethodTypeParam", "MethodTraitObject"];
1425 this.read_enum_variant(variants, |this, i| {
1428 let def_id = this.read_def_id(dcx);
1429 ty::MethodStatic(def_id)
1433 let def_id = this.read_def_id(dcx);
1434 ty::MethodStaticClosure(def_id)
1438 this.read_struct("MethodTypeParam", 2, |this| {
1439 Ok(ty::MethodTypeParam(
1442 this.read_struct_field("trait_ref", 0, |this| {
1443 Ok(this.read_trait_ref(dcx))
1447 this.read_struct_field("method_num", 1, |this| {
1452 this.read_struct_field("impl_def_id", 2, |this| {
1453 this.read_option(|this, b| {
1455 Ok(Some(this.read_def_id(dcx)))
1467 this.read_struct("MethodTraitObject", 2, |this| {
1468 Ok(ty::MethodTraitObject(
1471 this.read_struct_field("trait_ref", 0, |this| {
1472 Ok(this.read_trait_ref(dcx))
1476 this.read_struct_field("object_trait_id", 1, |this| {
1477 Ok(this.read_def_id(dcx))
1481 this.read_struct_field("method_num", 2, |this| {
1486 this.read_struct_field("vtable_index", 3, |this| {
1501 fn read_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> Ty<'tcx> {
1502 // Note: regions types embed local node ids. In principle, we
1503 // should translate these node ids into the new decode
1504 // context. However, we do not bother, because region types
1505 // are not used during trans.
1507 return self.read_opaque(|this, doc| {
1508 debug!("read_ty({})", type_string(doc));
1510 let ty = tydecode::parse_ty_data(
1515 |s, a| this.convert_def_id(dcx, s, a));
1520 fn type_string(doc: rbml::Doc) -> String {
1521 let mut str = String::new();
1522 for i in doc.start..doc.end {
1523 str.push(doc.data[i] as char);
1529 fn read_tys<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1531 self.read_to_vec(|this| Ok(this.read_ty(dcx))).unwrap().into_iter().collect()
1534 fn read_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1535 -> Rc<ty::TraitRef<'tcx>> {
1536 self.read_opaque(|this, doc| {
1537 let ty = tydecode::parse_trait_ref_data(
1542 |s, a| this.convert_def_id(dcx, s, a));
1547 fn read_poly_trait_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1548 -> ty::PolyTraitRef<'tcx> {
1549 ty::Binder(self.read_opaque(|this, doc| {
1550 let ty = tydecode::parse_trait_ref_data(
1555 |s, a| this.convert_def_id(dcx, s, a));
1560 fn read_type_param_def<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1561 -> ty::TypeParameterDef<'tcx> {
1562 self.read_opaque(|this, doc| {
1563 Ok(tydecode::parse_type_param_def_data(
1568 |s, a| this.convert_def_id(dcx, s, a)))
1572 fn read_predicate<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1573 -> ty::Predicate<'tcx>
1575 self.read_opaque(|this, doc| {
1576 Ok(tydecode::parse_predicate_data(doc.data, doc.start, dcx.cdata.cnum, dcx.tcx,
1577 |s, a| this.convert_def_id(dcx, s, a)))
1581 fn read_type_scheme<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1582 -> ty::TypeScheme<'tcx> {
1583 self.read_struct("TypeScheme", 3, |this| {
1585 generics: this.read_struct_field("generics", 0, |this| {
1586 this.read_struct("Generics", 2, |this| {
1589 this.read_struct_field("types", 0, |this| {
1590 Ok(this.read_vec_per_param_space(
1591 |this| this.read_type_param_def(dcx)))
1595 this.read_struct_field("regions", 1, |this| {
1596 Ok(this.read_vec_per_param_space(
1597 |this| Decodable::decode(this).unwrap()))
1602 ty: this.read_struct_field("ty", 1, |this| {
1603 Ok(this.read_ty(dcx))
1609 fn read_existential_bounds<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1610 -> ty::ExistentialBounds<'tcx>
1612 self.read_opaque(|this, doc| {
1613 Ok(tydecode::parse_existential_bounds_data(doc.data,
1617 |s, a| this.convert_def_id(dcx, s, a)))
1621 fn read_substs<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1622 -> subst::Substs<'tcx> {
1623 self.read_opaque(|this, doc| {
1624 Ok(tydecode::parse_substs_data(doc.data,
1628 |s, a| this.convert_def_id(dcx, s, a)))
1632 fn read_auto_adjustment<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1633 -> ty::AutoAdjustment<'tcx> {
1634 self.read_enum("AutoAdjustment", |this| {
1635 let variants = ["AutoAddEnv", "AutoDerefRef"];
1636 this.read_enum_variant(&variants, |this, i| {
1639 let def_id: ast::DefId =
1640 this.read_def_id(dcx);
1642 ty::AdjustReifyFnPointer(def_id)
1645 let auto_deref_ref: ty::AutoDerefRef =
1646 this.read_enum_variant_arg(0,
1647 |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
1649 ty::AdjustDerefRef(auto_deref_ref)
1651 _ => panic!("bad enum variant for ty::AutoAdjustment")
1657 fn read_auto_deref_ref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1658 -> ty::AutoDerefRef<'tcx> {
1659 self.read_struct("AutoDerefRef", 2, |this| {
1660 Ok(ty::AutoDerefRef {
1661 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
1662 Decodable::decode(this)
1664 autoref: this.read_struct_field("autoref", 1, |this| {
1665 this.read_option(|this, b| {
1667 Ok(Some(this.read_autoref(dcx)))
1677 fn read_autoref<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) -> ty::AutoRef<'tcx> {
1678 self.read_enum("AutoRef", |this| {
1679 let variants = ["AutoPtr",
1683 this.read_enum_variant(&variants, |this, i| {
1687 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1688 let m: ast::Mutability =
1689 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1690 let a: Option<Box<ty::AutoRef>> =
1691 this.read_enum_variant_arg(2, |this| this.read_option(|this, b| {
1693 Ok(Some(box this.read_autoref(dcx)))
1699 ty::AutoPtr(r.tr(dcx), m, a)
1702 let uk: ty::UnsizeKind =
1703 this.read_enum_variant_arg(0,
1704 |this| Ok(this.read_unsize_kind(dcx))).unwrap();
1709 let uk: ty::UnsizeKind =
1710 this.read_enum_variant_arg(0,
1711 |this| Ok(this.read_unsize_kind(dcx))).unwrap();
1713 ty::AutoUnsizeUniq(uk)
1716 let m: ast::Mutability =
1717 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1718 let a: Option<Box<ty::AutoRef>> =
1719 this.read_enum_variant_arg(1, |this| this.read_option(|this, b| {
1721 Ok(Some(box this.read_autoref(dcx)))
1727 ty::AutoUnsafe(m, a)
1729 _ => panic!("bad enum variant for ty::AutoRef")
1735 fn read_unsize_kind<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1736 -> ty::UnsizeKind<'tcx> {
1737 self.read_enum("UnsizeKind", |this| {
1738 let variants = &["UnsizeLength", "UnsizeStruct", "UnsizeVtable"];
1739 this.read_enum_variant(variants, |this, i| {
1743 this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
1745 ty::UnsizeLength(len)
1748 let uk: ty::UnsizeKind =
1749 this.read_enum_variant_arg(0,
1750 |this| Ok(this.read_unsize_kind(dcx))).unwrap();
1752 this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap();
1754 ty::UnsizeStruct(box uk, idx)
1757 let ty_trait = try!(this.read_enum_variant_arg(0, |this| {
1758 let principal = try!(this.read_struct_field("principal", 0, |this| {
1759 Ok(this.read_poly_trait_ref(dcx))
1762 principal: principal,
1763 bounds: try!(this.read_struct_field("bounds", 1, |this| {
1764 Ok(this.read_existential_bounds(dcx))
1769 this.read_enum_variant_arg(1, |this| Ok(this.read_ty(dcx))).unwrap();
1770 ty::UnsizeVtable(ty_trait, self_ty)
1772 _ => panic!("bad enum variant for ty::UnsizeKind")
1778 fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1781 Decodable::decode(self).ok().unwrap()
1784 fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
1785 -> ty::ClosureTy<'tcx>
1787 self.read_opaque(|this, doc| {
1788 Ok(tydecode::parse_ty_closure_data(
1793 |s, a| this.convert_def_id(dcx, s, a)))
1797 /// Converts a def-id that appears in a type. The correct
1798 /// translation will depend on what kind of def-id this is.
1799 /// This is a subtle point: type definitions are not
1800 /// inlined into the current crate, so if the def-id names
1801 /// a nominal type or type alias, then it should be
1802 /// translated to refer to the source crate.
1804 /// However, *type parameters* are cloned along with the function
1805 /// they are attached to. So we should translate those def-ids
1806 /// to refer to the new, cloned copy of the type parameter.
1807 /// We only see references to free type parameters in the body of
1808 /// an inlined function. In such cases, we need the def-id to
1809 /// be a local id so that the TypeContents code is able to lookup
1810 /// the relevant info in the ty_param_defs table.
1812 /// *Region parameters*, unfortunately, are another kettle of fish.
1813 /// In such cases, def_id's can appear in types to distinguish
1814 /// shadowed bound regions and so forth. It doesn't actually
1815 /// matter so much what we do to these, since regions are erased
1816 /// at trans time, but it's good to keep them consistent just in
1817 /// case. We translate them with `tr_def_id()` which will map
1818 /// the crate numbers back to the original source crate.
1820 /// Unboxed closures are cloned along with the function being
1821 /// inlined, and all side tables use interned node IDs, so we
1822 /// translate their def IDs accordingly.
1824 /// It'd be really nice to refactor the type repr to not include
1825 /// def-ids so that all these distinctions were unnecessary.
1826 fn convert_def_id(&mut self,
1827 dcx: &DecodeContext,
1828 source: tydecode::DefIdSource,
1831 let r = match source {
1832 NominalType | TypeWithId | RegionParameter => dcx.tr_def_id(did),
1833 TypeParameter | ClosureSource => dcx.tr_intern_def_id(did)
1835 debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r);
1840 fn decode_side_tables(dcx: &DecodeContext,
1841 ast_doc: rbml::Doc) {
1842 let tbl_doc = ast_doc.get(c::tag_table as uint);
1843 reader::docs(tbl_doc, |tag, entry_doc| {
1844 let id0 = entry_doc.get(c::tag_table_id as uint).as_int();
1845 let id = dcx.tr_id(id0 as ast::NodeId);
1847 debug!(">> Side table document with tag 0x{:x} \
1848 found for id {} (orig {})",
1850 let decoded_tag: Option<c::astencode_tag> = FromPrimitive::from_uint(tag);
1854 &format!("unknown tag found in side tables: {:x}",
1858 let val_doc = entry_doc.get(c::tag_table_val as uint);
1859 let mut val_dsr = reader::Decoder::new(val_doc);
1860 let val_dsr = &mut val_dsr;
1863 c::tag_table_def => {
1864 let def = decode_def(dcx, val_doc);
1865 dcx.tcx.def_map.borrow_mut().insert(id, def);
1867 c::tag_table_node_type => {
1868 let ty = val_dsr.read_ty(dcx);
1869 debug!("inserting ty for node {}: {}",
1870 id, ty_to_string(dcx.tcx, ty));
1871 dcx.tcx.node_types.borrow_mut().insert(id, ty);
1873 c::tag_table_item_subst => {
1874 let item_substs = ty::ItemSubsts {
1875 substs: val_dsr.read_substs(dcx)
1877 dcx.tcx.item_substs.borrow_mut().insert(
1880 c::tag_table_freevars => {
1881 let fv_info = val_dsr.read_to_vec(|val_dsr| {
1882 Ok(val_dsr.read_freevar_entry(dcx))
1883 }).unwrap().into_iter().collect();
1884 dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
1886 c::tag_table_upvar_capture_map => {
1887 let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
1888 let upvar_id = ty::UpvarId {
1889 var_id: dcx.tr_id(var_id),
1892 let ub: ty::UpvarCapture = Decodable::decode(val_dsr).unwrap();
1893 dcx.tcx.upvar_capture_map.borrow_mut().insert(upvar_id, ub.tr(dcx));
1895 c::tag_table_tcache => {
1896 let type_scheme = val_dsr.read_type_scheme(dcx);
1897 let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id };
1898 dcx.tcx.tcache.borrow_mut().insert(lid, type_scheme);
1900 c::tag_table_param_defs => {
1901 let bounds = val_dsr.read_type_param_def(dcx);
1902 dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds);
1904 c::tag_table_method_map => {
1905 let (adjustment, method) = val_dsr.read_method_callee(dcx);
1906 let method_call = MethodCall {
1908 adjustment: adjustment
1910 dcx.tcx.method_map.borrow_mut().insert(method_call, method);
1912 c::tag_table_object_cast_map => {
1913 let trait_ref = val_dsr.read_poly_trait_ref(dcx);
1914 dcx.tcx.object_cast_map.borrow_mut()
1915 .insert(id, trait_ref);
1917 c::tag_table_adjustments => {
1918 let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(dcx);
1919 dcx.tcx.adjustments.borrow_mut().insert(id, adj);
1921 c::tag_table_closure_tys => {
1923 val_dsr.read_closure_ty(dcx);
1924 dcx.tcx.closure_tys.borrow_mut().insert(ast_util::local_def(id),
1927 c::tag_table_closure_kinds => {
1929 val_dsr.read_closure_kind(dcx);
1930 dcx.tcx.closure_kinds.borrow_mut().insert(ast_util::local_def(id),
1933 c::tag_table_const_qualif => {
1934 let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
1935 dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
1939 &format!("unknown tag found in side tables: {:x}",
1946 debug!(">< Side table doc loaded");
1951 // ______________________________________________________________________
1952 // Testing of astencode_gen
1955 fn encode_item_ast(rbml_w: &mut Encoder, item: &ast::Item) {
1956 rbml_w.start_tag(c::tag_tree as uint);
1957 (*item).encode(rbml_w);
1962 fn decode_item_ast(par_doc: rbml::Doc) -> ast::Item {
1963 let chi_doc = par_doc.get(c::tag_tree as uint);
1964 let mut d = reader::Decoder::new(chi_doc);
1965 Decodable::decode(&mut d).unwrap()
1969 trait fake_ext_ctxt {
1970 fn cfg(&self) -> ast::CrateConfig;
1971 fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess;
1972 fn call_site(&self) -> Span;
1973 fn ident_of(&self, st: &str) -> ast::Ident;
1977 impl fake_ext_ctxt for parse::ParseSess {
1978 fn cfg(&self) -> ast::CrateConfig {
1981 fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { self }
1982 fn call_site(&self) -> Span {
1984 lo: codemap::BytePos(0),
1985 hi: codemap::BytePos(0),
1986 expn_id: codemap::NO_EXPANSION
1989 fn ident_of(&self, st: &str) -> ast::Ident {
1990 token::str_to_ident(st)
1995 fn mk_ctxt() -> parse::ParseSess {
1996 parse::new_parse_sess()
2000 fn roundtrip(in_item: Option<P<ast::Item>>) {
2001 let in_item = in_item.unwrap();
2002 let mut wr = SeekableMemWriter::new();
2003 encode_item_ast(&mut writer::Encoder::new(&mut wr), &*in_item);
2004 let rbml_doc = rbml::Doc::new(wr.get_ref());
2005 let out_item = decode_item_ast(rbml_doc);
2007 assert!(*in_item == out_item);
2013 roundtrip(quote_item!(&cx,
2017 /* NOTE: When there's a snapshot, update this (yay quasiquoter!)
2019 fn test_smalltalk() {
2021 roundtrip(quote_item!(&cx,
2022 fn foo() -> int { 3 + 4 } // first smalltalk program ever executed.
2030 roundtrip(quote_item!(&cx,
2031 fn foo(x: uint, y: uint) -> uint {
2039 fn test_simplification() {
2041 let item = quote_item!(&cx,
2042 fn new_int_alist<B>() -> alist<int, B> {
2043 fn eq_int(a: int, b: int) -> bool { a == b }
2044 return alist {eq_fn: eq_int, data: Vec::new()};
2047 let item_in = e::IIItemRef(&*item);
2048 let item_out = simplify_ast(item_in);
2049 let item_exp = ast::IIItem(quote_item!(&cx,
2050 fn new_int_alist<B>() -> alist<int, B> {
2051 return alist {eq_fn: eq_int, data: Vec::new()};
2054 match (item_out, item_exp) {
2055 (ast::IIItem(item_out), ast::IIItem(item_exp)) => {
2056 assert!(pprust::item_to_string(&*item_out) ==
2057 pprust::item_to_string(&*item_exp));