1
Fork 0

try! -> ?

Automated conversion using the untry tool [1] and the following command:

```
$ find -name '*.rs' -type f | xargs untry
```

at the root of the Rust repo.

[1]: https://github.com/japaric/untry
This commit is contained in:
Jorge Aparicio 2016-03-22 22:01:37 -05:00
parent 0dcc413e42
commit 0f02309e4b
132 changed files with 3755 additions and 3770 deletions

View file

@ -280,16 +280,16 @@ fn collect_tests_from_dir(config: &Config,
-> io::Result<()> {
// Ignore directories that contain a file
// `compiletest-ignore-dir`.
for file in try!(fs::read_dir(dir)) {
let file = try!(file);
for file in fs::read_dir(dir)? {
let file = file?;
if file.file_name() == *"compiletest-ignore-dir" {
return Ok(());
}
}
let dirs = try!(fs::read_dir(dir));
let dirs = fs::read_dir(dir)?;
for file in dirs {
let file = try!(file);
let file = file?;
let file_path = file.path();
debug!("inspecting file {:?}", file_path.display());
if is_test(config, &file_path) {
@ -310,11 +310,11 @@ fn collect_tests_from_dir(config: &Config,
tests.push(make_test(config, &paths))
} else if file_path.is_dir() {
let relative_file_path = relative_dir_path.join(file.file_name());
try!(collect_tests_from_dir(config,
collect_tests_from_dir(config,
base,
&file_path,
&relative_file_path,
tests));
tests)?;
}
}
Ok(())

View file

@ -29,7 +29,7 @@ impl<'a, 'b: 'a> fmt::Write for PadAdapter<'a, 'b> {
fn write_str(&mut self, mut s: &str) -> fmt::Result {
while !s.is_empty() {
if self.on_newline {
try!(self.fmt.write_str(" "));
self.fmt.write_str(" ")?;
}
let split = match s.find('\n') {
@ -42,7 +42,7 @@ impl<'a, 'b: 'a> fmt::Write for PadAdapter<'a, 'b> {
s.len()
}
};
try!(self.fmt.write_str(&s[..split]));
self.fmt.write_str(&s[..split])?;
s = &s[split..];
}
@ -169,10 +169,10 @@ impl<'a, 'b: 'a> DebugTuple<'a, 'b> {
if self.fields > 0 {
self.result = self.result.and_then(|_| {
if self.is_pretty() {
try!(self.fmt.write_str("\n"));
self.fmt.write_str("\n")?;
}
if self.fields == 1 && self.empty_name {
try!(self.fmt.write_str(","));
self.fmt.write_str(",")?;
}
self.fmt.write_str(")")
});

View file

@ -795,16 +795,16 @@ pub fn write(output: &mut Write, args: Arguments) -> Result {
None => {
// We can use default formatting parameters for all arguments.
for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
try!(formatter.buf.write_str(*piece));
try!((arg.formatter)(arg.value, &mut formatter));
formatter.buf.write_str(*piece)?;
(arg.formatter)(arg.value, &mut formatter)?;
}
}
Some(fmt) => {
// Every spec has a corresponding argument that is preceded by
// a string piece.
for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
try!(formatter.buf.write_str(*piece));
try!(formatter.run(arg));
formatter.buf.write_str(*piece)?;
formatter.run(arg)?;
}
}
}
@ -812,7 +812,7 @@ pub fn write(output: &mut Write, args: Arguments) -> Result {
// There can be only one trailing string piece left.
match pieces.next() {
Some(piece) => {
try!(formatter.buf.write_str(*piece));
formatter.buf.write_str(*piece)?;
}
None => {}
}
@ -897,9 +897,9 @@ impl<'a> Formatter<'a> {
// Writes the sign if it exists, and then the prefix if it was requested
let write_prefix = |f: &mut Formatter| {
if let Some(c) = sign {
try!(f.buf.write_str(unsafe {
f.buf.write_str(unsafe {
str::from_utf8_unchecked(c.encode_utf8().as_slice())
}));
})?;
}
if prefixed { f.buf.write_str(prefix) }
else { Ok(()) }
@ -910,18 +910,18 @@ impl<'a> Formatter<'a> {
// If there's no minimum length requirements then we can just
// write the bytes.
None => {
try!(write_prefix(self)); self.buf.write_str(buf)
write_prefix(self)?; self.buf.write_str(buf)
}
// Check if we're over the minimum width, if so then we can also
// just write the bytes.
Some(min) if width >= min => {
try!(write_prefix(self)); self.buf.write_str(buf)
write_prefix(self)?; self.buf.write_str(buf)
}
// The sign and prefix goes before the padding if the fill character
// is zero
Some(min) if self.sign_aware_zero_pad() => {
self.fill = '0';
try!(write_prefix(self));
write_prefix(self)?;
self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
f.buf.write_str(buf)
})
@ -929,7 +929,7 @@ impl<'a> Formatter<'a> {
// Otherwise, the sign and prefix goes after the padding
Some(min) => {
self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
try!(write_prefix(f)); f.buf.write_str(buf)
write_prefix(f)?; f.buf.write_str(buf)
})
}
}
@ -1008,13 +1008,13 @@ impl<'a> Formatter<'a> {
};
for _ in 0..pre_pad {
try!(self.buf.write_str(fill));
self.buf.write_str(fill)?;
}
try!(f(self));
f(self)?;
for _ in 0..post_pad {
try!(self.buf.write_str(fill));
self.buf.write_str(fill)?;
}
Ok(())
@ -1033,7 +1033,7 @@ impl<'a> Formatter<'a> {
if self.sign_aware_zero_pad() {
// a sign always goes first
let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
try!(self.buf.write_str(sign));
self.buf.write_str(sign)?;
// remove the sign from the formatted parts
formatted.sign = b"";
@ -1065,7 +1065,7 @@ impl<'a> Formatter<'a> {
}
if !formatted.sign.is_empty() {
try!(write_bytes(self.buf, formatted.sign));
write_bytes(self.buf, formatted.sign)?;
}
for part in formatted.parts {
match *part {
@ -1073,11 +1073,11 @@ impl<'a> Formatter<'a> {
const ZEROES: &'static str = // 64 zeroes
"0000000000000000000000000000000000000000000000000000000000000000";
while nzeroes > ZEROES.len() {
try!(self.buf.write_str(ZEROES));
self.buf.write_str(ZEROES)?;
nzeroes -= ZEROES.len();
}
if nzeroes > 0 {
try!(self.buf.write_str(&ZEROES[..nzeroes]));
self.buf.write_str(&ZEROES[..nzeroes])?;
}
}
flt2dec::Part::Num(mut v) => {
@ -1087,10 +1087,10 @@ impl<'a> Formatter<'a> {
*c = b'0' + (v % 10) as u8;
v /= 10;
}
try!(write_bytes(self.buf, &s[..len]));
write_bytes(self.buf, &s[..len])?;
}
flt2dec::Part::Copy(buf) => {
try!(write_bytes(self.buf, buf));
write_bytes(self.buf, buf)?;
}
}
}
@ -1349,20 +1349,20 @@ impl Display for bool {
#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for str {
fn fmt(&self, f: &mut Formatter) -> Result {
try!(f.write_char('"'));
f.write_char('"')?;
let mut from = 0;
for (i, c) in self.char_indices() {
let esc = c.escape_default();
// If char needs escaping, flush backlog so far and write, else skip
if esc.size_hint() != (1, Some(1)) {
try!(f.write_str(&self[from..i]));
f.write_str(&self[from..i])?;
for c in esc {
try!(f.write_char(c));
f.write_char(c)?;
}
from = i + c.len_utf8();
}
}
try!(f.write_str(&self[from..]));
f.write_str(&self[from..])?;
f.write_char('"')
}
}
@ -1377,9 +1377,9 @@ impl Display for str {
#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for char {
fn fmt(&self, f: &mut Formatter) -> Result {
try!(f.write_char('\''));
f.write_char('\'')?;
for c in self.escape_default() {
try!(f.write_char(c))
f.write_char(c)?
}
f.write_char('\'')
}

View file

@ -214,7 +214,7 @@ fn dec2flt<T: RawFloat>(s: &str) -> Result<T, ParseFloatError> {
}
let (sign, s) = extract_sign(s);
let flt = match parse_decimal(s) {
ParseResult::Valid(decimal) => try!(convert(decimal)),
ParseResult::Valid(decimal) => convert(decimal)?,
ParseResult::ShortcutToInf => T::infinity(),
ParseResult::ShortcutToZero => T::zero(),
ParseResult::Invalid => match s {

View file

@ -240,7 +240,7 @@ impl Utf8Error {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
try!(run_utf8_validation(v));
run_utf8_validation(v)?;
Ok(unsafe { from_utf8_unchecked(v) })
}

View file

@ -662,7 +662,7 @@ pub fn render_opts<'a, N, E, G, W>(g: &'a G,
{
fn writeln<W: Write>(w: &mut W, arg: &[&str]) -> io::Result<()> {
for &s in arg {
try!(w.write_all(s.as_bytes()));
w.write_all(s.as_bytes())?;
}
write!(w, "\n")
}
@ -671,9 +671,9 @@ pub fn render_opts<'a, N, E, G, W>(g: &'a G,
w.write_all(b" ")
}
try!(writeln(w, &["digraph ", g.graph_id().as_slice(), " {"]));
writeln(w, &["digraph ", g.graph_id().as_slice(), " {"])?;
for n in g.nodes().iter() {
try!(indent(w));
indent(w)?;
let id = g.node_id(n);
let escaped = &g.node_label(n).to_dot_string();
@ -702,12 +702,12 @@ pub fn render_opts<'a, N, E, G, W>(g: &'a G,
}
text.push(";");
try!(writeln(w, &text));
writeln(w, &text)?;
}
for e in g.edges().iter() {
let escaped_label = &g.edge_label(e).to_dot_string();
try!(indent(w));
indent(w)?;
let source = g.source(e);
let target = g.target(e);
let source_id = g.node_id(&source);
@ -729,7 +729,7 @@ pub fn render_opts<'a, N, E, G, W>(g: &'a G,
}
text.push(";");
try!(writeln(w, &text));
writeln(w, &text)?;
}
writeln(w, &["}"])
@ -959,7 +959,7 @@ mod tests {
let mut writer = Vec::new();
render(&g, &mut writer).unwrap();
let mut s = String::new();
try!(Read::read_to_string(&mut &*writer, &mut s));
Read::read_to_string(&mut &*writer, &mut s)?;
Ok(s)
}

View file

@ -398,8 +398,8 @@ pub mod reader {
}
pub fn doc_at<'a>(data: &'a [u8], start: usize) -> DecodeResult<TaggedDoc<'a>> {
let elt_tag = try!(tag_at(data, start));
let elt_size = try!(tag_len_at(data, elt_tag));
let elt_tag = tag_at(data, start)?;
let elt_size = tag_len_at(data, elt_tag)?;
let end = elt_size.next + elt_size.val;
Ok(TaggedDoc {
tag: elt_tag.val,
@ -581,7 +581,7 @@ pub mod reader {
if self.pos >= self.parent.end {
return Err(Expected(format!("no more documents in current node!")));
}
let TaggedDoc { tag: r_tag, doc: r_doc } = try!(doc_at(self.parent.data, self.pos));
let TaggedDoc { tag: r_tag, doc: r_doc } = doc_at(self.parent.data, self.pos)?;
debug!("self.parent={:?}-{:?} self.pos={:?} r_tag={:?} r_doc={:?}-{:?}",
self.parent.start,
self.parent.end,
@ -607,12 +607,12 @@ pub mod reader {
fn push_doc<T, F>(&mut self, exp_tag: EbmlEncoderTag, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
{
let d = try!(self.next_doc(exp_tag));
let d = self.next_doc(exp_tag)?;
let old_parent = self.parent;
let old_pos = self.pos;
self.parent = d;
self.pos = d.start;
let r = try!(f(self));
let r = f(self)?;
self.parent = old_parent;
self.pos = old_pos;
Ok(r)
@ -624,7 +624,7 @@ pub mod reader {
return Ok(0);
}
let TaggedDoc { tag: r_tag, doc: r_doc } = try!(doc_at(self.parent.data, self.pos));
let TaggedDoc { tag: r_tag, doc: r_doc } = doc_at(self.parent.data, self.pos)?;
let r = if r_tag == (EsSub8 as usize) {
doc_as_u8(r_doc) as usize
} else if r_tag == (EsSub32 as usize) {
@ -659,7 +659,7 @@ pub mod reader {
return Err(Expected(format!("no more documents in current node!")));
}
let TaggedDoc { tag: r_tag, doc: r_doc } = try!(doc_at(self.parent.data, self.pos));
let TaggedDoc { tag: r_tag, doc: r_doc } = doc_at(self.parent.data, self.pos)?;
let r = if first_tag as usize <= r_tag && r_tag <= last_tag as usize {
match r_tag - first_tag as usize {
0 => doc_as_u8(r_doc) as u64,
@ -689,11 +689,11 @@ pub mod reader {
pub fn read_opaque<R, F>(&mut self, op: F) -> DecodeResult<R>
where F: FnOnce(&mut opaque::Decoder, Doc) -> DecodeResult<R>
{
let doc = try!(self.next_doc(EsOpaque));
let doc = self.next_doc(EsOpaque)?;
let result = {
let mut opaque_decoder = opaque::Decoder::new(doc.data, doc.start);
try!(op(&mut opaque_decoder, doc))
op(&mut opaque_decoder, doc)?
};
Ok(result)
@ -718,16 +718,16 @@ pub mod reader {
self._next_int(EsU8, EsU64)
}
fn read_u32(&mut self) -> DecodeResult<u32> {
Ok(try!(self._next_int(EsU8, EsU32)) as u32)
Ok(self._next_int(EsU8, EsU32)? as u32)
}
fn read_u16(&mut self) -> DecodeResult<u16> {
Ok(try!(self._next_int(EsU8, EsU16)) as u16)
Ok(self._next_int(EsU8, EsU16)? as u16)
}
fn read_u8(&mut self) -> DecodeResult<u8> {
Ok(doc_as_u8(try!(self.next_doc(EsU8))))
Ok(doc_as_u8(self.next_doc(EsU8)?))
}
fn read_uint(&mut self) -> DecodeResult<usize> {
let v = try!(self._next_int(EsU8, EsU64));
let v = self._next_int(EsU8, EsU64)?;
if v > (::std::usize::MAX as u64) {
Err(IntTooBig(v as usize))
} else {
@ -736,19 +736,19 @@ pub mod reader {
}
fn read_i64(&mut self) -> DecodeResult<i64> {
Ok(try!(self._next_int(EsI8, EsI64)) as i64)
Ok(self._next_int(EsI8, EsI64)? as i64)
}
fn read_i32(&mut self) -> DecodeResult<i32> {
Ok(try!(self._next_int(EsI8, EsI32)) as i32)
Ok(self._next_int(EsI8, EsI32)? as i32)
}
fn read_i16(&mut self) -> DecodeResult<i16> {
Ok(try!(self._next_int(EsI8, EsI16)) as i16)
Ok(self._next_int(EsI8, EsI16)? as i16)
}
fn read_i8(&mut self) -> DecodeResult<i8> {
Ok(doc_as_u8(try!(self.next_doc(EsI8))) as i8)
Ok(doc_as_u8(self.next_doc(EsI8)?) as i8)
}
fn read_int(&mut self) -> DecodeResult<isize> {
let v = try!(self._next_int(EsI8, EsI64)) as i64;
let v = self._next_int(EsI8, EsI64)? as i64;
if v > (isize::MAX as i64) || v < (isize::MIN as i64) {
debug!("FIXME \\#6122: Removing this makes this function miscompile");
Err(IntTooBig(v as usize))
@ -758,22 +758,22 @@ pub mod reader {
}
fn read_bool(&mut self) -> DecodeResult<bool> {
Ok(doc_as_u8(try!(self.next_doc(EsBool))) != 0)
Ok(doc_as_u8(self.next_doc(EsBool)?) != 0)
}
fn read_f64(&mut self) -> DecodeResult<f64> {
let bits = doc_as_u64(try!(self.next_doc(EsF64)));
let bits = doc_as_u64(self.next_doc(EsF64)?);
Ok(unsafe { transmute(bits) })
}
fn read_f32(&mut self) -> DecodeResult<f32> {
let bits = doc_as_u32(try!(self.next_doc(EsF32)));
let bits = doc_as_u32(self.next_doc(EsF32)?);
Ok(unsafe { transmute(bits) })
}
fn read_char(&mut self) -> DecodeResult<char> {
Ok(char::from_u32(doc_as_u32(try!(self.next_doc(EsChar)))).unwrap())
Ok(char::from_u32(doc_as_u32(self.next_doc(EsChar)?)).unwrap())
}
fn read_str(&mut self) -> DecodeResult<String> {
Ok(try!(self.next_doc(EsStr)).as_str())
Ok(self.next_doc(EsStr)?.as_str())
}
// Compound types:
@ -782,13 +782,13 @@ pub mod reader {
{
debug!("read_enum({})", name);
let doc = try!(self.next_doc(EsEnum));
let doc = self.next_doc(EsEnum)?;
let (old_parent, old_pos) = (self.parent, self.pos);
self.parent = doc;
self.pos = self.parent.start;
let result = try!(f(self));
let result = f(self)?;
self.parent = old_parent;
self.pos = old_pos;
@ -799,7 +799,7 @@ pub mod reader {
where F: FnMut(&mut Decoder<'doc>, usize) -> DecodeResult<T>
{
debug!("read_enum_variant()");
let idx = try!(self._next_sub());
let idx = self._next_sub()?;
debug!(" idx={}", idx);
f(self, idx)
@ -816,7 +816,7 @@ pub mod reader {
where F: FnMut(&mut Decoder<'doc>, usize) -> DecodeResult<T>
{
debug!("read_enum_struct_variant()");
let idx = try!(self._next_sub());
let idx = self._next_sub()?;
debug!(" idx={}", idx);
f(self, idx)
@ -904,7 +904,7 @@ pub mod reader {
{
debug!("read_seq()");
self.push_doc(EsVec, move |d| {
let len = try!(d._next_sub());
let len = d._next_sub()?;
debug!(" len={}", len);
f(d, len)
})
@ -922,7 +922,7 @@ pub mod reader {
{
debug!("read_map()");
self.push_doc(EsMap, move |d| {
let len = try!(d._next_sub());
let len = d._next_sub()?;
debug!(" len={}", len);
f(d, len)
})
@ -1020,10 +1020,10 @@ pub mod writer {
assert!(tag_id >= NUM_IMPLICIT_TAGS);
// Write the enum ID:
try!(write_tag(self.writer, tag_id));
write_tag(self.writer, tag_id)?;
// Write a placeholder four-byte size.
let cur_pos = try!(self.writer.seek(SeekFrom::Current(0)));
let cur_pos = self.writer.seek(SeekFrom::Current(0))?;
self.size_positions.push(cur_pos);
let zeroes: &[u8] = &[0, 0, 0, 0];
self.writer.write_all(zeroes)
@ -1031,8 +1031,8 @@ pub mod writer {
pub fn end_tag(&mut self) -> EncodeResult {
let last_size_pos = self.size_positions.pop().unwrap();
let cur_pos = try!(self.writer.seek(SeekFrom::Current(0)));
try!(self.writer.seek(SeekFrom::Start(last_size_pos)));
let cur_pos = self.writer.seek(SeekFrom::Current(0))?;
self.writer.seek(SeekFrom::Start(last_size_pos))?;
let size = (cur_pos - last_size_pos - 4) as usize;
// relax the size encoding for small tags (bigger tags are costly to move).
@ -1048,12 +1048,12 @@ pub mod writer {
}
// overwrite the size and data and continue
try!(write_vuint(self.writer, size));
try!(self.writer.write_all(&buf[..size]));
write_vuint(self.writer, size)?;
self.writer.write_all(&buf[..size])?;
} else {
// overwrite the size with an overlong encoding and skip past the data
try!(write_sized_vuint(self.writer, size, 4));
try!(self.writer.seek(SeekFrom::Start(cur_pos)));
write_sized_vuint(self.writer, size, 4)?;
self.writer.seek(SeekFrom::Start(cur_pos))?;
}
debug!("End tag (size = {:?})", size);
@ -1063,15 +1063,15 @@ pub mod writer {
pub fn wr_tag<F>(&mut self, tag_id: usize, blk: F) -> EncodeResult
where F: FnOnce() -> EncodeResult
{
try!(self.start_tag(tag_id));
try!(blk());
self.start_tag(tag_id)?;
blk()?;
self.end_tag()
}
pub fn wr_tagged_bytes(&mut self, tag_id: usize, b: &[u8]) -> EncodeResult {
assert!(tag_id >= NUM_IMPLICIT_TAGS);
try!(write_tag(self.writer, tag_id));
try!(write_vuint(self.writer, b.len()));
write_tag(self.writer, tag_id)?;
write_vuint(self.writer, b.len())?;
self.writer.write_all(b)
}
@ -1124,7 +1124,7 @@ pub mod writer {
// for auto-serialization
fn wr_tagged_raw_bytes(&mut self, tag_id: usize, b: &[u8]) -> EncodeResult {
try!(write_tag(self.writer, tag_id));
write_tag(self.writer, tag_id)?;
self.writer.write_all(b)
}
@ -1200,11 +1200,11 @@ pub mod writer {
pub fn emit_opaque<F>(&mut self, f: F) -> EncodeResult
where F: FnOnce(&mut opaque::Encoder) -> EncodeResult
{
try!(self.start_tag(EsOpaque as usize));
self.start_tag(EsOpaque as usize)?;
{
let mut opaque_encoder = opaque::Encoder::new(self.writer);
try!(f(&mut opaque_encoder));
f(&mut opaque_encoder)?;
}
self.mark_stable_position();
@ -1298,15 +1298,15 @@ pub mod writer {
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
{
try!(self.start_tag(EsEnum as usize));
try!(f(self));
self.start_tag(EsEnum as usize)?;
f(self)?;
self.end_tag()
}
fn emit_enum_variant<F>(&mut self, _: &str, v_id: usize, _: usize, f: F) -> EncodeResult
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
{
try!(self._emit_tagged_sub(v_id));
self._emit_tagged_sub(v_id)?;
f(self)
}
@ -1390,9 +1390,9 @@ pub mod writer {
return self.wr_tagged_bytes(EsVec as usize, &[]);
}
try!(self.start_tag(EsVec as usize));
try!(self._emit_tagged_sub(len));
try!(f(self));
self.start_tag(EsVec as usize)?;
self._emit_tagged_sub(len)?;
f(self)?;
self.end_tag()
}
@ -1400,8 +1400,8 @@ pub mod writer {
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
{
try!(self.start_tag(EsVecElt as usize));
try!(f(self));
self.start_tag(EsVecElt as usize)?;
f(self)?;
self.end_tag()
}
@ -1413,9 +1413,9 @@ pub mod writer {
return self.wr_tagged_bytes(EsMap as usize, &[]);
}
try!(self.start_tag(EsMap as usize));
try!(self._emit_tagged_sub(len));
try!(f(self));
self.start_tag(EsMap as usize)?;
self._emit_tagged_sub(len)?;
f(self)?;
self.end_tag()
}
@ -1423,16 +1423,16 @@ pub mod writer {
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
{
try!(self.start_tag(EsMapKey as usize));
try!(f(self));
self.start_tag(EsMapKey as usize)?;
f(self)?;
self.end_tag()
}
fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
{
try!(self.start_tag(EsMapVal as usize));
try!(f(self));
self.start_tag(EsMapVal as usize)?;
f(self)?;
self.end_tag()
}
}

View file

@ -120,7 +120,7 @@ impl<'a> serialize::Encoder for Encoder<'a> {
}
fn emit_str(&mut self, v: &str) -> EncodeResult {
try!(self.emit_uint(v.len()));
self.emit_uint(v.len())?;
let _ = self.cursor.write_all(v.as_bytes());
Ok(())
}
@ -139,7 +139,7 @@ impl<'a> serialize::Encoder for Encoder<'a> {
-> EncodeResult
where F: FnOnce(&mut Self) -> EncodeResult
{
try!(self.emit_uint(v_id));
self.emit_uint(v_id)?;
f(self)
}
@ -221,7 +221,7 @@ impl<'a> serialize::Encoder for Encoder<'a> {
fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
{
try!(self.emit_uint(len));
self.emit_uint(len)?;
f(self)
}
@ -234,7 +234,7 @@ impl<'a> serialize::Encoder for Encoder<'a> {
fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
{
try!(self.emit_uint(len));
self.emit_uint(len)?;
f(self)
}
@ -356,27 +356,27 @@ impl<'a> serialize::Decoder for Decoder<'a> {
}
fn read_bool(&mut self) -> Result<bool, Self::Error> {
let value = try!(self.read_u8());
let value = self.read_u8()?;
Ok(value != 0)
}
fn read_f64(&mut self) -> Result<f64, Self::Error> {
let bits = try!(self.read_u64());
let bits = self.read_u64()?;
Ok(unsafe { ::std::mem::transmute(bits) })
}
fn read_f32(&mut self) -> Result<f32, Self::Error> {
let bits = try!(self.read_u32());
let bits = self.read_u32()?;
Ok(unsafe { ::std::mem::transmute(bits) })
}
fn read_char(&mut self) -> Result<char, Self::Error> {
let bits = try!(self.read_u32());
let bits = self.read_u32()?;
Ok(::std::char::from_u32(bits).unwrap())
}
fn read_str(&mut self) -> Result<String, Self::Error> {
let len = try!(self.read_uint());
let len = self.read_uint()?;
let s = ::std::str::from_utf8(&self.data[self.position..self.position + len]).unwrap();
self.position += len;
Ok(s.to_string())
@ -391,7 +391,7 @@ impl<'a> serialize::Decoder for Decoder<'a> {
fn read_enum_variant<T, F>(&mut self, _: &[&str], mut f: F) -> Result<T, Self::Error>
where F: FnMut(&mut Decoder<'a>, usize) -> Result<T, Self::Error>
{
let disr = try!(self.read_uint());
let disr = self.read_uint()?;
f(self, disr)
}
@ -404,7 +404,7 @@ impl<'a> serialize::Decoder for Decoder<'a> {
fn read_enum_struct_variant<T, F>(&mut self, _: &[&str], mut f: F) -> Result<T, Self::Error>
where F: FnMut(&mut Decoder<'a>, usize) -> Result<T, Self::Error>
{
let disr = try!(self.read_uint());
let disr = self.read_uint()?;
f(self, disr)
}
@ -483,7 +483,7 @@ impl<'a> serialize::Decoder for Decoder<'a> {
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
where F: FnOnce(&mut Decoder<'a>, usize) -> Result<T, Self::Error>
{
let len = try!(self.read_uint());
let len = self.read_uint()?;
f(self, len)
}
@ -496,7 +496,7 @@ impl<'a> serialize::Decoder for Decoder<'a> {
fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
where F: FnOnce(&mut Decoder<'a>, usize) -> Result<T, Self::Error>
{
let len = try!(self.read_uint());
let len = self.read_uint()?;
f(self, len)
}

View file

@ -68,7 +68,7 @@ struct Matrix<'a>(Vec<Vec<&'a Pat>>);
/// ++++++++++++++++++++++++++
impl<'a> fmt::Debug for Matrix<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "\n"));
write!(f, "\n")?;
let &Matrix(ref m) = self;
let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
@ -85,16 +85,16 @@ impl<'a> fmt::Debug for Matrix<'a> {
let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
let br = repeat('+').take(total_width).collect::<String>();
try!(write!(f, "{}\n", br));
write!(f, "{}\n", br)?;
for row in pretty_printed_matrix {
try!(write!(f, "+"));
write!(f, "+")?;
for (column, pat_str) in row.into_iter().enumerate() {
try!(write!(f, " "));
try!(write!(f, "{:1$}", pat_str, column_widths[column]));
try!(write!(f, " +"));
write!(f, " ")?;
write!(f, "{:1$}", pat_str, column_widths[column])?;
write!(f, " +")?;
}
try!(write!(f, "\n"));
try!(write!(f, "{}\n", br));
write!(f, "\n")?;
write!(f, "{}\n", br)?;
}
Ok(())
}

View file

@ -639,14 +639,14 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
_ => {},
}
}
match try!(eval_const_expr_partial(tcx, &inner, ty_hint, fn_args)) {
match eval_const_expr_partial(tcx, &inner, ty_hint, fn_args)? {
Float(f) => Float(-f),
Integral(i) => Integral(math!(e, -i)),
const_val => signal!(e, NegateOn(const_val)),
}
}
hir::ExprUnary(hir::UnNot, ref inner) => {
match try!(eval_const_expr_partial(tcx, &inner, ty_hint, fn_args)) {
match eval_const_expr_partial(tcx, &inner, ty_hint, fn_args)? {
Integral(i) => Integral(math!(e, !i)),
Bool(b) => Bool(!b),
const_val => signal!(e, NotOn(const_val)),
@ -661,8 +661,8 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
// gives us a type through a type-suffix, cast or const def type
// we need to re-eval the other value of the BinOp if it was
// not inferred
match (try!(eval_const_expr_partial(tcx, &a, ty_hint, fn_args)),
try!(eval_const_expr_partial(tcx, &b, b_ty, fn_args))) {
match (eval_const_expr_partial(tcx, &a, ty_hint, fn_args)?,
eval_const_expr_partial(tcx, &b, b_ty, fn_args)?) {
(Float(a), Float(b)) => {
match op.node {
hir::BiAdd => Float(a + b),
@ -744,7 +744,7 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
// we had a type hint, so we can't have an unknown type
None => unreachable!(),
};
try!(eval_const_expr_partial(tcx, &base, hint, fn_args))
eval_const_expr_partial(tcx, &base, hint, fn_args)?
},
Err(e) => return Err(e),
};
@ -781,14 +781,14 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
Some(ty) => ty_hint.checked_or(ty),
None => ty_hint,
};
try!(eval_const_expr_partial(tcx, e, item_hint, None))
eval_const_expr_partial(tcx, e, item_hint, None)?
} else {
signal!(e, NonConstPath);
}
},
Def::Variant(enum_def, variant_def) => {
if let Some(const_expr) = lookup_variant_by_id(tcx, enum_def, variant_def) {
try!(eval_const_expr_partial(tcx, const_expr, ty_hint, None))
eval_const_expr_partial(tcx, const_expr, ty_hint, None)?
} else {
signal!(e, NonConstPath);
}
@ -810,7 +810,7 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
}
hir::ExprCall(ref callee, ref args) => {
let sub_ty_hint = ty_hint.erase_hint();
let callee_val = try!(eval_const_expr_partial(tcx, callee, sub_ty_hint, fn_args));
let callee_val = eval_const_expr_partial(tcx, callee, sub_ty_hint, fn_args)?;
let did = match callee_val {
Function(did) => did,
callee => signal!(e, CallOn(callee)),
@ -826,27 +826,27 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
let mut call_args = NodeMap();
for (arg, arg_expr) in decl.inputs.iter().zip(args.iter()) {
let arg_hint = ty_hint.erase_hint();
let arg_val = try!(eval_const_expr_partial(
let arg_val = eval_const_expr_partial(
tcx,
arg_expr,
arg_hint,
fn_args
));
)?;
debug!("const call arg: {:?}", arg);
let old = call_args.insert(arg.pat.id, arg_val);
assert!(old.is_none());
}
debug!("const call({:?})", call_args);
try!(eval_const_expr_partial(tcx, &result, ty_hint, Some(&call_args)))
eval_const_expr_partial(tcx, &result, ty_hint, Some(&call_args))?
},
hir::ExprLit(ref lit) => try!(lit_to_const(&lit.node, tcx, ety, lit.span)),
hir::ExprLit(ref lit) => lit_to_const(&lit.node, tcx, ety, lit.span)?,
hir::ExprBlock(ref block) => {
match block.expr {
Some(ref expr) => try!(eval_const_expr_partial(tcx, &expr, ty_hint, fn_args)),
Some(ref expr) => eval_const_expr_partial(tcx, &expr, ty_hint, fn_args)?,
None => unreachable!(),
}
}
hir::ExprType(ref e, _) => try!(eval_const_expr_partial(tcx, &e, ty_hint, fn_args)),
hir::ExprType(ref e, _) => eval_const_expr_partial(tcx, &e, ty_hint, fn_args)?,
hir::ExprTup(_) => Tuple(e.id),
hir::ExprStruct(..) => Struct(e.id),
hir::ExprIndex(ref arr, ref idx) => {
@ -854,9 +854,9 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
signal!(e, IndexOpFeatureGated);
}
let arr_hint = ty_hint.erase_hint();
let arr = try!(eval_const_expr_partial(tcx, arr, arr_hint, fn_args));
let arr = eval_const_expr_partial(tcx, arr, arr_hint, fn_args)?;
let idx_hint = ty_hint.checked_or(tcx.types.usize);
let idx = match try!(eval_const_expr_partial(tcx, idx, idx_hint, fn_args)) {
let idx = match eval_const_expr_partial(tcx, idx, idx_hint, fn_args)? {
Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
Integral(_) => unreachable!(),
_ => signal!(idx, IndexNotInt),
@ -866,18 +866,18 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
Array(_, n) if idx >= n => signal!(e, IndexOutOfBounds),
Array(v, n) => if let hir::ExprVec(ref v) = tcx.map.expect_expr(v).node {
assert_eq!(n as usize as u64, n);
try!(eval_const_expr_partial(tcx, &v[idx as usize], ty_hint, fn_args))
eval_const_expr_partial(tcx, &v[idx as usize], ty_hint, fn_args)?
} else {
unreachable!()
},
Repeat(_, n) if idx >= n => signal!(e, IndexOutOfBounds),
Repeat(elem, _) => try!(eval_const_expr_partial(
Repeat(elem, _) => eval_const_expr_partial(
tcx,
&tcx.map.expect_expr(elem),
ty_hint,
fn_args,
)),
)?,
ByteStr(ref data) if idx >= data.len() as u64 => signal!(e, IndexOutOfBounds),
ByteStr(data) => {
@ -894,7 +894,7 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
let len_hint = ty_hint.checked_or(tcx.types.usize);
Repeat(
e.id,
match try!(eval_const_expr_partial(tcx, &n, len_hint, fn_args)) {
match eval_const_expr_partial(tcx, &n, len_hint, fn_args)? {
Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
Integral(_) => signal!(e, RepeatCountNotNatural),
_ => signal!(e, RepeatCountNotInt),
@ -903,11 +903,11 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
},
hir::ExprTupField(ref base, index) => {
let base_hint = ty_hint.erase_hint();
let c = try!(eval_const_expr_partial(tcx, base, base_hint, fn_args));
let c = eval_const_expr_partial(tcx, base, base_hint, fn_args)?;
if let Tuple(tup_id) = c {
if let hir::ExprTup(ref fields) = tcx.map.expect_expr(tup_id).node {
if index.node < fields.len() {
try!(eval_const_expr_partial(tcx, &fields[index.node], ty_hint, fn_args))
eval_const_expr_partial(tcx, &fields[index.node], ty_hint, fn_args)?
} else {
signal!(e, TupleIndexOutOfBounds);
}
@ -921,14 +921,14 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
hir::ExprField(ref base, field_name) => {
let base_hint = ty_hint.erase_hint();
// Get the base expression if it is a struct and it is constant
let c = try!(eval_const_expr_partial(tcx, base, base_hint, fn_args));
let c = eval_const_expr_partial(tcx, base, base_hint, fn_args)?;
if let Struct(struct_id) = c {
if let hir::ExprStruct(_, ref fields, _) = tcx.map.expect_expr(struct_id).node {
// Check that the given field exists and evaluate it
// if the idents are compared run-pass/issue-19244 fails
if let Some(f) = fields.iter().find(|f| f.name.node
== field_name.node) {
try!(eval_const_expr_partial(tcx, &f.expr, ty_hint, fn_args))
eval_const_expr_partial(tcx, &f.expr, ty_hint, fn_args)?
} else {
signal!(e, MissingStructField);
}
@ -943,7 +943,7 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
};
match (ety.map(|t| &t.sty), result) {
(Some(ref ty_hint), Integral(i)) => Ok(Integral(try!(infer(i, tcx, ty_hint, e.span)))),
(Some(ref ty_hint), Integral(i)) => Ok(Integral(infer(i, tcx, ty_hint, e.span)?)),
(_, result) => Ok(result),
}
}
@ -1105,14 +1105,14 @@ fn cast_const_int<'tcx>(tcx: &TyCtxt<'tcx>, val: ConstInt, ty: ty::Ty) -> CastRe
ty::TyFloat(ast::FloatTy::F64) if val.is_negative() => {
// FIXME: this could probably be prettier
// there's no easy way to turn an `Infer` into a f64
let val = try!((-val).map_err(Math));
let val = (-val).map_err(Math)?;
let val = val.to_u64().unwrap() as f64;
let val = -val;
Ok(Float(val))
},
ty::TyFloat(ast::FloatTy::F64) => Ok(Float(val.to_u64().unwrap() as f64)),
ty::TyFloat(ast::FloatTy::F32) if val.is_negative() => {
let val = try!((-val).map_err(Math));
let val = (-val).map_err(Math)?;
let val = val.to_u64().unwrap() as f32;
let val = -val;
Ok(Float(val as f64))

View file

@ -152,10 +152,10 @@ impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O
"".to_string()
};
try!(ps.synth_comment(
ps.synth_comment(
format!("id {}: {}{}{}{}", id, entry_str,
gens_str, action_kills_str, scope_kills_str)));
try!(pp::space(&mut ps.s));
gens_str, action_kills_str, scope_kills_str))?;
pp::space(&mut ps.s)?;
}
Ok(())
}
@ -534,9 +534,9 @@ impl<'a, 'tcx, O:DataFlowOperator+Clone+'static> DataFlowContext<'a, 'tcx, O> {
fn pretty_print_to<'b>(&self, wr: Box<io::Write + 'b>,
blk: &hir::Block) -> io::Result<()> {
let mut ps = pprust::rust_printer_annotated(wr, self, None);
try!(ps.cbox(pprust::indent_unit));
try!(ps.ibox(0));
try!(ps.print_block(blk));
ps.cbox(pprust::indent_unit)?;
ps.ibox(0)?;
ps.print_block(blk)?;
pp::eof(&mut ps.s)
}
}

View file

@ -55,8 +55,8 @@ pub struct DefId {
impl fmt::Debug for DefId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "DefId {{ krate: {:?}, node: {:?}",
self.krate, self.index));
write!(f, "DefId {{ krate: {:?}, node: {:?}",
self.krate, self.index)?;
// Unfortunately, there seems to be no way to attempt to print
// a path for a def-id, so I'll just make a best effort for now
@ -64,12 +64,12 @@ impl fmt::Debug for DefId {
if self.is_local() { // (1)
// (1) side-step fact that not all external things have paths at
// the moment, such as type parameters
try!(ty::tls::with_opt(|opt_tcx| {
ty::tls::with_opt(|opt_tcx| {
if let Some(tcx) = opt_tcx {
try!(write!(f, " => {}", tcx.item_path_str(*self)));
write!(f, " => {}", tcx.item_path_str(*self))?;
}
Ok(())
}));
})?;
}
write!(f, " }}")

View file

@ -1182,7 +1182,7 @@ impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> {
// Create the cmt for the variable being borrowed, from the
// caller's perspective
let var_id = upvar_def.var_id();
let var_ty = try!(self.typer.node_ty(var_id));
let var_ty = self.typer.node_ty(var_id)?;
self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
}
}

View file

@ -86,12 +86,12 @@ impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Bivariate<'a, 'tcx> {
}
(&ty::TyInfer(TyVar(a_id)), _) => {
try!(self.fields.instantiate(b, BiTo, a_id));
self.fields.instantiate(b, BiTo, a_id)?;
Ok(a)
}
(_, &ty::TyInfer(TyVar(b_id))) => {
try!(self.fields.instantiate(a, BiTo, b_id));
self.fields.instantiate(a, BiTo, b_id)?;
Ok(a)
}
@ -111,7 +111,7 @@ impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Bivariate<'a, 'tcx> {
{
let a1 = self.tcx().erase_late_bound_regions(a);
let b1 = self.tcx().erase_late_bound_regions(b);
let c = try!(self.relate(&a1, &b1));
let c = self.relate(&a1, &b1)?;
Ok(ty::Binder(c))
}
}

View file

@ -70,10 +70,10 @@ pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>,
match (&a.sty, &b.sty) {
// Relate integral variables to other types
(&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => {
try!(infcx.int_unification_table
infcx.int_unification_table
.borrow_mut()
.unify_var_var(a_id, b_id)
.map_err(|e| int_unification_error(a_is_expected, e)));
.map_err(|e| int_unification_error(a_is_expected, e))?;
Ok(a)
}
(&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => {
@ -91,10 +91,10 @@ pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>,
// Relate floating-point variables to other types
(&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => {
try!(infcx.float_unification_table
infcx.float_unification_table
.borrow_mut()
.unify_var_var(a_id, b_id)
.map_err(|e| float_unification_error(relation.a_is_expected(), e)));
.map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
Ok(a)
}
(&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => {
@ -123,11 +123,11 @@ fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
val: ty::IntVarValue)
-> RelateResult<'tcx, Ty<'tcx>>
{
try!(infcx
infcx
.int_unification_table
.borrow_mut()
.unify_var_value(vid, val)
.map_err(|e| int_unification_error(vid_is_expected, e)));
.map_err(|e| int_unification_error(vid_is_expected, e))?;
match val {
IntType(v) => Ok(infcx.tcx.mk_mach_int(v)),
UintType(v) => Ok(infcx.tcx.mk_mach_uint(v)),
@ -140,11 +140,11 @@ fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
val: ast::FloatTy)
-> RelateResult<'tcx, Ty<'tcx>>
{
try!(infcx
infcx
.float_unification_table
.borrow_mut()
.unify_var_value(vid, val)
.map_err(|e| float_unification_error(vid_is_expected, e)));
.map_err(|e| float_unification_error(vid_is_expected, e))?;
Ok(infcx.tcx.mk_mach_float(val))
}
@ -229,10 +229,10 @@ impl<'a, 'tcx> CombineFields<'a, 'tcx> {
Some(t) => t, // ...already instantiated.
None => { // ...not yet instantiated:
// Generalize type if necessary.
let generalized_ty = try!(match dir {
let generalized_ty = match dir {
EqTo => self.generalize(a_ty, b_vid, false),
BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true),
});
}?;
debug!("instantiate(a_ty={:?}, dir={:?}, \
b_vid={:?}, generalized_ty={:?})",
a_ty, dir, b_vid,
@ -252,12 +252,12 @@ impl<'a, 'tcx> CombineFields<'a, 'tcx> {
// relations wind up attributed to the same spans. We need
// to associate causes/spans with each of the relations in
// the stack to get this right.
try!(match dir {
match dir {
BiTo => self.bivariate().relate(&a_ty, &b_ty),
EqTo => self.equate().relate(&a_ty, &b_ty),
SubtypeOf => self.sub().relate(&a_ty, &b_ty),
SupertypeOf => self.sub().relate_with_variance(ty::Contravariant, &a_ty, &b_ty),
});
}?;
}
Ok(())

View file

@ -59,17 +59,17 @@ impl<'a, 'tcx> TypeRelation<'a,'tcx> for Equate<'a, 'tcx> {
}
(&ty::TyInfer(TyVar(a_id)), _) => {
try!(self.fields.instantiate(b, EqTo, a_id));
self.fields.instantiate(b, EqTo, a_id)?;
Ok(a)
}
(_, &ty::TyInfer(TyVar(b_id))) => {
try!(self.fields.instantiate(a, EqTo, b_id));
self.fields.instantiate(a, EqTo, b_id)?;
Ok(a)
}
_ => {
try!(combine::super_combine_tys(self.fields.infcx, self, a, b));
combine::super_combine_tys(self.fields.infcx, self, a, b)?;
Ok(a)
}
}
@ -89,7 +89,7 @@ impl<'a, 'tcx> TypeRelation<'a,'tcx> for Equate<'a, 'tcx> {
-> RelateResult<'tcx, ty::Binder<T>>
where T: Relate<'a, 'tcx>
{
try!(self.fields.higher_ranked_sub(a, b));
self.fields.higher_ranked_sub(a, b)?;
self.fields.higher_ranked_sub(b, a)
}
}

View file

@ -78,8 +78,8 @@ impl<'a, 'tcx> LatticeDir<'a,'tcx> for Glb<'a, 'tcx> {
fn relate_bound(&self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> {
let mut sub = self.fields.sub();
try!(sub.relate(&v, &a));
try!(sub.relate(&v, &b));
sub.relate(&v, &a)?;
sub.relate(&v, &b)?;
Ok(())
}
}

View file

@ -75,7 +75,7 @@ impl<'a,'tcx> HigherRankedRelations<'a,'tcx> for CombineFields<'a,'tcx> {
debug!("b_prime={:?}", b_prime);
// Compare types now that bound regions have been replaced.
let result = try!(self.sub().relate(&a_prime, &b_prime));
let result = self.sub().relate(&a_prime, &b_prime)?;
// Presuming type comparison succeeds, we need to check
// that the skolemized regions do not "leak".
@ -118,7 +118,7 @@ impl<'a,'tcx> HigherRankedRelations<'a,'tcx> for CombineFields<'a,'tcx> {
// Collect constraints.
let result0 =
try!(self.lub().relate(&a_with_fresh, &b_with_fresh));
self.lub().relate(&a_with_fresh, &b_with_fresh)?;
let result0 =
self.infcx.resolve_type_vars_if_possible(&result0);
debug!("lub result0 = {:?}", result0);
@ -212,7 +212,7 @@ impl<'a,'tcx> HigherRankedRelations<'a,'tcx> for CombineFields<'a,'tcx> {
// Collect constraints.
let result0 =
try!(self.glb().relate(&a_with_fresh, &b_with_fresh));
self.glb().relate(&a_with_fresh, &b_with_fresh)?;
let result0 =
self.infcx.resolve_type_vars_if_possible(&result0);
debug!("glb result0 = {:?}", result0);

View file

@ -66,14 +66,14 @@ pub fn super_lattice_tys<'a,'tcx,L:LatticeDir<'a,'tcx>>(this: &mut L,
(&ty::TyInfer(TyVar(..)), &ty::TyInfer(TyVar(..)))
if infcx.type_var_diverges(a) && infcx.type_var_diverges(b) => {
let v = infcx.next_diverging_ty_var();
try!(this.relate_bound(v, a, b));
this.relate_bound(v, a, b)?;
Ok(v)
}
(&ty::TyInfer(TyVar(..)), _) |
(_, &ty::TyInfer(TyVar(..))) => {
let v = infcx.next_ty_var();
try!(this.relate_bound(v, a, b));
this.relate_bound(v, a, b)?;
Ok(v)
}

View file

@ -78,8 +78,8 @@ impl<'a, 'tcx> LatticeDir<'a,'tcx> for Lub<'a, 'tcx> {
fn relate_bound(&self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> {
let mut sub = self.fields.sub();
try!(sub.relate(&a, &v));
try!(sub.relate(&b, &v));
sub.relate(&a, &v)?;
sub.relate(&b, &v)?;
Ok(())
}
}

View file

@ -960,7 +960,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
let (ty::EquatePredicate(a, b), skol_map) =
self.skolemize_late_bound_regions(predicate, snapshot);
let origin = TypeOrigin::EquatePredicate(span);
let () = try!(mk_eqty(self, false, origin, a, b));
let () = mk_eqty(self, false, origin, a, b)?;
self.leak_check(&skol_map, snapshot)
})
}

View file

@ -75,13 +75,13 @@ impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Sub<'a, 'tcx> {
Ok(a)
}
(&ty::TyInfer(TyVar(a_id)), _) => {
try!(self.fields
self.fields
.switch_expected()
.instantiate(b, SupertypeOf, a_id));
.instantiate(b, SupertypeOf, a_id)?;
Ok(a)
}
(_, &ty::TyInfer(TyVar(b_id))) => {
try!(self.fields.instantiate(a, SubtypeOf, b_id));
self.fields.instantiate(a, SubtypeOf, b_id)?;
Ok(a)
}
@ -90,7 +90,7 @@ impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Sub<'a, 'tcx> {
}
_ => {
try!(combine::super_combine_tys(self.fields.infcx, self, a, b));
combine::super_combine_tys(self.fields.infcx, self, a, b)?;
Ok(a)
}
}

View file

@ -686,7 +686,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
for var_idx in 0..self.ir.num_vars {
let idx = node_base_idx + var_idx;
if test(idx).is_valid() {
try!(write!(wr, " {:?}", Variable(var_idx)));
write!(wr, " {:?}", Variable(var_idx))?;
}
}
Ok(())

View file

@ -378,7 +378,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
}
fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
let unadjusted_ty = try!(self.expr_ty(expr));
let unadjusted_ty = self.expr_ty(expr)?;
Ok(unadjusted_ty.adjust(
self.tcx(), expr.span, expr.id,
self.typer.adjustments().get(&expr.id),
@ -390,7 +390,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
}
fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
let base_ty = try!(self.typer.node_ty(pat.id));
let base_ty = self.typer.node_ty(pat.id)?;
// FIXME (Issue #18207): This code detects whether we are
// looking at a `ref x`, and if so, figures out what the type
// *being borrowed* is. But ideally we would put in a more
@ -436,7 +436,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
adjustment,
expr);
// Result is an rvalue.
let expr_ty = try!(self.expr_ty_adjusted(expr));
let expr_ty = self.expr_ty_adjusted(expr)?;
Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
}
}
@ -448,12 +448,12 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
expr: &hir::Expr,
autoderefs: usize)
-> McResult<cmt<'tcx>> {
let mut cmt = try!(self.cat_expr_unadjusted(expr));
let mut cmt = self.cat_expr_unadjusted(expr)?;
debug!("cat_expr_autoderefd: autoderefs={}, cmt={:?}",
autoderefs,
cmt);
for deref in 1..autoderefs + 1 {
cmt = try!(self.cat_deref(expr, cmt, deref, None));
cmt = self.cat_deref(expr, cmt, deref, None)?;
}
return Ok(cmt);
}
@ -461,15 +461,15 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
debug!("cat_expr: id={} expr={:?}", expr.id, expr);
let expr_ty = try!(self.expr_ty(expr));
let expr_ty = self.expr_ty(expr)?;
match expr.node {
hir::ExprUnary(hir::UnDeref, ref e_base) => {
let base_cmt = try!(self.cat_expr(&e_base));
let base_cmt = self.cat_expr(&e_base)?;
self.cat_deref(expr, base_cmt, 0, None)
}
hir::ExprField(ref base, f_name) => {
let base_cmt = try!(self.cat_expr(&base));
let base_cmt = self.cat_expr(&base)?;
debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
expr.id,
expr,
@ -478,7 +478,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
}
hir::ExprTupField(ref base, idx) => {
let base_cmt = try!(self.cat_expr(&base));
let base_cmt = self.cat_expr(&base)?;
Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
}
@ -509,7 +509,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
self.cat_deref_common(expr, base_cmt, 1, elem_ty, Some(context), true)
}
None => {
self.cat_index(expr, try!(self.cat_expr(&base)), context)
self.cat_index(expr, self.cat_expr(&base)?, context)
}
}
}
@ -575,7 +575,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
}
Def::Upvar(_, var_id, _, fn_node_id) => {
let ty = try!(self.node_ty(fn_node_id));
let ty = self.node_ty(fn_node_id)?;
match ty.sty {
ty::TyClosure(closure_id, _) => {
match self.typer.closure_kind(closure_id) {
@ -649,7 +649,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
let upvar_id = ty::UpvarId { var_id: var_id,
closure_expr_id: fn_node_id };
let var_ty = try!(self.node_ty(var_id));
let var_ty = self.node_ty(var_id)?;
// Mutability of original variable itself
let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
@ -921,7 +921,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
implicit: bool)
-> McResult<cmt<'tcx>>
{
let (m, cat) = match try!(deref_kind(base_cmt.ty, deref_context)) {
let (m, cat) = match deref_kind(base_cmt.ty, deref_context)? {
deref_ptr(ptr) => {
let ptr = if implicit {
match ptr {
@ -1030,7 +1030,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
context: InteriorOffsetKind)
-> McResult<cmt<'tcx>>
{
let ret = match try!(deref_kind(base_cmt.ty, Some(context))) {
let ret = match deref_kind(base_cmt.ty, Some(context))? {
deref_ptr(ptr) => {
// for unique ptrs, we inherit mutability from the
// owning reference.
@ -1069,13 +1069,13 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
vec_cmt: cmt<'tcx>,
slice_pat: &hir::Pat)
-> McResult<(cmt<'tcx>, hir::Mutability, ty::Region)> {
let slice_ty = try!(self.node_ty(slice_pat.id));
let slice_ty = self.node_ty(slice_pat.id)?;
let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
slice_pat,
slice_ty);
let context = InteriorOffsetKind::Pattern;
let cmt_vec = try!(self.deref_vec(slice_pat, vec_cmt, context));
let cmt_slice = try!(self.cat_index(slice_pat, cmt_vec, context));
let cmt_vec = self.deref_vec(slice_pat, vec_cmt, context)?;
let cmt_slice = self.cat_index(slice_pat, cmt_vec, context)?;
return Ok((cmt_slice, slice_mutbl, slice_r));
/// In a pattern like [a, b, ..c], normally `c` has slice type, but if you have [a, b,
@ -1235,29 +1235,29 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
Some(Def::Variant(..)) => {
// variant(x, y, z)
for (i, subpat) in subpats.iter().enumerate() {
let subpat_ty = try!(self.pat_ty(&subpat)); // see (*2)
let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
let subcmt =
self.cat_imm_interior(
pat, cmt.clone(), subpat_ty,
InteriorField(PositionalField(i)));
try!(self.cat_pattern_(subcmt, &subpat, op));
self.cat_pattern_(subcmt, &subpat, op)?;
}
}
Some(Def::Struct(..)) => {
for (i, subpat) in subpats.iter().enumerate() {
let subpat_ty = try!(self.pat_ty(&subpat)); // see (*2)
let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
let cmt_field =
self.cat_imm_interior(
pat, cmt.clone(), subpat_ty,
InteriorField(PositionalField(i)));
try!(self.cat_pattern_(cmt_field, &subpat, op));
self.cat_pattern_(cmt_field, &subpat, op)?;
}
}
Some(Def::Const(..)) | Some(Def::AssociatedConst(..)) => {
for subpat in subpats {
try!(self.cat_pattern_(cmt.clone(), &subpat, op));
self.cat_pattern_(cmt.clone(), &subpat, op)?;
}
}
_ => {
@ -1273,27 +1273,27 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
}
PatKind::Ident(_, _, Some(ref subpat)) => {
try!(self.cat_pattern_(cmt, &subpat, op));
self.cat_pattern_(cmt, &subpat, op)?;
}
PatKind::Struct(_, ref field_pats, _) => {
// {f1: p1, ..., fN: pN}
for fp in field_pats {
let field_ty = try!(self.pat_ty(&fp.node.pat)); // see (*2)
let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
try!(self.cat_pattern_(cmt_field, &fp.node.pat, op));
self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
}
}
PatKind::Tup(ref subpats) => {
// (p1, ..., pN)
for (i, subpat) in subpats.iter().enumerate() {
let subpat_ty = try!(self.pat_ty(&subpat)); // see (*2)
let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
let subcmt =
self.cat_imm_interior(
pat, cmt.clone(), subpat_ty,
InteriorField(PositionalField(i)));
try!(self.cat_pattern_(subcmt, &subpat, op));
self.cat_pattern_(subcmt, &subpat, op)?;
}
}
@ -1301,24 +1301,24 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
// box p1, &p1, &mut p1. we can ignore the mutability of
// PatKind::Ref since that information is already contained
// in the type.
let subcmt = try!(self.cat_deref(pat, cmt, 0, None));
try!(self.cat_pattern_(subcmt, &subpat, op));
let subcmt = self.cat_deref(pat, cmt, 0, None)?;
self.cat_pattern_(subcmt, &subpat, op)?;
}
PatKind::Vec(ref before, ref slice, ref after) => {
let context = InteriorOffsetKind::Pattern;
let vec_cmt = try!(self.deref_vec(pat, cmt, context));
let elt_cmt = try!(self.cat_index(pat, vec_cmt, context));
let vec_cmt = self.deref_vec(pat, cmt, context)?;
let elt_cmt = self.cat_index(pat, vec_cmt, context)?;
for before_pat in before {
try!(self.cat_pattern_(elt_cmt.clone(), &before_pat, op));
self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
}
if let Some(ref slice_pat) = *slice {
let slice_ty = try!(self.pat_ty(&slice_pat));
let slice_ty = self.pat_ty(&slice_pat)?;
let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
try!(self.cat_pattern_(slice_cmt, &slice_pat, op));
self.cat_pattern_(slice_cmt, &slice_pat, op)?;
}
for after_pat in after {
try!(self.cat_pattern_(elt_cmt.clone(), &after_pat, op));
self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
}
}

View file

@ -41,15 +41,15 @@ pub struct CodeExtent(u32);
impl fmt::Debug for CodeExtent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "CodeExtent({:?}", self.0));
write!(f, "CodeExtent({:?}", self.0)?;
try!(ty::tls::with_opt(|opt_tcx| {
ty::tls::with_opt(|opt_tcx| {
if let Some(tcx) = opt_tcx {
let data = tcx.region_maps.code_extents.borrow()[self.0 as usize];
try!(write!(f, "/{:?}", data));
write!(f, "/{:?}", data)?;
}
Ok(())
}));
})?;
write!(f, ")")
}

View file

@ -102,7 +102,7 @@ pub fn krate(sess: &Session,
let _task = hir_map.dep_graph.in_task(DepNode::ResolveLifetimes);
let krate = hir_map.krate();
let mut named_region_map = NodeMap();
try!(sess.track_errors(|| {
sess.track_errors(|| {
krate.visit_all_items(&mut LifetimeContext {
sess: sess,
named_region_map: &mut named_region_map,
@ -111,7 +111,7 @@ pub fn krate(sess: &Session,
trait_ref_hack: false,
labels_in_fn: vec![],
});
}));
})?;
Ok(named_region_map)
}

View file

@ -211,7 +211,7 @@ impl<'tcx> FulfillmentContext<'tcx> {
infcx: &InferCtxt<'a,'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
try!(self.select_where_possible(infcx));
self.select_where_possible(infcx)?;
let errors: Vec<_> =
self.predicates.to_errors(CodeAmbiguity)
.into_iter()

View file

@ -320,12 +320,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
let _task = self.tcx().dep_graph.in_task(dep_node);
let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
match try!(self.candidate_from_obligation(&stack)) {
match self.candidate_from_obligation(&stack)? {
None => {
self.consider_unification_despite_ambiguity(obligation);
Ok(None)
}
Some(candidate) => Ok(Some(try!(self.confirm_candidate(obligation, candidate)))),
Some(candidate) => Ok(Some(self.confirm_candidate(obligation, candidate)?)),
}
}
@ -786,7 +786,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
return Ok(None);
}
let candidate_set = try!(self.assemble_candidates(stack));
let candidate_set = self.assemble_candidates(stack)?;
if candidate_set.ambiguous {
debug!("candidate set contains ambig");
@ -1034,19 +1034,19 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
// User-defined copy impls are permitted, but only for
// structs and enums.
try!(self.assemble_candidates_from_impls(obligation, &mut candidates));
self.assemble_candidates_from_impls(obligation, &mut candidates)?;
// For other types, we'll use the builtin rules.
try!(self.assemble_builtin_bound_candidates(ty::BoundCopy,
self.assemble_builtin_bound_candidates(ty::BoundCopy,
obligation,
&mut candidates));
&mut candidates)?;
}
Some(bound @ ty::BoundSized) => {
// Sized is never implementable by end-users, it is
// always automatically computed.
try!(self.assemble_builtin_bound_candidates(bound,
self.assemble_builtin_bound_candidates(bound,
obligation,
&mut candidates));
&mut candidates)?;
}
None if self.tcx().lang_items.unsize_trait() ==
@ -1057,19 +1057,19 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
Some(ty::BoundSend) |
Some(ty::BoundSync) |
None => {
try!(self.assemble_closure_candidates(obligation, &mut candidates));
try!(self.assemble_fn_pointer_candidates(obligation, &mut candidates));
try!(self.assemble_candidates_from_impls(obligation, &mut candidates));
self.assemble_closure_candidates(obligation, &mut candidates)?;
self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
self.assemble_candidates_from_impls(obligation, &mut candidates)?;
self.assemble_candidates_from_object_ty(obligation, &mut candidates);
}
}
self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
try!(self.assemble_candidates_from_caller_bounds(stack, &mut candidates));
self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
// Default implementations have lower priority, so we only
// consider triggering a default if there is no other impl that can apply.
if candidates.vec.is_empty() {
try!(self.assemble_candidates_from_default_impls(obligation, &mut candidates));
self.assemble_candidates_from_default_impls(obligation, &mut candidates)?;
}
debug!("candidate list size: {}", candidates.vec.len());
Ok(candidates)
@ -2044,7 +2044,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
match candidate {
BuiltinCandidate(builtin_bound) => {
Ok(VtableBuiltin(
try!(self.confirm_builtin_candidate(obligation, builtin_bound))))
self.confirm_builtin_candidate(obligation, builtin_bound)?))
}
ParamCandidate(param) => {
@ -2064,13 +2064,13 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
ImplCandidate(impl_def_id) => {
let vtable_impl =
try!(self.confirm_impl_candidate(obligation, impl_def_id));
self.confirm_impl_candidate(obligation, impl_def_id)?;
Ok(VtableImpl(vtable_impl))
}
ClosureCandidate(closure_def_id, substs) => {
let vtable_closure =
try!(self.confirm_closure_candidate(obligation, closure_def_id, substs));
self.confirm_closure_candidate(obligation, closure_def_id, substs)?;
Ok(VtableClosure(vtable_closure))
}
@ -2090,7 +2090,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
FnPointerCandidate => {
let fn_type =
try!(self.confirm_fn_pointer_candidate(obligation));
self.confirm_fn_pointer_candidate(obligation)?;
Ok(VtableFnPointer(fn_type))
}
@ -2100,7 +2100,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
}
BuiltinUnsizeCandidate => {
let data = try!(self.confirm_builtin_unsize_candidate(obligation));
let data = self.confirm_builtin_unsize_candidate(obligation)?;
Ok(VtableBuiltin(data))
}
}
@ -2152,7 +2152,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
debug!("confirm_builtin_candidate({:?})",
obligation);
match try!(self.builtin_bound(bound, obligation)) {
match self.builtin_bound(bound, obligation)? {
If(nested) => Ok(self.vtable_builtin_data(obligation, bound, nested)),
AmbiguousBuiltin | ParameterBuiltin => {
self.tcx().sess.span_bug(
@ -2421,9 +2421,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
util::TupleArgumentsFlag::Yes)
.map_bound(|(trait_ref, _)| trait_ref);
try!(self.confirm_poly_trait_refs(obligation.cause.clone(),
self.confirm_poly_trait_refs(obligation.cause.clone(),
obligation.predicate.to_poly_trait_ref(),
trait_ref));
trait_ref)?;
Ok(self_ty)
}
@ -2449,9 +2449,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
trait_ref,
obligations);
try!(self.confirm_poly_trait_refs(obligation.cause.clone(),
self.confirm_poly_trait_refs(obligation.cause.clone(),
obligation.predicate.to_poly_trait_ref(),
trait_ref));
trait_ref)?;
Ok(VtableClosureData {
closure_def_id: closure_def_id,
@ -2795,7 +2795,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
-> Result<Vec<PredicateObligation<'tcx>>,()>
{
try!(self.match_poly_trait_ref(obligation, where_clause_trait_ref));
self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
Ok(Vec::new())
}

View file

@ -418,7 +418,7 @@ pub fn predicate_for_builtin_bound<'tcx>(
param_ty: Ty<'tcx>)
-> Result<PredicateObligation<'tcx>, ErrorReported>
{
let trait_ref = try!(trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty));
let trait_ref = trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty)?;
Ok(predicate_for_trait_ref(cause, trait_ref, recursion_depth))
}

View file

@ -91,6 +91,6 @@ impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Match<'a, 'tcx> {
-> RelateResult<'tcx, ty::Binder<T>>
where T: Relate<'a,'tcx>
{
Ok(ty::Binder(try!(self.relate(a.skip_binder(), b.skip_binder()))))
Ok(ty::Binder(self.relate(a.skip_binder(), b.skip_binder())?))
}
}

View file

@ -1473,7 +1473,7 @@ impl<'tcx> Encodable for AdtDef<'tcx> {
impl<'tcx> Decodable for AdtDef<'tcx> {
fn decode<D: Decoder>(d: &mut D) -> Result<AdtDef<'tcx>, D::Error> {
let def_id: DefId = try!{ Decodable::decode(d) };
let def_id: DefId = Decodable::decode(d)?;
cstore::tls::with_decoding_context(d, |dcx, _| {
let def_id = dcx.translate_def_id(def_id);

View file

@ -108,7 +108,7 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::TypeAndMut<'tcx> {
ast::Mutability::MutImmutable => ty::Covariant,
ast::Mutability::MutMutable => ty::Invariant,
};
let ty = try!(relation.relate_with_variance(variance, &a.ty, &b.ty));
let ty = relation.relate_with_variance(variance, &a.ty, &b.ty)?;
Ok(ty::TypeAndMut {ty: ty, mutbl: mutbl})
}
}
@ -152,7 +152,7 @@ pub fn relate_substs<'a,'tcx:'a,R>(relation: &mut R,
let a_tps = a_subst.types.get_slice(space);
let b_tps = b_subst.types.get_slice(space);
let t_variances = variances.map(|v| v.types.get_slice(space));
let tps = try!(relate_type_params(relation, t_variances, a_tps, b_tps));
let tps = relate_type_params(relation, t_variances, a_tps, b_tps)?;
substs.types.replace(space, tps);
}
@ -166,10 +166,10 @@ pub fn relate_substs<'a,'tcx:'a,R>(relation: &mut R,
let a_regions = a.get_slice(space);
let b_regions = b.get_slice(space);
let r_variances = variances.map(|v| v.regions.get_slice(space));
let regions = try!(relate_region_params(relation,
let regions = relate_region_params(relation,
r_variances,
a_regions,
b_regions));
b_regions)?;
substs.mut_regions().replace(space, regions);
}
}
@ -239,9 +239,9 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::BareFnTy<'tcx> {
-> RelateResult<'tcx, ty::BareFnTy<'tcx>>
where R: TypeRelation<'a,'tcx>
{
let unsafety = try!(relation.relate(&a.unsafety, &b.unsafety));
let abi = try!(relation.relate(&a.abi, &b.abi));
let sig = try!(relation.relate(&a.sig, &b.sig));
let unsafety = relation.relate(&a.unsafety, &b.unsafety)?;
let abi = relation.relate(&a.abi, &b.abi)?;
let sig = relation.relate(&a.sig, &b.sig)?;
Ok(ty::BareFnTy {unsafety: unsafety,
abi: abi,
sig: sig})
@ -260,19 +260,19 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::FnSig<'tcx> {
expected_found(relation, &a.variadic, &b.variadic)));
}
let inputs = try!(relate_arg_vecs(relation,
let inputs = relate_arg_vecs(relation,
&a.inputs,
&b.inputs));
&b.inputs)?;
let output = try!(match (a.output, b.output) {
let output = match (a.output, b.output) {
(ty::FnConverging(a_ty), ty::FnConverging(b_ty)) =>
Ok(ty::FnConverging(try!(relation.relate(&a_ty, &b_ty)))),
Ok(ty::FnConverging(relation.relate(&a_ty, &b_ty)?)),
(ty::FnDiverging, ty::FnDiverging) =>
Ok(ty::FnDiverging),
(a, b) =>
Err(TypeError::ConvergenceMismatch(
expected_found(relation, &(a != ty::FnDiverging), &(b != ty::FnDiverging)))),
});
}?;
return Ok(ty::FnSig {inputs: inputs,
output: output,
@ -336,7 +336,7 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::ProjectionTy<'tcx> {
Err(TypeError::ProjectionNameMismatched(
expected_found(relation, &a.item_name, &b.item_name)))
} else {
let trait_ref = try!(relation.relate(&a.trait_ref, &b.trait_ref));
let trait_ref = relation.relate(&a.trait_ref, &b.trait_ref)?;
Ok(ty::ProjectionTy { trait_ref: trait_ref, item_name: a.item_name })
}
}
@ -349,8 +349,8 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::ProjectionPredicate<'tcx> {
-> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>>
where R: TypeRelation<'a,'tcx>
{
let projection_ty = try!(relation.relate(&a.projection_ty, &b.projection_ty));
let ty = try!(relation.relate(&a.ty, &b.ty));
let projection_ty = relation.relate(&a.projection_ty, &b.projection_ty)?;
let ty = relation.relate(&a.ty, &b.ty)?;
Ok(ty::ProjectionPredicate { projection_ty: projection_ty, ty: ty })
}
}
@ -385,13 +385,13 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::ExistentialBounds<'tcx> {
where R: TypeRelation<'a,'tcx>
{
let r =
try!(relation.with_cause(
relation.with_cause(
Cause::ExistentialRegionBound,
|relation| relation.relate_with_variance(ty::Contravariant,
&a.region_bound,
&b.region_bound)));
let nb = try!(relation.relate(&a.builtin_bounds, &b.builtin_bounds));
let pb = try!(relation.relate(&a.projection_bounds, &b.projection_bounds));
&b.region_bound))?;
let nb = relation.relate(&a.builtin_bounds, &b.builtin_bounds)?;
let pb = relation.relate(&a.projection_bounds, &b.projection_bounds)?;
Ok(ty::ExistentialBounds { region_bound: r,
builtin_bounds: nb,
projection_bounds: pb })
@ -426,7 +426,7 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::TraitRef<'tcx> {
if a.def_id != b.def_id {
Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
} else {
let substs = try!(relate_item_substs(relation, a.def_id, a.substs, b.substs));
let substs = relate_item_substs(relation, a.def_id, a.substs, b.substs)?;
Ok(ty::TraitRef { def_id: a.def_id, substs: relation.tcx().mk_substs(substs) })
}
}
@ -489,21 +489,21 @@ pub fn super_relate_tys<'a,'tcx:'a,R>(relation: &mut R,
(&ty::TyEnum(a_def, a_substs), &ty::TyEnum(b_def, b_substs))
if a_def == b_def =>
{
let substs = try!(relate_item_substs(relation, a_def.did, a_substs, b_substs));
let substs = relate_item_substs(relation, a_def.did, a_substs, b_substs)?;
Ok(tcx.mk_enum(a_def, tcx.mk_substs(substs)))
}
(&ty::TyTrait(ref a_), &ty::TyTrait(ref b_)) =>
{
let principal = try!(relation.relate(&a_.principal, &b_.principal));
let bounds = try!(relation.relate(&a_.bounds, &b_.bounds));
let principal = relation.relate(&a_.principal, &b_.principal)?;
let bounds = relation.relate(&a_.bounds, &b_.bounds)?;
Ok(tcx.mk_trait(principal, bounds))
}
(&ty::TyStruct(a_def, a_substs), &ty::TyStruct(b_def, b_substs))
if a_def == b_def =>
{
let substs = try!(relate_item_substs(relation, a_def.did, a_substs, b_substs));
let substs = relate_item_substs(relation, a_def.did, a_substs, b_substs)?;
Ok(tcx.mk_struct(a_def, tcx.mk_substs(substs)))
}
@ -514,32 +514,32 @@ pub fn super_relate_tys<'a,'tcx:'a,R>(relation: &mut R,
// All TyClosure types with the same id represent
// the (anonymous) type of the same closure expression. So
// all of their regions should be equated.
let substs = try!(relation.relate(a_substs, b_substs));
let substs = relation.relate(a_substs, b_substs)?;
Ok(tcx.mk_closure_from_closure_substs(a_id, substs))
}
(&ty::TyBox(a_inner), &ty::TyBox(b_inner)) =>
{
let typ = try!(relation.relate(&a_inner, &b_inner));
let typ = relation.relate(&a_inner, &b_inner)?;
Ok(tcx.mk_box(typ))
}
(&ty::TyRawPtr(ref a_mt), &ty::TyRawPtr(ref b_mt)) =>
{
let mt = try!(relation.relate(a_mt, b_mt));
let mt = relation.relate(a_mt, b_mt)?;
Ok(tcx.mk_ptr(mt))
}
(&ty::TyRef(a_r, ref a_mt), &ty::TyRef(b_r, ref b_mt)) =>
{
let r = try!(relation.relate_with_variance(ty::Contravariant, a_r, b_r));
let mt = try!(relation.relate(a_mt, b_mt));
let r = relation.relate_with_variance(ty::Contravariant, a_r, b_r)?;
let mt = relation.relate(a_mt, b_mt)?;
Ok(tcx.mk_ref(tcx.mk_region(r), mt))
}
(&ty::TyArray(a_t, sz_a), &ty::TyArray(b_t, sz_b)) =>
{
let t = try!(relation.relate(&a_t, &b_t));
let t = relation.relate(&a_t, &b_t)?;
if sz_a == sz_b {
Ok(tcx.mk_array(t, sz_a))
} else {
@ -549,16 +549,16 @@ pub fn super_relate_tys<'a,'tcx:'a,R>(relation: &mut R,
(&ty::TySlice(a_t), &ty::TySlice(b_t)) =>
{
let t = try!(relation.relate(&a_t, &b_t));
let t = relation.relate(&a_t, &b_t)?;
Ok(tcx.mk_slice(t))
}
(&ty::TyTuple(ref as_), &ty::TyTuple(ref bs)) =>
{
if as_.len() == bs.len() {
let ts = try!(as_.iter().zip(bs)
let ts = as_.iter().zip(bs)
.map(|(a, b)| relation.relate(a, b))
.collect::<Result<_, _>>());
.collect::<Result<_, _>>()?;
Ok(tcx.mk_tup(ts))
} else if !(as_.is_empty() || bs.is_empty()) {
Err(TypeError::TupleSize(
@ -572,20 +572,20 @@ pub fn super_relate_tys<'a,'tcx:'a,R>(relation: &mut R,
&ty::TyFnDef(b_def_id, b_substs, b_fty))
if a_def_id == b_def_id =>
{
let substs = try!(relate_substs(relation, None, a_substs, b_substs));
let fty = try!(relation.relate(a_fty, b_fty));
let substs = relate_substs(relation, None, a_substs, b_substs)?;
let fty = relation.relate(a_fty, b_fty)?;
Ok(tcx.mk_fn_def(a_def_id, tcx.mk_substs(substs), fty))
}
(&ty::TyFnPtr(a_fty), &ty::TyFnPtr(b_fty)) =>
{
let fty = try!(relation.relate(a_fty, b_fty));
let fty = relation.relate(a_fty, b_fty)?;
Ok(tcx.mk_fn_ptr(fty))
}
(&ty::TyProjection(ref a_data), &ty::TyProjection(ref b_data)) =>
{
let projection_ty = try!(relation.relate(a_data, b_data));
let projection_ty = relation.relate(a_data, b_data)?;
Ok(tcx.mk_projection(projection_ty.trait_ref, projection_ty.item_name))
}
@ -603,8 +603,8 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::ClosureSubsts<'tcx> {
-> RelateResult<'tcx, ty::ClosureSubsts<'tcx>>
where R: TypeRelation<'a,'tcx>
{
let func_substs = try!(relate_substs(relation, None, a.func_substs, b.func_substs));
let upvar_tys = try!(relation.relate_zip(&a.upvar_tys, &b.upvar_tys));
let func_substs = relate_substs(relation, None, a.func_substs, b.func_substs)?;
let upvar_tys = relation.relate_zip(&a.upvar_tys, &b.upvar_tys)?;
Ok(ty::ClosureSubsts { func_substs: relation.tcx().mk_substs(func_substs),
upvar_tys: upvar_tys })
}
@ -645,7 +645,7 @@ impl<'a,'tcx:'a,T> Relate<'a,'tcx> for Rc<T>
{
let a: &T = a;
let b: &T = b;
Ok(Rc::new(try!(relation.relate(a, b))))
Ok(Rc::new(relation.relate(a, b)?))
}
}
@ -660,7 +660,7 @@ impl<'a,'tcx:'a,T> Relate<'a,'tcx> for Box<T>
{
let a: &T = a;
let b: &T = b;
Ok(Box::new(try!(relation.relate(a, b))))
Ok(Box::new(relation.relate(a, b)?))
}
}

View file

@ -250,7 +250,7 @@ pub struct ClosureSubsts<'tcx> {
impl<'tcx> Decodable for &'tcx ClosureSubsts<'tcx> {
fn decode<S: Decoder>(s: &mut S) -> Result<&'tcx ClosureSubsts<'tcx>, S::Error> {
let closure_substs = try! { Decodable::decode(s) };
let closure_substs = Decodable::decode(s)?;
let dummy_def_id: DefId = unsafe { mem::zeroed() };
cstore::tls::with_decoding_context(s, |dcx, _| {

View file

@ -356,7 +356,7 @@ impl<'tcx> BasicBlockData<'tcx> {
impl<'tcx> Debug for Terminator<'tcx> {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
try!(self.fmt_head(fmt));
self.fmt_head(fmt)?;
let successors = self.successors();
let labels = self.fmt_successor_labels();
assert_eq!(successors.len(), labels.len());
@ -367,12 +367,12 @@ impl<'tcx> Debug for Terminator<'tcx> {
1 => write!(fmt, " -> {:?}", successors[0]),
_ => {
try!(write!(fmt, " -> ["));
write!(fmt, " -> [")?;
for (i, target) in successors.iter().enumerate() {
if i > 0 {
try!(write!(fmt, ", "));
write!(fmt, ", ")?;
}
try!(write!(fmt, "{}: {:?}", labels[i], target));
write!(fmt, "{}: {:?}", labels[i], target)?;
}
write!(fmt, "]")
}
@ -397,14 +397,14 @@ impl<'tcx> Terminator<'tcx> {
Drop { ref value, .. } => write!(fmt, "drop({:?})", value),
Call { ref func, ref args, ref destination, .. } => {
if let Some((ref destination, _)) = *destination {
try!(write!(fmt, "{:?} = ", destination));
write!(fmt, "{:?} = ", destination)?;
}
try!(write!(fmt, "{:?}(", func));
write!(fmt, "{:?}(", func)?;
for (index, arg) in args.iter().enumerate() {
if index > 0 {
try!(write!(fmt, ", "));
write!(fmt, ", ")?;
}
try!(write!(fmt, "{:?}", arg));
write!(fmt, "{:?}", arg)?;
}
write!(fmt, ")")
}
@ -808,11 +808,11 @@ impl<'tcx> Debug for Rvalue<'tcx> {
Adt(adt_def, variant, substs) => {
let variant_def = &adt_def.variants[variant];
try!(ppaux::parameterized(fmt, substs, variant_def.did,
ppaux::parameterized(fmt, substs, variant_def.did,
ppaux::Ns::Value, &[],
|tcx| {
tcx.lookup_item_type(variant_def.did).generics
}));
})?;
match variant_def.kind() {
ty::VariantKind::Unit => Ok(()),
@ -903,7 +903,7 @@ impl<'tcx> Debug for Literal<'tcx> {
|tcx| tcx.lookup_item_type(def_id).generics)
}
Value { ref value } => {
try!(write!(fmt, "const "));
write!(fmt, "const ")?;
fmt_const_val(fmt, value)
}
}

View file

@ -34,23 +34,23 @@ fn fn_sig(f: &mut fmt::Formatter,
variadic: bool,
output: ty::FnOutput)
-> fmt::Result {
try!(write!(f, "("));
write!(f, "(")?;
let mut inputs = inputs.iter();
if let Some(&ty) = inputs.next() {
try!(write!(f, "{}", ty));
write!(f, "{}", ty)?;
for &ty in inputs {
try!(write!(f, ", {}", ty));
write!(f, ", {}", ty)?;
}
if variadic {
try!(write!(f, ", ..."));
write!(f, ", ...")?;
}
}
try!(write!(f, ")"));
write!(f, ")")?;
match output {
ty::FnConverging(ty) => {
if !ty.is_nil() {
try!(write!(f, " -> {}", ty));
write!(f, " -> {}", ty)?;
}
Ok(())
}
@ -77,10 +77,10 @@ pub fn parameterized<GG>(f: &mut fmt::Formatter,
where GG: for<'tcx> FnOnce(&TyCtxt<'tcx>) -> ty::Generics<'tcx>
{
if let (Ns::Value, Some(self_ty)) = (ns, substs.self_ty()) {
try!(write!(f, "<{} as ", self_ty));
write!(f, "<{} as ", self_ty)?;
}
let (fn_trait_kind, verbose, last_name) = try!(ty::tls::with(|tcx| {
let (fn_trait_kind, verbose, last_name) = ty::tls::with(|tcx| {
let (did, last_name) = if ns == Ns::Value {
// Try to get the impl/trait parent, if this is an
// associated value item (method or constant).
@ -89,9 +89,9 @@ pub fn parameterized<GG>(f: &mut fmt::Formatter,
} else {
(did, None)
};
try!(write!(f, "{}", tcx.item_path_str(did)));
write!(f, "{}", tcx.item_path_str(did))?;
Ok((tcx.lang_items.fn_trait_kind(did), tcx.sess.verbose(), last_name))
}));
})?;
let mut empty = true;
let mut start_or_continue = |f: &mut fmt::Formatter, start: &str, cont: &str| {
@ -106,25 +106,25 @@ pub fn parameterized<GG>(f: &mut fmt::Formatter,
if verbose {
match substs.regions {
subst::ErasedRegions => {
try!(start_or_continue(f, "<", ", "));
try!(write!(f, ".."));
start_or_continue(f, "<", ", ")?;
write!(f, "..")?;
}
subst::NonerasedRegions(ref regions) => {
for region in regions {
try!(start_or_continue(f, "<", ", "));
try!(write!(f, "{:?}", region));
start_or_continue(f, "<", ", ")?;
write!(f, "{:?}", region)?;
}
}
}
for &ty in &substs.types {
try!(start_or_continue(f, "<", ", "));
try!(write!(f, "{}", ty));
start_or_continue(f, "<", ", ")?;
write!(f, "{}", ty)?;
}
for projection in projections {
try!(start_or_continue(f, "<", ", "));
try!(write!(f, "{}={}",
start_or_continue(f, "<", ", ")?;
write!(f, "{}={}",
projection.projection_ty.item_name,
projection.ty));
projection.ty)?;
}
return start_or_continue(f, "", ">");
}
@ -140,7 +140,7 @@ pub fn parameterized<GG>(f: &mut fmt::Formatter,
subst::ErasedRegions => { }
subst::NonerasedRegions(ref regions) => {
for &r in regions {
try!(start_or_continue(f, "<", ", "));
start_or_continue(f, "<", ", ")?;
let s = r.to_string();
if s.is_empty() {
// This happens when the value of the region
@ -148,9 +148,9 @@ pub fn parameterized<GG>(f: &mut fmt::Formatter,
// because the user omitted it in the first place,
// or because it refers to some block in the code,
// etc. I'm not sure how best to serialize this.
try!(write!(f, "'_"));
write!(f, "'_")?;
} else {
try!(write!(f, "{}", s));
write!(f, "{}", s)?;
}
}
}
@ -194,35 +194,35 @@ pub fn parameterized<GG>(f: &mut fmt::Formatter,
});
for &ty in &tps[..tps.len() - num_defaults] {
try!(start_or_continue(f, "<", ", "));
try!(write!(f, "{}", ty));
start_or_continue(f, "<", ", ")?;
write!(f, "{}", ty)?;
}
for projection in projections {
try!(start_or_continue(f, "<", ", "));
try!(write!(f, "{}={}",
start_or_continue(f, "<", ", ")?;
write!(f, "{}={}",
projection.projection_ty.item_name,
projection.ty));
projection.ty)?;
}
try!(start_or_continue(f, "", ">"));
start_or_continue(f, "", ">")?;
// For values, also print their name and type parameters.
if ns == Ns::Value {
if substs.self_ty().is_some() {
try!(write!(f, ">"));
write!(f, ">")?;
}
if let Some(name) = last_name {
try!(write!(f, "::{}", name));
write!(f, "::{}", name)?;
}
let tps = substs.types.get_slice(subst::FnSpace);
if !tps.is_empty() {
try!(write!(f, "::<{}", tps[0]));
write!(f, "::<{}", tps[0])?;
for ty in &tps[1..] {
try!(write!(f, ", {}", ty));
write!(f, ", {}", ty)?;
}
try!(write!(f, ">"));
write!(f, ">")?;
}
}
@ -273,7 +273,7 @@ fn in_binder<'tcx, T, U>(f: &mut fmt::Formatter,
})
}).0;
try!(start_or_continue(f, "", "> "));
start_or_continue(f, "", "> ")?;
write!(f, "{}", new_value)
}
@ -317,7 +317,7 @@ impl<'tcx> fmt::Display for ty::TraitTy<'tcx> {
let bounds = &self.bounds;
// Generate the main trait ref, including associated types.
try!(ty::tls::with(|tcx| {
ty::tls::with(|tcx| {
let principal = tcx.lift(&self.principal.0)
.expect("could not lift TraitRef for printing");
let projections = tcx.lift(&bounds.projection_bounds[..])
@ -326,11 +326,11 @@ impl<'tcx> fmt::Display for ty::TraitTy<'tcx> {
let tap = ty::Binder(TraitAndProjections(principal, projections));
in_binder(f, tcx, &ty::Binder(""), Some(tap))
}));
})?;
// Builtin bounds.
for bound in &bounds.builtin_bounds {
try!(write!(f, " + {:?}", bound));
write!(f, " + {:?}", bound)?;
}
// FIXME: It'd be nice to compute from context when this bound
@ -340,7 +340,7 @@ impl<'tcx> fmt::Display for ty::TraitTy<'tcx> {
// people aware that it's there.
let bound = bounds.region_bound.to_string();
if !bound.is_empty() {
try!(write!(f, " + {}", bound));
write!(f, " + {}", bound)?;
}
Ok(())
@ -648,19 +648,19 @@ impl<'tcx> fmt::Debug for ty::InstantiatedPredicates<'tcx> {
impl<'tcx> fmt::Debug for ty::ImplOrTraitItem<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "ImplOrTraitItem("));
try!(match *self {
write!(f, "ImplOrTraitItem(")?;
match *self {
ty::ImplOrTraitItem::MethodTraitItem(ref i) => write!(f, "{:?}", i),
ty::ImplOrTraitItem::ConstTraitItem(ref i) => write!(f, "{:?}", i),
ty::ImplOrTraitItem::TypeTraitItem(ref i) => write!(f, "{:?}", i),
});
}?;
write!(f, ")")
}
}
impl<'tcx> fmt::Display for ty::FnSig<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "fn"));
write!(f, "fn")?;
fn_sig(f, &self.inputs, self.variadic, self.output)
}
}
@ -679,18 +679,18 @@ impl<'tcx> fmt::Debug for ty::ExistentialBounds<'tcx> {
let region_str = format!("{:?}", self.region_bound);
if !region_str.is_empty() {
try!(maybe_continue(f));
try!(write!(f, "{}", region_str));
maybe_continue(f)?;
write!(f, "{}", region_str)?;
}
for bound in &self.builtin_bounds {
try!(maybe_continue(f));
try!(write!(f, "{:?}", bound));
maybe_continue(f)?;
write!(f, "{:?}", bound)?;
}
for projection_bound in &self.projection_bounds {
try!(maybe_continue(f));
try!(write!(f, "{:?}", projection_bound));
maybe_continue(f)?;
write!(f, "{:?}", projection_bound)?;
}
Ok(())
@ -701,9 +701,9 @@ impl fmt::Display for ty::BuiltinBounds {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut bounds = self.iter();
if let Some(bound) = bounds.next() {
try!(write!(f, "{:?}", bound));
write!(f, "{:?}", bound)?;
for bound in bounds {
try!(write!(f, " + {:?}", bound));
write!(f, " + {:?}", bound)?;
}
}
Ok(())
@ -832,23 +832,23 @@ impl<'tcx> fmt::Display for ty::TypeVariants<'tcx> {
}, tm.ty)
}
TyRef(r, ref tm) => {
try!(write!(f, "&"));
write!(f, "&")?;
let s = r.to_string();
try!(write!(f, "{}", s));
write!(f, "{}", s)?;
if !s.is_empty() {
try!(write!(f, " "));
write!(f, " ")?;
}
write!(f, "{}", tm)
}
TyTuple(ref tys) => {
try!(write!(f, "("));
write!(f, "(")?;
let mut tys = tys.iter();
if let Some(&ty) = tys.next() {
try!(write!(f, "{},", ty));
write!(f, "{},", ty)?;
if let Some(&ty) = tys.next() {
try!(write!(f, " {}", ty));
write!(f, " {}", ty)?;
for &ty in tys {
try!(write!(f, ", {}", ty));
write!(f, ", {}", ty)?;
}
}
}
@ -856,25 +856,25 @@ impl<'tcx> fmt::Display for ty::TypeVariants<'tcx> {
}
TyFnDef(def_id, substs, ref bare_fn) => {
if bare_fn.unsafety == hir::Unsafety::Unsafe {
try!(write!(f, "unsafe "));
write!(f, "unsafe ")?;
}
if bare_fn.abi != Abi::Rust {
try!(write!(f, "extern {} ", bare_fn.abi));
write!(f, "extern {} ", bare_fn.abi)?;
}
try!(write!(f, "{} {{", bare_fn.sig.0));
try!(parameterized(f, substs, def_id, Ns::Value, &[],
|tcx| tcx.lookup_item_type(def_id).generics));
write!(f, "{} {{", bare_fn.sig.0)?;
parameterized(f, substs, def_id, Ns::Value, &[],
|tcx| tcx.lookup_item_type(def_id).generics)?;
write!(f, "}}")
}
TyFnPtr(ref bare_fn) => {
if bare_fn.unsafety == hir::Unsafety::Unsafe {
try!(write!(f, "unsafe "));
write!(f, "unsafe ")?;
}
if bare_fn.abi != Abi::Rust {
try!(write!(f, "extern {} ", bare_fn.abi));
write!(f, "extern {} ", bare_fn.abi)?;
}
write!(f, "{}", bare_fn.sig.0)
@ -897,30 +897,30 @@ impl<'tcx> fmt::Display for ty::TypeVariants<'tcx> {
ty::TyProjection(ref data) => write!(f, "{}", data),
TyStr => write!(f, "str"),
TyClosure(did, ref substs) => ty::tls::with(|tcx| {
try!(write!(f, "[closure"));
write!(f, "[closure")?;
if let Some(node_id) = tcx.map.as_local_node_id(did) {
try!(write!(f, "@{:?}", tcx.map.span(node_id)));
write!(f, "@{:?}", tcx.map.span(node_id))?;
let mut sep = " ";
try!(tcx.with_freevars(node_id, |freevars| {
tcx.with_freevars(node_id, |freevars| {
for (freevar, upvar_ty) in freevars.iter().zip(&substs.upvar_tys) {
let node_id = freevar.def.var_id();
try!(write!(f,
write!(f,
"{}{}:{}",
sep,
tcx.local_var_name_str(node_id),
upvar_ty));
upvar_ty)?;
sep = ", ";
}
Ok(())
}))
})?
} else {
// cross-crate closure types should only be
// visible in trans bug reports, I imagine.
try!(write!(f, "@{:?}", did));
write!(f, "@{:?}", did)?;
let mut sep = " ";
for (index, upvar_ty) in substs.upvar_tys.iter().enumerate() {
try!(write!(f, "{}{}:{}", sep, index, upvar_ty));
write!(f, "{}{}:{}", sep, index, upvar_ty)?;
sep = ", ";
}
}

View file

@ -464,11 +464,11 @@ impl Target {
use serialize::json;
fn load_file(path: &Path) -> Result<Target, String> {
let mut f = try!(File::open(path).map_err(|e| e.to_string()));
let mut f = File::open(path).map_err(|e| e.to_string())?;
let mut contents = Vec::new();
try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
let obj = try!(json::from_reader(&mut &contents[..])
.map_err(|e| e.to_string()));
f.read_to_end(&mut contents).map_err(|e| e.to_string())?;
let obj = json::from_reader(&mut &contents[..])
.map_err(|e| e.to_string())?;
Ok(Target::from_json(obj))
}

View file

@ -45,7 +45,7 @@ impl TempDir {
let storage;
let mut tmpdir = tmpdir;
if !tmpdir.is_absolute() {
let cur_dir = try!(env::current_dir());
let cur_dir = env::current_dir()?;
storage = cur_dir.join(tmpdir);
tmpdir = &storage;
// return TempDir::new_in(&cur_dir.join(tmpdir), prefix);

View file

@ -112,15 +112,15 @@ impl<'tcx> PreMovePath<'tcx> {
impl<'tcx> fmt::Debug for MovePath<'tcx> {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
try!(write!(w, "MovePath {{"));
write!(w, "MovePath {{")?;
if let Some(parent) = self.parent {
try!(write!(w, " parent: {:?},", parent));
write!(w, " parent: {:?},", parent)?;
}
if let Some(first_child) = self.first_child {
try!(write!(w, " first_child: {:?},", first_child));
write!(w, " first_child: {:?},", first_child)?;
}
if let Some(next_sibling) = self.next_sibling {
try!(write!(w, " next_sibling: {:?}", next_sibling));
write!(w, " next_sibling: {:?}", next_sibling)?;
}
write!(w, " content: {:?} }}", self.content)
}

View file

@ -31,7 +31,7 @@ pub fn print_borrowck_graph_to(mbcx: &MirBorrowckCtxt,
path: &str) -> io::Result<()> {
let g = Graph { mbcx: mbcx, context: context };
let mut v = Vec::new();
try!(dot::render(&g, &mut v));
dot::render(&g, &mut v)?;
println!("print_borrowck_graph_to path: {} context: {} node_id: {}",
path, context, mbcx.node_id);
File::create(path).and_then(|mut f| f.write_all(&v))
@ -121,18 +121,18 @@ impl<'c, 'b:'c, 'a:'b, 'tcx:'a> dot::Labeller<'c> for Graph<'c,'b,'a,'tcx> {
for c in interpreted.chunks(chunk_size) {
if seen_one {
// if not the first row, finish off the previous row
try!(write!(w, "</td><td></td><td></td></tr>"));
write!(w, "</td><td></td><td></td></tr>")?;
}
try!(write!(w, "<tr><td></td><td {bg} {align}>{objs:?}",
write!(w, "<tr><td></td><td {bg} {align}>{objs:?}",
bg = BG_FLOWCONTENT,
align = ALIGN_RIGHT,
objs = c));
objs = c)?;
seen_one = true;
}
if !seen_one {
try!(write!(w, "<tr><td></td><td {bg} {align}>[]",
write!(w, "<tr><td></td><td {bg} {align}>[]",
bg = BG_FLOWCONTENT,
align = ALIGN_RIGHT));
align = ALIGN_RIGHT)?;
}
Ok(())
}
@ -141,7 +141,7 @@ impl<'c, 'b:'c, 'a:'b, 'tcx:'a> dot::Labeller<'c> for Graph<'c,'b,'a,'tcx> {
|w| {
let flow = &self.mbcx.flow_state;
let entry = flow.interpret_set(flow.sets.on_entry_set_for(i));
try!(chunked_present_left(w, &entry[..], chunk_size));
chunked_present_left(w, &entry[..], chunk_size)?;
write!(w, "= ENTRY:</td><td {bg}><FONT {face}>{entrybits:?}</FONT></td>\
<td></td></tr>",
bg = BG_FLOWCONTENT,
@ -153,40 +153,40 @@ impl<'c, 'b:'c, 'a:'b, 'tcx:'a> dot::Labeller<'c> for Graph<'c,'b,'a,'tcx> {
let flow = &self.mbcx.flow_state;
let gen = flow.interpret_set( flow.sets.gen_set_for(i));
let kill = flow.interpret_set(flow.sets.kill_set_for(i));
try!(chunked_present_left(w, &gen[..], chunk_size));
try!(write!(w, " = GEN:</td><td {bg}><FONT {face}>{genbits:?}</FONT></td>\
chunked_present_left(w, &gen[..], chunk_size)?;
write!(w, " = GEN:</td><td {bg}><FONT {face}>{genbits:?}</FONT></td>\
<td></td></tr>",
bg = BG_FLOWCONTENT,
face = FACE_MONOSPACE,
genbits=bits_to_string( flow.sets.gen_set_for(i),
flow.sets.bytes_per_block())));
try!(write!(w, "<tr><td></td><td {bg} {align}>KILL:</td>\
flow.sets.bytes_per_block()))?;
write!(w, "<tr><td></td><td {bg} {align}>KILL:</td>\
<td {bg}><FONT {face}>{killbits:?}</FONT></td>",
bg = BG_FLOWCONTENT,
align = ALIGN_RIGHT,
face = FACE_MONOSPACE,
killbits=bits_to_string(flow.sets.kill_set_for(i),
flow.sets.bytes_per_block())));
flow.sets.bytes_per_block()))?;
// (chunked_present_right)
let mut seen_one = false;
for k in kill.chunks(chunk_size) {
if !seen_one {
// continuation of row; this is fourth <td>
try!(write!(w, "<td {bg}>= {kill:?}</td></tr>",
write!(w, "<td {bg}>= {kill:?}</td></tr>",
bg = BG_FLOWCONTENT,
kill=k));
kill=k)?;
} else {
// new row, with indent of three <td>'s
try!(write!(w, "<tr><td></td><td></td><td></td><td {bg}>{kill:?}</td></tr>",
write!(w, "<tr><td></td><td></td><td></td><td {bg}>{kill:?}</td></tr>",
bg = BG_FLOWCONTENT,
kill=k));
kill=k)?;
}
seen_one = true;
}
if !seen_one {
try!(write!(w, "<td {bg}>= []</td></tr>",
bg = BG_FLOWCONTENT));
write!(w, "<td {bg}>= []</td></tr>",
bg = BG_FLOWCONTENT)?;
}
Ok(())

View file

@ -220,7 +220,7 @@ impl ConstInt {
/// Compares the values if they are of the same type
pub fn try_cmp(self, rhs: Self) -> Result<::std::cmp::Ordering, ConstMathErr> {
match try!(self.infer(rhs)) {
match self.infer(rhs)? {
(I8(a), I8(b)) => Ok(a.cmp(&b)),
(I16(a), I16(b)) => Ok(a.cmp(&b)),
(I32(a), I32(b)) => Ok(a.cmp(&b)),
@ -420,8 +420,8 @@ fn check_division(
impl ::std::ops::Div for ConstInt {
type Output = Result<Self, ConstMathErr>;
fn div(self, rhs: Self) -> Result<Self, ConstMathErr> {
let (lhs, rhs) = try!(self.infer(rhs));
try!(check_division(lhs, rhs, Op::Div, DivisionByZero));
let (lhs, rhs) = self.infer(rhs)?;
check_division(lhs, rhs, Op::Div, DivisionByZero)?;
match (lhs, rhs) {
(I8(a), I8(b)) => Ok(I8(a/b)),
(I16(a), I16(b)) => Ok(I16(a/b)),
@ -447,9 +447,9 @@ impl ::std::ops::Div for ConstInt {
impl ::std::ops::Rem for ConstInt {
type Output = Result<Self, ConstMathErr>;
fn rem(self, rhs: Self) -> Result<Self, ConstMathErr> {
let (lhs, rhs) = try!(self.infer(rhs));
let (lhs, rhs) = self.infer(rhs)?;
// should INT_MIN%-1 be zero or an error?
try!(check_division(lhs, rhs, Op::Rem, RemainderByZero));
check_division(lhs, rhs, Op::Rem, RemainderByZero)?;
match (lhs, rhs) {
(I8(a), I8(b)) => Ok(I8(a%b)),
(I16(a), I16(b)) => Ok(I16(a%b)),
@ -475,7 +475,7 @@ impl ::std::ops::Rem for ConstInt {
impl ::std::ops::Shl<ConstInt> for ConstInt {
type Output = Result<Self, ConstMathErr>;
fn shl(self, rhs: Self) -> Result<Self, ConstMathErr> {
let b = try!(rhs.to_u32().ok_or(ShiftNegative));
let b = rhs.to_u32().ok_or(ShiftNegative)?;
match self {
I8(a) => Ok(I8(overflowing!(a.overflowing_shl(b), Op::Shl))),
I16(a) => Ok(I16(overflowing!(a.overflowing_shl(b), Op::Shl))),
@ -498,7 +498,7 @@ impl ::std::ops::Shl<ConstInt> for ConstInt {
impl ::std::ops::Shr<ConstInt> for ConstInt {
type Output = Result<Self, ConstMathErr>;
fn shr(self, rhs: Self) -> Result<Self, ConstMathErr> {
let b = try!(rhs.to_u32().ok_or(ShiftNegative));
let b = rhs.to_u32().ok_or(ShiftNegative)?;
match self {
I8(a) => Ok(I8(overflowing!(a.overflowing_shr(b), Op::Shr))),
I16(a) => Ok(I16(overflowing!(a.overflowing_shr(b), Op::Shr))),

View file

@ -99,11 +99,11 @@ pub fn compile_input(sess: &Session,
let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
let id = link::find_crate_name(Some(sess), &krate.attrs, input);
let expanded_crate = try!(phase_2_configure_and_expand(sess,
let expanded_crate = phase_2_configure_and_expand(sess,
&cstore,
krate,
&id[..],
addl_plugins));
addl_plugins)?;
(outputs, expanded_crate, id)
};
@ -168,7 +168,7 @@ pub fn compile_input(sess: &Session,
None
};
try!(try!(phase_3_run_analysis_passes(sess,
phase_3_run_analysis_passes(sess,
&cstore,
hir_map,
&arenas,
@ -196,7 +196,7 @@ pub fn compile_input(sess: &Session,
}
}
try!(result);
result?;
if log_enabled!(::log::INFO) {
println!("Pre-trans");
@ -215,7 +215,7 @@ pub fn compile_input(sess: &Session,
token::get_ident_interner().clear();
Ok((outputs, trans))
})))
})??
};
let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
@ -224,7 +224,7 @@ pub fn compile_input(sess: &Session,
sess,
CompileState::state_after_llvm(input, sess, outdir, &trans),
phase5_result);
try!(phase5_result);
phase5_result?;
phase_6_link_output(sess, &trans, &outputs);
@ -428,7 +428,7 @@ pub fn phase_1_parse_input<'a>(sess: &'a Session,
syntax::ext::mtwt::reset_tables();
token::reset_ident_interner();
let krate = try!(time(sess.time_passes(), "parsing", || {
let krate = time(sess.time_passes(), "parsing", || {
match *input {
Input::File(ref file) => {
parse::parse_crate_from_file(file, cfg.clone(), &sess.parse_sess)
@ -440,7 +440,7 @@ pub fn phase_1_parse_input<'a>(sess: &'a Session,
&sess.parse_sess)
}
}
}));
})?;
if sess.opts.debugging_opts.ast_json_noexpand {
println!("{}", json::as_json(&krate));
@ -491,13 +491,13 @@ pub fn phase_2_configure_and_expand(sess: &Session,
// baz! should not use this definition unless foo is enabled.
let mut feature_gated_cfgs = vec![];
krate = try!(time(time_passes, "configuration 1", || {
krate = time(time_passes, "configuration 1", || {
sess.track_errors(|| {
syntax::config::strip_unconfigured_items(sess.diagnostic(),
krate,
&mut feature_gated_cfgs)
})
}));
})?;
*sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
*sess.crate_metadata.borrow_mut() = collect_crate_metadata(sess, &krate.attrs);
@ -506,7 +506,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
middle::recursion_limit::update_recursion_limit(sess, &krate);
});
try!(time(time_passes, "gated macro checking", || {
time(time_passes, "gated macro checking", || {
sess.track_errors(|| {
let features =
syntax::feature_gate::check_crate_macros(sess.codemap(),
@ -516,7 +516,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
// these need to be set "early" so that expansion sees `quote` if enabled.
*sess.features.borrow_mut() = features;
})
}));
})?;
krate = time(time_passes, "crate injection", || {
@ -553,7 +553,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
llvm_passes, attributes, mir_passes, .. } = registry;
try!(sess.track_errors(|| {
sess.track_errors(|| {
let mut ls = sess.lint_store.borrow_mut();
for pass in early_lint_passes {
ls.register_early_pass(Some(sess), true, pass);
@ -569,14 +569,14 @@ pub fn phase_2_configure_and_expand(sess: &Session,
*sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
sess.mir_passes.borrow_mut().extend(mir_passes);
*sess.plugin_attributes.borrow_mut() = attributes.clone();
}));
})?;
// Lint plugins are registered; now we can process command line flags.
if sess.opts.describe_lints {
super::describe_lints(&sess.lint_store.borrow(), true);
return Err(0);
}
try!(sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess)));
sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
krate = time(time_passes, "expansion", || {
// Windows dlls do not have rpaths, so they don't know how to find their
@ -619,7 +619,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
// of macro expansion. This runs before #[cfg] to try to catch as
// much as possible (e.g. help the programmer avoid platform
// specific differences)
try!(time(time_passes, "complete gated feature checking 1", || {
time(time_passes, "complete gated feature checking 1", || {
sess.track_errors(|| {
let features = syntax::feature_gate::check_crate(sess.codemap(),
&sess.parse_sess.span_diagnostic,
@ -628,12 +628,12 @@ pub fn phase_2_configure_and_expand(sess: &Session,
sess.opts.unstable_features);
*sess.features.borrow_mut() = features;
})
}));
})?;
// JBC: make CFG processing part of expansion to avoid this problem:
// strip again, in case expansion added anything with a #[cfg].
krate = try!(sess.track_errors(|| {
krate = sess.track_errors(|| {
let krate = time(time_passes, "configuration 2", || {
syntax::config::strip_unconfigured_items(sess.diagnostic(),
krate,
@ -650,7 +650,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
});
krate
}));
})?;
krate = time(time_passes, "maybe building test harness", || {
syntax::test::modify_for_testing(&sess.parse_sess, &sess.opts.cfg, krate, sess.diagnostic())
@ -671,7 +671,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
// One final feature gating of the true AST that gets compiled
// later, to make sure we've got everything (e.g. configuration
// can insert new attributes via `cfg_attr`)
try!(time(time_passes, "complete gated feature checking 2", || {
time(time_passes, "complete gated feature checking 2", || {
sess.track_errors(|| {
let features = syntax::feature_gate::check_crate(sess.codemap(),
&sess.parse_sess.span_diagnostic,
@ -680,11 +680,11 @@ pub fn phase_2_configure_and_expand(sess: &Session,
sess.opts.unstable_features);
*sess.features.borrow_mut() = features;
})
}));
})?;
try!(time(time_passes,
time(time_passes,
"const fn bodies and arguments",
|| const_fn::check_crate(sess, &krate)));
|| const_fn::check_crate(sess, &krate))?;
if sess.opts.debugging_opts.input_stats {
println!("Post-expansion node count: {}", count_nodes(&krate));
@ -756,11 +756,11 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
"external crate/lib resolution",
|| LocalCrateReader::new(sess, cstore, &hir_map).read_crates());
let lang_items = try!(time(time_passes, "language item collection", || {
let lang_items = time(time_passes, "language item collection", || {
sess.track_errors(|| {
middle::lang_items::collect_language_items(&sess, &hir_map)
})
}));
})?;
let resolve::CrateMap {
def_map,
@ -780,11 +780,11 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
glob_map: glob_map,
};
let named_region_map = try!(time(time_passes,
let named_region_map = time(time_passes,
"lifetime resolution",
|| middle::resolve_lifetime::krate(sess,
&hir_map,
&def_map.borrow())));
&def_map.borrow()))?;
time(time_passes,
"looking for entry point",
@ -802,9 +802,9 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
"loop checking",
|| loops::check_crate(sess, &hir_map));
try!(time(time_passes,
time(time_passes,
"static item recursion checking",
|| static_recursion::check_crate(sess, &def_map.borrow(), &hir_map)));
|| static_recursion::check_crate(sess, &def_map.borrow(), &hir_map))?;
let index = stability::Index::new(&hir_map);
@ -1023,16 +1023,16 @@ fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
.filter(|fmap| !fmap.is_imported())
.map(|fmap| escape_dep_filename(&fmap.name))
.collect();
let mut file = try!(fs::File::create(&deps_filename));
let mut file = fs::File::create(&deps_filename)?;
for path in &out_filenames {
try!(write!(file, "{}: {}\n\n", path.display(), files.join(" ")));
write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
}
// Emit a fake target for each input file to the compilation. This
// prevents `make` from spitting out an error if a file is later
// deleted. For more info see #28735
for path in files {
try!(writeln!(file, "{}:", path));
writeln!(file, "{}:", path)?;
}
Ok(())
})();

View file

@ -325,24 +325,24 @@ impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
pprust::NodeItem(item) => {
try!(pp::space(&mut s.s));
pp::space(&mut s.s)?;
s.synth_comment(item.id.to_string())
}
pprust::NodeSubItem(id) => {
try!(pp::space(&mut s.s));
pp::space(&mut s.s)?;
s.synth_comment(id.to_string())
}
pprust::NodeBlock(blk) => {
try!(pp::space(&mut s.s));
pp::space(&mut s.s)?;
s.synth_comment(format!("block {}", blk.id))
}
pprust::NodeExpr(expr) => {
try!(pp::space(&mut s.s));
try!(s.synth_comment(expr.id.to_string()));
pp::space(&mut s.s)?;
s.synth_comment(expr.id.to_string())?;
s.pclose()
}
pprust::NodePat(pat) => {
try!(pp::space(&mut s.s));
pp::space(&mut s.s)?;
s.synth_comment(format!("pat {}", pat.id))
}
}
@ -374,24 +374,24 @@ impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> {
match node {
pprust_hir::NodeName(_) => Ok(()),
pprust_hir::NodeItem(item) => {
try!(pp::space(&mut s.s));
pp::space(&mut s.s)?;
s.synth_comment(item.id.to_string())
}
pprust_hir::NodeSubItem(id) => {
try!(pp::space(&mut s.s));
pp::space(&mut s.s)?;
s.synth_comment(id.to_string())
}
pprust_hir::NodeBlock(blk) => {
try!(pp::space(&mut s.s));
pp::space(&mut s.s)?;
s.synth_comment(format!("block {}", blk.id))
}
pprust_hir::NodeExpr(expr) => {
try!(pp::space(&mut s.s));
try!(s.synth_comment(expr.id.to_string()));
pp::space(&mut s.s)?;
s.synth_comment(expr.id.to_string())?;
s.pclose()
}
pprust_hir::NodePat(pat) => {
try!(pp::space(&mut s.s));
pp::space(&mut s.s)?;
s.synth_comment(format!("pat {}", pat.id))
}
}
@ -421,13 +421,13 @@ impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
match node {
pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
try!(pp::space(&mut s.s));
pp::space(&mut s.s)?;
// FIXME #16420: this doesn't display the connections
// between syntax contexts
s.synth_comment(format!("{}#{}", nm, ctxt.0))
}
pprust::NodeName(&ast::Name(nm)) => {
try!(pp::space(&mut s.s));
pp::space(&mut s.s)?;
s.synth_comment(nm.to_string())
}
_ => Ok(()),
@ -464,10 +464,10 @@ impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
match node {
pprust_hir::NodeExpr(expr) => {
try!(pp::space(&mut s.s));
try!(pp::word(&mut s.s, "as"));
try!(pp::space(&mut s.s));
try!(pp::word(&mut s.s, &self.tcx.expr_ty(expr).to_string()));
pp::space(&mut s.s)?;
pp::word(&mut s.s, "as")?;
pp::space(&mut s.s)?;
pp::word(&mut s.s, &self.tcx.expr_ty(expr).to_string())?;
s.pclose()
}
_ => Ok(()),
@ -806,10 +806,10 @@ pub fn pretty_print_input(sess: Session,
Some(ast_map.krate()));
for node_id in uii.all_matching_node_ids(ast_map) {
let node = ast_map.get(node_id);
try!(pp_state.print_node(&node));
try!(pp::space(&mut pp_state.s));
try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
try!(pp::hardbreak(&mut pp_state.s));
pp_state.print_node(&node)?;
pp::space(&mut pp_state.s)?;
pp_state.synth_comment(ast_map.path_to_string(node_id))?;
pp::hardbreak(&mut pp_state.s)?;
}
pp::eof(&mut pp_state.s)
})
@ -836,15 +836,15 @@ pub fn pretty_print_input(sess: Session,
let mir = mir_map.map.get(&nodeid).unwrap_or_else(|| {
sess.fatal(&format!("no MIR map entry for node {}", nodeid))
});
try!(match pp_type {
match pp_type {
PpmMir => write_mir_pretty(tcx, iter::once((&nodeid, mir)), &mut out),
_ => write_mir_graphviz(tcx, iter::once((&nodeid, mir)), &mut out)
});
}?;
} else {
try!(match pp_type {
match pp_type {
PpmMir => write_mir_pretty(tcx, mir_map.map.iter(), &mut out),
_ => write_mir_graphviz(tcx, mir_map.map.iter(), &mut out)
});
}?;
}
}
Ok(())

View file

@ -119,7 +119,7 @@ impl Encodable for Ident {
impl Decodable for Ident {
fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
Ok(Ident::from_name(try!(Name::decode(d))))
Ok(Ident::from_name(Name::decode(d)?))
}
}

File diff suppressed because it is too large Load diff

View file

@ -1221,11 +1221,11 @@ fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
out: &mut io::Write) -> io::Result<()> {
try!(write!(out, "=Crate Attributes ({})=\n", *hash));
write!(out, "=Crate Attributes ({})=\n", *hash)?;
let r = get_attributes(md);
for attr in &r {
try!(write!(out, "{}\n", pprust::attribute_to_string(attr)));
write!(out, "{}\n", pprust::attribute_to_string(attr))?;
}
write!(out, "\n\n")
@ -1267,11 +1267,11 @@ pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
}
fn list_crate_deps(data: &[u8], out: &mut io::Write) -> io::Result<()> {
try!(write!(out, "=External Dependencies=\n"));
write!(out, "=External Dependencies=\n")?;
for dep in &get_crate_deps(data) {
try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash));
write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash)?;
}
try!(write!(out, "\n"));
write!(out, "\n")?;
Ok(())
}
@ -1308,7 +1308,7 @@ pub fn get_crate_name(data: &[u8]) -> String {
pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
let hash = get_crate_hash(bytes);
let md = rbml::Doc::new(bytes);
try!(list_crate_attributes(md, &hash, out));
list_crate_attributes(md, &hash, out)?;
list_crate_deps(bytes, out)
}

View file

@ -19,26 +19,26 @@ use syntax::ast::NodeId;
pub fn write_mir_graphviz<'a, 't, W, I>(tcx: &ty::TyCtxt<'t>, iter: I, w: &mut W) -> io::Result<()>
where W: Write, I: Iterator<Item=(&'a NodeId, &'a Mir<'a>)> {
for (&nodeid, mir) in iter {
try!(writeln!(w, "digraph Mir_{} {{", nodeid));
writeln!(w, "digraph Mir_{} {{", nodeid)?;
// Global graph properties
try!(writeln!(w, r#" graph [fontname="monospace"];"#));
try!(writeln!(w, r#" node [fontname="monospace"];"#));
try!(writeln!(w, r#" edge [fontname="monospace"];"#));
writeln!(w, r#" graph [fontname="monospace"];"#)?;
writeln!(w, r#" node [fontname="monospace"];"#)?;
writeln!(w, r#" edge [fontname="monospace"];"#)?;
// Graph label
try!(write_graph_label(tcx, nodeid, mir, w));
write_graph_label(tcx, nodeid, mir, w)?;
// Nodes
for block in mir.all_basic_blocks() {
try!(write_node(block, mir, w));
write_node(block, mir, w)?;
}
// Edges
for source in mir.all_basic_blocks() {
try!(write_edges(source, mir, w));
write_edges(source, mir, w)?;
}
try!(writeln!(w, "}}"))
writeln!(w, "}}")?
}
Ok(())
}
@ -61,32 +61,32 @@ pub fn write_node_label<W: Write, INIT, FINI>(block: BasicBlock,
{
let data = mir.basic_block_data(block);
try!(write!(w, r#"<table border="0" cellborder="1" cellspacing="0">"#));
write!(w, r#"<table border="0" cellborder="1" cellspacing="0">"#)?;
// Basic block number at the top.
try!(write!(w, r#"<tr><td {attrs} colspan="{colspan}">{blk}</td></tr>"#,
write!(w, r#"<tr><td {attrs} colspan="{colspan}">{blk}</td></tr>"#,
attrs=r#"bgcolor="gray" align="center""#,
colspan=num_cols,
blk=block.index()));
blk=block.index())?;
try!(init(w));
init(w)?;
// List of statements in the middle.
if !data.statements.is_empty() {
try!(write!(w, r#"<tr><td align="left" balign="left">"#));
write!(w, r#"<tr><td align="left" balign="left">"#)?;
for statement in &data.statements {
try!(write!(w, "{}<br/>", escape(statement)));
write!(w, "{}<br/>", escape(statement))?;
}
try!(write!(w, "</td></tr>"));
write!(w, "</td></tr>")?;
}
// Terminator head at the bottom, not including the list of successor blocks. Those will be
// displayed as labels on the edges between blocks.
let mut terminator_head = String::new();
data.terminator().fmt_head(&mut terminator_head).unwrap();
try!(write!(w, r#"<tr><td align="left">{}</td></tr>"#, dot::escape_html(&terminator_head)));
write!(w, r#"<tr><td align="left">{}</td></tr>"#, dot::escape_html(&terminator_head))?;
try!(fini(w));
fini(w)?;
// Close the table
writeln!(w, "</table>")
@ -95,8 +95,8 @@ pub fn write_node_label<W: Write, INIT, FINI>(block: BasicBlock,
/// Write a graphviz DOT node for the given basic block.
fn write_node<W: Write>(block: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
// Start a new node with the label to follow, in one of DOT's pseudo-HTML tables.
try!(write!(w, r#" {} [shape="none", label=<"#, node(block)));
try!(write_node_label(block, mir, w, 1, |_| Ok(()), |_| Ok(())));
write!(w, r#" {} [shape="none", label=<"#, node(block))?;
write_node_label(block, mir, w, 1, |_| Ok(()), |_| Ok(()))?;
// Close the node label and the node itself.
writeln!(w, ">];")
}
@ -107,7 +107,7 @@ fn write_edges<W: Write>(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result
let labels = terminator.fmt_successor_labels();
for (&target, label) in terminator.successors().iter().zip(labels) {
try!(writeln!(w, r#" {} -> {} [label="{}"];"#, node(source), node(target), label));
writeln!(w, r#" {} -> {} [label="{}"];"#, node(source), node(target), label)?;
}
Ok(())
@ -118,40 +118,40 @@ fn write_edges<W: Write>(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result
/// all the variables and temporaries.
fn write_graph_label<W: Write>(tcx: &ty::TyCtxt, nid: NodeId, mir: &Mir, w: &mut W)
-> io::Result<()> {
try!(write!(w, " label=<fn {}(", dot::escape_html(&tcx.map.path_to_string(nid))));
write!(w, " label=<fn {}(", dot::escape_html(&tcx.map.path_to_string(nid)))?;
// fn argument types.
for (i, arg) in mir.arg_decls.iter().enumerate() {
if i > 0 {
try!(write!(w, ", "));
write!(w, ", ")?;
}
try!(write!(w, "{:?}: {}", Lvalue::Arg(i as u32), escape(&arg.ty)));
write!(w, "{:?}: {}", Lvalue::Arg(i as u32), escape(&arg.ty))?;
}
try!(write!(w, ") -&gt; "));
write!(w, ") -&gt; ")?;
// fn return type.
match mir.return_ty {
ty::FnOutput::FnConverging(ty) => try!(write!(w, "{}", escape(ty))),
ty::FnOutput::FnDiverging => try!(write!(w, "!")),
ty::FnOutput::FnConverging(ty) => write!(w, "{}", escape(ty))?,
ty::FnOutput::FnDiverging => write!(w, "!")?,
}
try!(write!(w, r#"<br align="left"/>"#));
write!(w, r#"<br align="left"/>"#)?;
// User variable types (including the user's name in a comment).
for (i, var) in mir.var_decls.iter().enumerate() {
try!(write!(w, "let "));
write!(w, "let ")?;
if var.mutability == Mutability::Mut {
try!(write!(w, "mut "));
write!(w, "mut ")?;
}
try!(write!(w, r#"{:?}: {}; // {}<br align="left"/>"#,
Lvalue::Var(i as u32), escape(&var.ty), var.name));
write!(w, r#"{:?}: {}; // {}<br align="left"/>"#,
Lvalue::Var(i as u32), escape(&var.ty), var.name)?;
}
// Compiler-introduced temporary types.
for (i, temp) in mir.temp_decls.iter().enumerate() {
try!(write!(w, r#"let mut {:?}: {};<br align="left"/>"#,
Lvalue::Temp(i as u32), escape(&temp.ty)));
write!(w, r#"let mut {:?}: {};<br align="left"/>"#,
Lvalue::Temp(i as u32), escape(&temp.ty))?;
}
writeln!(w, ">;")

View file

@ -19,12 +19,12 @@ const INDENT: &'static str = " ";
pub fn write_mir_pretty<'a, 't, W, I>(tcx: &ty::TyCtxt<'t>, iter: I, w: &mut W) -> io::Result<()>
where W: Write, I: Iterator<Item=(&'a NodeId, &'a Mir<'a>)> {
for (&nodeid, mir) in iter {
try!(write_mir_intro(tcx, nodeid, mir, w));
write_mir_intro(tcx, nodeid, mir, w)?;
// Nodes
for block in mir.all_basic_blocks() {
try!(write_basic_block(block, mir, w));
write_basic_block(block, mir, w)?;
}
try!(writeln!(w, "}}"))
writeln!(w, "}}")?
}
Ok(())
}
@ -34,15 +34,15 @@ fn write_basic_block<W: Write>(block: BasicBlock, mir: &Mir, w: &mut W) -> io::R
let data = mir.basic_block_data(block);
// Basic block label at the top.
try!(writeln!(w, "\n{}{:?}: {{", INDENT, block));
writeln!(w, "\n{}{:?}: {{", INDENT, block)?;
// List of statements in the middle.
for statement in &data.statements {
try!(writeln!(w, "{0}{0}{1:?};", INDENT, statement));
writeln!(w, "{0}{0}{1:?};", INDENT, statement)?;
}
// Terminator at the bottom.
try!(writeln!(w, "{0}{0}{1:?};", INDENT, data.terminator()));
writeln!(w, "{0}{0}{1:?};", INDENT, data.terminator())?;
writeln!(w, "{}}}", INDENT)
}
@ -52,38 +52,38 @@ fn write_basic_block<W: Write>(block: BasicBlock, mir: &Mir, w: &mut W) -> io::R
fn write_mir_intro<W: Write>(tcx: &ty::TyCtxt, nid: NodeId, mir: &Mir, w: &mut W)
-> io::Result<()> {
try!(write!(w, "fn {}(", tcx.map.path_to_string(nid)));
write!(w, "fn {}(", tcx.map.path_to_string(nid))?;
// fn argument types.
for (i, arg) in mir.arg_decls.iter().enumerate() {
if i > 0 {
try!(write!(w, ", "));
write!(w, ", ")?;
}
try!(write!(w, "{:?}: {}", Lvalue::Arg(i as u32), arg.ty));
write!(w, "{:?}: {}", Lvalue::Arg(i as u32), arg.ty)?;
}
try!(write!(w, ") -> "));
write!(w, ") -> ")?;
// fn return type.
match mir.return_ty {
ty::FnOutput::FnConverging(ty) => try!(write!(w, "{}", ty)),
ty::FnOutput::FnDiverging => try!(write!(w, "!")),
ty::FnOutput::FnConverging(ty) => write!(w, "{}", ty)?,
ty::FnOutput::FnDiverging => write!(w, "!")?,
}
try!(writeln!(w, " {{"));
writeln!(w, " {{")?;
// User variable types (including the user's name in a comment).
for (i, var) in mir.var_decls.iter().enumerate() {
try!(write!(w, "{}let ", INDENT));
write!(w, "{}let ", INDENT)?;
if var.mutability == Mutability::Mut {
try!(write!(w, "mut "));
write!(w, "mut ")?;
}
try!(writeln!(w, "{:?}: {}; // {}", Lvalue::Var(i as u32), var.ty, var.name));
writeln!(w, "{:?}: {}; // {}", Lvalue::Var(i as u32), var.ty, var.name)?;
}
// Compiler-introduced temporary types.
for (i, temp) in mir.temp_decls.iter().enumerate() {
try!(writeln!(w, "{}let mut {:?}: {};", INDENT, Lvalue::Temp(i as u32), temp.ty));
writeln!(w, "{}let mut {:?}: {};", INDENT, Lvalue::Temp(i as u32), temp.ty)?;
}
Ok(())

View file

@ -254,8 +254,8 @@ impl<'a> ArchiveBuilder<'a> {
// want to modify this archive, so we use `io::copy` to not preserve
// permission bits.
if let Some(ref s) = self.config.src {
try!(io::copy(&mut try!(File::open(s)),
&mut try!(File::create(&self.config.dst))));
io::copy(&mut File::open(s)?,
&mut File::create(&self.config.dst)?)?;
}
if removals.len() > 0 {
@ -267,12 +267,12 @@ impl<'a> ArchiveBuilder<'a> {
match addition {
Addition::File { path, name_in_archive } => {
let dst = self.work_dir.path().join(&name_in_archive);
try!(fs::copy(&path, &dst));
fs::copy(&path, &dst)?;
members.push(PathBuf::from(name_in_archive));
}
Addition::Archive { archive, archive_name, mut skip } => {
try!(self.add_archive_members(&mut members, archive,
&archive_name, &mut *skip));
self.add_archive_members(&mut members, archive,
&archive_name, &mut *skip)?;
}
}
}
@ -334,7 +334,7 @@ impl<'a> ArchiveBuilder<'a> {
// all SYMDEF files as these are just magical placeholders which get
// re-created when we make a new archive anyway.
for file in archive.iter() {
let file = try!(file.map_err(string_to_io_error));
let file = file.map_err(string_to_io_error)?;
if !is_relevant_child(&file) {
continue
}
@ -388,7 +388,7 @@ impl<'a> ArchiveBuilder<'a> {
}
}
let dst = self.work_dir.path().join(&new_filename);
try!(try!(File::create(&dst)).write_all(file.data()));
File::create(&dst)?.write_all(file.data())?;
members.push(PathBuf::from(new_filename));
}
Ok(())
@ -455,7 +455,7 @@ impl<'a> ArchiveBuilder<'a> {
unsafe {
if let Some(archive) = self.src_archive() {
for child in archive.iter() {
let child = try!(child.map_err(string_to_io_error));
let child = child.map_err(string_to_io_error)?;
let child_name = match child.name() {
Some(s) => s,
None => continue,
@ -464,7 +464,7 @@ impl<'a> ArchiveBuilder<'a> {
continue
}
let name = try!(CString::new(child_name));
let name = CString::new(child_name)?;
members.push(llvm::LLVMRustArchiveMemberNew(ptr::null(),
name.as_ptr(),
child.raw()));
@ -474,8 +474,8 @@ impl<'a> ArchiveBuilder<'a> {
for addition in mem::replace(&mut self.additions, Vec::new()) {
match addition {
Addition::File { path, name_in_archive } => {
let path = try!(CString::new(path.to_str().unwrap()));
let name = try!(CString::new(name_in_archive));
let path = CString::new(path.to_str().unwrap())?;
let name = CString::new(name_in_archive)?;
members.push(llvm::LLVMRustArchiveMemberNew(path.as_ptr(),
name.as_ptr(),
ptr::null_mut()));
@ -484,7 +484,7 @@ impl<'a> ArchiveBuilder<'a> {
}
Addition::Archive { archive, archive_name: _, mut skip } => {
for child in archive.iter() {
let child = try!(child.map_err(string_to_io_error));
let child = child.map_err(string_to_io_error)?;
if !is_relevant_child(&child) {
continue
}
@ -502,7 +502,7 @@ impl<'a> ArchiveBuilder<'a> {
let child_name = Path::new(child_name)
.file_name().unwrap()
.to_str().unwrap();
let name = try!(CString::new(child_name));
let name = CString::new(child_name)?;
let m = llvm::LLVMRustArchiveMemberNew(ptr::null(),
name.as_ptr(),
child.raw());
@ -515,7 +515,7 @@ impl<'a> ArchiveBuilder<'a> {
}
let dst = self.config.dst.to_str().unwrap().as_bytes();
let dst = try!(CString::new(dst));
let dst = CString::new(dst)?;
let r = llvm::LLVMRustWriteArchive(dst.as_ptr(),
members.len() as libc::size_t,
members.as_ptr(),

View file

@ -757,9 +757,9 @@ fn write_rlib_bytecode_object_v1(writer: &mut Write,
bc_data_deflated: &[u8]) -> io::Result<()> {
let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64;
try!(writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC));
try!(writer.write_all(&[1, 0, 0, 0]));
try!(writer.write_all(&[
writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC)?;
writer.write_all(&[1, 0, 0, 0])?;
writer.write_all(&[
(bc_data_deflated_size >> 0) as u8,
(bc_data_deflated_size >> 8) as u8,
(bc_data_deflated_size >> 16) as u8,
@ -768,8 +768,8 @@ fn write_rlib_bytecode_object_v1(writer: &mut Write,
(bc_data_deflated_size >> 40) as u8,
(bc_data_deflated_size >> 48) as u8,
(bc_data_deflated_size >> 56) as u8,
]));
try!(writer.write_all(&bc_data_deflated));
])?;
writer.write_all(&bc_data_deflated)?;
let number_of_bytes_written_so_far =
RLIB_BYTECODE_OBJECT_MAGIC.len() + // magic id
@ -781,7 +781,7 @@ fn write_rlib_bytecode_object_v1(writer: &mut Write,
// padding byte to make it even. This works around a crash bug in LLDB
// (see issue #15950)
if number_of_bytes_written_so_far % 2 == 1 {
try!(writer.write_all(&[0]));
writer.write_all(&[0])?;
}
return Ok(());

View file

@ -327,16 +327,16 @@ impl<'a> Linker for MsvcLinker<'a> {
tmpdir: &Path) {
let path = tmpdir.join("lib.def");
let res = (|| -> io::Result<()> {
let mut f = BufWriter::new(try!(File::create(&path)));
let mut f = BufWriter::new(File::create(&path)?);
// Start off with the standard module name header and then go
// straight to exports.
try!(writeln!(f, "LIBRARY"));
try!(writeln!(f, "EXPORTS"));
writeln!(f, "LIBRARY")?;
writeln!(f, "EXPORTS")?;
// Write out all our local symbols
for sym in trans.reachable.iter() {
try!(writeln!(f, " {}", sym));
writeln!(f, " {}", sym)?;
}
// Take a look at how all upstream crates are linked into this
@ -357,7 +357,7 @@ impl<'a> Linker for MsvcLinker<'a> {
cstore.item_symbol(did)
});
for symbol in symbols {
try!(writeln!(f, " {}", symbol));
writeln!(f, " {}", symbol)?;
}
Ok(())
})();

View file

@ -175,9 +175,9 @@ impl<'blk, 'tcx: 'blk> fmt::Debug for CleanupScopeKind<'blk, 'tcx> {
CustomScopeKind => write!(f, "CustomScopeKind"),
AstScopeKind(nid) => write!(f, "AstScopeKind({})", nid),
LoopScopeKind(nid, ref blks) => {
try!(write!(f, "LoopScopeKind({}, [", nid));
write!(f, "LoopScopeKind({}, [", nid)?;
for blk in blks {
try!(write!(f, "{:p}, ", blk));
write!(f, "{:p}, ", blk)?;
}
write!(f, "])")
}

View file

@ -316,9 +316,9 @@ pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
let val = if qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
// Avoid autorefs as they would create global instead of stack
// references, even when only the latter are correct.
try!(const_expr_unadjusted(ccx, expr, ty, param_substs, None, trueconst))
const_expr_unadjusted(ccx, expr, ty, param_substs, None, trueconst)?
} else {
try!(const_expr(ccx, expr, param_substs, None, trueconst)).0
const_expr(ccx, expr, param_substs, None, trueconst)?.0
};
// boolean SSA values are i1, but they have to be stored in i8 slots,
@ -344,7 +344,7 @@ pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
-> Result<(ValueRef, Ty<'tcx>), ConstEvalFailure> {
let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
&cx.tcx().expr_ty(e));
let llconst = try!(const_expr_unadjusted(cx, e, ety, param_substs, fn_args, trueconst));
let llconst = const_expr_unadjusted(cx, e, ety, param_substs, fn_args, trueconst)?;
let mut llconst = llconst;
let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
&cx.tcx().expr_ty_adjusted(e));
@ -594,18 +594,18 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
hir::ExprBinary(b, ref e1, ref e2) => {
/* Neither type is bottom, and we expect them to be unified
* already, so the following is safe. */
let (te1, ty) = try!(const_expr(cx, &e1, param_substs, fn_args, trueconst));
let (te1, ty) = const_expr(cx, &e1, param_substs, fn_args, trueconst)?;
debug!("const_expr_unadjusted: te1={:?}, ty={:?}",
Value(te1), ty);
assert!(!ty.is_simd());
let is_float = ty.is_fp();
let signed = ty.is_signed();
let (te2, ty2) = try!(const_expr(cx, &e2, param_substs, fn_args, trueconst));
let (te2, ty2) = const_expr(cx, &e2, param_substs, fn_args, trueconst)?;
debug!("const_expr_unadjusted: te2={:?}, ty={:?}",
Value(te2), ty2);
try!(check_binary_expr_validity(cx, e, ty, te1, te2, trueconst));
check_binary_expr_validity(cx, e, ty, te1, te2, trueconst)?;
unsafe { match b.node {
hir::BiAdd if is_float => llvm::LLVMConstFAdd(te1, te2),
@ -651,9 +651,9 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
} } // unsafe { match b.node {
},
hir::ExprUnary(u, ref inner_e) => {
let (te, ty) = try!(const_expr(cx, &inner_e, param_substs, fn_args, trueconst));
let (te, ty) = const_expr(cx, &inner_e, param_substs, fn_args, trueconst)?;
try!(check_unary_expr_validity(cx, e, ty, te, trueconst));
check_unary_expr_validity(cx, e, ty, te, trueconst)?;
let is_float = ty.is_fp();
unsafe { match u {
@ -664,21 +664,21 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
} }
},
hir::ExprField(ref base, field) => {
let (bv, bt) = try!(const_expr(cx, &base, param_substs, fn_args, trueconst));
let (bv, bt) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
let brepr = adt::represent_type(cx, bt);
let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
let ix = vinfo.field_index(field.node);
adt::const_get_field(cx, &brepr, bv, vinfo.discr, ix)
},
hir::ExprTupField(ref base, idx) => {
let (bv, bt) = try!(const_expr(cx, &base, param_substs, fn_args, trueconst));
let (bv, bt) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
let brepr = adt::represent_type(cx, bt);
let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
adt::const_get_field(cx, &brepr, bv, vinfo.discr, idx.node)
},
hir::ExprIndex(ref base, ref index) => {
let (bv, bt) = try!(const_expr(cx, &base, param_substs, fn_args, trueconst));
let iv = try!(const_expr(cx, &index, param_substs, fn_args, TrueConst::Yes)).0;
let (bv, bt) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
let iv = const_expr(cx, &index, param_substs, fn_args, TrueConst::Yes)?.0;
let iv = if let Some(iv) = const_to_opt_uint(iv) {
iv
} else {
@ -729,7 +729,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
hir::ExprCast(ref base, _) => {
let t_cast = ety;
let llty = type_of::type_of(cx, t_cast);
let (v, t_expr) = try!(const_expr(cx, &base, param_substs, fn_args, trueconst));
let (v, t_expr) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
debug!("trans_const_cast({:?} as {:?})", t_expr, t_cast);
if expr::cast_is_noop(cx.tcx(), base, t_expr, t_cast) {
return Ok(v);
@ -811,30 +811,30 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
} else {
// If this isn't the address of a static, then keep going through
// normal constant evaluation.
let (v, ty) = try!(const_expr(cx, &sub, param_substs, fn_args, trueconst));
let (v, ty) = const_expr(cx, &sub, param_substs, fn_args, trueconst)?;
addr_of(cx, v, type_of::align_of(cx, ty), "ref")
}
},
hir::ExprAddrOf(hir::MutMutable, ref sub) => {
let (v, ty) = try!(const_expr(cx, &sub, param_substs, fn_args, trueconst));
let (v, ty) = const_expr(cx, &sub, param_substs, fn_args, trueconst)?;
addr_of_mut(cx, v, type_of::align_of(cx, ty), "ref_mut_slice")
},
hir::ExprTup(ref es) => {
let repr = adt::represent_type(cx, ety);
let vals = try!(map_list(&es[..]));
let vals = map_list(&es[..])?;
adt::trans_const(cx, &repr, Disr(0), &vals[..])
},
hir::ExprStruct(_, ref fs, ref base_opt) => {
let repr = adt::represent_type(cx, ety);
let base_val = match *base_opt {
Some(ref base) => Some(try!(const_expr(
Some(ref base) => Some(const_expr(
cx,
&base,
param_substs,
fn_args,
trueconst,
))),
)?),
None => None
};
@ -851,7 +851,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
.collect::<Vec<Result<_, ConstEvalFailure>>>()
.into_iter()
.collect::<Result<Vec<_>,ConstEvalFailure>>();
let cs = try!(cs);
let cs = cs?;
if ety.is_simd() {
C_vector(&cs[..])
} else {
@ -872,7 +872,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
.collect::<Vec<Result<_, ConstEvalFailure>>>()
.into_iter()
.collect::<Result<Vec<_>, ConstEvalFailure>>();
let vs = try!(vs);
let vs = vs?;
// If the vector contains enums, an LLVM array won't work.
if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
C_struct(cx, &vs[..], false)
@ -884,7 +884,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
let unit_ty = ety.sequence_element_type(cx.tcx());
let llunitty = type_of::type_of(cx, unit_ty);
let n = cx.tcx().eval_repeat_count(count);
let unit_val = try!(const_expr(cx, &elem, param_substs, fn_args, trueconst)).0;
let unit_val = const_expr(cx, &elem, param_substs, fn_args, trueconst)?.0;
let vs = vec![unit_val; n];
if val_ty(unit_val) != llunitty {
C_struct(cx, &vs[..], false)
@ -904,7 +904,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
}
Def::Fn(..) | Def::Method(..) => C_nil(cx),
Def::Const(def_id) | Def::AssociatedConst(def_id) => {
load_const(cx, try!(get_const_val(cx, def_id, e, param_substs)),
load_const(cx, get_const_val(cx, def_id, e, param_substs)?,
ety)
}
Def::Variant(enum_did, variant_did) => {
@ -940,17 +940,17 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
};
}
let def = cx.tcx().def_map.borrow()[&callee.id].full_def();
let arg_vals = try!(map_list(args));
let arg_vals = map_list(args)?;
match def {
Def::Fn(did) | Def::Method(did) => {
try!(const_fn_call(
const_fn_call(
cx,
did,
cx.tcx().node_id_item_substs(callee.id).substs,
&arg_vals,
param_substs,
trueconst,
))
)?
}
Def::Struct(..) => {
if ety.is_simd() {
@ -972,22 +972,22 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
}
},
hir::ExprMethodCall(_, _, ref args) => {
let arg_vals = try!(map_list(args));
let arg_vals = map_list(args)?;
let method_call = ty::MethodCall::expr(e.id);
let method = cx.tcx().tables.borrow().method_map[&method_call];
try!(const_fn_call(cx, method.def_id, method.substs.clone(),
&arg_vals, param_substs, trueconst))
const_fn_call(cx, method.def_id, method.substs.clone(),
&arg_vals, param_substs, trueconst)?
},
hir::ExprType(ref e, _) => try!(const_expr(cx, &e, param_substs, fn_args, trueconst)).0,
hir::ExprType(ref e, _) => const_expr(cx, &e, param_substs, fn_args, trueconst)?.0,
hir::ExprBlock(ref block) => {
match block.expr {
Some(ref expr) => try!(const_expr(
Some(ref expr) => const_expr(
cx,
&expr,
param_substs,
fn_args,
trueconst,
)).0,
)?.0,
None => C_nil(cx),
}
},
@ -1149,13 +1149,13 @@ pub fn trans_static(ccx: &CrateContext,
let datum = get_static(ccx, def_id);
let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
let (v, _) = try!(const_expr(
let (v, _) = const_expr(
ccx,
expr,
empty_substs,
None,
TrueConst::Yes,
).map_err(|e| e.into_inner()));
).map_err(|e| e.into_inner())?;
// boolean SSA values are i1, but they have to be stored in i8 slots,
// otherwise some LLVM optimization passes don't work as expected

View file

@ -934,7 +934,7 @@ fn ast_type_binding_to_poly_projection_predicate<'tcx>(
tcx.mk_substs(dummy_substs)));
}
try!(this.ensure_super_predicates(binding.span, trait_ref.def_id()));
this.ensure_super_predicates(binding.span, trait_ref.def_id())?;
let mut candidates: Vec<ty::PolyTraitRef> =
traits::supertraits(tcx, trait_ref.clone())
@ -953,11 +953,11 @@ fn ast_type_binding_to_poly_projection_predicate<'tcx>(
}
}
let candidate = try!(one_bound_for_assoc_type(tcx,
let candidate = one_bound_for_assoc_type(tcx,
candidates,
&trait_ref.to_string(),
&binding.item_name.as_str(),
binding.span));
binding.span)?;
Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------------+
projection_ty: ty::ProjectionTy { // |

View file

@ -220,7 +220,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
let (r_a, mt_a) = match a.sty {
ty::TyRef(r_a, mt_a) => {
try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl));
coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
(r_a, mt_a)
}
_ => return self.unify_and_identity(a, b)
@ -414,7 +414,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
// Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
let (source, reborrow) = match (&source.sty, &target.sty) {
(&ty::TyRef(_, mt_a), &ty::TyRef(_, mt_b)) => {
try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl));
coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
let coercion = Coercion(self.origin.span());
let r_borrow = self.fcx.infcx().next_region_var(coercion);
@ -422,7 +422,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
(mt_a.ty, Some(AutoPtr(region, mt_b.mutbl)))
}
(&ty::TyRef(_, mt_a), &ty::TyRawPtr(mt_b)) => {
try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl));
coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
(mt_a.ty, Some(AutoUnsafe(mt_b.mutbl)))
}
_ => (source, None)
@ -564,8 +564,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
// Check that the types which they point at are compatible.
let a_unsafe = self.tcx().mk_ptr(ty::TypeAndMut{ mutbl: mutbl_b, ty: mt_a.ty });
let (ty, noop) = try!(self.unify_and_identity(a_unsafe, b));
try!(coerce_mutbls(mt_a.mutbl, mutbl_b));
let (ty, noop) = self.unify_and_identity(a_unsafe, b)?;
coerce_mutbls(mt_a.mutbl, mutbl_b)?;
// Although references and unsafe ptrs have the same
// representation, we still register an AutoDerefRef so that
@ -592,7 +592,7 @@ fn apply<'a, 'b, 'tcx, E, I>(coerce: &mut Coerce<'a, 'tcx>,
where E: Fn() -> I,
I: IntoIterator<Item=&'b hir::Expr> {
let (ty, adjustment) = try!(indent(|| coerce.coerce(exprs, a, b)));
let (ty, adjustment) = indent(|| coerce.coerce(exprs, a, b))?;
let fcx = coerce.fcx;
if let AdjustDerefRef(auto) = adjustment {
@ -621,7 +621,7 @@ pub fn try<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
let mut coerce = Coerce::new(fcx, TypeOrigin::ExprAssignable(expr.span));
fcx.infcx().commit_if_ok(|_| {
let (ty, adjustment) =
try!(apply(&mut coerce, &|| Some(expr), source, target));
apply(&mut coerce, &|| Some(expr), source, target)?;
if !adjustment.is_identity() {
debug!("Success, coerced with {:?}", adjustment);
assert!(!fcx.inh.tables.borrow().adjustments.contains_key(&expr.id));
@ -657,7 +657,7 @@ pub fn try_find_lub<'a, 'b, 'tcx, E, I>(fcx: &FnCtxt<'a, 'tcx>,
(&ty::TyFnDef(a_def_id, a_substs, a_fty),
&ty::TyFnDef(b_def_id, b_substs, b_fty)) => {
// The signature must always match.
let fty = try!(lub.relate(a_fty, b_fty));
let fty = lub.relate(a_fty, b_fty)?;
if a_def_id == b_def_id {
// Same function, maybe the parameters match.

View file

@ -323,7 +323,7 @@ pub fn compare_impl_method<'tcx>(tcx: &TyCtxt<'tcx>,
debug!("compare_impl_method: trait_fty={:?}",
trait_fty);
try!(infer::mk_subty(&infcx, false, origin, impl_fty, trait_fty));
infer::mk_subty(&infcx, false, origin, impl_fty, trait_fty)?;
infcx.leak_check(&skol_map, snapshot)
});

View file

@ -46,11 +46,11 @@ pub fn check_drop_impl(tcx: &TyCtxt, drop_impl_did: DefId) -> Result<(), ()> {
match dtor_self_type.sty {
ty::TyEnum(adt_def, self_to_impl_substs) |
ty::TyStruct(adt_def, self_to_impl_substs) => {
try!(ensure_drop_params_and_item_params_correspond(tcx,
ensure_drop_params_and_item_params_correspond(tcx,
drop_impl_did,
dtor_generics,
&dtor_self_type,
adt_def.did));
adt_def.did)?;
ensure_drop_predicates_are_implied_by_item_defn(tcx,
drop_impl_did,
@ -452,7 +452,7 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'b, 'tcx>(
let fty = field.ty(tcx, substs);
let fty = cx.rcx.fcx.resolve_type_vars_if_possible(
cx.rcx.fcx.normalize_associated_types_in(cx.span, &fty));
try!(iterate_over_potentially_unsafe_regions_in_type(
iterate_over_potentially_unsafe_regions_in_type(
cx,
TypeContext::ADT {
def_id: did,
@ -460,7 +460,7 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'b, 'tcx>(
variant: variant.name,
},
fty,
depth+1))
depth+1)?
}
}
Ok(())
@ -469,8 +469,8 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'b, 'tcx>(
ty::TyTuple(ref tys) |
ty::TyClosure(_, box ty::ClosureSubsts { upvar_tys: ref tys, .. }) => {
for ty in tys {
try!(iterate_over_potentially_unsafe_regions_in_type(
cx, context, ty, depth+1))
iterate_over_potentially_unsafe_regions_in_type(
cx, context, ty, depth+1)?
}
Ok(())
}

View file

@ -124,7 +124,7 @@ pub fn lookup<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
let mode = probe::Mode::MethodCall;
let self_ty = fcx.infcx().resolve_type_vars_if_possible(&self_ty);
let pick = try!(probe::probe(fcx, span, mode, method_name, self_ty, call_expr.id));
let pick = probe::probe(fcx, span, mode, method_name, self_ty, call_expr.id)?;
Ok(confirm::confirm(fcx, span, self_expr, call_expr, self_ty, pick, supplied_method_types))
}
@ -337,7 +337,7 @@ pub fn resolve_ufcs<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
-> Result<Def, MethodError<'tcx>>
{
let mode = probe::Mode::Path;
let pick = try!(probe::probe(fcx, span, mode, method_name, self_ty, expr_id));
let pick = probe::probe(fcx, span, mode, method_name, self_ty, expr_id)?;
let def = pick.item.def();
if let probe::InherentImplPick = pick.kind {

View file

@ -186,7 +186,7 @@ pub fn probe<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
steps,
opt_simplified_steps);
probe_cx.assemble_inherent_candidates();
try!(probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id));
probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?;
probe_cx.pick()
})
}
@ -568,7 +568,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> {
if let Some(applicable_traits) = opt_applicable_traits {
for &trait_did in applicable_traits {
if duplicates.insert(trait_did) {
try!(self.assemble_extension_candidates_for_trait(trait_did));
self.assemble_extension_candidates_for_trait(trait_did)?;
}
}
}
@ -579,7 +579,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> {
let mut duplicates = HashSet::new();
for trait_info in suggest::all_traits(self.fcx.ccx) {
if duplicates.insert(trait_info.def_id) {
try!(self.assemble_extension_candidates_for_trait(trait_info.def_id));
self.assemble_extension_candidates_for_trait(trait_info.def_id)?;
}
}
Ok(())
@ -612,7 +612,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> {
self.assemble_extension_candidates_for_trait_impls(trait_def_id, item.clone());
try!(self.assemble_closure_candidates(trait_def_id, item.clone()));
self.assemble_closure_candidates(trait_def_id, item.clone())?;
self.assemble_projection_candidates(trait_def_id, item.clone());
@ -854,7 +854,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> {
let span = self.span;
let tcx = self.tcx();
try!(self.assemble_extension_candidates_for_all_traits());
self.assemble_extension_candidates_for_all_traits()?;
let out_of_scope_traits = match self.pick_core() {
Some(Ok(p)) => vec![p.item.container().id()],

View file

@ -292,7 +292,7 @@ impl<'a,'tcx> CrateCtxt<'a,'tcx> {
let def_ids = ensure_super_predicates_step(self, trait_def_id);
for def_id in def_ids {
try!(self.ensure_super_predicates(span, def_id));
self.ensure_super_predicates(span, def_id)?;
}
Ok(())

View file

@ -339,31 +339,31 @@ pub fn check_crate(tcx: &TyCtxt, trait_map: ty::TraitMap) -> CompileResult {
// this ensures that later parts of type checking can assume that items
// have valid types and not error
try!(tcx.sess.track_errors(|| {
tcx.sess.track_errors(|| {
time(time_passes, "type collecting", ||
collect::collect_item_types(tcx));
}));
})?;
time(time_passes, "variance inference", ||
variance::infer_variance(tcx));
try!(tcx.sess.track_errors(|| {
tcx.sess.track_errors(|| {
time(time_passes, "coherence checking", ||
coherence::check_coherence(&ccx));
}));
})?;
try!(time(time_passes, "wf checking", ||
check::check_wf_new(&ccx)));
time(time_passes, "wf checking", ||
check::check_wf_new(&ccx))?;
try!(time(time_passes, "item-types checking", ||
check::check_item_types(&ccx)));
time(time_passes, "item-types checking", ||
check::check_item_types(&ccx))?;
try!(time(time_passes, "item-bodies checking", ||
check::check_item_bodies(&ccx)));
time(time_passes, "item-bodies checking", ||
check::check_item_bodies(&ccx))?;
try!(time(time_passes, "drop-impl checking", ||
check::check_drop_impls(&ccx)));
time(time_passes, "drop-impl checking", ||
check::check_drop_impls(&ccx))?;
check_for_entry_fn(&ccx);

View file

@ -38,9 +38,9 @@ impl ExternalHtml {
}
pub fn load_string(input: &Path) -> io::Result<Option<String>> {
let mut f = try!(File::open(input));
let mut f = File::open(input)?;
let mut d = Vec::new();
try!(f.read_to_end(&mut d));
f.read_to_end(&mut d)?;
Ok(str::from_utf8(&d).map(|s| s.to_string()).ok())
}

View file

@ -29,7 +29,7 @@ impl<'a> fmt::Display for Escape<'a> {
for (i, ch) in s.bytes().enumerate() {
match ch as char {
'<' | '>' | '&' | '\'' | '"' => {
try!(fmt.write_str(&pile_o_bits[last.. i]));
fmt.write_str(&pile_o_bits[last.. i])?;
let s = match ch as char {
'>' => "&gt;",
'<' => "&lt;",
@ -38,7 +38,7 @@ impl<'a> fmt::Display for Escape<'a> {
'"' => "&quot;",
_ => unreachable!()
};
try!(fmt.write_str(s));
fmt.write_str(s)?;
last = i + 1;
}
_ => {}
@ -46,7 +46,7 @@ impl<'a> fmt::Display for Escape<'a> {
}
if last < s.len() {
try!(fmt.write_str(&pile_o_bits[last..]));
fmt.write_str(&pile_o_bits[last..])?;
}
Ok(())
}

View file

@ -77,8 +77,8 @@ impl ConstnessSpace {
impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, item) in self.0.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}", item));
if i != 0 { write!(f, ", ")?; }
write!(f, "{}", item)?;
}
Ok(())
}
@ -89,9 +89,9 @@ impl<'a> fmt::Display for TyParamBounds<'a> {
let &TyParamBounds(bounds) = self;
for (i, bound) in bounds.iter().enumerate() {
if i > 0 {
try!(f.write_str(" + "));
f.write_str(" + ")?;
}
try!(write!(f, "{}", *bound));
write!(f, "{}", *bound)?;
}
Ok(())
}
@ -100,36 +100,36 @@ impl<'a> fmt::Display for TyParamBounds<'a> {
impl fmt::Display for clean::Generics {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.lifetimes.is_empty() && self.type_params.is_empty() { return Ok(()) }
try!(f.write_str("&lt;"));
f.write_str("&lt;")?;
for (i, life) in self.lifetimes.iter().enumerate() {
if i > 0 {
try!(f.write_str(", "));
f.write_str(", ")?;
}
try!(write!(f, "{}", *life));
write!(f, "{}", *life)?;
}
if !self.type_params.is_empty() {
if !self.lifetimes.is_empty() {
try!(f.write_str(", "));
f.write_str(", ")?;
}
for (i, tp) in self.type_params.iter().enumerate() {
if i > 0 {
try!(f.write_str(", "))
f.write_str(", ")?
}
try!(f.write_str(&tp.name));
f.write_str(&tp.name)?;
if !tp.bounds.is_empty() {
try!(write!(f, ": {}", TyParamBounds(&tp.bounds)));
write!(f, ": {}", TyParamBounds(&tp.bounds))?;
}
match tp.default {
Some(ref ty) => { try!(write!(f, " = {}", ty)); },
Some(ref ty) => { write!(f, " = {}", ty)?; },
None => {}
};
}
}
try!(f.write_str("&gt;"));
f.write_str("&gt;")?;
Ok(())
}
}
@ -140,40 +140,40 @@ impl<'a> fmt::Display for WhereClause<'a> {
if gens.where_predicates.is_empty() {
return Ok(());
}
try!(f.write_str(" <span class='where'>where "));
f.write_str(" <span class='where'>where ")?;
for (i, pred) in gens.where_predicates.iter().enumerate() {
if i > 0 {
try!(f.write_str(", "));
f.write_str(", ")?;
}
match pred {
&clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
let bounds = bounds;
try!(write!(f, "{}: {}", ty, TyParamBounds(bounds)));
write!(f, "{}: {}", ty, TyParamBounds(bounds))?;
}
&clean::WherePredicate::RegionPredicate { ref lifetime,
ref bounds } => {
try!(write!(f, "{}: ", lifetime));
write!(f, "{}: ", lifetime)?;
for (i, lifetime) in bounds.iter().enumerate() {
if i > 0 {
try!(f.write_str(" + "));
f.write_str(" + ")?;
}
try!(write!(f, "{}", lifetime));
write!(f, "{}", lifetime)?;
}
}
&clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
try!(write!(f, "{} == {}", lhs, rhs));
write!(f, "{} == {}", lhs, rhs)?;
}
}
}
try!(f.write_str("</span>"));
f.write_str("</span>")?;
Ok(())
}
}
impl fmt::Display for clean::Lifetime {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str(self.get_ref()));
f.write_str(self.get_ref())?;
Ok(())
}
}
@ -181,14 +181,14 @@ impl fmt::Display for clean::Lifetime {
impl fmt::Display for clean::PolyTrait {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if !self.lifetimes.is_empty() {
try!(f.write_str("for&lt;"));
f.write_str("for&lt;")?;
for (i, lt) in self.lifetimes.iter().enumerate() {
if i > 0 {
try!(f.write_str(", "));
f.write_str(", ")?;
}
try!(write!(f, "{}", lt));
write!(f, "{}", lt)?;
}
try!(f.write_str("&gt; "));
f.write_str("&gt; ")?;
}
write!(f, "{}", self.trait_)
}
@ -218,46 +218,46 @@ impl fmt::Display for clean::PathParameters {
ref lifetimes, ref types, ref bindings
} => {
if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
try!(f.write_str("&lt;"));
f.write_str("&lt;")?;
let mut comma = false;
for lifetime in lifetimes {
if comma {
try!(f.write_str(", "));
f.write_str(", ")?;
}
comma = true;
try!(write!(f, "{}", *lifetime));
write!(f, "{}", *lifetime)?;
}
for ty in types {
if comma {
try!(f.write_str(", "));
f.write_str(", ")?;
}
comma = true;
try!(write!(f, "{}", *ty));
write!(f, "{}", *ty)?;
}
for binding in bindings {
if comma {
try!(f.write_str(", "));
f.write_str(", ")?;
}
comma = true;
try!(write!(f, "{}", *binding));
write!(f, "{}", *binding)?;
}
try!(f.write_str("&gt;"));
f.write_str("&gt;")?;
}
}
clean::PathParameters::Parenthesized { ref inputs, ref output } => {
try!(f.write_str("("));
f.write_str("(")?;
let mut comma = false;
for ty in inputs {
if comma {
try!(f.write_str(", "));
f.write_str(", ")?;
}
comma = true;
try!(write!(f, "{}", *ty));
write!(f, "{}", *ty)?;
}
try!(f.write_str(")"));
f.write_str(")")?;
if let Some(ref ty) = *output {
try!(f.write_str(" -&gt; "));
try!(write!(f, "{}", ty));
f.write_str(" -&gt; ")?;
write!(f, "{}", ty)?;
}
}
}
@ -267,7 +267,7 @@ impl fmt::Display for clean::PathParameters {
impl fmt::Display for clean::PathSegment {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str(&self.name));
f.write_str(&self.name)?;
write!(f, "{}", self.params)
}
}
@ -275,14 +275,14 @@ impl fmt::Display for clean::PathSegment {
impl fmt::Display for clean::Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.global {
try!(f.write_str("::"))
f.write_str("::")?
}
for (i, seg) in self.segments.iter().enumerate() {
if i > 0 {
try!(f.write_str("::"))
f.write_str("::")?
}
try!(write!(f, "{}", seg));
write!(f, "{}", seg)?;
}
Ok(())
}
@ -339,20 +339,20 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
Some(mut root) => {
for seg in &path.segments[..amt] {
if "super" == seg.name || "self" == seg.name {
try!(write!(w, "{}::", seg.name));
write!(w, "{}::", seg.name)?;
} else {
root.push_str(&seg.name);
root.push_str("/");
try!(write!(w, "<a class='mod'
write!(w, "<a class='mod'
href='{}index.html'>{}</a>::",
root,
seg.name));
seg.name)?;
}
}
}
None => {
for seg in &path.segments[..amt] {
try!(write!(w, "{}::", seg.name));
write!(w, "{}::", seg.name)?;
}
}
}
@ -360,12 +360,12 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
match href(did) {
Some((url, shortty, fqp)) => {
try!(write!(w, "<a class='{}' href='{}' title='{}'>{}</a>",
shortty, url, fqp.join("::"), last.name));
write!(w, "<a class='{}' href='{}' title='{}'>{}</a>",
shortty, url, fqp.join("::"), last.name)?;
}
_ => try!(write!(w, "{}", last.name)),
_ => write!(w, "{}", last.name)?,
}
try!(write!(w, "{}", last.params));
write!(w, "{}", last.params)?;
Ok(())
}
@ -378,9 +378,9 @@ fn primitive_link(f: &mut fmt::Formatter,
Some(&LOCAL_CRATE) => {
let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
let len = if len == 0 {0} else {len - 1};
try!(write!(f, "<a class='primitive' href='{}primitive.{}.html'>",
write!(f, "<a class='primitive' href='{}primitive.{}.html'>",
repeat("../").take(len).collect::<String>(),
prim.to_url_str()));
prim.to_url_str())?;
needs_termination = true;
}
Some(&cnum) => {
@ -398,10 +398,10 @@ fn primitive_link(f: &mut fmt::Formatter,
};
match loc {
Some(root) => {
try!(write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
root,
path.0.first().unwrap(),
prim.to_url_str()));
prim.to_url_str())?;
needs_termination = true;
}
None => {}
@ -409,9 +409,9 @@ fn primitive_link(f: &mut fmt::Formatter,
}
None => {}
}
try!(write!(f, "{}", name));
write!(f, "{}", name)?;
if needs_termination {
try!(write!(f, "</a>"));
write!(f, "</a>")?;
}
Ok(())
}
@ -422,8 +422,8 @@ fn tybounds(w: &mut fmt::Formatter,
match *typarams {
Some(ref params) => {
for param in params {
try!(write!(w, " + "));
try!(write!(w, "{}", *param));
write!(w, " + ")?;
write!(w, "{}", *param)?;
}
Ok(())
}
@ -439,7 +439,7 @@ impl fmt::Display for clean::Type {
}
clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
// Paths like T::Output and Self::Output should be rendered with all segments
try!(resolved_path(f, did, path, is_generic));
resolved_path(f, did, path, is_generic)?;
tybounds(f, typarams)
}
clean::Infer => write!(f, "_"),
@ -459,25 +459,25 @@ impl fmt::Display for clean::Type {
match &**typs {
[] => primitive_link(f, clean::PrimitiveTuple, "()"),
[ref one] => {
try!(primitive_link(f, clean::PrimitiveTuple, "("));
try!(write!(f, "{},", one));
primitive_link(f, clean::PrimitiveTuple, "(")?;
write!(f, "{},", one)?;
primitive_link(f, clean::PrimitiveTuple, ")")
}
many => {
try!(primitive_link(f, clean::PrimitiveTuple, "("));
try!(write!(f, "{}", CommaSep(&many)));
primitive_link(f, clean::PrimitiveTuple, "(")?;
write!(f, "{}", CommaSep(&many))?;
primitive_link(f, clean::PrimitiveTuple, ")")
}
}
}
clean::Vector(ref t) => {
try!(primitive_link(f, clean::Slice, &format!("[")));
try!(write!(f, "{}", t));
primitive_link(f, clean::Slice, &format!("["))?;
write!(f, "{}", t)?;
primitive_link(f, clean::Slice, &format!("]"))
}
clean::FixedVector(ref t, ref s) => {
try!(primitive_link(f, clean::PrimitiveType::Array, "["));
try!(write!(f, "{}", t));
primitive_link(f, clean::PrimitiveType::Array, "[")?;
write!(f, "{}", t)?;
primitive_link(f, clean::PrimitiveType::Array,
&format!("; {}]", *s))
}
@ -489,8 +489,8 @@ impl fmt::Display for clean::Type {
&format!("*{}{}", RawMutableSpace(m), t))
}
_ => {
try!(primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
&format!("*{}", RawMutableSpace(m))));
primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
&format!("*{}", RawMutableSpace(m)))?;
write!(f, "{}", t)
}
}
@ -508,9 +508,9 @@ impl fmt::Display for clean::Type {
primitive_link(f, clean::Slice,
&format!("&amp;{}{}[{}]", lt, m, **bt)),
_ => {
try!(primitive_link(f, clean::Slice,
&format!("&amp;{}{}[", lt, m)));
try!(write!(f, "{}", **bt));
primitive_link(f, clean::Slice,
&format!("&amp;{}{}[", lt, m))?;
write!(f, "{}", **bt)?;
primitive_link(f, clean::Slice, "]")
}
}
@ -523,9 +523,9 @@ impl fmt::Display for clean::Type {
clean::PolyTraitRef(ref bounds) => {
for (i, bound) in bounds.iter().enumerate() {
if i != 0 {
try!(write!(f, " + "));
write!(f, " + ")?;
}
try!(write!(f, "{}", *bound));
write!(f, "{}", *bound)?;
}
Ok(())
}
@ -544,9 +544,9 @@ impl fmt::Display for clean::Type {
ref self_type,
trait_: box clean::ResolvedPath { did, ref typarams, .. },
} => {
try!(write!(f, "{}::", self_type));
write!(f, "{}::", self_type)?;
let path = clean::Path::singleton(name.clone());
try!(resolved_path(f, did, &path, false));
resolved_path(f, did, &path, false)?;
// FIXME: `typarams` are not rendered, and this seems bad?
drop(typarams);
@ -564,13 +564,13 @@ impl fmt::Display for clean::Type {
impl fmt::Display for clean::Impl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "impl{} ", self.generics));
write!(f, "impl{} ", self.generics)?;
if let Some(ref ty) = self.trait_ {
try!(write!(f, "{}{} for ",
write!(f, "{}{} for ",
if self.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" },
*ty));
*ty)?;
}
try!(write!(f, "{}{}", self.for_, WhereClause(&self.generics)));
write!(f, "{}{}", self.for_, WhereClause(&self.generics))?;
Ok(())
}
}
@ -578,11 +578,11 @@ impl fmt::Display for clean::Impl {
impl fmt::Display for clean::Arguments {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, input) in self.values.iter().enumerate() {
if i > 0 { try!(write!(f, ", ")); }
if i > 0 { write!(f, ", ")?; }
if !input.name.is_empty() {
try!(write!(f, "{}: ", input.name));
write!(f, "{}: ", input.name)?;
}
try!(write!(f, "{}", input.type_));
write!(f, "{}", input.type_)?;
}
Ok(())
}
@ -678,12 +678,12 @@ impl fmt::Display for clean::Import {
write!(f, "use {}::*;", *src)
}
clean::ImportList(ref src, ref names) => {
try!(write!(f, "use {}::{{", *src));
write!(f, "use {}::{{", *src)?;
for (i, n) in names.iter().enumerate() {
if i > 0 {
try!(write!(f, ", "));
write!(f, ", ")?;
}
try!(write!(f, "{}", *n));
write!(f, "{}", *n)?;
}
write!(f, "}};")
}
@ -698,9 +698,9 @@ impl fmt::Display for clean::ImportSource {
_ => {
for (i, seg) in self.path.segments.iter().enumerate() {
if i > 0 {
try!(write!(f, "::"))
write!(f, "::")?
}
try!(write!(f, "{}", seg.name));
write!(f, "{}", seg.name)?;
}
Ok(())
}
@ -713,13 +713,13 @@ impl fmt::Display for clean::ViewListIdent {
match self.source {
Some(did) => {
let path = clean::Path::singleton(self.name.clone());
try!(resolved_path(f, did, &path, false));
resolved_path(f, did, &path, false)?;
}
_ => try!(write!(f, "{}", self.name)),
_ => write!(f, "{}", self.name)?,
}
if let Some(ref name) = self.rename {
try!(write!(f, " as {}", name));
write!(f, " as {}", name)?;
}
Ok(())
}

View file

@ -48,12 +48,12 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
out: &mut Write) -> io::Result<()> {
use syntax::parse::lexer::Reader;
try!(write!(out, "<pre "));
write!(out, "<pre ")?;
match id {
Some(id) => try!(write!(out, "id='{}' ", id)),
Some(id) => write!(out, "id='{}' ", id)?,
None => {}
}
try!(write!(out, "class='rust {}'>\n", class.unwrap_or("")));
write!(out, "class='rust {}'>\n", class.unwrap_or(""))?;
let mut is_attribute = false;
let mut is_macro = false;
let mut is_macro_nonterminal = false;
@ -66,16 +66,16 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
let klass = match next.tok {
token::Whitespace => {
try!(write!(out, "{}", Escape(&snip(next.sp))));
write!(out, "{}", Escape(&snip(next.sp)))?;
continue
},
token::Comment => {
try!(write!(out, "<span class='comment'>{}</span>",
Escape(&snip(next.sp))));
write!(out, "<span class='comment'>{}</span>",
Escape(&snip(next.sp)))?;
continue
},
token::Shebang(s) => {
try!(write!(out, "{}", Escape(&s.as_str())));
write!(out, "{}", Escape(&s.as_str()))?;
continue
},
// If this '&' token is directly adjacent to another token, assume
@ -114,13 +114,13 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
// span when we see the ']'.
token::Pound => {
is_attribute = true;
try!(write!(out, r"<span class='attribute'>#"));
write!(out, r"<span class='attribute'>#")?;
continue
}
token::CloseDelim(token::Bracket) => {
if is_attribute {
is_attribute = false;
try!(write!(out, "]</span>"));
write!(out, "]</span>")?;
continue
} else {
""
@ -178,10 +178,10 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
// stringifying this token
let snip = sess.codemap().span_to_snippet(next.sp).unwrap();
if klass == "" {
try!(write!(out, "{}", Escape(&snip)));
write!(out, "{}", Escape(&snip))?;
} else {
try!(write!(out, "<span class='{}'>{}</span>", klass,
Escape(&snip)));
write!(out, "<span class='{}'>{}</span>", klass,
Escape(&snip))?;
}
}

File diff suppressed because it is too large Load diff

View file

@ -183,15 +183,15 @@ impl fmt::Debug for Toc {
impl fmt::Display for Toc {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "<ul>"));
write!(fmt, "<ul>")?;
for entry in &self.entries {
// recursively format this table of contents (the
// `{children}` is the key).
try!(write!(fmt,
write!(fmt,
"\n<li><a href=\"#{id}\">{num} {name}</a>{children}</li>",
id = entry.id,
num = entry.sec_number, name = entry.name,
children = entry.children))
children = entry.children)?
}
write!(fmt, "</ul>")
}

View file

@ -332,10 +332,10 @@ fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
let mut externs = HashMap::new();
for arg in &matches.opt_strs("extern") {
let mut parts = arg.splitn(2, '=');
let name = try!(parts.next().ok_or("--extern value must not be empty".to_string()));
let location = try!(parts.next()
let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
let location = parts.next()
.ok_or("--extern value must be of the format `foo=bar`"
.to_string()));
.to_string())?;
let name = name.to_string();
externs.entry(name).or_insert(vec![]).push(location.to_string());
}
@ -502,6 +502,6 @@ fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
json.insert("crate".to_string(), crate_json);
json.insert("plugins".to_string(), Json::Object(plugins_json));
let mut file = try!(File::create(&dst));
let mut file = File::create(&dst)?;
write!(&mut file, "{}", Json::Object(json))
}

View file

@ -23,7 +23,7 @@ impl<
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
try!(s.emit_seq_elt(i, |s| e.encode(s)));
s.emit_seq_elt(i, |s| e.encode(s))?;
}
Ok(())
})
@ -35,7 +35,7 @@ impl<T:Decodable> Decodable for LinkedList<T> {
d.read_seq(|d, len| {
let mut list = LinkedList::new();
for i in 0..len {
list.push_back(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
list.push_back(d.read_seq_elt(i, |d| Decodable::decode(d))?);
}
Ok(list)
})
@ -46,7 +46,7 @@ impl<T: Encodable> Encodable for VecDeque<T> {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
try!(s.emit_seq_elt(i, |s| e.encode(s)));
s.emit_seq_elt(i, |s| e.encode(s))?;
}
Ok(())
})
@ -58,7 +58,7 @@ impl<T:Decodable> Decodable for VecDeque<T> {
d.read_seq(|d, len| {
let mut deque: VecDeque<T> = VecDeque::new();
for i in 0..len {
deque.push_back(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
deque.push_back(d.read_seq_elt(i, |d| Decodable::decode(d))?);
}
Ok(deque)
})
@ -73,8 +73,8 @@ impl<
e.emit_map(self.len(), |e| {
let mut i = 0;
for (key, val) in self {
try!(e.emit_map_elt_key(i, |e| key.encode(e)));
try!(e.emit_map_elt_val(i, |e| val.encode(e)));
e.emit_map_elt_key(i, |e| key.encode(e))?;
e.emit_map_elt_val(i, |e| val.encode(e))?;
i += 1;
}
Ok(())
@ -90,8 +90,8 @@ impl<
d.read_map(|d, len| {
let mut map = BTreeMap::new();
for i in 0..len {
let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d)));
let key = d.read_map_elt_key(i, |d| Decodable::decode(d))?;
let val = d.read_map_elt_val(i, |d| Decodable::decode(d))?;
map.insert(key, val);
}
Ok(map)
@ -106,7 +106,7 @@ impl<
s.emit_seq(self.len(), |s| {
let mut i = 0;
for e in self {
try!(s.emit_seq_elt(i, |s| e.encode(s)));
s.emit_seq_elt(i, |s| e.encode(s))?;
i += 1;
}
Ok(())
@ -121,7 +121,7 @@ impl<
d.read_seq(|d, len| {
let mut set = BTreeSet::new();
for i in 0..len {
set.insert(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
set.insert(d.read_seq_elt(i, |d| Decodable::decode(d))?);
}
Ok(set)
})
@ -144,7 +144,7 @@ impl<
T: Decodable + CLike
> Decodable for EnumSet<T> {
fn decode<D: Decoder>(d: &mut D) -> Result<EnumSet<T>, D::Error> {
let bits = try!(d.read_uint());
let bits = d.read_uint()?;
let mut set = EnumSet::new();
for bit in 0..(mem::size_of::<usize>()*8) {
if bits & (1 << bit) != 0 {
@ -164,8 +164,8 @@ impl<K, V, S> Encodable for HashMap<K, V, S>
e.emit_map(self.len(), |e| {
let mut i = 0;
for (key, val) in self {
try!(e.emit_map_elt_key(i, |e| key.encode(e)));
try!(e.emit_map_elt_val(i, |e| val.encode(e)));
e.emit_map_elt_key(i, |e| key.encode(e))?;
e.emit_map_elt_val(i, |e| val.encode(e))?;
i += 1;
}
Ok(())
@ -183,8 +183,8 @@ impl<K, V, S> Decodable for HashMap<K, V, S>
let state = Default::default();
let mut map = HashMap::with_capacity_and_hasher(len, state);
for i in 0..len {
let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d)));
let key = d.read_map_elt_key(i, |d| Decodable::decode(d))?;
let val = d.read_map_elt_val(i, |d| Decodable::decode(d))?;
map.insert(key, val);
}
Ok(map)
@ -200,7 +200,7 @@ impl<T, S> Encodable for HashSet<T, S>
s.emit_seq(self.len(), |s| {
let mut i = 0;
for e in self {
try!(s.emit_seq_elt(i, |s| e.encode(s)));
s.emit_seq_elt(i, |s| e.encode(s))?;
i += 1;
}
Ok(())
@ -217,7 +217,7 @@ impl<T, S> Decodable for HashSet<T, S>
let state = Default::default();
let mut set = HashSet::with_capacity_and_hasher(len, state);
for i in 0..len {
set.insert(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
set.insert(d.read_seq_elt(i, |d| Decodable::decode(d))?);
}
Ok(set)
})

View file

@ -319,7 +319,7 @@ pub fn encode<T: ::Encodable>(object: &T) -> Result<string::String, EncoderError
let mut s = String::new();
{
let mut encoder = Encoder::new(&mut s);
try!(object.encode(&mut encoder));
object.encode(&mut encoder)?;
}
Ok(s)
}
@ -371,7 +371,7 @@ pub type EncodeResult = Result<(), EncoderError>;
pub type DecodeResult<T> = Result<T, DecoderError>;
fn escape_str(wr: &mut fmt::Write, v: &str) -> EncodeResult {
try!(wr.write_str("\""));
wr.write_str("\"")?;
let mut start = 0;
@ -416,19 +416,19 @@ fn escape_str(wr: &mut fmt::Write, v: &str) -> EncodeResult {
};
if start < i {
try!(wr.write_str(&v[start..i]));
wr.write_str(&v[start..i])?;
}
try!(wr.write_str(escaped));
wr.write_str(escaped)?;
start = i + 1;
}
if start != v.len() {
try!(wr.write_str(&v[start..]));
wr.write_str(&v[start..])?;
}
try!(wr.write_str("\""));
wr.write_str("\"")?;
Ok(())
}
@ -442,12 +442,12 @@ fn spaces(wr: &mut fmt::Write, mut n: usize) -> EncodeResult {
const BUF: &'static str = " ";
while n >= BUF.len() {
try!(wr.write_str(BUF));
wr.write_str(BUF)?;
n -= BUF.len();
}
if n > 0 {
try!(wr.write_str(&BUF[..n]));
wr.write_str(&BUF[..n])?;
}
Ok(())
}
@ -491,7 +491,7 @@ impl<'a> ::Encoder for Encoder<'a> {
fn emit_nil(&mut self) -> EncodeResult {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "null"));
write!(self.writer, "null")?;
Ok(())
}
@ -510,9 +510,9 @@ impl<'a> ::Encoder for Encoder<'a> {
fn emit_bool(&mut self, v: bool) -> EncodeResult {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if v {
try!(write!(self.writer, "true"));
write!(self.writer, "true")?;
} else {
try!(write!(self.writer, "false"));
write!(self.writer, "false")?;
}
Ok(())
}
@ -551,11 +551,11 @@ impl<'a> ::Encoder for Encoder<'a> {
escape_str(self.writer, name)
} else {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "{{\"variant\":"));
try!(escape_str(self.writer, name));
try!(write!(self.writer, ",\"fields\":["));
try!(f(self));
try!(write!(self.writer, "]}}"));
write!(self.writer, "{{\"variant\":")?;
escape_str(self.writer, name)?;
write!(self.writer, ",\"fields\":[")?;
f(self)?;
write!(self.writer, "]}}")?;
Ok(())
}
}
@ -565,7 +565,7 @@ impl<'a> ::Encoder for Encoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx != 0 {
try!(write!(self.writer, ","));
write!(self.writer, ",")?;
}
f(self)
}
@ -595,9 +595,9 @@ impl<'a> ::Encoder for Encoder<'a> {
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "{{"));
try!(f(self));
try!(write!(self.writer, "}}"));
write!(self.writer, "{{")?;
f(self)?;
write!(self.writer, "}}")?;
Ok(())
}
@ -605,9 +605,9 @@ impl<'a> ::Encoder for Encoder<'a> {
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx != 0 { try!(write!(self.writer, ",")); }
try!(escape_str(self.writer, name));
try!(write!(self.writer, ":"));
if idx != 0 { write!(self.writer, ",")?; }
escape_str(self.writer, name)?;
write!(self.writer, ":")?;
f(self)
}
@ -658,9 +658,9 @@ impl<'a> ::Encoder for Encoder<'a> {
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "["));
try!(f(self));
try!(write!(self.writer, "]"));
write!(self.writer, "[")?;
f(self)?;
write!(self.writer, "]")?;
Ok(())
}
@ -669,7 +669,7 @@ impl<'a> ::Encoder for Encoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx != 0 {
try!(write!(self.writer, ","));
write!(self.writer, ",")?;
}
f(self)
}
@ -678,9 +678,9 @@ impl<'a> ::Encoder for Encoder<'a> {
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "{{"));
try!(f(self));
try!(write!(self.writer, "}}"));
write!(self.writer, "{{")?;
f(self)?;
write!(self.writer, "}}")?;
Ok(())
}
@ -688,9 +688,9 @@ impl<'a> ::Encoder for Encoder<'a> {
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx != 0 { try!(write!(self.writer, ",")) }
if idx != 0 { write!(self.writer, ",")? }
self.is_emitting_map_key = true;
try!(f(self));
f(self)?;
self.is_emitting_map_key = false;
Ok(())
}
@ -699,7 +699,7 @@ impl<'a> ::Encoder for Encoder<'a> {
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, ":"));
write!(self.writer, ":")?;
f(self)
}
}
@ -739,7 +739,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
fn emit_nil(&mut self) -> EncodeResult {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "null"));
write!(self.writer, "null")?;
Ok(())
}
@ -758,9 +758,9 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
fn emit_bool(&mut self, v: bool) -> EncodeResult {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if v {
try!(write!(self.writer, "true"));
write!(self.writer, "true")?;
} else {
try!(write!(self.writer, "false"));
write!(self.writer, "false")?;
}
Ok(())
}
@ -797,23 +797,23 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
escape_str(self.writer, name)
} else {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "{{\n"));
write!(self.writer, "{{\n")?;
self.curr_indent += self.indent;
try!(spaces(self.writer, self.curr_indent));
try!(write!(self.writer, "\"variant\": "));
try!(escape_str(self.writer, name));
try!(write!(self.writer, ",\n"));
try!(spaces(self.writer, self.curr_indent));
try!(write!(self.writer, "\"fields\": [\n"));
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "\"variant\": ")?;
escape_str(self.writer, name)?;
write!(self.writer, ",\n")?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "\"fields\": [\n")?;
self.curr_indent += self.indent;
try!(f(self));
f(self)?;
self.curr_indent -= self.indent;
try!(write!(self.writer, "\n"));
try!(spaces(self.writer, self.curr_indent));
write!(self.writer, "\n")?;
spaces(self.writer, self.curr_indent)?;
self.curr_indent -= self.indent;
try!(write!(self.writer, "]\n"));
try!(spaces(self.writer, self.curr_indent));
try!(write!(self.writer, "}}"));
write!(self.writer, "]\n")?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "}}")?;
Ok(())
}
}
@ -823,9 +823,9 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx != 0 {
try!(write!(self.writer, ",\n"));
write!(self.writer, ",\n")?;
}
try!(spaces(self.writer, self.curr_indent));
spaces(self.writer, self.curr_indent)?;
f(self)
}
@ -856,15 +856,15 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if len == 0 {
try!(write!(self.writer, "{{}}"));
write!(self.writer, "{{}}")?;
} else {
try!(write!(self.writer, "{{"));
write!(self.writer, "{{")?;
self.curr_indent += self.indent;
try!(f(self));
f(self)?;
self.curr_indent -= self.indent;
try!(write!(self.writer, "\n"));
try!(spaces(self.writer, self.curr_indent));
try!(write!(self.writer, "}}"));
write!(self.writer, "\n")?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "}}")?;
}
Ok(())
}
@ -874,13 +874,13 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx == 0 {
try!(write!(self.writer, "\n"));
write!(self.writer, "\n")?;
} else {
try!(write!(self.writer, ",\n"));
write!(self.writer, ",\n")?;
}
try!(spaces(self.writer, self.curr_indent));
try!(escape_str(self.writer, name));
try!(write!(self.writer, ": "));
spaces(self.writer, self.curr_indent)?;
escape_str(self.writer, name)?;
write!(self.writer, ": ")?;
f(self)
}
@ -932,15 +932,15 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if len == 0 {
try!(write!(self.writer, "[]"));
write!(self.writer, "[]")?;
} else {
try!(write!(self.writer, "["));
write!(self.writer, "[")?;
self.curr_indent += self.indent;
try!(f(self));
f(self)?;
self.curr_indent -= self.indent;
try!(write!(self.writer, "\n"));
try!(spaces(self.writer, self.curr_indent));
try!(write!(self.writer, "]"));
write!(self.writer, "\n")?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "]")?;
}
Ok(())
}
@ -950,11 +950,11 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx == 0 {
try!(write!(self.writer, "\n"));
write!(self.writer, "\n")?;
} else {
try!(write!(self.writer, ",\n"));
write!(self.writer, ",\n")?;
}
try!(spaces(self.writer, self.curr_indent));
spaces(self.writer, self.curr_indent)?;
f(self)
}
@ -963,15 +963,15 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if len == 0 {
try!(write!(self.writer, "{{}}"));
write!(self.writer, "{{}}")?;
} else {
try!(write!(self.writer, "{{"));
write!(self.writer, "{{")?;
self.curr_indent += self.indent;
try!(f(self));
f(self)?;
self.curr_indent -= self.indent;
try!(write!(self.writer, "\n"));
try!(spaces(self.writer, self.curr_indent));
try!(write!(self.writer, "}}"));
write!(self.writer, "\n")?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "}}")?;
}
Ok(())
}
@ -981,13 +981,13 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx == 0 {
try!(write!(self.writer, "\n"));
write!(self.writer, "\n")?;
} else {
try!(write!(self.writer, ",\n"));
write!(self.writer, ",\n")?;
}
try!(spaces(self.writer, self.curr_indent));
spaces(self.writer, self.curr_indent)?;
self.is_emitting_map_key = true;
try!(f(self));
f(self)?;
self.is_emitting_map_key = false;
Ok(())
}
@ -996,7 +996,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, ": "));
write!(self.writer, ": ")?;
f(self)
}
}
@ -1695,7 +1695,7 @@ impl<T: Iterator<Item=char>> Parser<T> {
'n' => res.push('\n'),
'r' => res.push('\r'),
't' => res.push('\t'),
'u' => match try!(self.decode_hex_escape()) {
'u' => match self.decode_hex_escape()? {
0xDC00 ... 0xDFFF => {
return self.error(LoneLeadingSurrogateInHexEscape)
}
@ -1708,7 +1708,7 @@ impl<T: Iterator<Item=char>> Parser<T> {
_ => return self.error(UnexpectedEndOfHexEscape),
}
let n2 = try!(self.decode_hex_escape());
let n2 = self.decode_hex_escape()?;
if n2 < 0xDC00 || n2 > 0xDFFF {
return self.error(LoneLeadingSurrogateInHexEscape)
}
@ -2174,7 +2174,7 @@ impl ::Decoder for Decoder {
}
fn read_char(&mut self) -> DecodeResult<char> {
let s = try!(self.read_str());
let s = self.read_str()?;
{
let mut it = s.chars();
match (it.next(), it.next()) {
@ -2264,7 +2264,7 @@ impl ::Decoder for Decoder {
fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T> where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
let value = try!(f(self));
let value = f(self)?;
self.pop();
Ok(value)
}
@ -2276,7 +2276,7 @@ impl ::Decoder for Decoder {
-> DecodeResult<T> where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
let mut obj = try!(expect!(self.pop(), Object));
let mut obj = expect!(self.pop(), Object)?;
let value = match obj.remove(&name.to_string()) {
None => {
@ -2290,7 +2290,7 @@ impl ::Decoder for Decoder {
},
Some(json) => {
self.stack.push(json);
try!(f(self))
f(self)?
}
};
self.stack.push(Json::Object(obj));
@ -2346,7 +2346,7 @@ impl ::Decoder for Decoder {
fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
{
let array = try!(expect!(self.pop(), Array));
let array = expect!(self.pop(), Array)?;
let len = array.len();
for v in array.into_iter().rev() {
self.stack.push(v);
@ -2363,7 +2363,7 @@ impl ::Decoder for Decoder {
fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
{
let obj = try!(expect!(self.pop(), Object));
let obj = expect!(self.pop(), Object)?;
let len = obj.len();
for (key, value) in obj {
self.stack.push(value);

View file

@ -410,13 +410,13 @@ impl<T: ?Sized + Encodable> Encodable for Box<T> {
impl< T: Decodable> Decodable for Box<T> {
fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
Ok(box try!(Decodable::decode(d)))
Ok(box Decodable::decode(d)?)
}
}
impl< T: Decodable> Decodable for Box<[T]> {
fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
let v: Vec<T> = try!(Decodable::decode(d));
let v: Vec<T> = Decodable::decode(d)?;
Ok(v.into_boxed_slice())
}
}
@ -431,7 +431,7 @@ impl<T:Encodable> Encodable for Rc<T> {
impl<T:Decodable> Decodable for Rc<T> {
#[inline]
fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
Ok(Rc::new(try!(Decodable::decode(d))))
Ok(Rc::new(Decodable::decode(d)?))
}
}
@ -439,7 +439,7 @@ impl<T:Encodable> Encodable for [T] {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
try!(s.emit_seq_elt(i, |s| e.encode(s)))
s.emit_seq_elt(i, |s| e.encode(s))?
}
Ok(())
})
@ -450,7 +450,7 @@ impl<T:Encodable> Encodable for Vec<T> {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
try!(s.emit_seq_elt(i, |s| e.encode(s)))
s.emit_seq_elt(i, |s| e.encode(s))?
}
Ok(())
})
@ -462,7 +462,7 @@ impl<T:Decodable> Decodable for Vec<T> {
d.read_seq(|d, len| {
let mut v = Vec::with_capacity(len);
for i in 0..len {
v.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
}
Ok(v)
})
@ -484,7 +484,7 @@ impl<T:Decodable> Decodable for Option<T> {
fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
d.read_option(|d, b| {
if b {
Ok(Some(try!(Decodable::decode(d))))
Ok(Some(Decodable::decode(d)?))
} else {
Ok(None)
}
@ -546,7 +546,7 @@ impl Encodable for path::PathBuf {
impl Decodable for path::PathBuf {
fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
let bytes: String = try!(Decodable::decode(d));
let bytes: String = Decodable::decode(d)?;
Ok(path::PathBuf::from(bytes))
}
}
@ -559,7 +559,7 @@ impl<T: Encodable + Copy> Encodable for Cell<T> {
impl<T: Decodable + Copy> Decodable for Cell<T> {
fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
Ok(Cell::new(try!(Decodable::decode(d))))
Ok(Cell::new(Decodable::decode(d)?))
}
}
@ -576,7 +576,7 @@ impl<T: Encodable> Encodable for RefCell<T> {
impl<T: Decodable> Decodable for RefCell<T> {
fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
Ok(RefCell::new(try!(Decodable::decode(d))))
Ok(RefCell::new(Decodable::decode(d)?))
}
}
@ -588,7 +588,7 @@ impl<T:Encodable> Encodable for Arc<T> {
impl<T:Decodable+Send+Sync> Decodable for Arc<T> {
fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
Ok(Arc::new(try!(Decodable::decode(d))))
Ok(Arc::new(Decodable::decode(d)?))
}
}
@ -607,9 +607,9 @@ impl<S:Encoder> EncoderHelpers for S {
{
self.emit_seq(v.len(), |this| {
for (i, e) in v.iter().enumerate() {
try!(this.emit_seq_elt(i, |this| {
this.emit_seq_elt(i, |this| {
f(this, e)
}));
})?;
}
Ok(())
})
@ -629,7 +629,7 @@ impl<D: Decoder> DecoderHelpers for D {
self.read_seq(|this, len| {
let mut v = Vec::with_capacity(len);
for i in 0..len {
v.push(try!(this.read_seq_elt(i, |this| f(this))));
v.push(this.read_seq_elt(i, |this| f(this))?);
}
Ok(v)
})

View file

@ -318,9 +318,9 @@ impl From<CString> for Vec<u8> {
#[stable(feature = "cstr_debug", since = "1.3.0")]
impl fmt::Debug for CStr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "\""));
write!(f, "\"")?;
for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
try!(f.write_char(byte as char));
f.write_char(byte as char)?;
}
write!(f, "\"")
}

View file

@ -305,7 +305,7 @@ impl File {
#[unstable(feature = "file_try_clone", reason = "newly added", issue = "31405")]
pub fn try_clone(&self) -> io::Result<File> {
Ok(File {
inner: try!(self.inner.duplicate())
inner: self.inner.duplicate()?
})
}
}
@ -565,7 +565,7 @@ impl OpenOptions {
}
fn _open(&self, path: &Path) -> io::Result<File> {
let inner = try!(fs_imp::File::open(path, &self.0));
let inner = fs_imp::File::open(path, &self.0)?;
Ok(File { inner: inner })
}
}
@ -1440,7 +1440,7 @@ impl DirBuilder {
fn create_dir_all(&self, path: &Path) -> io::Result<()> {
if path == Path::new("") || path.is_dir() { return Ok(()) }
if let Some(p) = path.parent() {
try!(self.create_dir_all(p))
self.create_dir_all(p)?
}
self.inner.mkdir(path)
}

View file

@ -172,8 +172,8 @@ impl<R: Read> Read for BufReader<R> {
return self.inner.read(buf);
}
let nread = {
let mut rem = try!(self.fill_buf());
try!(rem.read(buf))
let mut rem = self.fill_buf()?;
rem.read(buf)?
};
self.consume(nread);
Ok(nread)
@ -186,7 +186,7 @@ impl<R: Read> BufRead for BufReader<R> {
// If we've reached the end of our internal buffer then we need to fetch
// some more data from the underlying reader.
if self.pos == self.cap {
self.cap = try!(self.inner.read(&mut self.buf));
self.cap = self.inner.read(&mut self.buf)?;
self.pos = 0;
}
Ok(&self.buf[self.pos..self.cap])
@ -237,16 +237,16 @@ impl<R: Seek> Seek for BufReader<R> {
// support seeking by i64::min_value() so we need to handle underflow when subtracting
// remainder.
if let Some(offset) = n.checked_sub(remainder) {
result = try!(self.inner.seek(SeekFrom::Current(offset)));
result = self.inner.seek(SeekFrom::Current(offset))?;
} else {
// seek backwards by our remainder, and then by the offset
try!(self.inner.seek(SeekFrom::Current(-remainder)));
self.inner.seek(SeekFrom::Current(-remainder))?;
self.pos = self.cap; // empty the buffer
result = try!(self.inner.seek(SeekFrom::Current(n)));
result = self.inner.seek(SeekFrom::Current(n))?;
}
} else {
// Seeking with Start/End doesn't care about our buffer length.
result = try!(self.inner.seek(pos));
result = self.inner.seek(pos)?;
}
self.pos = self.cap; // empty the buffer
Ok(result)
@ -461,7 +461,7 @@ impl<W: Write> BufWriter<W> {
impl<W: Write> Write for BufWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if self.buf.len() + buf.len() > self.buf.capacity() {
try!(self.flush_buf());
self.flush_buf()?;
}
if buf.len() >= self.buf.capacity() {
self.panicked = true;
@ -761,7 +761,7 @@ impl<W: Write> Write for LineWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match memchr::memrchr(b'\n', buf) {
Some(i) => {
let n = try!(self.inner.write(&buf[..i + 1]));
let n = self.inner.write(&buf[..i + 1])?;
if n != i + 1 || self.inner.flush().is_err() {
// Do not return errors on partial writes.
return Ok(n);

View file

@ -213,7 +213,7 @@ impl<T> io::Seek for Cursor<T> where T: AsRef<[u8]> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Read for Cursor<T> where T: AsRef<[u8]> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = try!(Read::read(&mut try!(self.fill_buf()), buf));
let n = Read::read(&mut self.fill_buf()?, buf)?;
self.pos += n as u64;
Ok(n)
}
@ -232,7 +232,7 @@ impl<T> BufRead for Cursor<T> where T: AsRef<[u8]> {
impl<'a> Write for Cursor<&'a mut [u8]> {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let pos = cmp::min(self.pos, self.inner.len() as u64);
let amt = try!((&mut self.inner[(pos as usize)..]).write(data));
let amt = (&mut self.inner[(pos as usize)..]).write(data)?;
self.pos += amt as u64;
Ok(amt)
}
@ -271,7 +271,7 @@ impl Write for Cursor<Vec<u8>> {
impl Write for Cursor<Box<[u8]>> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let pos = cmp::min(self.pos, self.inner.len() as u64);
let amt = try!((&mut self.inner[(pos as usize)..]).write(buf));
let amt = (&mut self.inner[(pos as usize)..]).write(buf)?;
self.pos += amt as u64;
Ok(amt)
}

View file

@ -196,7 +196,7 @@ impl<'a> Write for &'a mut [u8] {
#[inline]
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
if try!(self.write(data)) == data.len() {
if self.write(data)? == data.len() {
Ok(())
} else {
Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"))

View file

@ -1433,7 +1433,7 @@ pub struct Chain<T, U> {
impl<T: Read, U: Read> Read for Chain<T, U> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
if !self.done_first {
match try!(self.first.read(buf)) {
match self.first.read(buf)? {
0 => { self.done_first = true; }
n => return Ok(n),
}
@ -1475,7 +1475,7 @@ impl<T: Read> Read for Take<T> {
}
let max = cmp::min(buf.len() as u64, self.limit) as usize;
let n = try!(self.inner.read(&mut buf[..max]));
let n = self.inner.read(&mut buf[..max])?;
self.limit -= n as u64;
Ok(n)
}
@ -1484,7 +1484,7 @@ impl<T: Read> Read for Take<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: BufRead> BufRead for Take<T> {
fn fill_buf(&mut self) -> Result<&[u8]> {
let buf = try!(self.inner.fill_buf());
let buf = self.inner.fill_buf()?;
let cap = cmp::min(buf.len() as u64, self.limit) as usize;
Ok(&buf[..cap])
}

View file

@ -55,7 +55,7 @@ pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
try!(writer.write_all(&buf[..len]));
writer.write_all(&buf[..len])?;
written += len as u64;
}
}

View file

@ -431,13 +431,13 @@ impl ToSocketAddrs for (Ipv6Addr, u16) {
}
fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
let ips = try!(lookup_host(s));
let v: Vec<_> = try!(ips.map(|a| {
let ips = lookup_host(s)?;
let v: Vec<_> = ips.map(|a| {
a.map(|mut a| {
a.set_port(p);
a
})
}).collect());
}).collect()?;
Ok(v.into_iter())
}

View file

@ -487,16 +487,16 @@ impl fmt::Display for Ipv6Addr {
if zeros_len > 1 {
fn fmt_subslice(segments: &[u16], fmt: &mut fmt::Formatter) -> fmt::Result {
if !segments.is_empty() {
try!(write!(fmt, "{:x}", segments[0]));
write!(fmt, "{:x}", segments[0])?;
for &seg in &segments[1..] {
try!(write!(fmt, ":{:x}", seg));
write!(fmt, ":{:x}", seg)?;
}
}
Ok(())
}
try!(fmt_subslice(&self.segments()[..zeros_at], fmt));
try!(fmt.write_str("::"));
fmt_subslice(&self.segments()[..zeros_at], fmt)?;
fmt.write_str("::")?;
fmt_subslice(&self.segments()[zeros_at + zeros_len..], fmt)
} else {
let &[a, b, c, d, e, f, g, h] = &self.segments();

View file

@ -74,7 +74,7 @@ fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T>
where F: FnMut(&SocketAddr) -> io::Result<T>
{
let mut last_err = None;
for addr in try!(addr.to_socket_addrs()) {
for addr in addr.to_socket_addrs()? {
match f(&addr) {
Ok(l) => return Ok(l),
Err(e) => last_err = Some(e),

View file

@ -70,7 +70,7 @@ impl UdpSocket {
#[stable(feature = "rust1", since = "1.0.0")]
pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A)
-> io::Result<usize> {
match try!(addr.to_socket_addrs()).next() {
match addr.to_socket_addrs()?.next() {
Some(addr) => self.0.send_to(buf, &addr),
None => Err(Error::new(ErrorKind::InvalidInput,
"no addresses to send data to")),

View file

@ -315,7 +315,7 @@ pub fn recover<F: FnOnce() -> R + RecoverSafe, R>(f: F) -> Result<R> {
let mut result = None;
unsafe {
let result = &mut result;
try!(unwind::try(move || *result = Some(f())))
unwind::try(move || *result = Some(f()))?
}
Ok(result.unwrap())
}

View file

@ -520,7 +520,7 @@ impl Child {
}
}
let status = try!(self.wait());
let status = self.wait()?;
Ok(Output {
status: status,
stdout: stdout,

View file

@ -234,7 +234,7 @@ impl<T: ?Sized> Mutex<T> {
pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
unsafe {
if self.inner.lock.try_lock() {
Ok(try!(MutexGuard::new(&*self.inner, &self.data)))
Ok(MutexGuard::new(&*self.inner, &self.data)?)
} else {
Err(TryLockError::WouldBlock)
}
@ -353,7 +353,7 @@ impl StaticMutex {
pub fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>> {
unsafe {
if self.lock.try_lock() {
Ok(try!(MutexGuard::new(self, &DUMMY.0)))
Ok(MutexGuard::new(self, &DUMMY.0)?)
} else {
Err(TryLockError::WouldBlock)
}

View file

@ -205,7 +205,7 @@ impl<T: ?Sized> RwLock<T> {
pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<T>> {
unsafe {
if self.inner.lock.try_read() {
Ok(try!(RwLockReadGuard::new(&*self.inner, &self.data)))
Ok(RwLockReadGuard::new(&*self.inner, &self.data)?)
} else {
Err(TryLockError::WouldBlock)
}
@ -257,7 +257,7 @@ impl<T: ?Sized> RwLock<T> {
pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<T>> {
unsafe {
if self.inner.lock.try_write() {
Ok(try!(RwLockWriteGuard::new(&*self.inner, &self.data)))
Ok(RwLockWriteGuard::new(&*self.inner, &self.data)?)
} else {
Err(TryLockError::WouldBlock)
}
@ -382,7 +382,7 @@ impl StaticRwLock {
-> TryLockResult<RwLockReadGuard<'static, ()>> {
unsafe {
if self.lock.try_read(){
Ok(try!(RwLockReadGuard::new(self, &DUMMY.0)))
Ok(RwLockReadGuard::new(self, &DUMMY.0)?)
} else {
Err(TryLockError::WouldBlock)
}
@ -409,7 +409,7 @@ impl StaticRwLock {
-> TryLockResult<RwLockWriteGuard<'static, ()>> {
unsafe {
if self.lock.try_write() {
Ok(try!(RwLockWriteGuard::new(self, &DUMMY.0)))
Ok(RwLockWriteGuard::new(self, &DUMMY.0)?)
} else {
Err(TryLockError::WouldBlock)
}

View file

@ -46,10 +46,10 @@ pub fn log_enabled() -> bool {
// These output functions should now be used everywhere to ensure consistency.
pub fn output(w: &mut Write, idx: isize, addr: *mut libc::c_void,
s: Option<&[u8]>) -> io::Result<()> {
try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH));
write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH)?;
match s.and_then(|s| str::from_utf8(s).ok()) {
Some(string) => try!(demangle(w, string)),
None => try!(write!(w, "<unknown>")),
Some(string) => demangle(w, string)?,
None => write!(w, "<unknown>")?,
}
w.write_all(&['\n' as u8])
}
@ -59,9 +59,9 @@ pub fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
more: bool) -> io::Result<()> {
let file = str::from_utf8(file).unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH)?;
if more {
try!(write!(w, " <... and possibly more>"));
write!(w, " <... and possibly more>")?;
}
w.write_all(&['\n' as u8])
}
@ -121,12 +121,12 @@ pub fn demangle(writer: &mut Write, s: &str) -> io::Result<()> {
// Alright, let's do this.
if !valid {
try!(writer.write_all(s.as_bytes()));
writer.write_all(s.as_bytes())?;
} else {
let mut first = true;
while !inner.is_empty() {
if !first {
try!(writer.write_all(b"::"));
writer.write_all(b"::")?;
} else {
first = false;
}
@ -177,7 +177,7 @@ pub fn demangle(writer: &mut Write, s: &str) -> io::Result<()> {
None => rest.len(),
Some(i) => i,
};
try!(writer.write_all(rest[..idx].as_bytes()));
writer.write_all(rest[..idx].as_bytes())?;
rest = &rest[idx..];
}
}

View file

@ -172,9 +172,9 @@ pub fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
data_addr as *mut libc::c_void)
};
if ret == 0 || data.is_null() {
try!(output(w, idx, addr, None));
output(w, idx, addr, None)?;
} else {
try!(output(w, idx, addr, Some(unsafe { CStr::from_ptr(data).to_bytes() })));
output(w, idx, addr, Some(unsafe { CStr::from_ptr(data).to_bytes() }))?;
}
// pcinfo may return an arbitrary number of file:line pairs,
@ -198,7 +198,7 @@ pub fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
for (i, &(file, line)) in fileline_buf[..fileline_count].iter().enumerate() {
if file.is_null() { continue; } // just to be sure
let file = unsafe { CStr::from_ptr(file).to_bytes() };
try!(output_fileline(w, file, line, i == FILELINE_SIZE - 1));
output_fileline(w, file, line, i == FILELINE_SIZE - 1)?;
}
}

View file

@ -48,8 +48,8 @@ pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
payload: T) -> io::Result<()> {
unsafe {
let payload = &payload as *const T as *const c_void;
try!(cvt(c::setsockopt(*sock.as_inner(), opt, val, payload,
mem::size_of::<T>() as c::socklen_t)));
cvt(c::setsockopt(*sock.as_inner(), opt, val, payload,
mem::size_of::<T>() as c::socklen_t))?;
Ok(())
}
}
@ -59,9 +59,9 @@ pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
unsafe {
let mut slot: T = mem::zeroed();
let mut len = mem::size_of::<T>() as c::socklen_t;
try!(cvt(c::getsockopt(*sock.as_inner(), opt, val,
cvt(c::getsockopt(*sock.as_inner(), opt, val,
&mut slot as *mut _ as *mut _,
&mut len)));
&mut len))?;
assert_eq!(len as usize, mem::size_of::<T>());
Ok(slot)
}
@ -73,7 +73,7 @@ fn sockname<F>(f: F) -> io::Result<SocketAddr>
unsafe {
let mut storage: c::sockaddr_storage = mem::zeroed();
let mut len = mem::size_of_val(&storage) as c::socklen_t;
try!(cvt(f(&mut storage as *mut _ as *mut _, &mut len)));
cvt(f(&mut storage as *mut _ as *mut _, &mut len))?;
sockaddr_to_addr(&storage, len as usize)
}
}
@ -143,11 +143,11 @@ impl Drop for LookupHost {
pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
init();
let c_host = try!(CString::new(host));
let c_host = CString::new(host)?;
let mut res = ptr::null_mut();
unsafe {
try!(cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), ptr::null(),
&mut res)));
cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), ptr::null(),
&mut res))?;
Ok(LookupHost { original: res, cur: res })
}
}
@ -164,10 +164,10 @@ impl TcpStream {
pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
init();
let sock = try!(Socket::new(addr, c::SOCK_STREAM));
let sock = Socket::new(addr, c::SOCK_STREAM)?;
let (addrp, len) = addr.into_inner();
try!(cvt_r(|| unsafe { c::connect(*sock.as_inner(), addrp, len) }));
cvt_r(|| unsafe { c::connect(*sock.as_inner(), addrp, len) })?;
Ok(TcpStream { inner: sock })
}
@ -201,12 +201,12 @@ impl TcpStream {
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
let ret = try!(cvt(unsafe {
let ret = cvt(unsafe {
c::send(*self.inner.as_inner(),
buf.as_ptr() as *const c_void,
len,
0)
}));
})?;
Ok(ret as usize)
}
@ -243,7 +243,7 @@ impl TcpStream {
}
pub fn ttl(&self) -> io::Result<u32> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL));
let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
Ok(raw as u32)
}
@ -252,7 +252,7 @@ impl TcpStream {
}
pub fn only_v6(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY));
let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY)?;
Ok(raw != 0)
}
@ -301,22 +301,22 @@ impl TcpListener {
pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> {
init();
let sock = try!(Socket::new(addr, c::SOCK_STREAM));
let sock = Socket::new(addr, c::SOCK_STREAM)?;
// On platforms with Berkeley-derived sockets, this allows
// to quickly rebind a socket, without needing to wait for
// the OS to clean up the previous one.
if !cfg!(windows) {
try!(setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR,
1 as c_int));
setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR,
1 as c_int)?;
}
// Bind our new socket
let (addrp, len) = addr.into_inner();
try!(cvt(unsafe { c::bind(*sock.as_inner(), addrp, len) }));
cvt(unsafe { c::bind(*sock.as_inner(), addrp, len) })?;
// Start listening
try!(cvt(unsafe { c::listen(*sock.as_inner(), 128) }));
cvt(unsafe { c::listen(*sock.as_inner(), 128) })?;
Ok(TcpListener { inner: sock })
}
@ -333,9 +333,9 @@ impl TcpListener {
pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
let mut len = mem::size_of_val(&storage) as c::socklen_t;
let sock = try!(self.inner.accept(&mut storage as *mut _ as *mut _,
&mut len));
let addr = try!(sockaddr_to_addr(&storage, len as usize));
let sock = self.inner.accept(&mut storage as *mut _ as *mut _,
&mut len)?;
let addr = sockaddr_to_addr(&storage, len as usize)?;
Ok((TcpStream { inner: sock, }, addr))
}
@ -348,7 +348,7 @@ impl TcpListener {
}
pub fn ttl(&self) -> io::Result<u32> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL));
let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
Ok(raw as u32)
}
@ -357,7 +357,7 @@ impl TcpListener {
}
pub fn only_v6(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY));
let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY)?;
Ok(raw != 0)
}
@ -402,9 +402,9 @@ impl UdpSocket {
pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> {
init();
let sock = try!(Socket::new(addr, c::SOCK_DGRAM));
let sock = Socket::new(addr, c::SOCK_DGRAM)?;
let (addrp, len) = addr.into_inner();
try!(cvt(unsafe { c::bind(*sock.as_inner(), addrp, len) }));
cvt(unsafe { c::bind(*sock.as_inner(), addrp, len) })?;
Ok(UdpSocket { inner: sock })
}
@ -423,23 +423,23 @@ impl UdpSocket {
let mut addrlen = mem::size_of_val(&storage) as c::socklen_t;
let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
let n = try!(cvt(unsafe {
let n = cvt(unsafe {
c::recvfrom(*self.inner.as_inner(),
buf.as_mut_ptr() as *mut c_void,
len, 0,
&mut storage as *mut _ as *mut _, &mut addrlen)
}));
Ok((n as usize, try!(sockaddr_to_addr(&storage, addrlen as usize))))
})?;
Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
}
pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> {
let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
let (dstp, dstlen) = dst.into_inner();
let ret = try!(cvt(unsafe {
let ret = cvt(unsafe {
c::sendto(*self.inner.as_inner(),
buf.as_ptr() as *const c_void, len,
0, dstp, dstlen)
}));
})?;
Ok(ret as usize)
}
@ -468,7 +468,7 @@ impl UdpSocket {
}
pub fn broadcast(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST));
let raw: c_int = getsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST)?;
Ok(raw != 0)
}
@ -477,7 +477,7 @@ impl UdpSocket {
}
pub fn multicast_loop_v4(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP));
let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP)?;
Ok(raw != 0)
}
@ -486,7 +486,7 @@ impl UdpSocket {
}
pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL));
let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL)?;
Ok(raw as u32)
}
@ -495,7 +495,7 @@ impl UdpSocket {
}
pub fn multicast_loop_v6(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP));
let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP)?;
Ok(raw != 0)
}
@ -540,7 +540,7 @@ impl UdpSocket {
}
pub fn ttl(&self) -> io::Result<u32> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL));
let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
Ok(raw as u32)
}
@ -549,7 +549,7 @@ impl UdpSocket {
}
pub fn only_v6(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY));
let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY)?;
Ok(raw != 0)
}
@ -567,12 +567,12 @@ impl UdpSocket {
pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
let ret = try!(cvt(unsafe {
let ret = cvt(unsafe {
c::send(*self.inner.as_inner(),
buf.as_ptr() as *const c_void,
len,
0)
}));
})?;
Ok(ret as usize)
}

View file

@ -99,7 +99,7 @@ impl<T> ReentrantMutex<T> {
/// acquired.
pub fn try_lock(&self) -> TryLockResult<ReentrantMutexGuard<T>> {
if unsafe { self.inner.try_lock() } {
Ok(try!(ReentrantMutexGuard::new(&self)))
Ok(ReentrantMutexGuard::new(&self)?)
} else {
Err(TryLockError::WouldBlock)
}

View file

@ -388,32 +388,32 @@ impl fmt::Debug for Wtf8 {
fn write_str_escaped(f: &mut fmt::Formatter, s: &str) -> fmt::Result {
use fmt::Write;
for c in s.chars().flat_map(|c| c.escape_default()) {
try!(f.write_char(c))
f.write_char(c)?
}
Ok(())
}
try!(formatter.write_str("\""));
formatter.write_str("\"")?;
let mut pos = 0;
loop {
match self.next_surrogate(pos) {
None => break,
Some((surrogate_pos, surrogate)) => {
try!(write_str_escaped(
write_str_escaped(
formatter,
unsafe { str::from_utf8_unchecked(
&self.bytes[pos .. surrogate_pos]
)},
));
try!(write!(formatter, "\\u{{{:X}}}", surrogate));
)?;
write!(formatter, "\\u{{{:X}}}", surrogate)?;
pos = surrogate_pos + 3;
}
}
}
try!(write_str_escaped(
write_str_escaped(
formatter,
unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) },
));
)?;
formatter.write_str("\"")
}
}

View file

@ -40,7 +40,7 @@ pub fn write(w: &mut Write) -> io::Result<()> {
static LOCK: StaticMutex = StaticMutex::new();
let _g = LOCK.lock();
try!(writeln!(w, "stack backtrace:"));
writeln!(w, "stack backtrace:")?;
// 100 lines should be enough
const SIZE: usize = 100;
let mut buf: [*mut libc::c_void; SIZE] = unsafe { mem::zeroed() };
@ -48,7 +48,7 @@ pub fn write(w: &mut Write) -> io::Result<()> {
// skipping the first one as it is write itself
for i in 1..cnt {
try!(print(w, i as isize, buf[i], buf[i]))
print(w, i as isize, buf[i], buf[i])?
}
Ok(())
}

View file

@ -33,7 +33,7 @@ pub fn write(w: &mut Write) -> io::Result<()> {
static LOCK: StaticMutex = StaticMutex::new();
let _g = LOCK.lock();
try!(writeln!(w, "stack backtrace:"));
writeln!(w, "stack backtrace:")?;
let mut cx = Context { writer: w, last_error: None, idx: 0 };
return match unsafe {

View file

@ -87,7 +87,7 @@ impl SocketAddr {
unsafe {
let mut addr: libc::sockaddr_un = mem::zeroed();
let mut len = mem::size_of::<libc::sockaddr_un>() as libc::socklen_t;
try!(cvt(f(&mut addr as *mut _ as *mut _, &mut len)));
cvt(f(&mut addr as *mut _ as *mut _, &mut len))?;
SocketAddr::from_parts(addr, len)
}
}
@ -155,9 +155,9 @@ struct AsciiEscaped<'a>(&'a [u8]);
impl<'a> fmt::Display for AsciiEscaped<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "\""));
write!(fmt, "\"")?;
for byte in self.0.iter().cloned().flat_map(ascii::escape_default) {
try!(write!(fmt, "{}", byte as char));
write!(fmt, "{}", byte as char)?;
}
write!(fmt, "\"")
}
@ -200,10 +200,10 @@ impl UnixStream {
pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
fn inner(path: &Path) -> io::Result<UnixStream> {
unsafe {
let inner = try!(Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM));
let (addr, len) = try!(sockaddr_un(path));
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
let (addr, len) = sockaddr_un(path)?;
try!(cvt(libc::connect(*inner.as_inner(), &addr as *const _ as *const _, len)));
cvt(libc::connect(*inner.as_inner(), &addr as *const _ as *const _, len))?;
Ok(UnixStream(inner))
}
}
@ -214,7 +214,7 @@ impl UnixStream {
///
/// Returns two `UnixStream`s which are connected to each other.
pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
let (i1, i2) = try!(Socket::new_pair(libc::AF_UNIX, libc::SOCK_STREAM));
let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_STREAM)?;
Ok((UnixStream(i1), UnixStream(i2)))
}
@ -395,11 +395,11 @@ impl UnixListener {
pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
fn inner(path: &Path) -> io::Result<UnixListener> {
unsafe {
let inner = try!(Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM));
let (addr, len) = try!(sockaddr_un(path));
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
let (addr, len) = sockaddr_un(path)?;
try!(cvt(libc::bind(*inner.as_inner(), &addr as *const _ as *const _, len)));
try!(cvt(libc::listen(*inner.as_inner(), 128)));
cvt(libc::bind(*inner.as_inner(), &addr as *const _ as *const _, len))?;
cvt(libc::listen(*inner.as_inner(), 128))?;
Ok(UnixListener(inner))
}
@ -415,8 +415,8 @@ impl UnixListener {
pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
let mut len = mem::size_of_val(&storage) as libc::socklen_t;
let sock = try!(self.0.accept(&mut storage as *mut _ as *mut _, &mut len));
let addr = try!(SocketAddr::from_parts(storage, len));
let sock = self.0.accept(&mut storage as *mut _ as *mut _, &mut len)?;
let addr = SocketAddr::from_parts(storage, len)?;
Ok((UnixStream(sock), addr))
}
@ -536,10 +536,10 @@ impl UnixDatagram {
pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
fn inner(path: &Path) -> io::Result<UnixDatagram> {
unsafe {
let socket = try!(UnixDatagram::unbound());
let (addr, len) = try!(sockaddr_un(path));
let socket = UnixDatagram::unbound()?;
let (addr, len) = sockaddr_un(path)?;
try!(cvt(libc::bind(*socket.0.as_inner(), &addr as *const _ as *const _, len)));
cvt(libc::bind(*socket.0.as_inner(), &addr as *const _ as *const _, len))?;
Ok(socket)
}
@ -549,7 +549,7 @@ impl UnixDatagram {
/// Creates a Unix Datagram socket which is not bound to any address.
pub fn unbound() -> io::Result<UnixDatagram> {
let inner = try!(Socket::new_raw(libc::AF_UNIX, libc::SOCK_DGRAM));
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_DGRAM)?;
Ok(UnixDatagram(inner))
}
@ -557,7 +557,7 @@ impl UnixDatagram {
///
/// Returns two `UnixDatagrams`s which are connected to each other.
pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
let (i1, i2) = try!(Socket::new_pair(libc::AF_UNIX, libc::SOCK_DGRAM));
let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_DGRAM)?;
Ok((UnixDatagram(i1), UnixDatagram(i2)))
}
@ -568,9 +568,9 @@ impl UnixDatagram {
pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
fn inner(d: &UnixDatagram, path: &Path) -> io::Result<()> {
unsafe {
let (addr, len) = try!(sockaddr_un(path));
let (addr, len) = sockaddr_un(path)?;
try!(cvt(libc::connect(*d.0.as_inner(), &addr as *const _ as *const _, len)));
cvt(libc::connect(*d.0.as_inner(), &addr as *const _ as *const _, len))?;
Ok(())
}
@ -605,7 +605,7 @@ impl UnixDatagram {
/// whence the data came.
pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
let mut count = 0;
let addr = try!(SocketAddr::new(|addr, len| {
let addr = SocketAddr::new(|addr, len| {
unsafe {
count = libc::recvfrom(*self.0.as_inner(),
buf.as_mut_ptr() as *mut _,
@ -621,7 +621,7 @@ impl UnixDatagram {
-1
}
}
}));
})?;
Ok((count as usize, addr))
}
@ -639,14 +639,14 @@ impl UnixDatagram {
pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
fn inner(d: &UnixDatagram, buf: &[u8], path: &Path) -> io::Result<usize> {
unsafe {
let (addr, len) = try!(sockaddr_un(path));
let (addr, len) = sockaddr_un(path)?;
let count = try!(cvt(libc::sendto(*d.0.as_inner(),
let count = cvt(libc::sendto(*d.0.as_inner(),
buf.as_ptr() as *const _,
buf.len(),
0,
&addr as *const _ as *const _,
len)));
len))?;
Ok(count as usize)
}
}

View file

@ -39,11 +39,11 @@ impl FileDesc {
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
let ret = try!(cvt(unsafe {
let ret = cvt(unsafe {
libc::read(self.fd,
buf.as_mut_ptr() as *mut c_void,
buf.len() as size_t)
}));
})?;
Ok(ret as usize)
}
@ -53,11 +53,11 @@ impl FileDesc {
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
let ret = try!(cvt(unsafe {
let ret = cvt(unsafe {
libc::write(self.fd,
buf.as_ptr() as *const c_void,
buf.len() as size_t)
}));
})?;
Ok(ret as usize)
}

View file

@ -418,18 +418,18 @@ impl OpenOptions {
impl File {
pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
let path = try!(cstr(path));
let path = cstr(path)?;
File::open_c(&path, opts)
}
pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
let flags = libc::O_CLOEXEC |
try!(opts.get_access_mode()) |
try!(opts.get_creation_mode()) |
opts.get_access_mode()? |
opts.get_creation_mode()? |
(opts.custom_flags as c_int & !libc::O_ACCMODE);
let fd = try!(cvt_r(|| unsafe {
let fd = cvt_r(|| unsafe {
open64(path.as_ptr(), flags, opts.mode as c_int)
}));
})?;
let fd = FileDesc::new(fd);
// Currently the standard library supports Linux 2.6.18 which did not
@ -448,19 +448,19 @@ impl File {
pub fn file_attr(&self) -> io::Result<FileAttr> {
let mut stat: stat64 = unsafe { mem::zeroed() };
try!(cvt(unsafe {
cvt(unsafe {
fstat64(self.0.raw(), &mut stat)
}));
})?;
Ok(FileAttr { stat: stat })
}
pub fn fsync(&self) -> io::Result<()> {
try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
cvt_r(|| unsafe { libc::fsync(self.0.raw()) })?;
Ok(())
}
pub fn datasync(&self) -> io::Result<()> {
try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
return Ok(());
#[cfg(any(target_os = "macos", target_os = "ios"))]
@ -476,9 +476,9 @@ impl File {
}
pub fn truncate(&self, size: u64) -> io::Result<()> {
try!(cvt_r(|| unsafe {
cvt_r(|| unsafe {
ftruncate64(self.0.raw(), size as off64_t)
}));
})?;
Ok(())
}
@ -502,7 +502,7 @@ impl File {
SeekFrom::End(off) => (libc::SEEK_END, off as off64_t),
SeekFrom::Current(off) => (libc::SEEK_CUR, off as off64_t),
};
let n = try!(cvt(unsafe { lseek64(self.0.raw(), pos, whence) }));
let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
Ok(n as u64)
}
@ -521,8 +521,8 @@ impl DirBuilder {
}
pub fn mkdir(&self, p: &Path) -> io::Result<()> {
let p = try!(cstr(p));
try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }));
let p = cstr(p)?;
cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
Ok(())
}
@ -532,7 +532,7 @@ impl DirBuilder {
}
fn cstr(path: &Path) -> io::Result<CString> {
Ok(try!(CString::new(path.as_os_str().as_bytes())))
Ok(CString::new(path.as_os_str().as_bytes())?)
}
impl FromInner<c_int> for File {
@ -610,7 +610,7 @@ impl fmt::Debug for File {
pub fn readdir(p: &Path) -> io::Result<ReadDir> {
let root = Arc::new(p.to_path_buf());
let p = try!(cstr(p));
let p = cstr(p)?;
unsafe {
let ptr = libc::opendir(p.as_ptr());
if ptr.is_null() {
@ -622,32 +622,32 @@ pub fn readdir(p: &Path) -> io::Result<ReadDir> {
}
pub fn unlink(p: &Path) -> io::Result<()> {
let p = try!(cstr(p));
try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
let p = cstr(p)?;
cvt(unsafe { libc::unlink(p.as_ptr()) })?;
Ok(())
}
pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
let old = try!(cstr(old));
let new = try!(cstr(new));
try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
let old = cstr(old)?;
let new = cstr(new)?;
cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
Ok(())
}
pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
let p = try!(cstr(p));
try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
let p = cstr(p)?;
cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
Ok(())
}
pub fn rmdir(p: &Path) -> io::Result<()> {
let p = try!(cstr(p));
try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
let p = cstr(p)?;
cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
Ok(())
}
pub fn remove_dir_all(path: &Path) -> io::Result<()> {
let filetype = try!(lstat(path)).file_type();
let filetype = lstat(path)?.file_type();
if filetype.is_symlink() {
unlink(path)
} else {
@ -656,27 +656,27 @@ pub fn remove_dir_all(path: &Path) -> io::Result<()> {
}
fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
for child in try!(readdir(path)) {
let child = try!(child);
if try!(child.file_type()).is_dir() {
try!(remove_dir_all_recursive(&child.path()));
for child in readdir(path)? {
let child = child?;
if child.file_type()?.is_dir() {
remove_dir_all_recursive(&child.path())?;
} else {
try!(unlink(&child.path()));
unlink(&child.path())?;
}
}
rmdir(path)
}
pub fn readlink(p: &Path) -> io::Result<PathBuf> {
let c_path = try!(cstr(p));
let c_path = cstr(p)?;
let p = c_path.as_ptr();
let mut buf = Vec::with_capacity(256);
loop {
let buf_read = try!(cvt(unsafe {
let buf_read = cvt(unsafe {
libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity() as libc::size_t)
})) as usize;
})? as usize;
unsafe { buf.set_len(buf_read); }
@ -694,39 +694,39 @@ pub fn readlink(p: &Path) -> io::Result<PathBuf> {
}
pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
let src = try!(cstr(src));
let dst = try!(cstr(dst));
try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
let src = cstr(src)?;
let dst = cstr(dst)?;
cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
Ok(())
}
pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
let src = try!(cstr(src));
let dst = try!(cstr(dst));
try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
let src = cstr(src)?;
let dst = cstr(dst)?;
cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
Ok(())
}
pub fn stat(p: &Path) -> io::Result<FileAttr> {
let p = try!(cstr(p));
let p = cstr(p)?;
let mut stat: stat64 = unsafe { mem::zeroed() };
try!(cvt(unsafe {
cvt(unsafe {
stat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
}));
})?;
Ok(FileAttr { stat: stat })
}
pub fn lstat(p: &Path) -> io::Result<FileAttr> {
let p = try!(cstr(p));
let p = cstr(p)?;
let mut stat: stat64 = unsafe { mem::zeroed() };
try!(cvt(unsafe {
cvt(unsafe {
lstat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
}));
})?;
Ok(FileAttr { stat: stat })
}
pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
let path = try!(CString::new(p.as_os_str().as_bytes()));
let path = CString::new(p.as_os_str().as_bytes())?;
let buf;
unsafe {
let r = libc::realpath(path.as_ptr(), ptr::null_mut());
@ -746,11 +746,11 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
"the source path is not an existing regular file"))
}
let mut reader = try!(File::open(from));
let mut writer = try!(File::create(to));
let perm = try!(reader.metadata()).permissions();
let mut reader = File::open(from)?;
let mut writer = File::create(to)?;
let perm = reader.metadata()?.permissions();
let ret = try!(io::copy(&mut reader, &mut writer));
try!(set_permissions(to, perm));
let ret = io::copy(&mut reader, &mut writer)?;
set_permissions(to, perm)?;
Ok(ret)
}

View file

@ -75,7 +75,7 @@ impl Socket {
}
}
let fd = try!(cvt(libc::socket(fam, ty, 0)));
let fd = cvt(libc::socket(fam, ty, 0))?;
let fd = FileDesc::new(fd);
fd.set_cloexec();
Ok(Socket(fd))
@ -97,7 +97,7 @@ impl Socket {
}
}
try!(cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr())));
cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
let a = FileDesc::new(fds[0]);
a.set_cloexec();
let b = FileDesc::new(fds[1]);
@ -128,9 +128,9 @@ impl Socket {
}
}
let fd = try!(cvt_r(|| unsafe {
let fd = cvt_r(|| unsafe {
libc::accept(self.0.raw(), storage, len)
}));
})?;
let fd = FileDesc::new(fd);
fd.set_cloexec();
Ok(Socket(fd))
@ -185,7 +185,7 @@ impl Socket {
}
pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
let raw: libc::timeval = try!(getsockopt(self, libc::SOL_SOCKET, kind));
let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
if raw.tv_sec == 0 && raw.tv_usec == 0 {
Ok(None)
} else {
@ -201,7 +201,7 @@ impl Socket {
Shutdown::Read => libc::SHUT_RD,
Shutdown::Both => libc::SHUT_RDWR,
};
try!(cvt(unsafe { libc::shutdown(self.0.raw(), how) }));
cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
Ok(())
}
@ -210,7 +210,7 @@ impl Socket {
}
pub fn nodelay(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY));
let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
Ok(raw != 0)
}
@ -220,7 +220,7 @@ impl Socket {
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
let raw: c_int = try!(getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR));
let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
if raw == 0 {
Ok(None)
} else {

View file

@ -110,7 +110,7 @@ pub fn getcwd() -> io::Result<PathBuf> {
pub fn chdir(p: &path::Path) -> io::Result<()> {
let p: &OsStr = p.as_ref();
let p = try!(CString::new(p.as_bytes()));
let p = CString::new(p.as_bytes())?;
unsafe {
match libc::chdir(p.as_ptr()) == (0 as c_int) {
true => Ok(()),
@ -180,16 +180,16 @@ pub fn current_exe() -> io::Result<PathBuf> {
libc::KERN_PROC_PATHNAME as c_int,
-1 as c_int];
let mut sz: libc::size_t = 0;
try!(cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
ptr::null_mut(), &mut sz, ptr::null_mut(),
0 as libc::size_t)));
0 as libc::size_t))?;
if sz == 0 {
return Err(io::Error::last_os_error())
}
let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
try!(cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
v.as_mut_ptr() as *mut libc::c_void, &mut sz,
ptr::null_mut(), 0 as libc::size_t)));
ptr::null_mut(), 0 as libc::size_t))?;
if sz == 0 {
return Err(io::Error::last_os_error());
}
@ -217,11 +217,11 @@ pub fn current_exe() -> io::Result<PathBuf> {
libc::KERN_PROC_ARGV];
let mib = mib.as_mut_ptr();
let mut argv_len = 0;
try!(cvt(libc::sysctl(mib, 4, 0 as *mut _, &mut argv_len,
0 as *mut _, 0)));
cvt(libc::sysctl(mib, 4, 0 as *mut _, &mut argv_len,
0 as *mut _, 0))?;
let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
try!(cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _,
&mut argv_len, 0 as *mut _, 0)));
cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _,
&mut argv_len, 0 as *mut _, 0))?;
argv.set_len(argv_len as usize);
if argv[0].is_null() {
return Err(io::Error::new(io::ErrorKind::Other,
@ -460,7 +460,7 @@ pub fn env() -> Env {
pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
// environment variables with a nul byte can't be set, so their value is
// always None as well
let k = try!(CString::new(k.as_bytes()));
let k = CString::new(k.as_bytes())?;
let _g = ENV_LOCK.lock();
Ok(unsafe {
let s = libc::getenv(k.as_ptr()) as *const _;
@ -473,8 +473,8 @@ pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
}
pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
let k = try!(CString::new(k.as_bytes()));
let v = try!(CString::new(v.as_bytes()));
let k = CString::new(k.as_bytes())?;
let v = CString::new(v.as_bytes())?;
let _g = ENV_LOCK.lock();
cvt(unsafe {
libc::setenv(k.as_ptr(), v.as_ptr(), 1)
@ -482,7 +482,7 @@ pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
}
pub fn unsetenv(n: &OsStr) -> io::Result<()> {
let nbuf = try!(CString::new(n.as_bytes()));
let nbuf = CString::new(n.as_bytes())?;
let _g = ENV_LOCK.lock();
cvt(unsafe {
libc::unsetenv(nbuf.as_ptr())

View file

@ -87,13 +87,13 @@ pub fn read2(p1: AnonPipe,
let max = cmp::max(p1.raw(), p2.raw());
loop {
// wait for either pipe to become readable using `select`
try!(cvt_r(|| unsafe {
cvt_r(|| unsafe {
let mut read: libc::fd_set = mem::zeroed();
libc::FD_SET(p1.raw(), &mut read);
libc::FD_SET(p2.raw(), &mut read);
libc::select(max + 1, &mut read, 0 as *mut _, 0 as *mut _,
0 as *mut _)
}));
})?;
// Read as much as we can from each pipe, ignoring EWOULDBLOCK or
// EAGAIN. If we hit EOF, then this will happen because the underlying
@ -113,11 +113,11 @@ pub fn read2(p1: AnonPipe,
}
}
};
if try!(read(&p1, v1)) {
if read(&p1, v1)? {
p2.set_nonblocking(false);
return p2.read_to_end(v2).map(|_| ());
}
if try!(read(&p2, v2)) {
if read(&p2, v2)? {
p1.set_nonblocking(false);
return p1.read_to_end(v1).map(|_| ());
}

View file

@ -225,11 +225,11 @@ impl Command {
"nul byte found in provided data"));
}
let (ours, theirs) = try!(self.setup_io(default, needs_stdin));
let (input, output) = try!(sys::pipe::anon_pipe());
let (ours, theirs) = self.setup_io(default, needs_stdin)?;
let (input, output) = sys::pipe::anon_pipe()?;
let pid = unsafe {
match try!(cvt(libc::fork())) {
match cvt(libc::fork())? {
0 => {
drop(input);
let err = self.do_exec(theirs);
@ -343,17 +343,17 @@ impl Command {
}
if let Some(fd) = stdio.stdin.fd() {
try!(cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO)));
cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO))?;
}
if let Some(fd) = stdio.stdout.fd() {
try!(cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO)));
cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO))?;
}
if let Some(fd) = stdio.stderr.fd() {
try!(cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO)));
cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO))?;
}
if let Some(u) = self.gid {
try!(cvt(libc::setgid(u as gid_t)));
cvt(libc::setgid(u as gid_t))?;
}
if let Some(u) = self.uid {
// When dropping privileges from root, the `setgroups` call
@ -365,7 +365,7 @@ impl Command {
// privilege dropping function.
let _ = libc::setgroups(0, ptr::null());
try!(cvt(libc::setuid(u as uid_t)));
cvt(libc::setuid(u as uid_t))?;
}
if self.session_leader {
// Don't check the error of setsid because it fails if we're the
@ -374,7 +374,7 @@ impl Command {
let _ = libc::setsid();
}
if let Some(ref cwd) = self.cwd {
try!(cvt(libc::chdir(cwd.as_ptr())));
cvt(libc::chdir(cwd.as_ptr()))?;
}
if let Some(ref envp) = self.envp {
*sys::os::environ() = envp.as_ptr();
@ -390,9 +390,9 @@ impl Command {
// need to clean things up now to avoid confusing the program
// we're about to run.
let mut set: libc::sigset_t = mem::uninitialized();
try!(cvt(libc::sigemptyset(&mut set)));
try!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, &set,
ptr::null_mut())));
cvt(libc::sigemptyset(&mut set))?;
cvt(libc::pthread_sigmask(libc::SIG_SETMASK, &set,
ptr::null_mut()))?;
let ret = libc::signal(libc::SIGPIPE, libc::SIG_DFL);
if ret == libc::SIG_ERR {
return io::Error::last_os_error()
@ -400,7 +400,7 @@ impl Command {
}
for callback in self.closures.iter_mut() {
try!(callback());
callback()?;
}
libc::execvp(self.argv[0], self.argv.as_ptr());
@ -415,9 +415,9 @@ impl Command {
let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
let stdout = self.stdout.as_ref().unwrap_or(&default);
let stderr = self.stderr.as_ref().unwrap_or(&default);
let (their_stdin, our_stdin) = try!(stdin.to_child_stdio(true));
let (their_stdout, our_stdout) = try!(stdout.to_child_stdio(false));
let (their_stderr, our_stderr) = try!(stderr.to_child_stdio(false));
let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
let ours = StdioPipes {
stdin: our_stdin,
stdout: our_stdout,
@ -454,14 +454,14 @@ impl Stdio {
// overwritten prematurely.
Stdio::Fd(ref fd) => {
if fd.raw() >= 0 && fd.raw() <= libc::STDERR_FILENO {
Ok((ChildStdio::Owned(try!(fd.duplicate())), None))
Ok((ChildStdio::Owned(fd.duplicate()?), None))
} else {
Ok((ChildStdio::Explicit(fd.raw()), None))
}
}
Stdio::MakePipe => {
let (reader, writer) = try!(pipe::anon_pipe());
let (reader, writer) = pipe::anon_pipe()?;
let (ours, theirs) = if readable {
(writer, reader)
} else {
@ -477,7 +477,7 @@ impl Stdio {
let path = unsafe {
CStr::from_ptr("/dev/null\0".as_ptr() as *const _)
};
let fd = try!(File::open_c(&path, &opts));
let fd = File::open_c(&path, &opts)?;
Ok((ChildStdio::Owned(fd.into_fd()), None))
}
}
@ -508,9 +508,9 @@ fn pair_to_key(key: &OsStr, value: &OsStr, saw_nul: &mut bool) -> CString {
impl fmt::Debug for Command {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{:?}", self.program));
write!(f, "{:?}", self.program)?;
for arg in &self.args {
try!(write!(f, " {:?}", arg));
write!(f, " {:?}", arg)?;
}
Ok(())
}
@ -589,7 +589,7 @@ impl Process {
return Ok(status)
}
let mut status = 0 as c_int;
try!(cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) }));
cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
self.status = Some(ExitStatus(status));
Ok(ExitStatus(status))
}

View file

@ -138,7 +138,7 @@ mod imp {
return Ok(OsRng { inner: OsGetrandomRng });
}
let reader = try!(File::open("/dev/urandom"));
let reader = File::open("/dev/urandom")?;
let reader_rng = ReaderRng::new(reader);
Ok(OsRng { inner: OsReaderRng(reader_rng) })

Some files were not shown because too many files have changed in this diff Show more