From 3819c222a84a9c21992b81939420643c0a969e7d Mon Sep 17 00:00:00 2001 From: Alexis Date: Thu, 15 Jan 2015 21:18:57 -0500 Subject: add a section on performance to collection docs --- src/libstd/collections/mod.rs | 54 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/collections/mod.rs b/src/libstd/collections/mod.rs index 71ab89027ff..8d40a35075a 100644 --- a/src/libstd/collections/mod.rs +++ b/src/libstd/collections/mod.rs @@ -49,8 +49,8 @@ //! * You want a double-ended queue (deque). //! //! ### Use a `DList` when: -//! * You want a `Vec` or `RingBuf` of unknown size, and can't tolerate inconsistent -//! performance during insertions. +//! * You want a `Vec` or `RingBuf` of unknown size, and can't tolerate amortization. +//! * You want to efficiently split and append lists. //! * You are *absolutely* certain you *really*, *truly*, want a doubly linked list. //! //! ### Use a `HashMap` when: @@ -85,6 +85,56 @@ //! or "most important" one at any given time. //! * You want a priority queue. //! +//! # Performance +//! +//! Choosing the right collection for the job requires an understanding of what each collection +//! is good at. Here we briefly summarize the performance of different collections for certain +//! important operations. For further details, see each type's documentation. +//! +//! Throughout the documentation, we will follow a few conventions. For all operations, +//! the collection's size is denoted by n. If another collection is involved in the operation, it +//! contains m elements. Operations which have an *amortized* cost are suffixed with a `*`. +//! Operations with an *expected* cost are suffixed with a `~`. +//! +//! All amortized costs are for the potential need to resize when capacity is exhausted. +//! If a resize occurs it will take O(n) time. Our collections never automatically shrink, +//! so removal operations aren't amortized. Over a sufficiently large series of +//! operations, the average cost per operation will deterministically equal the given cost. +//! +//! Only HashMap has expected costs, due to the probabilistic nature of hashing. It is +//! theoretically possible, though very unlikely, for HashMap to experience worse performance. +//! +//! ## Sequences +//! +//! | | get(i) | insert(i) | remove(i) | append | split_off(i) | +//! |---------|----------------|-----------------|----------------|--------|----------------| +//! | Vec | O(1) | O(n-i)* | O(n-i) | O(m)* | O(n-i) | +//! | RingBuf | O(1) | O(min(i, n-i))* | O(min(i, n-i)) | O(m)* | O(min(i, n-i)) | +//! | DList | O(min(i, n-i)) | O(min(i, n-i)) | O(min(i, n-i)) | O(1) | O(min(i, n-i)) | +//! | Bitv | O(1) | O(n-i)* | O(n-i) | O(m)* | O(n-i) | +//! +//! Note that where ties occur, Vec is generally going to be faster than RingBuf, and RingBuf +//! is generally going to be faster than DList. Bitv is not a general purpose collection, and +//! therefore cannot reasonably be compared. +//! +//! ## Maps +//! +//! For Sets, all operations have the cost of the equivalent Map operation. For BitvSet, +//! refer to VecMap. +//! +//! | | get | insert | remove | predecessor | +//! |----------|-----------|----------|----------|-------------| +//! | HashMap | O(1)~ | O(1)~* | O(1)~ | N/A | +//! | BTreeMap | O(log n) | O(log n) | O(log n) | O(log n) | +//! | VecMap | O(1) | O(1)? | O(1) | O(n) | +//! +//! Note that VecMap is *incredibly* inefficient in terms of space. The O(1) insertion time +//! assumes space for the element is already allocated. Otherwise, a large key may require a +//! massive reallocation, with no direct relation to the number of elements in the collection. +//! VecMap should only be seriously considered for small keys. +//! +//! Note also that BTreeMap's precise preformance depends on the value of B. +//! //! # Correct and Efficient Usage of Collections //! //! Of course, knowing which collection is the right one for the job doesn't instantly -- cgit 1.4.1-3-g733a5 From 618cf5f8d79dc92bcbdbe2c0e91d681e2e685cd7 Mon Sep 17 00:00:00 2001 From: Simonas Kazlauskas Date: Sat, 17 Jan 2015 23:44:04 +0200 Subject: Refine wording of Thread::panicking MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previous wording wasn’t clear about its actual behaviour. It could be interpreted as answering either: * Can current thread panic? * Is current thread unwinding because of panic? --- src/libstd/rt/unwind.rs | 2 +- src/libstd/thread.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/rt/unwind.rs b/src/libstd/rt/unwind.rs index 73b8f104c23..b313a5312bc 100644 --- a/src/libstd/rt/unwind.rs +++ b/src/libstd/rt/unwind.rs @@ -152,7 +152,7 @@ pub unsafe fn try(f: F) -> Result<(), Box> { } } -/// Test if the current thread is currently panicking. +/// Determines whether the current thread is unwinding because of panic. pub fn panicking() -> bool { PANICKING.with(|s| s.get()) } diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index 932556fe1a6..bcd4dee63b0 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -382,7 +382,7 @@ impl Thread { unsafe { imp::yield_now() } } - /// Determines whether the current thread is panicking. + /// Determines whether the current thread is unwinding because of panic. #[inline] #[stable] pub fn panicking() -> bool { -- cgit 1.4.1-3-g733a5 From 2c2480df5d340f4c7b2deeef0177e4fd22f2b03a Mon Sep 17 00:00:00 2001 From: we Date: Mon, 19 Jan 2015 08:27:09 +0300 Subject: Replace `0 as *const/mut T` with `ptr::null/null_mut()` --- src/liballoc/heap.rs | 2 +- src/liblog/lib.rs | 5 +++-- src/librustc_llvm/diagnostic.rs | 9 +++++---- src/librustc_llvm/lib.rs | 21 ++++++++++----------- src/librustc_trans/trans/type_.rs | 5 +++-- src/libstd/io/stdio.rs | 3 ++- src/libstd/sync/mpsc/mpsc_queue.rs | 3 ++- src/libstd/sync/mpsc/select.rs | 17 +++++++++-------- src/libstd/sync/mpsc/spsc_queue.rs | 5 +++-- src/libstd/sync/mpsc/sync.rs | 17 +++++++++-------- src/libstd/sys/common/helper_thread.rs | 3 ++- src/libstd/sys/unix/backtrace.rs | 2 +- src/libstd/sys/unix/condvar.rs | 3 ++- src/libstd/sys/unix/fs.rs | 3 ++- src/libstd/sys/unix/os.rs | 2 +- src/libstd/sys/unix/process.rs | 2 +- src/libstd/sys/windows/backtrace.rs | 10 +++++----- src/libstd/sys/windows/thread_local.rs | 4 ++-- src/libstd/thread_local/mod.rs | 4 ++-- 19 files changed, 65 insertions(+), 55 deletions(-) (limited to 'src/libstd') diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs index b7bc1b47646..d3041eaa884 100644 --- a/src/liballoc/heap.rs +++ b/src/liballoc/heap.rs @@ -280,7 +280,7 @@ mod imp { if align <= MIN_ALIGN { libc::malloc(size as libc::size_t) as *mut u8 } else { - let mut out = 0 as *mut libc::c_void; + let mut out = ptr::null(); let ret = posix_memalign(&mut out, align as libc::size_t, size as libc::size_t); diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index a166dc369cb..433b8aa6941 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -179,6 +179,7 @@ use std::io::LineBufferedWriter; use std::io; use std::mem; use std::os; +use std::ptr; use std::rt; use std::slice; use std::sync::{Once, ONCE_INIT}; @@ -436,11 +437,11 @@ fn init() { assert!(!DIRECTIVES.is_null()); let _directives: Box> = mem::transmute(DIRECTIVES); - DIRECTIVES = 0 as *const Vec; + DIRECTIVES = ptr::null(); if !FILTER.is_null() { let _filter: Box = mem::transmute(FILTER); - FILTER = 0 as *const _; + FILTER = ptr::null(); } }); } diff --git a/src/librustc_llvm/diagnostic.rs b/src/librustc_llvm/diagnostic.rs index 464f9f98e7f..db2a569cdef 100644 --- a/src/librustc_llvm/diagnostic.rs +++ b/src/librustc_llvm/diagnostic.rs @@ -14,6 +14,7 @@ pub use self::OptimizationDiagnosticKind::*; pub use self::Diagnostic::*; use libc::c_char; +use std::ptr; use {ValueRef, TwineRef, DebugLocRef, DiagnosticInfoRef}; @@ -52,10 +53,10 @@ impl OptimizationDiagnostic { let mut opt = OptimizationDiagnostic { kind: kind, - pass_name: 0 as *const c_char, - function: 0 as ValueRef, - debug_loc: 0 as DebugLocRef, - message: 0 as TwineRef, + pass_name: ptr::null(), + function: ptr::null_mut(), + debug_loc: ptr::null_mut(), + message: ptr::null_mut(), }; super::LLVMUnpackOptimizationDiagnostic(di, diff --git a/src/librustc_llvm/lib.rs b/src/librustc_llvm/lib.rs index 3edb1ec48a0..03021b7700c 100644 --- a/src/librustc_llvm/lib.rs +++ b/src/librustc_llvm/lib.rs @@ -51,7 +51,7 @@ pub use self::Linkage::*; use std::ffi::CString; use std::cell::RefCell; -use std::{raw, mem}; +use std::{raw, mem, ptr}; use libc::{c_uint, c_ushort, uint64_t, c_int, size_t, c_char}; use libc::{c_longlong, c_ulonglong, c_void}; use debuginfo::{DIBuilderRef, DIDescriptor, @@ -2260,19 +2260,18 @@ pub unsafe fn static_link_hack_this_sucks() { LLVMInitializePowerPCAsmPrinter(); LLVMInitializePowerPCAsmParser(); - LLVMRustSetLLVMOptions(0 as c_int, - 0 as *const _); + LLVMRustSetLLVMOptions(0 as c_int, ptr::null()); - LLVMPassManagerBuilderPopulateModulePassManager(0 as *mut _, 0 as *mut _); - LLVMPassManagerBuilderPopulateLTOPassManager(0 as *mut _, 0 as *mut _, False, False); - LLVMPassManagerBuilderPopulateFunctionPassManager(0 as *mut _, 0 as *mut _); - LLVMPassManagerBuilderSetOptLevel(0 as *mut _, 0 as c_uint); - LLVMPassManagerBuilderUseInlinerWithThreshold(0 as *mut _, 0 as c_uint); - LLVMWriteBitcodeToFile(0 as *mut _, 0 as *const _); + LLVMPassManagerBuilderPopulateModulePassManager(ptr::null_mut(), ptr::null_mut()); + LLVMPassManagerBuilderPopulateLTOPassManager(ptr::null_mut(), ptr::null_mut(), False, False); + LLVMPassManagerBuilderPopulateFunctionPassManager(ptr::null_mut(), ptr::null_mut()); + LLVMPassManagerBuilderSetOptLevel(ptr::null_mut(), 0 as c_uint); + LLVMPassManagerBuilderUseInlinerWithThreshold(ptr::null_mut(), 0 as c_uint); + LLVMWriteBitcodeToFile(ptr::null_mut(), ptr::null()); LLVMPassManagerBuilderCreate(); - LLVMPassManagerBuilderDispose(0 as *mut _); + LLVMPassManagerBuilderDispose(ptr::null_mut()); - LLVMRustLinkInExternalBitcode(0 as *mut _, 0 as *const _, 0 as size_t); + LLVMRustLinkInExternalBitcode(ptr::null_mut(), ptr::null(), 0 as size_t); LLVMLinkInMCJIT(); LLVMLinkInInterpreter(); diff --git a/src/librustc_trans/trans/type_.rs b/src/librustc_trans/trans/type_.rs index 9cae142c03a..469d351f61a 100644 --- a/src/librustc_trans/trans/type_.rs +++ b/src/librustc_trans/trans/type_.rs @@ -21,6 +21,7 @@ use syntax::ast; use std::ffi::CString; use std::mem; +use std::ptr; use std::cell::RefCell; use std::iter::repeat; @@ -296,7 +297,7 @@ impl Type { if n_elts == 0 { return Vec::new(); } - let mut elts: Vec<_> = repeat(Type { rf: 0 as TypeRef }).take(n_elts).collect(); + let mut elts: Vec<_> = repeat(Type { rf: ptr::null_mut() }).take(n_elts).collect(); llvm::LLVMGetStructElementTypes(self.to_ref(), elts.as_mut_ptr() as *mut TypeRef); elts @@ -310,7 +311,7 @@ impl Type { pub fn func_params(&self) -> Vec { unsafe { let n_args = llvm::LLVMCountParamTypes(self.to_ref()) as uint; - let mut args: Vec<_> = repeat(Type { rf: 0 as TypeRef }).take(n_args).collect(); + let mut args: Vec<_> = repeat(Type { rf: ptr::null_mut() }).take(n_args).collect(); llvm::LLVMGetParamTypes(self.to_ref(), args.as_mut_ptr() as *mut TypeRef); args diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 9ee2f5705b8..a5664b9f013 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -40,6 +40,7 @@ use mem; use option::Option; use option::Option::{Some, None}; use ops::{Deref, DerefMut, FnOnce}; +use ptr; use result::Result::{Ok, Err}; use rt; use slice::SliceExt; @@ -238,7 +239,7 @@ pub fn stdin() -> StdinReader { // Make sure to free it at exit rt::at_exit(|| { mem::transmute::<_, Box>(STDIN); - STDIN = 0 as *const _; + STDIN = ptr::null(); }); }); diff --git a/src/libstd/sync/mpsc/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs index 83de98fdbff..ea81ed30a9c 100644 --- a/src/libstd/sync/mpsc/mpsc_queue.rs +++ b/src/libstd/sync/mpsc/mpsc_queue.rs @@ -46,6 +46,7 @@ use core::prelude::*; use alloc::boxed::Box; use core::mem; +use core::ptr; use core::cell::UnsafeCell; use sync::atomic::{AtomicPtr, Ordering}; @@ -82,7 +83,7 @@ unsafe impl Sync for Queue { } impl Node { unsafe fn new(v: Option) -> *mut Node { mem::transmute(box Node { - next: AtomicPtr::new(0 as *mut Node), + next: AtomicPtr::new(ptr::null_mut()), value: v, }) } diff --git a/src/libstd/sync/mpsc/select.rs b/src/libstd/sync/mpsc/select.rs index 62a7b823ec8..3331411eee7 100644 --- a/src/libstd/sync/mpsc/select.rs +++ b/src/libstd/sync/mpsc/select.rs @@ -59,6 +59,7 @@ use core::prelude::*; use core::cell::Cell; use core::marker; use core::mem; +use core::ptr; use core::uint; use sync::mpsc::{Receiver, RecvError}; @@ -130,8 +131,8 @@ impl Select { pub fn new() -> Select { Select { marker1: marker::NoSend, - head: 0 as *mut Handle<'static, ()>, - tail: 0 as *mut Handle<'static, ()>, + head: ptr::null_mut(), + tail: ptr::null_mut(), next_id: Cell::new(1), } } @@ -144,8 +145,8 @@ impl Select { #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn new() -> Select { Select { - head: 0 as *mut Handle<'static, ()>, - tail: 0 as *mut Handle<'static, ()>, + head: ptr::null_mut(), + tail: ptr::null_mut(), next_id: Cell::new(1), } } @@ -159,8 +160,8 @@ impl Select { Handle { id: id, selector: self, - next: 0 as *mut Handle<'static, ()>, - prev: 0 as *mut Handle<'static, ()>, + next: ptr::null_mut(), + prev: ptr::null_mut(), added: false, rx: rx, packet: rx, @@ -325,8 +326,8 @@ impl<'rx, T: Send> Handle<'rx, T> { (*self.next).prev = self.prev; } - self.next = 0 as *mut Handle<'static, ()>; - self.prev = 0 as *mut Handle<'static, ()>; + self.next = ptr::null_mut(); + self.prev = ptr::null_mut(); self.added = false; } diff --git a/src/libstd/sync/mpsc/spsc_queue.rs b/src/libstd/sync/mpsc/spsc_queue.rs index 34fd6bb70dc..8cd88cedf6b 100644 --- a/src/libstd/sync/mpsc/spsc_queue.rs +++ b/src/libstd/sync/mpsc/spsc_queue.rs @@ -39,6 +39,7 @@ use core::prelude::*; use alloc::boxed::Box; use core::mem; +use core::ptr; use core::cell::UnsafeCell; use sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; @@ -82,7 +83,7 @@ impl Node { unsafe { mem::transmute(box Node { value: None, - next: AtomicPtr::new(0 as *mut Node), + next: AtomicPtr::new(ptr::null_mut::>()), }) } } @@ -131,7 +132,7 @@ impl Queue { let n = self.alloc(); assert!((*n).value.is_none()); (*n).value = Some(t); - (*n).next.store(0 as *mut Node, Ordering::Relaxed); + (*n).next.store(ptr::null_mut(), Ordering::Relaxed); (**self.head.get()).next.store(n, Ordering::Release); *self.head.get() = n; } diff --git a/src/libstd/sync/mpsc/sync.rs b/src/libstd/sync/mpsc/sync.rs index 30304dffb75..d38f14a9130 100644 --- a/src/libstd/sync/mpsc/sync.rs +++ b/src/libstd/sync/mpsc/sync.rs @@ -40,6 +40,7 @@ use self::Blocker::*; use vec::Vec; use core::mem; +use core::ptr; use sync::atomic::{Ordering, AtomicUsize}; use sync::mpsc::blocking::{self, WaitToken, SignalToken}; @@ -145,8 +146,8 @@ impl Packet { cap: cap, canceled: None, queue: Queue { - head: 0 as *mut Node, - tail: 0 as *mut Node, + head: ptr::null_mut(), + tail: ptr::null_mut(), }, buf: Buffer { buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(), @@ -160,7 +161,7 @@ impl Packet { // wait until a send slot is available, returning locked access to // the channel state. fn acquire_send_slot(&self) -> MutexGuard> { - let mut node = Node { token: None, next: 0 as *mut Node }; + let mut node = Node { token: None, next: ptr::null_mut() }; loop { let mut guard = self.lock.lock().unwrap(); // are we ready to go? @@ -343,8 +344,8 @@ impl Packet { Vec::new() }; let mut queue = mem::replace(&mut guard.queue, Queue { - head: 0 as *mut Node, - tail: 0 as *mut Node, + head: ptr::null_mut(), + tail: ptr::null_mut(), }); let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) { @@ -453,7 +454,7 @@ impl Queue { fn enqueue(&mut self, node: &mut Node) -> WaitToken { let (wait_token, signal_token) = blocking::tokens(); node.token = Some(signal_token); - node.next = 0 as *mut Node; + node.next = ptr::null_mut(); if self.tail.is_null() { self.head = node as *mut Node; @@ -475,10 +476,10 @@ impl Queue { let node = self.head; self.head = unsafe { (*node).next }; if self.head.is_null() { - self.tail = 0 as *mut Node; + self.tail = ptr::null_mut(); } unsafe { - (*node).next = 0 as *mut Node; + (*node).next = ptr::null_mut(); Some((*node).token.take().unwrap()) } } diff --git a/src/libstd/sys/common/helper_thread.rs b/src/libstd/sys/common/helper_thread.rs index f940b6ed368..6f6179a436e 100644 --- a/src/libstd/sys/common/helper_thread.rs +++ b/src/libstd/sys/common/helper_thread.rs @@ -24,6 +24,7 @@ use prelude::v1::*; use cell::UnsafeCell; use mem; +use ptr; use rt; use sync::{StaticMutex, StaticCondvar}; use sync::mpsc::{channel, Sender, Receiver}; @@ -132,7 +133,7 @@ impl Helper { // Close the channel by destroying it let chan: Box> = mem::transmute(*self.chan.get()); - *self.chan.get() = 0 as *mut Sender; + *self.chan.get() = ptr::null_mut(); drop(chan); helper_signal::signal(*self.signal.get() as helper_signal::signal); diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index 7164931c55a..3340a018d94 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -353,7 +353,7 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> { if state.is_null() { return output(w, idx, addr, None) } - let mut data = 0 as *const libc::c_char; + let mut data = ptr::null(); let data_addr = &mut data as *mut *const libc::c_char; let ret = unsafe { backtrace_syminfo(state, addr as libc::uintptr_t, diff --git a/src/libstd/sys/unix/condvar.rs b/src/libstd/sys/unix/condvar.rs index 85a65bbef50..3bc41473152 100644 --- a/src/libstd/sys/unix/condvar.rs +++ b/src/libstd/sys/unix/condvar.rs @@ -10,6 +10,7 @@ use cell::UnsafeCell; use libc; +use ptr; use std::option::Option::{Some, None}; use sys::mutex::{self, Mutex}; use sys::time; @@ -62,7 +63,7 @@ impl Condvar { // time. let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 }; let stable_now = time::SteadyTime::now(); - let r = ffi::gettimeofday(&mut sys_now, 0 as *mut _); + let r = ffi::gettimeofday(&mut sys_now, ptr::null_mut()); debug_assert_eq!(r, 0); let seconds = NumCast::from(dur.num_seconds()); diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index c53f9d22790..dd478347f81 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -19,6 +19,7 @@ use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append}; use io; use libc::{self, c_int, c_void}; use mem; +use ptr; use sys::retry; use sys_common::{keep_going, eof, mkerr_libc}; @@ -207,7 +208,7 @@ pub fn readdir(p: &Path) -> IoResult> { if dir_ptr as uint != 0 { let mut paths = vec!(); - let mut entry_ptr = 0 as *mut dirent_t; + let mut entry_ptr = ptr::null_mut(); while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } { if entry_ptr.is_null() { break } paths.push(unsafe { diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index 175c4e2e353..2c25af055ee 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -143,7 +143,7 @@ pub unsafe fn get_env_pairs() -> Vec> { os::last_os_error()); } let mut result = Vec::new(); - while *environ != 0 as *const _ { + while *environ != ptr::null() { let env_pair = ffi::c_str_to_bytes(&*environ).to_vec(); result.push(env_pair); environ = environ.offset(1); diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs index 36bf696dba5..0eab27de43a 100644 --- a/src/libstd/sys/unix/process.rs +++ b/src/libstd/sys/unix/process.rs @@ -251,7 +251,7 @@ impl Process { fn setgroups(ngroups: libc::c_int, ptr: *const libc::c_void) -> libc::c_int; } - let _ = setgroups(0, 0 as *const libc::c_void); + let _ = setgroups(0, ptr::null()); if libc::setuid(u as libc::uid_t) != 0 { fail(&mut output); diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index ee2dd14955b..ce6af9fab8b 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -327,7 +327,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> { let image = arch::init_frame(&mut frame, &context); // Initialize this process's symbols - let ret = SymInitialize(process, 0 as *mut libc::c_void, libc::TRUE); + let ret = SymInitialize(process, ptr::null_mut(), libc::TRUE); if ret != libc::TRUE { return Ok(()) } let _c = Cleanup { handle: process, SymCleanup: SymCleanup }; @@ -335,10 +335,10 @@ pub fn write(w: &mut Writer) -> IoResult<()> { let mut i = 0i; try!(write!(w, "stack backtrace:\n")); while StackWalk64(image, process, thread, &mut frame, &mut context, - 0 as *mut libc::c_void, - 0 as *mut libc::c_void, - 0 as *mut libc::c_void, - 0 as *mut libc::c_void) == libc::TRUE{ + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut()) == libc::TRUE{ let addr = frame.AddrPC.Offset; if addr == frame.AddrReturn.Offset || addr == 0 || frame.AddrReturn.Offset == 0 { break } diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs index d371023f218..83c116e9b05 100644 --- a/src/libstd/sys/windows/thread_local.rs +++ b/src/libstd/sys/windows/thread_local.rs @@ -137,7 +137,7 @@ unsafe fn init_dtors() { rt::at_exit(move|| { DTOR_LOCK.lock(); let dtors = DTORS; - DTORS = 0 as *mut _; + DTORS = ptr::null_mut(); mem::transmute::<_, Box>>(dtors); assert!(DTORS.is_null()); // can't re-init after destructing DTOR_LOCK.unlock(); @@ -250,7 +250,7 @@ unsafe fn run_dtors() { for &(key, dtor) in dtors.iter() { let ptr = TlsGetValue(key); if !ptr.is_null() { - TlsSetValue(key, 0 as *mut _); + TlsSetValue(key, ptr::null_mut()); dtor(ptr as *mut _); any_run = true; } diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index e7c4e4ccdfb..cd2a5134e3c 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -425,7 +425,7 @@ mod imp { dtor(ptr); } ptr = DTORS.get(); - DTORS.set(0 as *mut _); + DTORS.set(ptr::null_mut()); } } } @@ -522,7 +522,7 @@ mod imp { let key = ptr.key; key.os.set(1 as *mut u8); drop(ptr); - key.os.set(0 as *mut u8); + key.os.set(ptr::null_mut()); } } -- cgit 1.4.1-3-g733a5 From abccfa4018a407bbe80e8acd0f83c023664ea49a Mon Sep 17 00:00:00 2001 From: Peter Atashian Date: Mon, 19 Jan 2015 05:55:15 -0500 Subject: Impl Send for Timer on Windows Fixes #20943 Signed-off-by: Peter Atashian --- src/libstd/io/timer.rs | 6 ++++++ src/libstd/sys/windows/timer.rs | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) (limited to 'src/libstd') diff --git a/src/libstd/io/timer.rs b/src/libstd/io/timer.rs index 844a97dea2d..68ae7d0ff20 100644 --- a/src/libstd/io/timer.rs +++ b/src/libstd/io/timer.rs @@ -227,6 +227,12 @@ mod test { use thread::Thread; use time::Duration; + #[test] + fn test_timer_send() { + let mut timer = Timer::new().unwrap(); + Thread::spawn(move || timer.sleep(Duration::milliseconds(1))); + } + #[test] fn test_io_timer_sleep_simple() { let mut timer = Timer::new().unwrap(); diff --git a/src/libstd/sys/windows/timer.rs b/src/libstd/sys/windows/timer.rs index 1ae3979cd9a..12b4e56bf52 100644 --- a/src/libstd/sys/windows/timer.rs +++ b/src/libstd/sys/windows/timer.rs @@ -48,9 +48,9 @@ pub enum Req { RemoveTimer(libc::HANDLE, Sender<()>), } +unsafe impl Send for Timer {} unsafe impl Send for Req {} - fn helper(input: libc::HANDLE, messages: Receiver, _: ()) { let mut objs = vec![input]; let mut chans = vec![]; -- cgit 1.4.1-3-g733a5 From 49684850bedcef007a2949c97872606d1d6dc325 Mon Sep 17 00:00:00 2001 From: Jorge Aparicio Date: Mon, 19 Jan 2015 11:07:13 -0500 Subject: remove unnecessary parentheses from range notation --- src/libcollections/bit.rs | 2 +- src/libcollections/vec.rs | 4 ++-- src/libcore/slice.rs | 8 ++++---- src/libcore/str/mod.rs | 2 +- src/libcoretest/iter.rs | 2 +- src/libgetopts/lib.rs | 2 +- src/libregex/parse.rs | 2 +- src/librustc/metadata/decoder.rs | 2 +- src/librustc/metadata/tydecode.rs | 2 +- src/librustc/middle/check_match.rs | 2 +- src/librustc/util/ppaux.rs | 6 +++--- src/librustc_back/sha2.rs | 2 +- src/librustc_resolve/lib.rs | 6 +++--- src/librustc_trans/back/link.rs | 2 +- src/librustc_trans/back/lto.rs | 4 ++-- src/librustc_trans/save/mod.rs | 2 +- src/librustc_trans/trans/_match.rs | 4 ++-- src/librustc_trans/trans/cabi_x86_64.rs | 2 +- src/librustc_trans/trans/debuginfo.rs | 4 ++-- src/librustdoc/html/format.rs | 2 +- src/librustdoc/html/render.rs | 12 ++++++------ src/libserialize/json.rs | 4 ++-- src/libstd/io/buffered.rs | 4 ++-- src/libstd/io/mem.rs | 4 ++-- src/libstd/io/mod.rs | 2 +- src/libstd/path/mod.rs | 2 +- src/libstd/path/posix.rs | 10 +++++----- src/libstd/path/windows.rs | 14 +++++++------- src/libstd/sys/windows/backtrace.rs | 2 +- src/libsyntax/ast_map/mod.rs | 2 +- src/libsyntax/diagnostic.rs | 2 +- src/libsyntax/parse/lexer/comments.rs | 4 ++-- src/libterm/terminfo/parser/compiled.rs | 4 ++-- src/test/bench/shootout-fannkuch-redux.rs | 2 +- src/test/bench/shootout-fasta.rs | 2 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 4 ++-- src/test/compile-fail/range-1.rs | 2 +- src/test/compile-fail/range-2.rs | 2 +- 38 files changed, 70 insertions(+), 70 deletions(-) (limited to 'src/libstd') diff --git a/src/libcollections/bit.rs b/src/libcollections/bit.rs index efd056b0d66..13e7e88d516 100644 --- a/src/libcollections/bit.rs +++ b/src/libcollections/bit.rs @@ -330,7 +330,7 @@ impl Bitv { if extra_bytes > 0 { let mut last_word = 0u32; - for (i, &byte) in bytes[(complete_words*4)..].iter().enumerate() { + for (i, &byte) in bytes[complete_words*4..].iter().enumerate() { last_word |= (reverse_bits(byte) as u32) << (i * 8); } bitv.storage.push(last_word); diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 689d96b4b29..27232007d92 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -2158,7 +2158,7 @@ mod tests { #[should_fail] fn test_slice_out_of_bounds_1() { let x: Vec = vec![1, 2, 3, 4, 5]; - &x[(-1)..]; + &x[-1..]; } #[test] @@ -2172,7 +2172,7 @@ mod tests { #[should_fail] fn test_slice_out_of_bounds_3() { let x: Vec = vec![1, 2, 3, 4, 5]; - &x[(-1)..4]; + &x[-1..4]; } #[test] diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 22da168911d..4c97472c001 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -240,7 +240,7 @@ impl SliceExt for [T] { #[inline] fn init(&self) -> &[T] { - &self[..(self.len() - 1)] + &self[..self.len() - 1] } #[inline] @@ -449,7 +449,7 @@ impl SliceExt for [T] { #[inline] fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq { let (m, n) = (self.len(), needle.len()); - m >= n && needle == &self[(m-n)..] + m >= n && needle == &self[m-n..] } #[unstable] @@ -973,7 +973,7 @@ impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool { None => self.finish(), Some(idx) => { let ret = Some(&self.v[..idx]); - self.v = &self.v[(idx + 1)..]; + self.v = &self.v[idx + 1..]; ret } } @@ -998,7 +998,7 @@ impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> boo match self.v.iter().rposition(|x| (self.pred)(x)) { None => self.finish(), Some(idx) => { - let ret = Some(&self.v[(idx + 1)..]); + let ret = Some(&self.v[idx + 1..]); self.v = &self.v[..idx]; ret } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index d9cf6dc086d..a54d8570795 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1418,7 +1418,7 @@ impl StrExt for str { #[inline] fn ends_with(&self, needle: &str) -> bool { let (m, n) = (self.len(), needle.len()); - m >= n && needle.as_bytes() == &self.as_bytes()[(m-n)..] + m >= n && needle.as_bytes() == &self.as_bytes()[m-n..] } #[inline] diff --git a/src/libcoretest/iter.rs b/src/libcoretest/iter.rs index 26819bf9209..4bbbde6b48c 100644 --- a/src/libcoretest/iter.rs +++ b/src/libcoretest/iter.rs @@ -585,7 +585,7 @@ fn check_randacc_iter(a: T, len: uint) where fn test_double_ended_flat_map() { let u = [0u,1]; let v = [5u,6,7,8]; - let mut it = u.iter().flat_map(|x| v[(*x)..v.len()].iter()); + let mut it = u.iter().flat_map(|x| v[*x..v.len()].iter()); assert_eq!(it.next_back().unwrap(), &8); assert_eq!(it.next().unwrap(), &5); assert_eq!(it.next_back().unwrap(), &7); diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index c2114d4c6df..86dad55a318 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -893,7 +893,7 @@ fn each_split_within(ss: &str, lim: uint, mut it: F) -> bool where (B, Cr, UnderLim) => { B } (B, Cr, OverLim) if (i - last_start + 1) > lim => panic!("word starting with {} longer than limit!", - &ss[last_start..(i + 1)]), + &ss[last_start..i + 1]), (B, Cr, OverLim) => { *cont = it(&ss[slice_start..last_end]); slice_start = last_start; diff --git a/src/libregex/parse.rs b/src/libregex/parse.rs index 1cc2b271e9c..a54db2654ab 100644 --- a/src/libregex/parse.rs +++ b/src/libregex/parse.rs @@ -518,7 +518,7 @@ impl<'a> Parser<'a> { }; self.chari = closer; let greed = try!(self.get_next_greedy()); - let inner = self.chars[(start+1)..closer].iter().cloned() + let inner = self.chars[start+1..closer].iter().cloned() .collect::(); // Parse the min and max values from the regex. diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 6bf1798d246..1197276b990 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -74,7 +74,7 @@ fn lookup_hash<'a, F>(d: rbml::Doc<'a>, mut eq_fn: F, hash: u64) -> Option ast::DefId { } let crate_part = &buf[0u..colon_idx]; - let def_part = &buf[(colon_idx + 1u)..len]; + let def_part = &buf[colon_idx + 1u..len]; let crate_num = match str::from_utf8(crate_part).ok().and_then(|s| s.parse::()) { Some(cn) => cn as ast::CrateNum, diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index a1a90395b3b..92603174266 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -927,7 +927,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat], }; head.map(|mut head| { head.push_all(&r[..col]); - head.push_all(&r[(col + 1)..]); + head.push_all(&r[col + 1..]); head }) } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index fb44d0cadfa..1be6c84f8e9 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -542,7 +542,7 @@ pub fn parameterized<'tcx>(cx: &ctxt<'tcx>, 0 }; - for t in tps[..(tps.len() - num_defaults)].iter() { + for t in tps[..tps.len() - num_defaults].iter() { strs.push(ty_to_string(cx, *t)) } @@ -550,9 +550,9 @@ pub fn parameterized<'tcx>(cx: &ctxt<'tcx>, format!("{}({}){}", base, if strs[0].starts_with("(") && strs[0].ends_with(",)") { - &strs[0][1 .. (strs[0].len() - 2)] // Remove '(' and ',)' + &strs[0][1 .. strs[0].len() - 2] // Remove '(' and ',)' } else if strs[0].starts_with("(") && strs[0].ends_with(")") { - &strs[0][1 .. (strs[0].len() - 1)] // Remove '(' and ')' + &strs[0][1 .. strs[0].len() - 1] // Remove '(' and ')' } else { &strs[0][] }, diff --git a/src/librustc_back/sha2.rs b/src/librustc_back/sha2.rs index e376ac50dcd..0228098b8f8 100644 --- a/src/librustc_back/sha2.rs +++ b/src/librustc_back/sha2.rs @@ -156,7 +156,7 @@ impl FixedBuffer for FixedBuffer64 { // While we have at least a full buffer size chunk's worth of data, process that data // without copying it into the buffer while input.len() - i >= size { - func(&input[i..(i + size)]); + func(&input[i..i + size]); i += size; } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 8c1e847748c..7353de8f260 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -2082,8 +2082,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let msg = format!("Could not find `{}` in `{}`", // idx +- 1 to account for the // colons on either side - &mpath[(idx + 1)..], - &mpath[..(idx - 1)]); + &mpath[idx + 1..], + &mpath[..idx - 1]); return Failed(Some((span, msg))); }, None => { @@ -2756,7 +2756,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { for (i, rib) in ribs.iter().enumerate().rev() { match rib.bindings.get(&name).cloned() { Some(def_like) => { - return self.upvarify(&ribs[(i + 1)..], def_like, span); + return self.upvarify(&ribs[i + 1..], def_like, span); } None => { // Continue. diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index dacf620cbd1..cfb8c88ce40 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -1183,7 +1183,7 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session, // against the archive. if sess.lto() { let name = cratepath.filename_str().unwrap(); - let name = &name[3..(name.len() - 5)]; // chop off lib/.rlib + let name = &name[3..name.len() - 5]; // chop off lib/.rlib time(sess.time_passes(), &format!("altering {}.rlib", name)[], (), |()| { diff --git a/src/librustc_trans/back/lto.rs b/src/librustc_trans/back/lto.rs index c0b1492a784..590354ab54e 100644 --- a/src/librustc_trans/back/lto.rs +++ b/src/librustc_trans/back/lto.rs @@ -60,7 +60,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, let archive = ArchiveRO::open(&path).expect("wanted an rlib"); let file = path.filename_str().unwrap(); - let file = &file[3..(file.len() - 5)]; // chop off lib/.rlib + let file = &file[3..file.len() - 5]; // chop off lib/.rlib debug!("reading {}", file); for i in iter::count(0u, 1) { let bc_encoded = time(sess.time_passes(), @@ -201,7 +201,7 @@ fn extract_compressed_bytecode_size_v1(bc: &[u8]) -> u64 { } fn read_from_le_bytes(bytes: &[u8], position_in_bytes: uint) -> T { - let byte_data = &bytes[position_in_bytes..(position_in_bytes + mem::size_of::())]; + let byte_data = &bytes[position_in_bytes..position_in_bytes + mem::size_of::()]; let data = unsafe { *(byte_data.as_ptr() as *const T) }; diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index b12903c814c..f5bf8b2d3e3 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -186,7 +186,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { if len <= 2 { return; } - let sub_paths = &sub_paths[..(len-2)]; + let sub_paths = &sub_paths[..len-2]; for &(ref span, ref qualname) in sub_paths.iter() { self.fmt.sub_mod_ref_str(path.span, *span, diff --git a/src/librustc_trans/trans/_match.rs b/src/librustc_trans/trans/_match.rs index be927503bad..4fc3159ad46 100644 --- a/src/librustc_trans/trans/_match.rs +++ b/src/librustc_trans/trans/_match.rs @@ -472,7 +472,7 @@ fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, enter_match(bcx, dm, m, col, val, |pats| { if pat_is_binding_or_wild(dm, &*pats[col]) { let mut r = pats[..col].to_vec(); - r.push_all(&pats[(col + 1)..]); + r.push_all(&pats[col + 1..]); Some(r) } else { None @@ -983,7 +983,7 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, let dm = &tcx.def_map; let mut vals_left = vals[0u..col].to_vec(); - vals_left.push_all(&vals[(col + 1u)..]); + vals_left.push_all(&vals[col + 1u..]); let ccx = bcx.fcx.ccx; // Find a real id (we're adding placeholder wildcard patterns, but diff --git a/src/librustc_trans/trans/cabi_x86_64.rs b/src/librustc_trans/trans/cabi_x86_64.rs index 980a70256e9..3c0530bbb9a 100644 --- a/src/librustc_trans/trans/cabi_x86_64.rs +++ b/src/librustc_trans/trans/cabi_x86_64.rs @@ -361,7 +361,7 @@ fn llreg_ty(ccx: &CrateContext, cls: &[RegClass]) -> Type { } _ => unreachable!(), }; - let vec_len = llvec_len(&cls[(i + 1u)..]); + let vec_len = llvec_len(&cls[i + 1u..]); let vec_ty = Type::vector(&elt_ty, vec_len as u64 * elts_per_word); tys.push(vec_ty); i += vec_len; diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index ea66b97bbf9..cda9110e024 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -1163,7 +1163,7 @@ pub fn get_cleanup_debug_loc_for_ast_node<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, if let Some(code_snippet) = code_snippet { let bytes = code_snippet.as_bytes(); - if bytes.len() > 0 && &bytes[(bytes.len()-1)..] == b"}" { + if bytes.len() > 0 && &bytes[bytes.len()-1..] == b"}" { cleanup_span = Span { lo: node_span.hi - codemap::BytePos(1), hi: node_span.hi, @@ -1752,7 +1752,7 @@ fn file_metadata(cx: &CrateContext, full_path: &str) -> DIFile { let work_dir = cx.sess().working_dir.as_str().unwrap(); let file_name = if full_path.starts_with(work_dir) { - &full_path[(work_dir.len() + 1u)..full_path.len()] + &full_path[work_dir.len() + 1u..full_path.len()] } else { full_path }; diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 57b8d666c95..928618467c4 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -358,7 +358,7 @@ fn path(w: &mut fmt::Formatter, // This is a documented path, link to it! Some((ref fqp, shortty)) if abs_root.is_some() => { let mut url = String::from_str(abs_root.unwrap().as_slice()); - let to_link = &fqp[..(fqp.len() - 1)]; + let to_link = &fqp[..fqp.len() - 1]; for component in to_link.iter() { url.push_str(component.as_slice()); url.push_str("/"); diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 839dfa339b3..403bd1c2961 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -404,7 +404,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult search_index.push(IndexItem { ty: shortty(item), name: item.name.clone().unwrap(), - path: fqp[..(fqp.len() - 1)].connect("::"), + path: fqp[..fqp.len() - 1].connect("::"), desc: shorter(item.doc_value()).to_string(), parent: Some(did), }); @@ -559,7 +559,7 @@ fn write_shared(cx: &Context, }; let mut mydst = dst.clone(); - for part in remote_path[..(remote_path.len() - 1)].iter() { + for part in remote_path[..remote_path.len() - 1].iter() { mydst.push(part.as_slice()); try!(mkdir(&mydst)); } @@ -842,7 +842,7 @@ impl DocFolder for Cache { clean::StructFieldItem(..) | clean::VariantItem(..) => { ((Some(*self.parent_stack.last().unwrap()), - Some(&self.stack[..(self.stack.len() - 1)])), + Some(&self.stack[..self.stack.len() - 1])), false) } clean::MethodItem(..) => { @@ -853,13 +853,13 @@ impl DocFolder for Cache { let did = *last; let path = match self.paths.get(&did) { Some(&(_, ItemType::Trait)) => - Some(&self.stack[..(self.stack.len() - 1)]), + Some(&self.stack[..self.stack.len() - 1]), // The current stack not necessarily has correlation for // where the type was defined. On the other hand, // `paths` always has the right information if present. Some(&(ref fqp, ItemType::Struct)) | Some(&(ref fqp, ItemType::Enum)) => - Some(&fqp[..(fqp.len() - 1)]), + Some(&fqp[..fqp.len() - 1]), Some(..) => Some(self.stack.as_slice()), None => None }; @@ -1185,7 +1185,7 @@ impl Context { .collect::(); match cache().paths.get(&it.def_id) { Some(&(ref names, _)) => { - for name in (&names[..(names.len() - 1)]).iter() { + for name in (&names[..names.len() - 1]).iter() { url.push_str(name.as_slice()); url.push_str("/"); } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 41499b5ae0e..92e2bd622d4 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -1222,7 +1222,7 @@ impl Stack { InternalIndex(i) => StackElement::Index(i), InternalKey(start, size) => { StackElement::Key(str::from_utf8( - &self.str_buffer[(start as uint) .. (start as uint + size as uint)]) + &self.str_buffer[start as uint .. start as uint + size as uint]) .unwrap()) } } @@ -1265,7 +1265,7 @@ impl Stack { Some(&InternalIndex(i)) => Some(StackElement::Index(i)), Some(&InternalKey(start, size)) => { Some(StackElement::Key(str::from_utf8( - &self.str_buffer[(start as uint) .. (start+size) as uint] + &self.str_buffer[start as uint .. (start+size) as uint] ).unwrap())) } } diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 8c38bc009cc..542a2d45237 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -281,9 +281,9 @@ impl Writer for LineBufferedWriter { fn write(&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(&buf[..i + 1])); try!(self.inner.flush()); - try!(self.inner.write(&buf[(i + 1)..])); + try!(self.inner.write(&buf[i + 1..])); Ok(()) } None => self.inner.write(buf), diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index ee05a9e5596..8d3c4f3053b 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -159,7 +159,7 @@ impl Reader for MemReader { let write_len = min(buf.len(), self.buf.len() - self.pos); { - let input = &self.buf[self.pos.. (self.pos + write_len)]; + let input = &self.buf[self.pos.. self.pos + write_len]; let output = buf.slice_to_mut(write_len); assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); @@ -349,7 +349,7 @@ impl<'a> Reader for BufReader<'a> { let write_len = min(buf.len(), self.buf.len() - self.pos); { - let input = &self.buf[self.pos.. (self.pos + write_len)]; + let input = &self.buf[self.pos.. self.pos + write_len]; let output = buf.slice_to_mut(write_len); assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index e2b71cd43af..d1ce0125fbb 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -1449,7 +1449,7 @@ pub trait Buffer: Reader { }; match available.iter().position(|&b| b == byte) { Some(i) => { - res.push_all(&available[..(i + 1)]); + res.push_all(&available[..i + 1]); used = i + 1; break } diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 541f1e77140..f4b99b4c793 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -399,7 +399,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { match name.rposition_elem(&dot) { None | Some(0) => None, Some(1) if name == b".." => None, - Some(pos) => Some(&name[(pos+1)..]) + Some(pos) => Some(&name[pos+1..]) } } } diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index aab64639ab5..422e2cedc48 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -126,7 +126,7 @@ impl GenericPathUnsafe for Path { None => { self.repr = Path::normalize(filename); } - Some(idx) if &self.repr[(idx+1)..] == b".." => { + Some(idx) if &self.repr[idx+1..] == b".." => { let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len()); v.push_all(self.repr.as_slice()); v.push(SEP_BYTE); @@ -136,7 +136,7 @@ impl GenericPathUnsafe for Path { } Some(idx) => { let mut v = Vec::with_capacity(idx + 1 + filename.len()); - v.push_all(&self.repr[..(idx+1)]); + v.push_all(&self.repr[..idx+1]); v.push_all(filename); // FIXME: this is slow self.repr = Path::normalize(v.as_slice()); @@ -178,7 +178,7 @@ impl GenericPath for Path { None if b".." == self.repr => self.repr.as_slice(), None => dot_static, Some(0) => &self.repr[..1], - Some(idx) if &self.repr[(idx+1)..] == b".." => self.repr.as_slice(), + Some(idx) if &self.repr[idx+1..] == b".." => self.repr.as_slice(), Some(idx) => &self.repr[..idx] } } @@ -188,9 +188,9 @@ impl GenericPath for Path { None if b"." == self.repr || b".." == self.repr => None, None => Some(self.repr.as_slice()), - Some(idx) if &self.repr[(idx+1)..] == b".." => None, + Some(idx) if &self.repr[idx+1..] == b".." => None, Some(0) if self.repr[1..].is_empty() => None, - Some(idx) => Some(&self.repr[(idx+1)..]) + Some(idx) => Some(&self.repr[idx+1..]) } } diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 3cff1c67be3..6802b411d1e 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -428,10 +428,10 @@ impl GenericPath for Path { if self.prefix.is_some() { Some(Path::new(match self.prefix { Some(DiskPrefix) if self.is_absolute() => { - &self.repr[..(self.prefix_len()+1)] + &self.repr[..self.prefix_len()+1] } Some(VerbatimDiskPrefix) => { - &self.repr[..(self.prefix_len()+1)] + &self.repr[..self.prefix_len()+1] } _ => &self.repr[..self.prefix_len()] })) @@ -635,7 +635,7 @@ impl Path { Some(_) => { let plen = self.prefix_len(); if repr.len() > plen && repr.as_bytes()[plen] == SEP_BYTE { - &repr[(plen+1)..] + &repr[plen+1..] } else { &repr[plen..] } } None if repr.as_bytes()[0] == SEP_BYTE => &repr[1..], @@ -786,9 +786,9 @@ impl Path { } Some(UNCPrefix(a,b)) => { s.push_str("\\\\"); - s.push_str(&prefix_[2..(a+2)]); + s.push_str(&prefix_[2..a+2]); s.push(SEP); - s.push_str(&prefix_[(3+a)..(3+a+b)]); + s.push_str(&prefix_[3+a..3+a+b]); } Some(_) => s.push_str(prefix_), None => () @@ -813,7 +813,7 @@ impl Path { fn update_sepidx(&mut self) { let s = if self.has_nonsemantic_trailing_slash() { - &self.repr[..(self.repr.len()-1)] + &self.repr[..self.repr.len()-1] } else { &self.repr[] }; let sep_test: fn(char) -> bool = if !prefix_is_verbatim(self.prefix) { is_sep @@ -1029,7 +1029,7 @@ fn parse_prefix<'a>(mut path: &'a str) -> Option { None => return None, Some(x) => x }; - path = &path[(idx_a+1)..]; + path = &path[idx_a+1..]; let idx_b = path.find(f).unwrap_or(path.len()); Some((idx_a, idx_b)) } diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index ee2dd14955b..03a23214cf3 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -362,7 +362,7 @@ 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(&bytes[..bytes.len()-1])), } } try!(w.write(&['\n' as u8])); diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index f462a730d3a..baa9516ae5d 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -525,7 +525,7 @@ impl<'ast> Map<'ast> { NodesMatchingSuffix { map: self, item_name: parts.last().unwrap(), - in_which: &parts[..(parts.len() - 1)], + in_which: &parts[..parts.len() - 1], idx: 0, } } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 7213b0fa955..745343ade63 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -280,7 +280,7 @@ fn print_maybe_styled(w: &mut EmitterWriter, // to be miscolored. We assume this is rare enough that we don't // have to worry about it. if msg.ends_with("\n") { - try!(t.write_str(&msg[..(msg.len()-1)])); + try!(t.write_str(&msg[..msg.len()-1])); try!(t.reset()); try!(t.write_str("\n")); } else { diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index 16ade904be8..79a85e9afbd 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -116,7 +116,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { if can_trim { lines.iter().map(|line| { - (&line[(i + 1)..line.len()]).to_string() + (&line[i + 1..line.len()]).to_string() }).collect() } else { lines @@ -132,7 +132,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { } if comment.starts_with("/*") { - let lines = comment[3u..(comment.len() - 2u)] + let lines = comment[3u..comment.len() - 2u] .lines_any() .map(|s| s.to_string()) .collect:: >(); diff --git a/src/libterm/terminfo/parser/compiled.rs b/src/libterm/terminfo/parser/compiled.rs index 4735b6e8f2a..eb300beae9f 100644 --- a/src/libterm/terminfo/parser/compiled.rs +++ b/src/libterm/terminfo/parser/compiled.rs @@ -284,12 +284,12 @@ pub fn parse(file: &mut io::Reader, longnames: bool) // Find the offset of the NUL we want to go to - let nulpos = string_table[(offset as uint) .. (string_table_bytes as uint)] + let nulpos = string_table[offset as uint .. string_table_bytes as uint] .iter().position(|&b| b == 0); match nulpos { Some(len) => { string_map.insert(name.to_string(), - string_table[(offset as uint) .. + string_table[offset as uint .. (offset as uint + len)].to_vec()) }, None => { diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index e8e8ac48485..daabae88bdf 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -103,7 +103,7 @@ impl Perm { let d = idx / self.fact[i] as i32; self.cnt[i] = d; idx %= self.fact[i] as i32; - for (place, val) in pp.iter_mut().zip(self.perm.p[..(i+1)].iter()) { + for (place, val) in pp.iter_mut().zip(self.perm.p[..i+1].iter()) { *place = (*val) as u8 } diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index e9da34615c1..1b849cd12f5 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -97,7 +97,7 @@ fn make_fasta>( } n -= nb; line[nb] = '\n' as u8; - try!(wr.write(&line[..(nb+1)])); + try!(wr.write(&line[..nb+1])); } Ok(()) } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 03268b40193..fdaeb9e74f5 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -101,11 +101,11 @@ fn windows_with_carry(bb: &[u8], nn: uint, mut it: F) -> Vec where let len = bb.len(); while ii < len - (nn - 1u) { - it(&bb[ii..(ii+nn)]); + it(&bb[ii..ii+nn]); ii += 1u; } - return bb[(len - (nn - 1u))..len].to_vec(); + return bb[len - (nn - 1u)..len].to_vec(); } fn make_sequence_processor(sz: uint, diff --git a/src/test/compile-fail/range-1.rs b/src/test/compile-fail/range-1.rs index 9888c085695..fdae5f79546 100644 --- a/src/test/compile-fail/range-1.rs +++ b/src/test/compile-fail/range-1.rs @@ -21,6 +21,6 @@ pub fn main() { // Unsized type. let arr: &[_] = &[1us, 2, 3]; - let range = (*arr)..; + let range = *arr..; //~^ ERROR the trait `core::marker::Sized` is not implemented } diff --git a/src/test/compile-fail/range-2.rs b/src/test/compile-fail/range-2.rs index 6d176ca3700..9d89f4b05c5 100644 --- a/src/test/compile-fail/range-2.rs +++ b/src/test/compile-fail/range-2.rs @@ -12,7 +12,7 @@ pub fn main() { let r = { - (&42is)..&42 + &42is..&42 //~^ ERROR borrowed value does not live long enough //~^^ ERROR borrowed value does not live long enough }; -- cgit 1.4.1-3-g733a5 From 940080501b76e559e3a2c0de1b15dc7b2353fd85 Mon Sep 17 00:00:00 2001 From: Eunji Jeong Date: Tue, 20 Jan 2015 15:03:44 +0900 Subject: Initial support for aarch64-linux-android --- mk/cfg/aarch64-linux-android.mk | 30 +++++++++++++++++++++++ mk/rt.mk | 2 ++ src/liblibc/lib.rs | 4 +-- src/librustc_back/target/aarch64_linux_android.rs | 28 +++++++++++++++++++++ src/librustc_back/target/mod.rs | 2 ++ src/libstd/sys/unix/backtrace.rs | 4 +-- 6 files changed, 66 insertions(+), 4 deletions(-) create mode 100644 mk/cfg/aarch64-linux-android.mk create mode 100644 src/librustc_back/target/aarch64_linux_android.rs (limited to 'src/libstd') diff --git a/mk/cfg/aarch64-linux-android.mk b/mk/cfg/aarch64-linux-android.mk new file mode 100644 index 00000000000..a6f7f2ba1d6 --- /dev/null +++ b/mk/cfg/aarch64-linux-android.mk @@ -0,0 +1,30 @@ +# aarch64-linux-android configuration +# CROSS_PREFIX_aarch64-linux-android- +CC_aarch64-linux-android=$(CFG_ANDROID_CROSS_PATH)/bin/aarch64-linux-android-gcc +CXX_aarch64-linux-android=$(CFG_ANDROID_CROSS_PATH)/bin/aarch64-linux-android-g++ +CPP_aarch64-linux-android=$(CFG_ANDROID_CROSS_PATH)/bin/aarch64-linux-android-gcc -E +AR_aarch64-linux-android=$(CFG_ANDROID_CROSS_PATH)/bin/aarch64-linux-android-ar +CFG_LIB_NAME_aarch64-linux-android=lib$(1).so +CFG_STATIC_LIB_NAME_aarch64-linux-android=lib$(1).a +CFG_LIB_GLOB_aarch64-linux-android=lib$(1)-*.so +CFG_LIB_DSYM_GLOB_aarch64-linux-android=lib$(1)-*.dylib.dSYM +CFG_JEMALLOC_CFLAGS_aarch64-linux-android := -D__aarch64__ -DANDROID -D__ANDROID__ $(CFLAGS) +CFG_GCCISH_CFLAGS_aarch64-linux-android := -Wall -g -fPIC -D__aarch64__ -DANDROID -D__ANDROID__ $(CFLAGS) +CFG_GCCISH_CXXFLAGS_aarch64-linux-android := -fno-rtti $(CXXFLAGS) +CFG_GCCISH_LINK_FLAGS_aarch64-linux-android := -shared -fPIC -ldl -g -lm -lsupc++ +CFG_GCCISH_DEF_FLAG_aarch64-linux-android := -Wl,--export-dynamic,--dynamic-list= +CFG_GCCISH_PRE_LIB_FLAGS_aarch64-linux-android := -Wl,-whole-archive +CFG_GCCISH_POST_LIB_FLAGS_aarch64-linux-android := -Wl,-no-whole-archive +CFG_DEF_SUFFIX_aarch64-linux-android := .android.def +CFG_LLC_FLAGS_aarch64-linux-android := +CFG_INSTALL_NAME_aarch64-linux-android = +CFG_EXE_SUFFIX_aarch64-linux-android := +CFG_WINDOWSY_aarch64-linux-android := +CFG_UNIXY_aarch64-linux-android := 1 +CFG_PATH_MUNGE_aarch64-linux-android := true +CFG_LDPATH_aarch64-linux-android := +CFG_RUN_aarch64-linux-android= +CFG_RUN_TARG_aarch64-linux-android= +RUSTC_FLAGS_aarch64-linux-android := +RUSTC_CROSS_FLAGS_aarch64-linux-android := +CFG_GNU_TRIPLE_aarch64-linux-android := aarch64-linux-android diff --git a/mk/rt.mk b/mk/rt.mk index 6a7be26c7a6..a8bbeb41517 100644 --- a/mk/rt.mk +++ b/mk/rt.mk @@ -141,6 +141,8 @@ else ifeq ($(OSTYPE_$(1)), apple-ios) JEMALLOC_ARGS_$(1) := --disable-tls else ifeq ($(OSTYPE_$(1)), linux-androideabi) JEMALLOC_ARGS_$(1) := --disable-tls +else ifeq ($(OSTYPE_$(1)), linux-android) + JEMALLOC_ARGS_$(1) := --disable-tls endif ################################################################################ diff --git a/src/liblibc/lib.rs b/src/liblibc/lib.rs index d010615a24c..2fd92695fe3 100644 --- a/src/liblibc/lib.rs +++ b/src/liblibc/lib.rs @@ -4647,13 +4647,13 @@ pub mod funcs { use types::os::arch::c95::c_int; use types::os::common::posix01::sighandler_t; - #[cfg(not(target_os = "android"))] + #[cfg(not(all(target_os = "android", target_arch = "arm")))] extern { pub fn signal(signum: c_int, handler: sighandler_t) -> sighandler_t; } - #[cfg(target_os = "android")] + #[cfg(all(target_os = "android", target_arch = "arm"))] extern { #[link_name = "bsd_signal"] pub fn signal(signum: c_int, diff --git a/src/librustc_back/target/aarch64_linux_android.rs b/src/librustc_back/target/aarch64_linux_android.rs new file mode 100644 index 00000000000..313c0dc2a6e --- /dev/null +++ b/src/librustc_back/target/aarch64_linux_android.rs @@ -0,0 +1,28 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use target::Target; + +pub fn target() -> Target { + let mut base = super::linux_base::opts(); + base.pre_link_args.push("-Wl,--allow-multiple-definition".to_string()); + base.position_independent_executables = true; + Target { + data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\ + f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\ + n32:64-S128".to_string(), + llvm_target: "aarch64-linux-android".to_string(), + target_endian: "little".to_string(), + target_pointer_width: "64".to_string(), + arch: "aarch64".to_string(), + target_os: "android".to_string(), + options: base, + } +} diff --git a/src/librustc_back/target/mod.rs b/src/librustc_back/target/mod.rs index f8eabb4375f..4626f2dc483 100644 --- a/src/librustc_back/target/mod.rs +++ b/src/librustc_back/target/mod.rs @@ -65,6 +65,7 @@ mod arm_linux_androideabi; mod arm_unknown_linux_gnueabi; mod arm_unknown_linux_gnueabihf; mod aarch64_apple_ios; +mod aarch64_linux_android; mod aarch64_unknown_linux_gnu; mod i686_apple_darwin; mod i686_pc_windows_gnu; @@ -357,6 +358,7 @@ impl Target { i386_apple_ios, x86_64_apple_ios, aarch64_apple_ios, + aarch64_linux_android, armv7_apple_ios, armv7s_apple_ios, diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index 7164931c55a..fe9c77c219a 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -418,7 +418,7 @@ mod uw { trace_argument: *mut libc::c_void) -> _Unwind_Reason_Code; - #[cfg(all(not(target_os = "android"), + #[cfg(all(not(all(target_os = "android", target_arch = "arm")), not(all(target_os = "linux", target_arch = "arm"))))] pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t; @@ -431,7 +431,7 @@ mod uw { // On android, the function _Unwind_GetIP is a macro, and this is the // expansion of the macro. This is all copy/pasted directly from the // header file with the definition of _Unwind_GetIP. - #[cfg(any(target_os = "android", + #[cfg(any(all(target_os = "android", target_arch = "arm"), all(target_os = "linux", target_arch = "arm")))] pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t { #[repr(C)] -- cgit 1.4.1-3-g733a5 From 01d7b8c6698311b1c610ae98e37839895a440951 Mon Sep 17 00:00:00 2001 From: Toby Scrace Date: Tue, 20 Jan 2015 12:18:23 +0000 Subject: Correct small typos in map.rs. This just corrects a couple of typos in doc comments, and changes some to conform to the Rust guidelines. --- src/libstd/collections/hash/map.rs | 46 +++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 23 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 80ae3076df3..09700673f0c 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -76,7 +76,7 @@ impl DefaultResizePolicy { // min_capacity(size) must be smaller than the internal capacity, // so that the map is not resized: // `min_capacity(usable_capacity(x)) <= x`. - // The lef-hand side can only be smaller due to flooring by integer + // The left-hand side can only be smaller due to flooring by integer // division. // // This doesn't have to be checked for overflow since allocation size @@ -838,8 +838,8 @@ impl HashMap /// map.insert("b", 2); /// map.insert("c", 3); /// - /// for key in map.values() { - /// println!("{}", key); + /// for val in map.values() { + /// println!("{}", val); /// } /// ``` #[stable] @@ -938,7 +938,7 @@ impl HashMap search_entry_hashed(&mut self.table, hash, key) } - /// Return the number of elements in the map. + /// Returns the number of elements in the map. /// /// # Example /// @@ -953,7 +953,7 @@ impl HashMap #[stable] pub fn len(&self) -> uint { self.table.size() } - /// Return true if the map contains no elements. + /// Returns true if the map contains no elements. /// /// # Example /// @@ -1274,7 +1274,7 @@ impl IndexMut for HashMap } } -/// HashMap iterator +/// HashMap iterator. #[stable] pub struct Iter<'a, K: 'a, V: 'a> { inner: table::Iter<'a, K, V> @@ -1289,13 +1289,13 @@ impl<'a, K, V> Clone for Iter<'a, K, V> { } } -/// HashMap mutable values iterator +/// HashMap mutable values iterator. #[stable] pub struct IterMut<'a, K: 'a, V: 'a> { inner: table::IterMut<'a, K, V> } -/// HashMap move iterator +/// HashMap move iterator. #[stable] pub struct IntoIter { inner: iter::Map< @@ -1306,7 +1306,7 @@ pub struct IntoIter { > } -/// HashMap keys iterator +/// HashMap keys iterator. #[stable] pub struct Keys<'a, K: 'a, V: 'a> { inner: Map<(&'a K, &'a V), &'a K, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K> @@ -1321,7 +1321,7 @@ impl<'a, K, V> Clone for Keys<'a, K, V> { } } -/// HashMap values iterator +/// HashMap values iterator. #[stable] pub struct Values<'a, K: 'a, V: 'a> { inner: Map<(&'a K, &'a V), &'a V, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V> @@ -1336,7 +1336,7 @@ impl<'a, K, V> Clone for Values<'a, K, V> { } } -/// HashMap drain iterator +/// HashMap drain iterator. #[unstable = "matches collection reform specification, waiting for dust to settle"] pub struct Drain<'a, K: 'a, V: 'a> { inner: iter::Map< @@ -1347,13 +1347,13 @@ pub struct Drain<'a, K: 'a, V: 'a> { > } -/// A view into a single occupied location in a HashMap +/// A view into a single occupied location in a HashMap. #[unstable = "precise API still being fleshed out"] pub struct OccupiedEntry<'a, K: 'a, V: 'a> { elem: FullBucket>, } -/// A view into a single empty location in a HashMap +/// A view into a single empty location in a HashMap. #[unstable = "precise API still being fleshed out"] pub struct VacantEntry<'a, K: 'a, V: 'a> { hash: SafeHash, @@ -1361,21 +1361,21 @@ pub struct VacantEntry<'a, K: 'a, V: 'a> { elem: VacantEntryState>, } -/// A view into a single location in a map, which may be vacant or occupied +/// A view into a single location in a map, which may be vacant or occupied. #[unstable = "precise API still being fleshed out"] pub enum Entry<'a, K: 'a, V: 'a> { - /// An occupied Entry + /// An occupied Entry. Occupied(OccupiedEntry<'a, K, V>), - /// A vacant Entry + /// A vacant Entry. Vacant(VacantEntry<'a, K, V>), } -/// Possible states of a VacantEntry +/// Possible states of a VacantEntry. enum VacantEntryState { /// The index is occupied, but the key to insert has precedence, - /// and will kick the current one out on insertion + /// and will kick the current one out on insertion. NeqElem(FullBucket, uint), - /// The index is genuinely vacant + /// The index is genuinely vacant. NoElem(EmptyBucket), } @@ -1453,7 +1453,7 @@ impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> { #[unstable = "matches collection reform v2 specification, waiting for dust to settle"] impl<'a, K, V> Entry<'a, K, V> { - /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant + /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant. pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> { match self { Occupied(entry) => Ok(entry.into_mut()), @@ -1464,12 +1464,12 @@ impl<'a, K, V> Entry<'a, K, V> { #[unstable = "matches collection reform v2 specification, waiting for dust to settle"] impl<'a, K, V> OccupiedEntry<'a, K, V> { - /// Gets a reference to the value in the entry + /// Gets a reference to the value in the entry. pub fn get(&self) -> &V { self.elem.read().1 } - /// Gets a mutable reference to the value in the entry + /// Gets a mutable reference to the value in the entry. pub fn get_mut(&mut self) -> &mut V { self.elem.read_mut().1 } -- cgit 1.4.1-3-g733a5 From f2b8404bcb095235efeaf7a39536cd55172ac18e Mon Sep 17 00:00:00 2001 From: Oliver Schneider Date: Fri, 16 Jan 2015 10:49:35 +0100 Subject: prettier Buffer::read_until --- src/libstd/io/mod.rs | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index e2b71cd43af..88be8d1189e 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -1436,33 +1436,31 @@ pub trait Buffer: Reader { fn read_until(&mut self, byte: u8) -> IoResult> { let mut res = Vec::new(); - let mut used; loop { - { + let (done, used) = { let available = match self.fill_buf() { Ok(n) => n, Err(ref e) if res.len() > 0 && e.kind == EndOfFile => { - used = 0; - break + return Ok(res); } Err(e) => return Err(e) }; match available.iter().position(|&b| b == byte) { Some(i) => { res.push_all(&available[..(i + 1)]); - used = i + 1; - break + (true, i + 1) } None => { res.push_all(available); - used = available.len(); + (false, available.len()) } } + }; + buffer.consume(used); + if done { + return Ok(res); } - self.consume(used); } - self.consume(used); - Ok(res) } /// Reads the next utf8-encoded character from the underlying stream. -- cgit 1.4.1-3-g733a5 From b6380f5c67cace73a1170f282e6cd7f8c65a0625 Mon Sep 17 00:00:00 2001 From: JP Sugarbroad Date: Tue, 20 Jan 2015 12:00:12 -0800 Subject: Kill RacyCell in favor of marking SyncSender explicitly Send. --- src/libstd/sync/mpsc/mod.rs | 51 +++++++++++++++------------------------------ 1 file changed, 17 insertions(+), 34 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 0ba19b70617..e1ad02498db 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -319,6 +319,7 @@ use prelude::v1::*; use sync::Arc; use fmt; +#[cfg(stage0)] // NOTE remove use after next snapshot use marker; use mem; use cell::UnsafeCell; @@ -372,7 +373,7 @@ unsafe impl Send for Sender { } #[stable] #[cfg(stage0)] // NOTE remove impl after next snapshot pub struct SyncSender { - inner: Arc>>, + inner: Arc>>, // can't share in an arc _marker: marker::NoSync, } @@ -382,11 +383,13 @@ pub struct SyncSender { #[stable] #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct SyncSender { - inner: Arc>>, + inner: Arc>>, } +unsafe impl Send for SyncSender {} + #[cfg(not(stage0))] // NOTE remove cfg after next snapshot -impl !marker::Sync for SyncSender {} +impl !Sync for SyncSender {} /// An error returned from the `send` function on channels. /// @@ -442,10 +445,10 @@ pub enum TrySendError { } enum Flavor { - Oneshot(Arc>>), - Stream(Arc>>), - Shared(Arc>>), - Sync(Arc>>), + Oneshot(Arc>>), + Stream(Arc>>), + Shared(Arc>>), + Sync(Arc>>), } #[doc(hidden)] @@ -497,7 +500,7 @@ impl UnsafeFlavor for Receiver { /// ``` #[stable] pub fn channel() -> (Sender, Receiver) { - let a = Arc::new(RacyCell::new(oneshot::Packet::new())); + let a = Arc::new(UnsafeCell::new(oneshot::Packet::new())); (Sender::new(Flavor::Oneshot(a.clone())), Receiver::new(Flavor::Oneshot(a))) } @@ -537,7 +540,7 @@ pub fn channel() -> (Sender, Receiver) { /// ``` #[stable] pub fn sync_channel(bound: uint) -> (SyncSender, Receiver) { - let a = Arc::new(RacyCell::new(sync::Packet::new(bound))); + let a = Arc::new(UnsafeCell::new(sync::Packet::new(bound))); (SyncSender::new(a.clone()), Receiver::new(Flavor::Sync(a))) } @@ -589,7 +592,7 @@ impl Sender { return (*p).send(t).map_err(SendError); } else { let a = - Arc::new(RacyCell::new(stream::Packet::new())); + Arc::new(UnsafeCell::new(stream::Packet::new())); let rx = Receiver::new(Flavor::Stream(a.clone())); match (*p).upgrade(rx) { oneshot::UpSuccess => { @@ -631,7 +634,7 @@ impl Clone for Sender { fn clone(&self) -> Sender { let (packet, sleeper, guard) = match *unsafe { self.inner() } { Flavor::Oneshot(ref p) => { - let a = Arc::new(RacyCell::new(shared::Packet::new())); + let a = Arc::new(UnsafeCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); let rx = Receiver::new(Flavor::Shared(a.clone())); @@ -643,7 +646,7 @@ impl Clone for Sender { } } Flavor::Stream(ref p) => { - let a = Arc::new(RacyCell::new(shared::Packet::new())); + let a = Arc::new(UnsafeCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); let rx = Receiver::new(Flavor::Shared(a.clone())); @@ -690,12 +693,12 @@ impl Drop for Sender { impl SyncSender { #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(inner: Arc>>) -> SyncSender { + fn new(inner: Arc>>) -> SyncSender { SyncSender { inner: inner, _marker: marker::NoSync } } #[cfg(not(stage0))] // NOTE remove cfg after next snapshot - fn new(inner: Arc>>) -> SyncSender { + fn new(inner: Arc>>) -> SyncSender { SyncSender { inner: inner } } @@ -978,26 +981,6 @@ impl Drop for Receiver { } } -/// A version of `UnsafeCell` intended for use in concurrent data -/// structures (for example, you might put it in an `Arc`). -struct RacyCell(pub UnsafeCell); - -impl RacyCell { - - fn new(value: T) -> RacyCell { - RacyCell(UnsafeCell { value: value }) - } - - unsafe fn get(&self) -> *mut T { - self.0.get() - } - -} - -unsafe impl Send for RacyCell { } - -unsafe impl Sync for RacyCell { } // Oh dear - impl fmt::Show for SendError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "sending on a closed channel".fmt(f) -- cgit 1.4.1-3-g733a5 From cd631c6914d384538352604059a7e4abb31d8c46 Mon Sep 17 00:00:00 2001 From: Flavio Percoco Date: Tue, 20 Jan 2015 15:51:09 +0100 Subject: Register snapshot for 9006c3c --- src/liballoc/rc.rs | 154 --------------------------------------- src/libcollections/btree/set.rs | 3 - src/libcore/marker.rs | 19 ----- src/librustc/middle/region.rs | 3 - src/libstd/io/process.rs | 3 - src/libstd/sync/mpsc/blocking.rs | 30 -------- src/libstd/sync/mpsc/mod.rs | 17 ----- src/libstd/sync/mpsc/select.rs | 27 ------- src/libstd/sync/mutex.rs | 32 -------- src/libstd/sync/rwlock.rs | 52 ------------- src/snapshots.txt | 9 +++ 11 files changed, 9 insertions(+), 340 deletions(-) (limited to 'src/libstd') diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 7191a7af346..b516d9b4d31 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -174,61 +174,17 @@ struct RcBox { /// See the [module level documentation](../index.html) for more details. #[unsafe_no_drop_flag] #[stable] -#[cfg(stage0)] // NOTE remove impl after next snapshot pub struct Rc { // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained // type via Deref _ptr: NonZero<*mut RcBox>, - _nosend: marker::NoSend, - _noshare: marker::NoSync } -/// An immutable reference-counted pointer type. -/// -/// See the [module level documentation](../index.html) for more details. -#[unsafe_no_drop_flag] -#[stable] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct Rc { - // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained - // type via Deref - _ptr: NonZero<*mut RcBox>, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !marker::Send for Rc {} -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !marker::Sync for Rc {} impl Rc { - /// Constructs a new `Rc`. - /// - /// # Examples - /// - /// ``` - /// use std::rc::Rc; - /// - /// let five = Rc::new(5i); - /// ``` - #[stable] - #[cfg(stage0)] // NOTE remove after next snapshot - pub fn new(value: T) -> Rc { - unsafe { - Rc { - // there is an implicit weak pointer owned by all the strong pointers, which - // ensures that the weak destructor never frees the allocation while the strong - // destructor is running, even if the weak pointer is stored inside the strong one. - _ptr: NonZero::new(transmute(box RcBox { - value: value, - strong: Cell::new(1), - weak: Cell::new(1) - })), - _nosend: marker::NoSend, - _noshare: marker::NoSync - } - } - } /// Constructs a new `Rc`. /// @@ -240,7 +196,6 @@ impl Rc { /// let five = Rc::new(5i); /// ``` #[stable] - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn new(value: T) -> Rc { unsafe { Rc { @@ -267,29 +222,6 @@ impl Rc { /// /// let weak_five = five.downgrade(); /// ``` - #[cfg(stage0)] // NOTE remove after next snapshot - #[unstable = "Weak pointers may not belong in this module"] - pub fn downgrade(&self) -> Weak { - self.inc_weak(); - Weak { - _ptr: self._ptr, - _nosend: marker::NoSend, - _noshare: marker::NoSync - } - } - - /// Downgrades the `Rc` to a `Weak` reference. - /// - /// # Examples - /// - /// ``` - /// use std::rc::Rc; - /// - /// let five = Rc::new(5i); - /// - /// let weak_five = five.downgrade(); - /// ``` - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot #[unstable = "Weak pointers may not belong in this module"] pub fn downgrade(&self) -> Weak { self.inc_weak(); @@ -483,25 +415,6 @@ impl Drop for Rc { #[stable] impl Clone for Rc { - /// Makes a clone of the `Rc`. - /// - /// This increases the strong reference count. - /// - /// # Examples - /// - /// ``` - /// use std::rc::Rc; - /// - /// let five = Rc::new(5i); - /// - /// five.clone(); - /// ``` - #[inline] - #[cfg(stage0)] // NOTE remove after next snapshot - fn clone(&self) -> Rc { - self.inc_strong(); - Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync } - } /// Makes a clone of the `Rc`. /// @@ -517,7 +430,6 @@ impl Clone for Rc { /// five.clone(); /// ``` #[inline] - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn clone(&self) -> Rc { self.inc_strong(); Rc { _ptr: self._ptr } @@ -714,66 +626,21 @@ impl fmt::String for Rc { /// See the [module level documentation](../index.html) for more. #[unsafe_no_drop_flag] #[unstable = "Weak pointers may not belong in this module."] -#[cfg(stage0)] // NOTE remove impl after next snapshot pub struct Weak { // FIXME #12808: strange names to try to avoid interfering with // field accesses of the contained type via Deref _ptr: NonZero<*mut RcBox>, - _nosend: marker::NoSend, - _noshare: marker::NoSync } -/// A weak version of `Rc`. -/// -/// Weak references do not count when determining if the inner value should be dropped. -/// -/// See the [module level documentation](../index.html) for more. -#[unsafe_no_drop_flag] -#[unstable = "Weak pointers may not belong in this module."] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct Weak { - // FIXME #12808: strange names to try to avoid interfering with - // field accesses of the contained type via Deref - _ptr: NonZero<*mut RcBox>, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot #[allow(unstable)] impl !marker::Send for Weak {} -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot #[allow(unstable)] impl !marker::Sync for Weak {} #[unstable = "Weak pointers may not belong in this module."] impl Weak { - /// Upgrades a weak reference to a strong reference. - /// - /// Upgrades the `Weak` reference to an `Rc`, if possible. - /// - /// Returns `None` if there were no strong references and the data was destroyed. - /// - /// # Examples - /// - /// ``` - /// use std::rc::Rc; - /// - /// let five = Rc::new(5i); - /// - /// let weak_five = five.downgrade(); - /// - /// let strong_five: Option> = weak_five.upgrade(); - /// ``` - #[cfg(stage0)] // NOTE remove after next snapshot - pub fn upgrade(&self) -> Option> { - if self.strong() == 0 { - None - } else { - self.inc_strong(); - Some(Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }) - } - } /// Upgrades a weak reference to a strong reference. /// @@ -792,7 +659,6 @@ impl Weak { /// /// let strong_five: Option> = weak_five.upgrade(); /// ``` - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn upgrade(&self) -> Option> { if self.strong() == 0 { None @@ -849,25 +715,6 @@ impl Drop for Weak { #[unstable = "Weak pointers may not belong in this module."] impl Clone for Weak { - /// Makes a clone of the `Weak`. - /// - /// This increases the weak reference count. - /// - /// # Examples - /// - /// ``` - /// use std::rc::Rc; - /// - /// let weak_five = Rc::new(5i).downgrade(); - /// - /// weak_five.clone(); - /// ``` - #[inline] - #[cfg(stage0)] // NOTE remove after next snapshot - fn clone(&self) -> Weak { - self.inc_weak(); - Weak { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync } - } /// Makes a clone of the `Weak`. /// @@ -883,7 +730,6 @@ impl Clone for Weak { /// weak_five.clone(); /// ``` #[inline] - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn clone(&self) -> Weak { self.inc_weak(); Weak { _ptr: self._ptr } diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 4d71f9dbea8..90b61d3c5d1 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -18,9 +18,6 @@ use core::cmp::Ordering::{self, Less, Greater, Equal}; use core::default::Default; use core::fmt::Show; use core::fmt; -// NOTE(stage0) remove import after a snapshot -#[cfg(stage0)] -use core::hash::Hash; use core::iter::{Peekable, Map, FromIterator}; use core::ops::{BitOr, BitAnd, BitXor, Sub}; diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs index 99ba9666cd2..a987a0a5068 100644 --- a/src/libcore/marker.rs +++ b/src/libcore/marker.rs @@ -376,16 +376,6 @@ pub struct ContravariantLifetime<'a>; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct InvariantLifetime<'a>; -/// A type which is considered "not sendable", meaning that it cannot -/// be safely sent between tasks, even if it is owned. This is -/// typically embedded in other types, such as `Gc`, to ensure that -/// their instances remain thread-local. -#[unstable = "likely to change with new variance strategy"] -#[lang="no_send_bound"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct NoSend; - /// A type which is considered "not POD", meaning that it is not /// implicitly copyable. This is typically embedded in other types to /// ensure that they are never copied, even if they lack a destructor. @@ -395,15 +385,6 @@ pub struct NoSend; #[allow(missing_copy_implementations)] pub struct NoCopy; -/// A type which is considered "not sync", meaning that -/// its contents are not threadsafe, hence they cannot be -/// shared between tasks. -#[unstable = "likely to change with new variance strategy"] -#[lang="no_sync_bound"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct NoSync; - /// A type which is considered managed by the GC. This is typically /// embedded in other types. #[unstable = "likely to change with new variance strategy"] diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 90ba442ee39..b4b2e1b63e8 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -22,9 +22,6 @@ use util::nodemap::{FnvHashMap, FnvHashSet, NodeMap}; use util::common::can_reach; use std::cell::RefCell; -// NOTE(stage0) remove import after a snapshot -#[cfg(stage0)] -use std::hash::{Hash}; use syntax::codemap::Span; use syntax::{ast, visit}; use syntax::ast::{Block, Item, FnDecl, NodeId, Arm, Pat, Stmt, Expr, Local}; diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 43ca7b13145..d98f155ba83 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -21,9 +21,6 @@ use prelude::v1::*; use collections::HashMap; use ffi::CString; use fmt; -// NOTE(stage0) remove import after a snapshot -#[cfg(stage0)] -use hash::Hash; use io::pipe::{PipeStream, PipePair}; use io::{IoResult, IoError}; use io; diff --git a/src/libstd/sync/mpsc/blocking.rs b/src/libstd/sync/mpsc/blocking.rs index 17e690e9540..61ffb532d36 100644 --- a/src/libstd/sync/mpsc/blocking.rs +++ b/src/libstd/sync/mpsc/blocking.rs @@ -14,8 +14,6 @@ use thread::Thread; use sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use sync::Arc; use marker::{Sync, Send}; -#[cfg(stage0)] // NOTE remove use after next snapshot -use marker::{NoSend, NoSync}; use mem; use clone::Clone; @@ -32,42 +30,14 @@ pub struct SignalToken { inner: Arc, } -#[cfg(stage0)] // NOTE remove impl after next snapshot pub struct WaitToken { inner: Arc, - no_send: NoSend, - no_sync: NoSync, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct WaitToken { - inner: Arc, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !Send for WaitToken {} -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !Sync for WaitToken {} -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub fn tokens() -> (WaitToken, SignalToken) { - let inner = Arc::new(Inner { - thread: Thread::current(), - woken: ATOMIC_BOOL_INIT, - }); - let wait_token = WaitToken { - inner: inner.clone(), - no_send: NoSend, - no_sync: NoSync, - }; - let signal_token = SignalToken { - inner: inner - }; - (wait_token, signal_token) -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn tokens() -> (WaitToken, SignalToken) { let inner = Arc::new(Inner { thread: Thread::current(), diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 0ba19b70617..375a85eb879 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -370,22 +370,10 @@ unsafe impl Send for Sender { } /// The sending-half of Rust's synchronous channel type. This half can only be /// owned by one task, but it can be cloned to send to other tasks. #[stable] -#[cfg(stage0)] // NOTE remove impl after next snapshot pub struct SyncSender { inner: Arc>>, - // can't share in an arc - _marker: marker::NoSync, } -/// The sending-half of Rust's synchronous channel type. This half can only be -/// owned by one task, but it can be cloned to send to other tasks. -#[stable] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct SyncSender { - inner: Arc>>, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !marker::Sync for SyncSender {} /// An error returned from the `send` function on channels. @@ -689,12 +677,7 @@ impl Drop for Sender { //////////////////////////////////////////////////////////////////////////////// impl SyncSender { - #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(inner: Arc>>) -> SyncSender { - SyncSender { inner: inner, _marker: marker::NoSync } - } - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn new(inner: Arc>>) -> SyncSender { SyncSender { inner: inner } } diff --git a/src/libstd/sync/mpsc/select.rs b/src/libstd/sync/mpsc/select.rs index 62a7b823ec8..e726b1f4846 100644 --- a/src/libstd/sync/mpsc/select.rs +++ b/src/libstd/sync/mpsc/select.rs @@ -66,24 +66,12 @@ use sync::mpsc::blocking::{self, SignalToken}; /// The "receiver set" of the select interface. This structure is used to manage /// a set of receivers which are being selected over. -#[cfg(stage0)] // NOTE remove impl after next snapshot pub struct Select { head: *mut Handle<'static, ()>, tail: *mut Handle<'static, ()>, next_id: Cell, - marker1: marker::NoSend, } -/// The "receiver set" of the select interface. This structure is used to manage -/// a set of receivers which are being selected over. -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct Select { - head: *mut Handle<'static, ()>, - tail: *mut Handle<'static, ()>, - next_id: Cell, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !marker::Send for Select {} /// A handle to a receiver which is currently a member of a `Select` set of @@ -121,27 +109,12 @@ pub trait Packet { } impl Select { - /// Creates a new selection structure. This set is initially empty and - /// `wait` will panic!() if called. - /// - /// Usage of this struct directly can sometimes be burdensome, and usage is - /// rather much easier through the `select!` macro. - #[cfg(stage0)] // NOTE remove impl after next snapshot - pub fn new() -> Select { - Select { - marker1: marker::NoSend, - head: 0 as *mut Handle<'static, ()>, - tail: 0 as *mut Handle<'static, ()>, - next_id: Cell::new(1), - } - } /// Creates a new selection structure. This set is initially empty and /// `wait` will panic!() if called. /// /// Usage of this struct directly can sometimes be burdensome, and usage is /// rather much easier through the `select!` macro. - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn new() -> Select { Select { head: 0 as *mut Handle<'static, ()>, diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 73d5332d16f..6ddfe3e075b 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -160,33 +160,14 @@ unsafe impl Sync for StaticMutex {} /// Deref and DerefMut implementations #[must_use] #[stable] -#[cfg(stage0)] // NOTE remove impl after next snapshot pub struct MutexGuard<'a, T: 'a> { // funny underscores due to how Deref/DerefMut currently work (they // disregard field privacy). __lock: &'a StaticMutex, __data: &'a UnsafeCell, __poison: poison::Guard, - __marker: marker::NoSend, } -/// An RAII implementation of a "scoped lock" of a mutex. When this structure is -/// dropped (falls out of scope), the lock will be unlocked. -/// -/// The data protected by the mutex can be access through this guard via its -/// Deref and DerefMut implementations -#[must_use] -#[stable] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct MutexGuard<'a, T: 'a> { - // funny underscores due to how Deref/DerefMut currently work (they - // disregard field privacy). - __lock: &'a StaticMutex, - __data: &'a UnsafeCell, - __poison: poison::Guard, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl<'a, T> !marker::Send for MutexGuard<'a, T> {} /// Static initialization of a mutex. This constant can be used to initialize @@ -299,20 +280,7 @@ impl StaticMutex { } impl<'mutex, T> MutexGuard<'mutex, T> { - #[cfg(stage0)] // NOTE remove afte next snapshot - fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell) - -> LockResult> { - poison::map_result(lock.poison.borrow(), |guard| { - MutexGuard { - __lock: lock, - __data: data, - __poison: guard, - __marker: marker::NoSend, - } - }) - } - #[cfg(not(stage0))] // NOTE remove cfg afte next snapshot fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell) -> LockResult> { poison::map_result(lock.poison.borrow(), |guard| { diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 237f6d08a95..35d305466b5 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -110,50 +110,23 @@ pub const RW_LOCK_INIT: StaticRwLock = StaticRwLock { /// dropped. #[must_use] #[stable] -#[cfg(stage0)] // NOTE remove impl after next snapshot pub struct RwLockReadGuard<'a, T: 'a> { __lock: &'a StaticRwLock, __data: &'a UnsafeCell, - __marker: marker::NoSend, } -/// RAII structure used to release the shared read access of a lock when -/// dropped. -#[must_use] -#[stable] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct RwLockReadGuard<'a, T: 'a> { - __lock: &'a StaticRwLock, - __data: &'a UnsafeCell, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl<'a, T> !marker::Send for RwLockReadGuard<'a, T> {} /// RAII structure used to release the exclusive write access of a lock when /// dropped. #[must_use] #[stable] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct RwLockWriteGuard<'a, T: 'a> { - __lock: &'a StaticRwLock, - __data: &'a UnsafeCell, - __poison: poison::Guard, - __marker: marker::NoSend, -} - -/// RAII structure used to release the exclusive write access of a lock when -/// dropped. -#[must_use] -#[stable] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct RwLockWriteGuard<'a, T: 'a> { __lock: &'a StaticRwLock, __data: &'a UnsafeCell, __poison: poison::Guard, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl<'a, T> !marker::Send for RwLockWriteGuard<'a, T> {} impl RwLock { @@ -332,19 +305,7 @@ impl StaticRwLock { } impl<'rwlock, T> RwLockReadGuard<'rwlock, T> { - #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) - -> LockResult> { - poison::map_result(lock.poison.borrow(), |_| { - RwLockReadGuard { - __lock: lock, - __data: data, - __marker: marker::NoSend, - } - }) - } - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) -> LockResult> { poison::map_result(lock.poison.borrow(), |_| { @@ -356,20 +317,7 @@ impl<'rwlock, T> RwLockReadGuard<'rwlock, T> { } } impl<'rwlock, T> RwLockWriteGuard<'rwlock, T> { - #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) - -> LockResult> { - poison::map_result(lock.poison.borrow(), |guard| { - RwLockWriteGuard { - __lock: lock, - __data: data, - __poison: guard, - __marker: marker::NoSend, - } - }) - } - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) -> LockResult> { poison::map_result(lock.poison.borrow(), |guard| { diff --git a/src/snapshots.txt b/src/snapshots.txt index 16fb109bb7d..8b502785733 100644 --- a/src/snapshots.txt +++ b/src/snapshots.txt @@ -1,3 +1,12 @@ +S 2015-01-20 9006c3c + freebsd-x86_64 240b30b33263d175e30f925ed1e1e1a4e553a513 + linux-i386 544c2063b8d5035342c705b881b8868244c1e9a1 + linux-x86_64 eb41db80978210a013a8dcf8f4fe804969197337 + macos-i386 3ed08c5ae66367e85b8f2b207615d45bfd9cf89d + macos-x86_64 d102760316b90b17d54b0bef02ca6dc35f82e6bd + winnt-i386 6940fef6caa2f64d158b8f5eb00afd5c8e0c71a5 + winnt-x86_64 36b6f239fe1264bceb4b8202e692b7d49947eebe + S 2015-01-15 9ade482 freebsd-x86_64 eb8f52c6e8dc24a293456d5e4dc5d1072442e758 linux-i386 0197ad7179d74eba06a8b46432548caf226aa03d -- cgit 1.4.1-3-g733a5 From 3cb9fa26ef9905c00a29ea577fb55a12a91c8e7b Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 20 Jan 2015 15:45:07 -0800 Subject: std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl FromError for Box` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436 --- src/compiletest/common.rs | 12 +- src/compiletest/runtest.rs | 6 +- src/liballoc/arc.rs | 13 +- src/liballoc/boxed.rs | 23 +++- src/liballoc/rc.rs | 16 +-- src/libcollections/bit.rs | 6 +- src/libcollections/btree/map.rs | 4 +- src/libcollections/btree/set.rs | 6 +- src/libcollections/dlist.rs | 4 +- src/libcollections/enum_set.rs | 2 +- src/libcollections/ring_buf.rs | 8 +- src/libcollections/slice.rs | 12 +- src/libcollections/string.rs | 43 ++++--- src/libcollections/vec.rs | 6 +- src/libcollections/vec_map.rs | 4 +- src/libcore/any.rs | 8 +- src/libcore/array.rs | 6 +- src/libcore/borrow.rs | 24 +++- src/libcore/error.rs | 110 ++++++++++++++++ src/libcore/fmt/mod.rs | 142 +++++++++++++-------- src/libcore/fmt/num.rs | 20 +-- src/libcore/lib.rs | 1 + src/libcore/ops.rs | 18 +-- src/libcore/result.rs | 10 +- src/libcore/str/mod.rs | 28 +++- src/libcoretest/finally.rs | 2 + src/libcoretest/fmt/num.rs | 24 ++-- src/libcoretest/num/mod.rs | 4 +- src/libcoretest/result.rs | 6 +- src/libcoretest/tuple.rs | 6 +- src/libgetopts/lib.rs | 2 +- src/libgraphviz/lib.rs | 16 +-- src/libgraphviz/maybe_owned_vec.rs | 2 +- src/liblog/lib.rs | 14 +- src/librbml/lib.rs | 8 ++ src/libregex/parse.rs | 3 +- src/libregex/re.rs | 4 +- src/librustc/middle/check_match.rs | 2 +- src/librustc/middle/graph.rs | 8 +- src/librustc/middle/infer/unify.rs | 4 +- src/librustc/middle/liveness.rs | 4 +- src/librustc/middle/resolve_lifetime.rs | 2 +- src/librustc/middle/subst.rs | 2 +- src/librustc/middle/traits/error_reporting.rs | 4 +- src/librustc/middle/traits/util.rs | 8 +- src/librustc/middle/ty.rs | 18 +-- src/librustc/session/config.rs | 4 +- src/librustc/util/common.rs | 4 +- src/librustc_back/archive.rs | 6 +- src/librustc_back/svh.rs | 10 +- src/librustc_borrowck/borrowck/gather_loans/mod.rs | 2 +- src/librustc_resolve/lib.rs | 2 +- src/librustc_trans/back/link.rs | 6 +- src/librustc_trans/back/write.rs | 8 +- src/librustc_trans/trans/cleanup.rs | 2 +- src/librustc_trans/trans/datum.rs | 4 +- src/librustc_typeck/variance.rs | 2 +- src/librustdoc/html/escape.rs | 2 +- src/librustdoc/html/format.rs | 52 ++++---- src/librustdoc/html/item_type.rs | 2 +- src/librustdoc/html/layout.rs | 2 +- src/librustdoc/html/markdown.rs | 4 +- src/librustdoc/html/render.rs | 8 +- src/librustdoc/html/toc.rs | 6 +- src/librustdoc/lib.rs | 2 +- src/libserialize/base64.rs | 8 +- src/libserialize/hex.rs | 8 +- src/libserialize/json.rs | 37 ++++-- src/libstd/collections/hash/map.rs | 12 +- src/libstd/collections/hash/set.rs | 10 +- src/libstd/error.rs | 137 -------------------- src/libstd/ffi/c_str.rs | 9 +- src/libstd/fmt.rs | 27 ++-- src/libstd/io/buffered.rs | 12 +- src/libstd/io/fs.rs | 50 ++++---- src/libstd/io/mem.rs | 4 +- src/libstd/io/mod.rs | 32 ++--- src/libstd/io/net/ip.rs | 6 +- src/libstd/io/process.rs | 15 +-- src/libstd/lib.rs | 2 +- src/libstd/num/mod.rs | 4 +- src/libstd/os.rs | 12 +- src/libstd/path/mod.rs | 8 +- src/libstd/path/posix.rs | 5 +- src/libstd/path/windows.rs | 5 +- src/libstd/sync/mpsc/mod.rs | 20 +-- src/libstd/sync/poison.rs | 8 +- src/libstd/thread.rs | 12 +- src/libstd/time/duration.rs | 3 +- src/libsyntax/abi.rs | 20 +-- src/libsyntax/ast.rs | 51 +++----- src/libsyntax/ast_map/mod.rs | 2 +- src/libsyntax/attr.rs | 4 +- src/libsyntax/diagnostic.rs | 4 +- src/libsyntax/ext/deriving/mod.rs | 2 + src/libsyntax/ext/deriving/show.rs | 4 +- src/libsyntax/ext/format.rs | 4 +- src/libsyntax/owned_slice.rs | 2 +- src/libsyntax/parse/lexer/mod.rs | 8 +- src/libsyntax/parse/token.rs | 10 +- src/libsyntax/ptr.rs | 11 +- src/libsyntax/util/interner.rs | 11 +- src/libterm/terminfo/mod.rs | 2 +- src/libterm/terminfo/parm.rs | 16 +-- src/libtest/lib.rs | 7 +- src/libtest/stats.rs | 4 +- src/test/compile-fail/dst-index.rs | 6 +- src/test/compile-fail/issue-14853.rs | 4 +- src/test/compile-fail/issue-15094.rs | 8 +- src/test/compile-fail/liveness-use-after-send.rs | 4 +- src/test/run-fail/assert-eq-macro-panic.rs | 2 +- src/test/run-pass/cfg_attr.rs | 38 +++--- src/test/run-pass/coerce-expect-unsized.rs | 10 +- src/test/run-pass/coherence-where-clause.rs | 6 +- src/test/run-pass/deriving-show-2.rs | 36 +++--- src/test/run-pass/deriving-show.rs | 16 +-- src/test/run-pass/dst-index.rs | 10 +- src/test/run-pass/ifmt.rs | 24 ++-- src/test/run-pass/issue-20676.rs | 2 +- src/test/run-pass/issue-3559.rs | 4 +- src/test/run-pass/issue-4252.rs | 12 +- src/test/run-pass/issue-8898.rs | 6 +- .../log-knows-the-names-of-variants-in-std.rs | 8 +- .../run-pass/log-knows-the-names-of-variants.rs | 8 +- src/test/run-pass/multidispatch1.rs | 4 +- src/test/run-pass/multidispatch2.rs | 4 +- src/test/run-pass/no-landing-pads.rs | 2 +- src/test/run-pass/overloaded-index-assoc-list.rs | 2 +- src/test/run-pass/rec-align-u32.rs | 6 +- src/test/run-pass/rec-align-u64.rs | 6 +- src/test/run-pass/sepcomp-unwind.rs | 2 +- src/test/run-pass/show-boxed-slice.rs | 2 +- src/test/run-pass/small-enums-with-fields.rs | 14 +- src/test/run-pass/tag-align-shape.rs | 6 +- src/test/run-pass/unit-like-struct-drop-run.rs | 2 +- src/test/run-pass/vec-to_str.rs | 6 +- src/test/run-pass/wait-forked-but-failed-child.rs | 2 +- 137 files changed, 865 insertions(+), 808 deletions(-) create mode 100644 src/libcore/error.rs delete mode 100644 src/libstd/error.rs (limited to 'src/libstd') diff --git a/src/compiletest/common.rs b/src/compiletest/common.rs index c29f74d7418..8de8d9ce741 100644 --- a/src/compiletest/common.rs +++ b/src/compiletest/common.rs @@ -13,7 +13,7 @@ use std::fmt; use std::str::FromStr; use regex::Regex; -#[derive(Clone, PartialEq)] +#[derive(Clone, PartialEq, Debug)] pub enum Mode { CompileFail, RunFail, @@ -43,9 +43,9 @@ impl FromStr for Mode { } } -impl fmt::String for Mode { +impl fmt::Display for Mode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(match *self { + fmt::Display::fmt(match *self { CompileFail => "compile-fail", RunFail => "run-fail", RunPass => "run-pass", @@ -58,12 +58,6 @@ impl fmt::String for Mode { } } -impl fmt::Show for Mode { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - #[derive(Clone)] pub struct Config { // The library paths required for running the compiler diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 5579479c5e5..d9debb88a5c 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -547,7 +547,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) { // Add line breakpoints for line in breakpoint_lines.iter() { - script_str.push_str(&format!("break '{:?}':{}\n", + script_str.push_str(&format!("break '{}':{}\n", testfile.filename_display(), *line)[]); } @@ -750,7 +750,7 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) status: status, stdout: out, stderr: err, - cmdline: format!("{}", cmd) + cmdline: format!("{:?}", cmd) }; } } @@ -953,7 +953,7 @@ fn check_expected_errors(expected_errors: Vec , } let prefixes = expected_errors.iter().map(|ee| { - format!("{:?}:{}:", testfile.display(), ee.line) + format!("{}:{}:", testfile.display(), ee.line) }).collect:: >(); #[cfg(windows)] diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index c0cd034abfa..5f8cd6baf9a 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -72,7 +72,7 @@ use core::prelude::*; use core::atomic; use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst}; use core::borrow::BorrowFrom; -use core::fmt::{self, Show}; +use core::fmt; use core::cmp::{Ordering}; use core::default::Default; use core::mem::{min_align_of, size_of}; @@ -578,16 +578,17 @@ impl Ord for Arc { #[stable] impl Eq for Arc {} -impl fmt::Show for Arc { +#[stable] +impl fmt::Display for Arc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Arc({:?})", (**self)) + fmt::Display::fmt(&**self, f) } } #[stable] -impl fmt::String for Arc { +impl fmt::Debug for Arc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&**self, f) + fmt::Debug::fmt(&**self, f) } } @@ -806,7 +807,7 @@ mod tests { #[test] fn show_arc() { let a = Arc::new(5u32); - assert!(format!("{:?}", a) == "Arc(5u32)") + assert_eq!(format!("{:?}", a), "5"); } // Make sure deriving works with Arc diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index a2cc98c7d01..c2ee1a5d024 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -16,16 +16,17 @@ use core::any::Any; use core::clone::Clone; use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering}; use core::default::Default; +use core::error::{Error, FromError}; use core::fmt; use core::hash::{self, Hash}; use core::marker::Sized; use core::mem; +use core::ops::{Deref, DerefMut}; use core::option::Option; use core::ptr::Unique; use core::raw::TraitObject; -use core::result::Result; use core::result::Result::{Ok, Err}; -use core::ops::{Deref, DerefMut}; +use core::result::Result; /// A value that represents the global exchange heap. This is the default /// place that the `box` keyword allocates into when no place is supplied. @@ -156,20 +157,22 @@ impl BoxAny for Box { } } -impl fmt::Show for Box { +#[stable] +impl fmt::Display for Box { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Box({:?})", &**self) + fmt::Display::fmt(&**self, f) } } #[stable] -impl fmt::String for Box { +impl fmt::Debug for Box { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&**self, f) + fmt::Debug::fmt(&**self, f) } } -impl fmt::Show for Box { +#[stable] +impl fmt::Debug for Box { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad("Box") } @@ -187,6 +190,12 @@ impl DerefMut for Box { fn deref_mut(&mut self) -> &mut T { &mut **self } } +impl<'a, E: Error + 'a> FromError for Box { + fn from_error(err: E) -> Box { + Box::new(err) + } +} + #[cfg(test)] mod test { #[test] diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 7191a7af346..9a4221699b1 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -693,17 +693,17 @@ impl> Hash for Rc { } } -#[unstable = "Show is experimental."] -impl fmt::Show for Rc { +#[stable] +impl fmt::Display for Rc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Rc({:?})", **self) + fmt::Display::fmt(&**self, f) } } #[stable] -impl fmt::String for Rc { +impl fmt::Debug for Rc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&**self, f) + fmt::Debug::fmt(&**self, f) } } @@ -890,8 +890,8 @@ impl Clone for Weak { } } -#[unstable = "Show is experimental."] -impl fmt::Show for Weak { +#[stable] +impl fmt::Debug for Weak { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "(Weak)") } @@ -1134,7 +1134,7 @@ mod tests { #[test] fn test_show() { let foo = Rc::new(75u); - assert!(format!("{:?}", foo) == "Rc(75u)") + assert_eq!(format!("{:?}", foo), "75"); } } diff --git a/src/libcollections/bit.rs b/src/libcollections/bit.rs index efd056b0d66..605828567b3 100644 --- a/src/libcollections/bit.rs +++ b/src/libcollections/bit.rs @@ -972,7 +972,7 @@ impl Ord for Bitv { } #[stable] -impl fmt::Show for Bitv { +impl fmt::Debug for Bitv { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { for bit in self.iter() { try!(write!(fmt, "{}", if bit { 1u32 } else { 0u32 })); @@ -1727,7 +1727,7 @@ impl BitvSet { } } -impl fmt::Show for BitvSet { +impl fmt::Debug for BitvSet { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "BitvSet {{")); let mut first = true; @@ -2622,7 +2622,7 @@ mod bitv_set_test { s.insert(10); s.insert(50); s.insert(2); - assert_eq!("BitvSet {1u, 2u, 10u, 50u}", format!("{:?}", s)); + assert_eq!("BitvSet {1, 2, 10, 50}", format!("{:?}", s)); } #[test] diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index c56592177b4..8c2f00a5695 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -22,7 +22,7 @@ use core::prelude::*; use core::borrow::BorrowFrom; use core::cmp::Ordering; use core::default::Default; -use core::fmt::Show; +use core::fmt::Debug; use core::hash::{Hash, Hasher}; use core::iter::{Map, FromIterator}; use core::ops::{Index, IndexMut}; @@ -871,7 +871,7 @@ impl Ord for BTreeMap { } #[stable] -impl Show for BTreeMap { +impl Debug for BTreeMap { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "BTreeMap {{")); diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 4d71f9dbea8..5966c11be1b 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -16,7 +16,7 @@ use core::prelude::*; use core::borrow::BorrowFrom; use core::cmp::Ordering::{self, Less, Greater, Equal}; use core::default::Default; -use core::fmt::Show; +use core::fmt::Debug; use core::fmt; // NOTE(stage0) remove import after a snapshot #[cfg(stage0)] @@ -592,7 +592,7 @@ impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet> for &'a BTreeSet { } #[stable] -impl Show for BTreeSet { +impl Debug for BTreeSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "BTreeSet {{")); @@ -892,7 +892,7 @@ mod test { let set_str = format!("{:?}", set); - assert_eq!(set_str, "BTreeSet {1i, 2i}"); + assert_eq!(set_str, "BTreeSet {1, 2}"); assert_eq!(format!("{:?}", empty), "BTreeSet {}"); } } diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index cce8cf398e1..73fd806c907 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -874,7 +874,7 @@ impl Clone for DList { } #[stable] -impl fmt::Show for DList { +impl fmt::Debug for DList { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "DList [")); @@ -1333,7 +1333,7 @@ mod tests { #[test] fn test_show() { let list: DList = range(0i, 10).collect(); - assert_eq!(format!("{:?}", list), "DList [0i, 1i, 2i, 3i, 4i, 5i, 6i, 7i, 8i, 9i]"); + assert_eq!(format!("{:?}", list), "DList [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); let list: DList<&str> = vec!["just", "one", "test", "more"].iter() .map(|&s| s) diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index 1b852d0ba68..a40a590c51a 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -31,7 +31,7 @@ pub struct EnumSet { impl Copy for EnumSet {} -impl fmt::Show for EnumSet { +impl fmt::Debug for EnumSet { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "EnumSet {{")); let mut first = true; diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index b9cb4be7c18..badd7a8d6cc 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -1611,7 +1611,7 @@ impl Extend for RingBuf { } #[stable] -impl fmt::Show for RingBuf { +impl fmt::Debug for RingBuf { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "RingBuf [")); @@ -1630,7 +1630,7 @@ mod tests { use self::Taggypar::*; use prelude::*; use core::iter; - use std::fmt::Show; + use std::fmt::Debug; use std::hash::{self, SipHasher}; use test::Bencher; use test; @@ -1678,7 +1678,7 @@ mod tests { } #[cfg(test)] - fn test_parameterized(a: T, b: T, c: T, d: T) { + fn test_parameterized(a: T, b: T, c: T, d: T) { let mut deq = RingBuf::new(); assert_eq!(deq.len(), 0); deq.push_front(a.clone()); @@ -2302,7 +2302,7 @@ mod tests { #[test] fn test_show() { let ringbuf: RingBuf = range(0i, 10).collect(); - assert_eq!(format!("{:?}", ringbuf), "RingBuf [0i, 1i, 2i, 3i, 4i, 5i, 6i, 7i, 8i, 9i]"); + assert_eq!(format!("{:?}", ringbuf), "RingBuf [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter() .map(|&s| s) diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 988ec4c661f..82966727037 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -2476,19 +2476,19 @@ mod tests { } let empty: Vec = vec![]; test_show_vec!(empty, "[]"); - test_show_vec!(vec![1i], "[1i]"); - test_show_vec!(vec![1i, 2, 3], "[1i, 2i, 3i]"); + test_show_vec!(vec![1i], "[1]"); + test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]"); test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]], - "[[], [1u], [1u, 1u]]"); + "[[], [1], [1, 1]]"); let empty_mut: &mut [int] = &mut[]; test_show_vec!(empty_mut, "[]"); let v: &mut[int] = &mut[1]; - test_show_vec!(v, "[1i]"); + test_show_vec!(v, "[1]"); let v: &mut[int] = &mut[1, 2, 3]; - test_show_vec!(v, "[1i, 2i, 3i]"); + test_show_vec!(v, "[1, 2, 3]"); let v: &mut [&mut[uint]] = &mut[&mut[], &mut[1u], &mut[1u, 1u]]; - test_show_vec!(v, "[[], [1u], [1u, 1u]]"); + test_show_vec!(v, "[[], [1], [1, 1]]"); } #[test] diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 5d35d8a8679..e6f438ecded 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -18,6 +18,7 @@ use core::prelude::*; use core::borrow::{Cow, IntoCow}; use core::default::Default; +use core::error::Error; use core::fmt; use core::hash; use core::iter::FromIterator; @@ -40,6 +41,7 @@ pub struct String { /// A possible error value from the `String::from_utf8` function. #[stable] +#[derive(Show)] pub struct FromUtf8Error { bytes: Vec, error: Utf8Error, @@ -48,6 +50,7 @@ pub struct FromUtf8Error { /// A possible error value from the `String::from_utf16` function. #[stable] #[allow(missing_copy_implementations)] +#[derive(Show)] pub struct FromUtf16Error(()); impl String { @@ -680,30 +683,28 @@ impl FromUtf8Error { pub fn utf8_error(&self) -> Utf8Error { self.error } } -impl fmt::Show for FromUtf8Error { +#[stable] +impl fmt::Display for FromUtf8Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt(&self.error, f) } } #[stable] -impl fmt::String for FromUtf8Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&self.error, f) - } +impl Error for FromUtf8Error { + fn description(&self) -> &str { "invalid utf-8" } } -impl fmt::Show for FromUtf16Error { +#[stable] +impl fmt::Display for FromUtf16Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt("invalid utf-16: lone surrogate found", f) } } #[stable] -impl fmt::String for FromUtf16Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt("invalid utf-16: lone surrogate found", f) - } +impl Error for FromUtf16Error { + fn description(&self) -> &str { "invalid utf-16" } } #[stable] @@ -814,18 +815,18 @@ impl Default for String { } #[stable] -impl fmt::String for String { +impl fmt::Display for String { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&**self, f) + fmt::Display::fmt(&**self, f) } } -#[unstable = "waiting on fmt stabilization"] -impl fmt::Show for String { +#[stable] +impl fmt::Debug for String { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(&**self, f) + fmt::Debug::fmt(&**self, f) } } @@ -934,7 +935,7 @@ pub trait ToString { fn to_string(&self) -> String; } -impl ToString for T { +impl ToString for T { #[inline] fn to_string(&self) -> String { use core::fmt::Writer; @@ -1295,10 +1296,10 @@ mod tests { fn test_vectors() { let x: Vec = vec![]; assert_eq!(format!("{:?}", x), "[]"); - assert_eq!(format!("{:?}", vec![1i]), "[1i]"); - assert_eq!(format!("{:?}", vec![1i, 2, 3]), "[1i, 2i, 3i]"); + assert_eq!(format!("{:?}", vec![1i]), "[1]"); + assert_eq!(format!("{:?}", vec![1i, 2, 3]), "[1, 2, 3]"); assert!(format!("{:?}", vec![vec![], vec![1i], vec![1i, 1]]) == - "[[], [1i], [1i, 1i]]"); + "[[], [1], [1, 1]]"); } #[test] diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 4ddab8c533a..0b20a3a5f75 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1486,10 +1486,10 @@ impl Default for Vec { } } -#[unstable = "waiting on Show stability"] -impl fmt::Show for Vec { +#[stable] +impl fmt::Debug for Vec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(self.as_slice(), f) + fmt::Debug::fmt(self.as_slice(), f) } } diff --git a/src/libcollections/vec_map.rs b/src/libcollections/vec_map.rs index 7ff2e953588..f178d5bc7e9 100644 --- a/src/libcollections/vec_map.rs +++ b/src/libcollections/vec_map.rs @@ -513,7 +513,7 @@ impl Ord for VecMap { } #[stable] -impl fmt::Show for VecMap { +impl fmt::Debug for VecMap { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "VecMap {{")); @@ -990,7 +990,7 @@ mod test_map { map.insert(3, 4i); let map_str = format!("{:?}", map); - assert!(map_str == "VecMap {1: 2i, 3: 4i}" || map_str == "{3: 4i, 1: 2i}"); + assert!(map_str == "VecMap {1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); assert_eq!(format!("{:?}", empty), "VecMap {}"); } diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 20ed2253861..6e9d2f349bf 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -34,11 +34,11 @@ //! use runtime reflection instead. //! //! ```rust -//! use std::fmt::Show; +//! use std::fmt::Debug; //! use std::any::Any; //! -//! // Logger function for any type that implements Show. -//! fn log(value: &T) { +//! // Logger function for any type that implements Debug. +//! fn log(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to @@ -55,7 +55,7 @@ //! } //! //! // This function wants to log its parameter out prior to doing work with it. -//! fn do_work(value: &T) { +//! fn do_work(value: &T) { //! log(value); //! // ...do some other work //! } diff --git a/src/libcore/array.rs b/src/libcore/array.rs index 0cc31bf70de..a83537e12f7 100644 --- a/src/libcore/array.rs +++ b/src/libcore/array.rs @@ -39,10 +39,10 @@ macro_rules! array_impls { } } - #[unstable = "waiting for Show to stabilize"] - impl fmt::Show for [T; $N] { + #[stable] + impl fmt::Debug for [T; $N] { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(&&self[], f) + fmt::Debug::fmt(&&self[], f) } } diff --git a/src/libcore/borrow.rs b/src/libcore/borrow.rs index 4363a0a4441..63614aaa463 100644 --- a/src/libcore/borrow.rs +++ b/src/libcore/borrow.rs @@ -133,7 +133,6 @@ impl ToOwned for T where T: Clone { /// } /// } /// ``` -#[derive(Show)] pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned { /// Borrowed data. Borrowed(&'a B), @@ -239,14 +238,27 @@ impl<'a, T, B: ?Sized> PartialOrd for Cow<'a, T, B> where B: PartialOrd + ToOwne } #[stable] -impl<'a, T, B: ?Sized> fmt::String for Cow<'a, T, B> where - B: fmt::String + ToOwned, - T: fmt::String, +impl<'a, T, B: ?Sized> fmt::Debug for Cow<'a, T, B> where + B: fmt::Debug + ToOwned, + T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Borrowed(ref b) => fmt::String::fmt(b, f), - Owned(ref o) => fmt::String::fmt(o, f), + Borrowed(ref b) => fmt::Debug::fmt(b, f), + Owned(ref o) => fmt::Debug::fmt(o, f), + } + } +} + +#[stable] +impl<'a, T, B: ?Sized> fmt::Display for Cow<'a, T, B> where + B: fmt::Display + ToOwned, + T: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Borrowed(ref b) => fmt::Display::fmt(b, f), + Owned(ref o) => fmt::Display::fmt(o, f), } } } diff --git a/src/libcore/error.rs b/src/libcore/error.rs new file mode 100644 index 00000000000..9ff38028df9 --- /dev/null +++ b/src/libcore/error.rs @@ -0,0 +1,110 @@ +// Copyright 2014 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Traits for working with Errors. +//! +//! # The `Error` trait +//! +//! `Error` is a trait representing the basic expectations for error values, +//! i.e. values of type `E` in `Result`. At a minimum, errors must provide +//! a description, but they may optionally provide additional detail (via +//! `Display`) and cause chain information: +//! +//! ``` +//! use std::fmt::Display; +//! +//! trait Error: Display { +//! fn description(&self) -> &str; +//! +//! fn cause(&self) -> Option<&Error> { None } +//! } +//! ``` +//! +//! The `cause` method is generally used when errors cross "abstraction +//! boundaries", i.e. when a one module must report an error that is "caused" +//! by an error from a lower-level module. This setup makes it possible for the +//! high-level module to provide its own errors that do not commit to any +//! particular implementation, but also reveal some of its implementation for +//! debugging via `cause` chains. +//! +//! # The `FromError` trait +//! +//! `FromError` is a simple trait that expresses conversions between different +//! error types. To provide maximum flexibility, it does not require either of +//! the types to actually implement the `Error` trait, although this will be the +//! common case. +//! +//! The main use of this trait is in the `try!` macro, which uses it to +//! automatically convert a given error to the error specified in a function's +//! return type. +//! +//! For example, +//! +//! ``` +//! use std::error::FromError; +//! use std::io::{File, IoError}; +//! use std::os::{MemoryMap, MapError}; +//! use std::path::Path; +//! +//! enum MyError { +//! Io(IoError), +//! Map(MapError) +//! } +//! +//! impl FromError for MyError { +//! fn from_error(err: IoError) -> MyError { +//! MyError::Io(err) +//! } +//! } +//! +//! impl FromError for MyError { +//! fn from_error(err: MapError) -> MyError { +//! MyError::Map(err) +//! } +//! } +//! +//! #[allow(unused_variables)] +//! fn open_and_map() -> Result<(), MyError> { +//! let f = try!(File::open(&Path::new("foo.txt"))); +//! let m = try!(MemoryMap::new(0, &[])); +//! // do something interesting here... +//! Ok(()) +//! } +//! ``` + +#![stable] + +use prelude::*; +use fmt::Display; + +/// Base functionality for all errors in Rust. +#[unstable = "the exact API of this trait may change"] +pub trait Error: Display { + /// A short description of the error; usually a static string. + fn description(&self) -> &str; + + /// The lower-level cause of this error, if any. + fn cause(&self) -> Option<&Error> { None } +} + +/// A trait for types that can be converted from a given error type `E`. +#[stable] +pub trait FromError { + /// Perform the conversion. + fn from_error(err: E) -> Self; +} + +// Any type is convertable from itself +#[stable] +impl FromError for E { + fn from_error(err: E) -> E { + err + } +} diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 535722f93bf..0e8d31a62ee 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -26,12 +26,15 @@ use ops::{Deref, FnOnce}; use result; use slice::SliceExt; use slice; -use str::{self, StrExt, Utf8Error}; +use str::{self, StrExt}; pub use self::num::radix; pub use self::num::Radix; pub use self::num::RadixFmt; +#[cfg(stage0)] pub use self::Debug as Show; +#[cfg(stage0)] pub use self::Display as String; + mod num; mod float; pub mod rt; @@ -46,7 +49,7 @@ pub type Result = result::Result<(), Error>; /// occurred. Any extra information must be arranged to be transmitted through /// some other means. #[unstable = "core and I/O reconciliation may alter this definition"] -#[derive(Copy)] +#[derive(Copy, Show)] pub struct Error; /// A collection of methods that are required to format a message into a stream. @@ -133,7 +136,7 @@ pub struct Argument<'a> { impl<'a> Argument<'a> { #[inline(never)] fn show_uint(x: &uint, f: &mut Formatter) -> Result { - Show::fmt(x, f) + Display::fmt(x, f) } fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter) -> Result) -> Argument<'b> { @@ -214,14 +217,15 @@ pub struct Arguments<'a> { args: &'a [Argument<'a>], } -impl<'a> Show for Arguments<'a> { +#[stable] +impl<'a> Debug for Arguments<'a> { fn fmt(&self, fmt: &mut Formatter) -> Result { - String::fmt(self, fmt) + Display::fmt(self, fmt) } } #[stable] -impl<'a> String for Arguments<'a> { +impl<'a> Display for Arguments<'a> { fn fmt(&self, fmt: &mut Formatter) -> Result { write(fmt.buf, *self) } @@ -229,20 +233,49 @@ impl<'a> String for Arguments<'a> { /// Format trait for the `:?` format. Useful for debugging, most all types /// should implement this. -#[unstable = "I/O and core have yet to be reconciled"] +#[deprecated = "renamed to Debug"] +#[cfg(not(stage0))] pub trait Show { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } +/// Format trait for the `:?` format. Useful for debugging, most all types +/// should implement this. +#[unstable = "I/O and core have yet to be reconciled"] +pub trait Debug { + /// Formats the value using the given formatter. + fn fmt(&self, &mut Formatter) -> Result; +} + +#[cfg(not(stage0))] +impl Debug for T { + #[allow(deprecated)] + fn fmt(&self, f: &mut Formatter) -> Result { Show::fmt(self, f) } +} + +/// When a value can be semantically expressed as a String, this trait may be +/// used. It corresponds to the default format, `{}`. +#[deprecated = "renamed to Display"] +#[cfg(not(stage0))] +pub trait String { + /// Formats the value using the given formatter. + fn fmt(&self, &mut Formatter) -> Result; +} + /// When a value can be semantically expressed as a String, this trait may be /// used. It corresponds to the default format, `{}`. #[unstable = "I/O and core have yet to be reconciled"] -pub trait String { +pub trait Display { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } +#[cfg(not(stage0))] +impl Display for T { + #[allow(deprecated)] + fn fmt(&self, f: &mut Formatter) -> Result { String::fmt(self, f) } +} /// Format trait for the `o` character #[unstable = "I/O and core have yet to be reconciled"] @@ -583,9 +616,10 @@ impl<'a> Formatter<'a> { pub fn precision(&self) -> Option { self.precision } } -impl Show for Error { +#[stable] +impl Display for Error { fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt("an error occurred when formatting an argument", f) + Display::fmt("an error occurred when formatting an argument", f) } } @@ -611,9 +645,11 @@ pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> { macro_rules! fmt_refs { ($($tr:ident),*) => { $( + #[stable] impl<'a, T: ?Sized + $tr> $tr for &'a T { fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) } } + #[stable] impl<'a, T: ?Sized + $tr> $tr for &'a mut T { fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) } } @@ -621,22 +657,24 @@ macro_rules! fmt_refs { } } -fmt_refs! { Show, String, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp } +fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp } -impl Show for bool { +#[stable] +impl Debug for bool { fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt(self, f) + Display::fmt(self, f) } } #[stable] -impl String for bool { +impl Display for bool { fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt(if *self { "true" } else { "false" }, f) + Display::fmt(if *self { "true" } else { "false" }, f) } } -impl Show for str { +#[stable] +impl Debug for str { fn fmt(&self, f: &mut Formatter) -> Result { try!(write!(f, "\"")); for c in self.chars().flat_map(|c| c.escape_default()) { @@ -647,13 +685,14 @@ impl Show for str { } #[stable] -impl String for str { +impl Display for str { fn fmt(&self, f: &mut Formatter) -> Result { f.pad(self) } } -impl Show for char { +#[stable] +impl Debug for char { fn fmt(&self, f: &mut Formatter) -> Result { use char::CharExt; try!(write!(f, "'")); @@ -665,15 +704,16 @@ impl Show for char { } #[stable] -impl String for char { +impl Display for char { fn fmt(&self, f: &mut Formatter) -> Result { let mut utf8 = [0u8; 4]; let amt = self.encode_utf8(&mut utf8).unwrap_or(0); let s: &str = unsafe { mem::transmute(&utf8[..amt]) }; - String::fmt(s, f) + Display::fmt(s, f) } } +#[stable] impl Pointer for *const T { fn fmt(&self, f: &mut Formatter) -> Result { f.flags |= 1 << (rt::FlagAlternate as uint); @@ -683,18 +723,21 @@ impl Pointer for *const T { } } +#[stable] impl Pointer for *mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(*self as *const T), f) } } +#[stable] impl<'a, T> Pointer for &'a T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(*self as *const T), f) } } +#[stable] impl<'a, T> Pointer for &'a mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(&**self as *const T), f) @@ -703,15 +746,15 @@ impl<'a, T> Pointer for &'a mut T { macro_rules! floating { ($ty:ident) => { - impl Show for $ty { + #[stable] + impl Debug for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { - try!(String::fmt(self, fmt)); - fmt.write_str(stringify!($ty)) + Display::fmt(self, fmt) } } #[stable] - impl String for $ty { + impl Display for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -732,6 +775,7 @@ macro_rules! floating { ($ty:ident) => { } } + #[stable] impl LowerExp for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -753,6 +797,7 @@ macro_rules! floating { ($ty:ident) => { } } + #[stable] impl UpperExp for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -777,12 +822,14 @@ macro_rules! floating { ($ty:ident) => { floating! { f32 } floating! { f64 } -// Implementation of Show for various core types +// Implementation of Display/Debug for various core types -impl Show for *const T { +#[stable] +impl Debug for *const T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } -impl Show for *mut T { +#[stable] +impl Debug for *mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } @@ -793,7 +840,8 @@ macro_rules! peel { macro_rules! tuple { () => (); ( $($name:ident,)+ ) => ( - impl<$($name:Show),*> Show for ($($name,)*) { + #[stable] + impl<$($name:Debug),*> Debug for ($($name,)*) { #[allow(non_snake_case, unused_assignments)] fn fmt(&self, f: &mut Formatter) -> Result { try!(write!(f, "(")); @@ -818,11 +866,13 @@ macro_rules! tuple { tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, } -impl<'a> Show for &'a (any::Any+'a) { +#[stable] +impl<'a> Debug for &'a (any::Any+'a) { fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") } } -impl Show for [T] { +#[stable] +impl Debug for [T] { fn fmt(&self, f: &mut Formatter) -> Result { if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 { try!(write!(f, "[")); @@ -843,20 +893,22 @@ impl Show for [T] { } } -impl Show for () { +#[stable] +impl Debug for () { fn fmt(&self, f: &mut Formatter) -> Result { f.pad("()") } } -impl Show for Cell { +#[stable] +impl Debug for Cell { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "Cell {{ value: {:?} }}", self.get()) } } -#[unstable] -impl Show for RefCell { +#[stable] +impl Debug for RefCell { fn fmt(&self, f: &mut Formatter) -> Result { match self.try_borrow() { Some(val) => write!(f, "RefCell {{ value: {:?} }}", val), @@ -865,29 +917,17 @@ impl Show for RefCell { } } -impl<'b, T: Show> Show for Ref<'b, T> { - fn fmt(&self, f: &mut Formatter) -> Result { - Show::fmt(&**self, f) - } -} - -impl<'b, T: Show> Show for RefMut<'b, T> { +#[stable] +impl<'b, T: Debug> Debug for Ref<'b, T> { fn fmt(&self, f: &mut Formatter) -> Result { - Show::fmt(&*(self.deref()), f) + Debug::fmt(&**self, f) } } #[stable] -impl String for Utf8Error { +impl<'b, T: Debug> Debug for RefMut<'b, T> { fn fmt(&self, f: &mut Formatter) -> Result { - match *self { - Utf8Error::InvalidByte(n) => { - write!(f, "invalid utf-8: invalid byte at index {}", n) - } - Utf8Error::TooShort => { - write!(f, "invalid utf-8: byte slice too short") - } - } + Debug::fmt(&*(self.deref()), f) } } diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index 1df6f845225..c456b3379e8 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -154,13 +154,14 @@ pub fn radix(x: T, base: u8) -> RadixFmt { macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident, $S:expr) => { - impl fmt::Show for RadixFmt<$T, Radix> { + #[stable] + impl fmt::Debug for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(fmt::String::fmt(self, f)); - f.write_str($S) + fmt::Display::fmt(self, f) } } - impl fmt::String for RadixFmt<$T, Radix> { + #[stable] + impl fmt::Display for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) } } @@ -169,6 +170,7 @@ macro_rules! radix_fmt { } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { + #[stable] impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { $Radix.fmt_int(*self as $U, f) @@ -179,10 +181,10 @@ macro_rules! int_base { macro_rules! show { ($T:ident with $S:expr) => { - impl fmt::Show for $T { + #[stable] + impl fmt::Debug for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(fmt::String::fmt(self, f)); - f.write_str($S) + fmt::Display::fmt(self, f) } } } @@ -192,7 +194,7 @@ macro_rules! integer { integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) } }; ($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => { - int_base! { String for $Int as $Int -> Decimal } + int_base! { Display for $Int as $Int -> Decimal } int_base! { Binary for $Int as $Uint -> Binary } int_base! { Octal for $Int as $Uint -> Octal } int_base! { LowerHex for $Int as $Uint -> LowerHex } @@ -200,7 +202,7 @@ macro_rules! integer { radix_fmt! { $Int as $Int, fmt_int, $SI } show! { $Int with $SI } - int_base! { String for $Uint as $Uint -> Decimal } + int_base! { Display for $Uint as $Uint -> Decimal } int_base! { Binary for $Uint as $Uint -> Binary } int_base! { Octal for $Uint as $Uint -> Octal } int_base! { LowerHex for $Uint as $Uint -> LowerHex } diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 0b150d1ecf9..bbe5cfe1cbb 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -136,6 +136,7 @@ pub mod slice; pub mod str; pub mod hash; pub mod fmt; +pub mod error; // note: does not need to be public mod tuple; diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 7131253d5c4..853e4adb892 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -885,10 +885,10 @@ pub trait IndexMut { #[unstable = "API still in development"] pub struct FullRange; -#[unstable = "API still in development"] -impl fmt::Show for FullRange { +#[stable] +impl fmt::Debug for FullRange { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt("..", fmt) + fmt::Debug::fmt("..", fmt) } } @@ -944,8 +944,8 @@ impl DoubleEndedIterator for Range { #[unstable = "API still in development"] impl ExactSizeIterator for Range {} -#[unstable = "API still in development"] -impl fmt::Show for Range { +#[stable] +impl fmt::Debug for Range { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}..{:?}", self.start, self.end) } @@ -973,8 +973,8 @@ impl Iterator for RangeFrom { } } -#[unstable = "API still in development"] -impl fmt::Show for RangeFrom { +#[stable] +impl fmt::Debug for RangeFrom { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}..", self.start) } @@ -989,8 +989,8 @@ pub struct RangeTo { pub end: Idx, } -#[unstable = "API still in development"] -impl fmt::Show for RangeTo { +#[stable] +impl fmt::Debug for RangeTo { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "..{:?}", self.end) } diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 1ab810f937d..c3d49e24978 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -229,7 +229,7 @@ use self::Result::{Ok, Err}; use clone::Clone; -use fmt::Show; +use fmt::Display; use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator}; use ops::{FnMut, FnOnce}; use option::Option::{self, None, Some}; @@ -714,7 +714,7 @@ impl Result { } #[stable] -impl Result { +impl Result { /// Unwraps a result, yielding the content of an `Ok`. /// /// # Panics @@ -739,13 +739,13 @@ impl Result { match self { Ok(t) => t, Err(e) => - panic!("called `Result::unwrap()` on an `Err` value: {:?}", e) + panic!("called `Result::unwrap()` on an `Err` value: {}", e) } } } #[stable] -impl Result { +impl Result { /// Unwraps a result, yielding the content of an `Err`. /// /// # Panics @@ -769,7 +769,7 @@ impl Result { pub fn unwrap_err(self) -> E { match self { Ok(t) => - panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t), + panic!("called `Result::unwrap_err()` on an `Ok` value: {}", t), Err(e) => e } } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 6a542b2c458..f8bd48220ba 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -20,8 +20,10 @@ use self::Searcher::{Naive, TwoWay, TwoWayLong}; use cmp::{self, Eq}; use default::Default; -use iter::range; +use error::Error; +use fmt; use iter::ExactSizeIterator; +use iter::range; use iter::{Map, Iterator, IteratorExt, DoubleEndedIterator}; use marker::Sized; use mem; @@ -242,6 +244,30 @@ impl<'a> CharEq for &'a [char] { } } +#[stable] +impl Error for Utf8Error { + fn description(&self) -> &str { + match *self { + Utf8Error::TooShort => "invalid utf-8: not enough bytes", + Utf8Error::InvalidByte(..) => "invalid utf-8: corrupt contents", + } + } +} + +#[stable] +impl fmt::Display for Utf8Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Utf8Error::InvalidByte(n) => { + write!(f, "invalid utf-8: invalid byte at index {}", n) + } + Utf8Error::TooShort => { + write!(f, "invalid utf-8: byte slice too short") + } + } + } +} + /* Section: Iterators */ diff --git a/src/libcoretest/finally.rs b/src/libcoretest/finally.rs index 979ddaecb4a..6ec87203e00 100644 --- a/src/libcoretest/finally.rs +++ b/src/libcoretest/finally.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(deprecated)] + use core::finally::{try_finally, Finally}; use std::thread::Thread; diff --git a/src/libcoretest/fmt/num.rs b/src/libcoretest/fmt/num.rs index c259e4cbb68..eb278d2cc90 100644 --- a/src/libcoretest/fmt/num.rs +++ b/src/libcoretest/fmt/num.rs @@ -26,11 +26,11 @@ fn test_format_int() { assert!(format!("{}", -1i16) == "-1"); assert!(format!("{}", -1i32) == "-1"); assert!(format!("{}", -1i64) == "-1"); - assert!(format!("{:?}", 1i) == "1i"); - assert!(format!("{:?}", 1i8) == "1i8"); - assert!(format!("{:?}", 1i16) == "1i16"); - assert!(format!("{:?}", 1i32) == "1i32"); - assert!(format!("{:?}", 1i64) == "1i64"); + assert!(format!("{:?}", 1i) == "1"); + assert!(format!("{:?}", 1i8) == "1"); + assert!(format!("{:?}", 1i16) == "1"); + assert!(format!("{:?}", 1i32) == "1"); + assert!(format!("{:?}", 1i64) == "1"); assert!(format!("{:b}", 1i) == "1"); assert!(format!("{:b}", 1i8) == "1"); assert!(format!("{:b}", 1i16) == "1"); @@ -57,11 +57,11 @@ fn test_format_int() { assert!(format!("{}", 1u16) == "1"); assert!(format!("{}", 1u32) == "1"); assert!(format!("{}", 1u64) == "1"); - assert!(format!("{:?}", 1u) == "1u"); - assert!(format!("{:?}", 1u8) == "1u8"); - assert!(format!("{:?}", 1u16) == "1u16"); - assert!(format!("{:?}", 1u32) == "1u32"); - assert!(format!("{:?}", 1u64) == "1u64"); + assert!(format!("{:?}", 1u) == "1"); + assert!(format!("{:?}", 1u8) == "1"); + assert!(format!("{:?}", 1u16) == "1"); + assert!(format!("{:?}", 1u32) == "1"); + assert!(format!("{:?}", 1u64) == "1"); assert!(format!("{:b}", 1u) == "1"); assert!(format!("{:b}", 1u8) == "1"); assert!(format!("{:b}", 1u16) == "1"); @@ -94,14 +94,14 @@ fn test_format_int() { #[test] fn test_format_int_zero() { assert!(format!("{}", 0i) == "0"); - assert!(format!("{:?}", 0i) == "0i"); + assert!(format!("{:?}", 0i) == "0"); assert!(format!("{:b}", 0i) == "0"); assert!(format!("{:o}", 0i) == "0"); assert!(format!("{:x}", 0i) == "0"); assert!(format!("{:X}", 0i) == "0"); assert!(format!("{}", 0u) == "0"); - assert!(format!("{:?}", 0u) == "0u"); + assert!(format!("{:?}", 0u) == "0"); assert!(format!("{:b}", 0u) == "0"); assert!(format!("{:o}", 0u) == "0"); assert!(format!("{:x}", 0u) == "0"); diff --git a/src/libcoretest/num/mod.rs b/src/libcoretest/num/mod.rs index 8186a4f0904..e0623bade5c 100644 --- a/src/libcoretest/num/mod.rs +++ b/src/libcoretest/num/mod.rs @@ -9,7 +9,7 @@ // except according to those terms. use core::cmp::PartialEq; -use core::fmt::Show; +use core::fmt::Debug; use core::num::{NumCast, cast}; use core::ops::{Add, Sub, Mul, Div, Rem}; use core::marker::Copy; @@ -37,7 +37,7 @@ pub fn test_num(ten: T, two: T) where T: PartialEq + NumCast + Add + Sub + Mul + Div - + Rem + Show + + Rem + Debug + Copy { assert_eq!(ten.add(two), cast(12i).unwrap()); diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index 485549cc552..daccb709890 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -14,11 +14,11 @@ pub fn op2() -> Result { Err("sadface") } #[test] pub fn test_and() { assert_eq!(op1().and(Ok(667i)).unwrap(), 667); - assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(), + assert_eq!(op1().and(Err::("bad")).unwrap_err(), "bad"); assert_eq!(op2().and(Ok(667i)).unwrap_err(), "sadface"); - assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(), + assert_eq!(op2().and(Err::("bad")).unwrap_err(), "sadface"); } @@ -94,7 +94,7 @@ pub fn test_fmt_default() { let err: Result = Err("Err"); let s = format!("{:?}", ok); - assert_eq!(s, "Ok(100i)"); + assert_eq!(s, "Ok(100)"); let s = format!("{:?}", err); assert_eq!(s, "Err(\"Err\")"); } diff --git a/src/libcoretest/tuple.rs b/src/libcoretest/tuple.rs index 62eb9f4ad34..e524d8de056 100644 --- a/src/libcoretest/tuple.rs +++ b/src/libcoretest/tuple.rs @@ -60,9 +60,9 @@ fn test_tuple_cmp() { #[test] fn test_show() { let s = format!("{:?}", (1i,)); - assert_eq!(s, "(1i,)"); + assert_eq!(s, "(1,)"); let s = format!("{:?}", (1i, true)); - assert_eq!(s, "(1i, true)"); + assert_eq!(s, "(1, true)"); let s = format!("{:?}", (1i, "hi", true)); - assert_eq!(s, "(1i, \"hi\", true)"); + assert_eq!(s, "(1, \"hi\", true)"); } diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index c2114d4c6df..9b0b741e692 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -544,7 +544,7 @@ impl Fail { } } -impl fmt::String for Fail { +impl fmt::Display for Fail { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ArgumentMissing(ref nm) => { diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 2d7d88f0f35..0ed32b7bf4f 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -358,19 +358,19 @@ impl<'a> Id<'a> { /// /// Passing an invalid string (containing spaces, brackets, /// quotes, ...) will return an empty `Err` value. - pub fn new>(name: Name) -> Result, ()> { + pub fn new>(name: Name) -> Option> { let name = name.into_cow(); { let mut chars = name.chars(); match chars.next() { Some(c) if is_letter_or_underscore(c) => { ; }, - _ => return Err(()) + _ => return None } if !chars.all(is_constituent) { - return Err(()); + return None } } - return Ok(Id{ name: name }); + return Some(Id{ name: name }); fn is_letter_or_underscore(c: char) -> bool { in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_' @@ -874,8 +874,8 @@ r#"digraph syntax_tree { fn simple_id_construction() { let id1 = Id::new("hello"); match id1 { - Ok(_) => {;}, - Err(_) => panic!("'hello' is not a valid value for id anymore") + Some(_) => {;}, + None => panic!("'hello' is not a valid value for id anymore") } } @@ -883,8 +883,8 @@ r#"digraph syntax_tree { fn badly_formatted_id() { let id2 = Id::new("Weird { struct : ure } !!!"); match id2 { - Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"), - Err(_) => {;} + Some(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"), + None => {;} } } } diff --git a/src/libgraphviz/maybe_owned_vec.rs b/src/libgraphviz/maybe_owned_vec.rs index 567fe04c5af..4e6437a5e76 100644 --- a/src/libgraphviz/maybe_owned_vec.rs +++ b/src/libgraphviz/maybe_owned_vec.rs @@ -124,7 +124,7 @@ impl<'a,T> FromIterator for MaybeOwnedVector<'a,T> { } } -impl<'a,T:fmt::Show> fmt::Show for MaybeOwnedVector<'a,T> { +impl<'a,T:fmt::Debug> fmt::Debug for MaybeOwnedVector<'a,T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_slice().fmt(f) } diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index dbd88434127..ba0f04d67da 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -239,21 +239,15 @@ struct DefaultLogger { } /// Wraps the log level with fmt implementations. -#[derive(Copy, PartialEq, PartialOrd)] +#[derive(Copy, PartialEq, PartialOrd, Show)] pub struct LogLevel(pub u32); -impl fmt::Show for LogLevel { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, fmt) - } -} - -impl fmt::String for LogLevel { +impl fmt::Display for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let LogLevel(level) = *self; match LOG_LEVEL_NAMES.get(level as uint - 1) { - Some(ref name) => fmt::String::fmt(name, fmt), - None => fmt::String::fmt(&level, fmt) + Some(ref name) => fmt::Display::fmt(name, fmt), + None => fmt::Display::fmt(&level, fmt) } } } diff --git a/src/librbml/lib.rs b/src/librbml/lib.rs index 25279796c03..50fe56ff5c0 100644 --- a/src/librbml/lib.rs +++ b/src/librbml/lib.rs @@ -38,6 +38,7 @@ pub use self::EbmlEncoderTag::*; pub use self::Error::*; use std::str; +use std::fmt; pub mod io; @@ -113,6 +114,13 @@ pub enum Error { IoError(std::io::IoError), ApplicationError(String) } + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // FIXME: this should be a more useful display form + fmt::Debug::fmt(self, f) + } +} // -------------------------------------- pub mod reader { diff --git a/src/libregex/parse.rs b/src/libregex/parse.rs index 1cc2b271e9c..7331bc36d79 100644 --- a/src/libregex/parse.rs +++ b/src/libregex/parse.rs @@ -30,6 +30,7 @@ static MAX_REPEAT: uint = 1000; /// /// (Once an expression is compiled, it is not possible to produce an error /// via searching, splitting or replacing.) +#[derive(Show)] pub struct Error { /// The *approximate* character index of where the error occurred. pub pos: uint, @@ -37,7 +38,7 @@ pub struct Error { pub msg: String, } -impl fmt::Show for Error { +impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Regex syntax error near position {}: {:?}", self.pos, self.msg) diff --git a/src/libregex/re.rs b/src/libregex/re.rs index abc51d62404..a740e2043b9 100644 --- a/src/libregex/re.rs +++ b/src/libregex/re.rs @@ -90,10 +90,10 @@ impl Clone for ExNative { } } -impl fmt::String for Regex { +impl fmt::Display for Regex { /// Shows the original regular expression. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self.as_str(), f) + fmt::Display::fmt(self.as_str(), f) } } diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index a1a90395b3b..4d0cea8d7e3 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -57,7 +57,7 @@ struct Matrix<'a>(Vec>); /// ++++++++++++++++++++++++++ /// + _ + [_, _, ..tail] + /// ++++++++++++++++++++++++++ -impl<'a> fmt::Show for Matrix<'a> { +impl<'a> fmt::Debug for Matrix<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "\n")); diff --git a/src/librustc/middle/graph.rs b/src/librustc/middle/graph.rs index 30e0ce33018..affeef330c4 100644 --- a/src/librustc/middle/graph.rs +++ b/src/librustc/middle/graph.rs @@ -32,7 +32,7 @@ #![allow(dead_code)] // still WIP -use std::fmt::{Formatter, Error, Show}; +use std::fmt::{Formatter, Error, Debug}; use std::uint; use std::collections::BitvSet; @@ -53,7 +53,7 @@ pub struct Edge { pub data: E, } -impl Show for Edge { +impl Debug for Edge { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { write!(f, "Edge {{ next_edge: [{:?}, {:?}], source: {:?}, target: {:?}, data: {:?} }}", self.next_edge[0], self.next_edge[1], self.source, @@ -353,7 +353,7 @@ impl Edge { #[cfg(test)] mod test { use middle::graph::*; - use std::fmt::Show; + use std::fmt::Debug; type TestNode = Node<&'static str>; type TestEdge = Edge<&'static str>; @@ -408,7 +408,7 @@ mod test { }); } - fn test_adjacent_edges(graph: &Graph, + fn test_adjacent_edges(graph: &Graph, start_index: NodeIndex, start_data: N, expected_incoming: &[(E,N)], diff --git a/src/librustc/middle/infer/unify.rs b/src/librustc/middle/infer/unify.rs index 4fa8e07ddd4..ed11cafdca9 100644 --- a/src/librustc/middle/infer/unify.rs +++ b/src/librustc/middle/infer/unify.rs @@ -17,7 +17,7 @@ use middle::ty::{self, Ty}; use middle::infer::{uok, ures}; use middle::infer::InferCtxt; use std::cell::RefCell; -use std::fmt::Show; +use std::fmt::Debug; use syntax::ast; use util::ppaux::Repr; use util::snapshot_vec as sv; @@ -32,7 +32,7 @@ use util::snapshot_vec as sv; /// (possibly not yet known) sort of integer. /// /// Implementations of this trait are at the end of this file. -pub trait UnifyKey<'tcx, V> : Clone + Show + PartialEq + Repr<'tcx> { +pub trait UnifyKey<'tcx, V> : Clone + Debug + PartialEq + Repr<'tcx> { fn index(&self) -> uint; fn from_index(u: uint) -> Self; diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 27a0324a3c4..7402bfc1efd 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -198,13 +198,13 @@ pub fn check_crate(tcx: &ty::ctxt) { tcx.sess.abort_if_errors(); } -impl fmt::Show for LiveNode { +impl fmt::Debug for LiveNode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ln({})", self.get()) } } -impl fmt::Show for Variable { +impl fmt::Debug for Variable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "v({})", self.get()) } diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index eff0018becc..7d879194067 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -602,7 +602,7 @@ fn early_bound_lifetime_names(generics: &ast::Generics) -> Vec { } } -impl<'a> fmt::Show for ScopeChain<'a> { +impl<'a> fmt::Debug for ScopeChain<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { EarlyScope(space, defs, _) => write!(fmt, "EarlyScope({:?}, {:?})", space, defs), diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index 9ad2dd499cc..83bb9a351e4 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -238,7 +238,7 @@ pub struct SeparateVecsPerParamSpace { pub fns: Vec, } -impl fmt::Show for VecPerParamSpace { +impl fmt::Debug for VecPerParamSpace { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "VecPerParamSpace {{")); for space in ParamSpace::all().iter() { diff --git a/src/librustc/middle/traits/error_reporting.rs b/src/librustc/middle/traits/error_reporting.rs index 6d0e60ec495..31f9d1bb2eb 100644 --- a/src/librustc/middle/traits/error_reporting.rs +++ b/src/librustc/middle/traits/error_reporting.rs @@ -200,7 +200,7 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, ty::Predicate::Equate(ref predicate) => { let predicate = infcx.resolve_type_vars_if_possible(predicate); let err = infcx.equality_predicate(obligation.cause.span, - &predicate).unwrap_err(); + &predicate).err().unwrap(); infcx.tcx.sess.span_err( obligation.cause.span, format!( @@ -212,7 +212,7 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, ty::Predicate::RegionOutlives(ref predicate) => { let predicate = infcx.resolve_type_vars_if_possible(predicate); let err = infcx.region_outlives_predicate(obligation.cause.span, - &predicate).unwrap_err(); + &predicate).err().unwrap(); infcx.tcx.sess.span_err( obligation.cause.span, format!( diff --git a/src/librustc/middle/traits/util.rs b/src/librustc/middle/traits/util.rs index fe8362223e3..bdf9b16f139 100644 --- a/src/librustc/middle/traits/util.rs +++ b/src/librustc/middle/traits/util.rs @@ -236,13 +236,13 @@ pub fn fresh_substs_for_impl<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, infcx.fresh_substs_for_generics(span, &impl_generics) } -impl<'tcx, N> fmt::Show for VtableImplData<'tcx, N> { +impl<'tcx, N> fmt::Debug for VtableImplData<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "VtableImpl({:?})", self.impl_def_id) } } -impl<'tcx> fmt::Show for super::VtableObjectData<'tcx> { +impl<'tcx> fmt::Debug for super::VtableObjectData<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "VtableObject(...)") } @@ -449,7 +449,7 @@ impl<'tcx> Repr<'tcx> for super::FulfillmentErrorCode<'tcx> { } } -impl<'tcx> fmt::Show for super::FulfillmentErrorCode<'tcx> { +impl<'tcx> fmt::Debug for super::FulfillmentErrorCode<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { super::CodeSelectionError(ref e) => write!(f, "{:?}", e), @@ -465,7 +465,7 @@ impl<'tcx> Repr<'tcx> for super::MismatchedProjectionTypes<'tcx> { } } -impl<'tcx> fmt::Show for super::MismatchedProjectionTypes<'tcx> { +impl<'tcx> fmt::Debug for super::MismatchedProjectionTypes<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "MismatchedProjectionTypes(..)") } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index be6c6b9d34f..8568f2c2946 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -934,7 +934,7 @@ pub struct TyS<'tcx> { region_depth: u32, } -impl fmt::Show for TypeFlags { +impl fmt::Debug for TypeFlags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.bits) } @@ -1703,37 +1703,37 @@ impl cmp::PartialEq for InferRegion { } } -impl fmt::Show for TyVid { +impl fmt::Debug for TyVid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{ write!(f, "_#{}t", self.index) } } -impl fmt::Show for IntVid { +impl fmt::Debug for IntVid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "_#{}i", self.index) } } -impl fmt::Show for FloatVid { +impl fmt::Debug for FloatVid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "_#{}f", self.index) } } -impl fmt::Show for RegionVid { +impl fmt::Debug for RegionVid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "'_#{}r", self.index) } } -impl<'tcx> fmt::Show for FnSig<'tcx> { +impl<'tcx> fmt::Debug for FnSig<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output) } } -impl fmt::Show for InferTy { +impl fmt::Debug for InferTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { TyVar(ref v) => v.fmt(f), @@ -1745,7 +1745,7 @@ impl fmt::Show for InferTy { } } -impl fmt::Show for IntVarValue { +impl fmt::Debug for IntVarValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { IntType(ref v) => v.fmt(f), @@ -3319,7 +3319,7 @@ impl ops::Sub for TypeContents { } } -impl fmt::Show for TypeContents { +impl fmt::Debug for TypeContents { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TypeContents({:b})", self.bits) } diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index d9bb1d769bf..ac0019fe1f5 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -249,7 +249,7 @@ pub enum EntryFnType { EntryNone, } -#[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash)] +#[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Show)] pub enum CrateType { CrateTypeExecutable, CrateTypeDylib, @@ -1159,7 +1159,7 @@ pub fn parse_crate_types_from_list(list_list: Vec) -> Result fmt::Result { match *self { CrateTypeExecutable => "bin".fmt(f), diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index c505e9e3112..8915d55e206 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -12,7 +12,7 @@ use std::cell::{RefCell, Cell}; use std::collections::HashMap; -use std::fmt::Show; +use std::fmt::Debug; use std::hash::{Hash, Hasher}; use std::iter::repeat; use std::time::Duration; @@ -58,7 +58,7 @@ pub fn time(do_it: bool, what: &str, u: U, f: F) -> T where } pub fn indent(op: F) -> R where - R: Show, + R: Debug, F: FnOnce() -> R, { // Use in conjunction with the log post-processor like `src/etc/indenter` diff --git a/src/librustc_back/archive.rs b/src/librustc_back/archive.rs index 7ea192b8d6b..fa754b4a301 100644 --- a/src/librustc_back/archive.rs +++ b/src/librustc_back/archive.rs @@ -59,7 +59,7 @@ fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option, let mut cmd = Command::new(ar); cmd.arg(args).args(paths); - debug!("{}", cmd); + debug!("{:?}", cmd); match cwd { Some(p) => { @@ -73,9 +73,7 @@ fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option, Ok(prog) => { let o = prog.wait_with_output().unwrap(); if !o.status.success() { - handler.err(&format!("{} failed with: {}", - cmd, - o.status)[]); + handler.err(&format!("{:?} failed with: {}", cmd, o.status)[]); handler.note(&format!("stdout ---\n{}", str::from_utf8(&o.output[]).unwrap())[]); handler.note(&format!("stderr ---\n{}", diff --git a/src/librustc_back/svh.rs b/src/librustc_back/svh.rs index b71e465b938..77ee59dc2ba 100644 --- a/src/librustc_back/svh.rs +++ b/src/librustc_back/svh.rs @@ -52,7 +52,7 @@ use std::iter::range_step; use syntax::ast; use syntax::visit; -#[derive(Clone, PartialEq)] +#[derive(Clone, PartialEq, Show)] pub struct Svh { hash: String, } @@ -117,13 +117,7 @@ impl Svh { } } -impl fmt::Show for Svh { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Svh {{ {} }}", self.as_str()) - } -} - -impl fmt::String for Svh { +impl fmt::Display for Svh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad(self.as_str()) } diff --git a/src/librustc_borrowck/borrowck/gather_loans/mod.rs b/src/librustc_borrowck/borrowck/gather_loans/mod.rs index 889a359b019..b1cc3a65120 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/mod.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/mod.rs @@ -491,7 +491,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for StaticInitializerCtxt<'a, 'tcx> { if let ast::ExprAddrOf(mutbl, ref base) = ex.node { let param_env = ty::empty_parameter_environment(self.bccx.tcx); let mc = mc::MemCategorizationContext::new(¶m_env); - let base_cmt = mc.cat_expr(&**base).unwrap(); + let base_cmt = mc.cat_expr(&**base).ok().unwrap(); let borrow_kind = ty::BorrowKind::from_mutbl(mutbl); // Check that we don't allow borrows of unsafe static items. if check_aliasability(self.bccx, ex.span, euv::AddrOf, diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 31999faa6df..37c75b45f0f 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -536,7 +536,7 @@ impl Module { } } -impl fmt::Show for Module { +impl fmt::Debug for Module { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}, kind: {:?}, {}", self.def_id, diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index dacf620cbd1..a46dc7b33f7 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -779,14 +779,14 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool, } if sess.opts.debugging_opts.print_link_args { - println!("{}", &cmd); + println!("{:?}", &cmd); } // May have not found libraries in the right formats. sess.abort_if_errors(); // Invoke the system linker - debug!("{}", &cmd); + debug!("{:?}", &cmd); let prog = time(sess.time_passes(), "running linker", (), |()| cmd.output()); match prog { Ok(prog) => { @@ -794,7 +794,7 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool, sess.err(&format!("linking with `{}` failed: {}", pname, prog.status)[]); - sess.note(&format!("{}", &cmd)[]); + sess.note(&format!("{:?}", &cmd)[]); let mut output = prog.error.clone(); output.push_all(&prog.output[]); sess.note(str::from_utf8(&output[]).unwrap()); diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index aa51b0c5ee2..0ade5aaab3d 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -716,7 +716,7 @@ pub fn run_passes(sess: &Session, cmd.args(&sess.target.target.options.post_link_args[]); if sess.opts.debugging_opts.print_link_args { - println!("{}", &cmd); + println!("{:?}", &cmd); } cmd.stdin(::std::io::process::Ignored) @@ -725,7 +725,7 @@ pub fn run_passes(sess: &Session, match cmd.status() { Ok(status) => { if !status.success() { - sess.err(&format!("linking of {} with `{}` failed", + sess.err(&format!("linking of {} with `{:?}` failed", output_path.display(), cmd)[]); sess.abort_if_errors(); } @@ -953,7 +953,7 @@ pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) { cmd.arg("-c").arg("-o").arg(outputs.path(config::OutputTypeObject)) .arg(outputs.temp_path(config::OutputTypeAssembly)); - debug!("{}", &cmd); + debug!("{:?}", &cmd); match cmd.output() { Ok(prog) => { @@ -961,7 +961,7 @@ pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) { sess.err(&format!("linking with `{}` failed: {}", pname, prog.status)[]); - sess.note(&format!("{}", &cmd)[]); + sess.note(&format!("{:?}", &cmd)[]); let mut note = prog.error.clone(); note.push_all(&prog.output[]); sess.note(str::from_utf8(¬e[]).unwrap()); diff --git a/src/librustc_trans/trans/cleanup.rs b/src/librustc_trans/trans/cleanup.rs index 5658889aaf3..de2a69226bd 100644 --- a/src/librustc_trans/trans/cleanup.rs +++ b/src/librustc_trans/trans/cleanup.rs @@ -65,7 +65,7 @@ pub enum CleanupScopeKind<'blk, 'tcx: 'blk> { LoopScopeKind(ast::NodeId, [Block<'blk, 'tcx>; EXIT_MAX]) } -impl<'blk, 'tcx: 'blk> fmt::Show for CleanupScopeKind<'blk, 'tcx> { +impl<'blk, 'tcx: 'blk> fmt::Debug for CleanupScopeKind<'blk, 'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { CustomScopeKind => write!(f, "CustomScopeKind"), diff --git a/src/librustc_trans/trans/datum.rs b/src/librustc_trans/trans/datum.rs index 8b52732f4ee..cba12babb9b 100644 --- a/src/librustc_trans/trans/datum.rs +++ b/src/librustc_trans/trans/datum.rs @@ -481,7 +481,7 @@ impl<'tcx> Datum<'tcx, Lvalue> { } /// Generic methods applicable to any sort of datum. -impl<'tcx, K: KindOps + fmt::Show> Datum<'tcx, K> { +impl<'tcx, K: KindOps + fmt::Debug> Datum<'tcx, K> { pub fn new(val: ValueRef, ty: Ty<'tcx>, kind: K) -> Datum<'tcx, K> { Datum { val: val, ty: ty, kind: kind } } @@ -591,7 +591,7 @@ impl<'blk, 'tcx, K> DatumBlock<'blk, 'tcx, K> { } } -impl<'blk, 'tcx, K: KindOps + fmt::Show> DatumBlock<'blk, 'tcx, K> { +impl<'blk, 'tcx, K: KindOps + fmt::Debug> DatumBlock<'blk, 'tcx, K> { pub fn to_expr_datumblock(self) -> DatumBlock<'blk, 'tcx, Expr> { DatumBlock::new(self.bcx, self.datum.to_expr_datum()) } diff --git a/src/librustc_typeck/variance.rs b/src/librustc_typeck/variance.rs index 86447e76a89..1f10f8eb1b6 100644 --- a/src/librustc_typeck/variance.rs +++ b/src/librustc_typeck/variance.rs @@ -240,7 +240,7 @@ enum VarianceTerm<'a> { InferredTerm(InferredIndex), } -impl<'a> fmt::Show for VarianceTerm<'a> { +impl<'a> fmt::Debug for VarianceTerm<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ConstantTerm(c1) => write!(f, "{:?}", c1), diff --git a/src/librustdoc/html/escape.rs b/src/librustdoc/html/escape.rs index 6fb78d9a833..c2b18962192 100644 --- a/src/librustdoc/html/escape.rs +++ b/src/librustdoc/html/escape.rs @@ -19,7 +19,7 @@ use std::fmt; /// string when passed to a format string. pub struct Escape<'a>(pub &'a str); -impl<'a> fmt::String for Escape<'a> { +impl<'a> fmt::Display for Escape<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Because the internet is always right, turns out there's not that many // characters to escape: http://stackoverflow.com/questions/7381974 diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 57b8d666c95..27b875ee286 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -66,7 +66,7 @@ impl UnsafetySpace { } } -impl<'a, T: fmt::String> fmt::String for CommaSep<'a, T> { +impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, item) in self.0.iter().enumerate() { if i != 0 { try!(write!(f, ", ")); } @@ -76,7 +76,7 @@ impl<'a, T: fmt::String> fmt::String for CommaSep<'a, T> { } } -impl<'a> fmt::String for TyParamBounds<'a> { +impl<'a> fmt::Display for TyParamBounds<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &TyParamBounds(bounds) = self; for (i, bound) in bounds.iter().enumerate() { @@ -89,7 +89,7 @@ impl<'a> fmt::String for TyParamBounds<'a> { } } -impl fmt::String for clean::Generics { +impl fmt::Display for clean::Generics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.lifetimes.len() == 0 && self.type_params.len() == 0 { return Ok(()) } try!(f.write_str("<")); @@ -126,7 +126,7 @@ impl fmt::String for clean::Generics { } } -impl<'a> fmt::String for WhereClause<'a> { +impl<'a> fmt::Display for WhereClause<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &WhereClause(gens) = self; if gens.where_predicates.len() == 0 { @@ -163,14 +163,14 @@ impl<'a> fmt::String for WhereClause<'a> { } } -impl fmt::String for clean::Lifetime { +impl fmt::Display for clean::Lifetime { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(self.get_ref())); Ok(()) } } -impl fmt::String for clean::PolyTrait { +impl fmt::Display for clean::PolyTrait { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.lifetimes.len() > 0 { try!(f.write_str("for<")); @@ -186,7 +186,7 @@ impl fmt::String for clean::PolyTrait { } } -impl fmt::String for clean::TyParamBound { +impl fmt::Display for clean::TyParamBound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::RegionBound(ref lt) => { @@ -203,7 +203,7 @@ impl fmt::String for clean::TyParamBound { } } -impl fmt::String for clean::PathParameters { +impl fmt::Display for clean::PathParameters { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::PathParameters::AngleBracketed { @@ -257,14 +257,14 @@ impl fmt::String for clean::PathParameters { } } -impl fmt::String for clean::PathSegment { +impl fmt::Display for clean::PathSegment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(self.name.as_slice())); write!(f, "{}", self.params) } } -impl fmt::String for clean::Path { +impl fmt::Display for clean::Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.global { try!(f.write_str("::")) @@ -450,7 +450,7 @@ fn tybounds(w: &mut fmt::Formatter, } } -impl fmt::String for clean::Type { +impl fmt::Display for clean::Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::TyParamBinder(id) => { @@ -539,7 +539,7 @@ impl fmt::String for clean::Type { } } -impl fmt::String for clean::Arguments { +impl fmt::Display for clean::Arguments { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, input) in self.values.iter().enumerate() { if i > 0 { try!(write!(f, ", ")); } @@ -552,7 +552,7 @@ impl fmt::String for clean::Arguments { } } -impl fmt::String for clean::FunctionRetTy { +impl fmt::Display for clean::FunctionRetTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()), @@ -563,13 +563,13 @@ impl fmt::String for clean::FunctionRetTy { } } -impl fmt::String for clean::FnDecl { +impl fmt::Display for clean::FnDecl { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output) } } -impl<'a> fmt::String for Method<'a> { +impl<'a> fmt::Display for Method<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Method(selfty, d) = *self; let mut args = String::new(); @@ -599,7 +599,7 @@ impl<'a> fmt::String for Method<'a> { } } -impl fmt::String for VisSpace { +impl fmt::Display for VisSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.get() { Some(ast::Public) => write!(f, "pub "), @@ -608,7 +608,7 @@ impl fmt::String for VisSpace { } } -impl fmt::String for UnsafetySpace { +impl fmt::Display for UnsafetySpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.get() { ast::Unsafety::Unsafe => write!(f, "unsafe "), @@ -617,7 +617,7 @@ impl fmt::String for UnsafetySpace { } } -impl fmt::String for clean::ViewPath { +impl fmt::Display for clean::ViewPath { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::SimpleImport(ref name, ref src) => { @@ -644,7 +644,7 @@ impl fmt::String for clean::ViewPath { } } -impl fmt::String for clean::ImportSource { +impl fmt::Display for clean::ImportSource { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.did { Some(did) => resolved_path(f, did, &self.path, true), @@ -661,7 +661,7 @@ impl fmt::String for clean::ImportSource { } } -impl fmt::String for clean::ViewListIdent { +impl fmt::Display for clean::ViewListIdent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.source { Some(did) => { @@ -683,13 +683,13 @@ impl fmt::String for clean::ViewListIdent { } } -impl fmt::String for clean::TypeBinding { +impl fmt::Display for clean::TypeBinding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}={}", self.name, self.ty) } } -impl fmt::String for MutableSpace { +impl fmt::Display for MutableSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { MutableSpace(clean::Immutable) => Ok(()), @@ -698,7 +698,7 @@ impl fmt::String for MutableSpace { } } -impl fmt::String for RawMutableSpace { +impl fmt::Display for RawMutableSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RawMutableSpace(clean::Immutable) => write!(f, "const "), @@ -707,7 +707,7 @@ impl fmt::String for RawMutableSpace { } } -impl<'a> fmt::String for Stability<'a> { +impl<'a> fmt::Display for Stability<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Stability(stab) = *self; match *stab { @@ -721,7 +721,7 @@ impl<'a> fmt::String for Stability<'a> { } } -impl<'a> fmt::String for ConciseStability<'a> { +impl<'a> fmt::Display for ConciseStability<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ConciseStability(stab) = *self; match *stab { @@ -738,7 +738,7 @@ impl<'a> fmt::String for ConciseStability<'a> { } } -impl fmt::String for ModuleSummary { +impl fmt::Display for ModuleSummary { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt_inner<'a>(f: &mut fmt::Formatter, context: &mut Vec<&'a str>, diff --git a/src/librustdoc/html/item_type.rs b/src/librustdoc/html/item_type.rs index db3319eb765..fbc8ae2c0b4 100644 --- a/src/librustdoc/html/item_type.rs +++ b/src/librustdoc/html/item_type.rs @@ -103,7 +103,7 @@ impl ItemType { } } -impl fmt::String for ItemType { +impl fmt::Display for ItemType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_static_str().fmt(f) } diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index f75ab3f431c..e3bd2b4e27f 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -30,7 +30,7 @@ pub struct Page<'a> { pub keywords: &'a str } -pub fn render( +pub fn render( dst: &mut io::Writer, layout: &Layout, page: &Page, sidebar: &S, t: &T) -> io::IoResult<()> { diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 0dbd13b4616..4bdc2a16482 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -426,7 +426,7 @@ pub fn reset_headers() { USED_HEADER_MAP.with(|s| s.borrow_mut().clear()); } -impl<'a> fmt::String for Markdown<'a> { +impl<'a> fmt::Display for Markdown<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Markdown(md) = *self; // This is actually common enough to special-case @@ -435,7 +435,7 @@ impl<'a> fmt::String for Markdown<'a> { } } -impl<'a> fmt::String for MarkdownWithToc<'a> { +impl<'a> fmt::Display for MarkdownWithToc<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let MarkdownWithToc(md) = *self; render(fmt, md.as_slice(), true) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index ab9700d966a..bd2213910be 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1351,7 +1351,7 @@ impl<'a> Item<'a> { } -impl<'a> fmt::String for Item<'a> { +impl<'a> fmt::Display for Item<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Write the breadcrumb trail header for the top try!(write!(fmt, "\n

