std: Rename {Option,Result}::chain{,_err}* to {and_then,or_else}

This commit is contained in:
Erick Tryzelaar 2013-09-11 12:52:17 -07:00
parent e03d60e9eb
commit 38f97ea103
25 changed files with 205 additions and 164 deletions

View File

@ -273,9 +273,9 @@ impl<T: FromStr + Clone + Integer + Ord>
return None
}
let a_option: Option<T> = FromStr::from_str(split[0]);
do a_option.chain |a| {
do a_option.and_then |a| {
let b_option: Option<T> = FromStr::from_str(split[1]);
do b_option.chain |b| {
do b_option.and_then |b| {
Some(Ratio::new(a.clone(), b.clone()))
}
}
@ -291,10 +291,10 @@ impl<T: FromStrRadix + Clone + Integer + Ord>
} else {
let a_option: Option<T> = FromStrRadix::from_str_radix(split[0],
radix);
do a_option.chain |a| {
do a_option.and_then |a| {
let b_option: Option<T> =
FromStrRadix::from_str_radix(split[1], radix);
do b_option.chain |b| {
do b_option.and_then |b| {
Some(Ratio::new(a.clone(), b.clone()))
}
}

View File

@ -442,21 +442,21 @@ fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
},
'c' => {
parse_type(s, pos, 'a', &mut *tm)
.chain(|pos| parse_char(s, pos, ' '))
.chain(|pos| parse_type(s, pos, 'b', &mut *tm))
.chain(|pos| parse_char(s, pos, ' '))
.chain(|pos| parse_type(s, pos, 'e', &mut *tm))
.chain(|pos| parse_char(s, pos, ' '))
.chain(|pos| parse_type(s, pos, 'T', &mut *tm))
.chain(|pos| parse_char(s, pos, ' '))
.chain(|pos| parse_type(s, pos, 'Y', &mut *tm))
.and_then(|pos| parse_char(s, pos, ' '))
.and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
.and_then(|pos| parse_char(s, pos, ' '))
.and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
.and_then(|pos| parse_char(s, pos, ' '))
.and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
.and_then(|pos| parse_char(s, pos, ' '))
.and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
}
'D' | 'x' => {
parse_type(s, pos, 'm', &mut *tm)
.chain(|pos| parse_char(s, pos, '/'))
.chain(|pos| parse_type(s, pos, 'd', &mut *tm))
.chain(|pos| parse_char(s, pos, '/'))
.chain(|pos| parse_type(s, pos, 'y', &mut *tm))
.and_then(|pos| parse_char(s, pos, '/'))
.and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
.and_then(|pos| parse_char(s, pos, '/'))
.and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
}
'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
31_i32) {
@ -475,10 +475,10 @@ fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
}
'F' => {
parse_type(s, pos, 'Y', &mut *tm)
.chain(|pos| parse_char(s, pos, '-'))
.chain(|pos| parse_type(s, pos, 'm', &mut *tm))
.chain(|pos| parse_char(s, pos, '-'))
.chain(|pos| parse_type(s, pos, 'd', &mut *tm))
.and_then(|pos| parse_char(s, pos, '-'))
.and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
.and_then(|pos| parse_char(s, pos, '-'))
.and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
}
'H' => {
match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
@ -553,17 +553,17 @@ fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
},
'R' => {
parse_type(s, pos, 'H', &mut *tm)
.chain(|pos| parse_char(s, pos, ':'))
.chain(|pos| parse_type(s, pos, 'M', &mut *tm))
.and_then(|pos| parse_char(s, pos, ':'))
.and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
}
'r' => {
parse_type(s, pos, 'I', &mut *tm)
.chain(|pos| parse_char(s, pos, ':'))
.chain(|pos| parse_type(s, pos, 'M', &mut *tm))
.chain(|pos| parse_char(s, pos, ':'))
.chain(|pos| parse_type(s, pos, 'S', &mut *tm))
.chain(|pos| parse_char(s, pos, ' '))
.chain(|pos| parse_type(s, pos, 'p', &mut *tm))
.and_then(|pos| parse_char(s, pos, ':'))
.and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
.and_then(|pos| parse_char(s, pos, ':'))
.and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
.and_then(|pos| parse_char(s, pos, ' '))
.and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
}
'S' => {
match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
@ -578,10 +578,10 @@ fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
//'s' {}
'T' | 'X' => {
parse_type(s, pos, 'H', &mut *tm)
.chain(|pos| parse_char(s, pos, ':'))
.chain(|pos| parse_type(s, pos, 'M', &mut *tm))
.chain(|pos| parse_char(s, pos, ':'))
.chain(|pos| parse_type(s, pos, 'S', &mut *tm))
.and_then(|pos| parse_char(s, pos, ':'))
.and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
.and_then(|pos| parse_char(s, pos, ':'))
.and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
}
't' => parse_char(s, pos, '\t'),
'u' => {
@ -596,10 +596,10 @@ fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
}
'v' => {
parse_type(s, pos, 'e', &mut *tm)
.chain(|pos| parse_char(s, pos, '-'))
.chain(|pos| parse_type(s, pos, 'b', &mut *tm))
.chain(|pos| parse_char(s, pos, '-'))
.chain(|pos| parse_type(s, pos, 'Y', &mut *tm))
.and_then(|pos| parse_char(s, pos, '-'))
.and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
.and_then(|pos| parse_char(s, pos, '-'))
.and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
}
//'W' {}
'w' => {

View File

@ -961,7 +961,7 @@ pub fn build_output_filenames(input: &input,
if !linkage_metas.is_empty() {
// But if a linkage meta is present, that overrides
let maybe_name = linkage_metas.iter().find(|m| "name" == m.name());
match maybe_name.chain(|m| m.value_str()) {
match maybe_name.and_then(|m| m.value_str()) {
Some(s) => stem = s,
_ => ()
}

View File

@ -58,7 +58,7 @@ fn filter_view_item<'r>(cx: @Context, view_item: &'r ast::view_item)-> Option<&'
fn fold_mod(cx: @Context, m: &ast::_mod, fld: @fold::ast_fold) -> ast::_mod {
let filtered_items = do m.items.iter().filter_map |a| {
filter_item(cx, *a).chain(|x| fld.fold_item(x))
filter_item(cx, *a).and_then(|x| fld.fold_item(x))
}.collect();
let filtered_view_items = do m.view_items.iter().filter_map |a| {
do filter_view_item(cx, a).map_move |x| {
@ -139,7 +139,7 @@ fn fold_block(
fld: @fold::ast_fold
) -> ast::Block {
let resulting_stmts = do b.stmts.iter().filter_map |a| {
filter_stmt(cx, *a).chain(|stmt| fld.fold_stmt(stmt))
filter_stmt(cx, *a).and_then(|stmt| fld.fold_stmt(stmt))
}.collect();
let filtered_view_items = do b.view_items.iter().filter_map |a| {
filter_view_item(cx, a).map(|x| fld.fold_view_item(*x))

View File

@ -184,7 +184,7 @@ fn visit_item(e: &Env, i: @ast::item) {
ast::named => {
let link_name = i.attrs.iter()
.find(|at| "link_name" == at.name())
.chain(|at| at.value_str());
.and_then(|at| at.value_str());
let foreign_name = match link_name {
Some(nn) => {

View File

@ -210,7 +210,7 @@ fn each_reexport(d: ebml::Doc, f: &fn(ebml::Doc) -> bool) -> bool {
}
fn variant_disr_val(d: ebml::Doc) -> Option<ty::Disr> {
do reader::maybe_get_doc(d, tag_disr_val).chain |val_doc| {
do reader::maybe_get_doc(d, tag_disr_val).and_then |val_doc| {
do reader::with_doc_data(val_doc) |data| { u64::parse_bytes(data, 10u) }
}
}

View File

@ -505,7 +505,10 @@ impl get_node_info for ast::Block {
impl get_node_info for Option<@ast::Expr> {
fn info(&self) -> Option<NodeInfo> {
self.chain_ref(|s| s.info())
match *self {
Some(ref s) => s.info(),
None => None,
}
}
}

View File

@ -50,9 +50,9 @@ impl Value {
/// must be the only user of this value, and there must not be any conditional
/// branches between the store and the given block.
pub fn get_dominating_store(self, bcx: @mut Block) -> Option<Value> {
match self.get_single_user().chain(|user| user.as_store_inst()) {
match self.get_single_user().and_then(|user| user.as_store_inst()) {
Some(store) => {
do store.get_parent().chain |store_bb| {
do store.get_parent().and_then |store_bb| {
let mut bb = BasicBlock(bcx.llbb);
let mut ret = Some(store);
while *bb != *store_bb {
@ -150,7 +150,7 @@ impl Iterator<Value> for UserIterator {
fn next(&mut self) -> Option<Value> {
let current = self.next;
self.next = do current.chain |u| { u.get_next_use() };
self.next = do current.and_then |u| { u.get_next_use() };
do current.map |u| { u.get_user() }
}

View File

@ -745,10 +745,17 @@ pub fn ty_of_closure<AC:AstConv,RS:RegionScope + Clone + 'static>(
RegionParamNames(bound_lifetime_names.clone()));
let input_tys = do decl.inputs.iter().enumerate().map |(i, a)| {
let expected_arg_ty = do expected_sig.chain_ref |e| {
// no guarantee that the correct number of expected args
// were supplied
if i < e.inputs.len() {Some(e.inputs[i])} else {None}
let expected_arg_ty = match expected_sig {
Some(ref e) => {
// no guarantee that the correct number of expected args
// were supplied
if i < e.inputs.len() {
Some(e.inputs[i])
} else {
None
}
}
None => None,
};
ty_of_arg(this, &rb, a, expected_arg_ty)
}.collect();

View File

@ -15,7 +15,7 @@
// the trait `Combine` and contains methods for combining two
// instances of various things and yielding a new instance. These
// combiner methods always yield a `result<T>`---failure is propagated
// upward using `chain()` methods. There is a lot of common code for
// upward using `and_then()` methods. There is a lot of common code for
// these operations, implemented as default methods on the `Combine`
// trait.
//
@ -108,7 +108,7 @@ pub trait Combine {
(Some(a), Some(b)) => {
// FIXME(#5781) this should be eq_tys
// eq_tys(self, a, b).then(|| Ok(Some(a)) )
self.contratys(a, b).chain(|t| Ok(Some(t)))
self.contratys(a, b).and_then(|t| Ok(Some(t)))
}
(None, Some(_)) |
(Some(_), None) => {
@ -162,13 +162,13 @@ pub trait Combine {
}
ty::rv_covariant => {
do this.regions(a_r, b_r).chain |r| {
do this.regions(a_r, b_r).and_then |r| {
Ok(ty::NonerasedRegions(opt_vec::with(r)))
}
}
ty::rv_contravariant => {
do this.contraregions(a_r, b_r).chain |r| {
do this.contraregions(a_r, b_r).and_then |r| {
Ok(ty::NonerasedRegions(opt_vec::with(r)))
}
}
@ -179,12 +179,12 @@ pub trait Combine {
}
}
do self.tps(as_.tps, bs.tps).chain |tps| {
do self.self_tys(as_.self_ty, bs.self_ty).chain |self_ty| {
do self.tps(as_.tps, bs.tps).and_then |tps| {
do self.self_tys(as_.self_ty, bs.self_ty).and_then |self_ty| {
do relate_region_params(self,
generics,
&as_.regions,
&bs.regions).chain |regions| {
&bs.regions).and_then |regions| {
Ok(substs {
regions: regions,
self_ty: self_ty,
@ -227,8 +227,8 @@ pub trait Combine {
fn flds(&self, a: ty::field, b: ty::field) -> cres<ty::field> {
if a.ident == b.ident {
self.mts(&a.mt, &b.mt)
.chain(|mt| Ok(ty::field {ident: a.ident, mt: mt}) )
.chain_err(|e| Err(ty::terr_in_field(@e, a.ident)) )
.and_then(|mt| Ok(ty::field {ident: a.ident, mt: mt}) )
.or_else(|e| Err(ty::terr_in_field(@e, a.ident)) )
} else {
Err(ty::terr_record_fields(
expected_found(self,
@ -238,7 +238,7 @@ pub trait Combine {
}
fn args(&self, a: ty::t, b: ty::t) -> cres<ty::t> {
do self.contratys(a, b).chain |t| {
do self.contratys(a, b).and_then |t| {
Ok(t)
}
}
@ -274,7 +274,7 @@ pub trait Combine {
match (a, b) {
(ty::vstore_slice(a_r), ty::vstore_slice(b_r)) => {
do self.contraregions(a_r, b_r).chain |r| {
do self.contraregions(a_r, b_r).and_then |r| {
Ok(ty::vstore_slice(r))
}
}
@ -299,7 +299,7 @@ pub trait Combine {
match (a, b) {
(ty::RegionTraitStore(a_r), ty::RegionTraitStore(b_r)) => {
do self.contraregions(a_r, b_r).chain |r| {
do self.contraregions(a_r, b_r).and_then |r| {
Ok(ty::RegionTraitStore(r))
}
}
@ -357,7 +357,7 @@ pub fn expected_found<C:Combine,T>(
pub fn eq_tys<C:Combine>(this: &C, a: ty::t, b: ty::t) -> ures {
let suber = this.sub();
do this.infcx().try {
do suber.tys(a, b).chain |_ok| {
do suber.tys(a, b).and_then |_ok| {
suber.contratys(a, b)
}.to_ures()
}
@ -371,10 +371,10 @@ pub fn eq_regions<C:Combine>(this: &C, a: ty::Region, b: ty::Region)
let sub = this.sub();
do indent {
this.infcx().try(|| {
do sub.regions(a, b).chain |_r| {
do sub.regions(a, b).and_then |_r| {
sub.contraregions(a, b)
}
}).chain_err(|e| {
}).or_else(|e| {
// substitute a better error, but use the regions
// found in the original error
match e {
@ -427,8 +427,8 @@ pub fn super_fn_sigs<C:Combine>(
}
do argvecs(this, a.inputs, b.inputs)
.chain |inputs| {
do this.tys(a.output, b.output).chain |output| {
.and_then |inputs| {
do this.tys(a.output, b.output).and_then |output| {
Ok(FnSig {bound_lifetime_names: opt_vec::Empty, // FIXME(#4846)
inputs: inputs.clone(),
output: output})
@ -508,7 +508,7 @@ pub fn super_tys<C:Combine>(
&ty::ty_enum(b_id, ref b_substs))
if a_id == b_id => {
let type_def = ty::lookup_item_type(tcx, a_id);
do this.substs(&type_def.generics, a_substs, b_substs).chain |substs| {
do this.substs(&type_def.generics, a_substs, b_substs).and_then |substs| {
Ok(ty::mk_enum(tcx, a_id, substs))
}
}
@ -517,9 +517,9 @@ pub fn super_tys<C:Combine>(
&ty::ty_trait(b_id, ref b_substs, b_store, b_mutbl, b_bounds))
if a_id == b_id && a_mutbl == b_mutbl => {
let trait_def = ty::lookup_trait_def(tcx, a_id);
do this.substs(&trait_def.generics, a_substs, b_substs).chain |substs| {
do this.trait_stores(ty::terr_trait, a_store, b_store).chain |s| {
do this.bounds(a_bounds, b_bounds).chain |bounds| {
do this.substs(&trait_def.generics, a_substs, b_substs).and_then |substs| {
do this.trait_stores(ty::terr_trait, a_store, b_store).and_then |s| {
do this.bounds(a_bounds, b_bounds).and_then |bounds| {
Ok(ty::mk_trait(tcx,
a_id,
substs.clone(),
@ -534,25 +534,25 @@ pub fn super_tys<C:Combine>(
(&ty::ty_struct(a_id, ref a_substs), &ty::ty_struct(b_id, ref b_substs))
if a_id == b_id => {
let type_def = ty::lookup_item_type(tcx, a_id);
do this.substs(&type_def.generics, a_substs, b_substs).chain |substs| {
do this.substs(&type_def.generics, a_substs, b_substs).and_then |substs| {
Ok(ty::mk_struct(tcx, a_id, substs))
}
}
(&ty::ty_box(ref a_mt), &ty::ty_box(ref b_mt)) => {
do this.mts(a_mt, b_mt).chain |mt| {
do this.mts(a_mt, b_mt).and_then |mt| {
Ok(ty::mk_box(tcx, mt))
}
}
(&ty::ty_uniq(ref a_mt), &ty::ty_uniq(ref b_mt)) => {
do this.mts(a_mt, b_mt).chain |mt| {
do this.mts(a_mt, b_mt).and_then |mt| {
Ok(ty::mk_uniq(tcx, mt))
}
}
(&ty::ty_ptr(ref a_mt), &ty::ty_ptr(ref b_mt)) => {
do this.mts(a_mt, b_mt).chain |mt| {
do this.mts(a_mt, b_mt).and_then |mt| {
Ok(ty::mk_ptr(tcx, mt))
}
}
@ -564,15 +564,15 @@ pub fn super_tys<C:Combine>(
}
(&ty::ty_evec(ref a_mt, vs_a), &ty::ty_evec(ref b_mt, vs_b)) => {
do this.mts(a_mt, b_mt).chain |mt| {
do this.vstores(ty::terr_vec, vs_a, vs_b).chain |vs| {
do this.mts(a_mt, b_mt).and_then |mt| {
do this.vstores(ty::terr_vec, vs_a, vs_b).and_then |vs| {
Ok(ty::mk_evec(tcx, mt, vs))
}
}
}
(&ty::ty_estr(vs_a), &ty::ty_estr(vs_b)) => {
do this.vstores(ty::terr_str, vs_a, vs_b).chain |vs| {
do this.vstores(ty::terr_str, vs_a, vs_b).and_then |vs| {
Ok(ty::mk_estr(tcx,vs))
}
}
@ -581,7 +581,7 @@ pub fn super_tys<C:Combine>(
if as_.len() == bs.len() {
result::collect(as_.iter().zip(bs.iter())
.map(|(a, b)| this.tys(*a, *b)))
.chain(|ts| Ok(ty::mk_tup(tcx, ts)) )
.and_then(|ts| Ok(ty::mk_tup(tcx, ts)) )
} else {
Err(ty::terr_tuple_size(
expected_found(this, as_.len(), bs.len())))
@ -589,13 +589,13 @@ pub fn super_tys<C:Combine>(
}
(&ty::ty_bare_fn(ref a_fty), &ty::ty_bare_fn(ref b_fty)) => {
do this.bare_fn_tys(a_fty, b_fty).chain |fty| {
do this.bare_fn_tys(a_fty, b_fty).and_then |fty| {
Ok(ty::mk_bare_fn(tcx, fty))
}
}
(&ty::ty_closure(ref a_fty), &ty::ty_closure(ref b_fty)) => {
do this.closure_tys(a_fty, b_fty).chain |fty| {
do this.closure_tys(a_fty, b_fty).and_then |fty| {
Ok(ty::mk_closure(tcx, fty))
}
}

View File

@ -61,7 +61,7 @@ impl Combine for Glb {
// If one side or both is immutable, we can use the GLB of
// both sides but mutbl must be `MutImmutable`.
(MutImmutable, MutImmutable) => {
self.tys(a.ty, b.ty).chain(|t| {
self.tys(a.ty, b.ty).and_then(|t| {
Ok(ty::mt {ty: t, mutbl: MutImmutable})
})
}

View File

@ -232,7 +232,7 @@ impl CombineFieldsLatticeMethods for CombineFields {
(&Some(_), &None) => Ok((*a).clone()),
(&None, &Some(_)) => Ok((*b).clone()),
(&Some(ref v_a), &Some(ref v_b)) => {
do lattice_op(self, v_a, v_b).chain |v| {
do lattice_op(self, v_a, v_b).and_then |v| {
Ok(Some(v))
}
}

View File

@ -62,7 +62,7 @@ impl Combine for Lub {
let m = a.mutbl;
match m {
MutImmutable => {
self.tys(a.ty, b.ty).chain(|t| Ok(ty::mt {ty: t, mutbl: m}) )
self.tys(a.ty, b.ty).and_then(|t| Ok(ty::mt {ty: t, mutbl: m}) )
}
MutMutable => {
@ -70,7 +70,7 @@ impl Combine for Lub {
eq_tys(self, a.ty, b.ty).then(|| {
Ok(ty::mt {ty: a.ty, mutbl: m})
})
}).chain_err(|e| Err(e))
}).or_else(|e| Err(e))
}
}
}

View File

@ -451,7 +451,7 @@ trait then {
impl then for ures {
fn then<T:Clone>(&self, f: &fn() -> Result<T,ty::type_err>)
-> Result<T,ty::type_err> {
self.chain(|_i| f())
self.and_then(|_i| f())
}
}
@ -474,7 +474,7 @@ trait CresCompare<T> {
impl<T:Clone + Eq> CresCompare<T> for cres<T> {
fn compare(&self, t: T, f: &fn() -> ty::type_err) -> cres<T> {
do (*self).clone().chain |s| {
do (*self).clone().and_then |s| {
if s == t {
(*self).clone()
} else {

View File

@ -79,7 +79,7 @@ impl Combine for Sub {
}
MutImmutable => {
// Otherwise we can be covariant:
self.tys(a.ty, b.ty).chain(|_t| Ok(*a) )
self.tys(a.ty, b.ty).and_then(|_t| Ok(*a) )
}
}
}

View File

@ -202,7 +202,7 @@ impl RegionScope for MethodRscope {
if !self.region_param_names.has_ident(id) {
return RegionParamNames::undeclared_name(None);
}
do EmptyRscope.named_region(span, id).chain_err |_e| {
do EmptyRscope.named_region(span, id).or_else |_e| {
result::Err(RegionError {
msg: ~"lifetime is not in scope",
replacement: ty::re_bound(ty::br_self)
@ -251,7 +251,7 @@ impl RegionScope for TypeRscope {
}
fn named_region(&self, span: Span, id: ast::Ident)
-> Result<ty::Region, RegionError> {
do EmptyRscope.named_region(span, id).chain_err |_e| {
do EmptyRscope.named_region(span, id).or_else |_e| {
result::Err(RegionError {
msg: ~"only 'self is allowed as part of a type declaration",
replacement: self.replacement()
@ -310,7 +310,7 @@ impl RegionScope for BindingRscope {
span: Span,
id: ast::Ident) -> Result<ty::Region, RegionError>
{
do self.base.named_region(span, id).chain_err |_e| {
do self.base.named_region(span, id).or_else |_e| {
let result = ty::re_bound(ty::br_named(id));
if self.region_param_names.has_ident(id) {
result::Ok(result)

View File

@ -138,7 +138,7 @@ fn config_from_opts(
let config = default_config(input_crate);
let result = result::Ok(config);
let result = do result.chain |config| {
let result = do result.and_then |config| {
let output_dir = getopts::opt_maybe_str(matches, opt_output_dir());
let output_dir = output_dir.map_move(|s| Path(s));
result::Ok(Config {
@ -146,10 +146,10 @@ fn config_from_opts(
.. config
})
};
let result = do result.chain |config| {
let result = do result.and_then |config| {
let output_format = getopts::opt_maybe_str(matches, opt_output_format());
do output_format.map_move_default(result::Ok(config.clone())) |output_format| {
do parse_output_format(output_format).chain |output_format| {
do parse_output_format(output_format).and_then |output_format| {
result::Ok(Config {
output_format: output_format,
.. config.clone()
@ -157,11 +157,11 @@ fn config_from_opts(
}
}
};
let result = do result.chain |config| {
let result = do result.and_then |config| {
let output_style =
getopts::opt_maybe_str(matches, opt_output_style());
do output_style.map_move_default(result::Ok(config.clone())) |output_style| {
do parse_output_style(output_style).chain |output_style| {
do parse_output_style(output_style).and_then |output_style| {
result::Ok(Config {
output_style: output_style,
.. config.clone()
@ -170,11 +170,11 @@ fn config_from_opts(
}
};
let process_output = Cell::new(process_output);
let result = do result.chain |config| {
let result = do result.and_then |config| {
let pandoc_cmd = getopts::opt_maybe_str(matches, opt_pandoc_cmd());
let pandoc_cmd = maybe_find_pandoc(
&config, pandoc_cmd, process_output.take());
do pandoc_cmd.chain |pandoc_cmd| {
do pandoc_cmd.and_then |pandoc_cmd| {
result::Ok(Config {
pandoc_cmd: pandoc_cmd,
.. config.clone()

View File

@ -118,7 +118,7 @@ pub fn try_getting_local_version(local_path: &Path) -> Option<Version> {
if !l.is_whitespace() {
output = Some(l);
}
match output.chain(try_parsing_version) {
match output.and_then(try_parsing_version) {
Some(v) => return Some(v),
None => ()
}
@ -158,7 +158,7 @@ pub fn try_getting_version(remote_path: &Path) -> Option<Version> {
}
}
output.chain(try_parsing_version)
output.and_then(try_parsing_version)
}
else {
None

View File

@ -1618,7 +1618,7 @@ impl<T:Writer> WriterUtil for T {
}
pub fn file_writer(path: &Path, flags: &[FileFlag]) -> Result<@Writer, ~str> {
mk_file_writer(path, flags).chain(|w| Ok(w))
mk_file_writer(path, flags).and_then(|w| Ok(w))
}
@ -1779,7 +1779,7 @@ pub fn seek_in_buf(offset: int, pos: uint, len: uint, whence: SeekStyle) ->
}
pub fn read_whole_file_str(file: &Path) -> Result<~str, ~str> {
do read_whole_file(file).chain |bytes| {
do read_whole_file(file).and_then |bytes| {
if str::is_utf8(bytes) {
Ok(str::from_utf8(bytes))
} else {
@ -1791,7 +1791,7 @@ pub fn read_whole_file_str(file: &Path) -> Result<~str, ~str> {
// FIXME (#2004): implement this in a low-level way. Going through the
// abstractions is pointless.
pub fn read_whole_file(file: &Path) -> Result<~[u8], ~str> {
do file_reader(file).chain |rdr| {
do file_reader(file).and_then |rdr| {
Ok(rdr.read_whole_stream())
}
}

View File

@ -1474,7 +1474,7 @@ pub struct Scan<'self, A, B, T, St> {
impl<'self, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'self, A, B, T, St> {
#[inline]
fn next(&mut self) -> Option<B> {
self.iter.next().chain(|a| (self.f)(&mut self.state, a))
self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
}
#[inline]
@ -1494,8 +1494,7 @@ pub struct FlatMap<'self, A, T, U> {
priv backiter: Option<U>,
}
impl<'self, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for
FlatMap<'self, A, T, U> {
impl<'self, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for FlatMap<'self, A, T, U> {
#[inline]
fn next(&mut self) -> Option<B> {
loop {
@ -1505,7 +1504,12 @@ impl<'self, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for
}
}
match self.iter.next().map_move(|x| (self.f)(x)) {
None => return self.backiter.chain_mut_ref(|it| it.next()),
None => {
return match self.backiter {
Some(ref mut it) => it.next(),
None => None,
};
}
next => self.frontiter = next,
}
}
@ -1537,7 +1541,12 @@ impl<'self,
}
}
match self.iter.next_back().map_move(|x| (self.f)(x)) {
None => return self.frontiter.chain_mut_ref(|it| it.next_back()),
None => {
return match self.frontiter {
Some(ref mut it) => it.next_back(),
None => None,
};
}
next => self.backiter = next,
}
}

View File

@ -141,9 +141,9 @@ impl<T> Option<T> {
/// Returns `None` if the option is `None`, otherwise calls and returns the
/// value of `f`.
#[inline]
pub fn and_then(self, f: &fn() -> Option<T>) -> Option<T> {
pub fn and_then<U>(self, f: &fn(T) -> Option<U>) -> Option<U> {
match self {
Some(_) => f(),
Some(x) => f(x),
None => None,
}
}
@ -167,36 +167,6 @@ impl<T> Option<T> {
}
}
/// Update an optional value by optionally running its content through a
/// function that returns an option.
#[inline]
pub fn chain<U>(self, f: &fn(T) -> Option<U>) -> Option<U> {
match self {
Some(t) => f(t),
None => None
}
}
/// Update an optional value by optionally running its content by reference
/// through a function that returns an option.
#[inline]
pub fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option<U>) -> Option<U> {
match *self {
Some(ref x) => f(x),
None => None
}
}
/// Update an optional value by optionally running its content by mut reference
/// through a function that returns an option.
#[inline]
pub fn chain_mut_ref<'a, U>(&'a mut self, f: &fn(x: &'a mut T) -> Option<U>) -> Option<U> {
match *self {
Some(ref mut x) => f(x),
None => None
}
}
/// Filters an optional value using given function.
#[inline(always)]
pub fn filtered(self, f: &fn(t: &T) -> bool) -> Option<T> {
@ -637,12 +607,12 @@ mod tests {
#[test]
fn test_and_then() {
let x: Option<int> = Some(1);
assert_eq!(x.and_then(|| Some(2)), Some(2));
assert_eq!(x.and_then(|| None), None);
assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
assert_eq!(x.and_then(|_| None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and_then(|| Some(2)), None);
assert_eq!(x.and_then(|| None), None);
assert_eq!(x.and_then(|x| Some(x + 1)), None);
assert_eq!(x.and_then(|_| None::<int>), None);
}
#[test]

View File

@ -171,10 +171,22 @@ impl<T, E: ToStr> Result<T, E> {
}
}
/// Call a method based on a previous result
///
/// If `self` is `Ok`, then `res` it is returned. If `self` is `Err`,
/// then `self` is returned.
#[inline]
pub fn and(self, res: Result<T, E>) -> Result<T, E> {
match self {
Ok(_) => res,
Err(_) => self,
}
}
/// Call a method based on a previous result
///
/// If `self` is `Ok` then the value is extracted and passed to `op`
/// whereupon `op`s result is returned. if `self` is `Err` then it is
/// whereupon `op`s result is returned. If `self` is `Err` then it is
/// immediately returned. This function can be used to compose the results
/// of two functions.
///
@ -184,13 +196,25 @@ impl<T, E: ToStr> Result<T, E> {
/// Ok(parse_bytes(buf))
/// };
#[inline]
pub fn chain<U>(self, op: &fn(T) -> Result<U, E>) -> Result<U, E> {
pub fn and_then<U>(self, op: &fn(T) -> Result<U, E>) -> Result<U, E> {
match self {
Ok(t) => op(t),
Err(e) => Err(e),
}
}
/// Call a method based on a previous result
///
/// If `self` is `Ok`, then `self` is returned. If `self` is `Err`
/// then `res` is returned.
#[inline]
pub fn or(self, res: Result<T, E>) -> Result<T, E> {
match self {
Ok(_) => self,
Err(_) => res,
}
}
/// Call a function based on a previous result
///
/// If `self` is `Err` then the value is extracted and passed to `op`
@ -198,7 +222,7 @@ impl<T, E: ToStr> Result<T, E> {
/// immediately returned. This function can be used to pass through a
/// successful result while handling an error.
#[inline]
pub fn chain_err<F>(self, op: &fn(E) -> Result<T, F>) -> Result<T, F> {
pub fn or_else<F>(self, op: &fn(E) -> Result<T, F>) -> Result<T, F> {
match self {
Ok(t) => Ok(t),
Err(e) => op(e),
@ -430,21 +454,42 @@ mod tests {
use vec::ImmutableVector;
pub fn op1() -> Result<int, ~str> { Ok(666) }
pub fn op2(i: int) -> Result<uint, ~str> {
Ok(i as uint + 1u)
}
pub fn op3() -> Result<int, ~str> { Err(~"sadface") }
pub fn op2() -> Result<int, ~str> { Err(~"sadface") }
#[test]
pub fn chain_success() {
assert_eq!(op1().chain(op2).unwrap(), 667u);
pub fn test_and() {
assert_eq!(op1().and(Ok(667)).unwrap(), 667);
assert_eq!(op1().and(Err(~"bad")).unwrap_err(), ~"bad");
assert_eq!(op2().and(Ok(667)).unwrap_err(), ~"sadface");
assert_eq!(op2().and(Err(~"bad")).unwrap_err(), ~"sadface");
}
#[test]
pub fn chain_failure() {
assert_eq!(op3().chain( op2).unwrap_err(), ~"sadface");
pub fn test_and_then() {
assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
assert_eq!(op1().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"bad");
assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(), ~"sadface");
assert_eq!(op2().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"sadface");
}
#[test]
pub fn test_or() {
assert_eq!(op1().or(Ok(667)).unwrap(), 666);
assert_eq!(op1().or(Err(~"bad")).unwrap(), 666);
assert_eq!(op2().or(Ok(667)).unwrap(), 667);
assert_eq!(op2().or(Err(~"bad")).unwrap_err(), ~"bad");
}
#[test]
pub fn test_or_else() {
assert_eq!(op1().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 666);
assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);
assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(), ~"sadface!");
}
#[test]

View File

@ -177,7 +177,7 @@ impl<'self> Parser<'self> {
}
do self.read_atomically |p| {
p.read_char().chain(|c| parse_digit(c, radix))
p.read_char().and_then(|c| parse_digit(c, radix))
}
}

View File

@ -187,12 +187,12 @@ pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
-> Option<@str> {
attrs.iter()
.find(|at| name == at.name())
.chain(|at| at.value_str())
.and_then(|at| at.value_str())
}
pub fn last_meta_item_value_str_by_name(items: &[@MetaItem], name: &str)
-> Option<@str> {
items.rev_iter().find(|mi| name == mi.name()).chain(|i| i.value_str())
items.rev_iter().find(|mi| name == mi.name()).and_then(|i| i.value_str())
}
/* Higher-level applications */

View File

@ -331,11 +331,18 @@ pub fn expand_item_mac(extsbox: @mut SyntaxEnv,
};
let maybe_it = match expanded {
MRItem(it) => mark_item(it,fm).chain(|i| {fld.fold_item(i)}),
MRExpr(_) => cx.span_fatal(pth.span,
fmt!("expr macro in item position: %s", extnamestr)),
MRAny(_, item_maker, _) => item_maker().chain(|i| {mark_item(i,fm)})
.chain(|i| {fld.fold_item(i)}),
MRItem(it) => {
mark_item(it,fm)
.and_then(|i| fld.fold_item(i))
}
MRExpr(_) => {
cx.span_fatal(pth.span, fmt!("expr macro in item position: %s", extnamestr))
}
MRAny(_, item_maker, _) => {
item_maker()
.and_then(|i| mark_item(i,fm))
.and_then(|i| fld.fold_item(i))
}
MRDef(ref mdef) => {
// yikes... no idea how to apply the mark to this. I'm afraid
// we're going to have to wait-and-see on this one.