Skip to content

Commit 2aa578e

Browse files
committed
auto merge of #9115 : erickt/rust/master, r=erickt
This is a series of patches to modernize option and result. The highlights are: * rename `.unwrap_or_default(value)` and etc to `.unwrap_or(value)` * add `.unwrap_or_default()` that uses the `Default` trait * add `Default` implementations for vecs, HashMap, Option * add `Option.and(T) -> Option<T>`, `Option.and_then(&fn() -> Option<T>) -> Option<T>`, `Option.or(T) -> Option<T>`, and `Option.or_else(&fn() -> Option<T>) -> Option<T>` * add `option::ToOption`, `option::IntoOption`, `option::AsOption`, `result::ToResult`, `result::IntoResult`, `result::AsResult`, `either::ToEither`, and `either::IntoEither`, `either::AsEither` * renamed `Option::chain*` and `Result::chain*` to `and_then` and `or_else` to avoid the eventual collision with `Iterator.chain`. * Added a bunch of impls of `Default` * Added a `#[deriving(Default)]` syntax extension * Removed impls of `Zero` for `Option<T>` and vecs.
2 parents 4ac10f8 + 93683ae commit 2aa578e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

55 files changed

+1099
-227
lines changed

doc/rust.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1717,7 +1717,8 @@ Supported traits for `deriving` are:
17171717
* `Clone` and `DeepClone`, to perform (deep) copies.
17181718
* `IterBytes`, to iterate over the bytes in a data type.
17191719
* `Rand`, to create a random instance of a data type.
1720-
* `Zero`, to create an zero (or empty) instance of a data type.
1720+
* `Default`, to create an empty instance of a data type.
1721+
* `Zero`, to create an zero instance of a numeric data type.
17211722
* `ToStr`, to convert to a string. For a type with this instance,
17221723
`obj.to_str()` has similar output as `fmt!("%?", obj)`, but it differs in that
17231724
each constituent field of the type must also implement `ToStr` and will have

doc/tutorial.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -2249,7 +2249,7 @@ enum ABC { A, B, C }
22492249

22502250
The full list of derivable traits is `Eq`, `TotalEq`, `Ord`,
22512251
`TotalOrd`, `Encodable` `Decodable`, `Clone`, `DeepClone`,
2252-
`IterBytes`, `Rand`, `Zero`, and `ToStr`.
2252+
`IterBytes`, `Rand`, `Default`, `Zero`, and `ToStr`.
22532253

22542254
# Crates and the module system
22552255

src/compiletest/compiletest.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ pub fn make_test_name(config: &config, testfile: &Path) -> test::TestName {
309309
let filename = path.filename();
310310
let p = path.pop();
311311
let dir = p.filename();
312-
fmt!("%s/%s", dir.unwrap_or_default(""), filename.unwrap_or_default(""))
312+
fmt!("%s/%s", dir.unwrap_or(""), filename.unwrap_or(""))
313313
}
314314

