auto merge of #13107 : seanmonstar/rust/encoder-errors, r=erickt

All of Decoder and Encoder's methods now return a Result.

Encodable.encode() and Decodable.decode() return a Result as well.

fixes #12292
This commit is contained in:
bors 2014-03-28 00:26:52 -07:00
commit ff64381c8b
27 changed files with 6558 additions and 1419 deletions

View file

@ -168,6 +168,18 @@ fn filestem(&self) -> ~str {
}
}
// FIXME: remove unwrap_ after snapshot
#[cfg(stage0)]
fn unwrap_<T>(t: T) -> T {
t
}
#[cfg(not(stage0))]
fn unwrap_<T, E>(r: Result<T, E>) -> T {
r.unwrap()
}
pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
-> ast::Crate {
let krate = time(sess.time_passes(), "parsing", (), |_| {
@ -187,7 +199,8 @@ pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
if sess.opts.debugging_opts & session::AST_JSON_NOEXPAND != 0 {
let mut stdout = io::BufferedWriter::new(io::stdout());
let mut json = json::PrettyEncoder::new(&mut stdout);
krate.encode(&mut json);
// unwrapping so IoError isn't ignored
unwrap_(krate.encode(&mut json));
}
if sess.show_span() {
@ -262,7 +275,8 @@ pub fn phase_2_configure_and_expand(sess: &Session,
if sess.opts.debugging_opts & session::AST_JSON != 0 {
let mut stdout = io::BufferedWriter::new(io::stdout());
let mut json = json::PrettyEncoder::new(&mut stdout);
krate.encode(&mut json);
// unwrapping so IoError isn't ignored
unwrap_(krate.encode(&mut json));
}
(krate, map)

View file

@ -47,6 +47,17 @@
pub type Cmd = @crate_metadata;
// FIXME: remove unwrap_ after a snapshot
#[cfg(stage0)]
fn unwrap_<T>(t: T) -> T {
t
}
#[cfg(not(stage0))]
fn unwrap_<T, E>(r: Result<T, E>) -> T {
r.unwrap()
}
// A function that takes a def_id relative to the crate being searched and
// returns a def_id relative to the compilation environment, i.e. if we hit a
// def_id for an item defined in another crate, somebody needs to figure out
@ -59,7 +70,7 @@ fn lookup_hash<'a>(d: ebml::Doc<'a>, eq_fn: |&[u8]| -> bool,
let table = reader::get_doc(index, tag_index_table);
let hash_pos = table.start + (hash % 256 * 4) as uint;
let pos = u64_from_be_bytes(d.data, hash_pos, 4) as uint;
let tagged_doc = reader::doc_at(d.data, pos);
let tagged_doc = unwrap_(reader::doc_at(d.data, pos));
let belt = tag_index_buckets_bucket_elt;
@ -67,7 +78,7 @@ fn lookup_hash<'a>(d: ebml::Doc<'a>, eq_fn: |&[u8]| -> bool,
reader::tagged_docs(tagged_doc.doc, belt, |elt| {
let pos = u64_from_be_bytes(elt.data, elt.start, 4) as uint;
if eq_fn(elt.data.slice(elt.start + 4, elt.end)) {
ret = Some(reader::doc_at(d.data, pos).doc);
ret = Some(unwrap_(reader::doc_at(d.data, pos)).doc);
false
} else {
true
@ -853,7 +864,7 @@ pub fn get_item_variances(cdata: Cmd, id: ast::NodeId) -> ty::ItemVariances {
let item_doc = lookup_item(id, data);
let variance_doc = reader::get_doc(item_doc, tag_item_variances);
let mut decoder = reader::Decoder(variance_doc);
Decodable::decode(&mut decoder)
unwrap_(Decodable::decode(&mut decoder))
}
pub fn get_provided_trait_methods(intr: @IdentInterner, cdata: Cmd,

View file

@ -62,8 +62,15 @@ pub enum InlinedItemRef<'a> {
IIForeignRef(&'a ast::ForeignItem)
}
// FIXME: remove this Encoder type after a snapshot
#[cfg(stage0)]
pub type Encoder<'a> = writer::Encoder<'a>;
#[cfg(not(stage0))]
pub type Encoder<'a> = writer::Encoder<'a, MemWriter>;
pub type EncodeInlinedItem<'a> = 'a |ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
ii: InlinedItemRef|;
pub struct EncodeParams<'a> {
@ -106,15 +113,15 @@ pub struct EncodeContext<'a> {
type_abbrevs: abbrev_map,
}
fn encode_name(ebml_w: &mut writer::Encoder, name: Name) {
fn encode_name(ebml_w: &mut Encoder, name: Name) {
ebml_w.wr_tagged_str(tag_paths_data_name, token::get_name(name).get());
}
fn encode_impl_type_basename(ebml_w: &mut writer::Encoder, name: Ident) {
fn encode_impl_type_basename(ebml_w: &mut Encoder, name: Ident) {
ebml_w.wr_tagged_str(tag_item_impl_type_basename, token::get_ident(name).get());
}
pub fn encode_def_id(ebml_w: &mut writer::Encoder, id: DefId) {
pub fn encode_def_id(ebml_w: &mut Encoder, id: DefId) {
ebml_w.wr_tagged_str(tag_def_id, def_to_str(id));
}
@ -124,7 +131,7 @@ struct entry<T> {
pos: u64
}
fn encode_trait_ref(ebml_w: &mut writer::Encoder,
fn encode_trait_ref(ebml_w: &mut Encoder,
ecx: &EncodeContext,
trait_ref: &ty::TraitRef,
tag: uint) {
@ -140,7 +147,7 @@ fn encode_trait_ref(ebml_w: &mut writer::Encoder,
ebml_w.end_tag();
}
fn encode_impl_vtables(ebml_w: &mut writer::Encoder,
fn encode_impl_vtables(ebml_w: &mut Encoder,
ecx: &EncodeContext,
vtables: &typeck::impl_res) {
ebml_w.start_tag(tag_item_impl_vtables);
@ -150,7 +157,7 @@ fn encode_impl_vtables(ebml_w: &mut writer::Encoder,
}
// Item info table encoding
fn encode_family(ebml_w: &mut writer::Encoder, c: char) {
fn encode_family(ebml_w: &mut Encoder, c: char) {
ebml_w.start_tag(tag_items_data_item_family);
ebml_w.writer.write(&[c as u8]);
ebml_w.end_tag();
@ -160,7 +167,7 @@ pub fn def_to_str(did: DefId) -> ~str {
format!("{}:{}", did.krate, did.node)
}
fn encode_ty_type_param_defs(ebml_w: &mut writer::Encoder,
fn encode_ty_type_param_defs(ebml_w: &mut Encoder,
ecx: &EncodeContext,
params: &[ty::TypeParameterDef],
tag: uint) {
@ -177,7 +184,7 @@ fn encode_ty_type_param_defs(ebml_w: &mut writer::Encoder,
}
}
fn encode_region_param_defs(ebml_w: &mut writer::Encoder,
fn encode_region_param_defs(ebml_w: &mut Encoder,
params: &[ty::RegionParameterDef]) {
for param in params.iter() {
ebml_w.start_tag(tag_region_param_def);
@ -193,7 +200,7 @@ fn encode_region_param_defs(ebml_w: &mut writer::Encoder,
}
}
fn encode_item_variances(ebml_w: &mut writer::Encoder,
fn encode_item_variances(ebml_w: &mut Encoder,
ecx: &EncodeContext,
id: ast::NodeId) {
let v = ty::item_variances(ecx.tcx, ast_util::local_def(id));
@ -202,7 +209,7 @@ fn encode_item_variances(ebml_w: &mut writer::Encoder,
ebml_w.end_tag();
}
fn encode_bounds_and_type(ebml_w: &mut writer::Encoder,
fn encode_bounds_and_type(ebml_w: &mut Encoder,
ecx: &EncodeContext,
tpt: &ty::ty_param_bounds_and_ty) {
encode_ty_type_param_defs(ebml_w, ecx, tpt.generics.type_param_defs(),
@ -211,7 +218,7 @@ fn encode_bounds_and_type(ebml_w: &mut writer::Encoder,
encode_type(ecx, ebml_w, tpt.ty);
}
fn encode_variant_id(ebml_w: &mut writer::Encoder, vid: DefId) {
fn encode_variant_id(ebml_w: &mut Encoder, vid: DefId) {
ebml_w.start_tag(tag_items_data_item_variant);
let s = def_to_str(vid);
ebml_w.writer.write(s.as_bytes());
@ -219,7 +226,7 @@ fn encode_variant_id(ebml_w: &mut writer::Encoder, vid: DefId) {
}
pub fn write_type(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
typ: ty::t) {
let ty_str_ctxt = &tyencode::ctxt {
diag: ecx.diag,
@ -231,7 +238,7 @@ pub fn write_type(ecx: &EncodeContext,
}
pub fn write_vstore(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
vstore: ty::vstore) {
let ty_str_ctxt = &tyencode::ctxt {
diag: ecx.diag,
@ -243,7 +250,7 @@ pub fn write_vstore(ecx: &EncodeContext,
}
fn encode_type(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
typ: ty::t) {
ebml_w.start_tag(tag_items_data_item_type);
write_type(ecx, ebml_w, typ);
@ -251,7 +258,7 @@ fn encode_type(ecx: &EncodeContext,
}
fn encode_method_fty(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
typ: &ty::BareFnTy) {
ebml_w.start_tag(tag_item_method_fty);
@ -267,7 +274,7 @@ fn encode_method_fty(ecx: &EncodeContext,
}
fn encode_symbol(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
id: NodeId) {
ebml_w.start_tag(tag_items_data_item_symbol);
match ecx.item_symbols.borrow().find(&id) {
@ -284,7 +291,7 @@ fn encode_symbol(ecx: &EncodeContext,
}
fn encode_disr_val(_: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
disr_val: ty::Disr) {
ebml_w.start_tag(tag_disr_val);
let s = disr_val.to_str();
@ -292,14 +299,14 @@ fn encode_disr_val(_: &EncodeContext,
ebml_w.end_tag();
}
fn encode_parent_item(ebml_w: &mut writer::Encoder, id: DefId) {
fn encode_parent_item(ebml_w: &mut Encoder, id: DefId) {
ebml_w.start_tag(tag_items_data_parent_item);
let s = def_to_str(id);
ebml_w.writer.write(s.as_bytes());
ebml_w.end_tag();
}
fn encode_struct_fields(ebml_w: &mut writer::Encoder,
fn encode_struct_fields(ebml_w: &mut Encoder,
def: @StructDef) {
for f in def.fields.iter() {
match f.node.kind {
@ -321,7 +328,7 @@ fn encode_struct_fields(ebml_w: &mut writer::Encoder,
}
fn encode_enum_variant_info(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
id: NodeId,
variants: &[P<Variant>],
index: @RefCell<Vec<entry<i64>> >,
@ -378,7 +385,7 @@ fn encode_enum_variant_info(ecx: &EncodeContext,
}
}
fn encode_path<PI: Iterator<PathElem> + Clone>(ebml_w: &mut writer::Encoder,
fn encode_path<PI: Iterator<PathElem> + Clone>(ebml_w: &mut Encoder,
mut path: PI) {
ebml_w.start_tag(tag_path);
ebml_w.wr_tagged_u32(tag_path_len, path.clone().len() as u32);
@ -392,7 +399,7 @@ fn encode_path<PI: Iterator<PathElem> + Clone>(ebml_w: &mut writer::Encoder,
ebml_w.end_tag();
}
fn encode_reexported_static_method(ebml_w: &mut writer::Encoder,
fn encode_reexported_static_method(ebml_w: &mut Encoder,
exp: &middle::resolve::Export2,
method_def_id: DefId,
method_ident: Ident) {
@ -409,7 +416,7 @@ fn encode_reexported_static_method(ebml_w: &mut writer::Encoder,
}
fn encode_reexported_static_base_methods(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
exp: &middle::resolve::Export2)
-> bool {
match ecx.tcx.inherent_impls.borrow().find(&exp.def_id) {
@ -429,7 +436,7 @@ fn encode_reexported_static_base_methods(ecx: &EncodeContext,
}
fn encode_reexported_static_trait_methods(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
exp: &middle::resolve::Export2)
-> bool {
match ecx.tcx.trait_methods_cache.borrow().find(&exp.def_id) {
@ -447,7 +454,7 @@ fn encode_reexported_static_trait_methods(ecx: &EncodeContext,
}
fn encode_reexported_static_methods(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
mod_path: PathElems,
exp: &middle::resolve::Export2) {
match ecx.tcx.map.find(exp.def_id.node) {
@ -527,7 +534,7 @@ fn each_auxiliary_node_id(item: @Item, callback: |NodeId| -> bool) -> bool {
}
fn encode_reexports(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
id: NodeId,
path: PathElems) {
debug!("(encoding info for module) encoding reexports for {}", id);
@ -560,7 +567,7 @@ fn encode_reexports(ecx: &EncodeContext,
}
fn encode_info_for_mod(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
md: &Mod,
id: NodeId,
path: PathElems,
@ -613,7 +620,7 @@ fn encode_info_for_mod(ecx: &EncodeContext,
ebml_w.end_tag();
}
fn encode_struct_field_family(ebml_w: &mut writer::Encoder,
fn encode_struct_field_family(ebml_w: &mut Encoder,
visibility: Visibility) {
encode_family(ebml_w, match visibility {
Public => 'g',
@ -622,7 +629,7 @@ fn encode_struct_field_family(ebml_w: &mut writer::Encoder,
});
}
fn encode_visibility(ebml_w: &mut writer::Encoder, visibility: Visibility) {
fn encode_visibility(ebml_w: &mut Encoder, visibility: Visibility) {
ebml_w.start_tag(tag_items_data_item_visibility);
let ch = match visibility {
Public => 'y',
@ -633,7 +640,7 @@ fn encode_visibility(ebml_w: &mut writer::Encoder, visibility: Visibility) {
ebml_w.end_tag();
}
fn encode_explicit_self(ebml_w: &mut writer::Encoder, explicit_self: ast::ExplicitSelf_) {
fn encode_explicit_self(ebml_w: &mut Encoder, explicit_self: ast::ExplicitSelf_) {
ebml_w.start_tag(tag_item_trait_method_explicit_self);
// Encode the base self type.
@ -650,7 +657,7 @@ fn encode_explicit_self(ebml_w: &mut writer::Encoder, explicit_self: ast::Explic
ebml_w.end_tag();
fn encode_mutability(ebml_w: &mut writer::Encoder,
fn encode_mutability(ebml_w: &mut Encoder,
m: ast::Mutability) {
match m {
MutImmutable => { ebml_w.writer.write(&[ 'i' as u8 ]); }
@ -659,13 +666,13 @@ fn encode_mutability(ebml_w: &mut writer::Encoder,
}
}
fn encode_method_sort(ebml_w: &mut writer::Encoder, sort: char) {
fn encode_method_sort(ebml_w: &mut Encoder, sort: char) {
ebml_w.start_tag(tag_item_trait_method_sort);
ebml_w.writer.write(&[ sort as u8 ]);
ebml_w.end_tag();
}
fn encode_provided_source(ebml_w: &mut writer::Encoder,
fn encode_provided_source(ebml_w: &mut Encoder,
source_opt: Option<DefId>) {
for source in source_opt.iter() {
ebml_w.start_tag(tag_item_method_provided_source);
@ -677,7 +684,7 @@ fn encode_provided_source(ebml_w: &mut writer::Encoder,
/* Returns an index of items in this class */
fn encode_info_for_struct(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
fields: &[StructField],
global_index: @RefCell<Vec<entry<i64>> >)
-> Vec<entry<i64>> {
@ -712,7 +719,7 @@ fn encode_info_for_struct(ecx: &EncodeContext,
}
fn encode_info_for_struct_ctor(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
name: ast::Ident,
ctor_id: NodeId,
index: @RefCell<Vec<entry<i64>> >,
@ -746,7 +753,7 @@ fn encode_info_for_struct_ctor(ecx: &EncodeContext,
}
fn encode_method_ty_fields(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
method_ty: &ty::Method) {
encode_def_id(ebml_w, method_ty.def_id);
encode_name(ebml_w, method_ty.ident.name);
@ -767,7 +774,7 @@ fn encode_method_ty_fields(ecx: &EncodeContext,
}
fn encode_info_for_method(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
m: &ty::Method,
impl_path: PathElems,
is_default_impl: bool,
@ -836,7 +843,7 @@ fn should_inline(attrs: &[Attribute]) -> bool {
// Encodes the inherent implementations of a structure, enumeration, or trait.
fn encode_inherent_implementations(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
def_id: DefId) {
match ecx.tcx.inherent_impls.borrow().find(&def_id) {
None => {}
@ -852,7 +859,7 @@ fn encode_inherent_implementations(ecx: &EncodeContext,
// Encodes the implementations of a trait defined in this crate.
fn encode_extension_implementations(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
trait_def_id: DefId) {
match ecx.tcx.trait_impls.borrow().find(&trait_def_id) {
None => {}
@ -867,14 +874,14 @@ fn encode_extension_implementations(ecx: &EncodeContext,
}
fn encode_info_for_item(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
item: &Item,
index: @RefCell<Vec<entry<i64>> >,
path: PathElems,
vis: ast::Visibility) {
let tcx = ecx.tcx;
fn add_to_index(item: &Item, ebml_w: &writer::Encoder,
fn add_to_index(item: &Item, ebml_w: &Encoder,
index: @RefCell<Vec<entry<i64>> >) {
index.borrow_mut().push(entry {
val: item.id as i64,
@ -1211,7 +1218,7 @@ fn add_to_index(item: &Item, ebml_w: &writer::Encoder,
}
fn encode_info_for_foreign_item(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
nitem: &ForeignItem,
index: @RefCell<Vec<entry<i64>> >,
path: PathElems,
@ -1253,7 +1260,7 @@ fn encode_info_for_foreign_item(ecx: &EncodeContext,
fn my_visit_expr(_e: &Expr) { }
fn my_visit_item(i: &Item,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
ecx_ptr: *int,
index: @RefCell<Vec<entry<i64>> >) {
let mut ebml_w = unsafe { ebml_w.unsafe_clone() };
@ -1265,7 +1272,7 @@ fn my_visit_item(i: &Item,
}
fn my_visit_foreign_item(ni: &ForeignItem,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
ecx_ptr:*int,
index: @RefCell<Vec<entry<i64>> >) {
// See above
@ -1286,7 +1293,7 @@ fn my_visit_foreign_item(ni: &ForeignItem,
}
struct EncodeVisitor<'a,'b> {
ebml_w_for_visit_item: &'a mut writer::Encoder<'b>,
ebml_w_for_visit_item: &'a mut Encoder<'b>,
ecx_ptr:*int,
index: @RefCell<Vec<entry<i64>> >,
}
@ -1313,7 +1320,7 @@ fn visit_foreign_item(&mut self, ni: &ForeignItem, _: ()) {
}
fn encode_info_for_items(ecx: &EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
krate: &Crate)
-> Vec<entry<i64>> {
let index = @RefCell::new(Vec::new());
@ -1369,7 +1376,7 @@ fn create_index<T:Clone + Hash + 'static>(
}
fn encode_index<T:'static>(
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
buckets: Vec<@Vec<entry<T>> > ,
write_fn: |&mut MemWriter, &T|) {
ebml_w.start_tag(tag_index);
@ -1407,7 +1414,7 @@ fn write_i64(writer: &mut MemWriter, &n: &i64) {
wr.write_be_u32(n as u32);
}
fn encode_meta_item(ebml_w: &mut writer::Encoder, mi: @MetaItem) {
fn encode_meta_item(ebml_w: &mut Encoder, mi: @MetaItem) {
match mi.node {
MetaWord(ref name) => {
ebml_w.start_tag(tag_meta_item_word);
@ -1444,7 +1451,7 @@ fn encode_meta_item(ebml_w: &mut writer::Encoder, mi: @MetaItem) {
}
}
fn encode_attributes(ebml_w: &mut writer::Encoder, attrs: &[Attribute]) {
fn encode_attributes(ebml_w: &mut Encoder, attrs: &[Attribute]) {
ebml_w.start_tag(tag_attributes);
for attr in attrs.iter() {
ebml_w.start_tag(tag_attribute);
@ -1480,7 +1487,7 @@ fn synthesize_crateid_attr(ecx: &EncodeContext) -> Attribute {
attrs
}
fn encode_crate_deps(ebml_w: &mut writer::Encoder, cstore: &cstore::CStore) {
fn encode_crate_deps(ebml_w: &mut Encoder, cstore: &cstore::CStore) {
fn get_ordered_deps(cstore: &cstore::CStore) -> Vec<decoder::CrateDep> {
// Pull the cnums and name,vers,hash out of cstore
let mut deps = Vec::new();
@ -1518,7 +1525,7 @@ fn get_ordered_deps(cstore: &cstore::CStore) -> Vec<decoder::CrateDep> {
ebml_w.end_tag();
}
fn encode_lang_items(ecx: &EncodeContext, ebml_w: &mut writer::Encoder) {
fn encode_lang_items(ecx: &EncodeContext, ebml_w: &mut Encoder) {
ebml_w.start_tag(tag_lang_items);
for (i, def_id) in ecx.tcx.lang_items.items() {
@ -1548,7 +1555,7 @@ fn encode_lang_items(ecx: &EncodeContext, ebml_w: &mut writer::Encoder) {
ebml_w.end_tag(); // tag_lang_items
}
fn encode_native_libraries(ecx: &EncodeContext, ebml_w: &mut writer::Encoder) {
fn encode_native_libraries(ecx: &EncodeContext, ebml_w: &mut Encoder) {
ebml_w.start_tag(tag_native_libraries);
for &(ref lib, kind) in ecx.tcx.sess.cstore.get_used_libraries()
@ -1574,7 +1581,7 @@ fn encode_native_libraries(ecx: &EncodeContext, ebml_w: &mut writer::Encoder) {
ebml_w.end_tag();
}
fn encode_macro_registrar_fn(ecx: &EncodeContext, ebml_w: &mut writer::Encoder) {
fn encode_macro_registrar_fn(ecx: &EncodeContext, ebml_w: &mut Encoder) {
match *ecx.tcx.sess.macro_registrar_fn.borrow() {
Some(did) => {
ebml_w.start_tag(tag_macro_registrar_fn);
@ -1587,7 +1594,7 @@ fn encode_macro_registrar_fn(ecx: &EncodeContext, ebml_w: &mut writer::Encoder)
struct MacroDefVisitor<'a, 'b> {
ecx: &'a EncodeContext<'a>,
ebml_w: &'a mut writer::Encoder<'b>
ebml_w: &'a mut Encoder<'b>
}
impl<'a, 'b> Visitor<()> for MacroDefVisitor<'a, 'b> {
@ -1608,7 +1615,7 @@ fn visit_item(&mut self, item: &Item, _: ()) {
fn encode_macro_defs(ecx: &EncodeContext,
krate: &Crate,
ebml_w: &mut writer::Encoder) {
ebml_w: &mut Encoder) {
ebml_w.start_tag(tag_exported_macros);
{
let mut visitor = MacroDefVisitor {
@ -1622,7 +1629,7 @@ fn encode_macro_defs(ecx: &EncodeContext,
struct ImplVisitor<'a,'b> {
ecx: &'a EncodeContext<'a>,
ebml_w: &'a mut writer::Encoder<'b>,
ebml_w: &'a mut Encoder<'b>,
}
impl<'a,'b> Visitor<()> for ImplVisitor<'a,'b> {
@ -1660,7 +1667,7 @@ fn visit_item(&mut self, item: &Item, _: ()) {
/// * Implementations of traits not defined in this crate.
fn encode_impls(ecx: &EncodeContext,
krate: &Crate,
ebml_w: &mut writer::Encoder) {
ebml_w: &mut Encoder) {
ebml_w.start_tag(tag_impls);
{
@ -1676,7 +1683,7 @@ fn encode_impls(ecx: &EncodeContext,
fn encode_misc_info(ecx: &EncodeContext,
krate: &Crate,
ebml_w: &mut writer::Encoder) {
ebml_w: &mut Encoder) {
ebml_w.start_tag(tag_misc_info);
ebml_w.start_tag(tag_misc_info_crate_items);
for &item in krate.module.items.iter() {
@ -1699,7 +1706,7 @@ fn encode_misc_info(ecx: &EncodeContext,
ebml_w.end_tag();
}
fn encode_crate_dep(ebml_w: &mut writer::Encoder,
fn encode_crate_dep(ebml_w: &mut Encoder,
dep: decoder::CrateDep) {
ebml_w.start_tag(tag_crate_dep);
ebml_w.start_tag(tag_crate_dep_crateid);
@ -1711,13 +1718,13 @@ fn encode_crate_dep(ebml_w: &mut writer::Encoder,
ebml_w.end_tag();
}
fn encode_hash(ebml_w: &mut writer::Encoder, hash: &Svh) {
fn encode_hash(ebml_w: &mut Encoder, hash: &Svh) {
ebml_w.start_tag(tag_crate_hash);
ebml_w.writer.write(hash.as_str().as_bytes());
ebml_w.end_tag();
}
fn encode_crate_id(ebml_w: &mut writer::Encoder, crate_id: &CrateId) {
fn encode_crate_id(ebml_w: &mut Encoder, crate_id: &CrateId) {
ebml_w.start_tag(tag_crate_crateid);
ebml_w.writer.write(crate_id.to_str().as_bytes());
ebml_w.end_tag();

View file

@ -9,6 +9,8 @@
// except according to those terms.
#[allow(non_camel_case_types)];
// FIXME: remove this after snapshot, and Results are handled
#[allow(unused_must_use)];
use c = metadata::common;
use cstore = metadata::cstore;
@ -36,6 +38,9 @@
use std::cast;
use std::cell::RefCell;
use std::io::Seek;
// FIXME: remove this attr after snapshot
#[cfg(not(stage0))]
use std::io::MemWriter;
use std::rc::Rc;
use serialize::ebml::reader;
@ -76,11 +81,41 @@ trait tr_intern {
fn tr_intern(&self, xcx: &ExtendedDecodeContext) -> ast::DefId;
}
// FIXME: remove this Encoder type after snapshot
#[cfg(stage0)]
pub type Encoder<'a> = writer::Encoder<'a>;
#[cfg(not(stage0))]
pub type Encoder<'a> = writer::Encoder<'a, MemWriter>;
// FIXME: remove unwrap_ and wrap_ after snapshot
#[cfg(stage0)]
fn unwrap_<T>(t: T) -> T {
t
}
#[cfg(not(stage0))]
fn unwrap_<T, E>(r: Result<T, E>) -> T {
r.unwrap()
}
#[cfg(stage0)]
fn wrap_<T>(t: T) -> T {
t
}
#[cfg(not(stage0))]
fn wrap_<T, E>(t: T) -> Result<T, E> {
Ok(t)
}
// ______________________________________________________________________
// Top-level methods.
pub fn encode_inlined_item(ecx: &e::EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
ii: e::InlinedItemRef,
maps: &Maps) {
let id = match ii {
@ -106,7 +141,7 @@ pub fn encode_inlined_item(ecx: &e::EncodeContext,
ebml_w.writer.tell());
}
pub fn encode_exported_macro(ebml_w: &mut writer::Encoder, i: &ast::Item) {
pub fn encode_exported_macro(ebml_w: &mut Encoder, i: &ast::Item) {
match i.node {
ast::ItemMac(..) => encode_ast(ebml_w, ast::IIItem(@i.clone())),
_ => fail!("expected a macro")
@ -136,7 +171,7 @@ pub fn decode_inlined_item(cdata: @cstore::crate_metadata,
path_as_str.as_ref().map(|x| x.as_slice())
});
let mut ast_dsr = reader::Decoder(ast_doc);
let from_id_range = Decodable::decode(&mut ast_dsr);
let from_id_range = unwrap_(Decodable::decode(&mut ast_dsr));
let to_id_range = reserve_id_range(&dcx.tcx.sess, from_id_range);
let xcx = &ExtendedDecodeContext {
dcx: dcx,
@ -272,27 +307,50 @@ trait def_id_encoder_helpers {
fn emit_def_id(&mut self, did: ast::DefId);
}
#[cfg(stage0)]
impl<S:serialize::Encoder> def_id_encoder_helpers for S {
fn emit_def_id(&mut self, did: ast::DefId) {
did.encode(self)
}
}
#[cfg(not(stage0))]
impl<S:serialize::Encoder<E>, E> def_id_encoder_helpers for S {
fn emit_def_id(&mut self, did: ast::DefId) {
unwrap_(did.encode(self))
}
}
trait def_id_decoder_helpers {
fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId;
fn read_def_id_noxcx(&mut self,
cdata: @cstore::crate_metadata) -> ast::DefId;
}
#[cfg(stage0)]
impl<D:serialize::Decoder> def_id_decoder_helpers for D {
fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId {
let did: ast::DefId = Decodable::decode(self);
let did: ast::DefId = unwrap_(Decodable::decode(self));
did.tr(xcx)
}
fn read_def_id_noxcx(&mut self,
cdata: @cstore::crate_metadata) -> ast::DefId {
let did: ast::DefId = Decodable::decode(self);
let did: ast::DefId = unwrap_(Decodable::decode(self));
decoder::translate_def_id(cdata, did)
}
}
#[cfg(not(stage0))]
impl<D:serialize::Decoder<E>, E> def_id_decoder_helpers for D {
fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId {
let did: ast::DefId = unwrap_(Decodable::decode(self));
did.tr(xcx)
}
fn read_def_id_noxcx(&mut self,
cdata: @cstore::crate_metadata) -> ast::DefId {
let did: ast::DefId = unwrap_(Decodable::decode(self));
decoder::translate_def_id(cdata, did)
}
}
@ -312,7 +370,7 @@ fn read_def_id_noxcx(&mut self,
// We also have to adjust the spans: for now we just insert a dummy span,
// but eventually we should add entries to the local codemap as required.
fn encode_ast(ebml_w: &mut writer::Encoder, item: ast::InlinedItem) {
fn encode_ast(ebml_w: &mut Encoder, item: ast::InlinedItem) {
ebml_w.start_tag(c::tag_tree as uint);
item.encode(ebml_w);
ebml_w.end_tag();
@ -372,7 +430,7 @@ fn simplify_ast(ii: e::InlinedItemRef) -> ast::InlinedItem {
fn decode_ast(par_doc: ebml::Doc) -> ast::InlinedItem {
let chi_doc = par_doc.get(c::tag_tree as uint);
let mut d = reader::Decoder(chi_doc);
Decodable::decode(&mut d)
unwrap_(Decodable::decode(&mut d))
}
struct AstRenumberer<'a> {
@ -418,7 +476,7 @@ fn renumber_and_map_ast(xcx: &ExtendedDecodeContext,
fn decode_def(xcx: &ExtendedDecodeContext, doc: ebml::Doc) -> ast::Def {
let mut dsr = reader::Decoder(doc);
let def: ast::Def = Decodable::decode(&mut dsr);
let def: ast::Def = unwrap_(Decodable::decode(&mut dsr));
def.tr(xcx)
}
@ -525,8 +583,8 @@ fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::BoundRegion {
// ______________________________________________________________________
// Encoding and decoding of freevar information
fn encode_freevar_entry(ebml_w: &mut writer::Encoder, fv: @freevar_entry) {
(*fv).encode(ebml_w)
fn encode_freevar_entry(ebml_w: &mut Encoder, fv: @freevar_entry) {
unwrap_((*fv).encode(ebml_w))
}
trait ebml_decoder_helper {
@ -537,7 +595,7 @@ fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
impl<'a> ebml_decoder_helper for reader::Decoder<'a> {
fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext)
-> freevar_entry {
let fv: freevar_entry = Decodable::decode(self);
let fv: freevar_entry = unwrap_(Decodable::decode(self));
fv.tr(xcx)
}
}
@ -562,7 +620,7 @@ fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
impl<'a> capture_var_helper for reader::Decoder<'a> {
fn read_capture_var(&mut self, xcx: &ExtendedDecodeContext)
-> moves::CaptureVar {
let cvar: moves::CaptureVar = Decodable::decode(self);
let cvar: moves::CaptureVar = unwrap_(Decodable::decode(self));
cvar.tr(xcx)
}
}
@ -585,45 +643,45 @@ trait read_method_callee_helper {
}
fn encode_method_callee(ecx: &e::EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
autoderef: u32,
method: &MethodCallee) {
ebml_w.emit_struct("MethodCallee", 4, |ebml_w| {
unwrap_(ebml_w.emit_struct("MethodCallee", 4, |ebml_w| {
ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
autoderef.encode(ebml_w);
autoderef.encode(ebml_w)
});
ebml_w.emit_struct_field("origin", 1u, |ebml_w| {
method.origin.encode(ebml_w);
method.origin.encode(ebml_w)
});
ebml_w.emit_struct_field("ty", 2u, |ebml_w| {
ebml_w.emit_ty(ecx, method.ty);
wrap_(ebml_w.emit_ty(ecx, method.ty))
});
ebml_w.emit_struct_field("substs", 3u, |ebml_w| {
ebml_w.emit_substs(ecx, &method.substs);
});
})
wrap_(ebml_w.emit_substs(ecx, &method.substs))
})
}));
}
impl<'a> read_method_callee_helper for reader::Decoder<'a> {
fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee) {
self.read_struct("MethodCallee", 4, |this| {
let autoderef = this.read_struct_field("autoderef", 0, |this| {
unwrap_(self.read_struct("MethodCallee", 4, |this| {
let autoderef = unwrap_(this.read_struct_field("autoderef", 0, |this| {
Decodable::decode(this)
});
(autoderef, MethodCallee {
origin: this.read_struct_field("origin", 1, |this| {
}));
wrap_((autoderef, MethodCallee {
origin: unwrap_(this.read_struct_field("origin", 1, |this| {
let method_origin: MethodOrigin =
Decodable::decode(this);
method_origin.tr(xcx)
}),
ty: this.read_struct_field("ty", 2, |this| {
this.read_ty(xcx)
}),
substs: this.read_struct_field("substs", 3, |this| {
this.read_substs(xcx)
})
})
})
unwrap_(Decodable::decode(this));
wrap_(method_origin.tr(xcx))
})),
ty: unwrap_(this.read_struct_field("ty", 2, |this| {
wrap_(this.read_ty(xcx))
})),
substs: unwrap_(this.read_struct_field("substs", 3, |this| {
wrap_(this.read_substs(xcx))
}))
}))
}))
}
}
@ -655,70 +713,70 @@ fn tr(&self, xcx: &ExtendedDecodeContext) -> MethodOrigin {
// Encoding and decoding vtable_res
fn encode_vtable_res_with_key(ecx: &e::EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
autoderef: u32,
dr: typeck::vtable_res) {
ebml_w.emit_struct("VtableWithKey", 2, |ebml_w| {
unwrap_(ebml_w.emit_struct("VtableWithKey", 2, |ebml_w| {
ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| {
autoderef.encode(ebml_w);
autoderef.encode(ebml_w)
});
ebml_w.emit_struct_field("vtable_res", 1u, |ebml_w| {
encode_vtable_res(ecx, ebml_w, dr);
});
})
wrap_(encode_vtable_res(ecx, ebml_w, dr))
})
}))
}
pub fn encode_vtable_res(ecx: &e::EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
dr: typeck::vtable_res) {
// can't autogenerate this code because automatic code of
// ty::t doesn't work, and there is no way (atm) to have
// hand-written encoding routines combine with auto-generated
// ones. perhaps we should fix this.
ebml_w.emit_from_vec(dr.as_slice(), |ebml_w, param_tables| {
encode_vtable_param_res(ecx, ebml_w, *param_tables);
})
unwrap_(ebml_w.emit_from_vec(dr.as_slice(), |ebml_w, param_tables| {
wrap_(encode_vtable_param_res(ecx, ebml_w, *param_tables))
}))
}
pub fn encode_vtable_param_res(ecx: &e::EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
param_tables: typeck::vtable_param_res) {
ebml_w.emit_from_vec(param_tables.as_slice(), |ebml_w, vtable_origin| {
encode_vtable_origin(ecx, ebml_w, vtable_origin)
})
unwrap_(ebml_w.emit_from_vec(param_tables.as_slice(), |ebml_w, vtable_origin| {
wrap_(encode_vtable_origin(ecx, ebml_w, vtable_origin))
}))
}
pub fn encode_vtable_origin(ecx: &e::EncodeContext,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
vtable_origin: &typeck::vtable_origin) {
ebml_w.emit_enum("vtable_origin", |ebml_w| {
unwrap_(ebml_w.emit_enum("vtable_origin", |ebml_w| {
match *vtable_origin {
typeck::vtable_static(def_id, ref tys, vtable_res) => {
ebml_w.emit_enum_variant("vtable_static", 0u, 3u, |ebml_w| {
ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
ebml_w.emit_def_id(def_id)
wrap_(ebml_w.emit_def_id(def_id))
});
ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
ebml_w.emit_tys(ecx, tys.as_slice());
wrap_(ebml_w.emit_tys(ecx, tys.as_slice()))
});
ebml_w.emit_enum_variant_arg(2u, |ebml_w| {
encode_vtable_res(ecx, ebml_w, vtable_res);
wrap_(encode_vtable_res(ecx, ebml_w, vtable_res))
})
})
}
typeck::vtable_param(pn, bn) => {
ebml_w.emit_enum_variant("vtable_param", 1u, 2u, |ebml_w| {
ebml_w.emit_enum_variant_arg(0u, |ebml_w| {
pn.encode(ebml_w);
pn.encode(ebml_w)
});
ebml_w.emit_enum_variant_arg(1u, |ebml_w| {
ebml_w.emit_uint(bn);
ebml_w.emit_uint(bn)
})
})
}
}
})
}))
}
pub trait vtable_decoder_helpers {
@ -742,21 +800,21 @@ fn read_vtable_res_with_key(&mut self,
tcx: &ty::ctxt,
cdata: @cstore::crate_metadata)
-> (u32, typeck::vtable_res) {
self.read_struct("VtableWithKey", 2, |this| {
let autoderef = this.read_struct_field("autoderef", 0, |this| {
unwrap_(self.read_struct("VtableWithKey", 2, |this| {
let autoderef = unwrap_(this.read_struct_field("autoderef", 0, |this| {
Decodable::decode(this)
});
(autoderef, this.read_struct_field("vtable_res", 1, |this| {
this.read_vtable_res(tcx, cdata)
}))
})
}));
wrap_((autoderef, unwrap_(this.read_struct_field("vtable_res", 1, |this| {
wrap_(this.read_vtable_res(tcx, cdata))
}))))
}))
}
fn read_vtable_res(&mut self,
tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
-> typeck::vtable_res {
@self.read_to_vec(|this|
this.read_vtable_param_res(tcx, cdata))
@unwrap_(self.read_to_vec(|this|
wrap_(this.read_vtable_param_res(tcx, cdata))))
.move_iter()
.collect()
}
@ -764,8 +822,8 @@ fn read_vtable_res(&mut self,
fn read_vtable_param_res(&mut self,
tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
-> typeck::vtable_param_res {
@self.read_to_vec(|this|
this.read_vtable_origin(tcx, cdata))
@unwrap_(self.read_to_vec(|this|
wrap_(this.read_vtable_origin(tcx, cdata))))
.move_iter()
.collect()
}
@ -773,40 +831,40 @@ fn read_vtable_param_res(&mut self,
fn read_vtable_origin(&mut self,
tcx: &ty::ctxt, cdata: @cstore::crate_metadata)
-> typeck::vtable_origin {
self.read_enum("vtable_origin", |this| {
unwrap_(self.read_enum("vtable_origin", |this| {
this.read_enum_variant(["vtable_static",
"vtable_param",
"vtable_self"],
|this, i| {
match i {
wrap_(match i {
0 => {
typeck::vtable_static(
this.read_enum_variant_arg(0u, |this| {
this.read_def_id_noxcx(cdata)
}),
this.read_enum_variant_arg(1u, |this| {
this.read_tys_noxcx(tcx, cdata)
}),
this.read_enum_variant_arg(2u, |this| {
this.read_vtable_res(tcx, cdata)
})
unwrap_(this.read_enum_variant_arg(0u, |this| {
wrap_(this.read_def_id_noxcx(cdata))
})),
unwrap_(this.read_enum_variant_arg(1u, |this| {
wrap_(this.read_tys_noxcx(tcx, cdata))
})),
unwrap_(this.read_enum_variant_arg(2u, |this| {
wrap_(this.read_vtable_res(tcx, cdata))
}))
)
}
1 => {
typeck::vtable_param(
this.read_enum_variant_arg(0u, |this| {
unwrap_(this.read_enum_variant_arg(0u, |this| {
Decodable::decode(this)
}),
this.read_enum_variant_arg(1u, |this| {
})),
unwrap_(this.read_enum_variant_arg(1u, |this| {
this.read_uint()
})
}))
)
}
// hard to avoid - user input
_ => fail!("bad enum variant")
}
})
})
})
}))
}
}
@ -842,27 +900,27 @@ fn emit_tpbt(&mut self,
fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment);
}
impl<'a> ebml_writer_helpers for writer::Encoder<'a> {
impl<'a> ebml_writer_helpers for Encoder<'a> {
fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t) {
self.emit_opaque(|this| e::write_type(ecx, this, ty))
self.emit_opaque(|this| wrap_(e::write_type(ecx, this, ty)));
}
fn emit_vstore(&mut self, ecx: &e::EncodeContext, vstore: ty::vstore) {
self.emit_opaque(|this| e::write_vstore(ecx, this, vstore))
self.emit_opaque(|this| wrap_(e::write_vstore(ecx, this, vstore)));
}
fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]) {
self.emit_from_vec(tys, |this, ty| this.emit_ty(ecx, *ty))
self.emit_from_vec(tys, |this, ty| wrap_(this.emit_ty(ecx, *ty)));
}
fn emit_type_param_def(&mut self,
ecx: &e::EncodeContext,
type_param_def: &ty::TypeParameterDef) {
self.emit_opaque(|this| {
tyencode::enc_type_param_def(this.writer,
wrap_(tyencode::enc_type_param_def(this.writer,
&ecx.ty_str_ctxt(),
type_param_def)
})
type_param_def))
});
}
fn emit_tpbt(&mut self,
@ -874,22 +932,24 @@ fn emit_tpbt(&mut self,
this.emit_struct_field("type_param_defs", 0, |this| {
this.emit_from_vec(tpbt.generics.type_param_defs(),
|this, type_param_def| {
this.emit_type_param_def(ecx, type_param_def);
wrap_(this.emit_type_param_def(ecx, type_param_def))
})
});
this.emit_struct_field("region_param_defs", 1, |this| {
tpbt.generics.region_param_defs().encode(this);
tpbt.generics.region_param_defs().encode(this)
})
})
});
this.emit_struct_field("ty", 1, |this| {
this.emit_ty(ecx, tpbt.ty);
wrap_(this.emit_ty(ecx, tpbt.ty))
})
})
});
}
fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &ty::substs) {
self.emit_opaque(|this| tyencode::enc_substs(this.writer, &ecx.ty_str_ctxt(), substs))
self.emit_opaque(|this| wrap_(tyencode::enc_substs(this.writer,
&ecx.ty_str_ctxt(),
substs)));
}
fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment) {
@ -898,14 +958,14 @@ fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustm
ty::AutoAddEnv(region, sigil) => {
this.emit_enum_variant("AutoAddEnv", 0, 2, |this| {
this.emit_enum_variant_arg(0, |this| region.encode(this));
this.emit_enum_variant_arg(1, |this| sigil.encode(this));
});
this.emit_enum_variant_arg(1, |this| sigil.encode(this))
})
}
ty::AutoDerefRef(ref auto_deref_ref) => {
this.emit_enum_variant("AutoDerefRef", 1, 1, |this| {
this.emit_enum_variant_arg(0, |this| auto_deref_ref.encode(this));
});
this.emit_enum_variant_arg(0, |this| auto_deref_ref.encode(this))
})
}
ty::AutoObject(sigil, region, m, b, def_id, ref substs) => {
@ -915,8 +975,8 @@ fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustm
this.emit_enum_variant_arg(2, |this| m.encode(this));
this.emit_enum_variant_arg(3, |this| b.encode(this));
this.emit_enum_variant_arg(4, |this| def_id.encode(this));
this.emit_enum_variant_arg(5, |this| this.emit_substs(ecx, substs));
});
this.emit_enum_variant_arg(5, |this| wrap_(this.emit_substs(ecx, substs)))
})
}
}
});
@ -928,23 +988,23 @@ trait write_tag_and_id {
fn id(&mut self, id: ast::NodeId);
}
impl<'a> write_tag_and_id for writer::Encoder<'a> {
impl<'a> write_tag_and_id for Encoder<'a> {
fn tag(&mut self,
tag_id: c::astencode_tag,
f: |&mut writer::Encoder<'a>|) {
f: |&mut Encoder<'a>|) {
self.start_tag(tag_id as uint);
f(self);
self.end_tag();
}
fn id(&mut self, id: ast::NodeId) {
self.wr_tagged_u64(c::tag_table_id as uint, id as u64)
self.wr_tagged_u64(c::tag_table_id as uint, id as u64);
}
}
struct SideTableEncodingIdVisitor<'a,'b> {
ecx_ptr: *libc::c_void,
new_ebml_w: &'a mut writer::Encoder<'b>,
new_ebml_w: &'a mut Encoder<'b>,
maps: &'a Maps,
}
@ -969,7 +1029,7 @@ fn visit_id(&self, id: ast::NodeId) {
fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
maps: &Maps,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
ii: &ast::InlinedItem) {
ebml_w.start_tag(c::tag_table as uint);
let mut new_ebml_w = unsafe {
@ -991,7 +1051,7 @@ fn encode_side_tables_for_ii(ecx: &e::EncodeContext,
fn encode_side_tables_for_id(ecx: &e::EncodeContext,
maps: &Maps,
ebml_w: &mut writer::Encoder,
ebml_w: &mut Encoder,
id: ast::NodeId) {
let tcx = ecx.tcx;
@ -1000,7 +1060,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
for def in tcx.def_map.borrow().find(&id).iter() {
ebml_w.tag(c::tag_table_def, |ebml_w| {
ebml_w.id(id);
ebml_w.tag(c::tag_table_val, |ebml_w| (*def).encode(ebml_w));
ebml_w.tag(c::tag_table_val, |ebml_w| unwrap_((*def).encode(ebml_w)));
})
}
@ -1027,8 +1087,8 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
ebml_w.id(id);
ebml_w.tag(c::tag_table_val, |ebml_w| {
ebml_w.emit_from_vec(fv.as_slice(), |ebml_w, fv_entry| {
encode_freevar_entry(ebml_w, *fv_entry)
})
wrap_(encode_freevar_entry(ebml_w, *fv_entry))
});
})
})
}
@ -1112,8 +1172,8 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
ebml_w.id(id);
ebml_w.tag(c::tag_table_val, |ebml_w| {
ebml_w.emit_from_vec(cap_vars.as_slice(), |ebml_w, cap_var| {
cap_var.encode(ebml_w);
})
cap_var.encode(ebml_w)
});
})
})
}
@ -1158,20 +1218,20 @@ fn read_tys_noxcx(&mut self,
impl<'a> ebml_decoder_decoder_helpers for reader::Decoder<'a> {
fn read_ty_noxcx(&mut self,
tcx: &ty::ctxt, cdata: @cstore::crate_metadata) -> ty::t {
self.read_opaque(|_, doc| {
tydecode::parse_ty_data(
unwrap_(self.read_opaque(|_, doc| {
wrap_(tydecode::parse_ty_data(
doc.data,
cdata.cnum,
doc.start,
tcx,
|_, id| decoder::translate_def_id(cdata, id))
})
|_, id| decoder::translate_def_id(cdata, id)))
}))
}
fn read_tys_noxcx(&mut self,
tcx: &ty::ctxt,
cdata: @cstore::crate_metadata) -> Vec<ty::t> {
self.read_to_vec(|this| this.read_ty_noxcx(tcx, cdata) )
unwrap_(self.read_to_vec(|this| wrap_(this.read_ty_noxcx(tcx, cdata)) ))
.move_iter()
.collect()
}
@ -1182,7 +1242,7 @@ fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t {
// context. However, we do not bother, because region types
// are not used during trans.
return self.read_opaque(|this, doc| {
return unwrap_(self.read_opaque(|this, doc| {
debug!("read_ty({})", type_string(doc));
let ty = tydecode::parse_ty_data(
@ -1192,8 +1252,8 @@ fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t {
xcx.dcx.tcx,
|s, a| this.convert_def_id(xcx, s, a));
ty
});
wrap_(ty)
}));
fn type_string(doc: ebml::Doc) -> ~str {
let mut str = ~"";
@ -1205,94 +1265,95 @@ fn type_string(doc: ebml::Doc) -> ~str {
}
fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t> {
self.read_to_vec(|this| this.read_ty(xcx)).move_iter().collect()
unwrap_(self.read_to_vec(|this| wrap_(this.read_ty(xcx)))).move_iter().collect()
}
fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext)
-> ty::TypeParameterDef {
self.read_opaque(|this, doc| {
tydecode::parse_type_param_def_data(
unwrap_(self.read_opaque(|this, doc| {
wrap_(tydecode::parse_type_param_def_data(
doc.data,
doc.start,
xcx.dcx.cdata.cnum,
xcx.dcx.tcx,
|s, a| this.convert_def_id(xcx, s, a))
})
|s, a| this.convert_def_id(xcx, s, a)))
}))
}
fn read_ty_param_bounds_and_ty(&mut self, xcx: &ExtendedDecodeContext)
-> ty::ty_param_bounds_and_ty {
self.read_struct("ty_param_bounds_and_ty", 2, |this| {
ty::ty_param_bounds_and_ty {
generics: this.read_struct_field("generics", 0, |this| {
unwrap_(self.read_struct("ty_param_bounds_and_ty", 2, |this| {
wrap_(ty::ty_param_bounds_and_ty {
generics: unwrap_(this.read_struct_field("generics", 0, |this| {
this.read_struct("Generics", 2, |this| {
ty::Generics {
wrap_(ty::Generics {
type_param_defs:
this.read_struct_field("type_param_defs",
unwrap_(this.read_struct_field("type_param_defs",
0,
|this| {
Rc::new(this.read_to_vec(|this|
this.read_type_param_def(xcx))
wrap_(Rc::new(unwrap_(this.read_to_vec(|this|
wrap_(this.read_type_param_def(xcx))))
.move_iter()
.collect())
}),
.collect()))
})),
region_param_defs:
this.read_struct_field("region_param_defs",
unwrap_(this.read_struct_field("region_param_defs",
1,
|this| {
Decodable::decode(this)
})
}
}))
})
})
}),
ty: this.read_struct_field("ty", 1, |this| {
this.read_ty(xcx)
})
}
})
})),
ty: unwrap_(this.read_struct_field("ty", 1, |this| {
wrap_(this.read_ty(xcx))
}))
})
}))
}
fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> ty::substs {
self.read_opaque(|this, doc| {
tydecode::parse_substs_data(doc.data,
unwrap_(self.read_opaque(|this, doc| {
wrap_(tydecode::parse_substs_data(doc.data,
xcx.dcx.cdata.cnum,
doc.start,
xcx.dcx.tcx,
|s, a| this.convert_def_id(xcx, s, a))
})
|s, a| this.convert_def_id(xcx, s, a)))
}))
}
fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment {
self.read_enum("AutoAdjustment", |this| {
unwrap_(self.read_enum("AutoAdjustment", |this| {
let variants = ["AutoAddEnv", "AutoDerefRef", "AutoObject"];
this.read_enum_variant(variants, |this, i| {
match i {
wrap_(match i {
0 => {
let region: ty::Region =
this.read_enum_variant_arg(0, |this| Decodable::decode(this));
unwrap_(this.read_enum_variant_arg(0, |this| Decodable::decode(this)));
let sigil: ast::Sigil =
this.read_enum_variant_arg(1, |this| Decodable::decode(this));
unwrap_(this.read_enum_variant_arg(1, |this| Decodable::decode(this)));
ty:: AutoAddEnv(region.tr(xcx), sigil)
}
1 => {
let auto_deref_ref: ty::AutoDerefRef =
this.read_enum_variant_arg(0, |this| Decodable::decode(this));
unwrap_(this.read_enum_variant_arg(0, |this| Decodable::decode(this)));
ty::AutoDerefRef(auto_deref_ref.tr(xcx))
}
2 => {
let sigil: ast::Sigil =
this.read_enum_variant_arg(0, |this| Decodable::decode(this));
unwrap_(this.read_enum_variant_arg(0, |this| Decodable::decode(this)));
let region: Option<ty::Region> =
this.read_enum_variant_arg(1, |this| Decodable::decode(this));
unwrap_(this.read_enum_variant_arg(1, |this| Decodable::decode(this)));
let m: ast::Mutability =
this.read_enum_variant_arg(2, |this| Decodable::decode(this));
unwrap_(this.read_enum_variant_arg(2, |this| Decodable::decode(this)));
let b: ty::BuiltinBounds =
this.read_enum_variant_arg(3, |this| Decodable::decode(this));
unwrap_(this.read_enum_variant_arg(3, |this| Decodable::decode(this)));
let def_id: ast::DefId =
this.read_enum_variant_arg(4, |this| Decodable::decode(this));
let substs = this.read_enum_variant_arg(5, |this| this.read_substs(xcx));
unwrap_(this.read_enum_variant_arg(4, |this| Decodable::decode(this)));
let substs = unwrap_(
this.read_enum_variant_arg(5, |this| wrap_(this.read_substs(xcx))));
let region = match region {
Some(r) => Some(r.tr(xcx)),
@ -1302,9 +1363,9 @@ fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjus
ty::AutoObject(sigil, region, m, b, def_id.tr(xcx), substs)
}
_ => fail!("bad enum variant for ty::AutoAdjustment")
}
})
})
})
}))
}
fn convert_def_id(&mut self,
@ -1387,9 +1448,9 @@ fn decode_side_tables(xcx: &ExtendedDecodeContext,
dcx.tcx.node_type_substs.borrow_mut().insert(id, tys);
}
c::tag_table_freevars => {
let fv_info = @val_dsr.read_to_vec(|val_dsr| {
@val_dsr.read_freevar_entry(xcx)
}).move_iter().collect();
let fv_info = @unwrap_(val_dsr.read_to_vec(|val_dsr| {
wrap_(@val_dsr.read_freevar_entry(xcx))
})).move_iter().collect();
dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
}
c::tag_table_tcache => {
@ -1425,7 +1486,8 @@ fn decode_side_tables(xcx: &ExtendedDecodeContext,
}
c::tag_table_capture_map => {
let cvars =
val_dsr.read_to_vec(|val_dsr| val_dsr.read_capture_var(xcx))
unwrap_(val_dsr.read_to_vec(
|val_dsr| wrap_(val_dsr.read_capture_var(xcx))))
.move_iter()
.collect();
dcx.maps.capture_map.borrow_mut().insert(id, Rc::new(cvars));
@ -1447,7 +1509,7 @@ fn decode_side_tables(xcx: &ExtendedDecodeContext,
// Testing of astencode_gen
#[cfg(test)]
fn encode_item_ast(ebml_w: &mut writer::Encoder, item: @ast::Item) {
fn encode_item_ast(ebml_w: &mut Encoder, item: @ast::Item) {
ebml_w.start_tag(c::tag_tree as uint);
(*item).encode(ebml_w);
ebml_w.end_tag();
@ -1457,7 +1519,7 @@ fn encode_item_ast(ebml_w: &mut writer::Encoder, item: @ast::Item) {
fn decode_item_ast(par_doc: ebml::Doc) -> @ast::Item {
let chi_doc = par_doc.get(c::tag_tree as uint);
let mut d = reader::Decoder(chi_doc);
@Decodable::decode(&mut d)
@unwrap_(Decodable::decode(&mut d))
}
#[cfg(test)]

View file

@ -327,6 +327,17 @@ fn rust_input(cratefile: &str, matches: &getopts::Matches) -> Output {
return pm.run_plugins(krate);
}
// FIXME: remove unwrap_ after snapshot
#[cfg(stage0)]
fn unwrap_<T>(t: T) -> T {
t
}
#[cfg(not(stage0))]
fn unwrap_<T, E>(r: Result<T, E>) -> T {
r.unwrap()
}
/// This input format purely deserializes the json output file. No passes are
/// run over the deserialized output.
fn json_input(input: &str) -> Result<Output, ~str> {
@ -352,7 +363,7 @@ fn json_input(input: &str) -> Result<Output, ~str> {
let krate = match obj.pop(&~"crate") {
Some(json) => {
let mut d = json::Decoder::new(json);
Decodable::decode(&mut d)
unwrap_(Decodable::decode(&mut d))
}
None => return Err(~"malformed json"),
};
@ -384,7 +395,7 @@ fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
let mut w = MemWriter::new();
{
let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
krate.encode(&mut encoder);
unwrap_(krate.encode(&mut encoder));
}
str::from_utf8_owned(w.unwrap()).unwrap()
};

View file

@ -20,272 +20,294 @@
use collections::enum_set::{EnumSet, CLike};
impl<
S: Encoder,
T: Encodable<S>
> Encodable<S> for DList<T> {
fn encode(&self, s: &mut S) {
E,
S: Encoder<E>,
T: Encodable<S, E>
> Encodable<S, E> for DList<T> {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s));
try!(s.emit_seq_elt(i, |s| e.encode(s)));
}
Ok(())
})
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for DList<T> {
fn decode(d: &mut D) -> DList<T> {
let mut list = DList::new();
impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for DList<T> {
fn decode(d: &mut D) -> Result<DList<T>, E> {
d.read_seq(|d, len| {
let mut list = DList::new();
for i in range(0u, len) {
list.push_back(d.read_seq_elt(i, |d| Decodable::decode(d)));
}
});
list
}
}
impl<
S: Encoder,
T: Encodable<S>
> Encodable<S> for RingBuf<T> {
fn encode(&self, s: &mut S) {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s));
list.push_back(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
}
Ok(list)
})
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for RingBuf<T> {
fn decode(d: &mut D) -> RingBuf<T> {
let mut deque = RingBuf::new();
d.read_seq(|d, len| {
for i in range(0u, len) {
deque.push_back(d.read_seq_elt(i, |d| Decodable::decode(d)));
impl<
E,
S: Encoder<E>,
T: Encodable<S, E>
> Encodable<S, E> for RingBuf<T> {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
try!(s.emit_seq_elt(i, |s| e.encode(s)));
}
});
deque
Ok(())
})
}
}
impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for RingBuf<T> {
fn decode(d: &mut D) -> Result<RingBuf<T>, E> {
d.read_seq(|d, len| {
let mut deque: RingBuf<T> = RingBuf::new();
for i in range(0u, len) {
deque.push_back(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
}
Ok(deque)
})
}
}
impl<
E: Encoder,
K: Encodable<E> + Eq + TotalOrd,
V: Encodable<E> + Eq
> Encodable<E> for TreeMap<K, V> {
fn encode(&self, e: &mut E) {
E,
S: Encoder<E>,
K: Encodable<S, E> + Eq + TotalOrd,
V: Encodable<S, E> + Eq
> Encodable<S, E> for TreeMap<K, V> {
fn encode(&self, e: &mut S) -> Result<(), E> {
e.emit_map(self.len(), |e| {
let mut i = 0;
for (key, val) in self.iter() {
e.emit_map_elt_key(i, |e| key.encode(e));
e.emit_map_elt_val(i, |e| val.encode(e));
try!(e.emit_map_elt_key(i, |e| key.encode(e)));
try!(e.emit_map_elt_val(i, |e| val.encode(e)));
i += 1;
}
Ok(())
})
}
}
impl<
D: Decoder,
K: Decodable<D> + Eq + TotalOrd,
V: Decodable<D> + Eq
> Decodable<D> for TreeMap<K, V> {
fn decode(d: &mut D) -> TreeMap<K, V> {
E,
D: Decoder<E>,
K: Decodable<D, E> + Eq + TotalOrd,
V: Decodable<D, E> + Eq
> Decodable<D, E> for TreeMap<K, V> {
fn decode(d: &mut D) -> Result<TreeMap<K, V>, E> {
d.read_map(|d, len| {
let mut map = TreeMap::new();
for i in range(0u, len) {
let key = d.read_map_elt_key(i, |d| Decodable::decode(d));
let val = d.read_map_elt_val(i, |d| Decodable::decode(d));
let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d)));
map.insert(key, val);
}
map
Ok(map)
})
}
}
impl<
S: Encoder,
T: Encodable<S> + Eq + TotalOrd
> Encodable<S> for TreeSet<T> {
fn encode(&self, s: &mut S) {
E,
S: Encoder<E>,
T: Encodable<S, E> + Eq + TotalOrd
> Encodable<S, E> for TreeSet<T> {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_seq(self.len(), |s| {
let mut i = 0;
for e in self.iter() {
s.emit_seq_elt(i, |s| e.encode(s));
try!(s.emit_seq_elt(i, |s| e.encode(s)));
i += 1;
}
Ok(())
})
}
}
impl<
D: Decoder,
T: Decodable<D> + Eq + TotalOrd
> Decodable<D> for TreeSet<T> {
fn decode(d: &mut D) -> TreeSet<T> {
E,
D: Decoder<E>,
T: Decodable<D, E> + Eq + TotalOrd
> Decodable<D, E> for TreeSet<T> {
fn decode(d: &mut D) -> Result<TreeSet<T>, E> {
d.read_seq(|d, len| {
let mut set = TreeSet::new();
for i in range(0u, len) {
set.insert(d.read_seq_elt(i, |d| Decodable::decode(d)));
set.insert(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
}
set
Ok(set)
})
}
}
impl<
S: Encoder,
T: Encodable<S> + CLike
> Encodable<S> for EnumSet<T> {
fn encode(&self, s: &mut S) {
E,
S: Encoder<E>,
T: Encodable<S, E> + CLike
> Encodable<S, E> for EnumSet<T> {
fn encode(&self, s: &mut S) -> Result<(), E> {
let mut bits = 0;
for item in self.iter() {
bits |= item.to_uint();
}
s.emit_uint(bits);
s.emit_uint(bits)
}
}
impl<
D: Decoder,
T: Decodable<D> + CLike
> Decodable<D> for EnumSet<T> {
fn decode(d: &mut D) -> EnumSet<T> {
let bits = d.read_uint();
E,
D: Decoder<E>,
T: Decodable<D, E> + CLike
> Decodable<D, E> for EnumSet<T> {
fn decode(d: &mut D) -> Result<EnumSet<T>, E> {
let bits = try!(d.read_uint());
let mut set = EnumSet::empty();
for bit in range(0, uint::BITS) {
if bits & (1 << bit) != 0 {
set.add(CLike::from_uint(1 << bit));
}
}
set
Ok(set)
}
}
impl<
E: Encoder,
K: Encodable<E> + Hash<S> + TotalEq,
V: Encodable<E>,
S,
H: Hasher<S>
> Encodable<E> for HashMap<K, V, H> {
fn encode(&self, e: &mut E) {
E,
S: Encoder<E>,
K: Encodable<S, E> + Hash<X> + TotalEq,
V: Encodable<S, E>,
X,
H: Hasher<X>
> Encodable<S, E> for HashMap<K, V, H> {
fn encode(&self, e: &mut S) -> Result<(), E> {
e.emit_map(self.len(), |e| {
let mut i = 0;
for (key, val) in self.iter() {
e.emit_map_elt_key(i, |e| key.encode(e));
e.emit_map_elt_val(i, |e| val.encode(e));
try!(e.emit_map_elt_key(i, |e| key.encode(e)));
try!(e.emit_map_elt_val(i, |e| val.encode(e)));
i += 1;
}
Ok(())
})
}
}
impl<
D: Decoder,
K: Decodable<D> + Hash<S> + TotalEq,
V: Decodable<D>,
E,
D: Decoder<E>,
K: Decodable<D, E> + Hash<S> + TotalEq,
V: Decodable<D, E>,
S,
H: Hasher<S> + Default
> Decodable<D> for HashMap<K, V, H> {
fn decode(d: &mut D) -> HashMap<K, V, H> {
> Decodable<D, E> for HashMap<K, V, H> {
fn decode(d: &mut D) -> Result<HashMap<K, V, H>, E> {
d.read_map(|d, len| {
let hasher = Default::default();
let mut map = HashMap::with_capacity_and_hasher(len, hasher);
for i in range(0u, len) {
let key = d.read_map_elt_key(i, |d| Decodable::decode(d));
let val = d.read_map_elt_val(i, |d| Decodable::decode(d));
let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d)));
map.insert(key, val);
}
map
Ok(map)
})
}
}
impl<
E: Encoder,
T: Encodable<E> + Hash<S> + TotalEq,
S,
H: Hasher<S>
> Encodable<E> for HashSet<T, H> {
fn encode(&self, s: &mut E) {
E,
S: Encoder<E>,
T: Encodable<S, E> + Hash<X> + TotalEq,
X,
H: Hasher<X>
> Encodable<S, E> for HashSet<T, H> {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_seq(self.len(), |s| {
let mut i = 0;
for e in self.iter() {
s.emit_seq_elt(i, |s| e.encode(s));
try!(s.emit_seq_elt(i, |s| e.encode(s)));
i += 1;
}
Ok(())
})
}
}
impl<
D: Decoder,
T: Decodable<D> + Hash<S> + TotalEq,
E,
D: Decoder<E>,
T: Decodable<D, E> + Hash<S> + TotalEq,
S,
H: Hasher<S> + Default
> Decodable<D> for HashSet<T, H> {
fn decode(d: &mut D) -> HashSet<T, H> {
> Decodable<D, E> for HashSet<T, H> {
fn decode(d: &mut D) -> Result<HashSet<T, H>, E> {
d.read_seq(|d, len| {
let mut set = HashSet::with_capacity_and_hasher(len, Default::default());
for i in range(0u, len) {
set.insert(d.read_seq_elt(i, |d| Decodable::decode(d)));
set.insert(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
}
set
Ok(set)
})
}
}
impl<
E: Encoder,
V: Encodable<E>
> Encodable<E> for TrieMap<V> {
fn encode(&self, e: &mut E) {
E,
S: Encoder<E>,
V: Encodable<S, E>
> Encodable<S, E> for TrieMap<V> {
fn encode(&self, e: &mut S) -> Result<(), E> {
e.emit_map(self.len(), |e| {
for (i, (key, val)) in self.iter().enumerate() {
e.emit_map_elt_key(i, |e| key.encode(e));
e.emit_map_elt_val(i, |e| val.encode(e));
}
});
}
}
impl<
D: Decoder,
V: Decodable<D>
> Decodable<D> for TrieMap<V> {
fn decode(d: &mut D) -> TrieMap<V> {
d.read_map(|d, len| {
let mut map = TrieMap::new();
for i in range(0u, len) {
let key = d.read_map_elt_key(i, |d| Decodable::decode(d));
let val = d.read_map_elt_val(i, |d| Decodable::decode(d));
map.insert(key, val);
}
map
})
}
}
impl<S: Encoder> Encodable<S> for TrieSet {
fn encode(&self, s: &mut S) {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s));
try!(e.emit_map_elt_key(i, |e| key.encode(e)));
try!(e.emit_map_elt_val(i, |e| val.encode(e)));
}
Ok(())
})
}
}
impl<D: Decoder> Decodable<D> for TrieSet {
fn decode(d: &mut D) -> TrieSet {
d.read_seq(|d, len| {
let mut set = TrieSet::new();
impl<
E,
D: Decoder<E>,
V: Decodable<D, E>
> Decodable<D, E> for TrieMap<V> {
fn decode(d: &mut D) -> Result<TrieMap<V>, E> {
d.read_map(|d, len| {
let mut map = TrieMap::new();
for i in range(0u, len) {
set.insert(d.read_seq_elt(i, |d| Decodable::decode(d)));
let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d)));
map.insert(key, val);
}
set
Ok(map)
})
}
}
impl<E, S: Encoder<E>> Encodable<S, E> for TrieSet {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
try!(s.emit_seq_elt(i, |s| e.encode(s)));
}
Ok(())
})
}
}
impl<E, D: Decoder<E>> Decodable<D, E> for TrieSet {
fn decode(d: &mut D) -> Result<TrieSet, E> {
d.read_seq(|d, len| {
let mut set = TrieSet::new();
for i in range(0u, len) {
set.insert(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
}
Ok(set)
})
}
}

View file

@ -0,0 +1,292 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Implementations of serialization for structures found in libcollections
use std::uint;
use std::default::Default;
use std::hash::{Hash, Hasher};
use {Decodable, Encodable, Decoder, Encoder};
use collections::{DList, RingBuf, TreeMap, TreeSet, Deque, HashMap, HashSet,
TrieMap, TrieSet};
use collections::enum_set::{EnumSet, CLike};
impl<
S: Encoder,
T: Encodable<S>
> Encodable<S> for DList<T> {
fn encode(&self, s: &mut S) {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s));
}
})
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for DList<T> {
fn decode(d: &mut D) -> DList<T> {
let mut list = DList::new();
d.read_seq(|d, len| {
for i in range(0u, len) {
list.push_back(d.read_seq_elt(i, |d| Decodable::decode(d)));
}
});
list
}
}
impl<
S: Encoder,
T: Encodable<S>
> Encodable<S> for RingBuf<T> {
fn encode(&self, s: &mut S) {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s));
}
})
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for RingBuf<T> {
fn decode(d: &mut D) -> RingBuf<T> {
let mut deque = RingBuf::new();
d.read_seq(|d, len| {
for i in range(0u, len) {
deque.push_back(d.read_seq_elt(i, |d| Decodable::decode(d)));
}
});
deque
}
}
impl<
E: Encoder,
K: Encodable<E> + Eq + TotalOrd,
V: Encodable<E> + Eq
> Encodable<E> for TreeMap<K, V> {
fn encode(&self, e: &mut E) {
e.emit_map(self.len(), |e| {
let mut i = 0;
for (key, val) in self.iter() {
e.emit_map_elt_key(i, |e| key.encode(e));
e.emit_map_elt_val(i, |e| val.encode(e));
i += 1;
}
})
}
}
impl<
D: Decoder,
K: Decodable<D> + Eq + TotalOrd,
V: Decodable<D> + Eq
> Decodable<D> for TreeMap<K, V> {
fn decode(d: &mut D) -> TreeMap<K, V> {
d.read_map(|d, len| {
let mut map = TreeMap::new();
for i in range(0u, len) {
let key = d.read_map_elt_key(i, |d| Decodable::decode(d));
let val = d.read_map_elt_val(i, |d| Decodable::decode(d));
map.insert(key, val);
}
map
})
}
}
impl<
S: Encoder,
T: Encodable<S> + Eq + TotalOrd
> Encodable<S> for TreeSet<T> {
fn encode(&self, s: &mut S) {
s.emit_seq(self.len(), |s| {
let mut i = 0;
for e in self.iter() {
s.emit_seq_elt(i, |s| e.encode(s));
i += 1;
}
})
}
}
impl<
D: Decoder,
T: Decodable<D> + Eq + TotalOrd
> Decodable<D> for TreeSet<T> {
fn decode(d: &mut D) -> TreeSet<T> {
d.read_seq(|d, len| {
let mut set = TreeSet::new();
for i in range(0u, len) {
set.insert(d.read_seq_elt(i, |d| Decodable::decode(d)));
}
set
})
}
}
impl<
S: Encoder,
T: Encodable<S> + CLike
> Encodable<S> for EnumSet<T> {
fn encode(&self, s: &mut S) {
let mut bits = 0;
for item in self.iter() {
bits |= item.to_uint();
}
s.emit_uint(bits);
}
}
impl<
D: Decoder,
T: Decodable<D> + CLike
> Decodable<D> for EnumSet<T> {
fn decode(d: &mut D) -> EnumSet<T> {
let bits = d.read_uint();
let mut set = EnumSet::empty();
for bit in range(0, uint::BITS) {
if bits & (1 << bit) != 0 {
set.add(CLike::from_uint(1 << bit));
}
}
set
}
}
impl<
E: Encoder,
K: Encodable<E> + Hash<S> + TotalEq,
V: Encodable<E>,
S,
H: Hasher<S>
> Encodable<E> for HashMap<K, V, H> {
fn encode(&self, e: &mut E) {
e.emit_map(self.len(), |e| {
let mut i = 0;
for (key, val) in self.iter() {
e.emit_map_elt_key(i, |e| key.encode(e));
e.emit_map_elt_val(i, |e| val.encode(e));
i += 1;
}
})
}
}
impl<
D: Decoder,
K: Decodable<D> + Hash<S> + TotalEq,
V: Decodable<D>,
S,
H: Hasher<S> + Default
> Decodable<D> for HashMap<K, V, H> {
fn decode(d: &mut D) -> HashMap<K, V, H> {
d.read_map(|d, len| {
let hasher = Default::default();
let mut map = HashMap::with_capacity_and_hasher(len, hasher);
for i in range(0u, len) {
let key = d.read_map_elt_key(i, |d| Decodable::decode(d));
let val = d.read_map_elt_val(i, |d| Decodable::decode(d));
map.insert(key, val);
}
map
})
}
}
impl<
E: Encoder,
T: Encodable<E> + Hash<S> + TotalEq,
S,
H: Hasher<S>
> Encodable<E> for HashSet<T, H> {
fn encode(&self, s: &mut E) {
s.emit_seq(self.len(), |s| {
let mut i = 0;
for e in self.iter() {
s.emit_seq_elt(i, |s| e.encode(s));
i += 1;
}
})
}
}
impl<
D: Decoder,
T: Decodable<D> + Hash<S> + TotalEq,
S,
H: Hasher<S> + Default
> Decodable<D> for HashSet<T, H> {
fn decode(d: &mut D) -> HashSet<T, H> {
d.read_seq(|d, len| {
let mut set = HashSet::with_capacity_and_hasher(len, Default::default());
for i in range(0u, len) {
set.insert(d.read_seq_elt(i, |d| Decodable::decode(d)));
}
set
})
}
}
impl<
E: Encoder,
V: Encodable<E>
> Encodable<E> for TrieMap<V> {
fn encode(&self, e: &mut E) {
e.emit_map(self.len(), |e| {
for (i, (key, val)) in self.iter().enumerate() {
e.emit_map_elt_key(i, |e| key.encode(e));
e.emit_map_elt_val(i, |e| val.encode(e));
}
});
}
}
impl<
D: Decoder,
V: Decodable<D>
> Decodable<D> for TrieMap<V> {
fn decode(d: &mut D) -> TrieMap<V> {
d.read_map(|d, len| {
let mut map = TrieMap::new();
for i in range(0u, len) {
let key = d.read_map_elt_key(i, |d| Decodable::decode(d));
let val = d.read_map_elt_val(i, |d| Decodable::decode(d));
map.insert(key, val);
}
map
})
}
}
impl<S: Encoder> Encodable<S> for TrieSet {
fn encode(&self, s: &mut S) {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s));
}
})
}
}
impl<D: Decoder> Decodable<D> for TrieSet {
fn decode(d: &mut D) -> TrieSet {
d.read_seq(|d, len| {
let mut set = TrieSet::new();
for i in range(0u, len) {
set.insert(d.read_seq_elt(i, |d| Decodable::decode(d)));
}
set
})
}
}

File diff suppressed because it is too large Load diff

1120
src/libserialize/ebml_old.rs Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

2606
src/libserialize/json_old.rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -34,10 +34,31 @@
pub use self::serialize::{Decoder, Encoder, Decodable, Encodable,
DecoderHelpers, EncoderHelpers};
// FIXME: remove _old.rs files after snapshot
#[cfg(not(stage0))]
mod serialize;
#[cfg(not(stage0))]
mod collection_impls;
pub mod base64;
#[cfg(not(stage0))]
pub mod ebml;
pub mod hex;
#[cfg(not(stage0))]
pub mod json;
#[cfg(stage0)]
#[path="./serialize_old.rs"]
pub mod serialize;
#[cfg(stage0)]
#[path="./collection_impls_old.rs"]
mod collection_impls;
#[cfg(stage0)]
#[path="./ebml_old.rs"]
pub mod ebml;
#[cfg(stage0)]
#[path="./json_old.rs"]
pub mod json;

View file

@ -18,444 +18,465 @@
use std::rc::Rc;
use std::slice;
pub trait Encoder {
pub trait Encoder<E> {
// Primitive types:
fn emit_nil(&mut self);
fn emit_uint(&mut self, v: uint);
fn emit_u64(&mut self, v: u64);
fn emit_u32(&mut self, v: u32);
fn emit_u16(&mut self, v: u16);
fn emit_u8(&mut self, v: u8);
fn emit_int(&mut self, v: int);
fn emit_i64(&mut self, v: i64);
fn emit_i32(&mut self, v: i32);
fn emit_i16(&mut self, v: i16);
fn emit_i8(&mut self, v: i8);
fn emit_bool(&mut self, v: bool);
fn emit_f64(&mut self, v: f64);
fn emit_f32(&mut self, v: f32);
fn emit_char(&mut self, v: char);
fn emit_str(&mut self, v: &str);
fn emit_nil(&mut self) -> Result<(), E>;
fn emit_uint(&mut self, v: uint) -> Result<(), E>;
fn emit_u64(&mut self, v: u64) -> Result<(), E>;
fn emit_u32(&mut self, v: u32) -> Result<(), E>;
fn emit_u16(&mut self, v: u16) -> Result<(), E>;
fn emit_u8(&mut self, v: u8) -> Result<(), E>;
fn emit_int(&mut self, v: int) -> Result<(), E>;
fn emit_i64(&mut self, v: i64) -> Result<(), E>;
fn emit_i32(&mut self, v: i32) -> Result<(), E>;
fn emit_i16(&mut self, v: i16) -> Result<(), E>;
fn emit_i8(&mut self, v: i8) -> Result<(), E>;
fn emit_bool(&mut self, v: bool) -> Result<(), E>;
fn emit_f64(&mut self, v: f64) -> Result<(), E>;
fn emit_f32(&mut self, v: f32) -> Result<(), E>;
fn emit_char(&mut self, v: char) -> Result<(), E>;
fn emit_str(&mut self, v: &str) -> Result<(), E>;
// Compound types:
fn emit_enum(&mut self, name: &str, f: |&mut Self|);
fn emit_enum(&mut self, name: &str, f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_enum_variant(&mut self,
v_name: &str,
v_id: uint,
len: uint,
f: |&mut Self|);
fn emit_enum_variant_arg(&mut self, a_idx: uint, f: |&mut Self|);
f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_enum_variant_arg(&mut self,
a_idx: uint,
f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_enum_struct_variant(&mut self,
v_name: &str,
v_id: uint,
len: uint,
f: |&mut Self|);
f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_enum_struct_variant_field(&mut self,
f_name: &str,
f_idx: uint,
f: |&mut Self|);
f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_struct(&mut self, name: &str, len: uint, f: |&mut Self|);
fn emit_struct(&mut self,
name: &str,
len: uint,
f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_struct_field(&mut self,
f_name: &str,
f_idx: uint,
f: |&mut Self|);
f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_tuple(&mut self, len: uint, f: |&mut Self|);
fn emit_tuple_arg(&mut self, idx: uint, f: |&mut Self|);
fn emit_tuple(&mut self, len: uint, f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_tuple_arg(&mut self, idx: uint, f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_tuple_struct(&mut self, name: &str, len: uint, f: |&mut Self|);
fn emit_tuple_struct_arg(&mut self, f_idx: uint, f: |&mut Self|);
fn emit_tuple_struct(&mut self,
name: &str,
len: uint,
f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_tuple_struct_arg(&mut self,
f_idx: uint,
f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
// Specialized types:
fn emit_option(&mut self, f: |&mut Self|);
fn emit_option_none(&mut self);
fn emit_option_some(&mut self, f: |&mut Self|);
fn emit_option(&mut self, f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_option_none(&mut self) -> Result<(), E>;
fn emit_option_some(&mut self, f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_seq(&mut self, len: uint, f: |this: &mut Self|);
fn emit_seq_elt(&mut self, idx: uint, f: |this: &mut Self|);
fn emit_seq(&mut self, len: uint, f: |this: &mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_seq_elt(&mut self, idx: uint, f: |this: &mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_map(&mut self, len: uint, f: |&mut Self|);
fn emit_map_elt_key(&mut self, idx: uint, f: |&mut Self|);
fn emit_map_elt_val(&mut self, idx: uint, f: |&mut Self|);
fn emit_map(&mut self, len: uint, f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_map_elt_key(&mut self, idx: uint, f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
fn emit_map_elt_val(&mut self, idx: uint, f: |&mut Self| -> Result<(), E>) -> Result<(), E>;
}
pub trait Decoder {
pub trait Decoder<E> {
// Primitive types:
fn read_nil(&mut self) -> ();
fn read_uint(&mut self) -> uint;
fn read_u64(&mut self) -> u64;
fn read_u32(&mut self) -> u32;
fn read_u16(&mut self) -> u16;
fn read_u8(&mut self) -> u8;
fn read_int(&mut self) -> int;
fn read_i64(&mut self) -> i64;
fn read_i32(&mut self) -> i32;
fn read_i16(&mut self) -> i16;
fn read_i8(&mut self) -> i8;
fn read_bool(&mut self) -> bool;
fn read_f64(&mut self) -> f64;
fn read_f32(&mut self) -> f32;
fn read_char(&mut self) -> char;
fn read_str(&mut self) -> ~str;
fn read_nil(&mut self) -> Result<(), E>;
fn read_uint(&mut self) -> Result<uint, E>;
fn read_u64(&mut self) -> Result<u64, E>;
fn read_u32(&mut self) -> Result<u32, E>;
fn read_u16(&mut self) -> Result<u16, E>;
fn read_u8(&mut self) -> Result<u8, E>;
fn read_int(&mut self) -> Result<int, E>;
fn read_i64(&mut self) -> Result<i64, E>;
fn read_i32(&mut self) -> Result<i32, E>;
fn read_i16(&mut self) -> Result<i16, E>;
fn read_i8(&mut self) -> Result<i8, E>;
fn read_bool(&mut self) -> Result<bool, E>;
fn read_f64(&mut self) -> Result<f64, E>;
fn read_f32(&mut self) -> Result<f32, E>;
fn read_char(&mut self) -> Result<char, E>;
fn read_str(&mut self) -> Result<~str, E>;
// Compound types:
fn read_enum<T>(&mut self, name: &str, f: |&mut Self| -> T) -> T;
fn read_enum<T>(&mut self, name: &str, f: |&mut Self| -> Result<T, E>) -> Result<T, E>;
fn read_enum_variant<T>(&mut self,
names: &[&str],
f: |&mut Self, uint| -> T)
-> T;
f: |&mut Self, uint| -> Result<T, E>)
-> Result<T, E>;
fn read_enum_variant_arg<T>(&mut self,
a_idx: uint,
f: |&mut Self| -> T)
-> T;
f: |&mut Self| -> Result<T, E>)
-> Result<T, E>;
fn read_enum_struct_variant<T>(&mut self,
names: &[&str],
f: |&mut Self, uint| -> T)
-> T;
f: |&mut Self, uint| -> Result<T, E>)
-> Result<T, E>;
fn read_enum_struct_variant_field<T>(&mut self,
&f_name: &str,
f_idx: uint,
f: |&mut Self| -> T)
-> T;
f: |&mut Self| -> Result<T, E>)
-> Result<T, E>;
fn read_struct<T>(&mut self, s_name: &str, len: uint, f: |&mut Self| -> T)
-> T;
fn read_struct<T>(&mut self, s_name: &str, len: uint, f: |&mut Self| -> Result<T, E>)
-> Result<T, E>;
fn read_struct_field<T>(&mut self,
f_name: &str,
f_idx: uint,
f: |&mut Self| -> T)
-> T;
f: |&mut Self| -> Result<T, E>)
-> Result<T, E>;
fn read_tuple<T>(&mut self, f: |&mut Self, uint| -> T) -> T;
fn read_tuple_arg<T>(&mut self, a_idx: uint, f: |&mut Self| -> T) -> T;
fn read_tuple<T>(&mut self, f: |&mut Self, uint| -> Result<T, E>) -> Result<T, E>;
fn read_tuple_arg<T>(&mut self, a_idx: uint, f: |&mut Self| -> Result<T, E>) -> Result<T, E>;
fn read_tuple_struct<T>(&mut self,
s_name: &str,
f: |&mut Self, uint| -> T)
-> T;
f: |&mut Self, uint| -> Result<T, E>)
-> Result<T, E>;
fn read_tuple_struct_arg<T>(&mut self,
a_idx: uint,
f: |&mut Self| -> T)
-> T;
f: |&mut Self| -> Result<T, E>)
-> Result<T, E>;
// Specialized types:
fn read_option<T>(&mut self, f: |&mut Self, bool| -> T) -> T;
fn read_option<T>(&mut self, f: |&mut Self, bool| -> Result<T, E>) -> Result<T, E>;
fn read_seq<T>(&mut self, f: |&mut Self, uint| -> T) -> T;
fn read_seq_elt<T>(&mut self, idx: uint, f: |&mut Self| -> T) -> T;
fn read_seq<T>(&mut self, f: |&mut Self, uint| -> Result<T, E>) -> Result<T, E>;
fn read_seq_elt<T>(&mut self, idx: uint, f: |&mut Self| -> Result<T, E>) -> Result<T, E>;
fn read_map<T>(&mut self, f: |&mut Self, uint| -> T) -> T;
fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Self| -> T) -> T;
fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Self| -> T) -> T;
fn read_map<T>(&mut self, f: |&mut Self, uint| -> Result<T, E>) -> Result<T, E>;
fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Self| -> Result<T, E>) -> Result<T, E>;
fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Self| -> Result<T, E>) -> Result<T, E>;
}
pub trait Encodable<S:Encoder> {
fn encode(&self, s: &mut S);
pub trait Encodable<S:Encoder<E>, E> {
fn encode(&self, s: &mut S) -> Result<(), E>;
}
pub trait Decodable<D:Decoder> {
fn decode(d: &mut D) -> Self;
pub trait Decodable<D:Decoder<E>, E> {
fn decode(d: &mut D) -> Result<Self, E>;
}
impl<S:Encoder> Encodable<S> for uint {
fn encode(&self, s: &mut S) {
macro_rules! try ( ($e:expr) => (
match $e { Ok(v) => v, Err(e) => return Err(e) }
))
impl<E, S:Encoder<E>> Encodable<S, E> for uint {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_uint(*self)
}
}
impl<D:Decoder> Decodable<D> for uint {
fn decode(d: &mut D) -> uint {
impl<E, D:Decoder<E>> Decodable<D, E> for uint {
fn decode(d: &mut D) -> Result<uint, E> {
d.read_uint()
}
}
impl<S:Encoder> Encodable<S> for u8 {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for u8 {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_u8(*self)
}
}
impl<D:Decoder> Decodable<D> for u8 {
fn decode(d: &mut D) -> u8 {
impl<E, D:Decoder<E>> Decodable<D, E> for u8 {
fn decode(d: &mut D) -> Result<u8, E> {
d.read_u8()
}
}
impl<S:Encoder> Encodable<S> for u16 {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for u16 {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_u16(*self)
}
}
impl<D:Decoder> Decodable<D> for u16 {
fn decode(d: &mut D) -> u16 {
impl<E, D:Decoder<E>> Decodable<D, E> for u16 {
fn decode(d: &mut D) -> Result<u16, E> {
d.read_u16()
}
}
impl<S:Encoder> Encodable<S> for u32 {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for u32 {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_u32(*self)
}
}
impl<D:Decoder> Decodable<D> for u32 {
fn decode(d: &mut D) -> u32 {
impl<E, D:Decoder<E>> Decodable<D, E> for u32 {
fn decode(d: &mut D) -> Result<u32, E> {
d.read_u32()
}
}
impl<S:Encoder> Encodable<S> for u64 {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for u64 {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_u64(*self)
}
}
impl<D:Decoder> Decodable<D> for u64 {
fn decode(d: &mut D) -> u64 {
impl<E, D:Decoder<E>> Decodable<D, E> for u64 {
fn decode(d: &mut D) -> Result<u64, E> {
d.read_u64()
}
}
impl<S:Encoder> Encodable<S> for int {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for int {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_int(*self)
}
}
impl<D:Decoder> Decodable<D> for int {
fn decode(d: &mut D) -> int {
impl<E, D:Decoder<E>> Decodable<D, E> for int {
fn decode(d: &mut D) -> Result<int, E> {
d.read_int()
}
}
impl<S:Encoder> Encodable<S> for i8 {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for i8 {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_i8(*self)
}
}
impl<D:Decoder> Decodable<D> for i8 {
fn decode(d: &mut D) -> i8 {
impl<E, D:Decoder<E>> Decodable<D, E> for i8 {
fn decode(d: &mut D) -> Result<i8, E> {
d.read_i8()
}
}
impl<S:Encoder> Encodable<S> for i16 {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for i16 {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_i16(*self)
}
}
impl<D:Decoder> Decodable<D> for i16 {
fn decode(d: &mut D) -> i16 {
impl<E, D:Decoder<E>> Decodable<D, E> for i16 {
fn decode(d: &mut D) -> Result<i16, E> {
d.read_i16()
}
}
impl<S:Encoder> Encodable<S> for i32 {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for i32 {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_i32(*self)
}
}
impl<D:Decoder> Decodable<D> for i32 {
fn decode(d: &mut D) -> i32 {
impl<E, D:Decoder<E>> Decodable<D, E> for i32 {
fn decode(d: &mut D) -> Result<i32, E> {
d.read_i32()
}
}
impl<S:Encoder> Encodable<S> for i64 {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for i64 {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_i64(*self)
}
}
impl<D:Decoder> Decodable<D> for i64 {
fn decode(d: &mut D) -> i64 {
impl<E, D:Decoder<E>> Decodable<D, E> for i64 {
fn decode(d: &mut D) -> Result<i64, E> {
d.read_i64()
}
}
impl<'a, S:Encoder> Encodable<S> for &'a str {
fn encode(&self, s: &mut S) {
impl<'a, E, S:Encoder<E>> Encodable<S, E> for &'a str {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_str(*self)
}
}
impl<S:Encoder> Encodable<S> for ~str {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for ~str {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_str(*self)
}
}
impl<D:Decoder> Decodable<D> for ~str {
fn decode(d: &mut D) -> ~str {
impl<E, D:Decoder<E>> Decodable<D, E> for ~str {
fn decode(d: &mut D) -> Result<~str, E> {
d.read_str()
}
}
impl<S:Encoder> Encodable<S> for f32 {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for f32 {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_f32(*self)
}
}
impl<D:Decoder> Decodable<D> for f32 {
fn decode(d: &mut D) -> f32 {
impl<E, D:Decoder<E>> Decodable<D, E> for f32 {
fn decode(d: &mut D) -> Result<f32, E> {
d.read_f32()
}
}
impl<S:Encoder> Encodable<S> for f64 {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for f64 {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_f64(*self)
}
}
impl<D:Decoder> Decodable<D> for f64 {
fn decode(d: &mut D) -> f64 {
impl<E, D:Decoder<E>> Decodable<D, E> for f64 {
fn decode(d: &mut D) -> Result<f64, E> {
d.read_f64()
}
}
impl<S:Encoder> Encodable<S> for bool {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for bool {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_bool(*self)
}
}
impl<D:Decoder> Decodable<D> for bool {
fn decode(d: &mut D) -> bool {
impl<E, D:Decoder<E>> Decodable<D, E> for bool {
fn decode(d: &mut D) -> Result<bool, E> {
d.read_bool()
}
}
impl<S:Encoder> Encodable<S> for char {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for char {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_char(*self)
}
}
impl<D:Decoder> Decodable<D> for char {
fn decode(d: &mut D) -> char {
impl<E, D:Decoder<E>> Decodable<D, E> for char {
fn decode(d: &mut D) -> Result<char, E> {
d.read_char()
}
}
impl<S:Encoder> Encodable<S> for () {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>> Encodable<S, E> for () {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_nil()
}
}
impl<D:Decoder> Decodable<D> for () {
fn decode(d: &mut D) -> () {
impl<E, D:Decoder<E>> Decodable<D, E> for () {
fn decode(d: &mut D) -> Result<(), E> {
d.read_nil()
}
}
impl<'a, S:Encoder,T:Encodable<S>> Encodable<S> for &'a T {
fn encode(&self, s: &mut S) {
impl<'a, E, S:Encoder<E>,T:Encodable<S, E>> Encodable<S, E> for &'a T {
fn encode(&self, s: &mut S) -> Result<(), E> {
(**self).encode(s)
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for ~T {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>,T:Encodable<S, E>> Encodable<S, E> for ~T {
fn encode(&self, s: &mut S) -> Result<(), E> {
(**self).encode(s)
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for ~T {
fn decode(d: &mut D) -> ~T {
~Decodable::decode(d)
impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for ~T {
fn decode(d: &mut D) -> Result<~T, E> {
Ok(~try!(Decodable::decode(d)))
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for @T {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>,T:Encodable<S, E>> Encodable<S, E> for @T {
fn encode(&self, s: &mut S) -> Result<(), E> {
(**self).encode(s)
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for Rc<T> {
impl<E, S:Encoder<E>,T:Encodable<S, E>> Encodable<S, E> for Rc<T> {
#[inline]
fn encode(&self, s: &mut S) {
fn encode(&self, s: &mut S) -> Result<(), E> {
(**self).encode(s)
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for Rc<T> {
impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for Rc<T> {
#[inline]
fn decode(d: &mut D) -> Rc<T> {
Rc::new(Decodable::decode(d))
fn decode(d: &mut D) -> Result<Rc<T>, E> {
Ok(Rc::new(try!(Decodable::decode(d))))
}
}
impl<D:Decoder,T:Decodable<D> + 'static> Decodable<D> for @T {
fn decode(d: &mut D) -> @T {
@Decodable::decode(d)
impl<E, D:Decoder<E>,T:Decodable<D, E> + 'static> Decodable<D, E> for @T {
fn decode(d: &mut D) -> Result<@T, E> {
Ok(@try!(Decodable::decode(d)))
}
}
impl<'a, S:Encoder,T:Encodable<S>> Encodable<S> for &'a [T] {
fn encode(&self, s: &mut S) {
impl<'a, E, S:Encoder<E>,T:Encodable<S, E>> Encodable<S, E> for &'a [T] {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s))
try!(s.emit_seq_elt(i, |s| e.encode(s)))
}
Ok(())
})
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for ~[T] {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>,T:Encodable<S, E>> Encodable<S, E> for ~[T] {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s))
try!(s.emit_seq_elt(i, |s| e.encode(s)))
}
Ok(())
})
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for ~[T] {
fn decode(d: &mut D) -> ~[T] {
impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for ~[T] {
fn decode(d: &mut D) -> Result<~[T], E> {
d.read_seq(|d, len| {
slice::from_fn(len, |i| {
d.read_seq_elt(i, |d| Decodable::decode(d))
})
let mut v: ~[T] = slice::with_capacity(len);
for i in range(0, len) {
v.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
}
Ok(v)
})
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for Vec<T> {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>,T:Encodable<S, E>> Encodable<S, E> for Vec<T> {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s))
try!(s.emit_seq_elt(i, |s| e.encode(s)))
}
Ok(())
})
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for Vec<T> {
fn decode(d: &mut D) -> Vec<T> {
impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for Vec<T> {
fn decode(d: &mut D) -> Result<Vec<T>, E> {
d.read_seq(|d, len| {
Vec::from_fn(len, |i| {
d.read_seq_elt(i, |d| Decodable::decode(d))
})
let mut v = Vec::with_capacity(len);
for i in range(0, len) {
v.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
}
Ok(v)
})
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for Option<T> {
fn encode(&self, s: &mut S) {
impl<E, S:Encoder<E>,T:Encodable<S, E>> Encodable<S, E> for Option<T> {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_option(|s| {
match *self {
None => s.emit_option_none(),
@ -465,13 +486,13 @@ fn encode(&self, s: &mut S) {
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for Option<T> {
fn decode(d: &mut D) -> Option<T> {
impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for Option<T> {
fn decode(d: &mut D) -> Result<Option<T>, E> {
d.read_option(|d, b| {
if b {
Some(Decodable::decode(d))
Ok(Some(try!(Decodable::decode(d))))
} else {
None
Ok(None)
}
})
}
@ -482,30 +503,31 @@ macro_rules! peel(($name:ident, $($other:ident,)*) => (tuple!($($other,)*)))
macro_rules! tuple (
() => ();
( $($name:ident,)+ ) => (
impl<D:Decoder,$($name:Decodable<D>),*> Decodable<D> for ($($name,)*) {
impl<E, D:Decoder<E>,$($name:Decodable<D, E>),*> Decodable<D,E> for ($($name,)*) {
#[allow(uppercase_variables)]
fn decode(d: &mut D) -> ($($name,)*) {
fn decode(d: &mut D) -> Result<($($name,)*), E> {
d.read_tuple(|d, amt| {
let mut i = 0;
let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> $name {
let ret = ($(try!(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name,E> {
Decodable::decode(d)
}),)*);
})),)*);
assert!(amt == i,
"expected tuple of length `{}`, found tuple \
of length `{}`", i, amt);
return ret;
return Ok(ret);
})
}
}
impl<S:Encoder,$($name:Encodable<S>),*> Encodable<S> for ($($name,)*) {
impl<E, S:Encoder<E>,$($name:Encodable<S, E>),*> Encodable<S, E> for ($($name,)*) {
#[allow(uppercase_variables)]
fn encode(&self, s: &mut S) {
fn encode(&self, s: &mut S) -> Result<(), E> {
let ($(ref $name,)*) = *self;
let mut n = 0;
$(let $name = $name; n += 1;)*
s.emit_tuple(n, |s| {
let mut i = 0;
$(s.emit_seq_elt({ i+=1; i-1 }, |s| $name.encode(s));)*
$(try!(s.emit_seq_elt({ i+=1; i-1 }, |s| $name.encode(s)));)*
Ok(())
})
}
}
@ -515,29 +537,29 @@ fn encode(&self, s: &mut S) {
tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
impl<E: Encoder> Encodable<E> for path::posix::Path {
fn encode(&self, e: &mut E) {
impl<E, S: Encoder<E>> Encodable<S, E> for path::posix::Path {
fn encode(&self, e: &mut S) -> Result<(), E> {
self.as_vec().encode(e)
}
}
impl<D: Decoder> Decodable<D> for path::posix::Path {
fn decode(d: &mut D) -> path::posix::Path {
let bytes: ~[u8] = Decodable::decode(d);
path::posix::Path::new(bytes)
impl<E, D: Decoder<E>> Decodable<D, E> for path::posix::Path {
fn decode(d: &mut D) -> Result<path::posix::Path, E> {
let bytes: ~[u8] = try!(Decodable::decode(d));
Ok(path::posix::Path::new(bytes))
}
}
impl<E: Encoder> Encodable<E> for path::windows::Path {
fn encode(&self, e: &mut E) {
impl<E, S: Encoder<E>> Encodable<S, E> for path::windows::Path {
fn encode(&self, e: &mut S) -> Result<(), E> {
self.as_vec().encode(e)
}
}
impl<D: Decoder> Decodable<D> for path::windows::Path {
fn decode(d: &mut D) -> path::windows::Path {
let bytes: ~[u8] = Decodable::decode(d);
path::windows::Path::new(bytes)
impl<E, D: Decoder<E>> Decodable<D, E> for path::windows::Path {
fn decode(d: &mut D) -> Result<path::windows::Path, E> {
let bytes: ~[u8] = try!(Decodable::decode(d));
Ok(path::windows::Path::new(bytes))
}
}
@ -546,32 +568,37 @@ fn decode(d: &mut D) -> path::windows::Path {
//
// In some cases, these should eventually be coded as traits.
pub trait EncoderHelpers {
fn emit_from_vec<T>(&mut self, v: &[T], f: |&mut Self, v: &T|);
pub trait EncoderHelpers<E> {
fn emit_from_vec<T>(&mut self,
v: &[T],
f: |&mut Self, v: &T| -> Result<(), E>) -> Result<(), E>;
}
impl<S:Encoder> EncoderHelpers for S {
fn emit_from_vec<T>(&mut self, v: &[T], f: |&mut S, &T|) {
impl<E, S:Encoder<E>> EncoderHelpers<E> for S {
fn emit_from_vec<T>(&mut self, v: &[T], f: |&mut S, &T| -> Result<(), E>) -> Result<(), E> {
self.emit_seq(v.len(), |this| {
for (i, e) in v.iter().enumerate() {
this.emit_seq_elt(i, |this| {
try!(this.emit_seq_elt(i, |this| {
f(this, e)
})
}));
}
Ok(())
})
}
}
pub trait DecoderHelpers {
fn read_to_vec<T>(&mut self, f: |&mut Self| -> T) -> ~[T];
pub trait DecoderHelpers<E> {
fn read_to_vec<T>(&mut self, f: |&mut Self| -> Result<T, E>) -> Result<~[T], E>;
}
impl<D:Decoder> DecoderHelpers for D {
fn read_to_vec<T>(&mut self, f: |&mut D| -> T) -> ~[T] {
impl<E, D:Decoder<E>> DecoderHelpers<E> for D {
fn read_to_vec<T>(&mut self, f: |&mut D| -> Result<T, E>) -> Result<~[T], E> {
self.read_seq(|this, len| {
slice::from_fn(len, |i| {
this.read_seq_elt(i, |this| f(this))
})
let mut v = slice::with_capacity(len);
for i in range(0, len) {
v.push(try!(this.read_seq_elt(i, |this| f(this))));
}
Ok(v)
})
}
}

View file

@ -0,0 +1,688 @@
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Support code for encoding and decoding types.
/*
Core encoding and decoding interfaces.
*/
use std::path;
use std::rc::Rc;
use std::slice;
pub trait Encoder {
// Primitive types:
fn emit_nil(&mut self);
fn emit_uint(&mut self, v: uint);
fn emit_u64(&mut self, v: u64);
fn emit_u32(&mut self, v: u32);
fn emit_u16(&mut self, v: u16);
fn emit_u8(&mut self, v: u8);
fn emit_int(&mut self, v: int);
fn emit_i64(&mut self, v: i64);
fn emit_i32(&mut self, v: i32);
fn emit_i16(&mut self, v: i16);
fn emit_i8(&mut self, v: i8);
fn emit_bool(&mut self, v: bool);
fn emit_f64(&mut self, v: f64);
fn emit_f32(&mut self, v: f32);
fn emit_char(&mut self, v: char);
fn emit_str(&mut self, v: &str);
// Compound types:
fn emit_enum(&mut self, name: &str, f: |&mut Self|);
fn emit_enum_variant(&mut self,
v_name: &str,
v_id: uint,
len: uint,
f: |&mut Self|);
fn emit_enum_variant_arg(&mut self, a_idx: uint, f: |&mut Self|);
fn emit_enum_struct_variant(&mut self,
v_name: &str,
v_id: uint,
len: uint,
f: |&mut Self|);
fn emit_enum_struct_variant_field(&mut self,
f_name: &str,
f_idx: uint,
f: |&mut Self|);
fn emit_struct(&mut self, name: &str, len: uint, f: |&mut Self|);
fn emit_struct_field(&mut self,
f_name: &str,
f_idx: uint,
f: |&mut Self|);
fn emit_tuple(&mut self, len: uint, f: |&mut Self|);
fn emit_tuple_arg(&mut self, idx: uint, f: |&mut Self|);
fn emit_tuple_struct(&mut self, name: &str, len: uint, f: |&mut Self|);
fn emit_tuple_struct_arg(&mut self, f_idx: uint, f: |&mut Self|);
// Specialized types:
fn emit_option(&mut self, f: |&mut Self|);
fn emit_option_none(&mut self);
fn emit_option_some(&mut self, f: |&mut Self|);
fn emit_seq(&mut self, len: uint, f: |this: &mut Self|);
fn emit_seq_elt(&mut self, idx: uint, f: |this: &mut Self|);
fn emit_map(&mut self, len: uint, f: |&mut Self|);
fn emit_map_elt_key(&mut self, idx: uint, f: |&mut Self|);
fn emit_map_elt_val(&mut self, idx: uint, f: |&mut Self|);
}
pub trait Decoder {
// Primitive types:
fn read_nil(&mut self) -> ();
fn read_uint(&mut self) -> uint;
fn read_u64(&mut self) -> u64;
fn read_u32(&mut self) -> u32;
fn read_u16(&mut self) -> u16;
fn read_u8(&mut self) -> u8;
fn read_int(&mut self) -> int;
fn read_i64(&mut self) -> i64;
fn read_i32(&mut self) -> i32;
fn read_i16(&mut self) -> i16;
fn read_i8(&mut self) -> i8;
fn read_bool(&mut self) -> bool;
fn read_f64(&mut self) -> f64;
fn read_f32(&mut self) -> f32;
fn read_char(&mut self) -> char;
fn read_str(&mut self) -> ~str;
// Compound types:
fn read_enum<T>(&mut self, name: &str, f: |&mut Self| -> T) -> T;
fn read_enum_variant<T>(&mut self,
names: &[&str],
f: |&mut Self, uint| -> T)
-> T;
fn read_enum_variant_arg<T>(&mut self,
a_idx: uint,
f: |&mut Self| -> T)
-> T;
fn read_enum_struct_variant<T>(&mut self,
names: &[&str],
f: |&mut Self, uint| -> T)
-> T;
fn read_enum_struct_variant_field<T>(&mut self,
&f_name: &str,
f_idx: uint,
f: |&mut Self| -> T)
-> T;
fn read_struct<T>(&mut self, s_name: &str, len: uint, f: |&mut Self| -> T)
-> T;
fn read_struct_field<T>(&mut self,
f_name: &str,
f_idx: uint,
f: |&mut Self| -> T)
-> T;
fn read_tuple<T>(&mut self, f: |&mut Self, uint| -> T) -> T;
fn read_tuple_arg<T>(&mut self, a_idx: uint, f: |&mut Self| -> T) -> T;
fn read_tuple_struct<T>(&mut self,
s_name: &str,
f: |&mut Self, uint| -> T)
-> T;
fn read_tuple_struct_arg<T>(&mut self,
a_idx: uint,
f: |&mut Self| -> T)
-> T;
// Specialized types:
fn read_option<T>(&mut self, f: |&mut Self, bool| -> T) -> T;
fn read_seq<T>(&mut self, f: |&mut Self, uint| -> T) -> T;
fn read_seq_elt<T>(&mut self, idx: uint, f: |&mut Self| -> T) -> T;
fn read_map<T>(&mut self, f: |&mut Self, uint| -> T) -> T;
fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Self| -> T) -> T;
fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Self| -> T) -> T;
}
pub trait Encodable<S:Encoder> {
fn encode(&self, s: &mut S);
}
pub trait Decodable<D:Decoder> {
fn decode(d: &mut D) -> Self;
}
impl<S:Encoder> Encodable<S> for uint {
fn encode(&self, s: &mut S) {
s.emit_uint(*self)
}
}
impl<D:Decoder> Decodable<D> for uint {
fn decode(d: &mut D) -> uint {
d.read_uint()
}
}
impl<S:Encoder> Encodable<S> for u8 {
fn encode(&self, s: &mut S) {
s.emit_u8(*self)
}
}
impl<D:Decoder> Decodable<D> for u8 {
fn decode(d: &mut D) -> u8 {
d.read_u8()
}
}
impl<S:Encoder> Encodable<S> for u16 {
fn encode(&self, s: &mut S) {
s.emit_u16(*self)
}
}
impl<D:Decoder> Decodable<D> for u16 {
fn decode(d: &mut D) -> u16 {
d.read_u16()
}
}
impl<S:Encoder> Encodable<S> for u32 {
fn encode(&self, s: &mut S) {
s.emit_u32(*self)
}
}
impl<D:Decoder> Decodable<D> for u32 {
fn decode(d: &mut D) -> u32 {
d.read_u32()
}
}
impl<S:Encoder> Encodable<S> for u64 {
fn encode(&self, s: &mut S) {
s.emit_u64(*self)
}
}
impl<D:Decoder> Decodable<D> for u64 {
fn decode(d: &mut D) -> u64 {
d.read_u64()
}
}
impl<S:Encoder> Encodable<S> for int {
fn encode(&self, s: &mut S) {
s.emit_int(*self)
}
}
impl<D:Decoder> Decodable<D> for int {
fn decode(d: &mut D) -> int {
d.read_int()
}
}
impl<S:Encoder> Encodable<S> for i8 {
fn encode(&self, s: &mut S) {
s.emit_i8(*self)
}
}
impl<D:Decoder> Decodable<D> for i8 {
fn decode(d: &mut D) -> i8 {
d.read_i8()
}
}
impl<S:Encoder> Encodable<S> for i16 {
fn encode(&self, s: &mut S) {
s.emit_i16(*self)
}
}
impl<D:Decoder> Decodable<D> for i16 {
fn decode(d: &mut D) -> i16 {
d.read_i16()
}
}
impl<S:Encoder> Encodable<S> for i32 {
fn encode(&self, s: &mut S) {
s.emit_i32(*self)
}
}
impl<D:Decoder> Decodable<D> for i32 {
fn decode(d: &mut D) -> i32 {
d.read_i32()
}
}
impl<S:Encoder> Encodable<S> for i64 {
fn encode(&self, s: &mut S) {
s.emit_i64(*self)
}
}
impl<D:Decoder> Decodable<D> for i64 {
fn decode(d: &mut D) -> i64 {
d.read_i64()
}
}
impl<'a, S:Encoder> Encodable<S> for &'a str {
fn encode(&self, s: &mut S) {
s.emit_str(*self)
}
}
impl<S:Encoder> Encodable<S> for ~str {
fn encode(&self, s: &mut S) {
s.emit_str(*self)
}
}
impl<D:Decoder> Decodable<D> for ~str {
fn decode(d: &mut D) -> ~str {
d.read_str()
}
}
impl<S:Encoder> Encodable<S> for f32 {
fn encode(&self, s: &mut S) {
s.emit_f32(*self)
}
}
impl<D:Decoder> Decodable<D> for f32 {
fn decode(d: &mut D) -> f32 {
d.read_f32()
}
}
impl<S:Encoder> Encodable<S> for f64 {
fn encode(&self, s: &mut S) {
s.emit_f64(*self)
}
}
impl<D:Decoder> Decodable<D> for f64 {
fn decode(d: &mut D) -> f64 {
d.read_f64()
}
}
impl<S:Encoder> Encodable<S> for bool {
fn encode(&self, s: &mut S) {
s.emit_bool(*self)
}
}
impl<D:Decoder> Decodable<D> for bool {
fn decode(d: &mut D) -> bool {
d.read_bool()
}
}
impl<S:Encoder> Encodable<S> for char {
fn encode(&self, s: &mut S) {
s.emit_char(*self)
}
}
impl<D:Decoder> Decodable<D> for char {
fn decode(d: &mut D) -> char {
d.read_char()
}
}
impl<S:Encoder> Encodable<S> for () {
fn encode(&self, s: &mut S) {
s.emit_nil()
}
}
impl<D:Decoder> Decodable<D> for () {
fn decode(d: &mut D) -> () {
d.read_nil()
}
}
impl<'a, S:Encoder,T:Encodable<S>> Encodable<S> for &'a T {
fn encode(&self, s: &mut S) {
(**self).encode(s)
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for ~T {
fn encode(&self, s: &mut S) {
(**self).encode(s)
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for ~T {
fn decode(d: &mut D) -> ~T {
~Decodable::decode(d)
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for @T {
fn encode(&self, s: &mut S) {
(**self).encode(s)
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for Rc<T> {
#[inline]
fn encode(&self, s: &mut S) {
(**self).encode(s)
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for Rc<T> {
#[inline]
fn decode(d: &mut D) -> Rc<T> {
Rc::new(Decodable::decode(d))
}
}
impl<D:Decoder,T:Decodable<D> + 'static> Decodable<D> for @T {
fn decode(d: &mut D) -> @T {
@Decodable::decode(d)
}
}
impl<'a, S:Encoder,T:Encodable<S>> Encodable<S> for &'a [T] {
fn encode(&self, s: &mut S) {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s))
}
})
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for ~[T] {
fn encode(&self, s: &mut S) {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s))
}
})
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for ~[T] {
fn decode(d: &mut D) -> ~[T] {
d.read_seq(|d, len| {
slice::from_fn(len, |i| {
d.read_seq_elt(i, |d| Decodable::decode(d))
})
})
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for Vec<T> {
fn encode(&self, s: &mut S) {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s))
}
})
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for Vec<T> {
fn decode(d: &mut D) -> Vec<T> {
d.read_seq(|d, len| {
Vec::from_fn(len, |i| {
d.read_seq_elt(i, |d| Decodable::decode(d))
})
})
}
}
impl<S:Encoder,T:Encodable<S>> Encodable<S> for Option<T> {
fn encode(&self, s: &mut S) {
s.emit_option(|s| {
match *self {
None => s.emit_option_none(),
Some(ref v) => s.emit_option_some(|s| v.encode(s)),
}
})
}
}
impl<D:Decoder,T:Decodable<D>> Decodable<D> for Option<T> {
fn decode(d: &mut D) -> Option<T> {
d.read_option(|d, b| {
if b {
Some(Decodable::decode(d))
} else {
None
}
})
}
}
impl<S:Encoder,T0:Encodable<S>,T1:Encodable<S>> Encodable<S> for (T0, T1) {
fn encode(&self, s: &mut S) {
match *self {
(ref t0, ref t1) => {
s.emit_seq(2, |s| {
s.emit_seq_elt(0, |s| t0.encode(s));
s.emit_seq_elt(1, |s| t1.encode(s));
})
}
}
}
}
impl<D:Decoder,T0:Decodable<D>,T1:Decodable<D>> Decodable<D> for (T0, T1) {
fn decode(d: &mut D) -> (T0, T1) {
d.read_seq(|d, len| {
assert_eq!(len, 2);
(
d.read_seq_elt(0, |d| Decodable::decode(d)),
d.read_seq_elt(1, |d| Decodable::decode(d))
)
})
}
}
impl<
S: Encoder,
T0: Encodable<S>,
T1: Encodable<S>,
T2: Encodable<S>
> Encodable<S> for (T0, T1, T2) {
fn encode(&self, s: &mut S) {
match *self {
(ref t0, ref t1, ref t2) => {
s.emit_seq(3, |s| {
s.emit_seq_elt(0, |s| t0.encode(s));
s.emit_seq_elt(1, |s| t1.encode(s));
s.emit_seq_elt(2, |s| t2.encode(s));
})
}
}
}
}
impl<
D: Decoder,
T0: Decodable<D>,
T1: Decodable<D>,
T2: Decodable<D>
> Decodable<D> for (T0, T1, T2) {
fn decode(d: &mut D) -> (T0, T1, T2) {
d.read_seq(|d, len| {
assert_eq!(len, 3);
(
d.read_seq_elt(0, |d| Decodable::decode(d)),
d.read_seq_elt(1, |d| Decodable::decode(d)),
d.read_seq_elt(2, |d| Decodable::decode(d))
)
})
}
}
impl<
S: Encoder,
T0: Encodable<S>,
T1: Encodable<S>,
T2: Encodable<S>,
T3: Encodable<S>
> Encodable<S> for (T0, T1, T2, T3) {
fn encode(&self, s: &mut S) {
match *self {
(ref t0, ref t1, ref t2, ref t3) => {
s.emit_seq(4, |s| {
s.emit_seq_elt(0, |s| t0.encode(s));
s.emit_seq_elt(1, |s| t1.encode(s));
s.emit_seq_elt(2, |s| t2.encode(s));
s.emit_seq_elt(3, |s| t3.encode(s));
})
}
}
}
}
impl<
D: Decoder,
T0: Decodable<D>,
T1: Decodable<D>,
T2: Decodable<D>,
T3: Decodable<D>
> Decodable<D> for (T0, T1, T2, T3) {
fn decode(d: &mut D) -> (T0, T1, T2, T3) {
d.read_seq(|d, len| {
assert_eq!(len, 4);
(
d.read_seq_elt(0, |d| Decodable::decode(d)),
d.read_seq_elt(1, |d| Decodable::decode(d)),
d.read_seq_elt(2, |d| Decodable::decode(d)),
d.read_seq_elt(3, |d| Decodable::decode(d))
)
})
}
}
impl<
S: Encoder,
T0: Encodable<S>,
T1: Encodable<S>,
T2: Encodable<S>,
T3: Encodable<S>,
T4: Encodable<S>
> Encodable<S> for (T0, T1, T2, T3, T4) {
fn encode(&self, s: &mut S) {
match *self {
(ref t0, ref t1, ref t2, ref t3, ref t4) => {
s.emit_seq(5, |s| {
s.emit_seq_elt(0, |s| t0.encode(s));
s.emit_seq_elt(1, |s| t1.encode(s));
s.emit_seq_elt(2, |s| t2.encode(s));
s.emit_seq_elt(3, |s| t3.encode(s));
s.emit_seq_elt(4, |s| t4.encode(s));
})
}
}
}
}
impl<
D: Decoder,
T0: Decodable<D>,
T1: Decodable<D>,
T2: Decodable<D>,
T3: Decodable<D>,
T4: Decodable<D>
> Decodable<D> for (T0, T1, T2, T3, T4) {
fn decode(d: &mut D) -> (T0, T1, T2, T3, T4) {
d.read_seq(|d, len| {
assert_eq!(len, 5);
(
d.read_seq_elt(0, |d| Decodable::decode(d)),
d.read_seq_elt(1, |d| Decodable::decode(d)),
d.read_seq_elt(2, |d| Decodable::decode(d)),
d.read_seq_elt(3, |d| Decodable::decode(d)),
d.read_seq_elt(4, |d| Decodable::decode(d))
)
})
}
}
impl<E: Encoder> Encodable<E> for path::posix::Path {
fn encode(&self, e: &mut E) {
self.as_vec().encode(e)
}
}
impl<D: Decoder> Decodable<D> for path::posix::Path {
fn decode(d: &mut D) -> path::posix::Path {
let bytes: ~[u8] = Decodable::decode(d);
path::posix::Path::new(bytes)
}
}
impl<E: Encoder> Encodable<E> for path::windows::Path {
fn encode(&self, e: &mut E) {
self.as_vec().encode(e)
}
}
impl<D: Decoder> Decodable<D> for path::windows::Path {
fn decode(d: &mut D) -> path::windows::Path {
let bytes: ~[u8] = Decodable::decode(d);
path::windows::Path::new(bytes)
}
}
// ___________________________________________________________________________
// Helper routines
//
// In some cases, these should eventually be coded as traits.
pub trait EncoderHelpers {
fn emit_from_vec<T>(&mut self, v: &[T], f: |&mut Self, v: &T|);
}
impl<S:Encoder> EncoderHelpers for S {
fn emit_from_vec<T>(&mut self, v: &[T], f: |&mut S, &T|) {
self.emit_seq(v.len(), |this| {
for (i, e) in v.iter().enumerate() {
this.emit_seq_elt(i, |this| {
f(this, e)
})
}
})
}
}
pub trait DecoderHelpers {
fn read_to_vec<T>(&mut self, f: |&mut Self| -> T) -> ~[T];
}
impl<D:Decoder> DecoderHelpers for D {
fn read_to_vec<T>(&mut self, f: |&mut D| -> T) -> ~[T] {
self.read_seq(|this, len| {
slice::from_fn(len, |i| {
this.read_seq_elt(i, |this| f(this))
})
})
}
}

View file

@ -98,18 +98,35 @@ fn ne(&self, other: &Ident) -> bool {
/// A mark represents a unique id associated with a macro expansion
pub type Mrk = u32;
// FIXME: remove stage0 Encodables after snapshot
#[cfg(stage0)]
impl<S: Encoder> Encodable<S> for Ident {
fn encode(&self, s: &mut S) {
s.emit_str(token::get_ident(*self).get());
}
}
#[cfg(stage0)]
impl<D:Decoder> Decodable<D> for Ident {
fn decode(d: &mut D) -> Ident {
str_to_ident(d.read_str())
}
}
#[cfg(not(stage0))]
impl<S: Encoder<E>, E> Encodable<S, E> for Ident {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_str(token::get_ident(*self).get())
}
}
#[cfg(not(stage0))]
impl<D:Decoder<E>, E> Decodable<D, E> for Ident {
fn decode(d: &mut D) -> Result<Ident, E> {
Ok(str_to_ident(try!(d.read_str())))
}
}
/// Function name (not all functions have names)
pub type FnIdent = Option<Ident>;
@ -1166,7 +1183,9 @@ mod test {
use super::*;
// are ASTs encodable?
// FIXME: remove stage0 test after snapshot
#[test]
#[cfg(stage0)]
fn check_asts_encodable() {
let e = Crate {
module: Mod {view_items: Vec::new(), items: Vec::new()},
@ -1181,4 +1200,22 @@ fn check_asts_encodable() {
// doesn't matter which encoder we use....
let _f = &e as &serialize::Encodable<json::Encoder>;
}
#[test]
#[cfg(not(stage0))]
fn check_asts_encodable() {
use std::io;
let e = Crate {
module: Mod {view_items: Vec::new(), items: Vec::new()},
attrs: Vec::new(),
config: Vec::new(),
span: Span {
lo: BytePos(10),
hi: BytePos(20),
expn_info: None,
},
};
// doesn't matter which encoder we use....
let _f = &e as &serialize::Encodable<json::Encoder, io::IoError>;
}
}

View file

@ -110,6 +110,8 @@ fn ne(&self, other: &Span) -> bool { !(*self).eq(other) }
impl TotalEq for Span {}
// FIXME: remove stage0 Encodables/Decodables after snapshot
#[cfg(stage0)]
impl<S:Encoder> Encodable<S> for Span {
/* Note #1972 -- spans are encoded but not decoded */
fn encode(&self, s: &mut S) {
@ -117,12 +119,28 @@ fn encode(&self, s: &mut S) {
}
}
#[cfg(stage0)]
impl<D:Decoder> Decodable<D> for Span {
fn decode(_d: &mut D) -> Span {
DUMMY_SP
}
}
#[cfg(not(stage0))]
impl<S:Encoder<E>, E> Encodable<S, E> for Span {
/* Note #1972 -- spans are encoded but not decoded */
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_nil()
}
}
#[cfg(not(stage0))]
impl<D:Decoder<E>, E> Decodable<D, E> for Span {
fn decode(_d: &mut D) -> Result<Span, E> {
Ok(DUMMY_SP)
}
}
pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
respan(mk_sp(lo, hi), t)
}

View file

@ -142,6 +142,10 @@ fn expr_method_call(&self, span: Span,
fn expr_fail(&self, span: Span, msg: InternedString) -> @ast::Expr;
fn expr_unreachable(&self, span: Span) -> @ast::Expr;
fn expr_ok(&self, span: Span, expr: @ast::Expr) -> @ast::Expr;
fn expr_err(&self, span: Span, expr: @ast::Expr) -> @ast::Expr;
fn expr_try(&self, span: Span, head: @ast::Expr) -> @ast::Expr;
fn pat(&self, span: Span, pat: ast::Pat_) -> @ast::Pat;
fn pat_wild(&self, span: Span) -> @ast::Pat;
fn pat_lit(&self, span: Span, expr: @ast::Expr) -> @ast::Pat;
@ -638,6 +642,50 @@ fn expr_unreachable(&self, span: Span) -> @ast::Expr {
"internal error: entered unreachable code"))
}
fn expr_ok(&self, sp: Span, expr: @ast::Expr) -> @ast::Expr {
let ok = vec!(
self.ident_of("std"),
self.ident_of("result"),
self.ident_of("Ok"));
self.expr_call_global(sp, ok, vec!(expr))
}
fn expr_err(&self, sp: Span, expr: @ast::Expr) -> @ast::Expr {
let err = vec!(
self.ident_of("std"),
self.ident_of("result"),
self.ident_of("Err"));
self.expr_call_global(sp, err, vec!(expr))
}
fn expr_try(&self, sp: Span, head: @ast::Expr) -> @ast::Expr {
let ok = self.ident_of("Ok");
let ok_path = self.path_ident(sp, ok);
let err = self.ident_of("Err");
let err_path = self.path_ident(sp, err);
let binding_variable = self.ident_of("__try_var");
let binding_pat = self.pat_ident(sp, binding_variable);
let binding_expr = self.expr_ident(sp, binding_variable);
// Ok(__try_var) pattern
let ok_pat = self.pat_enum(sp, ok_path, vec!(binding_pat));
// Err(__try_var) (pattern and expression resp.)
let err_pat = self.pat_enum(sp, err_path, vec!(binding_pat));
let err_inner_expr = self.expr_call_ident(sp, err, vec!(binding_expr));
// return Err(__try_var)
let err_expr = self.expr(sp, ast::ExprRet(Some(err_inner_expr)));
// Ok(__try_var) => __try_var
let ok_arm = self.arm(sp, vec!(ok_pat), binding_expr);
// Err(__try_var) => return Err(__try_var)
let err_arm = self.arm(sp, vec!(err_pat), err_expr);
// match head { Ok() => ..., Err() => ... }
self.expr_match(sp, head, vec!(ok_arm, err_arm))
}
fn pat(&self, span: Span, pat: ast::Pat_) -> @ast::Pat {
@ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: span }

View file

@ -30,11 +30,15 @@ pub fn expand_deriving_decodable(cx: &mut ExtCtxt,
span: span,
attributes: Vec::new(),
path: Path::new_(vec!("serialize", "Decodable"), None,
vec!(~Literal(Path::new_local("__D"))), true),
vec!(~Literal(Path::new_local("__D")),
~Literal(Path::new_local("__E"))), true),
additional_bounds: Vec::new(),
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec!(("__D", vec!(Path::new(vec!("serialize", "Decoder"))))),
bounds: vec!(("__D", vec!(Path::new_(
vec!("serialize", "Decoder"), None,
vec!(~Literal(Path::new_local("__E"))), true))),
("__E", vec!()))
},
methods: vec!(
MethodDef {
@ -43,7 +47,8 @@ pub fn expand_deriving_decodable(cx: &mut ExtCtxt,
explicit_self: None,
args: vec!(Ptr(~Literal(Path::new_local("__D")),
Borrowed(None, MutMutable))),
ret_ty: Self,
ret_ty: Literal(Path::new_(vec!("std", "result", "Result"), None,
vec!(~Self, ~Literal(Path::new_local("__E"))), true)),
inline: false,
const_nonmatching: true,
combine_substructure: decodable_substructure,
@ -78,11 +83,13 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
substr.type_ident,
summary,
|cx, span, name, field| {
cx.expr_method_call(span, blkdecoder, read_struct_field,
vec!(cx.expr_str(span, name),
cx.expr_uint(span, field),
lambdadecode))
cx.expr_try(span,
cx.expr_method_call(span, blkdecoder, read_struct_field,
vec!(cx.expr_str(span, name),
cx.expr_uint(span, field),
lambdadecode)))
});
let result = cx.expr_ok(trait_span, result);
cx.expr_method_call(trait_span,
decoder,
cx.ident_of("read_struct"),
@ -108,8 +115,9 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
parts,
|cx, span, _, field| {
let idx = cx.expr_uint(span, field);
cx.expr_method_call(span, blkdecoder, rvariant_arg,
vec!(idx, lambdadecode))
cx.expr_try(span,
cx.expr_method_call(span, blkdecoder, rvariant_arg,
vec!(idx, lambdadecode)))
});
arms.push(cx.arm(v_span,
@ -119,7 +127,9 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
arms.push(cx.arm_unreachable(trait_span));
let result = cx.expr_match(trait_span, cx.expr_ident(trait_span, variant), arms);
let result = cx.expr_ok(trait_span,
cx.expr_match(trait_span,
cx.expr_ident(trait_span, variant), arms));
let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result);
let variant_vec = cx.expr_vec(trait_span, variants);
let result = cx.expr_method_call(trait_span, blkdecoder,

View file

@ -82,7 +82,7 @@ fn decode(d: &D) -> spanned<T> {
```
*/
use ast::{MetaItem, Item, Expr, MutMutable};
use ast::{MetaItem, Item, Expr, ExprRet, MutMutable, LitNil};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
@ -98,20 +98,28 @@ pub fn expand_deriving_encodable(cx: &mut ExtCtxt,
span: span,
attributes: Vec::new(),
path: Path::new_(vec!("serialize", "Encodable"), None,
vec!(~Literal(Path::new_local("__E"))), true),
vec!(~Literal(Path::new_local("__S")),
~Literal(Path::new_local("__E"))), true),
additional_bounds: Vec::new(),
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec!(("__E", vec!(Path::new(vec!("serialize", "Encoder"))))),
bounds: vec!(("__S", vec!(Path::new_(
vec!("serialize", "Encoder"), None,
vec!(~Literal(Path::new_local("__E"))), true))),
("__E", vec!()))
},
methods: vec!(
MethodDef {
name: "encode",
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec!(Ptr(~Literal(Path::new_local("__E")),
args: vec!(Ptr(~Literal(Path::new_local("__S")),
Borrowed(None, MutMutable))),
ret_ty: nil_ty(),
ret_ty: Literal(Path::new_(vec!("std", "result", "Result"),
None,
vec!(~Tuple(Vec::new()),
~Literal(Path::new_local("__E"))),
true)),
inline: false,
const_nonmatching: true,
combine_substructure: encodable_substructure,
@ -133,6 +141,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
Struct(ref fields) => {
let emit_struct_field = cx.ident_of("emit_struct_field");
let mut stmts = Vec::new();
let last = fields.len() - 1;
for (i, &FieldInfo {
name,
self_,
@ -152,6 +161,13 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
vec!(cx.expr_str(span, name),
cx.expr_uint(span, i),
lambda));
// last call doesn't need a try!
let call = if i != last {
cx.expr_try(span, call)
} else {
cx.expr(span, ExprRet(Some(call)))
};
stmts.push(cx.stmt_expr(call));
}
@ -175,6 +191,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
let encoder = cx.expr_ident(trait_span, blkarg);
let emit_variant_arg = cx.ident_of("emit_enum_variant_arg");
let mut stmts = Vec::new();
let last = fields.len() - 1;
for (i, &FieldInfo { self_, span, .. }) in fields.iter().enumerate() {
let enc = cx.expr_method_call(span, self_, encode, vec!(blkencoder));
let lambda = cx.lambda_expr_1(span, enc, blkarg);
@ -182,9 +199,22 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
emit_variant_arg,
vec!(cx.expr_uint(span, i),
lambda));
let call = if i != last {
cx.expr_try(span, call)
} else {
cx.expr(span, ExprRet(Some(call)))
};
stmts.push(cx.stmt_expr(call));
}
// enums with no fields need to return Ok()
if stmts.len() == 0 {
let ret_ok = cx.expr(trait_span,
ExprRet(Some(cx.expr_ok(trait_span,
cx.expr_lit(trait_span, LitNil)))));
stmts.push(cx.stmt_expr(ret_ok));
}
let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
let name = cx.expr_str(trait_span, token::get_ident(variant.node.name));
let call = cx.expr_method_call(trait_span, blkencoder,

View file

@ -131,14 +131,34 @@ fn from_iterator<I: Iterator<T>>(mut iter: I) -> OwnedSlice<T> {
}
}
// FIXME: remove stage0 Encodables/Decodables after snapshot
#[cfg(stage0)]
impl<S: Encoder, T: Encodable<S>> Encodable<S> for OwnedSlice<T> {
fn encode(&self, s: &mut S) {
self.as_slice().encode(s)
}
}
#[cfg(stage0)]
impl<D: Decoder, T: Decodable<D>> Decodable<D> for OwnedSlice<T> {
fn decode(d: &mut D) -> OwnedSlice<T> {
OwnedSlice::from_vec(Decodable::decode(d))
}
}
#[cfg(not(stage0))]
impl<S: Encoder<E>, T: Encodable<S, E>, E> Encodable<S, E> for OwnedSlice<T> {
fn encode(&self, s: &mut S) -> Result<(), E> {
self.as_slice().encode(s)
}
}
#[cfg(not(stage0))]
impl<D: Decoder<E>, T: Decodable<D, E>, E> Decodable<D, E> for OwnedSlice<T> {
fn decode(d: &mut D) -> Result<OwnedSlice<T>, E> {
Ok(OwnedSlice::from_vec(match Decodable::decode(d) {
Ok(t) => t,
Err(e) => return Err(e)
}))
}
}

View file

@ -288,7 +288,8 @@ mod test {
use util::parser_testing::{string_to_expr, string_to_item};
use util::parser_testing::string_to_stmt;
#[cfg(test)]
// FIXME: remove stage0 to_json_str after snapshot
#[cfg(stage0)]
fn to_json_str<'a, E: Encodable<json::Encoder<'a>>>(val: &E) -> ~str {
let mut writer = MemWriter::new();
let mut encoder = json::Encoder::new(&mut writer as &mut io::Writer);
@ -296,6 +297,14 @@ fn to_json_str<'a, E: Encodable<json::Encoder<'a>>>(val: &E) -> ~str {
str::from_utf8_owned(writer.unwrap()).unwrap()
}
#[cfg(not(stage0))]
fn to_json_str<'a, E: Encodable<json::Encoder<'a>, io::IoError>>(val: &E) -> ~str {
let mut writer = MemWriter::new();
let mut encoder = json::Encoder::new(&mut writer as &mut io::Writer);
let _ = val.encode(&mut encoder);
str::from_utf8_owned(writer.unwrap()).unwrap()
}
// produce a codemap::span
fn sp(a: u32, b: u32) -> Span {
Span{lo:BytePos(a),hi:BytePos(b),expn_info:None}

View file

@ -602,18 +602,35 @@ fn equiv(&self, other: & &'a str) -> bool {
}
}
// FIXME: remove stage0 Encodables/Decodables after snapshot
#[cfg(stage0)]
impl<D:Decoder> Decodable<D> for InternedString {
fn decode(d: &mut D) -> InternedString {
get_name(get_ident_interner().intern(d.read_str()))
}
}
#[cfg(stage0)]
impl<E:Encoder> Encodable<E> for InternedString {
fn encode(&self, e: &mut E) {
e.emit_str(self.string.as_slice())
}
}
#[cfg(not(stage0))]
impl<D:Decoder<E>, E> Decodable<D, E> for InternedString {
fn decode(d: &mut D) -> Result<InternedString, E> {
Ok(get_name(get_ident_interner().intern(try!(d.read_str()))))
}
}
#[cfg(not(stage0))]
impl<S:Encoder<E>, E> Encodable<S, E> for InternedString {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_str(self.string.as_slice())
}
}
/// Returns the string contents of a name, using the task-local interner.
#[inline]
pub fn get_name(name: Name) -> InternedString {

View file

@ -46,7 +46,7 @@
use time::precise_time_ns;
use getopts::{OptGroup, optflag, optopt};
use serialize::{json, Decodable};
use serialize::json::ToJson;
use serialize::json::{Json, ToJson};
use term::Terminal;
use term::color::{Color, RED, YELLOW, GREEN, CYAN};
@ -1018,6 +1018,23 @@ fn to_json(&self) -> json::Json {
}
}
// FIXME: remove decode_ after snapshot
#[cfg(stage0)]
fn decode_(json: Json) -> MetricMap {
let mut decoder = json::Decoder::new(json);
MetricMap(Decodable::decode(&mut decoder))
}
#[cfg(not(stage0))]
fn decode_(json: Json) -> MetricMap {
let mut decoder = json::Decoder::new(json);
MetricMap(match Decodable::decode(&mut decoder) {
Ok(t) => t,
Err(e) => fail!("failure decoding JSON: {}", e)
})
}
impl MetricMap {
pub fn new() -> MetricMap {
@ -1034,8 +1051,7 @@ pub fn load(p: &Path) -> MetricMap {
assert!(p.exists());
let mut f = File::open(p).unwrap();
let value = json::from_reader(&mut f as &mut io::Reader).unwrap();
let mut decoder = json::Decoder::new(value);
MetricMap(Decodable::decode(&mut decoder))
decode_(value)
}
/// Write MetricDiff to a file.

View file

@ -490,13 +490,16 @@ fn eq(&self, other: &Uuid) -> bool {
impl TotalEq for Uuid {}
// FIXME #9845: Test these more thoroughly
// FIXME: remove stage0 Encodable/Decodable after snapshot
#[cfg(stage0)]
impl<T: Encoder> Encodable<T> for Uuid {
/// Encode a UUID as a hypenated string
fn encode(&self, e: &mut T) {
e.emit_str(self.to_hyphenated_str());
e.emit_str(self.to_hyphenated_str())
}
}
#[cfg(stage0)]
impl<T: Decoder> Decodable<T> for Uuid {
/// Decode a UUID from a string
fn decode(d: &mut T) -> Uuid {
@ -504,6 +507,22 @@ fn decode(d: &mut T) -> Uuid {
}
}
#[cfg(not(stage0))]
impl<T: Encoder<E>, E> Encodable<T, E> for Uuid {
/// Encode a UUID as a hypenated string
fn encode(&self, e: &mut T) -> Result<(), E> {
e.emit_str(self.to_hyphenated_str())
}
}
#[cfg(not(stage0))]
impl<T: Decoder<E>, E> Decodable<T, E> for Uuid {
/// Decode a UUID from a string
fn decode(d: &mut T) -> Result<Uuid, E> {
Ok(from_str(try!(d.read_str())).unwrap())
}
}
/// Generates a random instance of UUID (V4 conformant)
impl rand::Rand for Uuid {
#[inline]
@ -528,6 +547,17 @@ mod test {
use std::str;
use std::io::MemWriter;
// FIXME: remove unwrap_ after snapshot
#[cfg(stage0)]
fn unwrap_<T>(t: T) -> T {
t
}
#[cfg(not(stage0))]
fn unwrap_<T, E>(t: Result<T, E>) -> T {
t.unwrap()
}
#[test]
fn test_nil() {
let nil = Uuid::nil();
@ -797,9 +827,9 @@ fn test_serialize_round_trip() {
let u = Uuid::new_v4();
let mut wr = MemWriter::new();
u.encode(&mut ebml::writer::Encoder(&mut wr));
let _ = u.encode(&mut ebml::writer::Encoder(&mut wr));
let doc = ebml::reader::Doc(wr.get_ref());
let u2 = Decodable::decode(&mut ebml::reader::Decoder(doc));
let u2 = unwrap_(Decodable::decode(&mut ebml::reader::Decoder(doc)));
assert_eq!(u, u2);
}

View file

@ -203,7 +203,7 @@ fn load(&mut self) {
self.db_filename.display(), e.to_str()),
Ok(r) => {
let mut decoder = json::Decoder::new(r);
self.db_cache = Decodable::decode(&mut decoder);
self.db_cache = Decodable::decode(&mut decoder).unwrap();
}
}
}
@ -252,19 +252,19 @@ enum Work<'a, T> {
WorkFromTask(&'a Prep<'a>, Receiver<(Exec, T)>),
}
fn json_encode<'a, T:Encodable<json::Encoder<'a>>>(t: &T) -> ~str {
fn json_encode<'a, T:Encodable<json::Encoder<'a>, io::IoError>>(t: &T) -> ~str {
let mut writer = MemWriter::new();
let mut encoder = json::Encoder::new(&mut writer as &mut io::Writer);
t.encode(&mut encoder);
let _ = t.encode(&mut encoder);
str::from_utf8_owned(writer.unwrap()).unwrap()
}
// FIXME(#5121)
fn json_decode<T:Decodable<json::Decoder>>(s: &str) -> T {
fn json_decode<T:Decodable<json::Decoder, json::Error>>(s: &str) -> T {
debug!("json decoding: {}", s);
let j = json::from_str(s).unwrap();
let mut decoder = json::Decoder::new(j);
Decodable::decode(&mut decoder)
Decodable::decode(&mut decoder).unwrap()
}
impl Context {
@ -392,15 +392,15 @@ fn all_fresh(&self, cat: &str, map: &WorkMap) -> bool {
}
pub fn exec<'a, T:Send +
Encodable<json::Encoder<'a>> +
Decodable<json::Decoder>>(
Encodable<json::Encoder<'a>, io::IoError> +
Decodable<json::Decoder, json::Error>>(
&'a self, blk: proc:Send(&mut Exec) -> T) -> T {
self.exec_work(blk).unwrap()
}
fn exec_work<'a, T:Send +
Encodable<json::Encoder<'a>> +
Decodable<json::Decoder>>( // FIXME(#5121)
Encodable<json::Encoder<'a>, io::IoError> +
Decodable<json::Decoder, json::Error>>( // FIXME(#5121)
&'a self, blk: proc:Send(&mut Exec) -> T) -> Work<'a, T> {
let mut bo = Some(blk);
@ -443,8 +443,8 @@ fn exec_work<'a, T:Send +
}
impl<'a, T:Send +
Encodable<json::Encoder<'a>> +
Decodable<json::Decoder>>
Encodable<json::Encoder<'a>, io::IoError> +
Decodable<json::Decoder, json::Error>>
Work<'a, T> { // FIXME(#5121)
pub fn from_value(elt: T) -> Work<'a, T> {

View file

@ -15,12 +15,12 @@
use serialize::{json, Decodable};
trait JD : Decodable<json::Decoder> { }
trait JD : Decodable<json::Decoder, json::Error> { }
fn exec<T: JD>() {
let doc = json::from_str("").unwrap();
let mut decoder = json::Decoder::new(doc);
let _v: T = Decodable::decode(&mut decoder);
let _v: T = Decodable::decode(&mut decoder).unwrap();
fail!()
}

View file

@ -20,5 +20,5 @@
pub fn main() {
let json = json::from_str("[1]").unwrap();
let mut decoder = json::Decoder::new(json);
let _x: Vec<int> = Decodable::decode(&mut decoder);
let _x: Vec<int> = Decodable::decode(&mut decoder).unwrap();
}