Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

don't use Result::ok just to be able to use unwrap/unwrap_or #23512

Merged
merged 1 commit into from
Mar 21, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/libcore/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
//! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
//!
//! // Consume the result and return the contents with `unwrap`.
//! let final_awesome_result = good_result.ok().unwrap();
//! let final_awesome_result = good_result.unwrap();
//! ```
//!
//! # Results must be used
Expand Down Expand Up @@ -460,7 +460,7 @@ impl<T, E> Result<T, E> {
/// line.trim_right().parse::<int>().unwrap_or(0)
/// });
/// // Add the value if there were no errors, otherwise add 0
/// sum += val.ok().unwrap_or(0);
/// sum += val.unwrap_or(0);
/// }
///
/// assert!(sum == 10);
Expand Down
20 changes: 13 additions & 7 deletions src/librustc/middle/astencode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ use std::io::SeekFrom;
use std::io::prelude::*;
use std::num::FromPrimitive;
use std::rc::Rc;
use std::fmt::Debug;

use rbml::reader;
use rbml::writer::Encoder;
Expand Down Expand Up @@ -298,9 +299,11 @@ trait def_id_encoder_helpers {
fn emit_def_id(&mut self, did: ast::DefId);
}

impl<S:serialize::Encoder> def_id_encoder_helpers for S {
impl<S:serialize::Encoder> def_id_encoder_helpers for S
where <S as serialize::serialize::Encoder>::Error: Debug
{
fn emit_def_id(&mut self, did: ast::DefId) {
did.encode(self).ok().unwrap()
did.encode(self).unwrap()
}
}

Expand All @@ -310,15 +313,18 @@ trait def_id_decoder_helpers {
cdata: &cstore::crate_metadata) -> ast::DefId;
}

impl<D:serialize::Decoder> def_id_decoder_helpers for D {
impl<D:serialize::Decoder> def_id_decoder_helpers for D
where <D as serialize::serialize::Decoder>::Error: Debug
{
fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId {
let did: ast::DefId = Decodable::decode(self).ok().unwrap();
let did: ast::DefId = Decodable::decode(self).unwrap();
did.tr(dcx)
}

fn read_def_id_nodcx(&mut self,
cdata: &cstore::crate_metadata) -> ast::DefId {
let did: ast::DefId = Decodable::decode(self).ok().unwrap();
cdata: &cstore::crate_metadata)
-> ast::DefId {
let did: ast::DefId = Decodable::decode(self).unwrap();
decoder::translate_def_id(cdata, did)
}
}
Expand Down Expand Up @@ -1769,7 +1775,7 @@ impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
-> ty::ClosureKind
{
Decodable::decode(self).ok().unwrap()
Decodable::decode(self).unwrap()
}

fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/middle/cfg/graphviz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ fn replace_newline_with_backslash_l(s: String) -> String {
}

impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> {
fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(&self.name[..]).ok().unwrap() }
fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(&self.name[..]).unwrap() }

fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> {
dot::Id::new(format!("N{}", i.node_id())).ok().unwrap()
dot::Id::new(format!("N{}", i.node_id())).unwrap()
}

fn node_label(&'a self, &(i, n): &Node<'a>) -> dot::LabelText<'a> {
Expand Down
10 changes: 5 additions & 5 deletions src/librustc/middle/infer/region_inference/graphviz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a,
return;
}

let requested_output = env::var("RUST_REGION_GRAPH").ok();
let requested_output = env::var("RUST_REGION_GRAPH");
debug!("requested_output: {:?} requested_node: {:?}",
requested_output, requested_node);