")); @@ -1626,7 +1626,7 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, struct Initializer<'a>(&'a str); -impl<'a> fmt::String for Initializer<'a> { +impl<'a> fmt::Display for Initializer<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Initializer(s) = *self; if s.len() == 0 { return Ok(()); } @@ -2188,7 +2188,7 @@ fn item_typedef(w: &mut fmt::Formatter, it: &clean::Item, document(w, it) } -impl<'a> fmt::String for Sidebar<'a> { +impl<'a> fmt::Display for Sidebar<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let cx = self.cx; let it = self.item; @@ -2243,7 +2243,7 @@ impl<'a> fmt::String for Sidebar<'a> { } } -impl<'a> fmt::String for Source<'a> { +impl<'a> fmt::Display for Source<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Source(s) = *self; let lines = s.lines().count(); diff --git a/src/librustdoc/html/toc.rs b/src/librustdoc/html/toc.rs index 8d94e1857c4..aca6e5bb10e 100644 --- a/src/librustdoc/html/toc.rs +++ b/src/librustdoc/html/toc.rs @@ -176,13 +176,13 @@ impl TocBuilder { } } -impl fmt::Show for Toc { +impl fmt::Debug for Toc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt(self, f) } } -impl fmt::String for Toc { +impl fmt::Display for Toc { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "
    ")); for entry in self.entries.iter() { diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 71bd53009af..b38c9464d94 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -111,7 +111,7 @@ pub fn main() { let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || { main_args(std::os::args().as_slice()) }).join(); - std::os::set_exit_status(res.map_err(|_| ()).unwrap()); + std::os::set_exit_status(res.ok().unwrap()); } pub fn opts() -> Vec { diff --git a/src/libserialize/base64.rs b/src/libserialize/base64.rs index d13d110320e..c97d67ba1b9 100644 --- a/src/libserialize/base64.rs +++ b/src/libserialize/base64.rs @@ -177,7 +177,7 @@ pub trait FromBase64 { } /// Errors that can occur when decoding a base64 encoded string -#[derive(Copy)] +#[derive(Copy, Show)] pub enum FromBase64Error { /// The input contained a character not part of the base64 format InvalidBase64Byte(u8, uint), @@ -185,7 +185,7 @@ pub enum FromBase64Error { InvalidBase64Length, } -impl fmt::Show for FromBase64Error { +impl fmt::Display for FromBase64Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidBase64Byte(ch, idx) => @@ -202,10 +202,6 @@ impl error::Error for FromBase64Error { InvalidBase64Length => "invalid length", } } - - fn detail(&self) -> Option { - Some(format!("{:?}", self)) - } } impl FromBase64 for str { diff --git a/src/libserialize/hex.rs b/src/libserialize/hex.rs index a11eb3f7898..e477f4418a5 100644 --- a/src/libserialize/hex.rs +++ b/src/libserialize/hex.rs @@ -61,7 +61,7 @@ pub trait FromHex { } /// Errors that can occur when decoding a hex encoded string -#[derive(Copy)] +#[derive(Copy, Show)] pub enum FromHexError { /// The input contained a character not part of the hex format InvalidHexCharacter(char, uint), @@ -69,7 +69,7 @@ pub enum FromHexError { InvalidHexLength, } -impl fmt::Show for FromHexError { +impl fmt::Display for FromHexError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidHexCharacter(ch, idx) => @@ -86,10 +86,6 @@ impl error::Error for FromHexError { InvalidHexLength => "invalid length", } } - - fn detail(&self) -> Option { - Some(format!("{:?}", self)) - } } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index a876ca3cb11..b8adb8aa7d8 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -235,7 +235,7 @@ pub struct AsJson<'a, T: 'a> { inner: &'a T } pub struct AsPrettyJson<'a, T: 'a> { inner: &'a T, indent: Option } /// The errors that can arise while parsing a JSON stream. -#[derive(Clone, Copy, PartialEq)] +#[derive(Clone, Copy, PartialEq, Show)] pub enum ErrorCode { InvalidSyntax, InvalidNumber, @@ -325,7 +325,7 @@ pub fn encode(object: &T) -> string::String { s } -impl fmt::Show for ErrorCode { +impl fmt::Display for ErrorCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { error_str(*self).fmt(f) } @@ -335,14 +335,33 @@ fn io_error_to_error(io: io::IoError) -> ParserError { IoError(io.kind, io.desc) } +impl fmt::Display for ParserError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // FIXME this should be a nicer error + fmt::Debug::fmt(self, f) + } +} + +impl fmt::Display for DecoderError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // FIXME this should be a nicer error + fmt::Debug::fmt(self, f) + } +} + impl std::error::Error for DecoderError { fn description(&self) -> &str { "decoder error" } - fn detail(&self) -> Option { Some(format!("{:?}", self)) } +} + +impl fmt::Display for EncoderError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // FIXME this should be a nicer error + fmt::Debug::fmt(self, f) + } } impl std::error::Error for EncoderError { fn description(&self) -> &str { "encoder error" } - fn detail(&self) -> Option { Some(format!("{:?}", self)) } } impl std::error::FromError for EncoderError { @@ -2519,7 +2538,7 @@ impl<'a, 'b> fmt::Writer for FormatShim<'a, 'b> { } } -impl fmt::String for Json { +impl fmt::Display for Json { /// Encodes a json value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut shim = FormatShim { inner: f }; @@ -2531,7 +2550,7 @@ impl fmt::String for Json { } } -impl<'a> fmt::String for PrettyJson<'a> { +impl<'a> fmt::Display for PrettyJson<'a> { /// Encodes a json value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut shim = FormatShim { inner: f }; @@ -2543,7 +2562,7 @@ impl<'a> fmt::String for PrettyJson<'a> { } } -impl<'a, T: Encodable> fmt::String for AsJson<'a, T> { +impl<'a, T: Encodable> fmt::Display for AsJson<'a, T> { /// Encodes a json value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut shim = FormatShim { inner: f }; @@ -2563,7 +2582,7 @@ impl<'a, T> AsPrettyJson<'a, T> { } } -impl<'a, T: Encodable> fmt::String for AsPrettyJson<'a, T> { +impl<'a, T: Encodable> fmt::Display for AsPrettyJson<'a, T> { /// Encodes a json value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut shim = FormatShim { inner: f }; @@ -3920,7 +3939,7 @@ mod tests { let mut mem_buf = Vec::new(); let mut encoder = Encoder::new(&mut mem_buf as &mut fmt::Writer); let result = hm.encode(&mut encoder); - match result.unwrap_err() { + match result.err().unwrap() { EncoderError::BadHashmapKey => (), _ => panic!("expected bad hash map key") } diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index d3ac632617d..0f1da8c5d3a 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -18,7 +18,7 @@ use borrow::BorrowFrom; use clone::Clone; use cmp::{max, Eq, PartialEq}; use default::Default; -use fmt::{self, Show}; +use fmt::{self, Debug}; use hash::{self, Hash, SipHasher}; use iter::{self, Iterator, ExactSizeIterator, IteratorExt, FromIterator, Extend, Map}; use marker::Sized; @@ -270,7 +270,7 @@ fn test_resize_policy() { /// ``` /// use std::collections::HashMap; /// -/// #[derive(Hash, Eq, PartialEq, Show)] +/// #[derive(Hash, Eq, PartialEq, Debug)] /// struct Viking { /// name: String, /// country: String, @@ -1216,8 +1216,8 @@ impl Eq for HashMap {} #[stable] -impl Show for HashMap - where K: Eq + Hash + Show, V: Show, +impl Debug for HashMap + where K: Eq + Hash + Debug, V: Debug, S: HashState, H: hash::Hasher { @@ -1996,8 +1996,8 @@ mod test_map { let map_str = format!("{:?}", map); - assert!(map_str == "HashMap {1i: 2i, 3i: 4i}" || - map_str == "HashMap {3i: 4i, 1i: 2i}"); + assert!(map_str == "HashMap {1: 2, 3: 4}" || + map_str == "HashMap {3: 4, 1: 2}"); assert_eq!(format!("{:?}", empty), "HashMap {}"); } diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index 1293f45161d..29e247d96d2 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -15,7 +15,7 @@ use clone::Clone; use cmp::{Eq, PartialEq}; use core::marker::Sized; use default::Default; -use fmt::Show; +use fmt::Debug; use fmt; use hash::{self, Hash}; use iter::{Iterator, ExactSizeIterator, IteratorExt, FromIterator, Map, Chain, Extend}; @@ -71,7 +71,7 @@ use super::state::HashState; /// /// ``` /// use std::collections::HashSet; -/// #[derive(Hash, Eq, PartialEq, Show)] +/// #[derive(Hash, Eq, PartialEq, Debug)] /// struct Viking<'a> { /// name: &'a str, /// power: uint, @@ -596,8 +596,8 @@ impl Eq for HashSet {} #[stable] -impl fmt::Show for HashSet - where T: Eq + Hash + fmt::Show, +impl fmt::Debug for HashSet + where T: Eq + Hash + fmt::Debug, S: HashState, H: hash::Hasher { @@ -1179,7 +1179,7 @@ mod test_set { let set_str = format!("{:?}", set); - assert!(set_str == "HashSet {1i, 2i}" || set_str == "HashSet {2i, 1i}"); + assert!(set_str == "HashSet {1, 2}" || set_str == "HashSet {2, 1}"); assert_eq!(format!("{:?}", empty), "HashSet {}"); } diff --git a/src/libstd/error.rs b/src/libstd/error.rs deleted file mode 100644 index ff128461978..00000000000 --- a/src/libstd/error.rs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2014 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Traits for working with Errors. -//! -//! # The `Error` trait -//! -//! `Error` is a trait representing the basic expectations for error values, -//! i.e. values of type `E` in `Result`. At a minimum, errors must provide -//! a description, but they may optionally provide additional detail and cause -//! chain information: -//! -//! ``` -//! trait Error { -//! fn description(&self) -> &str; -//! -//! fn detail(&self) -> Option { None } -//! fn cause(&self) -> Option<&Error> { None } -//! } -//! ``` -//! -//! The `cause` method is generally used when errors cross "abstraction -//! boundaries", i.e. when a one module must report an error that is "caused" -//! by an error from a lower-level module. This setup makes it possible for the -//! high-level module to provide its own errors that do not commit to any -//! particular implementation, but also reveal some of its implementation for -//! debugging via `cause` chains. -//! -//! # The `FromError` trait -//! -//! `FromError` is a simple trait that expresses conversions between different -//! error types. To provide maximum flexibility, it does not require either of -//! the types to actually implement the `Error` trait, although this will be the -//! common case. -//! -//! The main use of this trait is in the `try!` macro, which uses it to -//! automatically convert a given error to the error specified in a function's -//! return type. -//! -//! For example, -//! -//! ``` -//! use std::error::FromError; -//! use std::io::{File, IoError}; -//! use std::os::{MemoryMap, MapError}; -//! use std::path::Path; -//! -//! enum MyError { -//! Io(IoError), -//! Map(MapError) -//! } -//! -//! impl FromError for MyError { -//! fn from_error(err: IoError) -> MyError { -//! MyError::Io(err) -//! } -//! } -//! -//! impl FromError for MyError { -//! fn from_error(err: MapError) -> MyError { -//! MyError::Map(err) -//! } -//! } -//! -//! #[allow(unused_variables)] -//! fn open_and_map() -> Result<(), MyError> { -//! let f = try!(File::open(&Path::new("foo.txt"))); -//! let m = try!(MemoryMap::new(0, &[])); -//! // do something interesting here... -//! Ok(()) -//! } -//! ``` - -#![stable] - -use prelude::v1::*; - -use str::Utf8Error; -use string::{FromUtf8Error, FromUtf16Error}; - -/// Base functionality for all errors in Rust. -#[unstable = "the exact API of this trait may change"] -pub trait Error { - /// A short description of the error; usually a static string. - fn description(&self) -> &str; - - /// A detailed description of the error, usually including dynamic information. - fn detail(&self) -> Option { None } - - /// The lower-level cause of this error, if any. - fn cause(&self) -> Option<&Error> { None } -} - -/// A trait for types that can be converted from a given error type `E`. -#[stable] -pub trait FromError { - /// Perform the conversion. - fn from_error(err: E) -> Self; -} - -// Any type is convertable from itself -#[stable] -impl FromError for E { - fn from_error(err: E) -> E { - err - } -} - -#[stable] -impl Error for Utf8Error { - fn description(&self) -> &str { - match *self { - Utf8Error::TooShort => "invalid utf-8: not enough bytes", - Utf8Error::InvalidByte(..) => "invalid utf-8: corrupt contents", - } - } - - fn detail(&self) -> Option { Some(self.to_string()) } -} - -#[stable] -impl Error for FromUtf8Error { - fn description(&self) -> &str { "invalid utf-8" } - fn detail(&self) -> Option { Some(self.to_string()) } -} - -#[stable] -impl Error for FromUtf16Error { - fn description(&self) -> &str { "invalid utf-16" } -} diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index d7f8eb2e415..b7f4b070591 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -119,7 +119,8 @@ impl Deref for CString { } } -impl fmt::Show for CString { +#[stable] +impl fmt::Debug for CString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { String::from_utf8_lossy(self.as_bytes()).fmt(f) } @@ -215,4 +216,10 @@ mod tests { assert_eq!(s.as_bytes(), b"\0"); } } + + #[test] + fn formatted() { + let s = CString::from_slice(b"12"); + assert_eq!(format!("{:?}", s), "\"12\""); + } } diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs index 88fb983361a..f3b159cf819 100644 --- a/src/libstd/fmt.rs +++ b/src/libstd/fmt.rs @@ -123,8 +123,8 @@ //! This allows multiple actual types to be formatted via `{:x}` (like `i8` as //! well as `int`). The current mapping of types to traits is: //! -//! * *nothing* ⇒ `String` -//! * `?` ⇒ `Show` +//! * *nothing* ⇒ `Display` +//! * `?` ⇒ `Debug` //! * `o` ⇒ `Octal` //! * `x` ⇒ `LowerHex` //! * `X` ⇒ `UpperHex` @@ -137,7 +137,7 @@ //! `std::fmt::Binary` trait can then be formatted with `{:b}`. Implementations //! are provided for these traits for a number of primitive types by the //! standard library as well. If no format is specified (as in `{}` or `{:6}`), -//! then the format trait used is the `String` trait. +//! then the format trait used is the `Display` trait. //! //! When implementing a format trait for your own type, you will have to //! implement a method of the signature: @@ -145,7 +145,7 @@ //! ```rust //! # use std::fmt; //! # struct Foo; // our custom type -//! # impl fmt::Show for Foo { +//! # impl fmt::Display for Foo { //! fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result { //! # write!(f, "testing, testing") //! # } } @@ -171,13 +171,13 @@ //! use std::f64; //! use std::num::Float; //! -//! #[derive(Show)] +//! #[derive(Debug)] //! struct Vector2D { //! x: int, //! y: int, //! } //! -//! impl fmt::String for Vector2D { +//! impl fmt::Display for Vector2D { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! // The `f` value implements the `Writer` trait, which is what the //! // write! macro is expecting. Note that this formatting ignores the @@ -211,22 +211,22 @@ //! } //! ``` //! -//! #### fmt::String vs fmt::Show +//! #### fmt::Display vs fmt::Debug //! //! These two formatting traits have distinct purposes: //! -//! - `fmt::String` implementations assert that the type can be faithfully +//! - `fmt::Display` implementations assert that the type can be faithfully //! represented as a UTF-8 string at all times. It is **not** expected that -//! all types implement the `String` trait. -//! - `fmt::Show` implementations should be implemented for **all** public types. +//! all types implement the `Display` trait. +//! - `fmt::Debug` implementations should be implemented for **all** public types. //! Output will typically represent the internal state as faithfully as possible. -//! The purpose of the `Show` trait is to facilitate debugging Rust code. In -//! most cases, using `#[derive(Show)]` is sufficient and recommended. +//! The purpose of the `Debug` trait is to facilitate debugging Rust code. In +//! most cases, using `#[derive(Debug)]` is sufficient and recommended. //! //! Some examples of the output from both traits: //! //! ``` -//! assert_eq!(format!("{} {:?}", 3i32, 4i32), "3 4i32"); +//! assert_eq!(format!("{} {:?}", 3i32, 4i32), "3 4"); //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'"); //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\""); //! ``` @@ -409,6 +409,7 @@ use string; pub use core::fmt::{Formatter, Result, Writer, rt}; pub use core::fmt::{Show, String, Octal, Binary}; +pub use core::fmt::{Display, Debug}; pub use core::fmt::{LowerHex, UpperHex, Pointer}; pub use core::fmt::{LowerExp, UpperExp}; pub use core::fmt::Error; diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 8c38bc009cc..c1244abbfcb 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -52,7 +52,8 @@ pub struct BufferedReader { cap: uint, } -impl fmt::Show for BufferedReader where R: fmt::Show { +#[stable] +impl fmt::Debug for BufferedReader where R: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "BufferedReader {{ reader: {:?}, buffer: {}/{} }}", self.inner, self.cap - self.pos, self.buf.len()) @@ -150,7 +151,8 @@ pub struct BufferedWriter { pos: uint } -impl fmt::Show for BufferedWriter where W: fmt::Show { +#[stable] +impl fmt::Debug for BufferedWriter where W: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "BufferedWriter {{ writer: {:?}, buffer: {}/{} }}", self.inner.as_ref().unwrap(), self.pos, self.buf.len()) @@ -249,7 +251,8 @@ pub struct LineBufferedWriter { inner: BufferedWriter, } -impl fmt::Show for LineBufferedWriter where W: fmt::Show { +#[stable] +impl fmt::Debug for LineBufferedWriter where W: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "LineBufferedWriter {{ writer: {:?}, buffer: {}/{} }}", self.inner.inner, self.inner.pos, self.inner.buf.len()) @@ -339,7 +342,8 @@ pub struct BufferedStream { inner: BufferedReader> } -impl fmt::Show for BufferedStream where S: fmt::Show { +#[stable] +impl fmt::Debug for BufferedStream where S: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let reader = &self.inner; let writer = &self.inner.inner.0; diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index 64406d88253..cc36c5640d0 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -156,7 +156,7 @@ impl File { }) } }).update_err("couldn't open path as file", |e| { - format!("{}; path={:?}; mode={}; access={}", e, path.display(), + format!("{}; path={}; mode={}; access={}", e, path.display(), mode_string(mode), access_string(access)) }) } @@ -211,7 +211,7 @@ impl File { pub fn fsync(&mut self) -> IoResult<()> { self.fd.fsync() .update_err("couldn't fsync file", - |e| format!("{}; path={:?}", e, self.path.display())) + |e| format!("{}; path={}", e, self.path.display())) } /// This function is similar to `fsync`, except that it may not synchronize @@ -221,7 +221,7 @@ impl File { pub fn datasync(&mut self) -> IoResult<()> { self.fd.datasync() .update_err("couldn't datasync file", - |e| format!("{}; path={:?}", e, self.path.display())) + |e| format!("{}; path={}", e, self.path.display())) } /// Either truncates or extends the underlying file, updating the size of @@ -235,7 +235,7 @@ impl File { pub fn truncate(&mut self, size: i64) -> IoResult<()> { self.fd.truncate(size) .update_err("couldn't truncate file", |e| - format!("{}; path={:?}; size={:?}", e, self.path.display(), size)) + format!("{}; path={}; size={}", e, self.path.display(), size)) } /// Returns true if the stream has reached the end of the file. @@ -255,7 +255,7 @@ impl File { pub fn stat(&self) -> IoResult { self.fd.fstat() .update_err("couldn't fstat file", |e| - format!("{}; path={:?}", e, self.path.display())) + format!("{}; path={}", e, self.path.display())) } } @@ -283,7 +283,7 @@ impl File { pub fn unlink(path: &Path) -> IoResult<()> { fs_imp::unlink(path) .update_err("couldn't unlink path", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } /// Given a path, query the file system to get information about a file, @@ -310,7 +310,7 @@ pub fn unlink(path: &Path) -> IoResult<()> { pub fn stat(path: &Path) -> IoResult { fs_imp::stat(path) .update_err("couldn't stat path", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } /// Perform the same operation as the `stat` function, except that this @@ -324,7 +324,7 @@ pub fn stat(path: &Path) -> IoResult { pub fn lstat(path: &Path) -> IoResult { fs_imp::lstat(path) .update_err("couldn't lstat path", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } /// Rename a file or directory to a new name. @@ -424,14 +424,14 @@ pub fn copy(from: &Path, to: &Path) -> IoResult<()> { pub fn chmod(path: &Path, mode: 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)) + format!("{}; path={}; mode={:?}", e, path.display(), mode)) } /// Change the user and group owners of a file at the specified path. pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> { fs_imp::chown(path, uid, gid) .update_err("couldn't chown path", |e| - format!("{}; path={:?}; uid={}; gid={}", e, path.display(), uid, gid)) + format!("{}; path={}; uid={}; gid={}", e, path.display(), uid, gid)) } /// Creates a new hard link on the filesystem. The `dst` path will be a @@ -460,7 +460,7 @@ pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> { pub fn readlink(path: &Path) -> IoResult { fs_imp::readlink(path) .update_err("couldn't resolve symlink for path", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } /// Create a new, empty directory at the provided path @@ -483,7 +483,7 @@ pub fn readlink(path: &Path) -> IoResult { pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> { fs_imp::mkdir(path, mode.bits() as uint) .update_err("couldn't create directory", |e| - format!("{}; path={:?}; mode={:?}", e, path.display(), mode)) + format!("{}; path={}; mode={}", e, path.display(), mode)) } /// Remove an existing, empty directory @@ -505,7 +505,7 @@ pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> { pub fn rmdir(path: &Path) -> IoResult<()> { fs_imp::rmdir(path) .update_err("couldn't remove directory", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } /// Retrieve a vector containing all entries within a provided directory @@ -545,7 +545,7 @@ pub fn rmdir(path: &Path) -> IoResult<()> { pub fn readdir(path: &Path) -> IoResult> { fs_imp::readdir(path) .update_err("couldn't read directory", - |e| format!("{}; path={:?}", e, path.display())) + |e| format!("{}; path={}", e, path.display())) } /// Returns an iterator that will recursively walk the directory structure @@ -555,7 +555,7 @@ pub fn readdir(path: &Path) -> IoResult> { pub fn walk_dir(path: &Path) -> IoResult { Ok(Directories { stack: try!(readdir(path).update_err("couldn't walk directory", - |e| format!("{}; path={:?}", e, path.display()))) + |e| format!("{}; path={}", e, path.display()))) }) } @@ -605,7 +605,7 @@ pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> { let result = mkdir(&curpath, mode) .update_err("couldn't recursively mkdir", - |e| format!("{}; path={:?}", e, path.display())); + |e| format!("{}; path={}", e, path.display())); match result { Err(mkdir_err) => { @@ -632,7 +632,7 @@ pub fn rmdir_recursive(path: &Path) -> IoResult<()> { rm_stack.push(path.clone()); fn rmdir_failed(err: &IoError, path: &Path) -> String { - format!("rmdir_recursive failed; path={:?}; cause={}", + format!("rmdir_recursive failed; path={}; cause={}", path.display(), err) } @@ -692,14 +692,14 @@ pub fn rmdir_recursive(path: &Path) -> IoResult<()> { pub fn change_file_times(path: &Path, atime: u64, mtime: u64) -> IoResult<()> { fs_imp::utime(path, atime, mtime) .update_err("couldn't change_file_times", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } impl Reader for File { fn read(&mut self, buf: &mut [u8]) -> IoResult { fn update_err(result: IoResult, file: &File) -> IoResult { result.update_err("couldn't read file", - |e| format!("{}; path={:?}", + |e| format!("{}; path={}", e, file.path.display())) } @@ -722,7 +722,7 @@ impl Writer for File { fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.fd.write(buf) .update_err("couldn't write to file", - |e| format!("{}; path={:?}", e, self.path.display())) + |e| format!("{}; path={}", e, self.path.display())) } } @@ -730,7 +730,7 @@ impl Seek for File { fn tell(&self) -> IoResult { self.fd.tell() .update_err("couldn't retrieve file cursor (`tell`)", - |e| format!("{}; path={:?}", e, self.path.display())) + |e| format!("{}; path={}", e, self.path.display())) } fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> { @@ -743,7 +743,7 @@ impl Seek for File { Err(e) => Err(e), }; err.update_err("couldn't seek in file", - |e| format!("{}; path={:?}", e, self.path.display())) + |e| format!("{}; path={}", e, self.path.display())) } } @@ -906,7 +906,7 @@ mod test { if cfg!(unix) { error!(result, "no such file or directory"); } - error!(result, format!("path={:?}; mode=open; access=read", filename.display())); + error!(result, format!("path={}; mode=open; access=read", filename.display())); } #[test] @@ -920,7 +920,7 @@ mod test { if cfg!(unix) { error!(result, "no such file or directory"); } - error!(result, format!("path={:?}", filename.display())); + error!(result, format!("path={}", filename.display())); } #[test] @@ -1188,7 +1188,7 @@ mod test { error!(result, "couldn't recursively mkdir"); error!(result, "couldn't create directory"); error!(result, "mode=0700"); - error!(result, format!("path={:?}", file.display())); + error!(result, format!("path={}", file.display())); } #[test] diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index ee05a9e5596..e281bd3d7e8 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -432,8 +432,8 @@ mod test { writer.write(&[]).unwrap(); assert_eq!(writer.tell(), Ok(8)); - assert_eq!(writer.write(&[8, 9]).unwrap_err().kind, io::ShortWrite(1)); - assert_eq!(writer.write(&[10]).unwrap_err().kind, io::EndOfFile); + assert_eq!(writer.write(&[8, 9]).err().unwrap().kind, io::ShortWrite(1)); + assert_eq!(writer.write(&[10]).err().unwrap().kind, io::EndOfFile); } let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8]; assert_eq!(buf, b); diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index dc21416df7b..bc86511165e 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -228,13 +228,12 @@ pub use self::FileAccess::*; pub use self::IoErrorKind::*; use char::CharExt; -use clone::Clone; use default::Default; -use error::{FromError, Error}; +use error::Error; use fmt; use int; use iter::{Iterator, IteratorExt}; -use marker::{Sized, Send}; +use marker::Sized; use mem::transmute; use ops::FnOnce; use option::Option; @@ -340,7 +339,8 @@ impl IoError { } } -impl fmt::String for IoError { +#[stable] +impl fmt::Display for IoError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } => @@ -354,19 +354,7 @@ impl fmt::String for IoError { } impl Error for IoError { - fn description(&self) -> &str { - self.desc - } - - fn detail(&self) -> Option { - self.detail.clone() - } -} - -impl FromError for Box { - fn from_error(err: IoError) -> Box { - box err - } + fn description(&self) -> &str { self.desc } } /// A list specifying general categories of I/O error. @@ -1781,6 +1769,7 @@ pub struct UnstableFileStat { bitflags! { /// A set of permissions for a file or directory is represented by a set of /// flags which are or'd together. + #[derive(Show)] flags FilePermission: u32 { const USER_READ = 0o400, const USER_WRITE = 0o200, @@ -1822,13 +1811,8 @@ impl Default for FilePermission { fn default() -> FilePermission { FilePermission::empty() } } -impl fmt::Show for FilePermission { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - -impl fmt::String for FilePermission { +#[stable] +impl fmt::Display for FilePermission { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:04o}", self.bits) } diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index adc122ff447..e8e065533e5 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -38,7 +38,8 @@ pub enum IpAddr { Ipv6Addr(u16, u16, u16, u16, u16, u16, u16, u16) } -impl fmt::String for IpAddr { +#[stable] +impl fmt::Display for IpAddr { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Ipv4Addr(a, b, c, d) => @@ -69,7 +70,8 @@ pub struct SocketAddr { pub port: Port, } -impl fmt::String for SocketAddr { +#[stable] +impl fmt::Display for SocketAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.ip { Ipv4Addr(..) => write!(f, "{}:{}", self.ip, self.port), diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 43ca7b13145..7b0a86777f6 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -397,7 +397,7 @@ impl Command { } } -impl fmt::String for Command { +impl fmt::Debug for Command { /// Format the program and arguments of a Command for display. Any /// non-utf8 data is lossily converted using the utf8 replacement /// character. @@ -496,7 +496,7 @@ pub enum StdioContainer { /// Describes the result of a process after it has terminated. /// Note that Windows have no signals, so the result is usually ExitStatus. -#[derive(PartialEq, Eq, Clone, Copy)] +#[derive(PartialEq, Eq, Clone, Copy, Show)] pub enum ProcessExit { /// Normal termination with an exit status. ExitStatus(int), @@ -505,15 +505,8 @@ pub enum ProcessExit { ExitSignal(int), } -impl fmt::Show for ProcessExit { - /// Format a ProcessExit enum, to nicely present the information. - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - - -impl fmt::String for ProcessExit { +#[stable] +impl fmt::Display for ProcessExit { /// Format a ProcessExit enum, to nicely present the information. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 648326eee99..9bfc15f1438 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -168,6 +168,7 @@ pub use core::raw; pub use core::simd; pub use core::result; pub use core::option; +pub use core::error; #[cfg(not(test))] pub use alloc::boxed; pub use alloc::rc; @@ -228,7 +229,6 @@ pub mod thunk; /* Common traits */ -pub mod error; pub mod num; /* Runtime and platform support */ diff --git a/src/libstd/num/mod.rs b/src/libstd/num/mod.rs index 3432767d6cd..9ced1a7e130 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num/mod.rs @@ -16,7 +16,7 @@ #![stable] #![allow(missing_docs)] -#[cfg(test)] use fmt::Show; +#[cfg(test)] use fmt::Debug; use ops::{Add, Sub, Mul, Div, Rem, Neg}; use marker::Copy; @@ -322,7 +322,7 @@ pub fn test_num(ten: T, two: T) where T: PartialEq + NumCast + Add + Sub + Mul + Div - + Rem + Show + + Rem + Debug + Copy { assert_eq!(ten.add(two), cast(12i).unwrap()); diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 78db6c158a8..985a8cd32e2 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -855,7 +855,7 @@ pub enum MapOption { impl Copy for MapOption {} /// Possible errors when creating a map. -#[derive(Copy)] +#[derive(Copy, Show)] pub enum MapError { /// # The following are POSIX-specific /// @@ -900,7 +900,8 @@ pub enum MapError { ErrMapViewOfFile(uint) } -impl fmt::Show for MapError { +#[stable] +impl fmt::Display for MapError { fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result { let str = match *self { ErrFdNotAvail => "fd not available for reading or writing", @@ -934,13 +935,6 @@ impl fmt::Show for MapError { impl Error for MapError { fn description(&self) -> &str { "memory map error" } - fn detail(&self) -> Option { Some(format!("{:?}", self)) } -} - -impl FromError for Box { - fn from_error(err: MapError) -> Box { - box err - } } // Round up `from` to be divisible by `to` diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 541f1e77140..ba61d7df915 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -823,13 +823,15 @@ pub struct Display<'a, P:'a> { filename: bool } -impl<'a, P: GenericPath> fmt::Show for Display<'a, P> { +#[stable] +impl<'a, P: GenericPath> fmt::Debug for Display<'a, P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Debug::fmt(&self.as_cow(), f) } } -impl<'a, P: GenericPath> fmt::String for Display<'a, P> { +#[stable] +impl<'a, P: GenericPath> fmt::Display for Display<'a, P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_cow().fmt(f) } diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index aab64639ab5..0edc01063cf 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -57,9 +57,10 @@ pub fn is_sep(c: char) -> bool { c == SEP } -impl fmt::Show for Path { +#[stable] +impl fmt::Debug for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(&self.display(), f) + fmt::Debug::fmt(&self.display(), f) } } diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 3cff1c67be3..59a071e8842 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -85,9 +85,10 @@ pub struct Path { sepidx: Option // index of the final separator in the non-prefix portion of repr } -impl fmt::Show for Path { +#[stable] +impl fmt::Debug for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(&self.display(), f) + fmt::Debug::fmt(&self.display(), f) } } diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 0ba19b70617..db9251131d1 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -393,7 +393,7 @@ impl !marker::Sync for SyncSender {} /// A `send` operation can only fail if the receiving end of a channel is /// disconnected, implying that the data could never be received. The error /// contains the data being sent as a payload so it can be recovered. -#[derive(PartialEq, Eq)] +#[derive(PartialEq, Eq, Show)] #[stable] pub struct SendError(pub T); @@ -401,13 +401,13 @@ pub struct SendError(pub T); /// /// The `recv` operation can only fail if the sending half of a channel is /// disconnected, implying that no further messages will ever be received. -#[derive(PartialEq, Eq, Clone, Copy)] +#[derive(PartialEq, Eq, Clone, Copy, Show)] #[stable] pub struct RecvError; /// This enumeration is the list of the possible reasons that try_recv could not /// return data when called. -#[derive(PartialEq, Clone, Copy)] +#[derive(PartialEq, Clone, Copy, Show)] #[stable] pub enum TryRecvError { /// This channel is currently empty, but the sender(s) have not yet @@ -423,7 +423,7 @@ pub enum TryRecvError { /// This enumeration is the list of the possible error outcomes for the /// `SyncSender::try_send` method. -#[derive(PartialEq, Clone)] +#[derive(PartialEq, Clone, Show)] #[stable] pub enum TrySendError { /// The data could not be sent on the channel because it would require that @@ -998,13 +998,15 @@ unsafe impl Send for RacyCell { } unsafe impl Sync for RacyCell { } // Oh dear -impl fmt::Show for SendError { +#[stable] +impl fmt::Display for SendError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "sending on a closed channel".fmt(f) } } -impl fmt::Show for TrySendError { +#[stable] +impl fmt::Display for TrySendError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { TrySendError::Full(..) => { @@ -1017,13 +1019,15 @@ impl fmt::Show for TrySendError { } } -impl fmt::Show for RecvError { +#[stable] +impl fmt::Display for RecvError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "receiving on a closed channel".fmt(f) } } -impl fmt::Show for TryRecvError { +#[stable] +impl fmt::Display for TryRecvError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { TryRecvError::Empty => { diff --git a/src/libstd/sync/poison.rs b/src/libstd/sync/poison.rs index e28c3c37b6f..c97fcf7cefb 100644 --- a/src/libstd/sync/poison.rs +++ b/src/libstd/sync/poison.rs @@ -53,6 +53,7 @@ pub struct Guard { /// is held. The precise semantics for when a lock is poisoned is documented on /// each lock, but once a lock is poisoned then all future acquisitions will /// return this error. +#[derive(Show)] #[stable] pub struct PoisonError { guard: T, @@ -60,6 +61,7 @@ pub struct PoisonError { /// An enumeration of possible errors which can occur while calling the /// `try_lock` method. +#[derive(Show)] #[stable] pub enum TryLockError { /// The lock could not be acquired because another task failed while holding @@ -90,7 +92,8 @@ pub type LockResult = Result>; #[stable] pub type TryLockResult = Result>; -impl fmt::Show for PoisonError { +#[stable] +impl fmt::Display for PoisonError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.description().fmt(f) } @@ -130,7 +133,8 @@ impl FromError> for TryLockError { } } -impl fmt::Show for TryLockError { +#[stable] +impl fmt::Display for TryLockError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.description().fmt(f) } diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index 932556fe1a6..1f181e1fa2a 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -519,14 +519,14 @@ mod test { fn test_unnamed_thread() { Thread::scoped(move|| { assert!(Thread::current().name().is_none()); - }).join().map_err(|_| ()).unwrap(); + }).join().ok().unwrap(); } #[test] fn test_named_thread() { Builder::new().name("ada lovelace".to_string()).scoped(move|| { assert!(Thread::current().name().unwrap() == "ada lovelace".to_string()); - }).join().map_err(|_| ()).unwrap(); + }).join().ok().unwrap(); } #[test] @@ -662,7 +662,7 @@ mod test { Err(e) => { type T = &'static str; assert!(e.is::()); - assert_eq!(*e.downcast::().unwrap(), "static string"); + assert_eq!(*e.downcast::().ok().unwrap(), "static string"); } Ok(()) => panic!() } @@ -676,7 +676,7 @@ mod test { Err(e) => { type T = String; assert!(e.is::()); - assert_eq!(*e.downcast::().unwrap(), "owned string".to_string()); + assert_eq!(*e.downcast::().ok().unwrap(), "owned string".to_string()); } Ok(()) => panic!() } @@ -690,9 +690,9 @@ mod test { Err(e) => { type T = Box; assert!(e.is::()); - let any = e.downcast::().unwrap(); + let any = e.downcast::().ok().unwrap(); assert!(any.is::()); - assert_eq!(*any.downcast::().unwrap(), 413u16); + assert_eq!(*any.downcast::().ok().unwrap(), 413u16); } Ok(()) => panic!() } diff --git a/src/libstd/time/duration.rs b/src/libstd/time/duration.rs index 162c3677168..2d56a8bcddf 100644 --- a/src/libstd/time/duration.rs +++ b/src/libstd/time/duration.rs @@ -334,7 +334,8 @@ impl Div for Duration { } } -impl fmt::String for Duration { +#[stable] +impl fmt::Display for Duration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // technically speaking, negative duration is not valid ISO 8601, // but we need to print it anyway. diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index 09235ee209c..7447e0b229e 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -15,7 +15,7 @@ pub use self::AbiArchitecture::*; use std::fmt; -#[derive(Copy, PartialEq)] +#[derive(Copy, PartialEq, Eq, Show)] pub enum Os { OsWindows, OsMacos, @@ -26,7 +26,7 @@ pub enum Os { OsDragonfly, } -#[derive(PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Clone, Copy)] +#[derive(PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Clone, Copy, Show)] pub enum Abi { // NB: This ordering MUST match the AbiDatas array below. // (This is ensured by the test indices_are_correct().) @@ -119,25 +119,13 @@ impl Abi { } } -impl fmt::Show for Abi { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - -impl fmt::String for Abi { +impl fmt::Display for Abi { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "\"{}\"", self.name()) } } -impl fmt::Show for Os { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - -impl fmt::String for Os { +impl fmt::Display for Os { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OsLinux => "linux".fmt(f), diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index fcf80410da2..6e2818bf267 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -100,28 +100,28 @@ impl Ident { } } -impl fmt::Show for Ident { +impl fmt::Debug for Ident { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}#{}", self.name, self.ctxt) } } -impl fmt::String for Ident { +impl fmt::Display for Ident { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&self.name, f) + fmt::Display::fmt(&self.name, f) } } -impl fmt::Show for Name { +impl fmt::Debug for Name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Name(nm) = *self; write!(f, "{:?}({})", token::get_name(*self).get(), nm) } } -impl fmt::String for Name { +impl fmt::Display for Name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(token::get_name(*self).get(), f) + fmt::Display::fmt(token::get_name(*self).get(), f) } } @@ -1100,13 +1100,13 @@ impl PartialEq for IntTy { } } -impl fmt::Show for IntTy { +impl fmt::Debug for IntTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt(self, f) } } -impl fmt::String for IntTy { +impl fmt::Display for IntTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::int_ty_to_string(*self, None)) } @@ -1155,13 +1155,13 @@ impl UintTy { } } -impl fmt::Show for UintTy { +impl fmt::Debug for UintTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt(self, f) } } -impl fmt::String for UintTy { +impl fmt::Display for UintTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::uint_ty_to_string(*self, None)) } @@ -1173,13 +1173,13 @@ pub enum FloatTy { TyF64, } -impl fmt::Show for FloatTy { +impl fmt::Debug for FloatTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt(self, f) } } -impl fmt::String for FloatTy { +impl fmt::Display for FloatTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::float_ty_to_string(*self)) } @@ -1222,24 +1222,15 @@ pub enum PrimTy { TyChar } -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, Show)] pub enum Onceness { Once, Many } -impl fmt::Show for Onceness { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(match *self { - Once => "once", - Many => "many", - }, f) - } -} - -impl fmt::String for Onceness { +impl fmt::Display for Onceness { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(match *self { + fmt::Display::fmt(match *self { Once => "once", Many => "many", }, f) @@ -1358,9 +1349,9 @@ pub enum Unsafety { Normal, } -impl fmt::String for Unsafety { +impl fmt::Display for Unsafety { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(match *self { + fmt::Display::fmt(match *self { Unsafety::Normal => "normal", Unsafety::Unsafe => "unsafe", }, f) @@ -1375,7 +1366,7 @@ pub enum ImplPolarity { Negative, } -impl fmt::Show for ImplPolarity { +impl fmt::Debug for ImplPolarity { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ImplPolarity::Positive => "positive".fmt(f), diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index f462a730d3a..fcdcd9d8263 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -46,7 +46,7 @@ impl PathElem { } } -impl fmt::String for PathElem { +impl fmt::Display for PathElem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let slot = token::get_name(self.name()); write!(f, "{}", slot) diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 6f57c06d33e..856237f2155 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -358,9 +358,9 @@ pub enum StabilityLevel { Locked } -impl fmt::String for StabilityLevel { +impl fmt::Display for StabilityLevel { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(self, f) + fmt::Debug::fmt(self, f) } } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 7213b0fa955..e8c2b0318ce 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -235,9 +235,9 @@ pub enum Level { Help, } -impl fmt::String for Level { +impl fmt::Display for Level { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use std::fmt::String; + use std::fmt::Display; match *self { Bug => "error: internal compiler error".fmt(f), diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index 603c4478007..e52a2b513ce 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -99,7 +99,9 @@ pub fn expand_meta_derive(cx: &mut ExtCtxt, "Rand" => expand!(rand::expand_deriving_rand), + // NOTE(stage0): remove "Show" "Show" => expand!(show::expand_deriving_show), + "Debug" => expand!(show::expand_deriving_show), "Default" => expand!(default::expand_deriving_default), diff --git a/src/libsyntax/ext/deriving/show.rs b/src/libsyntax/ext/deriving/show.rs index 48034ce50ab..f5b5d4dda19 100644 --- a/src/libsyntax/ext/deriving/show.rs +++ b/src/libsyntax/ext/deriving/show.rs @@ -35,7 +35,7 @@ pub fn expand_deriving_show(cx: &mut ExtCtxt, let trait_def = TraitDef { span: span, attributes: Vec::new(), - path: Path::new(vec!("std", "fmt", "Show")), + path: Path::new(vec!("std", "fmt", "Debug")), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!( @@ -67,7 +67,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span, Struct(_) => substr.type_ident, EnumMatching(_, v, _) => v.node.name, EnumNonMatchingCollapsed(..) | StaticStruct(..) | StaticEnum(..) => { - cx.span_bug(span, "nonsensical .fields in `#[derive(Show)]`") + cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`") } }; diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index f512b33f024..84f2ef0678d 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -603,8 +603,8 @@ impl<'a, 'b> Context<'a, 'b> { let trait_ = match *ty { Known(ref tyname) => { match &tyname[] { - "" => "String", - "?" => "Show", + "" => "Display", + "?" => "Debug", "e" => "LowerExp", "E" => "UpperExp", "o" => "Octal", diff --git a/src/libsyntax/owned_slice.rs b/src/libsyntax/owned_slice.rs index 707e540a17b..872354024e9 100644 --- a/src/libsyntax/owned_slice.rs +++ b/src/libsyntax/owned_slice.rs @@ -22,7 +22,7 @@ pub struct OwnedSlice { data: Box<[T]> } -impl fmt::Show for OwnedSlice { +impl fmt::Debug for OwnedSlice { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { self.data.fmt(fmt) } diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 4cdafb36eec..f9de55756b5 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -586,10 +586,10 @@ impl<'a> StringReader<'a> { /// `\x00` marker. #[inline(never)] fn scan_embedded_hygienic_ident(&mut self) -> ast::Ident { - fn bump_expecting_char<'a,D:fmt::Show>(r: &mut StringReader<'a>, - c: char, - described_c: D, - whence: &str) { + fn bump_expecting_char<'a,D:fmt::Debug>(r: &mut StringReader<'a>, + c: char, + described_c: D, + whence: &str) { match r.curr { Some(r_c) if r_c == c => r.bump(), Some(r_c) => panic!("expected {:?}, hit {:?}, {}", described_c, r_c, whence), diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index e5aef12e827..6112ee851ac 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -375,7 +375,7 @@ pub enum Nonterminal { NtTT(P), // needs P'ed to break a circularity } -impl fmt::Show for Nonterminal { +impl fmt::Debug for Nonterminal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { NtItem(..) => f.pad("NtItem(..)"), @@ -651,15 +651,15 @@ impl BytesContainer for InternedString { } } -impl fmt::Show for InternedString { +impl fmt::Debug for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Debug::fmt(&self.string[], f) } } -impl fmt::String for InternedString { +impl fmt::Display for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", &self.string[]) + fmt::Display::fmt(&self.string[], f) } } diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index 37fa8703706..01f3839b039 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -36,7 +36,7 @@ //! implementation changes (using a special thread-local heap, for example). //! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated. -use std::fmt::{self, Show}; +use std::fmt::{self, Display, Debug}; use std::hash::{Hash, Hasher}; use std::ops::Deref; use std::ptr; @@ -100,9 +100,14 @@ impl PartialEq for P { impl Eq for P {} -impl Show for P { +impl Debug for P { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - (**self).fmt(f) + Debug::fmt(&**self, f) + } +} +impl Display for P { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) } } diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 5dca39f1aea..35654ae0598 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -114,9 +114,16 @@ impl Ord for RcStr { } } -impl fmt::Show for RcStr { +impl fmt::Debug for RcStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use std::fmt::Show; + use std::fmt::Debug; + self[].fmt(f) + } +} + +impl fmt::Display for RcStr { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use std::fmt::Display; self[].fmt(f) } } diff --git a/src/libterm/terminfo/mod.rs b/src/libterm/terminfo/mod.rs index 4933938f338..2ef0bca3785 100644 --- a/src/libterm/terminfo/mod.rs +++ b/src/libterm/terminfo/mod.rs @@ -197,7 +197,7 @@ impl TerminfoTerminal { let mut file = entry.unwrap(); let ti = parse(&mut file, false); if ti.is_err() { - debug!("error parsing terminfo entry: {:?}", ti.unwrap_err()); + debug!("error parsing terminfo entry: {:?}", ti.err().unwrap()); return None; } diff --git a/src/libterm/terminfo/parm.rs b/src/libterm/terminfo/parm.rs index b0bce8f3112..0b51a976c0e 100644 --- a/src/libterm/terminfo/parm.rs +++ b/src/libterm/terminfo/parm.rs @@ -624,7 +624,7 @@ mod test { }; let res = get_res("%p1", cap, &[p], vars); assert!(res.is_ok(), - "Op {} failed with 1 stack entry: {}", cap, res.unwrap_err()); + "Op {} failed with 1 stack entry: {}", cap, res.err().unwrap()); } let caps = ["%+", "%-", "%*", "%/", "%m", "%&", "%|", "%A", "%O"]; for &cap in caps.iter() { @@ -636,7 +636,7 @@ mod test { "Binop {} succeeded incorrectly with 1 stack entry", cap); let res = get_res("%{1}%{2}", cap, &[], vars); assert!(res.is_ok(), - "Binop {} failed with 2 stack entries: {:?}", cap, res.unwrap_err()); + "Binop {} failed with 2 stack entries: {:?}", cap, res.err().unwrap()); } } @@ -651,15 +651,15 @@ mod test { for &(op, bs) in v.iter() { let s = format!("%{{1}}%{{2}}%{}%d", op); let res = expand(s.as_bytes(), &[], &mut Variables::new()); - assert!(res.is_ok(), res.unwrap_err()); + assert!(res.is_ok(), res.err().unwrap()); assert_eq!(res.unwrap(), vec!(b'0' + bs[0])); let s = format!("%{{1}}%{{1}}%{}%d", op); let res = expand(s.as_bytes(), &[], &mut Variables::new()); - assert!(res.is_ok(), res.unwrap_err()); + assert!(res.is_ok(), res.err().unwrap()); assert_eq!(res.unwrap(), vec!(b'0' + bs[1])); let s = format!("%{{2}}%{{1}}%{}%d", op); let res = expand(s.as_bytes(), &[], &mut Variables::new()); - assert!(res.is_ok(), res.unwrap_err()); + assert!(res.is_ok(), res.err().unwrap()); assert_eq!(res.unwrap(), vec!(b'0' + bs[2])); } } @@ -669,15 +669,15 @@ mod test { let mut vars = Variables::new(); let s = b"\\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m"; let res = expand(s, &[Number(1)], &mut vars); - assert!(res.is_ok(), res.unwrap_err()); + assert!(res.is_ok(), res.err().unwrap()); assert_eq!(res.unwrap(), "\\E[31m".bytes().collect::>()); let res = expand(s, &[Number(8)], &mut vars); - assert!(res.is_ok(), res.unwrap_err()); + assert!(res.is_ok(), res.err().unwrap()); assert_eq!(res.unwrap(), "\\E[90m".bytes().collect::>()); let res = expand(s, &[Number(42)], &mut vars); - assert!(res.is_ok(), res.unwrap_err()); + assert!(res.is_ok(), res.err().unwrap()); assert_eq!(res.unwrap(), "\\E[38;5;42m".bytes().collect::>()); } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index f9fb767f77e..f2706298066 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -63,7 +63,6 @@ use std::any::Any; use std::cmp; use std::collections::BTreeMap; use std::f64; -use std::fmt::Show; use std::fmt; use std::io::fs::PathExtensions; use std::io::stdio::StdWriter; @@ -109,9 +108,9 @@ impl TestName { } } } -impl fmt::String for TestName { +impl fmt::Display for TestName { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self.as_slice(), f) + fmt::Display::fmt(self.as_slice(), f) } } @@ -172,7 +171,7 @@ impl TestFn { } } -impl fmt::Show for TestFn { +impl fmt::Debug for TestFn { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { StaticTestFn(..) => "StaticTestFn(..)", diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index 6061c4fd1d3..cd461cf5766 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -333,7 +333,7 @@ pub fn winsorize(samples: &mut [T], pct: T) { } /// Render writes the min, max and quartiles of the provided `Summary` to the provided `Writer`. -pub fn write_5_number_summary(w: &mut W, +pub fn write_5_number_summary(w: &mut W, s: &Summary) -> io::IoResult<()> { let (q1,q2,q3) = s.quartiles; write!(w, "(min={}, q1={}, med={}, q3={}, max={})", @@ -355,7 +355,7 @@ pub fn write_5_number_summary(w: /// ```{.ignore} /// 10 | [--****#******----------] | 40 /// ``` -pub fn write_boxplot( +pub fn write_boxplot( w: &mut W, s: &Summary, width_hint: uint) diff --git a/src/test/compile-fail/dst-index.rs b/src/test/compile-fail/dst-index.rs index 2a66b87fece..876c98298dc 100644 --- a/src/test/compile-fail/dst-index.rs +++ b/src/test/compile-fail/dst-index.rs @@ -12,7 +12,7 @@ // can't be used as rvalues use std::ops::Index; -use std::fmt::Show; +use std::fmt::Debug; struct S; @@ -31,9 +31,9 @@ struct T; impl Copy for T {} impl Index for T { - type Output = Show + 'static; + type Output = Debug + 'static; - fn index<'a>(&'a self, idx: &usize) -> &'a (Show + 'static) { + fn index<'a>(&'a self, idx: &usize) -> &'a (Debug + 'static) { static x: usize = 42; &x } diff --git a/src/test/compile-fail/issue-14853.rs b/src/test/compile-fail/issue-14853.rs index 22ba54fea14..51deb99a4f2 100644 --- a/src/test/compile-fail/issue-14853.rs +++ b/src/test/compile-fail/issue-14853.rs @@ -8,12 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::fmt::Show; +use std::fmt::Debug; trait Str {} trait Something { - fn yay(_: Option, thing: &[T]); + fn yay(_: Option, thing: &[T]); } struct X { data: u32 } diff --git a/src/test/compile-fail/issue-15094.rs b/src/test/compile-fail/issue-15094.rs index 5b33069b595..2c03a9e0733 100644 --- a/src/test/compile-fail/issue-15094.rs +++ b/src/test/compile-fail/issue-15094.rs @@ -12,19 +12,19 @@ use std::{fmt, ops}; -struct Shower { +struct Debuger { x: T } -impl ops::Fn<(), ()> for Shower { +impl ops::Fn<(), ()> for Debuger { fn call(&self, _args: ()) { //~^ ERROR `call` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn println!("{:?}", self.x); } } -fn make_shower(x: T) -> Shower { - Shower { x: x } +fn make_shower(x: T) -> Debuger { + Debuger { x: x } } pub fn main() { diff --git a/src/test/compile-fail/liveness-use-after-send.rs b/src/test/compile-fail/liveness-use-after-send.rs index 4ba24800f5d..a49339ecd7f 100644 --- a/src/test/compile-fail/liveness-use-after-send.rs +++ b/src/test/compile-fail/liveness-use-after-send.rs @@ -8,13 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn send(ch: _chan, data: T) { +fn send(ch: _chan, data: T) { println!("{:?}", ch); println!("{:?}", data); panic!(); } -#[derive(Show)] +#[derive(Debug)] struct _chan(isize); // Tests that "log(debug, message);" is flagged as using diff --git a/src/test/run-fail/assert-eq-macro-panic.rs b/src/test/run-fail/assert-eq-macro-panic.rs index 4b1a420cb78..69ed025070b 100644 --- a/src/test/run-fail/assert-eq-macro-panic.rs +++ b/src/test/run-fail/assert-eq-macro-panic.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// error-pattern:assertion failed: `(left == right) && (right == left)` (left: `14i`, right: `15i`) +// error-pattern:assertion failed: `(left == right) && (right == left)` (left: `14`, right: `15`) fn main() { assert_eq!(14i,15i); diff --git a/src/test/run-pass/cfg_attr.rs b/src/test/run-pass/cfg_attr.rs index 7e508d91c87..9bef7f70420 100644 --- a/src/test/run-pass/cfg_attr.rs +++ b/src/test/run-pass/cfg_attr.rs @@ -10,44 +10,44 @@ // compile-flags:--cfg set1 --cfg set2 #![allow(dead_code)] -use std::fmt::Show; +use std::fmt::Debug; -struct NotShowable; +struct NotDebugable; -#[cfg_attr(set1, derive(Show))] +#[cfg_attr(set1, derive(Debug))] struct Set1; -#[cfg_attr(notset, derive(Show))] -struct Notset(NotShowable); +#[cfg_attr(notset, derive(Debug))] +struct Notset(NotDebugable); -#[cfg_attr(not(notset), derive(Show))] +#[cfg_attr(not(notset), derive(Debug))] struct NotNotset; -#[cfg_attr(not(set1), derive(Show))] -struct NotSet1(NotShowable); +#[cfg_attr(not(set1), derive(Debug))] +struct NotSet1(NotDebugable); -#[cfg_attr(all(set1, set2), derive(Show))] +#[cfg_attr(all(set1, set2), derive(Debug))] struct AllSet1Set2; -#[cfg_attr(all(set1, notset), derive(Show))] -struct AllSet1Notset(NotShowable); +#[cfg_attr(all(set1, notset), derive(Debug))] +struct AllSet1Notset(NotDebugable); -#[cfg_attr(any(set1, notset), derive(Show))] +#[cfg_attr(any(set1, notset), derive(Debug))] struct AnySet1Notset; -#[cfg_attr(any(notset, notset2), derive(Show))] -struct AnyNotsetNotset2(NotShowable); +#[cfg_attr(any(notset, notset2), derive(Debug))] +struct AnyNotsetNotset2(NotDebugable); -#[cfg_attr(all(not(notset), any(set1, notset)), derive(Show))] +#[cfg_attr(all(not(notset), any(set1, notset)), derive(Debug))] struct Complex; -#[cfg_attr(any(notset, not(any(set1, notset))), derive(Show))] -struct ComplexNot(NotShowable); +#[cfg_attr(any(notset, not(any(set1, notset))), derive(Debug))] +struct ComplexNot(NotDebugable); -#[cfg_attr(any(target_endian = "little", target_endian = "big"), derive(Show))] +#[cfg_attr(any(target_endian = "little", target_endian = "big"), derive(Debug))] struct KeyValue; -fn is_show() {} +fn is_show() {} fn main() { is_show::(); diff --git a/src/test/run-pass/coerce-expect-unsized.rs b/src/test/run-pass/coerce-expect-unsized.rs index f590e6e0728..06849a2b973 100644 --- a/src/test/run-pass/coerce-expect-unsized.rs +++ b/src/test/run-pass/coerce-expect-unsized.rs @@ -11,7 +11,7 @@ #![allow(unknown_features)] #![feature(box_syntax)] -use std::fmt::Show; +use std::fmt::Debug; // Check that coercions apply at the pointer level and don't cause // rvalue expressions to be unsized. See #20169 for more information. @@ -21,15 +21,15 @@ pub fn main() { let _: Box<[int]> = box if true { [1, 2, 3] } else { [1, 3, 4] }; let _: Box<[int]> = box match true { true => [1, 2, 3], false => [1, 3, 4] }; let _: Box _> = box { |x| (x as u8) }; - let _: Box = box if true { false } else { true }; - let _: Box = box match true { true => 'a', false => 'b' }; + let _: Box = box if true { false } else { true }; + let _: Box = box match true { true => 'a', false => 'b' }; let _: &[int] = &{ [1, 2, 3] }; let _: &[int] = &if true { [1, 2, 3] } else { [1, 3, 4] }; let _: &[int] = &match true { true => [1, 2, 3], false => [1, 3, 4] }; let _: &Fn(int) -> _ = &{ |x| (x as u8) }; - let _: &Show = &if true { false } else { true }; - let _: &Show = &match true { true => 'a', false => 'b' }; + let _: &Debug = &if true { false } else { true }; + let _: &Debug = &match true { true => 'a', false => 'b' }; let _: Box<[int]> = Box::new([1, 2, 3]); let _: Box _> = Box::new(|x| (x as u8)); diff --git a/src/test/run-pass/coherence-where-clause.rs b/src/test/run-pass/coherence-where-clause.rs index 99c475b7207..78b603690fd 100644 --- a/src/test/run-pass/coherence-where-clause.rs +++ b/src/test/run-pass/coherence-where-clause.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::fmt::Show; +use std::fmt::Debug; use std::default::Default; trait MyTrait { @@ -23,7 +23,7 @@ impl MyTrait for T } } -#[derive(Clone,Show,PartialEq)] +#[derive(Clone,Debug,PartialEq)] struct MyType { dummy: uint } @@ -35,7 +35,7 @@ impl MyTrait for MyType { } fn test_eq(m: M, n: M) -where M : MyTrait + Show + PartialEq +where M : MyTrait + Debug + PartialEq { assert_eq!(m.get(), n); } diff --git a/src/test/run-pass/deriving-show-2.rs b/src/test/run-pass/deriving-show-2.rs index 8465f521e43..acd07bc98d3 100644 --- a/src/test/run-pass/deriving-show-2.rs +++ b/src/test/run-pass/deriving-show-2.rs @@ -10,39 +10,39 @@ use std::fmt; -#[derive(Show)] +#[derive(Debug)] enum A {} -#[derive(Show)] +#[derive(Debug)] enum B { B1, B2, B3 } -#[derive(Show)] +#[derive(Debug)] enum C { C1(int), C2(B), C3(String) } -#[derive(Show)] +#[derive(Debug)] enum D { D1{ a: int } } -#[derive(Show)] +#[derive(Debug)] struct E; -#[derive(Show)] +#[derive(Debug)] struct F(int); -#[derive(Show)] +#[derive(Debug)] struct G(int, int); -#[derive(Show)] +#[derive(Debug)] struct H { a: int } -#[derive(Show)] +#[derive(Debug)] struct I { a: int, b: int } -#[derive(Show)] +#[derive(Debug)] struct J(Custom); struct Custom; -impl fmt::Show for Custom { +impl fmt::Debug for Custom { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "yay") } } -trait ToShow { +trait ToDebug { fn to_show(&self) -> String; } -impl ToShow for T { +impl ToDebug for T { fn to_show(&self) -> String { format!("{:?}", self) } @@ -51,12 +51,12 @@ impl ToShow for T { pub fn main() { assert_eq!(B::B1.to_show(), "B1".to_string()); assert_eq!(B::B2.to_show(), "B2".to_string()); - assert_eq!(C::C1(3).to_show(), "C1(3i)".to_string()); + assert_eq!(C::C1(3).to_show(), "C1(3)".to_string()); assert_eq!(C::C2(B::B2).to_show(), "C2(B2)".to_string()); - assert_eq!(D::D1{ a: 2 }.to_show(), "D1 { a: 2i }".to_string()); + assert_eq!(D::D1{ a: 2 }.to_show(), "D1 { a: 2 }".to_string()); assert_eq!(E.to_show(), "E".to_string()); - assert_eq!(F(3).to_show(), "F(3i)".to_string()); - assert_eq!(G(3, 4).to_show(), "G(3i, 4i)".to_string()); - assert_eq!(I{ a: 2, b: 4 }.to_show(), "I { a: 2i, b: 4i }".to_string()); + assert_eq!(F(3).to_show(), "F(3)".to_string()); + assert_eq!(G(3, 4).to_show(), "G(3, 4)".to_string()); + assert_eq!(I{ a: 2, b: 4 }.to_show(), "I { a: 2, b: 4 }".to_string()); assert_eq!(J(Custom).to_show(), "J(yay)".to_string()); } diff --git a/src/test/run-pass/deriving-show.rs b/src/test/run-pass/deriving-show.rs index 99c73dd94a6..7986b97685f 100644 --- a/src/test/run-pass/deriving-show.rs +++ b/src/test/run-pass/deriving-show.rs @@ -8,16 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#[derive(Show)] +#[derive(Debug)] struct Unit; -#[derive(Show)] +#[derive(Debug)] struct Tuple(int, uint); -#[derive(Show)] +#[derive(Debug)] struct Struct { x: int, y: uint } -#[derive(Show)] +#[derive(Debug)] enum Enum { Nullary, Variant(int, uint), @@ -32,9 +32,9 @@ macro_rules! t { pub fn main() { t!(Unit, "Unit"); - t!(Tuple(1, 2), "Tuple(1i, 2u)"); - t!(Struct { x: 1, y: 2 }, "Struct { x: 1i, y: 2u }"); + t!(Tuple(1, 2), "Tuple(1, 2)"); + t!(Struct { x: 1, y: 2 }, "Struct { x: 1, y: 2 }"); t!(Enum::Nullary, "Nullary"); - t!(Enum::Variant(1, 2), "Variant(1i, 2u)"); - t!(Enum::StructVariant { x: 1, y: 2 }, "StructVariant { x: 1i, y: 2u }"); + t!(Enum::Variant(1, 2), "Variant(1, 2)"); + t!(Enum::StructVariant { x: 1, y: 2 }, "StructVariant { x: 1, y: 2 }"); } diff --git a/src/test/run-pass/dst-index.rs b/src/test/run-pass/dst-index.rs index dfb28fc9344..0c7ecfcefff 100644 --- a/src/test/run-pass/dst-index.rs +++ b/src/test/run-pass/dst-index.rs @@ -12,7 +12,7 @@ // work and don't ICE. use std::ops::Index; -use std::fmt::Show; +use std::fmt::Debug; struct S; @@ -27,16 +27,16 @@ impl Index for S { struct T; impl Index for T { - type Output = Show + 'static; + type Output = Debug + 'static; - fn index<'a>(&'a self, idx: &uint) -> &'a (Show + 'static) { + fn index<'a>(&'a self, idx: &uint) -> &'a (Debug + 'static) { static X: uint = 42; - &X as &(Show + 'static) + &X as &(Debug + 'static) } } fn main() { assert_eq!(&S[0], "hello"); &T[0]; - // let x = &x as &Show; + // let x = &x as &Debug; } diff --git a/src/test/run-pass/ifmt.rs b/src/test/run-pass/ifmt.rs index c22fb811a7b..e273baef256 100644 --- a/src/test/run-pass/ifmt.rs +++ b/src/test/run-pass/ifmt.rs @@ -33,7 +33,7 @@ impl fmt::UpperHex for B { f.write_str("adios") } } -impl fmt::String for C { +impl fmt::Display for C { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad_integral(true, "☃", "123") } @@ -63,8 +63,8 @@ pub fn main() { t!(format!("{}", 10i), "10"); t!(format!("{}", 10u), "10"); t!(format!("{:?}", '☃'), "'\\u{2603}'"); - t!(format!("{:?}", 10i), "10i"); - t!(format!("{:?}", 10u), "10u"); + t!(format!("{:?}", 10i), "10"); + t!(format!("{:?}", 10u), "10"); t!(format!("{:?}", "true"), "\"true\""); t!(format!("{:?}", "foo\nbar"), "\"foo\\nbar\""); t!(format!("{:o}", 10u), "12"); @@ -72,22 +72,22 @@ pub fn main() { t!(format!("{:X}", 10u), "A"); t!(format!("{}", "foo"), "foo"); t!(format!("{}", "foo".to_string()), "foo"); - t!(format!("{:p}", 0x1234 as *const int), "0x1234"); - t!(format!("{:p}", 0x1234 as *mut int), "0x1234"); + t!(format!("{:p}", 0x1234 as *const isize), "0x1234"); + t!(format!("{:p}", 0x1234 as *mut isize), "0x1234"); t!(format!("{:x}", A), "aloha"); t!(format!("{:X}", B), "adios"); t!(format!("foo {} ☃☃☃☃☃☃", "bar"), "foo bar ☃☃☃☃☃☃"); t!(format!("{1} {0}", 0i, 1i), "1 0"); - t!(format!("{foo} {bar}", foo=0i, bar=1i), "0 1"); - t!(format!("{foo} {1} {bar} {0}", 0i, 1i, foo=2i, bar=3i), "2 1 3 0"); + t!(format!("{foo} {bar}", foo=0i, bar=1is), "0 1"); + t!(format!("{foo} {1} {bar} {0}", 0is, 1is, foo=2is, bar=3is), "2 1 3 0"); t!(format!("{} {0}", "a"), "a a"); t!(format!("{foo_bar}", foo_bar=1i), "1"); t!(format!("{}", 5i + 5i), "10"); t!(format!("{:#4}", C), "☃123"); // FIXME(#20676) - // let a: &fmt::Show = &1i; - // t!(format!("{:?}", a), "1i"); + // let a: &fmt::Debug = &1i; + // t!(format!("{:?}", a), "1"); // Formatting strings and their arguments @@ -154,7 +154,7 @@ pub fn main() { // make sure that format! doesn't cause spurious unused-unsafe warnings when // it's inside of an outer unsafe block unsafe { - let a: int = ::std::mem::transmute(3u); + let a: isize = ::std::mem::transmute(3u); format!("{}", a); } @@ -215,8 +215,8 @@ fn test_format_args() { fn test_order() { // Make sure format!() arguments are always evaluated in a left-to-right // ordering - fn foo() -> int { - static mut FOO: int = 0; + fn foo() -> isize { + static mut FOO: isize = 0; unsafe { FOO += 1; FOO diff --git a/src/test/run-pass/issue-20676.rs b/src/test/run-pass/issue-20676.rs index fd99fc01a23..01a2322ae93 100644 --- a/src/test/run-pass/issue-20676.rs +++ b/src/test/run-pass/issue-20676.rs @@ -15,6 +15,6 @@ use std::fmt; fn main() { - let a: &fmt::Show = &1_i32; + let a: &fmt::Debug = &1_i32; format!("{:?}", a); } diff --git a/src/test/run-pass/issue-3559.rs b/src/test/run-pass/issue-3559.rs index 633832f424c..0118fce4ec3 100644 --- a/src/test/run-pass/issue-3559.rs +++ b/src/test/run-pass/issue-3559.rs @@ -24,6 +24,6 @@ pub fn main() { let mut table = HashMap::new(); table.insert("one".to_string(), 1i); table.insert("two".to_string(), 2i); - assert!(check_strs(format!("{:?}", table).as_slice(), "HashMap {\"one\": 1i, \"two\": 2i}") || - check_strs(format!("{:?}", table).as_slice(), "HashMap {\"two\": 2i, \"one\": 1i}")); + assert!(check_strs(format!("{:?}", table).as_slice(), "HashMap {\"one\": 1, \"two\": 2}") || + check_strs(format!("{:?}", table).as_slice(), "HashMap {\"two\": 2, \"one\": 1}")); } diff --git a/src/test/run-pass/issue-4252.rs b/src/test/run-pass/issue-4252.rs index 3606aff05ff..9d5f8576c63 100644 --- a/src/test/run-pass/issue-4252.rs +++ b/src/test/run-pass/issue-4252.rs @@ -11,28 +11,28 @@ #![feature(unsafe_destructor)] trait X { - fn call(&self, x: &T); - fn default_method(&self, x: &T) { + fn call(&self, x: &T); + fn default_method(&self, x: &T) { println!("X::default_method {:?}", x); } } -#[derive(Show)] +#[derive(Debug)] struct Y(int); -#[derive(Show)] +#[derive(Debug)] struct Z { x: T } impl X for Y { - fn call(&self, x: &T) { + fn call(&self, x: &T) { println!("X::call {:?} {:?}", self, x); } } #[unsafe_destructor] -impl Drop for Z { +impl Drop for Z { fn drop(&mut self) { // These statements used to cause an ICE. self.x.call(self); diff --git a/src/test/run-pass/issue-8898.rs b/src/test/run-pass/issue-8898.rs index f845db9c421..379b8f7700e 100644 --- a/src/test/run-pass/issue-8898.rs +++ b/src/test/run-pass/issue-8898.rs @@ -8,17 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn assert_repr_eq(obj : T, expected : String) { +fn assert_repr_eq(obj : T, expected : String) { assert_eq!(expected, format!("{:?}", obj)); } pub fn main() { - let abc = [1i, 2, 3]; + let abc = [1, 2, 3]; let tf = [true, false]; let x = [(), ()]; let slice = &x[..1]; - assert_repr_eq(&abc[], "[1i, 2i, 3i]".to_string()); + assert_repr_eq(&abc[], "[1, 2, 3]".to_string()); assert_repr_eq(&tf[], "[true, false]".to_string()); assert_repr_eq(&x[], "[(), ()]".to_string()); assert_repr_eq(slice, "[()]".to_string()); diff --git a/src/test/run-pass/log-knows-the-names-of-variants-in-std.rs b/src/test/run-pass/log-knows-the-names-of-variants-in-std.rs index 7fb2390b84b..c4b45ae0f0e 100644 --- a/src/test/run-pass/log-knows-the-names-of-variants-in-std.rs +++ b/src/test/run-pass/log-knows-the-names-of-variants-in-std.rs @@ -8,19 +8,19 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#[derive(Clone, Show)] +#[derive(Clone, Debug)] enum foo { a(uint), b(String), } -fn check_log(exp: String, v: T) { +fn check_log(exp: String, v: T) { assert_eq!(exp, format!("{:?}", v)); } pub fn main() { - let mut x = Some(foo::a(22u)); - let exp = "Some(a(22u))".to_string(); + let mut x = Some(foo::a(22)); + let exp = "Some(a(22))".to_string(); let act = format!("{:?}", x); assert_eq!(act, exp); check_log(exp, x); diff --git a/src/test/run-pass/log-knows-the-names-of-variants.rs b/src/test/run-pass/log-knows-the-names-of-variants.rs index 45fd2098dc4..e8852377957 100644 --- a/src/test/run-pass/log-knows-the-names-of-variants.rs +++ b/src/test/run-pass/log-knows-the-names-of-variants.rs @@ -8,20 +8,20 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#[derive(Show)] +#[derive(Debug)] enum foo { - a(uint), + a(usize), b(String), c, } -#[derive(Show)] +#[derive(Debug)] enum bar { d, e, f } pub fn main() { - assert_eq!("a(22u)".to_string(), format!("{:?}", foo::a(22u))); + assert_eq!("a(22)".to_string(), format!("{:?}", foo::a(22))); assert_eq!("c".to_string(), format!("{:?}", foo::c)); assert_eq!("d".to_string(), format!("{:?}", bar::d)); } diff --git a/src/test/run-pass/multidispatch1.rs b/src/test/run-pass/multidispatch1.rs index 87d188418bd..15df67e1488 100644 --- a/src/test/run-pass/multidispatch1.rs +++ b/src/test/run-pass/multidispatch1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::fmt::Show; +use std::fmt::Debug; trait MyTrait { fn get(&self) -> T; @@ -29,7 +29,7 @@ impl MyTrait for MyType { } fn test_eq(m: M, v: T) -where T : Eq + Show, +where T : Eq + Debug, M : MyTrait { assert_eq!(m.get(), v); diff --git a/src/test/run-pass/multidispatch2.rs b/src/test/run-pass/multidispatch2.rs index 1aa15cc5983..0c2652e6a7c 100644 --- a/src/test/run-pass/multidispatch2.rs +++ b/src/test/run-pass/multidispatch2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::fmt::Show; +use std::fmt::Debug; use std::default::Default; trait MyTrait { @@ -34,7 +34,7 @@ impl MyTrait for MyType { } fn test_eq(m: M, v: T) -where T : Eq + Show, +where T : Eq + Debug, M : MyTrait { assert_eq!(m.get(), v); diff --git a/src/test/run-pass/no-landing-pads.rs b/src/test/run-pass/no-landing-pads.rs index 64e78c3483b..c90c6ce87f0 100644 --- a/src/test/run-pass/no-landing-pads.rs +++ b/src/test/run-pass/no-landing-pads.rs @@ -26,6 +26,6 @@ fn main() { Thread::scoped(move|| -> () { let _a = A; panic!(); - }).join().unwrap_err(); + }).join().err().unwrap(); assert!(unsafe { !HIT }); } diff --git a/src/test/run-pass/overloaded-index-assoc-list.rs b/src/test/run-pass/overloaded-index-assoc-list.rs index 2e044227eb1..5e0523d7041 100644 --- a/src/test/run-pass/overloaded-index-assoc-list.rs +++ b/src/test/run-pass/overloaded-index-assoc-list.rs @@ -28,7 +28,7 @@ impl AssociationList { } } -impl Index for AssociationList { +impl Index for AssociationList { type Output = V; fn index<'a>(&'a self, index: &K) -> &'a V { diff --git a/src/test/run-pass/rec-align-u32.rs b/src/test/run-pass/rec-align-u32.rs index 5b91d5e930f..05643b0b56b 100644 --- a/src/test/run-pass/rec-align-u32.rs +++ b/src/test/run-pass/rec-align-u32.rs @@ -22,14 +22,14 @@ mod rusti { } // This is the type with the questionable alignment -#[derive(Show)] +#[derive(Debug)] struct Inner { c64: u32 } // This is the type that contains the type with the // questionable alignment, for testing -#[derive(Show)] +#[derive(Debug)] struct Outer { c8: u8, t: Inner @@ -66,6 +66,6 @@ pub fn main() { // because `inner`s alignment was 4. assert_eq!(mem::size_of::(), m::size()); - assert_eq!(y, "Outer { c8: 22u8, t: Inner { c64: 44u32 } }".to_string()); + assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } } diff --git a/src/test/run-pass/rec-align-u64.rs b/src/test/run-pass/rec-align-u64.rs index 27941542d00..eaf76ef5714 100644 --- a/src/test/run-pass/rec-align-u64.rs +++ b/src/test/run-pass/rec-align-u64.rs @@ -22,14 +22,14 @@ mod rusti { } // This is the type with the questionable alignment -#[derive(Show)] +#[derive(Debug)] struct Inner { c64: u64 } // This is the type that contains the type with the // questionable alignment, for testing -#[derive(Show)] +#[derive(Debug)] struct Outer { c8: u8, t: Inner @@ -95,6 +95,6 @@ pub fn main() { // because `Inner`s alignment was 4. assert_eq!(mem::size_of::(), m::m::size()); - assert_eq!(y, "Outer { c8: 22u8, t: Inner { c64: 44u64 } }".to_string()); + assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } } diff --git a/src/test/run-pass/sepcomp-unwind.rs b/src/test/run-pass/sepcomp-unwind.rs index b8bb3b4e7f8..f68dea04a08 100644 --- a/src/test/run-pass/sepcomp-unwind.rs +++ b/src/test/run-pass/sepcomp-unwind.rs @@ -36,5 +36,5 @@ mod b { } fn main() { - Thread::scoped(move|| { ::b::g() }).join().unwrap_err(); + Thread::scoped(move|| { ::b::g() }).join().err().unwrap(); } diff --git a/src/test/run-pass/show-boxed-slice.rs b/src/test/run-pass/show-boxed-slice.rs index fc0b501e9c5..f496765edca 100644 --- a/src/test/run-pass/show-boxed-slice.rs +++ b/src/test/run-pass/show-boxed-slice.rs @@ -11,7 +11,7 @@ #![allow(unknown_features)] #![feature(box_syntax)] -#[derive(Show)] +#[derive(Debug)] struct Foo(Box<[u8]>); pub fn main() { diff --git a/src/test/run-pass/small-enums-with-fields.rs b/src/test/run-pass/small-enums-with-fields.rs index c793deaae2b..fc45e107bb0 100644 --- a/src/test/run-pass/small-enums-with-fields.rs +++ b/src/test/run-pass/small-enums-with-fields.rs @@ -10,7 +10,7 @@ use std::mem::size_of; -#[derive(PartialEq, Show)] +#[derive(PartialEq, Debug)] enum Either { Left(T), Right(U) } macro_rules! check { @@ -29,14 +29,14 @@ macro_rules! check { pub fn main() { check!(Option, 2, None, "None", - Some(129u8), "Some(129u8)"); + Some(129u8), "Some(129)"); check!(Option, 4, None, "None", - Some(-20000i16), "Some(-20000i16)"); + Some(-20000i16), "Some(-20000)"); check!(Either, 2, - Either::Left(132u8), "Left(132u8)", - Either::Right(-32i8), "Right(-32i8)"); + Either::Left(132u8), "Left(132)", + Either::Right(-32i8), "Right(-32)"); check!(Either, 4, - Either::Left(132u8), "Left(132u8)", - Either::Right(-20000i16), "Right(-20000i16)"); + Either::Left(132u8), "Left(132)", + Either::Right(-20000i16), "Right(-20000)"); } diff --git a/src/test/run-pass/tag-align-shape.rs b/src/test/run-pass/tag-align-shape.rs index b88357252d8..cc0a75181db 100644 --- a/src/test/run-pass/tag-align-shape.rs +++ b/src/test/run-pass/tag-align-shape.rs @@ -8,12 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#[derive(Show)] +#[derive(Debug)] enum a_tag { a_tag_var(u64) } -#[derive(Show)] +#[derive(Debug)] struct t_rec { c8: u8, t: a_tag @@ -23,5 +23,5 @@ pub fn main() { let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)}; let y = format!("{:?}", x); println!("y = {:?}", y); - assert_eq!(y, "t_rec { c8: 22u8, t: a_tag_var(44u64) }".to_string()); + assert_eq!(y, "t_rec { c8: 22, t: a_tag_var(44) }".to_string()); } diff --git a/src/test/run-pass/unit-like-struct-drop-run.rs b/src/test/run-pass/unit-like-struct-drop-run.rs index 4c866503282..3c50712b464 100644 --- a/src/test/run-pass/unit-like-struct-drop-run.rs +++ b/src/test/run-pass/unit-like-struct-drop-run.rs @@ -26,6 +26,6 @@ pub fn main() { let _b = Foo; }).join(); - let s = x.unwrap_err().downcast::<&'static str>().unwrap(); + let s = x.err().unwrap().downcast::<&'static str>().ok().unwrap(); assert_eq!(s.as_slice(), "This panic should happen."); } diff --git a/src/test/run-pass/vec-to_str.rs b/src/test/run-pass/vec-to_str.rs index 97c12d0954e..31f26126242 100644 --- a/src/test/run-pass/vec-to_str.rs +++ b/src/test/run-pass/vec-to_str.rs @@ -9,11 +9,11 @@ // except according to those terms. pub fn main() { - assert_eq!(format!("{:?}", vec!(0i, 1)), "[0i, 1i]".to_string()); + assert_eq!(format!("{:?}", vec!(0i, 1)), "[0, 1]".to_string()); let foo = vec!(3i, 4); let bar: &[int] = &[4, 5]; - assert_eq!(format!("{:?}", foo), "[3i, 4i]"); - assert_eq!(format!("{:?}", bar), "[4i, 5i]"); + assert_eq!(format!("{:?}", foo), "[3, 4]"); + assert_eq!(format!("{:?}", bar), "[4, 5]"); } 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 eb7205b5e0a..ffeb4be349a 100644 --- a/src/test/run-pass/wait-forked-but-failed-child.rs +++ b/src/test/run-pass/wait-forked-but-failed-child.rs @@ -58,7 +58,7 @@ fn main() { let _failures = range(0, 100).map(|_| { let cmd = Command::new(too_long.as_slice()); let failed = cmd.spawn(); - assert!(failed.is_err(), "Make sure the command fails to spawn(): {}", cmd); + assert!(failed.is_err(), "Make sure the command fails to spawn(): {:?}", cmd); failed }).collect::>(); -- cgit 1.4.1-3-g733a5 From a506d4cbfe8f20a2725c7efd9d43359a0bbd0e9e Mon Sep 17 00:00:00 2001 From: Aaron Turon Date: Sat, 17 Jan 2015 16:15:52 -0800 Subject: Fallout from stabilization. --- src/compiletest/header.rs | 3 +-- src/compiletest/runtest.rs | 4 +-- src/doc/intro.md | 4 +-- src/libcollections/btree/node.rs | 21 ++++++++-------- src/libcollections/ring_buf.rs | 2 +- src/libcollections/slice.rs | 2 +- src/libcollections/str.rs | 26 ++++++++++++-------- src/libcore/fmt/float.rs | 4 +-- src/librand/chacha.rs | 3 +-- src/librbml/io.rs | 2 +- src/libregex/re.rs | 2 +- src/librustc/metadata/cstore.rs | 2 +- src/librustc/metadata/loader.rs | 4 +-- src/librustc/middle/cfg/construct.rs | 2 +- src/librustc/middle/dataflow.rs | 30 +++++++++++------------ src/librustc/middle/infer/region_inference/mod.rs | 5 ++-- src/librustc/middle/subst.rs | 4 +-- src/librustc/session/search_paths.rs | 8 +++--- src/librustc_borrowck/borrowck/check_loans.rs | 2 +- src/librustc_trans/back/link.rs | 2 +- src/librustc_trans/save/mod.rs | 4 +-- src/librustc_trans/trans/debuginfo.rs | 5 ++-- src/librustc_trans/trans/meth.rs | 4 +-- src/librustc_typeck/astconv.rs | 8 +++--- src/librustc_typeck/check/regionck.rs | 2 +- src/librustc_typeck/coherence/overlap.rs | 2 +- src/librustdoc/html/escape.rs | 4 +-- src/librustdoc/html/markdown.rs | 2 +- src/librustdoc/html/render.rs | 4 +-- src/librustdoc/markdown.rs | 4 +-- src/librustdoc/passes.rs | 2 +- src/libstd/ffi/c_str.rs | 2 +- src/libstd/io/buffered.rs | 2 +- src/libstd/io/comm_adapters.rs | 4 +-- src/libstd/io/mem.rs | 10 ++++---- src/libstd/io/mod.rs | 4 +-- src/libstd/io/net/ip.rs | 2 +- src/libstd/io/util.rs | 2 +- src/libstd/num/strconv.rs | 4 +-- src/libstd/rand/os.rs | 2 +- src/libstd/rt/util.rs | 2 +- src/libstd/sys/common/backtrace.rs | 16 ++++++------ src/libstd/sys/unix/process.rs | 4 +-- src/libstd/sys/windows/fs.rs | 2 +- src/libstd/sys/windows/os.rs | 2 +- src/libsyntax/parse/lexer/mod.rs | 6 ++--- src/libsyntax/parse/parser.rs | 2 +- src/libsyntax/print/pprust.rs | 4 +-- src/libunicode/u_str.rs | 8 +++--- 49 files changed, 126 insertions(+), 125 deletions(-) (limited to 'src/libstd') diff --git a/src/compiletest/header.rs b/src/compiletest/header.rs index 2413a001ee8..d7af767688e 100644 --- a/src/compiletest/header.rs +++ b/src/compiletest/header.rs @@ -332,8 +332,7 @@ pub fn parse_name_value_directive(line: &str, directive: &str) let keycolon = format!("{}:", directive); match line.find_str(keycolon.as_slice()) { Some(colon) => { - let value = line.slice(colon + keycolon.len(), - line.len()).to_string(); + let value = line[(colon + keycolon.len()) .. line.len()].to_string(); debug!("{}: {}", directive, value); Some(value) } diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 5579479c5e5..8936c20cefd 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -862,7 +862,7 @@ fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String]) break; } Some(i) => { - rest = rest.slice_from(i + frag.len()); + rest = &rest[(i + frag.len())..]; } } first = false; @@ -1045,7 +1045,7 @@ fn scan_until_char(haystack: &str, needle: char, idx: &mut uint) -> bool { if *idx >= haystack.len() { return false; } - let opt = haystack.slice_from(*idx).find(needle); + let opt = haystack[(*idx)..].find(needle); if opt.is_none() { return false; } diff --git a/src/doc/intro.md b/src/doc/intro.md index 3487738467f..a7c37ba8e07 100644 --- a/src/doc/intro.md +++ b/src/doc/intro.md @@ -485,9 +485,9 @@ fn main() { Thread::spawn(move || { let mut array = number.lock().unwrap(); - (*array)[i] += 1; + array[i as usize] += 1; - println!("numbers[{}] is {}", i, (*array)[i]); + println!("numbers[{}] is {}", i, array[i as usize]); }); } } diff --git a/src/libcollections/btree/node.rs b/src/libcollections/btree/node.rs index fa890643089..50857c78469 100644 --- a/src/libcollections/btree/node.rs +++ b/src/libcollections/btree/node.rs @@ -21,7 +21,7 @@ use core::prelude::*; use core::borrow::BorrowFrom; use core::cmp::Ordering::{Greater, Less, Equal}; use core::iter::Zip; -use core::ops::{Deref, DerefMut}; +use core::ops::{Deref, DerefMut, Index, IndexMut}; use core::ptr::Unique; use core::{slice, mem, ptr, cmp, num, raw}; use alloc::heap; @@ -1487,7 +1487,7 @@ impl AbsTraversal macro_rules! node_slice_impl { ($NodeSlice:ident, $Traversal:ident, - $as_slices_internal:ident, $slice_from:ident, $slice_to:ident, $iter:ident) => { + $as_slices_internal:ident, $index:ident, $iter:ident) => { impl<'a, K: Ord + 'a, V: 'a> $NodeSlice<'a, K, V> { /// Performs linear search in a slice. Returns a tuple of (index, is_exact_match). fn search_linear(&self, key: &Q) -> (uint, bool) @@ -1521,10 +1521,10 @@ macro_rules! node_slice_impl { edges: if !self.has_edges { self.edges } else { - self.edges.$slice_from(pos) + self.edges.$index(&(pos ..)) }, - keys: self.keys.slice_from(pos), - vals: self.vals.$slice_from(pos), + keys: &self.keys[pos ..], + vals: self.vals.$index(&(pos ..)), head_is_edge: !pos_is_kv, tail_is_edge: self.tail_is_edge, } @@ -1550,10 +1550,10 @@ macro_rules! node_slice_impl { edges: if !self.has_edges { self.edges } else { - self.edges.$slice_to(pos + 1) + self.edges.$index(&(.. (pos + 1))) }, - keys: self.keys.slice_to(pos), - vals: self.vals.$slice_to(pos), + keys: &self.keys[..pos], + vals: self.vals.$index(&(.. pos)), head_is_edge: self.head_is_edge, tail_is_edge: !pos_is_kv, } @@ -1583,6 +1583,5 @@ macro_rules! node_slice_impl { } } -node_slice_impl!(NodeSlice, Traversal, as_slices_internal, slice_from, slice_to, iter); -node_slice_impl!(MutNodeSlice, MutTraversal, as_slices_internal_mut, slice_from_mut, - slice_to_mut, iter_mut); +node_slice_impl!(NodeSlice, Traversal, as_slices_internal, index, iter); +node_slice_impl!(MutNodeSlice, MutTraversal, as_slices_internal_mut, index_mut, iter_mut); diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index b9cb4be7c18..69d64bcdf6d 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -578,7 +578,7 @@ impl RingBuf { if contiguous { let (empty, buf) = buf.split_at_mut(0); - (buf.slice_mut(tail, head), empty) + (&mut buf[tail .. head], empty) } else { let (mid, right) = buf.split_at_mut(tail); let (left, _) = mid.split_at_mut(head); diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index a640e4ee0e3..16e5a89f343 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -686,7 +686,7 @@ impl SliceExt for [T] { #[inline] fn move_from(&mut self, mut src: Vec, start: uint, end: uint) -> uint { - for (a, b) in self.iter_mut().zip(src.slice_mut(start, end).iter_mut()) { + for (a, b) in self.iter_mut().zip(src[start .. end].iter_mut()) { mem::swap(a, b); } cmp::min(self.len(), end-start) diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index 94554fd1e81..6608d0ee9a7 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -752,21 +752,15 @@ pub trait StrExt: Index { /// Deprecated: use `s[a .. b]` instead. #[deprecated = "use slice notation [a..b] instead"] - fn slice(&self, begin: uint, end: uint) -> &str { - core_str::StrExt::slice(&self[], begin, end) - } + fn slice(&self, begin: uint, end: uint) -> &str; /// Deprecated: use `s[a..]` instead. #[deprecated = "use slice notation [a..] instead"] - fn slice_from(&self, begin: uint) -> &str { - core_str::StrExt::slice_from(&self[], begin) - } + fn slice_from(&self, begin: uint) -> &str; /// Deprecated: use `s[..a]` instead. #[deprecated = "use slice notation [..a] instead"] - fn slice_to(&self, end: uint) -> &str { - core_str::StrExt::slice_to(&self[], end) - } + fn slice_to(&self, end: uint) -> &str; /// Returns a slice of the string from the character range /// [`begin`..`end`). @@ -1304,7 +1298,19 @@ pub trait StrExt: Index { } #[stable] -impl StrExt for str {} +impl StrExt for str { + fn slice(&self, begin: uint, end: uint) -> &str { + &self[begin..end] + } + + fn slice_from(&self, begin: uint) -> &str { + &self[begin..] + } + + fn slice_to(&self, end: uint) -> &str { + &self[..end] + } +} #[cfg(test)] mod tests { diff --git a/src/libcore/fmt/float.rs b/src/libcore/fmt/float.rs index f1b9ebe6d90..245dc00d838 100644 --- a/src/libcore/fmt/float.rs +++ b/src/libcore/fmt/float.rs @@ -179,7 +179,7 @@ pub fn float_to_str_bytes_common( _ => () } - buf.slice_to_mut(end).reverse(); + buf[..end].reverse(); // Remember start of the fractional digits. // Points one beyond end of buf if none get generated, @@ -316,7 +316,7 @@ pub fn float_to_str_bytes_common( impl<'a> fmt::Writer for Filler<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { - slice::bytes::copy_memory(self.buf.slice_from_mut(*self.end), + slice::bytes::copy_memory(&mut self.buf[(*self.end)..], s.as_bytes()); *self.end += s.len(); Ok(()) diff --git a/src/librand/chacha.rs b/src/librand/chacha.rs index 815fc0e7ec7..3332e06e19e 100644 --- a/src/librand/chacha.rs +++ b/src/librand/chacha.rs @@ -174,7 +174,7 @@ impl<'a> SeedableRng<&'a [u32]> for ChaChaRng { // reset state self.init(&[0u32; KEY_WORDS]); // set key in place - let key = self.state.slice_mut(4, 4+KEY_WORDS); + let key = &mut self.state[4 .. 4+KEY_WORDS]; for (k, s) in key.iter_mut().zip(seed.iter()) { *k = *s; } @@ -292,4 +292,3 @@ mod test { } } } - diff --git a/src/librbml/io.rs b/src/librbml/io.rs index f39860c8695..9c746c69baa 100644 --- a/src/librbml/io.rs +++ b/src/librbml/io.rs @@ -103,7 +103,7 @@ impl Writer for SeekableMemWriter { // Do the necessary writes if left.len() > 0 { - slice::bytes::copy_memory(self.buf.slice_from_mut(self.pos), left); + slice::bytes::copy_memory(&mut self.buf[self.pos..], left); } if right.len() > 0 { self.buf.push_all(right); diff --git a/src/libregex/re.rs b/src/libregex/re.rs index abc51d62404..3cdc0be45a6 100644 --- a/src/libregex/re.rs +++ b/src/libregex/re.rs @@ -459,7 +459,7 @@ impl<'t> Captures<'t> { pub fn at(&self, i: uint) -> Option<&'t str> { match self.pos(i) { None => None, - Some((s, e)) => Some(self.text.slice(s, e)) + Some((s, e)) => Some(&self.text[s.. e]) } } diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index a928d1c9022..7b7159da438 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -242,7 +242,7 @@ impl MetadataBlob { ((slice[2] as u32) << 8) | ((slice[3] as u32) << 0)) as uint; if len + 4 <= slice.len() { - slice.slice(4, len + 4) + &slice[4.. len + 4] } else { &[] // corrupt or old metadata } diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index 70b6ddf23fd..b1043a4152c 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -392,11 +392,11 @@ impl<'a> Context<'a> { }; let (hash, rlib) = if file.starts_with(&rlib_prefix[]) && file.ends_with(".rlib") { - (file.slice(rlib_prefix.len(), file.len() - ".rlib".len()), + (&file[(rlib_prefix.len()) .. (file.len() - ".rlib".len())], true) } else if file.starts_with(dylib_prefix.as_slice()) && file.ends_with(dypair.1.as_slice()) { - (file.slice(dylib_prefix.len(), file.len() - dypair.1.len()), + (&file[(dylib_prefix.len()) .. (file.len() - dypair.1.len())], false) } else { return FileDoesntMatch diff --git a/src/librustc/middle/cfg/construct.rs b/src/librustc/middle/cfg/construct.rs index a1ac25a5650..1a2162b3076 100644 --- a/src/librustc/middle/cfg/construct.rs +++ b/src/librustc/middle/cfg/construct.rs @@ -424,7 +424,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } ast::ExprMethodCall(_, _, ref args) => { - self.call(expr, pred, &*args[0], args.slice_from(1).iter().map(|e| &**e)) + self.call(expr, pred, &*args[0], args[1..].iter().map(|e| &**e)) } ast::ExprIndex(ref l, ref r) | diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 2b9bd1cd09f..a1727869810 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -118,17 +118,17 @@ impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O assert!(self.bits_per_id > 0); let cfgidx = to_cfgidx_or_die(id, &self.nodeid_to_index); let (start, end) = self.compute_id_range(cfgidx); - let on_entry = self.on_entry.slice(start, end); + let on_entry = &self.on_entry[start.. end]; let entry_str = bits_to_string(on_entry); - let gens = self.gens.slice(start, end); + let gens = &self.gens[start.. end]; let gens_str = if gens.iter().any(|&u| u != 0) { format!(" gen: {}", bits_to_string(gens)) } else { "".to_string() }; - let kills = self.kills.slice(start, end); + let kills = &self.kills[start .. end]; let kills_str = if kills.iter().any(|&u| u != 0) { format!(" kill: {}", bits_to_string(kills)) } else { @@ -232,7 +232,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let cfgidx = to_cfgidx_or_die(id, &self.nodeid_to_index); let (start, end) = self.compute_id_range(cfgidx); - let gens = self.gens.slice_mut(start, end); + let gens = &mut self.gens[start.. end]; set_bit(gens, bit); } @@ -245,7 +245,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let cfgidx = to_cfgidx_or_die(id, &self.nodeid_to_index); let (start, end) = self.compute_id_range(cfgidx); - let kills = self.kills.slice_mut(start, end); + let kills = &mut self.kills[start.. end]; set_bit(kills, bit); } @@ -256,9 +256,9 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { assert!(self.bits_per_id > 0); let (start, end) = self.compute_id_range(cfgidx); - let gens = self.gens.slice(start, end); + let gens = &self.gens[start.. end]; bitwise(bits, gens, &Union); - let kills = self.kills.slice(start, end); + let kills = &self.kills[start.. end]; bitwise(bits, kills, &Subtract); debug!("{} apply_gen_kill(cfgidx={:?}, bits={}) [after]", @@ -304,7 +304,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { } let (start, end) = self.compute_id_range(cfgidx); - let on_entry = self.on_entry.slice(start, end); + let on_entry = &self.on_entry[start.. end]; let temp_bits; let slice = match e { Entry => on_entry, @@ -336,7 +336,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let cfgidx = to_cfgidx_or_die(id, &self.nodeid_to_index); let (start, end) = self.compute_id_range(cfgidx); - let gens = self.gens.slice(start, end); + let gens = &self.gens[start.. end]; debug!("{} each_gen_bit(id={}, gens={})", self.analysis_name, id, bits_to_string(gens)); self.each_bit(gens, f) @@ -396,7 +396,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { cfg.graph.each_edge(|_edge_index, edge| { let flow_exit = edge.source(); let (start, end) = self.compute_id_range(flow_exit); - let mut orig_kills = self.kills.slice(start, end).to_vec(); + let mut orig_kills = self.kills[start.. end].to_vec(); let mut changed = false; for &node_id in edge.data.exiting_scopes.iter() { @@ -404,7 +404,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { match opt_cfg_idx { Some(cfg_idx) => { let (start, end) = self.compute_id_range(cfg_idx); - let kills = self.kills.slice(start, end); + let kills = &self.kills[start.. end]; if bitwise(orig_kills.as_mut_slice(), kills, &Union) { changed = true; } @@ -418,7 +418,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { } if changed { - let bits = self.kills.slice_mut(start, end); + let bits = &mut self.kills[start.. end]; debug!("{} add_kills_from_flow_exits flow_exit={:?} bits={} [before]", self.analysis_name, flow_exit, mut_bits_to_string(bits)); bits.clone_from_slice(&orig_kills[]); @@ -487,7 +487,7 @@ impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> { let (start, end) = self.dfcx.compute_id_range(node_index); // Initialize local bitvector with state on-entry. - in_out.clone_from_slice(self.dfcx.on_entry.slice(start, end)); + in_out.clone_from_slice(&self.dfcx.on_entry[start.. end]); // Compute state on-exit by applying transfer function to // state on-entry. @@ -528,13 +528,13 @@ impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> { let (start, end) = self.dfcx.compute_id_range(cfgidx); let changed = { // (scoping mutable borrow of self.dfcx.on_entry) - let on_entry = self.dfcx.on_entry.slice_mut(start, end); + let on_entry = &mut self.dfcx.on_entry[start.. end]; bitwise(on_entry, pred_bits, &self.dfcx.oper) }; if changed { debug!("{} changed entry set for {:?} to {}", self.dfcx.analysis_name, cfgidx, - bits_to_string(self.dfcx.on_entry.slice(start, end))); + bits_to_string(&self.dfcx.on_entry[start.. end])); self.changed = true; } } diff --git a/src/librustc/middle/infer/region_inference/mod.rs b/src/librustc/middle/infer/region_inference/mod.rs index 0f487fffe5c..9339f435d8f 100644 --- a/src/librustc/middle/infer/region_inference/mod.rs +++ b/src/librustc/middle/infer/region_inference/mod.rs @@ -609,8 +609,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { pub fn vars_created_since_snapshot(&self, mark: &RegionSnapshot) -> Vec { - self.undo_log.borrow() - .slice_from(mark.length) + self.undo_log.borrow()[mark.length..] .iter() .filter_map(|&elt| match elt { AddVar(vid) => Some(vid), @@ -637,7 +636,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { debug!("result_index={}, r={:?}", result_index, r); for undo_entry in - self.undo_log.borrow().slice_from(mark.length).iter() + self.undo_log.borrow()[mark.length..].iter() { match undo_entry { &AddConstraint(ConstrainVarSubVar(a, b)) => { diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index 9ad2dd499cc..031eb26300f 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -373,12 +373,12 @@ impl VecPerParamSpace { pub fn get_slice<'a>(&'a self, space: ParamSpace) -> &'a [T] { let (start, limit) = self.limits(space); - self.content.slice(start, limit) + &self.content[start.. limit] } pub fn get_mut_slice<'a>(&'a mut self, space: ParamSpace) -> &'a mut [T] { let (start, limit) = self.limits(space); - self.content.slice_mut(start, limit) + &mut self.content[start.. limit] } pub fn opt_get<'a>(&'a self, diff --git a/src/librustc/session/search_paths.rs b/src/librustc/session/search_paths.rs index 0cf04fe0a00..dfc27d3ae68 100644 --- a/src/librustc/session/search_paths.rs +++ b/src/librustc/session/search_paths.rs @@ -36,13 +36,13 @@ impl SearchPaths { pub fn add_path(&mut self, path: &str) { let (kind, path) = if path.starts_with("native=") { - (PathKind::Native, path.slice_from("native=".len())) + (PathKind::Native, &path["native=".len()..]) } else if path.starts_with("crate=") { - (PathKind::Crate, path.slice_from("crate=".len())) + (PathKind::Crate, &path["crate=".len()..]) } else if path.starts_with("dependency=") { - (PathKind::Dependency, path.slice_from("dependency=".len())) + (PathKind::Dependency, &path["dependency=".len()..]) } else if path.starts_with("all=") { - (PathKind::All, path.slice_from("all=".len())) + (PathKind::All, &path["all=".len()..]) } else { (PathKind::All, path) }; diff --git a/src/librustc_borrowck/borrowck/check_loans.rs b/src/librustc_borrowck/borrowck/check_loans.rs index d5ad201eabf..0ade916f639 100644 --- a/src/librustc_borrowck/borrowck/check_loans.rs +++ b/src/librustc_borrowck/borrowck/check_loans.rs @@ -370,7 +370,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { for (i, &x) in new_loan_indices.iter().enumerate() { let old_loan = &self.all_loans[x]; - for &y in new_loan_indices.slice_from(i+1).iter() { + for &y in new_loan_indices[(i+1) ..].iter() { let new_loan = &self.all_loans[y]; self.report_error_if_loans_conflict(old_loan, new_loan); } diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index dacf620cbd1..efa948f0942 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -178,7 +178,7 @@ pub fn build_link_meta(sess: &Session, krate: &ast::Crate, fn truncated_hash_result(symbol_hasher: &mut Sha256) -> String { let output = symbol_hasher.result_bytes(); // 64 bits should be enough to avoid collisions. - output.slice_to(8).to_hex().to_string() + output[.. 8].to_hex().to_string() } diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index b12903c814c..c765698fc0c 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -157,7 +157,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { return; } - let sub_paths = sub_paths.slice(0, len-1); + let sub_paths = &sub_paths[.. (len-1)]; for &(ref span, ref qualname) in sub_paths.iter() { self.fmt.sub_mod_ref_str(path.span, *span, @@ -174,7 +174,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { if len <= 1 { return; } - let sub_paths = sub_paths.slice_to(len-1); + let sub_paths = &sub_paths[.. (len-1)]; // write the trait part of the sub-path let (ref span, ref qualname) = sub_paths[len-2]; diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index 2f01f0328e2..7d0ff5f2adc 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -1615,8 +1615,8 @@ fn compile_unit_metadata(cx: &CrateContext) -> DIDescriptor { let prefix: &[u8] = &[dotdot[0], ::std::path::SEP_BYTE]; let mut path_bytes = p.as_vec().to_vec(); - if path_bytes.slice_to(2) != prefix && - path_bytes.slice_to(2) != dotdot { + if &path_bytes[..2] != prefix && + &path_bytes[..2] != dotdot { path_bytes.insert(0, prefix[0]); path_bytes.insert(1, prefix[1]); } @@ -4122,4 +4122,3 @@ fn needs_gdb_debug_scripts_section(ccx: &CrateContext) -> bool { !ccx.sess().target.target.options.is_like_windows && ccx.sess().opts.debuginfo != NoDebugInfo } - diff --git a/src/librustc_trans/trans/meth.rs b/src/librustc_trans/trans/meth.rs index 0fb0dffe930..2a893a6cfdf 100644 --- a/src/librustc_trans/trans/meth.rs +++ b/src/librustc_trans/trans/meth.rs @@ -494,7 +494,7 @@ pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty::ty_bare_fn(_, ref f) if f.abi == Rust || f.abi == RustCall => { let fake_sig = ty::Binder(ty::FnSig { - inputs: f.sig.0.inputs.slice_from(1).to_vec(), + inputs: f.sig.0.inputs[1..].to_vec(), output: f.sig.0.output, variadic: f.sig.0.variadic, }); @@ -634,7 +634,7 @@ pub fn trans_object_shim<'a, 'tcx>( } _ => { // skip the self parameter: - sig.inputs.slice_from(1) + &sig.inputs[1..] } }; diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 42b12c15866..428c5680a48 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -1321,7 +1321,7 @@ fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>, // HACK(eddyb) replace the fake self type in the AST with the actual type. let input_params = if self_ty.is_some() { - decl.inputs.slice_from(1) + &decl.inputs[1..] } else { &decl.inputs[] }; @@ -1339,9 +1339,9 @@ fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>, let lifetimes_for_params = if implied_output_region.is_none() { let input_tys = if self_ty.is_some() { // Skip the first argument if `self` is present. - self_and_input_tys.slice_from(1) + &self_and_input_tys[1..] } else { - self_and_input_tys.slice_from(0) + &self_and_input_tys[] }; let (ior, lfp) = find_implied_output_region(input_tys, input_pats); @@ -1665,7 +1665,7 @@ fn compute_opt_region_bound<'tcx>(tcx: &ty::ctxt<'tcx>, // of derived region bounds. If so, use that. Otherwise, report an // error. let r = derived_region_bounds[0]; - if derived_region_bounds.slice_from(1).iter().any(|r1| r != *r1) { + if derived_region_bounds[1..].iter().any(|r1| r != *r1) { tcx.sess.span_err( span, &format!("ambiguous lifetime bound, \ diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index 3b5027dbb9e..e4b28bf5648 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -531,7 +531,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) { ast::ExprMethodCall(_, _, ref args) => { constrain_call(rcx, expr, Some(&*args[0]), - args.slice_from(1).iter().map(|e| &**e), false); + args[1..].iter().map(|e| &**e), false); visit::walk_expr(rcx, expr); } diff --git a/src/librustc_typeck/coherence/overlap.rs b/src/librustc_typeck/coherence/overlap.rs index ce7ba9ac11e..a7bad3dc789 100644 --- a/src/librustc_typeck/coherence/overlap.rs +++ b/src/librustc_typeck/coherence/overlap.rs @@ -65,7 +65,7 @@ impl<'cx, 'tcx> OverlapChecker<'cx, 'tcx> { continue; } - for &impl2_def_id in trait_impls.slice_from(i+1).iter() { + for &impl2_def_id in trait_impls[(i+1)..].iter() { self.check_if_impls_overlap(trait_def_id, impl1_def_id, impl2_def_id); diff --git a/src/librustdoc/html/escape.rs b/src/librustdoc/html/escape.rs index 6fb78d9a833..db7253c9ef3 100644 --- a/src/librustdoc/html/escape.rs +++ b/src/librustdoc/html/escape.rs @@ -29,7 +29,7 @@ impl<'a> fmt::String for Escape<'a> { for (i, ch) in s.bytes().enumerate() { match ch as char { '<' | '>' | '&' | '\'' | '"' => { - try!(fmt.write_str(pile_o_bits.slice(last, i))); + try!(fmt.write_str(&pile_o_bits[last.. i])); let s = match ch as char { '>' => ">", '<' => "<", @@ -46,7 +46,7 @@ impl<'a> fmt::String for Escape<'a> { } if last < s.len() { - try!(fmt.write_str(pile_o_bits.slice_from(last))); + try!(fmt.write_str(&pile_o_bits[last..])); } Ok(()) } diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 0dbd13b4616..1c800771c70 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -146,7 +146,7 @@ extern { fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> { let trimmed = s.trim(); if trimmed.starts_with("# ") { - Some(trimmed.slice_from(2)) + Some(&trimmed[2..]) } else { None } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index ab9700d966a..ea535a1490b 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -749,7 +749,7 @@ impl<'a> SourceCollector<'a> { // Remove the utf-8 BOM if any let contents = if contents.starts_with("\u{feff}") { - contents.slice_from(3) + &contents[3..] } else { contents }; @@ -1469,7 +1469,7 @@ fn full_path(cx: &Context, item: &clean::Item) -> String { fn shorter<'a>(s: Option<&'a str>) -> &'a str { match s { Some(s) => match s.find_str("\n\n") { - Some(pos) => s.slice_to(pos), + Some(pos) => &s[..pos], None => s, }, None => "" diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index dc98a56eb1a..594cf3dcd43 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -28,10 +28,10 @@ fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { for line in s.lines() { if line.starts_with("%") { // remove % - metadata.push(line.slice_from(1).trim_left()) + metadata.push(line[1..].trim_left()) } else { let line_start_byte = s.subslice_offset(line); - return (metadata, s.slice_from(line_start_byte)); + return (metadata, &s[line_start_byte..]); } } // if we're here, then all lines were metadata % lines. diff --git a/src/librustdoc/passes.rs b/src/librustdoc/passes.rs index 9a67b479106..34a23774e5b 100644 --- a/src/librustdoc/passes.rs +++ b/src/librustdoc/passes.rs @@ -357,7 +357,7 @@ pub fn unindent(s: &str) -> String { line.to_string() } else { assert!(line.len() >= min_indent); - line.slice_from(min_indent).to_string() + line[min_indent..].to_string() } }).collect::>().as_slice()); unindented.connect("\n") diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index d7f8eb2e415..6d6aaac22a2 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -115,7 +115,7 @@ impl Deref for CString { type Target = [libc::c_char]; fn deref(&self) -> &[libc::c_char] { - self.inner.slice_to(self.inner.len() - 1) + &self.inner[..(self.inner.len() - 1)] } } diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 8c38bc009cc..2b293d6eef2 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -219,7 +219,7 @@ impl Writer for BufferedWriter { if buf.len() > self.buf.len() { self.inner.as_mut().unwrap().write(buf) } else { - let dst = self.buf.slice_from_mut(self.pos); + let dst = &mut self.buf[self.pos..]; slice::bytes::copy_memory(dst, buf); self.pos += buf.len(); Ok(()) diff --git a/src/libstd/io/comm_adapters.rs b/src/libstd/io/comm_adapters.rs index 4b0014c68f7..4649012d454 100644 --- a/src/libstd/io/comm_adapters.rs +++ b/src/libstd/io/comm_adapters.rs @@ -72,7 +72,7 @@ impl Buffer for ChanReader { if self.closed { Err(io::standard_error(io::EndOfFile)) } else { - Ok(self.buf.slice_from(self.pos)) + Ok(&self.buf[self.pos..]) } } @@ -88,7 +88,7 @@ impl Reader for ChanReader { loop { let count = match self.fill_buf().ok() { Some(src) => { - let dst = buf.slice_from_mut(num_read); + let dst = &mut buf[num_read..]; let count = cmp::min(src.len(), dst.len()); bytes::copy_memory(dst, &src[..count]); count diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index ee05a9e5596..884582cbaa8 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -160,7 +160,7 @@ impl Reader for MemReader { let write_len = min(buf.len(), self.buf.len() - self.pos); { let input = &self.buf[self.pos.. (self.pos + write_len)]; - let output = buf.slice_to_mut(write_len); + let output = &mut buf[.. write_len]; assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); } @@ -205,11 +205,11 @@ impl<'a> Reader for &'a [u8] { let write_len = min(buf.len(), self.len()); { let input = &self[..write_len]; - let output = buf.slice_to_mut(write_len); + let output = &mut buf[.. write_len]; slice::bytes::copy_memory(output, input); } - *self = self.slice_from(write_len); + *self = &self[write_len..]; Ok(write_len) } @@ -270,7 +270,7 @@ impl<'a> BufWriter<'a> { impl<'a> Writer for BufWriter<'a> { #[inline] fn write(&mut self, src: &[u8]) -> IoResult<()> { - let dst = self.buf.slice_from_mut(self.pos); + let dst = &mut self.buf[self.pos..]; let dst_len = dst.len(); if dst_len == 0 { @@ -350,7 +350,7 @@ impl<'a> Reader for BufReader<'a> { let write_len = min(buf.len(), self.buf.len() - self.pos); { let input = &self.buf[self.pos.. (self.pos + write_len)]; - let output = buf.slice_to_mut(write_len); + let output = &mut buf[.. write_len]; assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); } diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index dc21416df7b..ba7c81bf3fb 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -516,7 +516,7 @@ pub trait Reader { while read < min { let mut zeroes = 0; loop { - match self.read(buf.slice_from_mut(read)) { + match self.read(&mut buf[read..]) { Ok(0) => { zeroes += 1; if zeroes >= NO_PROGRESS_LIMIT { @@ -1481,7 +1481,7 @@ pub trait Buffer: Reader { { let mut start = 1; while start < width { - match try!(self.read(buf.slice_mut(start, width))) { + match try!(self.read(&mut buf[start .. width])) { n if n == width - start => break, n if n < width - start => { start += n; } _ => return Err(standard_error(InvalidInput)), diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index adc122ff447..2c79d7a373d 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -251,7 +251,7 @@ impl<'a> Parser<'a> { assert!(head.len() + tail.len() <= 8); let mut gs = [0u16; 8]; gs.clone_from_slice(head); - gs.slice_mut(8 - tail.len(), 8).clone_from_slice(tail); + gs[(8 - tail.len()) .. 8].clone_from_slice(tail); Ipv6Addr(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7]) } diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index adfd88644cc..e4bf38a9ef5 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -48,7 +48,7 @@ impl Reader for LimitReader { } let len = cmp::min(self.limit, buf.len()); - let res = self.inner.read(buf.slice_to_mut(len)); + let res = self.inner.read(&mut buf[..len]); match res { Ok(len) => self.limit -= len, _ => {} diff --git a/src/libstd/num/strconv.rs b/src/libstd/num/strconv.rs index 67fe599ecd6..1d3bf484edb 100644 --- a/src/libstd/num/strconv.rs +++ b/src/libstd/num/strconv.rs @@ -379,14 +379,14 @@ pub fn float_to_str_bytes_common( // only resize buf if we actually remove digits if i < buf_max_i { - buf = buf.slice(0, i + 1).to_vec(); + buf = buf[.. (i + 1)].to_vec(); } } } // If exact and trailing '.', just cut that else { let max_i = buf.len() - 1; if buf[max_i] == b'.' { - buf = buf.slice(0, max_i).to_vec(); + buf = buf[.. max_i].to_vec(); } } diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index 68ba7e1dd29..bafbde2511d 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -65,7 +65,7 @@ mod imp { let mut read = 0; let len = v.len(); while read < len { - let result = getrandom(v.slice_from_mut(read)); + let result = getrandom(&mut v[read..]); if result == -1 { let err = errno() as libc::c_int; if err == libc::EINTR { diff --git a/src/libstd/rt/util.rs b/src/libstd/rt/util.rs index 235cedcda52..4023a0a4c10 100644 --- a/src/libstd/rt/util.rs +++ b/src/libstd/rt/util.rs @@ -130,7 +130,7 @@ pub fn abort(args: fmt::Arguments) -> ! { } impl<'a> fmt::Writer for BufWriter<'a> { fn write_str(&mut self, bytes: &str) -> fmt::Result { - let left = self.buf.slice_from_mut(self.pos); + let left = &mut self.buf[self.pos..]; let to_write = &bytes.as_bytes()[..cmp::min(bytes.len(), left.len())]; slice::bytes::copy_memory(left, to_write); self.pos += to_write.len(); diff --git a/src/libstd/sys/common/backtrace.rs b/src/libstd/sys/common/backtrace.rs index d8b85987236..d069d9ee3b8 100644 --- a/src/libstd/sys/common/backtrace.rs +++ b/src/libstd/sys/common/backtrace.rs @@ -42,10 +42,10 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { let mut valid = true; let mut inner = s; if s.len() > 4 && s.starts_with("_ZN") && s.ends_with("E") { - inner = s.slice(3, s.len() - 1); + inner = &s[3 .. s.len() - 1]; // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" form too. } else if s.len() > 3 && s.starts_with("ZN") && s.ends_with("E") { - inner = s.slice(2, s.len() - 1); + inner = &s[2 .. s.len() - 1]; } else { valid = false; } @@ -83,11 +83,11 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { } let mut rest = inner; while rest.char_at(0).is_numeric() { - rest = rest.slice_from(1); + rest = &rest[1..]; } - let i: uint = inner.slice_to(inner.len() - rest.len()).parse().unwrap(); - inner = rest.slice_from(i); - rest = rest.slice_to(i); + let i: uint = inner[.. (inner.len() - rest.len())].parse().unwrap(); + inner = &rest[i..]; + rest = &rest[..i]; while rest.len() > 0 { if rest.starts_with("$") { macro_rules! demangle { @@ -128,8 +128,8 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { None => rest.len(), Some(i) => i, }; - try!(writer.write_str(rest.slice_to(idx))); - rest = rest.slice_from(idx); + try!(writer.write_str(&rest[..idx])); + rest = &rest[idx..]; } } } diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs index 36bf696dba5..46639d7d8f0 100644 --- a/src/libstd/sys/unix/process.rs +++ b/src/libstd/sys/unix/process.rs @@ -125,9 +125,9 @@ impl Process { let mut bytes = [0; 8]; return match input.read(&mut bytes) { Ok(8) => { - assert!(combine(CLOEXEC_MSG_FOOTER) == combine(bytes.slice(4, 8)), + assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]), "Validation on the CLOEXEC pipe failed: {:?}", bytes); - let errno = combine(bytes.slice(0, 4)); + let errno = combine(&bytes[0.. 4]); assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic"); Err(super::decode_error(errno)) } diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index a7330f7c67c..cb8ef7eb66b 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -376,7 +376,7 @@ pub fn readlink(p: &Path) -> IoResult { }); let ret = match ret { Some(ref s) if s.starts_with(r"\\?\") => { // " - Ok(Path::new(s.slice_from(4))) + Ok(Path::new(&s[4..])) } Some(s) => Ok(Path::new(s)), None => Err(super::last_error()), diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index e9490dc95c9..36dc9b2afe4 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -146,7 +146,7 @@ pub fn fill_utf16_buf_and_decode(mut f: F) -> Option where done = true; } if k != 0 && done { - let sub = buf.slice(0, k as uint); + let sub = &buf[.. (k as uint)]; // We want to explicitly catch the case when the // closure returned invalid UTF-16, rather than // set `res` to None and continue. diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 4cdafb36eec..7852b077b53 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -271,9 +271,9 @@ impl<'a> StringReader<'a> { fn with_str_from_to(&self, start: BytePos, end: BytePos, f: F) -> T where F: FnOnce(&str) -> T, { - f(self.filemap.src.slice( - self.byte_offset(start).to_uint(), - self.byte_offset(end).to_uint())) + f(&self.filemap.src[ + self.byte_offset(start).to_uint().. + self.byte_offset(end).to_uint()]) } /// Converts CRLF to LF in the given string, raising an error on bare CR. diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 83a7504bc49..932c5ce23ea 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -5223,7 +5223,7 @@ impl<'a> Parser<'a> { Some(i) => { let mut err = String::from_str("circular modules: "); let len = included_mod_stack.len(); - for p in included_mod_stack.slice(i, len).iter() { + for p in included_mod_stack[i.. len].iter() { err.push_str(&p.display().as_cow()[]); err.push_str(" -> "); } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index b59e770c6ba..cf5066ae474 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1590,7 +1590,7 @@ impl<'a> State<'a> { ident: ast::SpannedIdent, tys: &[P], args: &[P]) -> IoResult<()> { - let base_args = args.slice_from(1); + let base_args = &args[1..]; try!(self.print_expr(&*args[0])); try!(word(&mut self.s, ".")); try!(self.print_ident(ident.node)); @@ -2312,7 +2312,7 @@ impl<'a> State<'a> { let args = if first { &decl.inputs[] } else { - decl.inputs.slice_from(1) + &decl.inputs[1..] }; for arg in args.iter() { diff --git a/src/libunicode/u_str.rs b/src/libunicode/u_str.rs index 13672a7b480..66cdf03a51e 100644 --- a/src/libunicode/u_str.rs +++ b/src/libunicode/u_str.rs @@ -249,8 +249,8 @@ impl<'a> Iterator for Graphemes<'a> { Some(cat) }; - let retstr = self.string.slice_to(idx); - self.string = self.string.slice_from(idx); + let retstr = &self.string[..idx]; + self.string = &self.string[idx..]; Some(retstr) } } @@ -350,8 +350,8 @@ impl<'a> DoubleEndedIterator for Graphemes<'a> { Some(cat) }; - let retstr = self.string.slice_from(idx); - self.string = self.string.slice_to(idx); + let retstr = &self.string[idx..]; + self.string = &self.string[..idx]; Some(retstr) } } -- cgit 1.4.1-3-g733a5 From 4ffde0814f43076c944f46890e0b6d401de92ca4 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 21 Jan 2015 09:23:27 -0800 Subject: Test fixes and rebase conflicts --- src/liballoc/heap.rs | 2 +- src/libcore/any.rs | 9 +-------- src/libcore/intrinsics.rs | 6 ------ src/librustdoc/clean/mod.rs | 2 +- src/libstd/io/mod.rs | 2 +- src/libstd/sync/mpsc/mod.rs | 2 -- src/libstd/sys/windows/backtrace.rs | 1 + src/libstd/sys/windows/thread_local.rs | 1 + src/libstd/thread_local/mod.rs | 1 + src/test/run-make/test-shard-completeness/Makefile | 7 ------- src/test/run-make/test-shard-completeness/main.rs | 16 ---------------- 11 files changed, 7 insertions(+), 42 deletions(-) delete mode 100644 src/test/run-make/test-shard-completeness/Makefile delete mode 100644 src/test/run-make/test-shard-completeness/main.rs (limited to 'src/libstd') diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs index 44be0503bc2..a2643f4d0f7 100644 --- a/src/liballoc/heap.rs +++ b/src/liballoc/heap.rs @@ -280,7 +280,7 @@ mod imp { if align <= MIN_ALIGN { libc::malloc(size as libc::size_t) as *mut u8 } else { - let mut out = ptr::null(); + let mut out = ptr::null_mut(); let ret = posix_memalign(&mut out, align as libc::size_t, size as libc::size_t); diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 6e9d2f349bf..9966f0d4bf7 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -75,7 +75,7 @@ use mem::transmute; use option::Option::{self, Some, None}; use raw::TraitObject; use intrinsics; -#[cfg(not(stage0))] use marker::Sized; +use marker::Sized; /////////////////////////////////////////////////////////////////////////////// // Any trait @@ -175,17 +175,10 @@ pub struct TypeId { impl TypeId { /// Returns the `TypeId` of the type this generic function has been /// instantiated with - #[cfg(not(stage0))] #[unstable = "may grow a `Reflect` bound soon via marker traits"] pub fn of() -> TypeId { TypeId { t: unsafe { intrinsics::type_id::() }, } } - - /// dox - #[cfg(stage0)] - pub fn of() -> TypeId { - unsafe { intrinsics::type_id::() } - } } diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index 73be68289c9..dd488a74216 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -44,8 +44,6 @@ use marker::Sized; -#[cfg(stage0)] use any::TypeId; - pub type GlueFn = extern "Rust" fn(*const i8); #[lang="ty_desc"] @@ -208,12 +206,8 @@ extern "rust-intrinsic" { /// Gets an identifier which is globally unique to the specified type. This /// function will return the same value for a type regardless of whichever /// crate it is invoked in. - #[cfg(not(stage0))] pub fn type_id() -> u64; - #[cfg(stage0)] - pub fn type_id() -> TypeId; - /// Create a value initialized to zero. /// /// `init` is unsafe because it returns a zeroed-out datum, diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 7c7db97951e..788ec5af44c 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2088,7 +2088,7 @@ impl Clean for ast::Mutability { } } -#[derive(Show, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Show)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Show)] pub enum ImplPolarity { Positive, Negative, diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 3ad1b5222cb..fdd8738a89d 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -1444,7 +1444,7 @@ pub trait Buffer: Reader { } } }; - buffer.consume(used); + self.consume(used); if done { return Ok(res); } diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 96b1636667e..062bdf346cd 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -319,8 +319,6 @@ use prelude::v1::*; use sync::Arc; use fmt; -#[cfg(stage0)] // NOTE remove use after next snapshot -use marker; use mem; use cell::UnsafeCell; diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index 2561b1bebb5..cba7d81937a 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -31,6 +31,7 @@ use mem; use ops::Drop; use option::Option::{Some, None}; use path::Path; +use ptr; use result::Result::{Ok, Err}; use slice::SliceExt; use str::{self, StrExt}; diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs index 83c116e9b05..d148f82184b 100644 --- a/src/libstd/sys/windows/thread_local.rs +++ b/src/libstd/sys/windows/thread_local.rs @@ -13,6 +13,7 @@ use prelude::v1::*; use libc::types::os::arch::extra::{DWORD, LPVOID, BOOL}; use mem; +use ptr; use rt; use sys_common::mutex::{MUTEX_INIT, Mutex}; diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index 24e46d8d88e..f7a2f8e10e9 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -459,6 +459,7 @@ mod imp { use cell::UnsafeCell; use mem; + use ptr; use sys_common::thread_local::StaticKey as OsStaticKey; #[doc(hidden)] diff --git a/src/test/run-make/test-shard-completeness/Makefile b/src/test/run-make/test-shard-completeness/Makefile deleted file mode 100644 index 16ab12a8252..00000000000 --- a/src/test/run-make/test-shard-completeness/Makefile +++ /dev/null @@ -1,7 +0,0 @@ --include ../tools.mk - -all: - # Running all the shards should hit every test - $(RUSTC) --test main.rs - $(call RUN,main) --test-shard 1.2 | grep "test_1 ... ok" - $(call RUN,main) --test-shard 2.2 | grep "test_2 ... ok" diff --git a/src/test/run-make/test-shard-completeness/main.rs b/src/test/run-make/test-shard-completeness/main.rs deleted file mode 100644 index 5eabd630b09..00000000000 --- a/src/test/run-make/test-shard-completeness/main.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2013 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![crate_type = "lib"] - -#[test] -fn test_1() { } -#[test] -fn test_2() { } -- cgit 1.4.1-3-g733a5 From bbbdd1086c5e08b12c6bf7193b15b9e8381c3fb2 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Wed, 21 Jan 2015 14:54:17 -0500 Subject: Improve RwLock::new's docs Fixes #21440" --- src/libstd/sync/rwlock.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'src/libstd') diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 237f6d08a95..f773e360ef8 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -157,7 +157,15 @@ pub struct RwLockWriteGuard<'a, T: 'a> { impl<'a, T> !marker::Send for RwLockWriteGuard<'a, T> {} impl RwLock { - /// Creates a new instance of an RwLock which is unlocked and read to go. + /// Creates a new instance of an `RwLock` which is unlocked. + /// + /// # Examples + /// + /// ``` + /// use std::sync::RwLock; + /// + /// let lock = RwLock::new(5); + /// ``` #[stable] pub fn new(t: T) -> RwLock { RwLock { inner: box RW_LOCK_INIT, data: UnsafeCell::new(t) } -- cgit 1.4.1-3-g733a5 From ecbee2e56824161fcc0decd087055d13e0876058 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 21 Jan 2015 11:56:52 -0800 Subject: More test fixes and rebase conflicts --- src/librustc/diagnostics.rs | 1 - src/librustc_resolve/diagnostics.rs | 1 + src/libstd/io/mem.rs | 2 +- src/libsyntax/parse/lexer/mod.rs | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src/libstd') diff --git a/src/librustc/diagnostics.rs b/src/librustc/diagnostics.rs index 04cfa16d2ed..653ade67b72 100644 --- a/src/librustc/diagnostics.rs +++ b/src/librustc/diagnostics.rs @@ -78,7 +78,6 @@ register_diagnostics! { E0139, E0152, E0153, - E0154, E0157, E0158, E0161, diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 2a4c31d62ab..dd9ccfbda7c 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -11,6 +11,7 @@ #![allow(non_snake_case)] register_diagnostics! { + E0154, E0157, E0153, E0251, // a named type or value has already been imported in this module diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index 786b5a08eed..ec4191297ce 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -350,7 +350,7 @@ impl<'a> Reader for BufReader<'a> { let write_len = min(buf.len(), self.buf.len() - self.pos); { let input = &self.buf[self.pos.. self.pos + write_len]; - let output = &mut buf.slice_to_mut[..write_len]; + let output = &mut buf[..write_len]; assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); } diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 33e37aa51bd..3b9dcf53009 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -271,7 +271,7 @@ impl<'a> StringReader<'a> { fn with_str_from_to(&self, start: BytePos, end: BytePos, f: F) -> T where F: FnOnce(&str) -> T, { - f(self.filemap.src[ + f(&self.filemap.src[ self.byte_offset(start).to_usize().. self.byte_offset(end).to_usize()]) } -- cgit 1.4.1-3-g733a5