1
Fork 0

Convert core::result to camel case

This commit is contained in:
Brian Anderson 2012-08-26 16:54:31 -07:00
parent 3a1582012e
commit 0c6e470a25
52 changed files with 844 additions and 844 deletions

View file

@ -7,7 +7,7 @@ import rustc::metadata::filesearch::{get_cargo_root, get_cargo_root_nearest,
get_cargo_sysroot, libdir}; get_cargo_sysroot, libdir};
import syntax::diagnostic; import syntax::diagnostic;
import result::{ok, err}; import result::{Ok, Err};
import io::WriterUtil; import io::WriterUtil;
import std::{map, json, tempfile, term, sort, getopts}; import std::{map, json, tempfile, term, sort, getopts};
import map::hashmap; import map::hashmap;
@ -429,14 +429,14 @@ fn try_parse_sources(filename: &Path, sources: map::hashmap<~str, source>) {
if !os::path_exists(filename) { return; } if !os::path_exists(filename) { return; }
let c = io::read_whole_file_str(filename); let c = io::read_whole_file_str(filename);
match json::from_str(result::get(c)) { match json::from_str(result::get(c)) {
ok(json::dict(j)) => { Ok(json::dict(j)) => {
for j.each |k, v| { for j.each |k, v| {
sources.insert(k, parse_source(k, v)); sources.insert(k, parse_source(k, v));
debug!("source: %s", k); debug!("source: %s", k);
} }
} }
ok(_) => fail ~"malformed sources.json", Ok(_) => fail ~"malformed sources.json",
err(e) => fail fmt!("%s:%s", filename.to_str(), e.to_str()) Err(e) => fail fmt!("%s:%s", filename.to_str(), e.to_str())
} }
} }
@ -548,17 +548,17 @@ fn load_source_info(c: cargo, src: source) {
if !os::path_exists(&srcfile) { return; } if !os::path_exists(&srcfile) { return; }
let srcstr = io::read_whole_file_str(&srcfile); let srcstr = io::read_whole_file_str(&srcfile);
match json::from_str(result::get(srcstr)) { match json::from_str(result::get(srcstr)) {
ok(json::dict(s)) => { Ok(json::dict(s)) => {
let o = parse_source(src.name, json::dict(s)); let o = parse_source(src.name, json::dict(s));
src.key = o.key; src.key = o.key;
src.keyfp = o.keyfp; src.keyfp = o.keyfp;
} }
ok(_) => { Ok(_) => {
warn(~"malformed source.json: " + src.name + warn(~"malformed source.json: " + src.name +
~"(source info is not a dict)"); ~"(source info is not a dict)");
} }
err(e) => { Err(e) => {
warn(fmt!("%s:%s", src.name, e.to_str())); warn(fmt!("%s:%s", src.name, e.to_str()));
} }
}; };
@ -570,7 +570,7 @@ fn load_source_packages(c: cargo, src: source) {
if !os::path_exists(&pkgfile) { return; } if !os::path_exists(&pkgfile) { return; }
let pkgstr = io::read_whole_file_str(&pkgfile); let pkgstr = io::read_whole_file_str(&pkgfile);
match json::from_str(result::get(pkgstr)) { match json::from_str(result::get(pkgstr)) {
ok(json::list(js)) => { Ok(json::list(js)) => {
for (*js).each |j| { for (*js).each |j| {
match j { match j {
json::dict(p) => { json::dict(p) => {
@ -583,11 +583,11 @@ fn load_source_packages(c: cargo, src: source) {
} }
} }
} }
ok(_) => { Ok(_) => {
warn(~"malformed packages.json: " + src.name + warn(~"malformed packages.json: " + src.name +
~"(packages is not a list)"); ~"(packages is not a list)");
} }
err(e) => { Err(e) => {
warn(fmt!("%s:%s", src.name, e.to_str())); warn(fmt!("%s:%s", src.name, e.to_str()));
} }
}; };
@ -595,8 +595,8 @@ fn load_source_packages(c: cargo, src: source) {
fn build_cargo_options(argv: ~[~str]) -> options { fn build_cargo_options(argv: ~[~str]) -> options {
let matches = match getopts::getopts(argv, opts()) { let matches = match getopts::getopts(argv, opts()) {
result::ok(m) => m, result::Ok(m) => m,
result::err(f) => { result::Err(f) => {
fail fmt!("%s", getopts::fail_str(f)); fail fmt!("%s", getopts::fail_str(f));
} }
}; };
@ -626,8 +626,8 @@ fn build_cargo_options(argv: ~[~str]) -> options {
fn configure(opts: options) -> cargo { fn configure(opts: options) -> cargo {
let home = match get_cargo_root() { let home = match get_cargo_root() {
ok(home) => home, Ok(home) => home,
err(_err) => result::get(get_cargo_sysroot()) Err(_err) => result::get(get_cargo_sysroot())
}; };
let get_cargo_dir = match opts.mode { let get_cargo_dir = match opts.mode {
@ -1571,7 +1571,7 @@ fn dump_sources(c: cargo) {
} }
match io::buffered_file_writer(&out) { match io::buffered_file_writer(&out) {
result::ok(writer) => { result::Ok(writer) => {
let hash = map::str_hash(); let hash = map::str_hash();
let root = json::dict(hash); let root = json::dict(hash);
@ -1600,7 +1600,7 @@ fn dump_sources(c: cargo) {
writer.write_str(json::to_str(root)); writer.write_str(json::to_str(root));
} }
result::err(e) => { result::Err(e) => {
error(fmt!("could not dump sources: %s", e)); error(fmt!("could not dump sources: %s", e));
} }
} }

View file

@ -6,7 +6,7 @@ import vec;
import task; import task;
import core::result; import core::result;
import result::{ok, err}; import result::{Ok, Err};
import common::config; import common::config;
import common::mode_run_pass; import common::mode_run_pass;
@ -38,8 +38,8 @@ fn parse_config(args: ~[~str]) -> config {
let args_ = vec::tail(args); let args_ = vec::tail(args);
let matches = let matches =
match getopts::getopts(args_, opts) { match getopts::getopts(args_, opts) {
ok(m) => m, Ok(m) => m,
err(f) => fail getopts::fail_str(f) Err(f) => fail getopts::fail_str(f)
}; };
fn opt_path(m: getopts::matches, nm: ~str) -> Path { fn opt_path(m: getopts::matches, nm: ~str) -> Path {

View file

@ -4,7 +4,7 @@
//! A type that represents one of two alternatives //! A type that represents one of two alternatives
import result::result; import result::Result;
/// The either type /// The either type
enum Either<T, U> { enum Either<T, U> {
@ -83,7 +83,7 @@ pure fn flip<T: copy, U: copy>(eith: &Either<T, U>) -> Either<U, T> {
} }
} }
pure fn to_result<T: copy, U: copy>(eith: &Either<T, U>) -> result<U, T> { pure fn to_result<T: copy, U: copy>(eith: &Either<T, U>) -> Result<U, T> {
/*! /*!
* Converts either::t to a result::t * Converts either::t to a result::t
* *
@ -92,8 +92,8 @@ pure fn to_result<T: copy, U: copy>(eith: &Either<T, U>) -> result<U, T> {
*/ */
match *eith { match *eith {
Right(r) => result::ok(r), Right(r) => result::Ok(r),
Left(l) => result::err(l) Left(l) => result::Err(l)
} }
} }

View file

@ -4,7 +4,7 @@ Module: io
Basic input/output Basic input/output
*/ */
import result::result; import result::Result;
import dvec::{DVec, dvec}; import dvec::{DVec, dvec};
import libc::{c_int, c_long, c_uint, c_void, size_t, ssize_t}; import libc::{c_int, c_long, c_uint, c_void, size_t, ssize_t};
@ -264,16 +264,16 @@ fn FILE_reader(f: *libc::FILE, cleanup: bool) -> Reader {
fn stdin() -> Reader { rustrt::rust_get_stdin() as Reader } fn stdin() -> Reader { rustrt::rust_get_stdin() as Reader }
fn file_reader(path: &Path) -> result<Reader, ~str> { fn file_reader(path: &Path) -> Result<Reader, ~str> {
let f = os::as_c_charp(path.to_str(), |pathbuf| { let f = os::as_c_charp(path.to_str(), |pathbuf| {
os::as_c_charp("r", |modebuf| os::as_c_charp("r", |modebuf|
libc::fopen(pathbuf, modebuf) libc::fopen(pathbuf, modebuf)
) )
}); });
return if f as uint == 0u { result::err(~"error opening " return if f as uint == 0u { result::Err(~"error opening "
+ path.to_str()) } + path.to_str()) }
else { else {
result::ok(FILE_reader(f, true)) result::Ok(FILE_reader(f, true))
} }
} }
@ -421,7 +421,7 @@ fn fd_writer(fd: fd_t, cleanup: bool) -> Writer {
fn mk_file_writer(path: &Path, flags: ~[FileFlag]) fn mk_file_writer(path: &Path, flags: ~[FileFlag])
-> result<Writer, ~str> { -> Result<Writer, ~str> {
#[cfg(windows)] #[cfg(windows)]
fn wb() -> c_int { (O_WRONLY | O_BINARY) as c_int } fn wb() -> c_int { (O_WRONLY | O_BINARY) as c_int }
@ -443,10 +443,10 @@ fn mk_file_writer(path: &Path, flags: ~[FileFlag])
(S_IRUSR | S_IWUSR) as c_int) (S_IRUSR | S_IWUSR) as c_int)
}; };
if fd < (0 as c_int) { if fd < (0 as c_int) {
result::err(fmt!("error opening %s: %s", path.to_str(), result::Err(fmt!("error opening %s: %s", path.to_str(),
os::last_os_error())) os::last_os_error()))
} else { } else {
result::ok(fd_writer(fd, true)) result::Ok(fd_writer(fd, true))
} }
} }
@ -623,21 +623,21 @@ impl<T: Writer> T : WriterUtil {
fn write_u8(n: u8) { self.write(&[n]) } fn write_u8(n: u8) { self.write(&[n]) }
} }
fn file_writer(path: &Path, flags: ~[FileFlag]) -> result<Writer, ~str> { fn file_writer(path: &Path, flags: ~[FileFlag]) -> Result<Writer, ~str> {
result::chain(mk_file_writer(path, flags), |w| result::ok(w)) result::chain(mk_file_writer(path, flags), |w| result::Ok(w))
} }
// FIXME: fileflags // #2004 // FIXME: fileflags // #2004
fn buffered_file_writer(path: &Path) -> result<Writer, ~str> { fn buffered_file_writer(path: &Path) -> Result<Writer, ~str> {
let f = do os::as_c_charp(path.to_str()) |pathbuf| { let f = do os::as_c_charp(path.to_str()) |pathbuf| {
do os::as_c_charp("w") |modebuf| { do os::as_c_charp("w") |modebuf| {
libc::fopen(pathbuf, modebuf) libc::fopen(pathbuf, modebuf)
} }
}; };
return if f as uint == 0u { result::err(~"error opening " return if f as uint == 0u { result::Err(~"error opening "
+ path.to_str()) } + path.to_str()) }
else { result::ok(FILE_writer(f, true)) } else { result::Ok(FILE_writer(f, true)) }
} }
// FIXME (#2004) it would be great if this could be a const // FIXME (#2004) it would be great if this could be a const
@ -719,21 +719,21 @@ fn seek_in_buf(offset: int, pos: uint, len: uint, whence: SeekStyle) ->
return bpos as uint; return bpos as uint;
} }
fn read_whole_file_str(file: &Path) -> result<~str, ~str> { fn read_whole_file_str(file: &Path) -> Result<~str, ~str> {
result::chain(read_whole_file(file), |bytes| { result::chain(read_whole_file(file), |bytes| {
if str::is_utf8(bytes) { if str::is_utf8(bytes) {
result::ok(str::from_bytes(bytes)) result::Ok(str::from_bytes(bytes))
} else { } else {
result::err(file.to_str() + ~" is not UTF-8") result::Err(file.to_str() + ~" is not UTF-8")
} }
}) })
} }
// 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.
fn read_whole_file(file: &Path) -> result<~[u8], ~str> { fn read_whole_file(file: &Path) -> Result<~[u8], ~str> {
result::chain(file_reader(file), |rdr| { result::chain(file_reader(file), |rdr| {
result::ok(rdr.read_whole_stream()) result::Ok(rdr.read_whole_stream())
}) })
} }
@ -892,30 +892,30 @@ mod tests {
#[test] #[test]
fn file_reader_not_exist() { fn file_reader_not_exist() {
match io::file_reader(&Path("not a file")) { match io::file_reader(&Path("not a file")) {
result::err(e) => { result::Err(e) => {
assert e == ~"error opening not a file"; assert e == ~"error opening not a file";
} }
result::ok(_) => fail result::Ok(_) => fail
} }
} }
#[test] #[test]
fn file_writer_bad_name() { fn file_writer_bad_name() {
match io::file_writer(&Path("?/?"), ~[]) { match io::file_writer(&Path("?/?"), ~[]) {
result::err(e) => { result::Err(e) => {
assert str::starts_with(e, "error opening"); assert str::starts_with(e, "error opening");
} }
result::ok(_) => fail result::Ok(_) => fail
} }
} }
#[test] #[test]
fn buffered_file_writer_bad_name() { fn buffered_file_writer_bad_name() {
match io::buffered_file_writer(&Path("?/?")) { match io::buffered_file_writer(&Path("?/?")) {
result::err(e) => { result::Err(e) => {
assert str::starts_with(e, "error opening"); assert str::starts_with(e, "error opening");
} }
result::ok(_) => fail result::Ok(_) => fail
} }
} }

View file

@ -3,11 +3,11 @@
import either::Either; import either::Either;
/// The result type /// The result type
enum result<T, U> { enum Result<T, U> {
/// Contains the successful result value /// Contains the successful result value
ok(T), Ok(T),
/// Contains the error value /// Contains the error value
err(U) Err(U)
} }
/** /**
@ -17,10 +17,10 @@ enum result<T, U> {
* *
* If the result is an error * If the result is an error
*/ */
pure fn get<T: copy, U>(res: result<T, U>) -> T { pure fn get<T: copy, U>(res: Result<T, U>) -> T {
match res { match res {
ok(t) => t, Ok(t) => t,
err(the_err) => unchecked { Err(the_err) => unchecked {
fail fmt!("get called on error result: %?", the_err) fail fmt!("get called on error result: %?", the_err)
} }
} }
@ -33,10 +33,10 @@ pure fn get<T: copy, U>(res: result<T, U>) -> T {
* *
* If the result is an error * If the result is an error
*/ */
pure fn get_ref<T, U>(res: &a/result<T, U>) -> &a/T { pure fn get_ref<T, U>(res: &a/Result<T, U>) -> &a/T {
match *res { match *res {
ok(ref t) => t, Ok(ref t) => t,
err(ref the_err) => unchecked { Err(ref the_err) => unchecked {
fail fmt!("get_ref called on error result: %?", the_err) fail fmt!("get_ref called on error result: %?", the_err)
} }
} }
@ -49,23 +49,23 @@ pure fn get_ref<T, U>(res: &a/result<T, U>) -> &a/T {
* *
* If the result is not an error * If the result is not an error
*/ */
pure fn get_err<T, U: copy>(res: result<T, U>) -> U { pure fn get_err<T, U: copy>(res: Result<T, U>) -> U {
match res { match res {
err(u) => u, Err(u) => u,
ok(_) => fail ~"get_error called on ok result" Ok(_) => fail ~"get_error called on ok result"
} }
} }
/// Returns true if the result is `ok` /// Returns true if the result is `ok`
pure fn is_ok<T, U>(res: result<T, U>) -> bool { pure fn is_ok<T, U>(res: Result<T, U>) -> bool {
match res { match res {
ok(_) => true, Ok(_) => true,
err(_) => false Err(_) => false
} }
} }
/// Returns true if the result is `err` /// Returns true if the result is `err`
pure fn is_err<T, U>(res: result<T, U>) -> bool { pure fn is_err<T, U>(res: Result<T, U>) -> bool {
!is_ok(res) !is_ok(res)
} }
@ -75,10 +75,10 @@ pure fn is_err<T, U>(res: result<T, U>) -> bool {
* `ok` result variants are converted to `either::right` variants, `err` * `ok` result variants are converted to `either::right` variants, `err`
* result variants are converted to `either::left`. * result variants are converted to `either::left`.
*/ */
pure fn to_either<T: copy, U: copy>(res: result<U, T>) -> Either<T, U> { pure fn to_either<T: copy, U: copy>(res: Result<U, T>) -> Either<T, U> {
match res { match res {
ok(res) => either::Right(res), Ok(res) => either::Right(res),
err(fail_) => either::Left(fail_) Err(fail_) => either::Left(fail_)
} }
} }
@ -96,11 +96,11 @@ pure fn to_either<T: copy, U: copy>(res: result<U, T>) -> Either<T, U> {
* ok(parse_buf(buf)) * ok(parse_buf(buf))
* } * }
*/ */
fn chain<T, U: copy, V: copy>(res: result<T, V>, op: fn(T) -> result<U, V>) fn chain<T, U: copy, V: copy>(res: Result<T, V>, op: fn(T) -> Result<U, V>)
-> result<U, V> { -> Result<U, V> {
match res { match res {
ok(t) => op(t), Ok(t) => op(t),
err(e) => err(e) Err(e) => Err(e)
} }
} }
@ -113,12 +113,12 @@ fn chain<T, U: copy, V: copy>(res: result<T, V>, op: fn(T) -> result<U, V>)
* successful result while handling an error. * successful result while handling an error.
*/ */
fn chain_err<T: copy, U: copy, V: copy>( fn chain_err<T: copy, U: copy, V: copy>(
res: result<T, V>, res: Result<T, V>,
op: fn(V) -> result<T, U>) op: fn(V) -> Result<T, U>)
-> result<T, U> { -> Result<T, U> {
match res { match res {
ok(t) => ok(t), Ok(t) => Ok(t),
err(v) => op(v) Err(v) => op(v)
} }
} }
@ -136,10 +136,10 @@ fn chain_err<T: copy, U: copy, V: copy>(
* print_buf(buf) * print_buf(buf)
* } * }
*/ */
fn iter<T, E>(res: result<T, E>, f: fn(T)) { fn iter<T, E>(res: Result<T, E>, f: fn(T)) {
match res { match res {
ok(t) => f(t), Ok(t) => f(t),
err(_) => () Err(_) => ()
} }
} }
@ -151,10 +151,10 @@ fn iter<T, E>(res: result<T, E>, f: fn(T)) {
* This function can be used to pass through a successful result while * This function can be used to pass through a successful result while
* handling an error. * handling an error.
*/ */
fn iter_err<T, E>(res: result<T, E>, f: fn(E)) { fn iter_err<T, E>(res: Result<T, E>, f: fn(E)) {
match res { match res {
ok(_) => (), Ok(_) => (),
err(e) => f(e) Err(e) => f(e)
} }
} }
@ -172,11 +172,11 @@ fn iter_err<T, E>(res: result<T, E>, f: fn(E)) {
* parse_buf(buf) * parse_buf(buf)
* } * }
*/ */
fn map<T, E: copy, U: copy>(res: result<T, E>, op: fn(T) -> U) fn map<T, E: copy, U: copy>(res: Result<T, E>, op: fn(T) -> U)
-> result<U, E> { -> Result<U, E> {
match res { match res {
ok(t) => ok(op(t)), Ok(t) => Ok(op(t)),
err(e) => err(e) Err(e) => Err(e)
} }
} }
@ -188,62 +188,62 @@ fn map<T, E: copy, U: copy>(res: result<T, E>, op: fn(T) -> U)
* is immediately returned. This function can be used to pass through a * is immediately returned. This function can be used to pass through a
* successful result while handling an error. * successful result while handling an error.
*/ */
fn map_err<T: copy, E, F: copy>(res: result<T, E>, op: fn(E) -> F) fn map_err<T: copy, E, F: copy>(res: Result<T, E>, op: fn(E) -> F)
-> result<T, F> { -> Result<T, F> {
match res { match res {
ok(t) => ok(t), Ok(t) => Ok(t),
err(e) => err(op(e)) Err(e) => Err(op(e))
} }
} }
impl<T, E> result<T, E> { impl<T, E> Result<T, E> {
fn is_ok() -> bool { is_ok(self) } fn is_ok() -> bool { is_ok(self) }
fn is_err() -> bool { is_err(self) } fn is_err() -> bool { is_err(self) }
fn iter(f: fn(T)) { fn iter(f: fn(T)) {
match self { match self {
ok(t) => f(t), Ok(t) => f(t),
err(_) => () Err(_) => ()
} }
} }
fn iter_err(f: fn(E)) { fn iter_err(f: fn(E)) {
match self { match self {
ok(_) => (), Ok(_) => (),
err(e) => f(e) Err(e) => f(e)
} }
} }
} }
impl<T: copy, E> result<T, E> { impl<T: copy, E> Result<T, E> {
fn get() -> T { get(self) } fn get() -> T { get(self) }
fn map_err<F:copy>(op: fn(E) -> F) -> result<T,F> { fn map_err<F:copy>(op: fn(E) -> F) -> Result<T,F> {
match self { match self {
ok(t) => ok(t), Ok(t) => Ok(t),
err(e) => err(op(e)) Err(e) => Err(op(e))
} }
} }
} }
impl<T, E: copy> result<T, E> { impl<T, E: copy> Result<T, E> {
fn get_err() -> E { get_err(self) } fn get_err() -> E { get_err(self) }
fn map<U:copy>(op: fn(T) -> U) -> result<U,E> { fn map<U:copy>(op: fn(T) -> U) -> Result<U,E> {
match self { match self {
ok(t) => ok(op(t)), Ok(t) => Ok(op(t)),
err(e) => err(e) Err(e) => Err(e)
} }
} }
} }
impl<T: copy, E: copy> result<T, E> { impl<T: copy, E: copy> Result<T, E> {
fn chain<U:copy>(op: fn(T) -> result<U,E>) -> result<U,E> { fn chain<U:copy>(op: fn(T) -> Result<U,E>) -> Result<U,E> {
chain(self, op) chain(self, op)
} }
fn chain_err<F:copy>(op: fn(E) -> result<T,F>) -> result<T,F> { fn chain_err<F:copy>(op: fn(E) -> Result<T,F>) -> Result<T,F> {
chain_err(self, op) chain_err(self, op)
} }
} }
@ -266,27 +266,27 @@ impl<T: copy, E: copy> result<T, E> {
* } * }
*/ */
fn map_vec<T,U:copy,V:copy>( fn map_vec<T,U:copy,V:copy>(
ts: &[T], op: fn(T) -> result<V,U>) -> result<~[V],U> { ts: &[T], op: fn(T) -> Result<V,U>) -> Result<~[V],U> {
let mut vs: ~[V] = ~[]; let mut vs: ~[V] = ~[];
vec::reserve(vs, vec::len(ts)); vec::reserve(vs, vec::len(ts));
for vec::each(ts) |t| { for vec::each(ts) |t| {
match op(t) { match op(t) {
ok(v) => vec::push(vs, v), Ok(v) => vec::push(vs, v),
err(u) => return err(u) Err(u) => return Err(u)
} }
} }
return ok(vs); return Ok(vs);
} }
fn map_opt<T,U:copy,V:copy>( fn map_opt<T,U:copy,V:copy>(
o_t: Option<T>, op: fn(T) -> result<V,U>) -> result<Option<V>,U> { o_t: Option<T>, op: fn(T) -> Result<V,U>) -> Result<Option<V>,U> {
match o_t { match o_t {
None => ok(None), None => Ok(None),
Some(t) => match op(t) { Some(t) => match op(t) {
ok(v) => ok(Some(v)), Ok(v) => Ok(Some(v)),
err(e) => err(e) Err(e) => Err(e)
} }
} }
} }
@ -301,7 +301,7 @@ fn map_opt<T,U:copy,V:copy>(
* to accommodate an error like the vectors being of different lengths. * to accommodate an error like the vectors being of different lengths.
*/ */
fn map_vec2<S,T,U:copy,V:copy>(ss: &[S], ts: &[T], fn map_vec2<S,T,U:copy,V:copy>(ss: &[S], ts: &[T],
op: fn(S,T) -> result<V,U>) -> result<~[V],U> { op: fn(S,T) -> Result<V,U>) -> Result<~[V],U> {
assert vec::same_length(ss, ts); assert vec::same_length(ss, ts);
let n = vec::len(ts); let n = vec::len(ts);
@ -310,12 +310,12 @@ fn map_vec2<S,T,U:copy,V:copy>(ss: &[S], ts: &[T],
let mut i = 0u; let mut i = 0u;
while i < n { while i < n {
match op(ss[i],ts[i]) { match op(ss[i],ts[i]) {
ok(v) => vec::push(vs, v), Ok(v) => vec::push(vs, v),
err(u) => return err(u) Err(u) => return Err(u)
} }
i += 1u; i += 1u;
} }
return ok(vs); return Ok(vs);
} }
/** /**
@ -324,27 +324,27 @@ fn map_vec2<S,T,U:copy,V:copy>(ss: &[S], ts: &[T],
* on its own as no result vector is built. * on its own as no result vector is built.
*/ */
fn iter_vec2<S,T,U:copy>(ss: &[S], ts: &[T], fn iter_vec2<S,T,U:copy>(ss: &[S], ts: &[T],
op: fn(S,T) -> result<(),U>) -> result<(),U> { op: fn(S,T) -> Result<(),U>) -> Result<(),U> {
assert vec::same_length(ss, ts); assert vec::same_length(ss, ts);
let n = vec::len(ts); let n = vec::len(ts);
let mut i = 0u; let mut i = 0u;
while i < n { while i < n {
match op(ss[i],ts[i]) { match op(ss[i],ts[i]) {
ok(()) => (), Ok(()) => (),
err(u) => return err(u) Err(u) => return Err(u)
} }
i += 1u; i += 1u;
} }
return ok(()); return Ok(());
} }
/// Unwraps a result, assuming it is an `ok(T)` /// Unwraps a result, assuming it is an `ok(T)`
fn unwrap<T, U>(-res: result<T, U>) -> T { fn unwrap<T, U>(-res: Result<T, U>) -> T {
unsafe { unsafe {
let addr = match res { let addr = match res {
ok(x) => ptr::addr_of(x), Ok(x) => ptr::addr_of(x),
err(_) => fail ~"error result" Err(_) => fail ~"error result"
}; };
let liberated_value = unsafe::reinterpret_cast(*addr); let liberated_value = unsafe::reinterpret_cast(*addr);
unsafe::forget(res); unsafe::forget(res);
@ -354,13 +354,13 @@ fn unwrap<T, U>(-res: result<T, U>) -> T {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
fn op1() -> result::result<int, ~str> { result::ok(666) } fn op1() -> result::Result<int, ~str> { result::Ok(666) }
fn op2(&&i: int) -> result::result<uint, ~str> { fn op2(&&i: int) -> result::Result<uint, ~str> {
result::ok(i as uint + 1u) result::Ok(i as uint + 1u)
} }
fn op3() -> result::result<int, ~str> { result::err(~"sadface") } fn op3() -> result::Result<int, ~str> { result::Err(~"sadface") }
#[test] #[test]
fn chain_success() { fn chain_success() {
@ -375,33 +375,33 @@ mod tests {
#[test] #[test]
fn test_impl_iter() { fn test_impl_iter() {
let mut valid = false; let mut valid = false;
ok::<~str, ~str>(~"a").iter(|_x| valid = true); Ok::<~str, ~str>(~"a").iter(|_x| valid = true);
assert valid; assert valid;
err::<~str, ~str>(~"b").iter(|_x| valid = false); Err::<~str, ~str>(~"b").iter(|_x| valid = false);
assert valid; assert valid;
} }
#[test] #[test]
fn test_impl_iter_err() { fn test_impl_iter_err() {
let mut valid = true; let mut valid = true;
ok::<~str, ~str>(~"a").iter_err(|_x| valid = false); Ok::<~str, ~str>(~"a").iter_err(|_x| valid = false);
assert valid; assert valid;
valid = false; valid = false;
err::<~str, ~str>(~"b").iter_err(|_x| valid = true); Err::<~str, ~str>(~"b").iter_err(|_x| valid = true);
assert valid; assert valid;
} }
#[test] #[test]
fn test_impl_map() { fn test_impl_map() {
assert ok::<~str, ~str>(~"a").map(|_x| ~"b") == ok(~"b"); assert Ok::<~str, ~str>(~"a").map(|_x| ~"b") == Ok(~"b");
assert err::<~str, ~str>(~"a").map(|_x| ~"b") == err(~"a"); assert Err::<~str, ~str>(~"a").map(|_x| ~"b") == Err(~"a");
} }
#[test] #[test]
fn test_impl_map_err() { fn test_impl_map_err() {
assert ok::<~str, ~str>(~"a").map_err(|_x| ~"b") == ok(~"a"); assert Ok::<~str, ~str>(~"a").map_err(|_x| ~"b") == Ok(~"a");
assert err::<~str, ~str>(~"a").map_err(|_x| ~"b") == err(~"b"); assert Err::<~str, ~str>(~"a").map_err(|_x| ~"b") == Err(~"b");
} }
} }

View file

@ -27,7 +27,7 @@
* ~~~ * ~~~
*/ */
import result::result; import result::Result;
export Task; export Task;
export TaskResult; export TaskResult;
@ -406,7 +406,7 @@ impl TaskBuilder {
* # Failure * # Failure
* Fails if a future_result was already set for this task. * Fails if a future_result was already set for this task.
*/ */
fn try<T: send>(+f: fn~() -> T) -> result<T,()> { fn try<T: send>(+f: fn~() -> T) -> Result<T,()> {
let po = comm::port(); let po = comm::port();
let ch = comm::chan(po); let ch = comm::chan(po);
let mut result = None; let mut result = None;
@ -415,8 +415,8 @@ impl TaskBuilder {
comm::send(ch, f()); comm::send(ch, f());
} }
match future::get(&option::unwrap(result)) { match future::get(&option::unwrap(result)) {
Success => result::ok(comm::recv(po)), Success => result::Ok(comm::recv(po)),
Failure => result::err(()) Failure => result::Err(())
} }
} }
} }
@ -526,7 +526,7 @@ fn spawn_sched(mode: SchedMode, +f: fn~()) {
task().sched_mode(mode).spawn(f) task().sched_mode(mode).spawn(f)
} }
fn try<T:send>(+f: fn~() -> T) -> result<T,()> { fn try<T:send>(+f: fn~() -> T) -> Result<T,()> {
/*! /*!
* Execute a function in another task and return either the return value * Execute a function in another task and return either the return value
* of the function or result::err. * of the function or result::err.
@ -1769,7 +1769,7 @@ fn test_try_success() {
match do try { match do try {
~"Success!" ~"Success!"
} { } {
result::ok(~"Success!") => (), result::Ok(~"Success!") => (),
_ => fail _ => fail
} }
} }
@ -1780,8 +1780,8 @@ fn test_try_fail() {
match do try { match do try {
fail fail
} { } {
result::err(()) => (), result::Err(()) => (),
result::ok(()) => fail result::Ok(()) => fail
} }
} }

View file

@ -62,7 +62,7 @@
* } * }
*/ */
import core::result::{err, ok}; import core::result::{Err, Ok};
import core::option; import core::option;
import core::option::{Some, None}; import core::option::{Some, None};
export opt; export opt;
@ -179,7 +179,7 @@ fn fail_str(f: fail_) -> ~str {
* The result of parsing a command line with a set of options * The result of parsing a command line with a set of options
* (result::t<matches, fail_>) * (result::t<matches, fail_>)
*/ */
type result = result::result<matches, fail_>; type result = result::Result<matches, fail_>;
/** /**
* Parse command line arguments according to the provided options * Parse command line arguments according to the provided options
@ -261,12 +261,12 @@ fn getopts(args: ~[~str], opts: ~[opt]) -> result unsafe {
name_pos += 1u; name_pos += 1u;
let optid = match find_opt(opts, nm) { let optid = match find_opt(opts, nm) {
Some(id) => id, Some(id) => id,
None => return err(unrecognized_option(name_str(nm))) None => return Err(unrecognized_option(name_str(nm)))
}; };
match opts[optid].hasarg { match opts[optid].hasarg {
no => { no => {
if !option::is_none::<~str>(i_arg) { if !option::is_none::<~str>(i_arg) {
return err(unexpected_argument(name_str(nm))); return Err(unexpected_argument(name_str(nm)));
} }
vec::push(vals[optid], given); vec::push(vals[optid], given);
} }
@ -283,7 +283,7 @@ fn getopts(args: ~[~str], opts: ~[opt]) -> result unsafe {
vec::push(vals[optid], vec::push(vals[optid],
val(option::get::<~str>(i_arg))); val(option::get::<~str>(i_arg)));
} else if i + 1u == l { } else if i + 1u == l {
return err(argument_missing(name_str(nm))); return Err(argument_missing(name_str(nm)));
} else { i += 1u; vec::push(vals[optid], val(args[i])); } } else { i += 1u; vec::push(vals[optid], val(args[i])); }
} }
} }
@ -297,17 +297,17 @@ fn getopts(args: ~[~str], opts: ~[opt]) -> result unsafe {
let occ = opts[i].occur; let occ = opts[i].occur;
if occ == req { if occ == req {
if n == 0u { if n == 0u {
return err(option_missing(name_str(opts[i].name))); return Err(option_missing(name_str(opts[i].name)));
} }
} }
if occ != multi { if occ != multi {
if n > 1u { if n > 1u {
return err(option_duplicated(name_str(opts[i].name))); return Err(option_duplicated(name_str(opts[i].name)));
} }
} }
i += 1u; i += 1u;
} }
return ok({opts: opts, vals: vec::from_mut(vals), free: free}); return Ok({opts: opts, vals: vec::from_mut(vals), free: free});
} }
fn opt_vals(m: matches, nm: ~str) -> ~[optval] { fn opt_vals(m: matches, nm: ~str) -> ~[optval] {
@ -404,7 +404,7 @@ fn opt_default(m: matches, nm: ~str, def: ~str) -> Option<~str> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
import opt = getopts; import opt = getopts;
import result::{err, ok}; import result::{Err, Ok};
enum fail_type { enum fail_type {
argument_missing_, argument_missing_,
@ -432,7 +432,7 @@ mod tests {
let opts = ~[reqopt(~"test")]; let opts = ~[reqopt(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => { Ok(m) => {
assert (opt_present(m, ~"test")); assert (opt_present(m, ~"test"));
assert (opt_str(m, ~"test") == ~"20"); assert (opt_str(m, ~"test") == ~"20");
} }
@ -446,7 +446,7 @@ mod tests {
let opts = ~[reqopt(~"test")]; let opts = ~[reqopt(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, option_missing_), Err(f) => check_fail_type(f, option_missing_),
_ => fail _ => fail
} }
} }
@ -457,7 +457,7 @@ mod tests {
let opts = ~[reqopt(~"test")]; let opts = ~[reqopt(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, argument_missing_), Err(f) => check_fail_type(f, argument_missing_),
_ => fail _ => fail
} }
} }
@ -468,7 +468,7 @@ mod tests {
let opts = ~[reqopt(~"test")]; let opts = ~[reqopt(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, option_duplicated_), Err(f) => check_fail_type(f, option_duplicated_),
_ => fail _ => fail
} }
} }
@ -479,7 +479,7 @@ mod tests {
let opts = ~[reqopt(~"t")]; let opts = ~[reqopt(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => { Ok(m) => {
assert (opt_present(m, ~"t")); assert (opt_present(m, ~"t"));
assert (opt_str(m, ~"t") == ~"20"); assert (opt_str(m, ~"t") == ~"20");
} }
@ -493,7 +493,7 @@ mod tests {
let opts = ~[reqopt(~"t")]; let opts = ~[reqopt(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, option_missing_), Err(f) => check_fail_type(f, option_missing_),
_ => fail _ => fail
} }
} }
@ -504,7 +504,7 @@ mod tests {
let opts = ~[reqopt(~"t")]; let opts = ~[reqopt(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, argument_missing_), Err(f) => check_fail_type(f, argument_missing_),
_ => fail _ => fail
} }
} }
@ -515,7 +515,7 @@ mod tests {
let opts = ~[reqopt(~"t")]; let opts = ~[reqopt(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, option_duplicated_), Err(f) => check_fail_type(f, option_duplicated_),
_ => fail _ => fail
} }
} }
@ -528,7 +528,7 @@ mod tests {
let opts = ~[optopt(~"test")]; let opts = ~[optopt(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => { Ok(m) => {
assert (opt_present(m, ~"test")); assert (opt_present(m, ~"test"));
assert (opt_str(m, ~"test") == ~"20"); assert (opt_str(m, ~"test") == ~"20");
} }
@ -542,7 +542,7 @@ mod tests {
let opts = ~[optopt(~"test")]; let opts = ~[optopt(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => assert (!opt_present(m, ~"test")), Ok(m) => assert (!opt_present(m, ~"test")),
_ => fail _ => fail
} }
} }
@ -553,7 +553,7 @@ mod tests {
let opts = ~[optopt(~"test")]; let opts = ~[optopt(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, argument_missing_), Err(f) => check_fail_type(f, argument_missing_),
_ => fail _ => fail
} }
} }
@ -564,7 +564,7 @@ mod tests {
let opts = ~[optopt(~"test")]; let opts = ~[optopt(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, option_duplicated_), Err(f) => check_fail_type(f, option_duplicated_),
_ => fail _ => fail
} }
} }
@ -575,7 +575,7 @@ mod tests {
let opts = ~[optopt(~"t")]; let opts = ~[optopt(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => { Ok(m) => {
assert (opt_present(m, ~"t")); assert (opt_present(m, ~"t"));
assert (opt_str(m, ~"t") == ~"20"); assert (opt_str(m, ~"t") == ~"20");
} }
@ -589,7 +589,7 @@ mod tests {
let opts = ~[optopt(~"t")]; let opts = ~[optopt(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => assert (!opt_present(m, ~"t")), Ok(m) => assert (!opt_present(m, ~"t")),
_ => fail _ => fail
} }
} }
@ -600,7 +600,7 @@ mod tests {
let opts = ~[optopt(~"t")]; let opts = ~[optopt(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, argument_missing_), Err(f) => check_fail_type(f, argument_missing_),
_ => fail _ => fail
} }
} }
@ -611,7 +611,7 @@ mod tests {
let opts = ~[optopt(~"t")]; let opts = ~[optopt(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, option_duplicated_), Err(f) => check_fail_type(f, option_duplicated_),
_ => fail _ => fail
} }
} }
@ -624,7 +624,7 @@ mod tests {
let opts = ~[optflag(~"test")]; let opts = ~[optflag(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => assert (opt_present(m, ~"test")), Ok(m) => assert (opt_present(m, ~"test")),
_ => fail _ => fail
} }
} }
@ -635,7 +635,7 @@ mod tests {
let opts = ~[optflag(~"test")]; let opts = ~[optflag(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => assert (!opt_present(m, ~"test")), Ok(m) => assert (!opt_present(m, ~"test")),
_ => fail _ => fail
} }
} }
@ -646,7 +646,7 @@ mod tests {
let opts = ~[optflag(~"test")]; let opts = ~[optflag(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => { Err(f) => {
log(error, fail_str(f)); log(error, fail_str(f));
check_fail_type(f, unexpected_argument_); check_fail_type(f, unexpected_argument_);
} }
@ -660,7 +660,7 @@ mod tests {
let opts = ~[optflag(~"test")]; let opts = ~[optflag(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, option_duplicated_), Err(f) => check_fail_type(f, option_duplicated_),
_ => fail _ => fail
} }
} }
@ -671,7 +671,7 @@ mod tests {
let opts = ~[optflag(~"t")]; let opts = ~[optflag(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => assert (opt_present(m, ~"t")), Ok(m) => assert (opt_present(m, ~"t")),
_ => fail _ => fail
} }
} }
@ -682,7 +682,7 @@ mod tests {
let opts = ~[optflag(~"t")]; let opts = ~[optflag(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => assert (!opt_present(m, ~"t")), Ok(m) => assert (!opt_present(m, ~"t")),
_ => fail _ => fail
} }
} }
@ -693,7 +693,7 @@ mod tests {
let opts = ~[optflag(~"t")]; let opts = ~[optflag(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => { Ok(m) => {
// The next variable after the flag is just a free argument // The next variable after the flag is just a free argument
assert (m.free[0] == ~"20"); assert (m.free[0] == ~"20");
@ -708,7 +708,7 @@ mod tests {
let opts = ~[optflag(~"t")]; let opts = ~[optflag(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, option_duplicated_), Err(f) => check_fail_type(f, option_duplicated_),
_ => fail _ => fail
} }
} }
@ -721,7 +721,7 @@ mod tests {
let opts = ~[optmulti(~"test")]; let opts = ~[optmulti(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => { Ok(m) => {
assert (opt_present(m, ~"test")); assert (opt_present(m, ~"test"));
assert (opt_str(m, ~"test") == ~"20"); assert (opt_str(m, ~"test") == ~"20");
} }
@ -735,7 +735,7 @@ mod tests {
let opts = ~[optmulti(~"test")]; let opts = ~[optmulti(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => assert (!opt_present(m, ~"test")), Ok(m) => assert (!opt_present(m, ~"test")),
_ => fail _ => fail
} }
} }
@ -746,7 +746,7 @@ mod tests {
let opts = ~[optmulti(~"test")]; let opts = ~[optmulti(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, argument_missing_), Err(f) => check_fail_type(f, argument_missing_),
_ => fail _ => fail
} }
} }
@ -757,7 +757,7 @@ mod tests {
let opts = ~[optmulti(~"test")]; let opts = ~[optmulti(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => { Ok(m) => {
assert (opt_present(m, ~"test")); assert (opt_present(m, ~"test"));
assert (opt_str(m, ~"test") == ~"20"); assert (opt_str(m, ~"test") == ~"20");
assert (opt_strs(m, ~"test")[0] == ~"20"); assert (opt_strs(m, ~"test")[0] == ~"20");
@ -773,7 +773,7 @@ mod tests {
let opts = ~[optmulti(~"t")]; let opts = ~[optmulti(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => { Ok(m) => {
assert (opt_present(m, ~"t")); assert (opt_present(m, ~"t"));
assert (opt_str(m, ~"t") == ~"20"); assert (opt_str(m, ~"t") == ~"20");
} }
@ -787,7 +787,7 @@ mod tests {
let opts = ~[optmulti(~"t")]; let opts = ~[optmulti(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => assert (!opt_present(m, ~"t")), Ok(m) => assert (!opt_present(m, ~"t")),
_ => fail _ => fail
} }
} }
@ -798,7 +798,7 @@ mod tests {
let opts = ~[optmulti(~"t")]; let opts = ~[optmulti(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, argument_missing_), Err(f) => check_fail_type(f, argument_missing_),
_ => fail _ => fail
} }
} }
@ -809,7 +809,7 @@ mod tests {
let opts = ~[optmulti(~"t")]; let opts = ~[optmulti(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => { Ok(m) => {
assert (opt_present(m, ~"t")); assert (opt_present(m, ~"t"));
assert (opt_str(m, ~"t") == ~"20"); assert (opt_str(m, ~"t") == ~"20");
assert (opt_strs(m, ~"t")[0] == ~"20"); assert (opt_strs(m, ~"t")[0] == ~"20");
@ -825,7 +825,7 @@ mod tests {
let opts = ~[optmulti(~"t")]; let opts = ~[optmulti(~"t")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, unrecognized_option_), Err(f) => check_fail_type(f, unrecognized_option_),
_ => fail _ => fail
} }
} }
@ -836,7 +836,7 @@ mod tests {
let opts = ~[optmulti(~"test")]; let opts = ~[optmulti(~"test")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
err(f) => check_fail_type(f, unrecognized_option_), Err(f) => check_fail_type(f, unrecognized_option_),
_ => fail _ => fail
} }
} }
@ -853,7 +853,7 @@ mod tests {
optopt(~"notpresent")]; optopt(~"notpresent")];
let rs = getopts(args, opts); let rs = getopts(args, opts);
match rs { match rs {
ok(m) => { Ok(m) => {
assert (m.free[0] == ~"prog"); assert (m.free[0] == ~"prog");
assert (m.free[1] == ~"free1"); assert (m.free[1] == ~"free1");
assert (opt_str(m, ~"s") == ~"20"); assert (opt_str(m, ~"s") == ~"20");
@ -876,8 +876,8 @@ mod tests {
let args = ~[~"-e", ~"foo", ~"--encrypt", ~"foo"]; let args = ~[~"-e", ~"foo", ~"--encrypt", ~"foo"];
let opts = ~[optopt(~"e"), optopt(~"encrypt")]; let opts = ~[optopt(~"e"), optopt(~"encrypt")];
let matches = match getopts(args, opts) { let matches = match getopts(args, opts) {
result::ok(m) => m, result::Ok(m) => m,
result::err(_) => fail result::Err(_) => fail
}; };
assert opts_present(matches, ~[~"e"]); assert opts_present(matches, ~[~"e"]);
assert opts_present(matches, ~[~"encrypt"]); assert opts_present(matches, ~[~"encrypt"]);
@ -897,8 +897,8 @@ mod tests {
let args = ~[~"-Lfoo"]; let args = ~[~"-Lfoo"];
let opts = ~[optmulti(~"L")]; let opts = ~[optmulti(~"L")];
let matches = match getopts(args, opts) { let matches = match getopts(args, opts) {
result::ok(m) => m, result::Ok(m) => m,
result::err(_) => fail result::Err(_) => fail
}; };
assert opts_present(matches, ~[~"L"]); assert opts_present(matches, ~[~"L"]);
assert opts_str(matches, ~[~"L"]) == ~"foo"; assert opts_str(matches, ~[~"L"]) == ~"foo";

View file

@ -3,7 +3,7 @@
//! json serialization //! json serialization
import result::{result, ok, err}; import result::{Result, Ok, Err};
import io; import io;
import io::WriterUtil; import io::WriterUtil;
import map; import map;
@ -138,18 +138,18 @@ impl parser {
self.ch self.ch
} }
fn error<T>(+msg: ~str) -> result<T, error> { fn error<T>(+msg: ~str) -> Result<T, error> {
err({ line: self.line, col: self.col, msg: @msg }) Err({ line: self.line, col: self.col, msg: @msg })
} }
fn parse() -> result<json, error> { fn parse() -> Result<json, error> {
match self.parse_value() { match self.parse_value() {
ok(value) => { Ok(value) => {
// Skip trailing whitespaces. // Skip trailing whitespaces.
self.parse_whitespace(); self.parse_whitespace();
// Make sure there is no trailing characters. // Make sure there is no trailing characters.
if self.eof() { if self.eof() {
ok(value) Ok(value)
} else { } else {
self.error(~"trailing characters") self.error(~"trailing characters")
} }
@ -158,7 +158,7 @@ impl parser {
} }
} }
fn parse_value() -> result<json, error> { fn parse_value() -> Result<json, error> {
self.parse_whitespace(); self.parse_whitespace();
if self.eof() { return self.error(~"EOF while parsing value"); } if self.eof() { return self.error(~"EOF while parsing value"); }
@ -169,8 +169,8 @@ impl parser {
'f' => self.parse_ident(~"alse", boolean(false)), 'f' => self.parse_ident(~"alse", boolean(false)),
'0' to '9' | '-' => self.parse_number(), '0' to '9' | '-' => self.parse_number(),
'"' => match self.parse_str() { '"' => match self.parse_str() {
ok(s) => ok(string(s)), Ok(s) => Ok(string(s)),
err(e) => err(e) Err(e) => Err(e)
}, },
'[' => self.parse_list(), '[' => self.parse_list(),
'{' => self.parse_object(), '{' => self.parse_object(),
@ -182,16 +182,16 @@ impl parser {
while char::is_whitespace(self.ch) { self.bump(); } while char::is_whitespace(self.ch) { self.bump(); }
} }
fn parse_ident(ident: ~str, value: json) -> result<json, error> { fn parse_ident(ident: ~str, value: json) -> Result<json, error> {
if str::all(ident, |c| c == self.next_char()) { if str::all(ident, |c| c == self.next_char()) {
self.bump(); self.bump();
ok(value) Ok(value)
} else { } else {
self.error(~"invalid syntax") self.error(~"invalid syntax")
} }
} }
fn parse_number() -> result<json, error> { fn parse_number() -> Result<json, error> {
let mut neg = 1f; let mut neg = 1f;
if self.ch == '-' { if self.ch == '-' {
@ -200,28 +200,28 @@ impl parser {
} }
let mut res = match self.parse_integer() { let mut res = match self.parse_integer() {
ok(res) => res, Ok(res) => res,
err(e) => return err(e) Err(e) => return Err(e)
}; };
if self.ch == '.' { if self.ch == '.' {
match self.parse_decimal(res) { match self.parse_decimal(res) {
ok(r) => res = r, Ok(r) => res = r,
err(e) => return err(e) Err(e) => return Err(e)
} }
} }
if self.ch == 'e' || self.ch == 'E' { if self.ch == 'e' || self.ch == 'E' {
match self.parse_exponent(res) { match self.parse_exponent(res) {
ok(r) => res = r, Ok(r) => res = r,
err(e) => return err(e) Err(e) => return Err(e)
} }
} }
ok(num(neg * res)) Ok(num(neg * res))
} }
fn parse_integer() -> result<float, error> { fn parse_integer() -> Result<float, error> {
let mut res = 0f; let mut res = 0f;
match self.ch { match self.ch {
@ -250,10 +250,10 @@ impl parser {
_ => return self.error(~"invalid number") _ => return self.error(~"invalid number")
} }
ok(res) Ok(res)
} }
fn parse_decimal(res: float) -> result<float, error> { fn parse_decimal(res: float) -> Result<float, error> {
self.bump(); self.bump();
// Make sure a digit follows the decimal place. // Make sure a digit follows the decimal place.
@ -276,10 +276,10 @@ impl parser {
} }
} }
ok(res) Ok(res)
} }
fn parse_exponent(res: float) -> result<float, error> { fn parse_exponent(res: float) -> Result<float, error> {
self.bump(); self.bump();
let mut res = res; let mut res = res;
@ -317,10 +317,10 @@ impl parser {
res *= exp; res *= exp;
} }
ok(res) Ok(res)
} }
fn parse_str() -> result<@~str, error> { fn parse_str() -> Result<@~str, error> {
let mut escape = false; let mut escape = false;
let mut res = ~""; let mut res = ~"";
@ -367,7 +367,7 @@ impl parser {
} else { } else {
if self.ch == '"' { if self.ch == '"' {
self.bump(); self.bump();
return ok(@res); return Ok(@res);
} }
str::push_char(res, self.ch); str::push_char(res, self.ch);
} }
@ -376,7 +376,7 @@ impl parser {
self.error(~"EOF while parsing string") self.error(~"EOF while parsing string")
} }
fn parse_list() -> result<json, error> { fn parse_list() -> Result<json, error> {
self.bump(); self.bump();
self.parse_whitespace(); self.parse_whitespace();
@ -384,12 +384,12 @@ impl parser {
if self.ch == ']' { if self.ch == ']' {
self.bump(); self.bump();
return ok(list(@values)); return Ok(list(@values));
} }
loop { loop {
match self.parse_value() { match self.parse_value() {
ok(v) => vec::push(values, v), Ok(v) => vec::push(values, v),
e => return e e => return e
} }
@ -400,13 +400,13 @@ impl parser {
match self.ch { match self.ch {
',' => self.bump(), ',' => self.bump(),
']' => { self.bump(); return ok(list(@values)); } ']' => { self.bump(); return Ok(list(@values)); }
_ => return self.error(~"expected `,` or `]`") _ => return self.error(~"expected `,` or `]`")
} }
}; };
} }
fn parse_object() -> result<json, error> { fn parse_object() -> Result<json, error> {
self.bump(); self.bump();
self.parse_whitespace(); self.parse_whitespace();
@ -414,7 +414,7 @@ impl parser {
if self.ch == '}' { if self.ch == '}' {
self.bump(); self.bump();
return ok(dict(values)); return Ok(dict(values));
} }
while !self.eof() { while !self.eof() {
@ -425,8 +425,8 @@ impl parser {
} }
let key = match self.parse_str() { let key = match self.parse_str() {
ok(key) => key, Ok(key) => key,
err(e) => return err(e) Err(e) => return Err(e)
}; };
self.parse_whitespace(); self.parse_whitespace();
@ -438,14 +438,14 @@ impl parser {
self.bump(); self.bump();
match self.parse_value() { match self.parse_value() {
ok(value) => { values.insert(copy *key, value); } Ok(value) => { values.insert(copy *key, value); }
e => return e e => return e
} }
self.parse_whitespace(); self.parse_whitespace();
match self.ch { match self.ch {
',' => self.bump(), ',' => self.bump(),
'}' => { self.bump(); return ok(dict(values)); } '}' => { self.bump(); return Ok(dict(values)); }
_ => { _ => {
if self.eof() { break; } if self.eof() { break; }
return self.error(~"expected `,` or `}`"); return self.error(~"expected `,` or `}`");
@ -458,7 +458,7 @@ impl parser {
} }
/// Deserializes a json value from an io::reader /// Deserializes a json value from an io::reader
fn from_reader(rdr: io::Reader) -> result<json, error> { fn from_reader(rdr: io::Reader) -> Result<json, error> {
let parser = parser_({ let parser = parser_({
rdr: rdr, rdr: rdr,
mut ch: rdr.read_char(), mut ch: rdr.read_char(),
@ -470,7 +470,7 @@ fn from_reader(rdr: io::Reader) -> result<json, error> {
} }
/// Deserializes a json value from a string /// Deserializes a json value from a string
fn from_str(s: ~str) -> result<json, error> { fn from_str(s: ~str) -> Result<json, error> {
io::with_str_reader(s, from_reader) io::with_str_reader(s, from_reader)
} }
@ -705,138 +705,138 @@ mod tests {
#[test] #[test]
fn test_trailing_characters() { fn test_trailing_characters() {
assert from_str(~"nulla") == assert from_str(~"nulla") ==
err({line: 1u, col: 5u, msg: @~"trailing characters"}); Err({line: 1u, col: 5u, msg: @~"trailing characters"});
assert from_str(~"truea") == assert from_str(~"truea") ==
err({line: 1u, col: 5u, msg: @~"trailing characters"}); Err({line: 1u, col: 5u, msg: @~"trailing characters"});
assert from_str(~"falsea") == assert from_str(~"falsea") ==
err({line: 1u, col: 6u, msg: @~"trailing characters"}); Err({line: 1u, col: 6u, msg: @~"trailing characters"});
assert from_str(~"1a") == assert from_str(~"1a") ==
err({line: 1u, col: 2u, msg: @~"trailing characters"}); Err({line: 1u, col: 2u, msg: @~"trailing characters"});
assert from_str(~"[]a") == assert from_str(~"[]a") ==
err({line: 1u, col: 3u, msg: @~"trailing characters"}); Err({line: 1u, col: 3u, msg: @~"trailing characters"});
assert from_str(~"{}a") == assert from_str(~"{}a") ==
err({line: 1u, col: 3u, msg: @~"trailing characters"}); Err({line: 1u, col: 3u, msg: @~"trailing characters"});
} }
#[test] #[test]
fn test_read_identifiers() { fn test_read_identifiers() {
assert from_str(~"n") == assert from_str(~"n") ==
err({line: 1u, col: 2u, msg: @~"invalid syntax"}); Err({line: 1u, col: 2u, msg: @~"invalid syntax"});
assert from_str(~"nul") == assert from_str(~"nul") ==
err({line: 1u, col: 4u, msg: @~"invalid syntax"}); Err({line: 1u, col: 4u, msg: @~"invalid syntax"});
assert from_str(~"t") == assert from_str(~"t") ==
err({line: 1u, col: 2u, msg: @~"invalid syntax"}); Err({line: 1u, col: 2u, msg: @~"invalid syntax"});
assert from_str(~"truz") == assert from_str(~"truz") ==
err({line: 1u, col: 4u, msg: @~"invalid syntax"}); Err({line: 1u, col: 4u, msg: @~"invalid syntax"});
assert from_str(~"f") == assert from_str(~"f") ==
err({line: 1u, col: 2u, msg: @~"invalid syntax"}); Err({line: 1u, col: 2u, msg: @~"invalid syntax"});
assert from_str(~"faz") == assert from_str(~"faz") ==
err({line: 1u, col: 3u, msg: @~"invalid syntax"}); Err({line: 1u, col: 3u, msg: @~"invalid syntax"});
assert from_str(~"null") == ok(null); assert from_str(~"null") == Ok(null);
assert from_str(~"true") == ok(boolean(true)); assert from_str(~"true") == Ok(boolean(true));
assert from_str(~"false") == ok(boolean(false)); assert from_str(~"false") == Ok(boolean(false));
assert from_str(~" null ") == ok(null); assert from_str(~" null ") == Ok(null);
assert from_str(~" true ") == ok(boolean(true)); assert from_str(~" true ") == Ok(boolean(true));
assert from_str(~" false ") == ok(boolean(false)); assert from_str(~" false ") == Ok(boolean(false));
} }
#[test] #[test]
fn test_read_num() { fn test_read_num() {
assert from_str(~"+") == assert from_str(~"+") ==
err({line: 1u, col: 1u, msg: @~"invalid syntax"}); Err({line: 1u, col: 1u, msg: @~"invalid syntax"});
assert from_str(~".") == assert from_str(~".") ==
err({line: 1u, col: 1u, msg: @~"invalid syntax"}); Err({line: 1u, col: 1u, msg: @~"invalid syntax"});
assert from_str(~"-") == assert from_str(~"-") ==
err({line: 1u, col: 2u, msg: @~"invalid number"}); Err({line: 1u, col: 2u, msg: @~"invalid number"});
assert from_str(~"00") == assert from_str(~"00") ==
err({line: 1u, col: 2u, msg: @~"invalid number"}); Err({line: 1u, col: 2u, msg: @~"invalid number"});
assert from_str(~"1.") == assert from_str(~"1.") ==
err({line: 1u, col: 3u, msg: @~"invalid number"}); Err({line: 1u, col: 3u, msg: @~"invalid number"});
assert from_str(~"1e") == assert from_str(~"1e") ==
err({line: 1u, col: 3u, msg: @~"invalid number"}); Err({line: 1u, col: 3u, msg: @~"invalid number"});
assert from_str(~"1e+") == assert from_str(~"1e+") ==
err({line: 1u, col: 4u, msg: @~"invalid number"}); Err({line: 1u, col: 4u, msg: @~"invalid number"});
assert from_str(~"3") == ok(num(3f)); assert from_str(~"3") == Ok(num(3f));
assert from_str(~"3.1") == ok(num(3.1f)); assert from_str(~"3.1") == Ok(num(3.1f));
assert from_str(~"-1.2") == ok(num(-1.2f)); assert from_str(~"-1.2") == Ok(num(-1.2f));
assert from_str(~"0.4") == ok(num(0.4f)); assert from_str(~"0.4") == Ok(num(0.4f));
assert from_str(~"0.4e5") == ok(num(0.4e5f)); assert from_str(~"0.4e5") == Ok(num(0.4e5f));
assert from_str(~"0.4e+15") == ok(num(0.4e15f)); assert from_str(~"0.4e+15") == Ok(num(0.4e15f));
assert from_str(~"0.4e-01") == ok(num(0.4e-01f)); assert from_str(~"0.4e-01") == Ok(num(0.4e-01f));
assert from_str(~" 3 ") == ok(num(3f)); assert from_str(~" 3 ") == Ok(num(3f));
} }
#[test] #[test]
fn test_read_str() { fn test_read_str() {
assert from_str(~"\"") == assert from_str(~"\"") ==
err({line: 1u, col: 2u, msg: @~"EOF while parsing string"}); Err({line: 1u, col: 2u, msg: @~"EOF while parsing string"});
assert from_str(~"\"lol") == assert from_str(~"\"lol") ==
err({line: 1u, col: 5u, msg: @~"EOF while parsing string"}); Err({line: 1u, col: 5u, msg: @~"EOF while parsing string"});
assert from_str(~"\"\"") == ok(string(@~"")); assert from_str(~"\"\"") == Ok(string(@~""));
assert from_str(~"\"foo\"") == ok(string(@~"foo")); assert from_str(~"\"foo\"") == Ok(string(@~"foo"));
assert from_str(~"\"\\\"\"") == ok(string(@~"\"")); assert from_str(~"\"\\\"\"") == Ok(string(@~"\""));
assert from_str(~"\"\\b\"") == ok(string(@~"\x08")); assert from_str(~"\"\\b\"") == Ok(string(@~"\x08"));
assert from_str(~"\"\\n\"") == ok(string(@~"\n")); assert from_str(~"\"\\n\"") == Ok(string(@~"\n"));
assert from_str(~"\"\\r\"") == ok(string(@~"\r")); assert from_str(~"\"\\r\"") == Ok(string(@~"\r"));
assert from_str(~"\"\\t\"") == ok(string(@~"\t")); assert from_str(~"\"\\t\"") == Ok(string(@~"\t"));
assert from_str(~" \"foo\" ") == ok(string(@~"foo")); assert from_str(~" \"foo\" ") == Ok(string(@~"foo"));
} }
#[test] #[test]
fn test_read_list() { fn test_read_list() {
assert from_str(~"[") == assert from_str(~"[") ==
err({line: 1u, col: 2u, msg: @~"EOF while parsing value"}); Err({line: 1u, col: 2u, msg: @~"EOF while parsing value"});
assert from_str(~"[1") == assert from_str(~"[1") ==
err({line: 1u, col: 3u, msg: @~"EOF while parsing list"}); Err({line: 1u, col: 3u, msg: @~"EOF while parsing list"});
assert from_str(~"[1,") == assert from_str(~"[1,") ==
err({line: 1u, col: 4u, msg: @~"EOF while parsing value"}); Err({line: 1u, col: 4u, msg: @~"EOF while parsing value"});
assert from_str(~"[1,]") == assert from_str(~"[1,]") ==
err({line: 1u, col: 4u, msg: @~"invalid syntax"}); Err({line: 1u, col: 4u, msg: @~"invalid syntax"});
assert from_str(~"[6 7]") == assert from_str(~"[6 7]") ==
err({line: 1u, col: 4u, msg: @~"expected `,` or `]`"}); Err({line: 1u, col: 4u, msg: @~"expected `,` or `]`"});
assert from_str(~"[]") == ok(list(@~[])); assert from_str(~"[]") == Ok(list(@~[]));
assert from_str(~"[ ]") == ok(list(@~[])); assert from_str(~"[ ]") == Ok(list(@~[]));
assert from_str(~"[true]") == ok(list(@~[boolean(true)])); assert from_str(~"[true]") == Ok(list(@~[boolean(true)]));
assert from_str(~"[ false ]") == ok(list(@~[boolean(false)])); assert from_str(~"[ false ]") == Ok(list(@~[boolean(false)]));
assert from_str(~"[null]") == ok(list(@~[null])); assert from_str(~"[null]") == Ok(list(@~[null]));
assert from_str(~"[3, 1]") == ok(list(@~[num(3f), num(1f)])); assert from_str(~"[3, 1]") == Ok(list(@~[num(3f), num(1f)]));
assert from_str(~"\n[3, 2]\n") == ok(list(@~[num(3f), num(2f)])); assert from_str(~"\n[3, 2]\n") == Ok(list(@~[num(3f), num(2f)]));
assert from_str(~"[2, [4, 1]]") == assert from_str(~"[2, [4, 1]]") ==
ok(list(@~[num(2f), list(@~[num(4f), num(1f)])])); Ok(list(@~[num(2f), list(@~[num(4f), num(1f)])]));
} }
#[test] #[test]
fn test_read_dict() { fn test_read_dict() {
assert from_str(~"{") == assert from_str(~"{") ==
err({line: 1u, col: 2u, msg: @~"EOF while parsing object"}); Err({line: 1u, col: 2u, msg: @~"EOF while parsing object"});
assert from_str(~"{ ") == assert from_str(~"{ ") ==
err({line: 1u, col: 3u, msg: @~"EOF while parsing object"}); Err({line: 1u, col: 3u, msg: @~"EOF while parsing object"});
assert from_str(~"{1") == assert from_str(~"{1") ==
err({line: 1u, col: 2u, msg: @~"key must be a string"}); Err({line: 1u, col: 2u, msg: @~"key must be a string"});
assert from_str(~"{ \"a\"") == assert from_str(~"{ \"a\"") ==
err({line: 1u, col: 6u, msg: @~"EOF while parsing object"}); Err({line: 1u, col: 6u, msg: @~"EOF while parsing object"});
assert from_str(~"{\"a\"") == assert from_str(~"{\"a\"") ==
err({line: 1u, col: 5u, msg: @~"EOF while parsing object"}); Err({line: 1u, col: 5u, msg: @~"EOF while parsing object"});
assert from_str(~"{\"a\" ") == assert from_str(~"{\"a\" ") ==
err({line: 1u, col: 6u, msg: @~"EOF while parsing object"}); Err({line: 1u, col: 6u, msg: @~"EOF while parsing object"});
assert from_str(~"{\"a\" 1") == assert from_str(~"{\"a\" 1") ==
err({line: 1u, col: 6u, msg: @~"expected `:`"}); Err({line: 1u, col: 6u, msg: @~"expected `:`"});
assert from_str(~"{\"a\":") == assert from_str(~"{\"a\":") ==
err({line: 1u, col: 6u, msg: @~"EOF while parsing value"}); Err({line: 1u, col: 6u, msg: @~"EOF while parsing value"});
assert from_str(~"{\"a\":1") == assert from_str(~"{\"a\":1") ==
err({line: 1u, col: 7u, msg: @~"EOF while parsing object"}); Err({line: 1u, col: 7u, msg: @~"EOF while parsing object"});
assert from_str(~"{\"a\":1 1") == assert from_str(~"{\"a\":1 1") ==
err({line: 1u, col: 8u, msg: @~"expected `,` or `}`"}); Err({line: 1u, col: 8u, msg: @~"expected `,` or `}`"});
assert from_str(~"{\"a\":1,") == assert from_str(~"{\"a\":1,") ==
err({line: 1u, col: 8u, msg: @~"EOF while parsing object"}); Err({line: 1u, col: 8u, msg: @~"EOF while parsing object"});
assert eq(result::get(from_str(~"{}")), mk_dict(~[])); assert eq(result::get(from_str(~"{}")), mk_dict(~[]));
assert eq(result::get(from_str(~"{\"a\": 3}")), assert eq(result::get(from_str(~"{\"a\": 3}")),
@ -879,6 +879,6 @@ mod tests {
#[test] #[test]
fn test_multiline_errors() { fn test_multiline_errors() {
assert from_str(~"{\n \"foo\":\n \"bar\"") == assert from_str(~"{\n \"foo\":\n \"bar\"") ==
err({line: 3u, col: 8u, msg: @~"EOF while parsing object"}); Err({line: 3u, col: 8u, msg: @~"EOF while parsing object"});
} }
} }

View file

@ -85,7 +85,7 @@ enum ip_get_addr_err {
* object in the case of failure * object in the case of failure
*/ */
fn get_addr(++node: ~str, iotask: iotask) fn get_addr(++node: ~str, iotask: iotask)
-> result::result<~[ip_addr], ip_get_addr_err> { -> result::Result<~[ip_addr], ip_get_addr_err> {
do core::comm::listen |output_ch| { do core::comm::listen |output_ch| {
do str::as_buf(node) |node_ptr, len| unsafe { do str::as_buf(node) |node_ptr, len| unsafe {
log(debug, fmt!("slice len %?", len)); log(debug, fmt!("slice len %?", len));
@ -108,7 +108,7 @@ fn get_addr(++node: ~str, iotask: iotask)
set_data_for_req(handle_ptr, handle_data_ptr); set_data_for_req(handle_ptr, handle_data_ptr);
} }
_ => { _ => {
output_ch.send(result::err(get_addr_unknown_error)); output_ch.send(result::Err(get_addr_unknown_error));
} }
} }
}; };
@ -135,8 +135,8 @@ mod v4 {
*/ */
fn parse_addr(ip: ~str) -> ip_addr { fn parse_addr(ip: ~str) -> ip_addr {
match try_parse_addr(ip) { match try_parse_addr(ip) {
result::ok(addr) => copy(addr), result::Ok(addr) => copy(addr),
result::err(err_data) => fail err_data.err_msg result::Err(err_data) => fail err_data.err_msg
} }
} }
// the simple, old style numberic representation of // the simple, old style numberic representation of
@ -153,7 +153,7 @@ mod v4 {
*((ptr::addr_of(self)) as *u32) *((ptr::addr_of(self)) as *u32)
} }
} }
fn parse_to_ipv4_rep(ip: ~str) -> result::result<ipv4_rep, ~str> { fn parse_to_ipv4_rep(ip: ~str) -> result::Result<ipv4_rep, ~str> {
let parts = vec::map(str::split_char(ip, '.'), |s| { let parts = vec::map(str::split_char(ip, '.'), |s| {
match uint::from_str(s) { match uint::from_str(s) {
Some(n) if n <= 255u => n, Some(n) if n <= 255u => n,
@ -161,23 +161,23 @@ mod v4 {
} }
}); });
if vec::len(parts) != 4u { if vec::len(parts) != 4u {
result::err(fmt!("'%s' doesn't have 4 parts", ip)) result::Err(fmt!("'%s' doesn't have 4 parts", ip))
} }
else if vec::contains(parts, 256u) { else if vec::contains(parts, 256u) {
result::err(fmt!("invalid octal in addr '%s'", ip)) result::Err(fmt!("invalid octal in addr '%s'", ip))
} }
else { else {
result::ok({a: parts[0] as u8, b: parts[1] as u8, result::Ok({a: parts[0] as u8, b: parts[1] as u8,
c: parts[2] as u8, d: parts[3] as u8}) c: parts[2] as u8, d: parts[3] as u8})
} }
} }
fn try_parse_addr(ip: ~str) -> result::result<ip_addr,parse_addr_err> { fn try_parse_addr(ip: ~str) -> result::Result<ip_addr,parse_addr_err> {
unsafe { unsafe {
let INADDR_NONE = ll::get_INADDR_NONE(); let INADDR_NONE = ll::get_INADDR_NONE();
let ip_rep_result = parse_to_ipv4_rep(ip); let ip_rep_result = parse_to_ipv4_rep(ip);
if result::is_err(ip_rep_result) { if result::is_err(ip_rep_result) {
let err_str = result::get_err(ip_rep_result); let err_str = result::get_err(ip_rep_result);
return result::err({err_msg: err_str}) return result::Err({err_msg: err_str})
} }
// ipv4_rep.as_u32 is unsafe :/ // ipv4_rep.as_u32 is unsafe :/
let input_is_inaddr_none = let input_is_inaddr_none =
@ -190,15 +190,15 @@ mod v4 {
let ref_ip_rep_result = parse_to_ipv4_rep(reformatted_name); let ref_ip_rep_result = parse_to_ipv4_rep(reformatted_name);
if result::is_err(ref_ip_rep_result) { if result::is_err(ref_ip_rep_result) {
let err_str = result::get_err(ref_ip_rep_result); let err_str = result::get_err(ref_ip_rep_result);
return result::err({err_msg: err_str}) return result::Err({err_msg: err_str})
} }
if result::get(ref_ip_rep_result).as_u32() == INADDR_NONE && if result::get(ref_ip_rep_result).as_u32() == INADDR_NONE &&
!input_is_inaddr_none { !input_is_inaddr_none {
return result::err( return result::Err(
{err_msg: ~"uv_ip4_name produced invalid result."}) {err_msg: ~"uv_ip4_name produced invalid result."})
} }
else { else {
result::ok(ipv4(copy(new_addr))) result::Ok(ipv4(copy(new_addr)))
} }
} }
} }
@ -221,11 +221,11 @@ mod v6 {
*/ */
fn parse_addr(ip: ~str) -> ip_addr { fn parse_addr(ip: ~str) -> ip_addr {
match try_parse_addr(ip) { match try_parse_addr(ip) {
result::ok(addr) => copy(addr), result::Ok(addr) => copy(addr),
result::err(err_data) => fail err_data.err_msg result::Err(err_data) => fail err_data.err_msg
} }
} }
fn try_parse_addr(ip: ~str) -> result::result<ip_addr,parse_addr_err> { fn try_parse_addr(ip: ~str) -> result::Result<ip_addr,parse_addr_err> {
unsafe { unsafe {
// need to figure out how to establish a parse failure.. // need to figure out how to establish a parse failure..
let new_addr = uv_ip6_addr(ip, 22); let new_addr = uv_ip6_addr(ip, 22);
@ -235,18 +235,18 @@ mod v6 {
// '::' appears to be uv_ip6_name() returns for bogus // '::' appears to be uv_ip6_name() returns for bogus
// parses.. // parses..
if ip != ~"::" && reparsed_name == ~"::" { if ip != ~"::" && reparsed_name == ~"::" {
result::err({err_msg:fmt!("failed to parse '%s'", result::Err({err_msg:fmt!("failed to parse '%s'",
ip)}) ip)})
} }
else { else {
result::ok(ipv6(new_addr)) result::Ok(ipv6(new_addr))
} }
} }
} }
} }
type get_addr_data = { type get_addr_data = {
output_ch: comm::Chan<result::result<~[ip_addr],ip_get_addr_err>> output_ch: comm::Chan<result::Result<~[ip_addr],ip_get_addr_err>>
}; };
extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int, extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int,
@ -272,7 +272,7 @@ extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int,
log(debug, ~"curr_addr is not of family AF_INET or "+ log(debug, ~"curr_addr is not of family AF_INET or "+
~"AF_INET6. Error."); ~"AF_INET6. Error.");
(*handle_data).output_ch.send( (*handle_data).output_ch.send(
result::err(get_addr_unknown_error)); result::Err(get_addr_unknown_error));
break; break;
}; };
out_vec += ~[new_ip_addr]; out_vec += ~[new_ip_addr];
@ -289,18 +289,18 @@ extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int,
} }
log(debug, fmt!("successful process addrinfo result, len: %?", log(debug, fmt!("successful process addrinfo result, len: %?",
vec::len(out_vec))); vec::len(out_vec)));
(*handle_data).output_ch.send(result::ok(out_vec)); (*handle_data).output_ch.send(result::Ok(out_vec));
} }
else { else {
log(debug, ~"addrinfo pointer is NULL"); log(debug, ~"addrinfo pointer is NULL");
(*handle_data).output_ch.send( (*handle_data).output_ch.send(
result::err(get_addr_unknown_error)); result::Err(get_addr_unknown_error));
} }
} }
else { else {
log(debug, ~"status != 0 error in get_addr_cb"); log(debug, ~"status != 0 error in get_addr_cb");
(*handle_data).output_ch.send( (*handle_data).output_ch.send(
result::err(get_addr_unknown_error)); result::Err(get_addr_unknown_error));
} }
if res != (ptr::null::<addrinfo>()) { if res != (ptr::null::<addrinfo>()) {
uv_freeaddrinfo(res); uv_freeaddrinfo(res);
@ -327,11 +327,11 @@ mod test {
#[test] #[test]
fn test_ip_ipv4_bad_parse() { fn test_ip_ipv4_bad_parse() {
match v4::try_parse_addr(~"b4df00d") { match v4::try_parse_addr(~"b4df00d") {
result::err(err_info) => { result::Err(err_info) => {
log(debug, fmt!("got error as expected %?", err_info)); log(debug, fmt!("got error as expected %?", err_info));
assert true; assert true;
} }
result::ok(addr) => { result::Ok(addr) => {
fail fmt!("Expected failure, but got addr %?", addr); fail fmt!("Expected failure, but got addr %?", addr);
} }
} }
@ -340,11 +340,11 @@ mod test {
#[ignore(target_os="win32")] #[ignore(target_os="win32")]
fn test_ip_ipv6_bad_parse() { fn test_ip_ipv6_bad_parse() {
match v6::try_parse_addr(~"::,~2234k;") { match v6::try_parse_addr(~"::,~2234k;") {
result::err(err_info) => { result::Err(err_info) => {
log(debug, fmt!("got error as expected %?", err_info)); log(debug, fmt!("got error as expected %?", err_info));
assert true; assert true;
} }
result::ok(addr) => { result::Ok(addr) => {
fail fmt!("Expected failure, but got addr %?", addr); fail fmt!("Expected failure, but got addr %?", addr);
} }
} }

View file

@ -120,7 +120,7 @@ enum tcp_connect_err_data {
*/ */
fn connect(-input_ip: ip::ip_addr, port: uint, fn connect(-input_ip: ip::ip_addr, port: uint,
iotask: iotask) iotask: iotask)
-> result::result<tcp_socket, tcp_connect_err_data> unsafe { -> result::Result<tcp_socket, tcp_connect_err_data> unsafe {
let result_po = core::comm::port::<conn_attempt>(); let result_po = core::comm::port::<conn_attempt>();
let closed_signal_po = core::comm::port::<()>(); let closed_signal_po = core::comm::port::<()>();
let conn_data = { let conn_data = {
@ -128,7 +128,7 @@ fn connect(-input_ip: ip::ip_addr, port: uint,
closed_signal_ch: core::comm::chan(closed_signal_po) closed_signal_ch: core::comm::chan(closed_signal_po)
}; };
let conn_data_ptr = ptr::addr_of(conn_data); let conn_data_ptr = ptr::addr_of(conn_data);
let reader_po = core::comm::port::<result::result<~[u8], tcp_err_data>>(); let reader_po = core::comm::port::<result::Result<~[u8], tcp_err_data>>();
let stream_handle_ptr = malloc_uv_tcp_t(); let stream_handle_ptr = malloc_uv_tcp_t();
*(stream_handle_ptr as *mut uv::ll::uv_tcp_t) = uv::ll::tcp_t(); *(stream_handle_ptr as *mut uv::ll::uv_tcp_t) = uv::ll::tcp_t();
let socket_data = @{ let socket_data = @{
@ -220,7 +220,7 @@ fn connect(-input_ip: ip::ip_addr, port: uint,
match core::comm::recv(result_po) { match core::comm::recv(result_po) {
conn_success => { conn_success => {
log(debug, ~"tcp::connect - received success on result_po"); log(debug, ~"tcp::connect - received success on result_po");
result::ok(tcp_socket(socket_data)) result::Ok(tcp_socket(socket_data))
} }
conn_failure(err_data) => { conn_failure(err_data) => {
core::comm::recv(closed_signal_po); core::comm::recv(closed_signal_po);
@ -232,7 +232,7 @@ fn connect(-input_ip: ip::ip_addr, port: uint,
~"ECONNREFUSED" => connection_refused, ~"ECONNREFUSED" => connection_refused,
_ => generic_connect_err(err_data.err_name, err_data.err_msg) _ => generic_connect_err(err_data.err_name, err_data.err_msg)
}; };
result::err(tcp_conn_err) result::Err(tcp_conn_err)
} }
} }
} }
@ -252,7 +252,7 @@ fn connect(-input_ip: ip::ip_addr, port: uint,
* `tcp_err_data` value as the `err` variant * `tcp_err_data` value as the `err` variant
*/ */
fn write(sock: tcp_socket, raw_write_data: ~[u8]) fn write(sock: tcp_socket, raw_write_data: ~[u8])
-> result::result<(), tcp_err_data> unsafe { -> result::Result<(), tcp_err_data> unsafe {
let socket_data_ptr = ptr::addr_of(*(sock.socket_data)); let socket_data_ptr = ptr::addr_of(*(sock.socket_data));
write_common_impl(socket_data_ptr, raw_write_data) write_common_impl(socket_data_ptr, raw_write_data)
} }
@ -289,7 +289,7 @@ fn write(sock: tcp_socket, raw_write_data: ~[u8])
* value as the `err` variant * value as the `err` variant
*/ */
fn write_future(sock: tcp_socket, raw_write_data: ~[u8]) fn write_future(sock: tcp_socket, raw_write_data: ~[u8])
-> future::Future<result::result<(), tcp_err_data>> unsafe { -> future::Future<result::Result<(), tcp_err_data>> unsafe {
let socket_data_ptr = ptr::addr_of(*(sock.socket_data)); let socket_data_ptr = ptr::addr_of(*(sock.socket_data));
do future_spawn { do future_spawn {
let data_copy = copy(raw_write_data); let data_copy = copy(raw_write_data);
@ -313,8 +313,8 @@ fn write_future(sock: tcp_socket, raw_write_data: ~[u8])
* `tcp_err_data` record * `tcp_err_data` record
*/ */
fn read_start(sock: tcp_socket) fn read_start(sock: tcp_socket)
-> result::result<comm::Port< -> result::Result<comm::Port<
result::result<~[u8], tcp_err_data>>, tcp_err_data> unsafe { result::Result<~[u8], tcp_err_data>>, tcp_err_data> unsafe {
let socket_data = ptr::addr_of(*(sock.socket_data)); let socket_data = ptr::addr_of(*(sock.socket_data));
read_start_common_impl(socket_data) read_start_common_impl(socket_data)
} }
@ -327,8 +327,8 @@ fn read_start(sock: tcp_socket)
* * `sock` - a `net::tcp::tcp_socket` that you wish to stop reading on * * `sock` - a `net::tcp::tcp_socket` that you wish to stop reading on
*/ */
fn read_stop(sock: tcp_socket, fn read_stop(sock: tcp_socket,
-read_port: comm::Port<result::result<~[u8], tcp_err_data>>) -> -read_port: comm::Port<result::Result<~[u8], tcp_err_data>>) ->
result::result<(), tcp_err_data> unsafe { result::Result<(), tcp_err_data> unsafe {
log(debug, fmt!("taking the read_port out of commission %?", read_port)); log(debug, fmt!("taking the read_port out of commission %?", read_port));
let socket_data = ptr::addr_of(*sock.socket_data); let socket_data = ptr::addr_of(*sock.socket_data);
read_stop_common_impl(socket_data) read_stop_common_impl(socket_data)
@ -350,7 +350,7 @@ fn read_stop(sock: tcp_socket,
* read attempt. Pass `0u` to wait indefinitely * read attempt. Pass `0u` to wait indefinitely
*/ */
fn read(sock: tcp_socket, timeout_msecs: uint) fn read(sock: tcp_socket, timeout_msecs: uint)
-> result::result<~[u8],tcp_err_data> { -> result::Result<~[u8],tcp_err_data> {
let socket_data = ptr::addr_of(*(sock.socket_data)); let socket_data = ptr::addr_of(*(sock.socket_data));
read_common_impl(socket_data, timeout_msecs) read_common_impl(socket_data, timeout_msecs)
} }
@ -385,7 +385,7 @@ fn read(sock: tcp_socket, timeout_msecs: uint)
* read attempt. Pass `0u` to wait indefinitely * read attempt. Pass `0u` to wait indefinitely
*/ */
fn read_future(sock: tcp_socket, timeout_msecs: uint) fn read_future(sock: tcp_socket, timeout_msecs: uint)
-> future::Future<result::result<~[u8],tcp_err_data>> { -> future::Future<result::Result<~[u8],tcp_err_data>> {
let socket_data = ptr::addr_of(*(sock.socket_data)); let socket_data = ptr::addr_of(*(sock.socket_data));
do future_spawn { do future_spawn {
read_common_impl(socket_data, timeout_msecs) read_common_impl(socket_data, timeout_msecs)
@ -462,7 +462,7 @@ fn read_future(sock: tcp_socket, timeout_msecs: uint)
* as the `err` variant of a `result`. * as the `err` variant of a `result`.
*/ */
fn accept(new_conn: tcp_new_connection) fn accept(new_conn: tcp_new_connection)
-> result::result<tcp_socket, tcp_err_data> unsafe { -> result::Result<tcp_socket, tcp_err_data> unsafe {
match new_conn{ match new_conn{
new_tcp_conn(server_handle_ptr) => { new_tcp_conn(server_handle_ptr) => {
@ -524,8 +524,8 @@ fn accept(new_conn: tcp_new_connection)
} }
// UNSAFE LIBUV INTERACTION END // UNSAFE LIBUV INTERACTION END
match core::comm::recv(result_po) { match core::comm::recv(result_po) {
Some(err_data) => result::err(err_data), Some(err_data) => result::Err(err_data),
None => result::ok(tcp_socket(client_socket_data)) None => result::Ok(tcp_socket(client_socket_data))
} }
} }
} }
@ -564,7 +564,7 @@ fn listen(-host_ip: ip::ip_addr, port: uint, backlog: uint,
on_establish_cb: fn~(comm::Chan<Option<tcp_err_data>>), on_establish_cb: fn~(comm::Chan<Option<tcp_err_data>>),
+new_connect_cb: fn~(tcp_new_connection, +new_connect_cb: fn~(tcp_new_connection,
comm::Chan<Option<tcp_err_data>>)) comm::Chan<Option<tcp_err_data>>))
-> result::result<(), tcp_listen_err_data> unsafe { -> result::Result<(), tcp_listen_err_data> unsafe {
do listen_common(host_ip, port, backlog, iotask, on_establish_cb) do listen_common(host_ip, port, backlog, iotask, on_establish_cb)
// on_connect_cb // on_connect_cb
|handle| unsafe { |handle| unsafe {
@ -580,7 +580,7 @@ fn listen_common(-host_ip: ip::ip_addr, port: uint, backlog: uint,
iotask: iotask, iotask: iotask,
on_establish_cb: fn~(comm::Chan<Option<tcp_err_data>>), on_establish_cb: fn~(comm::Chan<Option<tcp_err_data>>),
-on_connect_cb: fn~(*uv::ll::uv_tcp_t)) -on_connect_cb: fn~(*uv::ll::uv_tcp_t))
-> result::result<(), tcp_listen_err_data> unsafe { -> result::Result<(), tcp_listen_err_data> unsafe {
let stream_closed_po = core::comm::port::<()>(); let stream_closed_po = core::comm::port::<()>();
let kill_po = core::comm::port::<Option<tcp_err_data>>(); let kill_po = core::comm::port::<Option<tcp_err_data>>();
let kill_ch = core::comm::chan(kill_po); let kill_ch = core::comm::chan(kill_po);
@ -666,16 +666,16 @@ fn listen_common(-host_ip: ip::ip_addr, port: uint, backlog: uint,
match err_data.err_name { match err_data.err_name {
~"EACCES" => { ~"EACCES" => {
log(debug, ~"Got EACCES error"); log(debug, ~"Got EACCES error");
result::err(access_denied) result::Err(access_denied)
} }
~"EADDRINUSE" => { ~"EADDRINUSE" => {
log(debug, ~"Got EADDRINUSE error"); log(debug, ~"Got EADDRINUSE error");
result::err(address_in_use) result::Err(address_in_use)
} }
_ => { _ => {
log(debug, fmt!("Got '%s' '%s' libuv error", log(debug, fmt!("Got '%s' '%s' libuv error",
err_data.err_name, err_data.err_msg)); err_data.err_name, err_data.err_msg));
result::err( result::Err(
generic_listen_err(err_data.err_name, err_data.err_msg)) generic_listen_err(err_data.err_name, err_data.err_msg))
} }
} }
@ -692,10 +692,10 @@ fn listen_common(-host_ip: ip::ip_addr, port: uint, backlog: uint,
stream_closed_po.recv(); stream_closed_po.recv();
match kill_result { match kill_result {
// some failure post bind/listen // some failure post bind/listen
Some(err_data) => result::err(generic_listen_err(err_data.err_name, Some(err_data) => result::Err(generic_listen_err(err_data.err_name,
err_data.err_msg)), err_data.err_msg)),
// clean exit // clean exit
None => result::ok(()) None => result::Ok(())
} }
} }
} }
@ -722,29 +722,29 @@ fn socket_buf(-sock: tcp_socket) -> tcp_socket_buf {
/// Convenience methods extending `net::tcp::tcp_socket` /// Convenience methods extending `net::tcp::tcp_socket`
impl tcp_socket { impl tcp_socket {
fn read_start() -> result::result<comm::Port< fn read_start() -> result::Result<comm::Port<
result::result<~[u8], tcp_err_data>>, tcp_err_data> { result::Result<~[u8], tcp_err_data>>, tcp_err_data> {
read_start(self) read_start(self)
} }
fn read_stop(-read_port: fn read_stop(-read_port:
comm::Port<result::result<~[u8], tcp_err_data>>) -> comm::Port<result::Result<~[u8], tcp_err_data>>) ->
result::result<(), tcp_err_data> { result::Result<(), tcp_err_data> {
read_stop(self, read_port) read_stop(self, read_port)
} }
fn read(timeout_msecs: uint) -> fn read(timeout_msecs: uint) ->
result::result<~[u8], tcp_err_data> { result::Result<~[u8], tcp_err_data> {
read(self, timeout_msecs) read(self, timeout_msecs)
} }
fn read_future(timeout_msecs: uint) -> fn read_future(timeout_msecs: uint) ->
future::Future<result::result<~[u8], tcp_err_data>> { future::Future<result::Result<~[u8], tcp_err_data>> {
read_future(self, timeout_msecs) read_future(self, timeout_msecs)
} }
fn write(raw_write_data: ~[u8]) fn write(raw_write_data: ~[u8])
-> result::result<(), tcp_err_data> { -> result::Result<(), tcp_err_data> {
write(self, raw_write_data) write(self, raw_write_data)
} }
fn write_future(raw_write_data: ~[u8]) fn write_future(raw_write_data: ~[u8])
-> future::Future<result::result<(), tcp_err_data>> { -> future::Future<result::Result<(), tcp_err_data>> {
write_future(self, raw_write_data) write_future(self, raw_write_data)
} }
} }
@ -856,13 +856,13 @@ fn tear_down_socket_data(socket_data: @tcp_socket_data) unsafe {
// shared implementation for tcp::read // shared implementation for tcp::read
fn read_common_impl(socket_data: *tcp_socket_data, timeout_msecs: uint) fn read_common_impl(socket_data: *tcp_socket_data, timeout_msecs: uint)
-> result::result<~[u8],tcp_err_data> unsafe { -> result::Result<~[u8],tcp_err_data> unsafe {
log(debug, ~"starting tcp::read"); log(debug, ~"starting tcp::read");
let iotask = (*socket_data).iotask; let iotask = (*socket_data).iotask;
let rs_result = read_start_common_impl(socket_data); let rs_result = read_start_common_impl(socket_data);
if result::is_err(rs_result) { if result::is_err(rs_result) {
let err_data = result::get_err(rs_result); let err_data = result::get_err(rs_result);
result::err(err_data) result::Err(err_data)
} }
else { else {
log(debug, ~"tcp::read before recv_timeout"); log(debug, ~"tcp::read before recv_timeout");
@ -881,7 +881,7 @@ fn read_common_impl(socket_data: *tcp_socket_data, timeout_msecs: uint)
err_msg: ~"req timed out" err_msg: ~"req timed out"
}; };
read_stop_common_impl(socket_data); read_stop_common_impl(socket_data);
result::err(err_data) result::Err(err_data)
} }
Some(data_result) => { Some(data_result) => {
log(debug, ~"tcp::read got data"); log(debug, ~"tcp::read got data");
@ -894,7 +894,7 @@ fn read_common_impl(socket_data: *tcp_socket_data, timeout_msecs: uint)
// shared impl for read_stop // shared impl for read_stop
fn read_stop_common_impl(socket_data: *tcp_socket_data) -> fn read_stop_common_impl(socket_data: *tcp_socket_data) ->
result::result<(), tcp_err_data> unsafe { result::Result<(), tcp_err_data> unsafe {
let stream_handle_ptr = (*socket_data).stream_handle_ptr; let stream_handle_ptr = (*socket_data).stream_handle_ptr;
let stop_po = core::comm::port::<Option<tcp_err_data>>(); let stop_po = core::comm::port::<Option<tcp_err_data>>();
let stop_ch = core::comm::chan(stop_po); let stop_ch = core::comm::chan(stop_po);
@ -913,15 +913,15 @@ fn read_stop_common_impl(socket_data: *tcp_socket_data) ->
} }
}; };
match core::comm::recv(stop_po) { match core::comm::recv(stop_po) {
Some(err_data) => result::err(err_data.to_tcp_err()), Some(err_data) => result::Err(err_data.to_tcp_err()),
None => result::ok(()) None => result::Ok(())
} }
} }
// shared impl for read_start // shared impl for read_start
fn read_start_common_impl(socket_data: *tcp_socket_data) fn read_start_common_impl(socket_data: *tcp_socket_data)
-> result::result<comm::Port< -> result::Result<comm::Port<
result::result<~[u8], tcp_err_data>>, tcp_err_data> unsafe { result::Result<~[u8], tcp_err_data>>, tcp_err_data> unsafe {
let stream_handle_ptr = (*socket_data).stream_handle_ptr; let stream_handle_ptr = (*socket_data).stream_handle_ptr;
let start_po = core::comm::port::<Option<uv::ll::uv_err_data>>(); let start_po = core::comm::port::<Option<uv::ll::uv_err_data>>();
let start_ch = core::comm::chan(start_po); let start_ch = core::comm::chan(start_po);
@ -943,8 +943,8 @@ fn read_start_common_impl(socket_data: *tcp_socket_data)
} }
}; };
match core::comm::recv(start_po) { match core::comm::recv(start_po) {
Some(err_data) => result::err(err_data.to_tcp_err()), Some(err_data) => result::Err(err_data.to_tcp_err()),
None => result::ok((*socket_data).reader_po) None => result::Ok((*socket_data).reader_po)
} }
} }
@ -953,7 +953,7 @@ fn read_start_common_impl(socket_data: *tcp_socket_data)
// shared implementation used by write and write_future // shared implementation used by write and write_future
fn write_common_impl(socket_data_ptr: *tcp_socket_data, fn write_common_impl(socket_data_ptr: *tcp_socket_data,
raw_write_data: ~[u8]) raw_write_data: ~[u8])
-> result::result<(), tcp_err_data> unsafe { -> result::Result<(), tcp_err_data> unsafe {
let write_req_ptr = ptr::addr_of((*socket_data_ptr).write_req); let write_req_ptr = ptr::addr_of((*socket_data_ptr).write_req);
let stream_handle_ptr = let stream_handle_ptr =
(*socket_data_ptr).stream_handle_ptr; (*socket_data_ptr).stream_handle_ptr;
@ -989,8 +989,8 @@ fn write_common_impl(socket_data_ptr: *tcp_socket_data,
// ownership of everything to the I/O task and let it deal with the // ownership of everything to the I/O task and let it deal with the
// aftermath, so we don't have to sit here blocking. // aftermath, so we don't have to sit here blocking.
match core::comm::recv(result_po) { match core::comm::recv(result_po) {
tcp_write_success => result::ok(()), tcp_write_success => result::Ok(()),
tcp_write_error(err_data) => result::err(err_data.to_tcp_err()) tcp_write_error(err_data) => result::Err(err_data.to_tcp_err())
} }
} }
@ -1083,7 +1083,7 @@ extern fn on_tcp_read_cb(stream: *uv::ll::uv_stream_t,
log(debug, fmt!("on_tcp_read_cb: incoming err.. name %? msg %?", log(debug, fmt!("on_tcp_read_cb: incoming err.. name %? msg %?",
err_data.err_name, err_data.err_msg)); err_data.err_name, err_data.err_msg));
let reader_ch = (*socket_data_ptr).reader_ch; let reader_ch = (*socket_data_ptr).reader_ch;
core::comm::send(reader_ch, result::err(err_data)); core::comm::send(reader_ch, result::Err(err_data));
} }
// do nothing .. unneeded buf // do nothing .. unneeded buf
0 => (), 0 => (),
@ -1094,7 +1094,7 @@ extern fn on_tcp_read_cb(stream: *uv::ll::uv_stream_t,
let reader_ch = (*socket_data_ptr).reader_ch; let reader_ch = (*socket_data_ptr).reader_ch;
let buf_base = uv::ll::get_base_from_buf(buf); let buf_base = uv::ll::get_base_from_buf(buf);
let new_bytes = vec::unsafe::from_buf(buf_base, nread as uint); let new_bytes = vec::unsafe::from_buf(buf_base, nread as uint);
core::comm::send(reader_ch, result::ok(new_bytes)); core::comm::send(reader_ch, result::Ok(new_bytes));
} }
} }
uv::ll::free_base_of_buf(buf); uv::ll::free_base_of_buf(buf);
@ -1197,8 +1197,8 @@ enum conn_attempt {
} }
type tcp_socket_data = { type tcp_socket_data = {
reader_po: comm::Port<result::result<~[u8], tcp_err_data>>, reader_po: comm::Port<result::Result<~[u8], tcp_err_data>>,
reader_ch: comm::Chan<result::result<~[u8], tcp_err_data>>, reader_ch: comm::Chan<result::Result<~[u8], tcp_err_data>>,
stream_handle_ptr: *uv::ll::uv_tcp_t, stream_handle_ptr: *uv::ll::uv_tcp_t,
connect_req: uv::ll::uv_connect_t, connect_req: uv::ll::uv_connect_t,
write_req: uv::ll::uv_write_t, write_req: uv::ll::uv_write_t,
@ -1515,7 +1515,7 @@ mod test {
~"connection!"); ~"connection!");
let received_req_bytes = read(sock, 0u); let received_req_bytes = read(sock, 0u);
match received_req_bytes { match received_req_bytes {
result::ok(data) => { result::Ok(data) => {
log(debug, ~"SERVER: got REQ str::from_bytes.."); log(debug, ~"SERVER: got REQ str::from_bytes..");
log(debug, fmt!("SERVER: REQ data len: %?", log(debug, fmt!("SERVER: REQ data len: %?",
vec::len(data))); vec::len(data)));
@ -1526,7 +1526,7 @@ mod test {
log(debug, ~"SERVER: after write.. die"); log(debug, ~"SERVER: after write.. die");
core::comm::send(kill_ch, None); core::comm::send(kill_ch, None);
} }
result::err(err_data) => { result::Err(err_data) => {
log(debug, fmt!("SERVER: error recvd: %s %s", log(debug, fmt!("SERVER: error recvd: %s %s",
err_data.err_name, err_data.err_msg)); err_data.err_name, err_data.err_msg));
core::comm::send(kill_ch, Some(err_data)); core::comm::send(kill_ch, Some(err_data));
@ -1585,7 +1585,7 @@ mod test {
fn run_tcp_test_client(server_ip: ~str, server_port: uint, resp: ~str, fn run_tcp_test_client(server_ip: ~str, server_port: uint, resp: ~str,
client_ch: comm::Chan<~str>, client_ch: comm::Chan<~str>,
iotask: iotask) -> result::result<~str, iotask: iotask) -> result::Result<~str,
tcp_connect_err_data> { tcp_connect_err_data> {
let server_ip_addr = ip::v4::parse_addr(server_ip); let server_ip_addr = ip::v4::parse_addr(server_ip);
@ -1594,7 +1594,7 @@ mod test {
if result::is_err(connect_result) { if result::is_err(connect_result) {
log(debug, ~"CLIENT: failed to connect"); log(debug, ~"CLIENT: failed to connect");
let err_data = result::get_err(connect_result); let err_data = result::get_err(connect_result);
err(err_data) Err(err_data)
} }
else { else {
let sock = result::unwrap(connect_result); let sock = result::unwrap(connect_result);
@ -1603,14 +1603,14 @@ mod test {
let read_result = sock.read(0u); let read_result = sock.read(0u);
if read_result.is_err() { if read_result.is_err() {
log(debug, ~"CLIENT: failure to read"); log(debug, ~"CLIENT: failure to read");
ok(~"") Ok(~"")
} }
else { else {
client_ch.send(str::from_bytes(read_result.get())); client_ch.send(str::from_bytes(read_result.get()));
let ret_val = client_ch.recv(); let ret_val = client_ch.recv();
log(debug, fmt!("CLIENT: after client_ch recv ret: '%s'", log(debug, fmt!("CLIENT: after client_ch recv ret: '%s'",
ret_val)); ret_val));
ok(ret_val) Ok(ret_val)
} }
} }
} }

View file

@ -330,38 +330,38 @@ fn query_to_str(query: query) -> ~str {
} }
// returns the scheme and the rest of the url, or a parsing error // returns the scheme and the rest of the url, or a parsing error
fn get_scheme(rawurl: ~str) -> result::result<(~str, ~str), @~str> { fn get_scheme(rawurl: ~str) -> result::Result<(~str, ~str), @~str> {
for str::each_chari(rawurl) |i,c| { for str::each_chari(rawurl) |i,c| {
match c { match c {
'A' to 'Z' | 'a' to 'z' => again, 'A' to 'Z' | 'a' to 'z' => again,
'0' to '9' | '+' | '-' | '.' => { '0' to '9' | '+' | '-' | '.' => {
if i == 0 { if i == 0 {
return result::err(@~"url: Scheme must begin with a letter."); return result::Err(@~"url: Scheme must begin with a letter.");
} }
again; again;
} }
':' => { ':' => {
if i == 0 { if i == 0 {
return result::err(@~"url: Scheme cannot be empty."); return result::Err(@~"url: Scheme cannot be empty.");
} else { } else {
return result::ok((rawurl.slice(0,i), return result::Ok((rawurl.slice(0,i),
rawurl.slice(i+1,str::len(rawurl)))); rawurl.slice(i+1,str::len(rawurl))));
} }
} }
_ => { _ => {
return result::err(@~"url: Invalid character in scheme."); return result::Err(@~"url: Invalid character in scheme.");
} }
} }
}; };
return result::err(@~"url: Scheme must be terminated with a colon."); return result::Err(@~"url: Scheme must be terminated with a colon.");
} }
// returns userinfo, host, port, and unparsed part, or an error // returns userinfo, host, port, and unparsed part, or an error
fn get_authority(rawurl: ~str) -> fn get_authority(rawurl: ~str) ->
result::result<(Option<userinfo>, ~str, Option<~str>, ~str), @~str> { result::Result<(Option<userinfo>, ~str, Option<~str>, ~str), @~str> {
if !str::starts_with(rawurl, ~"//") { if !str::starts_with(rawurl, ~"//") {
// there is no authority. // there is no authority.
return result::ok((option::None, ~"", option::None, copy rawurl)); return result::Ok((option::None, ~"", option::None, copy rawurl));
} }
enum state { enum state {
@ -407,7 +407,7 @@ fn get_authority(rawurl: ~str) ->
// separators, don't change anything // separators, don't change anything
} }
_ => { _ => {
return result::err(@~"Illegal character in authority"); return result::Err(@~"Illegal character in authority");
} }
} }
@ -423,7 +423,7 @@ fn get_authority(rawurl: ~str) ->
pass_host_port => { pass_host_port => {
// multiple colons means ipv6 address. // multiple colons means ipv6 address.
if in == unreserved { if in == unreserved {
return result::err( return result::Err(
@~"Illegal characters in IPv6 address."); @~"Illegal characters in IPv6 address.");
} }
st = ip6_host; st = ip6_host;
@ -432,13 +432,13 @@ fn get_authority(rawurl: ~str) ->
pos = i; pos = i;
// can't be sure whether this is an ipv6 address or a port // can't be sure whether this is an ipv6 address or a port
if in == unreserved { if in == unreserved {
return result::err(@~"Illegal characters in authority."); return result::Err(@~"Illegal characters in authority.");
} }
st = ip6_port; st = ip6_port;
} }
ip6_port => { ip6_port => {
if in == unreserved { if in == unreserved {
return result::err(@~"Illegal characters in authority."); return result::Err(@~"Illegal characters in authority.");
} }
st = ip6_host; st = ip6_host;
} }
@ -450,7 +450,7 @@ fn get_authority(rawurl: ~str) ->
} }
} }
_ => { _ => {
return result::err(@~"Invalid ':' in authority."); return result::Err(@~"Invalid ':' in authority.");
} }
} }
in = digit; // reset input class in = digit; // reset input class
@ -474,7 +474,7 @@ fn get_authority(rawurl: ~str) ->
st = in_host; st = in_host;
} }
_ => { _ => {
return result::err(@~"Invalid '@' in authority."); return result::Err(@~"Invalid '@' in authority.");
} }
} }
begin = i+1; begin = i+1;
@ -507,7 +507,7 @@ fn get_authority(rawurl: ~str) ->
} }
pass_host_port | ip6_port => { pass_host_port | ip6_port => {
if in != digit { if in != digit {
return result::err(@~"Non-digit characters in port."); return result::Err(@~"Non-digit characters in port.");
} }
host = str::slice(rawurl, begin, pos); host = str::slice(rawurl, begin, pos);
port = option::Some(str::slice(rawurl, pos+1, end)); port = option::Some(str::slice(rawurl, pos+1, end));
@ -517,7 +517,7 @@ fn get_authority(rawurl: ~str) ->
} }
in_port => { in_port => {
if in != digit { if in != digit {
return result::err(@~"Non-digit characters in port."); return result::Err(@~"Non-digit characters in port.");
} }
port = option::Some(str::slice(rawurl, pos+1, end)); port = option::Some(str::slice(rawurl, pos+1, end));
} }
@ -525,13 +525,13 @@ fn get_authority(rawurl: ~str) ->
let rest = if host_is_end_plus_one() { ~"" } let rest = if host_is_end_plus_one() { ~"" }
else { str::slice(rawurl, end, len) }; else { str::slice(rawurl, end, len) };
return result::ok((userinfo, host, port, rest)); return result::Ok((userinfo, host, port, rest));
} }
// returns the path and unparsed part of url, or an error // returns the path and unparsed part of url, or an error
fn get_path(rawurl: ~str, authority : bool) -> fn get_path(rawurl: ~str, authority : bool) ->
result::result<(~str, ~str), @~str> { result::Result<(~str, ~str), @~str> {
let len = str::len(rawurl); let len = str::len(rawurl);
let mut end = len; let mut end = len;
for str::each_chari(rawurl) |i,c| { for str::each_chari(rawurl) |i,c| {
@ -545,39 +545,39 @@ fn get_path(rawurl: ~str, authority : bool) ->
end = i; end = i;
break; break;
} }
_ => return result::err(@~"Invalid character in path.") _ => return result::Err(@~"Invalid character in path.")
} }
} }
if authority { if authority {
if end != 0 && !str::starts_with(rawurl, ~"/") { if end != 0 && !str::starts_with(rawurl, ~"/") {
return result::err(@~"Non-empty path must begin with\ return result::Err(@~"Non-empty path must begin with\
'/' in presence of authority."); '/' in presence of authority.");
} }
} }
return result::ok((decode_component(str::slice(rawurl, 0, end)), return result::Ok((decode_component(str::slice(rawurl, 0, end)),
str::slice(rawurl, end, len))); str::slice(rawurl, end, len)));
} }
// returns the parsed query and the fragment, if present // returns the parsed query and the fragment, if present
fn get_query_fragment(rawurl: ~str) -> fn get_query_fragment(rawurl: ~str) ->
result::result<(query, Option<~str>), @~str> { result::Result<(query, Option<~str>), @~str> {
if !str::starts_with(rawurl, ~"?") { if !str::starts_with(rawurl, ~"?") {
if str::starts_with(rawurl, ~"#") { if str::starts_with(rawurl, ~"#") {
let f = decode_component(str::slice(rawurl, let f = decode_component(str::slice(rawurl,
1, 1,
str::len(rawurl))); str::len(rawurl)));
return result::ok((~[], option::Some(f))); return result::Ok((~[], option::Some(f)));
} else { } else {
return result::ok((~[], option::None)); return result::Ok((~[], option::None));
} }
} }
let (q, r) = split_char_first(str::slice(rawurl, 1, let (q, r) = split_char_first(str::slice(rawurl, 1,
str::len(rawurl)), '#'); str::len(rawurl)), '#');
let f = if str::len(r) != 0 { let f = if str::len(r) != 0 {
option::Some(decode_component(r)) } else { option::None }; option::Some(decode_component(r)) } else { option::None };
return result::ok((query_from_str(q), f)); return result::Ok((query_from_str(q), f));
} }
/** /**
@ -593,18 +593,18 @@ fn get_query_fragment(rawurl: ~str) ->
* *
*/ */
fn from_str(rawurl: ~str) -> result::result<url, ~str> { fn from_str(rawurl: ~str) -> result::Result<url, ~str> {
// scheme // scheme
let mut schm = get_scheme(rawurl); let mut schm = get_scheme(rawurl);
if result::is_err(schm) { if result::is_err(schm) {
return result::err(copy *result::get_err(schm)); return result::Err(copy *result::get_err(schm));
} }
let (scheme, rest) = result::unwrap(schm); let (scheme, rest) = result::unwrap(schm);
// authority // authority
let mut auth = get_authority(rest); let mut auth = get_authority(rest);
if result::is_err(auth) { if result::is_err(auth) {
return result::err(copy *result::get_err(auth)); return result::Err(copy *result::get_err(auth));
} }
let (userinfo, host, port, rest) = result::unwrap(auth); let (userinfo, host, port, rest) = result::unwrap(auth);
@ -612,18 +612,18 @@ fn from_str(rawurl: ~str) -> result::result<url, ~str> {
let has_authority = if host == ~"" { false } else { true }; let has_authority = if host == ~"" { false } else { true };
let mut pth = get_path(rest, has_authority); let mut pth = get_path(rest, has_authority);
if result::is_err(pth) { if result::is_err(pth) {
return result::err(copy *result::get_err(pth)); return result::Err(copy *result::get_err(pth));
} }
let (path, rest) = result::unwrap(pth); let (path, rest) = result::unwrap(pth);
// query and fragment // query and fragment
let mut qry = get_query_fragment(rest); let mut qry = get_query_fragment(rest);
if result::is_err(qry) { if result::is_err(qry) {
return result::err(copy *result::get_err(qry)); return result::Err(copy *result::get_err(qry));
} }
let (query, fragment) = result::unwrap(qry); let (query, fragment) = result::unwrap(qry);
return result::ok(url(scheme, userinfo, host, return result::Ok(url(scheme, userinfo, host,
port, path, query, fragment)); port, path, query, fragment));
} }

View file

@ -855,7 +855,7 @@ mod tests {
let m = ~mutex(); let m = ~mutex();
let m2 = ~m.clone(); let m2 = ~m.clone();
let result: result::result<(),()> = do task::try { let result: result::Result<(),()> = do task::try {
do m2.lock { do m2.lock {
fail; fail;
} }
@ -871,7 +871,7 @@ mod tests {
let m = ~mutex(); let m = ~mutex();
let m2 = ~m.clone(); let m2 = ~m.clone();
let result: result::result<(),()> = do task::try { let result: result::Result<(),()> = do task::try {
let (c,p) = pipes::stream(); let (c,p) = pipes::stream();
do task::spawn { // linked do task::spawn { // linked
let _ = p.recv(); // wait for sibling to get in the mutex let _ = p.recv(); // wait for sibling to get in the mutex
@ -896,7 +896,7 @@ mod tests {
let m2 = ~m.clone(); let m2 = ~m.clone();
let (c,p) = pipes::stream(); let (c,p) = pipes::stream();
let result: result::result<(),()> = do task::try { let result: result::Result<(),()> = do task::try {
let mut sibling_convos = ~[]; let mut sibling_convos = ~[];
for 2.times { for 2.times {
let (c,p) = pipes::stream(); let (c,p) = pipes::stream();
@ -1196,7 +1196,7 @@ mod tests {
let x = ~rwlock(); let x = ~rwlock();
let x2 = ~x.clone(); let x2 = ~x.clone();
let result: result::result<(),()> = do task::try { let result: result::Result<(),()> = do task::try {
do lock_rwlock_in_mode(x2, mode1) { do lock_rwlock_in_mode(x2, mode1) {
fail; fail;
} }

View file

@ -6,7 +6,7 @@
// while providing a base that other test frameworks may build off of. // while providing a base that other test frameworks may build off of.
import either::Either; import either::Either;
import result::{ok, err}; import result::{Ok, Err};
import io::WriterUtil; import io::WriterUtil;
import libc::size_t; import libc::size_t;
import task::TaskBuilder; import task::TaskBuilder;
@ -71,8 +71,8 @@ fn parse_opts(args: ~[~str]) -> opt_res {
let opts = ~[getopts::optflag(~"ignored"), getopts::optopt(~"logfile")]; let opts = ~[getopts::optflag(~"ignored"), getopts::optopt(~"logfile")];
let matches = let matches =
match getopts::getopts(args_, opts) { match getopts::getopts(args_, opts) {
ok(m) => m, Ok(m) => m,
err(f) => return either::Right(getopts::fail_str(f)) Err(f) => return either::Right(getopts::fail_str(f))
}; };
let filter = let filter =
@ -143,8 +143,8 @@ fn run_tests_console(opts: test_opts,
let log_out = match opts.logfile { let log_out = match opts.logfile {
Some(path) => match io::file_writer(&Path(path), Some(path) => match io::file_writer(&Path(path),
~[io::Create, io::Truncate]) { ~[io::Create, io::Truncate]) {
result::ok(w) => Some(w), result::Ok(w) => Some(w),
result::err(s) => { result::Err(s) => {
fail(fmt!("can't open output file: %s", s)) fail(fmt!("can't open output file: %s", s))
} }
}, },

View file

@ -3,7 +3,7 @@
import libc::{c_char, c_int, c_long, size_t, time_t}; import libc::{c_char, c_int, c_long, size_t, time_t};
import io::Reader; import io::Reader;
import result::{result, ok, err}; import result::{Result, Ok, Err};
export export
timespec, timespec,
@ -131,7 +131,7 @@ fn now() -> tm {
} }
/// Parses the time from the string according to the format string. /// Parses the time from the string according to the format string.
fn strptime(s: &str, format: &str) -> result<tm, ~str> { fn strptime(s: &str, format: &str) -> Result<tm, ~str> {
type tm_mut = { type tm_mut = {
mut tm_sec: i32, mut tm_sec: i32,
mut tm_min: i32, mut tm_min: i32,
@ -197,20 +197,20 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
Some((value, pos)) Some((value, pos))
} }
fn parse_char(s: &str, pos: uint, c: char) -> result<uint, ~str> { fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, ~str> {
let {ch, next} = str::char_range_at(s, pos); let {ch, next} = str::char_range_at(s, pos);
if c == ch { if c == ch {
ok(next) Ok(next)
} else { } else {
err(fmt!("Expected %?, found %?", Err(fmt!("Expected %?, found %?",
str::from_char(c), str::from_char(c),
str::from_char(ch))) str::from_char(ch)))
} }
} }
fn parse_type(s: &str, pos: uint, ch: char, tm: &tm_mut) fn parse_type(s: &str, pos: uint, ch: char, tm: &tm_mut)
-> result<uint, ~str> { -> Result<uint, ~str> {
match ch { match ch {
'A' => match match_strs(s, pos, ~[ 'A' => match match_strs(s, pos, ~[
(~"Sunday", 0_i32), (~"Sunday", 0_i32),
@ -221,8 +221,8 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
(~"Friday", 5_i32), (~"Friday", 5_i32),
(~"Saturday", 6_i32) (~"Saturday", 6_i32)
]) { ]) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
None => err(~"Invalid day") None => Err(~"Invalid day")
}, },
'a' => match match_strs(s, pos, ~[ 'a' => match match_strs(s, pos, ~[
(~"Sun", 0_i32), (~"Sun", 0_i32),
@ -233,8 +233,8 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
(~"Fri", 5_i32), (~"Fri", 5_i32),
(~"Sat", 6_i32) (~"Sat", 6_i32)
]) { ]) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
None => err(~"Invalid day") None => Err(~"Invalid day")
}, },
'B' => match match_strs(s, pos, ~[ 'B' => match match_strs(s, pos, ~[
(~"January", 0_i32), (~"January", 0_i32),
@ -250,8 +250,8 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
(~"November", 10_i32), (~"November", 10_i32),
(~"December", 11_i32) (~"December", 11_i32)
]) { ]) {
Some(item) => { let (v, pos) = item; tm.tm_mon = v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
None => err(~"Invalid month") None => Err(~"Invalid month")
}, },
'b' | 'h' => match match_strs(s, pos, ~[ 'b' | 'h' => match match_strs(s, pos, ~[
(~"Jan", 0_i32), (~"Jan", 0_i32),
@ -267,16 +267,16 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
(~"Nov", 10_i32), (~"Nov", 10_i32),
(~"Dec", 11_i32) (~"Dec", 11_i32)
]) { ]) {
Some(item) => { let (v, pos) = item; tm.tm_mon = v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
None => err(~"Invalid month") None => Err(~"Invalid month")
}, },
'C' => match match_digits(s, pos, 2u, false) { 'C' => match match_digits(s, pos, 2u, false) {
Some(item) => { Some(item) => {
let (v, pos) = item; let (v, pos) = item;
tm.tm_year += (v * 100_i32) - 1900_i32; tm.tm_year += (v * 100_i32) - 1900_i32;
ok(pos) Ok(pos)
} }
None => err(~"Invalid year") None => Err(~"Invalid year")
}, },
'c' => { 'c' => {
parse_type(s, pos, 'a', tm) parse_type(s, pos, 'a', tm)
@ -297,12 +297,12 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
.chain(|pos| parse_type(s, pos, 'y', tm)) .chain(|pos| parse_type(s, pos, 'y', tm))
} }
'd' => match match_digits(s, pos, 2u, false) { 'd' => match match_digits(s, pos, 2u, false) {
Some(item) => { let (v, pos) = item; tm.tm_mday = v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
None => err(~"Invalid day of the month") None => Err(~"Invalid day of the month")
}, },
'e' => match match_digits(s, pos, 2u, true) { 'e' => match match_digits(s, pos, 2u, true) {
Some(item) => { let (v, pos) = item; tm.tm_mday = v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
None => err(~"Invalid day of the month") None => Err(~"Invalid day of the month")
}, },
'F' => { 'F' => {
parse_type(s, pos, 'Y', tm) parse_type(s, pos, 'Y', tm)
@ -314,8 +314,8 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
'H' => { 'H' => {
// FIXME (#2350): range check. // FIXME (#2350): range check.
match match_digits(s, pos, 2u, false) { match match_digits(s, pos, 2u, false) {
Some(item) => { let (v, pos) = item; tm.tm_hour = v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
None => err(~"Invalid hour") None => Err(~"Invalid hour")
} }
} }
'I' => { 'I' => {
@ -324,9 +324,9 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
Some(item) => { Some(item) => {
let (v, pos) = item; let (v, pos) = item;
tm.tm_hour = if v == 12_i32 { 0_i32 } else { v }; tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
ok(pos) Ok(pos)
} }
None => err(~"Invalid hour") None => Err(~"Invalid hour")
} }
} }
'j' => { 'j' => {
@ -335,16 +335,16 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
Some(item) => { Some(item) => {
let (v, pos) = item; let (v, pos) = item;
tm.tm_yday = v - 1_i32; tm.tm_yday = v - 1_i32;
ok(pos) Ok(pos)
} }
None => err(~"Invalid year") None => Err(~"Invalid year")
} }
} }
'k' => { 'k' => {
// FIXME (#2350): range check. // FIXME (#2350): range check.
match match_digits(s, pos, 2u, true) { match match_digits(s, pos, 2u, true) {
Some(item) => { let (v, pos) = item; tm.tm_hour = v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
None => err(~"Invalid hour") None => Err(~"Invalid hour")
} }
} }
'l' => { 'l' => {
@ -353,16 +353,16 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
Some(item) => { Some(item) => {
let (v, pos) = item; let (v, pos) = item;
tm.tm_hour = if v == 12_i32 { 0_i32 } else { v }; tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
ok(pos) Ok(pos)
} }
None => err(~"Invalid hour") None => Err(~"Invalid hour")
} }
} }
'M' => { 'M' => {
// FIXME (#2350): range check. // FIXME (#2350): range check.
match match_digits(s, pos, 2u, false) { match match_digits(s, pos, 2u, false) {
Some(item) => { let (v, pos) = item; tm.tm_min = v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
None => err(~"Invalid minute") None => Err(~"Invalid minute")
} }
} }
'm' => { 'm' => {
@ -371,23 +371,23 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
Some(item) => { Some(item) => {
let (v, pos) = item; let (v, pos) = item;
tm.tm_mon = v - 1_i32; tm.tm_mon = v - 1_i32;
ok(pos) Ok(pos)
} }
None => err(~"Invalid month") None => Err(~"Invalid month")
} }
} }
'n' => parse_char(s, pos, '\n'), 'n' => parse_char(s, pos, '\n'),
'P' => match match_strs(s, pos, 'P' => match match_strs(s, pos,
~[(~"am", 0_i32), (~"pm", 12_i32)]) { ~[(~"am", 0_i32), (~"pm", 12_i32)]) {
Some(item) => { let (v, pos) = item; tm.tm_hour += v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
None => err(~"Invalid hour") None => Err(~"Invalid hour")
}, },
'p' => match match_strs(s, pos, 'p' => match match_strs(s, pos,
~[(~"AM", 0_i32), (~"PM", 12_i32)]) { ~[(~"AM", 0_i32), (~"PM", 12_i32)]) {
Some(item) => { let (v, pos) = item; tm.tm_hour += v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
None => err(~"Invalid hour") None => Err(~"Invalid hour")
}, },
'R' => { 'R' => {
parse_type(s, pos, 'H', tm) parse_type(s, pos, 'H', tm)
@ -409,9 +409,9 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
Some(item) => { Some(item) => {
let (v, pos) = item; let (v, pos) = item;
tm.tm_sec = v; tm.tm_sec = v;
ok(pos) Ok(pos)
} }
None => err(~"Invalid second") None => Err(~"Invalid second")
} }
} }
//'s' {} //'s' {}
@ -429,9 +429,9 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
Some(item) => { Some(item) => {
let (v, pos) = item; let (v, pos) = item;
tm.tm_wday = v; tm.tm_wday = v;
ok(pos) Ok(pos)
} }
None => err(~"Invalid weekday") None => Err(~"Invalid weekday")
} }
} }
'v' => { 'v' => {
@ -445,8 +445,8 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
'w' => { 'w' => {
// FIXME (#2350): range check. // FIXME (#2350): range check.
match match_digits(s, pos, 1u, false) { match match_digits(s, pos, 1u, false) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; ok(pos) } Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
None => err(~"Invalid weekday") None => Err(~"Invalid weekday")
} }
} }
//'X' {} //'X' {}
@ -457,9 +457,9 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
Some(item) => { Some(item) => {
let (v, pos) = item; let (v, pos) = item;
tm.tm_year = v - 1900_i32; tm.tm_year = v - 1900_i32;
ok(pos) Ok(pos)
} }
None => err(~"Invalid weekday") None => Err(~"Invalid weekday")
} }
} }
'y' => { 'y' => {
@ -468,16 +468,16 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
Some(item) => { Some(item) => {
let (v, pos) = item; let (v, pos) = item;
tm.tm_year = v - 1900_i32; tm.tm_year = v - 1900_i32;
ok(pos) Ok(pos)
} }
None => err(~"Invalid weekday") None => Err(~"Invalid weekday")
} }
} }
'Z' => { 'Z' => {
if match_str(s, pos, ~"UTC") || match_str(s, pos, ~"GMT") { if match_str(s, pos, ~"UTC") || match_str(s, pos, ~"GMT") {
tm.tm_gmtoff = 0_i32; tm.tm_gmtoff = 0_i32;
tm.tm_zone = ~"UTC"; tm.tm_zone = ~"UTC";
ok(pos + 3u) Ok(pos + 3u)
} else { } else {
// It's odd, but to maintain compatibility with c's // It's odd, but to maintain compatibility with c's
// strptime we ignore the timezone. // strptime we ignore the timezone.
@ -489,7 +489,7 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
if ch == ' ' { break; } if ch == ' ' { break; }
} }
ok(pos) Ok(pos)
} }
} }
'z' => { 'z' => {
@ -504,17 +504,17 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
tm.tm_zone = ~"UTC"; tm.tm_zone = ~"UTC";
} }
ok(pos) Ok(pos)
} }
None => err(~"Invalid zone offset") None => Err(~"Invalid zone offset")
} }
} else { } else {
err(~"Invalid zone offset") Err(~"Invalid zone offset")
} }
} }
'%' => parse_char(s, pos, '%'), '%' => parse_char(s, pos, '%'),
ch => { ch => {
err(fmt!("unknown formatting type: %?", str::from_char(ch))) Err(fmt!("unknown formatting type: %?", str::from_char(ch)))
} }
} }
} }
@ -536,15 +536,15 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
}; };
let mut pos = 0u; let mut pos = 0u;
let len = str::len(s); let len = str::len(s);
let mut result = err(~"Invalid time"); let mut result = Err(~"Invalid time");
while !rdr.eof() && pos < len { while !rdr.eof() && pos < len {
let {ch, next} = str::char_range_at(s, pos); let {ch, next} = str::char_range_at(s, pos);
match rdr.read_char() { match rdr.read_char() {
'%' => match parse_type(s, pos, rdr.read_char(), &tm) { '%' => match parse_type(s, pos, rdr.read_char(), &tm) {
ok(next) => pos = next, Ok(next) => pos = next,
err(e) => { result = err(e); break; } Err(e) => { result = Err(e); break; }
}, },
c => { c => {
if c != ch { break } if c != ch { break }
@ -554,7 +554,7 @@ fn strptime(s: &str, format: &str) -> result<tm, ~str> {
} }
if pos == len && rdr.eof() { if pos == len && rdr.eof() {
ok(tm_({ Ok(tm_({
tm_sec: tm.tm_sec, tm_sec: tm.tm_sec,
tm_min: tm.tm_min, tm_min: tm.tm_min,
tm_hour: tm.tm_hour, tm_hour: tm.tm_hour,
@ -947,7 +947,7 @@ mod tests {
tzset(); tzset();
match strptime(~"", ~"") { match strptime(~"", ~"") {
ok(tm) => { Ok(tm) => {
assert tm.tm_sec == 0_i32; assert tm.tm_sec == 0_i32;
assert tm.tm_min == 0_i32; assert tm.tm_min == 0_i32;
assert tm.tm_hour == 0_i32; assert tm.tm_hour == 0_i32;
@ -960,17 +960,17 @@ mod tests {
assert tm.tm_zone == ~""; assert tm.tm_zone == ~"";
assert tm.tm_nsec == 0_i32; assert tm.tm_nsec == 0_i32;
} }
err(_) => () Err(_) => ()
} }
let format = ~"%a %b %e %T %Y"; let format = ~"%a %b %e %T %Y";
assert strptime(~"", format) == err(~"Invalid time"); assert strptime(~"", format) == Err(~"Invalid time");
assert strptime(~"Fri Feb 13 15:31:30", format) assert strptime(~"Fri Feb 13 15:31:30", format)
== err(~"Invalid time"); == Err(~"Invalid time");
match strptime(~"Fri Feb 13 15:31:30 2009", format) { match strptime(~"Fri Feb 13 15:31:30 2009", format) {
err(e) => fail e, Err(e) => fail e,
ok(tm) => { Ok(tm) => {
assert tm.tm_sec == 30_i32; assert tm.tm_sec == 30_i32;
assert tm.tm_min == 31_i32; assert tm.tm_min == 31_i32;
assert tm.tm_hour == 15_i32; assert tm.tm_hour == 15_i32;
@ -988,8 +988,8 @@ mod tests {
fn test(s: &str, format: &str) -> bool { fn test(s: &str, format: &str) -> bool {
match strptime(s, format) { match strptime(s, format) {
ok(tm) => tm.strftime(format) == str::from_slice(s), Ok(tm) => tm.strftime(format) == str::from_slice(s),
err(e) => fail e Err(e) => fail e
} }
} }

View file

@ -72,8 +72,8 @@ fn expand_include_str(cx: ext_ctxt, sp: codemap::span, arg: ast::mac_arg,
let res = io::read_whole_file_str(&res_rel_file(cx, sp, &Path(file))); let res = io::read_whole_file_str(&res_rel_file(cx, sp, &Path(file)));
match res { match res {
result::ok(_) => { /* Continue. */ } result::Ok(_) => { /* Continue. */ }
result::err(e) => { result::Err(e) => {
cx.parse_sess().span_diagnostic.handler().fatal(e); cx.parse_sess().span_diagnostic.handler().fatal(e);
} }
} }
@ -88,13 +88,13 @@ fn expand_include_bin(cx: ext_ctxt, sp: codemap::span, arg: ast::mac_arg,
let file = expr_to_str(cx, args[0], ~"#include_bin requires a string"); let file = expr_to_str(cx, args[0], ~"#include_bin requires a string");
match io::read_whole_file(&res_rel_file(cx, sp, &Path(file))) { match io::read_whole_file(&res_rel_file(cx, sp, &Path(file))) {
result::ok(src) => { result::Ok(src) => {
let u8_exprs = vec::map(src, |char: u8| { let u8_exprs = vec::map(src, |char: u8| {
mk_u8(cx, sp, char) mk_u8(cx, sp, char)
}); });
return mk_base_vec_e(cx, sp, u8_exprs); return mk_base_vec_e(cx, sp, u8_exprs);
} }
result::err(e) => { result::Err(e) => {
cx.parse_sess().span_diagnostic.handler().fatal(e) cx.parse_sess().span_diagnostic.handler().fatal(e)
} }
} }

View file

@ -187,8 +187,8 @@ fn new_parser_etc_from_file(sess: parse_sess, cfg: ast::crate_cfg,
(parser, string_reader) { (parser, string_reader) {
let res = io::read_whole_file_str(path); let res = io::read_whole_file_str(path);
match res { match res {
result::ok(_) => { /* Continue. */ } result::Ok(_) => { /* Continue. */ }
result::err(e) => sess.span_diagnostic.handler().fatal(e) result::Err(e) => sess.span_diagnostic.handler().fatal(e)
} }
let src = @result::unwrap(res); let src = @result::unwrap(res);
let filemap = codemap::new_filemap(path.to_str(), src, let filemap = codemap::new_filemap(path.to_str(), src,

View file

@ -54,8 +54,8 @@ fn parse_companion_mod(cx: ctx, prefix: &Path, suffix: &Option<Path>)
// Crude, but there's no lib function for this and I'm not // Crude, but there's no lib function for this and I'm not
// up to writing it just now // up to writing it just now
match io::file_reader(path) { match io::file_reader(path) {
result::ok(_) => true, result::Ok(_) => true,
result::err(_) => false result::Err(_) => false
} }
} }

View file

@ -1,6 +1,6 @@
import print::pprust::expr_to_str; import print::pprust::expr_to_str;
import result::result; import result::Result;
import either::{Either, Left, Right}; import either::{Either, Left, Right};
import std::map::{hashmap, str_hash}; import std::map::{hashmap, str_hash};
import token::{can_begin_expr, is_ident, is_ident_or_path, is_plain_ident, import token::{can_begin_expr, is_ident, is_ident_or_path, is_plain_ident,

View file

@ -8,7 +8,7 @@ import middle::{trans, freevars, kind, ty, typeck, lint};
import syntax::print::{pp, pprust}; import syntax::print::{pp, pprust};
import util::ppaux; import util::ppaux;
import back::link; import back::link;
import result::{ok, err}; import result::{Ok, Err};
import std::getopts; import std::getopts;
import io::WriterUtil; import io::WriterUtil;
import getopts::{optopt, optmulti, optflag, optflagopt, opt_present}; import getopts::{optopt, optmulti, optflag, optflagopt, opt_present};
@ -715,8 +715,8 @@ mod test {
fn test_switch_implies_cfg_test() { fn test_switch_implies_cfg_test() {
let matches = let matches =
match getopts::getopts(~[~"--test"], opts()) { match getopts::getopts(~[~"--test"], opts()) {
ok(m) => m, Ok(m) => m,
err(f) => fail ~"test_switch_implies_cfg_test: " + Err(f) => fail ~"test_switch_implies_cfg_test: " +
getopts::fail_str(f) getopts::fail_str(f)
}; };
let sessopts = build_session_options(matches, diagnostic::emit); let sessopts = build_session_options(matches, diagnostic::emit);
@ -731,8 +731,8 @@ mod test {
fn test_switch_implies_cfg_test_unless_cfg_test() { fn test_switch_implies_cfg_test_unless_cfg_test() {
let matches = let matches =
match getopts::getopts(~[~"--test", ~"--cfg=test"], opts()) { match getopts::getopts(~[~"--test", ~"--cfg=test"], opts()) {
ok(m) => m, Ok(m) => m,
err(f) => { Err(f) => {
fail ~"test_switch_implies_cfg_test_unless_cfg_test: " + fail ~"test_switch_implies_cfg_test_unless_cfg_test: " +
getopts::fail_str(f); getopts::fail_str(f);
} }

View file

@ -9,7 +9,7 @@ use syntax(vers = "0.3");
import core::*; import core::*;
// -*- rust -*- // -*- rust -*-
import result::{ok, err}; import result::{Ok, Err};
import std::getopts; import std::getopts;
import std::map::hashmap; import std::map::hashmap;
import getopts::{opt_present}; import getopts::{opt_present};
@ -124,8 +124,8 @@ fn run_compiler(args: ~[~str], demitter: diagnostic::emitter) {
let matches = let matches =
match getopts::getopts(args, opts()) { match getopts::getopts(args, opts()) {
ok(m) => m, Ok(m) => m,
err(f) => { Err(f) => {
early_error(demitter, getopts::fail_str(f)) early_error(demitter, getopts::fail_str(f))
} }
}; };
@ -242,8 +242,8 @@ fn monitor(+f: fn~(diagnostic::emitter)) {
f(demitter) f(demitter)
} { } {
result::ok(_) => { /* fallthrough */ } result::Ok(_) => { /* fallthrough */ }
result::err(_) => { result::Err(_) => {
// Task failed without emitting a fatal diagnostic // Task failed without emitting a fatal diagnostic
if comm::recv(p) == done { if comm::recv(p) == done {
diagnostic::emit( diagnostic::emit(

View file

@ -2,7 +2,7 @@
// FIXME (#2658): I'm not happy how this module turned out. Should // FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore. // probably just be folded into cstore.
import result::result; import result::Result;
export filesearch; export filesearch;
export mk_filesearch; export mk_filesearch;
export pick; export pick;
@ -43,12 +43,12 @@ fn mk_filesearch(maybe_sysroot: Option<Path>,
make_target_lib_path(&self.sysroot, make_target_lib_path(&self.sysroot,
self.target_triple)); self.target_triple));
match get_cargo_lib_path_nearest() { match get_cargo_lib_path_nearest() {
result::ok(p) => vec::push(paths, p), result::Ok(p) => vec::push(paths, p),
result::err(_) => () result::Err(_) => ()
} }
match get_cargo_lib_path() { match get_cargo_lib_path() {
result::ok(p) => vec::push(paths, p), result::Ok(p) => vec::push(paths, p),
result::err(_) => () result::Err(_) => ()
} }
paths paths
} }
@ -112,31 +112,31 @@ fn get_sysroot(maybe_sysroot: Option<Path>) -> Path {
} }
} }
fn get_cargo_sysroot() -> result<Path, ~str> { fn get_cargo_sysroot() -> Result<Path, ~str> {
result::ok(get_default_sysroot().push_many([libdir(), ~"cargo"])) result::Ok(get_default_sysroot().push_many([libdir(), ~"cargo"]))
} }
fn get_cargo_root() -> result<Path, ~str> { fn get_cargo_root() -> Result<Path, ~str> {
match os::getenv(~"CARGO_ROOT") { match os::getenv(~"CARGO_ROOT") {
Some(_p) => result::ok(Path(_p)), Some(_p) => result::Ok(Path(_p)),
None => match os::homedir() { None => match os::homedir() {
Some(_q) => result::ok(_q.push(".cargo")), Some(_q) => result::Ok(_q.push(".cargo")),
None => result::err(~"no CARGO_ROOT or home directory") None => result::Err(~"no CARGO_ROOT or home directory")
} }
} }
} }
fn get_cargo_root_nearest() -> result<Path, ~str> { fn get_cargo_root_nearest() -> Result<Path, ~str> {
do result::chain(get_cargo_root()) |p| { do result::chain(get_cargo_root()) |p| {
let cwd = os::getcwd(); let cwd = os::getcwd();
let cwd_cargo = cwd.push(".cargo"); let cwd_cargo = cwd.push(".cargo");
let mut par_cargo = cwd.pop().push(".cargo"); let mut par_cargo = cwd.pop().push(".cargo");
let mut rslt = result::ok(cwd_cargo); let mut rslt = result::Ok(cwd_cargo);
if !os::path_is_dir(&cwd_cargo) && cwd_cargo != p { if !os::path_is_dir(&cwd_cargo) && cwd_cargo != p {
while par_cargo != p { while par_cargo != p {
if os::path_is_dir(&par_cargo) { if os::path_is_dir(&par_cargo) {
rslt = result::ok(par_cargo); rslt = result::Ok(par_cargo);
break; break;
} }
if par_cargo.components.len() == 1 { if par_cargo.components.len() == 1 {
@ -150,15 +150,15 @@ fn get_cargo_root_nearest() -> result<Path, ~str> {
} }
} }
fn get_cargo_lib_path() -> result<Path, ~str> { fn get_cargo_lib_path() -> Result<Path, ~str> {
do result::chain(get_cargo_root()) |p| { do result::chain(get_cargo_root()) |p| {
result::ok(p.push(libdir())) result::Ok(p.push(libdir()))
} }
} }
fn get_cargo_lib_path_nearest() -> result<Path, ~str> { fn get_cargo_lib_path_nearest() -> Result<Path, ~str> {
do result::chain(get_cargo_root_nearest()) |p| { do result::chain(get_cargo_root_nearest()) |p| {
result::ok(p.push(libdir())) result::Ok(p.push(libdir()))
} }
} }

View file

@ -224,7 +224,7 @@ import util::ppaux::{ty_to_str, region_to_str, explain_region};
import std::map::{int_hash, hashmap, set}; import std::map::{int_hash, hashmap, set};
import std::list; import std::list;
import std::list::{list, cons, nil}; import std::list::{list, cons, nil};
import result::{result, ok, err}; import result::{Result, Ok, Err};
import syntax::print::pprust; import syntax::print::pprust;
import util::common::indenter; import util::common::indenter;
import ty::to_str; import ty::to_str;
@ -327,7 +327,7 @@ enum bckerr_code {
type bckerr = {cmt: cmt, code: bckerr_code}; type bckerr = {cmt: cmt, code: bckerr_code};
// shorthand for something that fails with `bckerr` or succeeds with `T` // shorthand for something that fails with `bckerr` or succeeds with `T`
type bckres<T> = result<T, bckerr>; type bckres<T> = Result<T, bckerr>;
/// a complete record of a loan that was granted /// a complete record of a loan that was granted
type loan = {lp: @loan_path, cmt: cmt, mutbl: ast::mutability}; type loan = {lp: @loan_path, cmt: cmt, mutbl: ast::mutability};
@ -404,8 +404,8 @@ impl borrowck_ctxt {
fn report_if_err(bres: bckres<()>) { fn report_if_err(bres: bckres<()>) {
match bres { match bres {
ok(()) => (), Ok(()) => (),
err(e) => self.report(e) Err(e) => self.report(e)
} }
} }

View file

@ -276,9 +276,9 @@ impl gather_loan_ctxt {
// error will be reported. // error will be reported.
Some(_) => { Some(_) => {
match self.bccx.loan(cmt, scope_r, req_mutbl) { match self.bccx.loan(cmt, scope_r, req_mutbl) {
err(e) => { self.bccx.report(e); } Err(e) => { self.bccx.report(e); }
ok(loans) if loans.len() == 0 => {} Ok(loans) if loans.len() == 0 => {}
ok(loans) => { Ok(loans) => {
match scope_r { match scope_r {
ty::re_scope(scope_id) => { ty::re_scope(scope_id) => {
self.add_loans(scope_id, loans); self.add_loans(scope_id, loans);
@ -318,19 +318,19 @@ impl gather_loan_ctxt {
do self.bccx.preserve(cmt, scope_r, do self.bccx.preserve(cmt, scope_r,
self.item_ub, self.item_ub,
self.root_ub).chain |pc2| { self.root_ub).chain |pc2| {
ok(pc1.combine(pc2)) Ok(pc1.combine(pc2))
} }
} }
}; };
match result { match result {
ok(pc_ok) => { Ok(pc_ok) => {
// we were able guarantee the validity of the ptr, // we were able guarantee the validity of the ptr,
// perhaps by rooting or because it is immutably // perhaps by rooting or because it is immutably
// rooted. good. // rooted. good.
self.bccx.stable_paths += 1; self.bccx.stable_paths += 1;
} }
ok(pc_if_pure(e)) => { Ok(pc_if_pure(e)) => {
// we are only able to guarantee the validity if // we are only able to guarantee the validity if
// the scope is pure // the scope is pure
match scope_r { match scope_r {
@ -353,7 +353,7 @@ impl gather_loan_ctxt {
} }
} }
} }
err(e) => { Err(e) => {
// we cannot guarantee the validity of this pointer // we cannot guarantee the validity of this pointer
self.bccx.report(e); self.bccx.report(e);
} }
@ -376,7 +376,7 @@ impl gather_loan_ctxt {
(m_const, _) | (m_const, _) |
(m_imm, m_imm) | (m_imm, m_imm) |
(m_mutbl, m_mutbl) => { (m_mutbl, m_mutbl) => {
ok(pc_ok) Ok(pc_ok)
} }
(_, m_const) | (_, m_const) |
@ -386,9 +386,9 @@ impl gather_loan_ctxt {
code: err_mutbl(req_mutbl, cmt.mutbl)}; code: err_mutbl(req_mutbl, cmt.mutbl)};
if req_mutbl == m_imm { if req_mutbl == m_imm {
// you can treat mutable things as imm if you are pure // you can treat mutable things as imm if you are pure
ok(pc_if_pure(e)) Ok(pc_if_pure(e))
} else { } else {
err(e) Err(e)
} }
} }
} }

View file

@ -3,7 +3,7 @@
// of the scope S, presuming that the returned set of loans `Ls` are honored. // of the scope S, presuming that the returned set of loans `Ls` are honored.
export public_methods; export public_methods;
import result::{result, ok, err}; import result::{Result, Ok, Err};
impl borrowck_ctxt { impl borrowck_ctxt {
fn loan(cmt: cmt, fn loan(cmt: cmt,
@ -13,8 +13,8 @@ impl borrowck_ctxt {
scope_region: scope_region, scope_region: scope_region,
loans: @dvec()}); loans: @dvec()});
match lc.loan(cmt, mutbl) { match lc.loan(cmt, mutbl) {
ok(()) => {ok(lc.loans)} Ok(()) => {Ok(lc.loans)}
err(e) => {err(e)} Err(e) => {Err(e)}
} }
} }
} }
@ -47,11 +47,11 @@ impl loan_ctxt {
(*self.loans).push({lp: option::get(cmt.lp), (*self.loans).push({lp: option::get(cmt.lp),
cmt: cmt, cmt: cmt,
mutbl: mutbl}); mutbl: mutbl});
ok(()) Ok(())
} else { } else {
// The loan being requested lives longer than the data // The loan being requested lives longer than the data
// being loaned out! // being loaned out!
err({cmt:cmt, code:err_out_of_scope(scope_ub, Err({cmt:cmt, code:err_out_of_scope(scope_ub,
self.scope_region)}) self.scope_region)})
} }
} }

View file

@ -68,7 +68,7 @@ priv impl &preserve_ctxt {
self.compare_scope(cmt, ty::re_scope(self.item_ub)) self.compare_scope(cmt, ty::re_scope(self.item_ub))
} }
cat_special(sk_static_item) | cat_special(sk_method) => { cat_special(sk_static_item) | cat_special(sk_method) => {
ok(pc_ok) Ok(pc_ok)
} }
cat_rvalue => { cat_rvalue => {
// when we borrow an rvalue, we can keep it rooted but only // when we borrow an rvalue, we can keep it rooted but only
@ -147,7 +147,7 @@ priv impl &preserve_ctxt {
} }
cat_deref(_, _, unsafe_ptr) => { cat_deref(_, _, unsafe_ptr) => {
// Unsafe pointers are the user's problem // Unsafe pointers are the user's problem
ok(pc_ok) Ok(pc_ok)
} }
cat_deref(base, derefs, gc_ptr) => { cat_deref(base, derefs, gc_ptr) => {
// GC'd pointers of type @MT: if this pointer lives in // GC'd pointers of type @MT: if this pointer lives in
@ -160,14 +160,14 @@ priv impl &preserve_ctxt {
let non_rooting_ctxt = let non_rooting_ctxt =
preserve_ctxt({root_managed_data: false with **self}); preserve_ctxt({root_managed_data: false with **self});
match (&non_rooting_ctxt).preserve(base) { match (&non_rooting_ctxt).preserve(base) {
ok(pc_ok) => { Ok(pc_ok) => {
ok(pc_ok) Ok(pc_ok)
} }
ok(pc_if_pure(_)) => { Ok(pc_if_pure(_)) => {
debug!("must root @T, otherwise purity req'd"); debug!("must root @T, otherwise purity req'd");
self.attempt_root(cmt, base, derefs) self.attempt_root(cmt, base, derefs)
} }
err(e) => { Err(e) => {
debug!("must root @T, err: %s", debug!("must root @T, err: %s",
self.bccx.bckerr_code_to_str(e.code)); self.bccx.bckerr_code_to_str(e.code));
self.attempt_root(cmt, base, derefs) self.attempt_root(cmt, base, derefs)
@ -251,25 +251,25 @@ priv impl &preserve_ctxt {
match self.preserve(cmt_base) { match self.preserve(cmt_base) {
// the base is preserved, but if we are not mutable then // the base is preserved, but if we are not mutable then
// purity is required // purity is required
ok(pc_ok) => { Ok(pc_ok) => {
match cmt_base.mutbl { match cmt_base.mutbl {
m_mutbl | m_const => { m_mutbl | m_const => {
ok(pc_if_pure({cmt:cmt, code:code})) Ok(pc_if_pure({cmt:cmt, code:code}))
} }
m_imm => { m_imm => {
ok(pc_ok) Ok(pc_ok)
} }
} }
} }
// the base requires purity too, that's fine // the base requires purity too, that's fine
ok(pc_if_pure(e)) => { Ok(pc_if_pure(e)) => {
ok(pc_if_pure(e)) Ok(pc_if_pure(e))
} }
// base is not stable, doesn't matter // base is not stable, doesn't matter
err(e) => { Err(e) => {
err(e) Err(e)
} }
} }
} }
@ -279,9 +279,9 @@ priv impl &preserve_ctxt {
fn compare_scope(cmt: cmt, fn compare_scope(cmt: cmt,
scope_ub: ty::region) -> bckres<preserve_condition> { scope_ub: ty::region) -> bckres<preserve_condition> {
if self.bccx.is_subregion_of(self.scope_region, scope_ub) { if self.bccx.is_subregion_of(self.scope_region, scope_ub) {
ok(pc_ok) Ok(pc_ok)
} else { } else {
err({cmt:cmt, code:err_out_of_scope(scope_ub, Err({cmt:cmt, code:err_out_of_scope(scope_ub,
self.scope_region)}) self.scope_region)})
} }
} }
@ -306,7 +306,7 @@ priv impl &preserve_ctxt {
// would be sort of pointless to avoid rooting the inner // would be sort of pointless to avoid rooting the inner
// box by rooting an outer box, as it would just keep more // box by rooting an outer box, as it would just keep more
// memory live than necessary, so we set root_ub to none. // memory live than necessary, so we set root_ub to none.
return err({cmt:cmt, code:err_root_not_permitted}); return Err({cmt:cmt, code:err_root_not_permitted});
} }
let root_region = ty::re_scope(self.root_ub); let root_region = ty::re_scope(self.root_ub);
@ -322,10 +322,10 @@ priv impl &preserve_ctxt {
#debug["Elected to root"]; #debug["Elected to root"];
let rk = {id: base.id, derefs: derefs}; let rk = {id: base.id, derefs: derefs};
self.bccx.root_map.insert(rk, scope_id); self.bccx.root_map.insert(rk, scope_id);
return ok(pc_ok); return Ok(pc_ok);
} else { } else {
#debug["Unable to root"]; #debug["Unable to root"];
return err({cmt:cmt, return Err({cmt:cmt,
code:err_out_of_root_scope(root_region, code:err_out_of_root_scope(root_region,
self.scope_region)}); self.scope_region)});
} }
@ -333,7 +333,7 @@ priv impl &preserve_ctxt {
// we won't be able to root long enough // we won't be able to root long enough
_ => { _ => {
return err({cmt:cmt, return Err({cmt:cmt,
code:err_out_of_root_scope(root_region, code:err_out_of_root_scope(root_region,
self.scope_region)}); self.scope_region)});
} }

View file

@ -2,7 +2,7 @@
#[warn(deprecated_pattern)]; #[warn(deprecated_pattern)];
import std::{map, smallintmap}; import std::{map, smallintmap};
import result::result; import result::Result;
import std::map::hashmap; import std::map::hashmap;
import driver::session; import driver::session;
import session::session; import session::session;
@ -2613,24 +2613,24 @@ fn arg_mode(cx: ctxt, a: arg) -> ast::rmode { resolved_mode(cx, a.mode) }
// Unifies `m1` and `m2`. Returns unified value or failure code. // Unifies `m1` and `m2`. Returns unified value or failure code.
fn unify_mode(cx: ctxt, modes: expected_found<ast::mode>) fn unify_mode(cx: ctxt, modes: expected_found<ast::mode>)
-> result<ast::mode, type_err> { -> Result<ast::mode, type_err> {
let m1 = modes.expected; let m1 = modes.expected;
let m2 = modes.found; let m2 = modes.found;
match (canon_mode(cx, m1), canon_mode(cx, m2)) { match (canon_mode(cx, m1), canon_mode(cx, m2)) {
(m1, m2) if (m1 == m2) => { (m1, m2) if (m1 == m2) => {
result::ok(m1) result::Ok(m1)
} }
(ast::infer(_), ast::infer(id2)) => { (ast::infer(_), ast::infer(id2)) => {
cx.inferred_modes.insert(id2, m1); cx.inferred_modes.insert(id2, m1);
result::ok(m1) result::Ok(m1)
} }
(ast::infer(id), m) | (m, ast::infer(id)) => { (ast::infer(id), m) | (m, ast::infer(id)) => {
cx.inferred_modes.insert(id, m); cx.inferred_modes.insert(id, m);
result::ok(m1) result::Ok(m1)
} }
(_, _) => { (_, _) => {
result::err(terr_mode_mismatch(modes)) result::Err(terr_mode_mismatch(modes))
} }
} }
} }

View file

@ -38,7 +38,7 @@ independently:
*/ */
import result::result; import result::Result;
import syntax::{ast, ast_util, ast_map}; import syntax::{ast, ast_util, ast_map};
import ast::spanned; import ast::spanned;
import ast::{required, provided}; import ast::{required, provided};
@ -226,8 +226,8 @@ fn require_same_types(
} }
match infer::mk_eqty(l_infcx, t1_is_expected, span, t1, t2) { match infer::mk_eqty(l_infcx, t1_is_expected, span, t1, t2) {
result::ok(()) => true, result::Ok(()) => true,
result::err(ref terr) => { result::Err(ref terr) => {
l_tcx.sess.span_err(span, msg() + ~": " + l_tcx.sess.span_err(span, msg() + ~": " +
ty::type_err_to_str(l_tcx, terr)); ty::type_err_to_str(l_tcx, terr));
false false

View file

@ -57,11 +57,11 @@ trait ast_conv {
fn get_region_reporting_err(tcx: ty::ctxt, fn get_region_reporting_err(tcx: ty::ctxt,
span: span, span: span,
res: result<ty::region, ~str>) -> ty::region { res: Result<ty::region, ~str>) -> ty::region {
match res { match res {
result::ok(r) => r, result::Ok(r) => r,
result::err(e) => { result::Err(e) => {
tcx.sess.span_err(span, e); tcx.sess.span_err(span, e);
ty::re_static ty::re_static
} }

View file

@ -553,17 +553,17 @@ impl @fn_ctxt: ast_conv {
} }
impl @fn_ctxt: region_scope { impl @fn_ctxt: region_scope {
fn anon_region(span: span) -> result<ty::region, ~str> { fn anon_region(span: span) -> Result<ty::region, ~str> {
result::ok(self.infcx.next_region_var_nb(span)) result::Ok(self.infcx.next_region_var_nb(span))
} }
fn named_region(span: span, id: ast::ident) -> result<ty::region, ~str> { fn named_region(span: span, id: ast::ident) -> Result<ty::region, ~str> {
do empty_rscope.named_region(span, id).chain_err |_e| { do empty_rscope.named_region(span, id).chain_err |_e| {
match self.in_scope_regions.find(ty::br_named(id)) { match self.in_scope_regions.find(ty::br_named(id)) {
Some(r) => result::ok(r), Some(r) => result::Ok(r),
None if id == syntax::parse::token::special_idents::blk None if id == syntax::parse::token::special_idents::blk
=> result::ok(self.block_region()), => result::Ok(self.block_region()),
None => { None => {
result::err(fmt!("named region `%s` not in scope here", result::Err(fmt!("named region `%s` not in scope here",
self.ccx.tcx.sess.str_of(id))) self.ccx.tcx.sess.str_of(id)))
} }
} }
@ -656,35 +656,35 @@ impl @fn_ctxt {
} }
fn mk_subty(a_is_expected: bool, span: span, fn mk_subty(a_is_expected: bool, span: span,
sub: ty::t, sup: ty::t) -> result<(), ty::type_err> { sub: ty::t, sup: ty::t) -> Result<(), ty::type_err> {
infer::mk_subty(self.infcx, a_is_expected, span, sub, sup) infer::mk_subty(self.infcx, a_is_expected, span, sub, sup)
} }
fn can_mk_subty(sub: ty::t, sup: ty::t) -> result<(), ty::type_err> { fn can_mk_subty(sub: ty::t, sup: ty::t) -> Result<(), ty::type_err> {
infer::can_mk_subty(self.infcx, sub, sup) infer::can_mk_subty(self.infcx, sub, sup)
} }
fn mk_assignty(expr: @ast::expr, borrow_lb: ast::node_id, fn mk_assignty(expr: @ast::expr, borrow_lb: ast::node_id,
sub: ty::t, sup: ty::t) -> result<(), ty::type_err> { sub: ty::t, sup: ty::t) -> Result<(), ty::type_err> {
let anmnt = &{expr_id: expr.id, span: expr.span, let anmnt = &{expr_id: expr.id, span: expr.span,
borrow_lb: borrow_lb}; borrow_lb: borrow_lb};
infer::mk_assignty(self.infcx, anmnt, sub, sup) infer::mk_assignty(self.infcx, anmnt, sub, sup)
} }
fn can_mk_assignty(expr: @ast::expr, borrow_lb: ast::node_id, fn can_mk_assignty(expr: @ast::expr, borrow_lb: ast::node_id,
sub: ty::t, sup: ty::t) -> result<(), ty::type_err> { sub: ty::t, sup: ty::t) -> Result<(), ty::type_err> {
let anmnt = &{expr_id: expr.id, span: expr.span, let anmnt = &{expr_id: expr.id, span: expr.span,
borrow_lb: borrow_lb}; borrow_lb: borrow_lb};
infer::can_mk_assignty(self.infcx, anmnt, sub, sup) infer::can_mk_assignty(self.infcx, anmnt, sub, sup)
} }
fn mk_eqty(a_is_expected: bool, span: span, fn mk_eqty(a_is_expected: bool, span: span,
sub: ty::t, sup: ty::t) -> result<(), ty::type_err> { sub: ty::t, sup: ty::t) -> Result<(), ty::type_err> {
infer::mk_eqty(self.infcx, a_is_expected, span, sub, sup) infer::mk_eqty(self.infcx, a_is_expected, span, sub, sup)
} }
fn mk_subr(a_is_expected: bool, span: span, fn mk_subr(a_is_expected: bool, span: span,
sub: ty::region, sup: ty::region) -> result<(), ty::type_err> { sub: ty::region, sup: ty::region) -> Result<(), ty::type_err> {
infer::mk_subr(self.infcx, a_is_expected, span, sub, sup) infer::mk_subr(self.infcx, a_is_expected, span, sub, sup)
} }
@ -1181,7 +1181,7 @@ fn check_expr_with_unifier(fcx: @fn_ctxt,
match expected { match expected {
Some(t) => { Some(t) => {
match resolve_type(fcx.infcx, t, force_tvar) { match resolve_type(fcx.infcx, t, force_tvar) {
result::ok(t) => unpack(ty::get(t).struct), result::Ok(t) => unpack(ty::get(t).struct),
_ => None _ => None
} }
} }
@ -1551,8 +1551,8 @@ fn check_expr_with_unifier(fcx: @fn_ctxt,
match expr_opt { match expr_opt {
None => match fcx.mk_eqty(false, expr.span, None => match fcx.mk_eqty(false, expr.span,
ret_ty, ty::mk_nil(tcx)) { ret_ty, ty::mk_nil(tcx)) {
result::ok(_) => { /* fall through */ } result::Ok(_) => { /* fall through */ }
result::err(_) => { result::Err(_) => {
tcx.sess.span_err( tcx.sess.span_err(
expr.span, expr.span,
~"`return;` in function returning non-nil"); ~"`return;` in function returning non-nil");
@ -1626,8 +1626,8 @@ fn check_expr_with_unifier(fcx: @fn_ctxt,
Some(ty::ty_fn(fty)) => { Some(ty::ty_fn(fty)) => {
match fcx.mk_subty(false, expr.span, match fcx.mk_subty(false, expr.span,
fty.output, ty::mk_bool(tcx)) { fty.output, ty::mk_bool(tcx)) {
result::ok(_) => (), result::Ok(_) => (),
result::err(_) => { result::Err(_) => {
tcx.sess.span_fatal( tcx.sess.span_fatal(
expr.span, fmt!("a `loop` function's last argument \ expr.span, fmt!("a `loop` function's last argument \
should return `bool`, not `%s`", should return `bool`, not `%s`",
@ -2417,7 +2417,7 @@ fn instantiate_path(fcx: @fn_ctxt,
// resolution is possible, then an error is reported. // resolution is possible, then an error is reported.
fn structurally_resolved_type(fcx: @fn_ctxt, sp: span, tp: ty::t) -> ty::t { fn structurally_resolved_type(fcx: @fn_ctxt, sp: span, tp: ty::t) -> ty::t {
match infer::resolve_type(fcx.infcx, tp, force_tvar) { match infer::resolve_type(fcx.infcx, tp, force_tvar) {
result::ok(t_s) if !ty::type_is_var(t_s) => return t_s, result::Ok(t_s) if !ty::type_is_var(t_s) => return t_s,
_ => { _ => {
fcx.ccx.tcx.sess.span_fatal fcx.ccx.tcx.sess.span_fatal
(sp, ~"the type of this value must be known in this context"); (sp, ~"the type of this value must be known in this context");

View file

@ -8,8 +8,8 @@ fn suptype(fcx: @fn_ctxt, sp: span,
// n.b.: order of actual, expected is reversed // n.b.: order of actual, expected is reversed
match infer::mk_subty(fcx.infcx, false, sp, match infer::mk_subty(fcx.infcx, false, sp,
actual, expected) { actual, expected) {
result::ok(()) => { /* ok */ } result::Ok(()) => { /* ok */ }
result::err(ref err) => { result::Err(ref err) => {
fcx.report_mismatched_types(sp, expected, actual, err); fcx.report_mismatched_types(sp, expected, actual, err);
} }
} }
@ -19,8 +19,8 @@ fn eqtype(fcx: @fn_ctxt, sp: span,
expected: ty::t, actual: ty::t) { expected: ty::t, actual: ty::t) {
match infer::mk_eqty(fcx.infcx, false, sp, actual, expected) { match infer::mk_eqty(fcx.infcx, false, sp, actual, expected) {
result::ok(()) => { /* ok */ } result::Ok(()) => { /* ok */ }
result::err(ref err) => { result::Err(ref err) => {
fcx.report_mismatched_types(sp, expected, actual, err); fcx.report_mismatched_types(sp, expected, actual, err);
} }
} }
@ -31,8 +31,8 @@ fn assign(fcx: @fn_ctxt, sp: span, borrow_lb: ast::node_id,
expected: ty::t, expr: @ast::expr) { expected: ty::t, expr: @ast::expr) {
let expr_ty = fcx.expr_ty(expr); let expr_ty = fcx.expr_ty(expr);
match fcx.mk_assignty(expr, borrow_lb, expr_ty, expected) { match fcx.mk_assignty(expr, borrow_lb, expr_ty, expected) {
result::ok(()) => { /* ok */ } result::Ok(()) => { /* ok */ }
result::err(ref err) => { result::Err(ref err) => {
fcx.report_mismatched_types(sp, expected, expr_ty, err); fcx.report_mismatched_types(sp, expected, expr_ty, err);
} }
} }

View file

@ -434,7 +434,7 @@ struct lookup {
fn check_type_match(impl_ty: ty::t, fn check_type_match(impl_ty: ty::t,
mode: method_lookup_mode) mode: method_lookup_mode)
-> result<(), ty::type_err> { -> Result<(), ty::type_err> {
// Depending on our argument, we find potential matches by // Depending on our argument, we find potential matches by
// checking subtypability, type assignability, or reference // checking subtypability, type assignability, or reference
// subtypability. Collect the matches. // subtypability. Collect the matches.
@ -492,8 +492,8 @@ struct lookup {
let matches = self.check_type_match(impl_ty, mode); let matches = self.check_type_match(impl_ty, mode);
debug!("matches = %?", matches); debug!("matches = %?", matches);
match matches { match matches {
result::err(_) => { /* keep looking */ } result::Err(_) => { /* keep looking */ }
result::ok(_) => { result::Ok(_) => {
if !self.candidate_impls.contains_key(im.did) { if !self.candidate_impls.contains_key(im.did) {
let fty = self.ty_from_did(m.did); let fty = self.ty_from_did(m.did);
self.candidates.push( self.candidates.push(
@ -650,8 +650,8 @@ struct lookup {
// is not from an impl, this'll basically be a no-nop. // is not from an impl, this'll basically be a no-nop.
match self.fcx.mk_assignty(self.self_expr, self.borrow_lb, match self.fcx.mk_assignty(self.self_expr, self.borrow_lb,
cand.self_ty, cand.rcvr_ty) { cand.self_ty, cand.rcvr_ty) {
result::ok(_) => (), result::Ok(_) => (),
result::err(_) => { result::Err(_) => {
self.tcx().sess.span_bug( self.tcx().sess.span_bug(
self.expr.span, self.expr.span,
fmt!("%s was assignable to %s but now is not?", fmt!("%s was assignable to %s but now is not?",

View file

@ -187,8 +187,8 @@ fn visit_expr(e: @ast::expr, &&rcx: @rcx, v: rvt) {
// check_cast_for_escaping_regions() in kind.rs explaining how // check_cast_for_escaping_regions() in kind.rs explaining how
// it goes about doing that. // it goes about doing that.
match rcx.resolve_node_type(e.id) { match rcx.resolve_node_type(e.id) {
result::err(_) => { return; /* typeck will fail anyhow */ } result::Err(_) => { return; /* typeck will fail anyhow */ }
result::ok(target_ty) => { result::Ok(target_ty) => {
match ty::get(target_ty).struct { match ty::get(target_ty).struct {
ty::ty_trait(_, substs, _) => { ty::ty_trait(_, substs, _) => {
let trait_region = match substs.self_r { let trait_region = match substs.self_r {
@ -213,8 +213,8 @@ fn visit_expr(e: @ast::expr, &&rcx: @rcx, v: rvt) {
ast::expr_fn(*) | ast::expr_fn_block(*) => { ast::expr_fn(*) | ast::expr_fn_block(*) => {
match rcx.resolve_node_type(e.id) { match rcx.resolve_node_type(e.id) {
result::err(_) => return, // Typechecking will fail anyhow. result::Err(_) => return, // Typechecking will fail anyhow.
result::ok(function_type) => { result::Ok(function_type) => {
match ty::get(function_type).struct { match ty::get(function_type).struct {
ty::ty_fn({ ty::ty_fn({
proto: proto_vstore(vstore_slice(region)), _ proto: proto_vstore(vstore_slice(region)), _
@ -249,8 +249,8 @@ fn visit_node(id: ast::node_id, span: span, rcx: @rcx) -> bool {
// is going to fail anyway, so just stop here and let typeck // is going to fail anyway, so just stop here and let typeck
// report errors later on in the writeback phase. // report errors later on in the writeback phase.
let ty = match rcx.resolve_node_type(id) { let ty = match rcx.resolve_node_type(id) {
result::err(_) => return true, result::Err(_) => return true,
result::ok(ty) => ty result::Ok(ty) => ty
}; };
// find the region where this expr evaluation is taking place // find the region where this expr evaluation is taking place
@ -279,8 +279,8 @@ fn constrain_free_variables(
let en_region = encl_region_of_def(rcx.fcx, def); let en_region = encl_region_of_def(rcx.fcx, def);
match rcx.fcx.mk_subr(true, freevar.span, match rcx.fcx.mk_subr(true, freevar.span,
region, en_region) { region, en_region) {
result::ok(()) => {} result::Ok(()) => {}
result::err(_) => { result::Err(_) => {
tcx.sess.span_err( tcx.sess.span_err(
freevar.span, freevar.span,
~"captured variable does not outlive the enclosing closure"); ~"captured variable does not outlive the enclosing closure");
@ -331,7 +331,7 @@ fn constrain_regions_in_type(
} }
match rcx.fcx.mk_subr(true, span, encl_region, region) { match rcx.fcx.mk_subr(true, span, encl_region, region) {
result::err(_) => { result::Err(_) => {
tcx.sess.span_err( tcx.sess.span_err(
span, span,
fmt!("reference is not valid outside of its lifetime")); fmt!("reference is not valid outside of its lifetime"));
@ -341,7 +341,7 @@ fn constrain_regions_in_type(
region); region);
rcx.errors_reported += 1u; rcx.errors_reported += 1u;
} }
result::ok(()) => { result::Ok(()) => {
} }
} }
} }

View file

@ -194,8 +194,8 @@ fn lookup_vtable(fcx: @fn_ctxt,
impl_self_ty(fcx, expr, im.did, false); impl_self_ty(fcx, expr, im.did, false);
let im_bs = ty::lookup_item_type(tcx, im.did).bounds; let im_bs = ty::lookup_item_type(tcx, im.did).bounds;
match fcx.mk_subty(false, expr.span, ty, for_ty) { match fcx.mk_subty(false, expr.span, ty, for_ty) {
result::err(_) => again, result::Err(_) => again,
result::ok(()) => () result::Ok(()) => ()
} }
// check that desired trait type unifies // check that desired trait type unifies
@ -260,15 +260,15 @@ fn fixup_ty(fcx: @fn_ctxt,
{ {
let tcx = fcx.ccx.tcx; let tcx = fcx.ccx.tcx;
match resolve_type(fcx.infcx, ty, resolve_and_force_all_but_regions) { match resolve_type(fcx.infcx, ty, resolve_and_force_all_but_regions) {
result::ok(new_type) => Some(new_type), result::Ok(new_type) => Some(new_type),
result::err(e) if !is_early => { result::Err(e) if !is_early => {
tcx.sess.span_fatal( tcx.sess.span_fatal(
expr.span, expr.span,
fmt!("cannot determine a type \ fmt!("cannot determine a type \
for this bounded type parameter: %s", for this bounded type parameter: %s",
fixup_err_to_str(e))) fixup_err_to_str(e)))
} }
result::err(_) => { result::Err(_) => {
None None
} }
} }

View file

@ -11,8 +11,8 @@ fn resolve_type_vars_in_type(fcx: @fn_ctxt, sp: span, typ: ty::t) ->
Option<ty::t> { Option<ty::t> {
if !ty::type_needs_infer(typ) { return Some(typ); } if !ty::type_needs_infer(typ) { return Some(typ); }
match resolve_type(fcx.infcx, typ, resolve_all | force_all) { match resolve_type(fcx.infcx, typ, resolve_all | force_all) {
result::ok(new_type) => return Some(new_type), result::Ok(new_type) => return Some(new_type),
result::err(e) => { result::Err(e) => {
if !fcx.ccx.tcx.sess.has_errors() { if !fcx.ccx.tcx.sess.has_errors() {
fcx.ccx.tcx.sess.span_err( fcx.ccx.tcx.sess.span_err(
sp, sp,
@ -128,13 +128,13 @@ fn visit_local(l: @ast::local, wbcx: wb_ctxt, v: wb_vt) {
let var_id = lookup_local(wbcx.fcx, l.span, l.node.id); let var_id = lookup_local(wbcx.fcx, l.span, l.node.id);
let var_ty = ty::mk_var(wbcx.fcx.tcx(), var_id); let var_ty = ty::mk_var(wbcx.fcx.tcx(), var_id);
match resolve_type(wbcx.fcx.infcx, var_ty, resolve_all | force_all) { match resolve_type(wbcx.fcx.infcx, var_ty, resolve_all | force_all) {
result::ok(lty) => { result::Ok(lty) => {
debug!("Type for local %s (id %d) resolved to %s", debug!("Type for local %s (id %d) resolved to %s",
pat_to_str(l.node.pat, wbcx.fcx.ccx.tcx.sess.intr()),l.node.id, pat_to_str(l.node.pat, wbcx.fcx.ccx.tcx.sess.intr()),l.node.id,
wbcx.fcx.infcx.ty_to_str(lty)); wbcx.fcx.infcx.ty_to_str(lty));
write_ty_to_tcx(wbcx.fcx.ccx.tcx, l.node.id, lty); write_ty_to_tcx(wbcx.fcx.ccx.tcx, l.node.id, lty);
} }
result::err(e) => { result::Err(e) => {
wbcx.fcx.ccx.tcx.sess.span_err( wbcx.fcx.ccx.tcx.sess.span_err(
l.span, l.span,
fmt!("cannot determine a type \ fmt!("cannot determine a type \

View file

@ -31,7 +31,7 @@ import syntax::visit::{visit_mod};
import util::ppaux::ty_to_str; import util::ppaux::ty_to_str;
import dvec::{DVec, dvec}; import dvec::{DVec, dvec};
import result::ok; import result::Ok;
import std::map::{hashmap, int_hash}; import std::map::{hashmap, int_hash};
import uint::range; import uint::range;
import vec::{len, push}; import vec::{len, push};
@ -43,7 +43,7 @@ fn get_base_type(inference_context: infer_ctxt, span: span, original_type: t)
match resolve_type(inference_context, match resolve_type(inference_context,
original_type, original_type,
resolve_ivar) { resolve_ivar) {
ok(resulting_type) if !type_is_var(resulting_type) => { Ok(resulting_type) if !type_is_var(resulting_type) => {
resolved_type = resulting_type; resolved_type = resulting_type;
} }
_ => { _ => {

View file

@ -255,7 +255,7 @@ import middle::ty::{tv_vid, tvi_vid, region_vid, vid,
import syntax::{ast, ast_util}; import syntax::{ast, ast_util};
import syntax::ast::{ret_style, purity}; import syntax::ast::{ret_style, purity};
import util::ppaux::{ty_to_str, mt_to_str}; import util::ppaux::{ty_to_str, mt_to_str};
import result::{result, ok, err, map_vec, map_vec2, iter_vec2}; import result::{Result, Ok, Err, map_vec, map_vec2, iter_vec2};
import ty::{mk_fn, type_is_bot}; import ty::{mk_fn, type_is_bot};
import check::regionmanip::{replace_bound_regions_in_fn_ty}; import check::regionmanip::{replace_bound_regions_in_fn_ty};
import driver::session::session; import driver::session::session;
@ -309,7 +309,7 @@ type assignment = {
type bound<T:copy> = Option<T>; type bound<T:copy> = Option<T>;
type bounds<T:copy> = {lb: bound<T>, ub: bound<T>}; type bounds<T:copy> = {lb: bound<T>, ub: bound<T>};
type cres<T> = result<T,ty::type_err>; type cres<T> = Result<T,ty::type_err>;
enum infer_ctxt = @{ enum infer_ctxt = @{
tcx: ty::ctxt, tcx: ty::ctxt,
@ -358,8 +358,8 @@ fn fixup_err_to_str(f: fixup_err) -> ~str {
} }
} }
type ures = result::result<(), ty::type_err>; type ures = result::Result<(), ty::type_err>;
type fres<T> = result::result<T, fixup_err>; type fres<T> = result::Result<T, fixup_err>;
fn new_vals_and_bindings<V:copy, T:copy>() -> vals_and_bindings<V, T> { fn new_vals_and_bindings<V:copy, T:copy>() -> vals_and_bindings<V, T> {
vals_and_bindings { vals_and_bindings {
@ -463,14 +463,14 @@ fn resolve_region(cx: infer_ctxt, r: ty::region, modes: uint)
fn resolve_borrowings(cx: infer_ctxt) { fn resolve_borrowings(cx: infer_ctxt) {
for cx.borrowings.each |item| { for cx.borrowings.each |item| {
match resolve_region(cx, item.scope, resolve_all|force_all) { match resolve_region(cx, item.scope, resolve_all|force_all) {
ok(region) => { Ok(region) => {
debug!("borrowing for expr %d resolved to region %?, mutbl %?", debug!("borrowing for expr %d resolved to region %?, mutbl %?",
item.expr_id, region, item.mutbl); item.expr_id, region, item.mutbl);
cx.tcx.borrowings.insert( cx.tcx.borrowings.insert(
item.expr_id, {region: region, mutbl: item.mutbl}); item.expr_id, {region: region, mutbl: item.mutbl});
} }
err(e) => { Err(e) => {
let str = fixup_err_to_str(e); let str = fixup_err_to_str(e);
cx.tcx.sess.span_err( cx.tcx.sess.span_err(
item.span, item.span,
@ -481,13 +481,13 @@ fn resolve_borrowings(cx: infer_ctxt) {
} }
trait then { trait then {
fn then<T:copy>(f: fn() -> result<T,ty::type_err>) fn then<T:copy>(f: fn() -> Result<T,ty::type_err>)
-> result<T,ty::type_err>; -> Result<T,ty::type_err>;
} }
impl ures: then { impl ures: then {
fn then<T:copy>(f: fn() -> result<T,ty::type_err>) fn then<T:copy>(f: fn() -> Result<T,ty::type_err>)
-> result<T,ty::type_err> { -> Result<T,ty::type_err> {
self.chain(|_i| f()) self.chain(|_i| f())
} }
} }
@ -500,8 +500,8 @@ trait cres_helpers<T> {
impl<T:copy> cres<T>: cres_helpers<T> { impl<T:copy> cres<T>: cres_helpers<T> {
fn to_ures() -> ures { fn to_ures() -> ures {
match self { match self {
ok(_v) => ok(()), Ok(_v) => Ok(()),
err(e) => err(e) Err(e) => Err(e)
} }
} }
@ -510,14 +510,14 @@ impl<T:copy> cres<T>: cres_helpers<T> {
if s == t { if s == t {
self self
} else { } else {
err(f()) Err(f())
} }
} }
} }
} }
fn uok() -> ures { fn uok() -> ures {
ok(()) Ok(())
} }
fn rollback_to<V:copy vid, T:copy>( fn rollback_to<V:copy vid, T:copy>(
@ -570,7 +570,7 @@ impl infer_ctxt {
} }
/// Execute `f` and commit the bindings if successful /// Execute `f` and commit the bindings if successful
fn commit<T,E>(f: fn() -> result<T,E>) -> result<T,E> { fn commit<T,E>(f: fn() -> Result<T,E>) -> Result<T,E> {
assert !self.in_snapshot(); assert !self.in_snapshot();
debug!("commit()"); debug!("commit()");
@ -588,21 +588,21 @@ impl infer_ctxt {
} }
/// Execute `f`, unroll bindings on failure /// Execute `f`, unroll bindings on failure
fn try<T,E>(f: fn() -> result<T,E>) -> result<T,E> { fn try<T,E>(f: fn() -> Result<T,E>) -> Result<T,E> {
debug!("try()"); debug!("try()");
do indent { do indent {
let snapshot = self.start_snapshot(); let snapshot = self.start_snapshot();
let r = f(); let r = f();
match r { match r {
ok(_) => (), Ok(_) => (),
err(_) => self.rollback_to(&snapshot) Err(_) => self.rollback_to(&snapshot)
} }
r r
} }
} }
/// Execute `f` then unroll any bindings it creates /// Execute `f` then unroll any bindings it creates
fn probe<T,E>(f: fn() -> result<T,E>) -> result<T,E> { fn probe<T,E>(f: fn() -> Result<T,E>) -> Result<T,E> {
debug!("probe()"); debug!("probe()");
do indent { do indent {
let snapshot = self.start_snapshot(); let snapshot = self.start_snapshot();
@ -674,8 +674,8 @@ impl infer_ctxt {
fn resolve_type_vars_if_possible(typ: ty::t) -> ty::t { fn resolve_type_vars_if_possible(typ: ty::t) -> ty::t {
match resolve_type(self, typ, resolve_nested_tvar | resolve_ivar) { match resolve_type(self, typ, resolve_nested_tvar | resolve_ivar) {
result::ok(new_type) => new_type, result::Ok(new_type) => new_type,
result::err(_) => typ result::Err(_) => typ
} }
} }
} }

View file

@ -113,8 +113,8 @@ fn eq_regions<C: combine>(self: &C, a: ty::region, b: ty::region) -> ures {
// found in the original error // found in the original error
match e { match e {
ty::terr_regions_does_not_outlive(a1, b1) => ty::terr_regions_does_not_outlive(a1, b1) =>
err(ty::terr_regions_not_same(a1, b1)), Err(ty::terr_regions_not_same(a1, b1)),
_ => err(e) _ => Err(e)
} }
}).to_ures() }).to_ures()
} }
@ -127,11 +127,11 @@ fn eq_opt_regions<C:combine>(
match (a, b) { match (a, b) {
(None, None) => { (None, None) => {
ok(None) Ok(None)
} }
(Some(a), Some(b)) => { (Some(a), Some(b)) => {
do eq_regions(self, a, b).then { do eq_regions(self, a, b).then {
ok(Some(a)) Ok(Some(a))
} }
} }
(_, _) => { (_, _) => {
@ -162,21 +162,21 @@ fn super_substs<C:combine>(
let polyty = ty::lookup_item_type(self.infcx().tcx, did); let polyty = ty::lookup_item_type(self.infcx().tcx, did);
match (polyty.region_param, a, b) { match (polyty.region_param, a, b) {
(None, None, None) => { (None, None, None) => {
ok(None) Ok(None)
} }
(Some(ty::rv_invariant), Some(a), Some(b)) => { (Some(ty::rv_invariant), Some(a), Some(b)) => {
do eq_regions(self, a, b).then { do eq_regions(self, a, b).then {
ok(Some(a)) Ok(Some(a))
} }
} }
(Some(ty::rv_covariant), Some(a), Some(b)) => { (Some(ty::rv_covariant), Some(a), Some(b)) => {
do self.regions(a, b).chain |r| { do self.regions(a, b).chain |r| {
ok(Some(r)) Ok(Some(r))
} }
} }
(Some(ty::rv_contravariant), Some(a), Some(b)) => { (Some(ty::rv_contravariant), Some(a), Some(b)) => {
do self.contraregions(a, b).chain |r| { do self.contraregions(a, b).chain |r| {
ok(Some(r)) Ok(Some(r))
} }
} }
(_, _, _) => { (_, _, _) => {
@ -200,7 +200,7 @@ fn super_substs<C:combine>(
do relate_region_param(self, did, do relate_region_param(self, did,
a.self_r, b.self_r).chain |self_r| a.self_r, b.self_r).chain |self_r|
{ {
ok({self_r: self_r, self_ty: self_ty, tps: tps}) Ok({self_r: self_r, self_ty: self_ty, tps: tps})
} }
} }
} }
@ -217,9 +217,9 @@ fn super_tps<C:combine>(
if vec::same_length(as, bs) { if vec::same_length(as, bs) {
iter_vec2(as, bs, |a, b| { iter_vec2(as, bs, |a, b| {
eq_tys(self, a, b) eq_tys(self, a, b)
}).then(|| ok(as.to_vec()) ) }).then(|| Ok(as.to_vec()) )
} else { } else {
err(ty::terr_ty_param_size( Err(ty::terr_ty_param_size(
expected_found(self, as.len(), bs.len()))) expected_found(self, as.len(), bs.len())))
} }
} }
@ -232,17 +232,17 @@ fn super_self_tys<C:combine>(
match (a, b) { match (a, b) {
(None, None) => { (None, None) => {
ok(None) Ok(None)
} }
(Some(a), Some(b)) => { (Some(a), Some(b)) => {
eq_tys(self, a, b).then(|| ok(Some(a)) ) eq_tys(self, a, b).then(|| Ok(Some(a)) )
} }
(None, Some(_)) | (None, Some(_)) |
(Some(_), None) => { (Some(_), None) => {
// I think it should never happen that we unify two substs and // I think it should never happen that we unify two substs and
// one of them has a self_ty and one doesn't...? I could be // one of them has a self_ty and one doesn't...? I could be
// wrong about this. // wrong about this.
err(ty::terr_self_substs) Err(ty::terr_self_substs)
} }
} }
} }
@ -252,10 +252,10 @@ fn super_flds<C:combine>(
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({ident: a.ident, mt: mt}) ) .chain(|mt| Ok({ident: a.ident, mt: mt}) )
.chain_err(|e| err(ty::terr_in_field(@e, a.ident)) ) .chain_err(|e| Err(ty::terr_in_field(@e, a.ident)) )
} else { } else {
err(ty::terr_record_fields( Err(ty::terr_record_fields(
expected_found(self, a.ident, b.ident))) expected_found(self, a.ident, b.ident)))
} }
} }
@ -274,7 +274,7 @@ fn super_args<C:combine>(
do self.modes(a.mode, b.mode).chain |m| { do self.modes(a.mode, b.mode).chain |m| {
do self.contratys(a.ty, b.ty).chain |t| { do self.contratys(a.ty, b.ty).chain |t| {
ok({mode: m, ty: t}) Ok({mode: m, ty: t})
} }
} }
} }
@ -286,16 +286,16 @@ fn super_vstores<C: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).chain |r| {
ok(ty::vstore_slice(r)) Ok(ty::vstore_slice(r))
} }
} }
_ if a == b => { _ if a == b => {
ok(a) Ok(a)
} }
_ => { _ => {
err(ty::terr_vstores_differ(vk, expected_found(self, a, b))) Err(ty::terr_vstores_differ(vk, expected_found(self, a, b)))
} }
} }
} }
@ -309,7 +309,7 @@ fn super_fns<C:combine>(
if vec::same_length(a_args, b_args) { if vec::same_length(a_args, b_args) {
map_vec2(a_args, b_args, |a, b| self.args(a, b) ) map_vec2(a_args, b_args, |a, b| self.args(a, b) )
} else { } else {
err(ty::terr_arg_count) Err(ty::terr_arg_count)
} }
} }
@ -321,7 +321,7 @@ fn super_fns<C:combine>(
// FIXME: uncomment if #2588 doesn't get accepted: // FIXME: uncomment if #2588 doesn't get accepted:
// self.infcx().constrvecs(a_f.constraints, // self.infcx().constrvecs(a_f.constraints,
// b_f.constraints).then {|| // b_f.constraints).then {||
ok({purity: purity, Ok({purity: purity,
proto: p, proto: p,
bounds: a_f.bounds, // XXX: This is wrong! bounds: a_f.bounds, // XXX: This is wrong!
inputs: inputs, inputs: inputs,
@ -354,15 +354,15 @@ fn super_tys<C:combine>(
// Relate integral variables to other types // Relate integral variables to other types
(ty::ty_var_integral(a_id), ty::ty_var_integral(b_id)) => { (ty::ty_var_integral(a_id), ty::ty_var_integral(b_id)) => {
self.infcx().vars_integral(a_id, b_id).then(|| ok(a) ) self.infcx().vars_integral(a_id, b_id).then(|| Ok(a) )
} }
(ty::ty_var_integral(a_id), ty::ty_int(_)) | (ty::ty_var_integral(a_id), ty::ty_int(_)) |
(ty::ty_var_integral(a_id), ty::ty_uint(_)) => { (ty::ty_var_integral(a_id), ty::ty_uint(_)) => {
self.infcx().var_integral_sub_t(a_id, b).then(|| ok(a) ) self.infcx().var_integral_sub_t(a_id, b).then(|| Ok(a) )
} }
(ty::ty_int(_), ty::ty_var_integral(b_id)) | (ty::ty_int(_), ty::ty_var_integral(b_id)) |
(ty::ty_uint(_), ty::ty_var_integral(b_id)) => { (ty::ty_uint(_), ty::ty_var_integral(b_id)) => {
self.infcx().t_sub_var_integral(a, b_id).then(|| ok(a) ) self.infcx().t_sub_var_integral(a, b_id).then(|| Ok(a) )
} }
(ty::ty_int(_), _) | (ty::ty_int(_), _) |
@ -371,9 +371,9 @@ fn super_tys<C:combine>(
let as = ty::get(a).struct; let as = ty::get(a).struct;
let bs = ty::get(b).struct; let bs = ty::get(b).struct;
if as == bs { if as == bs {
ok(a) Ok(a)
} else { } else {
err(ty::terr_sorts(expected_found(self, a, b))) Err(ty::terr_sorts(expected_found(self, a, b)))
} }
} }
@ -381,21 +381,21 @@ fn super_tys<C:combine>(
(ty::ty_bool, _) => { (ty::ty_bool, _) => {
let cfg = tcx.sess.targ_cfg; let cfg = tcx.sess.targ_cfg;
if ty::mach_sty(cfg, a) == ty::mach_sty(cfg, b) { if ty::mach_sty(cfg, a) == ty::mach_sty(cfg, b) {
ok(a) Ok(a)
} else { } else {
err(ty::terr_sorts(expected_found(self, a, b))) Err(ty::terr_sorts(expected_found(self, a, b)))
} }
} }
(ty::ty_param(a_p), ty::ty_param(b_p)) if a_p.idx == b_p.idx => { (ty::ty_param(a_p), ty::ty_param(b_p)) if a_p.idx == b_p.idx => {
ok(a) Ok(a)
} }
(ty::ty_enum(a_id, ref a_substs), (ty::ty_enum(a_id, ref a_substs),
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 => {
do self.substs(a_id, a_substs, b_substs).chain |substs| { do self.substs(a_id, a_substs, b_substs).chain |substs| {
ok(ty::mk_enum(tcx, a_id, substs)) Ok(ty::mk_enum(tcx, a_id, substs))
} }
} }
@ -404,7 +404,7 @@ fn super_tys<C:combine>(
if a_id == b_id => { if a_id == b_id => {
do self.substs(a_id, a_substs, b_substs).chain |substs| { do self.substs(a_id, a_substs, b_substs).chain |substs| {
do self.vstores(ty::terr_trait, a_vstore, b_vstore).chain |vs| { do self.vstores(ty::terr_trait, a_vstore, b_vstore).chain |vs| {
ok(ty::mk_trait(tcx, a_id, substs, vs)) Ok(ty::mk_trait(tcx, a_id, substs, vs))
} }
} }
} }
@ -412,32 +412,32 @@ fn super_tys<C:combine>(
(ty::ty_class(a_id, ref a_substs), ty::ty_class(b_id, ref b_substs)) (ty::ty_class(a_id, ref a_substs), ty::ty_class(b_id, ref b_substs))
if a_id == b_id => { if a_id == b_id => {
do self.substs(a_id, a_substs, b_substs).chain |substs| { do self.substs(a_id, a_substs, b_substs).chain |substs| {
ok(ty::mk_class(tcx, a_id, substs)) Ok(ty::mk_class(tcx, a_id, substs))
} }
} }
(ty::ty_box(a_mt), ty::ty_box(b_mt)) => { (ty::ty_box(a_mt), ty::ty_box(b_mt)) => {
do self.mts(a_mt, b_mt).chain |mt| { do self.mts(a_mt, b_mt).chain |mt| {
ok(ty::mk_box(tcx, mt)) Ok(ty::mk_box(tcx, mt))
} }
} }
(ty::ty_uniq(a_mt), ty::ty_uniq(b_mt)) => { (ty::ty_uniq(a_mt), ty::ty_uniq(b_mt)) => {
do self.mts(a_mt, b_mt).chain |mt| { do self.mts(a_mt, b_mt).chain |mt| {
ok(ty::mk_uniq(tcx, mt)) Ok(ty::mk_uniq(tcx, mt))
} }
} }
(ty::ty_ptr(a_mt), ty::ty_ptr(b_mt)) => { (ty::ty_ptr(a_mt), ty::ty_ptr(b_mt)) => {
do self.mts(a_mt, b_mt).chain |mt| { do self.mts(a_mt, b_mt).chain |mt| {
ok(ty::mk_ptr(tcx, mt)) Ok(ty::mk_ptr(tcx, mt))
} }
} }
(ty::ty_rptr(a_r, a_mt), ty::ty_rptr(b_r, b_mt)) => { (ty::ty_rptr(a_r, a_mt), ty::ty_rptr(b_r, b_mt)) => {
do self.contraregions(a_r, b_r).chain |r| { do self.contraregions(a_r, b_r).chain |r| {
do self.mts(a_mt, b_mt).chain |mt| { do self.mts(a_mt, b_mt).chain |mt| {
ok(ty::mk_rptr(tcx, r, mt)) Ok(ty::mk_rptr(tcx, r, mt))
} }
} }
} }
@ -445,14 +445,14 @@ fn super_tys<C:combine>(
(ty::ty_evec(a_mt, vs_a), ty::ty_evec(b_mt, vs_b)) => { (ty::ty_evec(a_mt, vs_a), ty::ty_evec(b_mt, vs_b)) => {
do self.mts(a_mt, b_mt).chain |mt| { do self.mts(a_mt, b_mt).chain |mt| {
do self.vstores(ty::terr_vec, vs_a, vs_b).chain |vs| { do self.vstores(ty::terr_vec, vs_a, vs_b).chain |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 self.vstores(ty::terr_str, vs_a, vs_b).chain |vs| { do self.vstores(ty::terr_str, vs_a, vs_b).chain |vs| {
ok(ty::mk_estr(tcx,vs)) Ok(ty::mk_estr(tcx,vs))
} }
} }
@ -460,9 +460,9 @@ fn super_tys<C:combine>(
if vec::same_length(as, bs) { if vec::same_length(as, bs) {
map_vec2(as, bs, |a,b| { map_vec2(as, bs, |a,b| {
self.flds(a, b) self.flds(a, b)
}).chain(|flds| ok(ty::mk_rec(tcx, flds)) ) }).chain(|flds| Ok(ty::mk_rec(tcx, flds)) )
} else { } else {
err(ty::terr_record_size(expected_found(self, as.len(), Err(ty::terr_record_size(expected_found(self, as.len(),
bs.len()))) bs.len())))
} }
} }
@ -470,19 +470,19 @@ fn super_tys<C:combine>(
(ty::ty_tup(as), ty::ty_tup(bs)) => { (ty::ty_tup(as), ty::ty_tup(bs)) => {
if vec::same_length(as, bs) { if vec::same_length(as, bs) {
map_vec2(as, bs, |a, b| self.tys(a, b) ) map_vec2(as, bs, |a, b| self.tys(a, b) )
.chain(|ts| ok(ty::mk_tup(tcx, ts)) ) .chain(|ts| Ok(ty::mk_tup(tcx, ts)) )
} else { } else {
err(ty::terr_tuple_size(expected_found(self, as.len(), bs.len()))) Err(ty::terr_tuple_size(expected_found(self, as.len(), bs.len())))
} }
} }
(ty::ty_fn(ref a_fty), ty::ty_fn(ref b_fty)) => { (ty::ty_fn(ref a_fty), ty::ty_fn(ref b_fty)) => {
do self.fns(a_fty, b_fty).chain |fty| { do self.fns(a_fty, b_fty).chain |fty| {
ok(ty::mk_fn(tcx, fty)) Ok(ty::mk_fn(tcx, fty))
} }
} }
_ => err(ty::terr_sorts(expected_found(self, a, b))) _ => Err(ty::terr_sorts(expected_found(self, a, b)))
} }
} }

View file

@ -26,17 +26,17 @@ impl Glb: combine {
// the precise type from the mut side. // the precise type from the mut side.
(m_mutbl, m_const) => { (m_mutbl, m_const) => {
Sub(*self).tys(a.ty, b.ty).chain(|_t| { Sub(*self).tys(a.ty, b.ty).chain(|_t| {
ok({ty: a.ty, mutbl: m_mutbl}) Ok({ty: a.ty, mutbl: m_mutbl})
}) })
} }
(m_const, m_mutbl) => { (m_const, m_mutbl) => {
Sub(*self).tys(b.ty, a.ty).chain(|_t| { Sub(*self).tys(b.ty, a.ty).chain(|_t| {
ok({ty: b.ty, mutbl: m_mutbl}) Ok({ty: b.ty, mutbl: m_mutbl})
}) })
} }
(m_mutbl, m_mutbl) => { (m_mutbl, m_mutbl) => {
eq_tys(&self, a.ty, b.ty).then(|| { eq_tys(&self, a.ty, b.ty).then(|| {
ok({ty: a.ty, mutbl: m_mutbl}) Ok({ty: a.ty, mutbl: m_mutbl})
}) })
} }
@ -46,7 +46,7 @@ impl Glb: combine {
(m_const, m_imm) | (m_const, m_imm) |
(m_imm, m_imm) => { (m_imm, m_imm) => {
self.tys(a.ty, b.ty).chain(|t| { self.tys(a.ty, b.ty).chain(|t| {
ok({ty: t, mutbl: m_imm}) Ok({ty: t, mutbl: m_imm})
}) })
} }
@ -54,14 +54,14 @@ impl Glb: combine {
// sides and mutbl of only `m_const`. // sides and mutbl of only `m_const`.
(m_const, m_const) => { (m_const, m_const) => {
self.tys(a.ty, b.ty).chain(|t| { self.tys(a.ty, b.ty).chain(|t| {
ok({ty: t, mutbl: m_const}) Ok({ty: t, mutbl: m_const})
}) })
} }
// There is no mutual subtype of these combinations. // There is no mutual subtype of these combinations.
(m_mutbl, m_imm) | (m_mutbl, m_imm) |
(m_imm, m_mutbl) => { (m_imm, m_mutbl) => {
err(ty::terr_mutability) Err(ty::terr_mutability)
} }
} }
} }
@ -72,39 +72,39 @@ impl Glb: combine {
fn protos(p1: ty::fn_proto, p2: ty::fn_proto) -> cres<ty::fn_proto> { fn protos(p1: ty::fn_proto, p2: ty::fn_proto) -> cres<ty::fn_proto> {
match (p1, p2) { match (p1, p2) {
(ty::proto_vstore(ty::vstore_slice(_)), _) => ok(p2), (ty::proto_vstore(ty::vstore_slice(_)), _) => Ok(p2),
(_, ty::proto_vstore(ty::vstore_slice(_))) => ok(p1), (_, ty::proto_vstore(ty::vstore_slice(_))) => Ok(p1),
(ty::proto_vstore(v1), ty::proto_vstore(v2)) => { (ty::proto_vstore(v1), ty::proto_vstore(v2)) => {
self.infcx.try(|| { self.infcx.try(|| {
do self.vstores(terr_fn, v1, v2).chain |vs| { do self.vstores(terr_fn, v1, v2).chain |vs| {
ok(ty::proto_vstore(vs)) Ok(ty::proto_vstore(vs))
} }
}).chain_err(|_err| { }).chain_err(|_err| {
// XXX: Totally unsound, but fixed up later. // XXX: Totally unsound, but fixed up later.
ok(ty::proto_bare) Ok(ty::proto_bare)
}) })
} }
_ => ok(ty::proto_bare) _ => Ok(ty::proto_bare)
} }
} }
fn purities(a: purity, b: purity) -> cres<purity> { fn purities(a: purity, b: purity) -> cres<purity> {
match (a, b) { match (a, b) {
(pure_fn, _) | (_, pure_fn) => ok(pure_fn), (pure_fn, _) | (_, pure_fn) => Ok(pure_fn),
(extern_fn, _) | (_, extern_fn) => ok(extern_fn), (extern_fn, _) | (_, extern_fn) => Ok(extern_fn),
(impure_fn, _) | (_, impure_fn) => ok(impure_fn), (impure_fn, _) | (_, impure_fn) => Ok(impure_fn),
(unsafe_fn, unsafe_fn) => ok(unsafe_fn) (unsafe_fn, unsafe_fn) => Ok(unsafe_fn)
} }
} }
fn ret_styles(r1: ret_style, r2: ret_style) -> cres<ret_style> { fn ret_styles(r1: ret_style, r2: ret_style) -> cres<ret_style> {
match (r1, r2) { match (r1, r2) {
(ast::return_val, ast::return_val) => { (ast::return_val, ast::return_val) => {
ok(ast::return_val) Ok(ast::return_val)
} }
(ast::noreturn, _) | (ast::noreturn, _) |
(_, ast::noreturn) => { (_, ast::noreturn) => {
ok(ast::noreturn) Ok(ast::noreturn)
} }
} }
} }

View file

@ -20,7 +20,7 @@ impl Lub: lattice_ops {
{ub: Some(t) with b} {ub: Some(t) with b}
} }
fn ty_bot(t: ty::t) -> cres<ty::t> { fn ty_bot(t: ty::t) -> cres<ty::t> {
ok(t) Ok(t)
} }
} }
@ -30,7 +30,7 @@ impl Glb: lattice_ops {
{lb: Some(t) with b} {lb: Some(t) with b}
} }
fn ty_bot(_t: ty::t) -> cres<ty::t> { fn ty_bot(_t: ty::t) -> cres<ty::t> {
ok(ty::mk_bot(self.infcx.tcx)) Ok(ty::mk_bot(self.infcx.tcx))
} }
} }
@ -40,7 +40,7 @@ fn lattice_tys<L:lattice_ops combine>(
debug!("%s.lattice_tys(%s, %s)", self.tag(), debug!("%s.lattice_tys(%s, %s)", self.tag(),
a.to_str(self.infcx()), a.to_str(self.infcx()),
b.to_str(self.infcx())); b.to_str(self.infcx()));
if a == b { return ok(a); } if a == b { return Ok(a); }
do indent { do indent {
match (ty::get(a).struct, ty::get(b).struct) { match (ty::get(a).struct, ty::get(b).struct) {
(ty::ty_bot, _) => self.ty_bot(b), (ty::ty_bot, _) => self.ty_bot(b),
@ -90,7 +90,7 @@ fn lattice_vars<L:lattice_ops combine>(
b_vid.to_str(), b_bounds.to_str(self.infcx())); b_vid.to_str(), b_bounds.to_str(self.infcx()));
if a_vid == b_vid { if a_vid == b_vid {
return ok(a_t); return Ok(a_t);
} }
// If both A and B have an UB type, then we can just compute the // If both A and B have an UB type, then we can just compute the
@ -99,8 +99,8 @@ fn lattice_vars<L:lattice_ops combine>(
match (a_bnd, b_bnd) { match (a_bnd, b_bnd) {
(Some(a_ty), Some(b_ty)) => { (Some(a_ty), Some(b_ty)) => {
match self.infcx().try(|| c_ts(a_ty, b_ty) ) { match self.infcx().try(|| c_ts(a_ty, b_ty) ) {
ok(t) => return ok(t), Ok(t) => return Ok(t),
err(_) => { /*fallthrough */ } Err(_) => { /*fallthrough */ }
} }
} }
_ => {/*fallthrough*/} _ => {/*fallthrough*/}
@ -108,7 +108,7 @@ fn lattice_vars<L:lattice_ops combine>(
// Otherwise, we need to merge A and B into one variable. We can // Otherwise, we need to merge A and B into one variable. We can
// then use either variable as an upper bound: // then use either variable as an upper bound:
var_sub_var(self, a_vid, b_vid).then(|| ok(a_t) ) var_sub_var(self, a_vid, b_vid).then(|| Ok(a_t) )
} }
fn lattice_var_and_t<L:lattice_ops combine>( fn lattice_var_and_t<L:lattice_ops combine>(
@ -141,7 +141,7 @@ fn lattice_var_and_t<L:lattice_ops combine>(
let a_bounds = self.with_bnd(a_bounds, b); let a_bounds = self.with_bnd(a_bounds, b);
do bnds(self, a_bounds.lb, a_bounds.ub).then { do bnds(self, a_bounds.lb, a_bounds.ub).then {
self.infcx().set(vb, a_id, root(a_bounds, nde_a.rank)); self.infcx().set(vb, a_id, root(a_bounds, nde_a.rank));
ok(b) Ok(b)
} }
} }
} }

View file

@ -13,7 +13,7 @@ impl Lub: combine {
fn lub() -> Lub { Lub(*self) } fn lub() -> Lub { Lub(*self) }
fn glb() -> Glb { Glb(*self) } fn glb() -> Glb { Glb(*self) }
fn bot_ty(b: ty::t) -> cres<ty::t> { ok(b) } fn bot_ty(b: ty::t) -> cres<ty::t> { Ok(b) }
fn ty_bot(b: ty::t) -> cres<ty::t> { self.bot_ty(b) } // commutative fn ty_bot(b: ty::t) -> cres<ty::t> { self.bot_ty(b) } // commutative
fn mts(a: ty::mt, b: ty::mt) -> cres<ty::mt> { fn mts(a: ty::mt, b: ty::mt) -> cres<ty::mt> {
@ -32,17 +32,17 @@ impl Lub: combine {
match m { match m {
m_imm | m_const => { m_imm | m_const => {
self.tys(a.ty, b.ty).chain(|t| ok({ty: t, mutbl: m}) ) self.tys(a.ty, b.ty).chain(|t| Ok({ty: t, mutbl: m}) )
} }
m_mutbl => { m_mutbl => {
self.infcx.try(|| { self.infcx.try(|| {
eq_tys(&self, a.ty, b.ty).then(|| { eq_tys(&self, a.ty, b.ty).then(|| {
ok({ty: a.ty, mutbl: m}) Ok({ty: a.ty, mutbl: m})
}) })
}).chain_err(|_e| { }).chain_err(|_e| {
self.tys(a.ty, b.ty).chain(|t| { self.tys(a.ty, b.ty).chain(|t| {
ok({ty: t, mutbl: m_const}) Ok({ty: t, mutbl: m_const})
}) })
}) })
} }
@ -56,16 +56,16 @@ impl Lub: combine {
// XXX: Wrong. // XXX: Wrong.
fn protos(p1: ty::fn_proto, p2: ty::fn_proto) -> cres<ty::fn_proto> { fn protos(p1: ty::fn_proto, p2: ty::fn_proto) -> cres<ty::fn_proto> {
match (p1, p2) { match (p1, p2) {
(ty::proto_bare, _) => ok(p2), (ty::proto_bare, _) => Ok(p2),
(_, ty::proto_bare) => ok(p1), (_, ty::proto_bare) => Ok(p1),
(ty::proto_vstore(v1), ty::proto_vstore(v2)) => { (ty::proto_vstore(v1), ty::proto_vstore(v2)) => {
self.infcx.try(|| { self.infcx.try(|| {
do self.vstores(terr_fn, v1, v2).chain |vs| { do self.vstores(terr_fn, v1, v2).chain |vs| {
ok(ty::proto_vstore(vs)) Ok(ty::proto_vstore(vs))
} }
}).chain_err(|_err| { }).chain_err(|_err| {
// XXX: Totally unsound, but fixed up later. // XXX: Totally unsound, but fixed up later.
ok(ty::proto_vstore(ty::vstore_slice(ty::re_static))) Ok(ty::proto_vstore(ty::vstore_slice(ty::re_static)))
}) })
} }
} }
@ -73,18 +73,18 @@ impl Lub: combine {
fn purities(a: purity, b: purity) -> cres<purity> { fn purities(a: purity, b: purity) -> cres<purity> {
match (a, b) { match (a, b) {
(unsafe_fn, _) | (_, unsafe_fn) => ok(unsafe_fn), (unsafe_fn, _) | (_, unsafe_fn) => Ok(unsafe_fn),
(impure_fn, _) | (_, impure_fn) => ok(impure_fn), (impure_fn, _) | (_, impure_fn) => Ok(impure_fn),
(extern_fn, _) | (_, extern_fn) => ok(extern_fn), (extern_fn, _) | (_, extern_fn) => Ok(extern_fn),
(pure_fn, pure_fn) => ok(pure_fn) (pure_fn, pure_fn) => Ok(pure_fn)
} }
} }
fn ret_styles(r1: ret_style, r2: ret_style) -> cres<ret_style> { fn ret_styles(r1: ret_style, r2: ret_style) -> cres<ret_style> {
match (r1, r2) { match (r1, r2) {
(ast::return_val, _) | (ast::return_val, _) |
(_, ast::return_val) => ok(ast::return_val), (_, ast::return_val) => Ok(ast::return_val),
(ast::noreturn, ast::noreturn) => ok(ast::noreturn) (ast::noreturn, ast::noreturn) => Ok(ast::noreturn)
} }
} }

View file

@ -306,8 +306,8 @@ because `&x` was created alone, but is relatable to `&A`.
#[warn(deprecated_pattern)]; #[warn(deprecated_pattern)];
import dvec::{DVec, dvec}; import dvec::{DVec, dvec};
import result::result; import result::Result;
import result::{ok, err}; import result::{Ok, Err};
import std::map::{hashmap, uint_hash}; import std::map::{hashmap, uint_hash};
import std::cell::{Cell, empty_cell}; import std::cell::{Cell, empty_cell};
import std::list::{list, nil, cons}; import std::list::{list, nil, cons};
@ -478,21 +478,21 @@ impl RegionVarBindings {
match (sub, sup) { match (sub, sup) {
(ty::re_var (sub_id), ty::re_var(sup_id)) => { (ty::re_var (sub_id), ty::re_var(sup_id)) => {
self.add_constraint(ConstrainVarSubVar(sub_id, sup_id), span); self.add_constraint(ConstrainVarSubVar(sub_id, sup_id), span);
ok(()) Ok(())
} }
(r, ty::re_var(sup_id)) => { (r, ty::re_var(sup_id)) => {
self.add_constraint(ConstrainRegSubVar(r, sup_id), span); self.add_constraint(ConstrainRegSubVar(r, sup_id), span);
ok(()) Ok(())
} }
(ty::re_var(sub_id), r) => { (ty::re_var(sub_id), r) => {
self.add_constraint(ConstrainVarSubReg(sub_id, r), span); self.add_constraint(ConstrainVarSubReg(sub_id, r), span);
ok(()) Ok(())
} }
_ => { _ => {
if self.is_subregion_of(sub, sup) { if self.is_subregion_of(sub, sup) {
ok(()) Ok(())
} else { } else {
err(ty::terr_regions_does_not_outlive(sub, sup)) Err(ty::terr_regions_does_not_outlive(sub, sup))
} }
} }
} }
@ -505,7 +505,7 @@ impl RegionVarBindings {
debug!("RegionVarBindings: lub_regions(%?, %?)", a, b); debug!("RegionVarBindings: lub_regions(%?, %?)", a, b);
match (a, b) { match (a, b) {
(ty::re_static, _) | (_, ty::re_static) => { (ty::re_static, _) | (_, ty::re_static) => {
ok(ty::re_static) // nothing lives longer than static Ok(ty::re_static) // nothing lives longer than static
} }
(ty::re_var(*), _) | (_, ty::re_var(*)) => { (ty::re_var(*), _) | (_, ty::re_var(*)) => {
@ -515,7 +515,7 @@ impl RegionVarBindings {
} }
_ => { _ => {
ok(self.lub_concrete_regions(a, b)) Ok(self.lub_concrete_regions(a, b))
} }
} }
} }
@ -528,7 +528,7 @@ impl RegionVarBindings {
match (a, b) { match (a, b) {
(ty::re_static, r) | (r, ty::re_static) => { (ty::re_static, r) | (r, ty::re_static) => {
// static lives longer than everything else // static lives longer than everything else
ok(r) Ok(r)
} }
(ty::re_var(*), _) | (_, ty::re_var(*)) => { (ty::re_var(*), _) | (_, ty::re_var(*)) => {
@ -561,7 +561,7 @@ impl RegionVarBindings {
let vars = TwoRegions { a: a, b: b }; let vars = TwoRegions { a: a, b: b };
match combines.find(vars) { match combines.find(vars) {
Some(c) => ok(ty::re_var(c)), Some(c) => Ok(ty::re_var(c)),
None => { None => {
let c = self.new_region_var(span); let c = self.new_region_var(span);
combines.insert(vars, c); combines.insert(vars, c);
@ -571,7 +571,7 @@ impl RegionVarBindings {
do relate(a, ty::re_var(c)).then { do relate(a, ty::re_var(c)).then {
do relate(b, ty::re_var(c)).then { do relate(b, ty::re_var(c)).then {
debug!("combine_vars() c=%?", ty::re_var(c)); debug!("combine_vars() c=%?", ty::re_var(c));
ok(ty::re_var(c)) Ok(ty::re_var(c))
} }
} }
} }
@ -655,7 +655,7 @@ priv impl RegionVarBindings {
match (a, b) { match (a, b) {
(ty::re_static, r) | (r, ty::re_static) => { (ty::re_static, r) | (r, ty::re_static) => {
// static lives longer than everything else // static lives longer than everything else
ok(r) Ok(r)
} }
(ty::re_var(v_id), _) | (_, ty::re_var(v_id)) => { (ty::re_var(v_id), _) | (_, ty::re_var(v_id)) => {
@ -674,8 +674,8 @@ priv impl RegionVarBindings {
// big the free region is precisely, the GLB is undefined. // big the free region is precisely, the GLB is undefined.
let rm = self.tcx.region_map; let rm = self.tcx.region_map;
match region::nearest_common_ancestor(rm, f_id, s_id) { match region::nearest_common_ancestor(rm, f_id, s_id) {
Some(r_id) if r_id == f_id => ok(s), Some(r_id) if r_id == f_id => Ok(s),
_ => err(ty::terr_regions_no_overlap(b, a)) _ => Err(ty::terr_regions_no_overlap(b, a))
} }
} }
@ -683,7 +683,7 @@ priv impl RegionVarBindings {
(ty::re_free(a_id, _), ty::re_free(b_id, _)) => { (ty::re_free(a_id, _), ty::re_free(b_id, _)) => {
if a == b { if a == b {
// Same scope or same free identifier, easy case. // Same scope or same free identifier, easy case.
ok(a) Ok(a)
} else { } else {
// We want to generate the intersection of two // We want to generate the intersection of two
// scopes or two free regions. So, if one of // scopes or two free regions. So, if one of
@ -691,9 +691,9 @@ priv impl RegionVarBindings {
// it. Otherwise fail. // it. Otherwise fail.
let rm = self.tcx.region_map; let rm = self.tcx.region_map;
match region::nearest_common_ancestor(rm, a_id, b_id) { match region::nearest_common_ancestor(rm, a_id, b_id) {
Some(r_id) if a_id == r_id => ok(ty::re_scope(b_id)), Some(r_id) if a_id == r_id => Ok(ty::re_scope(b_id)),
Some(r_id) if b_id == r_id => ok(ty::re_scope(a_id)), Some(r_id) if b_id == r_id => Ok(ty::re_scope(a_id)),
_ => err(ty::terr_regions_no_overlap(b, a)) _ => Err(ty::terr_regions_no_overlap(b, a))
} }
} }
} }
@ -706,9 +706,9 @@ priv impl RegionVarBindings {
(ty::re_free(_, _), ty::re_bound(_)) | (ty::re_free(_, _), ty::re_bound(_)) |
(ty::re_scope(_), ty::re_bound(_)) => { (ty::re_scope(_), ty::re_bound(_)) => {
if a == b { if a == b {
ok(a) Ok(a)
} else { } else {
err(ty::terr_regions_no_overlap(b, a)) Err(ty::terr_regions_no_overlap(b, a))
} }
} }
} }
@ -961,7 +961,7 @@ impl RegionVarBindings {
a_region: region, a_region: region,
b_region: region) -> bool { b_region: region) -> bool {
match self.glb_concrete_regions(a_region, b_region) { match self.glb_concrete_regions(a_region, b_region) {
ok(glb) => { Ok(glb) => {
if glb == a_region { if glb == a_region {
false false
} else { } else {
@ -971,7 +971,7 @@ impl RegionVarBindings {
true true
} }
} }
err(_) => { Err(_) => {
a_node.value = ErrorValue; a_node.value = ErrorValue;
false false
} }
@ -1101,8 +1101,8 @@ impl RegionVarBindings {
for vec::each(upper_bounds) |upper_bound_2| { for vec::each(upper_bounds) |upper_bound_2| {
match self.glb_concrete_regions(upper_bound_1.region, match self.glb_concrete_regions(upper_bound_1.region,
upper_bound_2.region) { upper_bound_2.region) {
ok(_) => {} Ok(_) => {}
err(_) => { Err(_) => {
if self.is_reported(dup_map, if self.is_reported(dup_map,
upper_bound_1.region, upper_bound_1.region,

View file

@ -92,9 +92,9 @@ impl resolve_state {
debug!("Resolved to %s (modes=%x)", debug!("Resolved to %s (modes=%x)",
ty_to_str(self.infcx.tcx, rty), ty_to_str(self.infcx.tcx, rty),
self.modes); self.modes);
return ok(rty); return Ok(rty);
} }
Some(e) => return err(e) Some(e) => return Err(e)
} }
} }
@ -102,8 +102,8 @@ impl resolve_state {
self.err = None; self.err = None;
let resolved = indent(|| self.resolve_region(orig) ); let resolved = indent(|| self.resolve_region(orig) );
match self.err { match self.err {
None => ok(resolved), None => Ok(resolved),
Some(e) => err(e) Some(e) => Err(e)
} }
} }

View file

@ -34,8 +34,8 @@ impl Sub: combine {
b.to_str(self.infcx)); b.to_str(self.infcx));
do indent { do indent {
match self.infcx.region_vars.make_subregion(self.span, a, b) { match self.infcx.region_vars.make_subregion(self.span, a, b) {
ok(()) => ok(a), Ok(()) => Ok(a),
err(e) => err(e) Err(e) => Err(e)
} }
} }
} }
@ -44,18 +44,18 @@ impl Sub: combine {
debug!("mts(%s <: %s)", a.to_str(self.infcx), b.to_str(self.infcx)); debug!("mts(%s <: %s)", a.to_str(self.infcx), b.to_str(self.infcx));
if a.mutbl != b.mutbl && b.mutbl != m_const { if a.mutbl != b.mutbl && b.mutbl != m_const {
return err(ty::terr_mutability); return Err(ty::terr_mutability);
} }
match b.mutbl { match b.mutbl {
m_mutbl => { m_mutbl => {
// If supertype is mut, subtype must match exactly // If supertype is mut, subtype must match exactly
// (i.e., invariant if mut): // (i.e., invariant if mut):
eq_tys(&self, a.ty, b.ty).then(|| ok(a) ) eq_tys(&self, a.ty, b.ty).then(|| Ok(a) )
} }
m_imm | m_const => { m_imm | m_const => {
// 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).chain(|_t| Ok(a) )
} }
} }
} }
@ -63,22 +63,22 @@ impl Sub: combine {
fn protos(a: ty::fn_proto, b: ty::fn_proto) -> cres<ty::fn_proto> { fn protos(a: ty::fn_proto, b: ty::fn_proto) -> cres<ty::fn_proto> {
match (a, b) { match (a, b) {
(ty::proto_bare, _) => (ty::proto_bare, _) =>
ok(ty::proto_bare), Ok(ty::proto_bare),
(ty::proto_vstore(ty::vstore_box), (ty::proto_vstore(ty::vstore_box),
ty::proto_vstore(ty::vstore_slice(_))) => ty::proto_vstore(ty::vstore_slice(_))) =>
ok(ty::proto_vstore(ty::vstore_box)), Ok(ty::proto_vstore(ty::vstore_box)),
(ty::proto_vstore(ty::vstore_uniq), (ty::proto_vstore(ty::vstore_uniq),
ty::proto_vstore(ty::vstore_slice(_))) => ty::proto_vstore(ty::vstore_slice(_))) =>
ok(ty::proto_vstore(ty::vstore_uniq)), Ok(ty::proto_vstore(ty::vstore_uniq)),
(_, ty::proto_bare) => (_, ty::proto_bare) =>
err(ty::terr_proto_mismatch(expected_found(&self, a, b))), Err(ty::terr_proto_mismatch(expected_found(&self, a, b))),
(ty::proto_vstore(vs_a), ty::proto_vstore(vs_b)) => { (ty::proto_vstore(vs_a), ty::proto_vstore(vs_b)) => {
do self.vstores(ty::terr_fn, vs_a, vs_b).chain |vs_c| { do self.vstores(ty::terr_fn, vs_a, vs_b).chain |vs_c| {
ok(ty::proto_vstore(vs_c)) Ok(ty::proto_vstore(vs_c))
} }
} }
} }
@ -99,23 +99,23 @@ impl Sub: combine {
fn tys(a: ty::t, b: ty::t) -> cres<ty::t> { fn tys(a: ty::t, b: ty::t) -> cres<ty::t> {
debug!("%s.tys(%s, %s)", self.tag(), debug!("%s.tys(%s, %s)", self.tag(),
a.to_str(self.infcx), b.to_str(self.infcx)); a.to_str(self.infcx), b.to_str(self.infcx));
if a == b { return ok(a); } if a == b { return Ok(a); }
do indent { do indent {
match (ty::get(a).struct, ty::get(b).struct) { match (ty::get(a).struct, ty::get(b).struct) {
(ty::ty_bot, _) => { (ty::ty_bot, _) => {
ok(a) Ok(a)
} }
(ty::ty_var(a_id), ty::ty_var(b_id)) => { (ty::ty_var(a_id), ty::ty_var(b_id)) => {
var_sub_var(&self, a_id, b_id).then(|| ok(a) ) var_sub_var(&self, a_id, b_id).then(|| Ok(a) )
} }
(ty::ty_var(a_id), _) => { (ty::ty_var(a_id), _) => {
var_sub_t(&self, a_id, b).then(|| ok(a) ) var_sub_t(&self, a_id, b).then(|| Ok(a) )
} }
(_, ty::ty_var(b_id)) => { (_, ty::ty_var(b_id)) => {
t_sub_var(&self, a, b_id).then(|| ok(a) ) t_sub_var(&self, a, b_id).then(|| Ok(a) )
} }
(_, ty::ty_bot) => { (_, ty::ty_bot) => {
err(ty::terr_sorts(expected_found(&self, a, b))) Err(ty::terr_sorts(expected_found(&self, a, b)))
} }
_ => { _ => {
super_tys(&self, a, b) super_tys(&self, a, b)

View file

@ -69,12 +69,12 @@ fn merge_bnd<C: combine>(
let _r = indenter(); let _r = indenter();
match (a, b) { match (a, b) {
(None, None) => ok(None), (None, None) => Ok(None),
(Some(_), None) => ok(a), (Some(_), None) => Ok(a),
(None, Some(_)) => ok(b), (None, Some(_)) => Ok(b),
(Some(v_a), Some(v_b)) => { (Some(v_a), Some(v_b)) => {
do merge_op(v_a, v_b).chain |v| { do merge_op(v_a, v_b).chain |v| {
ok(Some(v)) Ok(Some(v))
} }
} }
} }
@ -96,7 +96,7 @@ fn merge_bnds<C: combine>(
a.lb.to_str(self.infcx()), a.lb.to_str(self.infcx()),
b.lb.to_str(self.infcx()), b.lb.to_str(self.infcx()),
lb.to_str(self.infcx())); lb.to_str(self.infcx()));
ok({lb: lb, ub: ub}) Ok({lb: lb, ub: ub})
} }
} }
} }
@ -198,8 +198,8 @@ fn var_sub_var<C: combine>(self: &C,
(Some(a_ub), Some(b_lb)) => { (Some(a_ub), Some(b_lb)) => {
let r = self.infcx().try(|| self.sub().tys(a_ub, b_lb)); let r = self.infcx().try(|| self.sub().tys(a_ub, b_lb));
match r { match r {
ok(_ty) => return result::ok(()), Ok(_ty) => return result::Ok(()),
err(_) => { /*fallthrough */ } Err(_) => { /*fallthrough */ }
} }
} }
_ => { /*fallthrough*/ } _ => { /*fallthrough*/ }
@ -311,7 +311,7 @@ impl infer_ctxt {
// possible types. // possible types.
let intersection = intersection(a_pt, b_pt); let intersection = intersection(a_pt, b_pt);
if *intersection == INT_TY_SET_EMPTY { if *intersection == INT_TY_SET_EMPTY {
return err(ty::terr_no_integral_type); return Err(ty::terr_no_integral_type);
} }
// Rank optimization // Rank optimization
@ -351,7 +351,7 @@ impl infer_ctxt {
intersection(a_pt, intersection(a_pt,
convert_integral_ty_to_int_ty_set(self.tcx, b)); convert_integral_ty_to_int_ty_set(self.tcx, b));
if *intersection == INT_TY_SET_EMPTY { if *intersection == INT_TY_SET_EMPTY {
return err(ty::terr_no_integral_type); return Err(ty::terr_no_integral_type);
} }
self.set(vb, a_id, root(intersection, nde_a.rank)); self.set(vb, a_id, root(intersection, nde_a.rank));
uok() uok()
@ -369,7 +369,7 @@ impl infer_ctxt {
intersection(b_pt, intersection(b_pt,
convert_integral_ty_to_int_ty_set(self.tcx, a)); convert_integral_ty_to_int_ty_set(self.tcx, a));
if *intersection == INT_TY_SET_EMPTY { if *intersection == INT_TY_SET_EMPTY {
return err(ty::terr_no_integral_type); return Err(ty::terr_no_integral_type);
} }
self.set(vb, b_id, root(intersection, nde_b.rank)); self.set(vb, b_id, root(intersection, nde_b.rank));
uok() uok()

View file

@ -1,37 +1,37 @@
import result::result; import result::Result;
import syntax::parse::token::special_idents; import syntax::parse::token::special_idents;
trait region_scope { trait region_scope {
fn anon_region(span: span) -> result<ty::region, ~str>; fn anon_region(span: span) -> Result<ty::region, ~str>;
fn named_region(span: span, id: ast::ident) -> result<ty::region, ~str>; fn named_region(span: span, id: ast::ident) -> Result<ty::region, ~str>;
} }
enum empty_rscope { empty_rscope } enum empty_rscope { empty_rscope }
impl empty_rscope: region_scope { impl empty_rscope: region_scope {
fn anon_region(_span: span) -> result<ty::region, ~str> { fn anon_region(_span: span) -> Result<ty::region, ~str> {
result::ok(ty::re_static) result::Ok(ty::re_static)
} }
fn named_region(_span: span, id: ast::ident) -> result<ty::region, ~str> { fn named_region(_span: span, id: ast::ident) -> Result<ty::region, ~str> {
if id == special_idents::static { result::ok(ty::re_static) } if id == special_idents::static { result::Ok(ty::re_static) }
else { result::err(~"only the static region is allowed here") } else { result::Err(~"only the static region is allowed here") }
} }
} }
enum type_rscope = Option<ty::region_variance>; enum type_rscope = Option<ty::region_variance>;
impl type_rscope: region_scope { impl type_rscope: region_scope {
fn anon_region(_span: span) -> result<ty::region, ~str> { fn anon_region(_span: span) -> Result<ty::region, ~str> {
match *self { match *self {
Some(_) => result::ok(ty::re_bound(ty::br_self)), Some(_) => result::Ok(ty::re_bound(ty::br_self)),
None => result::err(~"to use region types here, the containing \ None => result::Err(~"to use region types here, the containing \
type must be declared with a region bound") type must be declared with a region bound")
} }
} }
fn named_region(span: span, id: ast::ident) -> result<ty::region, ~str> { fn named_region(span: span, id: ast::ident) -> Result<ty::region, ~str> {
do empty_rscope.named_region(span, id).chain_err |_e| { do empty_rscope.named_region(span, id).chain_err |_e| {
if id == special_idents::self_ { if id == special_idents::self_ {
self.anon_region(span) self.anon_region(span)
} else { } else {
result::err(~"named regions other than `self` are not \ result::Err(~"named regions other than `self` are not \
allowed as part of a type declaration") allowed as part of a type declaration")
} }
} }
@ -51,10 +51,10 @@ fn in_anon_rscope<RS: region_scope copy owned>(self: RS, r: ty::region)
@anon_rscope({anon: r, base: self as region_scope}) @anon_rscope({anon: r, base: self as region_scope})
} }
impl @anon_rscope: region_scope { impl @anon_rscope: region_scope {
fn anon_region(_span: span) -> result<ty::region, ~str> { fn anon_region(_span: span) -> Result<ty::region, ~str> {
result::ok(self.anon) result::Ok(self.anon)
} }
fn named_region(span: span, id: ast::ident) -> result<ty::region, ~str> { fn named_region(span: span, id: ast::ident) -> Result<ty::region, ~str> {
self.base.named_region(span, id) self.base.named_region(span, id)
} }
} }
@ -69,14 +69,14 @@ fn in_binding_rscope<RS: region_scope copy owned>(self: RS)
@binding_rscope { base: base, anon_bindings: 0 } @binding_rscope { base: base, anon_bindings: 0 }
} }
impl @binding_rscope: region_scope { impl @binding_rscope: region_scope {
fn anon_region(_span: span) -> result<ty::region, ~str> { fn anon_region(_span: span) -> Result<ty::region, ~str> {
let idx = self.anon_bindings; let idx = self.anon_bindings;
self.anon_bindings += 1; self.anon_bindings += 1;
result::ok(ty::re_bound(ty::br_anon(idx))) result::Ok(ty::re_bound(ty::br_anon(idx)))
} }
fn named_region(span: span, id: ast::ident) -> result<ty::region, ~str> { fn named_region(span: span, id: ast::ident) -> Result<ty::region, ~str> {
do self.base.named_region(span, id).chain_err |_e| { do self.base.named_region(span, id).chain_err |_e| {
result::ok(ty::re_bound(ty::br_named(id))) result::Ok(ty::re_bound(ty::br_named(id)))
} }
} }
} }

View file

@ -1,4 +1,4 @@
import result::result; import result::Result;
import std::getopts; import std::getopts;
export output_format; export output_format;
@ -90,29 +90,29 @@ fn mock_program_output(_prog: &str, _args: &[~str]) -> {
} }
} }
fn parse_config(args: ~[~str]) -> result<config, ~str> { fn parse_config(args: ~[~str]) -> Result<config, ~str> {
parse_config_(args, run::program_output) parse_config_(args, run::program_output)
} }
fn parse_config_( fn parse_config_(
args: ~[~str], args: ~[~str],
program_output: program_output program_output: program_output
) -> result<config, ~str> { ) -> Result<config, ~str> {
let args = vec::tail(args); let args = vec::tail(args);
let opts = vec::unzip(opts()).first(); let opts = vec::unzip(opts()).first();
match getopts::getopts(args, opts) { match getopts::getopts(args, opts) {
result::ok(matches) => { result::Ok(matches) => {
if vec::len(matches.free) == 1u { if vec::len(matches.free) == 1u {
let input_crate = Path(vec::head(matches.free)); let input_crate = Path(vec::head(matches.free));
config_from_opts(&input_crate, matches, program_output) config_from_opts(&input_crate, matches, program_output)
} else if vec::is_empty(matches.free) { } else if vec::is_empty(matches.free) {
result::err(~"no crates specified") result::Err(~"no crates specified")
} else { } else {
result::err(~"multiple crates specified") result::Err(~"multiple crates specified")
} }
} }
result::err(f) => { result::Err(f) => {
result::err(getopts::fail_str(f)) result::Err(getopts::fail_str(f))
} }
} }
} }
@ -121,14 +121,14 @@ fn config_from_opts(
input_crate: &Path, input_crate: &Path,
matches: getopts::matches, matches: getopts::matches,
program_output: program_output program_output: program_output
) -> result<config, ~str> { ) -> Result<config, ~str> {
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(result) |config| { let result = do result::chain(result) |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 = option::map(output_dir, |s| Path(s)); let output_dir = option::map(output_dir, |s| Path(s));
result::ok({ result::Ok({
output_dir: option::get_default(output_dir, config.output_dir) output_dir: option::get_default(output_dir, config.output_dir)
with config with config
}) })
@ -136,12 +136,12 @@ fn config_from_opts(
let result = do result::chain(result) |config| { let result = do result::chain(result) |config| {
let output_format = getopts::opt_maybe_str( let output_format = getopts::opt_maybe_str(
matches, opt_output_format()); matches, opt_output_format());
do option::map_default(output_format, result::ok(config)) do option::map_default(output_format, result::Ok(config))
|output_format| { |output_format| {
do result::chain(parse_output_format(output_format)) do result::chain(parse_output_format(output_format))
|output_format| { |output_format| {
result::ok({ result::Ok({
output_format: output_format output_format: output_format
with config with config
}) })
@ -151,11 +151,11 @@ fn config_from_opts(
let result = do result::chain(result) |config| { let result = do result::chain(result) |config| {
let output_style = let output_style =
getopts::opt_maybe_str(matches, opt_output_style()); getopts::opt_maybe_str(matches, opt_output_style());
do option::map_default(output_style, result::ok(config)) do option::map_default(output_style, result::Ok(config))
|output_style| { |output_style| {
do result::chain(parse_output_style(output_style)) do result::chain(parse_output_style(output_style))
|output_style| { |output_style| {
result::ok({ result::Ok({
output_style: output_style output_style: output_style
with config with config
}) })
@ -167,7 +167,7 @@ fn config_from_opts(
let pandoc_cmd = maybe_find_pandoc( let pandoc_cmd = maybe_find_pandoc(
config, pandoc_cmd, program_output); config, pandoc_cmd, program_output);
do result::chain(pandoc_cmd) |pandoc_cmd| { do result::chain(pandoc_cmd) |pandoc_cmd| {
result::ok({ result::Ok({
pandoc_cmd: pandoc_cmd pandoc_cmd: pandoc_cmd
with config with config
}) })
@ -176,19 +176,19 @@ fn config_from_opts(
return result; return result;
} }
fn parse_output_format(output_format: ~str) -> result<output_format, ~str> { fn parse_output_format(output_format: ~str) -> Result<output_format, ~str> {
match output_format { match output_format {
~"markdown" => result::ok(markdown), ~"markdown" => result::Ok(markdown),
~"html" => result::ok(pandoc_html), ~"html" => result::Ok(pandoc_html),
_ => result::err(fmt!("unknown output format '%s'", output_format)) _ => result::Err(fmt!("unknown output format '%s'", output_format))
} }
} }
fn parse_output_style(output_style: ~str) -> result<output_style, ~str> { fn parse_output_style(output_style: ~str) -> Result<output_style, ~str> {
match output_style { match output_style {
~"doc-per-crate" => result::ok(doc_per_crate), ~"doc-per-crate" => result::Ok(doc_per_crate),
~"doc-per-mod" => result::ok(doc_per_mod), ~"doc-per-mod" => result::Ok(doc_per_mod),
_ => result::err(fmt!("unknown output style '%s'", output_style)) _ => result::Err(fmt!("unknown output style '%s'", output_style))
} }
} }
@ -196,9 +196,9 @@ fn maybe_find_pandoc(
config: config, config: config,
maybe_pandoc_cmd: Option<~str>, maybe_pandoc_cmd: Option<~str>,
program_output: program_output program_output: program_output
) -> result<Option<~str>, ~str> { ) -> Result<Option<~str>, ~str> {
if config.output_format != pandoc_html { if config.output_format != pandoc_html {
return result::ok(maybe_pandoc_cmd); return result::Ok(maybe_pandoc_cmd);
} }
let possible_pandocs = match maybe_pandoc_cmd { let possible_pandocs = match maybe_pandoc_cmd {
@ -220,9 +220,9 @@ fn maybe_find_pandoc(
}; };
if option::is_some(pandoc) { if option::is_some(pandoc) {
result::ok(pandoc) result::Ok(pandoc)
} else { } else {
result::err(~"couldn't find pandoc") result::Err(~"couldn't find pandoc")
} }
} }
@ -240,7 +240,7 @@ fn should_find_pandoc() {
} }
}; };
let result = maybe_find_pandoc(config, None, mock_program_output); let result = maybe_find_pandoc(config, None, mock_program_output);
assert result == result::ok(Some(~"pandoc")); assert result == result::Ok(Some(~"pandoc"));
} }
#[test] #[test]
@ -257,12 +257,12 @@ fn should_error_with_no_pandoc() {
} }
}; };
let result = maybe_find_pandoc(config, None, mock_program_output); let result = maybe_find_pandoc(config, None, mock_program_output);
assert result == result::err(~"couldn't find pandoc"); assert result == result::Err(~"couldn't find pandoc");
} }
#[cfg(test)] #[cfg(test)]
mod test { mod test {
fn parse_config(args: ~[~str]) -> result<config, ~str> { fn parse_config(args: ~[~str]) -> Result<config, ~str> {
parse_config_(args, mock_program_output) parse_config_(args, mock_program_output)
} }
} }

View file

@ -258,10 +258,10 @@ fn write_file(path: &Path, s: ~str) {
import io::WriterUtil; import io::WriterUtil;
match io::file_writer(path, ~[io::Create, io::Truncate]) { match io::file_writer(path, ~[io::Create, io::Truncate]) {
result::ok(writer) => { result::Ok(writer) => {
writer.write_str(s); writer.write_str(s);
} }
result::err(e) => fail e result::Err(e) => fail e
} }
} }

View file

@ -108,8 +108,8 @@ fn main(args: ~[~str]) {
} }
let config = match config::parse_config(args) { let config = match config::parse_config(args) {
result::ok(config) => config, result::Ok(config) => config,
result::err(err) => { result::Err(err) => {
io::println(fmt!("error: %s", err)); io::println(fmt!("error: %s", err));
return; return;
} }

View file

@ -21,7 +21,7 @@ import pipes::send;
import pipes::recv; import pipes::recv;
import core::result; import core::result;
import result::{ok, err}; import result::{Ok, Err};
fn fib(n: int) -> int { fn fib(n: int) -> int {
fn pfib(c: chan<int>, n: int) { fn pfib(c: chan<int>, n: int) {
@ -52,8 +52,8 @@ fn parse_opts(argv: ~[~str]) -> config {
let opt_args = vec::slice(argv, 1u, vec::len(argv)); let opt_args = vec::slice(argv, 1u, vec::len(argv));
match getopts::getopts(opt_args, opts) { match getopts::getopts(opt_args, opts) {
ok(m) => { return {stress: getopts::opt_present(m, ~"stress")} } Ok(m) => { return {stress: getopts::opt_present(m, ~"stress")} }
err(_) => { fail; } Err(_) => { fail; }
} }
} }

View file

@ -51,7 +51,7 @@ fn main(args: ~[~str]) {
// Main group #0 waits for unsupervised group #1. // Main group #0 waits for unsupervised group #1.
// Grandparent group #1 waits for middle group #2, then fails, killing #3. // Grandparent group #1 waits for middle group #2, then fails, killing #3.
// Middle group #2 creates grandchild_group #3, waits for it to be ready, exits. // Middle group #2 creates grandchild_group #3, waits for it to be ready, exits.
let x: result::result<(),()> = do task::try { // unlinked let x: result::Result<(),()> = do task::try { // unlinked
do spawn_supervised_blocking("grandparent") { do spawn_supervised_blocking("grandparent") {
do spawn_supervised_blocking("middle") { do spawn_supervised_blocking("middle") {
grandchild_group(num_tasks); grandchild_group(num_tasks);

View file

@ -81,8 +81,8 @@ impl io::Reader: word_reader {
fn file_word_reader(filename: ~str) -> word_reader { fn file_word_reader(filename: ~str) -> word_reader {
match io::file_reader(&Path(filename)) { match io::file_reader(&Path(filename)) {
result::ok(f) => { f as word_reader } result::Ok(f) => { f as word_reader }
result::err(e) => { fail fmt!("%?", e) } result::Err(e) => { fail fmt!("%?", e) }
} }
} }

View file

@ -1,4 +1,4 @@
// error-pattern:get called on error result: ~"kitty" // error-pattern:get called on error result: ~"kitty"
fn main() { fn main() {
log(error, result::get(result::err::<int,~str>(~"kitty"))); log(error, result::get(result::Err::<int,~str>(~"kitty")));
} }