let output_path = {
let output_template = match requested_output {
Some(ref s) if &**s == "help" => {
Ok(ref s) if &**s == "help" => {
static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT;
if !PRINTED_YET.load(Ordering::SeqCst) {
print_help_message();
Expand All @@ -84,8 +84,8 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a,
return;
}

Some(other_path) => other_path,
None => "/tmp/constraints.node%.dot".to_string(),
Ok(other_path) => other_path,
Err(_) => "/tmp/constraints.node%.dot".to_string(),
};

if output_template.len() == 0 {
Expand Down Expand Up @@ -171,7 +171,7 @@ impl<'a, 'tcx> ConstraintGraph<'a, 'tcx> {

impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> {
fn graph_id(&self) -> dot::Id {
dot::Id::new(&*self.graph_name).ok().unwrap()
dot::Id::new(&*self.graph_name).unwrap()
}
fn node_id(&self, n: &Node) -> dot::Id {
let node_id = match self.node_ids.get(n) {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_borrowck/borrowck/gather_loans/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for StaticInitializerCtxt<'a, 'tcx> {
if let ast::ExprAddrOf(mutbl, ref base) = ex.node {
let param_env = ty::empty_parameter_environment(self.bccx.tcx);
let mc = mc::MemCategorizationContext::new(&param_env);
let base_cmt = mc.cat_expr(&**base).ok().unwrap();
let base_cmt = mc.cat_expr(&**base).unwrap();
let borrow_kind = ty::BorrowKind::from_mutbl(mutbl);
// Check that we don't allow borrows of unsafe static items.
if check_aliasability(self.bccx, ex.span, euv::AddrOf,
Expand Down
2 changes: 1 addition & 1 deletion src/libstd/fs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1532,7 +1532,7 @@ mod tests {
#[test]
fn binary_file() {
let mut bytes = [0; 1024];
StdRng::new().ok().unwrap().fill_bytes(&mut bytes);
StdRng::new().unwrap().fill_bytes(&mut bytes);

let tmpdir = tmpdir();

Expand Down
2 changes: 1 addition & 1 deletion src/libstd/io/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ mod tests {
fn read_to_end() {
let mut reader = Cursor::new(vec!(0, 1, 2, 3, 4, 5, 6, 7));
let mut v = Vec::new();
reader.read_to_end(&mut v).ok().unwrap();
reader.read_to_end(&mut v).unwrap();
assert_eq!(v, [0, 1, 2, 3, 4, 5, 6, 7]);
}

Expand Down
2 changes: 1 addition & 1 deletion src/libstd/net/addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -617,7 +617,7 @@ mod tests {
unique_local: bool, global: bool,
u_link_local: bool, u_site_local: bool, u_global: bool,
m_scope: Option<Ipv6MulticastScope>) {
let ip: Ipv6Addr = str_addr.parse().ok().unwrap();
let ip: Ipv6Addr = str_addr.parse().unwrap();
assert_eq!(str_addr, ip.to_string());

assert_eq!(ip.is_unspecified(), unspec);
Expand Down
2 changes: 1 addition & 1 deletion src/libstd/old_io/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1608,7 +1608,7 @@ mod test {
use rand::{StdRng, Rng};

let mut bytes = [0; 1024];
StdRng::new().ok().unwrap().fill_bytes(&mut bytes);
StdRng::new().unwrap().fill_bytes(&mut bytes);

let tmpdir = tmpdir();

Expand Down
2 changes: 1 addition & 1 deletion src/libstd/sync/mpsc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ impl<T: Send> Sender<T> {
// asleep (we're looking at it), so the receiver
// can't go away.
(*a.get()).send(t).ok().unwrap();
token.signal();
token.signal();
(a, Ok(()))
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/libstd/sys/unix/backtrace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ fn output(w: &mut Write, idx: int, addr: *mut libc::c_void,
#[allow(dead_code)]
fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
more: bool) -> io::Result<()> {
let file = str::from_utf8(file).ok().unwrap_or("<unknown>");
let file = str::from_utf8(file).unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more {
Expand Down
2 changes: 1 addition & 1 deletion src/libstd/sys/unix/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ mod tests {
let mut reader = FileDesc::new(reader, true);
let mut writer = FileDesc::new(writer, true);

writer.write(b"test").ok().unwrap();
writer.write(b"test").unwrap();
let mut buf = [0; 4];
match reader.read(&mut buf) {
Ok(4) => {
Expand Down
2 changes: 1 addition & 1 deletion src/libstd/sys/unix/helper_signal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub fn new() -> (signal, signal) {
}

pub fn signal(fd: libc::c_int) {
FileDesc::new(fd, false).write(&[0]).ok().unwrap();
FileDesc::new(fd, false).write(&[0]).unwrap();
}

pub fn close(fd: libc::c_int) {
Expand Down
2 changes: 1 addition & 1 deletion src/libstd/sys/unix/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>, _: ()) {

// drain the file descriptor
let mut buf = [0];
assert_eq!(fd.read(&mut buf).ok().unwrap(), 1);
assert_eq!(fd.read(&mut buf).unwrap(), 1);
}

-1 if os::errno() == libc::EINTR as i32 => {}
Expand Down
4 changes: 2 additions & 2 deletions src/libstd/sys/windows/pipe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -757,10 +757,10 @@ impl UnixAcceptor {

impl Clone for UnixAcceptor {
fn clone(&self) -> UnixAcceptor {
let name = to_utf16(&self.listener.name).ok().unwrap();
let name = to_utf16(&self.listener.name).unwrap();
UnixAcceptor {
inner: self.inner.clone(),
event: Event::new(true, false).ok().unwrap(),
event: Event::new(true, false).unwrap(),
deadline: 0,
listener: UnixListener {
name: self.listener.name.clone(),
Expand Down
8 changes: 4 additions & 4 deletions src/libstd/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -869,7 +869,7 @@ mod test {
Err(e) => {
type T = &'static str;
assert!(e.is::<T>());
assert_eq!(*e.downcast::<T>().ok().unwrap(), "static string");
assert_eq!(*e.downcast::<T>().unwrap(), "static string");
}
Ok(()) => panic!()
}
Expand All @@ -883,7 +883,7 @@ mod test {
Err(e) => {
type T = String;
assert!(e.is::<T>());
assert_eq!(*e.downcast::<T>().ok().unwrap(), "owned string".to_string());
assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
}
Ok(()) => panic!()
}
Expand All @@ -897,9 +897,9 @@ mod test {
Err(e) => {
type T = Box<Any + Send>;
assert!(e.is::<T>());
let any = e.downcast::<T>().ok().unwrap();
let any = e.downcast::<T>().unwrap();
assert!(any.is::<u16>());
assert_eq!(*any.downcast::<u16>().ok().unwrap(), 413);
assert_eq!(*any.downcast::<u16>().unwrap(), 413);
}
Ok(()) => panic!()
}
Expand Down
6 changes: 3 additions & 3 deletions src/libsyntax/ext/deriving/encodable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
//! fn encode(&self, s: &mut S) -> Result<(), E> {
//! s.emit_struct("Spanned", 2, |this| {
//! this.emit_struct_field("node", 0, |this| self.node.encode(this))
//! .ok().unwrap();
//! .unwrap();
//! this.emit_struct_field("span", 1, |this| self.span.encode(this))
//! })
//! }
Expand All @@ -79,9 +79,9 @@
//! d.read_struct("Spanned", 2, |this| {
//! Ok(Spanned {
//! node: this.read_struct_field("node", 0, |this| Decodable::decode(this))
//! .ok().unwrap(),
//! .unwrap(),
//! span: this.read_struct_field("span", 1, |this| Decodable::decode(this))
//! .ok().unwrap(),
//! .unwrap(),
//! })
//! })
//! }
Expand Down
4 changes: 2 additions & 2 deletions src/libsyntax/parse/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,7 @@ impl<'a> StringReader<'a> {
// find the integer representing the name
self.scan_digits(base);
let encoded_name : u32 = self.with_str_from(start_bpos, |s| {
num::from_str_radix(s, 10).ok().unwrap_or_else(|| {
num::from_str_radix(s, 10).unwrap_or_else(|_| {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

which is more expressive? maybe needs a style-guide?

panic!("expected digits representing a name, got {:?}, {}, range [{:?},{:?}]",
s, whence, start_bpos, self.last_pos);
})
Expand All @@ -641,7 +641,7 @@ impl<'a> StringReader<'a> {
let start_bpos = self.last_pos;
self.scan_digits(base);
let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| {
num::from_str_radix(s, 10).ok().unwrap_or_else(|| {
num::from_str_radix(s, 10).unwrap_or_else(|_| {
panic!("expected digits representing a ctxt, got {:?}, {}", s, whence);
})
});
Expand Down
31 changes: 17 additions & 14 deletions src/libterm/terminfo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,21 +181,24 @@ impl<T: Write+Send+'static> TerminfoTerminal<T> {
}
};

let entry = open(&term[..]);
if entry.is_err() {
if env::var("MSYSCON").ok().map_or(false, |s| {
"mintty.exe" == s
}) {
// msys terminal
return Some(box TerminfoTerminal {out: out,
ti: msys_terminfo(),
num_colors: 8} as Box<Terminal<T>+Send>);
}
debug!("error finding terminfo entry: {:?}", entry.err().unwrap());
return None;
}
let mut file = match open(&term[..]) {
Ok(f) => f,
Err(err) => return match env::var("MSYSCON") {
Ok(ref val) if &val[..] == "mintty.exe" => {
// msys terminal
Some(box TerminfoTerminal{
out: out,
ti: msys_terminfo(),
num_colors: 8,
} as Box<Terminal<T>+Send>)
},
_ => {
debug!("error finding terminfo entry: {:?}", err);
None
},
},
};

let mut file = entry.unwrap();
let ti = parse(&mut file, false);
if ti.is_err() {
debug!("error parsing terminfo entry: {:?}", ti.err().unwrap());
Expand Down
2 changes: 1 addition & 1 deletion src/test/run-pass/spawn2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use std::thread;

pub fn main() {
let t = thread::spawn(move|| child((10, 20, 30, 40, 50, 60, 70, 80, 90)) );
t.join().ok().unwrap();
t.join().ok().unwrap(); // forget Err value, since it doesn't implement Debug
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

join() returns a Result<T, Box<Any + Send + 'static>>

there are lots of other cases where the result is ignored since Debug cannot be implemented generically to return "thread panicked" on Err

}

fn child(args: (int, int, int, int, int, int, int, int, int)) {
Expand Down
2 changes: 1 addition & 1 deletion src/test/run-pass/unit-like-struct-drop-run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@ pub fn main() {
let _b = Foo;
}).join();

let s = x.err().unwrap().downcast::<&'static str>().ok().unwrap();
let s = x.err().unwrap().downcast::<&'static str>().unwrap();
assert_eq!(&**s, "This panic should happen.");
}