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:
parent
0dcc413e42
commit
0f02309e4b
132 changed files with 3755 additions and 3770 deletions
|
@ -280,16 +280,16 @@ fn collect_tests_from_dir(config: &Config,
|
||||||
-> io::Result<()> {
|
-> io::Result<()> {
|
||||||
// Ignore directories that contain a file
|
// Ignore directories that contain a file
|
||||||
// `compiletest-ignore-dir`.
|
// `compiletest-ignore-dir`.
|
||||||
for file in try!(fs::read_dir(dir)) {
|
for file in fs::read_dir(dir)? {
|
||||||
let file = try!(file);
|
let file = file?;
|
||||||
if file.file_name() == *"compiletest-ignore-dir" {
|
if file.file_name() == *"compiletest-ignore-dir" {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let dirs = try!(fs::read_dir(dir));
|
let dirs = fs::read_dir(dir)?;
|
||||||
for file in dirs {
|
for file in dirs {
|
||||||
let file = try!(file);
|
let file = file?;
|
||||||
let file_path = file.path();
|
let file_path = file.path();
|
||||||
debug!("inspecting file {:?}", file_path.display());
|
debug!("inspecting file {:?}", file_path.display());
|
||||||
if is_test(config, &file_path) {
|
if is_test(config, &file_path) {
|
||||||
|
@ -310,11 +310,11 @@ fn collect_tests_from_dir(config: &Config,
|
||||||
tests.push(make_test(config, &paths))
|
tests.push(make_test(config, &paths))
|
||||||
} else if file_path.is_dir() {
|
} else if file_path.is_dir() {
|
||||||
let relative_file_path = relative_dir_path.join(file.file_name());
|
let relative_file_path = relative_dir_path.join(file.file_name());
|
||||||
try!(collect_tests_from_dir(config,
|
collect_tests_from_dir(config,
|
||||||
base,
|
base,
|
||||||
&file_path,
|
&file_path,
|
||||||
&relative_file_path,
|
&relative_file_path,
|
||||||
tests));
|
tests)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -29,7 +29,7 @@ impl<'a, 'b: 'a> fmt::Write for PadAdapter<'a, 'b> {
|
||||||
fn write_str(&mut self, mut s: &str) -> fmt::Result {
|
fn write_str(&mut self, mut s: &str) -> fmt::Result {
|
||||||
while !s.is_empty() {
|
while !s.is_empty() {
|
||||||
if self.on_newline {
|
if self.on_newline {
|
||||||
try!(self.fmt.write_str(" "));
|
self.fmt.write_str(" ")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let split = match s.find('\n') {
|
let split = match s.find('\n') {
|
||||||
|
@ -42,7 +42,7 @@ impl<'a, 'b: 'a> fmt::Write for PadAdapter<'a, 'b> {
|
||||||
s.len()
|
s.len()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
try!(self.fmt.write_str(&s[..split]));
|
self.fmt.write_str(&s[..split])?;
|
||||||
s = &s[split..];
|
s = &s[split..];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -169,10 +169,10 @@ impl<'a, 'b: 'a> DebugTuple<'a, 'b> {
|
||||||
if self.fields > 0 {
|
if self.fields > 0 {
|
||||||
self.result = self.result.and_then(|_| {
|
self.result = self.result.and_then(|_| {
|
||||||
if self.is_pretty() {
|
if self.is_pretty() {
|
||||||
try!(self.fmt.write_str("\n"));
|
self.fmt.write_str("\n")?;
|
||||||
}
|
}
|
||||||
if self.fields == 1 && self.empty_name {
|
if self.fields == 1 && self.empty_name {
|
||||||
try!(self.fmt.write_str(","));
|
self.fmt.write_str(",")?;
|
||||||
}
|
}
|
||||||
self.fmt.write_str(")")
|
self.fmt.write_str(")")
|
||||||
});
|
});
|
||||||
|
|
|
@ -795,16 +795,16 @@ pub fn write(output: &mut Write, args: Arguments) -> Result {
|
||||||
None => {
|
None => {
|
||||||
// We can use default formatting parameters for all arguments.
|
// We can use default formatting parameters for all arguments.
|
||||||
for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
|
for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
|
||||||
try!(formatter.buf.write_str(*piece));
|
formatter.buf.write_str(*piece)?;
|
||||||
try!((arg.formatter)(arg.value, &mut formatter));
|
(arg.formatter)(arg.value, &mut formatter)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(fmt) => {
|
Some(fmt) => {
|
||||||
// Every spec has a corresponding argument that is preceded by
|
// Every spec has a corresponding argument that is preceded by
|
||||||
// a string piece.
|
// a string piece.
|
||||||
for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
|
for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
|
||||||
try!(formatter.buf.write_str(*piece));
|
formatter.buf.write_str(*piece)?;
|
||||||
try!(formatter.run(arg));
|
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.
|
// There can be only one trailing string piece left.
|
||||||
match pieces.next() {
|
match pieces.next() {
|
||||||
Some(piece) => {
|
Some(piece) => {
|
||||||
try!(formatter.buf.write_str(*piece));
|
formatter.buf.write_str(*piece)?;
|
||||||
}
|
}
|
||||||
None => {}
|
None => {}
|
||||||
}
|
}
|
||||||
|
@ -897,9 +897,9 @@ impl<'a> Formatter<'a> {
|
||||||
// Writes the sign if it exists, and then the prefix if it was requested
|
// Writes the sign if it exists, and then the prefix if it was requested
|
||||||
let write_prefix = |f: &mut Formatter| {
|
let write_prefix = |f: &mut Formatter| {
|
||||||
if let Some(c) = sign {
|
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())
|
str::from_utf8_unchecked(c.encode_utf8().as_slice())
|
||||||
}));
|
})?;
|
||||||
}
|
}
|
||||||
if prefixed { f.buf.write_str(prefix) }
|
if prefixed { f.buf.write_str(prefix) }
|
||||||
else { Ok(()) }
|
else { Ok(()) }
|
||||||
|
@ -910,18 +910,18 @@ impl<'a> Formatter<'a> {
|
||||||
// If there's no minimum length requirements then we can just
|
// If there's no minimum length requirements then we can just
|
||||||
// write the bytes.
|
// write the bytes.
|
||||||
None => {
|
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
|
// Check if we're over the minimum width, if so then we can also
|
||||||
// just write the bytes.
|
// just write the bytes.
|
||||||
Some(min) if width >= min => {
|
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
|
// The sign and prefix goes before the padding if the fill character
|
||||||
// is zero
|
// is zero
|
||||||
Some(min) if self.sign_aware_zero_pad() => {
|
Some(min) if self.sign_aware_zero_pad() => {
|
||||||
self.fill = '0';
|
self.fill = '0';
|
||||||
try!(write_prefix(self));
|
write_prefix(self)?;
|
||||||
self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
|
self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
|
||||||
f.buf.write_str(buf)
|
f.buf.write_str(buf)
|
||||||
})
|
})
|
||||||
|
@ -929,7 +929,7 @@ impl<'a> Formatter<'a> {
|
||||||
// Otherwise, the sign and prefix goes after the padding
|
// Otherwise, the sign and prefix goes after the padding
|
||||||
Some(min) => {
|
Some(min) => {
|
||||||
self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
|
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 {
|
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 {
|
for _ in 0..post_pad {
|
||||||
try!(self.buf.write_str(fill));
|
self.buf.write_str(fill)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -1033,7 +1033,7 @@ impl<'a> Formatter<'a> {
|
||||||
if self.sign_aware_zero_pad() {
|
if self.sign_aware_zero_pad() {
|
||||||
// a sign always goes first
|
// a sign always goes first
|
||||||
let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
|
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
|
// remove the sign from the formatted parts
|
||||||
formatted.sign = b"";
|
formatted.sign = b"";
|
||||||
|
@ -1065,7 +1065,7 @@ impl<'a> Formatter<'a> {
|
||||||
}
|
}
|
||||||
|
|
||||||
if !formatted.sign.is_empty() {
|
if !formatted.sign.is_empty() {
|
||||||
try!(write_bytes(self.buf, formatted.sign));
|
write_bytes(self.buf, formatted.sign)?;
|
||||||
}
|
}
|
||||||
for part in formatted.parts {
|
for part in formatted.parts {
|
||||||
match *part {
|
match *part {
|
||||||
|
@ -1073,11 +1073,11 @@ impl<'a> Formatter<'a> {
|
||||||
const ZEROES: &'static str = // 64 zeroes
|
const ZEROES: &'static str = // 64 zeroes
|
||||||
"0000000000000000000000000000000000000000000000000000000000000000";
|
"0000000000000000000000000000000000000000000000000000000000000000";
|
||||||
while nzeroes > ZEROES.len() {
|
while nzeroes > ZEROES.len() {
|
||||||
try!(self.buf.write_str(ZEROES));
|
self.buf.write_str(ZEROES)?;
|
||||||
nzeroes -= ZEROES.len();
|
nzeroes -= ZEROES.len();
|
||||||
}
|
}
|
||||||
if nzeroes > 0 {
|
if nzeroes > 0 {
|
||||||
try!(self.buf.write_str(&ZEROES[..nzeroes]));
|
self.buf.write_str(&ZEROES[..nzeroes])?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
flt2dec::Part::Num(mut v) => {
|
flt2dec::Part::Num(mut v) => {
|
||||||
|
@ -1087,10 +1087,10 @@ impl<'a> Formatter<'a> {
|
||||||
*c = b'0' + (v % 10) as u8;
|
*c = b'0' + (v % 10) as u8;
|
||||||
v /= 10;
|
v /= 10;
|
||||||
}
|
}
|
||||||
try!(write_bytes(self.buf, &s[..len]));
|
write_bytes(self.buf, &s[..len])?;
|
||||||
}
|
}
|
||||||
flt2dec::Part::Copy(buf) => {
|
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")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
impl Debug for str {
|
impl Debug for str {
|
||||||
fn fmt(&self, f: &mut Formatter) -> Result {
|
fn fmt(&self, f: &mut Formatter) -> Result {
|
||||||
try!(f.write_char('"'));
|
f.write_char('"')?;
|
||||||
let mut from = 0;
|
let mut from = 0;
|
||||||
for (i, c) in self.char_indices() {
|
for (i, c) in self.char_indices() {
|
||||||
let esc = c.escape_default();
|
let esc = c.escape_default();
|
||||||
// If char needs escaping, flush backlog so far and write, else skip
|
// If char needs escaping, flush backlog so far and write, else skip
|
||||||
if esc.size_hint() != (1, Some(1)) {
|
if esc.size_hint() != (1, Some(1)) {
|
||||||
try!(f.write_str(&self[from..i]));
|
f.write_str(&self[from..i])?;
|
||||||
for c in esc {
|
for c in esc {
|
||||||
try!(f.write_char(c));
|
f.write_char(c)?;
|
||||||
}
|
}
|
||||||
from = i + c.len_utf8();
|
from = i + c.len_utf8();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try!(f.write_str(&self[from..]));
|
f.write_str(&self[from..])?;
|
||||||
f.write_char('"')
|
f.write_char('"')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1377,9 +1377,9 @@ impl Display for str {
|
||||||
#[stable(feature = "rust1", since = "1.0.0")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
impl Debug for char {
|
impl Debug for char {
|
||||||
fn fmt(&self, f: &mut Formatter) -> Result {
|
fn fmt(&self, f: &mut Formatter) -> Result {
|
||||||
try!(f.write_char('\''));
|
f.write_char('\'')?;
|
||||||
for c in self.escape_default() {
|
for c in self.escape_default() {
|
||||||
try!(f.write_char(c))
|
f.write_char(c)?
|
||||||
}
|
}
|
||||||
f.write_char('\'')
|
f.write_char('\'')
|
||||||
}
|
}
|
||||||
|
|
|
@ -214,7 +214,7 @@ fn dec2flt<T: RawFloat>(s: &str) -> Result<T, ParseFloatError> {
|
||||||
}
|
}
|
||||||
let (sign, s) = extract_sign(s);
|
let (sign, s) = extract_sign(s);
|
||||||
let flt = match parse_decimal(s) {
|
let flt = match parse_decimal(s) {
|
||||||
ParseResult::Valid(decimal) => try!(convert(decimal)),
|
ParseResult::Valid(decimal) => convert(decimal)?,
|
||||||
ParseResult::ShortcutToInf => T::infinity(),
|
ParseResult::ShortcutToInf => T::infinity(),
|
||||||
ParseResult::ShortcutToZero => T::zero(),
|
ParseResult::ShortcutToZero => T::zero(),
|
||||||
ParseResult::Invalid => match s {
|
ParseResult::Invalid => match s {
|
||||||
|
|
|
@ -240,7 +240,7 @@ impl Utf8Error {
|
||||||
/// ```
|
/// ```
|
||||||
#[stable(feature = "rust1", since = "1.0.0")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
|
pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
|
||||||
try!(run_utf8_validation(v));
|
run_utf8_validation(v)?;
|
||||||
Ok(unsafe { from_utf8_unchecked(v) })
|
Ok(unsafe { from_utf8_unchecked(v) })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -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<()> {
|
fn writeln<W: Write>(w: &mut W, arg: &[&str]) -> io::Result<()> {
|
||||||
for &s in arg {
|
for &s in arg {
|
||||||
try!(w.write_all(s.as_bytes()));
|
w.write_all(s.as_bytes())?;
|
||||||
}
|
}
|
||||||
write!(w, "\n")
|
write!(w, "\n")
|
||||||
}
|
}
|
||||||
|
@ -671,9 +671,9 @@ pub fn render_opts<'a, N, E, G, W>(g: &'a G,
|
||||||
w.write_all(b" ")
|
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() {
|
for n in g.nodes().iter() {
|
||||||
try!(indent(w));
|
indent(w)?;
|
||||||
let id = g.node_id(n);
|
let id = g.node_id(n);
|
||||||
|
|
||||||
let escaped = &g.node_label(n).to_dot_string();
|
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(";");
|
text.push(";");
|
||||||
try!(writeln(w, &text));
|
writeln(w, &text)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
for e in g.edges().iter() {
|
for e in g.edges().iter() {
|
||||||
let escaped_label = &g.edge_label(e).to_dot_string();
|
let escaped_label = &g.edge_label(e).to_dot_string();
|
||||||
try!(indent(w));
|
indent(w)?;
|
||||||
let source = g.source(e);
|
let source = g.source(e);
|
||||||
let target = g.target(e);
|
let target = g.target(e);
|
||||||
let source_id = g.node_id(&source);
|
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(";");
|
text.push(";");
|
||||||
try!(writeln(w, &text));
|
writeln(w, &text)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
writeln(w, &["}"])
|
writeln(w, &["}"])
|
||||||
|
@ -959,7 +959,7 @@ mod tests {
|
||||||
let mut writer = Vec::new();
|
let mut writer = Vec::new();
|
||||||
render(&g, &mut writer).unwrap();
|
render(&g, &mut writer).unwrap();
|
||||||
let mut s = String::new();
|
let mut s = String::new();
|
||||||
try!(Read::read_to_string(&mut &*writer, &mut s));
|
Read::read_to_string(&mut &*writer, &mut s)?;
|
||||||
Ok(s)
|
Ok(s)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -398,8 +398,8 @@ pub mod reader {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn doc_at<'a>(data: &'a [u8], start: usize) -> DecodeResult<TaggedDoc<'a>> {
|
pub fn doc_at<'a>(data: &'a [u8], start: usize) -> DecodeResult<TaggedDoc<'a>> {
|
||||||
let elt_tag = try!(tag_at(data, start));
|
let elt_tag = tag_at(data, start)?;
|
||||||
let elt_size = try!(tag_len_at(data, elt_tag));
|
let elt_size = tag_len_at(data, elt_tag)?;
|
||||||
let end = elt_size.next + elt_size.val;
|
let end = elt_size.next + elt_size.val;
|
||||||
Ok(TaggedDoc {
|
Ok(TaggedDoc {
|
||||||
tag: elt_tag.val,
|
tag: elt_tag.val,
|
||||||
|
@ -581,7 +581,7 @@ pub mod reader {
|
||||||
if self.pos >= self.parent.end {
|
if self.pos >= self.parent.end {
|
||||||
return Err(Expected(format!("no more documents in current node!")));
|
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={:?}-{:?}",
|
debug!("self.parent={:?}-{:?} self.pos={:?} r_tag={:?} r_doc={:?}-{:?}",
|
||||||
self.parent.start,
|
self.parent.start,
|
||||||
self.parent.end,
|
self.parent.end,
|
||||||
|
@ -607,12 +607,12 @@ pub mod reader {
|
||||||
fn push_doc<T, F>(&mut self, exp_tag: EbmlEncoderTag, f: F) -> DecodeResult<T>
|
fn push_doc<T, F>(&mut self, exp_tag: EbmlEncoderTag, f: F) -> DecodeResult<T>
|
||||||
where F: FnOnce(&mut Decoder<'doc>) -> 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_parent = self.parent;
|
||||||
let old_pos = self.pos;
|
let old_pos = self.pos;
|
||||||
self.parent = d;
|
self.parent = d;
|
||||||
self.pos = d.start;
|
self.pos = d.start;
|
||||||
let r = try!(f(self));
|
let r = f(self)?;
|
||||||
self.parent = old_parent;
|
self.parent = old_parent;
|
||||||
self.pos = old_pos;
|
self.pos = old_pos;
|
||||||
Ok(r)
|
Ok(r)
|
||||||
|
@ -624,7 +624,7 @@ pub mod reader {
|
||||||
return Ok(0);
|
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) {
|
let r = if r_tag == (EsSub8 as usize) {
|
||||||
doc_as_u8(r_doc) as usize
|
doc_as_u8(r_doc) as usize
|
||||||
} else if r_tag == (EsSub32 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!")));
|
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 {
|
let r = if first_tag as usize <= r_tag && r_tag <= last_tag as usize {
|
||||||
match r_tag - first_tag as usize {
|
match r_tag - first_tag as usize {
|
||||||
0 => doc_as_u8(r_doc) as u64,
|
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>
|
pub fn read_opaque<R, F>(&mut self, op: F) -> DecodeResult<R>
|
||||||
where F: FnOnce(&mut opaque::Decoder, Doc) -> 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 result = {
|
||||||
let mut opaque_decoder = opaque::Decoder::new(doc.data, doc.start);
|
let mut opaque_decoder = opaque::Decoder::new(doc.data, doc.start);
|
||||||
try!(op(&mut opaque_decoder, doc))
|
op(&mut opaque_decoder, doc)?
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(result)
|
Ok(result)
|
||||||
|
@ -718,16 +718,16 @@ pub mod reader {
|
||||||
self._next_int(EsU8, EsU64)
|
self._next_int(EsU8, EsU64)
|
||||||
}
|
}
|
||||||
fn read_u32(&mut self) -> DecodeResult<u32> {
|
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> {
|
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> {
|
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> {
|
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) {
|
if v > (::std::usize::MAX as u64) {
|
||||||
Err(IntTooBig(v as usize))
|
Err(IntTooBig(v as usize))
|
||||||
} else {
|
} else {
|
||||||
|
@ -736,19 +736,19 @@ pub mod reader {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_i64(&mut self) -> DecodeResult<i64> {
|
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> {
|
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> {
|
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> {
|
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> {
|
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) {
|
if v > (isize::MAX as i64) || v < (isize::MIN as i64) {
|
||||||
debug!("FIXME \\#6122: Removing this makes this function miscompile");
|
debug!("FIXME \\#6122: Removing this makes this function miscompile");
|
||||||
Err(IntTooBig(v as usize))
|
Err(IntTooBig(v as usize))
|
||||||
|
@ -758,22 +758,22 @@ pub mod reader {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_bool(&mut self) -> DecodeResult<bool> {
|
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> {
|
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) })
|
Ok(unsafe { transmute(bits) })
|
||||||
}
|
}
|
||||||
fn read_f32(&mut self) -> DecodeResult<f32> {
|
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) })
|
Ok(unsafe { transmute(bits) })
|
||||||
}
|
}
|
||||||
fn read_char(&mut self) -> DecodeResult<char> {
|
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> {
|
fn read_str(&mut self) -> DecodeResult<String> {
|
||||||
Ok(try!(self.next_doc(EsStr)).as_str())
|
Ok(self.next_doc(EsStr)?.as_str())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compound types:
|
// Compound types:
|
||||||
|
@ -782,13 +782,13 @@ pub mod reader {
|
||||||
{
|
{
|
||||||
debug!("read_enum({})", name);
|
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);
|
let (old_parent, old_pos) = (self.parent, self.pos);
|
||||||
self.parent = doc;
|
self.parent = doc;
|
||||||
self.pos = self.parent.start;
|
self.pos = self.parent.start;
|
||||||
|
|
||||||
let result = try!(f(self));
|
let result = f(self)?;
|
||||||
|
|
||||||
self.parent = old_parent;
|
self.parent = old_parent;
|
||||||
self.pos = old_pos;
|
self.pos = old_pos;
|
||||||
|
@ -799,7 +799,7 @@ pub mod reader {
|
||||||
where F: FnMut(&mut Decoder<'doc>, usize) -> DecodeResult<T>
|
where F: FnMut(&mut Decoder<'doc>, usize) -> DecodeResult<T>
|
||||||
{
|
{
|
||||||
debug!("read_enum_variant()");
|
debug!("read_enum_variant()");
|
||||||
let idx = try!(self._next_sub());
|
let idx = self._next_sub()?;
|
||||||
debug!(" idx={}", idx);
|
debug!(" idx={}", idx);
|
||||||
|
|
||||||
f(self, idx)
|
f(self, idx)
|
||||||
|
@ -816,7 +816,7 @@ pub mod reader {
|
||||||
where F: FnMut(&mut Decoder<'doc>, usize) -> DecodeResult<T>
|
where F: FnMut(&mut Decoder<'doc>, usize) -> DecodeResult<T>
|
||||||
{
|
{
|
||||||
debug!("read_enum_struct_variant()");
|
debug!("read_enum_struct_variant()");
|
||||||
let idx = try!(self._next_sub());
|
let idx = self._next_sub()?;
|
||||||
debug!(" idx={}", idx);
|
debug!(" idx={}", idx);
|
||||||
|
|
||||||
f(self, idx)
|
f(self, idx)
|
||||||
|
@ -904,7 +904,7 @@ pub mod reader {
|
||||||
{
|
{
|
||||||
debug!("read_seq()");
|
debug!("read_seq()");
|
||||||
self.push_doc(EsVec, move |d| {
|
self.push_doc(EsVec, move |d| {
|
||||||
let len = try!(d._next_sub());
|
let len = d._next_sub()?;
|
||||||
debug!(" len={}", len);
|
debug!(" len={}", len);
|
||||||
f(d, len)
|
f(d, len)
|
||||||
})
|
})
|
||||||
|
@ -922,7 +922,7 @@ pub mod reader {
|
||||||
{
|
{
|
||||||
debug!("read_map()");
|
debug!("read_map()");
|
||||||
self.push_doc(EsMap, move |d| {
|
self.push_doc(EsMap, move |d| {
|
||||||
let len = try!(d._next_sub());
|
let len = d._next_sub()?;
|
||||||
debug!(" len={}", len);
|
debug!(" len={}", len);
|
||||||
f(d, len)
|
f(d, len)
|
||||||
})
|
})
|
||||||
|
@ -1020,10 +1020,10 @@ pub mod writer {
|
||||||
assert!(tag_id >= NUM_IMPLICIT_TAGS);
|
assert!(tag_id >= NUM_IMPLICIT_TAGS);
|
||||||
|
|
||||||
// Write the enum ID:
|
// Write the enum ID:
|
||||||
try!(write_tag(self.writer, tag_id));
|
write_tag(self.writer, tag_id)?;
|
||||||
|
|
||||||
// Write a placeholder four-byte size.
|
// 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);
|
self.size_positions.push(cur_pos);
|
||||||
let zeroes: &[u8] = &[0, 0, 0, 0];
|
let zeroes: &[u8] = &[0, 0, 0, 0];
|
||||||
self.writer.write_all(zeroes)
|
self.writer.write_all(zeroes)
|
||||||
|
@ -1031,8 +1031,8 @@ pub mod writer {
|
||||||
|
|
||||||
pub fn end_tag(&mut self) -> EncodeResult {
|
pub fn end_tag(&mut self) -> EncodeResult {
|
||||||
let last_size_pos = self.size_positions.pop().unwrap();
|
let last_size_pos = self.size_positions.pop().unwrap();
|
||||||
let cur_pos = try!(self.writer.seek(SeekFrom::Current(0)));
|
let cur_pos = self.writer.seek(SeekFrom::Current(0))?;
|
||||||
try!(self.writer.seek(SeekFrom::Start(last_size_pos)));
|
self.writer.seek(SeekFrom::Start(last_size_pos))?;
|
||||||
let size = (cur_pos - last_size_pos - 4) as usize;
|
let size = (cur_pos - last_size_pos - 4) as usize;
|
||||||
|
|
||||||
// relax the size encoding for small tags (bigger tags are costly to move).
|
// 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
|
// overwrite the size and data and continue
|
||||||
try!(write_vuint(self.writer, size));
|
write_vuint(self.writer, size)?;
|
||||||
try!(self.writer.write_all(&buf[..size]));
|
self.writer.write_all(&buf[..size])?;
|
||||||
} else {
|
} else {
|
||||||
// overwrite the size with an overlong encoding and skip past the data
|
// overwrite the size with an overlong encoding and skip past the data
|
||||||
try!(write_sized_vuint(self.writer, size, 4));
|
write_sized_vuint(self.writer, size, 4)?;
|
||||||
try!(self.writer.seek(SeekFrom::Start(cur_pos)));
|
self.writer.seek(SeekFrom::Start(cur_pos))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
debug!("End tag (size = {:?})", size);
|
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
|
pub fn wr_tag<F>(&mut self, tag_id: usize, blk: F) -> EncodeResult
|
||||||
where F: FnOnce() -> EncodeResult
|
where F: FnOnce() -> EncodeResult
|
||||||
{
|
{
|
||||||
try!(self.start_tag(tag_id));
|
self.start_tag(tag_id)?;
|
||||||
try!(blk());
|
blk()?;
|
||||||
self.end_tag()
|
self.end_tag()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn wr_tagged_bytes(&mut self, tag_id: usize, b: &[u8]) -> EncodeResult {
|
pub fn wr_tagged_bytes(&mut self, tag_id: usize, b: &[u8]) -> EncodeResult {
|
||||||
assert!(tag_id >= NUM_IMPLICIT_TAGS);
|
assert!(tag_id >= NUM_IMPLICIT_TAGS);
|
||||||
try!(write_tag(self.writer, tag_id));
|
write_tag(self.writer, tag_id)?;
|
||||||
try!(write_vuint(self.writer, b.len()));
|
write_vuint(self.writer, b.len())?;
|
||||||
self.writer.write_all(b)
|
self.writer.write_all(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1124,7 +1124,7 @@ pub mod writer {
|
||||||
|
|
||||||
// for auto-serialization
|
// for auto-serialization
|
||||||
fn wr_tagged_raw_bytes(&mut self, tag_id: usize, b: &[u8]) -> EncodeResult {
|
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)
|
self.writer.write_all(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1200,11 +1200,11 @@ pub mod writer {
|
||||||
pub fn emit_opaque<F>(&mut self, f: F) -> EncodeResult
|
pub fn emit_opaque<F>(&mut self, f: F) -> EncodeResult
|
||||||
where F: FnOnce(&mut opaque::Encoder) -> 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);
|
let mut opaque_encoder = opaque::Encoder::new(self.writer);
|
||||||
try!(f(&mut opaque_encoder));
|
f(&mut opaque_encoder)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.mark_stable_position();
|
self.mark_stable_position();
|
||||||
|
@ -1298,15 +1298,15 @@ pub mod writer {
|
||||||
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
|
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
|
||||||
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
||||||
{
|
{
|
||||||
try!(self.start_tag(EsEnum as usize));
|
self.start_tag(EsEnum as usize)?;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.end_tag()
|
self.end_tag()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn emit_enum_variant<F>(&mut self, _: &str, v_id: usize, _: usize, f: F) -> EncodeResult
|
fn emit_enum_variant<F>(&mut self, _: &str, v_id: usize, _: usize, f: F) -> EncodeResult
|
||||||
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
||||||
{
|
{
|
||||||
try!(self._emit_tagged_sub(v_id));
|
self._emit_tagged_sub(v_id)?;
|
||||||
f(self)
|
f(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1390,9 +1390,9 @@ pub mod writer {
|
||||||
return self.wr_tagged_bytes(EsVec as usize, &[]);
|
return self.wr_tagged_bytes(EsVec as usize, &[]);
|
||||||
}
|
}
|
||||||
|
|
||||||
try!(self.start_tag(EsVec as usize));
|
self.start_tag(EsVec as usize)?;
|
||||||
try!(self._emit_tagged_sub(len));
|
self._emit_tagged_sub(len)?;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.end_tag()
|
self.end_tag()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1400,8 +1400,8 @@ pub mod writer {
|
||||||
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
||||||
{
|
{
|
||||||
|
|
||||||
try!(self.start_tag(EsVecElt as usize));
|
self.start_tag(EsVecElt as usize)?;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.end_tag()
|
self.end_tag()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1413,9 +1413,9 @@ pub mod writer {
|
||||||
return self.wr_tagged_bytes(EsMap as usize, &[]);
|
return self.wr_tagged_bytes(EsMap as usize, &[]);
|
||||||
}
|
}
|
||||||
|
|
||||||
try!(self.start_tag(EsMap as usize));
|
self.start_tag(EsMap as usize)?;
|
||||||
try!(self._emit_tagged_sub(len));
|
self._emit_tagged_sub(len)?;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.end_tag()
|
self.end_tag()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1423,16 +1423,16 @@ pub mod writer {
|
||||||
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
||||||
{
|
{
|
||||||
|
|
||||||
try!(self.start_tag(EsMapKey as usize));
|
self.start_tag(EsMapKey as usize)?;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.end_tag()
|
self.end_tag()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
|
fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
|
||||||
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
||||||
{
|
{
|
||||||
try!(self.start_tag(EsMapVal as usize));
|
self.start_tag(EsMapVal as usize)?;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.end_tag()
|
self.end_tag()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -120,7 +120,7 @@ impl<'a> serialize::Encoder for Encoder<'a> {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn emit_str(&mut self, v: &str) -> EncodeResult {
|
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());
|
let _ = self.cursor.write_all(v.as_bytes());
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -139,7 +139,7 @@ impl<'a> serialize::Encoder for Encoder<'a> {
|
||||||
-> EncodeResult
|
-> EncodeResult
|
||||||
where F: FnOnce(&mut Self) -> EncodeResult
|
where F: FnOnce(&mut Self) -> EncodeResult
|
||||||
{
|
{
|
||||||
try!(self.emit_uint(v_id));
|
self.emit_uint(v_id)?;
|
||||||
f(self)
|
f(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -221,7 +221,7 @@ impl<'a> serialize::Encoder for Encoder<'a> {
|
||||||
fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
|
fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
|
||||||
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
||||||
{
|
{
|
||||||
try!(self.emit_uint(len));
|
self.emit_uint(len)?;
|
||||||
f(self)
|
f(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -234,7 +234,7 @@ impl<'a> serialize::Encoder for Encoder<'a> {
|
||||||
fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
|
fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
|
||||||
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
where F: FnOnce(&mut Encoder<'a>) -> EncodeResult
|
||||||
{
|
{
|
||||||
try!(self.emit_uint(len));
|
self.emit_uint(len)?;
|
||||||
f(self)
|
f(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -356,27 +356,27 @@ impl<'a> serialize::Decoder for Decoder<'a> {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_bool(&mut self) -> Result<bool, Self::Error> {
|
fn read_bool(&mut self) -> Result<bool, Self::Error> {
|
||||||
let value = try!(self.read_u8());
|
let value = self.read_u8()?;
|
||||||
Ok(value != 0)
|
Ok(value != 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_f64(&mut self) -> Result<f64, Self::Error> {
|
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) })
|
Ok(unsafe { ::std::mem::transmute(bits) })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_f32(&mut self) -> Result<f32, Self::Error> {
|
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) })
|
Ok(unsafe { ::std::mem::transmute(bits) })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_char(&mut self) -> Result<char, Self::Error> {
|
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())
|
Ok(::std::char::from_u32(bits).unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_str(&mut self) -> Result<String, Self::Error> {
|
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();
|
let s = ::std::str::from_utf8(&self.data[self.position..self.position + len]).unwrap();
|
||||||
self.position += len;
|
self.position += len;
|
||||||
Ok(s.to_string())
|
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>
|
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>
|
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)
|
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>
|
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>
|
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)
|
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>
|
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
|
||||||
where F: FnOnce(&mut Decoder<'a>, usize) -> 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)
|
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>
|
fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
|
||||||
where F: FnOnce(&mut Decoder<'a>, usize) -> 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)
|
f(self, len)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -68,7 +68,7 @@ struct Matrix<'a>(Vec<Vec<&'a Pat>>);
|
||||||
/// ++++++++++++++++++++++++++
|
/// ++++++++++++++++++++++++++
|
||||||
impl<'a> fmt::Debug for Matrix<'a> {
|
impl<'a> fmt::Debug for Matrix<'a> {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
try!(write!(f, "\n"));
|
write!(f, "\n")?;
|
||||||
|
|
||||||
let &Matrix(ref m) = self;
|
let &Matrix(ref m) = self;
|
||||||
let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
|
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 total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
|
||||||
let br = repeat('+').take(total_width).collect::<String>();
|
let br = repeat('+').take(total_width).collect::<String>();
|
||||||
try!(write!(f, "{}\n", br));
|
write!(f, "{}\n", br)?;
|
||||||
for row in pretty_printed_matrix {
|
for row in pretty_printed_matrix {
|
||||||
try!(write!(f, "+"));
|
write!(f, "+")?;
|
||||||
for (column, pat_str) in row.into_iter().enumerate() {
|
for (column, pat_str) in row.into_iter().enumerate() {
|
||||||
try!(write!(f, " "));
|
write!(f, " ")?;
|
||||||
try!(write!(f, "{:1$}", pat_str, column_widths[column]));
|
write!(f, "{:1$}", pat_str, column_widths[column])?;
|
||||||
try!(write!(f, " +"));
|
write!(f, " +")?;
|
||||||
}
|
}
|
||||||
try!(write!(f, "\n"));
|
write!(f, "\n")?;
|
||||||
try!(write!(f, "{}\n", br));
|
write!(f, "{}\n", br)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -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),
|
Float(f) => Float(-f),
|
||||||
Integral(i) => Integral(math!(e, -i)),
|
Integral(i) => Integral(math!(e, -i)),
|
||||||
const_val => signal!(e, NegateOn(const_val)),
|
const_val => signal!(e, NegateOn(const_val)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
hir::ExprUnary(hir::UnNot, ref inner) => {
|
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)),
|
Integral(i) => Integral(math!(e, !i)),
|
||||||
Bool(b) => Bool(!b),
|
Bool(b) => Bool(!b),
|
||||||
const_val => signal!(e, NotOn(const_val)),
|
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
|
// 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
|
// we need to re-eval the other value of the BinOp if it was
|
||||||
// not inferred
|
// not inferred
|
||||||
match (try!(eval_const_expr_partial(tcx, &a, ty_hint, fn_args)),
|
match (eval_const_expr_partial(tcx, &a, ty_hint, fn_args)?,
|
||||||
try!(eval_const_expr_partial(tcx, &b, b_ty, fn_args))) {
|
eval_const_expr_partial(tcx, &b, b_ty, fn_args)?) {
|
||||||
(Float(a), Float(b)) => {
|
(Float(a), Float(b)) => {
|
||||||
match op.node {
|
match op.node {
|
||||||
hir::BiAdd => Float(a + b),
|
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
|
// we had a type hint, so we can't have an unknown type
|
||||||
None => unreachable!(),
|
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),
|
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),
|
Some(ty) => ty_hint.checked_or(ty),
|
||||||
None => ty_hint,
|
None => ty_hint,
|
||||||
};
|
};
|
||||||
try!(eval_const_expr_partial(tcx, e, item_hint, None))
|
eval_const_expr_partial(tcx, e, item_hint, None)?
|
||||||
} else {
|
} else {
|
||||||
signal!(e, NonConstPath);
|
signal!(e, NonConstPath);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Def::Variant(enum_def, variant_def) => {
|
Def::Variant(enum_def, variant_def) => {
|
||||||
if let Some(const_expr) = lookup_variant_by_id(tcx, 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 {
|
} else {
|
||||||
signal!(e, NonConstPath);
|
signal!(e, NonConstPath);
|
||||||
}
|
}
|
||||||
|
@ -810,7 +810,7 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
|
||||||
}
|
}
|
||||||
hir::ExprCall(ref callee, ref args) => {
|
hir::ExprCall(ref callee, ref args) => {
|
||||||
let sub_ty_hint = ty_hint.erase_hint();
|
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 {
|
let did = match callee_val {
|
||||||
Function(did) => did,
|
Function(did) => did,
|
||||||
callee => signal!(e, CallOn(callee)),
|
callee => signal!(e, CallOn(callee)),
|
||||||
|
@ -826,27 +826,27 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
|
||||||
let mut call_args = NodeMap();
|
let mut call_args = NodeMap();
|
||||||
for (arg, arg_expr) in decl.inputs.iter().zip(args.iter()) {
|
for (arg, arg_expr) in decl.inputs.iter().zip(args.iter()) {
|
||||||
let arg_hint = ty_hint.erase_hint();
|
let arg_hint = ty_hint.erase_hint();
|
||||||
let arg_val = try!(eval_const_expr_partial(
|
let arg_val = eval_const_expr_partial(
|
||||||
tcx,
|
tcx,
|
||||||
arg_expr,
|
arg_expr,
|
||||||
arg_hint,
|
arg_hint,
|
||||||
fn_args
|
fn_args
|
||||||
));
|
)?;
|
||||||
debug!("const call arg: {:?}", arg);
|
debug!("const call arg: {:?}", arg);
|
||||||
let old = call_args.insert(arg.pat.id, arg_val);
|
let old = call_args.insert(arg.pat.id, arg_val);
|
||||||
assert!(old.is_none());
|
assert!(old.is_none());
|
||||||
}
|
}
|
||||||
debug!("const call({:?})", call_args);
|
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) => {
|
hir::ExprBlock(ref block) => {
|
||||||
match block.expr {
|
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!(),
|
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::ExprTup(_) => Tuple(e.id),
|
||||||
hir::ExprStruct(..) => Struct(e.id),
|
hir::ExprStruct(..) => Struct(e.id),
|
||||||
hir::ExprIndex(ref arr, ref idx) => {
|
hir::ExprIndex(ref arr, ref idx) => {
|
||||||
|
@ -854,9 +854,9 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
|
||||||
signal!(e, IndexOpFeatureGated);
|
signal!(e, IndexOpFeatureGated);
|
||||||
}
|
}
|
||||||
let arr_hint = ty_hint.erase_hint();
|
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_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(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
|
||||||
Integral(_) => unreachable!(),
|
Integral(_) => unreachable!(),
|
||||||
_ => signal!(idx, IndexNotInt),
|
_ => 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(_, n) if idx >= n => signal!(e, IndexOutOfBounds),
|
||||||
Array(v, n) => if let hir::ExprVec(ref v) = tcx.map.expect_expr(v).node {
|
Array(v, n) => if let hir::ExprVec(ref v) = tcx.map.expect_expr(v).node {
|
||||||
assert_eq!(n as usize as u64, n);
|
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 {
|
} else {
|
||||||
unreachable!()
|
unreachable!()
|
||||||
},
|
},
|
||||||
|
|
||||||
Repeat(_, n) if idx >= n => signal!(e, IndexOutOfBounds),
|
Repeat(_, n) if idx >= n => signal!(e, IndexOutOfBounds),
|
||||||
Repeat(elem, _) => try!(eval_const_expr_partial(
|
Repeat(elem, _) => eval_const_expr_partial(
|
||||||
tcx,
|
tcx,
|
||||||
&tcx.map.expect_expr(elem),
|
&tcx.map.expect_expr(elem),
|
||||||
ty_hint,
|
ty_hint,
|
||||||
fn_args,
|
fn_args,
|
||||||
)),
|
)?,
|
||||||
|
|
||||||
ByteStr(ref data) if idx >= data.len() as u64 => signal!(e, IndexOutOfBounds),
|
ByteStr(ref data) if idx >= data.len() as u64 => signal!(e, IndexOutOfBounds),
|
||||||
ByteStr(data) => {
|
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);
|
let len_hint = ty_hint.checked_or(tcx.types.usize);
|
||||||
Repeat(
|
Repeat(
|
||||||
e.id,
|
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(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
|
||||||
Integral(_) => signal!(e, RepeatCountNotNatural),
|
Integral(_) => signal!(e, RepeatCountNotNatural),
|
||||||
_ => signal!(e, RepeatCountNotInt),
|
_ => signal!(e, RepeatCountNotInt),
|
||||||
|
@ -903,11 +903,11 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
|
||||||
},
|
},
|
||||||
hir::ExprTupField(ref base, index) => {
|
hir::ExprTupField(ref base, index) => {
|
||||||
let base_hint = ty_hint.erase_hint();
|
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 Tuple(tup_id) = c {
|
||||||
if let hir::ExprTup(ref fields) = tcx.map.expect_expr(tup_id).node {
|
if let hir::ExprTup(ref fields) = tcx.map.expect_expr(tup_id).node {
|
||||||
if index.node < fields.len() {
|
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 {
|
} else {
|
||||||
signal!(e, TupleIndexOutOfBounds);
|
signal!(e, TupleIndexOutOfBounds);
|
||||||
}
|
}
|
||||||
|
@ -921,14 +921,14 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
|
||||||
hir::ExprField(ref base, field_name) => {
|
hir::ExprField(ref base, field_name) => {
|
||||||
let base_hint = ty_hint.erase_hint();
|
let base_hint = ty_hint.erase_hint();
|
||||||
// Get the base expression if it is a struct and it is constant
|
// 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 Struct(struct_id) = c {
|
||||||
if let hir::ExprStruct(_, ref fields, _) = tcx.map.expect_expr(struct_id).node {
|
if let hir::ExprStruct(_, ref fields, _) = tcx.map.expect_expr(struct_id).node {
|
||||||
// Check that the given field exists and evaluate it
|
// Check that the given field exists and evaluate it
|
||||||
// if the idents are compared run-pass/issue-19244 fails
|
// if the idents are compared run-pass/issue-19244 fails
|
||||||
if let Some(f) = fields.iter().find(|f| f.name.node
|
if let Some(f) = fields.iter().find(|f| f.name.node
|
||||||
== field_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 {
|
} else {
|
||||||
signal!(e, MissingStructField);
|
signal!(e, MissingStructField);
|
||||||
}
|
}
|
||||||
|
@ -943,7 +943,7 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &TyCtxt<'tcx>,
|
||||||
};
|
};
|
||||||
|
|
||||||
match (ety.map(|t| &t.sty), result) {
|
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),
|
(_, 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() => {
|
ty::TyFloat(ast::FloatTy::F64) if val.is_negative() => {
|
||||||
// FIXME: this could probably be prettier
|
// FIXME: this could probably be prettier
|
||||||
// there's no easy way to turn an `Infer` into a f64
|
// 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.to_u64().unwrap() as f64;
|
||||||
let val = -val;
|
let val = -val;
|
||||||
Ok(Float(val))
|
Ok(Float(val))
|
||||||
},
|
},
|
||||||
ty::TyFloat(ast::FloatTy::F64) => Ok(Float(val.to_u64().unwrap() as f64)),
|
ty::TyFloat(ast::FloatTy::F64) => Ok(Float(val.to_u64().unwrap() as f64)),
|
||||||
ty::TyFloat(ast::FloatTy::F32) if val.is_negative() => {
|
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.to_u64().unwrap() as f32;
|
||||||
let val = -val;
|
let val = -val;
|
||||||
Ok(Float(val as f64))
|
Ok(Float(val as f64))
|
||||||
|
|
|
@ -152,10 +152,10 @@ impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O
|
||||||
"".to_string()
|
"".to_string()
|
||||||
};
|
};
|
||||||
|
|
||||||
try!(ps.synth_comment(
|
ps.synth_comment(
|
||||||
format!("id {}: {}{}{}{}", id, entry_str,
|
format!("id {}: {}{}{}{}", id, entry_str,
|
||||||
gens_str, action_kills_str, scope_kills_str)));
|
gens_str, action_kills_str, scope_kills_str))?;
|
||||||
try!(pp::space(&mut ps.s));
|
pp::space(&mut ps.s)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
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>,
|
fn pretty_print_to<'b>(&self, wr: Box<io::Write + 'b>,
|
||||||
blk: &hir::Block) -> io::Result<()> {
|
blk: &hir::Block) -> io::Result<()> {
|
||||||
let mut ps = pprust::rust_printer_annotated(wr, self, None);
|
let mut ps = pprust::rust_printer_annotated(wr, self, None);
|
||||||
try!(ps.cbox(pprust::indent_unit));
|
ps.cbox(pprust::indent_unit)?;
|
||||||
try!(ps.ibox(0));
|
ps.ibox(0)?;
|
||||||
try!(ps.print_block(blk));
|
ps.print_block(blk)?;
|
||||||
pp::eof(&mut ps.s)
|
pp::eof(&mut ps.s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -55,8 +55,8 @@ pub struct DefId {
|
||||||
|
|
||||||
impl fmt::Debug for DefId {
|
impl fmt::Debug for DefId {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
try!(write!(f, "DefId {{ krate: {:?}, node: {:?}",
|
write!(f, "DefId {{ krate: {:?}, node: {:?}",
|
||||||
self.krate, self.index));
|
self.krate, self.index)?;
|
||||||
|
|
||||||
// Unfortunately, there seems to be no way to attempt to print
|
// 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
|
// 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)
|
if self.is_local() { // (1)
|
||||||
// (1) side-step fact that not all external things have paths at
|
// (1) side-step fact that not all external things have paths at
|
||||||
// the moment, such as type parameters
|
// 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 {
|
if let Some(tcx) = opt_tcx {
|
||||||
try!(write!(f, " => {}", tcx.item_path_str(*self)));
|
write!(f, " => {}", tcx.item_path_str(*self))?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
})?;
|
||||||
}
|
}
|
||||||
|
|
||||||
write!(f, " }}")
|
write!(f, " }}")
|
||||||
|
|
|
@ -1182,7 +1182,7 @@ impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> {
|
||||||
// Create the cmt for the variable being borrowed, from the
|
// Create the cmt for the variable being borrowed, from the
|
||||||
// caller's perspective
|
// caller's perspective
|
||||||
let var_id = upvar_def.var_id();
|
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)
|
self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -86,12 +86,12 @@ impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Bivariate<'a, 'tcx> {
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyInfer(TyVar(a_id)), _) => {
|
(&ty::TyInfer(TyVar(a_id)), _) => {
|
||||||
try!(self.fields.instantiate(b, BiTo, a_id));
|
self.fields.instantiate(b, BiTo, a_id)?;
|
||||||
Ok(a)
|
Ok(a)
|
||||||
}
|
}
|
||||||
|
|
||||||
(_, &ty::TyInfer(TyVar(b_id))) => {
|
(_, &ty::TyInfer(TyVar(b_id))) => {
|
||||||
try!(self.fields.instantiate(a, BiTo, b_id));
|
self.fields.instantiate(a, BiTo, b_id)?;
|
||||||
Ok(a)
|
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 a1 = self.tcx().erase_late_bound_regions(a);
|
||||||
let b1 = self.tcx().erase_late_bound_regions(b);
|
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))
|
Ok(ty::Binder(c))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -70,10 +70,10 @@ pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>,
|
||||||
match (&a.sty, &b.sty) {
|
match (&a.sty, &b.sty) {
|
||||||
// Relate integral variables to other types
|
// Relate integral variables to other types
|
||||||
(&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => {
|
(&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => {
|
||||||
try!(infcx.int_unification_table
|
infcx.int_unification_table
|
||||||
.borrow_mut()
|
.borrow_mut()
|
||||||
.unify_var_var(a_id, b_id)
|
.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)
|
Ok(a)
|
||||||
}
|
}
|
||||||
(&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => {
|
(&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
|
// Relate floating-point variables to other types
|
||||||
(&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => {
|
(&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => {
|
||||||
try!(infcx.float_unification_table
|
infcx.float_unification_table
|
||||||
.borrow_mut()
|
.borrow_mut()
|
||||||
.unify_var_var(a_id, b_id)
|
.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)
|
Ok(a)
|
||||||
}
|
}
|
||||||
(&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => {
|
(&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)
|
val: ty::IntVarValue)
|
||||||
-> RelateResult<'tcx, Ty<'tcx>>
|
-> RelateResult<'tcx, Ty<'tcx>>
|
||||||
{
|
{
|
||||||
try!(infcx
|
infcx
|
||||||
.int_unification_table
|
.int_unification_table
|
||||||
.borrow_mut()
|
.borrow_mut()
|
||||||
.unify_var_value(vid, val)
|
.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 {
|
match val {
|
||||||
IntType(v) => Ok(infcx.tcx.mk_mach_int(v)),
|
IntType(v) => Ok(infcx.tcx.mk_mach_int(v)),
|
||||||
UintType(v) => Ok(infcx.tcx.mk_mach_uint(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)
|
val: ast::FloatTy)
|
||||||
-> RelateResult<'tcx, Ty<'tcx>>
|
-> RelateResult<'tcx, Ty<'tcx>>
|
||||||
{
|
{
|
||||||
try!(infcx
|
infcx
|
||||||
.float_unification_table
|
.float_unification_table
|
||||||
.borrow_mut()
|
.borrow_mut()
|
||||||
.unify_var_value(vid, val)
|
.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))
|
Ok(infcx.tcx.mk_mach_float(val))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -229,10 +229,10 @@ impl<'a, 'tcx> CombineFields<'a, 'tcx> {
|
||||||
Some(t) => t, // ...already instantiated.
|
Some(t) => t, // ...already instantiated.
|
||||||
None => { // ...not yet instantiated:
|
None => { // ...not yet instantiated:
|
||||||
// Generalize type if necessary.
|
// Generalize type if necessary.
|
||||||
let generalized_ty = try!(match dir {
|
let generalized_ty = match dir {
|
||||||
EqTo => self.generalize(a_ty, b_vid, false),
|
EqTo => self.generalize(a_ty, b_vid, false),
|
||||||
BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true),
|
BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true),
|
||||||
});
|
}?;
|
||||||
debug!("instantiate(a_ty={:?}, dir={:?}, \
|
debug!("instantiate(a_ty={:?}, dir={:?}, \
|
||||||
b_vid={:?}, generalized_ty={:?})",
|
b_vid={:?}, generalized_ty={:?})",
|
||||||
a_ty, dir, b_vid,
|
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
|
// relations wind up attributed to the same spans. We need
|
||||||
// to associate causes/spans with each of the relations in
|
// to associate causes/spans with each of the relations in
|
||||||
// the stack to get this right.
|
// the stack to get this right.
|
||||||
try!(match dir {
|
match dir {
|
||||||
BiTo => self.bivariate().relate(&a_ty, &b_ty),
|
BiTo => self.bivariate().relate(&a_ty, &b_ty),
|
||||||
EqTo => self.equate().relate(&a_ty, &b_ty),
|
EqTo => self.equate().relate(&a_ty, &b_ty),
|
||||||
SubtypeOf => self.sub().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),
|
SupertypeOf => self.sub().relate_with_variance(ty::Contravariant, &a_ty, &b_ty),
|
||||||
});
|
}?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -59,17 +59,17 @@ impl<'a, 'tcx> TypeRelation<'a,'tcx> for Equate<'a, 'tcx> {
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyInfer(TyVar(a_id)), _) => {
|
(&ty::TyInfer(TyVar(a_id)), _) => {
|
||||||
try!(self.fields.instantiate(b, EqTo, a_id));
|
self.fields.instantiate(b, EqTo, a_id)?;
|
||||||
Ok(a)
|
Ok(a)
|
||||||
}
|
}
|
||||||
|
|
||||||
(_, &ty::TyInfer(TyVar(b_id))) => {
|
(_, &ty::TyInfer(TyVar(b_id))) => {
|
||||||
try!(self.fields.instantiate(a, EqTo, b_id));
|
self.fields.instantiate(a, EqTo, b_id)?;
|
||||||
Ok(a)
|
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)
|
Ok(a)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -89,7 +89,7 @@ impl<'a, 'tcx> TypeRelation<'a,'tcx> for Equate<'a, 'tcx> {
|
||||||
-> RelateResult<'tcx, ty::Binder<T>>
|
-> RelateResult<'tcx, ty::Binder<T>>
|
||||||
where T: Relate<'a, 'tcx>
|
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)
|
self.fields.higher_ranked_sub(b, a)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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, ()> {
|
fn relate_bound(&self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> {
|
||||||
let mut sub = self.fields.sub();
|
let mut sub = self.fields.sub();
|
||||||
try!(sub.relate(&v, &a));
|
sub.relate(&v, &a)?;
|
||||||
try!(sub.relate(&v, &b));
|
sub.relate(&v, &b)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -75,7 +75,7 @@ impl<'a,'tcx> HigherRankedRelations<'a,'tcx> for CombineFields<'a,'tcx> {
|
||||||
debug!("b_prime={:?}", b_prime);
|
debug!("b_prime={:?}", b_prime);
|
||||||
|
|
||||||
// Compare types now that bound regions have been replaced.
|
// 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
|
// Presuming type comparison succeeds, we need to check
|
||||||
// that the skolemized regions do not "leak".
|
// that the skolemized regions do not "leak".
|
||||||
|
@ -118,7 +118,7 @@ impl<'a,'tcx> HigherRankedRelations<'a,'tcx> for CombineFields<'a,'tcx> {
|
||||||
|
|
||||||
// Collect constraints.
|
// Collect constraints.
|
||||||
let result0 =
|
let result0 =
|
||||||
try!(self.lub().relate(&a_with_fresh, &b_with_fresh));
|
self.lub().relate(&a_with_fresh, &b_with_fresh)?;
|
||||||
let result0 =
|
let result0 =
|
||||||
self.infcx.resolve_type_vars_if_possible(&result0);
|
self.infcx.resolve_type_vars_if_possible(&result0);
|
||||||
debug!("lub result0 = {:?}", result0);
|
debug!("lub result0 = {:?}", result0);
|
||||||
|
@ -212,7 +212,7 @@ impl<'a,'tcx> HigherRankedRelations<'a,'tcx> for CombineFields<'a,'tcx> {
|
||||||
|
|
||||||
// Collect constraints.
|
// Collect constraints.
|
||||||
let result0 =
|
let result0 =
|
||||||
try!(self.glb().relate(&a_with_fresh, &b_with_fresh));
|
self.glb().relate(&a_with_fresh, &b_with_fresh)?;
|
||||||
let result0 =
|
let result0 =
|
||||||
self.infcx.resolve_type_vars_if_possible(&result0);
|
self.infcx.resolve_type_vars_if_possible(&result0);
|
||||||
debug!("glb result0 = {:?}", result0);
|
debug!("glb result0 = {:?}", result0);
|
||||||
|
|
|
@ -66,14 +66,14 @@ pub fn super_lattice_tys<'a,'tcx,L:LatticeDir<'a,'tcx>>(this: &mut L,
|
||||||
(&ty::TyInfer(TyVar(..)), &ty::TyInfer(TyVar(..)))
|
(&ty::TyInfer(TyVar(..)), &ty::TyInfer(TyVar(..)))
|
||||||
if infcx.type_var_diverges(a) && infcx.type_var_diverges(b) => {
|
if infcx.type_var_diverges(a) && infcx.type_var_diverges(b) => {
|
||||||
let v = infcx.next_diverging_ty_var();
|
let v = infcx.next_diverging_ty_var();
|
||||||
try!(this.relate_bound(v, a, b));
|
this.relate_bound(v, a, b)?;
|
||||||
Ok(v)
|
Ok(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyInfer(TyVar(..)), _) |
|
(&ty::TyInfer(TyVar(..)), _) |
|
||||||
(_, &ty::TyInfer(TyVar(..))) => {
|
(_, &ty::TyInfer(TyVar(..))) => {
|
||||||
let v = infcx.next_ty_var();
|
let v = infcx.next_ty_var();
|
||||||
try!(this.relate_bound(v, a, b));
|
this.relate_bound(v, a, b)?;
|
||||||
Ok(v)
|
Ok(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -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, ()> {
|
fn relate_bound(&self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> {
|
||||||
let mut sub = self.fields.sub();
|
let mut sub = self.fields.sub();
|
||||||
try!(sub.relate(&a, &v));
|
sub.relate(&a, &v)?;
|
||||||
try!(sub.relate(&b, &v));
|
sub.relate(&b, &v)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -960,7 +960,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
|
||||||
let (ty::EquatePredicate(a, b), skol_map) =
|
let (ty::EquatePredicate(a, b), skol_map) =
|
||||||
self.skolemize_late_bound_regions(predicate, snapshot);
|
self.skolemize_late_bound_regions(predicate, snapshot);
|
||||||
let origin = TypeOrigin::EquatePredicate(span);
|
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)
|
self.leak_check(&skol_map, snapshot)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -75,13 +75,13 @@ impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Sub<'a, 'tcx> {
|
||||||
Ok(a)
|
Ok(a)
|
||||||
}
|
}
|
||||||
(&ty::TyInfer(TyVar(a_id)), _) => {
|
(&ty::TyInfer(TyVar(a_id)), _) => {
|
||||||
try!(self.fields
|
self.fields
|
||||||
.switch_expected()
|
.switch_expected()
|
||||||
.instantiate(b, SupertypeOf, a_id));
|
.instantiate(b, SupertypeOf, a_id)?;
|
||||||
Ok(a)
|
Ok(a)
|
||||||
}
|
}
|
||||||
(_, &ty::TyInfer(TyVar(b_id))) => {
|
(_, &ty::TyInfer(TyVar(b_id))) => {
|
||||||
try!(self.fields.instantiate(a, SubtypeOf, b_id));
|
self.fields.instantiate(a, SubtypeOf, b_id)?;
|
||||||
Ok(a)
|
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)
|
Ok(a)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -686,7 +686,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
|
||||||
for var_idx in 0..self.ir.num_vars {
|
for var_idx in 0..self.ir.num_vars {
|
||||||
let idx = node_base_idx + var_idx;
|
let idx = node_base_idx + var_idx;
|
||||||
if test(idx).is_valid() {
|
if test(idx).is_valid() {
|
||||||
try!(write!(wr, " {:?}", Variable(var_idx)));
|
write!(wr, " {:?}", Variable(var_idx))?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -378,7 +378,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'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(
|
Ok(unadjusted_ty.adjust(
|
||||||
self.tcx(), expr.span, expr.id,
|
self.tcx(), expr.span, expr.id,
|
||||||
self.typer.adjustments().get(&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>> {
|
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
|
// FIXME (Issue #18207): This code detects whether we are
|
||||||
// looking at a `ref x`, and if so, figures out what the type
|
// looking at a `ref x`, and if so, figures out what the type
|
||||||
// *being borrowed* is. But ideally we would put in a more
|
// *being borrowed* is. But ideally we would put in a more
|
||||||
|
@ -436,7 +436,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
|
||||||
adjustment,
|
adjustment,
|
||||||
expr);
|
expr);
|
||||||
// Result is an rvalue.
|
// 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))
|
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,
|
expr: &hir::Expr,
|
||||||
autoderefs: usize)
|
autoderefs: usize)
|
||||||
-> McResult<cmt<'tcx>> {
|
-> 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={:?}",
|
debug!("cat_expr_autoderefd: autoderefs={}, cmt={:?}",
|
||||||
autoderefs,
|
autoderefs,
|
||||||
cmt);
|
cmt);
|
||||||
for deref in 1..autoderefs + 1 {
|
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);
|
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>> {
|
pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
|
||||||
debug!("cat_expr: id={} expr={:?}", expr.id, expr);
|
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 {
|
match expr.node {
|
||||||
hir::ExprUnary(hir::UnDeref, ref e_base) => {
|
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)
|
self.cat_deref(expr, base_cmt, 0, None)
|
||||||
}
|
}
|
||||||
|
|
||||||
hir::ExprField(ref base, f_name) => {
|
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={:?}",
|
debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
|
||||||
expr.id,
|
expr.id,
|
||||||
expr,
|
expr,
|
||||||
|
@ -478,7 +478,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
|
||||||
}
|
}
|
||||||
|
|
||||||
hir::ExprTupField(ref base, idx) => {
|
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))
|
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)
|
self.cat_deref_common(expr, base_cmt, 1, elem_ty, Some(context), true)
|
||||||
}
|
}
|
||||||
None => {
|
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) => {
|
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 {
|
match ty.sty {
|
||||||
ty::TyClosure(closure_id, _) => {
|
ty::TyClosure(closure_id, _) => {
|
||||||
match self.typer.closure_kind(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,
|
let upvar_id = ty::UpvarId { var_id: var_id,
|
||||||
closure_expr_id: fn_node_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
|
// Mutability of original variable itself
|
||||||
let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
|
let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
|
||||||
|
@ -921,7 +921,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
|
||||||
implicit: bool)
|
implicit: bool)
|
||||||
-> McResult<cmt<'tcx>>
|
-> 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) => {
|
deref_ptr(ptr) => {
|
||||||
let ptr = if implicit {
|
let ptr = if implicit {
|
||||||
match ptr {
|
match ptr {
|
||||||
|
@ -1030,7 +1030,7 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
|
||||||
context: InteriorOffsetKind)
|
context: InteriorOffsetKind)
|
||||||
-> McResult<cmt<'tcx>>
|
-> 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) => {
|
deref_ptr(ptr) => {
|
||||||
// for unique ptrs, we inherit mutability from the
|
// for unique ptrs, we inherit mutability from the
|
||||||
// owning reference.
|
// owning reference.
|
||||||
|
@ -1069,13 +1069,13 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
|
||||||
vec_cmt: cmt<'tcx>,
|
vec_cmt: cmt<'tcx>,
|
||||||
slice_pat: &hir::Pat)
|
slice_pat: &hir::Pat)
|
||||||
-> McResult<(cmt<'tcx>, hir::Mutability, ty::Region)> {
|
-> 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(),
|
let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
|
||||||
slice_pat,
|
slice_pat,
|
||||||
slice_ty);
|
slice_ty);
|
||||||
let context = InteriorOffsetKind::Pattern;
|
let context = InteriorOffsetKind::Pattern;
|
||||||
let cmt_vec = try!(self.deref_vec(slice_pat, vec_cmt, context));
|
let cmt_vec = self.deref_vec(slice_pat, vec_cmt, context)?;
|
||||||
let cmt_slice = try!(self.cat_index(slice_pat, cmt_vec, context));
|
let cmt_slice = self.cat_index(slice_pat, cmt_vec, context)?;
|
||||||
return Ok((cmt_slice, slice_mutbl, slice_r));
|
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,
|
/// 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(..)) => {
|
Some(Def::Variant(..)) => {
|
||||||
// variant(x, y, z)
|
// variant(x, y, z)
|
||||||
for (i, subpat) in subpats.iter().enumerate() {
|
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 =
|
let subcmt =
|
||||||
self.cat_imm_interior(
|
self.cat_imm_interior(
|
||||||
pat, cmt.clone(), subpat_ty,
|
pat, cmt.clone(), subpat_ty,
|
||||||
InteriorField(PositionalField(i)));
|
InteriorField(PositionalField(i)));
|
||||||
|
|
||||||
try!(self.cat_pattern_(subcmt, &subpat, op));
|
self.cat_pattern_(subcmt, &subpat, op)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(Def::Struct(..)) => {
|
Some(Def::Struct(..)) => {
|
||||||
for (i, subpat) in subpats.iter().enumerate() {
|
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 =
|
let cmt_field =
|
||||||
self.cat_imm_interior(
|
self.cat_imm_interior(
|
||||||
pat, cmt.clone(), subpat_ty,
|
pat, cmt.clone(), subpat_ty,
|
||||||
InteriorField(PositionalField(i)));
|
InteriorField(PositionalField(i)));
|
||||||
try!(self.cat_pattern_(cmt_field, &subpat, op));
|
self.cat_pattern_(cmt_field, &subpat, op)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(Def::Const(..)) | Some(Def::AssociatedConst(..)) => {
|
Some(Def::Const(..)) | Some(Def::AssociatedConst(..)) => {
|
||||||
for subpat in subpats {
|
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)) => {
|
PatKind::Ident(_, _, Some(ref subpat)) => {
|
||||||
try!(self.cat_pattern_(cmt, &subpat, op));
|
self.cat_pattern_(cmt, &subpat, op)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
PatKind::Struct(_, ref field_pats, _) => {
|
PatKind::Struct(_, ref field_pats, _) => {
|
||||||
// {f1: p1, ..., fN: pN}
|
// {f1: p1, ..., fN: pN}
|
||||||
for fp in field_pats {
|
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);
|
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) => {
|
PatKind::Tup(ref subpats) => {
|
||||||
// (p1, ..., pN)
|
// (p1, ..., pN)
|
||||||
for (i, subpat) in subpats.iter().enumerate() {
|
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 =
|
let subcmt =
|
||||||
self.cat_imm_interior(
|
self.cat_imm_interior(
|
||||||
pat, cmt.clone(), subpat_ty,
|
pat, cmt.clone(), subpat_ty,
|
||||||
InteriorField(PositionalField(i)));
|
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
|
// box p1, &p1, &mut p1. we can ignore the mutability of
|
||||||
// PatKind::Ref since that information is already contained
|
// PatKind::Ref since that information is already contained
|
||||||
// in the type.
|
// in the type.
|
||||||
let subcmt = try!(self.cat_deref(pat, cmt, 0, None));
|
let subcmt = self.cat_deref(pat, cmt, 0, None)?;
|
||||||
try!(self.cat_pattern_(subcmt, &subpat, op));
|
self.cat_pattern_(subcmt, &subpat, op)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
PatKind::Vec(ref before, ref slice, ref after) => {
|
PatKind::Vec(ref before, ref slice, ref after) => {
|
||||||
let context = InteriorOffsetKind::Pattern;
|
let context = InteriorOffsetKind::Pattern;
|
||||||
let vec_cmt = try!(self.deref_vec(pat, cmt, context));
|
let vec_cmt = self.deref_vec(pat, cmt, context)?;
|
||||||
let elt_cmt = try!(self.cat_index(pat, vec_cmt, context));
|
let elt_cmt = self.cat_index(pat, vec_cmt, context)?;
|
||||||
for before_pat in before {
|
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 {
|
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);
|
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 {
|
for after_pat in after {
|
||||||
try!(self.cat_pattern_(elt_cmt.clone(), &after_pat, op));
|
self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -41,15 +41,15 @@ pub struct CodeExtent(u32);
|
||||||
|
|
||||||
impl fmt::Debug for CodeExtent {
|
impl fmt::Debug for CodeExtent {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
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 {
|
if let Some(tcx) = opt_tcx {
|
||||||
let data = tcx.region_maps.code_extents.borrow()[self.0 as usize];
|
let data = tcx.region_maps.code_extents.borrow()[self.0 as usize];
|
||||||
try!(write!(f, "/{:?}", data));
|
write!(f, "/{:?}", data)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
write!(f, ")")
|
write!(f, ")")
|
||||||
}
|
}
|
||||||
|
|
|
@ -102,7 +102,7 @@ pub fn krate(sess: &Session,
|
||||||
let _task = hir_map.dep_graph.in_task(DepNode::ResolveLifetimes);
|
let _task = hir_map.dep_graph.in_task(DepNode::ResolveLifetimes);
|
||||||
let krate = hir_map.krate();
|
let krate = hir_map.krate();
|
||||||
let mut named_region_map = NodeMap();
|
let mut named_region_map = NodeMap();
|
||||||
try!(sess.track_errors(|| {
|
sess.track_errors(|| {
|
||||||
krate.visit_all_items(&mut LifetimeContext {
|
krate.visit_all_items(&mut LifetimeContext {
|
||||||
sess: sess,
|
sess: sess,
|
||||||
named_region_map: &mut named_region_map,
|
named_region_map: &mut named_region_map,
|
||||||
|
@ -111,7 +111,7 @@ pub fn krate(sess: &Session,
|
||||||
trait_ref_hack: false,
|
trait_ref_hack: false,
|
||||||
labels_in_fn: vec![],
|
labels_in_fn: vec![],
|
||||||
});
|
});
|
||||||
}));
|
})?;
|
||||||
Ok(named_region_map)
|
Ok(named_region_map)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -211,7 +211,7 @@ impl<'tcx> FulfillmentContext<'tcx> {
|
||||||
infcx: &InferCtxt<'a,'tcx>)
|
infcx: &InferCtxt<'a,'tcx>)
|
||||||
-> Result<(),Vec<FulfillmentError<'tcx>>>
|
-> Result<(),Vec<FulfillmentError<'tcx>>>
|
||||||
{
|
{
|
||||||
try!(self.select_where_possible(infcx));
|
self.select_where_possible(infcx)?;
|
||||||
let errors: Vec<_> =
|
let errors: Vec<_> =
|
||||||
self.predicates.to_errors(CodeAmbiguity)
|
self.predicates.to_errors(CodeAmbiguity)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
|
|
@ -320,12 +320,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
let _task = self.tcx().dep_graph.in_task(dep_node);
|
let _task = self.tcx().dep_graph.in_task(dep_node);
|
||||||
|
|
||||||
let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
|
let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
|
||||||
match try!(self.candidate_from_obligation(&stack)) {
|
match self.candidate_from_obligation(&stack)? {
|
||||||
None => {
|
None => {
|
||||||
self.consider_unification_despite_ambiguity(obligation);
|
self.consider_unification_despite_ambiguity(obligation);
|
||||||
Ok(None)
|
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);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
let candidate_set = try!(self.assemble_candidates(stack));
|
let candidate_set = self.assemble_candidates(stack)?;
|
||||||
|
|
||||||
if candidate_set.ambiguous {
|
if candidate_set.ambiguous {
|
||||||
debug!("candidate set contains ambig");
|
debug!("candidate set contains ambig");
|
||||||
|
@ -1034,19 +1034,19 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
|
|
||||||
// User-defined copy impls are permitted, but only for
|
// User-defined copy impls are permitted, but only for
|
||||||
// structs and enums.
|
// 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.
|
// 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,
|
obligation,
|
||||||
&mut candidates));
|
&mut candidates)?;
|
||||||
}
|
}
|
||||||
Some(bound @ ty::BoundSized) => {
|
Some(bound @ ty::BoundSized) => {
|
||||||
// Sized is never implementable by end-users, it is
|
// Sized is never implementable by end-users, it is
|
||||||
// always automatically computed.
|
// always automatically computed.
|
||||||
try!(self.assemble_builtin_bound_candidates(bound,
|
self.assemble_builtin_bound_candidates(bound,
|
||||||
obligation,
|
obligation,
|
||||||
&mut candidates));
|
&mut candidates)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
None if self.tcx().lang_items.unsize_trait() ==
|
None if self.tcx().lang_items.unsize_trait() ==
|
||||||
|
@ -1057,19 +1057,19 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
Some(ty::BoundSend) |
|
Some(ty::BoundSend) |
|
||||||
Some(ty::BoundSync) |
|
Some(ty::BoundSync) |
|
||||||
None => {
|
None => {
|
||||||
try!(self.assemble_closure_candidates(obligation, &mut candidates));
|
self.assemble_closure_candidates(obligation, &mut candidates)?;
|
||||||
try!(self.assemble_fn_pointer_candidates(obligation, &mut candidates));
|
self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
|
||||||
try!(self.assemble_candidates_from_impls(obligation, &mut candidates));
|
self.assemble_candidates_from_impls(obligation, &mut candidates)?;
|
||||||
self.assemble_candidates_from_object_ty(obligation, &mut candidates);
|
self.assemble_candidates_from_object_ty(obligation, &mut candidates);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.assemble_candidates_from_projected_tys(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
|
// Default implementations have lower priority, so we only
|
||||||
// consider triggering a default if there is no other impl that can apply.
|
// consider triggering a default if there is no other impl that can apply.
|
||||||
if candidates.vec.is_empty() {
|
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());
|
debug!("candidate list size: {}", candidates.vec.len());
|
||||||
Ok(candidates)
|
Ok(candidates)
|
||||||
|
@ -2044,7 +2044,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
match candidate {
|
match candidate {
|
||||||
BuiltinCandidate(builtin_bound) => {
|
BuiltinCandidate(builtin_bound) => {
|
||||||
Ok(VtableBuiltin(
|
Ok(VtableBuiltin(
|
||||||
try!(self.confirm_builtin_candidate(obligation, builtin_bound))))
|
self.confirm_builtin_candidate(obligation, builtin_bound)?))
|
||||||
}
|
}
|
||||||
|
|
||||||
ParamCandidate(param) => {
|
ParamCandidate(param) => {
|
||||||
|
@ -2064,13 +2064,13 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
|
|
||||||
ImplCandidate(impl_def_id) => {
|
ImplCandidate(impl_def_id) => {
|
||||||
let vtable_impl =
|
let vtable_impl =
|
||||||
try!(self.confirm_impl_candidate(obligation, impl_def_id));
|
self.confirm_impl_candidate(obligation, impl_def_id)?;
|
||||||
Ok(VtableImpl(vtable_impl))
|
Ok(VtableImpl(vtable_impl))
|
||||||
}
|
}
|
||||||
|
|
||||||
ClosureCandidate(closure_def_id, substs) => {
|
ClosureCandidate(closure_def_id, substs) => {
|
||||||
let vtable_closure =
|
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))
|
Ok(VtableClosure(vtable_closure))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2090,7 +2090,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
|
|
||||||
FnPointerCandidate => {
|
FnPointerCandidate => {
|
||||||
let fn_type =
|
let fn_type =
|
||||||
try!(self.confirm_fn_pointer_candidate(obligation));
|
self.confirm_fn_pointer_candidate(obligation)?;
|
||||||
Ok(VtableFnPointer(fn_type))
|
Ok(VtableFnPointer(fn_type))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2100,7 +2100,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
}
|
}
|
||||||
|
|
||||||
BuiltinUnsizeCandidate => {
|
BuiltinUnsizeCandidate => {
|
||||||
let data = try!(self.confirm_builtin_unsize_candidate(obligation));
|
let data = self.confirm_builtin_unsize_candidate(obligation)?;
|
||||||
Ok(VtableBuiltin(data))
|
Ok(VtableBuiltin(data))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2152,7 +2152,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
debug!("confirm_builtin_candidate({:?})",
|
debug!("confirm_builtin_candidate({:?})",
|
||||||
obligation);
|
obligation);
|
||||||
|
|
||||||
match try!(self.builtin_bound(bound, obligation)) {
|
match self.builtin_bound(bound, obligation)? {
|
||||||
If(nested) => Ok(self.vtable_builtin_data(obligation, bound, nested)),
|
If(nested) => Ok(self.vtable_builtin_data(obligation, bound, nested)),
|
||||||
AmbiguousBuiltin | ParameterBuiltin => {
|
AmbiguousBuiltin | ParameterBuiltin => {
|
||||||
self.tcx().sess.span_bug(
|
self.tcx().sess.span_bug(
|
||||||
|
@ -2421,9 +2421,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
util::TupleArgumentsFlag::Yes)
|
util::TupleArgumentsFlag::Yes)
|
||||||
.map_bound(|(trait_ref, _)| trait_ref);
|
.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(),
|
obligation.predicate.to_poly_trait_ref(),
|
||||||
trait_ref));
|
trait_ref)?;
|
||||||
Ok(self_ty)
|
Ok(self_ty)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2449,9 +2449,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
trait_ref,
|
trait_ref,
|
||||||
obligations);
|
obligations);
|
||||||
|
|
||||||
try!(self.confirm_poly_trait_refs(obligation.cause.clone(),
|
self.confirm_poly_trait_refs(obligation.cause.clone(),
|
||||||
obligation.predicate.to_poly_trait_ref(),
|
obligation.predicate.to_poly_trait_ref(),
|
||||||
trait_ref));
|
trait_ref)?;
|
||||||
|
|
||||||
Ok(VtableClosureData {
|
Ok(VtableClosureData {
|
||||||
closure_def_id: closure_def_id,
|
closure_def_id: closure_def_id,
|
||||||
|
@ -2795,7 +2795,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
||||||
where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
|
where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
|
||||||
-> Result<Vec<PredicateObligation<'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())
|
Ok(Vec::new())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -418,7 +418,7 @@ pub fn predicate_for_builtin_bound<'tcx>(
|
||||||
param_ty: Ty<'tcx>)
|
param_ty: Ty<'tcx>)
|
||||||
-> Result<PredicateObligation<'tcx>, ErrorReported>
|
-> 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))
|
Ok(predicate_for_trait_ref(cause, trait_ref, recursion_depth))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -91,6 +91,6 @@ impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Match<'a, 'tcx> {
|
||||||
-> RelateResult<'tcx, ty::Binder<T>>
|
-> RelateResult<'tcx, ty::Binder<T>>
|
||||||
where T: Relate<'a,'tcx>
|
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())?))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1473,7 +1473,7 @@ impl<'tcx> Encodable for AdtDef<'tcx> {
|
||||||
|
|
||||||
impl<'tcx> Decodable for AdtDef<'tcx> {
|
impl<'tcx> Decodable for AdtDef<'tcx> {
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<AdtDef<'tcx>, D::Error> {
|
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, _| {
|
cstore::tls::with_decoding_context(d, |dcx, _| {
|
||||||
let def_id = dcx.translate_def_id(def_id);
|
let def_id = dcx.translate_def_id(def_id);
|
||||||
|
|
|
@ -108,7 +108,7 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::TypeAndMut<'tcx> {
|
||||||
ast::Mutability::MutImmutable => ty::Covariant,
|
ast::Mutability::MutImmutable => ty::Covariant,
|
||||||
ast::Mutability::MutMutable => ty::Invariant,
|
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})
|
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 a_tps = a_subst.types.get_slice(space);
|
||||||
let b_tps = b_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 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);
|
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 a_regions = a.get_slice(space);
|
||||||
let b_regions = b.get_slice(space);
|
let b_regions = b.get_slice(space);
|
||||||
let r_variances = variances.map(|v| v.regions.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,
|
r_variances,
|
||||||
a_regions,
|
a_regions,
|
||||||
b_regions));
|
b_regions)?;
|
||||||
substs.mut_regions().replace(space, 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>>
|
-> RelateResult<'tcx, ty::BareFnTy<'tcx>>
|
||||||
where R: TypeRelation<'a,'tcx>
|
where R: TypeRelation<'a,'tcx>
|
||||||
{
|
{
|
||||||
let unsafety = try!(relation.relate(&a.unsafety, &b.unsafety));
|
let unsafety = relation.relate(&a.unsafety, &b.unsafety)?;
|
||||||
let abi = try!(relation.relate(&a.abi, &b.abi));
|
let abi = relation.relate(&a.abi, &b.abi)?;
|
||||||
let sig = try!(relation.relate(&a.sig, &b.sig));
|
let sig = relation.relate(&a.sig, &b.sig)?;
|
||||||
Ok(ty::BareFnTy {unsafety: unsafety,
|
Ok(ty::BareFnTy {unsafety: unsafety,
|
||||||
abi: abi,
|
abi: abi,
|
||||||
sig: sig})
|
sig: sig})
|
||||||
|
@ -260,19 +260,19 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::FnSig<'tcx> {
|
||||||
expected_found(relation, &a.variadic, &b.variadic)));
|
expected_found(relation, &a.variadic, &b.variadic)));
|
||||||
}
|
}
|
||||||
|
|
||||||
let inputs = try!(relate_arg_vecs(relation,
|
let inputs = relate_arg_vecs(relation,
|
||||||
&a.inputs,
|
&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)) =>
|
(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) =>
|
(ty::FnDiverging, ty::FnDiverging) =>
|
||||||
Ok(ty::FnDiverging),
|
Ok(ty::FnDiverging),
|
||||||
(a, b) =>
|
(a, b) =>
|
||||||
Err(TypeError::ConvergenceMismatch(
|
Err(TypeError::ConvergenceMismatch(
|
||||||
expected_found(relation, &(a != ty::FnDiverging), &(b != ty::FnDiverging)))),
|
expected_found(relation, &(a != ty::FnDiverging), &(b != ty::FnDiverging)))),
|
||||||
});
|
}?;
|
||||||
|
|
||||||
return Ok(ty::FnSig {inputs: inputs,
|
return Ok(ty::FnSig {inputs: inputs,
|
||||||
output: output,
|
output: output,
|
||||||
|
@ -336,7 +336,7 @@ impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::ProjectionTy<'tcx> {
|
||||||
Err(TypeError::ProjectionNameMismatched(
|
Err(TypeError::ProjectionNameMismatched(
|
||||||
expected_found(relation, &a.item_name, &b.item_name)))
|
expected_found(relation, &a.item_name, &b.item_name)))
|
||||||
} else {
|
} 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 })
|
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>>
|
-> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>>
|
||||||
where R: TypeRelation<'a,'tcx>
|
where R: TypeRelation<'a,'tcx>
|
||||||
{
|
{
|
||||||
let projection_ty = try!(relation.relate(&a.projection_ty, &b.projection_ty));
|
let projection_ty = relation.relate(&a.projection_ty, &b.projection_ty)?;
|
||||||
let ty = try!(relation.relate(&a.ty, &b.ty));
|
let ty = relation.relate(&a.ty, &b.ty)?;
|
||||||
Ok(ty::ProjectionPredicate { projection_ty: projection_ty, ty: 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>
|
where R: TypeRelation<'a,'tcx>
|
||||||
{
|
{
|
||||||
let r =
|
let r =
|
||||||
try!(relation.with_cause(
|
relation.with_cause(
|
||||||
Cause::ExistentialRegionBound,
|
Cause::ExistentialRegionBound,
|
||||||
|relation| relation.relate_with_variance(ty::Contravariant,
|
|relation| relation.relate_with_variance(ty::Contravariant,
|
||||||
&a.region_bound,
|
&a.region_bound,
|
||||||
&b.region_bound)));
|
&b.region_bound))?;
|
||||||
let nb = try!(relation.relate(&a.builtin_bounds, &b.builtin_bounds));
|
let nb = relation.relate(&a.builtin_bounds, &b.builtin_bounds)?;
|
||||||
let pb = try!(relation.relate(&a.projection_bounds, &b.projection_bounds));
|
let pb = relation.relate(&a.projection_bounds, &b.projection_bounds)?;
|
||||||
Ok(ty::ExistentialBounds { region_bound: r,
|
Ok(ty::ExistentialBounds { region_bound: r,
|
||||||
builtin_bounds: nb,
|
builtin_bounds: nb,
|
||||||
projection_bounds: pb })
|
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 {
|
if a.def_id != b.def_id {
|
||||||
Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
|
Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
|
||||||
} else {
|
} 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) })
|
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))
|
(&ty::TyEnum(a_def, a_substs), &ty::TyEnum(b_def, b_substs))
|
||||||
if a_def == b_def =>
|
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)))
|
Ok(tcx.mk_enum(a_def, tcx.mk_substs(substs)))
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyTrait(ref a_), &ty::TyTrait(ref b_)) =>
|
(&ty::TyTrait(ref a_), &ty::TyTrait(ref b_)) =>
|
||||||
{
|
{
|
||||||
let principal = try!(relation.relate(&a_.principal, &b_.principal));
|
let principal = relation.relate(&a_.principal, &b_.principal)?;
|
||||||
let bounds = try!(relation.relate(&a_.bounds, &b_.bounds));
|
let bounds = relation.relate(&a_.bounds, &b_.bounds)?;
|
||||||
Ok(tcx.mk_trait(principal, bounds))
|
Ok(tcx.mk_trait(principal, bounds))
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyStruct(a_def, a_substs), &ty::TyStruct(b_def, b_substs))
|
(&ty::TyStruct(a_def, a_substs), &ty::TyStruct(b_def, b_substs))
|
||||||
if a_def == b_def =>
|
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)))
|
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
|
// All TyClosure types with the same id represent
|
||||||
// the (anonymous) type of the same closure expression. So
|
// the (anonymous) type of the same closure expression. So
|
||||||
// all of their regions should be equated.
|
// 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))
|
Ok(tcx.mk_closure_from_closure_substs(a_id, substs))
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyBox(a_inner), &ty::TyBox(b_inner)) =>
|
(&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))
|
Ok(tcx.mk_box(typ))
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyRawPtr(ref a_mt), &ty::TyRawPtr(ref b_mt)) =>
|
(&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))
|
Ok(tcx.mk_ptr(mt))
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyRef(a_r, ref a_mt), &ty::TyRef(b_r, ref b_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 r = relation.relate_with_variance(ty::Contravariant, a_r, b_r)?;
|
||||||
let mt = try!(relation.relate(a_mt, b_mt));
|
let mt = relation.relate(a_mt, b_mt)?;
|
||||||
Ok(tcx.mk_ref(tcx.mk_region(r), mt))
|
Ok(tcx.mk_ref(tcx.mk_region(r), mt))
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyArray(a_t, sz_a), &ty::TyArray(b_t, sz_b)) =>
|
(&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 {
|
if sz_a == sz_b {
|
||||||
Ok(tcx.mk_array(t, sz_a))
|
Ok(tcx.mk_array(t, sz_a))
|
||||||
} else {
|
} 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)) =>
|
(&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))
|
Ok(tcx.mk_slice(t))
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyTuple(ref as_), &ty::TyTuple(ref bs)) =>
|
(&ty::TyTuple(ref as_), &ty::TyTuple(ref bs)) =>
|
||||||
{
|
{
|
||||||
if as_.len() == bs.len() {
|
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))
|
.map(|(a, b)| relation.relate(a, b))
|
||||||
.collect::<Result<_, _>>());
|
.collect::<Result<_, _>>()?;
|
||||||
Ok(tcx.mk_tup(ts))
|
Ok(tcx.mk_tup(ts))
|
||||||
} else if !(as_.is_empty() || bs.is_empty()) {
|
} else if !(as_.is_empty() || bs.is_empty()) {
|
||||||
Err(TypeError::TupleSize(
|
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))
|
&ty::TyFnDef(b_def_id, b_substs, b_fty))
|
||||||
if a_def_id == b_def_id =>
|
if a_def_id == b_def_id =>
|
||||||
{
|
{
|
||||||
let substs = try!(relate_substs(relation, None, a_substs, b_substs));
|
let substs = relate_substs(relation, None, a_substs, b_substs)?;
|
||||||
let fty = try!(relation.relate(a_fty, b_fty));
|
let fty = relation.relate(a_fty, b_fty)?;
|
||||||
Ok(tcx.mk_fn_def(a_def_id, tcx.mk_substs(substs), fty))
|
Ok(tcx.mk_fn_def(a_def_id, tcx.mk_substs(substs), fty))
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyFnPtr(a_fty), &ty::TyFnPtr(b_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))
|
Ok(tcx.mk_fn_ptr(fty))
|
||||||
}
|
}
|
||||||
|
|
||||||
(&ty::TyProjection(ref a_data), &ty::TyProjection(ref b_data)) =>
|
(&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))
|
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>>
|
-> RelateResult<'tcx, ty::ClosureSubsts<'tcx>>
|
||||||
where R: TypeRelation<'a,'tcx>
|
where R: TypeRelation<'a,'tcx>
|
||||||
{
|
{
|
||||||
let func_substs = try!(relate_substs(relation, None, a.func_substs, b.func_substs));
|
let func_substs = relate_substs(relation, None, a.func_substs, b.func_substs)?;
|
||||||
let upvar_tys = try!(relation.relate_zip(&a.upvar_tys, &b.upvar_tys));
|
let upvar_tys = relation.relate_zip(&a.upvar_tys, &b.upvar_tys)?;
|
||||||
Ok(ty::ClosureSubsts { func_substs: relation.tcx().mk_substs(func_substs),
|
Ok(ty::ClosureSubsts { func_substs: relation.tcx().mk_substs(func_substs),
|
||||||
upvar_tys: upvar_tys })
|
upvar_tys: upvar_tys })
|
||||||
}
|
}
|
||||||
|
@ -645,7 +645,7 @@ impl<'a,'tcx:'a,T> Relate<'a,'tcx> for Rc<T>
|
||||||
{
|
{
|
||||||
let a: &T = a;
|
let a: &T = a;
|
||||||
let b: &T = b;
|
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 a: &T = a;
|
||||||
let b: &T = b;
|
let b: &T = b;
|
||||||
Ok(Box::new(try!(relation.relate(a, b))))
|
Ok(Box::new(relation.relate(a, b)?))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -250,7 +250,7 @@ pub struct ClosureSubsts<'tcx> {
|
||||||
|
|
||||||
impl<'tcx> Decodable for &'tcx ClosureSubsts<'tcx> {
|
impl<'tcx> Decodable for &'tcx ClosureSubsts<'tcx> {
|
||||||
fn decode<S: Decoder>(s: &mut S) -> Result<&'tcx ClosureSubsts<'tcx>, S::Error> {
|
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() };
|
let dummy_def_id: DefId = unsafe { mem::zeroed() };
|
||||||
|
|
||||||
cstore::tls::with_decoding_context(s, |dcx, _| {
|
cstore::tls::with_decoding_context(s, |dcx, _| {
|
||||||
|
|
|
@ -356,7 +356,7 @@ impl<'tcx> BasicBlockData<'tcx> {
|
||||||
|
|
||||||
impl<'tcx> Debug for Terminator<'tcx> {
|
impl<'tcx> Debug for Terminator<'tcx> {
|
||||||
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
|
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
|
||||||
try!(self.fmt_head(fmt));
|
self.fmt_head(fmt)?;
|
||||||
let successors = self.successors();
|
let successors = self.successors();
|
||||||
let labels = self.fmt_successor_labels();
|
let labels = self.fmt_successor_labels();
|
||||||
assert_eq!(successors.len(), labels.len());
|
assert_eq!(successors.len(), labels.len());
|
||||||
|
@ -367,12 +367,12 @@ impl<'tcx> Debug for Terminator<'tcx> {
|
||||||
1 => write!(fmt, " -> {:?}", successors[0]),
|
1 => write!(fmt, " -> {:?}", successors[0]),
|
||||||
|
|
||||||
_ => {
|
_ => {
|
||||||
try!(write!(fmt, " -> ["));
|
write!(fmt, " -> [")?;
|
||||||
for (i, target) in successors.iter().enumerate() {
|
for (i, target) in successors.iter().enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
try!(write!(fmt, ", "));
|
write!(fmt, ", ")?;
|
||||||
}
|
}
|
||||||
try!(write!(fmt, "{}: {:?}", labels[i], target));
|
write!(fmt, "{}: {:?}", labels[i], target)?;
|
||||||
}
|
}
|
||||||
write!(fmt, "]")
|
write!(fmt, "]")
|
||||||
}
|
}
|
||||||
|
@ -397,14 +397,14 @@ impl<'tcx> Terminator<'tcx> {
|
||||||
Drop { ref value, .. } => write!(fmt, "drop({:?})", value),
|
Drop { ref value, .. } => write!(fmt, "drop({:?})", value),
|
||||||
Call { ref func, ref args, ref destination, .. } => {
|
Call { ref func, ref args, ref destination, .. } => {
|
||||||
if let Some((ref destination, _)) = *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() {
|
for (index, arg) in args.iter().enumerate() {
|
||||||
if index > 0 {
|
if index > 0 {
|
||||||
try!(write!(fmt, ", "));
|
write!(fmt, ", ")?;
|
||||||
}
|
}
|
||||||
try!(write!(fmt, "{:?}", arg));
|
write!(fmt, "{:?}", arg)?;
|
||||||
}
|
}
|
||||||
write!(fmt, ")")
|
write!(fmt, ")")
|
||||||
}
|
}
|
||||||
|
@ -808,11 +808,11 @@ impl<'tcx> Debug for Rvalue<'tcx> {
|
||||||
Adt(adt_def, variant, substs) => {
|
Adt(adt_def, variant, substs) => {
|
||||||
let variant_def = &adt_def.variants[variant];
|
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, &[],
|
ppaux::Ns::Value, &[],
|
||||||
|tcx| {
|
|tcx| {
|
||||||
tcx.lookup_item_type(variant_def.did).generics
|
tcx.lookup_item_type(variant_def.did).generics
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
match variant_def.kind() {
|
match variant_def.kind() {
|
||||||
ty::VariantKind::Unit => Ok(()),
|
ty::VariantKind::Unit => Ok(()),
|
||||||
|
@ -903,7 +903,7 @@ impl<'tcx> Debug for Literal<'tcx> {
|
||||||
|tcx| tcx.lookup_item_type(def_id).generics)
|
|tcx| tcx.lookup_item_type(def_id).generics)
|
||||||
}
|
}
|
||||||
Value { ref value } => {
|
Value { ref value } => {
|
||||||
try!(write!(fmt, "const "));
|
write!(fmt, "const ")?;
|
||||||
fmt_const_val(fmt, value)
|
fmt_const_val(fmt, value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,23 +34,23 @@ fn fn_sig(f: &mut fmt::Formatter,
|
||||||
variadic: bool,
|
variadic: bool,
|
||||||
output: ty::FnOutput)
|
output: ty::FnOutput)
|
||||||
-> fmt::Result {
|
-> fmt::Result {
|
||||||
try!(write!(f, "("));
|
write!(f, "(")?;
|
||||||
let mut inputs = inputs.iter();
|
let mut inputs = inputs.iter();
|
||||||
if let Some(&ty) = inputs.next() {
|
if let Some(&ty) = inputs.next() {
|
||||||
try!(write!(f, "{}", ty));
|
write!(f, "{}", ty)?;
|
||||||
for &ty in inputs {
|
for &ty in inputs {
|
||||||
try!(write!(f, ", {}", ty));
|
write!(f, ", {}", ty)?;
|
||||||
}
|
}
|
||||||
if variadic {
|
if variadic {
|
||||||
try!(write!(f, ", ..."));
|
write!(f, ", ...")?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try!(write!(f, ")"));
|
write!(f, ")")?;
|
||||||
|
|
||||||
match output {
|
match output {
|
||||||
ty::FnConverging(ty) => {
|
ty::FnConverging(ty) => {
|
||||||
if !ty.is_nil() {
|
if !ty.is_nil() {
|
||||||
try!(write!(f, " -> {}", ty));
|
write!(f, " -> {}", ty)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -77,10 +77,10 @@ pub fn parameterized<GG>(f: &mut fmt::Formatter,
|
||||||
where GG: for<'tcx> FnOnce(&TyCtxt<'tcx>) -> ty::Generics<'tcx>
|
where GG: for<'tcx> FnOnce(&TyCtxt<'tcx>) -> ty::Generics<'tcx>
|
||||||
{
|
{
|
||||||
if let (Ns::Value, Some(self_ty)) = (ns, substs.self_ty()) {
|
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 {
|
let (did, last_name) = if ns == Ns::Value {
|
||||||
// Try to get the impl/trait parent, if this is an
|
// Try to get the impl/trait parent, if this is an
|
||||||
// associated value item (method or constant).
|
// associated value item (method or constant).
|
||||||
|
@ -89,9 +89,9 @@ pub fn parameterized<GG>(f: &mut fmt::Formatter,
|
||||||
} else {
|
} else {
|
||||||
(did, None)
|
(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))
|
Ok((tcx.lang_items.fn_trait_kind(did), tcx.sess.verbose(), last_name))
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
let mut empty = true;
|
let mut empty = true;
|
||||||
let mut start_or_continue = |f: &mut fmt::Formatter, start: &str, cont: &str| {
|
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 {
|
if verbose {
|
||||||
match substs.regions {
|
match substs.regions {
|
||||||
subst::ErasedRegions => {
|
subst::ErasedRegions => {
|
||||||
try!(start_or_continue(f, "<", ", "));
|
start_or_continue(f, "<", ", ")?;
|
||||||
try!(write!(f, ".."));
|
write!(f, "..")?;
|
||||||
}
|
}
|
||||||
subst::NonerasedRegions(ref regions) => {
|
subst::NonerasedRegions(ref regions) => {
|
||||||
for region in regions {
|
for region in regions {
|
||||||
try!(start_or_continue(f, "<", ", "));
|
start_or_continue(f, "<", ", ")?;
|
||||||
try!(write!(f, "{:?}", region));
|
write!(f, "{:?}", region)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for &ty in &substs.types {
|
for &ty in &substs.types {
|
||||||
try!(start_or_continue(f, "<", ", "));
|
start_or_continue(f, "<", ", ")?;
|
||||||
try!(write!(f, "{}", ty));
|
write!(f, "{}", ty)?;
|
||||||
}
|
}
|
||||||
for projection in projections {
|
for projection in projections {
|
||||||
try!(start_or_continue(f, "<", ", "));
|
start_or_continue(f, "<", ", ")?;
|
||||||
try!(write!(f, "{}={}",
|
write!(f, "{}={}",
|
||||||
projection.projection_ty.item_name,
|
projection.projection_ty.item_name,
|
||||||
projection.ty));
|
projection.ty)?;
|
||||||
}
|
}
|
||||||
return start_or_continue(f, "", ">");
|
return start_or_continue(f, "", ">");
|
||||||
}
|
}
|
||||||
|
@ -140,7 +140,7 @@ pub fn parameterized<GG>(f: &mut fmt::Formatter,
|
||||||
subst::ErasedRegions => { }
|
subst::ErasedRegions => { }
|
||||||
subst::NonerasedRegions(ref regions) => {
|
subst::NonerasedRegions(ref regions) => {
|
||||||
for &r in regions {
|
for &r in regions {
|
||||||
try!(start_or_continue(f, "<", ", "));
|
start_or_continue(f, "<", ", ")?;
|
||||||
let s = r.to_string();
|
let s = r.to_string();
|
||||||
if s.is_empty() {
|
if s.is_empty() {
|
||||||
// This happens when the value of the region
|
// 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,
|
// because the user omitted it in the first place,
|
||||||
// or because it refers to some block in the code,
|
// or because it refers to some block in the code,
|
||||||
// etc. I'm not sure how best to serialize this.
|
// etc. I'm not sure how best to serialize this.
|
||||||
try!(write!(f, "'_"));
|
write!(f, "'_")?;
|
||||||
} else {
|
} 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] {
|
for &ty in &tps[..tps.len() - num_defaults] {
|
||||||
try!(start_or_continue(f, "<", ", "));
|
start_or_continue(f, "<", ", ")?;
|
||||||
try!(write!(f, "{}", ty));
|
write!(f, "{}", ty)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
for projection in projections {
|
for projection in projections {
|
||||||
try!(start_or_continue(f, "<", ", "));
|
start_or_continue(f, "<", ", ")?;
|
||||||
try!(write!(f, "{}={}",
|
write!(f, "{}={}",
|
||||||
projection.projection_ty.item_name,
|
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.
|
// For values, also print their name and type parameters.
|
||||||
if ns == Ns::Value {
|
if ns == Ns::Value {
|
||||||
if substs.self_ty().is_some() {
|
if substs.self_ty().is_some() {
|
||||||
try!(write!(f, ">"));
|
write!(f, ">")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(name) = last_name {
|
if let Some(name) = last_name {
|
||||||
try!(write!(f, "::{}", name));
|
write!(f, "::{}", name)?;
|
||||||
}
|
}
|
||||||
let tps = substs.types.get_slice(subst::FnSpace);
|
let tps = substs.types.get_slice(subst::FnSpace);
|
||||||
if !tps.is_empty() {
|
if !tps.is_empty() {
|
||||||
try!(write!(f, "::<{}", tps[0]));
|
write!(f, "::<{}", tps[0])?;
|
||||||
for ty in &tps[1..] {
|
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;
|
}).0;
|
||||||
|
|
||||||
try!(start_or_continue(f, "", "> "));
|
start_or_continue(f, "", "> ")?;
|
||||||
write!(f, "{}", new_value)
|
write!(f, "{}", new_value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -317,7 +317,7 @@ impl<'tcx> fmt::Display for ty::TraitTy<'tcx> {
|
||||||
let bounds = &self.bounds;
|
let bounds = &self.bounds;
|
||||||
|
|
||||||
// Generate the main trait ref, including associated types.
|
// Generate the main trait ref, including associated types.
|
||||||
try!(ty::tls::with(|tcx| {
|
ty::tls::with(|tcx| {
|
||||||
let principal = tcx.lift(&self.principal.0)
|
let principal = tcx.lift(&self.principal.0)
|
||||||
.expect("could not lift TraitRef for printing");
|
.expect("could not lift TraitRef for printing");
|
||||||
let projections = tcx.lift(&bounds.projection_bounds[..])
|
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));
|
let tap = ty::Binder(TraitAndProjections(principal, projections));
|
||||||
in_binder(f, tcx, &ty::Binder(""), Some(tap))
|
in_binder(f, tcx, &ty::Binder(""), Some(tap))
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
// Builtin bounds.
|
// Builtin bounds.
|
||||||
for bound in &bounds.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
|
// 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.
|
// people aware that it's there.
|
||||||
let bound = bounds.region_bound.to_string();
|
let bound = bounds.region_bound.to_string();
|
||||||
if !bound.is_empty() {
|
if !bound.is_empty() {
|
||||||
try!(write!(f, " + {}", bound));
|
write!(f, " + {}", bound)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -648,19 +648,19 @@ impl<'tcx> fmt::Debug for ty::InstantiatedPredicates<'tcx> {
|
||||||
|
|
||||||
impl<'tcx> fmt::Debug for ty::ImplOrTraitItem<'tcx> {
|
impl<'tcx> fmt::Debug for ty::ImplOrTraitItem<'tcx> {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
try!(write!(f, "ImplOrTraitItem("));
|
write!(f, "ImplOrTraitItem(")?;
|
||||||
try!(match *self {
|
match *self {
|
||||||
ty::ImplOrTraitItem::MethodTraitItem(ref i) => write!(f, "{:?}", i),
|
ty::ImplOrTraitItem::MethodTraitItem(ref i) => write!(f, "{:?}", i),
|
||||||
ty::ImplOrTraitItem::ConstTraitItem(ref i) => write!(f, "{:?}", i),
|
ty::ImplOrTraitItem::ConstTraitItem(ref i) => write!(f, "{:?}", i),
|
||||||
ty::ImplOrTraitItem::TypeTraitItem(ref i) => write!(f, "{:?}", i),
|
ty::ImplOrTraitItem::TypeTraitItem(ref i) => write!(f, "{:?}", i),
|
||||||
});
|
}?;
|
||||||
write!(f, ")")
|
write!(f, ")")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'tcx> fmt::Display for ty::FnSig<'tcx> {
|
impl<'tcx> fmt::Display for ty::FnSig<'tcx> {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
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)
|
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);
|
let region_str = format!("{:?}", self.region_bound);
|
||||||
if !region_str.is_empty() {
|
if !region_str.is_empty() {
|
||||||
try!(maybe_continue(f));
|
maybe_continue(f)?;
|
||||||
try!(write!(f, "{}", region_str));
|
write!(f, "{}", region_str)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
for bound in &self.builtin_bounds {
|
for bound in &self.builtin_bounds {
|
||||||
try!(maybe_continue(f));
|
maybe_continue(f)?;
|
||||||
try!(write!(f, "{:?}", bound));
|
write!(f, "{:?}", bound)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
for projection_bound in &self.projection_bounds {
|
for projection_bound in &self.projection_bounds {
|
||||||
try!(maybe_continue(f));
|
maybe_continue(f)?;
|
||||||
try!(write!(f, "{:?}", projection_bound));
|
write!(f, "{:?}", projection_bound)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -701,9 +701,9 @@ impl fmt::Display for ty::BuiltinBounds {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
let mut bounds = self.iter();
|
let mut bounds = self.iter();
|
||||||
if let Some(bound) = bounds.next() {
|
if let Some(bound) = bounds.next() {
|
||||||
try!(write!(f, "{:?}", bound));
|
write!(f, "{:?}", bound)?;
|
||||||
for bound in bounds {
|
for bound in bounds {
|
||||||
try!(write!(f, " + {:?}", bound));
|
write!(f, " + {:?}", bound)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -832,23 +832,23 @@ impl<'tcx> fmt::Display for ty::TypeVariants<'tcx> {
|
||||||
}, tm.ty)
|
}, tm.ty)
|
||||||
}
|
}
|
||||||
TyRef(r, ref tm) => {
|
TyRef(r, ref tm) => {
|
||||||
try!(write!(f, "&"));
|
write!(f, "&")?;
|
||||||
let s = r.to_string();
|
let s = r.to_string();
|
||||||
try!(write!(f, "{}", s));
|
write!(f, "{}", s)?;
|
||||||
if !s.is_empty() {
|
if !s.is_empty() {
|
||||||
try!(write!(f, " "));
|
write!(f, " ")?;
|
||||||
}
|
}
|
||||||
write!(f, "{}", tm)
|
write!(f, "{}", tm)
|
||||||
}
|
}
|
||||||
TyTuple(ref tys) => {
|
TyTuple(ref tys) => {
|
||||||
try!(write!(f, "("));
|
write!(f, "(")?;
|
||||||
let mut tys = tys.iter();
|
let mut tys = tys.iter();
|
||||||
if let Some(&ty) = tys.next() {
|
if let Some(&ty) = tys.next() {
|
||||||
try!(write!(f, "{},", ty));
|
write!(f, "{},", ty)?;
|
||||||
if let Some(&ty) = tys.next() {
|
if let Some(&ty) = tys.next() {
|
||||||
try!(write!(f, " {}", ty));
|
write!(f, " {}", ty)?;
|
||||||
for &ty in tys {
|
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) => {
|
TyFnDef(def_id, substs, ref bare_fn) => {
|
||||||
if bare_fn.unsafety == hir::Unsafety::Unsafe {
|
if bare_fn.unsafety == hir::Unsafety::Unsafe {
|
||||||
try!(write!(f, "unsafe "));
|
write!(f, "unsafe ")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if bare_fn.abi != Abi::Rust {
|
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));
|
write!(f, "{} {{", bare_fn.sig.0)?;
|
||||||
try!(parameterized(f, substs, def_id, Ns::Value, &[],
|
parameterized(f, substs, def_id, Ns::Value, &[],
|
||||||
|tcx| tcx.lookup_item_type(def_id).generics));
|
|tcx| tcx.lookup_item_type(def_id).generics)?;
|
||||||
write!(f, "}}")
|
write!(f, "}}")
|
||||||
}
|
}
|
||||||
TyFnPtr(ref bare_fn) => {
|
TyFnPtr(ref bare_fn) => {
|
||||||
if bare_fn.unsafety == hir::Unsafety::Unsafe {
|
if bare_fn.unsafety == hir::Unsafety::Unsafe {
|
||||||
try!(write!(f, "unsafe "));
|
write!(f, "unsafe ")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if bare_fn.abi != Abi::Rust {
|
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)
|
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),
|
ty::TyProjection(ref data) => write!(f, "{}", data),
|
||||||
TyStr => write!(f, "str"),
|
TyStr => write!(f, "str"),
|
||||||
TyClosure(did, ref substs) => ty::tls::with(|tcx| {
|
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) {
|
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 = " ";
|
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) {
|
for (freevar, upvar_ty) in freevars.iter().zip(&substs.upvar_tys) {
|
||||||
let node_id = freevar.def.var_id();
|
let node_id = freevar.def.var_id();
|
||||||
try!(write!(f,
|
write!(f,
|
||||||
"{}{}:{}",
|
"{}{}:{}",
|
||||||
sep,
|
sep,
|
||||||
tcx.local_var_name_str(node_id),
|
tcx.local_var_name_str(node_id),
|
||||||
upvar_ty));
|
upvar_ty)?;
|
||||||
sep = ", ";
|
sep = ", ";
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}))
|
})?
|
||||||
} else {
|
} else {
|
||||||
// cross-crate closure types should only be
|
// cross-crate closure types should only be
|
||||||
// visible in trans bug reports, I imagine.
|
// visible in trans bug reports, I imagine.
|
||||||
try!(write!(f, "@{:?}", did));
|
write!(f, "@{:?}", did)?;
|
||||||
let mut sep = " ";
|
let mut sep = " ";
|
||||||
for (index, upvar_ty) in substs.upvar_tys.iter().enumerate() {
|
for (index, upvar_ty) in substs.upvar_tys.iter().enumerate() {
|
||||||
try!(write!(f, "{}{}:{}", sep, index, upvar_ty));
|
write!(f, "{}{}:{}", sep, index, upvar_ty)?;
|
||||||
sep = ", ";
|
sep = ", ";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -464,11 +464,11 @@ impl Target {
|
||||||
use serialize::json;
|
use serialize::json;
|
||||||
|
|
||||||
fn load_file(path: &Path) -> Result<Target, String> {
|
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();
|
let mut contents = Vec::new();
|
||||||
try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
|
f.read_to_end(&mut contents).map_err(|e| e.to_string())?;
|
||||||
let obj = try!(json::from_reader(&mut &contents[..])
|
let obj = json::from_reader(&mut &contents[..])
|
||||||
.map_err(|e| e.to_string()));
|
.map_err(|e| e.to_string())?;
|
||||||
Ok(Target::from_json(obj))
|
Ok(Target::from_json(obj))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -45,7 +45,7 @@ impl TempDir {
|
||||||
let storage;
|
let storage;
|
||||||
let mut tmpdir = tmpdir;
|
let mut tmpdir = tmpdir;
|
||||||
if !tmpdir.is_absolute() {
|
if !tmpdir.is_absolute() {
|
||||||
let cur_dir = try!(env::current_dir());
|
let cur_dir = env::current_dir()?;
|
||||||
storage = cur_dir.join(tmpdir);
|
storage = cur_dir.join(tmpdir);
|
||||||
tmpdir = &storage;
|
tmpdir = &storage;
|
||||||
// return TempDir::new_in(&cur_dir.join(tmpdir), prefix);
|
// return TempDir::new_in(&cur_dir.join(tmpdir), prefix);
|
||||||
|
|
|
@ -112,15 +112,15 @@ impl<'tcx> PreMovePath<'tcx> {
|
||||||
|
|
||||||
impl<'tcx> fmt::Debug for MovePath<'tcx> {
|
impl<'tcx> fmt::Debug for MovePath<'tcx> {
|
||||||
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
|
||||||
try!(write!(w, "MovePath {{"));
|
write!(w, "MovePath {{")?;
|
||||||
if let Some(parent) = self.parent {
|
if let Some(parent) = self.parent {
|
||||||
try!(write!(w, " parent: {:?},", parent));
|
write!(w, " parent: {:?},", parent)?;
|
||||||
}
|
}
|
||||||
if let Some(first_child) = self.first_child {
|
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 {
|
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)
|
write!(w, " content: {:?} }}", self.content)
|
||||||
}
|
}
|
||||||
|
|
|
@ -31,7 +31,7 @@ pub fn print_borrowck_graph_to(mbcx: &MirBorrowckCtxt,
|
||||||
path: &str) -> io::Result<()> {
|
path: &str) -> io::Result<()> {
|
||||||
let g = Graph { mbcx: mbcx, context: context };
|
let g = Graph { mbcx: mbcx, context: context };
|
||||||
let mut v = Vec::new();
|
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: {}",
|
println!("print_borrowck_graph_to path: {} context: {} node_id: {}",
|
||||||
path, context, mbcx.node_id);
|
path, context, mbcx.node_id);
|
||||||
File::create(path).and_then(|mut f| f.write_all(&v))
|
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) {
|
for c in interpreted.chunks(chunk_size) {
|
||||||
if seen_one {
|
if seen_one {
|
||||||
// if not the first row, finish off the previous row
|
// 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,
|
bg = BG_FLOWCONTENT,
|
||||||
align = ALIGN_RIGHT,
|
align = ALIGN_RIGHT,
|
||||||
objs = c));
|
objs = c)?;
|
||||||
seen_one = true;
|
seen_one = true;
|
||||||
}
|
}
|
||||||
if !seen_one {
|
if !seen_one {
|
||||||
try!(write!(w, "<tr><td></td><td {bg} {align}>[]",
|
write!(w, "<tr><td></td><td {bg} {align}>[]",
|
||||||
bg = BG_FLOWCONTENT,
|
bg = BG_FLOWCONTENT,
|
||||||
align = ALIGN_RIGHT));
|
align = ALIGN_RIGHT)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -141,7 +141,7 @@ impl<'c, 'b:'c, 'a:'b, 'tcx:'a> dot::Labeller<'c> for Graph<'c,'b,'a,'tcx> {
|
||||||
|w| {
|
|w| {
|
||||||
let flow = &self.mbcx.flow_state;
|
let flow = &self.mbcx.flow_state;
|
||||||
let entry = flow.interpret_set(flow.sets.on_entry_set_for(i));
|
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>\
|
write!(w, "= ENTRY:</td><td {bg}><FONT {face}>{entrybits:?}</FONT></td>\
|
||||||
<td></td></tr>",
|
<td></td></tr>",
|
||||||
bg = BG_FLOWCONTENT,
|
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 flow = &self.mbcx.flow_state;
|
||||||
let gen = flow.interpret_set( flow.sets.gen_set_for(i));
|
let gen = flow.interpret_set( flow.sets.gen_set_for(i));
|
||||||
let kill = flow.interpret_set(flow.sets.kill_set_for(i));
|
let kill = flow.interpret_set(flow.sets.kill_set_for(i));
|
||||||
try!(chunked_present_left(w, &gen[..], chunk_size));
|
chunked_present_left(w, &gen[..], chunk_size)?;
|
||||||
try!(write!(w, " = GEN:</td><td {bg}><FONT {face}>{genbits:?}</FONT></td>\
|
write!(w, " = GEN:</td><td {bg}><FONT {face}>{genbits:?}</FONT></td>\
|
||||||
<td></td></tr>",
|
<td></td></tr>",
|
||||||
bg = BG_FLOWCONTENT,
|
bg = BG_FLOWCONTENT,
|
||||||
face = FACE_MONOSPACE,
|
face = FACE_MONOSPACE,
|
||||||
genbits=bits_to_string( flow.sets.gen_set_for(i),
|
genbits=bits_to_string( flow.sets.gen_set_for(i),
|
||||||
flow.sets.bytes_per_block())));
|
flow.sets.bytes_per_block()))?;
|
||||||
try!(write!(w, "<tr><td></td><td {bg} {align}>KILL:</td>\
|
write!(w, "<tr><td></td><td {bg} {align}>KILL:</td>\
|
||||||
<td {bg}><FONT {face}>{killbits:?}</FONT></td>",
|
<td {bg}><FONT {face}>{killbits:?}</FONT></td>",
|
||||||
bg = BG_FLOWCONTENT,
|
bg = BG_FLOWCONTENT,
|
||||||
align = ALIGN_RIGHT,
|
align = ALIGN_RIGHT,
|
||||||
face = FACE_MONOSPACE,
|
face = FACE_MONOSPACE,
|
||||||
killbits=bits_to_string(flow.sets.kill_set_for(i),
|
killbits=bits_to_string(flow.sets.kill_set_for(i),
|
||||||
flow.sets.bytes_per_block())));
|
flow.sets.bytes_per_block()))?;
|
||||||
|
|
||||||
// (chunked_present_right)
|
// (chunked_present_right)
|
||||||
let mut seen_one = false;
|
let mut seen_one = false;
|
||||||
for k in kill.chunks(chunk_size) {
|
for k in kill.chunks(chunk_size) {
|
||||||
if !seen_one {
|
if !seen_one {
|
||||||
// continuation of row; this is fourth <td>
|
// 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,
|
bg = BG_FLOWCONTENT,
|
||||||
kill=k));
|
kill=k)?;
|
||||||
} else {
|
} else {
|
||||||
// new row, with indent of three <td>'s
|
// 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,
|
bg = BG_FLOWCONTENT,
|
||||||
kill=k));
|
kill=k)?;
|
||||||
}
|
}
|
||||||
seen_one = true;
|
seen_one = true;
|
||||||
}
|
}
|
||||||
if !seen_one {
|
if !seen_one {
|
||||||
try!(write!(w, "<td {bg}>= []</td></tr>",
|
write!(w, "<td {bg}>= []</td></tr>",
|
||||||
bg = BG_FLOWCONTENT));
|
bg = BG_FLOWCONTENT)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -220,7 +220,7 @@ impl ConstInt {
|
||||||
|
|
||||||
/// Compares the values if they are of the same type
|
/// Compares the values if they are of the same type
|
||||||
pub fn try_cmp(self, rhs: Self) -> Result<::std::cmp::Ordering, ConstMathErr> {
|
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)),
|
(I8(a), I8(b)) => Ok(a.cmp(&b)),
|
||||||
(I16(a), I16(b)) => Ok(a.cmp(&b)),
|
(I16(a), I16(b)) => Ok(a.cmp(&b)),
|
||||||
(I32(a), I32(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 {
|
impl ::std::ops::Div for ConstInt {
|
||||||
type Output = Result<Self, ConstMathErr>;
|
type Output = Result<Self, ConstMathErr>;
|
||||||
fn div(self, rhs: Self) -> Result<Self, ConstMathErr> {
|
fn div(self, rhs: Self) -> Result<Self, ConstMathErr> {
|
||||||
let (lhs, rhs) = try!(self.infer(rhs));
|
let (lhs, rhs) = self.infer(rhs)?;
|
||||||
try!(check_division(lhs, rhs, Op::Div, DivisionByZero));
|
check_division(lhs, rhs, Op::Div, DivisionByZero)?;
|
||||||
match (lhs, rhs) {
|
match (lhs, rhs) {
|
||||||
(I8(a), I8(b)) => Ok(I8(a/b)),
|
(I8(a), I8(b)) => Ok(I8(a/b)),
|
||||||
(I16(a), I16(b)) => Ok(I16(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 {
|
impl ::std::ops::Rem for ConstInt {
|
||||||
type Output = Result<Self, ConstMathErr>;
|
type Output = Result<Self, ConstMathErr>;
|
||||||
fn rem(self, rhs: Self) -> 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?
|
// 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) {
|
match (lhs, rhs) {
|
||||||
(I8(a), I8(b)) => Ok(I8(a%b)),
|
(I8(a), I8(b)) => Ok(I8(a%b)),
|
||||||
(I16(a), I16(b)) => Ok(I16(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 {
|
impl ::std::ops::Shl<ConstInt> for ConstInt {
|
||||||
type Output = Result<Self, ConstMathErr>;
|
type Output = Result<Self, ConstMathErr>;
|
||||||
fn shl(self, rhs: Self) -> 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 {
|
match self {
|
||||||
I8(a) => Ok(I8(overflowing!(a.overflowing_shl(b), Op::Shl))),
|
I8(a) => Ok(I8(overflowing!(a.overflowing_shl(b), Op::Shl))),
|
||||||
I16(a) => Ok(I16(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 {
|
impl ::std::ops::Shr<ConstInt> for ConstInt {
|
||||||
type Output = Result<Self, ConstMathErr>;
|
type Output = Result<Self, ConstMathErr>;
|
||||||
fn shr(self, rhs: Self) -> 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 {
|
match self {
|
||||||
I8(a) => Ok(I8(overflowing!(a.overflowing_shr(b), Op::Shr))),
|
I8(a) => Ok(I8(overflowing!(a.overflowing_shr(b), Op::Shr))),
|
||||||
I16(a) => Ok(I16(overflowing!(a.overflowing_shr(b), Op::Shr))),
|
I16(a) => Ok(I16(overflowing!(a.overflowing_shr(b), Op::Shr))),
|
||||||
|
|
|
@ -99,11 +99,11 @@ pub fn compile_input(sess: &Session,
|
||||||
|
|
||||||
let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
|
let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
|
||||||
let id = link::find_crate_name(Some(sess), &krate.attrs, input);
|
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,
|
&cstore,
|
||||||
krate,
|
krate,
|
||||||
&id[..],
|
&id[..],
|
||||||
addl_plugins));
|
addl_plugins)?;
|
||||||
|
|
||||||
(outputs, expanded_crate, id)
|
(outputs, expanded_crate, id)
|
||||||
};
|
};
|
||||||
|
@ -168,7 +168,7 @@ pub fn compile_input(sess: &Session,
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
try!(try!(phase_3_run_analysis_passes(sess,
|
phase_3_run_analysis_passes(sess,
|
||||||
&cstore,
|
&cstore,
|
||||||
hir_map,
|
hir_map,
|
||||||
&arenas,
|
&arenas,
|
||||||
|
@ -196,7 +196,7 @@ pub fn compile_input(sess: &Session,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try!(result);
|
result?;
|
||||||
|
|
||||||
if log_enabled!(::log::INFO) {
|
if log_enabled!(::log::INFO) {
|
||||||
println!("Pre-trans");
|
println!("Pre-trans");
|
||||||
|
@ -215,7 +215,7 @@ pub fn compile_input(sess: &Session,
|
||||||
token::get_ident_interner().clear();
|
token::get_ident_interner().clear();
|
||||||
|
|
||||||
Ok((outputs, trans))
|
Ok((outputs, trans))
|
||||||
})))
|
})??
|
||||||
};
|
};
|
||||||
|
|
||||||
let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
|
let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
|
||||||
|
@ -224,7 +224,7 @@ pub fn compile_input(sess: &Session,
|
||||||
sess,
|
sess,
|
||||||
CompileState::state_after_llvm(input, sess, outdir, &trans),
|
CompileState::state_after_llvm(input, sess, outdir, &trans),
|
||||||
phase5_result);
|
phase5_result);
|
||||||
try!(phase5_result);
|
phase5_result?;
|
||||||
|
|
||||||
phase_6_link_output(sess, &trans, &outputs);
|
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();
|
syntax::ext::mtwt::reset_tables();
|
||||||
token::reset_ident_interner();
|
token::reset_ident_interner();
|
||||||
|
|
||||||
let krate = try!(time(sess.time_passes(), "parsing", || {
|
let krate = time(sess.time_passes(), "parsing", || {
|
||||||
match *input {
|
match *input {
|
||||||
Input::File(ref file) => {
|
Input::File(ref file) => {
|
||||||
parse::parse_crate_from_file(file, cfg.clone(), &sess.parse_sess)
|
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)
|
&sess.parse_sess)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
if sess.opts.debugging_opts.ast_json_noexpand {
|
if sess.opts.debugging_opts.ast_json_noexpand {
|
||||||
println!("{}", json::as_json(&krate));
|
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.
|
// baz! should not use this definition unless foo is enabled.
|
||||||
|
|
||||||
let mut feature_gated_cfgs = vec![];
|
let mut feature_gated_cfgs = vec![];
|
||||||
krate = try!(time(time_passes, "configuration 1", || {
|
krate = time(time_passes, "configuration 1", || {
|
||||||
sess.track_errors(|| {
|
sess.track_errors(|| {
|
||||||
syntax::config::strip_unconfigured_items(sess.diagnostic(),
|
syntax::config::strip_unconfigured_items(sess.diagnostic(),
|
||||||
krate,
|
krate,
|
||||||
&mut feature_gated_cfgs)
|
&mut feature_gated_cfgs)
|
||||||
})
|
})
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
*sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
|
*sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
|
||||||
*sess.crate_metadata.borrow_mut() = collect_crate_metadata(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);
|
middle::recursion_limit::update_recursion_limit(sess, &krate);
|
||||||
});
|
});
|
||||||
|
|
||||||
try!(time(time_passes, "gated macro checking", || {
|
time(time_passes, "gated macro checking", || {
|
||||||
sess.track_errors(|| {
|
sess.track_errors(|| {
|
||||||
let features =
|
let features =
|
||||||
syntax::feature_gate::check_crate_macros(sess.codemap(),
|
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.
|
// these need to be set "early" so that expansion sees `quote` if enabled.
|
||||||
*sess.features.borrow_mut() = features;
|
*sess.features.borrow_mut() = features;
|
||||||
})
|
})
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
|
|
||||||
krate = time(time_passes, "crate injection", || {
|
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,
|
let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
|
||||||
llvm_passes, attributes, mir_passes, .. } = registry;
|
llvm_passes, attributes, mir_passes, .. } = registry;
|
||||||
|
|
||||||
try!(sess.track_errors(|| {
|
sess.track_errors(|| {
|
||||||
let mut ls = sess.lint_store.borrow_mut();
|
let mut ls = sess.lint_store.borrow_mut();
|
||||||
for pass in early_lint_passes {
|
for pass in early_lint_passes {
|
||||||
ls.register_early_pass(Some(sess), true, pass);
|
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.plugin_llvm_passes.borrow_mut() = llvm_passes;
|
||||||
sess.mir_passes.borrow_mut().extend(mir_passes);
|
sess.mir_passes.borrow_mut().extend(mir_passes);
|
||||||
*sess.plugin_attributes.borrow_mut() = attributes.clone();
|
*sess.plugin_attributes.borrow_mut() = attributes.clone();
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
// Lint plugins are registered; now we can process command line flags.
|
// Lint plugins are registered; now we can process command line flags.
|
||||||
if sess.opts.describe_lints {
|
if sess.opts.describe_lints {
|
||||||
super::describe_lints(&sess.lint_store.borrow(), true);
|
super::describe_lints(&sess.lint_store.borrow(), true);
|
||||||
return Err(0);
|
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", || {
|
krate = time(time_passes, "expansion", || {
|
||||||
// Windows dlls do not have rpaths, so they don't know how to find their
|
// 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
|
// of macro expansion. This runs before #[cfg] to try to catch as
|
||||||
// much as possible (e.g. help the programmer avoid platform
|
// much as possible (e.g. help the programmer avoid platform
|
||||||
// specific differences)
|
// specific differences)
|
||||||
try!(time(time_passes, "complete gated feature checking 1", || {
|
time(time_passes, "complete gated feature checking 1", || {
|
||||||
sess.track_errors(|| {
|
sess.track_errors(|| {
|
||||||
let features = syntax::feature_gate::check_crate(sess.codemap(),
|
let features = syntax::feature_gate::check_crate(sess.codemap(),
|
||||||
&sess.parse_sess.span_diagnostic,
|
&sess.parse_sess.span_diagnostic,
|
||||||
|
@ -628,12 +628,12 @@ pub fn phase_2_configure_and_expand(sess: &Session,
|
||||||
sess.opts.unstable_features);
|
sess.opts.unstable_features);
|
||||||
*sess.features.borrow_mut() = features;
|
*sess.features.borrow_mut() = features;
|
||||||
})
|
})
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
// JBC: make CFG processing part of expansion to avoid this problem:
|
// JBC: make CFG processing part of expansion to avoid this problem:
|
||||||
|
|
||||||
// strip again, in case expansion added anything with a #[cfg].
|
// 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", || {
|
let krate = time(time_passes, "configuration 2", || {
|
||||||
syntax::config::strip_unconfigured_items(sess.diagnostic(),
|
syntax::config::strip_unconfigured_items(sess.diagnostic(),
|
||||||
krate,
|
krate,
|
||||||
|
@ -650,7 +650,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
|
||||||
});
|
});
|
||||||
|
|
||||||
krate
|
krate
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
krate = time(time_passes, "maybe building test harness", || {
|
krate = time(time_passes, "maybe building test harness", || {
|
||||||
syntax::test::modify_for_testing(&sess.parse_sess, &sess.opts.cfg, krate, sess.diagnostic())
|
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
|
// One final feature gating of the true AST that gets compiled
|
||||||
// later, to make sure we've got everything (e.g. configuration
|
// later, to make sure we've got everything (e.g. configuration
|
||||||
// can insert new attributes via `cfg_attr`)
|
// 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(|| {
|
sess.track_errors(|| {
|
||||||
let features = syntax::feature_gate::check_crate(sess.codemap(),
|
let features = syntax::feature_gate::check_crate(sess.codemap(),
|
||||||
&sess.parse_sess.span_diagnostic,
|
&sess.parse_sess.span_diagnostic,
|
||||||
|
@ -680,11 +680,11 @@ pub fn phase_2_configure_and_expand(sess: &Session,
|
||||||
sess.opts.unstable_features);
|
sess.opts.unstable_features);
|
||||||
*sess.features.borrow_mut() = features;
|
*sess.features.borrow_mut() = features;
|
||||||
})
|
})
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
try!(time(time_passes,
|
time(time_passes,
|
||||||
"const fn bodies and arguments",
|
"const fn bodies and arguments",
|
||||||
|| const_fn::check_crate(sess, &krate)));
|
|| const_fn::check_crate(sess, &krate))?;
|
||||||
|
|
||||||
if sess.opts.debugging_opts.input_stats {
|
if sess.opts.debugging_opts.input_stats {
|
||||||
println!("Post-expansion node count: {}", count_nodes(&krate));
|
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",
|
"external crate/lib resolution",
|
||||||
|| LocalCrateReader::new(sess, cstore, &hir_map).read_crates());
|
|| 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(|| {
|
sess.track_errors(|| {
|
||||||
middle::lang_items::collect_language_items(&sess, &hir_map)
|
middle::lang_items::collect_language_items(&sess, &hir_map)
|
||||||
})
|
})
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
let resolve::CrateMap {
|
let resolve::CrateMap {
|
||||||
def_map,
|
def_map,
|
||||||
|
@ -780,11 +780,11 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
|
||||||
glob_map: glob_map,
|
glob_map: glob_map,
|
||||||
};
|
};
|
||||||
|
|
||||||
let named_region_map = try!(time(time_passes,
|
let named_region_map = time(time_passes,
|
||||||
"lifetime resolution",
|
"lifetime resolution",
|
||||||
|| middle::resolve_lifetime::krate(sess,
|
|| middle::resolve_lifetime::krate(sess,
|
||||||
&hir_map,
|
&hir_map,
|
||||||
&def_map.borrow())));
|
&def_map.borrow()))?;
|
||||||
|
|
||||||
time(time_passes,
|
time(time_passes,
|
||||||
"looking for entry point",
|
"looking for entry point",
|
||||||
|
@ -802,9 +802,9 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
|
||||||
"loop checking",
|
"loop checking",
|
||||||
|| loops::check_crate(sess, &hir_map));
|
|| loops::check_crate(sess, &hir_map));
|
||||||
|
|
||||||
try!(time(time_passes,
|
time(time_passes,
|
||||||
"static item recursion checking",
|
"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);
|
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())
|
.filter(|fmap| !fmap.is_imported())
|
||||||
.map(|fmap| escape_dep_filename(&fmap.name))
|
.map(|fmap| escape_dep_filename(&fmap.name))
|
||||||
.collect();
|
.collect();
|
||||||
let mut file = try!(fs::File::create(&deps_filename));
|
let mut file = fs::File::create(&deps_filename)?;
|
||||||
for path in &out_filenames {
|
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
|
// Emit a fake target for each input file to the compilation. This
|
||||||
// prevents `make` from spitting out an error if a file is later
|
// prevents `make` from spitting out an error if a file is later
|
||||||
// deleted. For more info see #28735
|
// deleted. For more info see #28735
|
||||||
for path in files {
|
for path in files {
|
||||||
try!(writeln!(file, "{}:", path));
|
writeln!(file, "{}:", path)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})();
|
})();
|
||||||
|
|
|
@ -325,24 +325,24 @@ impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
|
||||||
pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
|
pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
|
||||||
|
|
||||||
pprust::NodeItem(item) => {
|
pprust::NodeItem(item) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
s.synth_comment(item.id.to_string())
|
s.synth_comment(item.id.to_string())
|
||||||
}
|
}
|
||||||
pprust::NodeSubItem(id) => {
|
pprust::NodeSubItem(id) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
s.synth_comment(id.to_string())
|
s.synth_comment(id.to_string())
|
||||||
}
|
}
|
||||||
pprust::NodeBlock(blk) => {
|
pprust::NodeBlock(blk) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
s.synth_comment(format!("block {}", blk.id))
|
s.synth_comment(format!("block {}", blk.id))
|
||||||
}
|
}
|
||||||
pprust::NodeExpr(expr) => {
|
pprust::NodeExpr(expr) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
try!(s.synth_comment(expr.id.to_string()));
|
s.synth_comment(expr.id.to_string())?;
|
||||||
s.pclose()
|
s.pclose()
|
||||||
}
|
}
|
||||||
pprust::NodePat(pat) => {
|
pprust::NodePat(pat) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
s.synth_comment(format!("pat {}", pat.id))
|
s.synth_comment(format!("pat {}", pat.id))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -374,24 +374,24 @@ impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> {
|
||||||
match node {
|
match node {
|
||||||
pprust_hir::NodeName(_) => Ok(()),
|
pprust_hir::NodeName(_) => Ok(()),
|
||||||
pprust_hir::NodeItem(item) => {
|
pprust_hir::NodeItem(item) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
s.synth_comment(item.id.to_string())
|
s.synth_comment(item.id.to_string())
|
||||||
}
|
}
|
||||||
pprust_hir::NodeSubItem(id) => {
|
pprust_hir::NodeSubItem(id) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
s.synth_comment(id.to_string())
|
s.synth_comment(id.to_string())
|
||||||
}
|
}
|
||||||
pprust_hir::NodeBlock(blk) => {
|
pprust_hir::NodeBlock(blk) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
s.synth_comment(format!("block {}", blk.id))
|
s.synth_comment(format!("block {}", blk.id))
|
||||||
}
|
}
|
||||||
pprust_hir::NodeExpr(expr) => {
|
pprust_hir::NodeExpr(expr) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
try!(s.synth_comment(expr.id.to_string()));
|
s.synth_comment(expr.id.to_string())?;
|
||||||
s.pclose()
|
s.pclose()
|
||||||
}
|
}
|
||||||
pprust_hir::NodePat(pat) => {
|
pprust_hir::NodePat(pat) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
s.synth_comment(format!("pat {}", pat.id))
|
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<()> {
|
fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
|
||||||
match node {
|
match node {
|
||||||
pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
|
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
|
// FIXME #16420: this doesn't display the connections
|
||||||
// between syntax contexts
|
// between syntax contexts
|
||||||
s.synth_comment(format!("{}#{}", nm, ctxt.0))
|
s.synth_comment(format!("{}#{}", nm, ctxt.0))
|
||||||
}
|
}
|
||||||
pprust::NodeName(&ast::Name(nm)) => {
|
pprust::NodeName(&ast::Name(nm)) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
s.synth_comment(nm.to_string())
|
s.synth_comment(nm.to_string())
|
||||||
}
|
}
|
||||||
_ => Ok(()),
|
_ => 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<()> {
|
fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
|
||||||
match node {
|
match node {
|
||||||
pprust_hir::NodeExpr(expr) => {
|
pprust_hir::NodeExpr(expr) => {
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
try!(pp::word(&mut s.s, "as"));
|
pp::word(&mut s.s, "as")?;
|
||||||
try!(pp::space(&mut s.s));
|
pp::space(&mut s.s)?;
|
||||||
try!(pp::word(&mut s.s, &self.tcx.expr_ty(expr).to_string()));
|
pp::word(&mut s.s, &self.tcx.expr_ty(expr).to_string())?;
|
||||||
s.pclose()
|
s.pclose()
|
||||||
}
|
}
|
||||||
_ => Ok(()),
|
_ => Ok(()),
|
||||||
|
@ -806,10 +806,10 @@ pub fn pretty_print_input(sess: Session,
|
||||||
Some(ast_map.krate()));
|
Some(ast_map.krate()));
|
||||||
for node_id in uii.all_matching_node_ids(ast_map) {
|
for node_id in uii.all_matching_node_ids(ast_map) {
|
||||||
let node = ast_map.get(node_id);
|
let node = ast_map.get(node_id);
|
||||||
try!(pp_state.print_node(&node));
|
pp_state.print_node(&node)?;
|
||||||
try!(pp::space(&mut pp_state.s));
|
pp::space(&mut pp_state.s)?;
|
||||||
try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
|
pp_state.synth_comment(ast_map.path_to_string(node_id))?;
|
||||||
try!(pp::hardbreak(&mut pp_state.s));
|
pp::hardbreak(&mut pp_state.s)?;
|
||||||
}
|
}
|
||||||
pp::eof(&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(|| {
|
let mir = mir_map.map.get(&nodeid).unwrap_or_else(|| {
|
||||||
sess.fatal(&format!("no MIR map entry for node {}", nodeid))
|
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),
|
PpmMir => write_mir_pretty(tcx, iter::once((&nodeid, mir)), &mut out),
|
||||||
_ => write_mir_graphviz(tcx, iter::once((&nodeid, mir)), &mut out)
|
_ => write_mir_graphviz(tcx, iter::once((&nodeid, mir)), &mut out)
|
||||||
});
|
}?;
|
||||||
} else {
|
} else {
|
||||||
try!(match pp_type {
|
match pp_type {
|
||||||
PpmMir => write_mir_pretty(tcx, mir_map.map.iter(), &mut out),
|
PpmMir => write_mir_pretty(tcx, mir_map.map.iter(), &mut out),
|
||||||
_ => write_mir_graphviz(tcx, mir_map.map.iter(), &mut out)
|
_ => write_mir_graphviz(tcx, mir_map.map.iter(), &mut out)
|
||||||
});
|
}?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -119,7 +119,7 @@ impl Encodable for Ident {
|
||||||
|
|
||||||
impl Decodable for Ident {
|
impl Decodable for Ident {
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
|
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
|
@ -1221,11 +1221,11 @@ fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
|
||||||
|
|
||||||
fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
|
fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
|
||||||
out: &mut io::Write) -> io::Result<()> {
|
out: &mut io::Write) -> io::Result<()> {
|
||||||
try!(write!(out, "=Crate Attributes ({})=\n", *hash));
|
write!(out, "=Crate Attributes ({})=\n", *hash)?;
|
||||||
|
|
||||||
let r = get_attributes(md);
|
let r = get_attributes(md);
|
||||||
for attr in &r {
|
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")
|
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<()> {
|
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) {
|
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(())
|
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<()> {
|
pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
|
||||||
let hash = get_crate_hash(bytes);
|
let hash = get_crate_hash(bytes);
|
||||||
let md = rbml::Doc::new(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)
|
list_crate_deps(bytes, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -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<()>
|
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>)> {
|
where W: Write, I: Iterator<Item=(&'a NodeId, &'a Mir<'a>)> {
|
||||||
for (&nodeid, mir) in iter {
|
for (&nodeid, mir) in iter {
|
||||||
try!(writeln!(w, "digraph Mir_{} {{", nodeid));
|
writeln!(w, "digraph Mir_{} {{", nodeid)?;
|
||||||
|
|
||||||
// Global graph properties
|
// Global graph properties
|
||||||
try!(writeln!(w, r#" graph [fontname="monospace"];"#));
|
writeln!(w, r#" graph [fontname="monospace"];"#)?;
|
||||||
try!(writeln!(w, r#" node [fontname="monospace"];"#));
|
writeln!(w, r#" node [fontname="monospace"];"#)?;
|
||||||
try!(writeln!(w, r#" edge [fontname="monospace"];"#));
|
writeln!(w, r#" edge [fontname="monospace"];"#)?;
|
||||||
|
|
||||||
// Graph label
|
// Graph label
|
||||||
try!(write_graph_label(tcx, nodeid, mir, w));
|
write_graph_label(tcx, nodeid, mir, w)?;
|
||||||
|
|
||||||
// Nodes
|
// Nodes
|
||||||
for block in mir.all_basic_blocks() {
|
for block in mir.all_basic_blocks() {
|
||||||
try!(write_node(block, mir, w));
|
write_node(block, mir, w)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Edges
|
// Edges
|
||||||
for source in mir.all_basic_blocks() {
|
for source in mir.all_basic_blocks() {
|
||||||
try!(write_edges(source, mir, w));
|
write_edges(source, mir, w)?;
|
||||||
}
|
}
|
||||||
try!(writeln!(w, "}}"))
|
writeln!(w, "}}")?
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -61,32 +61,32 @@ pub fn write_node_label<W: Write, INIT, FINI>(block: BasicBlock,
|
||||||
{
|
{
|
||||||
let data = mir.basic_block_data(block);
|
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.
|
// 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""#,
|
attrs=r#"bgcolor="gray" align="center""#,
|
||||||
colspan=num_cols,
|
colspan=num_cols,
|
||||||
blk=block.index()));
|
blk=block.index())?;
|
||||||
|
|
||||||
try!(init(w));
|
init(w)?;
|
||||||
|
|
||||||
// List of statements in the middle.
|
// List of statements in the middle.
|
||||||
if !data.statements.is_empty() {
|
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 {
|
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
|
// Terminator head at the bottom, not including the list of successor blocks. Those will be
|
||||||
// displayed as labels on the edges between blocks.
|
// displayed as labels on the edges between blocks.
|
||||||
let mut terminator_head = String::new();
|
let mut terminator_head = String::new();
|
||||||
data.terminator().fmt_head(&mut terminator_head).unwrap();
|
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
|
// Close the table
|
||||||
writeln!(w, "</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.
|
/// Write a graphviz DOT node for the given basic block.
|
||||||
fn write_node<W: Write>(block: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
|
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.
|
// 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)));
|
write!(w, r#" {} [shape="none", label=<"#, node(block))?;
|
||||||
try!(write_node_label(block, mir, w, 1, |_| Ok(()), |_| Ok(())));
|
write_node_label(block, mir, w, 1, |_| Ok(()), |_| Ok(()))?;
|
||||||
// Close the node label and the node itself.
|
// Close the node label and the node itself.
|
||||||
writeln!(w, ">];")
|
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();
|
let labels = terminator.fmt_successor_labels();
|
||||||
|
|
||||||
for (&target, label) in terminator.successors().iter().zip(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(())
|
Ok(())
|
||||||
|
@ -118,40 +118,40 @@ fn write_edges<W: Write>(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result
|
||||||
/// all the variables and temporaries.
|
/// all the variables and temporaries.
|
||||||
fn write_graph_label<W: Write>(tcx: &ty::TyCtxt, nid: NodeId, mir: &Mir, w: &mut W)
|
fn write_graph_label<W: Write>(tcx: &ty::TyCtxt, nid: NodeId, mir: &Mir, w: &mut W)
|
||||||
-> io::Result<()> {
|
-> 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.
|
// fn argument types.
|
||||||
for (i, arg) in mir.arg_decls.iter().enumerate() {
|
for (i, arg) in mir.arg_decls.iter().enumerate() {
|
||||||
if i > 0 {
|
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, ") -> "));
|
write!(w, ") -> ")?;
|
||||||
|
|
||||||
// fn return type.
|
// fn return type.
|
||||||
match mir.return_ty {
|
match mir.return_ty {
|
||||||
ty::FnOutput::FnConverging(ty) => try!(write!(w, "{}", escape(ty))),
|
ty::FnOutput::FnConverging(ty) => write!(w, "{}", escape(ty))?,
|
||||||
ty::FnOutput::FnDiverging => try!(write!(w, "!")),
|
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).
|
// User variable types (including the user's name in a comment).
|
||||||
for (i, var) in mir.var_decls.iter().enumerate() {
|
for (i, var) in mir.var_decls.iter().enumerate() {
|
||||||
try!(write!(w, "let "));
|
write!(w, "let ")?;
|
||||||
if var.mutability == Mutability::Mut {
|
if var.mutability == Mutability::Mut {
|
||||||
try!(write!(w, "mut "));
|
write!(w, "mut ")?;
|
||||||
}
|
}
|
||||||
try!(write!(w, r#"{:?}: {}; // {}<br align="left"/>"#,
|
write!(w, r#"{:?}: {}; // {}<br align="left"/>"#,
|
||||||
Lvalue::Var(i as u32), escape(&var.ty), var.name));
|
Lvalue::Var(i as u32), escape(&var.ty), var.name)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compiler-introduced temporary types.
|
// Compiler-introduced temporary types.
|
||||||
for (i, temp) in mir.temp_decls.iter().enumerate() {
|
for (i, temp) in mir.temp_decls.iter().enumerate() {
|
||||||
try!(write!(w, r#"let mut {:?}: {};<br align="left"/>"#,
|
write!(w, r#"let mut {:?}: {};<br align="left"/>"#,
|
||||||
Lvalue::Temp(i as u32), escape(&temp.ty)));
|
Lvalue::Temp(i as u32), escape(&temp.ty))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
writeln!(w, ">;")
|
writeln!(w, ">;")
|
||||||
|
|
|
@ -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<()>
|
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>)> {
|
where W: Write, I: Iterator<Item=(&'a NodeId, &'a Mir<'a>)> {
|
||||||
for (&nodeid, mir) in iter {
|
for (&nodeid, mir) in iter {
|
||||||
try!(write_mir_intro(tcx, nodeid, mir, w));
|
write_mir_intro(tcx, nodeid, mir, w)?;
|
||||||
// Nodes
|
// Nodes
|
||||||
for block in mir.all_basic_blocks() {
|
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(())
|
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);
|
let data = mir.basic_block_data(block);
|
||||||
|
|
||||||
// Basic block label at the top.
|
// Basic block label at the top.
|
||||||
try!(writeln!(w, "\n{}{:?}: {{", INDENT, block));
|
writeln!(w, "\n{}{:?}: {{", INDENT, block)?;
|
||||||
|
|
||||||
// List of statements in the middle.
|
// List of statements in the middle.
|
||||||
for statement in &data.statements {
|
for statement in &data.statements {
|
||||||
try!(writeln!(w, "{0}{0}{1:?};", INDENT, statement));
|
writeln!(w, "{0}{0}{1:?};", INDENT, statement)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Terminator at the bottom.
|
// Terminator at the bottom.
|
||||||
try!(writeln!(w, "{0}{0}{1:?};", INDENT, data.terminator()));
|
writeln!(w, "{0}{0}{1:?};", INDENT, data.terminator())?;
|
||||||
|
|
||||||
writeln!(w, "{}}}", INDENT)
|
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)
|
fn write_mir_intro<W: Write>(tcx: &ty::TyCtxt, nid: NodeId, mir: &Mir, w: &mut W)
|
||||||
-> io::Result<()> {
|
-> io::Result<()> {
|
||||||
|
|
||||||
try!(write!(w, "fn {}(", tcx.map.path_to_string(nid)));
|
write!(w, "fn {}(", tcx.map.path_to_string(nid))?;
|
||||||
|
|
||||||
// fn argument types.
|
// fn argument types.
|
||||||
for (i, arg) in mir.arg_decls.iter().enumerate() {
|
for (i, arg) in mir.arg_decls.iter().enumerate() {
|
||||||
if i > 0 {
|
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.
|
// fn return type.
|
||||||
match mir.return_ty {
|
match mir.return_ty {
|
||||||
ty::FnOutput::FnConverging(ty) => try!(write!(w, "{}", ty)),
|
ty::FnOutput::FnConverging(ty) => write!(w, "{}", ty)?,
|
||||||
ty::FnOutput::FnDiverging => try!(write!(w, "!")),
|
ty::FnOutput::FnDiverging => write!(w, "!")?,
|
||||||
}
|
}
|
||||||
|
|
||||||
try!(writeln!(w, " {{"));
|
writeln!(w, " {{")?;
|
||||||
|
|
||||||
// User variable types (including the user's name in a comment).
|
// User variable types (including the user's name in a comment).
|
||||||
for (i, var) in mir.var_decls.iter().enumerate() {
|
for (i, var) in mir.var_decls.iter().enumerate() {
|
||||||
try!(write!(w, "{}let ", INDENT));
|
write!(w, "{}let ", INDENT)?;
|
||||||
if var.mutability == Mutability::Mut {
|
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.
|
// Compiler-introduced temporary types.
|
||||||
for (i, temp) in mir.temp_decls.iter().enumerate() {
|
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(())
|
Ok(())
|
||||||
|
|
|
@ -254,8 +254,8 @@ impl<'a> ArchiveBuilder<'a> {
|
||||||
// want to modify this archive, so we use `io::copy` to not preserve
|
// want to modify this archive, so we use `io::copy` to not preserve
|
||||||
// permission bits.
|
// permission bits.
|
||||||
if let Some(ref s) = self.config.src {
|
if let Some(ref s) = self.config.src {
|
||||||
try!(io::copy(&mut try!(File::open(s)),
|
io::copy(&mut File::open(s)?,
|
||||||
&mut try!(File::create(&self.config.dst))));
|
&mut File::create(&self.config.dst)?)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if removals.len() > 0 {
|
if removals.len() > 0 {
|
||||||
|
@ -267,12 +267,12 @@ impl<'a> ArchiveBuilder<'a> {
|
||||||
match addition {
|
match addition {
|
||||||
Addition::File { path, name_in_archive } => {
|
Addition::File { path, name_in_archive } => {
|
||||||
let dst = self.work_dir.path().join(&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));
|
members.push(PathBuf::from(name_in_archive));
|
||||||
}
|
}
|
||||||
Addition::Archive { archive, archive_name, mut skip } => {
|
Addition::Archive { archive, archive_name, mut skip } => {
|
||||||
try!(self.add_archive_members(&mut members, archive,
|
self.add_archive_members(&mut members, archive,
|
||||||
&archive_name, &mut *skip));
|
&archive_name, &mut *skip)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -334,7 +334,7 @@ impl<'a> ArchiveBuilder<'a> {
|
||||||
// all SYMDEF files as these are just magical placeholders which get
|
// all SYMDEF files as these are just magical placeholders which get
|
||||||
// re-created when we make a new archive anyway.
|
// re-created when we make a new archive anyway.
|
||||||
for file in archive.iter() {
|
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) {
|
if !is_relevant_child(&file) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
@ -388,7 +388,7 @@ impl<'a> ArchiveBuilder<'a> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let dst = self.work_dir.path().join(&new_filename);
|
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));
|
members.push(PathBuf::from(new_filename));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -455,7 +455,7 @@ impl<'a> ArchiveBuilder<'a> {
|
||||||
unsafe {
|
unsafe {
|
||||||
if let Some(archive) = self.src_archive() {
|
if let Some(archive) = self.src_archive() {
|
||||||
for child in archive.iter() {
|
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() {
|
let child_name = match child.name() {
|
||||||
Some(s) => s,
|
Some(s) => s,
|
||||||
None => continue,
|
None => continue,
|
||||||
|
@ -464,7 +464,7 @@ impl<'a> ArchiveBuilder<'a> {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
let name = try!(CString::new(child_name));
|
let name = CString::new(child_name)?;
|
||||||
members.push(llvm::LLVMRustArchiveMemberNew(ptr::null(),
|
members.push(llvm::LLVMRustArchiveMemberNew(ptr::null(),
|
||||||
name.as_ptr(),
|
name.as_ptr(),
|
||||||
child.raw()));
|
child.raw()));
|
||||||
|
@ -474,8 +474,8 @@ impl<'a> ArchiveBuilder<'a> {
|
||||||
for addition in mem::replace(&mut self.additions, Vec::new()) {
|
for addition in mem::replace(&mut self.additions, Vec::new()) {
|
||||||
match addition {
|
match addition {
|
||||||
Addition::File { path, name_in_archive } => {
|
Addition::File { path, name_in_archive } => {
|
||||||
let path = try!(CString::new(path.to_str().unwrap()));
|
let path = CString::new(path.to_str().unwrap())?;
|
||||||
let name = try!(CString::new(name_in_archive));
|
let name = CString::new(name_in_archive)?;
|
||||||
members.push(llvm::LLVMRustArchiveMemberNew(path.as_ptr(),
|
members.push(llvm::LLVMRustArchiveMemberNew(path.as_ptr(),
|
||||||
name.as_ptr(),
|
name.as_ptr(),
|
||||||
ptr::null_mut()));
|
ptr::null_mut()));
|
||||||
|
@ -484,7 +484,7 @@ impl<'a> ArchiveBuilder<'a> {
|
||||||
}
|
}
|
||||||
Addition::Archive { archive, archive_name: _, mut skip } => {
|
Addition::Archive { archive, archive_name: _, mut skip } => {
|
||||||
for child in archive.iter() {
|
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) {
|
if !is_relevant_child(&child) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
@ -502,7 +502,7 @@ impl<'a> ArchiveBuilder<'a> {
|
||||||
let child_name = Path::new(child_name)
|
let child_name = Path::new(child_name)
|
||||||
.file_name().unwrap()
|
.file_name().unwrap()
|
||||||
.to_str().unwrap();
|
.to_str().unwrap();
|
||||||
let name = try!(CString::new(child_name));
|
let name = CString::new(child_name)?;
|
||||||
let m = llvm::LLVMRustArchiveMemberNew(ptr::null(),
|
let m = llvm::LLVMRustArchiveMemberNew(ptr::null(),
|
||||||
name.as_ptr(),
|
name.as_ptr(),
|
||||||
child.raw());
|
child.raw());
|
||||||
|
@ -515,7 +515,7 @@ impl<'a> ArchiveBuilder<'a> {
|
||||||
}
|
}
|
||||||
|
|
||||||
let dst = self.config.dst.to_str().unwrap().as_bytes();
|
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(),
|
let r = llvm::LLVMRustWriteArchive(dst.as_ptr(),
|
||||||
members.len() as libc::size_t,
|
members.len() as libc::size_t,
|
||||||
members.as_ptr(),
|
members.as_ptr(),
|
||||||
|
|
|
@ -757,9 +757,9 @@ fn write_rlib_bytecode_object_v1(writer: &mut Write,
|
||||||
bc_data_deflated: &[u8]) -> io::Result<()> {
|
bc_data_deflated: &[u8]) -> io::Result<()> {
|
||||||
let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64;
|
let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64;
|
||||||
|
|
||||||
try!(writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC));
|
writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC)?;
|
||||||
try!(writer.write_all(&[1, 0, 0, 0]));
|
writer.write_all(&[1, 0, 0, 0])?;
|
||||||
try!(writer.write_all(&[
|
writer.write_all(&[
|
||||||
(bc_data_deflated_size >> 0) as u8,
|
(bc_data_deflated_size >> 0) as u8,
|
||||||
(bc_data_deflated_size >> 8) as u8,
|
(bc_data_deflated_size >> 8) as u8,
|
||||||
(bc_data_deflated_size >> 16) 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 >> 40) as u8,
|
||||||
(bc_data_deflated_size >> 48) as u8,
|
(bc_data_deflated_size >> 48) as u8,
|
||||||
(bc_data_deflated_size >> 56) 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 =
|
let number_of_bytes_written_so_far =
|
||||||
RLIB_BYTECODE_OBJECT_MAGIC.len() + // magic id
|
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
|
// padding byte to make it even. This works around a crash bug in LLDB
|
||||||
// (see issue #15950)
|
// (see issue #15950)
|
||||||
if number_of_bytes_written_so_far % 2 == 1 {
|
if number_of_bytes_written_so_far % 2 == 1 {
|
||||||
try!(writer.write_all(&[0]));
|
writer.write_all(&[0])?;
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(());
|
return Ok(());
|
||||||
|
|
|
@ -327,16 +327,16 @@ impl<'a> Linker for MsvcLinker<'a> {
|
||||||
tmpdir: &Path) {
|
tmpdir: &Path) {
|
||||||
let path = tmpdir.join("lib.def");
|
let path = tmpdir.join("lib.def");
|
||||||
let res = (|| -> io::Result<()> {
|
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
|
// Start off with the standard module name header and then go
|
||||||
// straight to exports.
|
// straight to exports.
|
||||||
try!(writeln!(f, "LIBRARY"));
|
writeln!(f, "LIBRARY")?;
|
||||||
try!(writeln!(f, "EXPORTS"));
|
writeln!(f, "EXPORTS")?;
|
||||||
|
|
||||||
// Write out all our local symbols
|
// Write out all our local symbols
|
||||||
for sym in trans.reachable.iter() {
|
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
|
// 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)
|
cstore.item_symbol(did)
|
||||||
});
|
});
|
||||||
for symbol in symbols {
|
for symbol in symbols {
|
||||||
try!(writeln!(f, " {}", symbol));
|
writeln!(f, " {}", symbol)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})();
|
})();
|
||||||
|
|
|
@ -175,9 +175,9 @@ impl<'blk, 'tcx: 'blk> fmt::Debug for CleanupScopeKind<'blk, 'tcx> {
|
||||||
CustomScopeKind => write!(f, "CustomScopeKind"),
|
CustomScopeKind => write!(f, "CustomScopeKind"),
|
||||||
AstScopeKind(nid) => write!(f, "AstScopeKind({})", nid),
|
AstScopeKind(nid) => write!(f, "AstScopeKind({})", nid),
|
||||||
LoopScopeKind(nid, ref blks) => {
|
LoopScopeKind(nid, ref blks) => {
|
||||||
try!(write!(f, "LoopScopeKind({}, [", nid));
|
write!(f, "LoopScopeKind({}, [", nid)?;
|
||||||
for blk in blks {
|
for blk in blks {
|
||||||
try!(write!(f, "{:p}, ", blk));
|
write!(f, "{:p}, ", blk)?;
|
||||||
}
|
}
|
||||||
write!(f, "])")
|
write!(f, "])")
|
||||||
}
|
}
|
||||||
|
|
|
@ -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) {
|
let val = if qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
|
||||||
// Avoid autorefs as they would create global instead of stack
|
// Avoid autorefs as they would create global instead of stack
|
||||||
// references, even when only the latter are correct.
|
// 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 {
|
} 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,
|
// 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> {
|
-> Result<(ValueRef, Ty<'tcx>), ConstEvalFailure> {
|
||||||
let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
|
let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
|
||||||
&cx.tcx().expr_ty(e));
|
&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 llconst = llconst;
|
||||||
let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
|
let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
|
||||||
&cx.tcx().expr_ty_adjusted(e));
|
&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) => {
|
hir::ExprBinary(b, ref e1, ref e2) => {
|
||||||
/* Neither type is bottom, and we expect them to be unified
|
/* Neither type is bottom, and we expect them to be unified
|
||||||
* already, so the following is safe. */
|
* 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={:?}",
|
debug!("const_expr_unadjusted: te1={:?}, ty={:?}",
|
||||||
Value(te1), ty);
|
Value(te1), ty);
|
||||||
assert!(!ty.is_simd());
|
assert!(!ty.is_simd());
|
||||||
let is_float = ty.is_fp();
|
let is_float = ty.is_fp();
|
||||||
let signed = ty.is_signed();
|
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={:?}",
|
debug!("const_expr_unadjusted: te2={:?}, ty={:?}",
|
||||||
Value(te2), ty2);
|
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 {
|
unsafe { match b.node {
|
||||||
hir::BiAdd if is_float => llvm::LLVMConstFAdd(te1, te2),
|
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 {
|
} } // unsafe { match b.node {
|
||||||
},
|
},
|
||||||
hir::ExprUnary(u, ref inner_e) => {
|
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();
|
let is_float = ty.is_fp();
|
||||||
unsafe { match u {
|
unsafe { match u {
|
||||||
|
@ -664,21 +664,21 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
|
||||||
} }
|
} }
|
||||||
},
|
},
|
||||||
hir::ExprField(ref base, field) => {
|
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 brepr = adt::represent_type(cx, bt);
|
||||||
let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
|
let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
|
||||||
let ix = vinfo.field_index(field.node);
|
let ix = vinfo.field_index(field.node);
|
||||||
adt::const_get_field(cx, &brepr, bv, vinfo.discr, ix)
|
adt::const_get_field(cx, &brepr, bv, vinfo.discr, ix)
|
||||||
},
|
},
|
||||||
hir::ExprTupField(ref base, idx) => {
|
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 brepr = adt::represent_type(cx, bt);
|
||||||
let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
|
let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
|
||||||
adt::const_get_field(cx, &brepr, bv, vinfo.discr, idx.node)
|
adt::const_get_field(cx, &brepr, bv, vinfo.discr, idx.node)
|
||||||
},
|
},
|
||||||
hir::ExprIndex(ref base, ref index) => {
|
hir::ExprIndex(ref base, ref index) => {
|
||||||
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 iv = try!(const_expr(cx, &index, param_substs, fn_args, TrueConst::Yes)).0;
|
let iv = const_expr(cx, &index, param_substs, fn_args, TrueConst::Yes)?.0;
|
||||||
let iv = if let Some(iv) = const_to_opt_uint(iv) {
|
let iv = if let Some(iv) = const_to_opt_uint(iv) {
|
||||||
iv
|
iv
|
||||||
} else {
|
} else {
|
||||||
|
@ -729,7 +729,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
|
||||||
hir::ExprCast(ref base, _) => {
|
hir::ExprCast(ref base, _) => {
|
||||||
let t_cast = ety;
|
let t_cast = ety;
|
||||||
let llty = type_of::type_of(cx, t_cast);
|
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);
|
debug!("trans_const_cast({:?} as {:?})", t_expr, t_cast);
|
||||||
if expr::cast_is_noop(cx.tcx(), base, t_expr, t_cast) {
|
if expr::cast_is_noop(cx.tcx(), base, t_expr, t_cast) {
|
||||||
return Ok(v);
|
return Ok(v);
|
||||||
|
@ -811,30 +811,30 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
|
||||||
} else {
|
} else {
|
||||||
// If this isn't the address of a static, then keep going through
|
// If this isn't the address of a static, then keep going through
|
||||||
// normal constant evaluation.
|
// 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")
|
addr_of(cx, v, type_of::align_of(cx, ty), "ref")
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
hir::ExprAddrOf(hir::MutMutable, ref sub) => {
|
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")
|
addr_of_mut(cx, v, type_of::align_of(cx, ty), "ref_mut_slice")
|
||||||
},
|
},
|
||||||
hir::ExprTup(ref es) => {
|
hir::ExprTup(ref es) => {
|
||||||
let repr = adt::represent_type(cx, ety);
|
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[..])
|
adt::trans_const(cx, &repr, Disr(0), &vals[..])
|
||||||
},
|
},
|
||||||
hir::ExprStruct(_, ref fs, ref base_opt) => {
|
hir::ExprStruct(_, ref fs, ref base_opt) => {
|
||||||
let repr = adt::represent_type(cx, ety);
|
let repr = adt::represent_type(cx, ety);
|
||||||
|
|
||||||
let base_val = match *base_opt {
|
let base_val = match *base_opt {
|
||||||
Some(ref base) => Some(try!(const_expr(
|
Some(ref base) => Some(const_expr(
|
||||||
cx,
|
cx,
|
||||||
&base,
|
&base,
|
||||||
param_substs,
|
param_substs,
|
||||||
fn_args,
|
fn_args,
|
||||||
trueconst,
|
trueconst,
|
||||||
))),
|
)?),
|
||||||
None => None
|
None => None
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -851,7 +851,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
|
||||||
.collect::<Vec<Result<_, ConstEvalFailure>>>()
|
.collect::<Vec<Result<_, ConstEvalFailure>>>()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.collect::<Result<Vec<_>,ConstEvalFailure>>();
|
.collect::<Result<Vec<_>,ConstEvalFailure>>();
|
||||||
let cs = try!(cs);
|
let cs = cs?;
|
||||||
if ety.is_simd() {
|
if ety.is_simd() {
|
||||||
C_vector(&cs[..])
|
C_vector(&cs[..])
|
||||||
} else {
|
} else {
|
||||||
|
@ -872,7 +872,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
|
||||||
.collect::<Vec<Result<_, ConstEvalFailure>>>()
|
.collect::<Vec<Result<_, ConstEvalFailure>>>()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.collect::<Result<Vec<_>, ConstEvalFailure>>();
|
.collect::<Result<Vec<_>, ConstEvalFailure>>();
|
||||||
let vs = try!(vs);
|
let vs = vs?;
|
||||||
// If the vector contains enums, an LLVM array won't work.
|
// If the vector contains enums, an LLVM array won't work.
|
||||||
if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
|
if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
|
||||||
C_struct(cx, &vs[..], false)
|
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 unit_ty = ety.sequence_element_type(cx.tcx());
|
||||||
let llunitty = type_of::type_of(cx, unit_ty);
|
let llunitty = type_of::type_of(cx, unit_ty);
|
||||||
let n = cx.tcx().eval_repeat_count(count);
|
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];
|
let vs = vec![unit_val; n];
|
||||||
if val_ty(unit_val) != llunitty {
|
if val_ty(unit_val) != llunitty {
|
||||||
C_struct(cx, &vs[..], false)
|
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::Fn(..) | Def::Method(..) => C_nil(cx),
|
||||||
Def::Const(def_id) | Def::AssociatedConst(def_id) => {
|
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)
|
ety)
|
||||||
}
|
}
|
||||||
Def::Variant(enum_did, variant_did) => {
|
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 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 {
|
match def {
|
||||||
Def::Fn(did) | Def::Method(did) => {
|
Def::Fn(did) | Def::Method(did) => {
|
||||||
try!(const_fn_call(
|
const_fn_call(
|
||||||
cx,
|
cx,
|
||||||
did,
|
did,
|
||||||
cx.tcx().node_id_item_substs(callee.id).substs,
|
cx.tcx().node_id_item_substs(callee.id).substs,
|
||||||
&arg_vals,
|
&arg_vals,
|
||||||
param_substs,
|
param_substs,
|
||||||
trueconst,
|
trueconst,
|
||||||
))
|
)?
|
||||||
}
|
}
|
||||||
Def::Struct(..) => {
|
Def::Struct(..) => {
|
||||||
if ety.is_simd() {
|
if ety.is_simd() {
|
||||||
|
@ -972,22 +972,22 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
hir::ExprMethodCall(_, _, ref args) => {
|
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_call = ty::MethodCall::expr(e.id);
|
||||||
let method = cx.tcx().tables.borrow().method_map[&method_call];
|
let method = cx.tcx().tables.borrow().method_map[&method_call];
|
||||||
try!(const_fn_call(cx, method.def_id, method.substs.clone(),
|
const_fn_call(cx, method.def_id, method.substs.clone(),
|
||||||
&arg_vals, param_substs, trueconst))
|
&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) => {
|
hir::ExprBlock(ref block) => {
|
||||||
match block.expr {
|
match block.expr {
|
||||||
Some(ref expr) => try!(const_expr(
|
Some(ref expr) => const_expr(
|
||||||
cx,
|
cx,
|
||||||
&expr,
|
&expr,
|
||||||
param_substs,
|
param_substs,
|
||||||
fn_args,
|
fn_args,
|
||||||
trueconst,
|
trueconst,
|
||||||
)).0,
|
)?.0,
|
||||||
None => C_nil(cx),
|
None => C_nil(cx),
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -1149,13 +1149,13 @@ pub fn trans_static(ccx: &CrateContext,
|
||||||
let datum = get_static(ccx, def_id);
|
let datum = get_static(ccx, def_id);
|
||||||
|
|
||||||
let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
|
let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
|
||||||
let (v, _) = try!(const_expr(
|
let (v, _) = const_expr(
|
||||||
ccx,
|
ccx,
|
||||||
expr,
|
expr,
|
||||||
empty_substs,
|
empty_substs,
|
||||||
None,
|
None,
|
||||||
TrueConst::Yes,
|
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,
|
// boolean SSA values are i1, but they have to be stored in i8 slots,
|
||||||
// otherwise some LLVM optimization passes don't work as expected
|
// otherwise some LLVM optimization passes don't work as expected
|
||||||
|
|
|
@ -934,7 +934,7 @@ fn ast_type_binding_to_poly_projection_predicate<'tcx>(
|
||||||
tcx.mk_substs(dummy_substs)));
|
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> =
|
let mut candidates: Vec<ty::PolyTraitRef> =
|
||||||
traits::supertraits(tcx, trait_ref.clone())
|
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,
|
candidates,
|
||||||
&trait_ref.to_string(),
|
&trait_ref.to_string(),
|
||||||
&binding.item_name.as_str(),
|
&binding.item_name.as_str(),
|
||||||
binding.span));
|
binding.span)?;
|
||||||
|
|
||||||
Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------------+
|
Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------------+
|
||||||
projection_ty: ty::ProjectionTy { // |
|
projection_ty: ty::ProjectionTy { // |
|
||||||
|
|
|
@ -220,7 +220,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
|
||||||
|
|
||||||
let (r_a, mt_a) = match a.sty {
|
let (r_a, mt_a) = match a.sty {
|
||||||
ty::TyRef(r_a, mt_a) => {
|
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)
|
(r_a, mt_a)
|
||||||
}
|
}
|
||||||
_ => return self.unify_and_identity(a, b)
|
_ => return self.unify_and_identity(a, b)
|
||||||
|
@ -414,7 +414,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
|
||||||
// Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
|
// Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
|
||||||
let (source, reborrow) = match (&source.sty, &target.sty) {
|
let (source, reborrow) = match (&source.sty, &target.sty) {
|
||||||
(&ty::TyRef(_, mt_a), &ty::TyRef(_, mt_b)) => {
|
(&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 coercion = Coercion(self.origin.span());
|
||||||
let r_borrow = self.fcx.infcx().next_region_var(coercion);
|
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)))
|
(mt_a.ty, Some(AutoPtr(region, mt_b.mutbl)))
|
||||||
}
|
}
|
||||||
(&ty::TyRef(_, mt_a), &ty::TyRawPtr(mt_b)) => {
|
(&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)))
|
(mt_a.ty, Some(AutoUnsafe(mt_b.mutbl)))
|
||||||
}
|
}
|
||||||
_ => (source, None)
|
_ => (source, None)
|
||||||
|
@ -564,8 +564,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
|
||||||
|
|
||||||
// Check that the types which they point at are compatible.
|
// 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 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));
|
let (ty, noop) = self.unify_and_identity(a_unsafe, b)?;
|
||||||
try!(coerce_mutbls(mt_a.mutbl, mutbl_b));
|
coerce_mutbls(mt_a.mutbl, mutbl_b)?;
|
||||||
|
|
||||||
// Although references and unsafe ptrs have the same
|
// Although references and unsafe ptrs have the same
|
||||||
// representation, we still register an AutoDerefRef so that
|
// 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,
|
where E: Fn() -> I,
|
||||||
I: IntoIterator<Item=&'b hir::Expr> {
|
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;
|
let fcx = coerce.fcx;
|
||||||
if let AdjustDerefRef(auto) = adjustment {
|
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));
|
let mut coerce = Coerce::new(fcx, TypeOrigin::ExprAssignable(expr.span));
|
||||||
fcx.infcx().commit_if_ok(|_| {
|
fcx.infcx().commit_if_ok(|_| {
|
||||||
let (ty, adjustment) =
|
let (ty, adjustment) =
|
||||||
try!(apply(&mut coerce, &|| Some(expr), source, target));
|
apply(&mut coerce, &|| Some(expr), source, target)?;
|
||||||
if !adjustment.is_identity() {
|
if !adjustment.is_identity() {
|
||||||
debug!("Success, coerced with {:?}", adjustment);
|
debug!("Success, coerced with {:?}", adjustment);
|
||||||
assert!(!fcx.inh.tables.borrow().adjustments.contains_key(&expr.id));
|
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(a_def_id, a_substs, a_fty),
|
||||||
&ty::TyFnDef(b_def_id, b_substs, b_fty)) => {
|
&ty::TyFnDef(b_def_id, b_substs, b_fty)) => {
|
||||||
// The signature must always match.
|
// 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 {
|
if a_def_id == b_def_id {
|
||||||
// Same function, maybe the parameters match.
|
// Same function, maybe the parameters match.
|
||||||
|
|
|
@ -323,7 +323,7 @@ pub fn compare_impl_method<'tcx>(tcx: &TyCtxt<'tcx>,
|
||||||
debug!("compare_impl_method: trait_fty={:?}",
|
debug!("compare_impl_method: trait_fty={:?}",
|
||||||
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)
|
infcx.leak_check(&skol_map, snapshot)
|
||||||
});
|
});
|
||||||
|
|
|
@ -46,11 +46,11 @@ pub fn check_drop_impl(tcx: &TyCtxt, drop_impl_did: DefId) -> Result<(), ()> {
|
||||||
match dtor_self_type.sty {
|
match dtor_self_type.sty {
|
||||||
ty::TyEnum(adt_def, self_to_impl_substs) |
|
ty::TyEnum(adt_def, self_to_impl_substs) |
|
||||||
ty::TyStruct(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,
|
drop_impl_did,
|
||||||
dtor_generics,
|
dtor_generics,
|
||||||
&dtor_self_type,
|
&dtor_self_type,
|
||||||
adt_def.did));
|
adt_def.did)?;
|
||||||
|
|
||||||
ensure_drop_predicates_are_implied_by_item_defn(tcx,
|
ensure_drop_predicates_are_implied_by_item_defn(tcx,
|
||||||
drop_impl_did,
|
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 = field.ty(tcx, substs);
|
||||||
let fty = cx.rcx.fcx.resolve_type_vars_if_possible(
|
let fty = cx.rcx.fcx.resolve_type_vars_if_possible(
|
||||||
cx.rcx.fcx.normalize_associated_types_in(cx.span, &fty));
|
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,
|
cx,
|
||||||
TypeContext::ADT {
|
TypeContext::ADT {
|
||||||
def_id: did,
|
def_id: did,
|
||||||
|
@ -460,7 +460,7 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'b, 'tcx>(
|
||||||
variant: variant.name,
|
variant: variant.name,
|
||||||
},
|
},
|
||||||
fty,
|
fty,
|
||||||
depth+1))
|
depth+1)?
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -469,8 +469,8 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'b, 'tcx>(
|
||||||
ty::TyTuple(ref tys) |
|
ty::TyTuple(ref tys) |
|
||||||
ty::TyClosure(_, box ty::ClosureSubsts { upvar_tys: ref tys, .. }) => {
|
ty::TyClosure(_, box ty::ClosureSubsts { upvar_tys: ref tys, .. }) => {
|
||||||
for ty in tys {
|
for ty in tys {
|
||||||
try!(iterate_over_potentially_unsafe_regions_in_type(
|
iterate_over_potentially_unsafe_regions_in_type(
|
||||||
cx, context, ty, depth+1))
|
cx, context, ty, depth+1)?
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -124,7 +124,7 @@ pub fn lookup<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
|
||||||
|
|
||||||
let mode = probe::Mode::MethodCall;
|
let mode = probe::Mode::MethodCall;
|
||||||
let self_ty = fcx.infcx().resolve_type_vars_if_possible(&self_ty);
|
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))
|
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>>
|
-> Result<Def, MethodError<'tcx>>
|
||||||
{
|
{
|
||||||
let mode = probe::Mode::Path;
|
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();
|
let def = pick.item.def();
|
||||||
|
|
||||||
if let probe::InherentImplPick = pick.kind {
|
if let probe::InherentImplPick = pick.kind {
|
||||||
|
|
|
@ -186,7 +186,7 @@ pub fn probe<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
|
||||||
steps,
|
steps,
|
||||||
opt_simplified_steps);
|
opt_simplified_steps);
|
||||||
probe_cx.assemble_inherent_candidates();
|
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()
|
probe_cx.pick()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -568,7 +568,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> {
|
||||||
if let Some(applicable_traits) = opt_applicable_traits {
|
if let Some(applicable_traits) = opt_applicable_traits {
|
||||||
for &trait_did in applicable_traits {
|
for &trait_did in applicable_traits {
|
||||||
if duplicates.insert(trait_did) {
|
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();
|
let mut duplicates = HashSet::new();
|
||||||
for trait_info in suggest::all_traits(self.fcx.ccx) {
|
for trait_info in suggest::all_traits(self.fcx.ccx) {
|
||||||
if duplicates.insert(trait_info.def_id) {
|
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(())
|
Ok(())
|
||||||
|
@ -612,7 +612,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> {
|
||||||
|
|
||||||
self.assemble_extension_candidates_for_trait_impls(trait_def_id, item.clone());
|
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());
|
self.assemble_projection_candidates(trait_def_id, item.clone());
|
||||||
|
|
||||||
|
@ -854,7 +854,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> {
|
||||||
let span = self.span;
|
let span = self.span;
|
||||||
let tcx = self.tcx();
|
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() {
|
let out_of_scope_traits = match self.pick_core() {
|
||||||
Some(Ok(p)) => vec![p.item.container().id()],
|
Some(Ok(p)) => vec![p.item.container().id()],
|
||||||
|
|
|
@ -292,7 +292,7 @@ impl<'a,'tcx> CrateCtxt<'a,'tcx> {
|
||||||
let def_ids = ensure_super_predicates_step(self, trait_def_id);
|
let def_ids = ensure_super_predicates_step(self, trait_def_id);
|
||||||
|
|
||||||
for def_id in def_ids {
|
for def_id in def_ids {
|
||||||
try!(self.ensure_super_predicates(span, def_id));
|
self.ensure_super_predicates(span, def_id)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -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
|
// this ensures that later parts of type checking can assume that items
|
||||||
// have valid types and not error
|
// have valid types and not error
|
||||||
try!(tcx.sess.track_errors(|| {
|
tcx.sess.track_errors(|| {
|
||||||
time(time_passes, "type collecting", ||
|
time(time_passes, "type collecting", ||
|
||||||
collect::collect_item_types(tcx));
|
collect::collect_item_types(tcx));
|
||||||
|
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
time(time_passes, "variance inference", ||
|
time(time_passes, "variance inference", ||
|
||||||
variance::infer_variance(tcx));
|
variance::infer_variance(tcx));
|
||||||
|
|
||||||
try!(tcx.sess.track_errors(|| {
|
tcx.sess.track_errors(|| {
|
||||||
time(time_passes, "coherence checking", ||
|
time(time_passes, "coherence checking", ||
|
||||||
coherence::check_coherence(&ccx));
|
coherence::check_coherence(&ccx));
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
try!(time(time_passes, "wf checking", ||
|
time(time_passes, "wf checking", ||
|
||||||
check::check_wf_new(&ccx)));
|
check::check_wf_new(&ccx))?;
|
||||||
|
|
||||||
try!(time(time_passes, "item-types checking", ||
|
time(time_passes, "item-types checking", ||
|
||||||
check::check_item_types(&ccx)));
|
check::check_item_types(&ccx))?;
|
||||||
|
|
||||||
try!(time(time_passes, "item-bodies checking", ||
|
time(time_passes, "item-bodies checking", ||
|
||||||
check::check_item_bodies(&ccx)));
|
check::check_item_bodies(&ccx))?;
|
||||||
|
|
||||||
try!(time(time_passes, "drop-impl checking", ||
|
time(time_passes, "drop-impl checking", ||
|
||||||
check::check_drop_impls(&ccx)));
|
check::check_drop_impls(&ccx))?;
|
||||||
|
|
||||||
check_for_entry_fn(&ccx);
|
check_for_entry_fn(&ccx);
|
||||||
|
|
||||||
|
|
|
@ -38,9 +38,9 @@ impl ExternalHtml {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_string(input: &Path) -> io::Result<Option<String>> {
|
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();
|
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())
|
Ok(str::from_utf8(&d).map(|s| s.to_string()).ok())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -29,7 +29,7 @@ impl<'a> fmt::Display for Escape<'a> {
|
||||||
for (i, ch) in s.bytes().enumerate() {
|
for (i, ch) in s.bytes().enumerate() {
|
||||||
match ch as char {
|
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 {
|
let s = match ch as char {
|
||||||
'>' => ">",
|
'>' => ">",
|
||||||
'<' => "<",
|
'<' => "<",
|
||||||
|
@ -38,7 +38,7 @@ impl<'a> fmt::Display for Escape<'a> {
|
||||||
'"' => """,
|
'"' => """,
|
||||||
_ => unreachable!()
|
_ => unreachable!()
|
||||||
};
|
};
|
||||||
try!(fmt.write_str(s));
|
fmt.write_str(s)?;
|
||||||
last = i + 1;
|
last = i + 1;
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
|
@ -46,7 +46,7 @@ impl<'a> fmt::Display for Escape<'a> {
|
||||||
}
|
}
|
||||||
|
|
||||||
if last < s.len() {
|
if last < s.len() {
|
||||||
try!(fmt.write_str(&pile_o_bits[last..]));
|
fmt.write_str(&pile_o_bits[last..])?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -77,8 +77,8 @@ impl ConstnessSpace {
|
||||||
impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
|
impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
for (i, item) in self.0.iter().enumerate() {
|
for (i, item) in self.0.iter().enumerate() {
|
||||||
if i != 0 { try!(write!(f, ", ")); }
|
if i != 0 { write!(f, ", ")?; }
|
||||||
try!(write!(f, "{}", item));
|
write!(f, "{}", item)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -89,9 +89,9 @@ impl<'a> fmt::Display for TyParamBounds<'a> {
|
||||||
let &TyParamBounds(bounds) = self;
|
let &TyParamBounds(bounds) = self;
|
||||||
for (i, bound) in bounds.iter().enumerate() {
|
for (i, bound) in bounds.iter().enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
try!(f.write_str(" + "));
|
f.write_str(" + ")?;
|
||||||
}
|
}
|
||||||
try!(write!(f, "{}", *bound));
|
write!(f, "{}", *bound)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -100,36 +100,36 @@ impl<'a> fmt::Display for TyParamBounds<'a> {
|
||||||
impl fmt::Display for clean::Generics {
|
impl fmt::Display for clean::Generics {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
if self.lifetimes.is_empty() && self.type_params.is_empty() { return Ok(()) }
|
if self.lifetimes.is_empty() && self.type_params.is_empty() { return Ok(()) }
|
||||||
try!(f.write_str("<"));
|
f.write_str("<")?;
|
||||||
|
|
||||||
for (i, life) in self.lifetimes.iter().enumerate() {
|
for (i, life) in self.lifetimes.iter().enumerate() {
|
||||||
if i > 0 {
|
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.type_params.is_empty() {
|
||||||
if !self.lifetimes.is_empty() {
|
if !self.lifetimes.is_empty() {
|
||||||
try!(f.write_str(", "));
|
f.write_str(", ")?;
|
||||||
}
|
}
|
||||||
for (i, tp) in self.type_params.iter().enumerate() {
|
for (i, tp) in self.type_params.iter().enumerate() {
|
||||||
if i > 0 {
|
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() {
|
if !tp.bounds.is_empty() {
|
||||||
try!(write!(f, ": {}", TyParamBounds(&tp.bounds)));
|
write!(f, ": {}", TyParamBounds(&tp.bounds))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
match tp.default {
|
match tp.default {
|
||||||
Some(ref ty) => { try!(write!(f, " = {}", ty)); },
|
Some(ref ty) => { write!(f, " = {}", ty)?; },
|
||||||
None => {}
|
None => {}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try!(f.write_str(">"));
|
f.write_str(">")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -140,40 +140,40 @@ impl<'a> fmt::Display for WhereClause<'a> {
|
||||||
if gens.where_predicates.is_empty() {
|
if gens.where_predicates.is_empty() {
|
||||||
return Ok(());
|
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() {
|
for (i, pred) in gens.where_predicates.iter().enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
try!(f.write_str(", "));
|
f.write_str(", ")?;
|
||||||
}
|
}
|
||||||
match pred {
|
match pred {
|
||||||
&clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
|
&clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
|
||||||
let bounds = bounds;
|
let bounds = bounds;
|
||||||
try!(write!(f, "{}: {}", ty, TyParamBounds(bounds)));
|
write!(f, "{}: {}", ty, TyParamBounds(bounds))?;
|
||||||
}
|
}
|
||||||
&clean::WherePredicate::RegionPredicate { ref lifetime,
|
&clean::WherePredicate::RegionPredicate { ref lifetime,
|
||||||
ref bounds } => {
|
ref bounds } => {
|
||||||
try!(write!(f, "{}: ", lifetime));
|
write!(f, "{}: ", lifetime)?;
|
||||||
for (i, lifetime) in bounds.iter().enumerate() {
|
for (i, lifetime) in bounds.iter().enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
try!(f.write_str(" + "));
|
f.write_str(" + ")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
try!(write!(f, "{}", lifetime));
|
write!(f, "{}", lifetime)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
&clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
|
&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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for clean::Lifetime {
|
impl fmt::Display for clean::Lifetime {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
try!(f.write_str(self.get_ref()));
|
f.write_str(self.get_ref())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -181,14 +181,14 @@ impl fmt::Display for clean::Lifetime {
|
||||||
impl fmt::Display for clean::PolyTrait {
|
impl fmt::Display for clean::PolyTrait {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
if !self.lifetimes.is_empty() {
|
if !self.lifetimes.is_empty() {
|
||||||
try!(f.write_str("for<"));
|
f.write_str("for<")?;
|
||||||
for (i, lt) in self.lifetimes.iter().enumerate() {
|
for (i, lt) in self.lifetimes.iter().enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
try!(f.write_str(", "));
|
f.write_str(", ")?;
|
||||||
}
|
}
|
||||||
try!(write!(f, "{}", lt));
|
write!(f, "{}", lt)?;
|
||||||
}
|
}
|
||||||
try!(f.write_str("> "));
|
f.write_str("> ")?;
|
||||||
}
|
}
|
||||||
write!(f, "{}", self.trait_)
|
write!(f, "{}", self.trait_)
|
||||||
}
|
}
|
||||||
|
@ -218,46 +218,46 @@ impl fmt::Display for clean::PathParameters {
|
||||||
ref lifetimes, ref types, ref bindings
|
ref lifetimes, ref types, ref bindings
|
||||||
} => {
|
} => {
|
||||||
if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
|
if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
|
||||||
try!(f.write_str("<"));
|
f.write_str("<")?;
|
||||||
let mut comma = false;
|
let mut comma = false;
|
||||||
for lifetime in lifetimes {
|
for lifetime in lifetimes {
|
||||||
if comma {
|
if comma {
|
||||||
try!(f.write_str(", "));
|
f.write_str(", ")?;
|
||||||
}
|
}
|
||||||
comma = true;
|
comma = true;
|
||||||
try!(write!(f, "{}", *lifetime));
|
write!(f, "{}", *lifetime)?;
|
||||||
}
|
}
|
||||||
for ty in types {
|
for ty in types {
|
||||||
if comma {
|
if comma {
|
||||||
try!(f.write_str(", "));
|
f.write_str(", ")?;
|
||||||
}
|
}
|
||||||
comma = true;
|
comma = true;
|
||||||
try!(write!(f, "{}", *ty));
|
write!(f, "{}", *ty)?;
|
||||||
}
|
}
|
||||||
for binding in bindings {
|
for binding in bindings {
|
||||||
if comma {
|
if comma {
|
||||||
try!(f.write_str(", "));
|
f.write_str(", ")?;
|
||||||
}
|
}
|
||||||
comma = true;
|
comma = true;
|
||||||
try!(write!(f, "{}", *binding));
|
write!(f, "{}", *binding)?;
|
||||||
}
|
}
|
||||||
try!(f.write_str(">"));
|
f.write_str(">")?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
clean::PathParameters::Parenthesized { ref inputs, ref output } => {
|
clean::PathParameters::Parenthesized { ref inputs, ref output } => {
|
||||||
try!(f.write_str("("));
|
f.write_str("(")?;
|
||||||
let mut comma = false;
|
let mut comma = false;
|
||||||
for ty in inputs {
|
for ty in inputs {
|
||||||
if comma {
|
if comma {
|
||||||
try!(f.write_str(", "));
|
f.write_str(", ")?;
|
||||||
}
|
}
|
||||||
comma = true;
|
comma = true;
|
||||||
try!(write!(f, "{}", *ty));
|
write!(f, "{}", *ty)?;
|
||||||
}
|
}
|
||||||
try!(f.write_str(")"));
|
f.write_str(")")?;
|
||||||
if let Some(ref ty) = *output {
|
if let Some(ref ty) = *output {
|
||||||
try!(f.write_str(" -> "));
|
f.write_str(" -> ")?;
|
||||||
try!(write!(f, "{}", ty));
|
write!(f, "{}", ty)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -267,7 +267,7 @@ impl fmt::Display for clean::PathParameters {
|
||||||
|
|
||||||
impl fmt::Display for clean::PathSegment {
|
impl fmt::Display for clean::PathSegment {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
try!(f.write_str(&self.name));
|
f.write_str(&self.name)?;
|
||||||
write!(f, "{}", self.params)
|
write!(f, "{}", self.params)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -275,14 +275,14 @@ impl fmt::Display for clean::PathSegment {
|
||||||
impl fmt::Display for clean::Path {
|
impl fmt::Display for clean::Path {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
if self.global {
|
if self.global {
|
||||||
try!(f.write_str("::"))
|
f.write_str("::")?
|
||||||
}
|
}
|
||||||
|
|
||||||
for (i, seg) in self.segments.iter().enumerate() {
|
for (i, seg) in self.segments.iter().enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
try!(f.write_str("::"))
|
f.write_str("::")?
|
||||||
}
|
}
|
||||||
try!(write!(f, "{}", seg));
|
write!(f, "{}", seg)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -339,20 +339,20 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
|
||||||
Some(mut root) => {
|
Some(mut root) => {
|
||||||
for seg in &path.segments[..amt] {
|
for seg in &path.segments[..amt] {
|
||||||
if "super" == seg.name || "self" == seg.name {
|
if "super" == seg.name || "self" == seg.name {
|
||||||
try!(write!(w, "{}::", seg.name));
|
write!(w, "{}::", seg.name)?;
|
||||||
} else {
|
} else {
|
||||||
root.push_str(&seg.name);
|
root.push_str(&seg.name);
|
||||||
root.push_str("/");
|
root.push_str("/");
|
||||||
try!(write!(w, "<a class='mod'
|
write!(w, "<a class='mod'
|
||||||
href='{}index.html'>{}</a>::",
|
href='{}index.html'>{}</a>::",
|
||||||
root,
|
root,
|
||||||
seg.name));
|
seg.name)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
for seg in &path.segments[..amt] {
|
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) {
|
match href(did) {
|
||||||
Some((url, shortty, fqp)) => {
|
Some((url, shortty, fqp)) => {
|
||||||
try!(write!(w, "<a class='{}' href='{}' title='{}'>{}</a>",
|
write!(w, "<a class='{}' href='{}' title='{}'>{}</a>",
|
||||||
shortty, url, fqp.join("::"), last.name));
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -378,9 +378,9 @@ fn primitive_link(f: &mut fmt::Formatter,
|
||||||
Some(&LOCAL_CRATE) => {
|
Some(&LOCAL_CRATE) => {
|
||||||
let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
|
let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
|
||||||
let len = if len == 0 {0} else {len - 1};
|
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>(),
|
repeat("../").take(len).collect::<String>(),
|
||||||
prim.to_url_str()));
|
prim.to_url_str())?;
|
||||||
needs_termination = true;
|
needs_termination = true;
|
||||||
}
|
}
|
||||||
Some(&cnum) => {
|
Some(&cnum) => {
|
||||||
|
@ -398,10 +398,10 @@ fn primitive_link(f: &mut fmt::Formatter,
|
||||||
};
|
};
|
||||||
match loc {
|
match loc {
|
||||||
Some(root) => {
|
Some(root) => {
|
||||||
try!(write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
|
write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
|
||||||
root,
|
root,
|
||||||
path.0.first().unwrap(),
|
path.0.first().unwrap(),
|
||||||
prim.to_url_str()));
|
prim.to_url_str())?;
|
||||||
needs_termination = true;
|
needs_termination = true;
|
||||||
}
|
}
|
||||||
None => {}
|
None => {}
|
||||||
|
@ -409,9 +409,9 @@ fn primitive_link(f: &mut fmt::Formatter,
|
||||||
}
|
}
|
||||||
None => {}
|
None => {}
|
||||||
}
|
}
|
||||||
try!(write!(f, "{}", name));
|
write!(f, "{}", name)?;
|
||||||
if needs_termination {
|
if needs_termination {
|
||||||
try!(write!(f, "</a>"));
|
write!(f, "</a>")?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -422,8 +422,8 @@ fn tybounds(w: &mut fmt::Formatter,
|
||||||
match *typarams {
|
match *typarams {
|
||||||
Some(ref params) => {
|
Some(ref params) => {
|
||||||
for param in params {
|
for param in params {
|
||||||
try!(write!(w, " + "));
|
write!(w, " + ")?;
|
||||||
try!(write!(w, "{}", *param));
|
write!(w, "{}", *param)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -439,7 +439,7 @@ impl fmt::Display for clean::Type {
|
||||||
}
|
}
|
||||||
clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
|
clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
|
||||||
// Paths like T::Output and Self::Output should be rendered with all segments
|
// 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)
|
tybounds(f, typarams)
|
||||||
}
|
}
|
||||||
clean::Infer => write!(f, "_"),
|
clean::Infer => write!(f, "_"),
|
||||||
|
@ -459,25 +459,25 @@ impl fmt::Display for clean::Type {
|
||||||
match &**typs {
|
match &**typs {
|
||||||
[] => primitive_link(f, clean::PrimitiveTuple, "()"),
|
[] => primitive_link(f, clean::PrimitiveTuple, "()"),
|
||||||
[ref one] => {
|
[ref one] => {
|
||||||
try!(primitive_link(f, clean::PrimitiveTuple, "("));
|
primitive_link(f, clean::PrimitiveTuple, "(")?;
|
||||||
try!(write!(f, "{},", one));
|
write!(f, "{},", one)?;
|
||||||
primitive_link(f, clean::PrimitiveTuple, ")")
|
primitive_link(f, clean::PrimitiveTuple, ")")
|
||||||
}
|
}
|
||||||
many => {
|
many => {
|
||||||
try!(primitive_link(f, clean::PrimitiveTuple, "("));
|
primitive_link(f, clean::PrimitiveTuple, "(")?;
|
||||||
try!(write!(f, "{}", CommaSep(&many)));
|
write!(f, "{}", CommaSep(&many))?;
|
||||||
primitive_link(f, clean::PrimitiveTuple, ")")
|
primitive_link(f, clean::PrimitiveTuple, ")")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
clean::Vector(ref t) => {
|
clean::Vector(ref t) => {
|
||||||
try!(primitive_link(f, clean::Slice, &format!("[")));
|
primitive_link(f, clean::Slice, &format!("["))?;
|
||||||
try!(write!(f, "{}", t));
|
write!(f, "{}", t)?;
|
||||||
primitive_link(f, clean::Slice, &format!("]"))
|
primitive_link(f, clean::Slice, &format!("]"))
|
||||||
}
|
}
|
||||||
clean::FixedVector(ref t, ref s) => {
|
clean::FixedVector(ref t, ref s) => {
|
||||||
try!(primitive_link(f, clean::PrimitiveType::Array, "["));
|
primitive_link(f, clean::PrimitiveType::Array, "[")?;
|
||||||
try!(write!(f, "{}", t));
|
write!(f, "{}", t)?;
|
||||||
primitive_link(f, clean::PrimitiveType::Array,
|
primitive_link(f, clean::PrimitiveType::Array,
|
||||||
&format!("; {}]", *s))
|
&format!("; {}]", *s))
|
||||||
}
|
}
|
||||||
|
@ -489,8 +489,8 @@ impl fmt::Display for clean::Type {
|
||||||
&format!("*{}{}", RawMutableSpace(m), t))
|
&format!("*{}{}", RawMutableSpace(m), t))
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
try!(primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
|
primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
|
||||||
&format!("*{}", RawMutableSpace(m))));
|
&format!("*{}", RawMutableSpace(m)))?;
|
||||||
write!(f, "{}", t)
|
write!(f, "{}", t)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -508,9 +508,9 @@ impl fmt::Display for clean::Type {
|
||||||
primitive_link(f, clean::Slice,
|
primitive_link(f, clean::Slice,
|
||||||
&format!("&{}{}[{}]", lt, m, **bt)),
|
&format!("&{}{}[{}]", lt, m, **bt)),
|
||||||
_ => {
|
_ => {
|
||||||
try!(primitive_link(f, clean::Slice,
|
primitive_link(f, clean::Slice,
|
||||||
&format!("&{}{}[", lt, m)));
|
&format!("&{}{}[", lt, m))?;
|
||||||
try!(write!(f, "{}", **bt));
|
write!(f, "{}", **bt)?;
|
||||||
primitive_link(f, clean::Slice, "]")
|
primitive_link(f, clean::Slice, "]")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -523,9 +523,9 @@ impl fmt::Display for clean::Type {
|
||||||
clean::PolyTraitRef(ref bounds) => {
|
clean::PolyTraitRef(ref bounds) => {
|
||||||
for (i, bound) in bounds.iter().enumerate() {
|
for (i, bound) in bounds.iter().enumerate() {
|
||||||
if i != 0 {
|
if i != 0 {
|
||||||
try!(write!(f, " + "));
|
write!(f, " + ")?;
|
||||||
}
|
}
|
||||||
try!(write!(f, "{}", *bound));
|
write!(f, "{}", *bound)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -544,9 +544,9 @@ impl fmt::Display for clean::Type {
|
||||||
ref self_type,
|
ref self_type,
|
||||||
trait_: box clean::ResolvedPath { did, ref typarams, .. },
|
trait_: box clean::ResolvedPath { did, ref typarams, .. },
|
||||||
} => {
|
} => {
|
||||||
try!(write!(f, "{}::", self_type));
|
write!(f, "{}::", self_type)?;
|
||||||
let path = clean::Path::singleton(name.clone());
|
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?
|
// FIXME: `typarams` are not rendered, and this seems bad?
|
||||||
drop(typarams);
|
drop(typarams);
|
||||||
|
@ -564,13 +564,13 @@ impl fmt::Display for clean::Type {
|
||||||
|
|
||||||
impl fmt::Display for clean::Impl {
|
impl fmt::Display for clean::Impl {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
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_ {
|
if let Some(ref ty) = self.trait_ {
|
||||||
try!(write!(f, "{}{} for ",
|
write!(f, "{}{} for ",
|
||||||
if self.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" },
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -578,11 +578,11 @@ impl fmt::Display for clean::Impl {
|
||||||
impl fmt::Display for clean::Arguments {
|
impl fmt::Display for clean::Arguments {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
for (i, input) in self.values.iter().enumerate() {
|
for (i, input) in self.values.iter().enumerate() {
|
||||||
if i > 0 { try!(write!(f, ", ")); }
|
if i > 0 { write!(f, ", ")?; }
|
||||||
if !input.name.is_empty() {
|
if !input.name.is_empty() {
|
||||||
try!(write!(f, "{}: ", input.name));
|
write!(f, "{}: ", input.name)?;
|
||||||
}
|
}
|
||||||
try!(write!(f, "{}", input.type_));
|
write!(f, "{}", input.type_)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -678,12 +678,12 @@ impl fmt::Display for clean::Import {
|
||||||
write!(f, "use {}::*;", *src)
|
write!(f, "use {}::*;", *src)
|
||||||
}
|
}
|
||||||
clean::ImportList(ref src, ref names) => {
|
clean::ImportList(ref src, ref names) => {
|
||||||
try!(write!(f, "use {}::{{", *src));
|
write!(f, "use {}::{{", *src)?;
|
||||||
for (i, n) in names.iter().enumerate() {
|
for (i, n) in names.iter().enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
try!(write!(f, ", "));
|
write!(f, ", ")?;
|
||||||
}
|
}
|
||||||
try!(write!(f, "{}", *n));
|
write!(f, "{}", *n)?;
|
||||||
}
|
}
|
||||||
write!(f, "}};")
|
write!(f, "}};")
|
||||||
}
|
}
|
||||||
|
@ -698,9 +698,9 @@ impl fmt::Display for clean::ImportSource {
|
||||||
_ => {
|
_ => {
|
||||||
for (i, seg) in self.path.segments.iter().enumerate() {
|
for (i, seg) in self.path.segments.iter().enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
try!(write!(f, "::"))
|
write!(f, "::")?
|
||||||
}
|
}
|
||||||
try!(write!(f, "{}", seg.name));
|
write!(f, "{}", seg.name)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -713,13 +713,13 @@ impl fmt::Display for clean::ViewListIdent {
|
||||||
match self.source {
|
match self.source {
|
||||||
Some(did) => {
|
Some(did) => {
|
||||||
let path = clean::Path::singleton(self.name.clone());
|
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 {
|
if let Some(ref name) = self.rename {
|
||||||
try!(write!(f, " as {}", name));
|
write!(f, " as {}", name)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -48,12 +48,12 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
|
||||||
out: &mut Write) -> io::Result<()> {
|
out: &mut Write) -> io::Result<()> {
|
||||||
use syntax::parse::lexer::Reader;
|
use syntax::parse::lexer::Reader;
|
||||||
|
|
||||||
try!(write!(out, "<pre "));
|
write!(out, "<pre ")?;
|
||||||
match id {
|
match id {
|
||||||
Some(id) => try!(write!(out, "id='{}' ", id)),
|
Some(id) => write!(out, "id='{}' ", id)?,
|
||||||
None => {}
|
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_attribute = false;
|
||||||
let mut is_macro = false;
|
let mut is_macro = false;
|
||||||
let mut is_macro_nonterminal = 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 {
|
let klass = match next.tok {
|
||||||
token::Whitespace => {
|
token::Whitespace => {
|
||||||
try!(write!(out, "{}", Escape(&snip(next.sp))));
|
write!(out, "{}", Escape(&snip(next.sp)))?;
|
||||||
continue
|
continue
|
||||||
},
|
},
|
||||||
token::Comment => {
|
token::Comment => {
|
||||||
try!(write!(out, "<span class='comment'>{}</span>",
|
write!(out, "<span class='comment'>{}</span>",
|
||||||
Escape(&snip(next.sp))));
|
Escape(&snip(next.sp)))?;
|
||||||
continue
|
continue
|
||||||
},
|
},
|
||||||
token::Shebang(s) => {
|
token::Shebang(s) => {
|
||||||
try!(write!(out, "{}", Escape(&s.as_str())));
|
write!(out, "{}", Escape(&s.as_str()))?;
|
||||||
continue
|
continue
|
||||||
},
|
},
|
||||||
// If this '&' token is directly adjacent to another token, assume
|
// 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 ']'.
|
// span when we see the ']'.
|
||||||
token::Pound => {
|
token::Pound => {
|
||||||
is_attribute = true;
|
is_attribute = true;
|
||||||
try!(write!(out, r"<span class='attribute'>#"));
|
write!(out, r"<span class='attribute'>#")?;
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
token::CloseDelim(token::Bracket) => {
|
token::CloseDelim(token::Bracket) => {
|
||||||
if is_attribute {
|
if is_attribute {
|
||||||
is_attribute = false;
|
is_attribute = false;
|
||||||
try!(write!(out, "]</span>"));
|
write!(out, "]</span>")?;
|
||||||
continue
|
continue
|
||||||
} else {
|
} else {
|
||||||
""
|
""
|
||||||
|
@ -178,10 +178,10 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
|
||||||
// stringifying this token
|
// stringifying this token
|
||||||
let snip = sess.codemap().span_to_snippet(next.sp).unwrap();
|
let snip = sess.codemap().span_to_snippet(next.sp).unwrap();
|
||||||
if klass == "" {
|
if klass == "" {
|
||||||
try!(write!(out, "{}", Escape(&snip)));
|
write!(out, "{}", Escape(&snip))?;
|
||||||
} else {
|
} else {
|
||||||
try!(write!(out, "<span class='{}'>{}</span>", klass,
|
write!(out, "<span class='{}'>{}</span>", klass,
|
||||||
Escape(&snip)));
|
Escape(&snip))?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -183,15 +183,15 @@ impl fmt::Debug for Toc {
|
||||||
|
|
||||||
impl fmt::Display for Toc {
|
impl fmt::Display for Toc {
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||||
try!(write!(fmt, "<ul>"));
|
write!(fmt, "<ul>")?;
|
||||||
for entry in &self.entries {
|
for entry in &self.entries {
|
||||||
// recursively format this table of contents (the
|
// recursively format this table of contents (the
|
||||||
// `{children}` is the key).
|
// `{children}` is the key).
|
||||||
try!(write!(fmt,
|
write!(fmt,
|
||||||
"\n<li><a href=\"#{id}\">{num} {name}</a>{children}</li>",
|
"\n<li><a href=\"#{id}\">{num} {name}</a>{children}</li>",
|
||||||
id = entry.id,
|
id = entry.id,
|
||||||
num = entry.sec_number, name = entry.name,
|
num = entry.sec_number, name = entry.name,
|
||||||
children = entry.children))
|
children = entry.children)?
|
||||||
}
|
}
|
||||||
write!(fmt, "</ul>")
|
write!(fmt, "</ul>")
|
||||||
}
|
}
|
||||||
|
|
|
@ -332,10 +332,10 @@ fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
|
||||||
let mut externs = HashMap::new();
|
let mut externs = HashMap::new();
|
||||||
for arg in &matches.opt_strs("extern") {
|
for arg in &matches.opt_strs("extern") {
|
||||||
let mut parts = arg.splitn(2, '=');
|
let mut parts = arg.splitn(2, '=');
|
||||||
let name = try!(parts.next().ok_or("--extern value must not be empty".to_string()));
|
let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
|
||||||
let location = try!(parts.next()
|
let location = parts.next()
|
||||||
.ok_or("--extern value must be of the format `foo=bar`"
|
.ok_or("--extern value must be of the format `foo=bar`"
|
||||||
.to_string()));
|
.to_string())?;
|
||||||
let name = name.to_string();
|
let name = name.to_string();
|
||||||
externs.entry(name).or_insert(vec![]).push(location.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("crate".to_string(), crate_json);
|
||||||
json.insert("plugins".to_string(), Json::Object(plugins_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))
|
write!(&mut file, "{}", Json::Object(json))
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,7 +23,7 @@ impl<
|
||||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
||||||
s.emit_seq(self.len(), |s| {
|
s.emit_seq(self.len(), |s| {
|
||||||
for (i, e) in self.iter().enumerate() {
|
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(())
|
Ok(())
|
||||||
})
|
})
|
||||||
|
@ -35,7 +35,7 @@ impl<T:Decodable> Decodable for LinkedList<T> {
|
||||||
d.read_seq(|d, len| {
|
d.read_seq(|d, len| {
|
||||||
let mut list = LinkedList::new();
|
let mut list = LinkedList::new();
|
||||||
for i in 0..len {
|
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)
|
Ok(list)
|
||||||
})
|
})
|
||||||
|
@ -46,7 +46,7 @@ impl<T: Encodable> Encodable for VecDeque<T> {
|
||||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
||||||
s.emit_seq(self.len(), |s| {
|
s.emit_seq(self.len(), |s| {
|
||||||
for (i, e) in self.iter().enumerate() {
|
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(())
|
Ok(())
|
||||||
})
|
})
|
||||||
|
@ -58,7 +58,7 @@ impl<T:Decodable> Decodable for VecDeque<T> {
|
||||||
d.read_seq(|d, len| {
|
d.read_seq(|d, len| {
|
||||||
let mut deque: VecDeque<T> = VecDeque::new();
|
let mut deque: VecDeque<T> = VecDeque::new();
|
||||||
for i in 0..len {
|
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)
|
Ok(deque)
|
||||||
})
|
})
|
||||||
|
@ -73,8 +73,8 @@ impl<
|
||||||
e.emit_map(self.len(), |e| {
|
e.emit_map(self.len(), |e| {
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
for (key, val) in self {
|
for (key, val) in self {
|
||||||
try!(e.emit_map_elt_key(i, |e| key.encode(e)));
|
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_val(i, |e| val.encode(e))?;
|
||||||
i += 1;
|
i += 1;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -90,8 +90,8 @@ impl<
|
||||||
d.read_map(|d, len| {
|
d.read_map(|d, len| {
|
||||||
let mut map = BTreeMap::new();
|
let mut map = BTreeMap::new();
|
||||||
for i in 0..len {
|
for i in 0..len {
|
||||||
let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
|
let key = d.read_map_elt_key(i, |d| Decodable::decode(d))?;
|
||||||
let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d)));
|
let val = d.read_map_elt_val(i, |d| Decodable::decode(d))?;
|
||||||
map.insert(key, val);
|
map.insert(key, val);
|
||||||
}
|
}
|
||||||
Ok(map)
|
Ok(map)
|
||||||
|
@ -106,7 +106,7 @@ impl<
|
||||||
s.emit_seq(self.len(), |s| {
|
s.emit_seq(self.len(), |s| {
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
for e in self {
|
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;
|
i += 1;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -121,7 +121,7 @@ impl<
|
||||||
d.read_seq(|d, len| {
|
d.read_seq(|d, len| {
|
||||||
let mut set = BTreeSet::new();
|
let mut set = BTreeSet::new();
|
||||||
for i in 0..len {
|
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)
|
Ok(set)
|
||||||
})
|
})
|
||||||
|
@ -144,7 +144,7 @@ impl<
|
||||||
T: Decodable + CLike
|
T: Decodable + CLike
|
||||||
> Decodable for EnumSet<T> {
|
> Decodable for EnumSet<T> {
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<EnumSet<T>, D::Error> {
|
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();
|
let mut set = EnumSet::new();
|
||||||
for bit in 0..(mem::size_of::<usize>()*8) {
|
for bit in 0..(mem::size_of::<usize>()*8) {
|
||||||
if bits & (1 << bit) != 0 {
|
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| {
|
e.emit_map(self.len(), |e| {
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
for (key, val) in self {
|
for (key, val) in self {
|
||||||
try!(e.emit_map_elt_key(i, |e| key.encode(e)));
|
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_val(i, |e| val.encode(e))?;
|
||||||
i += 1;
|
i += 1;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -183,8 +183,8 @@ impl<K, V, S> Decodable for HashMap<K, V, S>
|
||||||
let state = Default::default();
|
let state = Default::default();
|
||||||
let mut map = HashMap::with_capacity_and_hasher(len, state);
|
let mut map = HashMap::with_capacity_and_hasher(len, state);
|
||||||
for i in 0..len {
|
for i in 0..len {
|
||||||
let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
|
let key = d.read_map_elt_key(i, |d| Decodable::decode(d))?;
|
||||||
let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d)));
|
let val = d.read_map_elt_val(i, |d| Decodable::decode(d))?;
|
||||||
map.insert(key, val);
|
map.insert(key, val);
|
||||||
}
|
}
|
||||||
Ok(map)
|
Ok(map)
|
||||||
|
@ -200,7 +200,7 @@ impl<T, S> Encodable for HashSet<T, S>
|
||||||
s.emit_seq(self.len(), |s| {
|
s.emit_seq(self.len(), |s| {
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
for e in self {
|
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;
|
i += 1;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -217,7 +217,7 @@ impl<T, S> Decodable for HashSet<T, S>
|
||||||
let state = Default::default();
|
let state = Default::default();
|
||||||
let mut set = HashSet::with_capacity_and_hasher(len, state);
|
let mut set = HashSet::with_capacity_and_hasher(len, state);
|
||||||
for i in 0..len {
|
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)
|
Ok(set)
|
||||||
})
|
})
|
||||||
|
|
|
@ -319,7 +319,7 @@ pub fn encode<T: ::Encodable>(object: &T) -> Result<string::String, EncoderError
|
||||||
let mut s = String::new();
|
let mut s = String::new();
|
||||||
{
|
{
|
||||||
let mut encoder = Encoder::new(&mut s);
|
let mut encoder = Encoder::new(&mut s);
|
||||||
try!(object.encode(&mut encoder));
|
object.encode(&mut encoder)?;
|
||||||
}
|
}
|
||||||
Ok(s)
|
Ok(s)
|
||||||
}
|
}
|
||||||
|
@ -371,7 +371,7 @@ pub type EncodeResult = Result<(), EncoderError>;
|
||||||
pub type DecodeResult<T> = Result<T, DecoderError>;
|
pub type DecodeResult<T> = Result<T, DecoderError>;
|
||||||
|
|
||||||
fn escape_str(wr: &mut fmt::Write, v: &str) -> EncodeResult {
|
fn escape_str(wr: &mut fmt::Write, v: &str) -> EncodeResult {
|
||||||
try!(wr.write_str("\""));
|
wr.write_str("\"")?;
|
||||||
|
|
||||||
let mut start = 0;
|
let mut start = 0;
|
||||||
|
|
||||||
|
@ -416,19 +416,19 @@ fn escape_str(wr: &mut fmt::Write, v: &str) -> EncodeResult {
|
||||||
};
|
};
|
||||||
|
|
||||||
if start < i {
|
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;
|
start = i + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if start != v.len() {
|
if start != v.len() {
|
||||||
try!(wr.write_str(&v[start..]));
|
wr.write_str(&v[start..])?;
|
||||||
}
|
}
|
||||||
|
|
||||||
try!(wr.write_str("\""));
|
wr.write_str("\"")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -442,12 +442,12 @@ fn spaces(wr: &mut fmt::Write, mut n: usize) -> EncodeResult {
|
||||||
const BUF: &'static str = " ";
|
const BUF: &'static str = " ";
|
||||||
|
|
||||||
while n >= BUF.len() {
|
while n >= BUF.len() {
|
||||||
try!(wr.write_str(BUF));
|
wr.write_str(BUF)?;
|
||||||
n -= BUF.len();
|
n -= BUF.len();
|
||||||
}
|
}
|
||||||
|
|
||||||
if n > 0 {
|
if n > 0 {
|
||||||
try!(wr.write_str(&BUF[..n]));
|
wr.write_str(&BUF[..n])?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -491,7 +491,7 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
|
|
||||||
fn emit_nil(&mut self) -> EncodeResult {
|
fn emit_nil(&mut self) -> EncodeResult {
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
try!(write!(self.writer, "null"));
|
write!(self.writer, "null")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -510,9 +510,9 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
fn emit_bool(&mut self, v: bool) -> EncodeResult {
|
fn emit_bool(&mut self, v: bool) -> EncodeResult {
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if v {
|
if v {
|
||||||
try!(write!(self.writer, "true"));
|
write!(self.writer, "true")?;
|
||||||
} else {
|
} else {
|
||||||
try!(write!(self.writer, "false"));
|
write!(self.writer, "false")?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -551,11 +551,11 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
escape_str(self.writer, name)
|
escape_str(self.writer, name)
|
||||||
} else {
|
} else {
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
try!(write!(self.writer, "{{\"variant\":"));
|
write!(self.writer, "{{\"variant\":")?;
|
||||||
try!(escape_str(self.writer, name));
|
escape_str(self.writer, name)?;
|
||||||
try!(write!(self.writer, ",\"fields\":["));
|
write!(self.writer, ",\"fields\":[")?;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
try!(write!(self.writer, "]}}"));
|
write!(self.writer, "]}}")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -565,7 +565,7 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if idx != 0 {
|
if idx != 0 {
|
||||||
try!(write!(self.writer, ","));
|
write!(self.writer, ",")?;
|
||||||
}
|
}
|
||||||
f(self)
|
f(self)
|
||||||
}
|
}
|
||||||
|
@ -595,9 +595,9 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
try!(write!(self.writer, "{{"));
|
write!(self.writer, "{{")?;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
try!(write!(self.writer, "}}"));
|
write!(self.writer, "}}")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -605,9 +605,9 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if idx != 0 { try!(write!(self.writer, ",")); }
|
if idx != 0 { write!(self.writer, ",")?; }
|
||||||
try!(escape_str(self.writer, name));
|
escape_str(self.writer, name)?;
|
||||||
try!(write!(self.writer, ":"));
|
write!(self.writer, ":")?;
|
||||||
f(self)
|
f(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -658,9 +658,9 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
try!(write!(self.writer, "["));
|
write!(self.writer, "[")?;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
try!(write!(self.writer, "]"));
|
write!(self.writer, "]")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -669,7 +669,7 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if idx != 0 {
|
if idx != 0 {
|
||||||
try!(write!(self.writer, ","));
|
write!(self.writer, ",")?;
|
||||||
}
|
}
|
||||||
f(self)
|
f(self)
|
||||||
}
|
}
|
||||||
|
@ -678,9 +678,9 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
try!(write!(self.writer, "{{"));
|
write!(self.writer, "{{")?;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
try!(write!(self.writer, "}}"));
|
write!(self.writer, "}}")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -688,9 +688,9 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
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;
|
self.is_emitting_map_key = true;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.is_emitting_map_key = false;
|
self.is_emitting_map_key = false;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -699,7 +699,7 @@ impl<'a> ::Encoder for Encoder<'a> {
|
||||||
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
try!(write!(self.writer, ":"));
|
write!(self.writer, ":")?;
|
||||||
f(self)
|
f(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -739,7 +739,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
|
|
||||||
fn emit_nil(&mut self) -> EncodeResult {
|
fn emit_nil(&mut self) -> EncodeResult {
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
try!(write!(self.writer, "null"));
|
write!(self.writer, "null")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -758,9 +758,9 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
fn emit_bool(&mut self, v: bool) -> EncodeResult {
|
fn emit_bool(&mut self, v: bool) -> EncodeResult {
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if v {
|
if v {
|
||||||
try!(write!(self.writer, "true"));
|
write!(self.writer, "true")?;
|
||||||
} else {
|
} else {
|
||||||
try!(write!(self.writer, "false"));
|
write!(self.writer, "false")?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -797,23 +797,23 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
escape_str(self.writer, name)
|
escape_str(self.writer, name)
|
||||||
} else {
|
} else {
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
try!(write!(self.writer, "{{\n"));
|
write!(self.writer, "{{\n")?;
|
||||||
self.curr_indent += self.indent;
|
self.curr_indent += self.indent;
|
||||||
try!(spaces(self.writer, self.curr_indent));
|
spaces(self.writer, self.curr_indent)?;
|
||||||
try!(write!(self.writer, "\"variant\": "));
|
write!(self.writer, "\"variant\": ")?;
|
||||||
try!(escape_str(self.writer, name));
|
escape_str(self.writer, name)?;
|
||||||
try!(write!(self.writer, ",\n"));
|
write!(self.writer, ",\n")?;
|
||||||
try!(spaces(self.writer, self.curr_indent));
|
spaces(self.writer, self.curr_indent)?;
|
||||||
try!(write!(self.writer, "\"fields\": [\n"));
|
write!(self.writer, "\"fields\": [\n")?;
|
||||||
self.curr_indent += self.indent;
|
self.curr_indent += self.indent;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.curr_indent -= self.indent;
|
self.curr_indent -= self.indent;
|
||||||
try!(write!(self.writer, "\n"));
|
write!(self.writer, "\n")?;
|
||||||
try!(spaces(self.writer, self.curr_indent));
|
spaces(self.writer, self.curr_indent)?;
|
||||||
self.curr_indent -= self.indent;
|
self.curr_indent -= self.indent;
|
||||||
try!(write!(self.writer, "]\n"));
|
write!(self.writer, "]\n")?;
|
||||||
try!(spaces(self.writer, self.curr_indent));
|
spaces(self.writer, self.curr_indent)?;
|
||||||
try!(write!(self.writer, "}}"));
|
write!(self.writer, "}}")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -823,9 +823,9 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if idx != 0 {
|
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)
|
f(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -856,15 +856,15 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if len == 0 {
|
if len == 0 {
|
||||||
try!(write!(self.writer, "{{}}"));
|
write!(self.writer, "{{}}")?;
|
||||||
} else {
|
} else {
|
||||||
try!(write!(self.writer, "{{"));
|
write!(self.writer, "{{")?;
|
||||||
self.curr_indent += self.indent;
|
self.curr_indent += self.indent;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.curr_indent -= self.indent;
|
self.curr_indent -= self.indent;
|
||||||
try!(write!(self.writer, "\n"));
|
write!(self.writer, "\n")?;
|
||||||
try!(spaces(self.writer, self.curr_indent));
|
spaces(self.writer, self.curr_indent)?;
|
||||||
try!(write!(self.writer, "}}"));
|
write!(self.writer, "}}")?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -874,13 +874,13 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if idx == 0 {
|
if idx == 0 {
|
||||||
try!(write!(self.writer, "\n"));
|
write!(self.writer, "\n")?;
|
||||||
} else {
|
} else {
|
||||||
try!(write!(self.writer, ",\n"));
|
write!(self.writer, ",\n")?;
|
||||||
}
|
}
|
||||||
try!(spaces(self.writer, self.curr_indent));
|
spaces(self.writer, self.curr_indent)?;
|
||||||
try!(escape_str(self.writer, name));
|
escape_str(self.writer, name)?;
|
||||||
try!(write!(self.writer, ": "));
|
write!(self.writer, ": ")?;
|
||||||
f(self)
|
f(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -932,15 +932,15 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if len == 0 {
|
if len == 0 {
|
||||||
try!(write!(self.writer, "[]"));
|
write!(self.writer, "[]")?;
|
||||||
} else {
|
} else {
|
||||||
try!(write!(self.writer, "["));
|
write!(self.writer, "[")?;
|
||||||
self.curr_indent += self.indent;
|
self.curr_indent += self.indent;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.curr_indent -= self.indent;
|
self.curr_indent -= self.indent;
|
||||||
try!(write!(self.writer, "\n"));
|
write!(self.writer, "\n")?;
|
||||||
try!(spaces(self.writer, self.curr_indent));
|
spaces(self.writer, self.curr_indent)?;
|
||||||
try!(write!(self.writer, "]"));
|
write!(self.writer, "]")?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -950,11 +950,11 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if idx == 0 {
|
if idx == 0 {
|
||||||
try!(write!(self.writer, "\n"));
|
write!(self.writer, "\n")?;
|
||||||
} else {
|
} 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)
|
f(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -963,15 +963,15 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if len == 0 {
|
if len == 0 {
|
||||||
try!(write!(self.writer, "{{}}"));
|
write!(self.writer, "{{}}")?;
|
||||||
} else {
|
} else {
|
||||||
try!(write!(self.writer, "{{"));
|
write!(self.writer, "{{")?;
|
||||||
self.curr_indent += self.indent;
|
self.curr_indent += self.indent;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.curr_indent -= self.indent;
|
self.curr_indent -= self.indent;
|
||||||
try!(write!(self.writer, "\n"));
|
write!(self.writer, "\n")?;
|
||||||
try!(spaces(self.writer, self.curr_indent));
|
spaces(self.writer, self.curr_indent)?;
|
||||||
try!(write!(self.writer, "}}"));
|
write!(self.writer, "}}")?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -981,13 +981,13 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
if idx == 0 {
|
if idx == 0 {
|
||||||
try!(write!(self.writer, "\n"));
|
write!(self.writer, "\n")?;
|
||||||
} else {
|
} 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;
|
self.is_emitting_map_key = true;
|
||||||
try!(f(self));
|
f(self)?;
|
||||||
self.is_emitting_map_key = false;
|
self.is_emitting_map_key = false;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -996,7 +996,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
|
||||||
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
|
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
|
||||||
{
|
{
|
||||||
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
|
||||||
try!(write!(self.writer, ": "));
|
write!(self.writer, ": ")?;
|
||||||
f(self)
|
f(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1695,7 +1695,7 @@ impl<T: Iterator<Item=char>> Parser<T> {
|
||||||
'n' => res.push('\n'),
|
'n' => res.push('\n'),
|
||||||
'r' => res.push('\r'),
|
'r' => res.push('\r'),
|
||||||
't' => res.push('\t'),
|
't' => res.push('\t'),
|
||||||
'u' => match try!(self.decode_hex_escape()) {
|
'u' => match self.decode_hex_escape()? {
|
||||||
0xDC00 ... 0xDFFF => {
|
0xDC00 ... 0xDFFF => {
|
||||||
return self.error(LoneLeadingSurrogateInHexEscape)
|
return self.error(LoneLeadingSurrogateInHexEscape)
|
||||||
}
|
}
|
||||||
|
@ -1708,7 +1708,7 @@ impl<T: Iterator<Item=char>> Parser<T> {
|
||||||
_ => return self.error(UnexpectedEndOfHexEscape),
|
_ => return self.error(UnexpectedEndOfHexEscape),
|
||||||
}
|
}
|
||||||
|
|
||||||
let n2 = try!(self.decode_hex_escape());
|
let n2 = self.decode_hex_escape()?;
|
||||||
if n2 < 0xDC00 || n2 > 0xDFFF {
|
if n2 < 0xDC00 || n2 > 0xDFFF {
|
||||||
return self.error(LoneLeadingSurrogateInHexEscape)
|
return self.error(LoneLeadingSurrogateInHexEscape)
|
||||||
}
|
}
|
||||||
|
@ -2174,7 +2174,7 @@ impl ::Decoder for Decoder {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_char(&mut self) -> DecodeResult<char> {
|
fn read_char(&mut self) -> DecodeResult<char> {
|
||||||
let s = try!(self.read_str());
|
let s = self.read_str()?;
|
||||||
{
|
{
|
||||||
let mut it = s.chars();
|
let mut it = s.chars();
|
||||||
match (it.next(), it.next()) {
|
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
|
fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T> where
|
||||||
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
|
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
|
||||||
{
|
{
|
||||||
let value = try!(f(self));
|
let value = f(self)?;
|
||||||
self.pop();
|
self.pop();
|
||||||
Ok(value)
|
Ok(value)
|
||||||
}
|
}
|
||||||
|
@ -2276,7 +2276,7 @@ impl ::Decoder for Decoder {
|
||||||
-> DecodeResult<T> where
|
-> DecodeResult<T> where
|
||||||
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
|
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()) {
|
let value = match obj.remove(&name.to_string()) {
|
||||||
None => {
|
None => {
|
||||||
|
@ -2290,7 +2290,7 @@ impl ::Decoder for Decoder {
|
||||||
},
|
},
|
||||||
Some(json) => {
|
Some(json) => {
|
||||||
self.stack.push(json);
|
self.stack.push(json);
|
||||||
try!(f(self))
|
f(self)?
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
self.stack.push(Json::Object(obj));
|
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
|
fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
|
||||||
F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
|
F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
|
||||||
{
|
{
|
||||||
let array = try!(expect!(self.pop(), Array));
|
let array = expect!(self.pop(), Array)?;
|
||||||
let len = array.len();
|
let len = array.len();
|
||||||
for v in array.into_iter().rev() {
|
for v in array.into_iter().rev() {
|
||||||
self.stack.push(v);
|
self.stack.push(v);
|
||||||
|
@ -2363,7 +2363,7 @@ impl ::Decoder for Decoder {
|
||||||
fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
|
fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
|
||||||
F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
|
F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
|
||||||
{
|
{
|
||||||
let obj = try!(expect!(self.pop(), Object));
|
let obj = expect!(self.pop(), Object)?;
|
||||||
let len = obj.len();
|
let len = obj.len();
|
||||||
for (key, value) in obj {
|
for (key, value) in obj {
|
||||||
self.stack.push(value);
|
self.stack.push(value);
|
||||||
|
|
|
@ -410,13 +410,13 @@ impl<T: ?Sized + Encodable> Encodable for Box<T> {
|
||||||
|
|
||||||
impl< T: Decodable> Decodable for Box<T> {
|
impl< T: Decodable> Decodable for Box<T> {
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
|
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]> {
|
impl< T: Decodable> Decodable for Box<[T]> {
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
|
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())
|
Ok(v.into_boxed_slice())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -431,7 +431,7 @@ impl<T:Encodable> Encodable for Rc<T> {
|
||||||
impl<T:Decodable> Decodable for Rc<T> {
|
impl<T:Decodable> Decodable for Rc<T> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
|
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> {
|
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
||||||
s.emit_seq(self.len(), |s| {
|
s.emit_seq(self.len(), |s| {
|
||||||
for (i, e) in self.iter().enumerate() {
|
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(())
|
Ok(())
|
||||||
})
|
})
|
||||||
|
@ -450,7 +450,7 @@ impl<T:Encodable> Encodable for Vec<T> {
|
||||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
||||||
s.emit_seq(self.len(), |s| {
|
s.emit_seq(self.len(), |s| {
|
||||||
for (i, e) in self.iter().enumerate() {
|
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(())
|
Ok(())
|
||||||
})
|
})
|
||||||
|
@ -462,7 +462,7 @@ impl<T:Decodable> Decodable for Vec<T> {
|
||||||
d.read_seq(|d, len| {
|
d.read_seq(|d, len| {
|
||||||
let mut v = Vec::with_capacity(len);
|
let mut v = Vec::with_capacity(len);
|
||||||
for i in 0..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)
|
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> {
|
fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
|
||||||
d.read_option(|d, b| {
|
d.read_option(|d, b| {
|
||||||
if b {
|
if b {
|
||||||
Ok(Some(try!(Decodable::decode(d))))
|
Ok(Some(Decodable::decode(d)?))
|
||||||
} else {
|
} else {
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
|
@ -546,7 +546,7 @@ impl Encodable for path::PathBuf {
|
||||||
|
|
||||||
impl Decodable for path::PathBuf {
|
impl Decodable for path::PathBuf {
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
|
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))
|
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> {
|
impl<T: Decodable + Copy> Decodable for Cell<T> {
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
|
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> {
|
impl<T: Decodable> Decodable for RefCell<T> {
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
|
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> {
|
impl<T:Decodable+Send+Sync> Decodable for Arc<T> {
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
|
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| {
|
self.emit_seq(v.len(), |this| {
|
||||||
for (i, e) in v.iter().enumerate() {
|
for (i, e) in v.iter().enumerate() {
|
||||||
try!(this.emit_seq_elt(i, |this| {
|
this.emit_seq_elt(i, |this| {
|
||||||
f(this, e)
|
f(this, e)
|
||||||
}));
|
})?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
|
@ -629,7 +629,7 @@ impl<D: Decoder> DecoderHelpers for D {
|
||||||
self.read_seq(|this, len| {
|
self.read_seq(|this, len| {
|
||||||
let mut v = Vec::with_capacity(len);
|
let mut v = Vec::with_capacity(len);
|
||||||
for i in 0..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)
|
Ok(v)
|
||||||
})
|
})
|
||||||
|
|
|
@ -318,9 +318,9 @@ impl From<CString> for Vec<u8> {
|
||||||
#[stable(feature = "cstr_debug", since = "1.3.0")]
|
#[stable(feature = "cstr_debug", since = "1.3.0")]
|
||||||
impl fmt::Debug for CStr {
|
impl fmt::Debug for CStr {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
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)) {
|
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, "\"")
|
write!(f, "\"")
|
||||||
}
|
}
|
||||||
|
|
|
@ -305,7 +305,7 @@ impl File {
|
||||||
#[unstable(feature = "file_try_clone", reason = "newly added", issue = "31405")]
|
#[unstable(feature = "file_try_clone", reason = "newly added", issue = "31405")]
|
||||||
pub fn try_clone(&self) -> io::Result<File> {
|
pub fn try_clone(&self) -> io::Result<File> {
|
||||||
Ok(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> {
|
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 })
|
Ok(File { inner: inner })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1440,7 +1440,7 @@ impl DirBuilder {
|
||||||
fn create_dir_all(&self, path: &Path) -> io::Result<()> {
|
fn create_dir_all(&self, path: &Path) -> io::Result<()> {
|
||||||
if path == Path::new("") || path.is_dir() { return Ok(()) }
|
if path == Path::new("") || path.is_dir() { return Ok(()) }
|
||||||
if let Some(p) = path.parent() {
|
if let Some(p) = path.parent() {
|
||||||
try!(self.create_dir_all(p))
|
self.create_dir_all(p)?
|
||||||
}
|
}
|
||||||
self.inner.mkdir(path)
|
self.inner.mkdir(path)
|
||||||
}
|
}
|
||||||
|
|
|
@ -172,8 +172,8 @@ impl<R: Read> Read for BufReader<R> {
|
||||||
return self.inner.read(buf);
|
return self.inner.read(buf);
|
||||||
}
|
}
|
||||||
let nread = {
|
let nread = {
|
||||||
let mut rem = try!(self.fill_buf());
|
let mut rem = self.fill_buf()?;
|
||||||
try!(rem.read(buf))
|
rem.read(buf)?
|
||||||
};
|
};
|
||||||
self.consume(nread);
|
self.consume(nread);
|
||||||
Ok(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
|
// If we've reached the end of our internal buffer then we need to fetch
|
||||||
// some more data from the underlying reader.
|
// some more data from the underlying reader.
|
||||||
if self.pos == self.cap {
|
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;
|
self.pos = 0;
|
||||||
}
|
}
|
||||||
Ok(&self.buf[self.pos..self.cap])
|
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
|
// support seeking by i64::min_value() so we need to handle underflow when subtracting
|
||||||
// remainder.
|
// remainder.
|
||||||
if let Some(offset) = n.checked_sub(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 {
|
} else {
|
||||||
// seek backwards by our remainder, and then by the offset
|
// 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
|
self.pos = self.cap; // empty the buffer
|
||||||
result = try!(self.inner.seek(SeekFrom::Current(n)));
|
result = self.inner.seek(SeekFrom::Current(n))?;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Seeking with Start/End doesn't care about our buffer length.
|
// 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
|
self.pos = self.cap; // empty the buffer
|
||||||
Ok(result)
|
Ok(result)
|
||||||
|
@ -461,7 +461,7 @@ impl<W: Write> BufWriter<W> {
|
||||||
impl<W: Write> Write for BufWriter<W> {
|
impl<W: Write> Write for BufWriter<W> {
|
||||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||||
if self.buf.len() + buf.len() > self.buf.capacity() {
|
if self.buf.len() + buf.len() > self.buf.capacity() {
|
||||||
try!(self.flush_buf());
|
self.flush_buf()?;
|
||||||
}
|
}
|
||||||
if buf.len() >= self.buf.capacity() {
|
if buf.len() >= self.buf.capacity() {
|
||||||
self.panicked = true;
|
self.panicked = true;
|
||||||
|
@ -761,7 +761,7 @@ impl<W: Write> Write for LineWriter<W> {
|
||||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||||
match memchr::memrchr(b'\n', buf) {
|
match memchr::memrchr(b'\n', buf) {
|
||||||
Some(i) => {
|
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() {
|
if n != i + 1 || self.inner.flush().is_err() {
|
||||||
// Do not return errors on partial writes.
|
// Do not return errors on partial writes.
|
||||||
return Ok(n);
|
return Ok(n);
|
||||||
|
|
|
@ -213,7 +213,7 @@ impl<T> io::Seek for Cursor<T> where T: AsRef<[u8]> {
|
||||||
#[stable(feature = "rust1", since = "1.0.0")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
impl<T> Read for Cursor<T> where T: AsRef<[u8]> {
|
impl<T> Read for Cursor<T> where T: AsRef<[u8]> {
|
||||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
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;
|
self.pos += n as u64;
|
||||||
Ok(n)
|
Ok(n)
|
||||||
}
|
}
|
||||||
|
@ -232,7 +232,7 @@ impl<T> BufRead for Cursor<T> where T: AsRef<[u8]> {
|
||||||
impl<'a> Write for Cursor<&'a mut [u8]> {
|
impl<'a> Write for Cursor<&'a mut [u8]> {
|
||||||
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
|
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
|
||||||
let pos = cmp::min(self.pos, self.inner.len() as u64);
|
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;
|
self.pos += amt as u64;
|
||||||
Ok(amt)
|
Ok(amt)
|
||||||
}
|
}
|
||||||
|
@ -271,7 +271,7 @@ impl Write for Cursor<Vec<u8>> {
|
||||||
impl Write for Cursor<Box<[u8]>> {
|
impl Write for Cursor<Box<[u8]>> {
|
||||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||||
let pos = cmp::min(self.pos, self.inner.len() as u64);
|
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;
|
self.pos += amt as u64;
|
||||||
Ok(amt)
|
Ok(amt)
|
||||||
}
|
}
|
||||||
|
|
|
@ -196,7 +196,7 @@ impl<'a> Write for &'a mut [u8] {
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
||||||
if try!(self.write(data)) == data.len() {
|
if self.write(data)? == data.len() {
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"))
|
Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"))
|
||||||
|
|
|
@ -1433,7 +1433,7 @@ pub struct Chain<T, U> {
|
||||||
impl<T: Read, U: Read> Read for Chain<T, U> {
|
impl<T: Read, U: Read> Read for Chain<T, U> {
|
||||||
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
|
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
|
||||||
if !self.done_first {
|
if !self.done_first {
|
||||||
match try!(self.first.read(buf)) {
|
match self.first.read(buf)? {
|
||||||
0 => { self.done_first = true; }
|
0 => { self.done_first = true; }
|
||||||
n => return Ok(n),
|
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 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;
|
self.limit -= n as u64;
|
||||||
Ok(n)
|
Ok(n)
|
||||||
}
|
}
|
||||||
|
@ -1484,7 +1484,7 @@ impl<T: Read> Read for Take<T> {
|
||||||
#[stable(feature = "rust1", since = "1.0.0")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
impl<T: BufRead> BufRead for Take<T> {
|
impl<T: BufRead> BufRead for Take<T> {
|
||||||
fn fill_buf(&mut self) -> Result<&[u8]> {
|
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;
|
let cap = cmp::min(buf.len() as u64, self.limit) as usize;
|
||||||
Ok(&buf[..cap])
|
Ok(&buf[..cap])
|
||||||
}
|
}
|
||||||
|
|
|
@ -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(ref e) if e.kind() == ErrorKind::Interrupted => continue,
|
||||||
Err(e) => return Err(e),
|
Err(e) => return Err(e),
|
||||||
};
|
};
|
||||||
try!(writer.write_all(&buf[..len]));
|
writer.write_all(&buf[..len])?;
|
||||||
written += len as u64;
|
written += len as u64;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -431,13 +431,13 @@ impl ToSocketAddrs for (Ipv6Addr, u16) {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
|
fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
|
||||||
let ips = try!(lookup_host(s));
|
let ips = lookup_host(s)?;
|
||||||
let v: Vec<_> = try!(ips.map(|a| {
|
let v: Vec<_> = ips.map(|a| {
|
||||||
a.map(|mut a| {
|
a.map(|mut a| {
|
||||||
a.set_port(p);
|
a.set_port(p);
|
||||||
a
|
a
|
||||||
})
|
})
|
||||||
}).collect());
|
}).collect()?;
|
||||||
Ok(v.into_iter())
|
Ok(v.into_iter())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -487,16 +487,16 @@ impl fmt::Display for Ipv6Addr {
|
||||||
if zeros_len > 1 {
|
if zeros_len > 1 {
|
||||||
fn fmt_subslice(segments: &[u16], fmt: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt_subslice(segments: &[u16], fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||||
if !segments.is_empty() {
|
if !segments.is_empty() {
|
||||||
try!(write!(fmt, "{:x}", segments[0]));
|
write!(fmt, "{:x}", segments[0])?;
|
||||||
for &seg in &segments[1..] {
|
for &seg in &segments[1..] {
|
||||||
try!(write!(fmt, ":{:x}", seg));
|
write!(fmt, ":{:x}", seg)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
try!(fmt_subslice(&self.segments()[..zeros_at], fmt));
|
fmt_subslice(&self.segments()[..zeros_at], fmt)?;
|
||||||
try!(fmt.write_str("::"));
|
fmt.write_str("::")?;
|
||||||
fmt_subslice(&self.segments()[zeros_at + zeros_len..], fmt)
|
fmt_subslice(&self.segments()[zeros_at + zeros_len..], fmt)
|
||||||
} else {
|
} else {
|
||||||
let &[a, b, c, d, e, f, g, h] = &self.segments();
|
let &[a, b, c, d, e, f, g, h] = &self.segments();
|
||||||
|
|
|
@ -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>
|
where F: FnMut(&SocketAddr) -> io::Result<T>
|
||||||
{
|
{
|
||||||
let mut last_err = None;
|
let mut last_err = None;
|
||||||
for addr in try!(addr.to_socket_addrs()) {
|
for addr in addr.to_socket_addrs()? {
|
||||||
match f(&addr) {
|
match f(&addr) {
|
||||||
Ok(l) => return Ok(l),
|
Ok(l) => return Ok(l),
|
||||||
Err(e) => last_err = Some(e),
|
Err(e) => last_err = Some(e),
|
||||||
|
|
|
@ -70,7 +70,7 @@ impl UdpSocket {
|
||||||
#[stable(feature = "rust1", since = "1.0.0")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A)
|
pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A)
|
||||||
-> io::Result<usize> {
|
-> io::Result<usize> {
|
||||||
match try!(addr.to_socket_addrs()).next() {
|
match addr.to_socket_addrs()?.next() {
|
||||||
Some(addr) => self.0.send_to(buf, &addr),
|
Some(addr) => self.0.send_to(buf, &addr),
|
||||||
None => Err(Error::new(ErrorKind::InvalidInput,
|
None => Err(Error::new(ErrorKind::InvalidInput,
|
||||||
"no addresses to send data to")),
|
"no addresses to send data to")),
|
||||||
|
|
|
@ -315,7 +315,7 @@ pub fn recover<F: FnOnce() -> R + RecoverSafe, R>(f: F) -> Result<R> {
|
||||||
let mut result = None;
|
let mut result = None;
|
||||||
unsafe {
|
unsafe {
|
||||||
let result = &mut result;
|
let result = &mut result;
|
||||||
try!(unwind::try(move || *result = Some(f())))
|
unwind::try(move || *result = Some(f()))?
|
||||||
}
|
}
|
||||||
Ok(result.unwrap())
|
Ok(result.unwrap())
|
||||||
}
|
}
|
||||||
|
|
|
@ -520,7 +520,7 @@ impl Child {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let status = try!(self.wait());
|
let status = self.wait()?;
|
||||||
Ok(Output {
|
Ok(Output {
|
||||||
status: status,
|
status: status,
|
||||||
stdout: stdout,
|
stdout: stdout,
|
||||||
|
|
|
@ -234,7 +234,7 @@ impl<T: ?Sized> Mutex<T> {
|
||||||
pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
|
pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
|
||||||
unsafe {
|
unsafe {
|
||||||
if self.inner.lock.try_lock() {
|
if self.inner.lock.try_lock() {
|
||||||
Ok(try!(MutexGuard::new(&*self.inner, &self.data)))
|
Ok(MutexGuard::new(&*self.inner, &self.data)?)
|
||||||
} else {
|
} else {
|
||||||
Err(TryLockError::WouldBlock)
|
Err(TryLockError::WouldBlock)
|
||||||
}
|
}
|
||||||
|
@ -353,7 +353,7 @@ impl StaticMutex {
|
||||||
pub fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>> {
|
pub fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>> {
|
||||||
unsafe {
|
unsafe {
|
||||||
if self.lock.try_lock() {
|
if self.lock.try_lock() {
|
||||||
Ok(try!(MutexGuard::new(self, &DUMMY.0)))
|
Ok(MutexGuard::new(self, &DUMMY.0)?)
|
||||||
} else {
|
} else {
|
||||||
Err(TryLockError::WouldBlock)
|
Err(TryLockError::WouldBlock)
|
||||||
}
|
}
|
||||||
|
|
|
@ -205,7 +205,7 @@ impl<T: ?Sized> RwLock<T> {
|
||||||
pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<T>> {
|
pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<T>> {
|
||||||
unsafe {
|
unsafe {
|
||||||
if self.inner.lock.try_read() {
|
if self.inner.lock.try_read() {
|
||||||
Ok(try!(RwLockReadGuard::new(&*self.inner, &self.data)))
|
Ok(RwLockReadGuard::new(&*self.inner, &self.data)?)
|
||||||
} else {
|
} else {
|
||||||
Err(TryLockError::WouldBlock)
|
Err(TryLockError::WouldBlock)
|
||||||
}
|
}
|
||||||
|
@ -257,7 +257,7 @@ impl<T: ?Sized> RwLock<T> {
|
||||||
pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<T>> {
|
pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<T>> {
|
||||||
unsafe {
|
unsafe {
|
||||||
if self.inner.lock.try_write() {
|
if self.inner.lock.try_write() {
|
||||||
Ok(try!(RwLockWriteGuard::new(&*self.inner, &self.data)))
|
Ok(RwLockWriteGuard::new(&*self.inner, &self.data)?)
|
||||||
} else {
|
} else {
|
||||||
Err(TryLockError::WouldBlock)
|
Err(TryLockError::WouldBlock)
|
||||||
}
|
}
|
||||||
|
@ -382,7 +382,7 @@ impl StaticRwLock {
|
||||||
-> TryLockResult<RwLockReadGuard<'static, ()>> {
|
-> TryLockResult<RwLockReadGuard<'static, ()>> {
|
||||||
unsafe {
|
unsafe {
|
||||||
if self.lock.try_read(){
|
if self.lock.try_read(){
|
||||||
Ok(try!(RwLockReadGuard::new(self, &DUMMY.0)))
|
Ok(RwLockReadGuard::new(self, &DUMMY.0)?)
|
||||||
} else {
|
} else {
|
||||||
Err(TryLockError::WouldBlock)
|
Err(TryLockError::WouldBlock)
|
||||||
}
|
}
|
||||||
|
@ -409,7 +409,7 @@ impl StaticRwLock {
|
||||||
-> TryLockResult<RwLockWriteGuard<'static, ()>> {
|
-> TryLockResult<RwLockWriteGuard<'static, ()>> {
|
||||||
unsafe {
|
unsafe {
|
||||||
if self.lock.try_write() {
|
if self.lock.try_write() {
|
||||||
Ok(try!(RwLockWriteGuard::new(self, &DUMMY.0)))
|
Ok(RwLockWriteGuard::new(self, &DUMMY.0)?)
|
||||||
} else {
|
} else {
|
||||||
Err(TryLockError::WouldBlock)
|
Err(TryLockError::WouldBlock)
|
||||||
}
|
}
|
||||||
|
|
|
@ -46,10 +46,10 @@ pub fn log_enabled() -> bool {
|
||||||
// These output functions should now be used everywhere to ensure consistency.
|
// These output functions should now be used everywhere to ensure consistency.
|
||||||
pub fn output(w: &mut Write, idx: isize, addr: *mut libc::c_void,
|
pub fn output(w: &mut Write, idx: isize, addr: *mut libc::c_void,
|
||||||
s: Option<&[u8]>) -> io::Result<()> {
|
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()) {
|
match s.and_then(|s| str::from_utf8(s).ok()) {
|
||||||
Some(string) => try!(demangle(w, string)),
|
Some(string) => demangle(w, string)?,
|
||||||
None => try!(write!(w, "<unknown>")),
|
None => write!(w, "<unknown>")?,
|
||||||
}
|
}
|
||||||
w.write_all(&['\n' as u8])
|
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<()> {
|
more: bool) -> io::Result<()> {
|
||||||
let file = str::from_utf8(file).unwrap_or("<unknown>");
|
let file = str::from_utf8(file).unwrap_or("<unknown>");
|
||||||
// prior line: " ##: {:2$} - func"
|
// prior line: " ##: {:2$} - func"
|
||||||
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
|
write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH)?;
|
||||||
if more {
|
if more {
|
||||||
try!(write!(w, " <... and possibly more>"));
|
write!(w, " <... and possibly more>")?;
|
||||||
}
|
}
|
||||||
w.write_all(&['\n' as u8])
|
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.
|
// Alright, let's do this.
|
||||||
if !valid {
|
if !valid {
|
||||||
try!(writer.write_all(s.as_bytes()));
|
writer.write_all(s.as_bytes())?;
|
||||||
} else {
|
} else {
|
||||||
let mut first = true;
|
let mut first = true;
|
||||||
while !inner.is_empty() {
|
while !inner.is_empty() {
|
||||||
if !first {
|
if !first {
|
||||||
try!(writer.write_all(b"::"));
|
writer.write_all(b"::")?;
|
||||||
} else {
|
} else {
|
||||||
first = false;
|
first = false;
|
||||||
}
|
}
|
||||||
|
@ -177,7 +177,7 @@ pub fn demangle(writer: &mut Write, s: &str) -> io::Result<()> {
|
||||||
None => rest.len(),
|
None => rest.len(),
|
||||||
Some(i) => i,
|
Some(i) => i,
|
||||||
};
|
};
|
||||||
try!(writer.write_all(rest[..idx].as_bytes()));
|
writer.write_all(rest[..idx].as_bytes())?;
|
||||||
rest = &rest[idx..];
|
rest = &rest[idx..];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -172,9 +172,9 @@ pub fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
|
||||||
data_addr as *mut libc::c_void)
|
data_addr as *mut libc::c_void)
|
||||||
};
|
};
|
||||||
if ret == 0 || data.is_null() {
|
if ret == 0 || data.is_null() {
|
||||||
try!(output(w, idx, addr, None));
|
output(w, idx, addr, None)?;
|
||||||
} else {
|
} 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,
|
// 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() {
|
for (i, &(file, line)) in fileline_buf[..fileline_count].iter().enumerate() {
|
||||||
if file.is_null() { continue; } // just to be sure
|
if file.is_null() { continue; } // just to be sure
|
||||||
let file = unsafe { CStr::from_ptr(file).to_bytes() };
|
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)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -48,8 +48,8 @@ pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
|
||||||
payload: T) -> io::Result<()> {
|
payload: T) -> io::Result<()> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let payload = &payload as *const T as *const c_void;
|
let payload = &payload as *const T as *const c_void;
|
||||||
try!(cvt(c::setsockopt(*sock.as_inner(), opt, val, payload,
|
cvt(c::setsockopt(*sock.as_inner(), opt, val, payload,
|
||||||
mem::size_of::<T>() as c::socklen_t)));
|
mem::size_of::<T>() as c::socklen_t))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -59,9 +59,9 @@ pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut slot: T = mem::zeroed();
|
let mut slot: T = mem::zeroed();
|
||||||
let mut len = mem::size_of::<T>() as c::socklen_t;
|
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 slot as *mut _ as *mut _,
|
||||||
&mut len)));
|
&mut len))?;
|
||||||
assert_eq!(len as usize, mem::size_of::<T>());
|
assert_eq!(len as usize, mem::size_of::<T>());
|
||||||
Ok(slot)
|
Ok(slot)
|
||||||
}
|
}
|
||||||
|
@ -73,7 +73,7 @@ fn sockname<F>(f: F) -> io::Result<SocketAddr>
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut storage: c::sockaddr_storage = mem::zeroed();
|
let mut storage: c::sockaddr_storage = mem::zeroed();
|
||||||
let mut len = mem::size_of_val(&storage) as c::socklen_t;
|
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)
|
sockaddr_to_addr(&storage, len as usize)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -143,11 +143,11 @@ impl Drop for LookupHost {
|
||||||
pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
|
pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
|
||||||
init();
|
init();
|
||||||
|
|
||||||
let c_host = try!(CString::new(host));
|
let c_host = CString::new(host)?;
|
||||||
let mut res = ptr::null_mut();
|
let mut res = ptr::null_mut();
|
||||||
unsafe {
|
unsafe {
|
||||||
try!(cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), ptr::null(),
|
cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), ptr::null(),
|
||||||
&mut res)));
|
&mut res))?;
|
||||||
Ok(LookupHost { original: res, cur: res })
|
Ok(LookupHost { original: res, cur: res })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -164,10 +164,10 @@ impl TcpStream {
|
||||||
pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
|
pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
|
||||||
init();
|
init();
|
||||||
|
|
||||||
let sock = try!(Socket::new(addr, c::SOCK_STREAM));
|
let sock = Socket::new(addr, c::SOCK_STREAM)?;
|
||||||
|
|
||||||
let (addrp, len) = addr.into_inner();
|
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 })
|
Ok(TcpStream { inner: sock })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -201,12 +201,12 @@ impl TcpStream {
|
||||||
|
|
||||||
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
|
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 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(),
|
c::send(*self.inner.as_inner(),
|
||||||
buf.as_ptr() as *const c_void,
|
buf.as_ptr() as *const c_void,
|
||||||
len,
|
len,
|
||||||
0)
|
0)
|
||||||
}));
|
})?;
|
||||||
Ok(ret as usize)
|
Ok(ret as usize)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -243,7 +243,7 @@ impl TcpStream {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn ttl(&self) -> io::Result<u32> {
|
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)
|
Ok(raw as u32)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -252,7 +252,7 @@ impl TcpStream {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn only_v6(&self) -> io::Result<bool> {
|
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)
|
Ok(raw != 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -301,22 +301,22 @@ impl TcpListener {
|
||||||
pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> {
|
pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> {
|
||||||
init();
|
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
|
// On platforms with Berkeley-derived sockets, this allows
|
||||||
// to quickly rebind a socket, without needing to wait for
|
// to quickly rebind a socket, without needing to wait for
|
||||||
// the OS to clean up the previous one.
|
// the OS to clean up the previous one.
|
||||||
if !cfg!(windows) {
|
if !cfg!(windows) {
|
||||||
try!(setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR,
|
setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR,
|
||||||
1 as c_int));
|
1 as c_int)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bind our new socket
|
// Bind our new socket
|
||||||
let (addrp, len) = addr.into_inner();
|
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
|
// Start listening
|
||||||
try!(cvt(unsafe { c::listen(*sock.as_inner(), 128) }));
|
cvt(unsafe { c::listen(*sock.as_inner(), 128) })?;
|
||||||
Ok(TcpListener { inner: sock })
|
Ok(TcpListener { inner: sock })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -333,9 +333,9 @@ impl TcpListener {
|
||||||
pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
|
pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
|
||||||
let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
|
let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
|
||||||
let mut len = mem::size_of_val(&storage) as c::socklen_t;
|
let mut len = mem::size_of_val(&storage) as c::socklen_t;
|
||||||
let sock = try!(self.inner.accept(&mut storage as *mut _ as *mut _,
|
let sock = self.inner.accept(&mut storage as *mut _ as *mut _,
|
||||||
&mut len));
|
&mut len)?;
|
||||||
let addr = try!(sockaddr_to_addr(&storage, len as usize));
|
let addr = sockaddr_to_addr(&storage, len as usize)?;
|
||||||
Ok((TcpStream { inner: sock, }, addr))
|
Ok((TcpStream { inner: sock, }, addr))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -348,7 +348,7 @@ impl TcpListener {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn ttl(&self) -> io::Result<u32> {
|
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)
|
Ok(raw as u32)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -357,7 +357,7 @@ impl TcpListener {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn only_v6(&self) -> io::Result<bool> {
|
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)
|
Ok(raw != 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -402,9 +402,9 @@ impl UdpSocket {
|
||||||
pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> {
|
pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> {
|
||||||
init();
|
init();
|
||||||
|
|
||||||
let sock = try!(Socket::new(addr, c::SOCK_DGRAM));
|
let sock = Socket::new(addr, c::SOCK_DGRAM)?;
|
||||||
let (addrp, len) = addr.into_inner();
|
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 })
|
Ok(UdpSocket { inner: sock })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -423,23 +423,23 @@ impl UdpSocket {
|
||||||
let mut addrlen = mem::size_of_val(&storage) as c::socklen_t;
|
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 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(),
|
c::recvfrom(*self.inner.as_inner(),
|
||||||
buf.as_mut_ptr() as *mut c_void,
|
buf.as_mut_ptr() as *mut c_void,
|
||||||
len, 0,
|
len, 0,
|
||||||
&mut storage as *mut _ as *mut _, &mut addrlen)
|
&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> {
|
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 len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
|
||||||
let (dstp, dstlen) = dst.into_inner();
|
let (dstp, dstlen) = dst.into_inner();
|
||||||
let ret = try!(cvt(unsafe {
|
let ret = cvt(unsafe {
|
||||||
c::sendto(*self.inner.as_inner(),
|
c::sendto(*self.inner.as_inner(),
|
||||||
buf.as_ptr() as *const c_void, len,
|
buf.as_ptr() as *const c_void, len,
|
||||||
0, dstp, dstlen)
|
0, dstp, dstlen)
|
||||||
}));
|
})?;
|
||||||
Ok(ret as usize)
|
Ok(ret as usize)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -468,7 +468,7 @@ impl UdpSocket {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn broadcast(&self) -> io::Result<bool> {
|
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)
|
Ok(raw != 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -477,7 +477,7 @@ impl UdpSocket {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn multicast_loop_v4(&self) -> io::Result<bool> {
|
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)
|
Ok(raw != 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -486,7 +486,7 @@ impl UdpSocket {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
|
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)
|
Ok(raw as u32)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -495,7 +495,7 @@ impl UdpSocket {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn multicast_loop_v6(&self) -> io::Result<bool> {
|
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)
|
Ok(raw != 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -540,7 +540,7 @@ impl UdpSocket {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn ttl(&self) -> io::Result<u32> {
|
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)
|
Ok(raw as u32)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -549,7 +549,7 @@ impl UdpSocket {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn only_v6(&self) -> io::Result<bool> {
|
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)
|
Ok(raw != 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -567,12 +567,12 @@ impl UdpSocket {
|
||||||
|
|
||||||
pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
|
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 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(),
|
c::send(*self.inner.as_inner(),
|
||||||
buf.as_ptr() as *const c_void,
|
buf.as_ptr() as *const c_void,
|
||||||
len,
|
len,
|
||||||
0)
|
0)
|
||||||
}));
|
})?;
|
||||||
Ok(ret as usize)
|
Ok(ret as usize)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -99,7 +99,7 @@ impl<T> ReentrantMutex<T> {
|
||||||
/// acquired.
|
/// acquired.
|
||||||
pub fn try_lock(&self) -> TryLockResult<ReentrantMutexGuard<T>> {
|
pub fn try_lock(&self) -> TryLockResult<ReentrantMutexGuard<T>> {
|
||||||
if unsafe { self.inner.try_lock() } {
|
if unsafe { self.inner.try_lock() } {
|
||||||
Ok(try!(ReentrantMutexGuard::new(&self)))
|
Ok(ReentrantMutexGuard::new(&self)?)
|
||||||
} else {
|
} else {
|
||||||
Err(TryLockError::WouldBlock)
|
Err(TryLockError::WouldBlock)
|
||||||
}
|
}
|
||||||
|
|
|
@ -388,32 +388,32 @@ impl fmt::Debug for Wtf8 {
|
||||||
fn write_str_escaped(f: &mut fmt::Formatter, s: &str) -> fmt::Result {
|
fn write_str_escaped(f: &mut fmt::Formatter, s: &str) -> fmt::Result {
|
||||||
use fmt::Write;
|
use fmt::Write;
|
||||||
for c in s.chars().flat_map(|c| c.escape_default()) {
|
for c in s.chars().flat_map(|c| c.escape_default()) {
|
||||||
try!(f.write_char(c))
|
f.write_char(c)?
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
try!(formatter.write_str("\""));
|
formatter.write_str("\"")?;
|
||||||
let mut pos = 0;
|
let mut pos = 0;
|
||||||
loop {
|
loop {
|
||||||
match self.next_surrogate(pos) {
|
match self.next_surrogate(pos) {
|
||||||
None => break,
|
None => break,
|
||||||
Some((surrogate_pos, surrogate)) => {
|
Some((surrogate_pos, surrogate)) => {
|
||||||
try!(write_str_escaped(
|
write_str_escaped(
|
||||||
formatter,
|
formatter,
|
||||||
unsafe { str::from_utf8_unchecked(
|
unsafe { str::from_utf8_unchecked(
|
||||||
&self.bytes[pos .. surrogate_pos]
|
&self.bytes[pos .. surrogate_pos]
|
||||||
)},
|
)},
|
||||||
));
|
)?;
|
||||||
try!(write!(formatter, "\\u{{{:X}}}", surrogate));
|
write!(formatter, "\\u{{{:X}}}", surrogate)?;
|
||||||
pos = surrogate_pos + 3;
|
pos = surrogate_pos + 3;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try!(write_str_escaped(
|
write_str_escaped(
|
||||||
formatter,
|
formatter,
|
||||||
unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) },
|
unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) },
|
||||||
));
|
)?;
|
||||||
formatter.write_str("\"")
|
formatter.write_str("\"")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -40,7 +40,7 @@ pub fn write(w: &mut Write) -> io::Result<()> {
|
||||||
static LOCK: StaticMutex = StaticMutex::new();
|
static LOCK: StaticMutex = StaticMutex::new();
|
||||||
let _g = LOCK.lock();
|
let _g = LOCK.lock();
|
||||||
|
|
||||||
try!(writeln!(w, "stack backtrace:"));
|
writeln!(w, "stack backtrace:")?;
|
||||||
// 100 lines should be enough
|
// 100 lines should be enough
|
||||||
const SIZE: usize = 100;
|
const SIZE: usize = 100;
|
||||||
let mut buf: [*mut libc::c_void; SIZE] = unsafe { mem::zeroed() };
|
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
|
// skipping the first one as it is write itself
|
||||||
for i in 1..cnt {
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,7 +33,7 @@ pub fn write(w: &mut Write) -> io::Result<()> {
|
||||||
static LOCK: StaticMutex = StaticMutex::new();
|
static LOCK: StaticMutex = StaticMutex::new();
|
||||||
let _g = LOCK.lock();
|
let _g = LOCK.lock();
|
||||||
|
|
||||||
try!(writeln!(w, "stack backtrace:"));
|
writeln!(w, "stack backtrace:")?;
|
||||||
|
|
||||||
let mut cx = Context { writer: w, last_error: None, idx: 0 };
|
let mut cx = Context { writer: w, last_error: None, idx: 0 };
|
||||||
return match unsafe {
|
return match unsafe {
|
||||||
|
|
|
@ -87,7 +87,7 @@ impl SocketAddr {
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut addr: libc::sockaddr_un = mem::zeroed();
|
let mut addr: libc::sockaddr_un = mem::zeroed();
|
||||||
let mut len = mem::size_of::<libc::sockaddr_un>() as libc::socklen_t;
|
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)
|
SocketAddr::from_parts(addr, len)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -155,9 +155,9 @@ struct AsciiEscaped<'a>(&'a [u8]);
|
||||||
|
|
||||||
impl<'a> fmt::Display for AsciiEscaped<'a> {
|
impl<'a> fmt::Display for AsciiEscaped<'a> {
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
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) {
|
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, "\"")
|
write!(fmt, "\"")
|
||||||
}
|
}
|
||||||
|
@ -200,10 +200,10 @@ impl UnixStream {
|
||||||
pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
|
pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
|
||||||
fn inner(path: &Path) -> io::Result<UnixStream> {
|
fn inner(path: &Path) -> io::Result<UnixStream> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let inner = try!(Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM));
|
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
|
||||||
let (addr, len) = try!(sockaddr_un(path));
|
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))
|
Ok(UnixStream(inner))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -214,7 +214,7 @@ impl UnixStream {
|
||||||
///
|
///
|
||||||
/// Returns two `UnixStream`s which are connected to each other.
|
/// Returns two `UnixStream`s which are connected to each other.
|
||||||
pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
|
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)))
|
Ok((UnixStream(i1), UnixStream(i2)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -395,11 +395,11 @@ impl UnixListener {
|
||||||
pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
|
pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
|
||||||
fn inner(path: &Path) -> io::Result<UnixListener> {
|
fn inner(path: &Path) -> io::Result<UnixListener> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let inner = try!(Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM));
|
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
|
||||||
let (addr, len) = try!(sockaddr_un(path));
|
let (addr, len) = sockaddr_un(path)?;
|
||||||
|
|
||||||
try!(cvt(libc::bind(*inner.as_inner(), &addr as *const _ as *const _, len)));
|
cvt(libc::bind(*inner.as_inner(), &addr as *const _ as *const _, len))?;
|
||||||
try!(cvt(libc::listen(*inner.as_inner(), 128)));
|
cvt(libc::listen(*inner.as_inner(), 128))?;
|
||||||
|
|
||||||
Ok(UnixListener(inner))
|
Ok(UnixListener(inner))
|
||||||
}
|
}
|
||||||
|
@ -415,8 +415,8 @@ impl UnixListener {
|
||||||
pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
|
pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
|
||||||
let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
|
let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
|
||||||
let mut len = mem::size_of_val(&storage) as libc::socklen_t;
|
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 sock = self.0.accept(&mut storage as *mut _ as *mut _, &mut len)?;
|
||||||
let addr = try!(SocketAddr::from_parts(storage, len));
|
let addr = SocketAddr::from_parts(storage, len)?;
|
||||||
Ok((UnixStream(sock), addr))
|
Ok((UnixStream(sock), addr))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -536,10 +536,10 @@ impl UnixDatagram {
|
||||||
pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
|
pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
|
||||||
fn inner(path: &Path) -> io::Result<UnixDatagram> {
|
fn inner(path: &Path) -> io::Result<UnixDatagram> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let socket = try!(UnixDatagram::unbound());
|
let socket = UnixDatagram::unbound()?;
|
||||||
let (addr, len) = try!(sockaddr_un(path));
|
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)
|
Ok(socket)
|
||||||
}
|
}
|
||||||
|
@ -549,7 +549,7 @@ impl UnixDatagram {
|
||||||
|
|
||||||
/// Creates a Unix Datagram socket which is not bound to any address.
|
/// Creates a Unix Datagram socket which is not bound to any address.
|
||||||
pub fn unbound() -> io::Result<UnixDatagram> {
|
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))
|
Ok(UnixDatagram(inner))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -557,7 +557,7 @@ impl UnixDatagram {
|
||||||
///
|
///
|
||||||
/// Returns two `UnixDatagrams`s which are connected to each other.
|
/// Returns two `UnixDatagrams`s which are connected to each other.
|
||||||
pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
|
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)))
|
Ok((UnixDatagram(i1), UnixDatagram(i2)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -568,9 +568,9 @@ impl UnixDatagram {
|
||||||
pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
|
pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
|
||||||
fn inner(d: &UnixDatagram, path: &Path) -> io::Result<()> {
|
fn inner(d: &UnixDatagram, path: &Path) -> io::Result<()> {
|
||||||
unsafe {
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -605,7 +605,7 @@ impl UnixDatagram {
|
||||||
/// whence the data came.
|
/// whence the data came.
|
||||||
pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
let addr = try!(SocketAddr::new(|addr, len| {
|
let addr = SocketAddr::new(|addr, len| {
|
||||||
unsafe {
|
unsafe {
|
||||||
count = libc::recvfrom(*self.0.as_inner(),
|
count = libc::recvfrom(*self.0.as_inner(),
|
||||||
buf.as_mut_ptr() as *mut _,
|
buf.as_mut_ptr() as *mut _,
|
||||||
|
@ -621,7 +621,7 @@ impl UnixDatagram {
|
||||||
-1
|
-1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
Ok((count as usize, addr))
|
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> {
|
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> {
|
fn inner(d: &UnixDatagram, buf: &[u8], path: &Path) -> io::Result<usize> {
|
||||||
unsafe {
|
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.as_ptr() as *const _,
|
||||||
buf.len(),
|
buf.len(),
|
||||||
0,
|
0,
|
||||||
&addr as *const _ as *const _,
|
&addr as *const _ as *const _,
|
||||||
len)));
|
len))?;
|
||||||
Ok(count as usize)
|
Ok(count as usize)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -39,11 +39,11 @@ impl FileDesc {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
|
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
let ret = try!(cvt(unsafe {
|
let ret = cvt(unsafe {
|
||||||
libc::read(self.fd,
|
libc::read(self.fd,
|
||||||
buf.as_mut_ptr() as *mut c_void,
|
buf.as_mut_ptr() as *mut c_void,
|
||||||
buf.len() as size_t)
|
buf.len() as size_t)
|
||||||
}));
|
})?;
|
||||||
Ok(ret as usize)
|
Ok(ret as usize)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -53,11 +53,11 @@ impl FileDesc {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
|
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
|
||||||
let ret = try!(cvt(unsafe {
|
let ret = cvt(unsafe {
|
||||||
libc::write(self.fd,
|
libc::write(self.fd,
|
||||||
buf.as_ptr() as *const c_void,
|
buf.as_ptr() as *const c_void,
|
||||||
buf.len() as size_t)
|
buf.len() as size_t)
|
||||||
}));
|
})?;
|
||||||
Ok(ret as usize)
|
Ok(ret as usize)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -418,18 +418,18 @@ impl OpenOptions {
|
||||||
|
|
||||||
impl File {
|
impl File {
|
||||||
pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<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)
|
File::open_c(&path, opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
|
pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
|
||||||
let flags = libc::O_CLOEXEC |
|
let flags = libc::O_CLOEXEC |
|
||||||
try!(opts.get_access_mode()) |
|
opts.get_access_mode()? |
|
||||||
try!(opts.get_creation_mode()) |
|
opts.get_creation_mode()? |
|
||||||
(opts.custom_flags as c_int & !libc::O_ACCMODE);
|
(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)
|
open64(path.as_ptr(), flags, opts.mode as c_int)
|
||||||
}));
|
})?;
|
||||||
let fd = FileDesc::new(fd);
|
let fd = FileDesc::new(fd);
|
||||||
|
|
||||||
// Currently the standard library supports Linux 2.6.18 which did not
|
// 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> {
|
pub fn file_attr(&self) -> io::Result<FileAttr> {
|
||||||
let mut stat: stat64 = unsafe { mem::zeroed() };
|
let mut stat: stat64 = unsafe { mem::zeroed() };
|
||||||
try!(cvt(unsafe {
|
cvt(unsafe {
|
||||||
fstat64(self.0.raw(), &mut stat)
|
fstat64(self.0.raw(), &mut stat)
|
||||||
}));
|
})?;
|
||||||
Ok(FileAttr { stat: stat })
|
Ok(FileAttr { stat: stat })
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fsync(&self) -> io::Result<()> {
|
pub fn fsync(&self) -> io::Result<()> {
|
||||||
try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
|
cvt_r(|| unsafe { libc::fsync(self.0.raw()) })?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn datasync(&self) -> io::Result<()> {
|
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(());
|
return Ok(());
|
||||||
|
|
||||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||||
|
@ -476,9 +476,9 @@ impl File {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn truncate(&self, size: u64) -> io::Result<()> {
|
pub fn truncate(&self, size: u64) -> io::Result<()> {
|
||||||
try!(cvt_r(|| unsafe {
|
cvt_r(|| unsafe {
|
||||||
ftruncate64(self.0.raw(), size as off64_t)
|
ftruncate64(self.0.raw(), size as off64_t)
|
||||||
}));
|
})?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -502,7 +502,7 @@ impl File {
|
||||||
SeekFrom::End(off) => (libc::SEEK_END, off as off64_t),
|
SeekFrom::End(off) => (libc::SEEK_END, off as off64_t),
|
||||||
SeekFrom::Current(off) => (libc::SEEK_CUR, 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)
|
Ok(n as u64)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -521,8 +521,8 @@ impl DirBuilder {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mkdir(&self, p: &Path) -> io::Result<()> {
|
pub fn mkdir(&self, p: &Path) -> io::Result<()> {
|
||||||
let p = try!(cstr(p));
|
let p = cstr(p)?;
|
||||||
try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }));
|
cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -532,7 +532,7 @@ impl DirBuilder {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cstr(path: &Path) -> io::Result<CString> {
|
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 {
|
impl FromInner<c_int> for File {
|
||||||
|
@ -610,7 +610,7 @@ impl fmt::Debug for File {
|
||||||
|
|
||||||
pub fn readdir(p: &Path) -> io::Result<ReadDir> {
|
pub fn readdir(p: &Path) -> io::Result<ReadDir> {
|
||||||
let root = Arc::new(p.to_path_buf());
|
let root = Arc::new(p.to_path_buf());
|
||||||
let p = try!(cstr(p));
|
let p = cstr(p)?;
|
||||||
unsafe {
|
unsafe {
|
||||||
let ptr = libc::opendir(p.as_ptr());
|
let ptr = libc::opendir(p.as_ptr());
|
||||||
if ptr.is_null() {
|
if ptr.is_null() {
|
||||||
|
@ -622,32 +622,32 @@ pub fn readdir(p: &Path) -> io::Result<ReadDir> {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn unlink(p: &Path) -> io::Result<()> {
|
pub fn unlink(p: &Path) -> io::Result<()> {
|
||||||
let p = try!(cstr(p));
|
let p = cstr(p)?;
|
||||||
try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
|
cvt(unsafe { libc::unlink(p.as_ptr()) })?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
|
pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
|
||||||
let old = try!(cstr(old));
|
let old = cstr(old)?;
|
||||||
let new = try!(cstr(new));
|
let new = cstr(new)?;
|
||||||
try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
|
cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
|
pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
|
||||||
let p = try!(cstr(p));
|
let p = cstr(p)?;
|
||||||
try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
|
cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn rmdir(p: &Path) -> io::Result<()> {
|
pub fn rmdir(p: &Path) -> io::Result<()> {
|
||||||
let p = try!(cstr(p));
|
let p = cstr(p)?;
|
||||||
try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
|
cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove_dir_all(path: &Path) -> io::Result<()> {
|
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() {
|
if filetype.is_symlink() {
|
||||||
unlink(path)
|
unlink(path)
|
||||||
} else {
|
} else {
|
||||||
|
@ -656,27 +656,27 @@ pub fn remove_dir_all(path: &Path) -> io::Result<()> {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
|
fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
|
||||||
for child in try!(readdir(path)) {
|
for child in readdir(path)? {
|
||||||
let child = try!(child);
|
let child = child?;
|
||||||
if try!(child.file_type()).is_dir() {
|
if child.file_type()?.is_dir() {
|
||||||
try!(remove_dir_all_recursive(&child.path()));
|
remove_dir_all_recursive(&child.path())?;
|
||||||
} else {
|
} else {
|
||||||
try!(unlink(&child.path()));
|
unlink(&child.path())?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
rmdir(path)
|
rmdir(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn readlink(p: &Path) -> io::Result<PathBuf> {
|
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 p = c_path.as_ptr();
|
||||||
|
|
||||||
let mut buf = Vec::with_capacity(256);
|
let mut buf = Vec::with_capacity(256);
|
||||||
|
|
||||||
loop {
|
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)
|
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); }
|
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<()> {
|
pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
|
||||||
let src = try!(cstr(src));
|
let src = cstr(src)?;
|
||||||
let dst = try!(cstr(dst));
|
let dst = cstr(dst)?;
|
||||||
try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
|
cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
|
pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
|
||||||
let src = try!(cstr(src));
|
let src = cstr(src)?;
|
||||||
let dst = try!(cstr(dst));
|
let dst = cstr(dst)?;
|
||||||
try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
|
cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn stat(p: &Path) -> io::Result<FileAttr> {
|
pub fn stat(p: &Path) -> io::Result<FileAttr> {
|
||||||
let p = try!(cstr(p));
|
let p = cstr(p)?;
|
||||||
let mut stat: stat64 = unsafe { mem::zeroed() };
|
let mut stat: stat64 = unsafe { mem::zeroed() };
|
||||||
try!(cvt(unsafe {
|
cvt(unsafe {
|
||||||
stat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
|
stat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
|
||||||
}));
|
})?;
|
||||||
Ok(FileAttr { stat: stat })
|
Ok(FileAttr { stat: stat })
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn lstat(p: &Path) -> io::Result<FileAttr> {
|
pub fn lstat(p: &Path) -> io::Result<FileAttr> {
|
||||||
let p = try!(cstr(p));
|
let p = cstr(p)?;
|
||||||
let mut stat: stat64 = unsafe { mem::zeroed() };
|
let mut stat: stat64 = unsafe { mem::zeroed() };
|
||||||
try!(cvt(unsafe {
|
cvt(unsafe {
|
||||||
lstat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
|
lstat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
|
||||||
}));
|
})?;
|
||||||
Ok(FileAttr { stat: stat })
|
Ok(FileAttr { stat: stat })
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
|
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;
|
let buf;
|
||||||
unsafe {
|
unsafe {
|
||||||
let r = libc::realpath(path.as_ptr(), ptr::null_mut());
|
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"))
|
"the source path is not an existing regular file"))
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut reader = try!(File::open(from));
|
let mut reader = File::open(from)?;
|
||||||
let mut writer = try!(File::create(to));
|
let mut writer = File::create(to)?;
|
||||||
let perm = try!(reader.metadata()).permissions();
|
let perm = reader.metadata()?.permissions();
|
||||||
|
|
||||||
let ret = try!(io::copy(&mut reader, &mut writer));
|
let ret = io::copy(&mut reader, &mut writer)?;
|
||||||
try!(set_permissions(to, perm));
|
set_permissions(to, perm)?;
|
||||||
Ok(ret)
|
Ok(ret)
|
||||||
}
|
}
|
||||||
|
|
|
@ -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);
|
let fd = FileDesc::new(fd);
|
||||||
fd.set_cloexec();
|
fd.set_cloexec();
|
||||||
Ok(Socket(fd))
|
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]);
|
let a = FileDesc::new(fds[0]);
|
||||||
a.set_cloexec();
|
a.set_cloexec();
|
||||||
let b = FileDesc::new(fds[1]);
|
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)
|
libc::accept(self.0.raw(), storage, len)
|
||||||
}));
|
})?;
|
||||||
let fd = FileDesc::new(fd);
|
let fd = FileDesc::new(fd);
|
||||||
fd.set_cloexec();
|
fd.set_cloexec();
|
||||||
Ok(Socket(fd))
|
Ok(Socket(fd))
|
||||||
|
@ -185,7 +185,7 @@ impl Socket {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
|
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 {
|
if raw.tv_sec == 0 && raw.tv_usec == 0 {
|
||||||
Ok(None)
|
Ok(None)
|
||||||
} else {
|
} else {
|
||||||
|
@ -201,7 +201,7 @@ impl Socket {
|
||||||
Shutdown::Read => libc::SHUT_RD,
|
Shutdown::Read => libc::SHUT_RD,
|
||||||
Shutdown::Both => libc::SHUT_RDWR,
|
Shutdown::Both => libc::SHUT_RDWR,
|
||||||
};
|
};
|
||||||
try!(cvt(unsafe { libc::shutdown(self.0.raw(), how) }));
|
cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -210,7 +210,7 @@ impl Socket {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn nodelay(&self) -> io::Result<bool> {
|
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)
|
Ok(raw != 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -220,7 +220,7 @@ impl Socket {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
|
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 {
|
if raw == 0 {
|
||||||
Ok(None)
|
Ok(None)
|
||||||
} else {
|
} else {
|
||||||
|
|
|
@ -110,7 +110,7 @@ pub fn getcwd() -> io::Result<PathBuf> {
|
||||||
|
|
||||||
pub fn chdir(p: &path::Path) -> io::Result<()> {
|
pub fn chdir(p: &path::Path) -> io::Result<()> {
|
||||||
let p: &OsStr = p.as_ref();
|
let p: &OsStr = p.as_ref();
|
||||||
let p = try!(CString::new(p.as_bytes()));
|
let p = CString::new(p.as_bytes())?;
|
||||||
unsafe {
|
unsafe {
|
||||||
match libc::chdir(p.as_ptr()) == (0 as c_int) {
|
match libc::chdir(p.as_ptr()) == (0 as c_int) {
|
||||||
true => Ok(()),
|
true => Ok(()),
|
||||||
|
@ -180,16 +180,16 @@ pub fn current_exe() -> io::Result<PathBuf> {
|
||||||
libc::KERN_PROC_PATHNAME as c_int,
|
libc::KERN_PROC_PATHNAME as c_int,
|
||||||
-1 as c_int];
|
-1 as c_int];
|
||||||
let mut sz: libc::size_t = 0;
|
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(),
|
ptr::null_mut(), &mut sz, ptr::null_mut(),
|
||||||
0 as libc::size_t)));
|
0 as libc::size_t))?;
|
||||||
if sz == 0 {
|
if sz == 0 {
|
||||||
return Err(io::Error::last_os_error())
|
return Err(io::Error::last_os_error())
|
||||||
}
|
}
|
||||||
let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
|
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,
|
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 {
|
if sz == 0 {
|
||||||
return Err(io::Error::last_os_error());
|
return Err(io::Error::last_os_error());
|
||||||
}
|
}
|
||||||
|
@ -217,11 +217,11 @@ pub fn current_exe() -> io::Result<PathBuf> {
|
||||||
libc::KERN_PROC_ARGV];
|
libc::KERN_PROC_ARGV];
|
||||||
let mib = mib.as_mut_ptr();
|
let mib = mib.as_mut_ptr();
|
||||||
let mut argv_len = 0;
|
let mut argv_len = 0;
|
||||||
try!(cvt(libc::sysctl(mib, 4, 0 as *mut _, &mut argv_len,
|
cvt(libc::sysctl(mib, 4, 0 as *mut _, &mut argv_len,
|
||||||
0 as *mut _, 0)));
|
0 as *mut _, 0))?;
|
||||||
let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
|
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 _,
|
cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _,
|
||||||
&mut argv_len, 0 as *mut _, 0)));
|
&mut argv_len, 0 as *mut _, 0))?;
|
||||||
argv.set_len(argv_len as usize);
|
argv.set_len(argv_len as usize);
|
||||||
if argv[0].is_null() {
|
if argv[0].is_null() {
|
||||||
return Err(io::Error::new(io::ErrorKind::Other,
|
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>> {
|
pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
|
||||||
// environment variables with a nul byte can't be set, so their value is
|
// environment variables with a nul byte can't be set, so their value is
|
||||||
// always None as well
|
// always None as well
|
||||||
let k = try!(CString::new(k.as_bytes()));
|
let k = CString::new(k.as_bytes())?;
|
||||||
let _g = ENV_LOCK.lock();
|
let _g = ENV_LOCK.lock();
|
||||||
Ok(unsafe {
|
Ok(unsafe {
|
||||||
let s = libc::getenv(k.as_ptr()) as *const _;
|
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<()> {
|
pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
|
||||||
let k = try!(CString::new(k.as_bytes()));
|
let k = CString::new(k.as_bytes())?;
|
||||||
let v = try!(CString::new(v.as_bytes()));
|
let v = CString::new(v.as_bytes())?;
|
||||||
let _g = ENV_LOCK.lock();
|
let _g = ENV_LOCK.lock();
|
||||||
cvt(unsafe {
|
cvt(unsafe {
|
||||||
libc::setenv(k.as_ptr(), v.as_ptr(), 1)
|
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<()> {
|
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();
|
let _g = ENV_LOCK.lock();
|
||||||
cvt(unsafe {
|
cvt(unsafe {
|
||||||
libc::unsetenv(nbuf.as_ptr())
|
libc::unsetenv(nbuf.as_ptr())
|
||||||
|
|
|
@ -87,13 +87,13 @@ pub fn read2(p1: AnonPipe,
|
||||||
let max = cmp::max(p1.raw(), p2.raw());
|
let max = cmp::max(p1.raw(), p2.raw());
|
||||||
loop {
|
loop {
|
||||||
// wait for either pipe to become readable using `select`
|
// wait for either pipe to become readable using `select`
|
||||||
try!(cvt_r(|| unsafe {
|
cvt_r(|| unsafe {
|
||||||
let mut read: libc::fd_set = mem::zeroed();
|
let mut read: libc::fd_set = mem::zeroed();
|
||||||
libc::FD_SET(p1.raw(), &mut read);
|
libc::FD_SET(p1.raw(), &mut read);
|
||||||
libc::FD_SET(p2.raw(), &mut read);
|
libc::FD_SET(p2.raw(), &mut read);
|
||||||
libc::select(max + 1, &mut read, 0 as *mut _, 0 as *mut _,
|
libc::select(max + 1, &mut read, 0 as *mut _, 0 as *mut _,
|
||||||
0 as *mut _)
|
0 as *mut _)
|
||||||
}));
|
})?;
|
||||||
|
|
||||||
// Read as much as we can from each pipe, ignoring EWOULDBLOCK or
|
// Read as much as we can from each pipe, ignoring EWOULDBLOCK or
|
||||||
// EAGAIN. If we hit EOF, then this will happen because the underlying
|
// 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);
|
p2.set_nonblocking(false);
|
||||||
return p2.read_to_end(v2).map(|_| ());
|
return p2.read_to_end(v2).map(|_| ());
|
||||||
}
|
}
|
||||||
if try!(read(&p2, v2)) {
|
if read(&p2, v2)? {
|
||||||
p1.set_nonblocking(false);
|
p1.set_nonblocking(false);
|
||||||
return p1.read_to_end(v1).map(|_| ());
|
return p1.read_to_end(v1).map(|_| ());
|
||||||
}
|
}
|
||||||
|
|
|
@ -225,11 +225,11 @@ impl Command {
|
||||||
"nul byte found in provided data"));
|
"nul byte found in provided data"));
|
||||||
}
|
}
|
||||||
|
|
||||||
let (ours, theirs) = try!(self.setup_io(default, needs_stdin));
|
let (ours, theirs) = self.setup_io(default, needs_stdin)?;
|
||||||
let (input, output) = try!(sys::pipe::anon_pipe());
|
let (input, output) = sys::pipe::anon_pipe()?;
|
||||||
|
|
||||||
let pid = unsafe {
|
let pid = unsafe {
|
||||||
match try!(cvt(libc::fork())) {
|
match cvt(libc::fork())? {
|
||||||
0 => {
|
0 => {
|
||||||
drop(input);
|
drop(input);
|
||||||
let err = self.do_exec(theirs);
|
let err = self.do_exec(theirs);
|
||||||
|
@ -343,17 +343,17 @@ impl Command {
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(fd) = stdio.stdin.fd() {
|
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() {
|
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() {
|
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 {
|
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 {
|
if let Some(u) = self.uid {
|
||||||
// When dropping privileges from root, the `setgroups` call
|
// When dropping privileges from root, the `setgroups` call
|
||||||
|
@ -365,7 +365,7 @@ impl Command {
|
||||||
// privilege dropping function.
|
// privilege dropping function.
|
||||||
let _ = libc::setgroups(0, ptr::null());
|
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 {
|
if self.session_leader {
|
||||||
// Don't check the error of setsid because it fails if we're the
|
// Don't check the error of setsid because it fails if we're the
|
||||||
|
@ -374,7 +374,7 @@ impl Command {
|
||||||
let _ = libc::setsid();
|
let _ = libc::setsid();
|
||||||
}
|
}
|
||||||
if let Some(ref cwd) = self.cwd {
|
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 {
|
if let Some(ref envp) = self.envp {
|
||||||
*sys::os::environ() = envp.as_ptr();
|
*sys::os::environ() = envp.as_ptr();
|
||||||
|
@ -390,9 +390,9 @@ impl Command {
|
||||||
// need to clean things up now to avoid confusing the program
|
// need to clean things up now to avoid confusing the program
|
||||||
// we're about to run.
|
// we're about to run.
|
||||||
let mut set: libc::sigset_t = mem::uninitialized();
|
let mut set: libc::sigset_t = mem::uninitialized();
|
||||||
try!(cvt(libc::sigemptyset(&mut set)));
|
cvt(libc::sigemptyset(&mut set))?;
|
||||||
try!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, &set,
|
cvt(libc::pthread_sigmask(libc::SIG_SETMASK, &set,
|
||||||
ptr::null_mut())));
|
ptr::null_mut()))?;
|
||||||
let ret = libc::signal(libc::SIGPIPE, libc::SIG_DFL);
|
let ret = libc::signal(libc::SIGPIPE, libc::SIG_DFL);
|
||||||
if ret == libc::SIG_ERR {
|
if ret == libc::SIG_ERR {
|
||||||
return io::Error::last_os_error()
|
return io::Error::last_os_error()
|
||||||
|
@ -400,7 +400,7 @@ impl Command {
|
||||||
}
|
}
|
||||||
|
|
||||||
for callback in self.closures.iter_mut() {
|
for callback in self.closures.iter_mut() {
|
||||||
try!(callback());
|
callback()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
libc::execvp(self.argv[0], self.argv.as_ptr());
|
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 stdin = self.stdin.as_ref().unwrap_or(default_stdin);
|
||||||
let stdout = self.stdout.as_ref().unwrap_or(&default);
|
let stdout = self.stdout.as_ref().unwrap_or(&default);
|
||||||
let stderr = self.stderr.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_stdin, our_stdin) = stdin.to_child_stdio(true)?;
|
||||||
let (their_stdout, our_stdout) = try!(stdout.to_child_stdio(false));
|
let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
|
||||||
let (their_stderr, our_stderr) = try!(stderr.to_child_stdio(false));
|
let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
|
||||||
let ours = StdioPipes {
|
let ours = StdioPipes {
|
||||||
stdin: our_stdin,
|
stdin: our_stdin,
|
||||||
stdout: our_stdout,
|
stdout: our_stdout,
|
||||||
|
@ -454,14 +454,14 @@ impl Stdio {
|
||||||
// overwritten prematurely.
|
// overwritten prematurely.
|
||||||
Stdio::Fd(ref fd) => {
|
Stdio::Fd(ref fd) => {
|
||||||
if fd.raw() >= 0 && fd.raw() <= libc::STDERR_FILENO {
|
if fd.raw() >= 0 && fd.raw() <= libc::STDERR_FILENO {
|
||||||
Ok((ChildStdio::Owned(try!(fd.duplicate())), None))
|
Ok((ChildStdio::Owned(fd.duplicate()?), None))
|
||||||
} else {
|
} else {
|
||||||
Ok((ChildStdio::Explicit(fd.raw()), None))
|
Ok((ChildStdio::Explicit(fd.raw()), None))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Stdio::MakePipe => {
|
Stdio::MakePipe => {
|
||||||
let (reader, writer) = try!(pipe::anon_pipe());
|
let (reader, writer) = pipe::anon_pipe()?;
|
||||||
let (ours, theirs) = if readable {
|
let (ours, theirs) = if readable {
|
||||||
(writer, reader)
|
(writer, reader)
|
||||||
} else {
|
} else {
|
||||||
|
@ -477,7 +477,7 @@ impl Stdio {
|
||||||
let path = unsafe {
|
let path = unsafe {
|
||||||
CStr::from_ptr("/dev/null\0".as_ptr() as *const _)
|
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))
|
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 {
|
impl fmt::Debug for Command {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
try!(write!(f, "{:?}", self.program));
|
write!(f, "{:?}", self.program)?;
|
||||||
for arg in &self.args {
|
for arg in &self.args {
|
||||||
try!(write!(f, " {:?}", arg));
|
write!(f, " {:?}", arg)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -589,7 +589,7 @@ impl Process {
|
||||||
return Ok(status)
|
return Ok(status)
|
||||||
}
|
}
|
||||||
let mut status = 0 as c_int;
|
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));
|
self.status = Some(ExitStatus(status));
|
||||||
Ok(ExitStatus(status))
|
Ok(ExitStatus(status))
|
||||||
}
|
}
|
||||||
|
|
|
@ -138,7 +138,7 @@ mod imp {
|
||||||
return Ok(OsRng { inner: OsGetrandomRng });
|
return Ok(OsRng { inner: OsGetrandomRng });
|
||||||
}
|
}
|
||||||
|
|
||||||
let reader = try!(File::open("/dev/urandom"));
|
let reader = File::open("/dev/urandom")?;
|
||||||
let reader_rng = ReaderRng::new(reader);
|
let reader_rng = ReaderRng::new(reader);
|
||||||
|
|
||||||
Ok(OsRng { inner: OsReaderRng(reader_rng) })
|
Ok(OsRng { inner: OsReaderRng(reader_rng) })
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue