diff options
| author | Brian Anderson <banderson@mozilla.com> | 2015-01-27 09:38:30 -0800 |
|---|---|---|
| committer | Brian Anderson <banderson@mozilla.com> | 2015-01-27 15:05:04 -0800 |
| commit | 71223050538939ed758fcd3b9114f71abff20bb2 (patch) | |
| tree | 43ddd18223904fa86601f1a0e16ebcbaddead270 | |
| parent | 3c172392cf0c86ffd1d7b39d3f44de98f77afc44 (diff) | |
| parent | 777435990e0e91df6b72ce80c9b6fa485eeb5daa (diff) | |
| download | rust-71223050538939ed758fcd3b9114f71abff20bb2.tar.gz rust-71223050538939ed758fcd3b9114f71abff20bb2.zip | |
Merge remote-tracking branch 'rust-lang/master'
Conflicts: src/libcore/cell.rs src/librustc_driver/test.rs src/libstd/old_io/net/tcp.rs src/libstd/old_io/process.rs
219 files changed, 1891 insertions, 1431 deletions
diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index d2d1d3d8368..eedff1d1176 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -32,8 +32,8 @@ extern crate getopts; extern crate log; use std::os; -use std::io; -use std::io::fs; +use std::old_io; +use std::old_io::fs; use std::str::FromStr; use std::thunk::Thunk; use getopts::{optopt, optflag, reqopt}; @@ -245,7 +245,7 @@ pub fn run_tests(config: &Config) { // sadly osx needs some file descriptor limits raised for running tests in // parallel (especially when we have lots and lots of child processes). // For context, see #8904 - io::test::raise_fd_limit(); + old_io::test::raise_fd_limit(); // Prevent issue #21352 UAC blocking .exe containing 'patch' etc. on Windows // If #11207 is resolved (adding manifest to .exe) this becomes unnecessary os::setenv("__COMPAT_LAYER", "RunAsInvoker"); diff --git a/src/compiletest/errors.rs b/src/compiletest/errors.rs index fc815d66a4d..868512c7943 100644 --- a/src/compiletest/errors.rs +++ b/src/compiletest/errors.rs @@ -9,7 +9,7 @@ // except according to those terms. use self::WhichLine::*; -use std::io::{BufferedReader, File}; +use std::old_io::{BufferedReader, File}; pub struct ExpectedError { pub line: uint, diff --git a/src/compiletest/header.rs b/src/compiletest/header.rs index d7af767688e..8458d880d05 100644 --- a/src/compiletest/header.rs +++ b/src/compiletest/header.rs @@ -223,7 +223,7 @@ pub fn is_test_ignored(config: &Config, testfile: &Path) -> bool { fn iter_header<F>(testfile: &Path, mut it: F) -> bool where F: FnMut(&str) -> bool, { - use std::io::{BufferedReader, File}; + use std::old_io::{BufferedReader, File}; let mut rdr = BufferedReader::new(File::open(testfile).unwrap()); for ln in rdr.lines() { diff --git a/src/compiletest/procsrv.rs b/src/compiletest/procsrv.rs index f3f860d470d..7f3865308da 100644 --- a/src/compiletest/procsrv.rs +++ b/src/compiletest/procsrv.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::process::{ProcessExit, Command, Process, ProcessOutput}; +use std::old_io::process::{ProcessExit, Command, Process, ProcessOutput}; use std::dynamic_lib::DynamicLibrary; fn add_target_env(cmd: &mut Command, lib_path: &str, aux_path: Option<&str>) { @@ -47,7 +47,7 @@ pub fn run(lib_path: &str, match cmd.spawn() { Ok(mut process) => { for input in input.iter() { - process.stdin.as_mut().unwrap().write(input.as_bytes()).unwrap(); + process.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap(); } let ProcessOutput { status, output, error } = process.wait_with_output().unwrap(); @@ -79,7 +79,7 @@ pub fn run_background(lib_path: &str, match cmd.spawn() { Ok(mut process) => { for input in input.iter() { - process.stdin.as_mut().unwrap().write(input.as_bytes()).unwrap(); + process.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap(); } Some(process) diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index e5a973e7501..0ae32bd00a4 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -23,14 +23,14 @@ use util; #[cfg(target_os = "windows")] use std::ascii::AsciiExt; -use std::io::File; -use std::io::fs::PathExtensions; -use std::io::fs; -use std::io::net::tcp; -use std::io::process::ProcessExit; -use std::io::process; -use std::io::timer; -use std::io; +use std::old_io::File; +use std::old_io::fs::PathExtensions; +use std::old_io::fs; +use std::old_io::net::tcp; +use std::old_io::process::ProcessExit; +use std::old_io::process; +use std::old_io::timer; +use std::old_io; use std::os; use std::iter::repeat; use std::str; @@ -619,7 +619,7 @@ fn find_rust_src_root(config: &Config) -> Option<Path> { } fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) { - use std::io::process::{Command, ProcessOutput}; + use std::old_io::process::{Command, ProcessOutput}; if config.lldb_python_dir.is_none() { fatal("Can't run LLDB test because LLDB's python path is not set."); @@ -764,7 +764,7 @@ struct DebuggerCommands { fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str) -> DebuggerCommands { - use std::io::{BufferedReader, File}; + use std::old_io::{BufferedReader, File}; let command_directive = format!("{}-command", debugger_prefix); let check_directive = format!("{}-check", debugger_prefix); @@ -1224,7 +1224,7 @@ fn compose_and_run_compiler( fn ensure_dir(path: &Path) { if path.is_dir() { return; } - fs::mkdir(path, io::USER_RWX).unwrap(); + fs::mkdir(path, old_io::USER_RWX).unwrap(); } fn compose_and_run(config: &Config, testfile: &Path, @@ -1401,7 +1401,7 @@ fn dump_output(config: &Config, testfile: &Path, out: &str, err: &str) { fn dump_output_file(config: &Config, testfile: &Path, out: &str, extension: &str) { let outfile = make_out_name(config, testfile, extension); - File::create(&outfile).write(out.as_bytes()).unwrap(); + File::create(&outfile).write_all(out.as_bytes()).unwrap(); } fn make_out_name(config: &Config, testfile: &Path, extension: &str) -> Path { diff --git a/src/doc/trpl/guessing-game.md b/src/doc/trpl/guessing-game.md index 6f67c88f2c0..f01b62223ca 100644 --- a/src/doc/trpl/guessing-game.md +++ b/src/doc/trpl/guessing-game.md @@ -75,14 +75,14 @@ Let's get to it! The first thing we need to do for our guessing game is allow our player to input a guess. Put this in your `src/main.rs`: ```{rust,no_run} -use std::io; +use std::old_io; fn main() { println!("Guess the number!"); println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); @@ -121,7 +121,7 @@ explanatory text, and then an example. Let's try to modify our code to add in th `random` function and see what happens: ```{rust,ignore} -use std::io; +use std::old_io; use std::rand; fn main() { @@ -133,7 +133,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); @@ -180,7 +180,7 @@ This says "please give me a random `i32` value." We can change our code to use this hint: ```{rust,no_run} -use std::io; +use std::old_io; use std::rand; fn main() { @@ -192,7 +192,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); @@ -233,7 +233,7 @@ unsigned integer approach. If we want a random positive number, we should ask fo a random positive number. Our code looks like this now: ```{rust,no_run} -use std::io; +use std::old_io; use std::rand; fn main() { @@ -245,7 +245,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); @@ -276,7 +276,7 @@ two numbers. Let's add that in, along with a `match` statement to compare our guess to the secret number: ```{rust,ignore} -use std::io; +use std::old_io; use std::rand; use std::cmp::Ordering; @@ -289,7 +289,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); @@ -331,7 +331,7 @@ but we've given it unsigned integers. In this case, the fix is easy, because we wrote the `cmp` function! Let's change it to take `u32`s: ```{rust,ignore} -use std::io; +use std::old_io; use std::rand; use std::cmp::Ordering; @@ -344,7 +344,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); @@ -397,7 +397,7 @@ Anyway, we have a `String`, but we need a `u32`. What to do? Well, there's a function for that: ```{rust,ignore} -let input = io::stdin().read_line() +let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); let input_num: Option<u32> = input.parse(); @@ -429,7 +429,7 @@ let input_num: Option<u32> = "5".parse(); // input_num: Option<u32> Anyway, with us now converting our input to a number, our code looks like this: ```{rust,ignore} -use std::io; +use std::old_io; use std::rand; use std::cmp::Ordering; @@ -442,7 +442,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); let input_num: Option<u32> = input.parse(); @@ -479,7 +479,7 @@ need to unwrap the Option. If you remember from before, `match` is a great way to do that. Try this code: ```{rust,no_run} -use std::io; +use std::old_io; use std::rand; use std::cmp::Ordering; @@ -492,7 +492,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); let input_num: Option<u32> = input.parse(); @@ -546,7 +546,7 @@ method we can use defined on them: `trim()`. One small modification, and our code looks like this: ```{rust,no_run} -use std::io; +use std::old_io; use std::rand; use std::cmp::Ordering; @@ -559,7 +559,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); let input_num: Option<u32> = input.trim().parse(); @@ -620,7 +620,7 @@ As we already discussed, the `loop` keyword gives us an infinite loop. Let's add that in: ```{rust,no_run} -use std::io; +use std::old_io; use std::rand; use std::cmp::Ordering; @@ -635,7 +635,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); let input_num: Option<u32> = input.trim().parse(); @@ -696,7 +696,7 @@ Ha! `quit` actually quits. As does any other non-number input. Well, this is suboptimal to say the least. First, let's actually quit when you win the game: ```{rust,no_run} -use std::io; +use std::old_io; use std::rand; use std::cmp::Ordering; @@ -711,7 +711,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); let input_num: Option<u32> = input.trim().parse(); @@ -752,7 +752,7 @@ we don't want to quit, we just want to ignore it. Change that `return` to ```{rust,no_run} -use std::io; +use std::old_io; use std::rand; use std::cmp::Ordering; @@ -767,7 +767,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); let input_num: Option<u32> = input.trim().parse(); @@ -831,7 +831,7 @@ think of what it is? That's right, we don't want to print out the secret number. It was good for testing, but it kind of ruins the game. Here's our final source: ```{rust,no_run} -use std::io; +use std::old_io; use std::rand; use std::cmp::Ordering; @@ -844,7 +844,7 @@ fn main() { println!("Please input your guess."); - let input = io::stdin().read_line() + let input = old_io::stdin().read_line() .ok() .expect("Failed to read line"); let input_num: Option<u32> = input.trim().parse(); diff --git a/src/doc/trpl/standard-input.md b/src/doc/trpl/standard-input.md index 7145139bba5..0c26fb2b44f 100644 --- a/src/doc/trpl/standard-input.md +++ b/src/doc/trpl/standard-input.md @@ -8,7 +8,7 @@ and then prints it back out: fn main() { println!("Type something!"); - let input = std::io::stdin().read_line().ok().expect("Failed to read line"); + let input = std::old_io::stdin().read_line().ok().expect("Failed to read line"); println!("{}", input); } @@ -17,7 +17,7 @@ fn main() { Let's go over these chunks, one by one: ```{rust,ignore} -std::io::stdin(); +std::old_io::stdin(); ``` This calls a function, `stdin()`, that lives inside the `std::io` module. As @@ -28,7 +28,7 @@ Since writing the fully qualified name all the time is annoying, we can use the `use` statement to import it in: ```{rust} -use std::io::stdin; +use std::old_io::stdin; stdin(); ``` @@ -37,20 +37,20 @@ However, it's considered better practice to not import individual functions, but to import the module, and only use one level of qualification: ```{rust} -use std::io; +use std::old_io; -io::stdin(); +old_io::stdin(); ``` Let's update our example to use this style: ```{rust,ignore} -use std::io; +use std::old_io; fn main() { println!("Type something!"); - let input = io::stdin().read_line().ok().expect("Failed to read line"); + let input = old_io::stdin().read_line().ok().expect("Failed to read line"); println!("{}", input); } @@ -121,12 +121,12 @@ For now, this gives you enough of a basic understanding to work with. Back to the code we were working on! Here's a refresher: ```{rust,ignore} -use std::io; +use std::old_io; fn main() { println!("Type something!"); - let input = io::stdin().read_line().ok().expect("Failed to read line"); + let input = old_io::stdin().read_line().ok().expect("Failed to read line"); println!("{}", input); } @@ -136,14 +136,14 @@ With long lines like this, Rust gives you some flexibility with the whitespace. We _could_ write the example like this: ```{rust,ignore} -use std::io; +use std::old_io; fn main() { println!("Type something!"); // here, we'll show the types at each step - let input = io::stdin() // std::io::stdio::StdinReader + let input = old_io::stdin() // std::old_io::stdio::StdinReader .read_line() // IoResult<String> .ok() // Option<String> .expect("Failed to read line"); // String diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index ddcc41938f2..02cc4038a69 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -10,39 +10,30 @@ //! Shareable mutable containers. //! -//! Values of the `Cell` and `RefCell` types may be mutated through -//! shared references (i.e. the common `&T` type), whereas most Rust -//! types can only be mutated through unique (`&mut T`) references. We -//! say that `Cell` and `RefCell` provide *interior mutability*, in -//! contrast with typical Rust types that exhibit *inherited -//! mutability*. +//! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e. +//! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`) +//! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast +//! with typical Rust types that exhibit 'inherited mutability'. //! -//! Cell types come in two flavors: `Cell` and `RefCell`. `Cell` -//! provides `get` and `set` methods that change the -//! interior value with a single method call. `Cell` though is only -//! compatible with types that implement `Copy`. For other types, -//! one must use the `RefCell` type, acquiring a write lock before -//! mutating. +//! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` provides `get` and `set` +//! methods that change the interior value with a single method call. `Cell<T>` though is only +//! compatible with types that implement `Copy`. For other types, one must use the `RefCell<T>` +//! type, acquiring a write lock before mutating. //! -//! `RefCell` uses Rust's lifetimes to implement *dynamic borrowing*, -//! a process whereby one can claim temporary, exclusive, mutable -//! access to the inner value. Borrows for `RefCell`s are tracked *at -//! runtime*, unlike Rust's native reference types which are entirely -//! tracked statically, at compile time. Because `RefCell` borrows are -//! dynamic it is possible to attempt to borrow a value that is -//! already mutably borrowed; when this happens it results in task -//! panic. +//! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can +//! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are +//! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked +//! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt +//! to borrow a value that is already mutably borrowed; when this happens it results in task panic. //! //! # When to choose interior mutability //! -//! The more common inherited mutability, where one must have unique -//! access to mutate a value, is one of the key language elements that -//! enables Rust to reason strongly about pointer aliasing, statically -//! preventing crash bugs. Because of that, inherited mutability is -//! preferred, and interior mutability is something of a last -//! resort. Since cell types enable mutation where it would otherwise -//! be disallowed though, there are occasions when interior -//! mutability might be appropriate, or even *must* be used, e.g. +//! The more common inherited mutability, where one must have unique access to mutate a value, is +//! one of the key language elements that enables Rust to reason strongly about pointer aliasing, +//! statically preventing crash bugs. Because of that, inherited mutability is preferred, and +//! interior mutability is something of a last resort. Since cell types enable mutation where it +//! would otherwise be disallowed though, there are occasions when interior mutability might be +//! appropriate, or even *must* be used, e.g. //! //! * Introducing inherited mutability roots to shared types. //! * Implementation details of logically-immutable methods. @@ -50,15 +41,13 @@ //! //! ## Introducing inherited mutability roots to shared types //! -//! Shared smart pointer types, including `Rc` and `Arc`, provide -//! containers that can be cloned and shared between multiple parties. -//! Because the contained values may be multiply-aliased, they can -//! only be borrowed as shared references, not mutable references. -//! Without cells it would be impossible to mutate data inside of -//! shared boxes at all! +//! Shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be +//! cloned and shared between multiple parties. Because the contained values may be +//! multiply-aliased, they can only be borrowed as shared references, not mutable references. +//! Without cells it would be impossible to mutate data inside of shared boxes at all! //! -//! It's very common then to put a `RefCell` inside shared pointer -//! types to reintroduce mutability: +//! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce +//! mutability: //! //! ``` //! use std::collections::HashMap; @@ -80,12 +69,10 @@ //! //! ## Implementation details of logically-immutable methods //! -//! Occasionally it may be desirable not to expose in an API that -//! there is mutation happening "under the hood". This may be because -//! logically the operation is immutable, but e.g. caching forces the -//! implementation to perform mutation; or because you must employ -//! mutation to implement a trait method that was originally defined -//! to take `&self`. +//! Occasionally it may be desirable not to expose in an API that there is mutation happening +//! "under the hood". This may be because logically the operation is immutable, but e.g. caching +//! forces the implementation to perform mutation; or because you must employ mutation to implement +//! a trait method that was originally defined to take `&self`. //! //! ``` //! use std::cell::RefCell; @@ -123,13 +110,11 @@ //! //! ## Mutating implementations of `clone` //! -//! This is simply a special - but common - case of the previous: -//! hiding mutability for operations that appear to be immutable. -//! The `clone` method is expected to not change the source value, and -//! is declared to take `&self`, not `&mut self`. Therefore any -//! mutation that happens in the `clone` method must use cell -//! types. For example, `Rc` maintains its reference counts within a -//! `Cell`. +//! This is simply a special - but common - case of the previous: hiding mutability for operations +//! that appear to be immutable. The `clone` method is expected to not change the source value, and +//! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the +//! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a +//! `Cell<T>`. //! //! ``` //! use std::cell::Cell; @@ -153,10 +138,6 @@ //! } //! ``` //! -// FIXME: Explain difference between Cell and RefCell -// FIXME: Downsides to interior mutability -// FIXME: Can't be shared between threads. Dynamic borrows -// FIXME: Relationship to Atomic types and RWLock #![stable(feature = "rust1", since = "1.0.0")] @@ -169,6 +150,8 @@ use option::Option; use option::Option::{None, Some}; /// A mutable memory location that admits only `Copy` data. +/// +/// See the [module-level documentation](../index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct Cell<T> { value: UnsafeCell<T>, @@ -176,6 +159,14 @@ pub struct Cell<T> { impl<T:Copy> Cell<T> { /// Creates a new `Cell` containing the given value. + /// + /// # Examples + /// + /// ``` + /// use std::cell::Cell; + /// + /// let c = Cell::new(5); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> Cell<T> { Cell { @@ -184,6 +175,16 @@ impl<T:Copy> Cell<T> { } /// Returns a copy of the contained value. + /// + /// # Examples + /// + /// ``` + /// use std::cell::Cell; + /// + /// let c = Cell::new(5); + /// + /// let five = c.get(); + /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn get(&self) -> T { @@ -191,6 +192,16 @@ impl<T:Copy> Cell<T> { } /// Sets the contained value. + /// + /// # Examples + /// + /// ``` + /// use std::cell::Cell; + /// + /// let c = Cell::new(5); + /// + /// c.set(10); + /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn set(&self, value: T) { @@ -201,9 +212,19 @@ impl<T:Copy> Cell<T> { /// Get a reference to the underlying `UnsafeCell`. /// - /// This can be used to circumvent `Cell`'s safety checks. + /// # Unsafety /// /// This function is `unsafe` because `UnsafeCell`'s field is public. + /// + /// # Examples + /// + /// ``` + /// use std::cell::Cell; + /// + /// let c = Cell::new(5); + /// + /// let uc = unsafe { c.as_unsafe_cell() }; + /// ``` #[inline] #[unstable(feature = "core")] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { @@ -237,6 +258,8 @@ impl<T:PartialEq + Copy> PartialEq for Cell<T> { } /// A mutable memory location with dynamically checked borrow rules +/// +/// See the [module-level documentation](../index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct RefCell<T> { value: UnsafeCell<T>, @@ -250,7 +273,15 @@ const UNUSED: BorrowFlag = 0; const WRITING: BorrowFlag = -1; impl<T> RefCell<T> { - /// Create a new `RefCell` containing `value` + /// Creates a new `RefCell` containing `value`. + /// + /// # Examples + /// + /// ``` + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> RefCell<T> { RefCell { @@ -260,6 +291,16 @@ impl<T> RefCell<T> { } /// Consumes the `RefCell`, returning the wrapped value. + /// + /// # Examples + /// + /// ``` + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// + /// let five = c.into_inner(); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(self) -> T { // Since this function takes `self` (the `RefCell`) by value, the @@ -285,12 +326,39 @@ impl<T> RefCell<T> { /// Immutably borrows the wrapped value. /// - /// The borrow lasts until the returned `Ref` exits scope. Multiple - /// immutable borrows can be taken out at the same time. + /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be + /// taken out at the same time. /// /// # Panics /// /// Panics if the value is currently mutably borrowed. + /// + /// # Examples + /// + /// ``` + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// + /// let borrowed_five = c.borrow(); + /// let borrowed_five2 = c.borrow(); + /// ``` + /// + /// An example of panic: + /// + /// ``` + /// use std::cell::RefCell; + /// use std::thread::Thread; + /// + /// let result = Thread::scoped(move || { + /// let c = RefCell::new(5); + /// let m = c.borrow_mut(); + /// + /// let b = c.borrow(); // this causes a panic + /// }).join(); + /// + /// assert!(result.is_err()); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { @@ -315,12 +383,38 @@ impl<T> RefCell<T> { /// Mutably borrows the wrapped value. /// - /// The borrow lasts until the returned `RefMut` exits scope. The value - /// cannot be borrowed while this borrow is active. + /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed + /// while this borrow is active. /// /// # Panics /// /// Panics if the value is currently borrowed. + /// + /// # Examples + /// + /// ``` + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// + /// let borrowed_five = c.borrow_mut(); + /// ``` + /// + /// An example of panic: + /// + /// ``` + /// use std::cell::RefCell; + /// use std::thread::Thread; + /// + /// let result = Thread::scoped(move || { + /// let c = RefCell::new(5); + /// let m = c.borrow_mut(); + /// + /// let b = c.borrow_mut(); // this causes a panic + /// }).join(); + /// + /// assert!(result.is_err()); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { match self.try_borrow_mut() { @@ -403,6 +497,9 @@ impl<'b> Clone for BorrowRef<'b> { } /// Wraps a borrowed reference to a value in a `RefCell` box. +/// A wrapper type for an immutably borrowed value from a `RefCell<T>`. +/// +/// See the [module-level documentation](../index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct Ref<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with @@ -461,7 +558,9 @@ impl<'b> BorrowRefMut<'b> { } } -/// Wraps a mutable borrowed reference to a value in a `RefCell` box. +/// A wrapper type for a mutably borrowed value from a `RefCell<T>`. +/// +/// See the [module-level documentation](../index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct RefMut<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with @@ -490,28 +589,25 @@ impl<'b, T> DerefMut for RefMut<'b, T> { /// The core primitive for interior mutability in Rust. /// -/// `UnsafeCell` type that wraps a type T and indicates unsafe interior -/// operations on the wrapped type. Types with an `UnsafeCell<T>` field are -/// considered to have an *unsafe interior*. The `UnsafeCell` type is the only -/// legal way to obtain aliasable data that is considered mutable. In general, -/// transmuting an &T type into an &mut T is considered undefined behavior. +/// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the +/// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'. +/// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered +/// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior. /// -/// Although it is possible to put an `UnsafeCell<T>` into static item, it is -/// not permitted to take the address of the static item if the item is not -/// declared as mutable. This rule exists because immutable static items are -/// stored in read-only memory, and thus any attempt to mutate their interior -/// can cause segfaults. Immutable static items containing `UnsafeCell<T>` -/// instances are still useful as read-only initializers, however, so we do not -/// forbid them altogether. +/// Although it is possible to put an `UnsafeCell<T>` into static item, it is not permitted to take +/// the address of the static item if the item is not declared as mutable. This rule exists because +/// immutable static items are stored in read-only memory, and thus any attempt to mutate their +/// interior can cause segfaults. Immutable static items containing `UnsafeCell<T>` instances are +/// still useful as read-only initializers, however, so we do not forbid them altogether. /// -/// Types like `Cell` and `RefCell` use this type to wrap their internal data. +/// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data. /// -/// `UnsafeCell` doesn't opt-out from any kind, instead, types with an -/// `UnsafeCell` interior are expected to opt-out from kinds themselves. +/// `UnsafeCell<T>` doesn't opt-out from any marker traits, instead, types with an `UnsafeCell<T>` +/// interior are expected to opt-out from those traits themselves. /// -/// # Example: +/// # Examples /// -/// ```rust +/// ``` /// use std::cell::UnsafeCell; /// use std::marker::Sync; /// @@ -522,9 +618,8 @@ impl<'b, T> DerefMut for RefMut<'b, T> { /// unsafe impl<T> Sync for NotThreadSafe<T> {} /// ``` /// -/// **NOTE:** `UnsafeCell<T>` fields are public to allow static initializers. It -/// is not recommended to access its fields directly, `get` should be used -/// instead. +/// **NOTE:** `UnsafeCell<T>`'s fields are public to allow static initializers. It is not +/// recommended to access its fields directly, `get` should be used instead. #[lang="unsafe"] #[stable(feature = "rust1", since = "1.0.0")] pub struct UnsafeCell<T> { @@ -540,22 +635,52 @@ impl<T> UnsafeCell<T> { /// Construct a new instance of `UnsafeCell` which will wrap the specified /// value. /// - /// All access to the inner value through methods is `unsafe`, and it is - /// highly discouraged to access the fields directly. + /// All access to the inner value through methods is `unsafe`, and it is highly discouraged to + /// access the fields directly. + /// + /// # Examples + /// + /// ``` + /// use std::cell::UnsafeCell; + /// + /// let uc = UnsafeCell::new(5); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> UnsafeCell<T> { UnsafeCell { value: value } } /// Gets a mutable pointer to the wrapped value. + /// + /// # Examples + /// + /// ``` + /// use std::cell::UnsafeCell; + /// + /// let uc = UnsafeCell::new(5); + /// + /// let five = uc.get(); + /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn get(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value /// - /// This function is unsafe because there is no guarantee that this or other - /// tasks are currently inspecting the inner value. + /// # Unsafety + /// + /// This function is unsafe because there is no guarantee that this or other threads are + /// currently inspecting the inner value. + /// + /// # Examples + /// + /// ``` + /// use std::cell::UnsafeCell; + /// + /// let uc = UnsafeCell::new(5); + /// + /// let five = unsafe { uc.into_inner() }; + /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn into_inner(self) -> T { self.value } diff --git a/src/libcore/error.rs b/src/libcore/error.rs index 9519539f000..71d5e88cccf 100644 --- a/src/libcore/error.rs +++ b/src/libcore/error.rs @@ -49,7 +49,7 @@ //! //! ``` //! use std::error::FromError; -//! use std::io::{File, IoError}; +//! use std::old_io::{File, IoError}; //! use std::os::{MemoryMap, MapError}; //! use std::path::Path; //! diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 8e6715fa38b..06428ad2f39 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -238,7 +238,7 @@ impl<'a> Display for Arguments<'a> { } } -/// Format trait for the `:?` format. Useful for debugging, most all types +/// Format trait for the `:?` format. Useful for debugging, all types /// should implement this. #[unstable(feature = "core", reason = "I/O and core have yet to be reconciled")] @@ -249,7 +249,7 @@ pub trait Show { fn fmt(&self, &mut Formatter) -> Result; } -/// Format trait for the `:?` format. Useful for debugging, most all types +/// Format trait for the `:?` format. Useful for debugging, all types /// should implement this. #[unstable(feature = "core", reason = "I/O and core have yet to be reconciled")] diff --git a/src/libcore/result.rs b/src/libcore/result.rs index bfbc96c5a39..ade257165c6 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -95,7 +95,7 @@ //! by the [`Writer`](../io/trait.Writer.html) trait: //! //! ``` -//! use std::io::IoError; +//! use std::old_io::IoError; //! //! trait Writer { //! fn write_line(&mut self, s: &str) -> Result<(), IoError>; @@ -110,7 +110,7 @@ //! something like this: //! //! ```{.ignore} -//! use std::io::{File, Open, Write}; +//! use std::old_io::{File, Open, Write}; //! //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write); //! // If `write_line` errors, then we'll never know, because the return @@ -128,7 +128,7 @@ //! a marginally useful message indicating why: //! //! ```{.no_run} -//! use std::io::{File, Open, Write}; +//! use std::old_io::{File, Open, Write}; //! //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write); //! file.write_line("important message").ok().expect("failed to write message"); @@ -138,7 +138,7 @@ //! You might also simply assert success: //! //! ```{.no_run} -//! # use std::io::{File, Open, Write}; +//! # use std::old_io::{File, Open, Write}; //! //! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write); //! assert!(file.write_line("important message").is_ok()); @@ -148,7 +148,7 @@ //! Or propagate the error up the call stack with `try!`: //! //! ``` -//! # use std::io::{File, Open, Write, IoError}; +//! # use std::old_io::{File, Open, Write, IoError}; //! fn write_message() -> Result<(), IoError> { //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write); //! try!(file.write_line("important message")); @@ -167,7 +167,7 @@ //! It replaces this: //! //! ``` -//! use std::io::{File, Open, Write, IoError}; +//! use std::old_io::{File, Open, Write, IoError}; //! //! struct Info { //! name: String, @@ -191,7 +191,7 @@ //! With this: //! //! ``` -//! use std::io::{File, Open, Write, IoError}; +//! use std::old_io::{File, Open, Write, IoError}; //! //! struct Info { //! name: String, @@ -445,7 +445,7 @@ impl<T, E> Result<T, E> { /// ignoring I/O and parse errors: /// /// ``` - /// use std::io::IoResult; + /// use std::old_io::IoResult; /// /// let mut buffer = &mut b"1\n2\n3\n4\n"; /// diff --git a/src/libcoretest/fmt/num.rs b/src/libcoretest/fmt/num.rs index 17180076cd8..dba355373ce 100644 --- a/src/libcoretest/fmt/num.rs +++ b/src/libcoretest/fmt/num.rs @@ -170,7 +170,7 @@ mod u32 { use test::Bencher; use core::fmt::radix; use std::rand::{weak_rng, Rng}; - use std::io::util::NullWriter; + use std::old_io::util::NullWriter; #[bench] fn format_bin(b: &mut Bencher) { @@ -213,7 +213,7 @@ mod i32 { use test::Bencher; use core::fmt::radix; use std::rand::{weak_rng, Rng}; - use std::io::util::NullWriter; + use std::old_io::util::NullWriter; #[bench] fn format_bin(b: &mut Bencher) { diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 5ed93f0fd99..171b4ec2097 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -96,7 +96,7 @@ //! ```no_run //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() } //! pub fn main() { -//! use std::io::File; +//! use std::old_io::File; //! let mut f = File::create(&Path::new("example1.dot")); //! render_to(&mut f) //! } @@ -188,7 +188,7 @@ //! ```no_run //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() } //! pub fn main() { -//! use std::io::File; +//! use std::old_io::File; //! let mut f = File::create(&Path::new("example2.dot")); //! render_to(&mut f) //! } @@ -252,7 +252,7 @@ //! ```no_run //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() } //! pub fn main() { -//! use std::io::File; +//! use std::old_io::File; //! let mut f = File::create(&Path::new("example3.dot")); //! render_to(&mut f) //! } @@ -283,7 +283,7 @@ use self::LabelText::*; use std::borrow::IntoCow; -use std::io; +use std::old_io; use std::string::CowString; use std::vec::CowVec; @@ -536,7 +536,7 @@ pub fn default_options() -> Vec<RenderOption> { vec![] } /// (Simple wrapper around `render_opts` that passes a default set of options.) pub fn render<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N,E>, W:Writer>( g: &'a G, - w: &mut W) -> io::IoResult<()> { + w: &mut W) -> old_io::IoResult<()> { render_opts(g, w, &[]) } @@ -545,14 +545,14 @@ pub fn render<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N,E>, pub fn render_opts<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N,E>, W:Writer>( g: &'a G, w: &mut W, - options: &[RenderOption]) -> io::IoResult<()> + options: &[RenderOption]) -> old_io::IoResult<()> { - fn writeln<W:Writer>(w: &mut W, arg: &[&str]) -> io::IoResult<()> { + fn writeln<W:Writer>(w: &mut W, arg: &[&str]) -> old_io::IoResult<()> { for &s in arg.iter() { try!(w.write_str(s)); } w.write_char('\n') } - fn indent<W:Writer>(w: &mut W) -> io::IoResult<()> { + fn indent<W:Writer>(w: &mut W) -> old_io::IoResult<()> { w.write_str(" ") } @@ -594,7 +594,7 @@ mod tests { use self::NodeLabels::*; use super::{Id, Labeller, Nodes, Edges, GraphWalk, render}; use super::LabelText::{self, LabelStr, EscStr}; - use std::io::IoResult; + use std::old_io::IoResult; use std::borrow::IntoCow; use std::iter::repeat; diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index 05b831a5a59..dfec2c18816 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -181,8 +181,8 @@ use std::cell::RefCell; use std::fmt; -use std::io::LineBufferedWriter; -use std::io; +use std::old_io::LineBufferedWriter; +use std::old_io; use std::mem; use std::os; use std::ptr; @@ -239,7 +239,7 @@ pub trait Logger { } struct DefaultLogger { - handle: LineBufferedWriter<io::stdio::StdWriter>, + handle: LineBufferedWriter<old_io::stdio::StdWriter>, } /// Wraps the log level with fmt implementations. @@ -301,7 +301,7 @@ pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) { let mut logger = LOCAL_LOGGER.with(|s| { s.borrow_mut().take() }).unwrap_or_else(|| { - box DefaultLogger { handle: io::stderr() } as Box<Logger + Send> + box DefaultLogger { handle: old_io::stderr() } as Box<Logger + Send> }); logger.log(&LogRecord { level: LogLevel(level), diff --git a/src/librbml/io.rs b/src/librbml/io.rs index 9c746c69baa..13ddad1fee2 100644 --- a/src/librbml/io.rs +++ b/src/librbml/io.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::{IoError, IoResult, SeekStyle}; -use std::io; +use std::old_io::{IoError, IoResult, SeekStyle}; +use std::old_io; use std::slice; use std::iter::repeat; @@ -18,14 +18,14 @@ static BUF_CAPACITY: uint = 128; fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> { // compute offset as signed and clamp to prevent overflow let pos = match seek { - io::SeekSet => 0, - io::SeekEnd => end, - io::SeekCur => cur, + old_io::SeekSet => 0, + old_io::SeekEnd => end, + old_io::SeekCur => cur, } as i64; if offset + pos < 0 { Err(IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "invalid seek to a negative offset", detail: None }) @@ -80,7 +80,7 @@ impl SeekableMemWriter { impl Writer for SeekableMemWriter { #[inline] - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { if self.pos == self.buf.len() { self.buf.push_all(buf) } else { @@ -132,7 +132,7 @@ impl Seek for SeekableMemWriter { mod tests { extern crate test; use super::SeekableMemWriter; - use std::io; + use std::old_io; use std::iter::repeat; use test::Bencher; @@ -148,23 +148,23 @@ mod tests { let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7]; assert_eq!(writer.get_ref(), b); - writer.seek(0, io::SeekSet).unwrap(); + writer.seek(0, old_io::SeekSet).unwrap(); assert_eq!(writer.tell(), Ok(0)); writer.write(&[3, 4]).unwrap(); let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7]; assert_eq!(writer.get_ref(), b); - writer.seek(1, io::SeekCur).unwrap(); + writer.seek(1, old_io::SeekCur).unwrap(); writer.write(&[0, 1]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7]; assert_eq!(writer.get_ref(), b); - writer.seek(-1, io::SeekEnd).unwrap(); + writer.seek(-1, old_io::SeekEnd).unwrap(); writer.write(&[1, 2]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2]; assert_eq!(writer.get_ref(), b); - writer.seek(1, io::SeekEnd).unwrap(); + writer.seek(1, old_io::SeekEnd).unwrap(); writer.write(&[1]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1]; assert_eq!(writer.get_ref(), b); @@ -173,14 +173,14 @@ mod tests { #[test] fn seek_past_end() { let mut r = SeekableMemWriter::new(); - r.seek(10, io::SeekSet).unwrap(); + r.seek(10, old_io::SeekSet).unwrap(); assert!(r.write(&[3]).is_ok()); } #[test] fn seek_before_0() { let mut r = SeekableMemWriter::new(); - assert!(r.seek(-1, io::SeekSet).is_err()); + assert!(r.seek(-1, old_io::SeekSet).is_err()); } fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint) { diff --git a/src/librbml/lib.rs b/src/librbml/lib.rs index 2819dec3ebb..2500cb86463 100644 --- a/src/librbml/lib.rs +++ b/src/librbml/lib.rs @@ -115,7 +115,7 @@ pub enum EbmlEncoderTag { pub enum Error { IntTooBig(uint), Expected(String), - IoError(std::io::IoError), + IoError(std::old_io::IoError), ApplicationError(String) } @@ -131,7 +131,7 @@ pub mod reader { use std::char; use std::int; - use std::io::extensions::u64_from_be_bytes; + use std::old_io::extensions::u64_from_be_bytes; use std::mem::transmute; use std::num::Int; use std::option::Option; @@ -689,9 +689,9 @@ pub mod reader { pub mod writer { use std::clone::Clone; - use std::io::extensions::u64_to_be_bytes; - use std::io::{Writer, Seek}; - use std::io; + use std::old_io::extensions::u64_to_be_bytes; + use std::old_io::{Writer, Seek}; + use std::old_io; use std::mem; use super::{ EsVec, EsMap, EsEnum, EsVecLen, EsVecElt, EsMapLen, EsMapKey, @@ -702,7 +702,7 @@ pub mod writer { use serialize; - pub type EncodeResult = io::IoResult<()>; + pub type EncodeResult = old_io::IoResult<()>; // rbml writing pub struct Encoder<'a, W:'a> { @@ -712,14 +712,14 @@ pub mod writer { fn write_sized_vuint<W: Writer>(w: &mut W, n: uint, size: uint) -> EncodeResult { match size { - 1u => w.write(&[0x80u8 | (n as u8)]), - 2u => w.write(&[0x40u8 | ((n >> 8_u) as u8), n as u8]), - 3u => w.write(&[0x20u8 | ((n >> 16_u) as u8), (n >> 8_u) as u8, + 1u => w.write_all(&[0x80u8 | (n as u8)]), + 2u => w.write_all(&[0x40u8 | ((n >> 8_u) as u8), n as u8]), + 3u => w.write_all(&[0x20u8 | ((n >> 16_u) as u8), (n >> 8_u) as u8, n as u8]), - 4u => w.write(&[0x10u8 | ((n >> 24_u) as u8), (n >> 16_u) as u8, + 4u => w.write_all(&[0x10u8 | ((n >> 24_u) as u8), (n >> 16_u) as u8, (n >> 8_u) as u8, n as u8]), - _ => Err(io::IoError { - kind: io::OtherIoError, + _ => Err(old_io::IoError { + kind: old_io::OtherIoError, desc: "int too big", detail: Some(format!("{}", n)) }) @@ -731,8 +731,8 @@ pub mod writer { if n < 0x4000_u { return write_sized_vuint(w, n, 2u); } if n < 0x200000_u { return write_sized_vuint(w, n, 3u); } if n < 0x10000000_u { return write_sized_vuint(w, n, 4u); } - Err(io::IoError { - kind: io::OtherIoError, + Err(old_io::IoError { + kind: old_io::OtherIoError, desc: "int too big", detail: Some(format!("{}", n)) }) @@ -764,16 +764,16 @@ pub mod writer { // Write a placeholder four-byte size. self.size_positions.push(try!(self.writer.tell()) as uint); let zeroes: &[u8] = &[0u8, 0u8, 0u8, 0u8]; - self.writer.write(zeroes) + self.writer.write_all(zeroes) } pub fn end_tag(&mut self) -> EncodeResult { let last_size_pos = self.size_positions.pop().unwrap(); let cur_pos = try!(self.writer.tell()); - try!(self.writer.seek(last_size_pos as i64, io::SeekSet)); + try!(self.writer.seek(last_size_pos as i64, old_io::SeekSet)); let size = cur_pos as uint - last_size_pos - 4; try!(write_sized_vuint(self.writer, size, 4u)); - let r = try!(self.writer.seek(cur_pos as i64, io::SeekSet)); + let r = try!(self.writer.seek(cur_pos as i64, old_io::SeekSet)); debug!("End tag (size = {:?})", size); Ok(r) @@ -790,7 +790,7 @@ pub mod writer { pub fn wr_tagged_bytes(&mut self, tag_id: uint, b: &[u8]) -> EncodeResult { try!(write_vuint(self.writer, tag_id)); try!(write_vuint(self.writer, b.len())); - self.writer.write(b) + self.writer.write_all(b) } pub fn wr_tagged_u64(&mut self, tag_id: uint, v: u64) -> EncodeResult { @@ -843,12 +843,12 @@ pub mod writer { pub fn wr_bytes(&mut self, b: &[u8]) -> EncodeResult { debug!("Write {:?} bytes", b.len()); - self.writer.write(b) + self.writer.write_all(b) } pub fn wr_str(&mut self, s: &str) -> EncodeResult { debug!("Write str: {:?}", s); - self.writer.write(s.as_bytes()) + self.writer.write_all(s.as_bytes()) } } @@ -890,7 +890,7 @@ pub mod writer { } impl<'a, W: Writer + Seek> serialize::Encoder for Encoder<'a, W> { - type Error = io::IoError; + type Error = old_io::IoError; fn emit_nil(&mut self) -> EncodeResult { Ok(()) diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 1197276b990..e6f76dedca9 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -34,8 +34,8 @@ use middle::astencode::vtable_decoder_helpers; use std::collections::HashMap; use std::hash::{self, Hash, SipHasher}; -use std::io::extensions::u64_from_be_bytes; -use std::io; +use std::old_io::extensions::u64_from_be_bytes; +use std::old_io; use std::num::FromPrimitive; use std::rc::Rc; use std::str; @@ -1178,7 +1178,7 @@ fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> { } fn list_crate_attributes(md: rbml::Doc, hash: &Svh, - out: &mut io::Writer) -> io::IoResult<()> { + out: &mut old_io::Writer) -> old_io::IoResult<()> { try!(write!(out, "=Crate Attributes ({})=\n", *hash)); let r = get_attributes(md); @@ -1223,7 +1223,7 @@ pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> { return deps; } -fn list_crate_deps(data: &[u8], out: &mut io::Writer) -> io::IoResult<()> { +fn list_crate_deps(data: &[u8], out: &mut old_io::Writer) -> old_io::IoResult<()> { try!(write!(out, "=External Dependencies=\n")); for dep in get_crate_deps(data).iter() { try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash)); @@ -1262,7 +1262,7 @@ pub fn get_crate_name(data: &[u8]) -> String { maybe_get_crate_name(data).expect("no crate name in crate") } -pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Writer) -> io::IoResult<()> { +pub fn list_crate_metadata(bytes: &[u8], out: &mut old_io::Writer) -> old_io::IoResult<()> { let hash = get_crate_hash(bytes); let md = rbml::Doc::new(bytes); try!(list_crate_attributes(md, &hash, out)); diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 2de45381249..f6c5ba4b52b 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -122,7 +122,7 @@ fn encode_trait_ref<'a, 'tcx>(rbml_w: &mut Encoder, // Item info table encoding fn encode_family(rbml_w: &mut Encoder, c: char) { rbml_w.start_tag(tag_items_data_item_family); - rbml_w.writer.write(&[c as u8]); + rbml_w.writer.write_all(&[c as u8]); rbml_w.end_tag(); } @@ -149,7 +149,7 @@ fn encode_bounds_and_type<'a, 'tcx>(rbml_w: &mut Encoder, fn encode_variant_id(rbml_w: &mut Encoder, vid: DefId) { rbml_w.start_tag(tag_items_data_item_variant); let s = def_to_string(vid); - rbml_w.writer.write(s.as_bytes()); + rbml_w.writer.write_all(s.as_bytes()); rbml_w.end_tag(); rbml_w.start_tag(tag_mod_child); @@ -259,7 +259,7 @@ fn encode_symbol(ecx: &EncodeContext, match ecx.item_symbols.borrow().get(&id) { Some(x) => { debug!("encode_symbol(id={}, str={})", id, *x); - rbml_w.writer.write(x.as_bytes()); + rbml_w.writer.write_all(x.as_bytes()); } None => { ecx.diag.handler().bug( @@ -274,14 +274,14 @@ fn encode_disr_val(_: &EncodeContext, disr_val: ty::Disr) { rbml_w.start_tag(tag_disr_val); let s = disr_val.to_string(); - rbml_w.writer.write(s.as_bytes()); + rbml_w.writer.write_all(s.as_bytes()); rbml_w.end_tag(); } fn encode_parent_item(rbml_w: &mut Encoder, id: DefId) { rbml_w.start_tag(tag_items_data_parent_item); let s = def_to_string(id); - rbml_w.writer.write(s.as_bytes()); + rbml_w.writer.write_all(s.as_bytes()); rbml_w.end_tag(); } @@ -299,7 +299,7 @@ fn encode_struct_fields(rbml_w: &mut Encoder, encode_def_id(rbml_w, f.id); rbml_w.start_tag(tag_item_field_origin); let s = def_to_string(origin); - rbml_w.writer.write(s.as_bytes()); + rbml_w.writer.write_all(s.as_bytes()); rbml_w.end_tag(); rbml_w.end_tag(); } @@ -636,17 +636,17 @@ fn encode_explicit_self(rbml_w: &mut Encoder, // Encode the base self type. match *explicit_self { ty::StaticExplicitSelfCategory => { - rbml_w.writer.write(&[ 's' as u8 ]); + rbml_w.writer.write_all(&[ 's' as u8 ]); } ty::ByValueExplicitSelfCategory => { - rbml_w.writer.write(&[ 'v' as u8 ]); + rbml_w.writer.write_all(&[ 'v' as u8 ]); } ty::ByBoxExplicitSelfCategory => { - rbml_w.writer.write(&[ '~' as u8 ]); + rbml_w.writer.write_all(&[ '~' as u8 ]); } ty::ByReferenceExplicitSelfCategory(_, m) => { // FIXME(#4846) encode custom lifetime - rbml_w.writer.write(&['&' as u8]); + rbml_w.writer.write_all(&['&' as u8]); encode_mutability(rbml_w, m); } } @@ -656,21 +656,21 @@ fn encode_explicit_self(rbml_w: &mut Encoder, fn encode_mutability(rbml_w: &mut Encoder, m: ast::Mutability) { match m { - ast::MutImmutable => { rbml_w.writer.write(&[ 'i' as u8 ]); } - ast::MutMutable => { rbml_w.writer.write(&[ 'm' as u8 ]); } + ast::MutImmutable => { rbml_w.writer.write_all(&[ 'i' as u8 ]); } + ast::MutMutable => { rbml_w.writer.write_all(&[ 'm' as u8 ]); } } } } fn encode_item_sort(rbml_w: &mut Encoder, sort: char) { rbml_w.start_tag(tag_item_trait_item_sort); - rbml_w.writer.write(&[ sort as u8 ]); + rbml_w.writer.write_all(&[ sort as u8 ]); rbml_w.end_tag(); } fn encode_parent_sort(rbml_w: &mut Encoder, sort: char) { rbml_w.start_tag(tag_item_trait_parent_sort); - rbml_w.writer.write(&[ sort as u8 ]); + rbml_w.writer.write_all(&[ sort as u8 ]); rbml_w.end_tag(); } @@ -679,7 +679,7 @@ fn encode_provided_source(rbml_w: &mut Encoder, for source in source_opt.iter() { rbml_w.start_tag(tag_item_method_provided_source); let s = def_to_string(*source); - rbml_w.writer.write(s.as_bytes()); + rbml_w.writer.write_all(s.as_bytes()); rbml_w.end_tag(); } } @@ -926,7 +926,7 @@ fn encode_method_argument_names(rbml_w: &mut Encoder, rbml_w.start_tag(tag_method_argument_name); if let ast::PatIdent(_, ref path1, _) = arg.pat.node { let name = token::get_ident(path1.node); - rbml_w.writer.write(name.get().as_bytes()); + rbml_w.writer.write_all(name.get().as_bytes()); } rbml_w.end_tag(); } @@ -1646,7 +1646,7 @@ fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) { ast::MetaWord(ref name) => { rbml_w.start_tag(tag_meta_item_word); rbml_w.start_tag(tag_meta_item_name); - rbml_w.writer.write(name.get().as_bytes()); + rbml_w.writer.write_all(name.get().as_bytes()); rbml_w.end_tag(); rbml_w.end_tag(); } @@ -1655,10 +1655,10 @@ fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) { ast::LitStr(ref value, _) => { rbml_w.start_tag(tag_meta_item_name_value); rbml_w.start_tag(tag_meta_item_name); - rbml_w.writer.write(name.get().as_bytes()); + rbml_w.writer.write_all(name.get().as_bytes()); rbml_w.end_tag(); rbml_w.start_tag(tag_meta_item_value); - rbml_w.writer.write(value.get().as_bytes()); + rbml_w.writer.write_all(value.get().as_bytes()); rbml_w.end_tag(); rbml_w.end_tag(); } @@ -1668,7 +1668,7 @@ fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) { ast::MetaList(ref name, ref items) => { rbml_w.start_tag(tag_meta_item_list); rbml_w.start_tag(tag_meta_item_name); - rbml_w.writer.write(name.get().as_bytes()); + rbml_w.writer.write_all(name.get().as_bytes()); rbml_w.end_tag(); for inner_item in items.iter() { encode_meta_item(rbml_w, &**inner_item); @@ -1800,7 +1800,7 @@ fn encode_native_libraries(ecx: &EncodeContext, rbml_w: &mut Encoder) { rbml_w.end_tag(); rbml_w.start_tag(tag_native_libraries_name); - rbml_w.writer.write(lib.as_bytes()); + rbml_w.writer.write_all(lib.as_bytes()); rbml_w.end_tag(); rbml_w.end_tag(); @@ -1975,29 +1975,29 @@ fn encode_crate_dep(rbml_w: &mut Encoder, dep: decoder::CrateDep) { rbml_w.start_tag(tag_crate_dep); rbml_w.start_tag(tag_crate_dep_crate_name); - rbml_w.writer.write(dep.name.as_bytes()); + rbml_w.writer.write_all(dep.name.as_bytes()); rbml_w.end_tag(); rbml_w.start_tag(tag_crate_dep_hash); - rbml_w.writer.write(dep.hash.as_str().as_bytes()); + rbml_w.writer.write_all(dep.hash.as_str().as_bytes()); rbml_w.end_tag(); rbml_w.end_tag(); } fn encode_hash(rbml_w: &mut Encoder, hash: &Svh) { rbml_w.start_tag(tag_crate_hash); - rbml_w.writer.write(hash.as_str().as_bytes()); + rbml_w.writer.write_all(hash.as_str().as_bytes()); rbml_w.end_tag(); } fn encode_crate_name(rbml_w: &mut Encoder, crate_name: &str) { rbml_w.start_tag(tag_crate_crate_name); - rbml_w.writer.write(crate_name.as_bytes()); + rbml_w.writer.write_all(crate_name.as_bytes()); rbml_w.end_tag(); } fn encode_crate_triple(rbml_w: &mut Encoder, triple: &str) { rbml_w.start_tag(tag_crate_triple); - rbml_w.writer.write(triple.as_bytes()); + rbml_w.writer.write_all(triple.as_bytes()); rbml_w.end_tag(); } @@ -2011,7 +2011,7 @@ fn encode_dylib_dependency_formats(rbml_w: &mut Encoder, ecx: &EncodeContext) { cstore::RequireStatic => "s", })).to_string()) }).collect::<Vec<String>>(); - rbml_w.writer.write(s.connect(",").as_bytes()); + rbml_w.writer.write_all(s.connect(",").as_bytes()); } None => {} } diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index ddee1f79d6a..26046cfb43d 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -13,8 +13,8 @@ pub use self::FileMatch::*; use std::collections::HashSet; -use std::io::fs::PathExtensions; -use std::io::fs; +use std::old_io::fs::PathExtensions; +use std::old_io::fs; use std::os; use util::fs as myfs; diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index b1043a4152c..3ee4017292c 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -231,8 +231,8 @@ use rustc_back::target::Target; use std::ffi::CString; use std::cmp; use std::collections::HashMap; -use std::io::fs::PathExtensions; -use std::io; +use std::old_io::fs::PathExtensions; +use std::old_io; use std::ptr; use std::slice; use std::time::Duration; @@ -796,7 +796,7 @@ pub fn read_meta_section_name(is_osx: bool) -> &'static str { // A diagnostic function for dumping crate metadata to an output stream pub fn list_file_metadata(is_osx: bool, path: &Path, - out: &mut io::Writer) -> io::IoResult<()> { + out: &mut old_io::Writer) -> old_io::IoResult<()> { match get_metadata_section(is_osx, path) { Ok(bytes) => decoder::list_crate_metadata(bytes.as_slice(), out), Err(msg) => { diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index cb6b7e56b57..2ee4b6fbbd4 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -377,6 +377,14 @@ fn parse_scope(st: &mut PState) -> region::CodeExtent { let node_id = parse_uint(st) as ast::NodeId; region::CodeExtent::Misc(node_id) } + 'B' => { + let node_id = parse_uint(st) as ast::NodeId; + let first_stmt_index = parse_uint(st); + let block_remainder = region::BlockRemainder { + block: node_id, first_statement_index: first_stmt_index, + }; + region::CodeExtent::Remainder(block_remainder) + } _ => panic!("parse_scope: bad input") } } diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index 54b930fbda9..2dc334bfe95 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -51,7 +51,7 @@ pub type abbrev_map<'tcx> = RefCell<FnvHashMap<Ty<'tcx>, ty_abbrev>>; pub fn enc_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, t: Ty<'tcx>) { match cx.abbrevs.borrow_mut().get(&t) { - Some(a) => { w.write(a.s.as_bytes()); return; } + Some(a) => { w.write_all(a.s.as_bytes()); return; } None => {} } let pos = w.tell().unwrap(); @@ -276,7 +276,9 @@ pub fn enc_region(w: &mut SeekableMemWriter, cx: &ctxt, r: ty::Region) { fn enc_scope(w: &mut SeekableMemWriter, _cx: &ctxt, scope: region::CodeExtent) { match scope { - region::CodeExtent::Misc(node_id) => mywrite!(w, "M{}", node_id) + region::CodeExtent::Misc(node_id) => mywrite!(w, "M{}", node_id), + region::CodeExtent::Remainder(region::BlockRemainder { + block: b, first_statement_index: i }) => mywrite!(w, "B{}{}", b, i), } } diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index fcc2be985a5..091ef9d52eb 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -37,7 +37,7 @@ use syntax::parse::token; use syntax::ptr::P; use syntax; -use std::io::Seek; +use std::old_io::Seek; use std::rc::Rc; use rbml::io::SeekableMemWriter; diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index a1727869810..d3c843d1d50 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -19,7 +19,7 @@ pub use self::EntryOrExit::*; use middle::cfg; use middle::cfg::CFGIndex; use middle::ty; -use std::io; +use std::old_io; use std::uint; use std::iter::repeat; use syntax::ast; @@ -105,7 +105,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O> { fn pre(&self, ps: &mut pprust::State, - node: pprust::AnnNode) -> io::IoResult<()> { + node: pprust::AnnNode) -> old_io::IoResult<()> { let id = match node { pprust::NodeIdent(_) | pprust::NodeName(_) => 0, pprust::NodeExpr(expr) => expr.id, @@ -457,13 +457,13 @@ impl<'a, 'tcx, O:DataFlowOperator+Clone+'static> DataFlowContext<'a, 'tcx, O> { debug!("Dataflow result for {}:", self.analysis_name); debug!("{}", { - self.pretty_print_to(box io::stderr(), blk).unwrap(); + self.pretty_print_to(box old_io::stderr(), blk).unwrap(); "" }); } - fn pretty_print_to(&self, wr: Box<io::Writer+'static>, - blk: &ast::Block) -> io::IoResult<()> { + fn pretty_print_to(&self, wr: Box<old_io::Writer+'static>, + blk: &ast::Block) -> old_io::IoResult<()> { let mut ps = pprust::rust_printer_annotated(wr, self); try!(ps.cbox(pprust::indent_unit)); try!(ps.ibox(0u)); diff --git a/src/librustc/middle/infer/error_reporting.rs b/src/librustc/middle/infer/error_reporting.rs index 18c36f870b5..cfef88a8deb 100644 --- a/src/librustc/middle/infer/error_reporting.rs +++ b/src/librustc/middle/infer/error_reporting.rs @@ -809,6 +809,8 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { let scope_id = same_regions[0].scope_id; let parent = self.tcx.map.get_parent(scope_id); let parent_node = self.tcx.map.find(parent); + let taken = lifetimes_in_scope(self.tcx, scope_id); + let life_giver = LifeGiver::with_taken(&taken[]); let node_inner = match parent_node { Some(ref node) => match *node { ast_map::NodeItem(ref item) => { @@ -851,8 +853,6 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { }; let (fn_decl, generics, unsafety, ident, expl_self, span) = node_inner.expect("expect item fn"); - let taken = lifetimes_in_scope(self.tcx, scope_id); - let life_giver = LifeGiver::with_taken(&taken[]); let rebuilder = Rebuilder::new(self.tcx, fn_decl, expl_self, generics, same_regions, &life_giver); let (fn_decl, expl_self, generics) = rebuilder.rebuild(); diff --git a/src/librustc/middle/infer/region_inference/graphviz.rs b/src/librustc/middle/infer/region_inference/graphviz.rs index f8f962cd86d..8803fe7cf38 100644 --- a/src/librustc/middle/infer/region_inference/graphviz.rs +++ b/src/librustc/middle/infer/region_inference/graphviz.rs @@ -26,7 +26,7 @@ use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; use std::collections::hash_map::Entry::Vacant; -use std::io::{self, File}; +use std::old_io::{self, File}; use std::os; use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use syntax::ast; @@ -217,7 +217,7 @@ pub type ConstraintMap<'tcx> = FnvHashMap<Constraint, SubregionOrigin<'tcx>>; fn dump_region_constraints_to<'a, 'tcx:'a >(tcx: &'a ty::ctxt<'tcx>, map: &ConstraintMap<'tcx>, - path: &str) -> io::IoResult<()> { + path: &str) -> old_io::IoResult<()> { debug!("dump_region_constraints map (len: {}) path: {}", map.len(), path); let g = ConstraintGraph::new(tcx, format!("region_constraints"), map); let mut f = File::create(&Path::new(path)); diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 0131b9f1491..00fa6546b48 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -118,7 +118,7 @@ use middle::ty::ClosureTyper; use lint; use util::nodemap::NodeMap; -use std::{fmt, io, uint}; +use std::{fmt, old_io, uint}; use std::rc::Rc; use std::iter::repeat; use syntax::ast::{self, NodeId, Expr}; @@ -693,10 +693,10 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } fn write_vars<F>(&self, - wr: &mut io::Writer, + wr: &mut old_io::Writer, ln: LiveNode, mut test: F) - -> io::IoResult<()> where + -> old_io::IoResult<()> where F: FnMut(uint) -> LiveNode, { let node_base_idx = self.idx(ln, Variable(0)); @@ -740,7 +740,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { fn ln_str(&self, ln: LiveNode) -> String { let mut wr = Vec::new(); { - let wr = &mut wr as &mut io::Writer; + let wr = &mut wr as &mut old_io::Writer; write!(wr, "[ln({:?}) of kind {:?} reads", ln.get(), self.ir.lnk(ln)); self.write_vars(wr, ln, |idx| self.users[idx].reader); write!(wr, " writes"); diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 67c0e52d664..9bba01f8af7 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -26,6 +26,7 @@ use syntax::codemap::{self, Span}; use syntax::{ast, visit}; use syntax::ast::{Block, Item, FnDecl, NodeId, Arm, Pat, Stmt, Expr, Local}; use syntax::ast_util::{stmt_id}; +use syntax::ast_map; use syntax::visit::{Visitor, FnKind}; /// CodeExtent represents a statically-describable extent that can be @@ -38,7 +39,32 @@ use syntax::visit::{Visitor, FnKind}; #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable, RustcDecodable, Show, Copy)] pub enum CodeExtent { - Misc(ast::NodeId) + Misc(ast::NodeId), + Remainder(BlockRemainder), +} + +/// Represents a subscope of `block` for a binding that is introduced +/// by `block.stmts[first_statement_index]`. Such subscopes represent +/// a suffix of the block. Note that each subscope does not include +/// the initializer expression, if any, for the statement indexed by +/// `first_statement_index`. +/// +/// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`: +/// +/// * the subscope with `first_statement_index == 0` is scope of both +/// `a` and `b`; it does not include EXPR_1, but does include +/// everything after that first `let`. (If you want a scope that +/// includes EXPR_1 as well, then do not use `CodeExtent::Remainder`, +/// but instead another `CodeExtent` that encompasses the whole block, +/// e.g. `CodeExtent::Misc`. +/// +/// * the subscope with `first_statement_index == 1` is scope of `c`, +/// and thus does not include EXPR_2, but covers the `...`. +#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable, + RustcDecodable, Show, Copy)] +pub struct BlockRemainder { + pub block: ast::NodeId, + pub first_statement_index: uint, } impl CodeExtent { @@ -55,6 +81,7 @@ impl CodeExtent { pub fn node_id(&self) -> ast::NodeId { match *self { CodeExtent::Misc(node_id) => node_id, + CodeExtent::Remainder(br) => br.block, } } @@ -65,8 +92,41 @@ impl CodeExtent { { match *self { CodeExtent::Misc(node_id) => CodeExtent::Misc(f_id(node_id)), + CodeExtent::Remainder(br) => + CodeExtent::Remainder(BlockRemainder { + block: f_id(br.block), first_statement_index: br.first_statement_index }), } } + + /// Returns the span of this CodeExtent. Note that in general the + /// returned span may not correspond to the span of any node id in + /// the AST. + pub fn span(&self, ast_map: &ast_map::Map) -> Option<Span> { + match ast_map.find(self.node_id()) { + Some(ast_map::NodeBlock(ref blk)) => { + match *self { + CodeExtent::Misc(_) => Some(blk.span), + + CodeExtent::Remainder(r) => { + assert_eq!(r.block, blk.id); + // Want span for extent starting after the + // indexed statement and ending at end of + // `blk`; reuse span of `blk` and shift `lo` + // forward to end of indexed statement. + // + // (This is the special case aluded to in the + // doc-comment for this method) + let stmt_span = blk.stmts[r.first_statement_index].span; + Some(Span { lo: stmt_span.hi, ..blk.span }) + } + } + } + Some(ast_map::NodeExpr(ref expr)) => Some(expr.span), + Some(ast_map::NodeStmt(ref stmt)) => Some(stmt.span), + Some(ast_map::NodeItem(ref item)) => Some(item.span), + Some(_) | None => None, + } + } } /// The region maps encode information about region relationships. @@ -74,7 +134,8 @@ impl CodeExtent { /// - `scope_map` maps from a scope id to the enclosing scope id; this is /// usually corresponding to the lexical nesting, though in the case of /// closures the parent scope is the innermost conditional expression or repeating -/// block +/// block. (Note that the enclosing scope id for the block +/// associated with a closure is the closure itself.) /// /// - `var_map` maps from a variable or binding id to the block in which /// that variable is declared. @@ -115,12 +176,77 @@ pub struct RegionMaps { terminating_scopes: RefCell<FnvHashSet<CodeExtent>>, } -#[derive(Copy)] +/// Carries the node id for the innermost block or match expression, +/// for building up the `var_map` which maps ids to the blocks in +/// which they were declared. +#[derive(PartialEq, Eq, Show, Copy)] +enum InnermostDeclaringBlock { + None, + Block(ast::NodeId), + Statement(DeclaringStatementContext), + Match(ast::NodeId), +} + +impl InnermostDeclaringBlock { + fn to_code_extent(&self) -> Option<CodeExtent> { + let extent = match *self { + InnermostDeclaringBlock::None => { + return Option::None; + } + InnermostDeclaringBlock::Block(id) | + InnermostDeclaringBlock::Match(id) => CodeExtent::from_node_id(id), + InnermostDeclaringBlock::Statement(s) => s.to_code_extent(), + }; + Option::Some(extent) + } +} + +/// Contextual information for declarations introduced by a statement +/// (i.e. `let`). It carries node-id's for statement and enclosing +/// block both, as well as the statement's index within the block. +#[derive(PartialEq, Eq, Show, Copy)] +struct DeclaringStatementContext { + stmt_id: ast::NodeId, + block_id: ast::NodeId, + stmt_index: uint, +} + +impl DeclaringStatementContext { + fn to_code_extent(&self) -> CodeExtent { + CodeExtent::Remainder(BlockRemainder { + block: self.block_id, + first_statement_index: self.stmt_index, + }) + } +} + +#[derive(PartialEq, Eq, Show, Copy)] +enum InnermostEnclosingExpr { + None, + Some(ast::NodeId), + Statement(DeclaringStatementContext), +} + +impl InnermostEnclosingExpr { + fn to_code_extent(&self) -> Option<CodeExtent> { + let extent = match *self { + InnermostEnclosingExpr::None => { + return Option::None; + } + InnermostEnclosingExpr::Statement(s) => + s.to_code_extent(), + InnermostEnclosingExpr::Some(parent_id) => + CodeExtent::from_node_id(parent_id), + }; + Some(extent) + } +} + +#[derive(Show, Copy)] pub struct Context { - var_parent: Option<ast::NodeId>, + var_parent: InnermostDeclaringBlock, - // Innermost enclosing expression - parent: Option<ast::NodeId>, + parent: InnermostEnclosingExpr, } struct RegionResolutionVisitor<'a> { @@ -381,16 +507,13 @@ impl RegionMaps { } } -/// Records the current parent (if any) as the parent of `child_id`. +/// Records the current parent (if any) as the parent of `child_scope`. fn record_superlifetime(visitor: &mut RegionResolutionVisitor, - child_id: ast::NodeId, + child_scope: CodeExtent, _sp: Span) { - match visitor.cx.parent { - Some(parent_id) => { - let child_scope = CodeExtent::from_node_id(child_id); - let parent_scope = CodeExtent::from_node_id(parent_id); - visitor.region_maps.record_encl_scope(child_scope, parent_scope); - } + match visitor.cx.parent.to_code_extent() { + Some(parent_scope) => + visitor.region_maps.record_encl_scope(child_scope, parent_scope), None => {} } } @@ -399,11 +522,9 @@ fn record_superlifetime(visitor: &mut RegionResolutionVisitor, fn record_var_lifetime(visitor: &mut RegionResolutionVisitor, var_id: ast::NodeId, _sp: Span) { - match visitor.cx.var_parent { - Some(parent_id) => { - let parent_scope = CodeExtent::from_node_id(parent_id); - visitor.region_maps.record_var_scope(var_id, parent_scope); - } + match visitor.cx.var_parent.to_code_extent() { + Some(parent_scope) => + visitor.region_maps.record_var_scope(var_id, parent_scope), None => { // this can happen in extern fn declarations like // @@ -415,21 +536,72 @@ fn record_var_lifetime(visitor: &mut RegionResolutionVisitor, fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) { debug!("resolve_block(blk.id={:?})", blk.id); - // Record the parent of this block. - record_superlifetime(visitor, blk.id, blk.span); + let prev_cx = visitor.cx; + + let blk_scope = CodeExtent::Misc(blk.id); + record_superlifetime(visitor, blk_scope, blk.span); // We treat the tail expression in the block (if any) somewhat // differently from the statements. The issue has to do with - // temporary lifetimes. If the user writes: + // temporary lifetimes. Consider the following: // - // { - // ... (&foo()) ... - // } + // quux({ + // let inner = ... (&bar()) ...; // + // (... (&foo()) ...) // (the tail expression) + // }, other_argument()); + // + // Each of the statements within the block is a terminating + // scope, and thus a temporary (e.g. the result of calling + // `bar()` in the initalizer expression for `let inner = ...;`) + // will be cleaned up immediately after its corresponding + // statement (i.e. `let inner = ...;`) executes. + // + // On the other hand, temporaries associated with evaluating the + // tail expression for the block are assigned lifetimes so that + // they will be cleaned up as part of the terminating scope + // *surrounding* the block expression. Here, the terminating + // scope for the block expression is the `quux(..)` call; so + // those temporaries will only be cleaned up *after* both + // `other_argument()` has run and also the call to `quux(..)` + // itself has returned. + + visitor.cx = Context { + var_parent: InnermostDeclaringBlock::Block(blk.id), + parent: InnermostEnclosingExpr::Some(blk.id), + }; + + { + // This block should be kept approximately in sync with + // `visit::walk_block`. (We manually walk the block, rather + // than call `walk_block`, in order to maintain precise + // `InnermostDeclaringBlock` information.) + + for (i, statement) in blk.stmts.iter().enumerate() { + if let ast::StmtDecl(_, stmt_id) = statement.node { + // Each StmtDecl introduces a subscope for bindings + // introduced by the declaration; this subscope covers + // a suffix of the block . Each subscope in a block + // has the previous subscope in the block as a parent, + // except for the first such subscope, which has the + // block itself as a parent. + let declaring = DeclaringStatementContext { + stmt_id: stmt_id, + block_id: blk.id, + stmt_index: i, + }; + record_superlifetime( + visitor, declaring.to_code_extent(), statement.span); + visitor.cx = Context { + var_parent: InnermostDeclaringBlock::Statement(declaring), + parent: InnermostEnclosingExpr::Statement(declaring), + }; + } + visitor.visit_stmt(&**statement) + } + visit::walk_expr_opt(visitor, &blk.expr) + } - let prev_cx = visitor.cx; - visitor.cx = Context {var_parent: Some(blk.id), parent: Some(blk.id)}; - visit::walk_block(visitor, blk); visitor.cx = prev_cx; } @@ -449,7 +621,7 @@ fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) { } fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) { - record_superlifetime(visitor, pat.id, pat.span); + record_superlifetime(visitor, CodeExtent::from_node_id(pat.id), pat.span); // If this is a binding (or maybe a binding, I'm too lazy to check // the def map) then record the lifetime of that binding. @@ -468,11 +640,17 @@ fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) { debug!("resolve_stmt(stmt.id={:?})", stmt_id); let stmt_scope = CodeExtent::from_node_id(stmt_id); + + // Every statement will clean up the temporaries created during + // execution of that statement. Therefore each statement has an + // associated destruction scope that represents the extent of the + // statement plus its destructors, and thus the extent for which + // regions referenced by the destructors need to survive. visitor.region_maps.mark_as_terminating_scope(stmt_scope); - record_superlifetime(visitor, stmt_id, stmt.span); + record_superlifetime(visitor, stmt_scope, stmt.span); let prev_parent = visitor.cx.parent; - visitor.cx.parent = Some(stmt_id); + visitor.cx.parent = InnermostEnclosingExpr::Some(stmt_id); visit::walk_stmt(visitor, stmt); visitor.cx.parent = prev_parent; } @@ -480,10 +658,11 @@ fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) { fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) { debug!("resolve_expr(expr.id={:?})", expr.id); - record_superlifetime(visitor, expr.id, expr.span); + let expr_scope = CodeExtent::Misc(expr.id); + record_superlifetime(visitor, expr_scope, expr.span); let prev_cx = visitor.cx; - visitor.cx.parent = Some(expr.id); + visitor.cx.parent = InnermostEnclosingExpr::Some(expr.id); { let region_maps = &mut visitor.region_maps; @@ -527,11 +706,11 @@ fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) { // The variable parent of everything inside (most importantly, the // pattern) is the body. - visitor.cx.var_parent = Some(body.id); + visitor.cx.var_parent = InnermostDeclaringBlock::Block(body.id); } ast::ExprMatch(..) => { - visitor.cx.var_parent = Some(expr.id); + visitor.cx.var_parent = InnermostDeclaringBlock::Match(expr.id); } ast::ExprAssignOp(..) | ast::ExprIndex(..) | @@ -568,19 +747,13 @@ fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) { debug!("resolve_local(local.id={:?},local.init={:?})", local.id,local.init.is_some()); - let blk_id = match visitor.cx.var_parent { - Some(id) => id, - None => { - visitor.sess.span_bug( - local.span, - "local without enclosing block"); - } - }; - // For convenience in trans, associate with the local-id the var // scope that will be used for any bindings declared in this // pattern. - let blk_scope = CodeExtent::from_node_id(blk_id); + let blk_scope = visitor.cx.var_parent.to_code_extent() + .unwrap_or_else(|| visitor.sess.span_bug( + local.span, "local without enclosing block")); + visitor.region_maps.record_var_scope(local.id, blk_scope); // As an exception to the normal rules governing temporary @@ -803,7 +976,10 @@ fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) { fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) { // Items create a new outer block scope as far as we're concerned. let prev_cx = visitor.cx; - visitor.cx = Context {var_parent: None, parent: None}; + visitor.cx = Context { + var_parent: InnermostDeclaringBlock::None, + parent: InnermostEnclosingExpr::None + }; visit::walk_item(visitor, item); visitor.cx = prev_cx; } @@ -829,15 +1005,20 @@ fn resolve_fn(visitor: &mut RegionResolutionVisitor, let outer_cx = visitor.cx; // The arguments and `self` are parented to the body of the fn. - visitor.cx = Context { parent: Some(body.id), - var_parent: Some(body.id) }; + visitor.cx = Context { + parent: InnermostEnclosingExpr::Some(body.id), + var_parent: InnermostDeclaringBlock::Block(body.id) + }; visit::walk_fn_decl(visitor, decl); // The body of the fn itself is either a root scope (top-level fn) // or it continues with the inherited scope (closures). match fk { visit::FkItemFn(..) | visit::FkMethod(..) => { - visitor.cx = Context { parent: None, var_parent: None }; + visitor.cx = Context { + parent: InnermostEnclosingExpr::None, + var_parent: InnermostDeclaringBlock::None + }; visitor.visit_block(body); visitor.cx = outer_cx; } @@ -898,7 +1079,10 @@ pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps { let mut visitor = RegionResolutionVisitor { sess: sess, region_maps: &maps, - cx: Context { parent: None, var_parent: None } + cx: Context { + parent: InnermostEnclosingExpr::None, + var_parent: InnermostDeclaringBlock::None, + } }; visit::walk_crate(&mut visitor, krate); } @@ -911,7 +1095,10 @@ pub fn resolve_inlined_item(sess: &Session, let mut visitor = RegionResolutionVisitor { sess: sess, region_maps: region_maps, - cx: Context { parent: None, var_parent: None } + cx: Context { + parent: InnermostEnclosingExpr::None, + var_parent: InnermostDeclaringBlock::None + } }; visit::walk_inlined_item(&mut visitor, item); } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 0ee26ce1cd3..86cf030c828 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -3126,7 +3126,6 @@ pub fn type_is_scalar(ty: Ty) -> bool { ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) | ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) | ty_bare_fn(..) | ty_ptr(_) => true, - ty_tup(ref tys) if tys.is_empty() => true, _ => false } } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index f93f5903e01..5601898136c 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -10,6 +10,7 @@ use middle::def; +use middle::region; use middle::subst::{VecPerParamSpace,Subst}; use middle::subst; use middle::ty::{BoundRegion, BrAnon, BrNamed}; @@ -84,37 +85,41 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region) -> (String, Option<Span>) { return match region { ReScope(scope) => { - match cx.map.find(scope.node_id()) { - Some(ast_map::NodeBlock(ref blk)) => { - explain_span(cx, "block", blk.span) - } - Some(ast_map::NodeExpr(expr)) => { - match expr.node { - ast::ExprCall(..) => explain_span(cx, "call", expr.span), - ast::ExprMethodCall(..) => { - explain_span(cx, "method call", expr.span) - }, - ast::ExprMatch(_, _, ast::MatchSource::IfLetDesugar { .. }) => - explain_span(cx, "if let", expr.span), - ast::ExprMatch(_, _, ast::MatchSource::WhileLetDesugar) => { - explain_span(cx, "while let", expr.span) - }, - ast::ExprMatch(..) => explain_span(cx, "match", expr.span), - _ => explain_span(cx, "expression", expr.span) - } - } - Some(ast_map::NodeStmt(stmt)) => { - explain_span(cx, "statement", stmt.span) - } - Some(ast_map::NodeItem(it)) => { - let tag = item_scope_tag(&*it); - explain_span(cx, tag, it.span) - } + let new_string; + let on_unknown_scope = |&:| { + (format!("unknown scope: {:?}. Please report a bug.", scope), None) + }; + let span = match scope.span(&cx.map) { + Some(s) => s, + None => return on_unknown_scope(), + }; + let tag = match cx.map.find(scope.node_id()) { + Some(ast_map::NodeBlock(_)) => "block", + Some(ast_map::NodeExpr(expr)) => match expr.node { + ast::ExprCall(..) => "call", + ast::ExprMethodCall(..) => "method call", + ast::ExprMatch(_, _, ast::MatchSource::IfLetDesugar { .. }) => "if let", + ast::ExprMatch(_, _, ast::MatchSource::WhileLetDesugar) => "while let", + ast::ExprMatch(..) => "match", + _ => "expression", + }, + Some(ast_map::NodeStmt(_)) => "statement", + Some(ast_map::NodeItem(it)) => item_scope_tag(&*it), Some(_) | None => { // this really should not happen - (format!("unknown scope: {:?}. Please report a bug.", scope), None) + return on_unknown_scope(); } - } + }; + let scope_decorated_tag = match scope { + region::CodeExtent::Misc(_) => tag, + region::CodeExtent::Remainder(r) => { + new_string = format!("block suffix following statement {}", + r.first_statement_index); + new_string.as_slice() + } + }; + explain_span(cx, scope_decorated_tag, span) + } ReFree(ref fr) => { @@ -867,6 +872,17 @@ impl<'tcx> Repr<'tcx> for ty::FreeRegion { } } +impl<'tcx> Repr<'tcx> for region::CodeExtent { + fn repr(&self, _tcx: &ctxt) -> String { + match *self { + region::CodeExtent::Misc(node_id) => + format!("Misc({})", node_id), + region::CodeExtent::Remainder(rem) => + format!("Remainder({}, {})", rem.block, rem.first_statement_index), + } + } +} + impl<'tcx> Repr<'tcx> for ast::DefId { fn repr(&self, tcx: &ctxt) -> String { // Unfortunately, there seems to be no way to attempt to print diff --git a/src/librustc_back/archive.rs b/src/librustc_back/archive.rs index fa754b4a301..ee8bc71668b 100644 --- a/src/librustc_back/archive.rs +++ b/src/librustc_back/archive.rs @@ -10,10 +10,10 @@ //! A helper class for dealing with static archives -use std::io::fs::PathExtensions; -use std::io::process::{Command, ProcessOutput}; -use std::io::{fs, TempDir}; -use std::io; +use std::old_io::fs::PathExtensions; +use std::old_io::process::{Command, ProcessOutput}; +use std::old_io::{fs, TempDir}; +use std::old_io; use std::os; use std::str; use syntax::diagnostic::Handler as ErrorHandler; @@ -172,7 +172,7 @@ impl<'a> ArchiveBuilder<'a> { /// Adds all of the contents of a native library to this archive. This will /// search in the relevant locations for a library named `name`. - pub fn add_native_library(&mut self, name: &str) -> io::IoResult<()> { + pub fn add_native_library(&mut self, name: &str) -> old_io::IoResult<()> { let location = find_library(name, &self.archive.slib_prefix[], &self.archive.slib_suffix[], @@ -187,7 +187,7 @@ impl<'a> ArchiveBuilder<'a> { /// This ignores adding the bytecode from the rlib, and if LTO is enabled /// then the object file also isn't added. pub fn add_rlib(&mut self, rlib: &Path, name: &str, - lto: bool) -> io::IoResult<()> { + lto: bool) -> old_io::IoResult<()> { // Ignoring obj file starting with the crate name // as simple comparison is not enough - there // might be also an extra name suffix @@ -205,7 +205,7 @@ impl<'a> ArchiveBuilder<'a> { } /// Adds an arbitrary file to this archive - pub fn add_file(&mut self, file: &Path) -> io::IoResult<()> { + pub fn add_file(&mut self, file: &Path) -> old_io::IoResult<()> { let filename = Path::new(file.filename().unwrap()); let new_file = self.work_dir.path().join(&filename); try!(fs::copy(file, &new_file)); @@ -274,8 +274,9 @@ impl<'a> ArchiveBuilder<'a> { self.archive } - fn add_archive<F>(&mut self, archive: &Path, name: &str, mut skip: F) -> io::IoResult<()> where - F: FnMut(&str) -> bool, + fn add_archive<F>(&mut self, archive: &Path, name: &str, + mut skip: F) -> old_io::IoResult<()> + where F: FnMut(&str) -> bool, { let loc = TempDir::new("rsar").unwrap(); diff --git a/src/librustc_back/fs.rs b/src/librustc_back/fs.rs index d7deb09985f..24f81b02478 100644 --- a/src/librustc_back/fs.rs +++ b/src/librustc_back/fs.rs @@ -8,13 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; -use std::io::fs; +use std::old_io; +use std::old_io::fs; use std::os; /// Returns an absolute path in the filesystem that `path` points to. The /// returned path does not contain any symlinks in its hierarchy. -pub fn realpath(original: &Path) -> io::IoResult<Path> { +pub fn realpath(original: &Path) -> old_io::IoResult<Path> { static MAX_LINKS_FOLLOWED: uint = 256; let original = os::make_absolute(original).unwrap(); @@ -32,12 +32,12 @@ pub fn realpath(original: &Path) -> io::IoResult<Path> { loop { if followed == MAX_LINKS_FOLLOWED { - return Err(io::standard_error(io::InvalidInput)) + return Err(old_io::standard_error(old_io::InvalidInput)) } match fs::lstat(&result) { Err(..) => break, - Ok(ref stat) if stat.kind != io::FileType::Symlink => break, + Ok(ref stat) if stat.kind != old_io::FileType::Symlink => break, Ok(..) => { followed += 1; let path = try!(fs::readlink(&result)); @@ -53,10 +53,10 @@ pub fn realpath(original: &Path) -> io::IoResult<Path> { #[cfg(all(not(windows), test))] mod test { - use std::io; - use std::io::fs::{File, symlink, mkdir, mkdir_recursive}; + use std::old_io; + use std::old_io::fs::{File, symlink, mkdir, mkdir_recursive}; use super::realpath; - use std::io::TempDir; + use std::old_io::TempDir; #[test] fn realpath_works() { @@ -68,7 +68,7 @@ mod test { let linkdir = tmpdir.join("test3"); File::create(&file).unwrap(); - mkdir(&dir, io::USER_RWX).unwrap(); + mkdir(&dir, old_io::USER_RWX).unwrap(); symlink(&file, &link).unwrap(); symlink(&dir, &linkdir).unwrap(); @@ -91,8 +91,8 @@ mod test { let e = d.join("e"); let f = a.join("f"); - mkdir_recursive(&b, io::USER_RWX).unwrap(); - mkdir_recursive(&d, io::USER_RWX).unwrap(); + mkdir_recursive(&b, old_io::USER_RWX).unwrap(); + mkdir_recursive(&d, old_io::USER_RWX).unwrap(); File::create(&f).unwrap(); symlink(&Path::new("../d/e"), &c).unwrap(); symlink(&Path::new("../f"), &e).unwrap(); diff --git a/src/librustc_back/rpath.rs b/src/librustc_back/rpath.rs index d24fd6a5b3f..bafd5fbe944 100644 --- a/src/librustc_back/rpath.rs +++ b/src/librustc_back/rpath.rs @@ -11,7 +11,7 @@ use std::collections::HashSet; use std::os; -use std::io::IoError; +use std::old_io::IoError; use syntax::ast; pub struct RPathConfig<F, G> where diff --git a/src/librustc_back/target/apple_ios_base.rs b/src/librustc_back/target/apple_ios_base.rs index ac133cabc3b..715bcc4f36d 100644 --- a/src/librustc_back/target/apple_ios_base.rs +++ b/src/librustc_back/target/apple_ios_base.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::{Command, IoError, OtherIoError}; +use std::old_io::{Command, IoError, OtherIoError}; use target::TargetOptions; use self::Arch::*; diff --git a/src/librustc_back/target/i686_apple_darwin.rs b/src/librustc_back/target/i686_apple_darwin.rs index 1b079323bf9..fcea900283d 100644 --- a/src/librustc_back/target/i686_apple_darwin.rs +++ b/src/librustc_back/target/i686_apple_darwin.rs @@ -12,6 +12,7 @@ use target::Target; pub fn target() -> Target { let mut base = super::apple_base::opts(); + base.cpu = "yonah".to_string(); base.pre_link_args.push("-m32".to_string()); Target { diff --git a/src/librustc_back/target/i686_pc_windows_gnu.rs b/src/librustc_back/target/i686_pc_windows_gnu.rs index c2ab68ee052..249f2d440e6 100644 --- a/src/librustc_back/target/i686_pc_windows_gnu.rs +++ b/src/librustc_back/target/i686_pc_windows_gnu.rs @@ -12,6 +12,7 @@ use target::Target; pub fn target() -> Target { let mut options = super::windows_base::opts(); + options.cpu = "pentium4".to_string(); // Mark all dynamic libraries and executables as compatible with the larger 4GiB address // space available to x86 Windows binaries on x86_64. diff --git a/src/librustc_back/target/i686_unknown_dragonfly.rs b/src/librustc_back/target/i686_unknown_dragonfly.rs index 7910eba7ea1..4450d8d6778 100644 --- a/src/librustc_back/target/i686_unknown_dragonfly.rs +++ b/src/librustc_back/target/i686_unknown_dragonfly.rs @@ -12,6 +12,7 @@ use target::Target; pub fn target() -> Target { let mut base = super::dragonfly_base::opts(); + base.cpu = "pentium4".to_string(); base.pre_link_args.push("-m32".to_string()); Target { diff --git a/src/librustc_back/target/i686_unknown_linux_gnu.rs b/src/librustc_back/target/i686_unknown_linux_gnu.rs index c93a564fef5..f21f6adfb4c 100644 --- a/src/librustc_back/target/i686_unknown_linux_gnu.rs +++ b/src/librustc_back/target/i686_unknown_linux_gnu.rs @@ -12,6 +12,7 @@ use target::Target; pub fn target() -> Target { let mut base = super::linux_base::opts(); + base.cpu = "pentium4".to_string(); base.pre_link_args.push("-m32".to_string()); Target { diff --git a/src/librustc_back/target/mod.rs b/src/librustc_back/target/mod.rs index dd0fa527f17..a63e8237b4b 100644 --- a/src/librustc_back/target/mod.rs +++ b/src/librustc_back/target/mod.rs @@ -48,7 +48,7 @@ use serialize::json::Json; use syntax::{diagnostic, abi}; use std::default::Default; -use std::io::fs::PathExtensions; +use std::old_io::fs::PathExtensions; mod windows_base; mod linux_base; @@ -302,7 +302,7 @@ impl Target { /// JSON decoding. pub fn search(target: &str) -> Result<Target, String> { use std::os; - use std::io::File; + use std::old_io::File; use std::path::Path; use serialize::json; diff --git a/src/librustc_back/target/x86_64_apple_darwin.rs b/src/librustc_back/target/x86_64_apple_darwin.rs index f2abfd4564c..0b3b2bea62d 100644 --- a/src/librustc_back/target/x86_64_apple_darwin.rs +++ b/src/librustc_back/target/x86_64_apple_darwin.rs @@ -12,7 +12,7 @@ use target::Target; pub fn target() -> Target { let mut base = super::apple_base::opts(); - base.cpu = "x86-64".to_string(); + base.cpu = "core2".to_string(); base.eliminate_frame_pointer = false; base.pre_link_args.push("-m64".to_string()); diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 4d5c2b765fe..6e76519ce23 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -30,8 +30,8 @@ use rustc_privacy; use serialize::json; -use std::io; -use std::io::fs; +use std::old_io; +use std::old_io::fs; use std::os; use syntax::ast; use syntax::ast_map; @@ -100,6 +100,7 @@ pub fn compile_input(sess: Session, &id[])); let mut forest = ast_map::Forest::new(expanded_crate); + let arenas = ty::CtxtArenas::new(); let ast_map = assign_node_ids_and_map(&sess, &mut forest); write_out_deps(&sess, input, &outputs, &id[]); @@ -111,7 +112,6 @@ pub fn compile_input(sess: Session, &ast_map, &id[])); - let arenas = ty::CtxtArenas::new(); let analysis = phase_3_run_analysis_passes(sess, ast_map, &arenas, @@ -794,14 +794,14 @@ fn write_out_deps(sess: &Session, _ => return, }; - let result = (|&:| -> io::IoResult<()> { + let result = (|&:| -> old_io::IoResult<()> { // Build a list of files used to compile the output and // write Makefile-compatible dependency rules let files: Vec<String> = sess.codemap().files.borrow() .iter().filter(|fmap| fmap.is_real_file()) .map(|fmap| escape_dep_filename(&fmap.name[])) .collect(); - let mut file = try!(io::File::create(&deps_filename)); + let mut file = try!(old_io::File::create(&deps_filename)); for path in out_filenames.iter() { try!(write!(&mut file as &mut Writer, "{}: {}\n\n", path.display(), files.connect(" "))); diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index ffce577899b..727638c29c3 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -73,7 +73,7 @@ use rustc::metadata::creader::CrateOrString::Str; use rustc::util::common::time; use std::cmp::Ordering::Equal; -use std::io; +use std::old_io; use std::iter::repeat; use std::os; use std::sync::mpsc::channel; @@ -142,7 +142,7 @@ fn run_compiler(args: &[String]) { 1u => { let ifile = &matches.free[0][]; if ifile == "-" { - let contents = io::stdin().read_to_end().unwrap(); + let contents = old_io::stdin().read_to_end().unwrap(); let src = String::from_utf8(contents).unwrap(); (Input::Str(src), None) } else { @@ -196,7 +196,7 @@ fn run_compiler(args: &[String]) { if r.contains(&("ls".to_string())) { match input { Input::File(ref ifile) => { - let mut stdout = io::stdout(); + let mut stdout = old_io::stdout(); list_metadata(&sess, &(*ifile), &mut stdout).unwrap(); } Input::Str(_) => { @@ -599,7 +599,7 @@ fn parse_crate_attrs(sess: &Session, input: &Input) -> } pub fn list_metadata(sess: &Session, path: &Path, - out: &mut io::Writer) -> io::IoResult<()> { + out: &mut old_io::Writer) -> old_io::IoResult<()> { metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx, path, out) } @@ -612,8 +612,8 @@ pub fn monitor<F:FnOnce()+Send>(f: F) { static STACK_SIZE: uint = 8 * 1024 * 1024; // 8MB let (tx, rx) = channel(); - let w = io::ChanWriter::new(tx); - let mut r = io::ChanReader::new(rx); + let w = old_io::ChanWriter::new(tx); + let mut r = old_io::ChanReader::new(rx); let mut cfg = thread::Builder::new().name("rustc".to_string()); @@ -623,7 +623,7 @@ pub fn monitor<F:FnOnce()+Send>(f: F) { cfg = cfg.stack_size(STACK_SIZE); } - match cfg.scoped(move || { std::io::stdio::set_stderr(box w); f() }).join() { + match cfg.scoped(move || { std::old_io::stdio::set_stderr(box w); f() }).join() { Ok(()) => { /* fallthrough */ } Err(value) => { // Thread panicked without emitting a fatal diagnostic @@ -665,7 +665,7 @@ pub fn monitor<F:FnOnce()+Send>(f: F) { // Panic so the process returns a failure code, but don't pollute the // output with some unnecessary panic messages, we've already // printed everything that we needed to. - io::stdio::set_stderr(box io::util::NullWriter); + old_io::stdio::set_stderr(box old_io::util::NullWriter); panic!(); } } diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 582e1032324..b09e9f14357 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -38,7 +38,7 @@ use syntax::ptr::P; use graphviz as dot; -use std::io::{self, MemReader}; +use std::old_io::{self, MemReader}; use std::option; use std::str::FromStr; @@ -208,7 +208,7 @@ impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> { impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> { fn pre(&self, s: &mut pprust::State, - node: pprust::AnnNode) -> io::IoResult<()> { + node: pprust::AnnNode) -> old_io::IoResult<()> { match node { pprust::NodeExpr(_) => s.popen(), _ => Ok(()) @@ -216,7 +216,7 @@ impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> { } fn post(&self, s: &mut pprust::State, - node: pprust::AnnNode) -> io::IoResult<()> { + node: pprust::AnnNode) -> old_io::IoResult<()> { match node { pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()), @@ -259,7 +259,7 @@ impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> { impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> { fn post(&self, s: &mut pprust::State, - node: pprust::AnnNode) -> io::IoResult<()> { + node: pprust::AnnNode) -> old_io::IoResult<()> { match node { pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => { try!(pp::space(&mut s.s)); @@ -294,7 +294,7 @@ impl<'tcx> PrinterSupport<'tcx> for TypedAnnotation<'tcx> { impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> { fn pre(&self, s: &mut pprust::State, - node: pprust::AnnNode) -> io::IoResult<()> { + node: pprust::AnnNode) -> old_io::IoResult<()> { match node { pprust::NodeExpr(_) => s.popen(), _ => Ok(()) @@ -302,7 +302,7 @@ impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> { } fn post(&self, s: &mut pprust::State, - node: pprust::AnnNode) -> io::IoResult<()> { + node: pprust::AnnNode) -> old_io::IoResult<()> { let tcx = &self.analysis.ty_cx; match node { pprust::NodeExpr(expr) => { @@ -548,9 +548,9 @@ pub fn pretty_print_input(sess: Session, let mut rdr = MemReader::new(src); let out = match ofile { - None => box io::stdout() as Box<Writer+'static>, + None => box old_io::stdout() as Box<Writer+'static>, Some(p) => { - let r = io::File::create(&p); + let r = old_io::File::create(&p); match r { Ok(w) => box w as Box<Writer+'static>, Err(e) => panic!("print-print failed to open {} due to {}", @@ -643,11 +643,11 @@ pub fn pretty_print_input(sess: Session, }.unwrap() } -fn print_flowgraph<W:io::Writer>(variants: Vec<borrowck_dot::Variant>, +fn print_flowgraph<W:old_io::Writer>(variants: Vec<borrowck_dot::Variant>, analysis: ty::CrateAnalysis, code: blocks::Code, mode: PpFlowGraphMode, - mut out: W) -> io::IoResult<()> { + mut out: W) -> old_io::IoResult<()> { let ty_cx = &analysis.ty_cx; let cfg = match code { blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block), @@ -687,11 +687,11 @@ fn print_flowgraph<W:io::Writer>(variants: Vec<borrowck_dot::Variant>, } } - fn expand_err_details(r: io::IoResult<()>) -> io::IoResult<()> { + fn expand_err_details(r: old_io::IoResult<()>) -> old_io::IoResult<()> { r.map_err(|ioerr| { let orig_detail = ioerr.detail.clone(); let m = "graphviz::render failed"; - io::IoError { + old_io::IoError { detail: Some(match orig_detail { None => m.to_string(), Some(d) => format!("{}: {}", m, d) diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index 3543fe07269..52d7415a523 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -103,7 +103,7 @@ fn test_env<F>(source_string: &str, let codemap = CodeMap::new(); let diagnostic_handler = - diagnostic::mk_handler(emitter); + diagnostic::mk_handler(true, emitter); let span_diagnostic_handler = diagnostic::mk_span_handler(diagnostic_handler, codemap); @@ -115,6 +115,7 @@ fn test_env<F>(source_string: &str, .expect("phase 2 aborted"); let mut forest = ast_map::Forest::new(krate); + let arenas = ty::CtxtArenas::new(); let ast_map = driver::assign_node_ids_and_map(&sess, &mut forest); let krate = ast_map.krate(); @@ -125,7 +126,6 @@ fn test_env<F>(source_string: &str, let named_region_map = resolve_lifetime::krate(&sess, krate, &def_map); let region_map = region::resolve_crate(&sess, krate); let stability_index = stability::Index::build(&sess, krate); - let arenas = ty::CtxtArenas::new(); let tcx = ty::mk_ctxt(sess, &arenas, def_map, diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index eedfc940751..f5a6f3d95a2 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -27,9 +27,9 @@ use util::common::time; use util::ppaux; use util::sha2::{Digest, Sha256}; -use std::io::fs::PathExtensions; -use std::io::{fs, TempDir, Command}; -use std::io; +use std::old_io::fs::PathExtensions; +use std::old_io::{fs, TempDir, Command}; +use std::old_io; use std::mem; use std::str; use std::string::String; @@ -425,7 +425,7 @@ pub fn invalid_output_for_target(sess: &Session, fn is_writeable(p: &Path) -> bool { match p.stat() { Err(..) => true, - Ok(m) => m.perm & io::USER_WRITE == io::USER_WRITE + Ok(m) => m.perm & old_io::USER_WRITE == old_io::USER_WRITE } } @@ -586,8 +586,7 @@ fn link_rlib<'a>(sess: &'a Session, // the same filename for metadata (stomping over one another) let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir"); let metadata = tmpdir.path().join(METADATA_FILENAME); - match fs::File::create(&metadata).write(&trans.metadata - []) { + match fs::File::create(&metadata).write_all(&trans.metadata[]) { Ok(..) => {} Err(e) => { sess.err(&format!("failed to write {}: {}", @@ -671,13 +670,13 @@ fn link_rlib<'a>(sess: &'a Session, fn write_rlib_bytecode_object_v1<T: Writer>(writer: &mut T, bc_data_deflated: &[u8]) - -> ::std::io::IoResult<()> { + -> ::std::old_io::IoResult<()> { let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64; - try! { writer.write(RLIB_BYTECODE_OBJECT_MAGIC) }; + try! { writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC) }; try! { writer.write_le_u32(1) }; try! { writer.write_le_u64(bc_data_deflated_size) }; - try! { writer.write(&bc_data_deflated[]) }; + try! { writer.write_all(&bc_data_deflated[]) }; let number_of_bytes_written_so_far = RLIB_BYTECODE_OBJECT_MAGIC.len() + // magic id @@ -1201,7 +1200,7 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session, // Fix up permissions of the copy, as fs::copy() preserves // permissions, but the original file may have been installed // by a package manager and may be read-only. - match fs::chmod(&dst, io::USER_READ | io::USER_WRITE) { + match fs::chmod(&dst, old_io::USER_READ | old_io::USER_WRITE) { Ok(..) => {} Err(e) => { sess.err(&format!("failed to chmod {} when preparing \ diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index 4fd456d813a..15b9d6237ed 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -23,8 +23,8 @@ use syntax::diagnostic; use syntax::diagnostic::{Emitter, Handler, Level, mk_handler}; use std::ffi::{self, CString}; -use std::io::Command; -use std::io::fs; +use std::old_io::Command; +use std::old_io::fs; use std::iter::Unfold; use std::ptr; use std::str; @@ -728,9 +728,9 @@ pub fn run_passes(sess: &Session, println!("{:?}", &cmd); } - cmd.stdin(::std::io::process::Ignored) - .stdout(::std::io::process::InheritFd(1)) - .stderr(::std::io::process::InheritFd(2)); + cmd.stdin(::std::old_io::process::Ignored) + .stdout(::std::old_io::process::InheritFd(1)) + .stderr(::std::old_io::process::InheritFd(2)); match cmd.status() { Ok(status) => { if !status.success() { diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index 71ca6a4db03..7e7176d661c 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -33,7 +33,7 @@ use middle::def; use middle::ty::{self, Ty}; use std::cell::Cell; -use std::io::{self, File, fs}; +use std::old_io::{self, File, fs}; use std::os; use syntax::ast_util::{self, PostExpansionMethod}; @@ -1532,7 +1532,7 @@ pub fn process_crate(sess: &Session, }, }; - match fs::mkdir_recursive(&root_path, io::USER_RWX) { + match fs::mkdir_recursive(&root_path, old_io::USER_RWX) { Err(e) => sess.err(&format!("Could not create directory {}: {}", root_path.display(), e)[]), _ => (), diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index 230a4c5d427..5a98bc4da36 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -1784,15 +1784,16 @@ pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>, debug!("trans_closure(..., param_substs={})", param_substs.repr(ccx.tcx())); - let arena = TypedArena::new(); - let fcx = new_fn_ctxt(ccx, - llfndecl, - fn_ast_id, - closure_env.kind != closure::NotClosure, - output_type, - param_substs, - Some(body.span), - &arena); + let (arena, fcx): (TypedArena<_>, FunctionContext); + arena = TypedArena::new(); + fcx = new_fn_ctxt(ccx, + llfndecl, + fn_ast_id, + closure_env.kind != closure::NotClosure, + output_type, + param_substs, + Some(body.span), + &arena); let mut bcx = init_function(&fcx, false, output_type); // cleanup scope for the incoming arguments @@ -2046,9 +2047,10 @@ fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx ty_to_string(ccx.tcx(), ctor_ty))[]) }; - let arena = TypedArena::new(); - let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty, - param_substs, None, &arena); + let (arena, fcx): (TypedArena<_>, FunctionContext); + arena = TypedArena::new(); + fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty, + param_substs, None, &arena); let bcx = init_function(&fcx, false, result_ty); assert!(!fcx.needs_ret_allocas); diff --git a/src/librustc_trans/trans/callee.rs b/src/librustc_trans/trans/callee.rs index 73d174c2c34..d038407791e 100644 --- a/src/librustc_trans/trans/callee.rs +++ b/src/librustc_trans/trans/callee.rs @@ -322,16 +322,17 @@ pub fn trans_fn_pointer_shim<'a, 'tcx>( &function_name[]); // - let block_arena = TypedArena::new(); let empty_substs = Substs::trans_empty(); - let fcx = new_fn_ctxt(ccx, - llfn, - ast::DUMMY_NODE_ID, - false, - sig.output, - &empty_substs, - None, - &block_arena); + let (block_arena, fcx): (TypedArena<_>, FunctionContext); + block_arena = TypedArena::new(); + fcx = new_fn_ctxt(ccx, + llfn, + ast::DUMMY_NODE_ID, + false, + sig.output, + &empty_substs, + None, + &block_arena); let mut bcx = init_function(&fcx, false, sig.output); // the first argument (`self`) will be ptr to the the fn pointer diff --git a/src/librustc_trans/trans/glue.rs b/src/librustc_trans/trans/glue.rs index c1d98987991..69d1922ab9a 100644 --- a/src/librustc_trans/trans/glue.rs +++ b/src/librustc_trans/trans/glue.rs @@ -540,11 +540,12 @@ fn make_generic_glue<'a, 'tcx, F>(ccx: &CrateContext<'a, 'tcx>, let glue_name = format!("glue {} {}", name, ty_to_short_str(ccx.tcx(), t)); let _s = StatRecorder::new(ccx, glue_name); - let arena = TypedArena::new(); let empty_param_substs = Substs::trans_empty(); - let fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, false, - ty::FnConverging(ty::mk_nil(ccx.tcx())), - &empty_param_substs, None, &arena); + let (arena, fcx): (TypedArena<_>, FunctionContext); + arena = TypedArena::new(); + fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, false, + ty::FnConverging(ty::mk_nil(ccx.tcx())), + &empty_param_substs, None, &arena); let bcx = init_function(&fcx, false, ty::FnConverging(ty::mk_nil(ccx.tcx()))); diff --git a/src/librustc_trans/trans/meth.rs b/src/librustc_trans/trans/meth.rs index 580a2d5ae3d..187b73b1b09 100644 --- a/src/librustc_trans/trans/meth.rs +++ b/src/librustc_trans/trans/meth.rs @@ -601,17 +601,17 @@ pub fn trans_object_shim<'a, 'tcx>( let sig = ty::erase_late_bound_regions(ccx.tcx(), &fty.sig); - // - let block_arena = TypedArena::new(); let empty_substs = Substs::trans_empty(); - let fcx = new_fn_ctxt(ccx, - llfn, - ast::DUMMY_NODE_ID, - false, - sig.output, - &empty_substs, - None, - &block_arena); + let (block_arena, fcx): (TypedArena<_>, FunctionContext); + block_arena = TypedArena::new(); + fcx = new_fn_ctxt(ccx, + llfn, + ast::DUMMY_NODE_ID, + false, + sig.output, + &empty_substs, + None, + &block_arena); let mut bcx = init_function(&fcx, false, sig.output); // the first argument (`self`) will be a trait object diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index 61332ada506..4c5a8144cbd 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -1049,8 +1049,8 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { // if there are any. assert_eq!(substs.types.len(subst::FnSpace), 0); assert_eq!(substs.regions().len(subst::FnSpace), 0); - let mut substs = substs; let placeholder; + let mut substs = substs; if !method.generics.types.is_empty_in(subst::FnSpace) || !method.generics.regions.is_empty_in(subst::FnSpace) diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 5b172598ebb..65560040f47 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -990,86 +990,65 @@ fn check_impl_items_against_trait<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, } } -fn check_cast(fcx: &FnCtxt, - cast_expr: &ast::Expr, - e: &ast::Expr, - t: &ast::Ty) { - let id = cast_expr.id; - let span = cast_expr.span; - - // Find the type of `e`. Supply hints based on the type we are casting to, - // if appropriate. - let t_1 = fcx.to_ty(t); - let t_1 = structurally_resolved_type(fcx, span, t_1); - - check_expr_with_expectation(fcx, e, ExpectCastableToType(t_1)); - - let t_e = fcx.expr_ty(e); - - debug!("t_1={}", fcx.infcx().ty_to_string(t_1)); - debug!("t_e={}", fcx.infcx().ty_to_string(t_e)); - - if ty::type_is_error(t_e) { - fcx.write_error(id); - return - } - - if !fcx.type_is_known_to_be_sized(t_1, cast_expr.span) { - let tstr = fcx.infcx().ty_to_string(t_1); - fcx.type_error_message(span, |actual| { - format!("cast to unsized type: `{}` as `{}`", actual, tstr) - }, t_e, None); - match t_e.sty { - ty::ty_rptr(_, ty::mt { mutbl: mt, .. }) => { - let mtstr = match mt { - ast::MutMutable => "mut ", - ast::MutImmutable => "" - }; - if ty::type_is_trait(t_1) { - span_help!(fcx.tcx().sess, t.span, "did you mean `&{}{}`?", mtstr, tstr); - } else { - span_help!(fcx.tcx().sess, span, - "consider using an implicit coercion to `&{}{}` instead", - mtstr, tstr); - } - } - ty::ty_uniq(..) => { - span_help!(fcx.tcx().sess, t.span, "did you mean `Box<{}>`?", tstr); - } - _ => { - span_help!(fcx.tcx().sess, e.span, - "consider using a box or reference as appropriate"); +fn report_cast_to_unsized_type<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, + span: Span, + t_span: Span, + e_span: Span, + t_1: Ty<'tcx>, + t_e: Ty<'tcx>, + id: ast::NodeId) { + let tstr = fcx.infcx().ty_to_string(t_1); + fcx.type_error_message(span, |actual| { + format!("cast to unsized type: `{}` as `{}`", actual, tstr) + }, t_e, None); + match t_e.sty { + ty::ty_rptr(_, ty::mt { mutbl: mt, .. }) => { + let mtstr = match mt { + ast::MutMutable => "mut ", + ast::MutImmutable => "" + }; + if ty::type_is_trait(t_1) { + span_help!(fcx.tcx().sess, t_span, "did you mean `&{}{}`?", mtstr, tstr); + } else { + span_help!(fcx.tcx().sess, span, + "consider using an implicit coercion to `&{}{}` instead", + mtstr, tstr); } } - fcx.write_error(id); - return - } - - if ty::type_is_trait(t_1) { - // This will be looked up later on. - vtable::check_object_cast(fcx, cast_expr, e, t_1); - fcx.write_ty(id, t_1); - return + ty::ty_uniq(..) => { + span_help!(fcx.tcx().sess, t_span, "did you mean `Box<{}>`?", tstr); + } + _ => { + span_help!(fcx.tcx().sess, e_span, + "consider using a box or reference as appropriate"); + } } + fcx.write_error(id); +} - let t_1 = structurally_resolved_type(fcx, span, t_1); - let t_e = structurally_resolved_type(fcx, span, t_e); - if ty::type_is_nil(t_e) { - fcx.type_error_message(span, |actual| { - format!("cast from nil: `{}` as `{}`", - actual, - fcx.infcx().ty_to_string(t_1)) - }, t_e, None); - } else if ty::type_is_nil(t_1) { +fn check_cast_inner<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, + span: Span, + t_1: Ty<'tcx>, + t_e: Ty<'tcx>, + e: &ast::Expr) { + fn cast_through_integer_err<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, + span: Span, + t_1: Ty<'tcx>, + t_e: Ty<'tcx>) { fcx.type_error_message(span, |actual| { - format!("cast to nil: `{}` as `{}`", + format!("illegal cast; cast through an \ + integer first: `{}` as `{}`", actual, fcx.infcx().ty_to_string(t_1)) }, t_e, None); } let t_e_is_bare_fn_item = ty::type_is_bare_fn_item(t_e); + let t_e_is_scalar = ty::type_is_scalar(t_e); + let t_e_is_integral = ty::type_is_integral(t_e); + let t_e_is_float = ty::type_is_floating_point(t_e); + let t_e_is_c_enum = ty::type_is_c_like_enum(fcx.tcx(), t_e); let t_1_is_scalar = ty::type_is_scalar(t_1); let t_1_is_char = ty::type_is_char(t_1); @@ -1078,18 +1057,9 @@ fn check_cast(fcx: &FnCtxt, // casts to scalars other than `char` and `bare fn` are trivial let t_1_is_trivial = t_1_is_scalar && !t_1_is_char && !t_1_is_bare_fn; + if t_e_is_bare_fn_item && t_1_is_bare_fn { demand::coerce(fcx, e.span, t_1, &*e); - } else if ty::type_is_c_like_enum(fcx.tcx(), t_e) && t_1_is_trivial { - if t_1_is_float || ty::type_is_unsafe_ptr(t_1) { - fcx.type_error_message(span, |actual| { - format!("illegal cast; cast through an \ - integer first: `{}` as `{}`", - actual, - fcx.infcx().ty_to_string(t_1)) - }, t_e, None); - } - // casts from C-like enums are allowed } else if t_1_is_char { let t_e = fcx.infcx().shallow_resolve(t_e); if t_e.sty != ty::ty_uint(ast::TyU8) { @@ -1101,6 +1071,16 @@ fn check_cast(fcx: &FnCtxt, } else if t_1.sty == ty::ty_bool { span_err!(fcx.tcx().sess, span, E0054, "cannot cast as `bool`, compare with zero instead"); + } else if t_1_is_float && (t_e_is_scalar || t_e_is_c_enum) && !( + t_e_is_integral || t_e_is_float || t_e.sty == ty::ty_bool) { + // Casts to float must go through an integer or boolean + cast_through_integer_err(fcx, span, t_1, t_e) + } else if t_e_is_c_enum && t_1_is_trivial { + if ty::type_is_unsafe_ptr(t_1) { + // ... and likewise with C enum -> *T + cast_through_integer_err(fcx, span, t_1, t_e) + } + // casts from C-like enums are allowed } else if ty::type_is_region_ptr(t_e) && ty::type_is_unsafe_ptr(t_1) { fn types_compatible<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, sp: Span, t1: Ty<'tcx>, t2: Ty<'tcx>) -> bool { @@ -1142,7 +1122,7 @@ fn check_cast(fcx: &FnCtxt, demand::coerce(fcx, e.span, t_1, &*e); } } - } else if !(ty::type_is_scalar(t_e) && t_1_is_trivial) { + } else if !(t_e_is_scalar && t_1_is_trivial) { /* If more type combinations should be supported than are supported here, then file an enhancement issue and @@ -1153,15 +1133,49 @@ fn check_cast(fcx: &FnCtxt, actual, fcx.infcx().ty_to_string(t_1)) }, t_e, None); - } else if ty::type_is_unsafe_ptr(t_e) && t_1_is_float { - fcx.type_error_message(span, |actual| { - format!("cannot cast from pointer to float directly: `{}` as `{}`; cast through an \ - integer first", - actual, - fcx.infcx().ty_to_string(t_1)) - }, t_e, None); } +} + +fn check_cast(fcx: &FnCtxt, + cast_expr: &ast::Expr, + e: &ast::Expr, + t: &ast::Ty) { + let id = cast_expr.id; + let span = cast_expr.span; + + // Find the type of `e`. Supply hints based on the type we are casting to, + // if appropriate. + let t_1 = fcx.to_ty(t); + let t_1 = structurally_resolved_type(fcx, span, t_1); + + check_expr_with_expectation(fcx, e, ExpectCastableToType(t_1)); + let t_e = fcx.expr_ty(e); + + debug!("t_1={}", fcx.infcx().ty_to_string(t_1)); + debug!("t_e={}", fcx.infcx().ty_to_string(t_e)); + + if ty::type_is_error(t_e) { + fcx.write_error(id); + return + } + + if !fcx.type_is_known_to_be_sized(t_1, cast_expr.span) { + report_cast_to_unsized_type(fcx, span, t.span, e.span, t_1, t_e, id); + return + } + + if ty::type_is_trait(t_1) { + // This will be looked up later on. + vtable::check_object_cast(fcx, cast_expr, e, t_1); + fcx.write_ty(id, t_1); + return + } + + let t_1 = structurally_resolved_type(fcx, span, t_1); + let t_e = structurally_resolved_type(fcx, span, t_e); + + check_cast_inner(fcx, span, t_1, t_e, e); fcx.write_ty(id, t_1); } @@ -3087,8 +3101,8 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, let name = ident.get(); // only find fits with at least one matching letter let mut best_dist = name.len(); - let mut best = None; let fields = ty::lookup_struct_fields(tcx, id); + let mut best = None; for elem in fields.iter() { let n = elem.name.as_str(); // ignore already set fields diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index a4cafe88bcd..fc3d6f5912f 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -126,9 +126,9 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec<String>, externs: Externs, .expect("phase_2_configure_and_expand aborted in rustdoc!"); let mut forest = ast_map::Forest::new(krate); + let arenas = ty::CtxtArenas::new(); let ast_map = driver::assign_node_ids_and_map(&sess, &mut forest); - let arenas = ty::CtxtArenas::new(); let ty::CrateAnalysis { exported_items, public_items, ty_cx, .. } = driver::phase_3_run_analysis_passes(sess, diff --git a/src/librustdoc/externalfiles.rs b/src/librustdoc/externalfiles.rs index 157d2580ad9..79ca24a18d4 100644 --- a/src/librustdoc/externalfiles.rs +++ b/src/librustdoc/externalfiles.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::{io, str}; +use std::{old_io, str}; #[derive(Clone)] pub struct ExternalHtml{ @@ -33,8 +33,8 @@ impl ExternalHtml { } } -pub fn load_string(input: &Path) -> io::IoResult<Option<String>> { - let mut f = try!(io::File::open(input)); +pub fn load_string(input: &Path) -> old_io::IoResult<Option<String>> { + let mut f = try!(old_io::File::open(input)); let d = try!(f.read_to_end()); Ok(str::from_utf8(d.as_slice()).map(|s| s.to_string()).ok()) } @@ -45,12 +45,12 @@ macro_rules! load_or_return { let input = Path::new($input); match ::externalfiles::load_string(&input) { Err(e) => { - let _ = writeln!(&mut io::stderr(), + let _ = writeln!(&mut old_io::stderr(), "error reading `{}`: {}", input.display(), e); return $cant_read; } Ok(None) => { - let _ = writeln!(&mut io::stderr(), + let _ = writeln!(&mut old_io::stderr(), "error reading `{}`: not UTF-8", input.display()); return $not_utf8; } diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index 885017152de..38b191846f1 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -15,7 +15,7 @@ use html::escape::Escape; -use std::io; +use std::old_io; use syntax::parse::lexer; use syntax::parse::token; use syntax::parse; @@ -46,7 +46,7 @@ pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String { /// source. fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader, class: Option<&str>, id: Option<&str>, - out: &mut Writer) -> io::IoResult<()> { + out: &mut Writer) -> old_io::IoResult<()> { use syntax::parse::lexer::Reader; try!(write!(out, "<pre ")); diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index e3bd2b4e27f..c537e370723 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -9,7 +9,7 @@ // except according to those terms. use std::fmt; -use std::io; +use std::old_io; use externalfiles::ExternalHtml; @@ -31,8 +31,8 @@ pub struct Page<'a> { } pub fn render<T: fmt::Display, S: fmt::Display>( - dst: &mut io::Writer, layout: &Layout, page: &Page, sidebar: &S, t: &T) - -> io::IoResult<()> + dst: &mut old_io::Writer, layout: &Layout, page: &Page, sidebar: &S, t: &T) + -> old_io::IoResult<()> { write!(dst, r##"<!DOCTYPE html> @@ -159,7 +159,7 @@ r##"<!DOCTYPE html> ) } -pub fn redirect(dst: &mut io::Writer, url: &str) -> io::IoResult<()> { +pub fn redirect(dst: &mut old_io::Writer, url: &str) -> old_io::IoResult<()> { // <script> triggers a redirect before refresh, so this is fine. write!(dst, r##"<!DOCTYPE html> diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 9a25993d28a..956d50efd69 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -39,9 +39,9 @@ use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use std::default::Default; use std::fmt; -use std::io::fs::PathExtensions; -use std::io::{fs, File, BufferedWriter, BufferedReader}; -use std::io; +use std::old_io::fs::PathExtensions; +use std::old_io::{fs, File, BufferedWriter, BufferedReader}; +use std::old_io; use std::iter::repeat; use std::str; use std::sync::Arc; @@ -257,7 +257,7 @@ thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = pub fn run(mut krate: clean::Crate, external_html: &ExternalHtml, dst: Path, - passes: HashSet<String>) -> io::IoResult<()> { + passes: HashSet<String>) -> old_io::IoResult<()> { let mut cx = Context { dst: dst, src_root: krate.src.dir_path(), @@ -391,7 +391,7 @@ pub fn run(mut krate: clean::Crate, cx.krate(krate, summary) } -fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult<String> { +fn build_index(krate: &clean::Crate, cache: &mut Cache) -> old_io::IoResult<String> { // Build the search index from the collected metadata let mut nodeid_to_pathid = HashMap::new(); let mut pathid_to_nodeid = Vec::new(); @@ -485,7 +485,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult<String> fn write_shared(cx: &Context, krate: &clean::Crate, cache: &Cache, - search_index: String) -> io::IoResult<()> { + search_index: String) -> old_io::IoResult<()> { // Write out the shared files. Note that these are shared among all rustdoc // docs placed in the output directory, so this needs to be a synchronized // operation with respect to all other rustdocs running around. @@ -517,7 +517,7 @@ fn write_shared(cx: &Context, include_bytes!("static/SourceCodePro-Semibold.woff"))); fn collect(path: &Path, krate: &str, - key: &str) -> io::IoResult<Vec<String>> { + key: &str) -> old_io::IoResult<Vec<String>> { let mut ret = Vec::new(); if path.exists() { for line in BufferedReader::new(File::open(path)).lines() { @@ -607,7 +607,7 @@ fn write_shared(cx: &Context, } fn render_sources(cx: &mut Context, - krate: clean::Crate) -> io::IoResult<clean::Crate> { + krate: clean::Crate) -> old_io::IoResult<clean::Crate> { info!("emitting source files"); let dst = cx.dst.join("src"); try!(mkdir(&dst)); @@ -625,15 +625,15 @@ fn render_sources(cx: &mut Context, /// Writes the entire contents of a string to a destination, not attempting to /// catch any errors. -fn write(dst: Path, contents: &[u8]) -> io::IoResult<()> { - File::create(&dst).write(contents) +fn write(dst: Path, contents: &[u8]) -> old_io::IoResult<()> { + File::create(&dst).write_all(contents) } /// Makes a directory on the filesystem, failing the task if an error occurs and /// skipping if the directory already exists. -fn mkdir(path: &Path) -> io::IoResult<()> { +fn mkdir(path: &Path) -> old_io::IoResult<()> { if !path.exists() { - fs::mkdir(path, io::USER_RWX) + fs::mkdir(path, old_io::USER_RWX) } else { Ok(()) } @@ -736,7 +736,7 @@ impl<'a> DocFolder for SourceCollector<'a> { impl<'a> SourceCollector<'a> { /// Renders the given filename into its corresponding HTML source file. - fn emit_source(&mut self, filename: &str) -> io::IoResult<()> { + fn emit_source(&mut self, filename: &str) -> old_io::IoResult<()> { let p = Path::new(filename); // If we couldn't open this file, then just returns because it @@ -1084,7 +1084,7 @@ impl Context { /// This currently isn't parallelized, but it'd be pretty easy to add /// parallelization to this function. fn krate(mut self, mut krate: clean::Crate, - stability: stability_summary::ModuleSummary) -> io::IoResult<()> { + stability: stability_summary::ModuleSummary) -> old_io::IoResult<()> { let mut item = match krate.module.take() { Some(i) => i, None => return Ok(()) @@ -1134,11 +1134,11 @@ impl Context { /// all sub-items which need to be rendered. /// /// The rendering driver uses this closure to queue up more work. - fn item<F>(&mut self, item: clean::Item, mut f: F) -> io::IoResult<()> where + fn item<F>(&mut self, item: clean::Item, mut f: F) -> old_io::IoResult<()> where F: FnMut(&mut Context, clean::Item), { - fn render(w: io::File, cx: &Context, it: &clean::Item, - pushname: bool) -> io::IoResult<()> { + fn render(w: old_io::File, cx: &Context, it: &clean::Item, + pushname: bool) -> old_io::IoResult<()> { info!("Rendering an item to {}", w.path().display()); // A little unfortunate that this is done like this, but it sure // does make formatting *a lot* nicer. diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index b3b0a1fb373..75812a2803c 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -49,8 +49,8 @@ extern crate "serialize" as rustc_serialize; // used by deriving use std::cell::RefCell; use std::collections::HashMap; -use std::io::File; -use std::io; +use std::old_io::File; +use std::old_io; use std::rc::Rc; use externalfiles::ExternalHtml; use serialize::Decodable; @@ -487,7 +487,7 @@ fn json_input(input: &str) -> Result<Output, String> { /// Outputs the crate/plugin json as a giant json blob at the specified /// destination. fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> , - dst: Path) -> io::IoResult<()> { + dst: Path) -> old_io::IoResult<()> { // { // "schema": version, // "crate": { parsed crate ... }, diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index 594cf3dcd43..7f932b6ca21 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; +use std::old_io; use core; use getopts; @@ -59,9 +59,9 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches, } let playground = playground.unwrap_or("".to_string()); - let mut out = match io::File::create(&output) { + let mut out = match old_io::File::create(&output) { Err(e) => { - let _ = writeln!(&mut io::stderr(), + let _ = writeln!(&mut old_io::stderr(), "error opening `{}` for writing: {}", output.display(), e); return 4; @@ -71,7 +71,7 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches, let (metadata, text) = extract_leading_metadata(input_str.as_slice()); if metadata.len() == 0 { - let _ = writeln!(&mut io::stderr(), + let _ = writeln!(&mut old_io::stderr(), "invalid markdown file: expecting initial line with `% ...TITLE...`"); return 5; } @@ -126,7 +126,7 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches, match err { Err(e) => { - let _ = writeln!(&mut io::stderr(), + let _ = writeln!(&mut old_io::stderr(), "error writing to `{}`: {}", output.display(), e); 6 diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 656daf6de84..2f692fe99cd 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -11,8 +11,8 @@ use std::cell::RefCell; use std::sync::mpsc::channel; use std::dynamic_lib::DynamicLibrary; -use std::io::{Command, TempDir}; -use std::io; +use std::old_io::{Command, TempDir}; +use std::old_io; use std::os; use std::str; use std::thread::Thread; @@ -145,20 +145,20 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths, // The basic idea is to not use a default_handler() for rustc, and then also // not print things by default to the actual stderr. let (tx, rx) = channel(); - let w1 = io::ChanWriter::new(tx); + let w1 = old_io::ChanWriter::new(tx); let w2 = w1.clone(); - let old = io::stdio::set_stderr(box w1); + let old = old_io::stdio::set_stderr(box w1); Thread::spawn(move |:| { - let mut p = io::ChanReader::new(rx); + let mut p = old_io::ChanReader::new(rx); let mut err = match old { Some(old) => { // Chop off the `Send` bound. let old: Box<Writer> = old; old } - None => box io::stderr() as Box<Writer>, + None => box old_io::stderr() as Box<Writer>, }; - io::util::copy(&mut p, &mut err).unwrap(); + old_io::util::copy(&mut p, &mut err).unwrap(); }); let emitter = diagnostic::EmitterWriter::new(box w2, None); @@ -200,7 +200,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths, match cmd.output() { Err(e) => panic!("couldn't run the test: {}{}", e, - if e.kind == io::PermissionDenied { + if e.kind == old_io::PermissionDenied { " - maybe your tempdir is mounted with noexec?" } else { "" }), Ok(out) => { diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 5f4ba8ef9fc..dad72fbd0e3 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -201,7 +201,7 @@ use self::InternalStackElement::*; use std; use std::collections::{HashMap, BTreeMap}; -use std::{char, f64, fmt, io, num, str}; +use std::{char, f64, fmt, old_io, num, str}; use std::mem::{swap}; use std::num::{Float, Int}; use std::num::FpCategory as Fp; @@ -260,7 +260,7 @@ pub enum ErrorCode { pub enum ParserError { /// msg, line, col SyntaxError(ErrorCode, uint, uint), - IoError(io::IoErrorKind, &'static str), + IoError(old_io::IoErrorKind, &'static str), } // Builder and Parser have the same errors. @@ -331,7 +331,7 @@ impl fmt::Display for ErrorCode { } } -fn io_error_to_error(io: io::IoError) -> ParserError { +fn io_error_to_error(io: old_io::IoError) -> ParserError { IoError(io.kind, io.desc) } @@ -2057,8 +2057,8 @@ impl<T: Iterator<Item=char>> Builder<T> { } } -/// Decodes a json value from an `&mut io::Reader` -pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> { +/// Decodes a json value from an `&mut old_io::Reader` +pub fn from_reader(rdr: &mut old_io::Reader) -> Result<Json, BuilderError> { let contents = match rdr.read_to_end() { Ok(c) => c, Err(e) => return Err(io_error_to_error(e)) @@ -2618,7 +2618,7 @@ mod tests { use super::JsonEvent::*; use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser, StackElement, Stack, Decoder, Encoder, EncoderError}; - use std::{i64, u64, f32, f64, io}; + use std::{i64, u64, f32, f64, old_io}; use std::collections::BTreeMap; use std::num::Float; use std::string; @@ -3456,7 +3456,7 @@ mod tests { #[test] fn test_encode_hashmap_with_numeric_key() { use std::str::from_utf8; - use std::io::Writer; + use std::old_io::Writer; use std::collections::HashMap; let mut hm: HashMap<uint, bool> = HashMap::new(); hm.insert(1, true); @@ -3472,7 +3472,7 @@ mod tests { #[test] fn test_prettyencode_hashmap_with_numeric_key() { use std::str::from_utf8; - use std::io::Writer; + use std::old_io::Writer; use std::collections::HashMap; let mut hm: HashMap<uint, bool> = HashMap::new(); hm.insert(1, true); @@ -3929,7 +3929,7 @@ mod tests { #[test] fn test_encode_hashmap_with_arbitrary_key() { use std::str::from_utf8; - use std::io::Writer; + use std::old_io::Writer; use std::collections::HashMap; use std::fmt; #[derive(PartialEq, Eq, Hash, RustcEncodable)] diff --git a/src/libstd/failure.rs b/src/libstd/failure.rs index 028973a1cf1..c184d3f4661 100644 --- a/src/libstd/failure.rs +++ b/src/libstd/failure.rs @@ -14,12 +14,12 @@ use prelude::v1::*; use any::Any; use cell::RefCell; -use io::IoResult; +use old_io::IoResult; use rt::{backtrace, unwind}; use rt::util::{Stderr, Stdio}; use thread::Thread; -// Defined in this module instead of io::stdio so that the unwinding +// Defined in this module instead of old_io::stdio so that the unwinding thread_local! { pub static LOCAL_STDERR: RefCell<Option<Box<Writer + Send>>> = { RefCell::new(None) @@ -27,7 +27,7 @@ thread_local! { } impl Writer for Stdio { - fn write(&mut self, bytes: &[u8]) -> IoResult<()> { + fn write_all(&mut self, bytes: &[u8]) -> IoResult<()> { let _ = self.write_bytes(bytes); Ok(()) } diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs index 6f2e011d595..4ab43e875cd 100644 --- a/src/libstd/fmt.rs +++ b/src/libstd/fmt.rs @@ -238,7 +238,7 @@ //! //! ```ignore //! format! // described above -//! write! // first argument is a &mut io::Writer, the destination +//! write! // first argument is a &mut old_io::Writer, the destination //! writeln! // same as write but appends a newline //! print! // the format string is printed to the standard output //! println! // same as print but appends a newline @@ -255,10 +255,8 @@ //! //! ```rust //! # #![allow(unused_must_use)] -//! use std::io; -//! //! let mut w = Vec::new(); -//! write!(&mut w as &mut io::Writer, "Hello {}!", "world"); +//! write!(&mut w, "Hello {}!", "world"); //! ``` //! //! #### `print!` @@ -282,15 +280,15 @@ //! //! ``` //! use std::fmt; -//! use std::io; +//! use std::old_io; //! //! fmt::format(format_args!("this returns {}", "String")); //! -//! let some_writer: &mut io::Writer = &mut io::stdout(); -//! write!(some_writer, "{}", format_args!("print with a {}", "macro")); +//! let mut some_writer = old_io::stdout(); +//! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro")); //! //! fn my_fmt_fn(args: fmt::Arguments) { -//! write!(&mut io::stdout(), "{}", args); +//! write!(&mut old_io::stdout(), "{}", args); //! } //! my_fmt_fn(format_args!("or a {} too", "function")); //! ``` diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 4827bc2b3c8..3a745389e1e 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -79,7 +79,8 @@ //! memory types, including [`atomic`](sync/atomic/index.html). //! //! Common types of I/O, including files, TCP, UDP, pipes, Unix domain sockets, -//! timers, and process spawning, are defined in the [`io`](io/index.html) module. +//! timers, and process spawning, are defined in the +//! [`old_io`](old_io/index.html) module. //! //! Rust's I/O and concurrency depends on a small runtime interface //! that lives, along with its support code, in mod [`rt`](rt/index.html). @@ -247,7 +248,7 @@ pub mod thread_local; pub mod dynamic_lib; pub mod ffi; pub mod fmt; -pub mod io; +pub mod old_io; pub mod os; pub mod path; pub mod rand; @@ -292,7 +293,7 @@ mod std { pub use sync; // used for select!() pub use error; // used for try!() pub use fmt; // used for any formatting strings - pub use io; // used for println!() + pub use old_io; // used for println!() pub use option; // used for bitflags!{} pub use rt; // used for panic!() pub use vec; // used for vec![] diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index 5d1f2aa9b1e..9c3285a9d08 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -81,14 +81,14 @@ macro_rules! format { #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] macro_rules! print { - ($($arg:tt)*) => ($crate::io::stdio::print_args(format_args!($($arg)*))) + ($($arg:tt)*) => ($crate::old_io::stdio::print_args(format_args!($($arg)*))) } /// Macro for printing to a task's stdout handle. /// -/// Each task can override its stdout handle via `std::io::stdio::set_stdout`. +/// Each task can override its stdout handle via `std::old_io::stdio::set_stdout`. /// The syntax of this macro is the same as that used for `format!`. For more -/// information, see `std::fmt` and `std::io::stdio`. +/// information, see `std::fmt` and `std::old_io::stdio`. /// /// # Example /// @@ -99,7 +99,7 @@ macro_rules! print { #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] macro_rules! println { - ($($arg:tt)*) => ($crate::io::stdio::println_args(format_args!($($arg)*))) + ($($arg:tt)*) => ($crate::old_io::stdio::println_args(format_args!($($arg)*))) } /// Helper macro for unwrapping `Result` values while returning early with an diff --git a/src/libstd/io/buffered.rs b/src/libstd/old_io/buffered.rs index 1c1c73cddd1..1590598c0b8 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/old_io/buffered.rs @@ -14,7 +14,7 @@ use cmp; use fmt; -use io::{Reader, Writer, Stream, Buffer, DEFAULT_BUF_SIZE, IoResult}; +use old_io::{Reader, Writer, Stream, Buffer, DEFAULT_BUF_SIZE, IoResult}; use iter::{IteratorExt, ExactSizeIterator, repeat}; use ops::Drop; use option::Option; @@ -34,7 +34,7 @@ use vec::Vec; /// # Example /// /// ```rust -/// use std::io::{BufferedReader, File}; +/// use std::old_io::{BufferedReader, File}; /// /// let file = File::open(&Path::new("message.txt")); /// let mut reader = BufferedReader::new(file); @@ -137,7 +137,7 @@ impl<R: Reader> Reader for BufferedReader<R> { /// # Example /// /// ```rust -/// use std::io::{BufferedWriter, File}; +/// use std::old_io::{BufferedWriter, File}; /// /// let file = File::create(&Path::new("message.txt")).unwrap(); /// let mut writer = BufferedWriter::new(file); @@ -184,7 +184,7 @@ impl<W: Writer> BufferedWriter<W> { fn flush_buf(&mut self) -> IoResult<()> { if self.pos != 0 { - let ret = self.inner.as_mut().unwrap().write(&self.buf[..self.pos]); + let ret = self.inner.as_mut().unwrap().write_all(&self.buf[..self.pos]); self.pos = 0; ret } else { @@ -213,13 +213,13 @@ impl<W: Writer> BufferedWriter<W> { } impl<W: Writer> Writer for BufferedWriter<W> { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { if self.pos + buf.len() > self.buf.len() { try!(self.flush_buf()); } if buf.len() > self.buf.len() { - self.inner.as_mut().unwrap().write(buf) + self.inner.as_mut().unwrap().write_all(buf) } else { let dst = &mut self.buf[self.pos..]; slice::bytes::copy_memory(dst, buf); @@ -281,15 +281,15 @@ impl<W: Writer> LineBufferedWriter<W> { } impl<W: Writer> Writer for LineBufferedWriter<W> { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { match buf.iter().rposition(|&b| b == b'\n') { Some(i) => { - try!(self.inner.write(&buf[..i + 1])); + try!(self.inner.write_all(&buf[..i + 1])); try!(self.inner.flush()); - try!(self.inner.write(&buf[i + 1..])); + try!(self.inner.write_all(&buf[i + 1..])); Ok(()) } - None => self.inner.write(buf), + None => self.inner.write_all(buf), } } @@ -324,12 +324,12 @@ impl<W: Reader> Reader for InternalBufferedWriter<W> { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io::{BufferedStream, File}; +/// use std::old_io::{BufferedStream, File}; /// /// let file = File::open(&Path::new("message.txt")); /// let mut stream = BufferedStream::new(file); /// -/// stream.write("hello, world".as_bytes()); +/// stream.write_all("hello, world".as_bytes()); /// stream.flush(); /// /// let mut buf = [0; 100]; @@ -412,8 +412,8 @@ impl<S: Stream> Reader for BufferedStream<S> { } impl<S: Stream> Writer for BufferedStream<S> { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { - self.inner.inner.get_mut().write(buf) + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { + self.inner.inner.get_mut().write_all(buf) } fn flush(&mut self) -> IoResult<()> { self.inner.inner.get_mut().flush() @@ -423,7 +423,7 @@ impl<S: Stream> Writer for BufferedStream<S> { #[cfg(test)] mod test { extern crate test; - use io; + use old_io; use prelude::v1::*; use super::*; use super::super::{IoResult, EndOfFile}; @@ -437,13 +437,13 @@ mod test { pub struct NullStream; impl Reader for NullStream { - fn read(&mut self, _: &mut [u8]) -> io::IoResult<uint> { - Err(io::standard_error(io::EndOfFile)) + fn read(&mut self, _: &mut [u8]) -> old_io::IoResult<uint> { + Err(old_io::standard_error(old_io::EndOfFile)) } } impl Writer for NullStream { - fn write(&mut self, _: &[u8]) -> io::IoResult<()> { Ok(()) } + fn write_all(&mut self, _: &[u8]) -> old_io::IoResult<()> { Ok(()) } } /// A dummy reader intended at testing short-reads propagation. @@ -452,9 +452,9 @@ mod test { } impl Reader for ShortReader { - fn read(&mut self, _: &mut [u8]) -> io::IoResult<uint> { + fn read(&mut self, _: &mut [u8]) -> old_io::IoResult<uint> { if self.lengths.is_empty() { - Err(io::standard_error(io::EndOfFile)) + Err(old_io::standard_error(old_io::EndOfFile)) } else { Ok(self.lengths.remove(0)) } @@ -503,34 +503,34 @@ mod test { let inner = Vec::new(); let mut writer = BufferedWriter::with_capacity(2, inner); - writer.write(&[0, 1]).unwrap(); + writer.write_all(&[0, 1]).unwrap(); let b: &[_] = &[]; assert_eq!(&writer.get_ref()[], b); - writer.write(&[2]).unwrap(); + writer.write_all(&[2]).unwrap(); let b: &[_] = &[0, 1]; assert_eq!(&writer.get_ref()[], b); - writer.write(&[3]).unwrap(); + writer.write_all(&[3]).unwrap(); assert_eq!(&writer.get_ref()[], b); writer.flush().unwrap(); let a: &[_] = &[0, 1, 2, 3]; assert_eq!(a, &writer.get_ref()[]); - writer.write(&[4]).unwrap(); - writer.write(&[5]).unwrap(); + writer.write_all(&[4]).unwrap(); + writer.write_all(&[5]).unwrap(); assert_eq!(a, &writer.get_ref()[]); - writer.write(&[6]).unwrap(); + writer.write_all(&[6]).unwrap(); let a: &[_] = &[0, 1, 2, 3, 4, 5]; assert_eq!(a, &writer.get_ref()[]); - writer.write(&[7, 8]).unwrap(); + writer.write_all(&[7, 8]).unwrap(); let a: &[_] = &[0, 1, 2, 3, 4, 5, 6]; assert_eq!(a, &writer.get_ref()[]); - writer.write(&[9, 10, 11]).unwrap(); + writer.write_all(&[9, 10, 11]).unwrap(); let a: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; assert_eq!(a, &writer.get_ref()[]); @@ -541,7 +541,7 @@ mod test { #[test] fn test_buffered_writer_inner_flushes() { let mut w = BufferedWriter::with_capacity(3, Vec::new()); - w.write(&[0, 1]).unwrap(); + w.write_all(&[0, 1]).unwrap(); let a: &[_] = &[]; assert_eq!(a, &w.get_ref()[]); let w = w.into_inner(); @@ -555,20 +555,20 @@ mod test { fn test_buffered_stream() { struct S; - impl io::Writer for S { - fn write(&mut self, _: &[u8]) -> io::IoResult<()> { Ok(()) } + impl old_io::Writer for S { + fn write_all(&mut self, _: &[u8]) -> old_io::IoResult<()> { Ok(()) } } - impl io::Reader for S { - fn read(&mut self, _: &mut [u8]) -> io::IoResult<uint> { - Err(io::standard_error(io::EndOfFile)) + impl old_io::Reader for S { + fn read(&mut self, _: &mut [u8]) -> old_io::IoResult<uint> { + Err(old_io::standard_error(old_io::EndOfFile)) } } let mut stream = BufferedStream::new(S); let mut buf = []; assert!(stream.read(&mut buf).is_err()); - stream.write(&buf).unwrap(); + stream.write_all(&buf).unwrap(); stream.flush().unwrap(); } @@ -586,21 +586,21 @@ mod test { #[test] fn test_line_buffer() { let mut writer = LineBufferedWriter::new(Vec::new()); - writer.write(&[0]).unwrap(); + writer.write_all(&[0]).unwrap(); let b: &[_] = &[]; assert_eq!(&writer.get_ref()[], b); - writer.write(&[1]).unwrap(); + writer.write_all(&[1]).unwrap(); assert_eq!(&writer.get_ref()[], b); writer.flush().unwrap(); let b: &[_] = &[0, 1]; assert_eq!(&writer.get_ref()[], b); - writer.write(&[0, b'\n', 1, b'\n', 2]).unwrap(); + writer.write_all(&[0, b'\n', 1, b'\n', 2]).unwrap(); let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n']; assert_eq!(&writer.get_ref()[], b); writer.flush().unwrap(); let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n', 2]; assert_eq!(&writer.get_ref()[], b); - writer.write(&[3, b'\n']).unwrap(); + writer.write_all(&[3, b'\n']).unwrap(); let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n', 2, 3, b'\n']; assert_eq!(&writer.get_ref()[], b); } @@ -663,8 +663,8 @@ mod test { struct FailFlushWriter; impl Writer for FailFlushWriter { - fn write(&mut self, _buf: &[u8]) -> IoResult<()> { Ok(()) } - fn flush(&mut self) -> IoResult<()> { Err(io::standard_error(EndOfFile)) } + fn write_all(&mut self, _buf: &[u8]) -> IoResult<()> { Ok(()) } + fn flush(&mut self) -> IoResult<()> { Err(old_io::standard_error(EndOfFile)) } } let writer = FailFlushWriter; diff --git a/src/libstd/io/comm_adapters.rs b/src/libstd/old_io/comm_adapters.rs index d3d49d41a67..feb2ef6f4f3 100644 --- a/src/libstd/io/comm_adapters.rs +++ b/src/libstd/old_io/comm_adapters.rs @@ -11,7 +11,7 @@ use clone::Clone; use cmp; use sync::mpsc::{Sender, Receiver}; -use io; +use old_io; use option::Option::{None, Some}; use result::Result::{Ok, Err}; use slice::{bytes, SliceExt}; @@ -24,7 +24,7 @@ use vec::Vec; /// /// ``` /// use std::sync::mpsc::channel; -/// use std::io::ChanReader; +/// use std::old_io::ChanReader; /// /// let (tx, rx) = channel(); /// # drop(tx); @@ -70,7 +70,7 @@ impl Buffer for ChanReader { } } if self.closed { - Err(io::standard_error(io::EndOfFile)) + Err(old_io::standard_error(old_io::EndOfFile)) } else { Ok(&self.buf[self.pos..]) } @@ -102,7 +102,7 @@ impl Reader for ChanReader { } } if self.closed && num_read == 0 { - Err(io::standard_error(io::EndOfFile)) + Err(old_io::standard_error(old_io::EndOfFile)) } else { Ok(num_read) } @@ -116,7 +116,7 @@ impl Reader for ChanReader { /// ``` /// # #![allow(unused_must_use)] /// use std::sync::mpsc::channel; -/// use std::io::ChanWriter; +/// use std::old_io::ChanWriter; /// /// let (tx, rx) = channel(); /// # drop(rx); @@ -142,10 +142,10 @@ impl Clone for ChanWriter { } impl Writer for ChanWriter { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.tx.send(buf.to_vec()).map_err(|_| { - io::IoError { - kind: io::BrokenPipe, + old_io::IoError { + kind: old_io::BrokenPipe, desc: "Pipe closed", detail: None } @@ -160,7 +160,7 @@ mod test { use sync::mpsc::channel; use super::*; - use io; + use old_io; use thread::Thread; #[test] @@ -193,14 +193,14 @@ mod test { match reader.read(buf.as_mut_slice()) { Ok(..) => panic!(), - Err(e) => assert_eq!(e.kind, io::EndOfFile), + Err(e) => assert_eq!(e.kind, old_io::EndOfFile), } assert_eq!(a, buf); // Ensure it continues to panic in the same way. match reader.read(buf.as_mut_slice()) { Ok(..) => panic!(), - Err(e) => assert_eq!(e.kind, io::EndOfFile), + Err(e) => assert_eq!(e.kind, old_io::EndOfFile), } assert_eq!(a, buf); } @@ -223,7 +223,7 @@ mod test { assert_eq!(Ok("how are you?".to_string()), reader.read_line()); match reader.read_line() { Ok(..) => panic!(), - Err(e) => assert_eq!(e.kind, io::EndOfFile), + Err(e) => assert_eq!(e.kind, old_io::EndOfFile), } } @@ -242,7 +242,7 @@ mod test { match writer.write_u8(1) { Ok(..) => panic!(), - Err(e) => assert_eq!(e.kind, io::BrokenPipe), + Err(e) => assert_eq!(e.kind, old_io::BrokenPipe), } } } diff --git a/src/libstd/io/extensions.rs b/src/libstd/old_io/extensions.rs index af08eea210e..826271a9f83 100644 --- a/src/libstd/io/extensions.rs +++ b/src/libstd/old_io/extensions.rs @@ -15,8 +15,8 @@ // FIXME: Not sure how this should be structured // FIXME: Iteration should probably be considered separately -use io::{IoError, IoResult, Reader}; -use io; +use old_io::{IoError, IoResult, Reader}; +use old_io; use iter::Iterator; use num::Int; use ops::FnOnce; @@ -59,7 +59,7 @@ impl<'r, R: Reader> Iterator for Bytes<'r, R> { fn next(&mut self) -> Option<IoResult<u8>> { match self.reader.read_byte() { Ok(x) => Some(Ok(x)), - Err(IoError { kind: io::EndOfFile, .. }) => None, + Err(IoError { kind: old_io::EndOfFile, .. }) => None, Err(e) => Some(Err(e)) } } @@ -178,15 +178,15 @@ pub fn u64_from_be_bytes(data: &[u8], start: uint, size: uint) -> u64 { #[cfg(test)] mod test { use prelude::v1::*; - use io; - use io::{MemReader, BytesReader}; + use old_io; + use old_io::{MemReader, BytesReader}; struct InitialZeroByteReader { count: int, } impl Reader for InitialZeroByteReader { - fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { + fn read(&mut self, buf: &mut [u8]) -> old_io::IoResult<uint> { if self.count == 0 { self.count = 1; Ok(0) @@ -200,16 +200,16 @@ mod test { struct EofReader; impl Reader for EofReader { - fn read(&mut self, _: &mut [u8]) -> io::IoResult<uint> { - Err(io::standard_error(io::EndOfFile)) + fn read(&mut self, _: &mut [u8]) -> old_io::IoResult<uint> { + Err(old_io::standard_error(old_io::EndOfFile)) } } struct ErroringReader; impl Reader for ErroringReader { - fn read(&mut self, _: &mut [u8]) -> io::IoResult<uint> { - Err(io::standard_error(io::InvalidInput)) + fn read(&mut self, _: &mut [u8]) -> old_io::IoResult<uint> { + Err(old_io::standard_error(old_io::InvalidInput)) } } @@ -218,7 +218,7 @@ mod test { } impl Reader for PartialReader { - fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { + fn read(&mut self, buf: &mut [u8]) -> old_io::IoResult<uint> { if self.count == 0 { self.count = 1; buf[0] = 10; @@ -237,13 +237,13 @@ mod test { } impl Reader for ErroringLaterReader { - fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { + fn read(&mut self, buf: &mut [u8]) -> old_io::IoResult<uint> { if self.count == 0 { self.count = 1; buf[0] = 10; Ok(1) } else { - Err(io::standard_error(io::InvalidInput)) + Err(old_io::standard_error(old_io::InvalidInput)) } } } @@ -253,7 +253,7 @@ mod test { } impl Reader for ThreeChunkReader { - fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { + fn read(&mut self, buf: &mut [u8]) -> old_io::IoResult<uint> { if self.count == 0 { self.count = 1; buf[0] = 10; @@ -265,7 +265,7 @@ mod test { buf[1] = 13; Ok(2) } else { - Err(io::standard_error(io::EndOfFile)) + Err(old_io::standard_error(old_io::EndOfFile)) } } } diff --git a/src/libstd/io/fs.rs b/src/libstd/old_io/fs.rs index cc36c5640d0..a1ac5d2eab0 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/old_io/fs.rs @@ -18,21 +18,21 @@ //! At the top-level of the module are a set of freestanding functions, associated //! 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. In the event of failure, all functions/methods +//! All operations in this module, including those as part of `File` et al 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 -//! metadata of a file. This includes getting the `stat` information, reading off -//! particular bits of it, etc. +//! defined in `std::path::Path`. The impl adds useful methods about inspecting +//! the metadata of a file. This includes getting the `stat` information, +//! reading off particular bits of it, etc. //! //! # Example //! //! ```rust //! # #![allow(unused_must_use)] -//! use std::io::fs::PathExtensions; -//! use std::io::{File, fs}; +//! use std::old_io::fs::PathExtensions; +//! use std::old_io::{File, fs}; //! //! let path = Path::new("foo.txt"); //! @@ -51,13 +51,13 @@ //! ``` use clone::Clone; -use io::standard_error; -use io::{FilePermission, Write, Open, FileAccess, FileMode, FileType}; -use io::{IoResult, IoError, InvalidInput}; -use io::{FileStat, SeekStyle, Seek, Writer, Reader}; -use io::{Read, Truncate, ReadWrite, Append}; -use io::UpdateIoError; -use io; +use old_io::standard_error; +use old_io::{FilePermission, Write, Open, FileAccess, FileMode, FileType}; +use old_io::{IoResult, IoError, InvalidInput}; +use old_io::{FileStat, SeekStyle, Seek, Writer, Reader}; +use old_io::{Read, Truncate, ReadWrite, Append}; +use old_io::UpdateIoError; +use old_io; use iter::{Iterator, Extend}; use option::Option; use option::Option::{Some, None}; @@ -101,7 +101,7 @@ impl File { /// # Example /// /// ```rust,should_fail - /// use std::io::{File, Open, ReadWrite}; + /// use std::old_io::{File, Open, ReadWrite}; /// /// let p = Path::new("/some/file/path.txt"); /// @@ -170,7 +170,7 @@ impl File { /// # Example /// /// ```rust - /// use std::io::File; + /// use std::old_io::File; /// /// let contents = File::open(&Path::new("foo.txt")).read_to_end(); /// ``` @@ -188,12 +188,12 @@ impl File { /// /// ```rust /// # #![allow(unused_must_use)] - /// use std::io::File; + /// use std::old_io::File; /// /// let mut f = File::create(&Path::new("foo.txt")); /// f.write(b"This is a sample file"); /// # drop(f); - /// # ::std::io::fs::unlink(&Path::new("foo.txt")); + /// # ::std::old_io::fs::unlink(&Path::new("foo.txt")); /// ``` pub fn create(path: &Path) -> IoResult<File> { File::open_mode(path, Truncate, Write) @@ -265,7 +265,7 @@ impl File { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io::fs; +/// use std::old_io::fs; /// /// let p = Path::new("/some/file/path.txt"); /// fs::unlink(&p); @@ -293,7 +293,7 @@ pub fn unlink(path: &Path) -> IoResult<()> { /// # Example /// /// ```rust -/// use std::io::fs; +/// use std::old_io::fs; /// /// let p = Path::new("/some/file/path.txt"); /// match fs::stat(&p) { @@ -333,7 +333,7 @@ pub fn lstat(path: &Path) -> IoResult<FileStat> { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io::fs; +/// use std::old_io::fs; /// /// fs::rename(&Path::new("foo"), &Path::new("bar")); /// ``` @@ -359,7 +359,7 @@ pub fn rename(from: &Path, to: &Path) -> IoResult<()> { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io::fs; +/// use std::old_io::fs; /// /// fs::copy(&Path::new("foo.txt"), &Path::new("bar.txt")); /// ``` @@ -386,7 +386,7 @@ pub fn copy(from: &Path, to: &Path) -> IoResult<()> { if !from.is_file() { return update_err(Err(IoError { - kind: io::MismatchedFileTypeForOperation, + kind: old_io::MismatchedFileTypeForOperation, desc: "the source path is not an existing file", detail: None }), from, to) @@ -407,13 +407,13 @@ pub fn copy(from: &Path, to: &Path) -> IoResult<()> { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io; -/// use std::io::fs; +/// use std::old_io; +/// use std::old_io::fs; /// -/// fs::chmod(&Path::new("file.txt"), io::USER_FILE); -/// fs::chmod(&Path::new("file.txt"), io::USER_READ | io::USER_WRITE); -/// fs::chmod(&Path::new("dir"), io::USER_DIR); -/// fs::chmod(&Path::new("file.exe"), io::USER_EXEC); +/// fs::chmod(&Path::new("file.txt"), old_io::USER_FILE); +/// fs::chmod(&Path::new("file.txt"), old_io::USER_READ | old_io::USER_WRITE); +/// fs::chmod(&Path::new("dir"), old_io::USER_DIR); +/// fs::chmod(&Path::new("file.exe"), old_io::USER_EXEC); /// ``` /// /// # Error @@ -421,7 +421,7 @@ pub fn copy(from: &Path, to: &Path) -> IoResult<()> { /// This function will return an error if the provided `path` doesn't exist, if /// the process lacks permissions to change the attributes of the file, or if /// some other I/O error is encountered. -pub fn chmod(path: &Path, mode: io::FilePermission) -> IoResult<()> { +pub fn chmod(path: &Path, mode: old_io::FilePermission) -> IoResult<()> { fs_imp::chmod(path, mode.bits() as uint) .update_err("couldn't chmod path", |e| format!("{}; path={}; mode={:?}", e, path.display(), mode)) @@ -469,11 +469,11 @@ pub fn readlink(path: &Path) -> IoResult<Path> { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io; -/// use std::io::fs; +/// use std::old_io; +/// use std::old_io::fs; /// /// let p = Path::new("/some/dir"); -/// fs::mkdir(&p, io::USER_RWX); +/// fs::mkdir(&p, old_io::USER_RWX); /// ``` /// /// # Error @@ -492,7 +492,7 @@ pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io::fs; +/// use std::old_io::fs; /// /// let p = Path::new("/some/dir"); /// fs::rmdir(&p); @@ -513,12 +513,12 @@ pub fn rmdir(path: &Path) -> IoResult<()> { /// # Example /// /// ```rust -/// use std::io::fs::PathExtensions; -/// use std::io::fs; -/// use std::io; +/// use std::old_io::fs::PathExtensions; +/// use std::old_io::fs; +/// use std::old_io; /// /// // one possible implementation of fs::walk_dir only visiting files -/// fn visit_dirs<F>(dir: &Path, cb: &mut F) -> io::IoResult<()> where +/// fn visit_dirs<F>(dir: &Path, cb: &mut F) -> old_io::IoResult<()> where /// F: FnMut(&Path), /// { /// if dir.is_dir() { @@ -532,7 +532,7 @@ pub fn rmdir(path: &Path) -> IoResult<()> { /// } /// Ok(()) /// } else { -/// Err(io::standard_error(io::InvalidInput)) +/// Err(old_io::standard_error(old_io::InvalidInput)) /// } /// } /// ``` @@ -664,7 +664,7 @@ pub fn rmdir_recursive(path: &Path) -> IoResult<()> { // (eg: deleted by someone else since readdir) match update_err(unlink(&child), path) { Ok(()) => (), - Err(ref e) if e.kind == io::FileNotFound => (), + Err(ref e) if e.kind == old_io::FileNotFound => (), Err(e) => return Err(e) } } @@ -675,7 +675,7 @@ pub fn rmdir_recursive(path: &Path) -> IoResult<()> { let result = update_err(rmdir(&rm_stack.pop().unwrap()), path); match result { Ok(()) => (), - Err(ref e) if e.kind == io::FileNotFound => (), + Err(ref e) if e.kind == old_io::FileNotFound => (), Err(e) => return Err(e) } } @@ -709,7 +709,7 @@ impl Reader for File { Ok(read) => { self.last_nread = read as int; match read { - 0 => update_err(Err(standard_error(io::EndOfFile)), self), + 0 => update_err(Err(standard_error(old_io::EndOfFile)), self), _ => Ok(read as uint) } }, @@ -719,7 +719,7 @@ impl Reader for File { } impl Writer for File { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.fd.write(buf) .update_err("couldn't write to file", |e| format!("{}; path={}", e, self.path.display())) @@ -824,10 +824,10 @@ fn access_string(access: FileAccess) -> &'static str { #[allow(unused_mut)] mod test { use prelude::v1::*; - use io::{SeekSet, SeekCur, SeekEnd, Read, Open, ReadWrite, FileType}; - use io; + use old_io::{SeekSet, SeekCur, SeekEnd, Read, Open, ReadWrite, FileType}; + use old_io; use str; - use io::fs::*; + use old_io::fs::*; macro_rules! check { ($e:expr) => ( match $e { @@ -863,7 +863,7 @@ mod test { // Gee, seeing how we're testing the fs module I sure hope that we // at least implement this correctly! let TempDir(ref p) = *self; - check!(io::fs::rmdir_recursive(p)); + check!(old_io::fs::rmdir_recursive(p)); } } @@ -871,7 +871,7 @@ mod test { use os; use rand; let ret = os::tmpdir().join(format!("rust-{}", rand::random::<u32>())); - check!(io::fs::mkdir(&ret, io::USER_RWX)); + check!(old_io::fs::mkdir(&ret, old_io::USER_RWX)); TempDir(ret) } @@ -1055,7 +1055,7 @@ mod test { fn file_test_stat_is_correct_on_is_dir() { let tmpdir = tmpdir(); let filename = &tmpdir.join("file_stat_correct_on_is_dir"); - check!(mkdir(filename, io::USER_RWX)); + check!(mkdir(filename, old_io::USER_RWX)); let stat_res_fn = check!(stat(filename)); assert!(stat_res_fn.kind == FileType::Directory); let stat_res_meth = check!(filename.stat()); @@ -1067,7 +1067,7 @@ mod test { fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() { let tmpdir = tmpdir(); let dir = &tmpdir.join("fileinfo_false_on_dir"); - check!(mkdir(dir, io::USER_RWX)); + check!(mkdir(dir, old_io::USER_RWX)); assert!(dir.is_file() == false); check!(rmdir(dir)); } @@ -1087,7 +1087,7 @@ mod test { let tmpdir = tmpdir(); let dir = &tmpdir.join("before_and_after_dir"); assert!(!dir.exists()); - check!(mkdir(dir, io::USER_RWX)); + check!(mkdir(dir, old_io::USER_RWX)); assert!(dir.exists()); assert!(dir.is_dir()); check!(rmdir(dir)); @@ -1099,7 +1099,7 @@ mod test { use str; let tmpdir = tmpdir(); let dir = &tmpdir.join("di_readdir"); - check!(mkdir(dir, io::USER_RWX)); + check!(mkdir(dir, old_io::USER_RWX)); let prefix = "foo"; for n in range(0i,3) { let f = dir.join(format!("{}.txt", n)); @@ -1130,14 +1130,14 @@ mod test { fn file_test_walk_dir() { let tmpdir = tmpdir(); let dir = &tmpdir.join("walk_dir"); - check!(mkdir(dir, io::USER_RWX)); + check!(mkdir(dir, old_io::USER_RWX)); let dir1 = &dir.join("01/02/03"); - check!(mkdir_recursive(dir1, io::USER_RWX)); + check!(mkdir_recursive(dir1, old_io::USER_RWX)); check!(File::create(&dir1.join("04"))); let dir2 = &dir.join("11/12/13"); - check!(mkdir_recursive(dir2, io::USER_RWX)); + check!(mkdir_recursive(dir2, old_io::USER_RWX)); check!(File::create(&dir2.join("14"))); let mut files = check!(walk_dir(dir)); @@ -1155,12 +1155,12 @@ mod test { #[test] fn mkdir_path_already_exists_error() { - use io::{IoError, PathAlreadyExists}; + use old_io::{IoError, PathAlreadyExists}; let tmpdir = tmpdir(); let dir = &tmpdir.join("mkdir_error_twice"); - check!(mkdir(dir, io::USER_RWX)); - match mkdir(dir, io::USER_RWX) { + check!(mkdir(dir, old_io::USER_RWX)); + match mkdir(dir, old_io::USER_RWX) { Err(IoError{kind:PathAlreadyExists,..}) => (), _ => assert!(false) }; @@ -1170,7 +1170,7 @@ mod test { fn recursive_mkdir() { let tmpdir = tmpdir(); let dir = tmpdir.join("d1/d2"); - check!(mkdir_recursive(&dir, io::USER_RWX)); + check!(mkdir_recursive(&dir, old_io::USER_RWX)); assert!(dir.is_dir()) } @@ -1180,10 +1180,10 @@ mod test { let dir = tmpdir.join("d1"); let file = dir.join("f1"); - check!(mkdir_recursive(&dir, io::USER_RWX)); + check!(mkdir_recursive(&dir, old_io::USER_RWX)); check!(File::create(&file)); - let result = mkdir_recursive(&file, io::USER_RWX); + let result = mkdir_recursive(&file, old_io::USER_RWX); error!(result, "couldn't recursively mkdir"); error!(result, "couldn't create directory"); @@ -1193,7 +1193,7 @@ mod test { #[test] fn recursive_mkdir_slash() { - check!(mkdir_recursive(&Path::new("/"), io::USER_RWX)); + check!(mkdir_recursive(&Path::new("/"), old_io::USER_RWX)); } // FIXME(#12795) depends on lstat to work on windows @@ -1206,8 +1206,8 @@ mod test { let dtt = dt.join("t"); let d2 = tmpdir.join("d2"); let canary = d2.join("do_not_delete"); - check!(mkdir_recursive(&dtt, io::USER_RWX)); - check!(mkdir_recursive(&d2, io::USER_RWX)); + check!(mkdir_recursive(&dtt, old_io::USER_RWX)); + check!(mkdir_recursive(&d2, old_io::USER_RWX)); check!(File::create(&canary).write(b"foo")); check!(symlink(&d2, &dt.join("d2"))); check!(rmdir_recursive(&d1)); @@ -1225,7 +1225,7 @@ mod test { let mut dirpath = tmpdir.path().clone(); dirpath.push(format!("test-가一ー你好")); - check!(mkdir(&dirpath, io::USER_RWX)); + check!(mkdir(&dirpath, old_io::USER_RWX)); assert!(dirpath.is_dir()); let mut filepath = dirpath; @@ -1243,7 +1243,7 @@ mod test { let tmpdir = tmpdir(); let unicode = tmpdir.path(); let unicode = unicode.join(format!("test-각丁ー再见")); - check!(mkdir(&unicode, io::USER_RWX)); + check!(mkdir(&unicode, old_io::USER_RWX)); assert!(unicode.exists()); assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists()); } @@ -1324,12 +1324,12 @@ mod test { let out = tmpdir.join("out.txt"); check!(File::create(&input)); - check!(chmod(&input, io::USER_READ)); + check!(chmod(&input, old_io::USER_READ)); check!(copy(&input, &out)); - assert!(!check!(out.stat()).perm.intersects(io::USER_WRITE)); + assert!(!check!(out.stat()).perm.intersects(old_io::USER_WRITE)); - check!(chmod(&input, io::USER_FILE)); - check!(chmod(&out, io::USER_FILE)); + check!(chmod(&input, old_io::USER_FILE)); + check!(chmod(&out, old_io::USER_FILE)); } #[cfg(not(windows))] // FIXME(#10264) operation not permitted? @@ -1405,16 +1405,16 @@ mod test { let file = tmpdir.join("in.txt"); check!(File::create(&file)); - assert!(check!(stat(&file)).perm.contains(io::USER_WRITE)); - check!(chmod(&file, io::USER_READ)); - assert!(!check!(stat(&file)).perm.contains(io::USER_WRITE)); + assert!(check!(stat(&file)).perm.contains(old_io::USER_WRITE)); + check!(chmod(&file, old_io::USER_READ)); + assert!(!check!(stat(&file)).perm.contains(old_io::USER_WRITE)); - match chmod(&tmpdir.join("foo"), io::USER_RWX) { + match chmod(&tmpdir.join("foo"), old_io::USER_RWX) { Ok(..) => panic!("wanted a panic"), Err(..) => {} } - check!(chmod(&file, io::USER_FILE)); + check!(chmod(&file, old_io::USER_FILE)); } #[test] @@ -1422,7 +1422,7 @@ mod test { let tmpdir = tmpdir(); let path = tmpdir.join("in.txt"); - let mut file = check!(File::open_mode(&path, io::Open, io::ReadWrite)); + let mut file = check!(File::open_mode(&path, old_io::Open, old_io::ReadWrite)); check!(file.fsync()); check!(file.datasync()); check!(file.write(b"foo")); @@ -1436,7 +1436,7 @@ mod test { let tmpdir = tmpdir(); let path = tmpdir.join("in.txt"); - let mut file = check!(File::open_mode(&path, io::Open, io::ReadWrite)); + let mut file = check!(File::open_mode(&path, old_io::Open, old_io::ReadWrite)); check!(file.write(b"foo")); check!(file.fsync()); @@ -1467,41 +1467,41 @@ mod test { fn open_flavors() { let tmpdir = tmpdir(); - match File::open_mode(&tmpdir.join("a"), io::Open, io::Read) { + match File::open_mode(&tmpdir.join("a"), old_io::Open, old_io::Read) { Ok(..) => panic!(), Err(..) => {} } // Perform each one twice to make sure that it succeeds the second time // (where the file exists) - check!(File::open_mode(&tmpdir.join("b"), io::Open, io::Write)); + check!(File::open_mode(&tmpdir.join("b"), old_io::Open, old_io::Write)); assert!(tmpdir.join("b").exists()); - check!(File::open_mode(&tmpdir.join("b"), io::Open, io::Write)); + check!(File::open_mode(&tmpdir.join("b"), old_io::Open, old_io::Write)); - check!(File::open_mode(&tmpdir.join("c"), io::Open, io::ReadWrite)); + check!(File::open_mode(&tmpdir.join("c"), old_io::Open, old_io::ReadWrite)); assert!(tmpdir.join("c").exists()); - check!(File::open_mode(&tmpdir.join("c"), io::Open, io::ReadWrite)); + check!(File::open_mode(&tmpdir.join("c"), old_io::Open, old_io::ReadWrite)); - check!(File::open_mode(&tmpdir.join("d"), io::Append, io::Write)); + check!(File::open_mode(&tmpdir.join("d"), old_io::Append, old_io::Write)); assert!(tmpdir.join("d").exists()); - check!(File::open_mode(&tmpdir.join("d"), io::Append, io::Write)); + check!(File::open_mode(&tmpdir.join("d"), old_io::Append, old_io::Write)); - check!(File::open_mode(&tmpdir.join("e"), io::Append, io::ReadWrite)); + check!(File::open_mode(&tmpdir.join("e"), old_io::Append, old_io::ReadWrite)); assert!(tmpdir.join("e").exists()); - check!(File::open_mode(&tmpdir.join("e"), io::Append, io::ReadWrite)); + check!(File::open_mode(&tmpdir.join("e"), old_io::Append, old_io::ReadWrite)); - check!(File::open_mode(&tmpdir.join("f"), io::Truncate, io::Write)); + check!(File::open_mode(&tmpdir.join("f"), old_io::Truncate, old_io::Write)); assert!(tmpdir.join("f").exists()); - check!(File::open_mode(&tmpdir.join("f"), io::Truncate, io::Write)); + check!(File::open_mode(&tmpdir.join("f"), old_io::Truncate, old_io::Write)); - check!(File::open_mode(&tmpdir.join("g"), io::Truncate, io::ReadWrite)); + check!(File::open_mode(&tmpdir.join("g"), old_io::Truncate, old_io::ReadWrite)); assert!(tmpdir.join("g").exists()); - check!(File::open_mode(&tmpdir.join("g"), io::Truncate, io::ReadWrite)); + check!(File::open_mode(&tmpdir.join("g"), old_io::Truncate, old_io::ReadWrite)); check!(File::create(&tmpdir.join("h")).write("foo".as_bytes())); - check!(File::open_mode(&tmpdir.join("h"), io::Open, io::Read)); + check!(File::open_mode(&tmpdir.join("h"), old_io::Open, old_io::Read)); { - let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Open, - io::Read)); + let mut f = check!(File::open_mode(&tmpdir.join("h"), old_io::Open, + old_io::Read)); match f.write("wut".as_bytes()) { Ok(..) => panic!(), Err(..) => {} } @@ -1509,15 +1509,15 @@ mod test { assert!(check!(stat(&tmpdir.join("h"))).size == 3, "write/stat failed"); { - let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Append, - io::Write)); + let mut f = check!(File::open_mode(&tmpdir.join("h"), old_io::Append, + old_io::Write)); check!(f.write("bar".as_bytes())); } assert!(check!(stat(&tmpdir.join("h"))).size == 6, "append didn't append"); { - let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Truncate, - io::Write)); + let mut f = check!(File::open_mode(&tmpdir.join("h"), old_io::Truncate, + old_io::Write)); check!(f.write("bar".as_bytes())); } assert!(check!(stat(&tmpdir.join("h"))).size == 3, @@ -1529,8 +1529,9 @@ mod test { let tmpdir = tmpdir(); let path = tmpdir.join("a"); check!(File::create(&path)); - // These numbers have to be bigger than the time in the day to account for timezones - // Windows in particular will fail in certain timezones with small enough values + // These numbers have to be bigger than the time in the day to account + // for timezones Windows in particular will fail in certain timezones + // with small enough values check!(change_file_times(&path, 100000, 200000)); assert_eq!(check!(path.stat()).accessed, 100000); assert_eq!(check!(path.stat()).modified, 200000); @@ -1565,7 +1566,7 @@ mod test { let tmpdir = tmpdir(); let path = tmpdir.join("file"); check!(File::create(&path)); - check!(chmod(&path, io::USER_READ)); + check!(chmod(&path, old_io::USER_READ)); check!(unlink(&path)); } } diff --git a/src/libstd/io/mem.rs b/src/libstd/old_io/mem.rs index 8c0de781994..254daf3202a 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/old_io/mem.rs @@ -15,8 +15,8 @@ use cmp::min; use option::Option::None; use result::Result::{Err, Ok}; -use io; -use io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult}; +use old_io; +use old_io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult}; use slice::{self, AsSlice, SliceExt}; use vec::Vec; @@ -25,14 +25,14 @@ const BUF_CAPACITY: uint = 128; fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> { // compute offset as signed and clamp to prevent overflow let pos = match seek { - io::SeekSet => 0, - io::SeekEnd => end, - io::SeekCur => cur, + old_io::SeekSet => 0, + old_io::SeekEnd => end, + old_io::SeekCur => cur, } as i64; if offset + pos < 0 { Err(IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "invalid seek to a negative offset", detail: None }) @@ -43,7 +43,7 @@ fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> impl Writer for Vec<u8> { #[inline] - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.push_all(buf); Ok(()) } @@ -55,7 +55,7 @@ impl Writer for Vec<u8> { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io::MemWriter; +/// use std::old_io::MemWriter; /// /// let mut w = MemWriter::new(); /// w.write(&[0, 1, 2]); @@ -101,7 +101,7 @@ impl MemWriter { impl Writer for MemWriter { #[inline] - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.buf.push_all(buf); Ok(()) } @@ -113,7 +113,7 @@ impl Writer for MemWriter { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io::MemReader; +/// use std::old_io::MemReader; /// /// let mut r = MemReader::new(vec!(0, 1, 2)); /// @@ -157,7 +157,7 @@ impl MemReader { impl Reader for MemReader { #[inline] fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { - if self.eof() { return Err(io::standard_error(io::EndOfFile)) } + if self.eof() { return Err(old_io::standard_error(old_io::EndOfFile)) } let write_len = min(buf.len(), self.buf.len() - self.pos); { @@ -191,7 +191,7 @@ impl Buffer for MemReader { if self.pos < self.buf.len() { Ok(&self.buf[self.pos..]) } else { - Err(io::standard_error(io::EndOfFile)) + Err(old_io::standard_error(old_io::EndOfFile)) } } @@ -202,7 +202,7 @@ impl Buffer for MemReader { impl<'a> Reader for &'a [u8] { #[inline] fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { - if self.is_empty() { return Err(io::standard_error(io::EndOfFile)); } + if self.is_empty() { return Err(old_io::standard_error(old_io::EndOfFile)); } let write_len = min(buf.len(), self.len()); { @@ -221,7 +221,7 @@ impl<'a> Buffer for &'a [u8] { #[inline] fn fill_buf(&mut self) -> IoResult<&[u8]> { if self.is_empty() { - Err(io::standard_error(io::EndOfFile)) + Err(old_io::standard_error(old_io::EndOfFile)) } else { Ok(*self) } @@ -243,7 +243,7 @@ impl<'a> Buffer for &'a [u8] { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io::BufWriter; +/// use std::old_io::BufWriter; /// /// let mut buf = [0; 4]; /// { @@ -271,12 +271,12 @@ impl<'a> BufWriter<'a> { impl<'a> Writer for BufWriter<'a> { #[inline] - fn write(&mut self, src: &[u8]) -> IoResult<()> { + fn write_all(&mut self, src: &[u8]) -> IoResult<()> { let dst = &mut self.buf[self.pos..]; let dst_len = dst.len(); if dst_len == 0 { - return Err(io::standard_error(io::EndOfFile)); + return Err(old_io::standard_error(old_io::EndOfFile)); } let src_len = src.len(); @@ -292,7 +292,7 @@ impl<'a> Writer for BufWriter<'a> { self.pos += dst_len; - Err(io::standard_error(io::ShortWrite(dst_len))) + Err(old_io::standard_error(old_io::ShortWrite(dst_len))) } } } @@ -315,7 +315,7 @@ impl<'a> Seek for BufWriter<'a> { /// /// ```rust /// # #![allow(unused_must_use)] -/// use std::io::BufReader; +/// use std::old_io::BufReader; /// /// let buf = [0, 1, 2, 3]; /// let mut r = BufReader::new(&buf); @@ -347,7 +347,7 @@ impl<'a> BufReader<'a> { impl<'a> Reader for BufReader<'a> { #[inline] fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { - if self.eof() { return Err(io::standard_error(io::EndOfFile)) } + if self.eof() { return Err(old_io::standard_error(old_io::EndOfFile)) } let write_len = min(buf.len(), self.buf.len() - self.pos); { @@ -381,7 +381,7 @@ impl<'a> Buffer for BufReader<'a> { if self.pos < self.buf.len() { Ok(&self.buf[self.pos..]) } else { - Err(io::standard_error(io::EndOfFile)) + Err(old_io::standard_error(old_io::EndOfFile)) } } @@ -392,10 +392,10 @@ impl<'a> Buffer for BufReader<'a> { #[cfg(test)] mod test { extern crate "test" as test_crate; - use io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek}; + use old_io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek}; use prelude::v1::{Ok, Err, range, Vec, Buffer, AsSlice, SliceExt}; use prelude::v1::IteratorExt; - use io; + use old_io; use iter::repeat; use self::test_crate::Bencher; use super::*; @@ -434,8 +434,8 @@ mod test { writer.write(&[]).unwrap(); assert_eq!(writer.tell(), Ok(8)); - assert_eq!(writer.write(&[8, 9]).err().unwrap().kind, io::ShortWrite(1)); - assert_eq!(writer.write(&[10]).err().unwrap().kind, io::EndOfFile); + assert_eq!(writer.write(&[8, 9]).err().unwrap().kind, old_io::ShortWrite(1)); + assert_eq!(writer.write(&[10]).err().unwrap().kind, old_io::EndOfFile); } let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8]; assert_eq!(buf, b); @@ -478,7 +478,7 @@ mod test { match writer.write(&[0, 0]) { Ok(..) => panic!(), - Err(e) => assert_eq!(e.kind, io::ShortWrite(1)), + Err(e) => assert_eq!(e.kind, old_io::ShortWrite(1)), } } diff --git a/src/libstd/io/mod.rs b/src/libstd/old_io/mod.rs index cc7f9f5b892..6c5ce129a33 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/old_io/mod.rs @@ -18,6 +18,24 @@ //! I/O, including files, networking, timers, and processes //! +//! > **Warning**: This module is currently called `old_io` for a reason! The +//! > module is currently being redesigned in a number of RFCs. For more details +//! > follow the RFC repository in connection with [RFC 517][base] or follow +//! > some of these sub-RFCs +//! > +//! > * [String handling][osstr] +//! > * [Core I/O support][core] +//! > * [Deadlines][deadlines] +//! > * [std::env][env] +//! > * [std::process][process] +//! +//! [base]: https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md +//! [osstr]: https://github.com/rust-lang/rfcs/pull/575 +//! [core]: https://github.com/rust-lang/rfcs/pull/576 +//! [deadlines]: https://github.com/rust-lang/rfcs/pull/577 +//! [env]: https://github.com/rust-lang/rfcs/pull/578 +//! [process]: https://github.com/rust-lang/rfcs/pull/579 +//! //! `std::io` provides Rust's basic I/O types, //! for reading and writing to files, TCP, UDP, //! and other types of sockets and pipes, @@ -30,7 +48,7 @@ //! * Read lines from stdin //! //! ```rust -//! use std::io; +//! use std::old_io as io; //! //! for line in io::stdin().lock().lines() { //! print!("{}", line.unwrap()); @@ -40,7 +58,7 @@ //! * Read a complete file //! //! ```rust -//! use std::io::File; +//! use std::old_io::File; //! //! let contents = File::open(&Path::new("message.txt")).read_to_end(); //! ``` @@ -49,19 +67,19 @@ //! //! ```rust //! # #![allow(unused_must_use)] -//! use std::io::File; +//! use std::old_io::File; //! //! let mut file = File::create(&Path::new("message.txt")); -//! file.write(b"hello, file!\n"); +//! file.write_all(b"hello, file!\n"); //! # drop(file); -//! # ::std::io::fs::unlink(&Path::new("message.txt")); +//! # ::std::old_io::fs::unlink(&Path::new("message.txt")); //! ``` //! //! * Iterate over the lines of a file //! //! ```rust,no_run -//! use std::io::BufferedReader; -//! use std::io::File; +//! use std::old_io::BufferedReader; +//! use std::old_io::File; //! //! let path = Path::new("message.txt"); //! let mut file = BufferedReader::new(File::open(&path)); @@ -73,8 +91,8 @@ //! * Pull the lines of a file into a vector of strings //! //! ```rust,no_run -//! use std::io::BufferedReader; -//! use std::io::File; +//! use std::old_io::BufferedReader; +//! use std::old_io::File; //! //! let path = Path::new("message.txt"); //! let mut file = BufferedReader::new(File::open(&path)); @@ -85,14 +103,14 @@ //! //! ```rust //! # #![allow(unused_must_use)] -//! use std::io::TcpStream; +//! use std::old_io::TcpStream; //! //! # // connection doesn't fail if a server is running on 8080 //! # // locally, we still want to be type checking this code, so lets //! # // just stop it running (#11576) //! # if false { //! let mut socket = TcpStream::connect("127.0.0.1:8080").unwrap(); -//! socket.write(b"GET / HTTP/1.0\n\n"); +//! socket.write_all(b"GET / HTTP/1.0\n\n"); //! let response = socket.read_to_end(); //! # } //! ``` @@ -103,8 +121,8 @@ //! # fn main() { } //! # fn foo() { //! # #![allow(dead_code)] -//! use std::io::{TcpListener, TcpStream}; -//! use std::io::{Acceptor, Listener}; +//! use std::old_io::{TcpListener, TcpStream}; +//! use std::old_io::{Acceptor, Listener}; //! use std::thread::Thread; //! //! let listener = TcpListener::bind("127.0.0.1:80"); @@ -156,7 +174,7 @@ //! to be 'unwrapped' before use. //! //! These features combine in the API to allow for expressions like -//! `File::create(&Path::new("diary.txt")).write(b"Met a girl.\n")` +//! `File::create(&Path::new("diary.txt")).write_all(b"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 then the result of the entire expression will @@ -166,14 +184,14 @@ //! //! ```rust //! # #![allow(unused_must_use)] -//! use std::io::File; +//! use std::old_io::File; //! -//! match File::create(&Path::new("diary.txt")).write(b"Met a girl.\n") { +//! match File::create(&Path::new("diary.txt")).write_all(b"Met a girl.\n") { //! Ok(()) => (), // succeeded //! Err(e) => println!("failed to write to my diary: {}", e), //! } //! -//! # ::std::io::fs::unlink(&Path::new("diary.txt")); +//! # ::std::old_io::fs::unlink(&Path::new("diary.txt")); //! ``` //! //! So what actually happens if `create` encounters an error? @@ -199,7 +217,7 @@ //! If you wanted to read several `u32`s from a file and return their product: //! //! ```rust -//! use std::io::{File, IoResult}; +//! use std::old_io::{File, IoResult}; //! //! fn file_product(p: &Path) -> IoResult<u32> { //! let mut f = File::open(p); @@ -925,9 +943,9 @@ unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) - /// # Examples /// /// ``` -/// use std::io; -/// use std::io::ByRefReader; -/// use std::io::util::LimitReader; +/// use std::old_io as io; +/// use std::old_io::ByRefReader; +/// use std::old_io::util::LimitReader; /// /// fn process_input<R: Reader>(r: R) {} /// @@ -979,7 +997,12 @@ pub trait Writer { /// `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<()>; + fn write_all(&mut self, buf: &[u8]) -> IoResult<()>; + + /// Deprecated, this method was renamed to `write_all` + #[unstable(feature = "io")] + #[deprecated(since = "1.0.0", reason = "renamed to `write_all`")] + fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write_all(buf) } /// Flush this output stream, ensuring that all intermediately buffered /// contents reach their destination. @@ -1008,7 +1031,7 @@ pub trait Writer { impl<'a, T: ?Sized + Writer> fmt::Writer for Adaptor<'a, T> { fn write_str(&mut self, s: &str) -> fmt::Result { - match self.inner.write(s.as_bytes()) { + match self.inner.write_all(s.as_bytes()) { Ok(()) => Ok(()), Err(e) => { self.error = Err(e); @@ -1034,7 +1057,7 @@ pub trait Writer { /// converted byte-array instead. #[inline] fn write_str(&mut self, s: &str) -> IoResult<()> { - self.write(s.as_bytes()) + self.write_all(s.as_bytes()) } /// Writes a string into this sink, and then writes a literal newline (`\n`) @@ -1046,7 +1069,7 @@ pub trait Writer { /// that the `write` method is used specifically instead. #[inline] fn write_line(&mut self, s: &str) -> IoResult<()> { - self.write_str(s).and_then(|()| self.write(&[b'\n'])) + self.write_str(s).and_then(|()| self.write_all(&[b'\n'])) } /// Write a single char, encoded as UTF-8. @@ -1054,7 +1077,7 @@ pub trait Writer { fn write_char(&mut self, c: char) -> IoResult<()> { let mut buf = [0u8; 4]; let n = c.encode_utf8(buf.as_mut_slice()).unwrap_or(0); - self.write(&buf[..n]) + self.write_all(&buf[..n]) } /// Write the result of passing n through `int::to_str_bytes`. @@ -1072,61 +1095,61 @@ pub trait Writer { /// Write a little-endian uint (number of bytes depends on system). #[inline] fn write_le_uint(&mut self, n: uint) -> IoResult<()> { - extensions::u64_to_le_bytes(n as u64, uint::BYTES, |v| self.write(v)) + extensions::u64_to_le_bytes(n as u64, uint::BYTES, |v| self.write_all(v)) } /// Write a little-endian int (number of bytes depends on system). #[inline] fn write_le_int(&mut self, n: int) -> IoResult<()> { - extensions::u64_to_le_bytes(n as u64, int::BYTES, |v| self.write(v)) + extensions::u64_to_le_bytes(n as u64, int::BYTES, |v| self.write_all(v)) } /// Write a big-endian uint (number of bytes depends on system). #[inline] fn write_be_uint(&mut self, n: uint) -> IoResult<()> { - extensions::u64_to_be_bytes(n as u64, uint::BYTES, |v| self.write(v)) + extensions::u64_to_be_bytes(n as u64, uint::BYTES, |v| self.write_all(v)) } /// Write a big-endian int (number of bytes depends on system). #[inline] fn write_be_int(&mut self, n: int) -> IoResult<()> { - extensions::u64_to_be_bytes(n as u64, int::BYTES, |v| self.write(v)) + extensions::u64_to_be_bytes(n as u64, int::BYTES, |v| self.write_all(v)) } /// Write a big-endian u64 (8 bytes). #[inline] fn write_be_u64(&mut self, n: u64) -> IoResult<()> { - extensions::u64_to_be_bytes(n, 8u, |v| self.write(v)) + extensions::u64_to_be_bytes(n, 8u, |v| self.write_all(v)) } /// Write a big-endian u32 (4 bytes). #[inline] fn write_be_u32(&mut self, n: u32) -> IoResult<()> { - extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v)) + extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write_all(v)) } /// Write a big-endian u16 (2 bytes). #[inline] fn write_be_u16(&mut self, n: u16) -> IoResult<()> { - extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v)) + extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write_all(v)) } /// Write a big-endian i64 (8 bytes). #[inline] fn write_be_i64(&mut self, n: i64) -> IoResult<()> { - extensions::u64_to_be_bytes(n as u64, 8u, |v| self.write(v)) + extensions::u64_to_be_bytes(n as u64, 8u, |v| self.write_all(v)) } /// Write a big-endian i32 (4 bytes). #[inline] fn write_be_i32(&mut self, n: i32) -> IoResult<()> { - extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v)) + extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write_all(v)) } /// Write a big-endian i16 (2 bytes). #[inline] fn write_be_i16(&mut self, n: i16) -> IoResult<()> { - extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v)) + extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write_all(v)) } /// Write a big-endian IEEE754 double-precision floating-point (8 bytes). @@ -1148,37 +1171,37 @@ pub trait Writer { /// Write a little-endian u64 (8 bytes). #[inline] fn write_le_u64(&mut self, n: u64) -> IoResult<()> { - extensions::u64_to_le_bytes(n, 8u, |v| self.write(v)) + extensions::u64_to_le_bytes(n, 8u, |v| self.write_all(v)) } /// Write a little-endian u32 (4 bytes). #[inline] fn write_le_u32(&mut self, n: u32) -> IoResult<()> { - extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v)) + extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write_all(v)) } /// Write a little-endian u16 (2 bytes). #[inline] fn write_le_u16(&mut self, n: u16) -> IoResult<()> { - extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v)) + extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write_all(v)) } /// Write a little-endian i64 (8 bytes). #[inline] fn write_le_i64(&mut self, n: i64) -> IoResult<()> { - extensions::u64_to_le_bytes(n as u64, 8u, |v| self.write(v)) + extensions::u64_to_le_bytes(n as u64, 8u, |v| self.write_all(v)) } /// Write a little-endian i32 (4 bytes). #[inline] fn write_le_i32(&mut self, n: i32) -> IoResult<()> { - extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v)) + extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write_all(v)) } /// Write a little-endian i16 (2 bytes). #[inline] fn write_le_i16(&mut self, n: i16) -> IoResult<()> { - extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v)) + extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write_all(v)) } /// Write a little-endian IEEE754 double-precision floating-point @@ -1202,13 +1225,13 @@ pub trait Writer { /// Write a u8 (1 byte). #[inline] fn write_u8(&mut self, n: u8) -> IoResult<()> { - self.write(&[n]) + self.write_all(&[n]) } /// Write an i8 (1 byte). #[inline] fn write_i8(&mut self, n: i8) -> IoResult<()> { - self.write(&[n as u8]) + self.write_all(&[n as u8]) } } @@ -1230,8 +1253,8 @@ impl<T: Writer> ByRefWriter for T { impl<'a> Writer for Box<Writer+'a> { #[inline] - fn write(&mut self, buf: &[u8]) -> IoResult<()> { - (&mut **self).write(buf) + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { + (&mut **self).write_all(buf) } #[inline] @@ -1242,7 +1265,7 @@ impl<'a> Writer for Box<Writer+'a> { impl<'a> Writer for &'a mut (Writer+'a) { #[inline] - fn write(&mut self, buf: &[u8]) -> IoResult<()> { (**self).write(buf) } + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { (**self).write_all(buf) } #[inline] fn flush(&mut self) -> IoResult<()> { (**self).flush() } @@ -1254,8 +1277,8 @@ impl<'a> Writer for &'a mut (Writer+'a) { /// # Example /// /// ``` -/// use std::io::util::TeeReader; -/// use std::io::{stdin, ByRefWriter}; +/// use std::old_io::util::TeeReader; +/// use std::old_io::{stdin, ByRefWriter}; /// /// fn process_input<R: Reader>(r: R) {} /// @@ -1277,7 +1300,7 @@ pub struct RefWriter<'a, W:'a> { impl<'a, W: Writer> Writer for RefWriter<'a, W> { #[inline] - fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write(buf) } + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write_all(buf) } #[inline] fn flush(&mut self) -> IoResult<()> { self.inner.flush() } @@ -1379,7 +1402,7 @@ pub trait Buffer: Reader { /// # Example /// /// ```rust - /// use std::io::BufReader; + /// use std::old_io::BufReader; /// /// let mut reader = BufReader::new(b"hello\nworld"); /// assert_eq!("hello\n", &*reader.read_line().unwrap()); @@ -1601,7 +1624,7 @@ impl<'a, T, A: ?Sized + Acceptor<T>> Iterator for IncomingConnections<'a, A> { /// # Example /// /// ``` -/// use std::io; +/// use std::old_io as io; /// /// let eof = io::standard_error(io::EndOfFile); /// let einval = io::standard_error(io::InvalidInput); @@ -1690,7 +1713,7 @@ pub enum FileType { /// /// ```no_run /// -/// use std::io::fs::PathExtensions; +/// use std::old_io::fs::PathExtensions; /// /// let info = match Path::new("foo.txt").stat() { /// Ok(stat) => stat, diff --git a/src/libstd/io/net/addrinfo.rs b/src/libstd/old_io/net/addrinfo.rs index 7825a4e16e1..9800cc6829e 100644 --- a/src/libstd/io/net/addrinfo.rs +++ b/src/libstd/old_io/net/addrinfo.rs @@ -20,8 +20,8 @@ pub use self::Flag::*; pub use self::Protocol::*; use iter::IteratorExt; -use io::{IoResult}; -use io::net::ip::{SocketAddr, IpAddr}; +use old_io::{IoResult}; +use old_io::net::ip::{SocketAddr, IpAddr}; use option::Option; use option::Option::{Some, None}; use string::String; @@ -114,7 +114,7 @@ fn lookup(hostname: Option<&str>, servname: Option<&str>, hint: Option<Hint>) mod test { use prelude::v1::*; use super::*; - use io::net::ip::*; + use old_io::net::ip::*; #[test] fn dns_smoke_test() { diff --git a/src/libstd/io/net/ip.rs b/src/libstd/old_io/net/ip.rs index 7e7603c826e..e60b455aecd 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/old_io/net/ip.rs @@ -19,8 +19,8 @@ pub use self::IpAddr::*; use boxed::Box; use fmt; -use io::{self, IoResult, IoError}; -use io::net; +use old_io::{self, IoResult, IoError}; +use old_io::net; use iter::{Iterator, IteratorExt}; use ops::{FnOnce, FnMut}; use option::Option; @@ -406,9 +406,9 @@ impl FromStr for SocketAddr { /// ```rust,no_run /// # #![allow(unused_must_use)] /// -/// use std::io::{TcpStream, TcpListener}; -/// use std::io::net::udp::UdpSocket; -/// use std::io::net::ip::{Ipv4Addr, SocketAddr}; +/// use std::old_io::{TcpStream, TcpListener}; +/// use std::old_io::net::udp::UdpSocket; +/// use std::old_io::net::ip::{Ipv4Addr, SocketAddr}; /// /// fn main() { /// // The following lines are equivalent modulo possible "localhost" name resolution @@ -438,7 +438,7 @@ pub trait ToSocketAddr { fn to_socket_addr(&self) -> IoResult<SocketAddr> { self.to_socket_addr_all() .and_then(|v| v.into_iter().next().ok_or_else(|| IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "no address available", detail: None })) @@ -481,7 +481,7 @@ fn parse_and_resolve_socket_addr(s: &str) -> IoResult<Vec<SocketAddr>> { match $e { Some(r) => r, None => return Err(IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: $msg, detail: None }) @@ -526,7 +526,7 @@ impl<'a> ToSocketAddr for &'a str { parse_and_resolve_socket_addr(*self) .and_then(|v| v.into_iter().next() .ok_or_else(|| IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "no address available", detail: None }) diff --git a/src/libstd/io/net/mod.rs b/src/libstd/old_io/net/mod.rs index 2056933e6df..d8394aa8b6a 100644 --- a/src/libstd/io/net/mod.rs +++ b/src/libstd/old_io/net/mod.rs @@ -10,7 +10,7 @@ //! Networking I/O -use io::{IoError, IoResult, InvalidInput}; +use old_io::{IoError, IoResult, InvalidInput}; use ops::FnMut; use option::Option::None; use result::Result::{Ok, Err}; diff --git a/src/libstd/io/net/pipe.rs b/src/libstd/old_io/net/pipe.rs index ac7e9ce5dde..71b77adcd96 100644 --- a/src/libstd/io/net/pipe.rs +++ b/src/libstd/old_io/net/pipe.rs @@ -24,7 +24,7 @@ use prelude::v1::*; use ffi::CString; use path::BytesContainer; -use io::{Listener, Acceptor, IoResult, TimedOut, standard_error}; +use old_io::{Listener, Acceptor, IoResult, TimedOut, standard_error}; use sys::pipe::UnixAcceptor as UnixAcceptorImp; use sys::pipe::UnixListener as UnixListenerImp; use sys::pipe::UnixStream as UnixStreamImp; @@ -48,7 +48,7 @@ impl UnixStream { /// /// ```rust /// # #![allow(unused_must_use)] - /// use std::io::net::pipe::UnixStream; + /// use std::old_io::net::pipe::UnixStream; /// /// let server = Path::new("path/to/my/socket"); /// let mut stream = UnixStream::connect(&server); @@ -146,7 +146,7 @@ impl Reader for UnixStream { } impl Writer for UnixStream { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write(buf) } } @@ -173,8 +173,8 @@ impl UnixListener { /// /// ``` /// # fn foo() { - /// use std::io::net::pipe::UnixListener; - /// use std::io::{Listener, Acceptor}; + /// use std::old_io::net::pipe::UnixListener; + /// use std::old_io::{Listener, Acceptor}; /// /// let server = Path::new("/path/to/my/socket"); /// let stream = UnixListener::bind(&server); @@ -275,11 +275,11 @@ impl sys_common::AsInner<UnixAcceptorImp> for UnixAcceptor { mod tests { use prelude::v1::*; - use io::fs::PathExtensions; - use io::{EndOfFile, TimedOut, ShortWrite, IoError, ConnectionReset}; - use io::{NotConnected, BrokenPipe, FileNotFound, InvalidInput, OtherIoError}; - use io::{PermissionDenied, Acceptor, Listener}; - use io::test::*; + use old_io::fs::PathExtensions; + use old_io::{EndOfFile, TimedOut, ShortWrite, IoError, ConnectionReset}; + use old_io::{NotConnected, BrokenPipe, FileNotFound, InvalidInput, OtherIoError}; + use old_io::{PermissionDenied, Acceptor, Listener}; + use old_io::test::*; use super::*; use sync::mpsc::channel; use thread::Thread; diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/old_io/net/tcp.rs index d5feb5977fb..1e76bb3ab0d 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/old_io/net/tcp.rs @@ -18,11 +18,11 @@ //! listener (socket server) implements the `Listener` and `Acceptor` traits. use clone::Clone; -use io::IoResult; +use old_io::IoResult; use result::Result::Err; -use io::net::ip::{SocketAddr, ToSocketAddr}; -use io::{Reader, Writer, Listener, Acceptor}; -use io::{standard_error, TimedOut}; +use old_io::net::ip::{SocketAddr, ToSocketAddr}; +use old_io::{Reader, Writer, Listener, Acceptor}; +use old_io::{standard_error, TimedOut}; use option::Option; use option::Option::{None, Some}; use time::Duration; @@ -41,7 +41,7 @@ use sys_common; /// # Example /// /// ```no_run -/// use std::io::TcpStream; +/// use std::old_io::TcpStream; /// /// { /// let mut stream = TcpStream::connect("127.0.0.1:34254"); @@ -134,8 +134,8 @@ impl TcpStream { /// /// ```no_run /// # #![allow(unused_must_use)] - /// use std::io::timer; - /// use std::io::TcpStream; + /// use std::old_io::timer; + /// use std::old_io::TcpStream; /// use std::time::Duration; /// use std::thread::Thread; /// @@ -262,7 +262,7 @@ impl Reader for TcpStream { } impl Writer for TcpStream { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write(buf) } } @@ -280,8 +280,8 @@ impl sys_common::AsInner<TcpStreamImp> for TcpStream { /// /// ``` /// # fn foo() { -/// use std::io::{TcpListener, TcpStream}; -/// use std::io::{Acceptor, Listener}; +/// use std::old_io::{TcpListener, TcpStream}; +/// use std::old_io::{Acceptor, Listener}; /// use std::thread::Thread; /// /// let listener = TcpListener::bind("127.0.0.1:80").unwrap(); @@ -376,8 +376,8 @@ impl TcpAcceptor { /// # Example /// /// ```no_run - /// use std::io::TcpListener; - /// use std::io::{Listener, Acceptor, TimedOut}; + /// use std::old_io::TcpListener; + /// use std::old_io::{Listener, Acceptor, TimedOut}; /// /// let mut a = TcpListener::bind("127.0.0.1:8482").listen().unwrap(); /// @@ -420,7 +420,7 @@ impl TcpAcceptor { /// # Example /// /// ``` - /// use std::io::{TcpListener, Listener, Acceptor, EndOfFile}; + /// use std::old_io::{TcpListener, Listener, Acceptor, EndOfFile}; /// use std::thread::Thread; /// /// let mut a = TcpListener::bind("127.0.0.1:8482").listen().unwrap(); @@ -488,13 +488,13 @@ mod test { use sync::mpsc::channel; use thread::Thread; - use io::net::tcp::*; - use io::net::ip::*; - use io::test::*; - use io::{EndOfFile, TimedOut, ShortWrite, IoError}; - use io::{ConnectionRefused, BrokenPipe, ConnectionAborted}; - use io::{ConnectionReset, NotConnected, PermissionDenied, OtherIoError}; - use io::{Acceptor, Listener}; + use old_io::net::tcp::*; + use old_io::net::ip::*; + use old_io::test::*; + use old_io::{EndOfFile, TimedOut, ShortWrite, IoError}; + use old_io::{ConnectionRefused, BrokenPipe, ConnectionAborted}; + use old_io::{ConnectionReset, NotConnected, PermissionDenied, OtherIoError}; + use old_io::{Acceptor, Listener}; // FIXME #11530 this fails on android because tests are run as root #[cfg_attr(any(windows, target_os = "android"), ignore)] diff --git a/src/libstd/io/net/udp.rs b/src/libstd/old_io/net/udp.rs index 6e336168b16..9055a089eec 100644 --- a/src/libstd/io/net/udp.rs +++ b/src/libstd/old_io/net/udp.rs @@ -16,8 +16,8 @@ //! datagram protocol. use clone::Clone; -use io::net::ip::{SocketAddr, IpAddr, ToSocketAddr}; -use io::IoResult; +use old_io::net::ip::{SocketAddr, IpAddr, ToSocketAddr}; +use old_io::IoResult; use option::Option; use sys::udp::UdpSocket as UdpSocketImp; use sys_common; @@ -34,8 +34,8 @@ use sys_common; /// # #![allow(unused_must_use)] /// #![feature(slicing_syntax)] /// -/// use std::io::net::udp::UdpSocket; -/// use std::io::net::ip::{Ipv4Addr, SocketAddr}; +/// use std::old_io::net::udp::UdpSocket; +/// use std::old_io::net::ip::{Ipv4Addr, SocketAddr}; /// fn main() { /// let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 34254 }; /// let mut socket = match UdpSocket::bind(addr) { @@ -183,9 +183,9 @@ mod test { use prelude::v1::*; use sync::mpsc::channel; - use io::net::ip::*; - use io::test::*; - use io::{IoError, TimedOut, PermissionDenied, ShortWrite}; + use old_io::net::ip::*; + use old_io::test::*; + use old_io::{IoError, TimedOut, PermissionDenied, ShortWrite}; use super::*; use thread::Thread; diff --git a/src/libstd/io/pipe.rs b/src/libstd/old_io/pipe.rs index 09dcafb0218..5843b1ba1b1 100644 --- a/src/libstd/io/pipe.rs +++ b/src/libstd/old_io/pipe.rs @@ -17,7 +17,7 @@ use prelude::v1::*; -use io::IoResult; +use old_io::IoResult; use libc; use sync::Arc; @@ -49,7 +49,7 @@ impl PipeStream { /// # #![allow(unused_must_use)] /// extern crate libc; /// - /// use std::io::pipe::PipeStream; + /// use std::old_io::pipe::PipeStream; /// /// fn main() { /// let mut pipe = PipeStream::open(libc::STDERR_FILENO); @@ -105,7 +105,7 @@ impl Reader for PipeStream { } impl Writer for PipeStream { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write(buf) } } @@ -120,7 +120,7 @@ mod test { #[test] fn partial_read() { use os; - use io::pipe::PipeStream; + use old_io::pipe::PipeStream; let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() }; let out = PipeStream::open(writer); diff --git a/src/libstd/io/process.rs b/src/libstd/old_io/process.rs index a406d3c2788..78910882467 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/old_io/process.rs @@ -20,9 +20,9 @@ use prelude::v1::*; use collections::HashMap; use ffi::CString; use fmt; -use io::pipe::{PipeStream, PipePair}; -use io::{IoResult, IoError}; -use io; +use old_io::pipe::{PipeStream, PipePair}; +use old_io::{IoResult, IoError}; +use old_io; use libc; use os; use path::BytesContainer; @@ -57,7 +57,7 @@ use thread::Thread; /// # Example /// /// ```should_fail -/// use std::io::Command; +/// use std::old_io::Command; /// /// let mut child = match Command::new("/bin/cat").arg("file.txt").spawn() { /// Ok(child) => child, @@ -158,7 +158,7 @@ pub type EnvMap = HashMap<EnvKey, CString>; /// to be changed (for example, by adding arguments) prior to spawning: /// /// ``` -/// use std::io::Command; +/// use std::old_io::Command; /// /// let mut process = match Command::new("sh").arg("-c").arg("echo hello").spawn() { /// Ok(p) => p, @@ -358,7 +358,7 @@ impl Command { /// # Example /// /// ``` - /// use std::io::Command; + /// use std::old_io::Command; /// /// let output = match Command::new("cat").arg("foot.txt").output() { /// Ok(output) => output, @@ -379,7 +379,7 @@ impl Command { /// # Example /// /// ``` - /// use std::io::Command; + /// use std::old_io::Command; /// /// let status = match Command::new("ls").status() { /// Ok(status) => status, @@ -582,7 +582,7 @@ impl Process { // newer process that happens to have the same (re-used) id if self.exit_code.is_some() { return Err(IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "invalid argument: can't kill an exited process", detail: None, }) @@ -652,8 +652,8 @@ impl Process { /// # Example /// /// ```no_run - /// use std::io::{Command, IoResult}; - /// use std::io::process::ProcessExit; + /// use std::old_io::{Command, IoResult}; + /// use std::old_io::process::ProcessExit; /// /// fn run_gracefully(prog: &str) -> IoResult<ProcessExit> { /// let mut p = try!(Command::new("long-running-process").spawn()); @@ -697,7 +697,7 @@ impl Process { /// fail. pub fn wait_with_output(mut self) -> IoResult<ProcessOutput> { drop(self.stdin.take()); - fn read(stream: Option<io::PipeStream>) -> Receiver<IoResult<Vec<u8>>> { + fn read(stream: Option<old_io::PipeStream>) -> Receiver<IoResult<Vec<u8>>> { let (tx, rx) = channel(); match stream { Some(stream) => { @@ -751,12 +751,12 @@ impl Drop for Process { #[cfg(test)] mod tests { - use io::{Truncate, Write, TimedOut, timer, process, FileNotFound}; + use old_io::{Truncate, Write, TimedOut, timer, process, FileNotFound}; use prelude::v1::{Ok, Err, range, drop, Some, None, Vec}; use prelude::v1::{Path, String, Reader, Writer, Clone}; use prelude::v1::{SliceExt, Str, StrExt, AsSlice, ToString, GenericPath}; - use io::fs::PathExtensions; - use io::timer::*; + use old_io::fs::PathExtensions; + use old_io::timer::*; use rt::running_on_valgrind; use str; use super::{CreatePipe}; @@ -1078,13 +1078,13 @@ mod tests { #[test] fn test_override_env() { use os; - let mut new_env = vec![("RUN_TEST_NEW_ENV", "123")]; // In some build environments (such as chrooted Nix builds), `env` can // only be found in the explicitly-provided PATH env variable, not in // default places such as /bin or /usr/bin. So we need to pass through // PATH to our sub-process. let path_val: String; + let mut new_env = vec![("RUN_TEST_NEW_ENV", "123")]; match os::getenv("PATH") { None => {} Some(val) => { diff --git a/src/libstd/io/result.rs b/src/libstd/old_io/result.rs index c1474650f1e..96b979860ae 100644 --- a/src/libstd/io/result.rs +++ b/src/libstd/old_io/result.rs @@ -19,9 +19,9 @@ use result::Result::{Ok, Err}; use super::{Reader, Writer, Listener, Acceptor, Seek, SeekStyle, IoResult}; impl<W: Writer> Writer for IoResult<W> { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { match *self { - Ok(ref mut writer) => writer.write(buf), + Ok(ref mut writer) => writer.write_all(buf), Err(ref e) => Err((*e).clone()) } } @@ -80,34 +80,34 @@ impl<T, A: Acceptor<T>> Acceptor<T> for IoResult<A> { mod test { use prelude::v1::*; use super::super::mem::*; - use io; + use old_io; #[test] fn test_option_writer() { - let mut writer: io::IoResult<Vec<u8>> = Ok(Vec::new()); - writer.write(&[0, 1, 2]).unwrap(); + let mut writer: old_io::IoResult<Vec<u8>> = Ok(Vec::new()); + writer.write_all(&[0, 1, 2]).unwrap(); writer.flush().unwrap(); assert_eq!(writer.unwrap(), vec!(0, 1, 2)); } #[test] fn test_option_writer_error() { - let mut writer: io::IoResult<Vec<u8>> = - Err(io::standard_error(io::EndOfFile)); + let mut writer: old_io::IoResult<Vec<u8>> = + Err(old_io::standard_error(old_io::EndOfFile)); - match writer.write(&[0, 0, 0]) { + match writer.write_all(&[0, 0, 0]) { Ok(..) => panic!(), - Err(e) => assert_eq!(e.kind, io::EndOfFile), + Err(e) => assert_eq!(e.kind, old_io::EndOfFile), } match writer.flush() { Ok(..) => panic!(), - Err(e) => assert_eq!(e.kind, io::EndOfFile), + Err(e) => assert_eq!(e.kind, old_io::EndOfFile), } } #[test] fn test_option_reader() { - let mut reader: io::IoResult<MemReader> = + let mut reader: old_io::IoResult<MemReader> = Ok(MemReader::new(vec!(0, 1, 2, 3))); let mut buf = [0, 0]; reader.read(&mut buf).unwrap(); @@ -117,13 +117,13 @@ mod test { #[test] fn test_option_reader_error() { - let mut reader: io::IoResult<MemReader> = - Err(io::standard_error(io::EndOfFile)); + let mut reader: old_io::IoResult<MemReader> = + Err(old_io::standard_error(old_io::EndOfFile)); let mut buf = []; match reader.read(&mut buf) { Ok(..) => panic!(), - Err(e) => assert_eq!(e.kind, io::EndOfFile), + Err(e) => assert_eq!(e.kind, old_io::EndOfFile), } } } diff --git a/src/libstd/io/stdio.rs b/src/libstd/old_io/stdio.rs index a5664b9f013..70400619bea 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/old_io/stdio.rs @@ -19,10 +19,10 @@ //! //! ```rust //! # #![allow(unused_must_use)] -//! use std::io; +//! use std::old_io; //! -//! let mut out = io::stdout(); -//! out.write(b"Hello, world!"); +//! let mut out = old_io::stdout(); +//! out.write_all(b"Hello, world!"); //! ``` use self::StdSource::*; @@ -32,7 +32,7 @@ use cell::RefCell; use clone::Clone; use failure::LOCAL_STDERR; use fmt; -use io::{Reader, Writer, IoResult, IoError, OtherIoError, Buffer, +use old_io::{Reader, Writer, IoResult, IoError, OtherIoError, Buffer, standard_error, EndOfFile, LineBufferedWriter, BufferedReader}; use marker::{Sync, Send}; use libc; @@ -141,9 +141,9 @@ impl StdinReader { /// # Examples /// /// ```rust - /// use std::io; + /// use std::old_io; /// - /// for line in io::stdin().lock().lines() { + /// for line in old_io::stdin().lock().lines() { /// println!("{}", line.unwrap()); /// } /// ``` @@ -370,14 +370,14 @@ pub fn flush() { /// Prints a string to the stdout of the current process. No newline is emitted /// after the string is printed. pub fn print(s: &str) { - with_task_stdout(|io| io.write(s.as_bytes())) + with_task_stdout(|io| io.write_all(s.as_bytes())) } /// Prints a string to the stdout of the current process. A literal /// `\n` character is printed to the console after the string. pub fn println(s: &str) { with_task_stdout(|io| { - io.write(s.as_bytes()).and_then(|()| io.write(&[b'\n'])) + io.write_all(s.as_bytes()).and_then(|()| io.write_all(&[b'\n'])) }) } @@ -498,7 +498,7 @@ impl StdWriter { } impl Writer for StdWriter { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { // As with stdin on windows, stdout often can't handle writes of large // sizes. For an example, see #14940. For this reason, chunk the output // buffer on windows, but on unix we can just write the whole buffer all @@ -539,7 +539,7 @@ mod tests { #[test] fn capture_stdout() { - use io::{ChanReader, ChanWriter}; + use old_io::{ChanReader, ChanWriter}; let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); @@ -552,7 +552,7 @@ mod tests { #[test] fn capture_stderr() { - use io::{ChanReader, ChanWriter, Reader}; + use old_io::{ChanReader, ChanWriter, Reader}; let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); diff --git a/src/libstd/io/tempfile.rs b/src/libstd/old_io/tempfile.rs index 394686be814..029fef7c197 100644 --- a/src/libstd/io/tempfile.rs +++ b/src/libstd/old_io/tempfile.rs @@ -10,8 +10,8 @@ //! Temporary files and directories -use io::{fs, IoError, IoErrorKind, IoResult}; -use io; +use old_io::{fs, IoError, IoErrorKind, IoResult}; +use old_io; use iter::{IteratorExt, range}; use ops::Drop; use option::Option; @@ -29,7 +29,7 @@ use string::String; /// # Examples /// /// ```no_run -/// use std::io::TempDir; +/// use std::old_io::TempDir; /// /// { /// // create a temporary directory @@ -113,7 +113,7 @@ impl TempDir { suffix }; let path = tmpdir.join(leaf); - match fs::mkdir(&path, io::USER_RWX) { + match fs::mkdir(&path, old_io::USER_RWX) { Ok(_) => return Ok(TempDir { path: Some(path), disarmed: false }), Err(IoError{kind:IoErrorKind::PathAlreadyExists,..}) => (), Err(e) => return Err(e) diff --git a/src/libstd/io/test.rs b/src/libstd/old_io/test.rs index 6de466eb20b..f49e2397d42 100644 --- a/src/libstd/io/test.rs +++ b/src/libstd/old_io/test.rs @@ -14,7 +14,7 @@ use prelude::v1::*; use libc; use os; -use std::io::net::ip::*; +use std::old_io::net::ip::*; use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; /// Get a port number, starting at 9600, for use in tests diff --git a/src/libstd/io/timer.rs b/src/libstd/old_io/timer.rs index 68ae7d0ff20..7e15c9ad7fc 100644 --- a/src/libstd/io/timer.rs +++ b/src/libstd/old_io/timer.rs @@ -17,7 +17,7 @@ use sync::mpsc::{Receiver, Sender, channel}; use time::Duration; -use io::IoResult; +use old_io::IoResult; use sys::timer::Callback; use sys::timer::Timer as TimerImp; @@ -31,7 +31,7 @@ use sys::timer::Timer as TimerImp; /// /// ``` /// # fn foo() { -/// use std::io::Timer; +/// use std::old_io::Timer; /// use std::time::Duration; /// /// let mut timer = Timer::new().unwrap(); @@ -50,11 +50,11 @@ use sys::timer::Timer as TimerImp; /// ``` /// /// If only sleeping is necessary, then a convenience API is provided through -/// the `io::timer` module. +/// the `old_io::timer` module. /// /// ``` /// # fn foo() { -/// use std::io::timer; +/// use std::old_io::timer; /// use std::time::Duration; /// /// // Put this task to sleep for 5 seconds @@ -115,7 +115,7 @@ impl Timer { /// # Example /// /// ```rust - /// use std::io::Timer; + /// use std::old_io::Timer; /// use std::time::Duration; /// /// let mut timer = Timer::new().unwrap(); @@ -128,7 +128,7 @@ impl Timer { /// ``` /// /// ```rust - /// use std::io::Timer; + /// use std::old_io::Timer; /// use std::time::Duration; /// /// // Incorrect, method chaining-style: @@ -167,7 +167,7 @@ impl Timer { /// # Example /// /// ```rust - /// use std::io::Timer; + /// use std::old_io::Timer; /// use std::time::Duration; /// /// let mut timer = Timer::new().unwrap(); @@ -186,7 +186,7 @@ impl Timer { /// ``` /// /// ```rust - /// use std::io::Timer; + /// use std::old_io::Timer; /// use std::time::Duration; /// /// // Incorrect, method chaining-style. diff --git a/src/libstd/io/util.rs b/src/libstd/old_io/util.rs index e4bf38a9ef5..4b6d9b08141 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/old_io/util.rs @@ -12,7 +12,7 @@ use prelude::v1::*; use cmp; -use io; +use old_io; use slice::bytes::MutableByteVector; /// Wraps a `Reader`, limiting the number of bytes that can be read from it. @@ -42,9 +42,9 @@ impl<R: Reader> LimitReader<R> { } impl<R: Reader> Reader for LimitReader<R> { - fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { + fn read(&mut self, buf: &mut [u8]) -> old_io::IoResult<uint> { if self.limit == 0 { - return Err(io::standard_error(io::EndOfFile)); + return Err(old_io::standard_error(old_io::EndOfFile)); } let len = cmp::min(self.limit, buf.len()); @@ -58,11 +58,11 @@ impl<R: Reader> Reader for LimitReader<R> { } impl<R: Buffer> Buffer for LimitReader<R> { - fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> { + fn fill_buf<'a>(&'a mut self) -> old_io::IoResult<&'a [u8]> { let amt = try!(self.inner.fill_buf()); let buf = &amt[..cmp::min(amt.len(), self.limit)]; if buf.len() == 0 { - Err(io::standard_error(io::EndOfFile)) + Err(old_io::standard_error(old_io::EndOfFile)) } else { Ok(buf) } @@ -83,7 +83,7 @@ pub struct NullWriter; impl Writer for NullWriter { #[inline] - fn write(&mut self, _buf: &[u8]) -> io::IoResult<()> { Ok(()) } + fn write_all(&mut self, _buf: &[u8]) -> old_io::IoResult<()> { Ok(()) } } /// A `Reader` which returns an infinite stream of 0 bytes, like /dev/zero. @@ -92,14 +92,14 @@ pub struct ZeroReader; impl Reader for ZeroReader { #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { + fn read(&mut self, buf: &mut [u8]) -> old_io::IoResult<uint> { buf.set_memory(0); Ok(buf.len()) } } impl Buffer for ZeroReader { - fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> { + fn fill_buf<'a>(&'a mut self) -> old_io::IoResult<&'a [u8]> { static DATA: [u8; 64] = [0; 64]; Ok(DATA.as_slice()) } @@ -113,14 +113,14 @@ pub struct NullReader; impl Reader for NullReader { #[inline] - fn read(&mut self, _buf: &mut [u8]) -> io::IoResult<uint> { - Err(io::standard_error(io::EndOfFile)) + fn read(&mut self, _buf: &mut [u8]) -> old_io::IoResult<uint> { + Err(old_io::standard_error(old_io::EndOfFile)) } } impl Buffer for NullReader { - fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> { - Err(io::standard_error(io::EndOfFile)) + fn fill_buf<'a>(&'a mut self) -> old_io::IoResult<&'a [u8]> { + Err(old_io::standard_error(old_io::EndOfFile)) } fn consume(&mut self, _amt: uint) {} } @@ -143,15 +143,15 @@ impl<W> MultiWriter<W> where W: Writer { impl<W> Writer for MultiWriter<W> where W: Writer { #[inline] - fn write(&mut self, buf: &[u8]) -> io::IoResult<()> { + fn write_all(&mut self, buf: &[u8]) -> old_io::IoResult<()> { for writer in self.writers.iter_mut() { - try!(writer.write(buf)); + try!(writer.write_all(buf)); } Ok(()) } #[inline] - fn flush(&mut self) -> io::IoResult<()> { + fn flush(&mut self) -> old_io::IoResult<()> { for writer in self.writers.iter_mut() { try!(writer.flush()); } @@ -176,13 +176,13 @@ impl<R: Reader, I: Iterator<Item=R>> ChainedReader<I, R> { } impl<R: Reader, I: Iterator<Item=R>> Reader for ChainedReader<I, R> { - fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { + fn read(&mut self, buf: &mut [u8]) -> old_io::IoResult<uint> { loop { let err = match self.cur_reader { Some(ref mut r) => { match r.read(buf) { Ok(len) => return Ok(len), - Err(ref e) if e.kind == io::EndOfFile => None, + Err(ref e) if e.kind == old_io::EndOfFile => None, Err(e) => Some(e), } } @@ -194,7 +194,7 @@ impl<R: Reader, I: Iterator<Item=R>> Reader for ChainedReader<I, R> { None => {} } } - Err(io::standard_error(io::EndOfFile)) + Err(old_io::standard_error(old_io::EndOfFile)) } } @@ -221,23 +221,23 @@ impl<R: Reader, W: Writer> TeeReader<R, W> { } impl<R: Reader, W: Writer> Reader for TeeReader<R, W> { - fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { + fn read(&mut self, buf: &mut [u8]) -> old_io::IoResult<uint> { self.reader.read(buf).and_then(|len| { - self.writer.write(&mut buf[..len]).map(|()| len) + self.writer.write_all(&mut buf[..len]).map(|()| len) }) } } /// Copies all data from a `Reader` to a `Writer`. -pub fn copy<R: Reader, W: Writer>(r: &mut R, w: &mut W) -> io::IoResult<()> { +pub fn copy<R: Reader, W: Writer>(r: &mut R, w: &mut W) -> old_io::IoResult<()> { let mut buf = [0; super::DEFAULT_BUF_SIZE]; loop { let len = match r.read(&mut buf) { Ok(len) => len, - Err(ref e) if e.kind == io::EndOfFile => return Ok(()), + Err(ref e) if e.kind == old_io::EndOfFile => return Ok(()), Err(e) => return Err(e), }; - try!(w.write(&buf[..len])); + try!(w.write_all(&buf[..len])); } } @@ -257,14 +257,14 @@ impl<T: Iterator<Item=u8>> IterReader<T> { impl<T: Iterator<Item=u8>> Reader for IterReader<T> { #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { + fn read(&mut self, buf: &mut [u8]) -> old_io::IoResult<uint> { let mut len = 0; for (slot, elt) in buf.iter_mut().zip(self.iter.by_ref()) { *slot = elt; len += 1; } if len == 0 && buf.len() != 0 { - Err(io::standard_error(io::EndOfFile)) + Err(old_io::standard_error(old_io::EndOfFile)) } else { Ok(len) } @@ -275,8 +275,8 @@ impl<T: Iterator<Item=u8>> Reader for IterReader<T> { mod test { use prelude::v1::*; - use io::{MemReader, ByRefReader}; - use io; + use old_io::{MemReader, ByRefReader}; + use old_io; use super::*; #[test] @@ -321,7 +321,7 @@ mod test { fn test_null_writer() { let mut s = NullWriter; let buf = vec![0, 0, 0]; - s.write(buf.as_slice()).unwrap(); + s.write_all(buf.as_slice()).unwrap(); s.flush().unwrap(); } @@ -347,12 +347,12 @@ mod test { struct TestWriter; impl Writer for TestWriter { - fn write(&mut self, _buf: &[u8]) -> io::IoResult<()> { + fn write_all(&mut self, _buf: &[u8]) -> old_io::IoResult<()> { unsafe { writes += 1 } Ok(()) } - fn flush(&mut self) -> io::IoResult<()> { + fn flush(&mut self) -> old_io::IoResult<()> { unsafe { flushes += 1 } Ok(()) } @@ -360,7 +360,7 @@ mod test { let mut multi = MultiWriter::new(vec!(box TestWriter as Box<Writer>, box TestWriter as Box<Writer>)); - multi.write(&[1, 2, 3]).unwrap(); + multi.write_all(&[1, 2, 3]).unwrap(); assert_eq!(2, unsafe { writes }); assert_eq!(0, unsafe { flushes }); multi.flush().unwrap(); @@ -400,7 +400,7 @@ mod test { let mut r = LimitReader::new(r.by_ref(), 3); assert_eq!(r.read_line(), Ok("012".to_string())); assert_eq!(r.limit(), 0); - assert_eq!(r.read_line().err().unwrap().kind, io::EndOfFile); + assert_eq!(r.read_line().err().unwrap().kind, old_io::EndOfFile); } { let mut r = LimitReader::new(r.by_ref(), 9); @@ -432,7 +432,7 @@ mod test { assert_eq!(len, 2); assert!(buf == [6, 7, 5]); - assert_eq!(r.read(&mut buf).unwrap_err().kind, io::EndOfFile); + assert_eq!(r.read(&mut buf).unwrap_err().kind, old_io::EndOfFile); } #[test] diff --git a/src/libstd/os.rs b/src/libstd/os.rs index d81e2b3aa4b..cd37a355e1d 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -10,17 +10,19 @@ //! Higher-level interfaces to libc::* functions and operating system services. //! -//! In general these take and return rust types, use rust idioms (enums, closures, vectors) rather -//! than C idioms, and do more extensive safety checks. +//! In general these take and return rust types, use rust idioms (enums, +//! closures, vectors) rather than C idioms, and do more extensive safety +//! checks. //! -//! This module is not meant to only contain 1:1 mappings to libc entries; any os-interface code -//! that is reasonably useful and broadly applicable can go here. Including utility routines that -//! merely build on other os code. +//! This module is not meant to only contain 1:1 mappings to libc entries; any +//! os-interface code that is reasonably useful and broadly applicable can go +//! here. Including utility routines that merely build on other os code. //! -//! We assume the general case is that users do not care, and do not want to be made to care, which -//! operating system they are on. While they may want to special case various special cases -- and -//! so we will not _hide_ the facts of which OS the user is on -- they should be given the -//! opportunity to write OS-ignorant code by default. +//! We assume the general case is that users do not care, and do not want to be +//! made to care, which operating system they are on. While they may want to +//! special case various special cases -- and so we will not _hide_ the facts of +//! which OS the user is on -- they should be given the opportunity to write +//! OS-ignorant code by default. #![unstable(feature = "os")] @@ -35,7 +37,7 @@ use self::MapError::*; use clone::Clone; use error::{FromError, Error}; use fmt; -use io::{IoResult, IoError}; +use old_io::{IoResult, IoError}; use iter::{Iterator, IteratorExt}; use marker::{Copy, Send}; use libc::{c_void, c_int, c_char}; @@ -374,7 +376,7 @@ pub struct Pipe { /// This function is also unsafe as there is no destructor associated with the /// `Pipe` structure will return. If it is not arranged for the returned file /// descriptors to be closed, the file descriptors will leak. For safe handling -/// of this scenario, use `std::io::PipeStream` instead. +/// of this scenario, use `std::old_io::PipeStream` instead. pub unsafe fn pipe() -> IoResult<Pipe> { let (reader, writer) = try!(sys::os::pipe()); Ok(Pipe { @@ -1635,10 +1637,10 @@ mod tests { fn memory_map_file() { use libc; use os::*; - use io::fs::{File, unlink}; - use io::SeekStyle::SeekSet; - use io::FileMode::Open; - use io::FileAccess::ReadWrite; + use old_io::fs::{File, unlink}; + use old_io::SeekStyle::SeekSet; + use old_io::FileMode::Open; + use old_io::FileAccess::ReadWrite; #[cfg(not(windows))] fn get_fd(file: &File) -> libc::c_int { diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index e4a662f8463..b42353e964c 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -49,7 +49,7 @@ //! ## Example //! //! ```rust -//! use std::io::fs::PathExtensions; +//! use std::old_io::fs::PathExtensions; //! //! let mut path = Path::new("/tmp/path"); //! println!("path: {}", path.display()); diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index 07fdd1a830f..39138e14803 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -14,7 +14,7 @@ use clone::Clone; use cmp::{Ordering, Eq, Ord, PartialEq, PartialOrd}; use fmt; use hash; -use io::Writer; +use old_io::Writer; use iter::{AdditiveIterator, Extend}; use iter::{Iterator, IteratorExt, Map}; use marker::Sized; diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index ebded1f0855..34faa65af75 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -20,7 +20,7 @@ use clone::Clone; use cmp::{Ordering, Eq, Ord, PartialEq, PartialOrd}; use fmt; use hash; -use io::Writer; +use old_io::Writer; use iter::{AdditiveIterator, Extend}; use iter::{Iterator, IteratorExt, Map, repeat}; use mem; diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs index 51cf173ca94..51c9f9de83c 100644 --- a/src/libstd/prelude/v1.rs +++ b/src/libstd/prelude/v1.rs @@ -62,6 +62,6 @@ // NB: remove when path reform lands #[doc(no_inline)] pub use path::{Path, GenericPath}; // NB: remove when I/O reform lands -#[doc(no_inline)] pub use io::{Buffer, Writer, Reader, Seek, BufferPrelude}; +#[doc(no_inline)] pub use old_io::{Buffer, Writer, Reader, Seek, BufferPrelude}; // NB: remove when range syntax lands #[doc(no_inline)] pub use iter::range; diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index 5844cc85c31..8f5d0e22c88 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -223,7 +223,7 @@ use cell::RefCell; use clone::Clone; -use io::IoResult; +use old_io::IoResult; use iter::{Iterator, IteratorExt}; use mem; use rc::Rc; diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index bafbde2511d..547c8131486 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -19,7 +19,7 @@ mod imp { use self::OsRngInner::*; - use io::{IoResult, File}; + use old_io::{IoResult, File}; use path::Path; use rand::Rng; use rand::reader::ReaderRng; @@ -187,7 +187,7 @@ mod imp { mod imp { extern crate libc; - use io::{IoResult}; + use old_io::{IoResult}; use marker::Sync; use mem; use os; @@ -259,7 +259,7 @@ mod imp { mod imp { extern crate libc; - use io::{IoResult, IoError}; + use old_io::{IoResult, IoError}; use mem; use ops::Drop; use os; diff --git a/src/libstd/rand/reader.rs b/src/libstd/rand/reader.rs index 177b7380831..afacfeeaa30 100644 --- a/src/libstd/rand/reader.rs +++ b/src/libstd/rand/reader.rs @@ -10,7 +10,7 @@ //! A wrapper around any Reader to treat it as an RNG. -use io::Reader; +use old_io::Reader; use rand::Rng; use result::Result::{Ok, Err}; use slice::SliceExt; @@ -26,7 +26,7 @@ use slice::SliceExt; /// /// ```rust /// use std::rand::{reader, Rng}; -/// use std::io::MemReader; +/// use std::old_io::MemReader; /// /// let mut rng = reader::ReaderRng::new(MemReader::new(vec!(1,2,3,4,5,6,7,8))); /// println!("{:x}", rng.gen::<uint>()); @@ -77,7 +77,7 @@ mod test { use prelude::v1::*; use super::ReaderRng; - use io::MemReader; + use old_io::MemReader; use num::Int; use rand::Rng; diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 92316fe26b4..322c6137984 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -120,7 +120,7 @@ //! //! ```no_run //! use std::sync::mpsc::channel; -//! use std::io::timer::Timer; +//! use std::old_io::timer::Timer; //! use std::time::Duration; //! //! let (tx, rx) = channel::<int>(); @@ -144,7 +144,7 @@ //! //! ```no_run //! use std::sync::mpsc::channel; -//! use std::io::timer::Timer; +//! use std::old_io::timer::Timer; //! use std::time::Duration; //! //! let (tx, rx) = channel::<int>(); diff --git a/src/libstd/sys/common/backtrace.rs b/src/libstd/sys/common/backtrace.rs index d069d9ee3b8..9b53ebf70a0 100644 --- a/src/libstd/sys/common/backtrace.rs +++ b/src/libstd/sys/common/backtrace.rs @@ -10,7 +10,7 @@ use prelude::v1::*; -use io::IoResult; +use old_io::IoResult; #[cfg(target_pointer_width = "64")] pub const HEX_WIDTH: uint = 18; diff --git a/src/libstd/sys/common/mod.rs b/src/libstd/sys/common/mod.rs index 272cf9bd0c0..ae01586c703 100644 --- a/src/libstd/sys/common/mod.rs +++ b/src/libstd/sys/common/mod.rs @@ -11,7 +11,7 @@ #![allow(missing_docs)] #![allow(dead_code)] -use io::{self, IoError, IoResult}; +use old_io::{self, IoError, IoResult}; use prelude::v1::*; use sys::{last_error, retry}; use ffi::CString; @@ -35,7 +35,7 @@ pub mod wtf8; pub fn eof() -> IoError { IoError { - kind: io::EndOfFile, + kind: old_io::EndOfFile, desc: "end of file", detail: None, } @@ -43,7 +43,7 @@ pub fn eof() -> IoError { pub fn timeout(desc: &'static str) -> IoError { IoError { - kind: io::TimedOut, + kind: old_io::TimedOut, desc: desc, detail: None, } @@ -51,7 +51,7 @@ pub fn timeout(desc: &'static str) -> IoError { pub fn short_write(n: uint, desc: &'static str) -> IoError { IoError { - kind: if n == 0 { io::TimedOut } else { io::ShortWrite(n) }, + kind: if n == 0 { old_io::TimedOut } else { old_io::ShortWrite(n) }, desc: desc, detail: None, } @@ -59,7 +59,7 @@ pub fn short_write(n: uint, desc: &'static str) -> IoError { pub fn unimpl() -> IoError { IoError { - kind: io::IoUnavailable, + kind: old_io::IoUnavailable, desc: "operations not yet supported", detail: None, } diff --git a/src/libstd/sys/common/net.rs b/src/libstd/sys/common/net.rs index 4cf891ac498..e42db42dc60 100644 --- a/src/libstd/sys/common/net.rs +++ b/src/libstd/sys/common/net.rs @@ -14,9 +14,9 @@ use self::InAddr::*; use ffi::CString; use ffi; -use io::net::addrinfo; -use io::net::ip::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr}; -use io::{IoResult, IoError}; +use old_io::net::addrinfo; +use old_io::net::ip::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr}; +use old_io::{IoResult, IoError}; use libc::{self, c_char, c_int}; use mem; use num::Int; @@ -28,7 +28,7 @@ use sys::{self, retry, c, sock_t, last_error, last_net_error, last_gai_error, cl use sync::{Arc, Mutex, MutexGuard}; use sys_common::{self, keep_going, short_write, timeout}; use cmp; -use io; +use old_io; // FIXME: move uses of Arc and deadline tracking to std::io @@ -208,7 +208,7 @@ pub fn sockaddr_to_addr(storage: &libc::sockaddr_storage, } _ => { Err(IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "invalid argument", detail: None, }) @@ -458,7 +458,7 @@ pub fn write<T, L, W>(fd: sock_t, // As with read(), first wait for the socket to be ready for // the I/O operation. match await(&[fd], deadline, Writable) { - Err(ref e) if e.kind == io::EndOfFile && written > 0 => { + Err(ref e) if e.kind == old_io::EndOfFile && written > 0 => { assert!(deadline.is_some()); return Err(short_write(written, "short write")) } diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index cb2edf50ebd..ca1a16d8e17 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -86,7 +86,7 @@ use prelude::v1::*; use ffi; -use io::IoResult; +use old_io::IoResult; use libc; use mem; use str; @@ -136,7 +136,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> { #[inline(never)] // if we know this is a function call, we can skip it when // tracing pub fn write(w: &mut Writer) -> IoResult<()> { - use io::IoError; + use old_io::IoError; struct Context<'a> { idx: int, @@ -375,7 +375,7 @@ fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void, Some(string) => try!(demangle(w, string)), None => try!(write!(w, "<unknown>")), } - w.write(&['\n' as u8]) + w.write_all(&['\n' as u8]) } /// Unwind library interface used for backtraces diff --git a/src/libstd/sys/unix/ext.rs b/src/libstd/sys/unix/ext.rs index 3cff5be071c..4a82b2807e7 100644 --- a/src/libstd/sys/unix/ext.rs +++ b/src/libstd/sys/unix/ext.rs @@ -18,7 +18,7 @@ //! ```rust,ignore //! #![feature(globs)] //! -//! use std::io::fs::File; +//! use std::old_io::fs::File; //! use std::os::unix::prelude::*; //! //! fn main() { @@ -37,7 +37,7 @@ use sys_common::{AsInner, IntoInner, FromInner}; use ffi::{OsStr, OsString}; use libc; -use io; +use old_io; /// Raw file descriptors. pub type Fd = libc::c_int; @@ -48,55 +48,55 @@ pub trait AsRawFd { fn as_raw_fd(&self) -> Fd; } -impl AsRawFd for io::fs::File { +impl AsRawFd for old_io::fs::File { fn as_raw_fd(&self) -> Fd { self.as_inner().fd() } } -impl AsRawFd for io::pipe::PipeStream { +impl AsRawFd for old_io::pipe::PipeStream { fn as_raw_fd(&self) -> Fd { self.as_inner().fd() } } -impl AsRawFd for io::net::pipe::UnixStream { +impl AsRawFd for old_io::net::pipe::UnixStream { fn as_raw_fd(&self) -> Fd { self.as_inner().fd() } } -impl AsRawFd for io::net::pipe::UnixListener { +impl AsRawFd for old_io::net::pipe::UnixListener { fn as_raw_fd(&self) -> Fd { self.as_inner().fd() } } -impl AsRawFd for io::net::pipe::UnixAcceptor { +impl AsRawFd for old_io::net::pipe::UnixAcceptor { fn as_raw_fd(&self) -> Fd { self.as_inner().fd() } } -impl AsRawFd for io::net::tcp::TcpStream { +impl AsRawFd for old_io::net::tcp::TcpStream { fn as_raw_fd(&self) -> Fd { self.as_inner().fd() } } -impl AsRawFd for io::net::tcp::TcpListener { +impl AsRawFd for old_io::net::tcp::TcpListener { fn as_raw_fd(&self) -> Fd { self.as_inner().fd() } } -impl AsRawFd for io::net::tcp::TcpAcceptor { +impl AsRawFd for old_io::net::tcp::TcpAcceptor { fn as_raw_fd(&self) -> Fd { self.as_inner().fd() } } -impl AsRawFd for io::net::udp::UdpSocket { +impl AsRawFd for old_io::net::udp::UdpSocket { fn as_raw_fd(&self) -> Fd { self.as_inner().fd() } diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index dd478347f81..66ae018cb36 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -13,10 +13,10 @@ use prelude::v1::*; use ffi::{self, CString}; -use io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode}; -use io::{IoResult, FileStat, SeekStyle}; -use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append}; -use io; +use old_io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode}; +use old_io::{IoResult, FileStat, SeekStyle}; +use old_io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append}; +use old_io; use libc::{self, c_int, c_void}; use mem; use ptr; @@ -304,12 +304,12 @@ fn mkstat(stat: &libc::stat) -> FileStat { FileStat { size: stat.st_size as u64, kind: match (stat.st_mode as libc::mode_t) & libc::S_IFMT { - libc::S_IFREG => io::FileType::RegularFile, - libc::S_IFDIR => io::FileType::Directory, - libc::S_IFIFO => io::FileType::NamedPipe, - libc::S_IFBLK => io::FileType::BlockSpecial, - libc::S_IFLNK => io::FileType::Symlink, - _ => io::FileType::Unknown, + libc::S_IFREG => old_io::FileType::RegularFile, + libc::S_IFDIR => old_io::FileType::Directory, + libc::S_IFIFO => old_io::FileType::NamedPipe, + libc::S_IFBLK => old_io::FileType::BlockSpecial, + libc::S_IFLNK => old_io::FileType::Symlink, + _ => old_io::FileType::Unknown, }, perm: FilePermission::from_bits_truncate(stat.st_mode as u32), created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64), diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs index 5493bc20a87..f2f2e7436bf 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -18,7 +18,7 @@ use prelude::v1::*; use ffi; -use io::{self, IoResult, IoError}; +use old_io::{self, IoResult, IoError}; use libc; use num::{Int, SignedInt}; use num; @@ -94,35 +94,35 @@ pub fn last_gai_error(s: libc::c_int) -> IoError { pub fn decode_error(errno: i32) -> IoError { // FIXME: this should probably be a bit more descriptive... let (kind, desc) = match errno { - libc::EOF => (io::EndOfFile, "end of file"), - libc::ECONNREFUSED => (io::ConnectionRefused, "connection refused"), - libc::ECONNRESET => (io::ConnectionReset, "connection reset"), + libc::EOF => (old_io::EndOfFile, "end of file"), + libc::ECONNREFUSED => (old_io::ConnectionRefused, "connection refused"), + libc::ECONNRESET => (old_io::ConnectionReset, "connection reset"), libc::EPERM | libc::EACCES => - (io::PermissionDenied, "permission denied"), - libc::EPIPE => (io::BrokenPipe, "broken pipe"), - libc::ENOTCONN => (io::NotConnected, "not connected"), - libc::ECONNABORTED => (io::ConnectionAborted, "connection aborted"), - libc::EADDRNOTAVAIL => (io::ConnectionRefused, "address not available"), - libc::EADDRINUSE => (io::ConnectionRefused, "address in use"), - libc::ENOENT => (io::FileNotFound, "no such file or directory"), - libc::EISDIR => (io::InvalidInput, "illegal operation on a directory"), - libc::ENOSYS => (io::IoUnavailable, "function not implemented"), - libc::EINVAL => (io::InvalidInput, "invalid argument"), + (old_io::PermissionDenied, "permission denied"), + libc::EPIPE => (old_io::BrokenPipe, "broken pipe"), + libc::ENOTCONN => (old_io::NotConnected, "not connected"), + libc::ECONNABORTED => (old_io::ConnectionAborted, "connection aborted"), + libc::EADDRNOTAVAIL => (old_io::ConnectionRefused, "address not available"), + libc::EADDRINUSE => (old_io::ConnectionRefused, "address in use"), + libc::ENOENT => (old_io::FileNotFound, "no such file or directory"), + libc::EISDIR => (old_io::InvalidInput, "illegal operation on a directory"), + libc::ENOSYS => (old_io::IoUnavailable, "function not implemented"), + libc::EINVAL => (old_io::InvalidInput, "invalid argument"), libc::ENOTTY => - (io::MismatchedFileTypeForOperation, + (old_io::MismatchedFileTypeForOperation, "file descriptor is not a TTY"), - libc::ETIMEDOUT => (io::TimedOut, "operation timed out"), - libc::ECANCELED => (io::TimedOut, "operation aborted"), + libc::ETIMEDOUT => (old_io::TimedOut, "operation timed out"), + libc::ECANCELED => (old_io::TimedOut, "operation aborted"), libc::consts::os::posix88::EEXIST => - (io::PathAlreadyExists, "path already exists"), + (old_io::PathAlreadyExists, "path already exists"), // These two constants can have the same value on some systems, // but different values on others, so we can't use a match // clause x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => - (io::ResourceUnavailable, "resource temporarily unavailable"), + (old_io::ResourceUnavailable, "resource temporarily unavailable"), - _ => (io::OtherIoError, "unknown error") + _ => (old_io::OtherIoError, "unknown error") }; IoError { kind: kind, desc: desc, detail: None } } diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index 2c25af055ee..5d5cda03f01 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -15,7 +15,7 @@ use prelude::v1::*; use error::{FromError, Error}; use ffi::{self, CString}; use fmt; -use io::{IoError, IoResult}; +use old_io::{IoError, IoResult}; use libc::{self, c_int, c_char, c_void}; use os::TMPBUF_SZ; use os; @@ -198,7 +198,7 @@ pub fn load_self() -> Option<Vec<u8>> { pub fn load_self() -> Option<Vec<u8>> { use std::io; - match io::fs::readlink(&Path::new("/proc/curproc/file")) { + match old_io::fs::readlink(&Path::new("/proc/curproc/file")) { Ok(path) => Some(path.into_vec()), Err(..) => None } @@ -206,9 +206,9 @@ pub fn load_self() -> Option<Vec<u8>> { #[cfg(any(target_os = "linux", target_os = "android"))] pub fn load_self() -> Option<Vec<u8>> { - use std::io; + use old_io; - match io::fs::readlink(&Path::new("/proc/self/exe")) { + match old_io::fs::readlink(&Path::new("/proc/self/exe")) { Ok(path) => Some(path.into_vec()), Err(..) => None } diff --git a/src/libstd/sys/unix/pipe.rs b/src/libstd/sys/unix/pipe.rs index 158a1ce2204..16274a2ab08 100644 --- a/src/libstd/sys/unix/pipe.rs +++ b/src/libstd/sys/unix/pipe.rs @@ -15,7 +15,7 @@ use libc; use mem; use sync::{Arc, Mutex}; use sync::atomic::{AtomicBool, Ordering}; -use io::{self, IoResult, IoError}; +use old_io::{self, IoResult, IoError}; use sys::{self, timer, retry, c, set_nonblocking, wouldblock}; use sys::fs::{fd_t, FileDesc}; @@ -41,7 +41,7 @@ fn addr_to_sockaddr_un(addr: &CString, let len = addr.len(); if len > s.sun_path.len() - 1 { return Err(IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "invalid argument: path must be smaller than SUN_LEN", detail: None, }) diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs index 2b4d168d881..6e12432649f 100644 --- a/src/libstd/sys/unix/process.rs +++ b/src/libstd/sys/unix/process.rs @@ -15,8 +15,8 @@ use collections::HashMap; use collections::hash_map::Hasher; use ffi::CString; use hash::Hash; -use io::process::{ProcessExit, ExitStatus, ExitSignal}; -use io::{self, IoResult, IoError, EndOfFile}; +use old_io::process::{ProcessExit, ExitStatus, ExitSignal}; +use old_io::{self, IoResult, IoError, EndOfFile}; use libc::{self, pid_t, c_void, c_int}; use mem; use os; diff --git a/src/libstd/sys/unix/tcp.rs b/src/libstd/sys/unix/tcp.rs index 59eebd3f28e..c8f9d318482 100644 --- a/src/libstd/sys/unix/tcp.rs +++ b/src/libstd/sys/unix/tcp.rs @@ -10,8 +10,8 @@ use prelude::v1::*; -use io::net::ip; -use io::IoResult; +use old_io::net::ip; +use old_io::IoResult; use libc; use mem; use ptr; diff --git a/src/libstd/sys/unix/timer.rs b/src/libstd/sys/unix/timer.rs index c0c231a9e73..6a4e47f58ce 100644 --- a/src/libstd/sys/unix/timer.rs +++ b/src/libstd/sys/unix/timer.rs @@ -49,7 +49,7 @@ use prelude::v1::*; use self::Req::*; -use io::IoResult; +use old_io::IoResult; use libc; use mem; use os; diff --git a/src/libstd/sys/unix/tty.rs b/src/libstd/sys/unix/tty.rs index d20469f5106..d414f70152d 100644 --- a/src/libstd/sys/unix/tty.rs +++ b/src/libstd/sys/unix/tty.rs @@ -12,7 +12,7 @@ use prelude::v1::*; use sys::fs::FileDesc; use libc::{self, c_int, c_ulong, funcs}; -use io::{self, IoResult, IoError}; +use old_io::{self, IoResult, IoError}; use sys::c; use sys_common; @@ -33,7 +33,7 @@ impl TTY { Ok(TTY { fd: FileDesc::new(fd, true) }) } else { Err(IoError { - kind: io::MismatchedFileTypeForOperation, + kind: old_io::MismatchedFileTypeForOperation, desc: "file descriptor is not a TTY", detail: None, }) @@ -67,7 +67,7 @@ impl TTY { let mut size = winsize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0 }; if c::ioctl(self.fd.fd(), TIOCGWINSZ, &mut size) == -1 { Err(IoError { - kind: io::OtherIoError, + kind: old_io::OtherIoError, desc: "Size of terminal could not be determined", detail: None, }) diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index cba7d81937a..a186465f234 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -25,7 +25,7 @@ use dynamic_lib::DynamicLibrary; use ffi; use core::ops::Index; use intrinsics; -use io::{IoResult, Writer}; +use old_io::{IoResult, Writer}; use libc; use mem; use ops::Drop; @@ -363,10 +363,10 @@ pub fn write(w: &mut Writer) -> IoResult<()> { let bytes = unsafe { ffi::c_str_to_bytes(&ptr) }; match str::from_utf8(bytes) { Ok(s) => try!(demangle(w, s)), - Err(..) => try!(w.write(&bytes[..bytes.len()-1])), + Err(..) => try!(w.write_all(&bytes[..bytes.len()-1])), } } - try!(w.write(&['\n' as u8])); + try!(w.write_all(&['\n' as u8])); } Ok(()) diff --git a/src/libstd/sys/windows/ext.rs b/src/libstd/sys/windows/ext.rs index 2f45cb78cda..a3bbf5c5fe7 100644 --- a/src/libstd/sys/windows/ext.rs +++ b/src/libstd/sys/windows/ext.rs @@ -23,7 +23,7 @@ use sys_common::{AsInner, FromInner}; use ffi::{OsStr, OsString}; use libc; -use io; +use old_io; /// Raw HANDLEs. pub type Handle = libc::HANDLE; @@ -37,31 +37,31 @@ pub trait AsRawHandle { fn as_raw_handle(&self) -> Handle; } -impl AsRawHandle for io::fs::File { +impl AsRawHandle for old_io::fs::File { fn as_raw_handle(&self) -> Handle { self.as_inner().handle() } } -impl AsRawHandle for io::pipe::PipeStream { +impl AsRawHandle for old_io::pipe::PipeStream { fn as_raw_handle(&self) -> Handle { self.as_inner().handle() } } -impl AsRawHandle for io::net::pipe::UnixStream { +impl AsRawHandle for old_io::net::pipe::UnixStream { fn as_raw_handle(&self) -> Handle { self.as_inner().handle() } } -impl AsRawHandle for io::net::pipe::UnixListener { +impl AsRawHandle for old_io::net::pipe::UnixListener { fn as_raw_handle(&self) -> Handle { self.as_inner().handle() } } -impl AsRawHandle for io::net::pipe::UnixAcceptor { +impl AsRawHandle for old_io::net::pipe::UnixAcceptor { fn as_raw_handle(&self) -> Handle { self.as_inner().handle() } @@ -72,25 +72,25 @@ pub trait AsRawSocket { fn as_raw_socket(&self) -> Socket; } -impl AsRawSocket for io::net::tcp::TcpStream { +impl AsRawSocket for old_io::net::tcp::TcpStream { fn as_raw_socket(&self) -> Socket { self.as_inner().fd() } } -impl AsRawSocket for io::net::tcp::TcpListener { +impl AsRawSocket for old_io::net::tcp::TcpListener { fn as_raw_socket(&self) -> Socket { self.as_inner().socket() } } -impl AsRawSocket for io::net::tcp::TcpAcceptor { +impl AsRawSocket for old_io::net::tcp::TcpAcceptor { fn as_raw_socket(&self) -> Socket { self.as_inner().socket() } } -impl AsRawSocket for io::net::udp::UdpSocket { +impl AsRawSocket for old_io::net::udp::UdpSocket { fn as_raw_socket(&self) -> Socket { self.as_inner().fd() } diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index cb8ef7eb66b..d9d1a374651 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -18,16 +18,16 @@ use sys::os::fill_utf16_buf_and_decode; use path; use ptr; use str; -use io; +use old_io; use prelude::v1::*; use sys; use sys::os; use sys_common::{keep_going, eof, mkerr_libc}; -use io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode}; -use io::{IoResult, IoError, FileStat, SeekStyle}; -use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append}; +use old_io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode}; +use old_io::{IoResult, IoError, FileStat, SeekStyle}; +use old_io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append}; pub type fd_t = libc::c_int; @@ -130,7 +130,7 @@ impl FileDesc { return ret; } - pub fn fstat(&self) -> IoResult<io::FileStat> { + pub fn fstat(&self) -> IoResult<old_io::FileStat> { let mut stat: libc::stat = unsafe { mem::zeroed() }; match unsafe { libc::fstat(self.fd(), &mut stat) } { 0 => Ok(mkstat(&stat)), @@ -268,7 +268,7 @@ pub fn readdir(p: &Path) -> IoResult<Vec<Path>> { Err(..) => { assert!(libc::FindClose(find_handle) != 0); return Err(IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "path was not valid UTF-16", detail: Some(format!("path was not valid UTF-16: {:?}", filename)), }) @@ -303,14 +303,14 @@ pub fn unlink(p: &Path) -> IoResult<()> { // however, it cannot. To keep the two platforms in line with // respect to their behavior, catch this case on windows, attempt to // change it to read-write, and then remove the file. - if e.kind == io::PermissionDenied { + if e.kind == old_io::PermissionDenied { let stat = match stat(p) { Ok(stat) => stat, Err(..) => return Err(e), }; - if stat.perm.intersects(io::USER_WRITE) { return Err(e) } + if stat.perm.intersects(old_io::USER_WRITE) { return Err(e) } - match chmod(p, (stat.perm | io::USER_WRITE).bits() as uint) { + match chmod(p, (stat.perm | old_io::USER_WRITE).bits() as uint) { Ok(()) => do_unlink(&p_utf16), Err(..) => { // Try to put it back as we found it @@ -406,12 +406,12 @@ fn mkstat(stat: &libc::stat) -> FileStat { FileStat { size: stat.st_size as u64, kind: match (stat.st_mode as libc::c_int) & libc::S_IFMT { - libc::S_IFREG => io::FileType::RegularFile, - libc::S_IFDIR => io::FileType::Directory, - libc::S_IFIFO => io::FileType::NamedPipe, - libc::S_IFBLK => io::FileType::BlockSpecial, - libc::S_IFLNK => io::FileType::Symlink, - _ => io::FileType::Unknown, + libc::S_IFREG => old_io::FileType::RegularFile, + libc::S_IFDIR => old_io::FileType::Directory, + libc::S_IFIFO => old_io::FileType::NamedPipe, + libc::S_IFBLK => old_io::FileType::BlockSpecial, + libc::S_IFLNK => old_io::FileType::Symlink, + _ => old_io::FileType::Unknown, }, perm: FilePermission::from_bits_truncate(stat.st_mode as u32), created: stat.st_ctime as u64, diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index 876159623ac..e8b65c9b64e 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -22,7 +22,7 @@ use prelude::v1::*; use num; use mem; -use io::{self, IoResult, IoError}; +use old_io::{self, IoResult, IoError}; use sync::{Once, ONCE_INIT}; macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => ( @@ -99,43 +99,43 @@ pub fn last_gai_error(_errno: i32) -> IoError { /// Convert an `errno` value into a high-level error variant and description. pub fn decode_error(errno: i32) -> IoError { let (kind, desc) = match errno { - libc::EOF => (io::EndOfFile, "end of file"), - libc::ERROR_NO_DATA => (io::BrokenPipe, "the pipe is being closed"), - libc::ERROR_FILE_NOT_FOUND => (io::FileNotFound, "file not found"), - libc::ERROR_INVALID_NAME => (io::InvalidInput, "invalid file name"), - libc::WSAECONNREFUSED => (io::ConnectionRefused, "connection refused"), - libc::WSAECONNRESET => (io::ConnectionReset, "connection reset"), + libc::EOF => (old_io::EndOfFile, "end of file"), + libc::ERROR_NO_DATA => (old_io::BrokenPipe, "the pipe is being closed"), + libc::ERROR_FILE_NOT_FOUND => (old_io::FileNotFound, "file not found"), + libc::ERROR_INVALID_NAME => (old_io::InvalidInput, "invalid file name"), + libc::WSAECONNREFUSED => (old_io::ConnectionRefused, "connection refused"), + libc::WSAECONNRESET => (old_io::ConnectionReset, "connection reset"), libc::ERROR_ACCESS_DENIED | libc::WSAEACCES => - (io::PermissionDenied, "permission denied"), + (old_io::PermissionDenied, "permission denied"), libc::WSAEWOULDBLOCK => { - (io::ResourceUnavailable, "resource temporarily unavailable") + (old_io::ResourceUnavailable, "resource temporarily unavailable") } - libc::WSAENOTCONN => (io::NotConnected, "not connected"), - libc::WSAECONNABORTED => (io::ConnectionAborted, "connection aborted"), - libc::WSAEADDRNOTAVAIL => (io::ConnectionRefused, "address not available"), - libc::WSAEADDRINUSE => (io::ConnectionRefused, "address in use"), - libc::ERROR_BROKEN_PIPE => (io::EndOfFile, "the pipe has ended"), + libc::WSAENOTCONN => (old_io::NotConnected, "not connected"), + libc::WSAECONNABORTED => (old_io::ConnectionAborted, "connection aborted"), + libc::WSAEADDRNOTAVAIL => (old_io::ConnectionRefused, "address not available"), + libc::WSAEADDRINUSE => (old_io::ConnectionRefused, "address in use"), + libc::ERROR_BROKEN_PIPE => (old_io::EndOfFile, "the pipe has ended"), libc::ERROR_OPERATION_ABORTED => - (io::TimedOut, "operation timed out"), - libc::WSAEINVAL => (io::InvalidInput, "invalid argument"), + (old_io::TimedOut, "operation timed out"), + libc::WSAEINVAL => (old_io::InvalidInput, "invalid argument"), libc::ERROR_CALL_NOT_IMPLEMENTED => - (io::IoUnavailable, "function not implemented"), + (old_io::IoUnavailable, "function not implemented"), libc::ERROR_INVALID_HANDLE => - (io::MismatchedFileTypeForOperation, + (old_io::MismatchedFileTypeForOperation, "invalid handle provided to function"), libc::ERROR_NOTHING_TO_TERMINATE => - (io::InvalidInput, "no process to kill"), + (old_io::InvalidInput, "no process to kill"), libc::ERROR_ALREADY_EXISTS => - (io::PathAlreadyExists, "path already exists"), + (old_io::PathAlreadyExists, "path already exists"), // libuv maps this error code to EISDIR. we do too. if it is found // to be incorrect, we can add in some more machinery to only // return this message when ERROR_INVALID_FUNCTION after certain // Windows calls. - libc::ERROR_INVALID_FUNCTION => (io::InvalidInput, + libc::ERROR_INVALID_FUNCTION => (old_io::InvalidInput, "illegal operation on a directory"), - _ => (io::OtherIoError, "unknown error") + _ => (old_io::OtherIoError, "unknown error") }; IoError { kind: kind, desc: desc, detail: None } } @@ -185,7 +185,7 @@ pub fn init_net() { pub fn unimpl() -> IoError { IoError { - kind: io::IoUnavailable, + kind: old_io::IoUnavailable, desc: "operation is not implemented", detail: None, } @@ -199,7 +199,7 @@ pub fn to_utf16(s: Option<&str>) -> IoResult<Vec<u16>> { s }), None => Err(IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "valid unicode input required", detail: None }) diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index 36dc9b2afe4..a82259ad5ec 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -16,7 +16,7 @@ use prelude::v1::*; use fmt; -use io::{IoResult, IoError}; +use old_io::{IoResult, IoError}; use iter::repeat; use libc::{c_int, c_void}; use libc; @@ -162,7 +162,7 @@ pub fn fill_utf16_buf_and_decode<F>(mut f: F) -> Option<String> where pub fn getcwd() -> IoResult<Path> { use libc::DWORD; use libc::GetCurrentDirectoryW; - use io::OtherIoError; + use old_io::OtherIoError; let mut buf = [0 as u16; BUF_BYTES]; unsafe { diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs index 9996909f2f5..dc9fb3253ff 100644 --- a/src/libstd/sys/windows/pipe.rs +++ b/src/libstd/sys/windows/pipe.rs @@ -88,7 +88,7 @@ use prelude::v1::*; use libc; use ffi::CString; -use io::{self, IoError, IoResult}; +use old_io::{self, IoError, IoResult}; use mem; use ptr; use str; @@ -202,7 +202,7 @@ pub fn await(handle: libc::HANDLE, deadline: u64, fn epipe() -> IoError { IoError { - kind: io::EndOfFile, + kind: old_io::EndOfFile, desc: "the pipe has ended", detail: None, } @@ -485,7 +485,7 @@ impl UnixStream { let amt = offset + bytes_written as uint; return if amt > 0 { Err(IoError { - kind: io::ShortWrite(amt), + kind: old_io::ShortWrite(amt), desc: "short write during write", detail: None, }) diff --git a/src/libstd/sys/windows/process.rs b/src/libstd/sys/windows/process.rs index 1b837385d1e..43f9e805db1 100644 --- a/src/libstd/sys/windows/process.rs +++ b/src/libstd/sys/windows/process.rs @@ -14,10 +14,10 @@ use collections; use ffi::CString; use hash::Hash; use collections::hash_map::Hasher; -use io::fs::PathExtensions; -use io::process::{ProcessExit, ExitStatus, ExitSignal}; -use io::{IoResult, IoError}; -use io; +use old_io::fs::PathExtensions; +use old_io::process::{ProcessExit, ExitStatus, ExitSignal}; +use old_io::{IoResult, IoError}; +use old_io; use libc::{pid_t, c_void, c_int}; use libc; use mem; @@ -84,7 +84,7 @@ impl Process { Err(super::last_error()) } else if status != libc::STILL_ACTIVE { Err(IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "no process to kill", detail: None, }) @@ -97,7 +97,7 @@ impl Process { super::mkerr_winbool(ret) } _ => Err(IoError { - kind: io::IoUnavailable, + kind: old_io::IoUnavailable, desc: "unsupported signal on windows", detail: None, }) @@ -133,7 +133,7 @@ impl Process { if cfg.gid().is_some() || cfg.uid().is_some() { return Err(IoError { - kind: io::IoUnavailable, + kind: old_io::IoUnavailable, desc: "unsupported gid/uid requested on windows", detail: None, }) diff --git a/src/libstd/sys/windows/tcp.rs b/src/libstd/sys/windows/tcp.rs index 77139b52efa..b7e27fb37f0 100644 --- a/src/libstd/sys/windows/tcp.rs +++ b/src/libstd/sys/windows/tcp.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use io::net::ip; -use io::IoResult; +use old_io::net::ip; +use old_io::IoResult; use libc; use mem; use ptr; diff --git a/src/libstd/sys/windows/timer.rs b/src/libstd/sys/windows/timer.rs index 12b4e56bf52..34f3c418c55 100644 --- a/src/libstd/sys/windows/timer.rs +++ b/src/libstd/sys/windows/timer.rs @@ -26,7 +26,7 @@ use prelude::v1::*; use libc; use ptr; -use io::IoResult; +use old_io::IoResult; use sync::mpsc::{channel, Sender, Receiver, TryRecvError}; use sys::c; use sys::fs::FileDesc; diff --git a/src/libstd/sys/windows/tty.rs b/src/libstd/sys/windows/tty.rs index f9e1f0d3ed0..6ecabfa9853 100644 --- a/src/libstd/sys/windows/tty.rs +++ b/src/libstd/sys/windows/tty.rs @@ -27,7 +27,7 @@ use prelude::v1::*; -use io::{self, IoError, IoResult, MemReader}; +use old_io::{self, IoError, IoResult, MemReader}; use iter::repeat; use libc::types::os::arch::extra::LPCVOID; use libc::{c_int, HANDLE, LPDWORD, DWORD, LPVOID}; @@ -44,7 +44,7 @@ use super::c::{GetConsoleScreenBufferInfo}; fn invalid_encoding() -> IoError { IoError { - kind: io::InvalidInput, + kind: old_io::InvalidInput, desc: "text was not valid unicode", detail: None, } @@ -83,7 +83,7 @@ impl TTY { }) } else { Err(IoError { - kind: io::MismatchedFileTypeForOperation, + kind: old_io::MismatchedFileTypeForOperation, desc: "invalid handle provided to function", detail: None, }) diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index 09f50059936..c19ec8ea25c 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -158,7 +158,7 @@ use sync::{Mutex, Condvar, Arc}; use str::Str; use string::String; use rt::{self, unwind}; -use io::{Writer, stdio}; +use old_io::{Writer, stdio}; use thunk::Thunk; use sys::thread as imp; @@ -516,7 +516,7 @@ mod test { use sync::mpsc::{channel, Sender}; use boxed::BoxAny; use result; - use std::io::{ChanReader, ChanWriter}; + use std::old_io::{ChanReader, ChanWriter}; use super::{Thread, Builder}; use thunk::Thunk; diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index 8a114e4b748..96476cabac5 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -25,7 +25,7 @@ use visit::{self, Visitor}; use arena::TypedArena; use std::cell::RefCell; use std::fmt; -use std::io::IoResult; +use std::old_io::IoResult; use std::iter::{self, repeat}; use std::mem; use std::slice; diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index a5e10f42750..e0d4f69a34c 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -364,9 +364,10 @@ impl CodeMap { }; // Append '\n' in case it's not already there. - // This is a workaround to prevent CodeMap.lookup_filemap_idx from accidentally - // overflowing into the next filemap in case the last byte of span is also the last - // byte of filemap, which leads to incorrect results from CodeMap.span_to_*. + // This is a workaround to prevent CodeMap.lookup_filemap_idx from + // accidentally overflowing into the next filemap in case the last byte + // of span is also the last byte of filemap, which leads to incorrect + // results from CodeMap.span_to_*. if src.len() > 0 && !src.ends_with("\n") { src.push('\n'); } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 01bb0e7a51c..f3e66897316 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -19,7 +19,7 @@ use diagnostics; use std::cell::{RefCell, Cell}; use std::fmt; -use std::io; +use std::old_io; use std::iter::range; use std::string::String; use term::WriterWrapper; @@ -272,7 +272,7 @@ impl Level { fn print_maybe_styled(w: &mut EmitterWriter, msg: &str, - color: term::attr::Attr) -> io::IoResult<()> { + color: term::attr::Attr) -> old_io::IoResult<()> { match w.dst { Terminal(ref mut t) => { try!(t.attr(color)); @@ -306,7 +306,7 @@ fn print_maybe_styled(w: &mut EmitterWriter, } fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level, - msg: &str, code: Option<&str>) -> io::IoResult<()> { + msg: &str, code: Option<&str>) -> old_io::IoResult<()> { if !topic.is_empty() { try!(write!(&mut dst.dst, "{} ", topic)); } @@ -342,7 +342,7 @@ enum Destination { impl EmitterWriter { pub fn stderr(color_config: ColorConfig, registry: Option<diagnostics::registry::Registry>) -> EmitterWriter { - let stderr = io::stderr(); + let stderr = old_io::stderr(); let use_color = match color_config { Always => true, @@ -368,10 +368,10 @@ impl EmitterWriter { } impl Writer for Destination { - fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> { + fn write_all(&mut self, bytes: &[u8]) -> old_io::IoResult<()> { match *self { - Terminal(ref mut t) => t.write(bytes), - Raw(ref mut w) => w.write(bytes), + Terminal(ref mut t) => t.write_all(bytes), + Raw(ref mut w) => w.write_all(bytes), } } } @@ -404,7 +404,7 @@ impl Emitter for EmitterWriter { } fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, - msg: &str, code: Option<&str>, lvl: Level, custom: bool) -> io::IoResult<()> { + msg: &str, code: Option<&str>, lvl: Level, custom: bool) -> old_io::IoResult<()> { let sp = rsp.span(); // We cannot check equality directly with COMMAND_LINE_SP @@ -452,7 +452,7 @@ fn highlight_lines(err: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span, lvl: Level, - lines: codemap::FileLines) -> io::IoResult<()> { + lines: codemap::FileLines) -> old_io::IoResult<()> { let fm = &*lines.file; let mut elided = false; @@ -535,7 +535,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, sp: Span, lvl: Level, lines: codemap::FileLines) - -> io::IoResult<()> { + -> old_io::IoResult<()> { let fm = &*lines.file; let lines = &lines.lines[]; @@ -576,7 +576,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, fn print_macro_backtrace(w: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span) - -> io::IoResult<()> { + -> old_io::IoResult<()> { let cs = try!(cm.with_expn_info(sp.expn_id, |expn_info| match expn_info { Some(ei) => { let ss = ei.callee.span.map_or(String::new(), |span| cm.span_to_string(span)); diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index a74adbf4085..fbc591834d0 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -20,7 +20,7 @@ use print::pprust; use ptr::P; use util::small_vector::SmallVector; -use std::io::File; +use std::old_io::File; use std::rc::Rc; // These macros all relate to the file system; they either return @@ -135,7 +135,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let bytes = match File::open(&file).read_to_end() { Err(e) => { cx.span_err(sp, - &format!("couldn't read {:?}: {}", + &format!("couldn't read {}: {}", file.display(), e)[]); return DummyResult::expr(sp); @@ -146,7 +146,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Ok(src) => { // Add this input file to the code map to make it available as // dependency information - let filename = format!("{:?}", file.display()); + let filename = format!("{}", file.display()); let interned = token::intern_and_get_ident(&src[]); cx.codemap().new_filemap(filename, src); @@ -154,7 +154,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) } Err(_) => { cx.span_err(sp, - &format!("{:?} wasn't a utf-8 file", + &format!("{} wasn't a utf-8 file", file.display())[]); return DummyResult::expr(sp); } @@ -171,7 +171,7 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) match File::open(&file).read_to_end() { Err(e) => { cx.span_err(sp, - &format!("couldn't read {:?}: {}", file.display(), e)[]); + &format!("couldn't read {}: {}", file.display(), e)[]); return DummyResult::expr(sp); } Ok(bytes) => { diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 9f8427cc8ae..bf822599a88 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -1430,7 +1430,7 @@ pub fn noop_fold_stmt<T: Folder>(Spanned {node, span}: Stmt, folder: &mut T) #[cfg(test)] mod test { - use std::io; + use std::old_io; use ast; use util::parser_testing::{string_to_crate, matches_codepattern}; use parse::token; @@ -1440,7 +1440,7 @@ mod test { // this version doesn't care about getting comments or docstrings in. fn fake_print_crate(s: &mut pprust::State, - krate: &ast::Crate) -> io::IoResult<()> { + krate: &ast::Crate) -> old_io::IoResult<()> { s.print_mod(&krate.module, krate.attrs.as_slice()) } diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index c58136b30aa..926385ccd11 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -19,7 +19,7 @@ use parse::lexer::is_block_doc_comment; use parse::lexer; use print::pprust; -use std::io; +use std::old_io; use std::str; use std::string::String; use std::usize; @@ -337,7 +337,7 @@ pub struct Literal { // probably not a good thing. pub fn gather_comments_and_literals(span_diagnostic: &diagnostic::SpanHandler, path: String, - srdr: &mut io::Reader) + srdr: &mut old_io::Reader) -> (Vec<Comment>, Vec<Literal>) { let src = srdr.read_to_end().unwrap(); let src = String::from_utf8(src).unwrap(); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 3b9dcf53009..99be1b11b11 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -1482,11 +1482,11 @@ mod test { use diagnostic; use parse::token; use parse::token::{str_to_ident}; - use std::io::util; + use std::old_io::util; fn mk_sh() -> diagnostic::SpanHandler { let emitter = diagnostic::EmitterWriter::new(box util::NullWriter, None); - let handler = diagnostic::mk_handler(box emitter); + let handler = diagnostic::mk_handler(true, box emitter); diagnostic::mk_span_handler(handler, CodeMap::new()) } diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 326aa1f3fc9..4bd476885a0 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -18,7 +18,7 @@ use parse::parser::Parser; use ptr::P; use std::cell::{Cell, RefCell}; -use std::io::File; +use std::old_io::File; use std::rc::Rc; use std::num::Int; use std::str; diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index eab24574bb1..fbea265597c 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -80,7 +80,7 @@ use ptr::P; use owned_slice::OwnedSlice; use std::collections::HashSet; -use std::io::fs::PathExtensions; +use std::old_io::fs::PathExtensions; use std::iter; use std::mem; use std::num::Float; diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 0b1bd282941..7fb2f9a80cc 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -59,7 +59,7 @@ //! line (which it can't) and so naturally place the content on its own line to //! avoid combining it with other lines and making matters even worse. -use std::io; +use std::old_io; use std::string; use std::iter::repeat; @@ -161,7 +161,7 @@ pub struct PrintStackElem { static SIZE_INFINITY: isize = 0xffff; -pub fn mk_printer(out: Box<io::Writer+'static>, linewidth: usize) -> Printer { +pub fn mk_printer(out: Box<old_io::Writer+'static>, linewidth: usize) -> Printer { // Yes 3, it makes the ring buffers big enough to never // fall behind. let n: usize = 3 * linewidth; @@ -266,7 +266,7 @@ pub fn mk_printer(out: Box<io::Writer+'static>, linewidth: usize) -> Printer { /// the method called 'pretty_print', and the 'PRINT' process is the method /// called 'print'. pub struct Printer { - pub out: Box<io::Writer+'static>, + pub out: Box<old_io::Writer+'static>, buf_len: usize, /// Width of lines we're constrained to margin: isize, @@ -311,7 +311,7 @@ impl Printer { pub fn replace_last_token(&mut self, t: Token) { self.token[self.right] = t; } - pub fn pretty_print(&mut self, token: Token) -> io::IoResult<()> { + pub fn pretty_print(&mut self, token: Token) -> old_io::IoResult<()> { debug!("pp ~[{},{}]", self.left, self.right); match token { Token::Eof => { @@ -385,7 +385,7 @@ impl Printer { } } } - pub fn check_stream(&mut self) -> io::IoResult<()> { + pub fn check_stream(&mut self) -> old_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 { @@ -445,7 +445,7 @@ impl Printer { self.right %= self.buf_len; assert!((self.right != self.left)); } - pub fn advance_left(&mut self) -> io::IoResult<()> { + pub fn advance_left(&mut self) -> old_io::IoResult<()> { debug!("advance_left ~[{},{}], sizeof({})={}", self.left, self.right, self.left, self.size[self.left]); @@ -506,7 +506,7 @@ impl Printer { } } } - pub fn print_newline(&mut self, amount: isize) -> io::IoResult<()> { + pub fn print_newline(&mut self, amount: isize) -> old_io::IoResult<()> { debug!("NEWLINE {}", amount); let ret = write!(self.out, "\n"); self.pending_indentation = 0; @@ -529,14 +529,14 @@ impl Printer { } } } - pub fn print_str(&mut self, s: &str) -> io::IoResult<()> { + pub fn print_str(&mut self, s: &str) -> old_io::IoResult<()> { while self.pending_indentation > 0 { try!(write!(self.out, " ")); self.pending_indentation -= 1; } write!(self.out, "{}", s) } - pub fn print(&mut self, token: Token, l: isize) -> io::IoResult<()> { + pub fn print(&mut self, token: Token, l: isize) -> old_io::IoResult<()> { debug!("print {} {} (remaining line space={})", tok_str(&token), l, self.space); debug!("{}", buf_str(&self.token[], @@ -620,61 +620,61 @@ impl Printer { // Convenience functions to talk to the printer. // // "raw box" -pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> io::IoResult<()> { +pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> old_io::IoResult<()> { p.pretty_print(Token::Begin(BeginToken { offset: indent as isize, breaks: b })) } -pub fn ibox(p: &mut Printer, indent: usize) -> io::IoResult<()> { +pub fn ibox(p: &mut Printer, indent: usize) -> old_io::IoResult<()> { rbox(p, indent, Breaks::Inconsistent) } -pub fn cbox(p: &mut Printer, indent: usize) -> io::IoResult<()> { +pub fn cbox(p: &mut Printer, indent: usize) -> old_io::IoResult<()> { rbox(p, indent, Breaks::Consistent) } -pub fn break_offset(p: &mut Printer, n: usize, off: isize) -> io::IoResult<()> { +pub fn break_offset(p: &mut Printer, n: usize, off: isize) -> old_io::IoResult<()> { p.pretty_print(Token::Break(BreakToken { offset: off, blank_space: n as isize })) } -pub fn end(p: &mut Printer) -> io::IoResult<()> { +pub fn end(p: &mut Printer) -> old_io::IoResult<()> { p.pretty_print(Token::End) } -pub fn eof(p: &mut Printer) -> io::IoResult<()> { +pub fn eof(p: &mut Printer) -> old_io::IoResult<()> { p.pretty_print(Token::Eof) } -pub fn word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { +pub fn word(p: &mut Printer, wrd: &str) -> old_io::IoResult<()> { p.pretty_print(Token::String(/* bad */ wrd.to_string(), wrd.len() as isize)) } -pub fn huge_word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { +pub fn huge_word(p: &mut Printer, wrd: &str) -> old_io::IoResult<()> { p.pretty_print(Token::String(/* bad */ wrd.to_string(), SIZE_INFINITY)) } -pub fn zero_word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { +pub fn zero_word(p: &mut Printer, wrd: &str) -> old_io::IoResult<()> { p.pretty_print(Token::String(/* bad */ wrd.to_string(), 0)) } -pub fn spaces(p: &mut Printer, n: usize) -> io::IoResult<()> { +pub fn spaces(p: &mut Printer, n: usize) -> old_io::IoResult<()> { break_offset(p, n, 0) } -pub fn zerobreak(p: &mut Printer) -> io::IoResult<()> { +pub fn zerobreak(p: &mut Printer) -> old_io::IoResult<()> { spaces(p, 0us) } -pub fn space(p: &mut Printer) -> io::IoResult<()> { +pub fn space(p: &mut Printer) -> old_io::IoResult<()> { spaces(p, 1us) } -pub fn hardbreak(p: &mut Printer) -> io::IoResult<()> { +pub fn hardbreak(p: &mut Printer) -> old_io::IoResult<()> { spaces(p, SIZE_INFINITY as usize) } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index d06ac50920e..ae3c4addf38 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -30,7 +30,7 @@ use print::pp::Breaks::{Consistent, Inconsistent}; use ptr::P; use std::{ascii, mem}; -use std::io::{self, IoResult}; +use std::old_io::{self, IoResult}; use std::iter; pub enum AnnNode<'a> { @@ -69,12 +69,12 @@ pub struct State<'a> { encode_idents_with_hygiene: bool, } -pub fn rust_printer(writer: Box<io::Writer+'static>) -> State<'static> { +pub fn rust_printer(writer: Box<old_io::Writer+'static>) -> State<'static> { static NO_ANN: NoAnn = NoAnn; rust_printer_annotated(writer, &NO_ANN) } -pub fn rust_printer_annotated<'a>(writer: Box<io::Writer+'static>, +pub fn rust_printer_annotated<'a>(writer: Box<old_io::Writer+'static>, ann: &'a PpAnn) -> State<'a> { State { s: pp::mk_printer(writer, default_columns), @@ -104,8 +104,8 @@ pub fn print_crate<'a>(cm: &'a CodeMap, span_diagnostic: &diagnostic::SpanHandler, krate: &ast::Crate, filename: String, - input: &mut io::Reader, - out: Box<io::Writer+'static>, + input: &mut old_io::Reader, + out: Box<old_io::Writer+'static>, ann: &'a PpAnn, is_expanded: bool) -> IoResult<()> { let mut s = State::new_from_input(cm, @@ -124,8 +124,8 @@ impl<'a> State<'a> { pub fn new_from_input(cm: &'a CodeMap, span_diagnostic: &diagnostic::SpanHandler, filename: String, - input: &mut io::Reader, - out: Box<io::Writer+'static>, + input: &mut old_io::Reader, + out: Box<old_io::Writer+'static>, ann: &'a PpAnn, is_expanded: bool) -> State<'a> { let (cmnts, lits) = comments::gather_comments_and_literals( @@ -145,7 +145,7 @@ impl<'a> State<'a> { } pub fn new(cm: &'a CodeMap, - out: Box<io::Writer+'static>, + out: Box<old_io::Writer+'static>, ann: &'a PpAnn, comments: Option<Vec<comments::Comment>>, literals: Option<Vec<comments::Literal>>) -> State<'a> { @@ -173,7 +173,7 @@ pub fn to_string<F>(f: F) -> String where f(&mut s).unwrap(); eof(&mut s.s).unwrap(); let wr = unsafe { - // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer` + // FIXME(pcwalton): A nasty function to extract the string from an `old_io::Writer` // that we "know" to be a `Vec<u8>` that works around the lack of checked // downcasts. let obj: &TraitObject = mem::transmute(&s.s.out); @@ -421,7 +421,7 @@ thing_to_string_impls! { to_string } pub mod with_hygiene { use abi; use ast; - use std::io::IoResult; + use std::old_io::IoResult; use super::indent_unit; // This function is the trick that all the rest of the routines diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index 213b7ba11b7..aa3af76d46c 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -70,7 +70,7 @@ pub use terminfo::TerminfoTerminal; #[cfg(windows)] pub use win::WinConsole; -use std::io::IoResult; +use std::old_io::IoResult; pub mod terminfo; @@ -85,8 +85,8 @@ pub struct WriterWrapper { impl Writer for WriterWrapper { #[inline] - fn write(&mut self, buf: &[u8]) -> IoResult<()> { - self.wrapped.write(buf) + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { + self.wrapped.write_all(buf) } #[inline] @@ -100,7 +100,7 @@ impl Writer for WriterWrapper { /// opened. pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> { TerminfoTerminal::new(WriterWrapper { - wrapped: box std::io::stdout() as Box<Writer + Send>, + wrapped: box std::old_io::stdout() as Box<Writer + Send>, }) } @@ -109,14 +109,14 @@ pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> { /// opened. pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> { let ti = TerminfoTerminal::new(WriterWrapper { - wrapped: box std::io::stdout() as Box<Writer + Send>, + wrapped: box std::old_io::stdout() as Box<Writer + Send>, }); match ti { Some(t) => Some(t), None => { WinConsole::new(WriterWrapper { - wrapped: box std::io::stdout() as Box<Writer + Send>, + wrapped: box std::old_io::stdout() as Box<Writer + Send>, }) } } @@ -127,7 +127,7 @@ pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> { /// opened. pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send>> { TerminfoTerminal::new(WriterWrapper { - wrapped: box std::io::stderr() as Box<Writer + Send>, + wrapped: box std::old_io::stderr() as Box<Writer + Send>, }) } @@ -136,14 +136,14 @@ pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send>> { /// opened. pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send>> { let ti = TerminfoTerminal::new(WriterWrapper { - wrapped: box std::io::stderr() as Box<Writer + Send>, + wrapped: box std::old_io::stderr() as Box<Writer + Send>, }); match ti { Some(t) => Some(t), None => { WinConsole::new(WriterWrapper { - wrapped: box std::io::stderr() as Box<Writer + Send>, + wrapped: box std::old_io::stderr() as Box<Writer + Send>, }) } } diff --git a/src/libterm/terminfo/mod.rs b/src/libterm/terminfo/mod.rs index 2ef0bca3785..a8df045e203 100644 --- a/src/libterm/terminfo/mod.rs +++ b/src/libterm/terminfo/mod.rs @@ -11,7 +11,7 @@ //! Terminfo database interface. use std::collections::HashMap; -use std::io::IoResult; +use std::old_io::IoResult; use std::os; use attr; @@ -83,7 +83,7 @@ impl<T: Writer+Send> Terminal<T> for TerminfoTerminal<T> { .as_slice(), &[Number(color as int)], &mut Variables::new()); if s.is_ok() { - try!(self.out.write(s.unwrap().as_slice())); + try!(self.out.write_all(s.unwrap().as_slice())); return Ok(true) } } @@ -100,7 +100,7 @@ impl<T: Writer+Send> Terminal<T> for TerminfoTerminal<T> { .as_slice(), &[Number(color as int)], &mut Variables::new()); if s.is_ok() { - try!(self.out.write(s.unwrap().as_slice())); + try!(self.out.write_all(s.unwrap().as_slice())); return Ok(true) } } @@ -119,7 +119,7 @@ impl<T: Writer+Send> Terminal<T> for TerminfoTerminal<T> { &[], &mut Variables::new()); if s.is_ok() { - try!(self.out.write(s.unwrap().as_slice())); + try!(self.out.write_all(s.unwrap().as_slice())); return Ok(true) } } @@ -154,7 +154,7 @@ impl<T: Writer+Send> Terminal<T> for TerminfoTerminal<T> { expand(op.as_slice(), &[], &mut Variables::new()) }); if s.is_ok() { - return self.out.write(s.unwrap().as_slice()) + return self.out.write_all(s.unwrap().as_slice()) } Ok(()) } @@ -221,8 +221,8 @@ impl<T: Writer+Send> TerminfoTerminal<T> { impl<T: Writer> Writer for TerminfoTerminal<T> { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { - self.out.write(buf) + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { + self.out.write_all(buf) } fn flush(&mut self) -> IoResult<()> { diff --git a/src/libterm/terminfo/parser/compiled.rs b/src/libterm/terminfo/parser/compiled.rs index eb300beae9f..f82c3ea2e7b 100644 --- a/src/libterm/terminfo/parser/compiled.rs +++ b/src/libterm/terminfo/parser/compiled.rs @@ -13,7 +13,7 @@ //! ncurses-compatible compiled terminfo format parsing (term(5)) use std::collections::HashMap; -use std::io; +use std::old_io; use super::super::TermInfo; // These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable. @@ -158,7 +158,7 @@ pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tb "box1"]; /// Parse a compiled terminfo entry, using long capability names if `longnames` is true -pub fn parse(file: &mut io::Reader, longnames: bool) +pub fn parse(file: &mut old_io::Reader, longnames: bool) -> Result<Box<TermInfo>, String> { macro_rules! try { ($e:expr) => ( match $e { @@ -340,6 +340,6 @@ mod test { #[ignore(reason = "no ncurses on buildbots, needs a bundled terminfo file to test against")] fn test_parse() { // FIXME #6870: Distribute a compiled file in src/tests and test there - // parse(io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false); + // parse(old_io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false); } } diff --git a/src/libterm/terminfo/searcher.rs b/src/libterm/terminfo/searcher.rs index 1fca3c62f78..1e84c0462d6 100644 --- a/src/libterm/terminfo/searcher.rs +++ b/src/libterm/terminfo/searcher.rs @@ -12,8 +12,8 @@ //! //! Does not support hashed database, only filesystem! -use std::io::File; -use std::io::fs::PathExtensions; +use std::old_io::File; +use std::old_io::fs::PathExtensions; use std::os::getenv; use std::os; diff --git a/src/libterm/win.rs b/src/libterm/win.rs index 3130ad0af3f..a56613681c8 100644 --- a/src/libterm/win.rs +++ b/src/libterm/win.rs @@ -14,7 +14,7 @@ extern crate libc; -use std::io::IoResult; +use std::old_io::IoResult; use attr; use color; @@ -130,8 +130,8 @@ impl<T: Writer+Send> WinConsole<T> { } impl<T: Writer> Writer for WinConsole<T> { - fn write(&mut self, buf: &[u8]) -> IoResult<()> { - self.buf.write(buf) + fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { + self.buf.write_all(buf) } fn flush(&mut self) -> IoResult<()> { diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 91031b15328..43a1bbd6c02 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -68,9 +68,9 @@ use std::any::Any; use std::cmp; use std::collections::BTreeMap; use std::fmt; -use std::io::stdio::StdWriter; -use std::io::{File, ChanReader, ChanWriter}; -use std::io; +use std::old_io::stdio::StdWriter; +use std::old_io::{File, ChanReader, ChanWriter}; +use std::old_io; use std::iter::repeat; use std::num::{Float, Int}; use std::os; @@ -451,13 +451,13 @@ struct ConsoleTestState<T> { impl<T: Writer> ConsoleTestState<T> { pub fn new(opts: &TestOpts, - _: Option<T>) -> io::IoResult<ConsoleTestState<StdWriter>> { + _: Option<T>) -> old_io::IoResult<ConsoleTestState<StdWriter>> { let log_out = match opts.logfile { Some(ref path) => Some(try!(File::create(path))), None => None }; let out = match term::stdout() { - None => Raw(io::stdio::stdout_raw()), + None => Raw(old_io::stdio::stdout_raw()), Some(t) => Pretty(t) }; @@ -476,64 +476,64 @@ impl<T: Writer> ConsoleTestState<T> { }) } - pub fn write_ok(&mut self) -> io::IoResult<()> { + pub fn write_ok(&mut self) -> old_io::IoResult<()> { self.write_pretty("ok", term::color::GREEN) } - pub fn write_failed(&mut self) -> io::IoResult<()> { + pub fn write_failed(&mut self) -> old_io::IoResult<()> { self.write_pretty("FAILED", term::color::RED) } - pub fn write_ignored(&mut self) -> io::IoResult<()> { + pub fn write_ignored(&mut self) -> old_io::IoResult<()> { self.write_pretty("ignored", term::color::YELLOW) } - pub fn write_metric(&mut self) -> io::IoResult<()> { + pub fn write_metric(&mut self) -> old_io::IoResult<()> { self.write_pretty("metric", term::color::CYAN) } - pub fn write_bench(&mut self) -> io::IoResult<()> { + pub fn write_bench(&mut self) -> old_io::IoResult<()> { self.write_pretty("bench", term::color::CYAN) } pub fn write_pretty(&mut self, word: &str, - color: term::color::Color) -> io::IoResult<()> { + color: term::color::Color) -> old_io::IoResult<()> { match self.out { Pretty(ref mut term) => { if self.use_color { try!(term.fg(color)); } - try!(term.write(word.as_bytes())); + try!(term.write_all(word.as_bytes())); if self.use_color { try!(term.reset()); } Ok(()) } - Raw(ref mut stdout) => stdout.write(word.as_bytes()) + Raw(ref mut stdout) => stdout.write_all(word.as_bytes()) } } - pub fn write_plain(&mut self, s: &str) -> io::IoResult<()> { + pub fn write_plain(&mut self, s: &str) -> old_io::IoResult<()> { match self.out { - Pretty(ref mut term) => term.write(s.as_bytes()), - Raw(ref mut stdout) => stdout.write(s.as_bytes()) + Pretty(ref mut term) => term.write_all(s.as_bytes()), + Raw(ref mut stdout) => stdout.write_all(s.as_bytes()) } } - pub fn write_run_start(&mut self, len: uint) -> io::IoResult<()> { + pub fn write_run_start(&mut self, len: uint) -> old_io::IoResult<()> { self.total = len; let noun = if len != 1 { "tests" } else { "test" }; self.write_plain(format!("\nrunning {} {}\n", len, noun).as_slice()) } pub fn write_test_start(&mut self, test: &TestDesc, - align: NamePadding) -> io::IoResult<()> { + align: NamePadding) -> old_io::IoResult<()> { let name = test.padded_name(self.max_name_len, align); self.write_plain(format!("test {} ... ", name).as_slice()) } - pub fn write_result(&mut self, result: &TestResult) -> io::IoResult<()> { + pub fn write_result(&mut self, result: &TestResult) -> old_io::IoResult<()> { try!(match *result { TrOk => self.write_ok(), TrFailed => self.write_failed(), @@ -555,7 +555,7 @@ impl<T: Writer> ConsoleTestState<T> { } pub fn write_log(&mut self, test: &TestDesc, - result: &TestResult) -> io::IoResult<()> { + result: &TestResult) -> old_io::IoResult<()> { match self.log_out { None => Ok(()), Some(ref mut o) => { @@ -566,12 +566,12 @@ impl<T: Writer> ConsoleTestState<T> { TrMetrics(ref mm) => mm.fmt_metrics(), TrBench(ref bs) => fmt_bench_samples(bs) }, test.name.as_slice()); - o.write(s.as_bytes()) + o.write_all(s.as_bytes()) } } } - pub fn write_failures(&mut self) -> io::IoResult<()> { + pub fn write_failures(&mut self) -> old_io::IoResult<()> { try!(self.write_plain("\nfailures:\n")); let mut failures = Vec::new(); let mut fail_out = String::new(); @@ -599,7 +599,7 @@ impl<T: Writer> ConsoleTestState<T> { Ok(()) } - pub fn write_run_finish(&mut self) -> io::IoResult<bool> { + pub fn write_run_finish(&mut self) -> old_io::IoResult<bool> { assert!(self.passed + self.failed + self.ignored + self.measured == self.total); let success = self.failed == 0u; @@ -635,9 +635,10 @@ pub fn fmt_bench_samples(bs: &BenchSamples) -> String { } // A simple console test runner -pub fn run_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn> ) -> io::IoResult<bool> { +pub fn run_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn> ) -> old_io::IoResult<bool> { - fn callback<T: Writer>(event: &TestEvent, st: &mut ConsoleTestState<T>) -> io::IoResult<()> { + fn callback<T: Writer>(event: &TestEvent, + st: &mut ConsoleTestState<T>) -> old_io::IoResult<()> { match (*event).clone() { TeFiltered(ref filtered_tests) => st.write_run_start(filtered_tests.len()), TeWait(ref test, padding) => st.write_test_start(test, padding), @@ -735,7 +736,7 @@ fn should_sort_failures_before_printing_them() { fn use_color(opts: &TestOpts) -> bool { match opts.color { - AutoColor => get_concurrency() == 1 && io::stdout().get_ref().isatty(), + AutoColor => get_concurrency() == 1 && old_io::stdout().get_ref().isatty(), AlwaysColor => true, NeverColor => false, } @@ -753,8 +754,8 @@ pub type MonitorMsg = (TestDesc, TestResult, Vec<u8> ); fn run_tests<F>(opts: &TestOpts, tests: Vec<TestDescAndFn> , - mut callback: F) -> io::IoResult<()> where - F: FnMut(TestEvent) -> io::IoResult<()>, + mut callback: F) -> old_io::IoResult<()> where + F: FnMut(TestEvent) -> old_io::IoResult<()>, { let filtered_tests = filter_tests(opts, tests); let filtered_descs = filtered_tests.iter() @@ -1127,7 +1128,7 @@ mod tests { TestDesc, TestDescAndFn, TestOpts, run_test, Metric, MetricMap, StaticTestName, DynTestName, DynTestFn, ShouldFail}; - use std::io::TempDir; + use std::old_io::TempDir; use std::thunk::Thunk; use std::sync::mpsc::channel; diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index 76b85cc10cd..2f551bb7f49 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -351,7 +351,7 @@ pub fn freq_count<T, U>(mut iter: T) -> hash_map::HashMap<U, uint> mod tests { use stats::Stats; use stats::Summary; - use std::io; + use std::old_io; use std::f64; macro_rules! assert_approx_eq { @@ -367,7 +367,7 @@ mod tests { let summ2 = Summary::new(samples); - let mut w = io::stdout(); + let mut w = old_io::stdout(); let w = &mut w; (write!(w, "\n")).unwrap(); diff --git a/src/rustbook/book.rs b/src/rustbook/book.rs index 3047e93137f..2707a6346c8 100644 --- a/src/rustbook/book.rs +++ b/src/rustbook/book.rs @@ -10,7 +10,7 @@ //! Basic data structures for representing a book. -use std::io::BufferedReader; +use std::old_io::BufferedReader; use std::iter; use std::iter::AdditiveIterator; diff --git a/src/rustbook/build.rs b/src/rustbook/build.rs index 93601c0f61b..ccb572a113a 100644 --- a/src/rustbook/build.rs +++ b/src/rustbook/build.rs @@ -11,8 +11,8 @@ //! Implementation of the `build` subcommand, used to compile a book. use std::os; -use std::io; -use std::io::{fs, File, BufferedWriter, TempDir, IoResult}; +use std::old_io; +use std::old_io::{fs, File, BufferedWriter, TempDir, IoResult}; use subcommand::Subcommand; use term::Term; @@ -119,7 +119,7 @@ fn render(book: &Book, tgt: &Path) -> CliResult<()> { try!(writeln!(&mut toc, "</div></div>")); } - try!(fs::mkdir_recursive(&out_path, io::USER_DIR)); + try!(fs::mkdir_recursive(&out_path, old_io::USER_DIR)); let rustdoc_args: &[String] = &[ "".to_string(), @@ -165,7 +165,7 @@ impl Subcommand for Build { tgt = Path::new(os::args()[3].clone()); } - try!(fs::mkdir(&tgt, io::USER_DIR)); + try!(fs::mkdir(&tgt, old_io::USER_DIR)); try!(File::create(&tgt.join("rust-book.css")).write_str(css::STYLE)); diff --git a/src/rustbook/error.rs b/src/rustbook/error.rs index 7d5e7efcc94..d4829a2c391 100644 --- a/src/rustbook/error.rs +++ b/src/rustbook/error.rs @@ -13,7 +13,7 @@ use std::fmt; use std::fmt::{Show, Formatter}; -use std::io::IoError; +use std::old_io::IoError; pub type CliError = Box<Error + 'static>; pub type CliResult<T> = Result<T, CliError>; diff --git a/src/rustbook/term.rs b/src/rustbook/term.rs index 471e22ce7c1..b922bf1cdd3 100644 --- a/src/rustbook/term.rs +++ b/src/rustbook/term.rs @@ -12,7 +12,7 @@ //! verbosity support. For now, just a wrapper around stdout/stderr. use std::os; -use std::io::stdio; +use std::old_io::stdio; pub struct Term { err: Box<Writer + 'static> diff --git a/src/rustbook/test.rs b/src/rustbook/test.rs index f2bf92585f7..db02481cb02 100644 --- a/src/rustbook/test.rs +++ b/src/rustbook/test.rs @@ -16,7 +16,7 @@ use error::CommandResult; use error::Error; use term::Term; use book; -use std::io::{Command, File}; +use std::old_io::{Command, File}; use std::os; struct Test; diff --git a/src/test/bench/core-std.rs b/src/test/bench/core-std.rs index 9007b4fd64c..a20a649dfe9 100644 --- a/src/test/bench/core-std.rs +++ b/src/test/bench/core-std.rs @@ -13,7 +13,7 @@ #![feature(unboxed_closures)] -use std::io::File; +use std::old_io::File; use std::iter::repeat; use std::mem::swap; use std::os; @@ -71,7 +71,7 @@ fn shift_push() { } fn read_line() { - use std::io::BufferedReader; + use std::old_io::BufferedReader; let mut path = Path::new(env!("CFG_SRC_DIR")); path.push("src/test/bench/shootout-k-nucleotide.data"); diff --git a/src/test/bench/shootout-fasta-redux.rs b/src/test/bench/shootout-fasta-redux.rs index 9e5618579e4..32242bee801 100644 --- a/src/test/bench/shootout-fasta-redux.rs +++ b/src/test/bench/shootout-fasta-redux.rs @@ -39,7 +39,7 @@ // OF THE POSSIBILITY OF SUCH DAMAGE. use std::cmp::min; -use std::io::{stdout, IoResult}; +use std::old_io::{stdout, IoResult}; use std::iter::repeat; use std::os; use std::slice::bytes::copy_memory; diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index 1b849cd12f5..193be04f809 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -39,8 +39,8 @@ // OF THE POSSIBILITY OF SUCH DAMAGE. use std::cmp::min; -use std::io::{BufferedWriter, File}; -use std::io; +use std::old_io::{BufferedWriter, File}; +use std::old_io; use std::num::Float; use std::os; @@ -86,7 +86,7 @@ impl<'a> Iterator for AAGen<'a> { fn make_fasta<W: Writer, I: Iterator<Item=u8>>( wr: &mut W, header: &str, mut it: I, mut n: uint) - -> std::io::IoResult<()> + -> std::old_io::IoResult<()> { try!(wr.write(header.as_bytes())); let mut line = [0u8; LINE_LENGTH + 1]; @@ -102,7 +102,7 @@ fn make_fasta<W: Writer, I: Iterator<Item=u8>>( Ok(()) } -fn run<W: Writer>(writer: &mut W) -> std::io::IoResult<()> { +fn run<W: Writer>(writer: &mut W) -> std::old_io::IoResult<()> { let args = os::args(); let args = args.as_slice(); let n = if os::getenv("RUST_BENCH").is_some() { @@ -147,7 +147,7 @@ fn main() { let mut file = BufferedWriter::new(File::create(&Path::new("./shootout-fasta.data"))); run(&mut file) } else { - run(&mut io::stdout()) + run(&mut old_io::stdout()) }; res.unwrap() } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index fdaeb9e74f5..377cb5c9bae 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -146,7 +146,7 @@ fn make_sequence_processor(sz: uint, // given a FASTA file on stdin, process sequence THREE fn main() { - use std::io::{stdio, MemReader, BufferedReader}; + use std::old_io::{stdio, MemReader, BufferedReader}; let rdr = if os::getenv("RUST_BENCH").is_some() { let foo = include_bytes!("shootout-k-nucleotide.data"); diff --git a/src/test/bench/shootout-k-nucleotide.rs b/src/test/bench/shootout-k-nucleotide.rs index 5256e607d20..657ae537f21 100644 --- a/src/test/bench/shootout-k-nucleotide.rs +++ b/src/test/bench/shootout-k-nucleotide.rs @@ -294,10 +294,10 @@ fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> { fn main() { let input = if std::os::getenv("RUST_BENCH").is_some() { - let fd = std::io::File::open(&Path::new("shootout-k-nucleotide.data")); - get_sequence(&mut std::io::BufferedReader::new(fd), ">THREE") + let fd = std::old_io::File::open(&Path::new("shootout-k-nucleotide.data")); + get_sequence(&mut std::old_io::BufferedReader::new(fd), ">THREE") } else { - get_sequence(&mut *std::io::stdin().lock(), ">THREE") + get_sequence(&mut *std::old_io::stdin().lock(), ">THREE") }; let input = Arc::new(input); diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index 0e80cdca9f8..0bd69b73214 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -42,7 +42,7 @@ // ignore-pretty very bad with line comments -use std::io; +use std::old_io; use std::os; use std::simd::f64x2; use std::sync::Arc; @@ -53,7 +53,7 @@ const LIMIT: f64 = 2.0; const WORKERS: uint = 16; #[inline(always)] -fn mandelbrot<W: io::Writer>(w: uint, mut out: W) -> io::IoResult<()> { +fn mandelbrot<W: old_io::Writer>(w: uint, mut out: W) -> old_io::IoResult<()> { assert!(WORKERS % 2 == 0); // Ensure w and h are multiples of 8. @@ -202,9 +202,9 @@ fn main() { let res = if args.len() < 2 { println!("Test mode: do not dump the image because it's not utf8, \ which interferes with the test runner."); - mandelbrot(1000, io::util::NullWriter) + mandelbrot(1000, old_io::util::NullWriter) } else { - mandelbrot(args[1].parse().unwrap(), io::stdout()) + mandelbrot(args[1].parse().unwrap(), old_io::stdout()) }; res.unwrap(); } diff --git a/src/test/bench/shootout-reverse-complement.rs b/src/test/bench/shootout-reverse-complement.rs index c8a74c7d735..6419ad551f4 100644 --- a/src/test/bench/shootout-reverse-complement.rs +++ b/src/test/bench/shootout-reverse-complement.rs @@ -44,8 +44,8 @@ extern crate libc; -use std::io::stdio::{stdin_raw, stdout_raw}; -use std::io::{IoResult, EndOfFile}; +use std::old_io::stdio::{stdin_raw, stdout_raw}; +use std::old_io::{IoResult, EndOfFile}; use std::ptr::{copy_memory, Unique}; use std::thread::Thread; diff --git a/src/test/bench/sudoku.rs b/src/test/bench/sudoku.rs index 67476eddbc7..30a0bd7bd91 100644 --- a/src/test/bench/sudoku.rs +++ b/src/test/bench/sudoku.rs @@ -13,9 +13,9 @@ #![feature(box_syntax)] #![allow(non_snake_case)] -use std::io::BufferedReader; -use std::io::stdio::StdReader; -use std::io; +use std::old_io::BufferedReader; +use std::old_io::stdio::StdReader; +use std::old_io; use std::iter::repeat; use std::num::Int; use std::os; @@ -80,7 +80,7 @@ impl Sudoku { return Sudoku::new(g) } - pub fn write(&self, writer: &mut io::Writer) { + pub fn write(&self, writer: &mut old_io::Writer) { for row in range(0u8, 9u8) { write!(writer, "{}", self.grid[row as uint][0]); for col in range(1u8, 9u8) { @@ -274,8 +274,8 @@ fn main() { let mut sudoku = if use_default { Sudoku::from_vec(&DEFAULT_SUDOKU) } else { - Sudoku::read(&mut *io::stdin().lock()) + Sudoku::read(&mut *old_io::stdin().lock()) }; sudoku.solve(); - sudoku.write(&mut io::stdout()); + sudoku.write(&mut old_io::stdout()); } diff --git a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs index 98d1905ed90..9c10f01e027 100644 --- a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs +++ b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs @@ -16,10 +16,11 @@ extern crate collections; use std::collections::HashMap; fn main() { + let tmp; let mut buggy_map: HashMap<usize, &usize> = HashMap::new(); buggy_map.insert(42, &*box 1); //~ ERROR borrowed value does not live long enough // but it is ok if we use a temporary - let tmp = box 2; + tmp = box 2; buggy_map.insert(43, &*tmp); } diff --git a/src/test/compile-fail/borrowck-let-suggestion-suffixes.rs b/src/test/compile-fail/borrowck-let-suggestion-suffixes.rs new file mode 100644 index 00000000000..f551a2aa811 --- /dev/null +++ b/src/test/compile-fail/borrowck-let-suggestion-suffixes.rs @@ -0,0 +1,57 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn f() { + let old = ['o']; // statement 0 + let mut v1 = Vec::new(); // statement 1 + + let mut v2 = Vec::new(); // statement 2 + //~^ NOTE reference must be valid for the block suffix following statement 2 + + let young = ['y']; // statement 3 + //~^ NOTE ...but borrowed value is only valid for the block suffix following statement 3 + + v2.push(&young[0]); // statement 4 + //~^ ERROR `young[..]` does not live long enough + + let mut v3 = Vec::new(); // statement 5 + //~^ NOTE reference must be valid for the block suffix following statement 5 + + v3.push(&'x'); // statement 6 + //~^ ERROR borrowed value does not live long enough + //~| NOTE ...but borrowed value is only valid for the statement + //~| HELP consider using a `let` binding to increase its lifetime + + { + + let mut v4 = Vec::new(); // (sub) statement 0 + //~^ NOTE reference must be valid for the block suffix following statement 0 + + v4.push(&'y'); + //~^ ERROR borrowed value does not live long enough + //~| NOTE ...but borrowed value is only valid for the statement + //~| HELP consider using a `let` binding to increase its lifetime + + } // (statement 7) + + let mut v5 = Vec::new(); // statement 8 + //~^ NOTE reference must be valid for the block suffix following statement 8 + + v5.push(&'z'); + //~^ ERROR borrowed value does not live long enough + //~| NOTE ...but borrowed value is only valid for the statement + //~| HELP consider using a `let` binding to increase its lifetime + + v1.push(&old[0]); +} + +fn main() { + f(); +} diff --git a/src/test/compile-fail/borrowck-let-suggestion.rs b/src/test/compile-fail/borrowck-let-suggestion.rs index 5f5ff4014e1..a08021919df 100644 --- a/src/test/compile-fail/borrowck-let-suggestion.rs +++ b/src/test/compile-fail/borrowck-let-suggestion.rs @@ -10,7 +10,7 @@ fn f() { let x = [1is].iter(); //~ ERROR borrowed value does not live long enough - //~^^ NOTE reference must be valid for the block + //~^ NOTE reference must be valid for the block suffix following statement //~^^ HELP consider using a `let` binding to increase its lifetime } diff --git a/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs b/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs index 9148f13c4dd..b106169c6fc 100644 --- a/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs +++ b/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs @@ -13,7 +13,7 @@ fn main() { move|:| { x = 2; }; //~^ ERROR: cannot assign to immutable captured outer variable - let s = std::io::stdin(); + let s = std::old_io::stdin(); move|:| { s.read_to_end(); }; //~^ ERROR: cannot borrow immutable captured outer variable } diff --git a/src/test/compile-fail/cast-from-nil.rs b/src/test/compile-fail/cast-from-nil.rs index 558a5478718..4c6dcaccc9a 100644 --- a/src/test/compile-fail/cast-from-nil.rs +++ b/src/test/compile-fail/cast-from-nil.rs @@ -8,5 +8,5 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// error-pattern: cast from nil: `()` as `u32` +// error-pattern: non-scalar cast: `()` as `u32` fn main() { let u = (assert!(true) as u32); } diff --git a/src/test/compile-fail/cast-to-nil.rs b/src/test/compile-fail/cast-to-nil.rs index 1a5c0744f70..e5fd5bb33eb 100644 --- a/src/test/compile-fail/cast-to-nil.rs +++ b/src/test/compile-fail/cast-to-nil.rs @@ -8,5 +8,5 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// error-pattern: cast to nil: `u32` as `()` +// error-pattern: non-scalar cast: `u32` as `()` fn main() { let u = 0u32 as (); } diff --git a/src/test/compile-fail/issue-10991.rs b/src/test/compile-fail/issue-10991.rs index 2913ddf395f..25060b94dcf 100644 --- a/src/test/compile-fail/issue-10991.rs +++ b/src/test/compile-fail/issue-10991.rs @@ -10,5 +10,5 @@ fn main() { let nil = (); - let _t = nil as usize; //~ ERROR: cast from nil: `()` as `usize` + let _t = nil as usize; //~ ERROR: non-scalar cast: `()` as `usize` } diff --git a/src/test/compile-fail/issue-11374.rs b/src/test/compile-fail/issue-11374.rs index 6b048528a99..aa2a71ca2db 100644 --- a/src/test/compile-fail/issue-11374.rs +++ b/src/test/compile-fail/issue-11374.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; +use std::old_io; use std::vec; pub struct Container<'a> { @@ -26,7 +26,7 @@ impl<'a> Container<'a> { } pub fn for_stdin<'a>() -> Container<'a> { - let mut r = io::stdin(); + let mut r = old_io::stdin(); Container::wrap(&mut r as &mut Reader) } diff --git a/src/test/compile-fail/issue-18783.rs b/src/test/compile-fail/issue-18783.rs index bed835d9bde..d26bf68cb5d 100644 --- a/src/test/compile-fail/issue-18783.rs +++ b/src/test/compile-fail/issue-18783.rs @@ -13,16 +13,16 @@ use std::cell::RefCell; fn main() { - let c = RefCell::new(vec![]); let mut y = 1us; + let c = RefCell::new(vec![]); c.push(box || y = 0); c.push(box || y = 0); //~^ ERROR cannot borrow `y` as mutable more than once at a time } fn ufcs() { - let c = RefCell::new(vec![]); let mut y = 1us; + let c = RefCell::new(vec![]); Push::push(&c, box || y = 0); Push::push(&c, box || y = 0); diff --git a/src/test/compile-fail/issue-21554.rs b/src/test/compile-fail/issue-21554.rs new file mode 100644 index 00000000000..a2cac55033c --- /dev/null +++ b/src/test/compile-fail/issue-21554.rs @@ -0,0 +1,15 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +struct Inches(i32); + +fn main() { + Inches as f32; //~ ERROR illegal cast; cast through an integer first +} diff --git a/src/test/compile-fail/lint-uppercase-variables.rs b/src/test/compile-fail/lint-uppercase-variables.rs index 6b3c680749f..057b8e3acc6 100644 --- a/src/test/compile-fail/lint-uppercase-variables.rs +++ b/src/test/compile-fail/lint-uppercase-variables.rs @@ -15,8 +15,8 @@ #![feature(path)] #![feature(io)] -use std::io::File; -use std::io::IoError; +use std::old_io::File; +use std::old_io::IoError; struct Something { X: usize //~ ERROR structure field `X` should have a snake case name such as `x` @@ -36,7 +36,7 @@ fn main() { Ok(cnt) => println!("read this many bytes: {}", cnt), Err(IoError{ kind: EndOfFile, .. }) => println!("Got end of file: {:?}", EndOfFile), //~^ ERROR variable `EndOfFile` should have a snake case name such as `end_of_file` -//~^^ WARN `EndOfFile` is named the same as one of the variants of the type `std::io::IoErrorKind` +//~^^ WARN `EndOfFile` is named the same as one of the variants of the type `std::old_io::IoErrorKind` } test(1); diff --git a/src/test/compile-fail/typeck-cast-pointer-to-float.rs b/src/test/compile-fail/typeck-cast-pointer-to-float.rs index 22a0978ef7c..285a5dbee05 100644 --- a/src/test/compile-fail/typeck-cast-pointer-to-float.rs +++ b/src/test/compile-fail/typeck-cast-pointer-to-float.rs @@ -11,5 +11,5 @@ fn main() { let x : i16 = 22; ((&x) as *const i16) as f32; - //~^ ERROR: cannot cast from pointer to float directly: `*const i16` as `f32` + //~^ ERROR illegal cast; cast through an integer first: `*const i16` as `f32` } diff --git a/src/test/debuginfo/function-arg-initialization.rs b/src/test/debuginfo/function-arg-initialization.rs index 55c5c504064..38875c7656e 100644 --- a/src/test/debuginfo/function-arg-initialization.rs +++ b/src/test/debuginfo/function-arg-initialization.rs @@ -226,7 +226,7 @@ #![omit_gdb_pretty_printer_section] fn immediate_args(a: int, b: bool, c: f64) { - ::std::io::print("") // #break + ::std::old_io::print("") // #break } struct BigStruct { @@ -241,21 +241,21 @@ struct BigStruct { } fn non_immediate_args(a: BigStruct, b: BigStruct) { - ::std::io::print("") // #break + ::std::old_io::print("") // #break } fn binding(a: i64, b: u64, c: f64) { let x = 0i; // #break - ::std::io::print("") + ::std::old_io::print("") } fn assignment(mut a: u64, b: u64, c: f64) { a = b; // #break - ::std::io::print("") + ::std::old_io::print("") } fn function_call(x: u64, y: u64, z: f64) { - std::io::stdio::print("Hi!") // #break + std::old_io::stdio::print("Hi!") // #break } fn identifier(x: u64, y: u64, z: f64) -> u64 { diff --git a/src/test/debuginfo/function-prologue-stepping-no-stack-check.rs b/src/test/debuginfo/function-prologue-stepping-no-stack-check.rs index e437e35db3a..4692318b98f 100644 --- a/src/test/debuginfo/function-prologue-stepping-no-stack-check.rs +++ b/src/test/debuginfo/function-prologue-stepping-no-stack-check.rs @@ -249,7 +249,7 @@ #[no_stack_check] fn immediate_args(a: int, b: bool, c: f64) { - ::std::io::print(""); + ::std::old_io::print(""); } struct BigStruct { @@ -265,24 +265,24 @@ struct BigStruct { #[no_stack_check] fn non_immediate_args(a: BigStruct, b: BigStruct) { - ::std::io::print(""); + ::std::old_io::print(""); } #[no_stack_check] fn binding(a: i64, b: u64, c: f64) { let x = 0i; - ::std::io::print(""); + ::std::old_io::print(""); } #[no_stack_check] fn assignment(mut a: u64, b: u64, c: f64) { a = b; - ::std::io::print(""); + ::std::old_io::print(""); } #[no_stack_check] fn function_call(x: u64, y: u64, z: f64) { - std::io::stdio::print("Hi!") + std::old_io::stdio::print("Hi!") } #[no_stack_check] diff --git a/src/test/debuginfo/function-prologue-stepping-regular.rs b/src/test/debuginfo/function-prologue-stepping-regular.rs index 05ea357389b..799352911f6 100644 --- a/src/test/debuginfo/function-prologue-stepping-regular.rs +++ b/src/test/debuginfo/function-prologue-stepping-regular.rs @@ -156,7 +156,7 @@ fn assignment(mut a: u64, b: u64, c: f64) { } fn function_call(x: u64, y: u64, z: f64) { - std::io::stdio::print("Hi!") + std::old_io::stdio::print("Hi!") } fn identifier(x: u64, y: u64, z: f64) -> u64 { diff --git a/src/test/debuginfo/issue13213.rs b/src/test/debuginfo/issue13213.rs index 474f34c4b45..dd61542b800 100644 --- a/src/test/debuginfo/issue13213.rs +++ b/src/test/debuginfo/issue13213.rs @@ -21,5 +21,5 @@ extern crate issue13213aux; // be available because they have been optimized out from the exporting crate. fn main() { let b: issue13213aux::S = issue13213aux::A; - ::std::io::println("Nothing to do here..."); + ::std::old_io::println("Nothing to do here..."); } diff --git a/src/test/run-make/cannot-read-embedded-idents/create_and_compile.rs b/src/test/run-make/cannot-read-embedded-idents/create_and_compile.rs index 2d8fa352e27..3adb45798e4 100644 --- a/src/test/run-make/cannot-read-embedded-idents/create_and_compile.rs +++ b/src/test/run-make/cannot-read-embedded-idents/create_and_compile.rs @@ -9,7 +9,7 @@ // except according to those terms. use std::os; -use std::io::{File, Command}; +use std::old_io::{File, Command}; // creates broken.rs, which has the Ident \x00name_0,ctxt_0\x00 // embedded within it, and then attempts to compile broken.rs with the diff --git a/src/test/run-make/unicode-input/multiple_files.rs b/src/test/run-make/unicode-input/multiple_files.rs index 88d8f10e709..eda89f2344b 100644 --- a/src/test/run-make/unicode-input/multiple_files.rs +++ b/src/test/run-make/unicode-input/multiple_files.rs @@ -9,7 +9,7 @@ // except according to those terms. use std::{char, os}; -use std::io::{File, Command}; +use std::old_io::{File, Command}; use std::rand::{thread_rng, Rng}; // creates unicode_input_multiple_files_{main,chars}.rs, where the diff --git a/src/test/run-make/unicode-input/span_length.rs b/src/test/run-make/unicode-input/span_length.rs index ae638399450..d387b9d71e3 100644 --- a/src/test/run-make/unicode-input/span_length.rs +++ b/src/test/run-make/unicode-input/span_length.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::{File, Command}; +use std::old_io::{File, Command}; use std::iter::repeat; use std::rand::{thread_rng, Rng}; use std::{char, os}; diff --git a/src/test/run-pass-valgrind/cleanup-stdin.rs b/src/test/run-pass-valgrind/cleanup-stdin.rs index 21160553f79..c16f1f4c842 100644 --- a/src/test/run-pass-valgrind/cleanup-stdin.rs +++ b/src/test/run-pass-valgrind/cleanup-stdin.rs @@ -9,5 +9,5 @@ // except according to those terms. fn main() { - let _ = std::io::stdin(); + let _ = std::old_io::stdin(); } diff --git a/src/test/run-pass/backtrace.rs b/src/test/run-pass/backtrace.rs index 320ad0bf4d1..a71794149be 100644 --- a/src/test/run-pass/backtrace.rs +++ b/src/test/run-pass/backtrace.rs @@ -15,7 +15,7 @@ #![feature(unsafe_destructor)] use std::os; -use std::io::process::Command; +use std::old_io::process::Command; use std::str; use std::ops::{Drop, FnMut, FnOnce}; diff --git a/src/test/run-pass/capturing-logging.rs b/src/test/run-pass/capturing-logging.rs index 00673bee8b4..fd988d28778 100644 --- a/src/test/run-pass/capturing-logging.rs +++ b/src/test/run-pass/capturing-logging.rs @@ -20,7 +20,7 @@ extern crate log; use log::{set_logger, Logger, LogRecord}; use std::sync::mpsc::channel; use std::fmt; -use std::io::{ChanReader, ChanWriter}; +use std::old_io::{ChanReader, ChanWriter}; use std::thread::Thread; struct MyWriter(ChanWriter); diff --git a/src/test/run-pass/closure-reform.rs b/src/test/run-pass/closure-reform.rs index a2e7d7bd7e3..a4495c3c68e 100644 --- a/src/test/run-pass/closure-reform.rs +++ b/src/test/run-pass/closure-reform.rs @@ -14,7 +14,7 @@ #![feature(unboxed_closures)] use std::mem; -use std::io::stdio::println; +use std::old_io::stdio::println; fn call_it<F>(f: F) where F : FnOnce(String) -> String diff --git a/src/test/run-pass/colorful-write-macros.rs b/src/test/run-pass/colorful-write-macros.rs index ca7f761b80d..bcb2e492041 100644 --- a/src/test/run-pass/colorful-write-macros.rs +++ b/src/test/run-pass/colorful-write-macros.rs @@ -11,7 +11,7 @@ // no-pretty-expanded #![allow(unused_must_use, dead_code, deprecated)] -use std::io::MemWriter; +use std::old_io::MemWriter; use std::fmt; struct Foo<'a> { diff --git a/src/test/run-pass/core-run-destroy.rs b/src/test/run-pass/core-run-destroy.rs index eeb044e5604..88d5b74708e 100644 --- a/src/test/run-pass/core-run-destroy.rs +++ b/src/test/run-pass/core-run-destroy.rs @@ -19,7 +19,7 @@ extern crate libc; -use std::io::{Process, Command, timer}; +use std::old_io::{Process, Command, timer}; use std::time::Duration; use std::str; use std::sync::mpsc::channel; @@ -56,8 +56,8 @@ fn test_destroy_twice() { } pub fn test_destroy_actually_kills(force: bool) { - use std::io::process::{Command, ProcessOutput, ExitStatus, ExitSignal}; - use std::io::timer; + use std::old_io::process::{Command, ProcessOutput, ExitStatus, ExitSignal}; + use std::old_io::timer; use libc; use std::str; diff --git a/src/test/run-pass/issue-10626.rs b/src/test/run-pass/issue-10626.rs index b06799444f4..4b69e1595bd 100644 --- a/src/test/run-pass/issue-10626.rs +++ b/src/test/run-pass/issue-10626.rs @@ -13,7 +13,7 @@ // that we don't die in a large ball of fire use std::os; -use std::io::process; +use std::old_io::process; pub fn main () { let args = os::args(); diff --git a/src/test/run-pass/issue-11881.rs b/src/test/run-pass/issue-11881.rs index d0d8a8589a4..10d694957f5 100644 --- a/src/test/run-pass/issue-11881.rs +++ b/src/test/run-pass/issue-11881.rs @@ -13,9 +13,9 @@ extern crate rbml; extern crate serialize; -use std::io; +use std::old_io; use std::fmt; -use std::io::{IoResult, SeekStyle}; +use std::old_io::{IoResult, SeekStyle}; use std::slice; use serialize::{Encodable, Encoder}; diff --git a/src/test/run-pass/issue-12684.rs b/src/test/run-pass/issue-12684.rs index a6a4d21e8f2..38731b8c8da 100644 --- a/src/test/run-pass/issue-12684.rs +++ b/src/test/run-pass/issue-12684.rs @@ -16,7 +16,7 @@ fn main() { } fn customtask() { - let mut timer = std::io::timer::Timer::new().unwrap(); + let mut timer = std::old_io::timer::Timer::new().unwrap(); let periodic = timer.periodic(Duration::milliseconds(10)); periodic.recv(); } diff --git a/src/test/run-pass/issue-12699.rs b/src/test/run-pass/issue-12699.rs index 2dc25181606..b55d6477753 100644 --- a/src/test/run-pass/issue-12699.rs +++ b/src/test/run-pass/issue-12699.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::timer; +use std::old_io::timer; use std::time::Duration; fn main() { diff --git a/src/test/run-pass/issue-13304.rs b/src/test/run-pass/issue-13304.rs index 11003c6fc52..f2a8bc47db8 100644 --- a/src/test/run-pass/issue-13304.rs +++ b/src/test/run-pass/issue-13304.rs @@ -11,7 +11,7 @@ // ignore-fast use std::os; -use std::io; +use std::old_io; use std::str; fn main() { @@ -27,7 +27,7 @@ fn main() { fn parent() { let args = os::args(); let args = args.as_slice(); - let mut p = io::process::Command::new(args[0].as_slice()) + let mut p = old_io::process::Command::new(args[0].as_slice()) .arg("child").spawn().unwrap(); p.stdin.as_mut().unwrap().write_str("test1\ntest2\ntest3").unwrap(); let out = p.wait_with_output().unwrap(); @@ -37,7 +37,7 @@ fn parent() { } fn child() { - for line in io::stdin().lock().lines() { + for line in old_io::stdin().lock().lines() { println!("{}", line.unwrap()); } } diff --git a/src/test/run-pass/issue-14456.rs b/src/test/run-pass/issue-14456.rs index f5fdf8704ed..a41e57f1002 100644 --- a/src/test/run-pass/issue-14456.rs +++ b/src/test/run-pass/issue-14456.rs @@ -9,9 +9,9 @@ // except according to those terms. -use std::io::process; -use std::io::Command; -use std::io; +use std::old_io::process; +use std::old_io::Command; +use std::old_io; use std::os; fn main() { @@ -25,9 +25,9 @@ fn main() { } fn child() { - io::stdout().write_line("foo").unwrap(); - io::stderr().write_line("bar").unwrap(); - assert_eq!(io::stdin().lock().read_line().err().unwrap().kind, io::EndOfFile); + old_io::stdout().write_line("foo").unwrap(); + old_io::stderr().write_line("bar").unwrap(); + assert_eq!(old_io::stdin().lock().read_line().err().unwrap().kind, old_io::EndOfFile); } fn test() { diff --git a/src/test/run-pass/issue-14901.rs b/src/test/run-pass/issue-14901.rs index e41754fd1b9..abb15dae00d 100644 --- a/src/test/run-pass/issue-14901.rs +++ b/src/test/run-pass/issue-14901.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::Reader; +use std::old_io::Reader; enum Wrapper<'a> { WrapReader(&'a (Reader + 'a)) diff --git a/src/test/run-pass/issue-14940.rs b/src/test/run-pass/issue-14940.rs index d815620c969..5ae0ad6c3e9 100644 --- a/src/test/run-pass/issue-14940.rs +++ b/src/test/run-pass/issue-14940.rs @@ -9,7 +9,7 @@ // except according to those terms. use std::os; -use std::io::{stdio, Command}; +use std::old_io::{stdio, Command}; fn main() { let args = os::args(); diff --git a/src/test/run-pass/issue-15149.rs b/src/test/run-pass/issue-15149.rs index bf395b14eb4..1d18f33fd18 100644 --- a/src/test/run-pass/issue-15149.rs +++ b/src/test/run-pass/issue-15149.rs @@ -9,7 +9,7 @@ // except according to those terms. use std::slice::SliceExt; -use std::io::{Command, fs, USER_RWX}; +use std::old_io::{Command, fs, USER_RWX}; use std::os; use std::path::BytesContainer; use std::rand::random; diff --git a/src/test/run-pass/issue-16272.rs b/src/test/run-pass/issue-16272.rs index 8c3d765b5ee..d73ca1b11a5 100644 --- a/src/test/run-pass/issue-16272.rs +++ b/src/test/run-pass/issue-16272.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::{process, Command}; +use std::old_io::{process, Command}; use std::os; fn main() { diff --git a/src/test/run-pass/issue-16671.rs b/src/test/run-pass/issue-16671.rs index e25b3e8e89c..124b0205fae 100644 --- a/src/test/run-pass/issue-16671.rs +++ b/src/test/run-pass/issue-16671.rs @@ -21,7 +21,7 @@ use std::thread::Thread; pub fn main() { - let mut stdin = std::io::stdin(); + let mut stdin = std::old_io::stdin(); Thread::spawn(move|| { let _ = stdin.read_to_end(); }); diff --git a/src/test/run-pass/issue-17121.rs b/src/test/run-pass/issue-17121.rs index f53bedc6dac..2f0b8c9f19b 100644 --- a/src/test/run-pass/issue-17121.rs +++ b/src/test/run-pass/issue-17121.rs @@ -8,10 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::BufReader; -use std::io::BufferedReader; -use std::io::File; -use std::io::IoResult; +use std::old_io::BufReader; +use std::old_io::BufferedReader; +use std::old_io::File; +use std::old_io::IoResult; struct Lexer<R: Reader> { diff --git a/src/test/run-pass/issue-17322.rs b/src/test/run-pass/issue-17322.rs index b50bf442b5d..dd1cfb5e342 100644 --- a/src/test/run-pass/issue-17322.rs +++ b/src/test/run-pass/issue-17322.rs @@ -11,13 +11,13 @@ #![allow(unknown_features)] #![feature(box_syntax)] -use std::io; +use std::old_io; fn f(wr: &mut Writer) { wr.write_str("hello").ok().expect("failed"); } fn main() { - let mut wr = box io::stdout() as Box<Writer + 'static>; + let mut wr = box old_io::stdout() as Box<Writer + 'static>; f(&mut wr); } diff --git a/src/test/run-pass/issue-18619.rs b/src/test/run-pass/issue-18619.rs index a885513611d..6b6296b0bd9 100644 --- a/src/test/run-pass/issue-18619.rs +++ b/src/test/run-pass/issue-18619.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::FileType; +use std::old_io::FileType; pub fn main() { let _ = FileType::RegularFile.clone(); diff --git a/src/test/run-pass/issue-20091.rs b/src/test/run-pass/issue-20091.rs index d653843ba05..3ef63a53a6d 100644 --- a/src/test/run-pass/issue-20091.rs +++ b/src/test/run-pass/issue-20091.rs @@ -10,7 +10,7 @@ // ignore-windows currently windows requires UTF-8 for spawning processes -use std::io::Command; +use std::old_io::Command; use std::os; fn main() { diff --git a/src/test/run-pass/issue-20644.rs b/src/test/run-pass/issue-20644.rs index f74b09a3d24..0d482548cc0 100644 --- a/src/test/run-pass/issue-20644.rs +++ b/src/test/run-pass/issue-20644.rs @@ -16,7 +16,7 @@ use std::iter; use std::os; -use std::io::File; +use std::old_io::File; #[allow(unused)] pub fn parse_summary<R: Reader>(_: R, _: &Path) { diff --git a/src/test/run-pass/issue-20797.rs b/src/test/run-pass/issue-20797.rs index 089b6f31975..049e08d2b94 100644 --- a/src/test/run-pass/issue-20797.rs +++ b/src/test/run-pass/issue-20797.rs @@ -14,9 +14,9 @@ // Regression test for #20797. use std::default::Default; -use std::io::IoResult; -use std::io::fs; -use std::io::fs::PathExtensions; +use std::old_io::IoResult; +use std::old_io::fs; +use std::old_io::fs::PathExtensions; /// A strategy for acquiring more subpaths to walk. pub trait Strategy { diff --git a/src/test/run-pass/issue-2904.rs b/src/test/run-pass/issue-2904.rs index f87eb46d553..27ac538b5b3 100644 --- a/src/test/run-pass/issue-2904.rs +++ b/src/test/run-pass/issue-2904.rs @@ -12,7 +12,7 @@ /// Map representation -use std::io; +use std::old_io; use std::fmt; use square::{bot, wall, rock, lambda, closed_lift, open_lift, earth, empty}; @@ -59,9 +59,9 @@ fn square_from_char(c: char) -> square { } } -fn read_board_grid<rdr:'static + io::Reader>(mut input: rdr) +fn read_board_grid<rdr:'static + old_io::Reader>(mut input: rdr) -> Vec<Vec<square>> { - let mut input: &mut io::Reader = &mut input; + let mut input: &mut old_io::Reader = &mut input; let mut grid = Vec::new(); let mut line = [0; 10]; input.read(&mut line); diff --git a/src/test/run-pass/issue-3026.rs b/src/test/run-pass/issue-3026.rs index cd71bfce274..25663f2605f 100644 --- a/src/test/run-pass/issue-3026.rs +++ b/src/test/run-pass/issue-3026.rs @@ -17,7 +17,8 @@ extern crate collections; use std::collections::HashMap; pub fn main() { + let x; let mut buggy_map: HashMap<uint, &uint> = HashMap::new(); - let x = box 1; + x = box 1; buggy_map.insert(42, &*x); } diff --git a/src/test/run-pass/issue-4333.rs b/src/test/run-pass/issue-4333.rs index fd67b767104..28ab3c3ef12 100644 --- a/src/test/run-pass/issue-4333.rs +++ b/src/test/run-pass/issue-4333.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; +use std::old_io; pub fn main() { - let stdout = &mut io::stdout() as &mut io::Writer; + let stdout = &mut old_io::stdout() as &mut old_io::Writer; stdout.write(b"Hello!"); } diff --git a/src/test/run-pass/issue-4446.rs b/src/test/run-pass/issue-4446.rs index 9c00348ad6a..ec4cd02e9fd 100644 --- a/src/test/run-pass/issue-4446.rs +++ b/src/test/run-pass/issue-4446.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::println; +use std::old_io::println; use std::sync::mpsc::channel; use std::thread::Thread; diff --git a/src/test/run-pass/issue-5988.rs b/src/test/run-pass/issue-5988.rs index cc95b135b27..1ad48d326ea 100644 --- a/src/test/run-pass/issue-5988.rs +++ b/src/test/run-pass/issue-5988.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; +use std::old_io; trait B { fn f(&self); } @@ -19,7 +19,7 @@ trait T : B { struct A; impl<U: T> B for U { - fn f(&self) { io::println("Hey, I'm a T!"); } + fn f(&self) { old_io::println("Hey, I'm a T!"); } } impl T for A { diff --git a/src/test/run-pass/issue-8398.rs b/src/test/run-pass/issue-8398.rs index 185d75743a4..e52e3295c6e 100644 --- a/src/test/run-pass/issue-8398.rs +++ b/src/test/run-pass/issue-8398.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; +use std::old_io; -fn foo(a: &mut io::Writer) { +fn foo(a: &mut old_io::Writer) { a.write(&[]).unwrap(); } diff --git a/src/test/run-pass/issue-9396.rs b/src/test/run-pass/issue-9396.rs index 73355d15a27..a98d1aba04d 100644 --- a/src/test/run-pass/issue-9396.rs +++ b/src/test/run-pass/issue-9396.rs @@ -9,7 +9,7 @@ // except according to those terms. use std::sync::mpsc::{TryRecvError, channel}; -use std::io::timer::Timer; +use std::old_io::timer::Timer; use std::thread::Thread; use std::time::Duration; diff --git a/src/test/run-pass/logging-separate-lines.rs b/src/test/run-pass/logging-separate-lines.rs index 0f13df644a1..44daa52886c 100644 --- a/src/test/run-pass/logging-separate-lines.rs +++ b/src/test/run-pass/logging-separate-lines.rs @@ -15,7 +15,7 @@ #[macro_use] extern crate log; -use std::io::Command; +use std::old_io::Command; use std::os; use std::str; diff --git a/src/test/run-pass/method-mut-self-modifies-mut-slice-lvalue.rs b/src/test/run-pass/method-mut-self-modifies-mut-slice-lvalue.rs index 9ae7f49c75a..76895af099d 100644 --- a/src/test/run-pass/method-mut-self-modifies-mut-slice-lvalue.rs +++ b/src/test/run-pass/method-mut-self-modifies-mut-slice-lvalue.rs @@ -15,7 +15,7 @@ use std::raw; use std::mem; use std::slice; -use std::io::IoResult; +use std::old_io::IoResult; trait MyWriter { fn my_write(&mut self, buf: &[u8]) -> IoResult<()>; diff --git a/src/test/run-pass/out-of-stack-new-thread-no-split.rs b/src/test/run-pass/out-of-stack-new-thread-no-split.rs index ce6604df49b..5d180c3a280 100644 --- a/src/test/run-pass/out-of-stack-new-thread-no-split.rs +++ b/src/test/run-pass/out-of-stack-new-thread-no-split.rs @@ -15,7 +15,7 @@ #![feature(asm)] -use std::io::process::Command; +use std::old_io::process::Command; use std::os; use std::thread::Thread; diff --git a/src/test/run-pass/out-of-stack-no-split.rs b/src/test/run-pass/out-of-stack-no-split.rs index 79926776abf..8178a0d5a6c 100644 --- a/src/test/run-pass/out-of-stack-no-split.rs +++ b/src/test/run-pass/out-of-stack-no-split.rs @@ -16,7 +16,7 @@ #![feature(asm)] -use std::io::process::Command; +use std::old_io::process::Command; use std::os; // lifted from the test module diff --git a/src/test/run-pass/out-of-stack.rs b/src/test/run-pass/out-of-stack.rs index 1594cca89e5..ef77f6e9901 100644 --- a/src/test/run-pass/out-of-stack.rs +++ b/src/test/run-pass/out-of-stack.rs @@ -12,7 +12,7 @@ #![feature(asm)] -use std::io::process::Command; +use std::old_io::process::Command; use std::os; // lifted from the test module diff --git a/src/test/run-pass/process-remove-from-env.rs b/src/test/run-pass/process-remove-from-env.rs index eab9c8a95da..e0fd0a13473 100644 --- a/src/test/run-pass/process-remove-from-env.rs +++ b/src/test/run-pass/process-remove-from-env.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::Command; +use std::old_io::Command; use std::os; #[cfg(all(unix, not(target_os="android")))] diff --git a/src/test/run-pass/process-spawn-with-unicode-params.rs b/src/test/run-pass/process-spawn-with-unicode-params.rs index cceb0bf4d96..5dcaa885e38 100644 --- a/src/test/run-pass/process-spawn-with-unicode-params.rs +++ b/src/test/run-pass/process-spawn-with-unicode-params.rs @@ -16,9 +16,9 @@ // non-ASCII characters. The child process ensures all the strings are // intact. -use std::io; -use std::io::fs; -use std::io::Command; +use std::old_io; +use std::old_io::fs; +use std::old_io::Command; use std::os; use std::path::Path; @@ -49,7 +49,7 @@ fn main() { let child_path = cwd.join(child_filename); // make a separate directory for the child - drop(fs::mkdir(&cwd, io::USER_RWX).is_ok()); + drop(fs::mkdir(&cwd, old_io::USER_RWX).is_ok()); assert!(fs::copy(&my_path, &child_path).is_ok()); let mut my_env = my_env; my_env.push(env); @@ -62,8 +62,8 @@ fn main() { .spawn().unwrap().wait_with_output().unwrap(); // display the output - assert!(io::stdout().write(p.output.as_slice()).is_ok()); - assert!(io::stderr().write(p.error.as_slice()).is_ok()); + assert!(old_io::stdout().write(p.output.as_slice()).is_ok()); + assert!(old_io::stderr().write(p.error.as_slice()).is_ok()); // make sure the child succeeded assert!(p.status.success()); diff --git a/src/test/run-pass/rename-directory.rs b/src/test/run-pass/rename-directory.rs index d610bf09edb..12e4f27a64f 100644 --- a/src/test/run-pass/rename-directory.rs +++ b/src/test/run-pass/rename-directory.rs @@ -14,10 +14,10 @@ extern crate libc; use std::ffi::CString; -use std::io::TempDir; -use std::io::fs::PathExtensions; -use std::io::fs; -use std::io; +use std::old_io::TempDir; +use std::old_io::fs::PathExtensions; +use std::old_io::fs; +use std::old_io; use std::os; fn rename_directory() { @@ -27,7 +27,7 @@ fn rename_directory() { let tmpdir = TempDir::new("rename_directory").ok().expect("rename_directory failed"); let tmpdir = tmpdir.path(); let old_path = tmpdir.join_many(&["foo", "bar", "baz"]); - fs::mkdir_recursive(&old_path, io::USER_RWX); + fs::mkdir_recursive(&old_path, old_io::USER_RWX); let test_file = &old_path.join("temp.txt"); /* Write the temp input file */ @@ -45,7 +45,7 @@ fn rename_directory() { assert_eq!(libc::fclose(ostream), (0u as libc::c_int)); let new_path = tmpdir.join_many(&["quux", "blat"]); - fs::mkdir_recursive(&new_path, io::USER_RWX); + fs::mkdir_recursive(&new_path, old_io::USER_RWX); fs::rename(&old_path, &new_path.join("newdir")); assert!(new_path.join("newdir").is_dir()); assert!(new_path.join_many(&["newdir", "temp.txt"]).exists()); diff --git a/src/test/run-pass/running-with-no-runtime.rs b/src/test/run-pass/running-with-no-runtime.rs index 7b809235e8d..32f9de71d53 100644 --- a/src/test/run-pass/running-with-no-runtime.rs +++ b/src/test/run-pass/running-with-no-runtime.rs @@ -11,7 +11,7 @@ #![feature(start)] use std::ffi; -use std::io::process::{Command, ProcessOutput}; +use std::old_io::process::{Command, ProcessOutput}; use std::os; use std::rt::unwind::try; use std::rt; diff --git a/src/test/run-pass/segfault-no-out-of-stack.rs b/src/test/run-pass/segfault-no-out-of-stack.rs index 6ef33c1a112..160c9f2c9d5 100644 --- a/src/test/run-pass/segfault-no-out-of-stack.rs +++ b/src/test/run-pass/segfault-no-out-of-stack.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::process::Command; +use std::old_io::process::Command; use std::os; fn main() { diff --git a/src/test/run-pass/signal-exit-status.rs b/src/test/run-pass/signal-exit-status.rs index dc72b6b0539..bf500bf0417 100644 --- a/src/test/run-pass/signal-exit-status.rs +++ b/src/test/run-pass/signal-exit-status.rs @@ -11,7 +11,7 @@ // ignore-windows use std::os; -use std::io::process::{Command, ExitSignal, ExitStatus}; +use std::old_io::process::{Command, ExitSignal, ExitStatus}; pub fn main() { let args = os::args(); diff --git a/src/test/run-pass/sigpipe-should-be-ignored.rs b/src/test/run-pass/sigpipe-should-be-ignored.rs index 1804dd2e135..23a92857176 100644 --- a/src/test/run-pass/sigpipe-should-be-ignored.rs +++ b/src/test/run-pass/sigpipe-should-be-ignored.rs @@ -12,8 +12,8 @@ // doesn't die in a ball of fire, but rather it's gracefully handled. use std::os; -use std::io::PipeStream; -use std::io::Command; +use std::old_io::PipeStream; +use std::old_io::Command; fn test() { let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() }; diff --git a/src/test/run-pass/stat.rs b/src/test/run-pass/stat.rs index 250eafa2f49..bf22fc3bd72 100644 --- a/src/test/run-pass/stat.rs +++ b/src/test/run-pass/stat.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::fs::PathExtensions; -use std::io::{File, TempDir}; +use std::old_io::fs::PathExtensions; +use std::old_io::{File, TempDir}; pub fn main() { let dir = TempDir::new_in(&Path::new("."), "").unwrap(); diff --git a/src/test/run-pass/task-stderr.rs b/src/test/run-pass/task-stderr.rs index 5e6247bac93..2bc7a5a88d5 100644 --- a/src/test/run-pass/task-stderr.rs +++ b/src/test/run-pass/task-stderr.rs @@ -12,7 +12,7 @@ #![feature(box_syntax)] use std::sync::mpsc::channel; -use std::io::{ChanReader, ChanWriter}; +use std::old_io::{ChanReader, ChanWriter}; use std::thread; fn main() { diff --git a/src/test/run-pass/tcp-accept-stress.rs b/src/test/run-pass/tcp-accept-stress.rs index c7149fa503b..fbe2309964b 100644 --- a/src/test/run-pass/tcp-accept-stress.rs +++ b/src/test/run-pass/tcp-accept-stress.rs @@ -13,7 +13,7 @@ // quite quickly and it takes a few seconds for the sockets to get // recycled. -use std::io::{TcpListener, Listener, Acceptor, EndOfFile, TcpStream}; +use std::old_io::{TcpListener, Listener, Acceptor, EndOfFile, TcpStream}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::channel; diff --git a/src/test/run-pass/tcp-connect-timeouts.rs b/src/test/run-pass/tcp-connect-timeouts.rs index 17a4b91467c..23c5501b4a4 100644 --- a/src/test/run-pass/tcp-connect-timeouts.rs +++ b/src/test/run-pass/tcp-connect-timeouts.rs @@ -20,9 +20,9 @@ #![allow(unused_imports)] -use std::io::*; -use std::io::test::*; -use std::io; +use std::old_io::*; +use std::old_io::test::*; +use std::old_io; use std::time::Duration; use std::sync::mpsc::channel; use std::thread::Thread; @@ -44,7 +44,7 @@ fn eventual_timeout() { for _ in range(0u, 10000) { match TcpStream::connect_timeout(addr, Duration::milliseconds(100)) { Ok(e) => v.push(e), - Err(ref e) if e.kind == io::TimedOut => return, + Err(ref e) if e.kind == old_io::TimedOut => return, Err(e) => panic!("other error: {}", e), } } diff --git a/src/test/run-pass/tcp-stress.rs b/src/test/run-pass/tcp-stress.rs index 0109d64ad53..e23d1a62225 100644 --- a/src/test/run-pass/tcp-stress.rs +++ b/src/test/run-pass/tcp-stress.rs @@ -17,15 +17,15 @@ extern crate log; extern crate libc; use std::sync::mpsc::channel; -use std::io::net::tcp::{TcpListener, TcpStream}; -use std::io::{Acceptor, Listener}; +use std::old_io::net::tcp::{TcpListener, TcpStream}; +use std::old_io::{Acceptor, Listener}; use std::thread::{Builder, Thread}; use std::time::Duration; fn main() { // This test has a chance to time out, try to not let it time out Thread::spawn(move|| -> () { - use std::io::timer; + use std::old_io::timer; timer::sleep(Duration::milliseconds(30 * 1000)); println!("timed out!"); unsafe { libc::exit(1) } diff --git a/src/test/run-pass/tempfile.rs b/src/test/run-pass/tempfile.rs index b931bd9609c..6695920723a 100644 --- a/src/test/run-pass/tempfile.rs +++ b/src/test/run-pass/tempfile.rs @@ -18,9 +18,9 @@ // they're in a different location than before. Hence, these tests are all run // serially here. -use std::io::fs::PathExtensions; -use std::io::{fs, TempDir}; -use std::io; +use std::old_io::fs::PathExtensions; +use std::old_io::{fs, TempDir}; +use std::old_io; use std::os; use std::sync::mpsc::channel; use std::thread::Thread; @@ -127,17 +127,17 @@ fn recursive_mkdir_rel() { let cwd = os::getcwd().unwrap(); println!("recursive_mkdir_rel: Making: {} in cwd {} [{}]", path.display(), cwd.display(), path.exists()); - fs::mkdir_recursive(&path, io::USER_RWX); + fs::mkdir_recursive(&path, old_io::USER_RWX); assert!(path.is_dir()); - fs::mkdir_recursive(&path, io::USER_RWX); + fs::mkdir_recursive(&path, old_io::USER_RWX); assert!(path.is_dir()); } fn recursive_mkdir_dot() { let dot = Path::new("."); - fs::mkdir_recursive(&dot, io::USER_RWX); + fs::mkdir_recursive(&dot, old_io::USER_RWX); let dotdot = Path::new(".."); - fs::mkdir_recursive(&dotdot, io::USER_RWX); + fs::mkdir_recursive(&dotdot, old_io::USER_RWX); } fn recursive_mkdir_rel_2() { @@ -145,20 +145,20 @@ fn recursive_mkdir_rel_2() { let cwd = os::getcwd().unwrap(); println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{}]", path.display(), cwd.display(), path.exists()); - fs::mkdir_recursive(&path, io::USER_RWX); + fs::mkdir_recursive(&path, old_io::USER_RWX); assert!(path.is_dir()); assert!(path.dir_path().is_dir()); let path2 = Path::new("quux/blat"); println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(), cwd.display()); - fs::mkdir_recursive(&path2, io::USER_RWX); + fs::mkdir_recursive(&path2, old_io::USER_RWX); assert!(path2.is_dir()); assert!(path2.dir_path().is_dir()); } // Ideally this would be in core, but needs TempFile pub fn test_rmdir_recursive_ok() { - let rwx = io::USER_RWX; + let rwx = old_io::USER_RWX; let tmpdir = TempDir::new("test").ok().expect("test_rmdir_recursive_ok: \ couldn't create temp dir"); diff --git a/src/test/run-pass/trait-coercion.rs b/src/test/run-pass/trait-coercion.rs index 0d4a05bed7f..11eaa4c9962 100644 --- a/src/test/run-pass/trait-coercion.rs +++ b/src/test/run-pass/trait-coercion.rs @@ -11,7 +11,7 @@ #![allow(unknown_features)] #![feature(box_syntax)] -use std::io; +use std::old_io; trait Trait { fn f(&self); @@ -41,7 +41,7 @@ pub fn main() { let c: &Trait = &a; c.f(); - let out = io::stdout(); + let out = old_io::stdout(); foo(box out); } diff --git a/src/test/run-pass/wait-forked-but-failed-child.rs b/src/test/run-pass/wait-forked-but-failed-child.rs index ffeb4be349a..4e5d61f166c 100644 --- a/src/test/run-pass/wait-forked-but-failed-child.rs +++ b/src/test/run-pass/wait-forked-but-failed-child.rs @@ -10,7 +10,7 @@ extern crate libc; -use std::io::process::Command; +use std::old_io::process::Command; use libc::funcs::posix88::unistd; |
