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

View File

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

View File

@@ -961,7 +961,7 @@ pub fn build_output_filenames(input: &input,
if !linkage_metas.is_empty() { if !linkage_metas.is_empty() {
// But if a linkage meta is present, that overrides // But if a linkage meta is present, that overrides
let maybe_name = linkage_metas.iter().find(|m| "name" == m.name()); 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, 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 { fn fold_mod(cx: @Context, m: &ast::_mod, fld: @fold::ast_fold) -> ast::_mod {
let filtered_items = do m.items.iter().filter_map |a| { 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(); }.collect();
let filtered_view_items = do m.view_items.iter().filter_map |a| { let filtered_view_items = do m.view_items.iter().filter_map |a| {
do filter_view_item(cx, a).map_move |x| { do filter_view_item(cx, a).map_move |x| {
@@ -139,7 +139,7 @@ fn fold_block(
fld: @fold::ast_fold fld: @fold::ast_fold
) -> ast::Block { ) -> ast::Block {
let resulting_stmts = do b.stmts.iter().filter_map |a| { 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(); }.collect();
let filtered_view_items = do b.view_items.iter().filter_map |a| { let filtered_view_items = do b.view_items.iter().filter_map |a| {
filter_view_item(cx, a).map(|x| fld.fold_view_item(*x)) 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 => { ast::named => {
let link_name = i.attrs.iter() let link_name = i.attrs.iter()
.find(|at| "link_name" == at.name()) .find(|at| "link_name" == at.name())
.chain(|at| at.value_str()); .and_then(|at| at.value_str());
let foreign_name = match link_name { let foreign_name = match link_name {
Some(nn) => { 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> { 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) } 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> { impl get_node_info for Option<@ast::Expr> {
fn info(&self) -> Option<NodeInfo> { 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 /// must be the only user of this value, and there must not be any conditional
/// branches between the store and the given block. /// branches between the store and the given block.
pub fn get_dominating_store(self, bcx: @mut Block) -> Option<Value> { 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) => { 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 bb = BasicBlock(bcx.llbb);
let mut ret = Some(store); let mut ret = Some(store);
while *bb != *store_bb { while *bb != *store_bb {
@@ -150,7 +150,7 @@ impl Iterator<Value> for UserIterator {
fn next(&mut self) -> Option<Value> { fn next(&mut self) -> Option<Value> {
let current = self.next; 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() } 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())); RegionParamNames(bound_lifetime_names.clone()));
let input_tys = do decl.inputs.iter().enumerate().map |(i, a)| { let input_tys = do decl.inputs.iter().enumerate().map |(i, a)| {
let expected_arg_ty = do expected_sig.chain_ref |e| { let expected_arg_ty = match expected_sig {
Some(ref e) => {
// no guarantee that the correct number of expected args // no guarantee that the correct number of expected args
// were supplied // were supplied
if i < e.inputs.len() {Some(e.inputs[i])} else {None} if i < e.inputs.len() {
Some(e.inputs[i])
} else {
None
}
}
None => None,
}; };
ty_of_arg(this, &rb, a, expected_arg_ty) ty_of_arg(this, &rb, a, expected_arg_ty)
}.collect(); }.collect();

View File

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

View File

@@ -232,7 +232,7 @@ impl CombineFieldsLatticeMethods for CombineFields {
(&Some(_), &None) => Ok((*a).clone()), (&Some(_), &None) => Ok((*a).clone()),
(&None, &Some(_)) => Ok((*b).clone()), (&None, &Some(_)) => Ok((*b).clone()),
(&Some(ref v_a), &Some(ref v_b)) => { (&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)) Ok(Some(v))
} }
} }

View File

@@ -62,7 +62,7 @@ impl Combine for Lub {
let m = a.mutbl; let m = a.mutbl;
match m { match m {
MutImmutable => { 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 => { MutMutable => {
@@ -70,7 +70,7 @@ impl Combine for Lub {
eq_tys(self, a.ty, b.ty).then(|| { eq_tys(self, a.ty, b.ty).then(|| {
Ok(ty::mt {ty: a.ty, mutbl: m}) 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 { impl then for ures {
fn then<T:Clone>(&self, f: &fn() -> Result<T,ty::type_err>) fn then<T:Clone>(&self, f: &fn() -> Result<T,ty::type_err>)
-> 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> { impl<T:Clone + Eq> CresCompare<T> for cres<T> {
fn compare(&self, t: T, f: &fn() -> ty::type_err) -> 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 { if s == t {
(*self).clone() (*self).clone()
} else { } else {

View File

@@ -79,7 +79,7 @@ impl Combine for Sub {
} }
MutImmutable => { MutImmutable => {
// Otherwise we can be covariant: // 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) { if !self.region_param_names.has_ident(id) {
return RegionParamNames::undeclared_name(None); 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 { result::Err(RegionError {
msg: ~"lifetime is not in scope", msg: ~"lifetime is not in scope",
replacement: ty::re_bound(ty::br_self) replacement: ty::re_bound(ty::br_self)
@@ -251,7 +251,7 @@ impl RegionScope for TypeRscope {
} }
fn named_region(&self, span: Span, id: ast::Ident) fn named_region(&self, span: Span, id: ast::Ident)
-> Result<ty::Region, RegionError> { -> 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 { result::Err(RegionError {
msg: ~"only 'self is allowed as part of a type declaration", msg: ~"only 'self is allowed as part of a type declaration",
replacement: self.replacement() replacement: self.replacement()
@@ -310,7 +310,7 @@ impl RegionScope for BindingRscope {
span: Span, span: Span,
id: ast::Ident) -> Result<ty::Region, RegionError> 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)); let result = ty::re_bound(ty::br_named(id));
if self.region_param_names.has_ident(id) { if self.region_param_names.has_ident(id) {
result::Ok(result) result::Ok(result)

View File

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

View File

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

View File

@@ -1618,7 +1618,7 @@ impl<T:Writer> WriterUtil for T {
} }
pub fn file_writer(path: &Path, flags: &[FileFlag]) -> Result<@Writer, ~str> { 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> { 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) { if str::is_utf8(bytes) {
Ok(str::from_utf8(bytes)) Ok(str::from_utf8(bytes))
} else { } 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 // FIXME (#2004): implement this in a low-level way. Going through the
// abstractions is pointless. // abstractions is pointless.
pub fn read_whole_file(file: &Path) -> Result<~[u8], ~str> { 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()) 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> { impl<'self, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'self, A, B, T, St> {
#[inline] #[inline]
fn next(&mut self) -> Option<B> { 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] #[inline]
@@ -1494,8 +1494,7 @@ pub struct FlatMap<'self, A, T, U> {
priv backiter: Option<U>, priv backiter: Option<U>,
} }
impl<'self, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for impl<'self, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for FlatMap<'self, A, T, U> {
FlatMap<'self, A, T, U> {
#[inline] #[inline]
fn next(&mut self) -> Option<B> { fn next(&mut self) -> Option<B> {
loop { 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)) { 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, next => self.frontiter = next,
} }
} }
@@ -1537,7 +1541,12 @@ impl<'self,
} }
} }
match self.iter.next_back().map_move(|x| (self.f)(x)) { 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, 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 /// Returns `None` if the option is `None`, otherwise calls and returns the
/// value of `f`. /// value of `f`.
#[inline] #[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 { match self {
Some(_) => f(), Some(x) => f(x),
None => None, 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. /// Filters an optional value using given function.
#[inline(always)] #[inline(always)]
pub fn filtered(self, f: &fn(t: &T) -> bool) -> Option<T> { pub fn filtered(self, f: &fn(t: &T) -> bool) -> Option<T> {
@@ -637,12 +607,12 @@ mod tests {
#[test] #[test]
fn test_and_then() { fn test_and_then() {
let x: Option<int> = Some(1); let x: Option<int> = Some(1);
assert_eq!(x.and_then(|| Some(2)), Some(2)); assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
assert_eq!(x.and_then(|| None), None); assert_eq!(x.and_then(|_| None::<int>), None);
let x: Option<int> = None; let x: Option<int> = None;
assert_eq!(x.and_then(|| Some(2)), None); assert_eq!(x.and_then(|x| Some(x + 1)), None);
assert_eq!(x.and_then(|| None), None); assert_eq!(x.and_then(|_| None::<int>), None);
} }
#[test] #[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 /// Call a method based on a previous result
/// ///
/// If `self` is `Ok` then the value is extracted and passed to `op` /// 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 /// immediately returned. This function can be used to compose the results
/// of two functions. /// of two functions.
/// ///
@@ -184,13 +196,25 @@ impl<T, E: ToStr> Result<T, E> {
/// Ok(parse_bytes(buf)) /// Ok(parse_bytes(buf))
/// }; /// };
#[inline] #[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 { match self {
Ok(t) => op(t), Ok(t) => op(t),
Err(e) => Err(e), 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 /// Call a function based on a previous result
/// ///
/// If `self` is `Err` then the value is extracted and passed to `op` /// 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 /// immediately returned. This function can be used to pass through a
/// successful result while handling an error. /// successful result while handling an error.
#[inline] #[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 { match self {
Ok(t) => Ok(t), Ok(t) => Ok(t),
Err(e) => op(e), Err(e) => op(e),
@@ -430,21 +454,42 @@ mod tests {
use vec::ImmutableVector; use vec::ImmutableVector;
pub fn op1() -> Result<int, ~str> { Ok(666) } pub fn op1() -> Result<int, ~str> { Ok(666) }
pub fn op2() -> Result<int, ~str> { Err(~"sadface") }
pub fn op2(i: int) -> Result<uint, ~str> {
Ok(i as uint + 1u)
}
pub fn op3() -> Result<int, ~str> { Err(~"sadface") }
#[test] #[test]
pub fn chain_success() { pub fn test_and() {
assert_eq!(op1().chain(op2).unwrap(), 667u); 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] #[test]
pub fn chain_failure() { pub fn test_and_then() {
assert_eq!(op3().chain( op2).unwrap_err(), ~"sadface"); 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] #[test]

View File

@@ -177,7 +177,7 @@ impl<'self> Parser<'self> {
} }
do self.read_atomically |p| { 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> { -> Option<@str> {
attrs.iter() attrs.iter()
.find(|at| name == at.name()) .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) pub fn last_meta_item_value_str_by_name(items: &[@MetaItem], name: &str)
-> Option<@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 */ /* Higher-level applications */

View File

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