315315
test::DynTestName(fmt!("[%s] %s",

src/libextra/glob.rs

+43-3
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,17 @@ fn list_dir_sorted(path: &Path) -> ~[Path] {
137137
/**
138138
* A compiled Unix shell style pattern.
139139
*/
140-
#[deriving(Clone, Eq, TotalEq, Ord, TotalOrd, IterBytes, Zero)]
140+
#[cfg(stage0)]
141+
#[deriving(Clone, Eq, TotalEq, Ord, TotalOrd, IterBytes)]
142+
pub struct Pattern {
143+
priv tokens: ~[PatternToken]
144+
}
145+
146+
/**
147+
* A compiled Unix shell style pattern.
148+
*/
149+
#[cfg(not(stage0))]
150+
#[deriving(Clone, Eq, TotalEq, Ord, TotalOrd, IterBytes, Default)]
141151
pub struct Pattern {
142152
priv tokens: ~[PatternToken]
143153
}
@@ -312,7 +322,7 @@ impl Pattern {
312322
let require_literal = |c| {
313323
(options.require_literal_separator && is_sep(c)) ||
314324
(options.require_literal_leading_dot && c == '.'
315-
&& is_sep(prev_char.unwrap_or_default('/')))
325+
&& is_sep(prev_char.unwrap_or('/')))
316326
};
317327
318328
for (ti, token) in self.tokens.slice_from(i).iter().enumerate() {
@@ -458,7 +468,37 @@ fn is_sep(c: char) -> bool {
458468
/**
459469
* Configuration options to modify the behaviour of `Pattern::matches_with(..)`
460470
*/
461-
#[deriving(Clone, Eq, TotalEq, Ord, TotalOrd, IterBytes, Zero)]
471+
#[cfg(stage0)]
472+
#[deriving(Clone, Eq, TotalEq, Ord, TotalOrd, IterBytes)]
473+
pub struct MatchOptions {
474+
475+
/**
476+
* Whether or not patterns should be matched in a case-sensitive manner. This
477+
* currently only considers upper/lower case relationships between ASCII characters,
478+
* but in future this might be extended to work with Unicode.
479+
*/
480+
case_sensitive: bool,
481+
482+
/**
483+
* If this is true then path-component separator characters (e.g. `/` on Posix)
484+
* must be matched by a literal `/`, rather than by `*` or `?` or `[...]`
485+
*/
486+
require_literal_separator: bool,
487+
488+
/**
489+
* If this is true then paths that contain components that start with a `.` will
490+
* not match unless the `.` appears literally in the pattern: `*`, `?` or `[...]`
491+
* will not match. This is useful because such files are conventionally considered
492+
* hidden on Unix systems and it might be desirable to skip them when listing files.
493+
*/
494+
require_literal_leading_dot: bool
495+
}
496+
497+
/**
498+
* Configuration options to modify the behaviour of `Pattern::matches_with(..)`
499+
*/
500+
#[cfg(not(stage0))]
501+
#[deriving(Clone, Eq, TotalEq, Ord, TotalOrd, IterBytes, Default)]
462502
pub struct MatchOptions {
463503
464504
/**

src/libextra/num/bigint.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -635,7 +635,7 @@ impl BigUint {
635635

636636
// Converts this BigUint into an int, unless it would overflow.
637637
pub fn to_int_opt(&self) -> Option<int> {
638-
self.to_uint_opt().chain(|n| {
638+
self.to_uint_opt().and_then(|n| {
639639
// If top bit of uint is set, it's too large to convert to
640640
// int.
641641
if (n >> (2*BigDigit::bits - 1) != 0) {
@@ -1221,7 +1221,7 @@ impl BigInt {
12211221
match self.sign {
12221222
Plus => self.data.to_int_opt(),
12231223
Zero => Some(0),
1224-
Minus => self.data.to_uint_opt().chain(|n| {
1224+
Minus => self.data.to_uint_opt().and_then(|n| {
12251225
let m: uint = 1 << (2*BigDigit::bits-1);
12261226
if (n > m) {
12271227
None

src/libextra/num/rational.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -273,9 +273,9 @@ impl<T: FromStr + Clone + Integer + Ord>
273273
return None
274274
}
275275
let a_option: Option<T> = FromStr::from_str(split[0]);
276-
do a_option.chain |a| {
276+
do a_option.and_then |a| {
277277
let b_option: Option<T> = FromStr::from_str(split[1]);
278-
do b_option.chain |b| {
278+
do b_option.and_then |b| {
279279
Some(Ratio::new(a.clone(), b.clone()))
280280
}
281281
}
@@ -291,10 +291,10 @@ impl<T: FromStrRadix + Clone + Integer + Ord>
291291
} else {
292292
let a_option: Option<T> = FromStrRadix::from_str_radix(split[0],
293293
radix);
294-
do a_option.chain |a| {
294+
do a_option.and_then |a| {
295295
let b_option: Option<T> =
296296
FromStrRadix::from_str_radix(split[1], radix);
297-
do b_option.chain |b| {
297+
do b_option.and_then |b| {
298298
Some(Ratio::new(a.clone(), b.clone()))
299299
}
300300
}

src/libextra/time.rs

+32-32
Original file line numberDiff line numberDiff line change
@@ -442,21 +442,21 @@ fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
442442
},
443443
'c' => {
444444
parse_type(s, pos, 'a', &mut *tm)
445-
.chain(|pos| parse_char(s, pos, ' '))
446-
.chain(|pos| parse_type(s, pos, 'b', &mut *tm))
447-
.chain(|pos| parse_char(s, pos, ' '))
448-
.chain(|pos| parse_type(s, pos, 'e', &mut *tm))
449-
.chain(|pos| parse_char(s, pos, ' '))
450-
.chain(|pos| parse_type(s, pos, 'T', &mut *tm))
451-
.chain(|pos| parse_char(s, pos, ' '))
452-
.chain(|pos| parse_type(s, pos, 'Y', &mut *tm))
445+
.and_then(|pos| parse_char(s, pos, ' '))
446+
.and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
447+
.and_then(|pos| parse_char(s, pos, ' '))
448+
.and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
449+
.and_then(|pos| parse_char(s, pos, ' '))
450+
.and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
451+
.and_then(|pos| parse_char(s, pos, ' '))
452+
.and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
453453
}
454454
'D' | 'x' => {
455455
parse_type(s, pos, 'm', &mut *tm)
456-
.chain(|pos| parse_char(s, pos, '/'))
457-
.chain(|pos| parse_type(s, pos, 'd', &mut *tm))
458-
.chain(|pos| parse_char(s, pos, '/'))
459-
.chain(|pos| parse_type(s, pos, 'y', &mut *tm))
456+
.and_then(|pos| parse_char(s, pos, '/'))
457+
.and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
458+
.and_then(|pos| parse_char(s, pos, '/'))
459+
.and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
460460
}
461461
'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
462462
31_i32) {
@@ -475,10 +475,10 @@ fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
475475
}
476476
'F' => {
477477
parse_type(s, pos, 'Y', &mut *tm)
478-
.chain(|pos| parse_char(s, pos, '-'))
479-
.chain(|pos| parse_type(s, pos, 'm', &mut *tm))
480-
.chain(|pos| parse_char(s, pos, '-'))
481-
.chain(|pos| parse_type(s, pos, 'd', &mut *tm))
478+
.and_then(|pos| parse_char(s, pos, '-'))
479+
.and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
480+
.and_then(|pos| parse_char(s, pos, '-'))
481+
.and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
482482
}
483483
'H' => {
484484
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> {
553553
},
554554
'R' => {
555555
parse_type(s, pos, 'H', &mut *tm)
556-
.chain(|pos| parse_char(s, pos, ':'))
557-
.chain(|pos| parse_type(s, pos, 'M', &mut *tm))
556+
.and_then(|pos| parse_char(s, pos, ':'))
557+
.and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
558558
}
559559
'r' => {
560560
parse_type(s, pos, 'I', &mut *tm)
561-
.chain(|pos| parse_char(s, pos, ':'))
562-
.chain(|pos| parse_type(s, pos, 'M', &mut *tm))
563-
.chain(|pos| parse_char(s, pos, ':'))
564-
.chain(|pos| parse_type(s, pos, 'S', &mut *tm))
565-
.chain(|pos| parse_char(s, pos, ' '))
566-
.chain(|pos| parse_type(s, pos, 'p', &mut *tm))
561+
.and_then(|pos| parse_char(s, pos, ':'))
562+
.and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
563+
.and_then(|pos| parse_char(s, pos, ':'))
564+
.and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
565+
.and_then(|pos| parse_char(s, pos, ' '))
566+
.and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
567567
}
568568
'S' => {
569569
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> {
578578
//'s' {}
579579
'T' | 'X' => {
580580
parse_type(s, pos, 'H', &mut *tm)
581-
.chain(|pos| parse_char(s, pos, ':'))
582-
.chain(|pos| parse_type(s, pos, 'M', &mut *tm))
583-
.chain(|pos| parse_char(s, pos, ':'))
584-
.chain(|pos| parse_type(s, pos, 'S', &mut *tm))
581+
.and_then(|pos| parse_char(s, pos, ':'))
582+
.and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
583+
.and_then(|pos| parse_char(s, pos, ':'))
584+
.and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
585585
}
586586
't' => parse_char(s, pos, '\t'),
587587
'u' => {
@@ -596,10 +596,10 @@ fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
596596
}
597597
'v' => {
598598
parse_type(s, pos, 'e', &mut *tm)
599-
.chain(|pos| parse_char(s, pos, '-'))
600-
.chain(|pos| parse_type(s, pos, 'b', &mut *tm))
601-
.chain(|pos| parse_char(s, pos, '-'))
602-
.chain(|pos| parse_type(s, pos, 'Y', &mut *tm))
599+
.and_then(|pos| parse_char(s, pos, '-'))
600+
.and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
601+
.and_then(|pos| parse_char(s, pos, '-'))
602+
.and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
603603
}
604604
//'W' {}
605605
'w' => {

src/libextra/uuid.rs

+7
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,13 @@ impl Uuid {
417417
}
418418
}
419419

420+
impl Default for Uuid {
421+
/// Returns the nil UUID, which is all zeroes
422+
fn default() -> Uuid {
423+
Uuid::new_nil()
424+
}
425+
}
426+
420427
impl Zero for Uuid {
421428
/// Returns the nil UUID, which is all zeroes
422429
fn zero() -> Uuid {

src/librustc/driver/driver.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -681,9 +681,9 @@ pub fn build_session_options(binary: @str,
681681
link::output_type_bitcode
682682
} else { link::output_type_exe };
683683
let sysroot_opt = getopts::opt_maybe_str(matches, "sysroot").map_move(|m| @Path(m));
684-
let target = getopts::opt_maybe_str(matches, "target").unwrap_or_default(host_triple());
685-
let target_cpu = getopts::opt_maybe_str(matches, "target-cpu").unwrap_or_default(~"generic");
686-
let target_feature = getopts::opt_maybe_str(matches, "target-feature").unwrap_or_default(~"");
684+
let target = getopts::opt_maybe_str(matches, "target").unwrap_or(host_triple());
685+
let target_cpu = getopts::opt_maybe_str(matches, "target-cpu").unwrap_or(~"generic");
686+
let target_feature = getopts::opt_maybe_str(matches, "target-feature").unwrap_or(~"");
687687
let save_temps = getopts::opt_present(matches, "save-temps");
688688
let opt_level = {
689689
if (debugging_opts & session::no_opt) != 0 {
@@ -961,7 +961,7 @@ pub fn build_output_filenames(input: &input,
961961
if !linkage_metas.is_empty() {
962962
// But if a linkage meta is present, that overrides
963963
let maybe_name = linkage_metas.iter().find(|m| "name" == m.name());
964-
match maybe_name.chain(|m| m.value_str()) {
964+
match maybe_name.and_then(|m| m.value_str()) {
965965
Some(s) => stem = s,
966966
_ => ()
967967
}

src/librustc/front/config.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ fn filter_view_item<'r>(cx: @Context, view_item: &'r ast::view_item)-> Option<&'
5858

5959
fn fold_mod(cx: @Context, m: &ast::_mod, fld: @fold::ast_fold) -> ast::_mod {
6060
let filtered_items = do m.items.iter().filter_map |a| {
61-
filter_item(cx, *a).chain(|x| fld.fold_item(x))
61+
filter_item(cx, *a).and_then(|x| fld.fold_item(x))
6262
}.collect();
6363
let filtered_view_items = do m.view_items.iter().filter_map |a| {
6464
do filter_view_item(cx, a).map_move |x| {
@@ -139,7 +139,7 @@ fn fold_block(
139139
fld: @fold::ast_fold
140140
) -> ast::Block {
141141
let resulting_stmts = do b.stmts.iter().filter_map |a| {
142-
filter_stmt(cx, *a).chain(|stmt| fld.fold_stmt(stmt))
142+
filter_stmt(cx, *a).and_then(|stmt| fld.fold_stmt(stmt))
143143
}.collect();
144144
let filtered_view_items = do b.view_items.iter().filter_map |a| {
145145
filter_view_item(cx, a).map(|x| fld.fold_view_item(*x))

src/librustc/metadata/creader.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ fn visit_item(e: &Env, i: @ast::item) {
184184
ast::named => {
185185
let link_name = i.attrs.iter()
186186
.find(|at| "link_name" == at.name())
187-
.chain(|at| at.value_str());
187+
.and_then(|at| at.value_str());
188188

189189
let foreign_name = match link_name {
190190
Some(nn) => {

src/librustc/metadata/decoder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ fn each_reexport(d: ebml::Doc, f: &fn(ebml::Doc) -> bool) -> bool {
210210
}
211211

212212
fn variant_disr_val(d: ebml::Doc) -> Option<ty::Disr> {
213-
do reader::maybe_get_doc(d, tag_disr_val).chain |val_doc| {
213+
do reader::maybe_get_doc(d, tag_disr_val).and_then |val_doc| {
214214
do reader::with_doc_data(val_doc) |data| { u64::parse_bytes(data, 10u) }
215215
}
216216
}

src/librustc/middle/privacy.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -221,8 +221,7 @@ impl PrivacyVisitor {
221221
// If the method is a default method, we need to use the def_id of
222222
// the default implementation.
223223
// Having to do this this is really unfortunate.
224-
let method_id = ty::method(self.tcx, method_id).provided_source
225-
.unwrap_or_default(method_id);
224+
let method_id = ty::method(self.tcx, method_id).provided_source.unwrap_or(method_id);
226225

227226
if method_id.crate == LOCAL_CRATE {
228227
let is_private = self.method_is_private(span, method_id.node);

src/librustc/middle/trans/common.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ impl get_node_info for ast::Block {
505505

506506
impl get_node_info for Option<@ast::Expr> {
507507
fn info(&self) -> Option<NodeInfo> {
508-
self.chain_ref(|s| s.info())
508+
self.and_then_ref(|s| s.info())
509509
}
510510
}
511511

src/librustc/middle/trans/value.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,9 @@ impl Value {
5050
/// must be the only user of this value, and there must not be any conditional
5151
/// branches between the store and the given block.
5252
pub fn get_dominating_store(self, bcx: @mut Block) -> Option<Value> {
53-
match self.get_single_user().chain(|user| user.as_store_inst()) {
53+
match self.get_single_user().and_then(|user| user.as_store_inst()) {
5454
Some(store) => {
55-
do store.get_parent().chain |store_bb| {
55+
do store.get_parent().and_then |store_bb| {
5656
let mut bb = BasicBlock(bcx.llbb);
5757
let mut ret = Some(store);
5858
while *bb != *store_bb {
@@ -150,7 +150,7 @@ impl Iterator<Value> for UserIterator {
150150
fn next(&mut self) -> Option<Value> {
151151
let current = self.next;
152152

153-
self.next = do current.chain |u| { u.get_next_use() };
153+
self.next = do current.and_then |u| { u.get_next_use() };
154154

155155
do current.map |u| { u.get_user() }
156156
}

src/librustc/middle/typeck/astconv.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -745,7 +745,7 @@ pub fn ty_of_closure<AC:AstConv,RS:RegionScope + Clone + 'static>(
745745
RegionParamNames(bound_lifetime_names.clone()));
746746

747747
let input_tys = do decl.inputs.iter().enumerate().map |(i, a)| {
748-
let expected_arg_ty = do expected_sig.chain_ref |e| {
748+
let expected_arg_ty = do expected_sig.and_then_ref |e| {
749749
// no guarantee that the correct number of expected args
750750
// were supplied
751751
if i < e.inputs.len() {Some(e.inputs[i])} else {None}

src/librustc/middle/typeck/check/_match.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ pub fn check_pat_variant(pcx: &pat_ctxt, pat: @ast::Pat, path: &ast::Path,
173173
fcx.write_error(pat.id);
174174
kind_name = "[error]";
175175
arg_types = (*subpats).clone()
176-
.unwrap_or_default(~[])
176+
.unwrap_or_default()
177177
.map(|_| ty::mk_err());
178178
}
179179
}
@@ -222,7 +222,7 @@ pub fn check_pat_variant(pcx: &pat_ctxt, pat: @ast::Pat, path: &ast::Path,
222222
fcx.write_error(pat.id);
223223
kind_name = "[error]";
224224
arg_types = (*subpats).clone()
225-
.unwrap_or_default(~[])
225+
.unwrap_or_default()
226226
.map(|_| ty::mk_err());
227227
}
228228
}

0 commit comments

Comments
 (0)