From 61ed2cfb5516f76487509766b1054275f1340f70 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sun, 13 Oct 2013 18:48:47 -0700 Subject: Remove even more of std::io Big fish fried here: extra::json most of the compiler extra::io_util removed extra::fileinput removed Fish left to fry extra::ebml --- src/libsyntax/ast_util.rs | 3 +-- src/libsyntax/diagnostic.rs | 38 +++++++++++++-------------- src/libsyntax/ext/expand.rs | 33 ++++++++++++----------- src/libsyntax/ext/log_syntax.rs | 4 +-- src/libsyntax/ext/source_util.rs | 51 ++++++++++++++++++++++++----------- src/libsyntax/parse/comments.rs | 7 ++--- src/libsyntax/parse/mod.rs | 52 ++++++++++++++++++++++++++---------- src/libsyntax/print/pp.rs | 14 +++++----- src/libsyntax/print/pprust.rs | 57 +++++++++++++++++++++------------------- 9 files changed, 151 insertions(+), 108 deletions(-) (limited to 'src/libsyntax') diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 1d9d5512ff4..456d344b838 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -962,7 +962,6 @@ pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> boo mod test { use ast::*; use super::*; - use std::io; use opt_vec; use std::hashmap::HashMap; @@ -1137,7 +1136,7 @@ mod test { // - two renames of the same var.. can only happen if you use // local-expand to prevent the inner binding from being renamed // during the rename-pass caused by the first: - io::println("about to run bad test"); + println("about to run bad test"); { let sc = unfold_test_sc(~[R(id(a,EMPTY_CTXT),50), R(id(a,EMPTY_CTXT),51)], EMPTY_CTXT,&mut t); diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index bbbaf2a2f60..736f92910af 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -11,7 +11,7 @@ use codemap::{Pos, Span}; use codemap; -use std::io; +use std::rt::io; use std::local_data; use extra::term; @@ -199,9 +199,14 @@ fn diagnosticcolor(lvl: level) -> term::color::Color { fn print_maybe_styled(msg: &str, color: term::attr::Attr) { local_data_key!(tls_terminal: @Option) - let stderr = io::stderr(); + let stderr = @mut io::stderr() as @mut io::Writer; + fn is_stderr_screen() -> bool { + #[fixed_stack_segment]; + use std::libc; + unsafe { libc::isatty(libc::STDERR_FILENO) != 0 } + } - if stderr.get_type() == io::Screen { + if is_stderr_screen() { let t = match local_data::get(tls_terminal, |v| v.map(|k| *k)) { None => { let t = term::Terminal::new(stderr); @@ -218,21 +223,21 @@ fn print_maybe_styled(msg: &str, color: term::attr::Attr) { match t { &Some(ref term) => { term.attr(color); - stderr.write_str(msg); + write!(stderr, "{}", msg); term.reset(); }, - _ => stderr.write_str(msg) + _ => write!(stderr, "{}", msg) } } else { - stderr.write_str(msg); + write!(stderr, "{}", msg); } } fn print_diagnostic(topic: &str, lvl: level, msg: &str) { - let stderr = io::stderr(); + let mut stderr = io::stderr(); if !topic.is_empty() { - stderr.write_str(format!("{} ", topic)); + write!(&mut stderr as &mut io::Writer, "{} ", topic); } print_maybe_styled(format!("{}: ", diagnosticstr(lvl)), @@ -266,6 +271,8 @@ fn highlight_lines(cm: @codemap::CodeMap, lvl: level, lines: @codemap::FileLines) { let fm = lines.file; + let mut err = io::stderr(); + let err = &mut err as &mut io::Writer; // arbitrarily only print up to six lines of the error let max_lines = 6u; @@ -277,21 +284,12 @@ fn highlight_lines(cm: @codemap::CodeMap, } // Print the offending lines for line in display_lines.iter() { - io::stderr().write_str(format!("{}:{} ", fm.name, *line + 1u)); - let s = fm.get_line(*line as int) + "\n"; - io::stderr().write_str(s); + 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); - let mut indent = s.len(); - let mut out = ~""; - while indent > 0u { - out.push_char(' '); - indent -= 1u; - } - out.push_str("...\n"); - io::stderr().write_str(out); + write!(err, "{0:1$}...\n", "", s.len()); } // FIXME (#3260) @@ -325,7 +323,7 @@ fn highlight_lines(cm: @codemap::CodeMap, _ => s.push_char(' '), }; } - io::stderr().write_str(s); + write!(err, "{}", s); let mut s = ~"^"; let hi = cm.lookup_char_pos(sp.hi); if hi.col != lo.col { diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 1018e79aabc..99bcb36eedb 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -1524,7 +1524,8 @@ mod test { } fn fake_print_crate(crate: &ast::Crate) { - let s = pprust::rust_printer(std::io::stderr(),get_ident_interner()); + let out = @mut std::rt::io::stderr() as @mut std::rt::io::Writer; + let s = pprust::rust_printer(out, get_ident_interner()); pprust::print_crate_(s, crate); } @@ -1536,7 +1537,7 @@ mod test { //fn expand_and_resolve(crate_str: @str) -> ast::crate { //let expanded_ast = expand_crate_str(crate_str); - // std::io::println(format!("expanded: {:?}\n",expanded_ast)); + // println(format!("expanded: {:?}\n",expanded_ast)); //mtwt_resolve_crate(expanded_ast) //} //fn expand_and_resolve_and_pretty_print (crate_str : @str) -> ~str { @@ -1645,9 +1646,9 @@ mod test { let varref_marks = mtwt_marksof(varref.segments[0].identifier.ctxt, invalid_name); if (!(varref_name==binding_name)){ - std::io::println("uh oh, should match but doesn't:"); - std::io::println(format!("varref: {:?}",varref)); - std::io::println(format!("binding: {:?}", bindings[binding_idx])); + 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); @@ -1665,12 +1666,12 @@ mod test { println!("text of test case: \"{}\"", teststr); println!(""); println!("uh oh, matches but shouldn't:"); - std::io::println(format!("varref: {:?}",varref)); + println!("varref: {:?}",varref); // good lord, you can't make a path with 0 segments, can you? println!("varref's first segment's uint: {}, and string: \"{}\"", varref.segments[0].identifier.name, ident_to_str(&varref.segments[0].identifier)); - std::io::println(format!("binding: {:?}", bindings[binding_idx])); + println!("binding: {:?}", bindings[binding_idx]); ast_util::display_sctable(get_sctable()); } assert!(!fail); @@ -1703,17 +1704,17 @@ foo_module!() && (@"xx" == (ident_to_str(&p.segments[0].identifier))) }).enumerate() { if (mtwt_resolve(v.segments[0].identifier) != resolved_binding) { - std::io::println("uh oh, xx binding didn't match xx varref:"); - std::io::println(format!("this is xx varref \\# {:?}",idx)); - std::io::println(format!("binding: {:?}",cxbind)); - std::io::println(format!("resolves to: {:?}",resolved_binding)); - std::io::println(format!("varref: {:?}",v.segments[0].identifier)); - std::io::println(format!("resolves to: {:?}", - mtwt_resolve(v.segments[0].identifier))); + println("uh oh, xx binding didn't match xx varref:"); + println!("this is xx varref \\# {:?}",idx); + println!("binding: {:?}",cxbind); + println!("resolves to: {:?}",resolved_binding); + println!("varref: {:?}",v.segments[0].identifier); + println!("resolves to: {:?}", + mtwt_resolve(v.segments[0].identifier)); let table = get_sctable(); - std::io::println("SC table:"); + println("SC table:"); for (idx,val) in table.table.iter().enumerate() { - std::io::println(format!("{:4u} : {:?}",idx,val)); + println!("{:4u} : {:?}",idx,val); } } assert_eq!(mtwt_resolve(v.segments[0].identifier),resolved_binding); diff --git a/src/libsyntax/ext/log_syntax.rs b/src/libsyntax/ext/log_syntax.rs index 52807009073..3e07b16221e 100644 --- a/src/libsyntax/ext/log_syntax.rs +++ b/src/libsyntax/ext/log_syntax.rs @@ -15,15 +15,13 @@ use ext::base; use print; use parse::token::{get_ident_interner}; -use std::io; - pub fn expand_syntax_ext(cx: @ExtCtxt, sp: codemap::Span, tt: &[ast::token_tree]) -> base::MacResult { cx.print_backtrace(); - io::stdout().write_line( + println( print::pprust::tt_to_str( &ast::tt_delim(@mut tt.to_owned()), get_ident_interner())); diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index dcfeb99365a..df177cf75dc 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -19,8 +19,10 @@ use parse; use parse::token::{get_ident_interner}; use print::pprust; -use std::io; -use std::result; +use std::rt::io; +use std::rt::io::extensions::ReaderUtil; +use std::rt::io::file::FileInfo; +use std::str; // These macros all relate to the file system; they either return // the column/row/filename of the expression, or they include @@ -89,14 +91,23 @@ pub fn expand_include(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) pub fn expand_include_str(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) -> base::MacResult { let file = get_single_str_from_tts(cx, sp, tts, "include_str!"); - let res = io::read_whole_file_str(&res_rel_file(cx, sp, &Path::new(file))); - match res { - result::Ok(res) => { - base::MRExpr(cx.expr_str(sp, res.to_managed())) - } - result::Err(e) => { - cx.span_fatal(sp, e); - } + let file = res_rel_file(cx, sp, &Path::new(file)); + let mut error = None; + let bytes = do io::read_error::cond.trap(|e| error = Some(e)).inside { + file.open_reader(io::Open).read_to_end() + }; + match error { + Some(e) => { + cx.span_fatal(sp, format!("couldn't read {}: {}", + file.display(), e.desc)); + } + None => {} + } + match str::from_utf8_owned_opt(bytes) { + Some(s) => base::MRExpr(cx.expr_str(sp, s.to_managed())), + None => { + cx.span_fatal(sp, format!("{} wasn't a utf-8 file", file.display())); + } } } @@ -106,13 +117,21 @@ pub fn expand_include_bin(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) use std::at_vec; let file = get_single_str_from_tts(cx, sp, tts, "include_bin!"); - match io::read_whole_file(&res_rel_file(cx, sp, &Path::new(file))) { - result::Ok(src) => { - let v = at_vec::to_managed_move(src); - base::MRExpr(cx.expr_lit(sp, ast::lit_binary(v))) + let file = res_rel_file(cx, sp, &Path::new(file)); + + let mut error = None; + let bytes = do io::read_error::cond.trap(|e| error = Some(e)).inside { + do io::io_error::cond.trap(|e| error = Some(e)).inside { + file.open_reader(io::Open).read_to_end() + } + }; + match error { + Some(e) => { + cx.span_fatal(sp, format!("couldn't read {}: {}", + file.display(), e.desc)); } - result::Err(ref e) => { - cx.parse_sess().span_diagnostic.handler().fatal((*e)) + None => { + base::MRExpr(cx.expr_lit(sp, ast::lit_binary(bytes))) } } } diff --git a/src/libsyntax/parse/comments.rs b/src/libsyntax/parse/comments.rs index 38921648a2b..e9e6eb872c8 100644 --- a/src/libsyntax/parse/comments.rs +++ b/src/libsyntax/parse/comments.rs @@ -18,7 +18,8 @@ use parse::lexer; use parse::token; use parse::token::{get_ident_interner}; -use std::io; +use std::rt::io; +use std::rt::io::extensions::ReaderUtil; use std::str; use std::uint; @@ -346,9 +347,9 @@ pub struct lit { pub fn gather_comments_and_literals(span_diagnostic: @mut diagnostic::span_handler, path: @str, - srdr: @io::Reader) + mut srdr: &mut io::Reader) -> (~[cmnt], ~[lit]) { - let src = str::from_utf8(srdr.read_whole_stream()).to_managed(); + let src = str::from_utf8(srdr.read_to_end()).to_managed(); 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 c9405d72464..93e5d3dd772 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -19,8 +19,11 @@ use parse::attr::parser_attr; use parse::lexer::reader; use parse::parser::Parser; -use std::io; use std::path::Path; +use std::rt::io; +use std::rt::io::extensions::ReaderUtil; +use std::rt::io::file::FileInfo; +use std::str; pub mod lexer; pub mod parser; @@ -260,16 +263,34 @@ pub fn new_parser_from_tts(sess: @mut ParseSess, /// add the path to the session's codemap and return the new filemap. pub fn file_to_filemap(sess: @mut ParseSess, path: &Path, spanopt: Option) -> @FileMap { - match io::read_whole_file_str(path) { - // FIXME (#9639): This needs to handle non-utf8 paths - Ok(src) => string_to_filemap(sess, src.to_managed(), path.as_str().unwrap().to_managed()), - Err(e) => { - match spanopt { - Some(span) => sess.span_diagnostic.span_fatal(span, e), - None => sess.span_diagnostic.handler().fatal(e) - } + let err = |msg: &str| { + match spanopt { + Some(sp) => sess.span_diagnostic.span_fatal(sp, msg), + None => sess.span_diagnostic.handler().fatal(msg), + } + }; + let mut error = None; + let bytes = do io::io_error::cond.trap(|e| error = Some(e)).inside { + do io::read_error::cond.trap(|e| error = Some(e)).inside { + path.open_reader(io::Open).read_to_end() } + }; + match error { + Some(e) => { + err(format!("couldn't read {}: {}", path.display(), e.desc)); + } + None => {} } + match str::from_utf8_owned_opt(bytes) { + Some(s) => { + return string_to_filemap(sess, s.to_managed(), + path.as_str().unwrap().to_managed()); + } + None => { + err(format!("{} is not UTF-8 encoded", path.display())) + } + } + unreachable!() } // given a session and a string, add the string to @@ -318,7 +339,10 @@ mod test { use super::*; use extra::serialize::Encodable; use extra; - use std::io; + use std::rt::io; + use std::rt::io::Decorator; + use std::rt::io::mem::MemWriter; + use std::str; use codemap::{Span, BytePos, Spanned}; use opt_vec; use ast; @@ -330,10 +354,10 @@ mod test { use util::parser_testing::string_to_stmt; #[cfg(test)] fn to_json_str>(val: @E) -> ~str { - do io::with_str_writer |writer| { - let mut encoder = extra::json::Encoder(writer); - val.encode(&mut encoder); - } + let writer = @mut MemWriter::new(); + let mut encoder = extra::json::Encoder(writer as @mut io::Writer); + val.encode(&mut encoder); + str::from_utf8(*writer.inner_ref()) } // produce a codemap::span diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 871584003b5..4801fa21fc4 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -61,7 +61,7 @@ * avoid combining it with other lines and making matters even worse. */ -use std::io; +use std::rt::io; use std::vec; #[deriving(Clone, Eq)] @@ -148,7 +148,7 @@ pub struct print_stack_elt { pub static size_infinity: int = 0xffff; -pub fn mk_printer(out: @io::Writer, linewidth: uint) -> @mut Printer { +pub fn mk_printer(out: @mut io::Writer, linewidth: uint) -> @mut Printer { // Yes 3, it makes the ring buffers big enough to never // fall behind. let n: uint = 3 * linewidth; @@ -157,7 +157,7 @@ pub fn mk_printer(out: @io::Writer, linewidth: uint) -> @mut Printer { let size: ~[int] = vec::from_elem(n, 0); let scan_stack: ~[uint] = vec::from_elem(n, 0u); @mut Printer { - out: @out, + out: out, buf_len: n, margin: linewidth as int, space: linewidth as int, @@ -255,7 +255,7 @@ pub fn mk_printer(out: @io::Writer, linewidth: uint) -> @mut Printer { * called 'print'. */ pub struct Printer { - out: @@io::Writer, + out: @mut io::Writer, buf_len: uint, margin: int, // width of lines we're constrained to space: int, // number of spaces left on line @@ -452,7 +452,7 @@ impl Printer { } pub fn print_newline(&mut self, amount: int) { debug!("NEWLINE {}", amount); - (*self.out).write_str("\n"); + write!(self.out, "\n"); self.pending_indentation = 0; self.indent(amount); } @@ -474,10 +474,10 @@ impl Printer { } pub fn print_str(&mut self, s: &str) { while self.pending_indentation > 0 { - (*self.out).write_str(" "); + write!(self.out, " "); self.pending_indentation -= 1; } - (*self.out).write_str(s); + write!(self.out, "{}", s); } pub fn print(&mut self, x: token, L: int) { debug!("print {} {} (remaining line space={})", tok_str(x), L, diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 0e330da31e6..400ff804485 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -28,7 +28,10 @@ use print::pp; use print::pprust; use std::char; -use std::io; +use std::str; +use std::rt::io; +use std::rt::io::Decorator; +use std::rt::io::mem::MemWriter; // The @ps is stored here to prevent recursive type. pub enum ann_node<'self> { @@ -83,11 +86,11 @@ pub fn end(s: @ps) { pp::end(s.s); } -pub fn rust_printer(writer: @io::Writer, intr: @ident_interner) -> @ps { +pub fn rust_printer(writer: @mut io::Writer, intr: @ident_interner) -> @ps { return rust_printer_annotated(writer, intr, @no_ann::new() as @pp_ann); } -pub fn rust_printer_annotated(writer: @io::Writer, +pub fn rust_printer_annotated(writer: @mut io::Writer, intr: @ident_interner, ann: @pp_ann) -> @ps { @@ -118,8 +121,8 @@ pub fn print_crate(cm: @CodeMap, span_diagnostic: @mut diagnostic::span_handler, crate: &ast::Crate, filename: @str, - input: @io::Reader, - out: @io::Writer, + input: @mut io::Reader, + out: @mut io::Writer, ann: @pp_ann, is_expanded: bool) { let (cmnts, lits) = comments::gather_comments_and_literals( @@ -200,26 +203,26 @@ pub fn path_to_str(p: &ast::Path, intr: @ident_interner) -> ~str { pub fn fun_to_str(decl: &ast::fn_decl, purity: ast::purity, name: ast::Ident, opt_explicit_self: Option, generics: &ast::Generics, intr: @ident_interner) -> ~str { - do io::with_str_writer |wr| { - let s = rust_printer(wr, intr); - print_fn(s, decl, Some(purity), AbiSet::Rust(), - name, generics, opt_explicit_self, ast::inherited); - end(s); // Close the head box - end(s); // Close the outer box - eof(s.s); - } + let wr = @mut MemWriter::new(); + let s = rust_printer(wr as @mut io::Writer, intr); + print_fn(s, decl, Some(purity), AbiSet::Rust(), + name, generics, opt_explicit_self, ast::inherited); + end(s); // Close the head box + end(s); // Close the outer box + eof(s.s); + str::from_utf8(*wr.inner_ref()) } pub fn block_to_str(blk: &ast::Block, intr: @ident_interner) -> ~str { - do io::with_str_writer |wr| { - let s = rust_printer(wr, intr); - // containing cbox, will be closed by print-block at } - cbox(s, indent_unit); - // head-ibox, will be closed by print-block after { - ibox(s, 0u); - print_block(s, blk); - eof(s.s); - } + let wr = @mut MemWriter::new(); + let s = rust_printer(wr as @mut io::Writer, intr); + // containing cbox, will be closed by print-block at } + cbox(s, indent_unit); + // head-ibox, will be closed by print-block after { + ibox(s, 0u); + print_block(s, blk); + eof(s.s); + str::from_utf8(*wr.inner_ref()) } pub fn meta_item_to_str(mi: &ast::MetaItem, intr: @ident_interner) -> ~str { @@ -2196,11 +2199,11 @@ pub fn print_string(s: @ps, st: &str, style: ast::StrStyle) { } pub fn to_str(t: &T, f: &fn(@ps, &T), intr: @ident_interner) -> ~str { - do io::with_str_writer |wr| { - let s = rust_printer(wr, intr); - f(s, t); - eof(s.s); - } + let wr = @mut MemWriter::new(); + let s = rust_printer(wr as @mut io::Writer, intr); + f(s, t); + eof(s.s); + str::from_utf8(*wr.inner_ref()) } pub fn next_comment(s: @ps) -> Option { -- cgit 1.4.1-3-g733a5 From 6b70ddfba1ed5fca7fa67e5f2d2691e9c667d3a3 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Fri, 18 Oct 2013 11:52:23 -0700 Subject: Remove io::read_error The general idea is to remove conditions completely from I/O, so in the meantime remove the read_error condition to mean the same thing as the io_error condition. --- src/libstd/rt/io/extensions.rs | 38 +++++++++++++++++++------------------- src/libstd/rt/io/file.rs | 12 ++++++------ src/libstd/rt/io/mod.rs | 8 +------- src/libstd/rt/io/net/tcp.rs | 8 ++++---- src/libstd/rt/io/net/udp.rs | 4 ++-- src/libstd/rt/io/option.rs | 8 ++++---- src/libstd/rt/io/pipe.rs | 4 ++-- src/libsyntax/ext/source_util.rs | 8 +++----- src/libsyntax/parse/mod.rs | 4 +--- 9 files changed, 42 insertions(+), 52 deletions(-) (limited to 'src/libsyntax') diff --git a/src/libstd/rt/io/extensions.rs b/src/libstd/rt/io/extensions.rs index 99634b532b0..c77e3b91609 100644 --- a/src/libstd/rt/io/extensions.rs +++ b/src/libstd/rt/io/extensions.rs @@ -18,7 +18,7 @@ use int; use iter::Iterator; use vec; use rt::io::{Reader, Writer, Decorator}; -use rt::io::{read_error, standard_error, EndOfFile, DEFAULT_BUF_SIZE}; +use rt::io::{io_error, standard_error, EndOfFile, DEFAULT_BUF_SIZE}; use option::{Option, Some, None}; use unstable::finally::Finally; use cast; @@ -41,8 +41,8 @@ pub trait ReaderUtil { /// /// # Failure /// - /// Raises the same conditions as `read`. Additionally raises `read_error` - /// on EOF. If `read_error` is handled then `push_bytes` may push less + /// 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. fn push_bytes(&mut self, buf: &mut ~[u8], len: uint); @@ -50,8 +50,8 @@ pub trait ReaderUtil { /// /// # Failure /// - /// Raises the same conditions as `read`. Additionally raises `read_error` - /// on EOF. If `read_error` is handled then the returned vector may + /// 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. fn read_bytes(&mut self, len: uint) -> ~[u8]; @@ -314,7 +314,7 @@ impl ReaderUtil for T { total_read += nread; } None => { - read_error::cond.raise(standard_error(EndOfFile)); + io_error::cond.raise(standard_error(EndOfFile)); break; } } @@ -334,11 +334,11 @@ impl ReaderUtil for T { fn read_to_end(&mut self) -> ~[u8] { let mut buf = vec::with_capacity(DEFAULT_BUF_SIZE); let mut keep_reading = true; - do read_error::cond.trap(|e| { + do io_error::cond.trap(|e| { if e.kind == EndOfFile { keep_reading = false; } else { - read_error::cond.raise(e) + io_error::cond.raise(e) } }).inside { while keep_reading { @@ -641,7 +641,7 @@ mod test { use cell::Cell; use rt::io::mem::{MemReader, MemWriter}; use rt::io::mock::MockReader; - use rt::io::{read_error, placeholder_error}; + use rt::io::{io_error, placeholder_error}; #[test] fn read_byte() { @@ -681,10 +681,10 @@ mod test { fn read_byte_error() { let mut reader = MockReader::new(); reader.read = |_| { - read_error::cond.raise(placeholder_error()); + io_error::cond.raise(placeholder_error()); None }; - do read_error::cond.trap(|_| { + do io_error::cond.trap(|_| { }).inside { let byte = reader.read_byte(); assert!(byte == None); @@ -722,11 +722,11 @@ mod test { fn bytes_error() { let mut reader = MockReader::new(); reader.read = |_| { - read_error::cond.raise(placeholder_error()); + io_error::cond.raise(placeholder_error()); None }; let mut it = reader.bytes(); - do read_error::cond.trap(|_| ()).inside { + do io_error::cond.trap(|_| ()).inside { let byte = it.next(); assert!(byte == None); } @@ -765,7 +765,7 @@ mod test { #[test] fn read_bytes_eof() { let mut reader = MemReader::new(~[10, 11]); - do read_error::cond.trap(|_| { + do io_error::cond.trap(|_| { }).inside { assert!(reader.read_bytes(4) == ~[10, 11]); } @@ -806,7 +806,7 @@ mod test { fn push_bytes_eof() { let mut reader = MemReader::new(~[10, 11]); let mut buf = ~[8, 9]; - do read_error::cond.trap(|_| { + do io_error::cond.trap(|_| { }).inside { reader.push_bytes(&mut buf, 4); assert!(buf == ~[8, 9, 10, 11]); @@ -824,13 +824,13 @@ mod test { buf[0] = 10; Some(1) } else { - read_error::cond.raise(placeholder_error()); + io_error::cond.raise(placeholder_error()); None } } }; let mut buf = ~[8, 9]; - do read_error::cond.trap(|_| { } ).inside { + do io_error::cond.trap(|_| { } ).inside { reader.push_bytes(&mut buf, 4); } assert!(buf == ~[8, 9, 10]); @@ -850,7 +850,7 @@ mod test { buf[0] = 10; Some(1) } else { - read_error::cond.raise(placeholder_error()); + io_error::cond.raise(placeholder_error()); None } } @@ -903,7 +903,7 @@ mod test { buf[1] = 11; Some(2) } else { - read_error::cond.raise(placeholder_error()); + io_error::cond.raise(placeholder_error()); None } } diff --git a/src/libstd/rt/io/file.rs b/src/libstd/rt/io/file.rs index 0bd0213b5b0..381fa9f2d07 100644 --- a/src/libstd/rt/io/file.rs +++ b/src/libstd/rt/io/file.rs @@ -19,7 +19,7 @@ on a `ToCStr` object. This trait is already defined for common objects such as strings and `Path` instances. All operations in this module, including those as part of `FileStream` et al -block the task during execution. Most will raise `std::rt::io::{io_error,read_error}` +block the task during execution. Most will raise `std::rt::io::{io_error,io_error}` conditions in the event of failure. Also included in this module are the `FileInfo` and `DirectoryInfo` traits. When @@ -35,7 +35,7 @@ use c_str::ToCStr; use super::{Reader, Writer, Seek}; use super::{SeekStyle, Read, Write}; use rt::rtio::{RtioFileStream, IoFactory, with_local_io}; -use rt::io::{io_error, read_error, EndOfFile, +use rt::io::{io_error, EndOfFile, FileMode, FileAccess, FileStat, IoError, PathAlreadyExists, PathDoesntExist, MismatchedFileTypeForOperation, ignore_io_error}; @@ -361,7 +361,7 @@ impl Reader for FileStream { Err(ioerr) => { // EOF is indicated by returning None if ioerr.kind != EndOfFile { - read_error::cond.raise(ioerr); + io_error::cond.raise(ioerr); } return None; } @@ -388,7 +388,7 @@ impl Writer for FileStream { match self.fd.flush() { Ok(_) => (), Err(ioerr) => { - read_error::cond.raise(ioerr); + io_error::cond.raise(ioerr); } } } @@ -401,7 +401,7 @@ impl Seek for FileStream { match res { Ok(cursor) => cursor, Err(ioerr) => { - read_error::cond.raise(ioerr); + io_error::cond.raise(ioerr); return -1; } } @@ -415,7 +415,7 @@ impl Seek for FileStream { () }, Err(ioerr) => { - read_error::cond.raise(ioerr); + io_error::cond.raise(ioerr); } } } diff --git a/src/libstd/rt/io/mod.rs b/src/libstd/rt/io/mod.rs index 240210880bf..7f5b01bb1ec 100644 --- a/src/libstd/rt/io/mod.rs +++ b/src/libstd/rt/io/mod.rs @@ -404,12 +404,6 @@ condition! { pub io_error: IoError -> (); } -// XXX: Can't put doc comments on macros -// Raised by `read` on error -condition! { - pub read_error: IoError -> (); -} - /// Helper for wrapper calls where you want to /// ignore any io_errors that might be raised pub fn ignore_io_error(cb: &fn() -> T) -> T { @@ -429,7 +423,7 @@ pub trait Reader { /// /// # Failure /// - /// Raises the `read_error` condition on error. If the condition + /// 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` (XXX see below). diff --git a/src/libstd/rt/io/net/tcp.rs b/src/libstd/rt/io/net/tcp.rs index 21f98c27296..4e841b36a5d 100644 --- a/src/libstd/rt/io/net/tcp.rs +++ b/src/libstd/rt/io/net/tcp.rs @@ -12,7 +12,7 @@ use option::{Option, Some, None}; use result::{Ok, Err}; use rt::io::net::ip::SocketAddr; use rt::io::{Reader, Writer, Listener, Acceptor}; -use rt::io::{io_error, read_error, EndOfFile}; +use rt::io::{io_error, EndOfFile}; use rt::rtio::{IoFactory, with_local_io, RtioSocket, RtioTcpListener, RtioTcpAcceptor, RtioTcpStream}; @@ -67,7 +67,7 @@ impl Reader for TcpStream { Err(ioerr) => { // EOF is indicated by returning None if ioerr.kind != EndOfFile { - read_error::cond.raise(ioerr); + io_error::cond.raise(ioerr); } return None; } @@ -308,7 +308,7 @@ mod test { let mut buf = [0]; let nread = stream.read(buf); assert!(nread.is_none()); - do read_error::cond.trap(|e| { + do io_error::cond.trap(|e| { if cfg!(windows) { assert_eq!(e.kind, NotConnected); } else { @@ -343,7 +343,7 @@ mod test { let mut buf = [0]; let nread = stream.read(buf); assert!(nread.is_none()); - do read_error::cond.trap(|e| { + do io_error::cond.trap(|e| { if cfg!(windows) { assert_eq!(e.kind, NotConnected); } else { diff --git a/src/libstd/rt/io/net/udp.rs b/src/libstd/rt/io/net/udp.rs index eee5dce7b6c..2e4ae95d98e 100644 --- a/src/libstd/rt/io/net/udp.rs +++ b/src/libstd/rt/io/net/udp.rs @@ -12,7 +12,7 @@ use option::{Option, Some, None}; use result::{Ok, Err}; use rt::io::net::ip::SocketAddr; use rt::io::{Reader, Writer}; -use rt::io::{io_error, read_error, EndOfFile}; +use rt::io::{io_error, EndOfFile}; use rt::rtio::{RtioSocket, RtioUdpSocket, IoFactory, with_local_io}; pub struct UdpSocket { @@ -38,7 +38,7 @@ impl UdpSocket { Err(ioerr) => { // EOF is indicated by returning None if ioerr.kind != EndOfFile { - read_error::cond.raise(ioerr); + io_error::cond.raise(ioerr); } None } diff --git a/src/libstd/rt/io/option.rs b/src/libstd/rt/io/option.rs index ecfc4a832bf..52699964b62 100644 --- a/src/libstd/rt/io/option.rs +++ b/src/libstd/rt/io/option.rs @@ -16,7 +16,7 @@ use option::*; use super::{Reader, Writer, Listener, Acceptor, Seek, SeekStyle}; -use super::{standard_error, PreviousIoError, io_error, read_error, IoError}; +use super::{standard_error, PreviousIoError, io_error, IoError}; fn prev_io_error() -> IoError { standard_error(PreviousIoError) @@ -43,7 +43,7 @@ impl Reader for Option { match *self { Some(ref mut reader) => reader.read(buf), None => { - read_error::cond.raise(prev_io_error()); + io_error::cond.raise(prev_io_error()); None } } @@ -107,7 +107,7 @@ mod test { use option::*; use super::super::mem::*; use rt::test::*; - use super::super::{PreviousIoError, io_error, read_error}; + use super::super::{PreviousIoError, io_error, io_error}; #[test] fn test_option_writer() { @@ -161,7 +161,7 @@ mod test { let mut buf = []; let mut called = false; - do read_error::cond.trap(|err| { + do io_error::cond.trap(|err| { assert_eq!(err.kind, PreviousIoError); called = true; }).inside { diff --git a/src/libstd/rt/io/pipe.rs b/src/libstd/rt/io/pipe.rs index c15fbc79da9..eba58b97c4d 100644 --- a/src/libstd/rt/io/pipe.rs +++ b/src/libstd/rt/io/pipe.rs @@ -15,7 +15,7 @@ use prelude::*; use super::{Reader, Writer}; -use rt::io::{io_error, read_error, EndOfFile}; +use rt::io::{io_error, EndOfFile}; use rt::rtio::RtioPipe; pub struct PipeStream { @@ -35,7 +35,7 @@ impl Reader for PipeStream { Err(ioerr) => { // EOF is indicated by returning None if ioerr.kind != EndOfFile { - read_error::cond.raise(ioerr); + io_error::cond.raise(ioerr); } return None; } diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index df177cf75dc..047fc541ba8 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -93,7 +93,7 @@ pub fn expand_include_str(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) let file = get_single_str_from_tts(cx, sp, tts, "include_str!"); let file = res_rel_file(cx, sp, &Path::new(file)); let mut error = None; - let bytes = do io::read_error::cond.trap(|e| error = Some(e)).inside { + let bytes = do io::io_error::cond.trap(|e| error = Some(e)).inside { file.open_reader(io::Open).read_to_end() }; match error { @@ -120,10 +120,8 @@ pub fn expand_include_bin(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) let file = res_rel_file(cx, sp, &Path::new(file)); let mut error = None; - let bytes = do io::read_error::cond.trap(|e| error = Some(e)).inside { - do io::io_error::cond.trap(|e| error = Some(e)).inside { - file.open_reader(io::Open).read_to_end() - } + let bytes = do io::io_error::cond.trap(|e| error = Some(e)).inside { + file.open_reader(io::Open).read_to_end() }; match error { Some(e) => { diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 93e5d3dd772..fad9eab7542 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -271,9 +271,7 @@ pub fn file_to_filemap(sess: @mut ParseSess, path: &Path, spanopt: Option) }; let mut error = None; let bytes = do io::io_error::cond.trap(|e| error = Some(e)).inside { - do io::read_error::cond.trap(|e| error = Some(e)).inside { - path.open_reader(io::Open).read_to_end() - } + path.open_reader(io::Open).read_to_end() }; match error { Some(e) => { -- cgit 1.4.1-3-g733a5 From 620ab3853abf99ecea3a3d055f47cd6d06433c95 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Thu, 17 Oct 2013 21:08:48 -0700 Subject: Test fixes and merge conflicts --- doc/tutorial-conditions.md | 10 ++-- doc/tutorial-tasks.md | 1 - doc/tutorial.md | 4 +- src/libstd/os.rs | 4 +- src/libstd/rt/io/native/file.rs | 18 +++++-- src/libstd/rt/io/net/addrinfo.rs | 7 ++- src/libstd/rt/util.rs | 20 ++++--- src/libstd/rt/uv/addrinfo.rs | 14 ++++- src/libstd/rt/uv/mod.rs | 7 +++ src/libstd/rt/uv/net.rs | 53 ++++++++++--------- src/libstd/rt/uv/uvio.rs | 2 +- src/libstd/rt/uv/uvll.rs | 25 ++++----- src/libstd/run.rs | 17 ++---- src/libsyntax/ext/source_util.rs | 1 + src/rt/rust_uv.cpp | 13 ----- src/rt/rustrt.def.in | 12 ----- src/test/bench/shootout-fasta.rs | 3 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 75 ++++++++++++++------------- src/test/bench/sudoku.rs | 20 ++++--- 19 files changed, 158 insertions(+), 148 deletions(-) (limited to 'src/libsyntax') diff --git a/doc/tutorial-conditions.md b/doc/tutorial-conditions.md index 726b8bb2b80..056d967ae6c 100644 --- a/doc/tutorial-conditions.md +++ b/doc/tutorial-conditions.md @@ -43,7 +43,7 @@ $ ./example numbers.txt An example program that does this task reads like this: -~~~~ +~~~~{.xfail-test} # #[allow(unused_imports)]; extern mod extra; use extra::fileinput::FileInput; @@ -430,7 +430,7 @@ To trap a condition, use `Condition::trap` in some caller of the site that calls For example, this version of the program traps the `malformed_line` condition and replaces bad input lines with the pair `(-1,-1)`: -~~~~ +~~~~{.xfail-test} # #[allow(unused_imports)]; extern mod extra; use extra::fileinput::FileInput; @@ -507,7 +507,7 @@ In the example program, the first form of the `malformed_line` API implicitly as This assumption may not be correct; some callers may wish to skip malformed lines, for example. Changing the condition's return type from `(int,int)` to `Option<(int,int)>` will suffice to support this type of recovery: -~~~~ +~~~~{.xfail-test} # #[allow(unused_imports)]; extern mod extra; use extra::fileinput::FileInput; @@ -594,7 +594,7 @@ until all relevant combinations encountered in practice are encoded. In the example, suppose a third possible recovery form arose: reusing the previous value read. This can be encoded in the handler API by introducing a helper type: `enum MalformedLineFix`. -~~~~ +~~~~{.xfail-test} # #[allow(unused_imports)]; extern mod extra; use extra::fileinput::FileInput; @@ -720,7 +720,7 @@ task failed at 'called `Option::unwrap()` on a `None` value', .../libs To make the program robust -- or at least flexible -- in the face of this potential failure, a second condition and a helper function will suffice: -~~~~ +~~~~{.xfail-test} # #[allow(unused_imports)]; extern mod extra; use extra::fileinput::FileInput; diff --git a/doc/tutorial-tasks.md b/doc/tutorial-tasks.md index 767f712a8d8..4983a5af3e5 100644 --- a/doc/tutorial-tasks.md +++ b/doc/tutorial-tasks.md @@ -69,7 +69,6 @@ calling the `spawn` function with a closure argument. `spawn` executes the closure in the new task. ~~~~ -# use std::io::println; # use std::task::spawn; // Print something profound in a different task using a named function diff --git a/doc/tutorial.md b/doc/tutorial.md index 7451919c5be..f9f110c122b 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -2907,12 +2907,12 @@ you just have to import it with an `use` statement. For example, it re-exports `println` which is defined in `std::io::println`: ~~~ -use puts = std::io::println; +use puts = std::rt::io::stdio::println; fn main() { println("println is imported per default."); puts("Doesn't hinder you from importing it under an different name yourself."); - ::std::io::println("Or from not using the automatic import."); + ::std::rt::io::stdio::println("Or from not using the automatic import."); } ~~~ diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 99930b39a65..1f32c6a0a35 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -189,6 +189,8 @@ pub fn env() -> ~[(~str,~str)] { #[cfg(windows)] unsafe fn get_env_pairs() -> ~[~str] { #[fixed_stack_segment]; #[inline(never)]; + use c_str; + use str::StrSlice; use libc::funcs::extra::kernel32::{ GetEnvironmentStringsA, @@ -201,7 +203,7 @@ pub fn env() -> ~[(~str,~str)] { } let mut result = ~[]; do c_str::from_c_multistring(ch as *libc::c_char, None) |cstr| { - result.push(cstr.as_str().to_owned()); + result.push(cstr.as_str().unwrap().to_owned()); }; FreeEnvironmentStringsA(ch); result diff --git a/src/libstd/rt/io/native/file.rs b/src/libstd/rt/io/native/file.rs index a2b2289679a..ba819df071a 100644 --- a/src/libstd/rt/io/native/file.rs +++ b/src/libstd/rt/io/native/file.rs @@ -17,9 +17,18 @@ use os; use prelude::*; use super::super::*; -fn raise_error() { +#[cfg(windows)] +fn get_err(errno: i32) -> (IoErrorKind, &'static str) { + match errno { + libc::EOF => (EndOfFile, "end of file"), + _ => (OtherIoError, "unknown error"), + } +} + +#[cfg(not(windows))] +fn get_err(errno: i32) -> (IoErrorKind, &'static str) { // XXX: this should probably be a bit more descriptive... - let (kind, desc) = match os::errno() as i32 { + match errno { libc::EOF => (EndOfFile, "end of file"), // These two constants can have the same value on some systems, but @@ -28,8 +37,11 @@ fn raise_error() { (ResourceUnavailable, "resource temporarily unavailable"), _ => (OtherIoError, "unknown error"), - }; + } +} +fn raise_error() { + let (kind, desc) = get_err(os::errno() as i32); io_error::cond.raise(IoError { kind: kind, desc: desc, diff --git a/src/libstd/rt/io/net/addrinfo.rs b/src/libstd/rt/io/net/addrinfo.rs index e0c92730cd9..27cf9781c9c 100644 --- a/src/libstd/rt/io/net/addrinfo.rs +++ b/src/libstd/rt/io/net/addrinfo.rs @@ -91,8 +91,11 @@ pub fn get_host_addresses(host: &str) -> Option<~[IpAddr]> { /// # Failure /// /// On failure, this will raise on the `io_error` condition. -pub fn lookup(hostname: Option<&str>, servname: Option<&str>, - hint: Option) -> Option<~[Info]> { +/// +/// XXX: 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) -> Option<~[Info]> { do with_local_io |io| { match io.get_host_addresses(hostname, servname, hint) { Ok(i) => Some(i), diff --git a/src/libstd/rt/util.rs b/src/libstd/rt/util.rs index e859f8e4fdb..070985fb0a5 100644 --- a/src/libstd/rt/util.rs +++ b/src/libstd/rt/util.rs @@ -72,16 +72,22 @@ pub fn default_sched_threads() -> uint { pub fn dumb_println(args: &fmt::Arguments) { use rt::io::native::stdio::stderr; use rt::io::{Writer, io_error, ResourceUnavailable}; + use rt::task::Task; + use rt::local::Local; let mut out = stderr(); - let mut again = true; - do io_error::cond.trap(|e| { - again = e.kind == ResourceUnavailable; - }).inside { - while again { - again = false; - fmt::writeln(&mut out as &mut Writer, args); + if Local::exists(None::) { + let mut again = true; + do io_error::cond.trap(|e| { + again = e.kind == ResourceUnavailable; + }).inside { + while again { + again = false; + fmt::writeln(&mut out as &mut Writer, args); + } } + } else { + fmt::writeln(&mut out as &mut Writer, args); } } diff --git a/src/libstd/rt/uv/addrinfo.rs b/src/libstd/rt/uv/addrinfo.rs index 7556d7db665..a1593d5c8db 100644 --- a/src/libstd/rt/uv/addrinfo.rs +++ b/src/libstd/rt/uv/addrinfo.rs @@ -73,13 +73,14 @@ impl GetAddrInfoRequest { cb(req, addrinfo, err) }; - let hint = hints.map(|hint| unsafe { + let hint = hints.map(|hint| { let mut flags = 0; do each_ai_flag |cval, aival| { if hint.flags & (aival as uint) != 0 { flags |= cval as i32; } } + /* XXX: do we really want to support these? let socktype = match hint.socktype { Some(ai::Stream) => uvll::rust_SOCK_STREAM(), Some(ai::Datagram) => uvll::rust_SOCK_DGRAM(), @@ -91,6 +92,9 @@ impl GetAddrInfoRequest { Some(ai::TCP) => uvll::rust_IPPROTO_TCP(), _ => 0, }; + */ + let socktype = 0; + let protocol = 0; uvll::addrinfo { ai_flags: flags, @@ -167,7 +171,8 @@ impl GetAddrInfoRequest { } } -fn each_ai_flag(f: &fn(c_int, ai::Flag)) { +fn each_ai_flag(_f: &fn(c_int, ai::Flag)) { + /* XXX: do we really want to support these? unsafe { f(uvll::rust_AI_ADDRCONFIG(), ai::AddrConfig); f(uvll::rust_AI_ALL(), ai::All); @@ -177,6 +182,7 @@ fn each_ai_flag(f: &fn(c_int, ai::Flag)) { f(uvll::rust_AI_PASSIVE(), ai::Passive); f(uvll::rust_AI_V4MAPPED(), ai::V4Mapped); } + */ } // Traverse the addrinfo linked list, producing a vector of Rust socket addresses @@ -197,6 +203,7 @@ pub fn accum_addrinfo(addr: &net::UvAddrInfo) -> ~[ai::Info] { } } + /* XXX: do we really want to support these let protocol = match (*addr).ai_protocol { p if p == uvll::rust_IPPROTO_UDP() => Some(ai::UDP), p if p == uvll::rust_IPPROTO_TCP() => Some(ai::TCP), @@ -208,6 +215,9 @@ pub fn accum_addrinfo(addr: &net::UvAddrInfo) -> ~[ai::Info] { p if p == uvll::rust_SOCK_RAW() => Some(ai::Raw), _ => None, }; + */ + let protocol = None; + let socktype = None; addrs.push(ai::Info { address: rustaddr, diff --git a/src/libstd/rt/uv/mod.rs b/src/libstd/rt/uv/mod.rs index 18c99157707..88bb28d3763 100644 --- a/src/libstd/rt/uv/mod.rs +++ b/src/libstd/rt/uv/mod.rs @@ -336,6 +336,13 @@ pub fn status_to_maybe_uv_error(status: c_int) -> Option /// The uv buffer type pub type Buf = uvll::uv_buf_t; +pub fn empty_buf() -> Buf { + uvll::uv_buf_t { + base: null(), + len: 0, + } +} + /// Borrow a slice to a Buf pub fn slice_to_uv_buf(v: &[u8]) -> Buf { let data = vec::raw::to_ptr(v); diff --git a/src/libstd/rt/uv/net.rs b/src/libstd/rt/uv/net.rs index 22d7c9c61b3..77de8348c14 100644 --- a/src/libstd/rt/uv/net.rs +++ b/src/libstd/rt/uv/net.rs @@ -14,7 +14,7 @@ use rt::uv::uvll; use rt::uv::uvll::*; use rt::uv::{AllocCallback, ConnectionCallback, ReadCallback, UdpReceiveCallback, UdpSendCallback}; use rt::uv::{Loop, Watcher, Request, UvError, Buf, NativeHandle, - status_to_maybe_uv_error, vec_to_uv_buf}; + status_to_maybe_uv_error, empty_buf}; use rt::io::net::ip::{SocketAddr, Ipv4Addr, Ipv6Addr}; use vec; use str; @@ -119,23 +119,17 @@ impl Watcher for StreamWatcher { } impl StreamWatcher { pub fn read_start(&mut self, alloc: AllocCallback, cb: ReadCallback) { - { - let data = self.get_watcher_data(); - data.alloc_cb = Some(alloc); - data.read_cb = Some(cb); - } - - let ret = unsafe { uvll::read_start(self.native_handle(), alloc_cb, read_cb) }; - - if ret != 0 { - // uvll::read_start failed, so read_cb will not be called. - // Call it manually for scheduling. - call_read_cb(self.native_handle(), ret as ssize_t); - } - - fn call_read_cb(stream: *uvll::uv_stream_t, errno: ssize_t) { - #[fixed_stack_segment]; #[inline(never)]; - read_cb(stream, errno, vec_to_uv_buf(~[])); + unsafe { + match uvll::read_start(self.native_handle(), alloc_cb, read_cb) { + 0 => { + let data = self.get_watcher_data(); + data.alloc_cb = Some(alloc); + data.read_cb = Some(cb); + } + n => { + cb(*self, 0, empty_buf(), Some(UvError(n))) + } + } } extern fn alloc_cb(stream: *uvll::uv_stream_t, suggested_size: size_t) -> Buf { @@ -163,16 +157,21 @@ impl StreamWatcher { } pub fn write(&mut self, buf: Buf, cb: ConnectionCallback) { - { - let data = self.get_watcher_data(); - assert!(data.write_cb.is_none()); - data.write_cb = Some(cb); - } - let req = WriteRequest::new(); - unsafe { - assert_eq!(0, uvll::write(req.native_handle(), self.native_handle(), [buf], write_cb)); - } + return unsafe { + match uvll::write(req.native_handle(), self.native_handle(), + [buf], write_cb) { + 0 => { + let data = self.get_watcher_data(); + assert!(data.write_cb.is_none()); + data.write_cb = Some(cb); + } + n => { + req.delete(); + cb(*self, Some(UvError(n))) + } + } + }; extern fn write_cb(req: *uvll::uv_write_t, status: c_int) { let write_request: WriteRequest = NativeHandle::from_native_handle(req); diff --git a/src/libstd/rt/uv/uvio.rs b/src/libstd/rt/uv/uvio.rs index 0d22aa51be5..f12b1bce9e6 100644 --- a/src/libstd/rt/uv/uvio.rs +++ b/src/libstd/rt/uv/uvio.rs @@ -229,7 +229,7 @@ impl EventLoop for UvEventLoop { } } - fn remote_callback(&mut self, f: ~fn()) -> ~RemoteCallback{ + fn remote_callback(&mut self, f: ~fn()) -> ~RemoteCallback { ~UvRemoteCallback::new(self.uvio.uv_loop(), f) as ~RemoteCallback } diff --git a/src/libstd/rt/uv/uvll.rs b/src/libstd/rt/uv/uvll.rs index 8f8aea9d121..f3e14dc314b 100644 --- a/src/libstd/rt/uv/uvll.rs +++ b/src/libstd/rt/uv/uvll.rs @@ -1146,17 +1146,18 @@ extern { height: *c_int) -> c_int; fn rust_uv_guess_handle(fd: c_int) -> uv_handle_type; + // XXX: see comments in addrinfo.rs // These should all really be constants... - #[rust_stack] pub fn rust_SOCK_STREAM() -> c_int; - #[rust_stack] pub fn rust_SOCK_DGRAM() -> c_int; - #[rust_stack] pub fn rust_SOCK_RAW() -> c_int; - #[rust_stack] pub fn rust_IPPROTO_UDP() -> c_int; - #[rust_stack] pub fn rust_IPPROTO_TCP() -> c_int; - #[rust_stack] pub fn rust_AI_ADDRCONFIG() -> c_int; - #[rust_stack] pub fn rust_AI_ALL() -> c_int; - #[rust_stack] pub fn rust_AI_CANONNAME() -> c_int; - #[rust_stack] pub fn rust_AI_NUMERICHOST() -> c_int; - #[rust_stack] pub fn rust_AI_NUMERICSERV() -> c_int; - #[rust_stack] pub fn rust_AI_PASSIVE() -> c_int; - #[rust_stack] pub fn rust_AI_V4MAPPED() -> c_int; + //#[rust_stack] pub fn rust_SOCK_STREAM() -> c_int; + //#[rust_stack] pub fn rust_SOCK_DGRAM() -> c_int; + //#[rust_stack] pub fn rust_SOCK_RAW() -> c_int; + //#[rust_stack] pub fn rust_IPPROTO_UDP() -> c_int; + //#[rust_stack] pub fn rust_IPPROTO_TCP() -> c_int; + //#[rust_stack] pub fn rust_AI_ADDRCONFIG() -> c_int; + //#[rust_stack] pub fn rust_AI_ALL() -> c_int; + //#[rust_stack] pub fn rust_AI_CANONNAME() -> c_int; + //#[rust_stack] pub fn rust_AI_NUMERICHOST() -> c_int; + //#[rust_stack] pub fn rust_AI_NUMERICSERV() -> c_int; + //#[rust_stack] pub fn rust_AI_PASSIVE() -> c_int; + //#[rust_stack] pub fn rust_AI_V4MAPPED() -> c_int; } diff --git a/src/libstd/run.rs b/src/libstd/run.rs index c4cb8be2061..d5f8e82b90f 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -19,6 +19,7 @@ use libc; use prelude::*; use rt::io::native::process; use rt::io; +use rt::io::extensions::ReaderUtil; use task; /** @@ -189,18 +190,6 @@ impl Process { let output = Cell::new(self.inner.take_output()); let error = Cell::new(self.inner.take_error()); - fn read_everything(r: &mut io::Reader) -> ~[u8] { - let mut ret = ~[]; - let mut buf = [0, ..1024]; - loop { - match r.read(buf) { - Some(n) => { ret.push_all(buf.slice_to(n)); } - None => break - } - } - return ret; - } - // Spawn two entire schedulers to read both stdout and sterr // in parallel so we don't deadlock while blocking on one // or the other. FIXME (#2625): Surely there's a much more @@ -210,13 +199,13 @@ impl Process { let ch_clone = ch.clone(); do task::spawn_sched(task::SingleThreaded) { match error.take() { - Some(ref mut e) => ch.send((2, read_everything(*e))), + Some(ref mut e) => ch.send((2, e.read_to_end())), None => ch.send((2, ~[])) } } do task::spawn_sched(task::SingleThreaded) { match output.take() { - Some(ref mut e) => ch_clone.send((1, read_everything(*e))), + Some(ref mut e) => ch_clone.send((1, e.read_to_end())), None => ch_clone.send((1, ~[])) } } diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 047fc541ba8..119a74cccd6 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -129,6 +129,7 @@ pub fn expand_include_bin(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) file.display(), e.desc)); } None => { + let bytes = at_vec::to_managed_move(bytes); base::MRExpr(cx.expr_lit(sp, ast::lit_binary(bytes))) } } diff --git a/src/rt/rust_uv.cpp b/src/rt/rust_uv.cpp index 7ab57e6909a..55fa09c3818 100644 --- a/src/rt/rust_uv.cpp +++ b/src/rt/rust_uv.cpp @@ -638,19 +638,6 @@ rust_uv_pipe_init(uv_loop_t *loop, uv_pipe_t* p, int ipc) { return uv_pipe_init(loop, p, ipc); } -extern "C" int rust_SOCK_STREAM() { return SOCK_STREAM; } -extern "C" int rust_SOCK_DGRAM() { return SOCK_DGRAM; } -extern "C" int rust_SOCK_RAW() { return SOCK_RAW; } -extern "C" int rust_IPPROTO_UDP() { return IPPROTO_UDP; } -extern "C" int rust_IPPROTO_TCP() { return IPPROTO_TCP; } -extern "C" int rust_AI_ADDRCONFIG() { return AI_ADDRCONFIG; } -extern "C" int rust_AI_ALL() { return AI_ALL; } -extern "C" int rust_AI_CANONNAME() { return AI_CANONNAME; } -extern "C" int rust_AI_NUMERICHOST() { return AI_NUMERICHOST; } -extern "C" int rust_AI_NUMERICSERV() { return AI_NUMERICSERV; } -extern "C" int rust_AI_PASSIVE() { return AI_PASSIVE; } -extern "C" int rust_AI_V4MAPPED() { return AI_V4MAPPED; } - extern "C" int rust_uv_pipe_open(uv_pipe_t *pipe, int file) { return uv_pipe_open(pipe, file); diff --git a/src/rt/rustrt.def.in b/src/rt/rustrt.def.in index 6c3988d6b01..203f2e4d5f2 100644 --- a/src/rt/rustrt.def.in +++ b/src/rt/rustrt.def.in @@ -199,18 +199,6 @@ bufrelease bufnew rust_take_dlerror_lock rust_drop_dlerror_lock -rust_SOCK_STREAM -rust_SOCK_DGRAM -rust_SOCK_RAW -rust_IPPROTO_UDP -rust_IPPROTO_TCP -rust_AI_ADDRCONFIG -rust_AI_ALL -rust_AI_CANONNAME -rust_AI_NUMERICHOST -rust_AI_NUMERICSERV -rust_AI_PASSIVE -rust_AI_V4MAPPED rust_uv_pipe_open rust_uv_pipe_bind rust_uv_pipe_connect diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index 3d1362b2f29..52f068b8b1c 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -111,6 +111,7 @@ fn acid(ch: char, prob: u32) -> AminoAcids { } fn main() { + use std::rt::io::file::FileInfo; let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { // alioth tests k-nucleotide with this data at 25,000,000 @@ -122,7 +123,7 @@ fn main() { }; let writer = if os::getenv("RUST_BENCH").is_some() { - let file = "./shootout-fasta.data".open_writer(io::CreateOrTruncate); + let file = Path::new("./shootout-fasta.data").open_writer(io::CreateOrTruncate); @mut file as @mut io::Writer } else { @mut io::stdout() as @mut io::Writer diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 83a0fbd42ce..cfc78e1615e 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -20,6 +20,7 @@ use std::comm; use std::hashmap::HashMap; use std::option; use std::os; +use std::rt::io; use std::str; use std::task; use std::util; @@ -193,48 +194,48 @@ fn main() { let mut proc_mode = false; loop { - let line = match rdr.read_line() { - Some(ln) => ln, None => break, - }; - let line = line.trim().to_owned(); - - if line.len() == 0u { continue; } - - match (line[0] as char, proc_mode) { - - // start processing if this is the one - ('>', false) => { - match line.slice_from(1).find_str("THREE") { - option::Some(_) => { proc_mode = true; } - option::None => { } - } - } - - // break our processing - ('>', true) => { break; } - - // process the sequence for k-mers - (_, true) => { - let line_bytes = line.as_bytes(); - - for (ii, _sz) in sizes.iter().enumerate() { - let lb = line_bytes.to_owned(); - to_child[ii].send(lb); - } - } - - // whatever - _ => { } - } + let line = match io::ignore_io_error(|| rdr.read_line()) { + Some(ln) => ln, None => break, + }; + let line = line.trim().to_owned(); + + if line.len() == 0u { continue; } + + match (line[0] as char, proc_mode) { + + // start processing if this is the one + ('>', false) => { + match line.slice_from(1).find_str("THREE") { + option::Some(_) => { proc_mode = true; } + option::None => { } + } + } + + // break our processing + ('>', true) => { break; } + + // process the sequence for k-mers + (_, true) => { + let line_bytes = line.as_bytes(); + + for (ii, _sz) in sizes.iter().enumerate() { + let lb = line_bytes.to_owned(); + to_child[ii].send(lb); + } + } + + // whatever + _ => { } + } } // finish... - for (ii, _sz) in sizes.iter().enumerate() { - to_child[ii].send(~[]); + for (ii, _sz) in sizes.iter().enumerate() { + to_child[ii].send(~[]); } // now fetch and print result messages - for (ii, _sz) in sizes.iter().enumerate() { - println(from_child[ii].recv()); + for (ii, _sz) in sizes.iter().enumerate() { + println(from_child[ii].recv()); } } diff --git a/src/test/bench/sudoku.rs b/src/test/bench/sudoku.rs index 21d492d85fc..d4f4a46af38 100644 --- a/src/test/bench/sudoku.rs +++ b/src/test/bench/sudoku.rs @@ -15,6 +15,8 @@ extern mod extra; use std::rt::io; +use std::rt::io::stdio::StdReader; +use std::rt::io::buffered::BufferedReader; use std::os; use std::uint; use std::unstable::intrinsics::cttz16; @@ -66,12 +68,14 @@ impl Sudoku { return true; } - pub fn read(reader: @mut io::Reader) -> Sudoku { - assert!(reader.read_line() == ~"9,9"); /* assert first line is exactly "9,9" */ + pub fn read(mut reader: BufferedReader) -> Sudoku { + assert!(reader.read_line().unwrap() == ~"9,9"); /* assert first line is exactly "9,9" */ let mut g = vec::from_fn(10u, { |_i| ~[0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8] }); - while !reader.eof() { - let line = reader.read_line(); + loop { + let line = match reader.read_line() { + Some(ln) => ln, None => break + }; let comps: ~[&str] = line.trim().split_iter(',').collect(); if comps.len() == 3u { @@ -88,11 +92,11 @@ impl Sudoku { pub fn write(&self, writer: @mut io::Writer) { for row in range(0u8, 9u8) { - writer.write_str(format!("{}", self.grid[row][0] as uint)); + write!(writer, "{}", self.grid[row][0]); for col in range(1u8, 9u8) { - writer.write_str(format!(" {}", self.grid[row][col] as uint)); + write!(writer, " {}", self.grid[row][col]); } - writer.write_char('\n'); + write!(writer, "\n"); } } @@ -277,7 +281,7 @@ fn main() { let mut sudoku = if use_default { Sudoku::from_vec(&DEFAULT_SUDOKU) } else { - Sudoku::read(@mut io::stdin() as @mut io::Reader) + Sudoku::read(BufferedReader::new(io::stdin())) }; sudoku.solve(); sudoku.write(@mut io::stdout() as @mut io::Writer); -- cgit 1.4.1-3-g733a5