From b211b00d21fc7c03c3c378ad5eab60666a00fc08 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 29 Jan 2014 17:39:21 -0800 Subject: syntax: Remove io_error usage --- src/libsyntax/diagnostic.rs | 112 +- src/libsyntax/ext/source_util.rs | 9 +- src/libsyntax/lib.rs | 5 + src/libsyntax/parse/comments.rs | 3 +- src/libsyntax/parse/mod.rs | 5 +- src/libsyntax/print/pp.rs | 104 +- src/libsyntax/print/pprust.rs | 2157 +++++++++++++++++++++----------------- 7 files changed, 1349 insertions(+), 1046 deletions(-) (limited to 'src/libsyntax') diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 90fe121160b..5b3b436a6fc 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -189,58 +189,61 @@ impl Level { } } -fn print_maybe_styled(msg: &str, color: term::attr::Attr) { - local_data_key!(tls_terminal: ~Option>) +fn print_maybe_styled(msg: &str, color: term::attr::Attr) -> io::IoResult<()> { + local_data_key!(tls_terminal: Option>) + fn is_stderr_screen() -> bool { use std::libc; unsafe { libc::isatty(libc::STDERR_FILENO) != 0 } } - fn write_pretty(term: &mut term::Terminal, s: &str, c: term::attr::Attr) { - term.attr(c); - term.write(s.as_bytes()); - term.reset(); + fn write_pretty(term: &mut term::Terminal, s: &str, + c: term::attr::Attr) -> io::IoResult<()> { + if_ok!(term.attr(c)); + if_ok!(term.write(s.as_bytes())); + if_ok!(term.reset()); + Ok(()) } if is_stderr_screen() { local_data::get_mut(tls_terminal, |term| { match term { Some(term) => { - match **term { + match *term { Some(ref mut term) => write_pretty(term, msg, color), None => io::stderr().write(msg.as_bytes()) } } None => { - let t = ~match term::Terminal::new(io::stderr()) { + let (t, ret) = match term::Terminal::new(io::stderr()) { Ok(mut term) => { - write_pretty(&mut term, msg, color); - Some(term) + let r = write_pretty(&mut term, msg, color); + (Some(term), r) } Err(_) => { - io::stderr().write(msg.as_bytes()); - None + (None, io::stderr().write(msg.as_bytes())) } }; local_data::set(tls_terminal, t); + ret } } - }); + }) } else { - io::stderr().write(msg.as_bytes()); + io::stderr().write(msg.as_bytes()) } } -fn print_diagnostic(topic: &str, lvl: Level, msg: &str) { - let mut stderr = io::stderr(); - +fn print_diagnostic(topic: &str, lvl: Level, msg: &str) -> io::IoResult<()> { if !topic.is_empty() { - write!(&mut stderr as &mut io::Writer, "{} ", topic); + let mut stderr = io::stderr(); + if_ok!(write!(&mut stderr as &mut io::Writer, "{} ", topic)); } - print_maybe_styled(format!("{}: ", lvl.to_str()), - term::attr::ForegroundColor(lvl.color())); - print_maybe_styled(format!("{}\n", msg), term::attr::Bold); + if_ok!(print_maybe_styled(format!("{}: ", lvl.to_str()), + term::attr::ForegroundColor(lvl.color()))); + if_ok!(print_maybe_styled(format!("{}\n", msg), term::attr::Bold)); + Ok(()) } pub struct DefaultEmitter; @@ -250,20 +253,28 @@ impl Emitter for DefaultEmitter { cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { - match cmsp { + let error = match cmsp { Some((cm, sp)) => emit(cm, sp, msg, lvl, false), None => print_diagnostic("", lvl, msg), + }; + + match error { + Ok(()) => {} + Err(e) => fail!("failed to print diagnostics: {}", e), } } fn custom_emit(&self, cm: &codemap::CodeMap, sp: Span, msg: &str, lvl: Level) { - emit(cm, sp, msg, lvl, true); + match emit(cm, sp, msg, lvl, true) { + Ok(()) => {} + Err(e) => fail!("failed to print diagnostics: {}", e), + } } } fn emit(cm: &codemap::CodeMap, sp: Span, - msg: &str, lvl: Level, custom: bool) { + msg: &str, lvl: Level, custom: bool) -> io::IoResult<()> { let ss = cm.span_to_str(sp); let lines = cm.span_to_lines(sp); if custom { @@ -272,19 +283,19 @@ fn emit(cm: &codemap::CodeMap, sp: Span, // the span) let span_end = Span { lo: sp.hi, hi: sp.hi, expn_info: sp.expn_info}; let ses = cm.span_to_str(span_end); - print_diagnostic(ses, lvl, msg); - custom_highlight_lines(cm, sp, lvl, lines); + if_ok!(print_diagnostic(ses, lvl, msg)); + if_ok!(custom_highlight_lines(cm, sp, lvl, lines)); } else { - print_diagnostic(ss, lvl, msg); - highlight_lines(cm, sp, lvl, lines); + if_ok!(print_diagnostic(ss, lvl, msg)); + if_ok!(highlight_lines(cm, sp, lvl, lines)); } - print_macro_backtrace(cm, sp); + print_macro_backtrace(cm, sp) } fn highlight_lines(cm: &codemap::CodeMap, sp: Span, lvl: Level, - lines: &codemap::FileLines) { + lines: &codemap::FileLines) -> io::IoResult<()> { let fm = lines.file; let mut err = io::stderr(); let err = &mut err as &mut io::Writer; @@ -297,12 +308,13 @@ fn highlight_lines(cm: &codemap::CodeMap, } // Print the offending lines for line in display_lines.iter() { - write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int)); + if_ok!(write!(err, "{}:{} {}\n", fm.name, *line + 1, + fm.get_line(*line as int))); } if elided { let last_line = display_lines[display_lines.len() - 1u]; let s = format!("{}:{} ", fm.name, last_line + 1u); - write!(err, "{0:1$}...\n", "", s.len()); + if_ok!(write!(err, "{0:1$}...\n", "", s.len())); } // FIXME (#3260) @@ -334,7 +346,7 @@ fn highlight_lines(cm: &codemap::CodeMap, _ => s.push_char(' '), }; } - write!(err, "{}", s); + if_ok!(write!(err, "{}", s)); let mut s = ~"^"; let hi = cm.lookup_char_pos(sp.hi); if hi.col != lo.col { @@ -342,8 +354,10 @@ fn highlight_lines(cm: &codemap::CodeMap, let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u; for _ in range(0, num_squigglies) { s.push_char('~'); } } - print_maybe_styled(s + "\n", term::attr::ForegroundColor(lvl.color())); + if_ok!(print_maybe_styled(s + "\n", + term::attr::ForegroundColor(lvl.color()))); } + Ok(()) } // Here are the differences between this and the normal `highlight_lines`: @@ -355,23 +369,23 @@ fn highlight_lines(cm: &codemap::CodeMap, fn custom_highlight_lines(cm: &codemap::CodeMap, sp: Span, lvl: Level, - lines: &codemap::FileLines) { + lines: &codemap::FileLines) -> io::IoResult<()> { let fm = lines.file; let mut err = io::stderr(); let err = &mut err as &mut io::Writer; let lines = lines.lines.as_slice(); if lines.len() > MAX_LINES { - write!(err, "{}:{} {}\n", fm.name, - lines[0] + 1, fm.get_line(lines[0] as int)); - write!(err, "...\n"); + if_ok!(write!(err, "{}:{} {}\n", fm.name, + lines[0] + 1, fm.get_line(lines[0] as int))); + if_ok!(write!(err, "...\n")); let last_line = lines[lines.len()-1]; - write!(err, "{}:{} {}\n", fm.name, - last_line + 1, fm.get_line(last_line as int)); + if_ok!(write!(err, "{}:{} {}\n", fm.name, + last_line + 1, fm.get_line(last_line as int))); } else { for line in lines.iter() { - write!(err, "{}:{} {}\n", fm.name, - *line + 1, fm.get_line(*line as int)); + if_ok!(write!(err, "{}:{} {}\n", fm.name, + *line + 1, fm.get_line(*line as int))); } } let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1]+1); @@ -381,22 +395,24 @@ fn custom_highlight_lines(cm: &codemap::CodeMap, let mut s = ~""; for _ in range(0, skip) { s.push_char(' '); } s.push_char('^'); - print_maybe_styled(s + "\n", term::attr::ForegroundColor(lvl.color())); + print_maybe_styled(s + "\n", term::attr::ForegroundColor(lvl.color())) } -fn print_macro_backtrace(cm: &codemap::CodeMap, sp: Span) { +fn print_macro_backtrace(cm: &codemap::CodeMap, sp: Span) -> io::IoResult<()> { for ei in sp.expn_info.iter() { let ss = ei.callee.span.as_ref().map_or(~"", |span| cm.span_to_str(*span)); let (pre, post) = match ei.callee.format { codemap::MacroAttribute => ("#[", "]"), codemap::MacroBang => ("", "!") }; - print_diagnostic(ss, Note, - format!("in expansion of {}{}{}", pre, ei.callee.name, post)); + if_ok!(print_diagnostic(ss, Note, + format!("in expansion of {}{}{}", pre, + ei.callee.name, post))); let ss = cm.span_to_str(ei.call_site); - print_diagnostic(ss, Note, "expansion site"); - print_macro_backtrace(cm, ei.call_site); + if_ok!(print_diagnostic(ss, Note, "expansion site")); + if_ok!(print_macro_backtrace(cm, ei.call_site)); } + Ok(()) } pub fn expect(diag: @SpanHandler, opt: Option, msg: || -> ~str) diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index f3f947ec00d..52010b39a54 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -20,7 +20,6 @@ use parse::token::get_ident_interner; use parse::token; use print::pprust; -use std::io; use std::io::File; use std::rc::Rc; use std::str; @@ -109,9 +108,9 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) None => return MacResult::dummy_expr() }; let file = res_rel_file(cx, sp, &Path::new(file)); - let bytes = match io::result(|| File::open(&file).read_to_end()) { + let bytes = match File::open(&file).read_to_end() { Err(e) => { - cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e.desc)); + cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e)); return MacResult::dummy_expr(); } Ok(bytes) => bytes, @@ -141,9 +140,9 @@ pub fn expand_include_bin(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) None => return MacResult::dummy_expr() }; let file = res_rel_file(cx, sp, &Path::new(file)); - match io::result(|| File::open(&file).read_to_end()) { + match File::open(&file).read_to_end() { Err(e) => { - cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e.desc)); + cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e)); return MacResult::dummy_expr(); } Ok(bytes) => { diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index e2460b0171a..e2aa9e3b3ee 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -33,6 +33,11 @@ This API is completely unstable and subject to change. extern mod extra; extern mod term; +#[cfg(stage0)] +macro_rules! if_ok ( + ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) }) +) + pub mod util { pub mod interner; #[cfg(test)] diff --git a/src/libsyntax/parse/comments.rs b/src/libsyntax/parse/comments.rs index 7165e7b404f..f65bc3ad7a3 100644 --- a/src/libsyntax/parse/comments.rs +++ b/src/libsyntax/parse/comments.rs @@ -350,7 +350,8 @@ pub fn gather_comments_and_literals(span_diagnostic: path: ~str, srdr: &mut io::Reader) -> (~[Comment], ~[Literal]) { - let src = str::from_utf8_owned(srdr.read_to_end()).unwrap(); + let src = srdr.read_to_end().unwrap(); + let src = str::from_utf8_owned(src).unwrap(); let cm = CodeMap::new(); let filemap = cm.new_filemap(path, src); let rdr = lexer::new_low_level_string_reader(span_diagnostic, filemap); diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index cec9f7c2d9f..328f0e7f221 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -19,7 +19,6 @@ use parse::attr::ParserAttr; use parse::parser::Parser; use std::cell::RefCell; -use std::io; use std::io::File; use std::str; @@ -232,10 +231,10 @@ pub fn file_to_filemap(sess: @ParseSess, path: &Path, spanopt: Option) None => sess.span_diagnostic.handler().fatal(msg), } }; - let bytes = match io::result(|| File::open(path).read_to_end()) { + let bytes = match File::open(path).read_to_end() { Ok(bytes) => bytes, Err(e) => { - err(format!("couldn't read {}: {}", path.display(), e.desc)); + err(format!("couldn't read {}: {}", path.display(), e)); unreachable!() } }; diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 3e1f5b4cfb3..bb287c0f5f8 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -292,7 +292,7 @@ impl Printer { pub fn replace_last_token(&mut self, t: Token) { self.token[self.right] = t; } - pub fn pretty_print(&mut self, t: Token) { + pub fn pretty_print(&mut self, t: Token) -> io::IoResult<()> { debug!("pp ~[{},{}]", self.left, self.right); match t { Eof => { @@ -301,31 +301,19 @@ impl Printer { let left = self.token[self.left].clone(); self.advance_left(left, self.size[self.left]); } - self.indent(0); - } - Begin(b) => { - if self.scan_stack_empty { - self.left_total = 1; - self.right_total = 1; - self.left = 0u; - self.right = 0u; - } else { self.advance_right(); } - debug!("pp Begin({})/buffer ~[{},{}]", - b.offset, self.left, self.right); - self.token[self.right] = t; - self.size[self.right] = -self.right_total; - self.scan_push(self.right); - } - End => { - if self.scan_stack_empty { - debug!("pp End/print ~[{},{}]", self.left, self.right); - self.print(t, 0); - } else { - debug!("pp End/buffer ~[{},{}]", self.left, self.right); - self.advance_right(); + Begin(b) => { + if self.scan_stack_empty { + self.left_total = 1; + self.right_total = 1; + self.left = 0u; + self.right = 0u; + } else { self.advance_right(); } + debug!("pp Begin({})/buffer ~[{},{}]", + b.offset, self.left, self.right); self.token[self.right] = t; - self.size[self.right] = -1; + self.size[self.right] = -self.right_total; self.scan_push(self.right); + Ok(()) } } Break(b) => { @@ -357,10 +345,9 @@ impl Printer { self.right_total += len; self.check_stream(); } - } } } - pub fn check_stream(&mut self) { + pub fn check_stream(&mut self) -> io::IoResult<()> { debug!("check_stream ~[{}, {}] with left_total={}, right_total={}", self.left, self.right, self.left_total, self.right_total); if self.right_total - self.left_total > self.space { @@ -376,6 +363,7 @@ impl Printer { self.advance_left(left, self.size[self.left]); if self.left != self.right { self.check_stream(); } } + Ok(()) } pub fn scan_push(&mut self, x: uint) { debug!("scan_push {}", x); @@ -413,7 +401,7 @@ impl Printer { self.right %= self.buf_len; assert!((self.right != self.left)); } - pub fn advance_left(&mut self, x: Token, L: int) { + pub fn advance_left(&mut self, x: Token, L: int) -> io::IoResult<()> { debug!("advnce_left ~[{},{}], sizeof({})={}", self.left, self.right, self.left, L); if L >= 0 { @@ -431,6 +419,9 @@ impl Printer { let left = self.token[self.left].clone(); self.advance_left(left, self.size[self.left]); } + ret + } else { + Ok(()) } } pub fn check_stack(&mut self, k: int) { @@ -456,11 +447,12 @@ impl Printer { } } } - pub fn print_newline(&mut self, amount: int) { + pub fn print_newline(&mut self, amount: int) -> io::IoResult<()> { debug!("NEWLINE {}", amount); - write!(self.out, "\n"); + let ret = write!(self.out, "\n"); self.pending_indentation = 0; self.indent(amount); + return ret; } pub fn indent(&mut self, amount: int) { debug!("INDENT {}", amount); @@ -478,12 +470,12 @@ impl Printer { } } } - pub fn print_str(&mut self, s: &str) { + pub fn print_str(&mut self, s: &str) -> io::IoResult<()> { while self.pending_indentation > 0 { - write!(self.out, " "); + if_ok!(write!(self.out, " ")); self.pending_indentation -= 1; } - write!(self.out, "{}", s); + write!(self.out, "{}", s) } pub fn print(&mut self, x: Token, L: int) { debug!("print {} {} (remaining line space={})", tok_str(x.clone()), L, @@ -509,12 +501,14 @@ impl Printer { pbreak: Fits }); } + Ok(()) } End => { debug!("print End -> pop End"); let print_stack = &mut self.print_stack; assert!((print_stack.len() != 0u)); print_stack.pop().unwrap(); + Ok(()) } Break(b) => { let top = self.get_top(); @@ -523,24 +517,28 @@ impl Printer { debug!("print Break({}) in fitting block", b.blank_space); self.space -= b.blank_space; self.indent(b.blank_space); + Ok(()) } Broken(Consistent) => { debug!("print Break({}+{}) in consistent block", top.offset, b.offset); - self.print_newline(top.offset + b.offset); + let ret = self.print_newline(top.offset + b.offset); self.space = self.margin - (top.offset + b.offset); + ret } Broken(Inconsistent) => { if L > self.space { debug!("print Break({}+{}) w/ newline in inconsistent", top.offset, b.offset); - self.print_newline(top.offset + b.offset); + let ret = self.print_newline(top.offset + b.offset); self.space = self.margin - (top.offset + b.offset); + ret } else { debug!("print Break({}) w/o newline in inconsistent", b.blank_space); self.indent(b.blank_space); self.space -= b.blank_space; + Ok(()) } } } @@ -550,7 +548,7 @@ impl Printer { assert_eq!(L, len); // assert!(L <= space); self.space -= len; - self.print_str(s); + self.print_str(s) } Eof => { // Eof should never get here. @@ -563,27 +561,31 @@ impl Printer { // Convenience functions to talk to the printer. // // "raw box" -pub fn rbox(p: &mut Printer, indent: uint, b: Breaks) { +pub fn rbox(p: &mut Printer, indent: uint, b: Breaks) -> io::IoResult<()> { p.pretty_print(Begin(BeginToken { offset: indent as int, breaks: b - })); + })) } -pub fn ibox(p: &mut Printer, indent: uint) { rbox(p, indent, Inconsistent); } +pub fn ibox(p: &mut Printer, indent: uint) -> io::IoResult<()> { + rbox(p, indent, Inconsistent) +} -pub fn cbox(p: &mut Printer, indent: uint) { rbox(p, indent, Consistent); } +pub fn cbox(p: &mut Printer, indent: uint) -> io::IoResult<()> { + rbox(p, indent, Consistent) +} -pub fn break_offset(p: &mut Printer, n: uint, off: int) { +pub fn break_offset(p: &mut Printer, n: uint, off: int) -> io::IoResult<()> { p.pretty_print(Break(BreakToken { offset: off, blank_space: n as int - })); + })) } -pub fn end(p: &mut Printer) { p.pretty_print(End); } +pub fn end(p: &mut Printer) -> io::IoResult<()> { p.pretty_print(End) } -pub fn eof(p: &mut Printer) { p.pretty_print(Eof); } +pub fn eof(p: &mut Printer) -> io::IoResult<()> { p.pretty_print(Eof) } pub fn word(p: &mut Printer, wrd: &str) { p.pretty_print(String(/* bad */ wrd.to_str(), wrd.len() as int)); @@ -597,13 +599,21 @@ pub fn zero_word(p: &mut Printer, wrd: &str) { p.pretty_print(String(/* bad */ wrd.to_str(), 0)); } -pub fn spaces(p: &mut Printer, n: uint) { break_offset(p, n, 0); } +pub fn spaces(p: &mut Printer, n: uint) -> io::IoResult<()> { + break_offset(p, n, 0) +} -pub fn zerobreak(p: &mut Printer) { spaces(p, 0u); } +pub fn zerobreak(p: &mut Printer) -> io::IoResult<()> { + spaces(p, 0u) +} -pub fn space(p: &mut Printer) { spaces(p, 1u); } +pub fn space(p: &mut Printer) -> io::IoResult<()> { + spaces(p, 1u) +} -pub fn hardbreak(p: &mut Printer) { spaces(p, SIZE_INFINITY as uint); } +pub fn hardbreak(p: &mut Printer) -> io::IoResult<()> { + spaces(p, SIZE_INFINITY as uint) +} pub fn hardbreak_tok_offset(off: int) -> Token { Break(BreakToken {offset: off, blank_space: SIZE_INFINITY}) diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 037c69eb918..17b0b7b9c38 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -43,8 +43,8 @@ pub enum AnnNode<'a,'b> { } pub trait PpAnn { - fn pre(&self, _node: AnnNode) {} - fn post(&self, _node: AnnNode) {} + fn pre(&self, _node: AnnNode) -> io::IoResult<()> { Ok(()) } + fn post(&self, _node: AnnNode) -> io::IoResult<()> { Ok(()) } } pub struct NoAnn; @@ -67,20 +67,20 @@ pub struct State { ann: @PpAnn } -pub fn ibox(s: &mut State, u: uint) { +pub fn ibox(s: &mut State, u: uint) -> io::IoResult<()> { { let mut boxes = s.boxes.borrow_mut(); boxes.get().push(pp::Inconsistent); } - pp::ibox(&mut s.s, u); + pp::ibox(&mut s.s, u) } -pub fn end(s: &mut State) { +pub fn end(s: &mut State) -> io::IoResult<()> { { let mut boxes = s.boxes.borrow_mut(); boxes.get().pop().unwrap(); } - pp::end(&mut s.s); + pp::end(&mut s.s) } pub fn rust_printer(writer: ~io::Writer, intr: @IdentInterner) -> State { @@ -121,7 +121,7 @@ pub fn print_crate(cm: @CodeMap, input: &mut io::Reader, out: ~io::Writer, ann: @PpAnn, - is_expanded: bool) { + is_expanded: bool) -> io::IoResult<()> { let (cmnts, lits) = comments::gather_comments_and_literals( span_diagnostic, filename, @@ -147,13 +147,14 @@ pub fn print_crate(cm: @CodeMap, boxes: RefCell::new(~[]), ann: ann }; - print_crate_(&mut s, crate); + print_crate_(&mut s, crate) } -pub fn print_crate_(s: &mut State, crate: &ast::Crate) { - print_mod(s, &crate.module, crate.attrs); - print_remaining_comments(s); - eof(&mut s.s); +pub fn print_crate_(s: &mut State, crate: &ast::Crate) -> io::IoResult<()> { + if_ok!(print_mod(s, &crate.module, crate.attrs)); + if_ok!(print_remaining_comments(s)); + if_ok!(eof(&mut s.s)); + Ok(()) } pub fn ty_to_str(ty: &ast::Ty, intr: @IdentInterner) -> ~str { @@ -203,10 +204,10 @@ pub fn fun_to_str(decl: &ast::FnDecl, purity: ast::Purity, name: ast::Ident, let wr = ~MemWriter::new(); let mut s = rust_printer(wr as ~io::Writer, intr); print_fn(&mut s, decl, Some(purity), AbiSet::Rust(), - name, generics, opt_explicit_self, ast::Inherited); - end(&mut s); // Close the head box - end(&mut s); // Close the outer box - eof(&mut s.s); + name, generics, opt_explicit_self, ast::Inherited).unwrap(); + end(&mut s).unwrap(); // Close the head box + end(&mut s).unwrap(); // Close the outer box + eof(&mut s.s).unwrap(); unsafe { get_mem_writer(&mut s.s.out) } @@ -216,11 +217,11 @@ pub fn block_to_str(blk: &ast::Block, intr: @IdentInterner) -> ~str { let wr = ~MemWriter::new(); let mut s = rust_printer(wr as ~io::Writer, intr); // containing cbox, will be closed by print-block at } - cbox(&mut s, indent_unit); + cbox(&mut s, indent_unit).unwrap(); // head-ibox, will be closed by print-block after { - ibox(&mut s, 0u); - print_block(&mut s, blk); - eof(&mut s.s); + ibox(&mut s, 0u).unwrap(); + print_block(&mut s, blk).unwrap(); + eof(&mut s.s).unwrap(); unsafe { get_mem_writer(&mut s.s.out) } @@ -238,63 +239,73 @@ pub fn variant_to_str(var: &ast::Variant, intr: @IdentInterner) -> ~str { to_str(var, print_variant, intr) } -pub fn cbox(s: &mut State, u: uint) { +pub fn cbox(s: &mut State, u: uint) -> io::IoResult<()> { { let mut boxes = s.boxes.borrow_mut(); boxes.get().push(pp::Consistent); } - pp::cbox(&mut s.s, u); + pp::cbox(&mut s.s, u) } // "raw box" -pub fn rbox(s: &mut State, u: uint, b: pp::Breaks) { +pub fn rbox(s: &mut State, u: uint, b: pp::Breaks) -> io::IoResult<()> { { let mut boxes = s.boxes.borrow_mut(); boxes.get().push(b); } - pp::rbox(&mut s.s, u, b); + pp::rbox(&mut s.s, u, b) } -pub fn nbsp(s: &mut State) { word(&mut s.s, " "); } +pub fn nbsp(s: &mut State) -> io::IoResult<()> { word(&mut s.s, " ") } -pub fn word_nbsp(s: &mut State, w: &str) { word(&mut s.s, w); nbsp(s); } +pub fn word_nbsp(s: &mut State, w: &str) -> io::IoResult<()> { + if_ok!(word(&mut s.s, w)); + nbsp(s) +} -pub fn word_space(s: &mut State, w: &str) { word(&mut s.s, w); space(&mut s.s); } +pub fn word_space(s: &mut State, w: &str) -> io::IoResult<()> { + if_ok!(word(&mut s.s, w)); + space(&mut s.s) +} -pub fn popen(s: &mut State) { word(&mut s.s, "("); } +pub fn popen(s: &mut State) -> io::IoResult<()> { word(&mut s.s, "(") } -pub fn pclose(s: &mut State) { word(&mut s.s, ")"); } +pub fn pclose(s: &mut State) -> io::IoResult<()> { word(&mut s.s, ")") } -pub fn head(s: &mut State, w: &str) { +pub fn head(s: &mut State, w: &str) -> io::IoResult<()> { // outer-box is consistent - cbox(s, indent_unit); + if_ok!(cbox(s, indent_unit)); // head-box is inconsistent - ibox(s, w.len() + 1); + if_ok!(ibox(s, w.len() + 1)); // keyword that starts the head if !w.is_empty() { - word_nbsp(s, w); + if_ok!(word_nbsp(s, w)); } + Ok(()) } -pub fn bopen(s: &mut State) { - word(&mut s.s, "{"); - end(s); // close the head-box +pub fn bopen(s: &mut State) -> io::IoResult<()> { + if_ok!(word(&mut s.s, "{")); + if_ok!(end(s)); // close the head-box + Ok(()) } -pub fn bclose_(s: &mut State, span: codemap::Span, indented: uint) { - bclose_maybe_open(s, span, indented, true); +pub fn bclose_(s: &mut State, span: codemap::Span, + indented: uint) -> io::IoResult<()> { + bclose_maybe_open(s, span, indented, true) } pub fn bclose_maybe_open (s: &mut State, span: codemap::Span, - indented: uint, close_box: bool) { - maybe_print_comment(s, span.hi); - break_offset_if_not_bol(s, 1u, -(indented as int)); - word(&mut s.s, "}"); + indented: uint, close_box: bool) -> io::IoResult<()> { + if_ok!(maybe_print_comment(s, span.hi)); + if_ok!(break_offset_if_not_bol(s, 1u, -(indented as int))); + if_ok!(word(&mut s.s, "}")); if close_box { - end(s); // close the outer-box + if_ok!(end(s)); // close the outer-box } + Ok(()) } -pub fn bclose(s: &mut State, span: codemap::Span) { - bclose_(s, span, indent_unit); +pub fn bclose(s: &mut State, span: codemap::Span) -> io::IoResult<()> { + bclose_(s, span, indent_unit) } pub fn is_begin(s: &mut State) -> bool { @@ -316,15 +327,20 @@ pub fn in_cbox(s: &mut State) -> bool { return boxes.get()[len - 1u] == pp::Consistent; } -pub fn hardbreak_if_not_bol(s: &mut State) { +pub fn hardbreak_if_not_bol(s: &mut State) -> io::IoResult<()> { if !is_bol(s) { - hardbreak(&mut s.s) + if_ok!(hardbreak(&mut s.s)) } + Ok(()) +} +pub fn space_if_not_bol(s: &mut State) -> io::IoResult<()> { + if !is_bol(s) { if_ok!(space(&mut s.s)); } + Ok(()) } -pub fn space_if_not_bol(s: &mut State) { if !is_bol(s) { space(&mut s.s); } } -pub fn break_offset_if_not_bol(s: &mut State, n: uint, off: int) { +pub fn break_offset_if_not_bol(s: &mut State, n: uint, + off: int) -> io::IoResult<()> { if !is_bol(s) { - break_offset(&mut s.s, n, off); + if_ok!(break_offset(&mut s.s, n, off)); } else { if off != 0 && s.s.last_token().is_hardbreak_tok() { // We do something pretty sketchy here: tuck the nonzero @@ -333,26 +349,31 @@ pub fn break_offset_if_not_bol(s: &mut State, n: uint, off: int) { s.s.replace_last_token(pp::hardbreak_tok_offset(off)); } } + Ok(()) } // Synthesizes a comment that was not textually present in the original source // file. -pub fn synth_comment(s: &mut State, text: ~str) { - word(&mut s.s, "/*"); - space(&mut s.s); - word(&mut s.s, text); - space(&mut s.s); - word(&mut s.s, "*/"); -} - -pub fn commasep(s: &mut State, b: Breaks, elts: &[T], op: |&mut State, &T|) { - rbox(s, 0u, b); +pub fn synth_comment(s: &mut State, text: ~str) -> io::IoResult<()> { + if_ok!(word(&mut s.s, "/*")); + if_ok!(space(&mut s.s)); + if_ok!(word(&mut s.s, text)); + if_ok!(space(&mut s.s)); + if_ok!(word(&mut s.s, "*/")); + Ok(()) +} + +pub fn commasep(s: &mut State, b: Breaks, elts: &[T], + op: |&mut State, &T| -> io::IoResult<()>) + -> io::IoResult<()> +{ + if_ok!(rbox(s, 0u, b)); let mut first = true; for elt in elts.iter() { - if first { first = false; } else { word_space(s, ","); } - op(s, elt); + if first { first = false; } else { if_ok!(word_space(s, ",")); } + if_ok!(op(s, elt)); } - end(s); + end(s) } @@ -360,177 +381,200 @@ pub fn commasep_cmnt( s: &mut State, b: Breaks, elts: &[T], - op: |&mut State, &T|, - get_span: |&T| -> codemap::Span) { - rbox(s, 0u, b); + op: |&mut State, &T| -> io::IoResult<()>, + get_span: |&T| -> codemap::Span) -> io::IoResult<()> { + if_ok!(rbox(s, 0u, b)); let len = elts.len(); let mut i = 0u; for elt in elts.iter() { - maybe_print_comment(s, get_span(elt).hi); - op(s, elt); + if_ok!(maybe_print_comment(s, get_span(elt).hi)); + if_ok!(op(s, elt)); i += 1u; if i < len { - word(&mut s.s, ","); - maybe_print_trailing_comment(s, get_span(elt), - Some(get_span(&elts[i]).hi)); - space_if_not_bol(s); + if_ok!(word(&mut s.s, ",")); + if_ok!(maybe_print_trailing_comment(s, get_span(elt), + Some(get_span(&elts[i]).hi))); + if_ok!(space_if_not_bol(s)); } } - end(s); + end(s) } -pub fn commasep_exprs(s: &mut State, b: Breaks, exprs: &[@ast::Expr]) { - commasep_cmnt(s, b, exprs, |p, &e| print_expr(p, e), |e| e.span); +pub fn commasep_exprs(s: &mut State, b: Breaks, + exprs: &[@ast::Expr]) -> io::IoResult<()> { + commasep_cmnt(s, b, exprs, |p, &e| print_expr(p, e), |e| e.span) } -pub fn print_mod(s: &mut State, _mod: &ast::Mod, attrs: &[ast::Attribute]) { - print_inner_attributes(s, attrs); +pub fn print_mod(s: &mut State, _mod: &ast::Mod, + attrs: &[ast::Attribute]) -> io::IoResult<()> { + if_ok!(print_inner_attributes(s, attrs)); for vitem in _mod.view_items.iter() { - print_view_item(s, vitem); + if_ok!(print_view_item(s, vitem)); } - for item in _mod.items.iter() { print_item(s, *item); } + for item in _mod.items.iter() { + if_ok!(print_item(s, *item)); + } + Ok(()) } pub fn print_foreign_mod(s: &mut State, nmod: &ast::ForeignMod, - attrs: &[ast::Attribute]) { - print_inner_attributes(s, attrs); + attrs: &[ast::Attribute]) -> io::IoResult<()> { + if_ok!(print_inner_attributes(s, attrs)); for vitem in nmod.view_items.iter() { - print_view_item(s, vitem); + if_ok!(print_view_item(s, vitem)); + } + for item in nmod.items.iter() { + if_ok!(print_foreign_item(s, *item)); } - for item in nmod.items.iter() { print_foreign_item(s, *item); } + Ok(()) } -pub fn print_opt_lifetime(s: &mut State, lifetime: &Option) { +pub fn print_opt_lifetime(s: &mut State, + lifetime: &Option) -> io::IoResult<()> { for l in lifetime.iter() { - print_lifetime(s, l); - nbsp(s); + if_ok!(print_lifetime(s, l)); + if_ok!(nbsp(s)); } + Ok(()) } -pub fn print_type(s: &mut State, ty: &ast::Ty) { - maybe_print_comment(s, ty.span.lo); - ibox(s, 0u); +pub fn print_type(s: &mut State, ty: &ast::Ty) -> io::IoResult<()> { + if_ok!(maybe_print_comment(s, ty.span.lo)); + if_ok!(ibox(s, 0u)); match ty.node { - ast::TyNil => word(&mut s.s, "()"), - ast::TyBot => word(&mut s.s, "!"), - ast::TyBox(ty) => { word(&mut s.s, "@"); print_type(s, ty); } - ast::TyUniq(ty) => { word(&mut s.s, "~"); print_type(s, ty); } + ast::TyNil => if_ok!(word(&mut s.s, "()")), + ast::TyBot => if_ok!(word(&mut s.s, "!")), + ast::TyBox(ty) => { + if_ok!(word(&mut s.s, "@")); + if_ok!(print_type(s, ty)); + } + ast::TyUniq(ty) => { + if_ok!(word(&mut s.s, "~")); + if_ok!(print_type(s, ty)); + } ast::TyVec(ty) => { - word(&mut s.s, "["); - print_type(s, ty); - word(&mut s.s, "]"); + if_ok!(word(&mut s.s, "[")); + if_ok!(print_type(s, ty)); + if_ok!(word(&mut s.s, "]")); + } + ast::TyPtr(ref mt) => { + if_ok!(word(&mut s.s, "*")); + if_ok!(print_mt(s, mt)); } - ast::TyPtr(ref mt) => { word(&mut s.s, "*"); print_mt(s, mt); } ast::TyRptr(ref lifetime, ref mt) => { - word(&mut s.s, "&"); - print_opt_lifetime(s, lifetime); - print_mt(s, mt); + if_ok!(word(&mut s.s, "&")); + if_ok!(print_opt_lifetime(s, lifetime)); + if_ok!(print_mt(s, mt)); } ast::TyTup(ref elts) => { - popen(s); - commasep(s, Inconsistent, *elts, print_type_ref); + if_ok!(popen(s)); + if_ok!(commasep(s, Inconsistent, *elts, print_type_ref)); if elts.len() == 1 { - word(&mut s.s, ","); + if_ok!(word(&mut s.s, ",")); } - pclose(s); + if_ok!(pclose(s)); } ast::TyBareFn(f) => { let generics = ast::Generics { lifetimes: f.lifetimes.clone(), ty_params: opt_vec::Empty }; - print_ty_fn(s, Some(f.abis), None, &None, - f.purity, ast::Many, f.decl, None, &None, - Some(&generics), None); + if_ok!(print_ty_fn(s, Some(f.abis), None, &None, + f.purity, ast::Many, f.decl, None, &None, + Some(&generics), None)); } ast::TyClosure(f) => { let generics = ast::Generics { lifetimes: f.lifetimes.clone(), ty_params: opt_vec::Empty }; - print_ty_fn(s, None, Some(f.sigil), &f.region, - f.purity, f.onceness, f.decl, None, &f.bounds, - Some(&generics), None); + if_ok!(print_ty_fn(s, None, Some(f.sigil), &f.region, + f.purity, f.onceness, f.decl, None, &f.bounds, + Some(&generics), None)); + } + ast::TyPath(ref path, ref bounds, _) => { + if_ok!(print_bounded_path(s, path, bounds)); } - ast::TyPath(ref path, ref bounds, _) => print_bounded_path(s, path, bounds), ast::TyFixedLengthVec(ty, v) => { - word(&mut s.s, "["); - print_type(s, ty); - word(&mut s.s, ", .."); - print_expr(s, v); - word(&mut s.s, "]"); + if_ok!(word(&mut s.s, "[")); + if_ok!(print_type(s, ty)); + if_ok!(word(&mut s.s, ", ..")); + if_ok!(print_expr(s, v)); + if_ok!(word(&mut s.s, "]")); } ast::TyTypeof(e) => { - word(&mut s.s, "typeof("); - print_expr(s, e); - word(&mut s.s, ")"); + if_ok!(word(&mut s.s, "typeof(")); + if_ok!(print_expr(s, e)); + if_ok!(word(&mut s.s, ")")); } ast::TyInfer => { fail!("print_type shouldn't see a ty_infer"); } } - end(s); + end(s) } -pub fn print_type_ref(s: &mut State, ty: &P) { - print_type(s, *ty); +pub fn print_type_ref(s: &mut State, ty: &P) -> io::IoResult<()> { + print_type(s, *ty) } -pub fn print_foreign_item(s: &mut State, item: &ast::ForeignItem) { - hardbreak_if_not_bol(s); - maybe_print_comment(s, item.span.lo); - print_outer_attributes(s, item.attrs); +pub fn print_foreign_item(s: &mut State, + item: &ast::ForeignItem) -> io::IoResult<()> { + if_ok!(hardbreak_if_not_bol(s)); + if_ok!(maybe_print_comment(s, item.span.lo)); + if_ok!(print_outer_attributes(s, item.attrs)); match item.node { - ast::ForeignItemFn(decl, ref generics) => { - print_fn(s, decl, None, AbiSet::Rust(), item.ident, generics, None, - item.vis); - end(s); // end head-ibox - word(&mut s.s, ";"); - end(s); // end the outer fn box - } - ast::ForeignItemStatic(t, m) => { - head(s, visibility_qualified(item.vis, "static")); - if m { - word_space(s, "mut"); - } - print_ident(s, item.ident); - word_space(s, ":"); - print_type(s, t); - word(&mut s.s, ";"); - end(s); // end the head-ibox - end(s); // end the outer cbox - } + ast::ForeignItemFn(decl, ref generics) => { + if_ok!(print_fn(s, decl, None, AbiSet::Rust(), item.ident, generics, + None, item.vis)); + if_ok!(end(s)); // end head-ibox + if_ok!(word(&mut s.s, ";")); + if_ok!(end(s)); // end the outer fn box + } + ast::ForeignItemStatic(t, m) => { + if_ok!(head(s, visibility_qualified(item.vis, "static"))); + if m { + if_ok!(word_space(s, "mut")); + } + if_ok!(print_ident(s, item.ident)); + if_ok!(word_space(s, ":")); + if_ok!(print_type(s, t)); + if_ok!(word(&mut s.s, ";")); + if_ok!(end(s)); // end the head-ibox + if_ok!(end(s)); // end the outer cbox + } } + Ok(()) } -pub fn print_item(s: &mut State, item: &ast::Item) { - hardbreak_if_not_bol(s); - maybe_print_comment(s, item.span.lo); - print_outer_attributes(s, item.attrs); +pub fn print_item(s: &mut State, item: &ast::Item) -> io::IoResult<()> { + if_ok!(hardbreak_if_not_bol(s)); + if_ok!(maybe_print_comment(s, item.span.lo)); + if_ok!(print_outer_attributes(s, item.attrs)); { let ann_node = NodeItem(s, item); - s.ann.pre(ann_node); + if_ok!(s.ann.pre(ann_node)); } match item.node { ast::ItemStatic(ty, m, expr) => { - head(s, visibility_qualified(item.vis, "static")); + if_ok!(head(s, visibility_qualified(item.vis, "static"))); if m == ast::MutMutable { - word_space(s, "mut"); + if_ok!(word_space(s, "mut")); } - print_ident(s, item.ident); - word_space(s, ":"); - print_type(s, ty); - space(&mut s.s); - end(s); // end the head-ibox + if_ok!(print_ident(s, item.ident)); + if_ok!(word_space(s, ":")); + if_ok!(print_type(s, ty)); + if_ok!(space(&mut s.s)); + if_ok!(end(s)); // end the head-ibox - word_space(s, "="); - print_expr(s, expr); - word(&mut s.s, ";"); - end(s); // end the outer cbox + if_ok!(word_space(s, "=")); + if_ok!(print_expr(s, expr)); + if_ok!(word(&mut s.s, ";")); + if_ok!(end(s)); // end the outer cbox } ast::ItemFn(decl, purity, abi, ref typarams, body) => { - print_fn( + if_ok!(print_fn( s, decl, Some(purity), @@ -539,150 +583,153 @@ pub fn print_item(s: &mut State, item: &ast::Item) { typarams, None, item.vis - ); - word(&mut s.s, " "); - print_block_with_attrs(s, body, item.attrs); + )); + if_ok!(word(&mut s.s, " ")); + if_ok!(print_block_with_attrs(s, body, item.attrs)); } ast::ItemMod(ref _mod) => { - head(s, visibility_qualified(item.vis, "mod")); - print_ident(s, item.ident); - nbsp(s); - bopen(s); - print_mod(s, _mod, item.attrs); - bclose(s, item.span); + if_ok!(head(s, visibility_qualified(item.vis, "mod"))); + if_ok!(print_ident(s, item.ident)); + if_ok!(nbsp(s)); + if_ok!(bopen(s)); + if_ok!(print_mod(s, _mod, item.attrs)); + if_ok!(bclose(s, item.span)); } ast::ItemForeignMod(ref nmod) => { - head(s, "extern"); - word_nbsp(s, nmod.abis.to_str()); - bopen(s); - print_foreign_mod(s, nmod, item.attrs); - bclose(s, item.span); + if_ok!(head(s, "extern")); + if_ok!(word_nbsp(s, nmod.abis.to_str())); + if_ok!(bopen(s)); + if_ok!(print_foreign_mod(s, nmod, item.attrs)); + if_ok!(bclose(s, item.span)); } ast::ItemTy(ty, ref params) => { - ibox(s, indent_unit); - ibox(s, 0u); - word_nbsp(s, visibility_qualified(item.vis, "type")); - print_ident(s, item.ident); - print_generics(s, params); - end(s); // end the inner ibox - - space(&mut s.s); - word_space(s, "="); - print_type(s, ty); - word(&mut s.s, ";"); - end(s); // end the outer ibox + if_ok!(ibox(s, indent_unit)); + if_ok!(ibox(s, 0u)); + if_ok!(word_nbsp(s, visibility_qualified(item.vis, "type"))); + if_ok!(print_ident(s, item.ident)); + if_ok!(print_generics(s, params)); + if_ok!(end(s)); // end the inner ibox + + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, "=")); + if_ok!(print_type(s, ty)); + if_ok!(word(&mut s.s, ";")); + if_ok!(end(s)); // end the outer ibox } ast::ItemEnum(ref enum_definition, ref params) => { - print_enum_def( + if_ok!(print_enum_def( s, enum_definition, params, item.ident, item.span, item.vis - ); + )); } ast::ItemStruct(struct_def, ref generics) => { - head(s, visibility_qualified(item.vis, "struct")); - print_struct(s, struct_def, generics, item.ident, item.span); + if_ok!(head(s, visibility_qualified(item.vis, "struct"))); + if_ok!(print_struct(s, struct_def, generics, item.ident, item.span)); } ast::ItemImpl(ref generics, ref opt_trait, ty, ref methods) => { - head(s, visibility_qualified(item.vis, "impl")); + if_ok!(head(s, visibility_qualified(item.vis, "impl"))); if generics.is_parameterized() { - print_generics(s, generics); - space(&mut s.s); + if_ok!(print_generics(s, generics)); + if_ok!(space(&mut s.s)); } match opt_trait { &Some(ref t) => { - print_trait_ref(s, t); - space(&mut s.s); - word_space(s, "for"); + if_ok!(print_trait_ref(s, t)); + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, "for")); } &None => () }; - print_type(s, ty); + if_ok!(print_type(s, ty)); - space(&mut s.s); - bopen(s); - print_inner_attributes(s, item.attrs); + if_ok!(space(&mut s.s)); + if_ok!(bopen(s)); + if_ok!(print_inner_attributes(s, item.attrs)); for meth in methods.iter() { - print_method(s, *meth); + if_ok!(print_method(s, *meth)); } - bclose(s, item.span); + if_ok!(bclose(s, item.span)); } ast::ItemTrait(ref generics, ref traits, ref methods) => { - head(s, visibility_qualified(item.vis, "trait")); - print_ident(s, item.ident); - print_generics(s, generics); + if_ok!(head(s, visibility_qualified(item.vis, "trait"))); + if_ok!(print_ident(s, item.ident)); + if_ok!(print_generics(s, generics)); if traits.len() != 0u { - word(&mut s.s, ":"); + if_ok!(word(&mut s.s, ":")); for (i, trait_) in traits.iter().enumerate() { - nbsp(s); + if_ok!(nbsp(s)); if i != 0 { - word_space(s, "+"); + if_ok!(word_space(s, "+")); } - print_path(s, &trait_.path, false); + if_ok!(print_path(s, &trait_.path, false)); } } - word(&mut s.s, " "); - bopen(s); + if_ok!(word(&mut s.s, " ")); + if_ok!(bopen(s)); for meth in methods.iter() { - print_trait_method(s, meth); + if_ok!(print_trait_method(s, meth)); } - bclose(s, item.span); + if_ok!(bclose(s, item.span)); } // I think it's reasonable to hide the context here: ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _), ..}) => { - print_visibility(s, item.vis); - print_path(s, pth, false); - word(&mut s.s, "! "); - print_ident(s, item.ident); - cbox(s, indent_unit); - popen(s); - print_tts(s, &(tts.as_slice())); - pclose(s); - end(s); + if_ok!(print_visibility(s, item.vis)); + if_ok!(print_path(s, pth, false)); + if_ok!(word(&mut s.s, "! ")); + if_ok!(print_ident(s, item.ident)); + if_ok!(cbox(s, indent_unit)); + if_ok!(popen(s)); + if_ok!(print_tts(s, &(tts.as_slice()))); + if_ok!(pclose(s)); + if_ok!(end(s)); } } { let ann_node = NodeItem(s, item); - s.ann.post(ann_node); + if_ok!(s.ann.post(ann_node)); } + Ok(()) } -fn print_trait_ref(s: &mut State, t: &ast::TraitRef) { - print_path(s, &t.path, false); +fn print_trait_ref(s: &mut State, t: &ast::TraitRef) -> io::IoResult<()> { + print_path(s, &t.path, false) } pub fn print_enum_def(s: &mut State, enum_definition: &ast::EnumDef, generics: &ast::Generics, ident: ast::Ident, - span: codemap::Span, visibility: ast::Visibility) { - head(s, visibility_qualified(visibility, "enum")); - print_ident(s, ident); - print_generics(s, generics); - space(&mut s.s); - print_variants(s, enum_definition.variants, span); + span: codemap::Span, + visibility: ast::Visibility) -> io::IoResult<()> { + if_ok!(head(s, visibility_qualified(visibility, "enum"))); + if_ok!(print_ident(s, ident)); + if_ok!(print_generics(s, generics)); + if_ok!(space(&mut s.s)); + if_ok!(print_variants(s, enum_definition.variants, span)); + Ok(()) } pub fn print_variants(s: &mut State, variants: &[P], - span: codemap::Span) { - bopen(s); + span: codemap::Span) -> io::IoResult<()> { + if_ok!(bopen(s)); for &v in variants.iter() { - space_if_not_bol(s); - maybe_print_comment(s, v.span.lo); - print_outer_attributes(s, v.node.attrs); - ibox(s, indent_unit); - print_variant(s, v); - word(&mut s.s, ","); - end(s); - maybe_print_trailing_comment(s, v.span, None); + if_ok!(space_if_not_bol(s)); + if_ok!(maybe_print_comment(s, v.span.lo)); + if_ok!(print_outer_attributes(s, v.node.attrs)); + if_ok!(ibox(s, indent_unit)); + if_ok!(print_variant(s, v)); + if_ok!(word(&mut s.s, ",")); + if_ok!(end(s)); + if_ok!(maybe_print_trailing_comment(s, v.span, None)); } - bclose(s, span); + bclose(s, span) } pub fn visibility_to_str(vis: ast::Visibility) -> ~str { @@ -700,60 +747,62 @@ pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> ~str { } } -pub fn print_visibility(s: &mut State, vis: ast::Visibility) { +pub fn print_visibility(s: &mut State, vis: ast::Visibility) -> io::IoResult<()> { match vis { ast::Private | ast::Public => - word_nbsp(s, visibility_to_str(vis)), + if_ok!(word_nbsp(s, visibility_to_str(vis))), ast::Inherited => () } + Ok(()) } pub fn print_struct(s: &mut State, struct_def: &ast::StructDef, generics: &ast::Generics, ident: ast::Ident, - span: codemap::Span) { - print_ident(s, ident); - print_generics(s, generics); + span: codemap::Span) -> io::IoResult<()> { + if_ok!(print_ident(s, ident)); + if_ok!(print_generics(s, generics)); if ast_util::struct_def_is_tuple_like(struct_def) { if !struct_def.fields.is_empty() { - popen(s); - commasep(s, Inconsistent, struct_def.fields, |s, field| { + if_ok!(popen(s)); + if_ok!(commasep(s, Inconsistent, struct_def.fields, |s, field| { match field.node.kind { ast::NamedField(..) => fail!("unexpected named field"), ast::UnnamedField => { - maybe_print_comment(s, field.span.lo); - print_type(s, field.node.ty); + if_ok!(maybe_print_comment(s, field.span.lo)); + if_ok!(print_type(s, field.node.ty)); } } - }); - pclose(s); + Ok(()) + })); + if_ok!(pclose(s)); } - word(&mut s.s, ";"); - end(s); - end(s); // close the outer-box + if_ok!(word(&mut s.s, ";")); + if_ok!(end(s)); + end(s) // close the outer-box } else { - nbsp(s); - bopen(s); - hardbreak_if_not_bol(s); + if_ok!(nbsp(s)); + if_ok!(bopen(s)); + if_ok!(hardbreak_if_not_bol(s)); for field in struct_def.fields.iter() { match field.node.kind { ast::UnnamedField => fail!("unexpected unnamed field"), ast::NamedField(ident, visibility) => { - hardbreak_if_not_bol(s); - maybe_print_comment(s, field.span.lo); - print_outer_attributes(s, field.node.attrs); - print_visibility(s, visibility); - print_ident(s, ident); - word_nbsp(s, ":"); - print_type(s, field.node.ty); - word(&mut s.s, ","); + if_ok!(hardbreak_if_not_bol(s)); + if_ok!(maybe_print_comment(s, field.span.lo)); + if_ok!(print_outer_attributes(s, field.node.attrs)); + if_ok!(print_visibility(s, visibility)); + if_ok!(print_ident(s, ident)); + if_ok!(word_nbsp(s, ":")); + if_ok!(print_type(s, field.node.ty)); + if_ok!(word(&mut s.s, ",")); } } } - bclose(s, span); + bclose(s, span) } } @@ -764,191 +813,219 @@ pub fn print_struct(s: &mut State, /// appropriate macro, transcribe back into the grammar we just parsed from, /// and then pretty-print the resulting AST nodes (so, e.g., we print /// expression arguments as expressions). It can be done! I think. -pub fn print_tt(s: &mut State, tt: &ast::TokenTree) { +pub fn print_tt(s: &mut State, tt: &ast::TokenTree) -> io::IoResult<()> { match *tt { - ast::TTDelim(ref tts) => print_tts(s, &(tts.as_slice())), - ast::TTTok(_, ref tk) => { - word(&mut s.s, parse::token::to_str(s.intr, tk)); - } - ast::TTSeq(_, ref tts, ref sep, zerok) => { - word(&mut s.s, "$("); - for tt_elt in (*tts).iter() { print_tt(s, tt_elt); } - word(&mut s.s, ")"); - match *sep { - Some(ref tk) => word(&mut s.s, parse::token::to_str(s.intr, tk)), - None => () + ast::TTDelim(ref tts) => print_tts(s, &(tts.as_slice())), + ast::TTTok(_, ref tk) => { + word(&mut s.s, parse::token::to_str(s.intr, tk)) + } + ast::TTSeq(_, ref tts, ref sep, zerok) => { + if_ok!(word(&mut s.s, "$(")); + for tt_elt in (*tts).iter() { + if_ok!(print_tt(s, tt_elt)); + } + if_ok!(word(&mut s.s, ")")); + match *sep { + Some(ref tk) => { + if_ok!(word(&mut s.s, parse::token::to_str(s.intr, tk))); + } + None => () + } + word(&mut s.s, if zerok { "*" } else { "+" }) + } + ast::TTNonterminal(_, name) => { + if_ok!(word(&mut s.s, "$")); + print_ident(s, name) } - word(&mut s.s, if zerok { "*" } else { "+" }); - } - ast::TTNonterminal(_, name) => { - word(&mut s.s, "$"); - print_ident(s, name); - } } } -pub fn print_tts(s: &mut State, tts: & &[ast::TokenTree]) { - ibox(s, 0); +pub fn print_tts(s: &mut State, tts: & &[ast::TokenTree]) -> io::IoResult<()> { + if_ok!(ibox(s, 0)); for (i, tt) in tts.iter().enumerate() { if i != 0 { - space(&mut s.s); + if_ok!(space(&mut s.s)); } - print_tt(s, tt); + if_ok!(print_tt(s, tt)); } - end(s); + end(s) } -pub fn print_variant(s: &mut State, v: &ast::Variant) { - print_visibility(s, v.node.vis); +pub fn print_variant(s: &mut State, v: &ast::Variant) -> io::IoResult<()> { + if_ok!(print_visibility(s, v.node.vis)); match v.node.kind { ast::TupleVariantKind(ref args) => { - print_ident(s, v.node.name); + if_ok!(print_ident(s, v.node.name)); if !args.is_empty() { - popen(s); - fn print_variant_arg(s: &mut State, arg: &ast::VariantArg) { - print_type(s, arg.ty); + if_ok!(popen(s)); + fn print_variant_arg(s: &mut State, + arg: &ast::VariantArg) -> io::IoResult<()> { + print_type(s, arg.ty) } - commasep(s, Consistent, *args, print_variant_arg); - pclose(s); + if_ok!(commasep(s, Consistent, *args, print_variant_arg)); + if_ok!(pclose(s)); } } ast::StructVariantKind(struct_def) => { - head(s, ""); + if_ok!(head(s, "")); let generics = ast_util::empty_generics(); - print_struct(s, struct_def, &generics, v.node.name, v.span); + if_ok!(print_struct(s, struct_def, &generics, v.node.name, v.span)); } } match v.node.disr_expr { Some(d) => { - space(&mut s.s); - word_space(s, "="); - print_expr(s, d); + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, "=")); + if_ok!(print_expr(s, d)); } _ => () } -} - -pub fn print_ty_method(s: &mut State, m: &ast::TypeMethod) { - hardbreak_if_not_bol(s); - maybe_print_comment(s, m.span.lo); - print_outer_attributes(s, m.attrs); - print_ty_fn(s, - None, - None, - &None, - m.purity, - ast::Many, - m.decl, - Some(m.ident), - &None, - Some(&m.generics), - Some(m.explicit_self.node)); - word(&mut s.s, ";"); -} - -pub fn print_trait_method(s: &mut State, m: &ast::TraitMethod) { + Ok(()) +} + +pub fn print_ty_method(s: &mut State, m: &ast::TypeMethod) -> io::IoResult<()> { + if_ok!(hardbreak_if_not_bol(s)); + if_ok!(maybe_print_comment(s, m.span.lo)); + if_ok!(print_outer_attributes(s, m.attrs)); + if_ok!(print_ty_fn(s, + None, + None, + &None, + m.purity, + ast::Many, + m.decl, + Some(m.ident), + &None, + Some(&m.generics), + Some(m.explicit_self.node))); + word(&mut s.s, ";") +} + +pub fn print_trait_method(s: &mut State, + m: &ast::TraitMethod) -> io::IoResult<()> { match *m { Required(ref ty_m) => print_ty_method(s, ty_m), Provided(m) => print_method(s, m) } } -pub fn print_method(s: &mut State, meth: &ast::Method) { - hardbreak_if_not_bol(s); - maybe_print_comment(s, meth.span.lo); - print_outer_attributes(s, meth.attrs); - print_fn(s, meth.decl, Some(meth.purity), AbiSet::Rust(), - meth.ident, &meth.generics, Some(meth.explicit_self.node), - meth.vis); - word(&mut s.s, " "); - print_block_with_attrs(s, meth.body, meth.attrs); +pub fn print_method(s: &mut State, meth: &ast::Method) -> io::IoResult<()> { + if_ok!(hardbreak_if_not_bol(s)); + if_ok!(maybe_print_comment(s, meth.span.lo)); + if_ok!(print_outer_attributes(s, meth.attrs)); + if_ok!(print_fn(s, meth.decl, Some(meth.purity), AbiSet::Rust(), + meth.ident, &meth.generics, Some(meth.explicit_self.node), + meth.vis)); + if_ok!(word(&mut s.s, " ")); + print_block_with_attrs(s, meth.body, meth.attrs) } -pub fn print_outer_attributes(s: &mut State, attrs: &[ast::Attribute]) { +pub fn print_outer_attributes(s: &mut State, + attrs: &[ast::Attribute]) -> io::IoResult<()> { let mut count = 0; for attr in attrs.iter() { match attr.node.style { - ast::AttrOuter => { print_attribute(s, attr); count += 1; } + ast::AttrOuter => { + if_ok!(print_attribute(s, attr)); + count += 1; + } _ => {/* fallthrough */ } } } - if count > 0 { hardbreak_if_not_bol(s); } + if count > 0 { + if_ok!(hardbreak_if_not_bol(s)); + } + Ok(()) } -pub fn print_inner_attributes(s: &mut State, attrs: &[ast::Attribute]) { +pub fn print_inner_attributes(s: &mut State, + attrs: &[ast::Attribute]) -> io::IoResult<()> { let mut count = 0; for attr in attrs.iter() { match attr.node.style { ast::AttrInner => { - print_attribute(s, attr); + if_ok!(print_attribute(s, attr)); if !attr.node.is_sugared_doc { - word(&mut s.s, ";"); + if_ok!(word(&mut s.s, ";")); } count += 1; } _ => {/* fallthrough */ } } } - if count > 0 { hardbreak_if_not_bol(s); } + if count > 0 { + if_ok!(hardbreak_if_not_bol(s)); + } + Ok(()) } -pub fn print_attribute(s: &mut State, attr: &ast::Attribute) { - hardbreak_if_not_bol(s); - maybe_print_comment(s, attr.span.lo); +pub fn print_attribute(s: &mut State, attr: &ast::Attribute) -> io::IoResult<()> { + if_ok!(hardbreak_if_not_bol(s)); + if_ok!(maybe_print_comment(s, attr.span.lo)); if attr.node.is_sugared_doc { let comment = attr.value_str().unwrap(); +<<<<<<< HEAD word(&mut s.s, comment.get()); +======= + if_ok!(word(&mut s.s, comment)); +>>>>>>> syntax: Remove io_error usage } else { - word(&mut s.s, "#["); - print_meta_item(s, attr.meta()); - word(&mut s.s, "]"); + if_ok!(word(&mut s.s, "#[")); + if_ok!(print_meta_item(s, attr.meta())); + if_ok!(word(&mut s.s, "]")); } + Ok(()) } -pub fn print_stmt(s: &mut State, st: &ast::Stmt) { - maybe_print_comment(s, st.span.lo); +pub fn print_stmt(s: &mut State, st: &ast::Stmt) -> io::IoResult<()> { + if_ok!(maybe_print_comment(s, st.span.lo)); match st.node { ast::StmtDecl(decl, _) => { - print_decl(s, decl); + if_ok!(print_decl(s, decl)); } ast::StmtExpr(expr, _) => { - space_if_not_bol(s); - print_expr(s, expr); + if_ok!(space_if_not_bol(s)); + if_ok!(print_expr(s, expr)); } ast::StmtSemi(expr, _) => { - space_if_not_bol(s); - print_expr(s, expr); - word(&mut s.s, ";"); + if_ok!(space_if_not_bol(s)); + if_ok!(print_expr(s, expr)); + if_ok!(word(&mut s.s, ";")); } ast::StmtMac(ref mac, semi) => { - space_if_not_bol(s); - print_mac(s, mac); - if semi { word(&mut s.s, ";"); } + if_ok!(space_if_not_bol(s)); + if_ok!(print_mac(s, mac)); + if semi { + if_ok!(word(&mut s.s, ";")); + } } } - if parse::classify::stmt_ends_with_semi(st) { word(&mut s.s, ";"); } - maybe_print_trailing_comment(s, st.span, None); + if parse::classify::stmt_ends_with_semi(st) { + if_ok!(word(&mut s.s, ";")); + } + maybe_print_trailing_comment(s, st.span, None) } -pub fn print_block(s: &mut State, blk: &ast::Block) { - print_possibly_embedded_block(s, blk, BlockNormal, indent_unit); +pub fn print_block(s: &mut State, blk: &ast::Block) -> io::IoResult<()> { + print_possibly_embedded_block(s, blk, BlockNormal, indent_unit) } -pub fn print_block_unclosed(s: &mut State, blk: &ast::Block) { +pub fn print_block_unclosed(s: &mut State, blk: &ast::Block) -> io::IoResult<()> { print_possibly_embedded_block_(s, blk, BlockNormal, indent_unit, &[], - false); + false) } -pub fn print_block_unclosed_indent(s: &mut State, blk: &ast::Block, indented: uint) { - print_possibly_embedded_block_(s, blk, BlockNormal, indented, &[], false); +pub fn print_block_unclosed_indent(s: &mut State, blk: &ast::Block, + indented: uint) -> io::IoResult<()> { + print_possibly_embedded_block_(s, blk, BlockNormal, indented, &[], false) } pub fn print_block_with_attrs(s: &mut State, blk: &ast::Block, - attrs: &[ast::Attribute]) { + attrs: &[ast::Attribute]) -> io::IoResult<()> { print_possibly_embedded_block_(s, blk, BlockNormal, indent_unit, attrs, - true); + true) } enum EmbedType { @@ -959,9 +1036,9 @@ enum EmbedType { pub fn print_possibly_embedded_block(s: &mut State, blk: &ast::Block, embedded: EmbedType, - indented: uint) { + indented: uint) -> io::IoResult<()> { print_possibly_embedded_block_( - s, blk, embedded, indented, &[], true); + s, blk, embedded, indented, &[], true) } pub fn print_possibly_embedded_block_(s: &mut State, @@ -969,102 +1046,123 @@ pub fn print_possibly_embedded_block_(s: &mut State, embedded: EmbedType, indented: uint, attrs: &[ast::Attribute], - close_box: bool) { + close_box: bool) -> io::IoResult<()> { match blk.rules { - ast::UnsafeBlock(..) => word_space(s, "unsafe"), + ast::UnsafeBlock(..) => if_ok!(word_space(s, "unsafe")), ast::DefaultBlock => () } - maybe_print_comment(s, blk.span.lo); + if_ok!(maybe_print_comment(s, blk.span.lo)); { let ann_node = NodeBlock(s, blk); - s.ann.pre(ann_node); + if_ok!(s.ann.pre(ann_node)); } - match embedded { + if_ok!(match embedded { BlockBlockFn => end(s), BlockNormal => bopen(s) - } + }); - print_inner_attributes(s, attrs); + if_ok!(print_inner_attributes(s, attrs)); - for vi in blk.view_items.iter() { print_view_item(s, vi); } + for vi in blk.view_items.iter() { + if_ok!(print_view_item(s, vi)); + } for st in blk.stmts.iter() { - print_stmt(s, *st); + if_ok!(print_stmt(s, *st)); } match blk.expr { Some(expr) => { - space_if_not_bol(s); - print_expr(s, expr); - maybe_print_trailing_comment(s, expr.span, Some(blk.span.hi)); + if_ok!(space_if_not_bol(s)); + if_ok!(print_expr(s, expr)); + if_ok!(maybe_print_trailing_comment(s, expr.span, Some(blk.span.hi))); } _ => () } - bclose_maybe_open(s, blk.span, indented, close_box); + if_ok!(bclose_maybe_open(s, blk.span, indented, close_box)); { let ann_node = NodeBlock(s, blk); - s.ann.post(ann_node); + if_ok!(s.ann.post(ann_node)); } + Ok(()) } pub fn print_if(s: &mut State, test: &ast::Expr, blk: &ast::Block, - elseopt: Option<@ast::Expr>, chk: bool) { - head(s, "if"); - if chk { word_nbsp(s, "check"); } - print_expr(s, test); - space(&mut s.s); - print_block(s, blk); - fn do_else(s: &mut State, els: Option<@ast::Expr>) { + elseopt: Option<@ast::Expr>, chk: bool) -> io::IoResult<()> { + if_ok!(head(s, "if")); + if chk { if_ok!(word_nbsp(s, "check")); } + if_ok!(print_expr(s, test)); + if_ok!(space(&mut s.s)); + if_ok!(print_block(s, blk)); + fn do_else(s: &mut State, els: Option<@ast::Expr>) -> io::IoResult<()> { match els { - Some(_else) => { - match _else.node { - // "another else-if" - ast::ExprIf(i, t, e) => { - cbox(s, indent_unit - 1u); - ibox(s, 0u); - word(&mut s.s, " else if "); - print_expr(s, i); - space(&mut s.s); - print_block(s, t); - do_else(s, e); - } - // "final else" - ast::ExprBlock(b) => { - cbox(s, indent_unit - 1u); - ibox(s, 0u); - word(&mut s.s, " else "); - print_block(s, b); - } - // BLEAH, constraints would be great here - _ => { - fail!("print_if saw if with weird alternative"); - } + Some(_else) => { + match _else.node { + // "another else-if" + ast::ExprIf(i, t, e) => { + if_ok!(cbox(s, indent_unit - 1u)); + if_ok!(ibox(s, 0u)); + if_ok!(word(&mut s.s, " else if ")); + if_ok!(print_expr(s, i)); + if_ok!(space(&mut s.s)); + if_ok!(print_block(s, t)); + if_ok!(do_else(s, e)); + } + // "final else" + ast::ExprBlock(b) => { + if_ok!(cbox(s, indent_unit - 1u)); + if_ok!(ibox(s, 0u)); + if_ok!(word(&mut s.s, " else ")); + if_ok!(print_block(s, b)); + } + // BLEAH, constraints would be great here + _ => { + fail!("print_if saw if with weird alternative"); + } + } } - } - _ => {/* fall through */ } + _ => {/* fall through */ } } + Ok(()) } - do_else(s, elseopt); + do_else(s, elseopt) } -pub fn print_mac(s: &mut State, m: &ast::Mac) { +pub fn print_mac(s: &mut State, m: &ast::Mac) -> io::IoResult<()> { match m.node { // I think it's reasonable to hide the ctxt here: ast::MacInvocTT(ref pth, ref tts, _) => { - print_path(s, pth, false); - word(&mut s.s, "!"); - popen(s); - print_tts(s, &tts.as_slice()); - pclose(s); + if_ok!(print_path(s, pth, false)); + if_ok!(word(&mut s.s, "!")); + if_ok!(popen(s)); + if_ok!(print_tts(s, &tts.as_slice())); + pclose(s) } } } +<<<<<<< HEAD pub fn print_expr_vstore(s: &mut State, t: ast::ExprVstore) { +======= +pub fn print_vstore(s: &mut State, t: ast::Vstore) -> io::IoResult<()> { + match t { + ast::VstoreFixed(Some(i)) => word(&mut s.s, format!("{}", i)), + ast::VstoreFixed(None) => word(&mut s.s, "_"), + ast::VstoreUniq => word(&mut s.s, "~"), + ast::VstoreBox => word(&mut s.s, "@"), + ast::VstoreSlice(ref r) => { + if_ok!(word(&mut s.s, "&")); + print_opt_lifetime(s, r) + } + } +} + +pub fn print_expr_vstore(s: &mut State, t: ast::ExprVstore) -> io::IoResult<()> { +>>>>>>> syntax: Remove io_error usage match t { ast::ExprVstoreUniq => word(&mut s.s, "~"), ast::ExprVstoreSlice => word(&mut s.s, "&"), ast::ExprVstoreMutSlice => { - word(&mut s.s, "&"); - word(&mut s.s, "mut"); + if_ok!(word(&mut s.s, "&")); + word(&mut s.s, "mut") } } } @@ -1072,222 +1170,227 @@ pub fn print_expr_vstore(s: &mut State, t: ast::ExprVstore) { pub fn print_call_pre(s: &mut State, sugar: ast::CallSugar, base_args: &mut ~[@ast::Expr]) - -> Option<@ast::Expr> { + -> io::IoResult> { match sugar { ast::ForSugar => { - head(s, "for"); - Some(base_args.pop().unwrap()) + if_ok!(head(s, "for")); + Ok(Some(base_args.pop().unwrap())) } - ast::NoSugar => None + ast::NoSugar => Ok(None) } } pub fn print_call_post(s: &mut State, sugar: ast::CallSugar, blk: &Option<@ast::Expr>, - base_args: &mut ~[@ast::Expr]) { + base_args: &mut ~[@ast::Expr]) -> io::IoResult<()> { if sugar == ast::NoSugar || !base_args.is_empty() { - popen(s); - commasep_exprs(s, Inconsistent, *base_args); - pclose(s); + if_ok!(popen(s)); + if_ok!(commasep_exprs(s, Inconsistent, *base_args)); + if_ok!(pclose(s)); } if sugar != ast::NoSugar { - nbsp(s); + if_ok!(nbsp(s)); // not sure if this can happen - print_expr(s, blk.unwrap()); + if_ok!(print_expr(s, blk.unwrap())); } + Ok(()) } -pub fn print_expr(s: &mut State, expr: &ast::Expr) { - fn print_field(s: &mut State, field: &ast::Field) { - ibox(s, indent_unit); - print_ident(s, field.ident.node); - word_space(s, ":"); - print_expr(s, field.expr); - end(s); +pub fn print_expr(s: &mut State, expr: &ast::Expr) -> io::IoResult<()> { + fn print_field(s: &mut State, field: &ast::Field) -> io::IoResult<()> { + if_ok!(ibox(s, indent_unit)); + if_ok!(print_ident(s, field.ident.node)); + if_ok!(word_space(s, ":")); + if_ok!(print_expr(s, field.expr)); + if_ok!(end(s)); + Ok(()) } fn get_span(field: &ast::Field) -> codemap::Span { return field.span; } - maybe_print_comment(s, expr.span.lo); - ibox(s, indent_unit); + if_ok!(maybe_print_comment(s, expr.span.lo)); + if_ok!(ibox(s, indent_unit)); { let ann_node = NodeExpr(s, expr); - s.ann.pre(ann_node); + if_ok!(s.ann.pre(ann_node)); } match expr.node { ast::ExprVstore(e, v) => { - print_expr_vstore(s, v); - print_expr(s, e); + if_ok!(print_expr_vstore(s, v)); + if_ok!(print_expr(s, e)); }, ast::ExprBox(p, e) => { - word(&mut s.s, "box"); - word(&mut s.s, "("); - print_expr(s, p); - word_space(s, ")"); - print_expr(s, e); + if_ok!(word(&mut s.s, "box")); + if_ok!(word(&mut s.s, "(")); + if_ok!(print_expr(s, p)); + if_ok!(word_space(s, ")")); + if_ok!(print_expr(s, e)); } ast::ExprVec(ref exprs, mutbl) => { - ibox(s, indent_unit); - word(&mut s.s, "["); + if_ok!(ibox(s, indent_unit)); + if_ok!(word(&mut s.s, "[")); if mutbl == ast::MutMutable { - word(&mut s.s, "mut"); - if exprs.len() > 0u { nbsp(s); } + if_ok!(word(&mut s.s, "mut")); + if exprs.len() > 0u { if_ok!(nbsp(s)); } } - commasep_exprs(s, Inconsistent, *exprs); - word(&mut s.s, "]"); - end(s); + if_ok!(commasep_exprs(s, Inconsistent, *exprs)); + if_ok!(word(&mut s.s, "]")); + if_ok!(end(s)); } ast::ExprRepeat(element, count, mutbl) => { - ibox(s, indent_unit); - word(&mut s.s, "["); + if_ok!(ibox(s, indent_unit)); + if_ok!(word(&mut s.s, "[")); if mutbl == ast::MutMutable { - word(&mut s.s, "mut"); - nbsp(s); + if_ok!(word(&mut s.s, "mut")); + if_ok!(nbsp(s)); } - print_expr(s, element); - word(&mut s.s, ","); - word(&mut s.s, ".."); - print_expr(s, count); - word(&mut s.s, "]"); - end(s); + if_ok!(print_expr(s, element)); + if_ok!(word(&mut s.s, ",")); + if_ok!(word(&mut s.s, "..")); + if_ok!(print_expr(s, count)); + if_ok!(word(&mut s.s, "]")); + if_ok!(end(s)); } ast::ExprStruct(ref path, ref fields, wth) => { - print_path(s, path, true); - word(&mut s.s, "{"); - commasep_cmnt(s, Consistent, (*fields), print_field, get_span); + if_ok!(print_path(s, path, true)); + if_ok!(word(&mut s.s, "{")); + if_ok!(commasep_cmnt(s, Consistent, (*fields), print_field, get_span)); match wth { Some(expr) => { - ibox(s, indent_unit); + if_ok!(ibox(s, indent_unit)); if !fields.is_empty() { - word(&mut s.s, ","); - space(&mut s.s); + if_ok!(word(&mut s.s, ",")); + if_ok!(space(&mut s.s)); } - word(&mut s.s, ".."); - print_expr(s, expr); - end(s); + if_ok!(word(&mut s.s, "..")); + if_ok!(print_expr(s, expr)); + if_ok!(end(s)); } - _ => (word(&mut s.s, ",")) + _ => if_ok!(word(&mut s.s, ",")) } - word(&mut s.s, "}"); + if_ok!(word(&mut s.s, "}")); } ast::ExprTup(ref exprs) => { - popen(s); - commasep_exprs(s, Inconsistent, *exprs); + if_ok!(popen(s)); + if_ok!(commasep_exprs(s, Inconsistent, *exprs)); if exprs.len() == 1 { - word(&mut s.s, ","); + if_ok!(word(&mut s.s, ",")); } - pclose(s); + if_ok!(pclose(s)); } ast::ExprCall(func, ref args, sugar) => { let mut base_args = (*args).clone(); - let blk = print_call_pre(s, sugar, &mut base_args); - print_expr(s, func); - print_call_post(s, sugar, &blk, &mut base_args); + let blk = if_ok!(print_call_pre(s, sugar, &mut base_args)); + if_ok!(print_expr(s, func)); + if_ok!(print_call_post(s, sugar, &blk, &mut base_args)); } ast::ExprMethodCall(_, ident, ref tys, ref args, sugar) => { let mut base_args = args.slice_from(1).to_owned(); - let blk = print_call_pre(s, sugar, &mut base_args); - print_expr(s, args[0]); - word(&mut s.s, "."); - print_ident(s, ident); + let blk = if_ok!(print_call_pre(s, sugar, &mut base_args)); + if_ok!(print_expr(s, args[0])); + if_ok!(word(&mut s.s, ".")); + if_ok!(print_ident(s, ident)); if tys.len() > 0u { - word(&mut s.s, "::<"); - commasep(s, Inconsistent, *tys, print_type_ref); - word(&mut s.s, ">"); + if_ok!(word(&mut s.s, "::<")); + if_ok!(commasep(s, Inconsistent, *tys, print_type_ref)); + if_ok!(word(&mut s.s, ">")); } - print_call_post(s, sugar, &blk, &mut base_args); + if_ok!(print_call_post(s, sugar, &blk, &mut base_args)); } ast::ExprBinary(_, op, lhs, rhs) => { - print_expr(s, lhs); - space(&mut s.s); - word_space(s, ast_util::binop_to_str(op)); - print_expr(s, rhs); + if_ok!(print_expr(s, lhs)); + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, ast_util::binop_to_str(op))); + if_ok!(print_expr(s, rhs)); } ast::ExprUnary(_, op, expr) => { - word(&mut s.s, ast_util::unop_to_str(op)); - print_expr(s, expr); + if_ok!(word(&mut s.s, ast_util::unop_to_str(op))); + if_ok!(print_expr(s, expr)); } ast::ExprAddrOf(m, expr) => { - word(&mut s.s, "&"); - print_mutability(s, m); + if_ok!(word(&mut s.s, "&")); + if_ok!(print_mutability(s, m)); // Avoid `& &e` => `&&e`. match (m, &expr.node) { - (ast::MutImmutable, &ast::ExprAddrOf(..)) => space(&mut s.s), + (ast::MutImmutable, &ast::ExprAddrOf(..)) => if_ok!(space(&mut s.s)), _ => { } } - print_expr(s, expr); + if_ok!(print_expr(s, expr)); } - ast::ExprLit(lit) => print_literal(s, lit), + ast::ExprLit(lit) => if_ok!(print_literal(s, lit)), ast::ExprCast(expr, ty) => { - print_expr(s, expr); - space(&mut s.s); - word_space(s, "as"); - print_type(s, ty); + if_ok!(print_expr(s, expr)); + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, "as")); + if_ok!(print_type(s, ty)); } ast::ExprIf(test, blk, elseopt) => { - print_if(s, test, blk, elseopt, false); + if_ok!(print_if(s, test, blk, elseopt, false)); } ast::ExprWhile(test, blk) => { - head(s, "while"); - print_expr(s, test); - space(&mut s.s); - print_block(s, blk); + if_ok!(head(s, "while")); + if_ok!(print_expr(s, test)); + if_ok!(space(&mut s.s)); + if_ok!(print_block(s, blk)); } ast::ExprForLoop(pat, iter, blk, opt_ident) => { for ident in opt_ident.iter() { - word(&mut s.s, "'"); - print_ident(s, *ident); - word_space(s, ":"); - } - head(s, "for"); - print_pat(s, pat); - space(&mut s.s); - word_space(s, "in"); - print_expr(s, iter); - space(&mut s.s); - print_block(s, blk); + if_ok!(word(&mut s.s, "'")); + if_ok!(print_ident(s, *ident)); + if_ok!(word_space(s, ":")); + } + if_ok!(head(s, "for")); + if_ok!(print_pat(s, pat)); + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, "in")); + if_ok!(print_expr(s, iter)); + if_ok!(space(&mut s.s)); + if_ok!(print_block(s, blk)); } ast::ExprLoop(blk, opt_ident) => { for ident in opt_ident.iter() { - word(&mut s.s, "'"); - print_ident(s, *ident); - word_space(s, ":"); + if_ok!(word(&mut s.s, "'")); + if_ok!(print_ident(s, *ident)); + if_ok!(word_space(s, ":")); } - head(s, "loop"); - space(&mut s.s); - print_block(s, blk); + if_ok!(head(s, "loop")); + if_ok!(space(&mut s.s)); + if_ok!(print_block(s, blk)); } ast::ExprMatch(expr, ref arms) => { - cbox(s, indent_unit); - ibox(s, 4); - word_nbsp(s, "match"); - print_expr(s, expr); - space(&mut s.s); - bopen(s); + if_ok!(cbox(s, indent_unit)); + if_ok!(ibox(s, 4)); + if_ok!(word_nbsp(s, "match")); + if_ok!(print_expr(s, expr)); + if_ok!(space(&mut s.s)); + if_ok!(bopen(s)); let len = arms.len(); for (i, arm) in arms.iter().enumerate() { - space(&mut s.s); - cbox(s, indent_unit); - ibox(s, 0u); + if_ok!(space(&mut s.s)); + if_ok!(cbox(s, indent_unit)); + if_ok!(ibox(s, 0u)); let mut first = true; for p in arm.pats.iter() { if first { first = false; - } else { space(&mut s.s); word_space(s, "|"); } - print_pat(s, *p); + } else { + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, "|")); + } + if_ok!(print_pat(s, *p)); } - space(&mut s.s); + if_ok!(space(&mut s.s)); match arm.guard { Some(e) => { - word_space(s, "if"); - print_expr(s, e); - space(&mut s.s); + if_ok!(word_space(s, "if")); + if_ok!(print_expr(s, e)); + if_ok!(space(&mut s.s)); } None => () } - word_space(s, "=>"); + if_ok!(word_space(s, "=>")); // Extract the expression from the extra block the parser adds // in the case of foo => expr @@ -1301,28 +1404,28 @@ pub fn print_expr(s: &mut State, expr: &ast::Expr) { match expr.node { ast::ExprBlock(blk) => { // the block will close the pattern's ibox - print_block_unclosed_indent( - s, blk, indent_unit); + if_ok!(print_block_unclosed_indent( + s, blk, indent_unit)); } _ => { - end(s); // close the ibox for the pattern - print_expr(s, expr); + if_ok!(end(s)); // close the ibox for the pattern + if_ok!(print_expr(s, expr)); } } if !expr_is_simple_block(expr) && i < len - 1 { - word(&mut s.s, ","); + if_ok!(word(&mut s.s, ",")); } - end(s); // close enclosing cbox + if_ok!(end(s)); // close enclosing cbox } None => fail!() } } else { // the block will close the pattern's ibox - print_block_unclosed_indent(s, arm.body, indent_unit); + if_ok!(print_block_unclosed_indent(s, arm.body, indent_unit)); } } - bclose_(s, expr.span, indent_unit); + if_ok!(bclose_(s, expr.span, indent_unit)); } ast::ExprFnBlock(decl, body) => { // in do/for blocks we don't want to show an empty @@ -1330,26 +1433,26 @@ pub fn print_expr(s: &mut State, expr: &ast::Expr) { // we are inside. // // if !decl.inputs.is_empty() { - print_fn_block_args(s, decl); - space(&mut s.s); + if_ok!(print_fn_block_args(s, decl)); + if_ok!(space(&mut s.s)); // } assert!(body.stmts.is_empty()); assert!(body.expr.is_some()); // we extract the block, so as not to create another set of boxes match body.expr.unwrap().node { ast::ExprBlock(blk) => { - print_block_unclosed(s, blk); + if_ok!(print_block_unclosed(s, blk)); } _ => { // this is a bare expression - print_expr(s, body.expr.unwrap()); - end(s); // need to close a box + if_ok!(print_expr(s, body.expr.unwrap())); + if_ok!(end(s)); // need to close a box } } // a box will be closed by print_expr, but we didn't want an overall // wrapper so we closed the corresponding opening. so create an // empty box to satisfy the close. - ibox(s, 0); + if_ok!(ibox(s, 0)); } ast::ExprProc(decl, body) => { // in do/for blocks we don't want to show an empty @@ -1357,100 +1460,104 @@ pub fn print_expr(s: &mut State, expr: &ast::Expr) { // we are inside. // // if !decl.inputs.is_empty() { - print_proc_args(s, decl); - space(&mut s.s); + if_ok!(print_proc_args(s, decl)); + if_ok!(space(&mut s.s)); // } assert!(body.stmts.is_empty()); assert!(body.expr.is_some()); // we extract the block, so as not to create another set of boxes match body.expr.unwrap().node { ast::ExprBlock(blk) => { - print_block_unclosed(s, blk); + if_ok!(print_block_unclosed(s, blk)); } _ => { // this is a bare expression - print_expr(s, body.expr.unwrap()); - end(s); // need to close a box + if_ok!(print_expr(s, body.expr.unwrap())); + if_ok!(end(s)); // need to close a box } } // a box will be closed by print_expr, but we didn't want an overall // wrapper so we closed the corresponding opening. so create an // empty box to satisfy the close. - ibox(s, 0); + if_ok!(ibox(s, 0)); } ast::ExprBlock(blk) => { // containing cbox, will be closed by print-block at } - cbox(s, indent_unit); + if_ok!(cbox(s, indent_unit)); // head-box, will be closed by print-block after { - ibox(s, 0u); - print_block(s, blk); + if_ok!(ibox(s, 0u)); + if_ok!(print_block(s, blk)); } ast::ExprAssign(lhs, rhs) => { - print_expr(s, lhs); - space(&mut s.s); - word_space(s, "="); - print_expr(s, rhs); + if_ok!(print_expr(s, lhs)); + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, "=")); + if_ok!(print_expr(s, rhs)); } ast::ExprAssignOp(_, op, lhs, rhs) => { - print_expr(s, lhs); - space(&mut s.s); - word(&mut s.s, ast_util::binop_to_str(op)); - word_space(s, "="); - print_expr(s, rhs); + if_ok!(print_expr(s, lhs)); + if_ok!(space(&mut s.s)); + if_ok!(word(&mut s.s, ast_util::binop_to_str(op))); + if_ok!(word_space(s, "=")); + if_ok!(print_expr(s, rhs)); } ast::ExprField(expr, id, ref tys) => { - print_expr(s, expr); - word(&mut s.s, "."); - print_ident(s, id); + if_ok!(print_expr(s, expr)); + if_ok!(word(&mut s.s, ".")); + if_ok!(print_ident(s, id)); if tys.len() > 0u { - word(&mut s.s, "::<"); - commasep(s, Inconsistent, *tys, print_type_ref); - word(&mut s.s, ">"); + if_ok!(word(&mut s.s, "::<")); + if_ok!(commasep(s, Inconsistent, *tys, print_type_ref)); + if_ok!(word(&mut s.s, ">")); } } ast::ExprIndex(_, expr, index) => { - print_expr(s, expr); - word(&mut s.s, "["); - print_expr(s, index); - word(&mut s.s, "]"); + if_ok!(print_expr(s, expr)); + if_ok!(word(&mut s.s, "[")); + if_ok!(print_expr(s, index)); + if_ok!(word(&mut s.s, "]")); } - ast::ExprPath(ref path) => print_path(s, path, true), + ast::ExprPath(ref path) => if_ok!(print_path(s, path, true)), ast::ExprBreak(opt_ident) => { - word(&mut s.s, "break"); - space(&mut s.s); + if_ok!(word(&mut s.s, "break")); + if_ok!(space(&mut s.s)); for ident in opt_ident.iter() { - word(&mut s.s, "'"); - print_name(s, *ident); - space(&mut s.s); + if_ok!(word(&mut s.s, "'")); + if_ok!(print_name(s, *ident)); + if_ok!(space(&mut s.s)); } } ast::ExprAgain(opt_ident) => { - word(&mut s.s, "continue"); - space(&mut s.s); + if_ok!(word(&mut s.s, "continue")); + if_ok!(space(&mut s.s)); for ident in opt_ident.iter() { - word(&mut s.s, "'"); - print_name(s, *ident); - space(&mut s.s) + if_ok!(word(&mut s.s, "'")); + if_ok!(print_name(s, *ident)); + if_ok!(space(&mut s.s)) } } ast::ExprRet(result) => { - word(&mut s.s, "return"); + if_ok!(word(&mut s.s, "return")); match result { - Some(expr) => { word(&mut s.s, " "); print_expr(s, expr); } + Some(expr) => { + if_ok!(word(&mut s.s, " ")); + if_ok!(print_expr(s, expr)); + } _ => () } } ast::ExprLogLevel => { - word(&mut s.s, "__log_level"); - popen(s); - pclose(s); + if_ok!(word(&mut s.s, "__log_level")); + if_ok!(popen(s)); + if_ok!(pclose(s)); } ast::ExprInlineAsm(ref a) => { if a.volatile { - word(&mut s.s, "__volatile__ asm!"); + if_ok!(word(&mut s.s, "__volatile__ asm!")); } else { - word(&mut s.s, "asm!"); + if_ok!(word(&mut s.s, "asm!")); } +<<<<<<< HEAD popen(s); print_string(s, a.asm.get(), a.asm_str_style); word_space(s, ":"); @@ -1472,58 +1579,87 @@ pub fn print_expr(s: &mut State, expr: &ast::Expr) { word_space(s, ":"); print_string(s, a.clobbers.get(), ast::CookedStr); pclose(s); - } - ast::ExprMac(ref m) => print_mac(s, m), +======= + if_ok!(popen(s)); + if_ok!(print_string(s, a.asm, a.asm_str_style)); + if_ok!(word_space(s, ":")); + for &(co, o) in a.outputs.iter() { + if_ok!(print_string(s, co, ast::CookedStr)); + if_ok!(popen(s)); + if_ok!(print_expr(s, o)); + if_ok!(pclose(s)); + if_ok!(word_space(s, ",")); + } + if_ok!(word_space(s, ":")); + for &(co, o) in a.inputs.iter() { + if_ok!(print_string(s, co, ast::CookedStr)); + if_ok!(popen(s)); + if_ok!(print_expr(s, o)); + if_ok!(pclose(s)); + if_ok!(word_space(s, ",")); + } + if_ok!(word_space(s, ":")); + if_ok!(print_string(s, a.clobbers, ast::CookedStr)); + if_ok!(pclose(s)); +>>>>>>> syntax: Remove io_error usage + } + ast::ExprMac(ref m) => if_ok!(print_mac(s, m)), ast::ExprParen(e) => { - popen(s); - print_expr(s, e); - pclose(s); + if_ok!(popen(s)); + if_ok!(print_expr(s, e)); + if_ok!(pclose(s)); } } { let ann_node = NodeExpr(s, expr); - s.ann.post(ann_node); + if_ok!(s.ann.post(ann_node)); } - end(s); + end(s) } -pub fn print_local_decl(s: &mut State, loc: &ast::Local) { - print_pat(s, loc.pat); +pub fn print_local_decl(s: &mut State, loc: &ast::Local) -> io::IoResult<()> { + if_ok!(print_pat(s, loc.pat)); match loc.ty.node { ast::TyInfer => {} - _ => { word_space(s, ":"); print_type(s, loc.ty); } + _ => { + if_ok!(word_space(s, ":")); + if_ok!(print_type(s, loc.ty)); + } } + Ok(()) } -pub fn print_decl(s: &mut State, decl: &ast::Decl) { - maybe_print_comment(s, decl.span.lo); +pub fn print_decl(s: &mut State, decl: &ast::Decl) -> io::IoResult<()> { + if_ok!(maybe_print_comment(s, decl.span.lo)); match decl.node { ast::DeclLocal(ref loc) => { - space_if_not_bol(s); - ibox(s, indent_unit); - word_nbsp(s, "let"); - - fn print_local(s: &mut State, loc: &ast::Local) { - ibox(s, indent_unit); - print_local_decl(s, loc); - end(s); + if_ok!(space_if_not_bol(s)); + if_ok!(ibox(s, indent_unit)); + if_ok!(word_nbsp(s, "let")); + + fn print_local(s: &mut State, loc: &ast::Local) -> io::IoResult<()> { + if_ok!(ibox(s, indent_unit)); + if_ok!(print_local_decl(s, loc)); + if_ok!(end(s)); match loc.init { Some(init) => { - nbsp(s); - word_space(s, "="); - print_expr(s, init); + if_ok!(nbsp(s)); + if_ok!(word_space(s, "=")); + if_ok!(print_expr(s, init)); } _ => () } + Ok(()) } - print_local(s, *loc); - end(s); + if_ok!(print_local(s, *loc)); + end(s) } ast::DeclItem(item) => print_item(s, item) } } +<<<<<<< HEAD pub fn print_ident(s: &mut State, ident: ast::Ident) { let string = token::get_ident(ident.name); word(&mut s.s, string.get()); @@ -1532,22 +1668,33 @@ pub fn print_ident(s: &mut State, ident: ast::Ident) { pub fn print_name(s: &mut State, name: ast::Name) { let string = token::get_ident(name); word(&mut s.s, string.get()); +======= +pub fn print_ident(s: &mut State, ident: ast::Ident) -> io::IoResult<()> { + word(&mut s.s, ident_to_str(&ident)) } -pub fn print_for_decl(s: &mut State, loc: &ast::Local, coll: &ast::Expr) { - print_local_decl(s, loc); - space(&mut s.s); - word_space(s, "in"); - print_expr(s, coll); +pub fn print_name(s: &mut State, name: ast::Name) -> io::IoResult<()> { + word(&mut s.s, interner_get(name)) +>>>>>>> syntax: Remove io_error usage +} + +pub fn print_for_decl(s: &mut State, loc: &ast::Local, + coll: &ast::Expr) -> io::IoResult<()> { + if_ok!(print_local_decl(s, loc)); + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, "in")); + print_expr(s, coll) } fn print_path_(s: &mut State, path: &ast::Path, colons_before_params: bool, - opt_bounds: &Option>) { - maybe_print_comment(s, path.span.lo); + opt_bounds: &Option>) + -> io::IoResult<()> +{ + if_ok!(maybe_print_comment(s, path.span.lo)); if path.global { - word(&mut s.s, "::"); + if_ok!(word(&mut s.s, "::")); } let mut first = true; @@ -1555,198 +1702,207 @@ fn print_path_(s: &mut State, if first { first = false } else { - word(&mut s.s, "::") + if_ok!(word(&mut s.s, "::")) } - print_ident(s, segment.identifier); + if_ok!(print_ident(s, segment.identifier)); // If this is the last segment, print the bounds. if i == path.segments.len() - 1 { match *opt_bounds { None => {} - Some(ref bounds) => print_bounds(s, bounds, true), + Some(ref bounds) => if_ok!(print_bounds(s, bounds, true)), } } if !segment.lifetimes.is_empty() || !segment.types.is_empty() { if colons_before_params { - word(&mut s.s, "::") + if_ok!(word(&mut s.s, "::")) } - word(&mut s.s, "<"); + if_ok!(word(&mut s.s, "<")); let mut comma = false; for lifetime in segment.lifetimes.iter() { if comma { - word_space(s, ",") + if_ok!(word_space(s, ",")) } - print_lifetime(s, lifetime); + if_ok!(print_lifetime(s, lifetime)); comma = true; } if !segment.types.is_empty() { if comma { - word_space(s, ",") + if_ok!(word_space(s, ",")) } - commasep(s, - Inconsistent, - segment.types.map_to_vec(|&t| t), - print_type_ref); + if_ok!(commasep(s, + Inconsistent, + segment.types.map_to_vec(|&t| t), + print_type_ref)); } - word(&mut s.s, ">") + if_ok!(word(&mut s.s, ">")) } } + Ok(()) } -pub fn print_path(s: &mut State, path: &ast::Path, colons_before_params: bool) { +pub fn print_path(s: &mut State, path: &ast::Path, + colons_before_params: bool) -> io::IoResult<()> { print_path_(s, path, colons_before_params, &None) } pub fn print_bounded_path(s: &mut State, path: &ast::Path, - bounds: &Option>) { + bounds: &Option>) + -> io::IoResult<()> +{ print_path_(s, path, false, bounds) } -pub fn print_pat(s: &mut State, pat: &ast::Pat) { - maybe_print_comment(s, pat.span.lo); +pub fn print_pat(s: &mut State, pat: &ast::Pat) -> io::IoResult<()> { + if_ok!(maybe_print_comment(s, pat.span.lo)); { let ann_node = NodePat(s, pat); - s.ann.pre(ann_node); + if_ok!(s.ann.pre(ann_node)); } /* Pat isn't normalized, but the beauty of it is that it doesn't matter */ match pat.node { - ast::PatWild => word(&mut s.s, "_"), - ast::PatWildMulti => word(&mut s.s, ".."), + ast::PatWild => if_ok!(word(&mut s.s, "_")), + ast::PatWildMulti => if_ok!(word(&mut s.s, "..")), ast::PatIdent(binding_mode, ref path, sub) => { match binding_mode { ast::BindByRef(mutbl) => { - word_nbsp(s, "ref"); - print_mutability(s, mutbl); + if_ok!(word_nbsp(s, "ref")); + if_ok!(print_mutability(s, mutbl)); } ast::BindByValue(ast::MutImmutable) => {} ast::BindByValue(ast::MutMutable) => { - word_nbsp(s, "mut"); + if_ok!(word_nbsp(s, "mut")); } } - print_path(s, path, true); + if_ok!(print_path(s, path, true)); match sub { Some(p) => { - word(&mut s.s, "@"); - print_pat(s, p); + if_ok!(word(&mut s.s, "@")); + if_ok!(print_pat(s, p)); } None => () } } ast::PatEnum(ref path, ref args_) => { - print_path(s, path, true); + if_ok!(print_path(s, path, true)); match *args_ { - None => word(&mut s.s, "(..)"), + None => if_ok!(word(&mut s.s, "(..)")), Some(ref args) => { if !args.is_empty() { - popen(s); - commasep(s, Inconsistent, *args, - |s, &p| print_pat(s, p)); - pclose(s); + if_ok!(popen(s)); + if_ok!(commasep(s, Inconsistent, *args, + |s, &p| print_pat(s, p))); + if_ok!(pclose(s)); } else { } } } } ast::PatStruct(ref path, ref fields, etc) => { - print_path(s, path, true); - word(&mut s.s, "{"); - fn print_field(s: &mut State, f: &ast::FieldPat) { - cbox(s, indent_unit); - print_ident(s, f.ident); - word_space(s, ":"); - print_pat(s, f.pat); - end(s); + if_ok!(print_path(s, path, true)); + if_ok!(word(&mut s.s, "{")); + fn print_field(s: &mut State, f: &ast::FieldPat) -> io::IoResult<()> { + if_ok!(cbox(s, indent_unit)); + if_ok!(print_ident(s, f.ident)); + if_ok!(word_space(s, ":")); + if_ok!(print_pat(s, f.pat)); + if_ok!(end(s)); + Ok(()) } fn get_span(f: &ast::FieldPat) -> codemap::Span { return f.pat.span; } - commasep_cmnt(s, Consistent, *fields, - |s, f| print_field(s,f), - get_span); + if_ok!(commasep_cmnt(s, Consistent, *fields, + |s, f| print_field(s,f), + get_span)); if etc { - if fields.len() != 0u { word_space(s, ","); } - word(&mut s.s, ".."); + if fields.len() != 0u { if_ok!(word_space(s, ",")); } + if_ok!(word(&mut s.s, "..")); } - word(&mut s.s, "}"); + if_ok!(word(&mut s.s, "}")); } ast::PatTup(ref elts) => { - popen(s); - commasep(s, Inconsistent, *elts, |s, &p| print_pat(s, p)); + if_ok!(popen(s)); + if_ok!(commasep(s, Inconsistent, *elts, |s, &p| print_pat(s, p))); if elts.len() == 1 { - word(&mut s.s, ","); + if_ok!(word(&mut s.s, ",")); } - pclose(s); + if_ok!(pclose(s)); } ast::PatUniq(inner) => { - word(&mut s.s, "~"); - print_pat(s, inner); + if_ok!(word(&mut s.s, "~")); + if_ok!(print_pat(s, inner)); } ast::PatRegion(inner) => { - word(&mut s.s, "&"); - print_pat(s, inner); + if_ok!(word(&mut s.s, "&")); + if_ok!(print_pat(s, inner)); } - ast::PatLit(e) => print_expr(s, e), + ast::PatLit(e) => if_ok!(print_expr(s, e)), ast::PatRange(begin, end) => { - print_expr(s, begin); - space(&mut s.s); - word(&mut s.s, ".."); - print_expr(s, end); + if_ok!(print_expr(s, begin)); + if_ok!(space(&mut s.s)); + if_ok!(word(&mut s.s, "..")); + if_ok!(print_expr(s, end)); } ast::PatVec(ref before, slice, ref after) => { - word(&mut s.s, "["); - commasep(s, Inconsistent, *before, |s, &p| print_pat(s, p)); + if_ok!(word(&mut s.s, "[")); + if_ok!(commasep(s, Inconsistent, *before, |s, &p| print_pat(s, p))); for &p in slice.iter() { - if !before.is_empty() { word_space(s, ","); } + if !before.is_empty() { if_ok!(word_space(s, ",")); } match *p { ast::Pat { node: ast::PatWildMulti, .. } => { // this case is handled by print_pat } - _ => word(&mut s.s, ".."), + _ => if_ok!(word(&mut s.s, "..")), } - print_pat(s, p); - if !after.is_empty() { word_space(s, ","); } + if_ok!(print_pat(s, p)); + if !after.is_empty() { if_ok!(word_space(s, ",")); } } - commasep(s, Inconsistent, *after, |s, &p| print_pat(s, p)); - word(&mut s.s, "]"); + if_ok!(commasep(s, Inconsistent, *after, |s, &p| print_pat(s, p))); + if_ok!(word(&mut s.s, "]")); } } { let ann_node = NodePat(s, pat); - s.ann.post(ann_node); + if_ok!(s.ann.post(ann_node)); } + Ok(()) } -pub fn explicit_self_to_str(explicit_self: &ast::ExplicitSelf_, intr: @IdentInterner) -> ~str { - to_str(explicit_self, |a, &b| { print_explicit_self(a, b, ast::MutImmutable); () }, intr) +pub fn explicit_self_to_str(explicit_self: &ast::ExplicitSelf_, + intr: @IdentInterner) -> ~str { + to_str(explicit_self, |a, &b| { + print_explicit_self(a, b, ast::MutImmutable).map(|_| ()) + }, intr) } // Returns whether it printed anything fn print_explicit_self(s: &mut State, explicit_self: ast::ExplicitSelf_, - mutbl: ast::Mutability) -> bool { - print_mutability(s, mutbl); + mutbl: ast::Mutability) -> io::IoResult { + if_ok!(print_mutability(s, mutbl)); match explicit_self { - ast::SelfStatic => { return false; } + ast::SelfStatic => { return Ok(false); } ast::SelfValue => { - word(&mut s.s, "self"); + if_ok!(word(&mut s.s, "self")); } ast::SelfUniq => { - word(&mut s.s, "~self"); + if_ok!(word(&mut s.s, "~self")); } ast::SelfRegion(ref lt, m) => { - word(&mut s.s, "&"); - print_opt_lifetime(s, lt); - print_mutability(s, m); - word(&mut s.s, "self"); + if_ok!(word(&mut s.s, "&")); + if_ok!(print_opt_lifetime(s, lt)); + if_ok!(print_mutability(s, m)); + if_ok!(word(&mut s.s, "self")); } ast::SelfBox => { - word(&mut s.s, "@self"); + if_ok!(word(&mut s.s, "@self")); } } - return true; + return Ok(true); } pub fn print_fn(s: &mut State, @@ -1756,20 +1912,24 @@ pub fn print_fn(s: &mut State, name: ast::Ident, generics: &ast::Generics, opt_explicit_self: Option, - vis: ast::Visibility) { - head(s, ""); - print_fn_header_info(s, opt_explicit_self, purity, abis, ast::Many, None, vis); - nbsp(s); - print_ident(s, name); - print_generics(s, generics); - print_fn_args_and_ret(s, decl, opt_explicit_self); + vis: ast::Visibility) -> io::IoResult<()> { + if_ok!(head(s, "")); + if_ok!(print_fn_header_info(s, opt_explicit_self, purity, abis, + ast::Many, None, vis)); + if_ok!(nbsp(s)); + if_ok!(print_ident(s, name)); + if_ok!(print_generics(s, generics)); + if_ok!(print_fn_args_and_ret(s, decl, opt_explicit_self)); + Ok(()) } pub fn print_fn_args(s: &mut State, decl: &ast::FnDecl, - opt_explicit_self: Option) { + opt_explicit_self: Option) + -> io::IoResult<()> +{ // It is unfortunate to duplicate the commasep logic, but we want the // self type and the args all in the same box. - rbox(s, 0u, Inconsistent); + if_ok!(rbox(s, 0u, Inconsistent)); let mut first = true; for &explicit_self in opt_explicit_self.iter() { let m = match explicit_self { @@ -1779,7 +1939,7 @@ pub fn print_fn_args(s: &mut State, decl: &ast::FnDecl, _ => ast::MutImmutable } }; - first = !print_explicit_self(s, explicit_self, m); + first = !if_ok!(print_explicit_self(s, explicit_self, m)); } // HACK(eddyb) ignore the separately printed self argument. @@ -1790,107 +1950,116 @@ pub fn print_fn_args(s: &mut State, decl: &ast::FnDecl, }; for arg in args.iter() { - if first { first = false; } else { word_space(s, ","); } - print_arg(s, arg); + if first { first = false; } else { if_ok!(word_space(s, ",")); } + if_ok!(print_arg(s, arg)); } - end(s); + end(s) } pub fn print_fn_args_and_ret(s: &mut State, decl: &ast::FnDecl, - opt_explicit_self: Option) { - popen(s); - print_fn_args(s, decl, opt_explicit_self); + opt_explicit_self: Option) + -> io::IoResult<()> +{ + if_ok!(popen(s)); + if_ok!(print_fn_args(s, decl, opt_explicit_self)); if decl.variadic { - word(&mut s.s, ", ..."); + if_ok!(word(&mut s.s, ", ...")); } - pclose(s); + if_ok!(pclose(s)); - maybe_print_comment(s, decl.output.span.lo); + if_ok!(maybe_print_comment(s, decl.output.span.lo)); match decl.output.node { ast::TyNil => {} _ => { - space_if_not_bol(s); - word_space(s, "->"); - print_type(s, decl.output); + if_ok!(space_if_not_bol(s)); + if_ok!(word_space(s, "->")); + if_ok!(print_type(s, decl.output)); } } + Ok(()) } -pub fn print_fn_block_args(s: &mut State, decl: &ast::FnDecl) { - word(&mut s.s, "|"); - print_fn_args(s, decl, None); - word(&mut s.s, "|"); +pub fn print_fn_block_args(s: &mut State, + decl: &ast::FnDecl) -> io::IoResult<()> { + if_ok!(word(&mut s.s, "|")); + if_ok!(print_fn_args(s, decl, None)); + if_ok!(word(&mut s.s, "|")); match decl.output.node { ast::TyInfer => {} _ => { - space_if_not_bol(s); - word_space(s, "->"); - print_type(s, decl.output); + if_ok!(space_if_not_bol(s)); + if_ok!(word_space(s, "->")); + if_ok!(print_type(s, decl.output)); } } - maybe_print_comment(s, decl.output.span.lo); + maybe_print_comment(s, decl.output.span.lo) } -pub fn print_proc_args(s: &mut State, decl: &ast::FnDecl) { - word(&mut s.s, "proc"); - word(&mut s.s, "("); - print_fn_args(s, decl, None); - word(&mut s.s, ")"); +pub fn print_proc_args(s: &mut State, decl: &ast::FnDecl) -> io::IoResult<()> { + if_ok!(word(&mut s.s, "proc")); + if_ok!(word(&mut s.s, "(")); + if_ok!(print_fn_args(s, decl, None)); + if_ok!(word(&mut s.s, ")")); match decl.output.node { ast::TyInfer => {} _ => { - space_if_not_bol(s); - word_space(s, "->"); - print_type(s, decl.output); + if_ok!(space_if_not_bol(s)); + if_ok!(word_space(s, "->")); + if_ok!(print_type(s, decl.output)); } } - maybe_print_comment(s, decl.output.span.lo); + maybe_print_comment(s, decl.output.span.lo) } pub fn print_bounds(s: &mut State, bounds: &OptVec, - print_colon_anyway: bool) { + print_colon_anyway: bool) -> io::IoResult<()> { if !bounds.is_empty() { - word(&mut s.s, ":"); + if_ok!(word(&mut s.s, ":")); let mut first = true; for bound in bounds.iter() { - nbsp(s); + if_ok!(nbsp(s)); if first { first = false; } else { - word_space(s, "+"); + if_ok!(word_space(s, "+")); } - match *bound { + if_ok!(match *bound { TraitTyParamBound(ref tref) => print_trait_ref(s, tref), RegionTyParamBound => word(&mut s.s, "'static"), - } + }) } } else if print_colon_anyway { - word(&mut s.s, ":"); + if_ok!(word(&mut s.s, ":")); } + Ok(()) } -pub fn print_lifetime(s: &mut State, lifetime: &ast::Lifetime) { - word(&mut s.s, "'"); - print_ident(s, lifetime.ident); +pub fn print_lifetime(s: &mut State, + lifetime: &ast::Lifetime) -> io::IoResult<()> { + if_ok!(word(&mut s.s, "'")); + print_ident(s, lifetime.ident) } -pub fn print_generics(s: &mut State, generics: &ast::Generics) { +pub fn print_generics(s: &mut State, + generics: &ast::Generics) -> io::IoResult<()> { let total = generics.lifetimes.len() + generics.ty_params.len(); if total > 0 { - word(&mut s.s, "<"); - fn print_item(s: &mut State, generics: &ast::Generics, idx: uint) { + if_ok!(word(&mut s.s, "<")); + fn print_item(s: &mut State, generics: &ast::Generics, + idx: uint) -> io::IoResult<()> { if idx < generics.lifetimes.len() { let lifetime = generics.lifetimes.get(idx); - print_lifetime(s, lifetime); + print_lifetime(s, lifetime) } else { let idx = idx - generics.lifetimes.len(); let param = generics.ty_params.get(idx); +<<<<<<< HEAD print_ident(s, param.ident); print_bounds(s, ¶m.bounds, false); match param.default { @@ -1901,6 +2070,10 @@ pub fn print_generics(s: &mut State, generics: &ast::Generics) { } _ => {} } +======= + if_ok!(print_ident(s, param.ident)); + print_bounds(s, ¶m.bounds, false) +>>>>>>> syntax: Remove io_error usage } } @@ -1909,15 +2082,17 @@ pub fn print_generics(s: &mut State, generics: &ast::Generics) { ints.push(i); } - commasep(s, Inconsistent, ints, - |s, &i| print_item(s, generics, i)); - word(&mut s.s, ">"); + if_ok!(commasep(s, Inconsistent, ints, + |s, &i| print_item(s, generics, i))); + if_ok!(word(&mut s.s, ">")); } + Ok(()) } -pub fn print_meta_item(s: &mut State, item: &ast::MetaItem) { - ibox(s, indent_unit); +pub fn print_meta_item(s: &mut State, item: &ast::MetaItem) -> io::IoResult<()> { + if_ok!(ibox(s, indent_unit)); match item.node { +<<<<<<< HEAD ast::MetaWord(ref name) => word(&mut s.s, name.get()), ast::MetaNameValue(ref name, ref value) => { word_space(s, name.get()); @@ -1932,90 +2107,116 @@ pub fn print_meta_item(s: &mut State, item: &ast::MetaItem) { items.as_slice(), |p, &i| print_meta_item(p, i)); pclose(s); +======= + ast::MetaWord(name) => { if_ok!(word(&mut s.s, name)); } + ast::MetaNameValue(name, value) => { + if_ok!(word_space(s, name)); + if_ok!(word_space(s, "=")); + if_ok!(print_literal(s, &value)); + } + ast::MetaList(name, ref items) => { + if_ok!(word(&mut s.s, name)); + if_ok!(popen(s)); + if_ok!(commasep(s, + Consistent, + items.as_slice(), + |p, &i| print_meta_item(p, i))); + if_ok!(pclose(s)); +>>>>>>> syntax: Remove io_error usage } } - end(s); + end(s) } -pub fn print_view_path(s: &mut State, vp: &ast::ViewPath) { +pub fn print_view_path(s: &mut State, vp: &ast::ViewPath) -> io::IoResult<()> { match vp.node { ast::ViewPathSimple(ident, ref path, _) => { // FIXME(#6993) can't compare identifiers directly here if path.segments.last().unwrap().identifier.name != ident.name { - print_ident(s, ident); - space(&mut s.s); - word_space(s, "="); + if_ok!(print_ident(s, ident)); + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, "=")); } - print_path(s, path, false); + print_path(s, path, false) } ast::ViewPathGlob(ref path, _) => { - print_path(s, path, false); - word(&mut s.s, "::*"); + if_ok!(print_path(s, path, false)); + word(&mut s.s, "::*") } ast::ViewPathList(ref path, ref idents, _) => { if path.segments.is_empty() { - word(&mut s.s, "{"); + if_ok!(word(&mut s.s, "{")); } else { - print_path(s, path, false); - word(&mut s.s, "::{"); + if_ok!(print_path(s, path, false)); + if_ok!(word(&mut s.s, "::{")); } - commasep(s, Inconsistent, (*idents), |s, w| { - print_ident(s, w.node.name); - }); - word(&mut s.s, "}"); + if_ok!(commasep(s, Inconsistent, (*idents), |s, w| { + print_ident(s, w.node.name) + })); + word(&mut s.s, "}") } } } -pub fn print_view_paths(s: &mut State, vps: &[@ast::ViewPath]) { - commasep(s, Inconsistent, vps, |p, &vp| print_view_path(p, vp)); +pub fn print_view_paths(s: &mut State, + vps: &[@ast::ViewPath]) -> io::IoResult<()> { + commasep(s, Inconsistent, vps, |p, &vp| print_view_path(p, vp)) } -pub fn print_view_item(s: &mut State, item: &ast::ViewItem) { - hardbreak_if_not_bol(s); - maybe_print_comment(s, item.span.lo); - print_outer_attributes(s, item.attrs); - print_visibility(s, item.vis); +pub fn print_view_item(s: &mut State, item: &ast::ViewItem) -> io::IoResult<()> { + if_ok!(hardbreak_if_not_bol(s)); + if_ok!(maybe_print_comment(s, item.span.lo)); + if_ok!(print_outer_attributes(s, item.attrs)); + if_ok!(print_visibility(s, item.vis)); match item.node { ast::ViewItemExternMod(id, ref optional_path, _) => { - head(s, "extern mod"); - print_ident(s, id); + if_ok!(head(s, "extern mod")); + if_ok!(print_ident(s, id)); for &(ref p, style) in optional_path.iter() { +<<<<<<< HEAD space(&mut s.s); word(&mut s.s, "="); space(&mut s.s); print_string(s, p.get(), style); +======= + if_ok!(space(&mut s.s)); + if_ok!(word(&mut s.s, "=")); + if_ok!(space(&mut s.s)); + if_ok!(print_string(s, *p, style)); +>>>>>>> syntax: Remove io_error usage } } ast::ViewItemUse(ref vps) => { - head(s, "use"); - print_view_paths(s, *vps); + if_ok!(head(s, "use")); + if_ok!(print_view_paths(s, *vps)); } } - word(&mut s.s, ";"); - end(s); // end inner head-block - end(s); // end outer head-block + if_ok!(word(&mut s.s, ";")); + if_ok!(end(s)); // end inner head-block + if_ok!(end(s)); // end outer head-block + Ok(()) } -pub fn print_mutability(s: &mut State, mutbl: ast::Mutability) { +pub fn print_mutability(s: &mut State, + mutbl: ast::Mutability) -> io::IoResult<()> { match mutbl { ast::MutMutable => word_nbsp(s, "mut"), - ast::MutImmutable => {/* nothing */ } + ast::MutImmutable => Ok(()), } } -pub fn print_mt(s: &mut State, mt: &ast::MutTy) { - print_mutability(s, mt.mutbl); - print_type(s, mt.ty); +pub fn print_mt(s: &mut State, mt: &ast::MutTy) -> io::IoResult<()> { + if_ok!(print_mutability(s, mt.mutbl)); + print_type(s, mt.ty) } -pub fn print_arg(s: &mut State, input: &ast::Arg) { - ibox(s, indent_unit); +pub fn print_arg(s: &mut State, input: &ast::Arg) -> io::IoResult<()> { + if_ok!(ibox(s, indent_unit)); match input.ty.node { - ast::TyInfer => print_pat(s, input.pat), + ast::TyInfer => if_ok!(print_pat(s, input.pat)), _ => { match input.pat.node { ast::PatIdent(_, ref path, _) if @@ -2025,15 +2226,15 @@ pub fn print_arg(s: &mut State, input: &ast::Arg) { // Do nothing. } _ => { - print_pat(s, input.pat); - word(&mut s.s, ":"); - space(&mut s.s); + if_ok!(print_pat(s, input.pat)); + if_ok!(word(&mut s.s, ":")); + if_ok!(space(&mut s.s)); } } - print_type(s, input.ty); + if_ok!(print_type(s, input.ty)); } } - end(s); + end(s) } pub fn print_ty_fn(s: &mut State, @@ -2046,120 +2247,137 @@ pub fn print_ty_fn(s: &mut State, id: Option, opt_bounds: &Option>, generics: Option<&ast::Generics>, - opt_explicit_self: Option) { - ibox(s, indent_unit); + opt_explicit_self: Option) + -> io::IoResult<()> +{ + if_ok!(ibox(s, indent_unit)); // Duplicates the logic in `print_fn_header_info()`. This is because that // function prints the sigil in the wrong place. That should be fixed. if opt_sigil == Some(ast::OwnedSigil) && onceness == ast::Once { - word(&mut s.s, "proc"); + if_ok!(word(&mut s.s, "proc")); } else if opt_sigil == Some(ast::BorrowedSigil) { - print_extern_opt_abis(s, opt_abis); + if_ok!(print_extern_opt_abis(s, opt_abis)); for lifetime in opt_region.iter() { - print_lifetime(s, lifetime); + if_ok!(print_lifetime(s, lifetime)); } - print_purity(s, purity); - print_onceness(s, onceness); + if_ok!(print_purity(s, purity)); + if_ok!(print_onceness(s, onceness)); } else { - print_opt_abis_and_extern_if_nondefault(s, opt_abis); - print_opt_sigil(s, opt_sigil); - print_opt_lifetime(s, opt_region); - print_purity(s, purity); - print_onceness(s, onceness); - word(&mut s.s, "fn"); + if_ok!(print_opt_abis_and_extern_if_nondefault(s, opt_abis)); + if_ok!(print_opt_sigil(s, opt_sigil)); + if_ok!(print_opt_lifetime(s, opt_region)); + if_ok!(print_purity(s, purity)); + if_ok!(print_onceness(s, onceness)); + if_ok!(word(&mut s.s, "fn")); } - match id { Some(id) => { word(&mut s.s, " "); print_ident(s, id); } _ => () } + match id { + Some(id) => { + if_ok!(word(&mut s.s, " ")); + if_ok!(print_ident(s, id)); + } + _ => () + } if opt_sigil != Some(ast::BorrowedSigil) { opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true)); } - match generics { Some(g) => print_generics(s, g), _ => () } - zerobreak(&mut s.s); + match generics { Some(g) => if_ok!(print_generics(s, g)), _ => () } + if_ok!(zerobreak(&mut s.s)); if opt_sigil == Some(ast::BorrowedSigil) { - word(&mut s.s, "|"); + if_ok!(word(&mut s.s, "|")); } else { - popen(s); + if_ok!(popen(s)); } - print_fn_args(s, decl, opt_explicit_self); + if_ok!(print_fn_args(s, decl, opt_explicit_self)); if opt_sigil == Some(ast::BorrowedSigil) { - word(&mut s.s, "|"); + if_ok!(word(&mut s.s, "|")); opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true)); } else { if decl.variadic { - word(&mut s.s, ", ..."); + if_ok!(word(&mut s.s, ", ...")); } - pclose(s); + if_ok!(pclose(s)); } - maybe_print_comment(s, decl.output.span.lo); + if_ok!(maybe_print_comment(s, decl.output.span.lo)); match decl.output.node { ast::TyNil => {} _ => { - space_if_not_bol(s); - ibox(s, indent_unit); - word_space(s, "->"); - if decl.cf == ast::NoReturn { word_nbsp(s, "!"); } - else { print_type(s, decl.output); } - end(s); + if_ok!(space_if_not_bol(s)); + if_ok!(ibox(s, indent_unit)); + if_ok!(word_space(s, "->")); + if decl.cf == ast::NoReturn { + if_ok!(word_nbsp(s, "!")); + } else { + if_ok!(print_type(s, decl.output)); + } + if_ok!(end(s)); } } - end(s); + end(s) } pub fn maybe_print_trailing_comment(s: &mut State, span: codemap::Span, - next_pos: Option) { + next_pos: Option) + -> io::IoResult<()> +{ let cm; - match s.cm { Some(ccm) => cm = ccm, _ => return } + match s.cm { Some(ccm) => cm = ccm, _ => return Ok(()) } match next_comment(s) { - Some(ref cmnt) => { - if (*cmnt).style != comments::Trailing { return; } - let span_line = cm.lookup_char_pos(span.hi); - let comment_line = cm.lookup_char_pos((*cmnt).pos); - let mut next = (*cmnt).pos + BytePos(1); - match next_pos { None => (), Some(p) => next = p } - if span.hi < (*cmnt).pos && (*cmnt).pos < next && - span_line.line == comment_line.line { - print_comment(s, cmnt); - s.cur_cmnt_and_lit.cur_cmnt += 1u; + Some(ref cmnt) => { + if (*cmnt).style != comments::Trailing { return Ok(()) } + let span_line = cm.lookup_char_pos(span.hi); + let comment_line = cm.lookup_char_pos((*cmnt).pos); + let mut next = (*cmnt).pos + BytePos(1); + match next_pos { None => (), Some(p) => next = p } + if span.hi < (*cmnt).pos && (*cmnt).pos < next && + span_line.line == comment_line.line { + if_ok!(print_comment(s, cmnt)); + s.cur_cmnt_and_lit.cur_cmnt += 1u; + } } - } - _ => () + _ => () } + Ok(()) } -pub fn print_remaining_comments(s: &mut State) { +pub fn print_remaining_comments(s: &mut State) -> io::IoResult<()> { // If there aren't any remaining comments, then we need to manually // make sure there is a line break at the end. - if next_comment(s).is_none() { hardbreak(&mut s.s); } + if next_comment(s).is_none() { + if_ok!(hardbreak(&mut s.s)); + } loop { match next_comment(s) { - Some(ref cmnt) => { - print_comment(s, cmnt); - s.cur_cmnt_and_lit.cur_cmnt += 1u; - } - _ => break + Some(ref cmnt) => { + if_ok!(print_comment(s, cmnt)); + s.cur_cmnt_and_lit.cur_cmnt += 1u; + } + _ => break } } + Ok(()) } -pub fn print_literal(s: &mut State, lit: &ast::Lit) { - maybe_print_comment(s, lit.span.lo); +pub fn print_literal(s: &mut State, lit: &ast::Lit) -> io::IoResult<()> { + if_ok!(maybe_print_comment(s, lit.span.lo)); match next_lit(s, lit.span.lo) { Some(ref ltrl) => { - word(&mut s.s, (*ltrl).lit); - return; + return word(&mut s.s, (*ltrl).lit); } _ => () } match lit.node { +<<<<<<< HEAD ast::LitStr(ref st, style) => print_string(s, st.get(), style), ast::LitChar(ch) => { let mut res = ~"'"; @@ -2176,19 +2394,52 @@ pub fn print_literal(s: &mut State, lit: &ast::Lit) { word(&mut s.s, (i as u64).to_str_radix(10u) + ast_util::int_ty_to_str(t)); +======= + ast::LitStr(st, style) => print_string(s, st, style), + ast::LitChar(ch) => { + let mut res = ~"'"; + char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c)); + res.push_char('\''); + word(&mut s.s, res) + } + ast::LitInt(i, t) => { + if i < 0_i64 { + word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u) + + ast_util::int_ty_to_str(t)) + } else { + word(&mut s.s, (i as u64).to_str_radix(10u) + + ast_util::int_ty_to_str(t)) + } +>>>>>>> syntax: Remove io_error usage } - } - ast::LitUint(u, t) => { - word(&mut s.s, - u.to_str_radix(10u) - + ast_util::uint_ty_to_str(t)); - } - ast::LitIntUnsuffixed(i) => { - if i < 0_i64 { - word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u)); - } else { - word(&mut s.s, (i as u64).to_str_radix(10u)); + ast::LitUint(u, t) => { + word(&mut s.s, u.to_str_radix(10u) + ast_util::uint_ty_to_str(t)) + } + ast::LitIntUnsuffixed(i) => { + if i < 0_i64 { + word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u)) + } else { + word(&mut s.s, (i as u64).to_str_radix(10u)) + } + } + ast::LitFloat(f, t) => { + word(&mut s.s, f.to_owned() + ast_util::float_ty_to_str(t)) + } + ast::LitFloatUnsuffixed(f) => word(&mut s.s, f), + ast::LitNil => word(&mut s.s, "()"), + ast::LitBool(val) => { + if val { word(&mut s.s, "true") } else { word(&mut s.s, "false") } + } + ast::LitBinary(arr) => { + if_ok!(ibox(s, indent_unit)); + if_ok!(word(&mut s.s, "[")); + if_ok!(commasep_cmnt(s, Inconsistent, arr, + |s, u| word(&mut s.s, format!("{}", *u)), + |_| lit.span)); + if_ok!(word(&mut s.s, "]")); + end(s) } +<<<<<<< HEAD } ast::LitFloat(ref f, t) => { word(&mut s.s, f.get() + ast_util::float_ty_to_str(t)); @@ -2206,6 +2457,8 @@ pub fn print_literal(s: &mut State, lit: &ast::Lit) { word(&mut s.s, "]"); end(s); } +======= +>>>>>>> syntax: Remove io_error usage } } @@ -2228,49 +2481,55 @@ pub fn next_lit(s: &mut State, pos: BytePos) -> Option { } } -pub fn maybe_print_comment(s: &mut State, pos: BytePos) { +pub fn maybe_print_comment(s: &mut State, pos: BytePos) -> io::IoResult<()> { loop { match next_comment(s) { Some(ref cmnt) => { if (*cmnt).pos < pos { - print_comment(s, cmnt); + if_ok!(print_comment(s, cmnt)); s.cur_cmnt_and_lit.cur_cmnt += 1u; } else { break; } } _ => break } } + Ok(()) } -pub fn print_comment(s: &mut State, cmnt: &comments::Comment) { +pub fn print_comment(s: &mut State, + cmnt: &comments::Comment) -> io::IoResult<()> { match cmnt.style { comments::Mixed => { assert_eq!(cmnt.lines.len(), 1u); - zerobreak(&mut s.s); - word(&mut s.s, cmnt.lines[0]); - zerobreak(&mut s.s); + if_ok!(zerobreak(&mut s.s)); + if_ok!(word(&mut s.s, cmnt.lines[0])); + if_ok!(zerobreak(&mut s.s)); } comments::Isolated => { - pprust::hardbreak_if_not_bol(s); + if_ok!(pprust::hardbreak_if_not_bol(s)); for line in cmnt.lines.iter() { // Don't print empty lines because they will end up as trailing // whitespace - if !line.is_empty() { word(&mut s.s, *line); } - hardbreak(&mut s.s); + if !line.is_empty() { + if_ok!(word(&mut s.s, *line)); + } + if_ok!(hardbreak(&mut s.s)); } } comments::Trailing => { - word(&mut s.s, " "); + if_ok!(word(&mut s.s, " ")); if cmnt.lines.len() == 1u { - word(&mut s.s, cmnt.lines[0]); - hardbreak(&mut s.s); + if_ok!(word(&mut s.s, cmnt.lines[0])); + if_ok!(hardbreak(&mut s.s)); } else { - ibox(s, 0u); + if_ok!(ibox(s, 0u)); for line in cmnt.lines.iter() { - if !line.is_empty() { word(&mut s.s, *line); } - hardbreak(&mut s.s); + if !line.is_empty() { + if_ok!(word(&mut s.s, *line)); + } + if_ok!(hardbreak(&mut s.s)); } - end(s); + if_ok!(end(s)); } } comments::BlankLine => { @@ -2279,19 +2538,23 @@ pub fn print_comment(s: &mut State, cmnt: &comments::Comment) { pp::String(s, _) => ";" == s, _ => false }; - if is_semi || is_begin(s) || is_end(s) { hardbreak(&mut s.s); } - hardbreak(&mut s.s); + if is_semi || is_begin(s) || is_end(s) { + if_ok!(hardbreak(&mut s.s)); + } + if_ok!(hardbreak(&mut s.s)); } } + Ok(()) } -pub fn print_string(s: &mut State, st: &str, style: ast::StrStyle) { +pub fn print_string(s: &mut State, st: &str, + style: ast::StrStyle) -> io::IoResult<()> { let st = match style { ast::CookedStr => format!("\"{}\"", st.escape_default()), ast::RawStr(n) => format!("r{delim}\"{string}\"{delim}", delim="#".repeat(n), string=st) }; - word(&mut s.s, st); + word(&mut s.s, st) } // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer` @@ -2304,11 +2567,12 @@ unsafe fn get_mem_writer(writer: &mut ~io::Writer) -> ~str { result } -pub fn to_str(t: &T, f: |&mut State, &T|, intr: @IdentInterner) -> ~str { +pub fn to_str(t: &T, f: |&mut State, &T| -> io::IoResult<()>, + intr: @IdentInterner) -> ~str { let wr = ~MemWriter::new(); let mut s = rust_printer(wr as ~io::Writer, intr); - f(&mut s, t); - eof(&mut s.s); + f(&mut s, t).unwrap(); + eof(&mut s.s).unwrap(); unsafe { get_mem_writer(&mut s.s.out) } @@ -2327,44 +2591,52 @@ pub fn next_comment(s: &mut State) -> Option { } } -pub fn print_opt_purity(s: &mut State, opt_purity: Option) { +pub fn print_opt_purity(s: &mut State, + opt_purity: Option) -> io::IoResult<()> { match opt_purity { Some(ast::ImpureFn) => { } Some(purity) => { - word_nbsp(s, purity_to_str(purity)); + if_ok!(word_nbsp(s, purity_to_str(purity))); } None => {} } + Ok(()) } pub fn print_opt_abis_and_extern_if_nondefault(s: &mut State, - opt_abis: Option) { + opt_abis: Option) + -> io::IoResult<()> +{ match opt_abis { Some(abis) if !abis.is_rust() => { - word_nbsp(s, "extern"); - word_nbsp(s, abis.to_str()); + if_ok!(word_nbsp(s, "extern")); + if_ok!(word_nbsp(s, abis.to_str())); } Some(_) | None => {} }; + Ok(()) } -pub fn print_extern_opt_abis(s: &mut State, opt_abis: Option) { +pub fn print_extern_opt_abis(s: &mut State, + opt_abis: Option) -> io::IoResult<()> { match opt_abis { Some(abis) => { - word_nbsp(s, "extern"); - word_nbsp(s, abis.to_str()); + if_ok!(word_nbsp(s, "extern")); + if_ok!(word_nbsp(s, abis.to_str())); } None => {} - }; + } + Ok(()) } -pub fn print_opt_sigil(s: &mut State, opt_sigil: Option) { +pub fn print_opt_sigil(s: &mut State, + opt_sigil: Option) -> io::IoResult<()> { match opt_sigil { - Some(ast::BorrowedSigil) => { word(&mut s.s, "&"); } - Some(ast::OwnedSigil) => { word(&mut s.s, "~"); } - Some(ast::ManagedSigil) => { word(&mut s.s, "@"); } - None => {} - }; + Some(ast::BorrowedSigil) => word(&mut s.s, "&"), + Some(ast::OwnedSigil) => word(&mut s.s, "~"), + Some(ast::ManagedSigil) => word(&mut s.s, "@"), + None => Ok(()) + } } pub fn print_fn_header_info(s: &mut State, @@ -2373,23 +2645,24 @@ pub fn print_fn_header_info(s: &mut State, abis: AbiSet, onceness: ast::Onceness, opt_sigil: Option, - vis: ast::Visibility) { - word(&mut s.s, visibility_qualified(vis, "")); + vis: ast::Visibility) -> io::IoResult<()> { + if_ok!(word(&mut s.s, visibility_qualified(vis, ""))); if abis != AbiSet::Rust() { - word_nbsp(s, "extern"); - word_nbsp(s, abis.to_str()); + if_ok!(word_nbsp(s, "extern")); + if_ok!(word_nbsp(s, abis.to_str())); if opt_purity != Some(ast::ExternFn) { - print_opt_purity(s, opt_purity); + if_ok!(print_opt_purity(s, opt_purity)); } } else { - print_opt_purity(s, opt_purity); + if_ok!(print_opt_purity(s, opt_purity)); } - print_onceness(s, onceness); - word(&mut s.s, "fn"); - print_opt_sigil(s, opt_sigil); + if_ok!(print_onceness(s, onceness)); + if_ok!(word(&mut s.s, "fn")); + if_ok!(print_opt_sigil(s, opt_sigil)); + Ok(()) } pub fn purity_to_str(p: ast::Purity) -> &'static str { @@ -2407,17 +2680,17 @@ pub fn onceness_to_str(o: ast::Onceness) -> &'static str { } } -pub fn print_purity(s: &mut State, p: ast::Purity) { +pub fn print_purity(s: &mut State, p: ast::Purity) -> io::IoResult<()> { match p { - ast::ImpureFn => (), + ast::ImpureFn => Ok(()), _ => word_nbsp(s, purity_to_str(p)) } } -pub fn print_onceness(s: &mut State, o: ast::Onceness) { +pub fn print_onceness(s: &mut State, o: ast::Onceness) -> io::IoResult<()> { match o { - ast::Once => { word_nbsp(s, "once"); } - ast::Many => {} + ast::Once => word_nbsp(s, "once"), + ast::Many => Ok(()) } } -- cgit 1.4.1-3-g733a5 From 2a7c5e0b724d8318a7e7762e483c225e8a7420a1 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Thu, 30 Jan 2014 14:28:44 -0800 Subject: syntax: Remove usage of io_error in tests --- src/libsyntax/ext/expand.rs | 9 ++++----- src/libsyntax/fold.rs | 6 ++++-- src/libsyntax/util/parser_testing.rs | 18 +++++++++--------- 3 files changed, 17 insertions(+), 16 deletions(-) (limited to 'src/libsyntax') diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index d8d98b27793..ae93c235ad2 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -957,14 +957,13 @@ mod test { use ast_util; use codemap; use codemap::Spanned; - use fold; use fold::*; use ext::base::{CrateLoader, MacroCrate}; use parse; use parse::token::{fresh_mark, gensym, intern}; use parse::token; use util::parser_testing::{string_to_crate, string_to_crate_and_sess}; - use util::parser_testing::{string_to_pat, string_to_tts, strs_to_idents}; + use util::parser_testing::{string_to_pat, strs_to_idents}; use visit; use visit::Visitor; @@ -1253,14 +1252,14 @@ mod test { let varref_name = mtwt_resolve(varref.segments[0].identifier); let varref_marks = mtwt_marksof(varref.segments[0].identifier.ctxt, invalid_name); - if (!(varref_name==binding_name)){ + if !(varref_name==binding_name) { println!("uh oh, should match but doesn't:"); println!("varref: {:?}",varref); println!("binding: {:?}", bindings[binding_idx]); ast_util::display_sctable(get_sctable()); } assert_eq!(varref_name,binding_name); - if (bound_ident_check) { + if bound_ident_check { // we're checking bound-identifier=?, and the marks // should be the same, too: assert_eq!(varref_marks,binding_marks.clone()); @@ -1269,7 +1268,7 @@ mod test { let fail = (varref.segments.len() == 1) && (mtwt_resolve(varref.segments[0].identifier) == binding_name); // temp debugging: - if (fail) { + if fail { println!("failure on test {}",test_idx); println!("text of test case: \"{}\"", teststr); println!(""); diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 8f5bbc2cdad..297ec6acf51 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -861,6 +861,7 @@ pub fn noop_fold_stmt(s: &Stmt, folder: &mut T) -> SmallVector<@Stmt> #[cfg(test)] mod test { + use std::io; use ast; use util::parser_testing::{string_to_crate, matches_codepattern}; use parse::token; @@ -868,8 +869,9 @@ mod test { use super::*; // this version doesn't care about getting comments or docstrings in. - fn fake_print_crate(s: &mut pprust::State, crate: &ast::Crate) { - pprust::print_mod(s, &crate.module, crate.attrs); + fn fake_print_crate(s: &mut pprust::State, + crate: &ast::Crate) -> io::IoResult<()> { + pprust::print_mod(s, &crate.module, crate.attrs) } // change every identifier to "zz" diff --git a/src/libsyntax/util/parser_testing.rs b/src/libsyntax/util/parser_testing.rs index 58c2bed7a45..aa22f47221b 100644 --- a/src/libsyntax/util/parser_testing.rs +++ b/src/libsyntax/util/parser_testing.rs @@ -101,30 +101,30 @@ pub fn matches_codepattern(a : &str, b : &str) -> bool { let mut idx_a = 0; let mut idx_b = 0; loop { - if (idx_a == a.len() && idx_b == b.len()) { + if idx_a == a.len() && idx_b == b.len() { return true; } - else if (idx_a == a.len()) {return false;} - else if (idx_b == b.len()) { + else if idx_a == a.len() {return false;} + else if idx_b == b.len() { // maybe the stuff left in a is all ws? - if (is_whitespace(a.char_at(idx_a))) { - return (scan_for_non_ws_or_end(a,idx_a) == a.len()); + if is_whitespace(a.char_at(idx_a)) { + return scan_for_non_ws_or_end(a,idx_a) == a.len(); } else { return false; } } // ws in both given and pattern: - else if (is_whitespace(a.char_at(idx_a)) - && is_whitespace(b.char_at(idx_b))) { + else if is_whitespace(a.char_at(idx_a)) + && is_whitespace(b.char_at(idx_b)) { idx_a = scan_for_non_ws_or_end(a,idx_a); idx_b = scan_for_non_ws_or_end(b,idx_b); } // ws in given only: - else if (is_whitespace(a.char_at(idx_a))) { + else if is_whitespace(a.char_at(idx_a)) { idx_a = scan_for_non_ws_or_end(a,idx_a); } // *don't* silently eat ws in expected only. - else if (a.char_at(idx_a) == b.char_at(idx_b)) { + else if a.char_at(idx_a) == b.char_at(idx_b) { idx_a += 1; idx_b += 1; } -- cgit 1.4.1-3-g733a5 From f9a32cdabc1680b89bd7b579dc1e3f8f18c28257 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Thu, 30 Jan 2014 16:55:20 -0800 Subject: std: Fixing all documentation * Stop referencing io_error * Start changing "Failure" sections to "Error" sections * Update all doc examples to work. --- src/libnative/io/timer_timerfd.rs | 7 +- src/libstd/fmt/mod.rs | 22 ++- src/libstd/io/buffered.rs | 13 +- src/libstd/io/fs.rs | 164 +++++++++------------- src/libstd/io/mem.rs | 12 +- src/libstd/io/mod.rs | 287 ++++++++++++++++++-------------------- src/libstd/io/net/addrinfo.rs | 8 -- src/libstd/io/net/unix.rs | 10 -- src/libstd/io/pipe.rs | 16 +-- src/libstd/io/process.rs | 2 +- src/libstd/io/result.rs | 6 +- src/libstd/io/signal.rs | 15 +- src/libstd/io/stdio.rs | 15 +- src/libstd/os.rs | 6 +- src/libsyntax/print/pprust.rs | 16 +-- 15 files changed, 274 insertions(+), 325 deletions(-) (limited to 'src/libsyntax') diff --git a/src/libnative/io/timer_timerfd.rs b/src/libnative/io/timer_timerfd.rs index ca20314997e..7c22e90bbff 100644 --- a/src/libnative/io/timer_timerfd.rs +++ b/src/libnative/io/timer_timerfd.rs @@ -96,7 +96,7 @@ fn helper(input: libc::c_int, messages: Port) { if fd == input { let mut buf = [0, ..1]; // drain the input file descriptor of its input - FileDesc::new(fd, false).inner_read(buf).unwrap(); + let _ = FileDesc::new(fd, false).inner_read(buf).unwrap(); incoming = true; } else { let mut bits = [0, ..8]; @@ -104,7 +104,7 @@ fn helper(input: libc::c_int, messages: Port) { // // FIXME: should this perform a send() this number of // times? - FileDesc::new(fd, false).inner_read(bits).unwrap(); + let _ = FileDesc::new(fd, false).inner_read(bits).unwrap(); let remove = { match map.find(&fd).expect("fd unregistered") { &(ref c, oneshot) => !c.try_send(()) || oneshot @@ -166,7 +166,8 @@ impl Timer { } pub fn sleep(ms: u64) { - unsafe { libc::usleep((ms * 1000) as libc::c_uint); } + // FIXME: this can fail because of EINTR, what do do? + let _ = unsafe { libc::usleep((ms * 1000) as libc::c_uint) }; } fn remove(&mut self) { diff --git a/src/libstd/fmt/mod.rs b/src/libstd/fmt/mod.rs index e0944dea9b2..0bc567b270a 100644 --- a/src/libstd/fmt/mod.rs +++ b/src/libstd/fmt/mod.rs @@ -163,9 +163,10 @@ method of the signature: ```rust # use std; +# mod fmt { pub type Result = (); } # struct T; # trait SomeName { -fn fmt(value: &T, f: &mut std::fmt::Formatter); +fn fmt(value: &T, f: &mut std::fmt::Formatter) -> fmt::Result; # } ``` @@ -174,7 +175,14 @@ emit output into the `f.buf` stream. It is up to each format trait implementation to correctly adhere to the requested formatting parameters. The values of these parameters will be listed in the fields of the `Formatter` struct. In order to help with this, the `Formatter` struct also provides some -helper methods. An example of implementing the formatting traits would look +helper methods. + +Additionally, the return value of this function is `fmt::Result` which is a +typedef to `Result<(), IoError>` (also known as `IoError<()>`). Formatting +implementations should ensure that they return errors from `write!` correctly +(propagating errors upward). + +An example of implementing the formatting traits would look like: ```rust @@ -187,7 +195,7 @@ struct Vector2D { } impl fmt::Show for Vector2D { - fn fmt(obj: &Vector2D, f: &mut fmt::Formatter) { + fn fmt(obj: &Vector2D, f: &mut fmt::Formatter) -> fmt::Result { // The `f.buf` value is of the type `&mut io::Writer`, which is what th // write! macro is expecting. Note that this formatting ignores the // various flags provided to format strings. @@ -198,7 +206,7 @@ impl fmt::Show for Vector2D { // Different traits allow different forms of output of a type. The meaning of // this format is to print the magnitude of a vector. impl fmt::Binary for Vector2D { - fn fmt(obj: &Vector2D, f: &mut fmt::Formatter) { + fn fmt(obj: &Vector2D, f: &mut fmt::Formatter) -> fmt::Result { let magnitude = (obj.x * obj.x + obj.y * obj.y) as f64; let magnitude = magnitude.sqrt(); @@ -207,7 +215,7 @@ impl fmt::Binary for Vector2D { // for details, and the function `pad` can be used to pad strings. let decimals = f.precision.unwrap_or(3); let string = f64::to_str_exact(magnitude, decimals); - f.pad_integral(string.as_bytes(), "", true); + f.pad_integral(string.as_bytes(), "", true) } } @@ -242,6 +250,7 @@ strings and instead directly write the output. Under the hood, this function is actually invoking the `write` function defined in this module. Example usage is: ```rust +# #[allow(unused_must_use)]; use std::io; let mut w = io::MemWriter::new(); @@ -655,11 +664,12 @@ uniform_fn_call_workaround! { /// # Example /// /// ```rust +/// # #[allow(unused_must_use)]; /// use std::fmt; /// use std::io; /// /// let w = &mut io::stdout() as &mut io::Writer; -/// format_args!(|args| { fmt::write(w, args) }, "Hello, {}!", "world"); +/// format_args!(|args| { fmt::write(w, args); }, "Hello, {}!", "world"); /// ``` pub fn write(output: &mut io::Writer, args: &Arguments) -> Result { unsafe { write_unsafe(output, args.fmt, args.args) } diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index e3bc97b6f28..256f9d325f3 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -31,14 +31,13 @@ use vec; /// ```rust /// use std::io::{BufferedReader, File}; /// -/// # let _g = ::std::io::ignore_io_error(); /// let file = File::open(&Path::new("message.txt")); /// let mut reader = BufferedReader::new(file); /// /// let mut buf = [0, ..100]; /// match reader.read(buf) { -/// Some(nread) => println!("Read {} bytes", nread), -/// None => println!("At the end of the file!") +/// Ok(nread) => println!("Read {} bytes", nread), +/// Err(e) => println!("error reading: {}", e) /// } /// ``` pub struct BufferedReader { @@ -121,9 +120,9 @@ impl Reader for BufferedReader { /// # Example /// /// ```rust +/// # #[allow(unused_must_use)]; /// use std::io::{BufferedWriter, File}; /// -/// # let _g = ::std::io::ignore_io_error(); /// let file = File::open(&Path::new("message.txt")); /// let mut writer = BufferedWriter::new(file); /// @@ -268,9 +267,9 @@ impl Reader for InternalBufferedWriter { /// # Example /// /// ```rust +/// # #[allow(unused_must_use)]; /// use std::io::{BufferedStream, File}; /// -/// # let _g = ::std::io::ignore_io_error(); /// let file = File::open(&Path::new("message.txt")); /// let mut stream = BufferedStream::new(file); /// @@ -279,8 +278,8 @@ impl Reader for InternalBufferedWriter { /// /// let mut buf = [0, ..100]; /// match stream.read(buf) { -/// Some(nread) => println!("Read {} bytes", nread), -/// None => println!("At the end of the stream!") +/// Ok(nread) => println!("Read {} bytes", nread), +/// Err(e) => println!("error reading: {}", e) /// } /// ``` pub struct BufferedStream { diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index 1b669539288..ef1b1a56ec0 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -14,11 +14,11 @@ This module provides a set of functions and traits for working with regular files & directories on a filesystem. At the top-level of the module are a set of freestanding functions, associated -with various filesystem operations. They all operate on a `Path` object. +with various filesystem operations. They all operate on `Path` objects. All operations in this module, including those as part of `File` et al -block the task during execution. Most will raise `std::io::io_error` -conditions in the event of failure. +block the task during execution. In the event of failure, all functions/methods +will return an `IoResult` type with an `Err` value. Also included in this module is an implementation block on the `Path` object defined in `std::path::Path`. The impl adds useful methods about inspecting the @@ -42,7 +42,7 @@ file.write(bytes!("foobar")); let mut file = File::open(&path); file.read_to_end(); -println!("{}", path.stat().size); +println!("{}", path.stat().unwrap().size); # drop(file); fs::unlink(&path); ``` @@ -68,11 +68,12 @@ use vec::{OwnedVector, ImmutableVector}; /// Can be constructed via `File::open()`, `File::create()`, and /// `File::open_mode()`. /// -/// # Errors +/// # Error /// -/// This type will raise an io_error condition if operations are attempted against -/// it for which its underlying file descriptor was not configured at creation -/// time, via the `FileAccess` parameter to `File::open_mode()`. +/// This type will return errors as an `IoResult` if operations are +/// attempted against it for which its underlying file descriptor was not +/// configured at creation time, via the `FileAccess` parameter to +/// `File::open_mode()`. pub struct File { priv fd: ~RtioFileStream, priv path: Path, @@ -85,7 +86,7 @@ impl File { /// /// # Example /// - /// ```rust + /// ```rust,should_fail /// use std::io::{File, Open, ReadWrite}; /// /// let p = Path::new("/some/file/path.txt"); @@ -107,12 +108,12 @@ impl File { /// /// Note that, with this function, a `File` is returned regardless of the /// access-limitations indicated by `FileAccess` (e.g. calling `write` on a - /// `File` opened as `Read` will raise an `io_error` condition at runtime). + /// `File` opened as `Read` will return an error at runtime). /// - /// # Errors + /// # Error /// - /// This function will raise an `io_error` condition under a number of - /// different circumstances, to include but not limited to: + /// This function will return an error under a number of different + /// circumstances, to include but not limited to: /// /// * Opening a file that does not exist with `Read` access. /// * Attempting to open a file with a `FileAccess` that the user lacks @@ -164,7 +165,7 @@ impl File { /// let mut f = File::create(&Path::new("foo.txt")); /// f.write(bytes!("This is a sample file")); /// # drop(f); - /// # ::std::io::fs::unlnk(&Path::new("foo.txt")); + /// # ::std::io::fs::unlink(&Path::new("foo.txt")); /// ``` pub fn create(path: &Path) -> IoResult { File::open_mode(path, Truncate, Write) @@ -178,10 +179,6 @@ impl File { /// Synchronizes all modifications to this file to its permanent storage /// device. This will flush any internal buffers necessary to perform this /// operation. - /// - /// # Errors - /// - /// This function will raise on the `io_error` condition on failure. pub fn fsync(&mut self) -> IoResult<()> { self.fd.fsync() } @@ -190,10 +187,6 @@ impl File { /// file metadata to the filesystem. This is intended for use case which /// must synchronize content, but don't need the metadata on disk. The goal /// of this method is to reduce disk operations. - /// - /// # Errors - /// - /// This function will raise on the `io_error` condition on failure. pub fn datasync(&mut self) -> IoResult<()> { self.fd.datasync() } @@ -206,10 +199,6 @@ impl File { /// be shrunk. If it is greater than the current file's size, then the file /// will be extended to `size` and have all of the intermediate data filled /// in with 0s. - /// - /// # Errors - /// - /// On error, this function will raise on the `io_error` condition. pub fn truncate(&mut self, size: i64) -> IoResult<()> { self.fd.truncate(size) } @@ -239,11 +228,11 @@ impl File { /// guaranteed that a file is immediately deleted (e.g. depending on /// platform, other open file descriptors may prevent immediate removal) /// -/// # Errors +/// # Error /// -/// This function will raise an `io_error` condition if the path points to a -/// directory, the user lacks permissions to remove the file, or if some -/// other filesystem-level error occurs. +/// This function will return an error if the path points to a directory, the +/// user lacks permissions to remove the file, or if some other filesystem-level +/// error occurs. pub fn unlink(path: &Path) -> IoResult<()> { LocalIo::maybe_raise(|io| io.fs_unlink(&path.to_c_str())) } @@ -259,7 +248,6 @@ pub fn unlink(path: &Path) -> IoResult<()> { /// # Example /// /// ```rust -/// use std::io; /// use std::io::fs; /// /// let p = Path::new("/some/file/path.txt"); @@ -269,11 +257,11 @@ pub fn unlink(path: &Path) -> IoResult<()> { /// } /// ``` /// -/// # Errors +/// # Error /// -/// This call will raise an `io_error` condition if the user lacks the -/// requisite permissions to perform a `stat` call on the given path or if -/// there is no entry in the filesystem at the provided path. +/// This call will return an error if the user lacks the requisite permissions +/// to perform a `stat` call on the given path or if there is no entry in the +/// filesystem at the provided path. pub fn stat(path: &Path) -> IoResult { LocalIo::maybe_raise(|io| { io.fs_stat(&path.to_c_str()) @@ -285,7 +273,7 @@ pub fn stat(path: &Path) -> IoResult { /// information about the symlink file instead of the file that it points /// to. /// -/// # Errors +/// # Error /// /// See `stat` pub fn lstat(path: &Path) -> IoResult { @@ -305,11 +293,11 @@ pub fn lstat(path: &Path) -> IoResult { /// fs::rename(&Path::new("foo"), &Path::new("bar")); /// ``` /// -/// # Errors +/// # Error /// -/// Will raise an `io_error` condition if the provided `path` doesn't exist, -/// the process lacks permissions to view the contents, or if some other -/// intermittent I/O error occurs. +/// Will return an error if the provided `path` doesn't exist, the process lacks +/// permissions to view the contents, or if some other intermittent I/O error +/// occurs. pub fn rename(from: &Path, to: &Path) -> IoResult<()> { LocalIo::maybe_raise(|io| io.fs_rename(&from.to_c_str(), &to.to_c_str())) } @@ -329,10 +317,10 @@ pub fn rename(from: &Path, to: &Path) -> IoResult<()> { /// fs::copy(&Path::new("foo.txt"), &Path::new("bar.txt")); /// ``` /// -/// # Errors +/// # Error /// -/// Will raise an `io_error` condition is the following situations, but is -/// not limited to just these cases: +/// Will return an error in the following situations, but is not limited to +/// just these cases: /// /// * The `from` path is not a file /// * The `from` file does not exist @@ -373,7 +361,7 @@ pub fn copy(from: &Path, to: &Path) -> IoResult<()> { /// # Example /// /// ```rust -/// # #[allow(unused_must_use)] +/// # #[allow(unused_must_use)]; /// use std::io; /// use std::io::fs; /// @@ -383,20 +371,16 @@ pub fn copy(from: &Path, to: &Path) -> IoResult<()> { /// fs::chmod(&Path::new("file.exe"), io::UserExec); /// ``` /// -/// # Errors +/// # Error /// -/// If this function encounters an I/O error, it will raise on the `io_error` -/// condition. Some possible error situations are not having the permission to +/// If this function encounters an I/O error, it will return an `Err` value. +/// Some possible error situations are not having the permission to /// change the attributes of a file or the file not existing. pub fn chmod(path: &Path, mode: io::FilePermission) -> IoResult<()> { LocalIo::maybe_raise(|io| io.fs_chmod(&path.to_c_str(), mode)) } /// Change the user and group owners of a file at the specified path. -/// -/// # Errors -/// -/// This function will raise on the `io_error` condition on failure. pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> { LocalIo::maybe_raise(|io| io.fs_chown(&path.to_c_str(), uid, gid)) } @@ -404,31 +388,22 @@ pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> { /// Creates a new hard link on the filesystem. The `dst` path will be a /// link pointing to the `src` path. Note that systems often require these /// two paths to both be located on the same filesystem. -/// -/// # Errors -/// -/// This function will raise on the `io_error` condition on failure. pub fn link(src: &Path, dst: &Path) -> IoResult<()> { LocalIo::maybe_raise(|io| io.fs_link(&src.to_c_str(), &dst.to_c_str())) } /// Creates a new symbolic link on the filesystem. The `dst` path will be a /// symlink pointing to the `src` path. -/// -/// # Errors -/// -/// This function will raise on the `io_error` condition on failure. pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> { LocalIo::maybe_raise(|io| io.fs_symlink(&src.to_c_str(), &dst.to_c_str())) } /// Reads a symlink, returning the file that the symlink points to. /// -/// # Errors +/// # Error /// -/// This function will raise on the `io_error` condition on failure. Failure -/// conditions include reading a file that does not exist or reading a file -/// which is not a symlink. +/// This function will return an error on failure. Failure conditions include +/// reading a file that does not exist or reading a file which is not a symlink. pub fn readlink(path: &Path) -> IoResult { LocalIo::maybe_raise(|io| io.fs_readlink(&path.to_c_str())) } @@ -446,11 +421,10 @@ pub fn readlink(path: &Path) -> IoResult { /// fs::mkdir(&p, io::UserRWX); /// ``` /// -/// # Errors +/// # Error /// -/// This call will raise an `io_error` condition if the user lacks permissions -/// to make a new directory at the provided path, or if the directory already -/// exists. +/// This call will return an error if the user lacks permissions to make a new +/// directory at the provided path, or if the directory already exists. pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> { LocalIo::maybe_raise(|io| io.fs_mkdir(&path.to_c_str(), mode)) } @@ -467,11 +441,10 @@ pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> { /// fs::rmdir(&p); /// ``` /// -/// # Errors +/// # Error /// -/// This call will raise an `io_error` condition if the user lacks permissions -/// to remove the directory at the provided path, or if the directory isn't -/// empty. +/// This call will return an error if the user lacks permissions to remove the +/// directory at the provided path, or if the directory isn't empty. pub fn rmdir(path: &Path) -> IoResult<()> { LocalIo::maybe_raise(|io| io.fs_rmdir(&path.to_c_str())) } @@ -481,26 +454,32 @@ pub fn rmdir(path: &Path) -> IoResult<()> { /// # Example /// /// ```rust +/// use std::io; /// use std::io::fs; /// /// // one possible implementation of fs::walk_dir only visiting files -/// fn visit_dirs(dir: &Path, cb: |&Path|) { +/// fn visit_dirs(dir: &Path, cb: |&Path|) -> io::IoResult<()> { /// if dir.is_dir() { -/// let contents = fs::readdir(dir).unwrap(); +/// let contents = if_ok!(fs::readdir(dir)); /// for entry in contents.iter() { -/// if entry.is_dir() { visit_dirs(entry, cb); } -/// else { cb(entry); } +/// if entry.is_dir() { +/// if_ok!(visit_dirs(entry, |p| cb(p))); +/// } else { +/// cb(entry); +/// } /// } +/// Ok(()) +/// } else { +/// Err(io::standard_error(io::InvalidInput)) /// } -/// else { fail!("nope"); } /// } /// ``` /// -/// # Errors +/// # Error /// -/// Will raise an `io_error` condition if the provided `from` doesn't exist, -/// the process lacks permissions to view the contents or if the `path` points -/// at a non-directory file +/// Will return an error if the provided `from` doesn't exist, the process lacks +/// permissions to view the contents or if the `path` points at a non-directory +/// file pub fn readdir(path: &Path) -> IoResult<~[Path]> { LocalIo::maybe_raise(|io| { io.fs_readdir(&path.to_c_str(), 0) @@ -539,11 +518,10 @@ impl Iterator for Directories { /// Recursively create a directory and all of its parent components if they /// are missing. /// -/// # Errors +/// # Error /// -/// This function will raise on the `io_error` condition if an error -/// happens, see `fs::mkdir` for more information about error conditions -/// and performance. +/// This function will return an `Err` value if an error happens, see +/// `fs::mkdir` for more information about error conditions and performance. pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> { // tjc: if directory exists but with different permissions, // should we return false? @@ -559,11 +537,10 @@ pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> { /// Removes a directory at this path, after removing all its contents. Use /// carefully! /// -/// # Errors +/// # Error /// -/// This function will raise on the `io_error` condition if an error -/// happens. See `file::unlink` and `fs::readdir` for possible error -/// conditions. +/// This function will return an `Err` value if an error happens. See +/// `file::unlink` and `fs::readdir` for possible error conditions. pub fn rmdir_recursive(path: &Path) -> IoResult<()> { let children = if_ok!(readdir(path)); for child in children.iter() { @@ -581,11 +558,6 @@ pub fn rmdir_recursive(path: &Path) -> IoResult<()> { /// The file at the path specified will have its last access time set to /// `atime` and its modification time set to `mtime`. The times specified should /// be in milliseconds. -/// -/// # Errors -/// -/// This function will raise on the `io_error` condition if an error -/// happens. // FIXME(#10301) these arguments should not be u64 pub fn change_file_times(path: &Path, atime: u64, mtime: u64) -> IoResult<()> { LocalIo::maybe_raise(|io| io.fs_utime(&path.to_c_str(), atime, mtime)) @@ -639,7 +611,7 @@ impl path::Path { /// filesystem. This will return true if the path points to either a /// directory or a file. /// - /// # Errors + /// # Error /// /// Will not raise a condition pub fn exists(&self) -> bool { @@ -651,7 +623,7 @@ impl path::Path { /// to non-existent locations or directories or other non-regular files /// (named pipes, etc). /// - /// # Errors + /// # Error /// /// Will not raise a condition pub fn is_file(&self) -> bool { @@ -666,7 +638,7 @@ impl path::Path { /// Will return false for paths to non-existent locations or if the item is /// not a directory (eg files, named pipes, links, etc) /// - /// # Errors + /// # Error /// /// Will not raise a condition pub fn is_dir(&self) -> bool { diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index 3a6aa1939a4..395ece17ede 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -25,6 +25,7 @@ use vec::{Vector, ImmutableVector, MutableVector, OwnedCloneableVector}; /// # Example /// /// ```rust +/// # #[allow(unused_must_use)]; /// use std::io::MemWriter; /// /// let mut w = MemWriter::new(); @@ -113,11 +114,12 @@ impl Seek for MemWriter { /// # Example /// /// ```rust +/// # #[allow(unused_must_use)]; /// use std::io::MemReader; /// /// let mut r = MemReader::new(~[0, 1, 2]); /// -/// assert_eq!(r.read_to_end(), ~[0, 1, 2]); +/// assert_eq!(r.read_to_end().unwrap(), ~[0, 1, 2]); /// ``` pub struct MemReader { priv buf: ~[u8], @@ -182,12 +184,13 @@ impl Buffer for MemReader { /// Writes to a fixed-size byte slice /// -/// If a write will not fit in the buffer, it raises the `io_error` -/// condition and does not write any data. +/// If a write will not fit in the buffer, it returns an error and does not +/// write any data. /// /// # Example /// /// ```rust +/// # #[allow(unused_must_use)]; /// use std::io::BufWriter; /// /// let mut buf = [0, ..4]; @@ -252,12 +255,13 @@ impl<'a> Seek for BufWriter<'a> { /// # Example /// /// ```rust +/// # #[allow(unused_must_use)]; /// use std::io::BufReader; /// /// let mut buf = [0, 1, 2, 3]; /// let mut r = BufReader::new(buf); /// -/// assert_eq!(r.read_to_end(), ~[0, 1, 2, 3]); +/// assert_eq!(r.read_to_end().unwrap(), ~[0, 1, 2, 3]); /// ``` pub struct BufReader<'a> { priv buf: &'a [u8], diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index bd7a349a2aa..58a35e96393 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -29,7 +29,6 @@ Some examples of obvious things you might want to do use std::io::BufferedReader; use std::io::stdin; - # let _g = ::std::io::ignore_io_error(); let mut stdin = BufferedReader::new(stdin()); for line in stdin.lines() { print!("{}", line); @@ -41,7 +40,6 @@ Some examples of obvious things you might want to do ```rust use std::io::File; - # let _g = ::std::io::ignore_io_error(); let contents = File::open(&Path::new("message.txt")).read_to_end(); ``` @@ -50,7 +48,6 @@ Some examples of obvious things you might want to do ```rust use std::io::File; - # let _g = ::std::io::ignore_io_error(); let mut file = File::create(&Path::new("message.txt")); file.write(bytes!("hello, file!\n")); # drop(file); @@ -63,7 +60,6 @@ Some examples of obvious things you might want to do use std::io::BufferedReader; use std::io::File; - # let _g = ::std::io::ignore_io_error(); let path = Path::new("message.txt"); let mut file = BufferedReader::new(File::open(&path)); for line in file.lines() { @@ -77,7 +73,6 @@ Some examples of obvious things you might want to do use std::io::BufferedReader; use std::io::File; - # let _g = ::std::io::ignore_io_error(); let path = Path::new("message.txt"); let mut file = BufferedReader::new(File::open(&path)); let lines: ~[~str] = file.lines().collect(); @@ -91,7 +86,6 @@ Some examples of obvious things you might want to do use std::io::net::ip::SocketAddr; use std::io::net::tcp::TcpStream; - # let _g = ::std::io::ignore_io_error(); let addr = from_str::("127.0.0.1:8080").unwrap(); let mut socket = TcpStream::connect(addr).unwrap(); socket.write(bytes!("GET / HTTP/1.0\n\n")); @@ -168,72 +162,50 @@ asynchronous request completes. # Error Handling I/O is an area where nearly every operation can result in unexpected -errors. It should allow errors to be handled efficiently. -It needs to be convenient to use I/O when you don't care -about dealing with specific errors. +errors. Errors should be painfully visible when they happen, and handling them +should be easy to work with. It should be convenient to handle specific I/O +errors, and it should also be convenient to not deal with I/O errors. Rust's I/O employs a combination of techniques to reduce boilerplate while still providing feedback about errors. The basic strategy: -* Errors are fatal by default, resulting in task failure -* Errors raise the `io_error` condition which provides an opportunity to inspect - an IoError object containing details. -* Return values must have a sensible null or zero value which is returned - if a condition is handled successfully. This may be an `Option`, an empty - vector, or other designated error value. -* Common traits are implemented for `Option`, e.g. `impl Reader for Option`, - so that nullable values do not have to be 'unwrapped' before use. +* All I/O operations return `IoResult` which is equivalent to + `Result`. The core `Result` type is defined in the `std::result` + module. +* If the `Result` type goes unused, then the compiler will by default emit a + warning about the unused result. +* Common traits are implemented for `IoResult`, e.g. + `impl Reader for IoResult`, so that error values do not have + to be 'unwrapped' before use. These features combine in the API to allow for expressions like `File::create(&Path::new("diary.txt")).write(bytes!("Met a girl.\n"))` without having to worry about whether "diary.txt" exists or whether the write succeeds. As written, if either `new` or `write_line` -encounters an error the task will fail. +encounters an error then the result of the entire expression will +be an error. If you wanted to handle the error though you might write: ```rust use std::io::File; -use std::io::{IoError, io_error}; -let mut error = None; -io_error::cond.trap(|e: IoError| { - error = Some(e); -}).inside(|| { - File::create(&Path::new("diary.txt")).write(bytes!("Met a girl.\n")); -}); - -if error.is_some() { - println!("failed to write my diary"); +match File::create(&Path::new("diary.txt")).write(bytes!("Met a girl.\n")) { + Ok(()) => { /* succeeded */ } + Err(e) => println!("failed to write to my diary: {}", e), } + # ::std::io::fs::unlink(&Path::new("diary.txt")); ``` -FIXME: Need better condition handling syntax - -In this case the condition handler will have the opportunity to -inspect the IoError raised by either the call to `new` or the call to -`write_line`, but then execution will continue. - -So what actually happens if `new` encounters an error? To understand -that it's important to know that what `new` returns is not a `File` -but an `Option`. If the file does not open, and the condition -is handled, then `new` will simply return `None`. Because there is an -implementation of `Writer` (the trait required ultimately required for -types to implement `write_line`) there is no need to inspect or unwrap -the `Option` and we simply call `write_line` on it. If `new` -returned a `None` then the followup call to `write_line` will also -raise an error. - -## Concerns about this strategy - -This structure will encourage a programming style that is prone -to errors similar to null pointer dereferences. -In particular code written to ignore errors and expect conditions to be unhandled -will start passing around null or zero objects when wrapped in a condition handler. - -* FIXME: How should we use condition handlers that return values? -* FIXME: Should EOF raise default conditions when EOF is not an error? +So what actually happens if `create` encounters an error? +It's important to know that what `new` returns is not a `File` +but an `IoResult`. If the file does not open, then `new` will simply +return `Err(..)`. Because there is an implementation of `Writer` (the trait +required ultimately required for types to implement `write_line`) there is no +need to inspect or unwrap the `IoResult` and we simply call `write_line` +on it. If `new` returned an `Err(..)` then the followup call to `write_line` +will also return an error. # Issues with i/o scheduler affinity, work stealing, task pinning @@ -460,40 +432,23 @@ impl ToStr for IoErrorKind { pub trait Reader { - // Only two methods which need to get implemented for this trait + // Only method which need to get implemented for this trait /// Read bytes, up to the length of `buf` and place them in `buf`. /// Returns the number of bytes read. The number of bytes read my - /// be less than the number requested, even 0. Returns `None` on EOF. - /// - /// # Failure + /// be less than the number requested, even 0. Returns `Err` on EOF. /// - /// Raises the `io_error` condition on error. If the condition - /// is handled then no guarantee is made about the number of bytes - /// read and the contents of `buf`. If the condition is handled - /// returns `None` (FIXME see below). + /// # Error /// - /// # FIXME - /// - /// * Should raise_default error on eof? - /// * If the condition is handled it should still return the bytes read, - /// in which case there's no need to return Option - but then you *have* - /// to install a handler to detect eof. - /// - /// This doesn't take a `len` argument like the old `read`. - /// Will people often need to slice their vectors to call this - /// and will that be annoying? - /// Is it actually possible for 0 bytes to be read successfully? + /// If an error occurs during this I/O operation, then it is returned as + /// `Err(IoError)`. Note that end-of-file is considered an error, and can be + /// inspected for in the error's `kind` field. Also note that reading 0 + /// bytes is not considered an error in all circumstances fn read(&mut self, buf: &mut [u8]) -> IoResult; // Convenient helper methods based on the above methods - /// Reads a single byte. Returns `None` on EOF. - /// - /// # Failure - /// - /// Raises the same conditions as the `read` method. Returns - /// `None` if the condition is handled. + /// Reads a single byte. Returns `Err` on EOF. fn read_byte(&mut self) -> IoResult { let mut buf = [0]; loop { @@ -511,13 +466,9 @@ pub trait Reader { /// Reads `len` bytes and appends them to a vector. /// /// May push fewer than the requested number of bytes on error - /// or EOF. Returns true on success, false on EOF or error. - /// - /// # Failure - /// - /// Raises the same conditions as `read`. Additionally raises `io_error` - /// on EOF. If `io_error` is handled then `push_bytes` may push less - /// than the requested number of bytes. + /// or EOF. If `Ok(())` is returned, then all of the requested bytes were + /// pushed on to the vector, otherwise the amount `len` bytes couldn't be + /// read (an error was encountered), and the error is returned. fn push_bytes(&mut self, buf: &mut ~[u8], len: uint) -> IoResult<()> { let start_len = buf.len(); let mut total_read = 0; @@ -542,29 +493,36 @@ pub trait Reader { /// Reads `len` bytes and gives you back a new vector of length `len` /// - /// # Failure + /// # Error /// - /// Raises the same conditions as `read`. Additionally raises `io_error` - /// on EOF. If `io_error` is handled then the returned vector may - /// contain less than the requested number of bytes. + /// Fails with the same conditions as `read`. Additionally returns error on + /// on EOF. Note that if an error is returned, then some number of bytes may + /// have already been consumed from the underlying reader, and they are lost + /// (not returned as part of the error). If this is unacceptable, then it is + /// recommended to use the `push_bytes` or `read` methods. fn read_bytes(&mut self, len: uint) -> IoResult<~[u8]> { let mut buf = vec::with_capacity(len); - if_ok!(self.push_bytes(&mut buf, len)); - return Ok(buf); + match self.push_bytes(&mut buf, len) { + Ok(()) => Ok(buf), + Err(e) => Err(e), + } } /// Reads all remaining bytes from the stream. /// - /// # Failure + /// # Error + /// + /// Returns any non-EOF error immediately. Previously read bytes are + /// discarded when an error is returned. /// - /// Raises the same conditions as the `read` method except for - /// `EndOfFile` which is swallowed. + /// When EOF is encountered, all bytes read up to that point are returned, + /// but if 0 bytes have been read then the EOF error is returned. fn read_to_end(&mut self) -> IoResult<~[u8]> { let mut buf = vec::with_capacity(DEFAULT_BUF_SIZE); loop { match self.push_bytes(&mut buf, DEFAULT_BUF_SIZE) { Ok(()) => {} - Err(ref e) if e.kind == EndOfFile => break, + Err(ref e) if buf.len() > 0 && e.kind == EndOfFile => break, Err(e) => return Err(e) } } @@ -574,10 +532,11 @@ pub trait Reader { /// Reads all of the remaining bytes of this stream, interpreting them as a /// UTF-8 encoded stream. The corresponding string is returned. /// - /// # Failure + /// # Error /// - /// This function will raise all the same conditions as the `read` method, - /// along with raising a condition if the input is not valid UTF-8. + /// This function returns all of the same errors as `read_to_end` with an + /// additional error if the reader's contents are not a valid sequence of + /// UTF-8 bytes. fn read_to_str(&mut self) -> IoResult<~str> { self.read_to_end().and_then(|s| { match str::from_utf8_owned(s) { @@ -590,11 +549,12 @@ pub trait Reader { /// Create an iterator that reads a single byte on /// each iteration, until EOF. /// - /// # Failure + /// # Error /// - /// Raises the same conditions as the `read` method, for - /// each call to its `.next()` method. - /// Ends the iteration if the condition is handled. + /// The iterator protocol causes all specifics about errors encountered to + /// be swallowed. All errors will be signified by returning `None` from the + /// iterator. If this is undesirable, it is recommended to use the + /// `read_byte` method. fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, Self> { extensions::Bytes::new(self) } @@ -825,11 +785,14 @@ fn extend_sign(val: u64, nbytes: uint) -> i64 { } pub trait Writer { - /// Write the given buffer + /// Write the entirety of a given buffer /// - /// # Failure + /// # Errors /// - /// Raises the `io_error` condition on error + /// If an error happens during the I/O operation, the error is returned as + /// `Err`. Note that it is considered an error if the entire buffer could + /// not be written, and if an error is returned then it is unknown how much + /// data (if any) was actually written. fn write(&mut self, buf: &[u8]) -> IoResult<()>; /// Flush this output stream, ensuring that all intermediately buffered @@ -1021,11 +984,11 @@ impl Stream for T {} /// an iteration, but continue to yield elements if iteration /// is attempted again. /// -/// # Failure +/// # Error /// -/// Raises the same conditions as the `read` method except for `EndOfFile` -/// which is swallowed. -/// Iteration yields `None` if the condition is handled. +/// This iterator will swallow all I/O errors, transforming `Err` values to +/// `None`. If errors need to be handled, it is recommended to use the +/// `read_line` method directly. pub struct Lines<'r, T> { priv buffer: &'r mut T, } @@ -1049,10 +1012,11 @@ pub trait Buffer: Reader { /// consumed from this buffer returned to ensure that the bytes are never /// returned twice. /// - /// # Failure + /// # Error /// - /// This function will raise on the `io_error` condition if a read error is - /// encountered. + /// This function will return an I/O error if the underlying reader was + /// read, but returned an error. Note that it is not an error to return a + /// 0-length buffer. fn fill<'a>(&'a mut self) -> IoResult<&'a [u8]>; /// Tells this buffer that `amt` bytes have been consumed from the buffer, @@ -1067,50 +1031,73 @@ pub trait Buffer: Reader { /// /// ```rust /// use std::io::{BufferedReader, stdin}; - /// # let _g = ::std::io::ignore_io_error(); /// /// let mut reader = BufferedReader::new(stdin()); /// - /// let input = reader.read_line().unwrap_or(~"nothing"); + /// let input = reader.read_line().ok().unwrap_or(~"nothing"); /// ``` /// - /// # Failure + /// # Error + /// + /// This function has the same error semantics as `read_until`: + /// + /// * All non-EOF errors will be returned immediately + /// * If an error is returned previously consumed bytes are lost + /// * EOF is only returned if no bytes have been read + /// * Reach EOF may mean that the delimiter is not present in the return + /// value /// - /// This function will raise on the `io_error` condition (except for - /// `EndOfFile` which is swallowed) if a read error is encountered. - /// The task will also fail if sequence of bytes leading up to - /// the newline character are not valid UTF-8. + /// Additionally, this function can fail if the line of input read is not a + /// valid UTF-8 sequence of bytes. fn read_line(&mut self) -> IoResult<~str> { - self.read_until('\n' as u8).map(|line| str::from_utf8_owned(line).unwrap()) + self.read_until('\n' as u8).and_then(|line| + match str::from_utf8_owned(line) { + Some(s) => Ok(s), + None => Err(standard_error(InvalidInput)), + } + ) } /// Create an iterator that reads a line on each iteration until EOF. /// - /// # Failure + /// # Error /// - /// Iterator raises the same conditions as the `read` method - /// except for `EndOfFile`. + /// This iterator will transform all error values to `None`, discarding the + /// cause of the error. If this is undesirable, it is recommended to call + /// `read_line` directly. fn lines<'r>(&'r mut self) -> Lines<'r, Self> { - Lines { - buffer: self, - } + Lines { buffer: self } } /// Reads a sequence of bytes leading up to a specified delimiter. Once the /// specified byte is encountered, reading ceases and the bytes up to and /// including the delimiter are returned. /// - /// # Failure + /// # Error /// - /// This function will raise on the `io_error` condition if a read error is - /// encountered, except that `EndOfFile` is swallowed. + /// If any I/O error is encountered other than EOF, the error is immediately + /// returned. Note that this may discard bytes which have already been read, + /// and those bytes will *not* be returned. It is recommended to use other + /// methods if this case is worrying. + /// + /// If EOF is encountered, then this function will return EOF if 0 bytes + /// have been read, otherwise the pending byte buffer is returned. This + /// is the reason that the byte buffer returned may not always contain the + /// delimiter. fn read_until(&mut self, byte: u8) -> IoResult<~[u8]> { let mut res = ~[]; let mut used; loop { { - let available = if_ok!(self.fill()); + let available = match self.fill() { + Ok(n) => n, + Err(ref e) if res.len() > 0 && e.kind == EndOfFile => { + used = 0; + break + } + Err(e) => return Err(e) + }; match available.iter().position(|&b| b == byte) { Some(i) => { res.push_all(available.slice_to(i + 1)); @@ -1131,13 +1118,11 @@ pub trait Buffer: Reader { /// Reads the next utf8-encoded character from the underlying stream. /// - /// This will return `None` if the following sequence of bytes in the - /// stream are not a valid utf8-sequence, or if an I/O error is encountered. + /// # Error /// - /// # Failure - /// - /// This function will raise on the `io_error` condition if a read error is - /// encountered. + /// If an I/O error occurs, or EOF, then this function will return `Err`. + /// This function will also return error if the stream does not contain a + /// valid utf-8 encoded codepoint as the next few bytes in the stream. fn read_char(&mut self) -> IoResult { let first_byte = if_ok!(self.read_byte()); let width = str::utf8_char_width(first_byte); @@ -1186,15 +1171,17 @@ pub trait Seek { fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()>; } -/// A listener is a value that can consume itself to start listening for connections. +/// A listener is a value that can consume itself to start listening for +/// connections. +/// /// Doing so produces some sort of Acceptor. pub trait Listener> { /// Spin up the listener and start queuing incoming connections /// - /// # Failure + /// # Error /// - /// Raises `io_error` condition. If the condition is handled, - /// then `listen` returns `None`. + /// Returns `Err` if this listener could not be bound to listen for + /// connections. In all cases, this listener is consumed. fn listen(self) -> IoResult; } @@ -1202,12 +1189,14 @@ pub trait Listener> { pub trait Acceptor { /// Wait for and accept an incoming connection /// - /// # Failure - /// Raise `io_error` condition. If the condition is handled, - /// then `accept` returns `None`. + /// # Error + /// + /// Returns `Err` if an I/O error is encountered. fn accept(&mut self) -> IoResult; - /// Create an iterator over incoming connection attempts + /// Create an iterator over incoming connection attempts. + /// + /// Note that I/O errors will be yielded by the iterator itself. fn incoming<'r>(&'r mut self) -> IncomingConnections<'r, Self> { IncomingConnections { inc: self } } @@ -1216,10 +1205,10 @@ pub trait Acceptor { /// An infinite iterator over incoming connection attempts. /// Calling `next` will block the task until a connection is attempted. /// -/// Since connection attempts can continue forever, this iterator always returns Some. -/// The Some contains another Option representing whether the connection attempt was succesful. -/// A successful connection will be wrapped in Some. -/// A failed connection is represented as a None and raises a condition. +/// Since connection attempts can continue forever, this iterator always returns +/// `Some`. The `Some` contains the `IoResult` representing whether the +/// connection attempt was succesful. A successful connection will be wrapped +/// in `Ok`. A failed connection is represented as an `Err`. pub struct IncomingConnections<'a, A> { priv inc: &'a mut A, } @@ -1265,7 +1254,7 @@ pub enum FileMode { } /// Access permissions with which the file should be opened. `File`s -/// opened with `Read` will raise an `io_error` condition if written to. +/// opened with `Read` will return an error if written to. pub enum FileAccess { Read, Write, diff --git a/src/libstd/io/net/addrinfo.rs b/src/libstd/io/net/addrinfo.rs index f72c6aecd64..e9ffe97f1c3 100644 --- a/src/libstd/io/net/addrinfo.rs +++ b/src/libstd/io/net/addrinfo.rs @@ -70,10 +70,6 @@ pub struct Info { /// Easy name resolution. Given a hostname, returns the list of IP addresses for /// that hostname. -/// -/// # Failure -/// -/// On failure, this will raise on the `io_error` condition. pub fn get_host_addresses(host: &str) -> IoResult<~[IpAddr]> { lookup(Some(host), None, None).map(|a| a.map(|i| i.address.ip)) } @@ -88,10 +84,6 @@ pub fn get_host_addresses(host: &str) -> IoResult<~[IpAddr]> { /// * hint - see the hint structure, and "man -s 3 getaddrinfo", for how this /// controls lookup /// -/// # Failure -/// -/// On failure, this will raise on the `io_error` condition. -/// /// FIXME: this is not public because the `Hint` structure is not ready for public /// consumption just yet. fn lookup(hostname: Option<&str>, servname: Option<&str>, hint: Option) diff --git a/src/libstd/io/net/unix.rs b/src/libstd/io/net/unix.rs index 63a2ba3d095..ce95b987663 100644 --- a/src/libstd/io/net/unix.rs +++ b/src/libstd/io/net/unix.rs @@ -45,11 +45,6 @@ impl UnixStream { /// /// The returned stream will be closed when the object falls out of scope. /// - /// # Failure - /// - /// This function will raise on the `io_error` condition if the connection - /// could not be made. - /// /// # Example /// /// ```rust @@ -86,11 +81,6 @@ impl UnixListener { /// /// This listener will be closed when it falls out of scope. /// - /// # Failure - /// - /// This function will raise on the `io_error` condition if the specified - /// path could not be bound. - /// /// # Example /// /// ``` diff --git a/src/libstd/io/pipe.rs b/src/libstd/io/pipe.rs index 75791164b89..ca85707149b 100644 --- a/src/libstd/io/pipe.rs +++ b/src/libstd/io/pipe.rs @@ -32,16 +32,14 @@ impl PipeStream { /// /// # Example /// - /// use std::libc; - /// use std::io::pipe; + /// ```rust + /// # #[allow(unused_must_use)]; + /// use std::libc; + /// use std::io::pipe::PipeStream; /// - /// let mut pipe = PipeStream::open(libc::STDERR_FILENO); - /// pipe.write(bytes!("Hello, stderr!")); - /// - /// # Failure - /// - /// If the pipe cannot be created, an error will be raised on the - /// `io_error` condition. + /// let mut pipe = PipeStream::open(libc::STDERR_FILENO); + /// pipe.write(bytes!("Hello, stderr!")); + /// ``` pub fn open(fd: libc::c_int) -> IoResult { LocalIo::maybe_raise(|io| { io.pipe_open(fd).map(|obj| PipeStream { obj: obj }) diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 87d47868d0a..ccf3d4582de 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -141,7 +141,7 @@ impl Process { /// Note that this is purely a wrapper around libuv's `uv_process_kill` /// function. /// - /// If the signal delivery fails, then the `io_error` condition is raised on + /// If the signal delivery fails, the corresponding error is returned. pub fn signal(&mut self, signal: int) -> IoResult<()> { self.handle.kill(signal) } diff --git a/src/libstd/io/result.rs b/src/libstd/io/result.rs index aa33ecb19e5..8e03cffd0fb 100644 --- a/src/libstd/io/result.rs +++ b/src/libstd/io/result.rs @@ -8,11 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Implementations of I/O traits for the Option type +//! Implementations of I/O traits for the IoResult type //! //! I/O constructors return option types to allow errors to be handled. -//! These implementations allow e.g. `Option` to be used -//! as a `Reader` without unwrapping the option first. +//! These implementations allow e.g. `IoResult` to be used +//! as a `Reader` without unwrapping the result first. use clone::Clone; use result::{Ok, Err}; diff --git a/src/libstd/io/signal.rs b/src/libstd/io/signal.rs index 8096bfeddfd..92b86afe24d 100644 --- a/src/libstd/io/signal.rs +++ b/src/libstd/io/signal.rs @@ -113,11 +113,10 @@ impl Listener { /// a signal, and a later call to `recv` will return the signal that was /// received while no task was waiting on it. /// - /// # Failure + /// # Error /// /// If this function fails to register a signal handler, then an error will - /// be raised on the `io_error` condition and the function will return - /// false. + /// be returned. pub fn register(&mut self, signum: Signum) -> io::IoResult<()> { if self.handles.contains_key(&signum) { return Ok(()); // self is already listening to signum, so succeed @@ -206,13 +205,11 @@ mod test { use super::User1; let mut s = Listener::new(); let mut called = false; - io::io_error::cond.trap(|_| { - called = true; - }).inside(|| { - if s.register(User1) { + match s.register(User1) { + Ok(..) => { fail!("Unexpected successful registry of signum {:?}", User1); } - }); - assert!(called); + Err(..) => {} + } } } diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 702ecfb6031..937ad0783e9 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -18,6 +18,7 @@ about the stream or terminal that it is attached to. # Example ```rust +# #[allow(unused_must_use)]; use std::io; let mut out = io::stdout(); @@ -283,12 +284,12 @@ impl StdWriter { /// when the writer is attached to something like a terminal, this is used /// to fetch the dimensions of the terminal. /// - /// If successful, returns Some((width, height)). + /// If successful, returns `Ok((width, height))`. /// - /// # Failure + /// # Error /// - /// This function will raise on the `io_error` condition if an error - /// happens. + /// This function will return an error if the output stream is not actually + /// connected to a TTY instance, or if querying the TTY instance fails. pub fn winsize(&mut self) -> IoResult<(int, int)> { match self.inner { TTY(ref mut tty) => tty.get_winsize(), @@ -305,10 +306,10 @@ impl StdWriter { /// Controls whether this output stream is a "raw stream" or simply a normal /// stream. /// - /// # Failure + /// # Error /// - /// This function will raise on the `io_error` condition if an error - /// happens. + /// This function will return an error if the output stream is not actually + /// connected to a TTY instance, or if querying the TTY instance fails. pub fn set_raw(&mut self, raw: bool) -> IoResult<()> { match self.inner { TTY(ref mut tty) => tty.set_raw(raw), diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 2457917d2e4..8815f88d694 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -372,9 +372,9 @@ pub fn self_exe_name() -> Option { fn load_self() -> Option<~[u8]> { use std::io; - match io::result(|| io::fs::readlink(&Path::new("/proc/self/exe"))) { - Ok(Some(path)) => Some(path.as_vec().to_owned()), - Ok(None) | Err(..) => None + match io::fs::readlink(&Path::new("/proc/self/exe")) { + Ok(path) => Some(path.as_vec().to_owned()), + Err(..) => None } } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 17b0b7b9c38..f0ef5014ca8 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -2059,21 +2059,17 @@ pub fn print_generics(s: &mut State, } else { let idx = idx - generics.lifetimes.len(); let param = generics.ty_params.get(idx); -<<<<<<< HEAD - print_ident(s, param.ident); - print_bounds(s, ¶m.bounds, false); + if_ok!(print_ident(s, param.ident)); + if_ok!(print_bounds(s, ¶m.bounds, false)); match param.default { Some(default) => { - space(&mut s.s); - word_space(s, "="); - print_type(s, default); + if_ok!(space(&mut s.s)); + if_ok!(word_space(s, "=")); + if_ok!(print_type(s, default)); } _ => {} } -======= - if_ok!(print_ident(s, param.ident)); - print_bounds(s, ¶m.bounds, false) ->>>>>>> syntax: Remove io_error usage + Ok(()) } } -- cgit 1.4.1-3-g733a5 From c765a8e7ad314651b92ff860cda0159c79dbec6e Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sat, 1 Feb 2014 11:24:42 -0800 Subject: Fixing remaining warnings and errors throughout --- src/doc/guide-conditions.md | 35 ++--- src/etc/combine-tests.py | 1 + src/libnative/io/file.rs | 8 +- src/libnative/io/process.rs | 25 ++- src/libnative/io/timer_helper.rs | 4 +- src/libnative/io/timer_win32.rs | 12 +- src/librustc/lib.rs | 4 +- src/librustc/metadata/decoder.rs | 12 +- src/librustdoc/html/format.rs | 1 - src/librustdoc/html/render.rs | 4 +- src/libstd/fmt/mod.rs | 27 ++-- src/libstd/io/mod.rs | 10 +- src/libstd/io/net/tcp.rs | 14 +- src/libstd/io/signal.rs | 1 + src/libstd/os.rs | 1 + src/libstd/path/mod.rs | 2 +- src/libsyntax/parse/token.rs | 4 +- src/libsyntax/print/pp.rs | 67 +++++--- src/libsyntax/print/pprust.rs | 218 +++++++------------------- src/libterm/lib.rs | 6 + src/test/bench/shootout-mandelbrot.rs | 3 +- src/test/bench/shootout-reverse-complement.rs | 3 +- 22 files changed, 185 insertions(+), 277 deletions(-) (limited to 'src/libsyntax') diff --git a/src/doc/guide-conditions.md b/src/doc/guide-conditions.md index d97de779902..5b7494c0618 100644 --- a/src/doc/guide-conditions.md +++ b/src/doc/guide-conditions.md @@ -47,7 +47,7 @@ An example program that does this task reads like this: # #[allow(unused_imports)]; use std::io::{BufferedReader, File}; # mod BufferedReader { -# use std::io::File; +# use std::io::{File, IoResult}; # use std::io::MemReader; # use std::io::BufferedReader; # static s : &'static [u8] = bytes!("1 2\n\ @@ -55,7 +55,7 @@ use std::io::{BufferedReader, File}; # 789 123\n\ # 45 67\n\ # "); -# pub fn new(_inner: Option) -> BufferedReader { +# pub fn new(_inner: IoResult) -> BufferedReader { # BufferedReader::new(MemReader::new(s.to_owned())) # } # } @@ -71,7 +71,6 @@ fn read_int_pairs() -> ~[(int,int)] { let mut pairs = ~[]; // Path takes a generic by-value, rather than by reference -# let _g = std::io::ignore_io_error(); let path = Path::new(&"foo.txt"); let mut reader = BufferedReader::new(File::open(&path)); @@ -245,7 +244,7 @@ and trapping its exit status using `task::try`: use std::io::{BufferedReader, File}; use std::task; # mod BufferedReader { -# use std::io::File; +# use std::io::{File, IoResult}; # use std::io::MemReader; # use std::io::BufferedReader; # static s : &'static [u8] = bytes!("1 2\n\ @@ -253,7 +252,7 @@ use std::task; # 789 123\n\ # 45 67\n\ # "); -# pub fn new(_inner: Option) -> BufferedReader { +# pub fn new(_inner: IoResult) -> BufferedReader { # BufferedReader::new(MemReader::new(s.to_owned())) # } # } @@ -277,7 +276,6 @@ fn main() { fn read_int_pairs() -> ~[(int,int)] { let mut pairs = ~[]; -# let _g = std::io::ignore_io_error(); let path = Path::new(&"foo.txt"); let mut reader = BufferedReader::new(File::open(&path)); @@ -347,7 +345,7 @@ but similarly clear as the version that used `fail!` in the logic where the erro # #[allow(unused_imports)]; use std::io::{BufferedReader, File}; # mod BufferedReader { -# use std::io::File; +# use std::io::{File, IoResult}; # use std::io::MemReader; # use std::io::BufferedReader; # static s : &'static [u8] = bytes!("1 2\n\ @@ -355,7 +353,7 @@ use std::io::{BufferedReader, File}; # 789 123\n\ # 45 67\n\ # "); -# pub fn new(_inner: Option) -> BufferedReader { +# pub fn new(_inner: IoResult) -> BufferedReader { # BufferedReader::new(MemReader::new(s.to_owned())) # } # } @@ -374,7 +372,6 @@ fn main() { fn read_int_pairs() -> ~[(int,int)] { let mut pairs = ~[]; -# let _g = std::io::ignore_io_error(); let path = Path::new(&"foo.txt"); let mut reader = BufferedReader::new(File::open(&path)); @@ -415,7 +412,7 @@ and replaces bad input lines with the pair `(-1,-1)`: # #[allow(unused_imports)]; use std::io::{BufferedReader, File}; # mod BufferedReader { -# use std::io::File; +# use std::io::{File, IoResult}; # use std::io::MemReader; # use std::io::BufferedReader; # static s : &'static [u8] = bytes!("1 2\n\ @@ -423,7 +420,7 @@ use std::io::{BufferedReader, File}; # 789 123\n\ # 45 67\n\ # "); -# pub fn new(_inner: Option) -> BufferedReader { +# pub fn new(_inner: IoResult) -> BufferedReader { # BufferedReader::new(MemReader::new(s.to_owned())) # } # } @@ -447,7 +444,6 @@ fn main() { fn read_int_pairs() -> ~[(int,int)] { let mut pairs = ~[]; -# let _g = std::io::ignore_io_error(); let path = Path::new(&"foo.txt"); let mut reader = BufferedReader::new(File::open(&path)); @@ -489,7 +485,7 @@ Changing the condition's return type from `(int,int)` to `Option<(int,int)>` wil # #[allow(unused_imports)]; use std::io::{BufferedReader, File}; # mod BufferedReader { -# use std::io::File; +# use std::io::{IoResult, File}; # use std::io::MemReader; # use std::io::BufferedReader; # static s : &'static [u8] = bytes!("1 2\n\ @@ -497,7 +493,7 @@ use std::io::{BufferedReader, File}; # 789 123\n\ # 45 67\n\ # "); -# pub fn new(_inner: Option) -> BufferedReader { +# pub fn new(_inner: IoResult) -> BufferedReader { # BufferedReader::new(MemReader::new(s.to_owned())) # } # } @@ -522,7 +518,6 @@ fn main() { fn read_int_pairs() -> ~[(int,int)] { let mut pairs = ~[]; -# let _g = std::io::ignore_io_error(); let path = Path::new(&"foo.txt"); let mut reader = BufferedReader::new(File::open(&path)); @@ -573,7 +568,7 @@ This can be encoded in the handler API by introducing a helper type: `enum Malfo # #[allow(unused_imports)]; use std::io::{BufferedReader, File}; # mod BufferedReader { -# use std::io::File; +# use std::io::{File, IoResult}; # use std::io::MemReader; # use std::io::BufferedReader; # static s : &'static [u8] = bytes!("1 2\n\ @@ -581,7 +576,7 @@ use std::io::{BufferedReader, File}; # 789 123\n\ # 45 67\n\ # "); -# pub fn new(_inner: Option) -> BufferedReader { +# pub fn new(_inner: IoResult) -> BufferedReader { # BufferedReader::new(MemReader::new(s.to_owned())) # } # } @@ -615,7 +610,6 @@ fn main() { fn read_int_pairs() -> ~[(int,int)] { let mut pairs = ~[]; -# let _g = std::io::ignore_io_error(); let path = Path::new(&"foo.txt"); let mut reader = BufferedReader::new(File::open(&path)); @@ -696,7 +690,7 @@ a second condition and a helper function will suffice: # #[allow(unused_imports)]; use std::io::{BufferedReader, File}; # mod BufferedReader { -# use std::io::File; +# use std::io::{File, IoResult}; # use std::io::MemReader; # use std::io::BufferedReader; # static s : &'static [u8] = bytes!("1 2\n\ @@ -704,7 +698,7 @@ use std::io::{BufferedReader, File}; # 789 123\n\ # 45 67\n\ # "); -# pub fn new(_inner: Option) -> BufferedReader { +# pub fn new(_inner: IoResult) -> BufferedReader { # BufferedReader::new(MemReader::new(s.to_owned())) # } # } @@ -752,7 +746,6 @@ fn parse_int(x: &str) -> int { fn read_int_pairs() -> ~[(int,int)] { let mut pairs = ~[]; -# let _g = std::io::ignore_io_error(); let path = Path::new(&"foo.txt"); let mut reader = BufferedReader::new(File::open(&path)); diff --git a/src/etc/combine-tests.py b/src/etc/combine-tests.py index e87187abbcb..457c0b683ac 100755 --- a/src/etc/combine-tests.py +++ b/src/etc/combine-tests.py @@ -69,6 +69,7 @@ extern mod run_pass_stage2; use run_pass_stage2::*; use std::io; use std::io::Writer; +#[allow(warnings)] fn main() { let mut out = io::stdout(); """ diff --git a/src/libnative/io/file.rs b/src/libnative/io/file.rs index e6bead60d1b..cc5b0770d4d 100644 --- a/src/libnative/io/file.rs +++ b/src/libnative/io/file.rs @@ -561,7 +561,7 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> { } more_files = FindNextFileW(find_handle, wfd_ptr as HANDLE); } - FindClose(find_handle); + assert!(FindClose(find_handle) != 0); free(wfd_ptr as *mut c_void); Ok(paths) } else { @@ -683,7 +683,9 @@ pub fn readlink(p: &CString) -> IoResult { ptr::mut_null()) }) }; - if handle == ptr::mut_null() { return Err(super::last_error()) } + if handle as int == libc::INVALID_HANDLE_VALUE as int { + return Err(super::last_error()) + } let ret = fill_utf16_buf_and_decode(|buf, sz| { unsafe { libc::GetFinalPathNameByHandleW(handle, buf as *u16, sz, @@ -694,7 +696,7 @@ pub fn readlink(p: &CString) -> IoResult { Some(s) => Ok(Path::new(s)), None => Err(super::last_error()), }; - unsafe { libc::CloseHandle(handle) }; + assert!(unsafe { libc::CloseHandle(handle) } != 0); return ret; } diff --git a/src/libnative/io/process.rs b/src/libnative/io/process.rs index c2522d551b6..2a061c5f9b2 100644 --- a/src/libnative/io/process.rs +++ b/src/libnative/io/process.rs @@ -149,9 +149,8 @@ impl rtio::RtioProcess for Process { unsafe fn killpid(pid: pid_t, signal: int) -> Result<(), io::IoError> { match signal { io::process::PleaseExitSignal | io::process::MustDieSignal => { - libc::funcs::extra::kernel32::TerminateProcess( - cast::transmute(pid), 1); - Ok(()) + let ret = libc::TerminateProcess(pid as libc::HANDLE, 1); + super::mkerr_winbool(ret) } _ => Err(io::IoError { kind: io::OtherIoError, @@ -255,9 +254,9 @@ fn spawn_process_os(prog: &str, args: &[~str], }) }); - CloseHandle(si.hStdInput); - CloseHandle(si.hStdOutput); - CloseHandle(si.hStdError); + assert!(CloseHandle(si.hStdInput) != 0); + assert!(CloseHandle(si.hStdOutput) != 0); + assert!(CloseHandle(si.hStdError) != 0); match create_err { Some(err) => return Err(err), @@ -269,7 +268,7 @@ fn spawn_process_os(prog: &str, args: &[~str], // able to close it later. We don't close the process handle however // because std::we want the process id to stay valid at least until the // calling code closes the process handle. - CloseHandle(pi.hThread); + assert!(CloseHandle(pi.hThread) != 0); Ok(SpawnProcessResult { pid: pi.dwProcessId as pid_t, @@ -576,9 +575,9 @@ fn with_dirp(d: Option<&Path>, cb: |*libc::c_char| -> T) -> T { #[cfg(windows)] fn free_handle(handle: *()) { - unsafe { - libc::funcs::extra::kernel32::CloseHandle(cast::transmute(handle)); - } + assert!(unsafe { + libc::CloseHandle(cast::transmute(handle)) != 0 + }) } #[cfg(unix)] @@ -629,15 +628,15 @@ fn waitpid(pid: pid_t) -> p::ProcessExit { loop { let mut status = 0; if GetExitCodeProcess(process, &mut status) == FALSE { - CloseHandle(process); + assert!(CloseHandle(process) != 0); fail!("failure in GetExitCodeProcess: {}", os::last_os_error()); } if status != STILL_ACTIVE { - CloseHandle(process); + assert!(CloseHandle(process) != 0); return p::ExitStatus(status as int); } if WaitForSingleObject(process, INFINITE) == WAIT_FAILED { - CloseHandle(process); + assert!(CloseHandle(process) != 0); fail!("failure in WaitForSingleObject: {}", os::last_os_error()); } } diff --git a/src/libnative/io/timer_helper.rs b/src/libnative/io/timer_helper.rs index 74759b467d4..7311be46e8b 100644 --- a/src/libnative/io/timer_helper.rs +++ b/src/libnative/io/timer_helper.rs @@ -126,11 +126,11 @@ mod imp { } pub fn signal(handle: HANDLE) { - unsafe { SetEvent(handle); } + assert!(unsafe { SetEvent(handle) != 0 }); } pub fn close(handle: HANDLE) { - unsafe { CloseHandle(handle); } + assert!(unsafe { CloseHandle(handle) != 0 }); } extern "system" { diff --git a/src/libnative/io/timer_win32.rs b/src/libnative/io/timer_win32.rs index e359d99eedf..6b472d2f46d 100644 --- a/src/libnative/io/timer_win32.rs +++ b/src/libnative/io/timer_win32.rs @@ -62,8 +62,8 @@ fn helper(input: libc::HANDLE, messages: Port) { c.send(()); match objs.iter().position(|&o| o == obj) { Some(i) => { - objs.remove(i); - chans.remove(i - 1); + drop(objs.remove(i)); + drop(chans.remove(i - 1)); } None => {} } @@ -83,8 +83,8 @@ fn helper(input: libc::HANDLE, messages: Port) { } }; if remove { - objs.remove(idx as uint); - chans.remove(idx as uint - 1); + drop(objs.remove(idx as uint)); + drop(chans.remove(idx as uint - 1)); } } } @@ -133,7 +133,7 @@ impl rtio::RtioTimer for Timer { ptr::mut_null(), 0) }, 1); - unsafe { imp::WaitForSingleObject(self.obj, libc::INFINITE); } + let _ = unsafe { imp::WaitForSingleObject(self.obj, libc::INFINITE) }; } fn oneshot(&mut self, msecs: u64) -> Port<()> { @@ -173,7 +173,7 @@ impl rtio::RtioTimer for Timer { impl Drop for Timer { fn drop(&mut self) { self.remove(); - unsafe { libc::CloseHandle(self.obj); } + assert!(unsafe { libc::CloseHandle(self.obj) != 0 }); } } diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index ef046419789..c5f7d61c224 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -241,8 +241,8 @@ pub fn run_compiler(args: &[~str], demitter: @diagnostic::Emitter) { 1u => { let ifile = matches.free[0].as_slice(); if ifile == "-" { - let src = - str::from_utf8_owned(io::stdin().read_to_end()).unwrap(); + let contents = io::stdin().read_to_end().unwrap(); + let src = str::from_utf8_owned(contents).unwrap(); (d::StrInput(src), None) } else { (d::FileInput(Path::new(ifile)), Some(Path::new(ifile))) diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 824d0efff25..8ba98e84dfa 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -1160,12 +1160,12 @@ fn list_crate_deps(data: &[u8], out: &mut io::Writer) -> io::IoResult<()> { let r = get_crate_deps(data); for dep in r.iter() { let string = token::get_ident(dep.name.name); - write!(out, - "{} {}-{}-{}\n", - dep.cnum, - string.get(), - dep.hash, - dep.vers); + if_ok!(write!(out, + "{} {}-{}-{}\n", + dep.cnum, + string.get(), + dep.hash, + dep.vers)); } if_ok!(write!(out, "\n")); diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 687f391c07f..92d15fbcd67 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -48,7 +48,6 @@ impl PuritySpace { } impl fmt::Show for clean::Generics { -impl fmt::Default for clean::Generics { fn fmt(g: &clean::Generics, f: &mut fmt::Formatter) -> fmt::Result { if g.lifetimes.len() == 0 && g.type_params.len() == 0 { return Ok(()) } if_ok!(f.buf.write("<".as_bytes())); diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 7dc89cca745..65696528a6f 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -804,13 +804,13 @@ impl<'a> fmt::Show for Item<'a> { fn fmt(it: &Item<'a>, fmt: &mut fmt::Formatter) -> fmt::Result { match attr::find_stability(it.item.attrs.iter()) { Some(ref stability) => { - write!(fmt.buf, + if_ok!(write!(fmt.buf, "{lvl}", lvl = stability.level.to_str(), reason = match stability.text { Some(ref s) => (*s).clone(), None => InternedString::new(""), - }); + })); } None => {} } diff --git a/src/libstd/fmt/mod.rs b/src/libstd/fmt/mod.rs index 0bc567b270a..06737e22007 100644 --- a/src/libstd/fmt/mod.rs +++ b/src/libstd/fmt/mod.rs @@ -477,16 +477,20 @@ will look like `"\\{"`. */ -#[cfg(not(stage0))] -use prelude::*; - use cast; use char::Char; +use container::Container; use io::MemWriter; use io; -use str; +use iter::{Iterator, range}; +use num::Signed; +use option::{Option,Some,None}; use repr; +use result::{Ok, Err}; +use str::StrSlice; +use str; use util; +use vec::ImmutableVector; use vec; // NOTE this is just because the `prelude::*` import above includes @@ -494,19 +498,6 @@ use vec; #[cfg(stage0)] pub use Default = fmt::Show; // export required for `format!()` etc. -#[cfg(stage0)] -use container::Container; -#[cfg(stage0)] -use iter::{Iterator, range}; -#[cfg(stage0)] -use option::{Option,Some,None}; -#[cfg(stage0)] -use vec::ImmutableVector; -#[cfg(stage0)] -use str::StrSlice; -#[cfg(stage0)] -use num::Signed; - pub mod parse; pub mod rt; @@ -628,7 +619,7 @@ macro_rules! uniform_fn_call_workaround { ($( $name: ident, $trait_: ident; )*) => { $( #[doc(hidden)] - pub fn $name(x: &T, fmt: &mut Formatter) { + pub fn $name(x: &T, fmt: &mut Formatter) -> Result { $trait_::fmt(x, fmt) } )* diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 58a35e96393..7690c88478f 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -46,6 +46,7 @@ Some examples of obvious things you might want to do * Write a line to a file ```rust + # #[allow(unused_must_use)]; use std::io::File; let mut file = File::create(&Path::new("message.txt")); @@ -83,6 +84,7 @@ Some examples of obvious things you might want to do `write_str` and `write_line` methods. ```rust,should_fail + # #[allow(unused_must_use)]; use std::io::net::ip::SocketAddr; use std::io::net::tcp::TcpStream; @@ -188,6 +190,7 @@ be an error. If you wanted to handle the error though you might write: ```rust +# #[allow(unused_must_use)]; use std::io::File; match File::create(&Path::new("diary.txt")).write(bytes!("Met a girl.\n")) { @@ -360,7 +363,7 @@ pub struct IoError { detail: Option<~str> } -impl fmt::Default for IoError { +impl fmt::Show for IoError { fn fmt(err: &IoError, fmt: &mut fmt::Formatter) -> fmt::Result { if_ok!(fmt.buf.write_str(err.desc)); match err.detail { @@ -515,14 +518,13 @@ pub trait Reader { /// Returns any non-EOF error immediately. Previously read bytes are /// discarded when an error is returned. /// - /// When EOF is encountered, all bytes read up to that point are returned, - /// but if 0 bytes have been read then the EOF error is returned. + /// When EOF is encountered, all bytes read up to that point are returned. fn read_to_end(&mut self) -> IoResult<~[u8]> { let mut buf = vec::with_capacity(DEFAULT_BUF_SIZE); loop { match self.push_bytes(&mut buf, DEFAULT_BUF_SIZE) { Ok(()) => {} - Err(ref e) if buf.len() > 0 && e.kind == EndOfFile => break, + Err(ref e) if e.kind == EndOfFile => break, Err(e) => return Err(e) } } diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/io/net/tcp.rs index f3db964b882..a0bdc193d98 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/io/net/tcp.rs @@ -192,9 +192,10 @@ mod test { match stream.read(buf) { Ok(..) => fail!(), - Err(ref e) if cfg!(windows) => assert_eq!(e.kind, NotConnected), - Err(ref e) if cfg!(unix) => assert_eq!(e.kind, EndOfFile), - Err(..) => fail!(), + Err(ref e) => { + assert!(e.kind == NotConnected || e.kind == EndOfFile, + "unknown kind: {:?}", e.kind); + } } }) @@ -217,9 +218,10 @@ mod test { match stream.read(buf) { Ok(..) => fail!(), - Err(ref e) if cfg!(windows) => assert_eq!(e.kind, NotConnected), - Err(ref e) if cfg!(unix) => assert_eq!(e.kind, EndOfFile), - Err(..) => fail!(), + Err(ref e) => { + assert!(e.kind == NotConnected || e.kind == EndOfFile, + "unknown kind: {:?}", e.kind); + } } }) diff --git a/src/libstd/io/signal.rs b/src/libstd/io/signal.rs index 92b86afe24d..75804c40c58 100644 --- a/src/libstd/io/signal.rs +++ b/src/libstd/io/signal.rs @@ -203,6 +203,7 @@ mod test { fn test_io_signal_invalid_signum() { use io; use super::User1; + use result::{Ok, Err}; let mut s = Listener::new(); let mut called = false; match s.register(User1) { diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 8815f88d694..541db01f148 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -1535,6 +1535,7 @@ mod tests { assert!(*chunk.data == 0xbe); close(fd); } + drop(chunk); fs::unlink(&path).unwrap(); } diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 190cf5745f4..4aa4a3feab1 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -533,7 +533,7 @@ pub struct Display<'a, P> { } impl<'a, P: GenericPath> fmt::Show for Display<'a, P> { - fn fmt(d: &Display

, f: &mut fmt::Formatter) -> fmt::Display { + fn fmt(d: &Display

, f: &mut fmt::Formatter) -> fmt::Result { d.with_str(|s| f.pad(s)) } } diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 6d2acd3d803..f1dd844fc7c 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -588,8 +588,8 @@ impl BytesContainer for InternedString { } impl fmt::Show for InternedString { - fn fmt(obj: &InternedString, f: &mut fmt::Formatter) { - write!(f.buf, "{}", obj.string.as_slice()); + fn fmt(obj: &InternedString, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", obj.string.as_slice()) } } diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index bb287c0f5f8..f6952261723 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -299,19 +299,34 @@ impl Printer { if !self.scan_stack_empty { self.check_stack(0); let left = self.token[self.left].clone(); - self.advance_left(left, self.size[self.left]); + if_ok!(self.advance_left(left, self.size[self.left])); } - Begin(b) => { - if self.scan_stack_empty { - self.left_total = 1; - self.right_total = 1; - self.left = 0u; - self.right = 0u; - } else { self.advance_right(); } - debug!("pp Begin({})/buffer ~[{},{}]", - b.offset, self.left, self.right); + self.indent(0); + Ok(()) + } + Begin(b) => { + if self.scan_stack_empty { + self.left_total = 1; + self.right_total = 1; + self.left = 0u; + self.right = 0u; + } else { self.advance_right(); } + debug!("pp Begin({})/buffer ~[{},{}]", + b.offset, self.left, self.right); + self.token[self.right] = t; + self.size[self.right] = -self.right_total; + self.scan_push(self.right); + Ok(()) + } + End => { + if self.scan_stack_empty { + debug!("pp End/print ~[{},{}]", self.left, self.right); + self.print(t, 0) + } else { + debug!("pp End/buffer ~[{},{}]", self.left, self.right); + self.advance_right(); self.token[self.right] = t; - self.size[self.right] = -self.right_total; + self.size[self.right] = -1; self.scan_push(self.right); Ok(()) } @@ -330,12 +345,13 @@ impl Printer { self.token[self.right] = t; self.size[self.right] = -self.right_total; self.right_total += b.blank_space; + Ok(()) } String(ref s, len) => { if self.scan_stack_empty { debug!("pp String('{}')/print ~[{},{}]", *s, self.left, self.right); - self.print(t.clone(), len); + self.print(t.clone(), len) } else { debug!("pp String('{}')/buffer ~[{},{}]", *s, self.left, self.right); @@ -343,8 +359,9 @@ impl Printer { self.token[self.right] = t.clone(); self.size[self.right] = len; self.right_total += len; - self.check_stream(); + self.check_stream() } + } } } pub fn check_stream(&mut self) -> io::IoResult<()> { @@ -360,8 +377,10 @@ impl Printer { } } let left = self.token[self.left].clone(); - self.advance_left(left, self.size[self.left]); - if self.left != self.right { self.check_stream(); } + if_ok!(self.advance_left(left, self.size[self.left])); + if self.left != self.right { + if_ok!(self.check_stream()); + } } Ok(()) } @@ -405,7 +424,7 @@ impl Printer { debug!("advnce_left ~[{},{}], sizeof({})={}", self.left, self.right, self.left, L); if L >= 0 { - self.print(x.clone(), L); + let ret = self.print(x.clone(), L); match x { Break(b) => self.left_total += b.blank_space, String(_, len) => { @@ -417,7 +436,7 @@ impl Printer { self.left += 1u; self.left %= self.buf_len; let left = self.token[self.left].clone(); - self.advance_left(left, self.size[self.left]); + if_ok!(self.advance_left(left, self.size[self.left])); } ret } else { @@ -477,7 +496,7 @@ impl Printer { } write!(self.out, "{}", s) } - pub fn print(&mut self, x: Token, L: int) { + pub fn print(&mut self, x: Token, L: int) -> io::IoResult<()> { debug!("print {} {} (remaining line space={})", tok_str(x.clone()), L, self.space); debug!("{}", buf_str(self.token.clone(), @@ -587,16 +606,16 @@ pub fn end(p: &mut Printer) -> io::IoResult<()> { p.pretty_print(End) } pub fn eof(p: &mut Printer) -> io::IoResult<()> { p.pretty_print(Eof) } -pub fn word(p: &mut Printer, wrd: &str) { - p.pretty_print(String(/* bad */ wrd.to_str(), wrd.len() as int)); +pub fn word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { + p.pretty_print(String(/* bad */ wrd.to_str(), wrd.len() as int)) } -pub fn huge_word(p: &mut Printer, wrd: &str) { - p.pretty_print(String(/* bad */ wrd.to_str(), SIZE_INFINITY)); +pub fn huge_word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { + p.pretty_print(String(/* bad */ wrd.to_str(), SIZE_INFINITY)) } -pub fn zero_word(p: &mut Printer, wrd: &str) { - p.pretty_print(String(/* bad */ wrd.to_str(), 0)); +pub fn zero_word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { + p.pretty_print(String(/* bad */ wrd.to_str(), 0)) } pub fn spaces(p: &mut Printer, n: uint) -> io::IoResult<()> { diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index f0ef5014ca8..e291583d121 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -964,11 +964,7 @@ pub fn print_attribute(s: &mut State, attr: &ast::Attribute) -> io::IoResult<()> if_ok!(maybe_print_comment(s, attr.span.lo)); if attr.node.is_sugared_doc { let comment = attr.value_str().unwrap(); -<<<<<<< HEAD - word(&mut s.s, comment.get()); -======= - if_ok!(word(&mut s.s, comment)); ->>>>>>> syntax: Remove io_error usage + if_ok!(word(&mut s.s, comment.get())); } else { if_ok!(word(&mut s.s, "#[")); if_ok!(print_meta_item(s, attr.meta())); @@ -1139,24 +1135,7 @@ pub fn print_mac(s: &mut State, m: &ast::Mac) -> io::IoResult<()> { } } -<<<<<<< HEAD -pub fn print_expr_vstore(s: &mut State, t: ast::ExprVstore) { -======= -pub fn print_vstore(s: &mut State, t: ast::Vstore) -> io::IoResult<()> { - match t { - ast::VstoreFixed(Some(i)) => word(&mut s.s, format!("{}", i)), - ast::VstoreFixed(None) => word(&mut s.s, "_"), - ast::VstoreUniq => word(&mut s.s, "~"), - ast::VstoreBox => word(&mut s.s, "@"), - ast::VstoreSlice(ref r) => { - if_ok!(word(&mut s.s, "&")); - print_opt_lifetime(s, r) - } - } -} - pub fn print_expr_vstore(s: &mut State, t: ast::ExprVstore) -> io::IoResult<()> { ->>>>>>> syntax: Remove io_error usage match t { ast::ExprVstoreUniq => word(&mut s.s, "~"), ast::ExprVstoreSlice => word(&mut s.s, "&"), @@ -1557,51 +1536,27 @@ pub fn print_expr(s: &mut State, expr: &ast::Expr) -> io::IoResult<()> { } else { if_ok!(word(&mut s.s, "asm!")); } -<<<<<<< HEAD - popen(s); - print_string(s, a.asm.get(), a.asm_str_style); - word_space(s, ":"); - for &(ref co, o) in a.outputs.iter() { - print_string(s, co.get(), ast::CookedStr); - popen(s); - print_expr(s, o); - pclose(s); - word_space(s, ","); - } - word_space(s, ":"); - for &(ref co, o) in a.inputs.iter() { - print_string(s, co.get(), ast::CookedStr); - popen(s); - print_expr(s, o); - pclose(s); - word_space(s, ","); - } - word_space(s, ":"); - print_string(s, a.clobbers.get(), ast::CookedStr); - pclose(s); -======= if_ok!(popen(s)); - if_ok!(print_string(s, a.asm, a.asm_str_style)); + if_ok!(print_string(s, a.asm.get(), a.asm_str_style)); if_ok!(word_space(s, ":")); - for &(co, o) in a.outputs.iter() { - if_ok!(print_string(s, co, ast::CookedStr)); + for &(ref co, o) in a.outputs.iter() { + if_ok!(print_string(s, co.get(), ast::CookedStr)); if_ok!(popen(s)); if_ok!(print_expr(s, o)); if_ok!(pclose(s)); if_ok!(word_space(s, ",")); } if_ok!(word_space(s, ":")); - for &(co, o) in a.inputs.iter() { - if_ok!(print_string(s, co, ast::CookedStr)); + for &(ref co, o) in a.inputs.iter() { + if_ok!(print_string(s, co.get(), ast::CookedStr)); if_ok!(popen(s)); if_ok!(print_expr(s, o)); if_ok!(pclose(s)); if_ok!(word_space(s, ",")); } if_ok!(word_space(s, ":")); - if_ok!(print_string(s, a.clobbers, ast::CookedStr)); + if_ok!(print_string(s, a.clobbers.get(), ast::CookedStr)); if_ok!(pclose(s)); ->>>>>>> syntax: Remove io_error usage } ast::ExprMac(ref m) => if_ok!(print_mac(s, m)), ast::ExprParen(e) => { @@ -1659,23 +1614,14 @@ pub fn print_decl(s: &mut State, decl: &ast::Decl) -> io::IoResult<()> { } } -<<<<<<< HEAD -pub fn print_ident(s: &mut State, ident: ast::Ident) { - let string = token::get_ident(ident.name); - word(&mut s.s, string.get()); -} - -pub fn print_name(s: &mut State, name: ast::Name) { - let string = token::get_ident(name); - word(&mut s.s, string.get()); -======= pub fn print_ident(s: &mut State, ident: ast::Ident) -> io::IoResult<()> { - word(&mut s.s, ident_to_str(&ident)) + let string = token::get_ident(ident.name); + word(&mut s.s, string.get()) } pub fn print_name(s: &mut State, name: ast::Name) -> io::IoResult<()> { - word(&mut s.s, interner_get(name)) ->>>>>>> syntax: Remove io_error usage + let string = token::get_ident(name); + word(&mut s.s, string.get()) } pub fn print_for_decl(s: &mut State, loc: &ast::Local, @@ -2088,38 +2034,23 @@ pub fn print_generics(s: &mut State, pub fn print_meta_item(s: &mut State, item: &ast::MetaItem) -> io::IoResult<()> { if_ok!(ibox(s, indent_unit)); match item.node { -<<<<<<< HEAD - ast::MetaWord(ref name) => word(&mut s.s, name.get()), - ast::MetaNameValue(ref name, ref value) => { - word_space(s, name.get()); - word_space(s, "="); - print_literal(s, value); - } - ast::MetaList(ref name, ref items) => { - word(&mut s.s, name.get()); - popen(s); - commasep(s, - Consistent, - items.as_slice(), - |p, &i| print_meta_item(p, i)); - pclose(s); -======= - ast::MetaWord(name) => { if_ok!(word(&mut s.s, name)); } - ast::MetaNameValue(name, value) => { - if_ok!(word_space(s, name)); - if_ok!(word_space(s, "=")); - if_ok!(print_literal(s, &value)); - } - ast::MetaList(name, ref items) => { - if_ok!(word(&mut s.s, name)); - if_ok!(popen(s)); - if_ok!(commasep(s, - Consistent, - items.as_slice(), - |p, &i| print_meta_item(p, i))); - if_ok!(pclose(s)); ->>>>>>> syntax: Remove io_error usage - } + ast::MetaWord(ref name) => { + if_ok!(word(&mut s.s, name.get())); + } + ast::MetaNameValue(ref name, ref value) => { + if_ok!(word_space(s, name.get())); + if_ok!(word_space(s, "=")); + if_ok!(print_literal(s, value)); + } + ast::MetaList(ref name, ref items) => { + if_ok!(word(&mut s.s, name.get())); + if_ok!(popen(s)); + if_ok!(commasep(s, + Consistent, + items.as_slice(), + |p, &i| print_meta_item(p, i))); + if_ok!(pclose(s)); + } } end(s) } @@ -2171,17 +2102,10 @@ pub fn print_view_item(s: &mut State, item: &ast::ViewItem) -> io::IoResult<()> if_ok!(head(s, "extern mod")); if_ok!(print_ident(s, id)); for &(ref p, style) in optional_path.iter() { -<<<<<<< HEAD - space(&mut s.s); - word(&mut s.s, "="); - space(&mut s.s); - print_string(s, p.get(), style); -======= if_ok!(space(&mut s.s)); if_ok!(word(&mut s.s, "=")); if_ok!(space(&mut s.s)); - if_ok!(print_string(s, *p, style)); ->>>>>>> syntax: Remove io_error usage + if_ok!(print_string(s, p.get(), style)); } } @@ -2373,88 +2297,54 @@ pub fn print_literal(s: &mut State, lit: &ast::Lit) -> io::IoResult<()> { _ => () } match lit.node { -<<<<<<< HEAD ast::LitStr(ref st, style) => print_string(s, st.get(), style), ast::LitChar(ch) => { let mut res = ~"'"; char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c)); res.push_char('\''); - word(&mut s.s, res); + word(&mut s.s, res) } ast::LitInt(i, t) => { if i < 0_i64 { word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u) - + ast_util::int_ty_to_str(t)); + + ast_util::int_ty_to_str(t)) } else { word(&mut s.s, (i as u64).to_str_radix(10u) - + ast_util::int_ty_to_str(t)); -======= - ast::LitStr(st, style) => print_string(s, st, style), - ast::LitChar(ch) => { - let mut res = ~"'"; - char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c)); - res.push_char('\''); - word(&mut s.s, res) - } - ast::LitInt(i, t) => { - if i < 0_i64 { - word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u) - + ast_util::int_ty_to_str(t)) - } else { - word(&mut s.s, (i as u64).to_str_radix(10u) - + ast_util::int_ty_to_str(t)) - } ->>>>>>> syntax: Remove io_error usage - } - ast::LitUint(u, t) => { - word(&mut s.s, u.to_str_radix(10u) + ast_util::uint_ty_to_str(t)) + + ast_util::int_ty_to_str(t)) } - ast::LitIntUnsuffixed(i) => { - if i < 0_i64 { - word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u)) - } else { - word(&mut s.s, (i as u64).to_str_radix(10u)) - } - } - ast::LitFloat(f, t) => { - word(&mut s.s, f.to_owned() + ast_util::float_ty_to_str(t)) - } - ast::LitFloatUnsuffixed(f) => word(&mut s.s, f), - ast::LitNil => word(&mut s.s, "()"), - ast::LitBool(val) => { - if val { word(&mut s.s, "true") } else { word(&mut s.s, "false") } - } - ast::LitBinary(arr) => { - if_ok!(ibox(s, indent_unit)); - if_ok!(word(&mut s.s, "[")); - if_ok!(commasep_cmnt(s, Inconsistent, arr, - |s, u| word(&mut s.s, format!("{}", *u)), - |_| lit.span)); - if_ok!(word(&mut s.s, "]")); - end(s) + } + ast::LitUint(u, t) => { + word(&mut s.s, + u.to_str_radix(10u) + + ast_util::uint_ty_to_str(t)) + } + ast::LitIntUnsuffixed(i) => { + if i < 0_i64 { + word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u)) + } else { + word(&mut s.s, (i as u64).to_str_radix(10u)) } -<<<<<<< HEAD } + ast::LitFloat(ref f, t) => { - word(&mut s.s, f.get() + ast_util::float_ty_to_str(t)); + word(&mut s.s, f.get() + ast_util::float_ty_to_str(t)) } ast::LitFloatUnsuffixed(ref f) => word(&mut s.s, f.get()), ast::LitNil => word(&mut s.s, "()"), ast::LitBool(val) => { - if val { word(&mut s.s, "true"); } else { word(&mut s.s, "false"); } + if val { word(&mut s.s, "true") } else { word(&mut s.s, "false") } } ast::LitBinary(ref arr) => { - ibox(s, indent_unit); - word(&mut s.s, "["); - commasep_cmnt(s, Inconsistent, *arr.borrow(), |s, u| word(&mut s.s, format!("{}", *u)), - |_| lit.span); - word(&mut s.s, "]"); - end(s); - } -======= ->>>>>>> syntax: Remove io_error usage + if_ok!(ibox(s, indent_unit)); + if_ok!(word(&mut s.s, "[")); + if_ok!(commasep_cmnt(s, Inconsistent, *arr.borrow(), + |s, u| word(&mut s.s, format!("{}", *u)), + |_| lit.span)); + if_ok!(word(&mut s.s, "]")); + end(s) + } } } diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index 98dd2b20a5f..c4481a1a07f 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -19,15 +19,21 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")]; +#[feature(macro_rules)]; #[deny(non_camel_case_types)]; #[allow(missing_doc)]; use std::os; +use std::io; use terminfo::TermInfo; use terminfo::searcher::open; use terminfo::parser::compiled::{parse, msys_terminfo}; use terminfo::parm::{expand, Number, Variables}; +macro_rules! if_ok ( + ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) }) +) + pub mod terminfo; // FIXME (#2807): Windows support. diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index a0e9f96b31d..6f4a4c43b03 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -8,11 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::io; use std::io::BufferedWriter; struct DummyWriter; impl Writer for DummyWriter { - fn write(&mut self, _: &[u8]) {} + fn write(&mut self, _: &[u8]) -> io::IoResult<()> { Ok(()) } } static ITER: int = 50; diff --git a/src/test/bench/shootout-reverse-complement.rs b/src/test/bench/shootout-reverse-complement.rs index 43167458e86..771e545ece8 100644 --- a/src/test/bench/shootout-reverse-complement.rs +++ b/src/test/bench/shootout-reverse-complement.rs @@ -36,11 +36,12 @@ fn make_complements() -> [u8, ..256] { fn main() { let complements = make_complements(); - let mut data = if std::os::getenv("RUST_BENCH").is_some() { + let data = if std::os::getenv("RUST_BENCH").is_some() { File::open(&Path::new("shootout-k-nucleotide.data")).read_to_end() } else { stdin().read_to_end() }; + let mut data = data.unwrap(); for seq in data.mut_split(|c| *c == '>' as u8) { // skip header and last \n -- cgit 1.4.1-3-g733a5